Posts

Showing posts from September, 2010

java - Return the number of elements in a linked list recursively -

i have following recursive method in class called imagenode passed head( this - start of linked list) class called image. thought code recursively go through each node, increase count when @ end return count, unfortunatly not. going wrong? private int countrec() { int count = 1; imagenode node = this; if (node.next != null ){ node = node.next; count++; countrec(); } return count; } you're ignoring result of countrec() - , you're iterating within recursive call, defeating purpose. (you're making recursive call on same object, no parameters , no change in state... can't good.) recursive approach based on design of: if next node null, size of list 1 otherwise, size 1 + size next node onwards. so: private int countrec() { return next == null ? 1 : 1 + next.countrec(); } now doesn't allow list of length 0 of course... want separate idea of list node, in case list class have like: public int

video streaming - I would like to understand how to play the Live Stream / VOD on native Android App -

we want create live-broadcasting/streaming platform can go live on click of button using his/her mobile camera. same live feed should viewable native mobile app. start with, support live broadcast , viewing live feed both ios , android platforms. using wowza media streaming server usecase : lets sitting @ home, want show new home friends. download mobile app on android , start live stream on click of button. friends, have downloaded same mobile app, can see live-stream through mobile. can see of vod content. understand how play live stream / vod on native android app ? thanks in advance :) openmax android give best flexibility & control, however, it's low level api mandate c++ & ndk usage, can use ffmpeg static libs in same manner

javascript - first Dropdown hide on second drop down click event -

i using 2 codrops dropdwon menus in single page. want close first drop down menu when user clicks on 2nd drop down menu. i using below code in project. <select id="select1" class="cd-select"> <option value="-1" selected>menu 1</option> <option value="7" >submenu1</option> <option value="8" >submenu2</option> <option value="9" >submenu3</option></select> // 2nd menu <select id="select2" class="cd-select"> <option value="-1" selected>menu 2</option> <option value="2" >submenu1</option> <option value="5" >submenu2</option></select> .aspx page java script <script type="text/javascript"> $(function () { $('#select1').dropdown({ gutter: 5, stack: false, delay: 100,

php - Date filter for inserting into DB -

i have built simple crawler 1 of our clients. facing issues duplicate entries in database. basically doing looking website has lot of houses sale , pulling there address, postcode, town, price , status. later when inserting database generating creation_date . the reason name can duplicate in case has been inserted @ least 2 years ago. 1 house can twice in database, long creation dates within minimum of 2 years range. <?php //comparison current houses $query = mysql_query("select street, postcode, town, price, status, creation_time, print_status house"); // selecting table if (!$query) { die('invalid query: ' . mysql_error()); // checking errors } while ($row = mysql_fetch_array($query)) { // $row['street']; // $row['postcode']; // $row['town']; // $row['price']; // $row['status']; $creation_time = $row['creation_time'];

angularjs - select in ng-option does not update -

i have list of data coming backend , want update select value in view not happening reason. i tried ng-selected not works efficiently, sometime model update spmetimes not. here code, can help? <div class="listitem" ng-repeat="d in data"> {{d.name}}: <select ng-model="d.option" ng-options="d.name d in options"></select> </div> controller var myapp = angular.module('myapp', []); myapp.controller("somecontroller", function($scope) { $scope.options = [{ "id": "id1", "name": "p1" }, { "id": "id2", "name": "p2" }]; $scope.data = [{ "name": "data1", "option": { "id": "id1", "name": "p1" }

frameworks - What kind of setup produces a link with the reference 'application-<#hash code>'? -

i see ocassionally web apps following type links: <link data-turbolinks-track="true" href="/assets/application-23ffa36115ca2d0b0a40e6ab87e6a992.css" media="all" rel="stylesheet" /> what type of setup outputs file 1 linked here: /assets/application-23ffa36115ca2d0b0a40e6ab87e6a992.css" ?

javascript - What do factory, service and dependency injection exactly mean in angular.js -

i little confused following angular.js concepts: factory service dependency injection can brief me on each 1 simple example or explanation? appreciated. these concepts part of javascript core. regexp factory: console.log(regexp("[0-9]") ); console.log(regexp("[a-z]") ); console.log(regexp("[a-z]") ); console.log(regexp("[0-9a-za-z]") ); math service: console.log(math.pi); console.log(math.round(math.pi)); console.log(number(math.random() * 1000).tofixed()); console.log(number(math.random() * 10).toprecision(2)); console.log(math.floor(math.random() * 20) + 1); call , apply dependency injection: "use strict"; var foo = { min: function min(array) { return math.min.apply(math, array); }, max: function max(array) { return math.max.apply(math, array); } }; var bar = foo.min([1,2,3]); var baz = foo.max([1,2,3]); console.log(&

excel - Remove current cell's value from active autofilter in same column -

i have big excel sheet containing +100k rows , have autofilter on 1 column of text values category numbers , descriptions. there thousands of different values in column f, updating autofilter impractical via using standard ui. how can create macro removes active cell's value autofilter active on same column? with of expert, came working solution case. just posting solution others: sub clear_filter_and_value() application.screenupdating = false application.displayalerts = false dim w worksheet dim filterarray() dim currentfiltrange string dim col integer dim flag boolean set w = activesheet if w.autofiltermode = false selection.autofilter flag = false on error goto exit1 w.autofilter currentfiltrange = .range.address .filters f = 1 .count .item(f) if .on if activecell.column = f redim filterarray(1 .count) if .count = 2 fil

java - Having Trouble Understanding How To Use Singleton Pattern? -

i've been trying code that: class 1 creates instance of class 2 (class t = new class() ). instance can used in class 1,2 , 3. i've been looking around bit , found "singleton pattern". don't understand how implement code though , fair few of sources saying different things... thanks help, appreciated :) singleton example: if have class phonebook , want every class of programm refer same phonebook. make class phonebook singleton-class. in other words: singleton pattern used, asure every other code refering same object of singleton-class. class phonebook { //make constructor private no 1 can create objects, class private phonebook() { } // static members hold (m_instance) , (getinstacnce) singleton instance of class private static phonebook m_instance; public static phonebook getinstance() { if (m_instance == null) { // first call getinstance, creates singelton instance, (phonebook) can call construct

javascript - What can I use as an alternative to the readAsDataURL method to get a base64 encoded data url -

i'm working on phonegap app , records audio , uploads audio server. code below allows me read recorded audio file , return data base64 encoded data url using readasdataurl method , display url in alert box. code works on android not on ios. documentation says in regard ios: "ios quirks encoding parameter not supported, utf8 encoding used." wondering if provide me alternative. end result same result on android, alert box displaying data url. understand alert box may not display entire url. using alert box confirmation. want variable have data url stored in it. my code: function gotfs(filesystem) { filesystem.root.getfile("myaudio.wav", null, gotfileentry, fail); } function gotfileentry(fileentry) { fileentry.file(gotfile, fail); } function gotfile(file){ readdataurl(file); } function readdataurl(file) { var reader = new filereader(); reader.onloadend = function(evt) { console.log("read data url"); console.log(evt.target.result);

ios - How to create a "live" icon like in Mac OS with the red circle in its top corner? -

i wonder, possible create icon or widget or whatever it'll in linux or windows it'll act icons in mac os in dock or osx in sense it'll show red number of (unread messages, usually) in top corner when occurs. if yes how? maybe mean badge number ? [[uiapplication sharedapplication] setapplicationiconbadgenumber:4];

android - How to request new facebook permission without logging out -

i integrating facebook login , publish feed in application. , using android simple facebook i implemented login flow, , working on publish flow. want following: when user clicks on share facebook button in app, don't want publish directly want publish permission can publish later (similar instagram, permission @ first , publish when add photo). for have done this: if (msimplefacebook.islogin()) { //the user logged in proceed if (msimplefacebook.getgrantedpermissions().contains( permission.publish_action.getvalue())) { haspermission = true; } else { //we don't have permission request it. msimplefacebook.requestnewpermissions( socialutilities.getfacebookpublishpermissions(), true, newpermissionlistener); } } however if logged in , have session prompted login again before getting permission. have looked in code of simple facebook library , appears logging out , logging in again, , after login req

javascript - Resetting KeyPressed() in Processing -

i have couple of functions in draw method right activated key presses. basically, there's complex grid of squares , each square's color filled in based upon key user presses ('a' makes red, 'b' makes green, etc), method assigned each square. however, each time first key pressed, fill in of squares based upon key (for example, if first key user presses 'a', squares red instead of first one). how make first key pressed applies first method, second key applies second method, , on, when it's in looping draw() method. here's overly-simplified version below: void draw(){ boxone(); boxtwo(); } void boxone(){ if(keypressed){ if(key == 'a'){ fill(red); } if(key == 'b'){ fill(green); } rect(10, 10, 10, 10); } } void boxtwo(){ if(keypressed){ if(key == 'a'){ fill(red); } if(key == 'b'){ fill(green);

c# - Create circle around point in dynamic display data map by radius and angle -

i using microsoft visual 2010 dynamic data display dll need circle around point angle , radius. have been successful it's wrong, think so. first of all, source code: i got preps mouseclick (it's not problem point perfect working can see next in picture) // x position of pointclicked cx = (double)preps.x; // y position of pointclicked cy = double.parse(this.plotter.viewport.transform.datatransform.viewporttodata(preps).y.tostring()); // new x position of pointclicked angel math calculation xendp = (float)(double.parse(txt_enterradius.text.tostring()) * math.cos(a * math.pi / 180f)) + cx; // new y position of pointclicked angel math calculation yendp = (float)(double.parse(txt_enterradius.text.tostring()) * math.sin(a * math.pi / 180f)) + cy; secondly actualy got : @ middle got perfect circle, in north , south circle type of ellip

python - What encryption is used by default SecureSocial for SecureSocialPasswordHasher? -

i've got passwords on datastore hashed using method securesocialpasswordhasher.passwordhash package securesocial.utils.securesocialpasswordhasher of securesocial , , have validate them through python. therefore, use of securesocial (or whole play framework) out of question. question is: use hashing when calling method? documentation seems bcrypt , wasn't clear enough me sure. ---------edit--------- i've been told on securesocial forums indeed uses bcrypt work factor 10 default. doens't reflect see on datastore. there 2 columns there, 1 salt, , 1 fro hashed password. neither of them have bcrypt header (such $2a$10$ ). also, salt size 11 characters long, , hashed password 22 characters long (and no signs of having salt inside string). found out default hashing passwords on securesocial indeed bcrypt . the default implementation it's hash method is: def hash(plainpassword: string): passwordinfo = { passwordinfo(id, bcrypt.hashp

amazon web services - Specifying Docker daemon host in Elastic Beanstalk -

i'd set proper docker host when running daemon on boot. is there way can pass runtime flags? ideally i'd reproduce: docker -h 0.0.0.0:2375 -d & i've been looking @ same , seems "right" way depends on system using. ubuntu-based systems the official docs explain ubuntu under networking section . update docker_host variable in /etc/default/docker , restart docker daemon. beanstalk docker ami the file in different location: /etc/sysconfig/docker , contains setting other_arg"-r=false" . add options want pass docker daemon @ startup. restarting docker daemon as not familiar internal workings of eb , how docker daemon run, i'd suggest rebooting ec2 instance afterwards. start docker modified settings in appropriate file. i hope helps.

c++ - Destructor called when objects are passed by value -

even though objects passed functions means of normal call-by-value parameter passing mechanism, which, in theory, protects , insulates calling argument, still possible side effect occur may affect, or damage, object used argument. example, if object used argument allocates memory , frees memory when destroyed, local copy inside function free same memory when destructor called. leave original object damaged , useless. this written in c++: complete reference in program here #include<iostream> using namespace std; class sample { public: int *ptr; sample(int i) { ptr = new int(i); } ~sample() { cout<<"destroyed"; delete ptr; } void printval() { cout << "the value " << *ptr; } }; void somefunc(sample x) { cout << "say in somefunc " << endl; } int main() {

php - Android MYSQL Select * to Consctruct Java Object -

Image
i trying retrieve data mysql database in android using following code: ... httpresponse response = httpclient.execute(httppost); bufferedreader in = new bufferedreader( new inputstreamreader(response.getentity() .getcontent())); stringbuffer sb = new stringbuffer(""); string line = ""; while ((line = in.readline()) != null) { sb.append(line); break; } in.close(); responsestring = sb.tostring(); responsestring = responsestring.substring(0, responsestring.length() - 1); showmessage(responsestring); system.out.println(responsestring); // handle response user.orderlist.clear(); string[] tmp1 = responsestring.split("\\|");

cryptography - MSCAPI : CNG and Security Descriptors -

the windows api provides ways set security descriptors on objects (allowing setup of access control lists , instance). security descriptors of cryptographic keys hosted key storage provider (ksp) can valued using ncryptsetproperty (and proper set of flags , parameters). the cryptography provider development kit (cpdk) doesn't require mandatory support of security descriptors though (and on dedicated servers no user account created, might not useful set access control list indeed). does know if security descriptors support ksp expected microsoft applications despite everything? (like active directory certificate services, instance)

ios - Navigating storyboard and sending data -

this link storyboard, want sent data vc 1 vc 3 . can travel vc 1 vc 3 segue perfectly,but cant sent data vc 1 vc 3 , cant create instance holding destination vc . help appreciated edit: vc1 firing [self performseguewithidentifier:@"firstseguefromleft" sender:self]; this segue first segue left (topone) cannot sent data vc3 method, traveling it. i getting error "unrecognized selector" when try access property declared in vc3 in prepareforsegue of vc1. solved : i able nsuserdefault. looked @ apple documentation @ how implemented , voila.

d3.js - python-nvd3 two and more graphs on a page -

thanks python-nvd3 can produce beautiful interactive graphs! but, id put 2 graphs on single page. far figure out how manually concatenate 2 python-nvd3 generated html files. (and thinking python script automate it, hoping there shortcut) how automatically in python-nvd3? i wanna this: http://i.stack.imgur.com/bulfs.png thank you! solved problem hand, beautiful soup. in python-nvd3 generate html plots, parse them beautiful soup, , append bodies elements plots first one, , write disk. couple of lines. btw, handy thing html parsing: http://www.crummy.com/software/beautifulsoup/

javascript - Can't seem to properly link an external java script -

i using wamp installation on localhost. teaching myself html/javascript/ect following tutorials on w3schools. works correctly if use following web code: <!doctype html> <html> <body> <h1>my first web page</h1> <p id="demo">my first paragraph.</p> <script> document.getelementbyid("demo").innerhtml = "paragraph changed."; </script> </body> </html> i trying move javascript separate file , isn't working. contents of html (in "index" file): <!doctype html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <script src="test.js"></script> </head> <body> <h1>my first web page</h1> <p id="demo">my first paragraph.</p> </body> </html> contents of test.js <script> document.getelementbyid(

coldfusion - check the result of a CFQUERY via CFIF statement -

i having issue sytnax on how value database , check value in if statement in coldfusion this have far: <cfquery name="reservecheck" datasource="rc"> select comp_type partnercompany comp_id = "#cookie.risourceusrid#" </cfquery> <cfoutput> <cfif #reservecheck# neq 4> <li><a href="http://mywebsite/gonow/index.cfm" title="product search" target="_blank">product search</a></li> </cfif> </cfoutput> change this: <cfif #reservecheck# neq 4> to this <cfif reservecheck.comp_type neq 4> this assumes query returns 1 row. if query returns more 1 row, code in answer looks @ first row. may or may not want.

javascript - Slick Carousel unable to call Methods -

i have several instances of slick carousel gallery set , working properly. however, cannot call methods described in documentation. ( http://kenwheeler.github.io/slick/ ) whenever try target existing instance of carousel, following error: "uncaught typeerror: cannot read property 'changeslide' of undefined." i'm trying automatically goto next slide after gallery initiated. i've put jsfiddle replicate issue: http://jsfiddle.net/d32x7nqp/ var gallery = $('.slick-container'); gallery.slick({ speed:100, dots:true, oninit: function(){ gallery.slicknext(); } }); error: uncaught typeerror: cannot read property 'changeslide' of undefined targeting this, $(this), $('.slick-container') , , gallery produce same exception. appreciated, thank you!! edit thanks sunand fix! dealing same issue, move method out of oninit callback. apparently slick instance not initialized when on

SQL SERVER - Efficiently joining two tables using BETWEEN operator -

i've seen similar posts, however, no conclusive answers. i using geolite (free database) lookup ip block geo ip, , in bulk- the respective ip's converted ipblocks, , sit table ( l ). every ipblock falls within range (between startipnum , endipnum), sits in table ( g ). the query below works, however, extremely inefficient since need perform on large time period - select l.ipaddress, g.locid l inner join g on l.ipblock between g.startipnum , g.endipnum both tables indexed (g compound indexed), a hash join cannot performed since join made on between operator. is feasible option restructure table g ? or there way? the best index a single query 1 has columns in where / join clause in nodes, , columns in select clause in leaf (if not in node already). try putting index on table l , see if performance improves: create index idx_l_ipblock on l (ipblock) include (ipaddress)

algorithm - Understanding divide and conquer paradigm -

suppose have 1d array = [0...n-1]. define "hole" position in adjacent positions greater it. 1d means [i] < [i-1] < [i+1] (if 0 check i+1 , if n-1 check n-2). divide , conquer method solve in 1d case, or in case of square matrix? in square matrix, (0,0) hole if it's less (0,1) , (1,0) (so corners corners). i feel understand divide , conquer, when comes applying problems stumped. asked 1d question in interview , failed solve it. interviewer told me 2d square case challenging extension practice (that hardly able solve in full). i'm happy psuedocode, want idea of what's going on.

c# - Creating a windows service from a windows forms application -

i have windows forms application, wonder how can modify windows service application. application windows forms configure parameters windows service. example: have button set windows service parameters. thanks, rodrigo you can start service setting startup parameters through form application using servicecontroller class available under namespace system.serviceprocess. servicecontroller service = new servicecontroller(); string[] args=new string[2]; args[0] = "your first argument"; args[1] = "your second argument"; service.displayname = "your service display name";//as appears in services.msc service.start(args);

xml - Android text alignment changed automatically -

Image
trying create layout working yesterday today opened xml view text of controls right aligned happen every screen. <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bg" > <relativelayout android:id="@+id/layout_logo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_above="@+id/layout_loginarea" android:gravity="center_horizontal" > <imageview android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/logo" /> </relativelayout> <linearlayout android:id=&qu

c# - WPF usercontrol Twoway binding Dependency Property -

i created dependency property in usercontrol, changes in usercontrol not notified viewmodel usercontrol <usercontrol x:class="dpsample.usercontrol1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:ignorable="d" d:designheight="300" d:designwidth="300"> <grid> <textbox x:name="txtname"></textbox> </grid> usercontrol.cs /// <summary> /// interaction logic usercontrol1.xaml /// </summary> public partial class usercontrol1 : usercontrol { public usercontrol1() { initializecomponent(); } #region sampleproperty public static readonly dependencyproperty s

java - How to customize the SpEL parser in Spring? -

spel excellent feature provided spring, sometimes, little tedious use spel call class constructors, example <bean id="plainpojo" class="mypackage.pojo"> <property name="date" value="#{new java.util.date()}"/> </bean> in order initiate date instance, have include fully-qualified name of date class. there way can define customize spel parser don't have write fully-qualified name of class want use? by way, ok write spel this: <bean id="plainpojo" class="mypackage.pojo"> <property name="name" value="#{new string('myname')}"/> </bean> the string class in java.lang package, think default spel parser spring framework used has include path java.lang . when using spel programmatically, can inject standardtypelocator evaluation context, after adding packages standardtypelocator using registerimport() . (that's how when using spel i

antlr4 - Correct way to address wrong grammar in ANTLR -

i use antlr parse programming language. according antlr book (chapter 9.4) implemented "error alternatives". easy implementation described in book notifying error listener: ..... | id '{' expr '}' '}' {notifyerrorlisteners("too many braces");} ..... after reading book thought easier implement notifications listeners wrote in baselistener: public void exitexprerror(@notnull myparser.exprerrorcontext ctx) { parser.notifyerrorlisteners(ctx.start, "too many braces", null); } in listener can extract start , stop token context gives me finer grained control mark error (ctx.start). however listener in grammar file simplier , faster implement listener. my question is: is possible add arguments listener in grammar file? something like: ..... | id '{' expr '}' '}' {notifyerrorlisteners(ctx.start,"too many braces");} .....

Hadoop: installation problems -

i have installed hadoop, have set java_home, still getting error, why? /opt/hadoop/2.5.1/sbin: $java_home -bash: /opt/java/6.0: directory /opt/hadoop/2.5.1/sbin: ./start-dfs.sh starting namenodes on [localhost] localhost: error: java_home not set , not found. localhost: error: java_home not set , not found. starting secondary namenodes [0.0.0.0] 0.0.0.0: error: java_home not set , not found. /opt/hadoop/2.5.1/sbin: if try: sh start-dfs.sh start-dfs.sh: 82: /opt/hadoop/2.5.1/sbin/../libexec/hadoop-config.sh: syntax error: word unexpected (expecting ")") use bash , not sh invoke scripts. solved problem.

metaprogramming - Ruby list an objects instance methods without it's getters and/or setters -

i'd able list of objects classes instance methods without getters , setters attr_accessor . i've written example , behaves way need to. i find hard believe there isn't easier way this. class object def instance_methods_without_variables self.class.instance_methods(false).reject {|x| x.to_s.include? "=" } - self.instance_variables.map {|x| x.to_s[1..-1].to_sym } end end class testclass attr_accessor :var1, :var2 def initialize @var1 = 'var1' @var2 = 'var2' end def method1() 'method1' end def method2() 'method2' end end t = testclass.new p t.instance_methods_without_variables # => [:method1, :method2] edit: after reviewing answers i've opted use following method within class , not object. def instance_methods_without_variables self.class.instance_methods(false).reject { |method| self.instance_variables.any? { |variable| method.to_s.include? variable.to_s[1..-1] } || me

How do 'for in' loops work in python? -

i'm new python (after c, c++). learning fine until got stuck @ 'for x in' loops. specific take example in program lists prime numbers: num in range(10,20): in range(2,num): if num%i == 0: j=num/i print ('%d equals %d * %d' % (num,i,j)) break else: print (num, 'is prime number') what happening in first 2 lines of code? how code flowing? please elaborate. for num in range(10,20): this creates range object (representing numbers 10 19 inclusive) , num iterates through it in range(2,num): this creates range object (representing numbers 2 num-1 inclusive) , i iterates through it much same as: for (int num = 0; num < 20; ++num) { (int = 2; < num; ++i) { in c-like languages, , no more ambiguous. at end of loop, else clause run if loop didn't encounter break statement.

script popup for android and iOS - for your device exist app, how? -

i developed simple android , ios app. want when user in site (from mobile phone), popup text redirect google play or apple store, "for device available android or ios application". my question how that? script can put in website when user surfing on website mobile device popup information exist mobile application device? thank you the way this, first find mobile type using mobile agent , base on redirect correct locations. e.g. putting java scripts on top of header page between <head></head> <script> if( /iphone|ipod/i.test(navigator.useragent) ) { window.location = "your apple app url goes here"; } else if( /android/i.test(navigator.useragent) ) { window.location = "your google play app url goes here"; } </script>

css - Selecting a class in Sass -

i have form has label on each input: <label>my label</label> i style with: label { &:before { background-color: red; } } i add class each label: <label class="blue">my label</label> <label class="yellow">my label</label> how can select before each class in sass? label { &:before { background-color: red; &.blue { background-color: blue; //??????? } } } please note, reason use ::before selector more complex changing labels background colour, have used simple example. here couple ways of writing sass generate label:before , label.blue:before , label.yellow:before label { &:before{ background-color:red; } &.blue:before{ background-color: blue; } &.yellow:before{ background-color:yellow; } } label { &:before{

unity3d - Unityscript transfer boolean value between functions -

i'm having bit of trouble unityscript. what want have gui message appear when objects touched (then vanish after time). think have worked out, message trips automatically. my attempted solution have conditional part of gui message allows appear when boolean true. in different script tripped when object touched, boolean set true, script can run, , reset boolean false. however i'm getting "you can call gui functions inside ongui. i'm not sure means. message code: youdied.js static var deathmessageshow : boolean = false; function ongui() { if(deathmessageshow == true){ if(time.time >= 5 ) gui.box(rect(200,300,275,150),"you died"); } deathmessageshow = false; } other code (truncated): dead.js function ontriggerenter() { //code resets environment youdied.deathmessageshow = true; } any suggestions on going on, or better solution appreciated. the following code show gui message 5 seconds hides it: youdied.js static

Regex help for ##.#.##.## -

i'm not sure how double digit regex numbers this have far [01-99]\.[0-4]\.[01-99]\.[01-99] the following should validate: 99.3.24.53 01.0.0.0 14.0.0.0 14.0.01.01 14.01.01.1 any letter should not validate, no slashes either. numbers , periods in specific format ##.#.##.## any appreciated! this matches of examples: \d{2}\.0?[0-4]\.\d{1,2}\.\d{1,2} i'm not sure how double digit regex numbers if ok leading zeroes: \d{1,2} if not ok leading zeroes, it's little more complicated: ^[1-9]\d$|^[1-9]$ . part before pipe handles numbers 10-99. part after pipe handles numbers 1-9. number 0 or 04 not match.

c++ - Implementing own data types in C# without enum? -

the main difference between built-in data types , user defined data types that: built-in data types can accept literal values(values inserted code directly,this process know hard-codding). so possible create custom data type same boolean accepts 3 values: yes/no/maybe without using enums. such following code: mycustomboolean = maybe; i asked above question because want understand built-in data types in c# instructed in core language(such c++ int,char...) or no? ---update--- for second question,let me ask question make 2nd question more clear: i know example string alias of system.string pure string in c# works without system.string? there no ways you've requested. can create constant fields in c# can accomplish result (named values) integral types or strings - in other words, things can use compile-time constants. can particularly useful otherwise magic values . public const string maybe = "maybe"; public const int maybe = 0; one way aroun

vba - IsFileOpen() NeverSees File as Open? -

in vba (from ms access) trying determine if xls file open calling following function, sending full path , filename: function isfileopen(filename string) dim ff long, errno long on error resume next ff = freefile() open filename input lock read #ff close ff errno = err on error goto 0 select case errno case 0: isfileopen = false case 70: isfileopen = true case 53: isfileopen = false ' file not found case else: error errno end select end function this routine ever returns (0) - file closed - regardless of status of file in question. have confirmed path , filename correct, constructed in access follows: strpath = left(currentdb.name, instrrev(currentdb.name, "\")) myfile = strpath & myinvid & "changetemplate.xlsx" any thoughts might missing here? thanks! argh! xls being saved accessmode := xlshared the file passed lock test routine. << topic clo

swing - How to add actions to a button in java -

i have been working java buttons, , have created button ,but when click button, want shape of object change. code i've worked on import java.awt.*; import javax.swing.*; import java.awt.event.*; public class shapes { public static void main(string[] a) { jframe f = new jframe("change shapes"); f.setdefaultcloseoperation(jframe.exit_on_close); jbutton b = new jbutton("shapes change"); f.getcontentpane().add(b); f.pack(); f.setvisible(true); } public void paint (graphics g) { //no clue here } private static abstract class mybutton extends jbutton implements actionlistener { mybutton() { addactionlistener(this); } public void actionperformed(actionevent e) { if (e.getsource() == b) { //no clue here } } } } at first, there shape created, once button clicked want change shape. there should need subclass jbutton . if want customise button, use action api inst

How to receive notifications from Paypal -

i'm hoping can point me in right direction have next no experience of integrating paypal. i wanting set subscription service on website working on. though i'd use basic buttons paypal provides , include type of token in return url. use token update back-end systems user in question had paid. i realised wouldn't receive notifications paypal if user unsubscribes through paypal website. is ipn solution best suited subscriptions. thanks, david yes, ipn best suited receiving notifcations , updating backend. there similar feature called "payment data transfer" (pdt) but, pdt applies website payment standard , has few limitations. i recommend using ipn, generic feature paypal products available , more secure , reliable pdt. advantages

javascript - Google map need page refresh before showing map pins -

i have code show multiple addresses on google map. the problem being when page first loads map shows blue sea , not geocode addresses, imagine using lat long of 0,0. when reload page, finds addresses , shows them on map. if leave page , come it, works, imagine, due caching. i need working , totally stumped. any ideas? function initialize() { var addresses = [ '60 hednesford road cannock west midlands ws11 1dj','172 high street bloxwich west midlands ws3 3la',]; var myoptions = { zoom: 10, center: new google.maps.latlng(0, 0), maptypeid: 'roadmap' } var map = new google.maps.map($('#map')[0], myoptions); var markerbounds = new google.maps.latlngbounds(); var infowindow = new google.maps.infowindow(); function makeinfowindowevent(map, infowindow, marker) { google.maps.event.addlistener(marker, 'click', function() { infowindow.open(map, marker); });

php - if query is not update -

i know best way make query's if statement. because use 1 function codeigniter edit main function, so combines both query's , makes if query not update insert way best way public function addusergroup($data) { $this->db->query("insert " . $this->db->dbprefix . "user_group set name = " . $this->db->escape($data['name']) . ", permission = " . (isset($data['permission']) ? $this->db->escape(serialize($data['permission'])) : '') . " "); } public function editusergroup($user_group_id, $data) { $this->db->query("update " . $this->db->dbprefix . "user_group set name = " . $this->db->escape($data['name']) . ", permission = " . (isset($data['permission']) ? $this->db->escape(serialize($data['permission'])) : '') . " user_group_id = '" . (int)$user_group_id .

android - Python can not capture full adb logs -

what want achieve - running adb log (logs running), doing activity on android, stop/end log capture (ctrl+c), post processing of logs. only issue face - can not capture full logcat log in file import sys import subprocess import time import ctypes # start print "test start" time.sleep(5) # log capturing start, log not stop keep on running proc = subprocess.popen("adb logcat -v time",stdout=subprocess.pipe ) time.sleep(3) # runs while print "calc start" time.sleep(5) #start test************************************ code testing #ctrl c************************************************* try: ctypes.windll.kernel32.generateconsolectrlevent(0, 0) proc.wait() except keyboardinterrupt: print "ignoring ctrlc" print "still running" #********************adb log saving****************** text = proc.stdout.read() f = open('c:\python27\out_logs_dd\log.txt', 'w') f.write(text) open('c:\python27\o

Convert folder backups to Git repo -

i have inherited project not developed using scm whatsoever. instead have series of folders like: my-project.201109011234 my-project.201110010908 my-project.201202040454 my-project.201203011123 ...and on... each folder complete copy of source code, , folder named after timestamp of when copy made. changes abound between each copy, i.e. files , folders added, removed, renamed , file contents changed. is there sort of tool, can feed list of folders , create git repo me, each folder becomes commit? after hope git knows changed between each commit? thanks adam. it sounds me particular problem solve (i.e. there isn't tried , tested method integrate git). that said, solution devised bit of shell/python/xyz scripting. steps these: make empty git repo make list of archives, sorted chronologically for each archive: delete contents of project directory (everything except .git directory) unzip archive project dir run "git add -u ." in directory run &q

PHP XML - get all attributes of segment by it's id -

i've got new question: is there way attributes of xml element when i'm selecting element it's id ? i've got xml response looks this: <availresponse> <tarifs currency="pln"> <tarif tarifid="206844566_206844566" adtbuy="167.96" adtsell="167.96" chdbuy="167.96" chdsell="167.96" infbuy="167.96" infsell="167.96" taxmode="incl" topcar="false" tophotel="false" adtcancel="0.0" chdcancel="0.0" infcancel="0.0" powerpricerdisplay="sell"> <farexrefs> <farexref fareid="206844566"> <flights> <flight flightid="1663150500" addadtprice="0.0" addchdprice="0.0" addinfprice="0.0" extflightinfo="lowest fare"> <legxrefs> <legxref legid="1981746874" class="r" cos="e" co

html - Facebook share button in hidden div -

i need show fb-share-button in div . div hidden display:none css property. in ie when fb-share-button in hidden div , button doesn't show, , when div showed button continues hidden. i try wait button loaded , hide div after, have no success. this code: master.page: <div id="fb-root"> </div> <script> (function(d, s, id) { var js, fjs = d.getelementsbytagname(s)[0]; if (d.getelementbyid(id)) { return; } js = d.createelement(s); js.id = id; js.src = "//connect.facebook.net/es_es/sdk.js#xfbml=1&appid=536816803117001&version=v2.1"; fjs.parentnode.insertbefore(js, fjs); } (document, 'script', 'facebook-jssdk')); </script> the code show content , buttons: <div id="sp_publicacionescapsula1" class="sp_publicacionesseccionoff"> <ul class="sintipo sinmarginsinpadding"> <% (int1

c - arranging the numbers with duplicate entries deleted -

#include<stdio.h> int main(){ int a[9],i,j,r,t,min,c=0; for(r=0;r<9;r++) scanf("%d",&a[r]); (j=0;j<9;j++) { min=a[j]; for(i=j;i<9;i++) { if(a[i] < min ) { c=i; min=a[i]; } } t=a[j]; a[j]=min; a[c]=t; } for(r=0;r<9;r++) printf("%d",a[r]); } this code have arrange numbers entered byt user in ascending order. if input 1 2 3 2 4 1 5 6 3 output 1 1 2 2 3 3 4 5 6 want output 1 2 3 4 5 6 i.e. duplicate entries deleted.please me. if range of numbers given can using boolean array store 1 corresponding index of element. #include <stdio.h> #include <stdbool.h> #define num_range 10 int main(){ int num; bool freq[num_range + 1] = {0}; for(int r = 0; r < 9; r++){ scanf("%d",&num); freq[num] = 1; } (int = 0; < num_range + 1; i++) if(freq[i]) printf("%d ", i); }

javascript - Add optgroup to dropdown created dynamically using REST, jQuery and Boostrap -

this first project using bootstrap , i'm pretty new jquery also, hope question not simple of you. have drop-down have created pulling data sharepoint using rest , ajax. part works great. js: $(document).ready(function () { var requesturi = "blah-blah/_api/web/lists/getbytitle('ad_db')/items?select=title,state"; var requestheaders = { "accept": "application/json;odata=verbose" } $.ajax({ url: requesturi, type: 'get', datatype: 'json', async: false, headers: requestheaders, success: function (data) { $.each(data.d.results, function (i, result) { var itemcasenumber = result.title; var itemstate = result.state; $('#mylist').append('<li role="presentation"><a role="menuitem" tabindex="-1" href="#">' + itemcasenumber + '</a></li>'); }); }, error: functi

css - How is "width: 100%" computed when I add an element to a table cell dynamically? -

backgrid allows editing values in table, , accomplishes putting <input type="text"> inside <td> . input set max-width: 100% still pushes size of column out farther in cases. for example, see grid on examples section , click item in "population" column. when gets editor class, padding set 0, , both <td> , <input> have box-sizing: border-box , width of column still increases. so width: 100% not mean 100% of width of <td> @ time? or not possible make work using css only? use backbone event size of td , set input same size sounds bit hacky. the way width of table columns calculated not trivial. try distribute available space among columns in way columns more content gets bigger share. if go , "the content should big column" make more complex because create ciruclar dependency between content width , column width. so width: 100% not mean 100% of width of <td> @ time? no. when changes, upda

Django Model instance value in ModelForm constructor -

i create dynamic form based on modelform . aim add fields information in json field. class myform(forms.modelform): class meta: model = mymodel fields = ['name', 'json'] def __init__(self, *args, **kwargs): super(myform, self).__init__(*args, **kwargs) [ create fields here] i can create fields dynamically this: variables = ('var_1', 'var_2',) v in variables: self.fields[v] = forms.charfield(label=v) now, replace variables json.variables value. tried this: self.fields['json'].initial , self.fields['json'].data , self.fields['json'].cleaned_data without success. do know how can have access model value? finally solution quite easy. have use self.instance.json .