Posts

Showing posts from August, 2011

regex - Perl one liner to remove comments, removes lines which are not comments also -

i using perl 1 liner remove comments from c file, removes lines have asterik(*) in between words, eg static void * here in 1 liner using: 'perl -0777 -pe ''s{/\*.*?\*/}{}gs'' ' sourcefile ' > ' destfile could please suggest? thanks this question answered in perlfaq. "how use regular expression strip c style comments file?" http://perldoc.perl.org/5.8.9/perlfaq6.html#how-do-i-use-a-regular-expression-to-strip-c-style-comments-from-a-file ?

exception - org.hibernate.MappingException: Unknown entity when trying to save POJO -

i below error when invoke method save entity database. error: org.aggu.sramam.exceptions.sramamexception - exception thrown: org.hibernate.mappingexception: unknown entity: org.aggu.sramam.pojo.sramasangham @ org.hibernate.internal.sessionfactoryimpl.getentitypersister(sessionfactoryimpl.java:1096) @ org.hibernate.internal.sessionimpl.getentitypersister(sessionimpl.java:1443 the pojo object there in package, , have below entry in hibernate-cfg.xml file <hibernate-configuration> <!-- list out entities (i.e pojo linked db table) here --> <session-factory> <mapping class="org.aggu.sramam.pojo.sramasangham" /> </session-factory> </hibernate-configuration> below entry in servlet-config.xml file, gives code base links <!-- below base package sramam apps --> <context:component-scan base-package="org.aggu.sramam" /> what have missed here? have added @entity, @table, @id tag...

jquery - How to get value from a DIV element using 'this' -

i trying id number later can use in jquery post. id number in variable called data.results[i].id . how can id number jquery post below. for (var in data.results) { document.getelementbyid("list-canvas").innerhtml += "<div id='list_element" + data.results[i].id + "' value=" + data.results[i].id + " class='list_element_class'>" + "<div id='list_image'>" + "<div id='actual_image'>" + data.results[i].feature_image + "</div>" + "</div>" + "</div>"; $('.list_element_class').on('click', this.id, function(){ $.post('sql_p.php', {id : this.value }, function(data) { $("#left_2").hide();$("#left_3").show(); document.getelementbyid("left_3").innerhtml = data; }); }); } there nothing wrong "this.id" cont...

mysql - How to limit Value Range in tinyint(1) field? -

i have table tblproducts. the table contains field listed tinyint(1) not null default 0 the field can take values between 0-9. is there way in mysql allow 2 values in field: either 1 or 0 you can convert existing column bit(1), example sql alter ignore table persons modify p_id bit(1) default 0 note: existing values >=1 converted 1;

php - Jquery ajax form submit response getting alert automatically -

This summary is not available. Please click here to view the post.

php - Yii CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: -

i error when didn't while, i'm not sure if session problem or not. the error message is: cdbcommand failed execute sql statement: sqlstate[42000]: syntax error or access violation: 1064 have error in sql syntax; check manual corresponds mysql server version right syntax use near '=='1')' @ line 1. sql statement executed was: select * games_developers_app t (status :ycp0) , (developer_id==:ycp1) the code is: public function actionsortreject(){ $util = new utility(); $util->detectmobilebrowser(); $util->checkwebsitelanguageincookies(); $this->layout = "masterlayout"; $count = '0'; $id = yii::app()->user->getstate('id'); $searchsort = "rej"; $sort = new cdbcriteria(); $sort->addsearchcondition('status', $searchsort); $sort->addcondition('developer_id='.$id); $models = gamesdevelopersapp::model()->findall($sort...

Conversion from SVG file to XML file -

can explain how convert svg files xml files? i having design tool(eb guide) generates svg file format (contains state diagram). need use svg file in order view state diagram in enterprise architect uml tool. but, ea tool not supporting svg file. try convert svg file xml file , import in ea tool. is possible convert svg file format in xml file format? there conversion tool available. logu svg file is already in xml format. describes picture. can use graphic programs convert other picture formats, e.g. bmp, png can inserted image element diagram drawing canvas. (see chapter "using image manager" in file) the xml file can imported ea model using xmi import , export tool must contain uml model in xmi format , not picture or printscreen

javascript - tel: href "Click to call" link not working in Android -

in cordova android app have link this <a href = "tel:011123456789">click call</a> this click call link working in ios expected, in android click preventing like 11-26 11:13:00.565: d/webcore(18944): uioverrideurlloading: shouldoverrideurlloading() returnstrue this log cat result when clicked on phone number link , redirection not working. also tried javascript click override redirection, not worked. please me find solution. i using cordova 3.6 this issues may due cordova whitelist permission issue. can specify access in config.xml file like <access origin="tel:*" launch-external="yes" /> in cordova 3.6.3 update there security update. the security fixes involves creating new whitelist non http/s protocols. if application uses other protocols besides http:// , https://, such sms:, mailto:, geo:, etc., need make configuration changes add these protocols whitelist. <access origin="tel:*" laun...

sed - linux delete multiple lines in a file -

i ios developer, not familiar linux, searched long time still not solve problem. hope can me, thanks! before delete: other contents...... # # proxy server iterm & terminal setup script # version 0.1 # vincentsit # nov 26, 2014 # function start_proxy { export http_proxy='abc.efgh.com:1234' export https_proxy='abc.efgh.com:1234' } function stop_proxy { export http_proxy='' export https_proxy='' } other contents...... after delete: other contents...... other contents...... update i'm writing shell script(can not use other languages.). on users system has text file named abc , content this: # other comments...... # other comments...... # other comments...... other contents...... # other comments...... # # proxy server iterm & terminal setup script # version 0.1 # vincentsit # nov 26, 2014 # function start_proxy { export http_proxy='abc.efgh.com:1234' export https_proxy='abc.efgh.com:1234' } functio...

salesforce - Is it possible to convert a string in to a programming statement in apex? -

public string var='public string var1=\'some text\'; ' ; i require string inside var execute , create variable "var1" , assigned value "some text". is possible this? if yes how possible? yes, sort of. possible mimic javascript eval() in apex making callout executeanonymous api method. there 2 common ways can response executeanonymous. throw deliberate exception @ end of execute , include response. kevin covers approach in eval() in apex. secure dynamic code evaluation on salesforce1 platform . i used variation of approach returned response via debug log rather intentional exception. see adding eval() support apex . using example apex like: public string var = soapsforcecom200608apex.evalstring( 'string var1=\'some text\'; system.debug(logginglevel.error, var1);'); you might not able perform callout during member initialisation or in constructor. incidentally, salesforce stackexchange sit...

android - Why can i not make a directory inside Environment.DIRECTORY_PICTURES? -

this code file selfielocation = new file(getexternalfilesdir(environment.directory_pictures), "daily selfies"); boolean isdirectory = false; if(!selfielocation.isdirectory()) { //creates directory named file selfielocation.mkdir(); isdirectory = selfielocation.isdirectory(); } //array of strings for(string selfiepath: selfielocation.list()) { selfies.add(selfiepath); } basically trying create own customizable directory inside of standard directory in place pictures available user. i looked @ related threads , saw one, android: unable create directory in default pictures folder . made sure had call getexternal...., , not have environment.directory_pictures parameter. looked on here http://developer.android.com/guide/topics/data/data-storage.html#filesexternal , saw had right method call/format create customizable folder in external memory. docs example file file = new file(environment.getexternalstoragepublicdir...

javascript - AJAX Not Loading JSON Object -

Image
i'm trying simple request acronym finder api reason json not being returned. here code: $.ajax('http://www.nactem.ac.uk/software/acromine/dictionary.py?sf=dod', { crossdomain:true, datatype: "jsonp", success: function(data){ console.log(data); } }); if visit url directly in browser, can see requested json, chrome console returns: resource interpreted script transferred mime type text/plain: "http://www.nactem.ac.uk/software/acromine/dictionary.py?sf=dod&callback=jquery1111025898682116530836_1417074190743&_=1417074190744". the chrome debugger network tab indicates correct file downloaded why isn't json being logged console? the error message indicates response mime type 'text/plain'. expecting script mime type. so need setup response @ backend dictionary.py (if under control). add content-type "application/x-javascript" response header. similar (in java): @requestmappin...

java - Extracting positive and negative numbers from char array -

i trying extract both positive , negative numbers character array (which coming file). apparently method wrote worked positive numbers. can please tell me how modify handle negative numbers well? let's character array {'1',' ','2','-','2',' ','3','4'} it should output list containing {1,2,-2,34} . some guidance appreciated. in advance my method is: private static arraylist<integer> extractintegers(char[] characters) { int beginning = -1; arraylist<integer> numbers = new arraylist<integer>(); (int = 0; < characters.length; i++) { boolean isnumber = character.isdigit(characters[i]); if (beginning != -1 && !isnumber) { numbers.add(parseintegers(characters, beginning, i)); beginning = -1; } else if (beginning == -1 && isnumber) { ...

When I use hmset in php redis, why does it sucess if I use 'test_a' as the key, it fails if use 'test' -

require_once libfile('class/myredis'); $myredis = myredis::instance(6381); $res = $myredis->hmset('test', array('a' => 1, 'b' => 2)); var_dump($res); /*the result: bool(false);*/ require_once libfile('class/myredis'); $myredis = & myredis::instance(6381); $res = $myredis->hmset('test_a', array('a' => 1, 'b' => 2)); var_dump($res); /* result: bool(true);*/ i can not understand why, there other differences between 2 keys, 'test' 'test_a', thank help!

PHP Session expiring and system force logout -

when left system in idle mode( means inactive mode) , , when come access system after 1 or 2 hours, system reacts when use single window when generate recieppt through ajax , open receipt in window.popup window system logs out. , redirect login page because session expired in idle mode , if set session lifetime, case '1': $_session['kid'] = $q4['id']; ini_set('session.gc_maxlifetime', 100*60*60); session_set_cookie_params(0,"/"); break; plese ...... ini_set('session.gc_maxlifetime', ...) should called before session_start()

xcode - iOS simulator: could not hardlink copy. Wrong path in my filesystem? -

i using xcode version 6.1 (6a1052d) i trying launch app on simulator. the first time works fine. if want launch second time, have error (see log below). in ios simulator "reset content , settings" , can launch again successfully. given error log, think must have wrong path. problem bad mac filesystem , path linking, appreciated. edit : here info.plist.xml (generated libgdx if matters) <?xml version="1.0" encoding="utf-8"?> <!doctype plist public "-//apple//dtd plist 1.0//en" "http://www.apple.com/dtds/propertylist-1.0.dtd"> <plist version="1.0"> <dict> <key>cfbundledevelopmentregion</key> <string>en</string> <key>cfbundledisplayname</key> <string>${app.name}</string> <key>cfbundleexecutable</key> <string>${app.executable}</string> <key>cfbundleidentifier</key> <string>...

php - How to use include() properly? -

this structure directory: main directory all.php file.php url1.txt subdirectory1 url2.txt file.php file file.php this: $filename = glob("url*"); echo $filename[0]; file all.php <?php include('./subdirectory1/file.php'); ?> the problem when run file all.php , browser show url1.txt . why doesn't show url2.txt. how fix ? thank ! working directory set main script location. try putting full path of location want search in: $filename = glob(__dir__ . directory_separator . 'url*'); __dir__ current file directory (since php 5.3, lower php version use dirname(__file__) ). http://php.net/manual/en/language.constants.predefined.php

udp - C Automatic testing client server program -

i have client-server program using udp , test connection times in automated way. the server closes after accepting or rejecting connection , can't make changes connection related code not client, nor server. the thing comes mind trying batch file (i'm in windows), don't know if possible run both commands same batch file in automated way. it happened easier thought, problem formulating correct question: how run multiple dos commands in parallel? for sake of completeness, script i'm using now. @echo off /l %%i in (1, 1, 100) ( start server.exe ping 192.0.2.2 -n 1 -w 2 > nul start /wait client.exe ) i start server , give him 2ms warm (if not, times client start before server , instance fail). call client , wait until it's finished.

javascript - How can I define event handlers in a Fabric.js subclass? -

i have following subclass of rect in fabric.js. adds image rect. var irect = fabric.util.createclass(fabric.rect, { type: 'irect', initialize: function(options) { options || (options = { }); this.callsuper('initialize', options); }, fromobject: function (object, callback) { return new irect(object); }, toobject: function() { return fabric.util.object.extend(this.callsuper('toobject'), {}); }, _render: function(ctx) { this.callsuper('_render', ctx); var c = document.getelementbyid('canvas'); var img = document.getelementbyid('info'); c.getcontext('2d').drawimage(img, -this.width/2, -this.height/2); } }); i want define specific event handlers irect . instance, when user clicks on irect , want alert('hello') . should in subclass ? how can reference canvas while defining subclass ? code , problem description can f...

java - Multi-threaded connection manager with Jersey Apache Client 4 -

i have jersey client , running, using apache client 4 library, this: private client createclient() { apachehttpclient4config cc = new defaultapachehttpclient4config(); // boring stuff here return apachehttpclient4.create(cc); } but default uses basicclientconnmanager , doesn't allow multi-threaded connections. the apachehttpclient4config javadoc says need set property_connection_manager threadsafeclientconnmanager instance if want multi-threaded operation. can this, , works ok: private client createclient() { apachehttpclient4config cc = new defaultapachehttpclient4config(); cc.getproperties().put(apachehttpclient4config.property_connection_manager, new threadsafeclientconnmanager()); // boring stuff here return apachehttpclient4.create(cc); } but threadsafeclientconnmanager deprecated. annoying. the more modern version poolinghttpclientconnectionmanager . unfortunately, though, apachehttpclient4.create() method requires conn...

reactjs - React.js Polymorphism: Checking Child Type Fails -

i've got situation have navgroup renderas prop possible values of div , collapsible , dropdown achieve sort of "polymorphism" in react.js. works until down collapsible or dropdown , want check children collapsiblehead or dropdowntoggle find navgrouphead . see jsbin . since dropdown , collapsible components can't find child looking event handlers aren't being attached , can't no satisfaction. i in need of enlightenment: on right track? there simple solution this? or thinking wrong , should different? there "react way" doing sort of thing? it? if not, should there be? you're seeing same type of component you've marked todo because cloned child components rendering returning type of component - doesn't replace child component. if use react developer tools, you'll see collapsible example: <collapible> <div> <navgrouphead> <collapsiblehead> i think doing you're tryi...

android - Why google_play_service_lib is broken in eclipse? -

i have been trying add google_play_service_lib project showing red x mark besides library. result couldn't work on library project. unfortunately same adt bundle working nicely on others computer. have has been shown in link1 , link2 . why happening? confused. how working nicely in computer of friend? make sure libraries , project @ same place 1 copy libraries in same folder project 2 import libraries (file > import > existing project in workspace) 3 open properties of library > android , select library 4 open project properties > android > add (library) 5 select library 6 save properties ref

android - Nested ViewPager not displaying -

i writing application used nested viewpager. every parent viewpager contain 7 child viewpager. it work first parent, when reached next page show blank @ place of child viewpager. any suggestion here, if it's feasible use nested view pager even? , if how can avoid case? parent viewpager layout , same child fragment: <framelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:customfont="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" > <android.support.v4.view.viewpager android:id="@+id/calendarviewpager" android:layout_width="match_parent" android:layout_height="match_parent" > </android.support.v4.view.viewpager> and child viewpager adapter imp...

jax rs - Use JSON.stringify and JSON.parse in resteasy -

i need use json.stringify , json.parse in java class contains resteasy services exchange information jquery script. library should import java class or should ?, because in script let me default. thank much. so understanding want able serialize , deserialize json , java object, that's json.stringify , json.parse javascript. to able handle that, need messagebodyreader , messagebodywriter handle conversion. resteasy has providers available part of framework. need add module. hopefully using maven, if not see post . maven should have either 1 of these dependencies <dependency> <groupid>org.jboss.resteasy</groupid> <artifactid>resteasy-jackson-provider</artifactid> <version>${resteasy.version}</version> </dependency> <dependency> <groupid>org.jboss.resteasy</groupid> <artifactid>resteasy-jackson2-provider</artifactid> <version>${resteasy.version}</versi...

camera - Issue with cam access in Android streaming application -

i'm using libstreaming works on many devices, on others when start streaming i've strange behaviour in logcat , streaming doesn't work: full of tag: camera ( 6254): rrf in specific, happens d/mtkomxvenc( 133): encode ok iskey(1), size(60) d/mtkomxvenc( 133): enctime=2 d/mtkomxvenc( 133): 447ca008 ebd (0x426c4010) (0x4449d000), mnumpendinginput(1) d/mtkomxvenc( 133): 447ca008 fbd (0x448a4898) (0x47025000) 147333 (60), mnumpendingoutput(7) d/camerasource( 133): signalbufferreturned: 0x4449d000,mframesbeingencoded.size()=2 d/mtkomxvenc( 133): avc encode 187465, 115200, 0x00000010, input va=0x444ba000 :offset 0x00000000, output va=0x47125000 :offset 0x00000000 d/camera ( 6254): rrf e/vdo_log ( 133): before set rc address: 0 0 d/cameraclient( 133): rrf:va(0x4449d000) d/cameraclient( 133): rrf:va(0x4449d000), mlock (6254) d/mtkcam/camclient/recordclient( 133): (6434)[releaserecordingframe] idx(0),va(0x4449d000) d/camerasource( 133): read, mframesreceived.siz...

What is Google app script URLFetch service response size limit? -

i'm writing google app script google spreadsheet , i'm facing problem urlfetch service. i'm requesting external service , sometimes receive empty response. external service pretty stable , must return something, @ least error message if wrong happens. but receive empty response, nothing. i can solve modifying request expected response should less in size, , fix issue. makes me think response size limitation. i doubt random problem because rerunning script again issue same request fails, unless, said, modify request receive response less in size. but on google's quota page , can't find clear answer question. at time of asking question, i'm facing problem of reading response supposed around 14.1 kb . knew size running request manually on browser. does know if there limitation , ? in experience limit 10mb. larger 14.1kb, application developed ( http://www.blinkreports.com ) routinely receives responses in excess of 1mb.

java - What is reason for sql result set couldn't return result set? -

i'm trying return result set method. i'm sure sql query out put result set. because in "while(rs.next())" method print values. problem when i'm returning result set values , try calling "while(rs.next())" in calling method doesn't print value. reason that? /* calling method */ public void corpusretrivedemo(){ arraylist<string> wordall= new arraylist<string>(); /* word list corpus retrive */ wordall=allwordslist(sentence1); resultset rsnew=corpussentenceretrive(wordall); try { while (rsnew.next()) { system.out.println("heloooo2..."); } } catch (sqlexception e) { // todo auto-generated catch block e.printstacktrace(); } /* uni gram calculate */ double d1=calculateprobunigram(wordall,rsnew); system.out.println(d1); } /* database retrieve method */ public resultset corpussentenceretrive(list wordlist) { preparedst...

python - Analyzing graphs in Django -

i have django based backend there many users (users 1, 2, 3 ... 100). each user x, can list of users (a, b, c) friends user on facebook (i can find using facebook api), , friends user on database (my own custom friendship model has information) i want way analyze "interconnectedness" on daily basis, maybe in django admin panel or somewhere else - drawing me 100 users , showing clusters of users friends each other (on facebook, on database) is there package readily enables me in django, or in platform (i can export django data in compatible way , feed other system) thanks what django google charts or django chartit ? or more complex can use free d3 js library.

c# - SignalR and single user authentication -

i created sort of chat application in asp.net mvc5. have chosen single user authentication when creating project. people can register , login. after created signalr hub. have map users single user authentication correct client in hub. i want username or claims of it. how can this? there many questions , answers this, never see single user authentication. i've tried use microsoft.aspnet.signalr.authorize , system.web.mvc.authorize (that 1 use controllers to) attribute above hub. gave both 401 unauthorized.

Access 2003 SQL Syntax error in join message -

i new @ coding in sql access 2003 , having problem showing additional column called action shown on tledgers table. recieving syntax error message not sure why? below code snippet causing issue from (tdailyentries inner join tdailyentries on tledgers.action = tdailyentries.actionno) below full code select distinct tprojects.cc_io projectno, year([datefrom]) & " accrual " & monthname(month([datefrom])) & " - "+[companyname] & " ( "+([lastname]) & ")" [line/item/text], tusers.lastname last_name, tdailyentries.userid userid, contractordailyrate dailyrate, contractordailyhours hours, round(contractordailyrate / contractordailyhours, 2) hourlyrate, round(sum(tdailyentries.calculateddailyhours), 2) monthlyhours, round((hourlyrate * monthlyhours), 2) charge, round(charge+round((charge*0.2),2),2) accruals, tprojects.project project (tdailyentries inner join tdailyentries on tledgers.action = tdailyentries.actionno) (...

Fix memory position for a function at compilation -

is possible set memory position function start from? want know if possible @ compilation, linking or in code. also i'm working freertos, possible too? what toolchain use? compilers have special syntax (e.g. word "absolute"), if using gcc should edit linker file (.ld). syntax rather cryptic @ first sight, have docs explained. in short, should mark function belongs section this: __attribute__((section(".mysection"))) void reflashable_function(... and add following text myproject.ld file after existing sections: .mysection 0xs0meaddress: { *(.mysection) *(.mysection*) } also, add key "-map=output.map" makefile generate mapfile , seek name of function in output.map check if has correct address. there may additional difficulties e.g. inlining function or inlining in it, suggest putting separate .c file. can addg reflashable memory memory section of .ld file, in case won't need add address, need add memory name this: .mysec...

c# - Parameter Binding in ASP.NET Web API -

i have delegatinghandler in web api authentification (hmac). i add parameter request return user's id controller. in handler, tried adding so: public class securityhandler : delegatinghandler { protected override task<httpresponsemessage> sendasync(httprequestmessage request, cancellationtoken cancellationtoken) { string apikey = request.headers.getvalues(authconfig.apikeyheader).first(); userdto user = userrepo.getuser(apikey); if (user == null) { return sendresponsetext("invalid api key"); } // validate signature ... // add user id uri request.requesturi = new uri(request.requesturi.originalstring + "&userid=" + user.id); return base.sendasync(request, cancellationtoken); } } in controller, i'm able newly added parameter request uri, parameter binding not working public class mymodel { public int userid { get; set; } ... } publ...

Delete rows before doing any transformation in datastage designer? -

i want delete rows before doing processing. don't know how in datastage designer? there stage holds sql requests?? not knowing job do "processing" can 1 job has 2 stages: row_generator , database link (depending on db). configure row generator generate 1 row only. on db stage can whatever delete ou want. job deletes rows want. after that, sequence job , add job you've done delete rows , link whatever jobs want run next - don't forget configure triggers on these links. hope helps.

android - Is there a way to correct the TalkBack pronunciation for the app_name or activity label? -

i've problem: have developed app italian users. app has english name , talkback pronunciates in wrong way! example, talkback says word "what" in way: "w - h - at". so, there way correct talkback pronunciation name of app or activity label? maybe via contentdescription or this... in advance!

java - How can I implement library which will supports data types for variables in PHP 5.x.x ? Instead of loose datatype binding in PHP -

i want extend core php library , want build wrapper library supports strict data types in php, java , c++. please give me steps / suggestions or reference urls. should start. if can extends code php library instead of modification in core distribution.

algorithm - Keep track on biggest element in FIFO queue -

this question has answer here: stack find-min/find-max more efficient o(n)? 4 answers problem i have fixed length fifo queue of integer values. everytime push new value it, oldest 1 removed. queue must able tell, after every insertion & removal operation, biggest value in it. question is there algorithm better doing loop on queue elements every time? after accept update because of limited domain of integers in application, thinking sparse histogram, containing counts of given value in queue. every time value arrives increment value in histogram, , decrement when given value removed. max/min need first/last histogram index non 0 count. in fact due specific structure of problem possible o(1) amortized operations, better using max-heap. application sliding window minimum algorithm. keep second queue contains decreasing subsequence of suffix m...

Ruby Date 1 month ago to String -

i need calculate date 1 month today in ruby , convert string in format: yyyy-dd-mmthh:mm:ss (e.g. 2014-08-26t00:00:00) i have tried: (datetime.now - date.today.prev_month).to_datetime.strftime("%ft%t") method not exist exception. try this: require 'date' d = date.today.prev_month # or date.today.next_month, depending want => #<date: 2014-12-27 ((2457019j,0s,0n),+0s,2299161j)> d.strftime("%ft%t") => "2014-12-27t00:00:00"

Why does Android require a Context to access a resource? -

i why android requires pass context object when trying view example, show toast, etc. however, don't point requiring access resources shared different contexts in application. i several times found myself trying access resource utility class using static method or along lines, , find pretty annoying require passing of context param. i fail see go south this. from official documentation : interface global information application environment. abstract class implementation provided android system. allows access application-specific resources , classes, up-calls application-level operations such launching activities, broadcasting , receiving intents, etc. in clear, context middleman between telephone resource, , code. , seems logical, cannot access everywhere. the reason can access context in activity , application classes, because both derives context : java.lang.object ↳ android.content.context ↳ android.content.contextwrapper ...

python 2.7 - What is the difference between these two examples? -

i going through python tutorial - static method, class method class pizza(object): @staticmethod def mix_ingredients(x, y): return x + y def cook(self): return self.mix_ingredients(self.cheese, self.vegetables) >>> pizza().cook pizza().cook false >>> pizza().mix_ingredients pizza.mix_ingredients true >>> pizza().mix_ingredients pizza().mix_ingredients true i don't quite understand result of ---> pizza().cook pizza().cook - > why different? and pizza().mix_ingredients pizza.mix_ingredients -> difference between having bracket , no bracket? finally, static method, why final result true? many thanks! a way think see cook method being 1 per pizza , whereas pizza s share same @staticmethod mix_ingrecdients . so pizza() gives new pizza, pizza().cook cook method of specific pizza (indicated self ) so, pizza().cook pizza().cook will therefore false . this partially answers next part of ...

wordpress - AddThis plugin showing cross domain error -

Image
i'm using addthis wordpress plugin social connectivity in website. strange showing error in following image, i googled type of error saying link in iframe different site link, cannot share data between different urls that. but haven't done that, enabled plugin , configured social buttons in addthis site. i'm using wordpress 4 , plugin addthis wordpress latest version. can please tell me how sort out issue.

f# - Tupled arguments in interfaces -

can explain f# curiosity? type ifoo = abstract member bar1: int * int -> int * int abstract member bar2: int * int -> (int * int) abstract member bar3: (int * int) -> int * int type foo() = class end interface ifoo member this.bar1 (x, y) = (x, y) member this.bar2 (x, y) = (x, y) // same impl bar1 i.e. parentheses on rhs of -> in interface member definition ignored // member this.bar3 (x, y) = (x, y) // compile error: "this override takes different number of arguments corresponding abstract member" member this.bar3 tuple = tuple // so, parentheses on lhs of -> in interface member definition *does* make difference! what difference in meaning between definitions of ifoo.bar1 , ifoo.bar3 ? here, input type can describe 2 different things: tuple or argument list of cli method. this makes no difference on return type, since interpretation of return t...

Cannot create index in MongoDB 2.4 -

my friend's app designed use mongodb indexes. fine while developing locally, once moved code hosting provider, code fails: db.createindex('collections', {title:"text", description:"text"}, function(err, indexname) { console.log("8. index name: " + indexname); }); the error message "index creation failed" provider says because not upgrade mongodb 2.6, version 2.4 , have no plans upgrade. looked mongodb website, indexes section not mention indexes not available until 2.6. says 2.6 has features. what's going on here, wrong code or mongodb not supporting indexes until 2.6, how be, or doing wrong, option have fast search mongodb 2.4? as lix said, createindex deprecated. should use ensureindex instead: collection.ensureindex({title:"text", description:"text"}, function(err, indexname) { //handle error , check index name }) please remember, compound index, not 2 seperate indexes created ...

python - Break or exit out of "with" statement? -

i'd exit out of with statement under conditions: with open(path) f: print 'before condition' if <condition>: break #syntax error! print 'after condition' of course, above doesn't work. there way this? (i know can invert condition: if not <condition>: print 'after condition' -- way above?) the best way encapsulate in function , use return : def do_it(): open(path) f: print 'before condition' if <condition>: return print 'after condition'

swift - How to detect if SKAction is running -

this skaction: naarrechts = skaction.movetox(positionx , duration: 0.22) player.runaction(naarrechts) in duration of 0.22 sec not want action run: if cgrectintersectsrect(player.frame, car.frame){ player.position.x = car.position.x } what magic line of code can detect if first skaction running, or detect wether player in movement or not.. you can create class variable var playerisinaction = false set true after run action. change method can write completion code (after action ends) set bool false . it should : playerisinaction = true player.runaction(naarrechts, completion: {() in playerisinaction = false }) and check bool if cgrectintersectsrect(player.frame, car.frame) && playerisinaction == false { //code }

asp.net mvc 4 - MVC4 dropdown helper with references -

i use mvc4 , trying make dropdown links. wrote helper: public static mvchtmlstring languageselectordropdown(this system.web.mvc.htmlhelper helper, string name) { var culture = thread.currentthread.currentculture; ilist<culture> data = new culturerepository().getenabled(); var items = new list<selectlistitem>(); items.addrange( (from item in data select new selectlistitem() { text = @"<a href='/home/edit/3'>i link</a>", //it's example. here run other method dynamic link value = item.id.tostring(), selected = culture.name.equals(item.id) }).tolist()); return new mvchtmlstring(httputility.htmldecode(helper.dropdownlist(name, items).tostring())); } at end of method have: helper.dropdownlist(name, items).tostring() = "<select id=\"languageselector\" name=\"languageselector\"><option value=\"de-de\">&lt;a href=&#39;/home...

ios - How to unit test a UIViewController - TDD/BDD -

unit testing never seem able head around can see why important , can huge time saver (if know you're doing). hoping can point me in right direction. i have following uiviewcontroller qbelectricitybasevc.h @interface qbelectricitybasevc : qbstatevc @property (nonatomic, strong) qbelectricityusage *electricityusage; @property (nonatomic, assign) cgfloat tabbarheight; - (void)updateelectricityusage; @end qbelectricitybasevc.m @implementation qbelectricitybasevc - (instancetype)init { self = [super init]; if (self) { self.tabbaritem = [[uitabbaritem alloc] initwithtitle:nslocalizedstring(@"electricity_title", nil) image:nil tag:0]; } return self; } - (void)viewwillappear:(bool)animated { [super viewwillappear:animated]; [self.notificationcenter addobserver:self selector:@selector(updateelectricityusage) name:kupdatedelectricityusagekey object:nil]; } - (void)viewwilldisappear...

delphi - Error with PrivateMessages in IdIRC -

hi have problem following code: program test; {$apptype console} {$r *.res} uses system.sysutils, idirc, idcontext, idglobal; // procedure tform1.idirc1privatemessage(asender: tidcontext; const anickname, // ahost, atarget, amessage: string); // procedure tform1.idirc1raw(asender: tidcontext; ain: boolean; // const amessage: string); procedure ircprivatemessage(aself: pointer; const anickname, ahost, atarget, amessage: string); begin writeln('[+] message ' + anickname + ' > ' + amessage); end; procedure ircraw(aself: pointer; asender: tidcontext; ain: boolean; const amessage: string); begin writeln(iif(ain, '[recv] ', '[sent] ') + amessage); end; var irc: tidirc; m1: tmethod; m2: tmethod; begin try irc := tidirc.create(nil); try irc.host := 'localhost'; irc.port := 6667; irc.nickname := 'tester'; irc.username := 'tester'; m1.code := @ircraw; m1.data :...

c - Keeping the value of a String initialized into a function -

i know title isn't clear, clearer code + examples. want initialize char* ("motsecret" in main, "mot" in function) containing word selected randomly file, doing function. array made dynamic using memory allocation. variable in function initialized, when print value after exited function, value change , become "0@" here part concerned in main : int main() { file* dico =null; char *motsecret, *motres; char lettre=' '; int check=0, nbcoups=10, longueur=0, nbmots=0; bool erreur = true; srand(time(null)); nbmots = scandico(dico); getword(dico, nbmots, motsecret); printf("mot : %s", motsecret); the problem appears after function getword(). here code of function : void getword(file* dico, int nblignes, char *mot) { int nummotchoisi=rand() % nblignes, nbchar=0; char charactuel=' '; dico = fopen("dico.txt", "r"); rewind(dico); if(dico != null) ...

Java Collection, Set, Map or Array to hold unique sorted non blank strings -

i new java , container can use hold strings not empty , have them sorted. so far, have been using arraylist, seems bit limited case. thanks use treeset or treemap , depending on requirements. both collections accept unique elements , keep them sorted.

playframework 2.3 - play 2.3 sbt-concat not working in prod -

i want use plugin addsbtplugin("net.ground5hark.sbt" % "sbt-concat" % "0.1.8") to concatenate assets. i have 3 groups : concat.groups := seq( "concat_main.css" -> group(seq( "stylesheets/bootstrap.min.css", "stylesheets/font-awesome.css", "stylesheets/totem/sidebar/component.css", "stylesheets/main.min.css" )), "concat_main.js" -> group(seq( "javascripts/jquery-2.1.0.min.js", "javascripts/bootstrap.min.js", "javascripts/totempage/sidebar/modernizr.custom.js", "javascripts/totempage/respond.min.js", "javascripts/totempage/html5shiv.js", "javascripts/totempage/sidebar/classie.js", "javascripts/main.js" )), "concat_noel.js" -> group(seq( "javascripts/totempage/ouibounce-modal.js", "javascripts/ouibounce_modal.js", ...

iphone - [UINavigationController setGoalName:]: unrecognized selector sent to instance 0x7964e2c0 -

i have created app following code. working fine ios7 throws below error when run ios8. [uinavigationcontroller setgoalname:]: unrecognized selector sent instance 0x7964e2c0 my firstviewcontroller.m - (void)prepareforsegue:(uistoryboardsegue *)segue sender:(id)sender { goaldetailsviewcontroller *goalsdetailsviewcontroller = segue.destinationviewcontroller; nslog(@"%@",[nsstring stringwithformat:@"%@", [[self.arrcategorytitle objectatindex:indexpath.row] objectatindex:indexofcategory]]); goalsdetailsviewcontroller.goalname = @"exercise daily"; } my goaldetailsviewcontroller.h @interface goaldetailsviewcontroller : uiviewcontroller <uitableviewdelegate, uitableviewdatasource> @property (nonatomic) nsstring *goalname; thanks in advance. seems destinationviewcontroller subclass of uinavigationcontroller. try this: - (void)prepareforsegue:(uistoryboardsegue *)segue sender:(id)sender { goaldetailsviewcontroller *goalsdetails...

amazon web services - AWS S3 client side encryption using KMS - Region being ignored -

i'm using release kms service amazon , i'm getting issue region being ignored when passed amazons3encryptionclient . amazons3encryptionclient s3 = new amazons3encryptionclient(credentials, new kmsencryptionmaterialsprovider(keyid)) .withregion(region.getregion(regions.eu_west_1)); the error message coming indicates key can't found in region us-east-1 despite actively setting eu-west-1 the error message com.amazonaws.services.kms.model.notfoundexception: key 'arn:aws:kms:us-east-1:account#:key/mykeyname' not exist (service: awskms; status code: 400; error code: notfoundexception; request id: 8fb90ad0-7644-11e4-bf12-0b5a59268629) i can't find documentation suggest specific bug in api, suggestions? try reading comments/suggestions @ bottom of thread: http://java.awsblog.com/post/tx19olb7m3d6ds8/s3-encryption-with-aws-key-management-service looks there release address issue addition of new parameter. i.e: amazons3 s3 = ne...

import - What is --with-indices in AllegroGraph -

i trying load data allegro graph server , 1 of parameters --with-indices . can explain about? i have read entire allegro graph documentation , mentions indices can spogi , sopgi , etc, not mention about. please explain precisely. (i not asking full-forms of spogi , sopgi , etc. want exact meaning.) your triple store contains triples spo (subject, predicate, object). query against graph stored may have traverse lot of graph find nodes match query. allegrograph can store indices make traversal faster: finding predicates match first, example, , subject , object nodes attached, can use index finds predicates first pso . if triples have named graphs can add g and, triples have ids i . ag can use index psogi . (from docs: allegrograph triple indices ) an ag triple store created default set of indices. generating specialized indices resource intensive, if know kinds of queries you're going getting, may find worthwhile specify appropriate indices optimize response time...