Posts

Showing posts from February, 2010

android - Error trying to call .buildClassifier (Weka) in Java AndroidStudio -

i trying use weka in android studio. , stuck @ line: linearregresion.buildclassifier(data); its red underlined , says: unhandled exception:java.lang.exception i trying other ways , different dataset , allways underlined @ .buildclassifier //test: naivebayes nb = new naivebayes(); nb.buildclassifier(dataset); //unhandled exception classifier cmodel = (classifier)new linearregression(); cmodel.buildclassifier(data); //unhandled exception trying fix hours, couldn't find solution on internet,i think missing maybe need import more? i doing tutorial code should work. tutorial: http://www.ibm.com/developerworks/opensource/library/os-weka3/index.html whole code import weka.*; import weka.classifiers.trees.j48; import weka.core.*; import weka.classifiers.classifier; import weka.core.instance; import weka.core.instances; import weka.classifiers.functions.linearregression; import weka.classifiers.bayes.naivebayes; public class meni extends acti...

How to remove comment HTML element in a String in iOS -

this last part of string: </div> </noscript><!-- g3.js-t oldalanként egyszer, </body> zárótag előtt kell meghívni --> <script type="text/javascript" charset="utf-8" src="//ad.adverticum.net/g3.js"></script> <div id="autosuggest"><ul></ul></div> </body> </html> and how want remove comment element, not work: var regex = nsregularexpression(pattern: "<!--[^<]*-->", options: nsregularexpressionoptions.caseinsensitive, error: nil)! str = regex.stringbyreplacingmatchesinstring(str, options: nil, range: nsmakerange(0, count(str)), withtemplate: "") any idea why? you can try using different regex: var regex = nsregularexpression(pattern: "<!--[\\s\\s]*-->", options: nsregularexpressionoptions.caseinsensitive, error: nil)!

java - Lambda Expressions functional programming -

i have programm regular expression lambda expressions university. got stuck 2 methods in method. here code: static string ausdruck = "abcd"; public static function<string, string> char = (c) -> { return (ausdruck.startswith(c)) ? ausdruck = ausdruck.substring(1, ausdruck.length()) : "value error"; }; public static bifunction<function<string, string>, function<string, string>, function<string, string>> , = (f1, f2) -> {return null;}; what want in and method is: char(char.apply("a")) -> want call function f2 f1 parameter. call of , method have like: and.apply(char.apply("a"), char.apply("b")); if understand question correctly, want create function compones new function, executing 1 function result of function. best way in lambda return new lambda. try this: bifunction<function<st...

excel - Avoid creation of duplicate sheet -

i trying make macro make budgets. have different business units multiple cost centers. want circulate macro enabled worksheet different business units , make budget predefined parameters. while doing setup, user selects business unit, available cost centers under same business unit creates 1 sheet each predefined names. problem is, if user go same setup again , select same business unit, show run time error sheet name cannot changed 1 sheet same name exist. i tried use on error function, new sheet created eg: sheet16. my requirement either continue file if nothing happened or pop msgbox predefined error message without creating new blank sheet. any ideas? you can first check if sheet exists , handle situation. can use following loop: for each in activeworkbook.sheets s = i.name ' name next

html - jQuery edit content of li element -

i'm making simple todo list jquery , stuck problem on how edit content of li element double clicking. wrote function, doesn't work. here code: http://jsfiddle.net/strangeviking/1vwho2ru/3/ : function addlistitem() { var text = $('#new-text').val(); $("#todolist").append('<li><input type="checkbox" class="edit" />' + text + ' <button class="delete">delete</button></li>'); $("#new-text").val(''); }; function deleteitem() { $(this).parent().remove(); } function finishitem() { if ($(this).parent().css('textdecoration') == 'line-through') { $(this).parent().css('textdecoration', 'none') } else { $(this).parent().css('textdecoration', 'line-through'); } } function edititem(e) { var $input = $(e.target).closest('li').addclass('editing').find('.ed...

failed installation - VS 2013 Ultimate, KB2829760 error on update 4 -

i attempting install update 4 (vs2013.4.exe) on update 3 , error kb2829760, hash value incorrect. i had cleaned pc , fix registry using ccleaner not helping log file: https://paste.ee/p/hqrxk i checked log , find following: error 0x80091007: hash mismatch path: c:\programdata\package cache.unverified\preparation_uninstall_vsupdate_kb2829760, expected: 99574152b1d10d8518e3aff5ffd4c5a0728238af, actual: 3f5c631f9622cd4062be85385e22d981bdec5c46 please check following msdn link solve issue: http://blogs.msdn.com/b/heaths/archive/2014/05/01/incorrect-hash-value-when-installing-visual-studio-2013-update-2.aspx let me know if you.

RethinkDB grouping and defining output -

i have table contains documents similar this: { "title": "title 2", "content": "this far, no further!", "category": "fiction" } this query i'm using: r.table('posts').group('title').map(lambda item: {'items': item['title']} ).run()) this output: { "title 1" : [ { "items" : "title 1" }, { "items" : "title 1" } ], "title 2" : [ { "items" : "title 2" }, { "items" : "title 2" }, { "items" : "title 2" }, { "items" : "title 2" } ], "title 3" : [ { "items" : "title 3" } ] } however output structure looks this: { "title 1" : { "item_count" : 3, "items" : [ {...

mongodb - Mongo DB: cross collection query (join style) -

i have db 2 collections: users , pages . in app each user can have 0 or more pages , each page belongs 1 or more users . each user has pages property consisting in array of objects id (not default _id field custom id coming social network i'm taking page data from) of page , couple other page info. pages have lot of props, 1 of is_synced (boolean). i want query users own synced pages (i want properties of page object, title ). i tried javascript function in console foreach ing on users query respective pages takes lifetime complete. i have no indexes on collections except default ones on _id fields (don't know how set/use them). what approach suggest? should make index on page custom id field? should save needed page properties in users collection if not needed application logic administration purposes? should perform form of aggregation (map/reduce or similar)? update as suggested i'm adding simplified version of json models... user { ...

Hadoop - Oozie : check if existing oozie workflow is running -

i have oozie co-ordinator jobs run @ 11:00am, 12:30pm,4:00pm, 7:00pm , 9:30pm. workflow these co-ordiinator jobs same run @ different times without specific frequency. if frequency same have done 1 co-ordinator job. my question how know co-ordinator job still running , make other co-ordinator job wait/sleep untill existing 1 running? can through oozie or need write seperate oozie api/javascript or shell script check it? thanks, asmath. you synchronize execution of workflows in different coordinators making use of <input-events> tag of coordinator. for example create directory like /some/hdfs/dir/coorda-status/success-2016-01-26 at end of every successful run of workflow run coordinator a. then make existence of directory condition coordinator b run via <dataset> , <input-events> tags.

php - ZF2 - issue with implementing Bootstrap Datetime picker in edit mode -

i implemented eonasdan-bootstrap-datetimepicker in zf2 application. see here implementation in add mode: <div class="form-group <?= ($this->formelementerrors($event->get('date'))) ? 'has-error' : ''; ?>"> <?php echo $this->formlabel($event->get('date')) . php_eol; ?> <div class="input-group date" id='date'> <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> <?php echo $this->formtext($event->get('date')) . php_eol; ?> </div> <?php echo $this->formelementerrors($event->get('date')) . php_eol; ?> </div> <script type="text/javascript"> $(function() { $('#date').datetimepicker({ format: 'dd-mmm-yyyy' }); }); </script> this works fine....

ms access - Update specific values in more than one column - SQL -

Image
i have table contains 2 columns, both have email values. want create query update specific data in both columns. for example if have 2 records of email 'a@aa.aa' in 1 column , 3 records of 'a@aa.aa' in other column want them both updated. here example want 'g@gg.ggg' 'a@aa.aa' : my question how query should like. the simplest way run 2 update statements: update table set col1 = <newval> col1 = <oldval>; update table set col2 = <newval> col2 = <oldval>; this begs of question of why two columns storing same data. perhaps need review data structure , use junction table information.

Fetch all feeds from my twitter timeline and show to my Android App -

i know research topic. not able find how should proceed , display accounts tweet android application. i reading document twitter , following this. https://dev.twitter.com/rest/tools/console i not able figure out how use this. as per understanding should use https://api.twitter.com/1.1/statuses/user_timeline.json not able figure out how proceed. if body know example or make me move ahead. in order achieve need download 1 of packages available access twitter api using proper token , key required. some of these packages include tweepy or sixohsix . i'm more familiar tweepy , there's plenty of documentation lead in right direction, including youtube videos. they're both available through github. if need code specific questions of 2 need first give them try, ask new questions problems you're encountering.

c# - Weird behavior of image -

Image
i see weird behavior of image. i have 2 methods wich calculate heatmap image. 1 method works in gui thread, , other 1 in background thread. both methods should same , output png seems good. gui thread created image able loaded in, created 1 background thread not. i save calculated image file on hard drive , load in again. when load , assign image source not null. when programm leaves allocating method image.source null. don't understand why. this code: private void loadimageclicked(object sender, routedeventargs e) { this.imageheatmap.begininit(); this.imageheatmap.source = new bitmapimage(new uri(@"heatmapimage.png", urikind.relative)); this.imageheatmap.endinit(); } and how save image png: public void savefile(bitmapsource source, string filepath) { using (var filestream = new filestream(filepath, filemode.create)) { bitmapencoder encoder = new pngbitmapencoder(); encoder.frames.add(bitmapframe.create(source)); ...

java - Difference between these two "methods" for simple character encryption -

i have trouble understanding simple method encrypting characters in string. here's method: encryptedchar = (char) (’a’ + (originalchar -’a’ + offset) % 26); i don't understand need 'a' - 'a' since cancel out. reason behind it? why shouldn't use following method? encryptedchar = (char) ((originalchar + offset) % 26); shouldn't work same? encryptedchar = (char) ('a' + (originalchar -'a' + offset) % 26); the 2 'a' don't cancel each other, since second 1 inside expression operand of modulus operator. 'a' + (originalchar -'a' + offset) % 26 - here each letter mapped different letter. ((originalchar + offset) % 26) - here each letter mapped character int value between 0 , 25.

php - Deploy code with phing -

i want sync files source folder public folder phing problem when use <copy todir="${libdir}"> <fileset dir="${gitdir}"> <include name="**"></include> <exclude name="public/**"/> </fileset> </copy> or <filesync sourcedir="${gitdir}" destinationdir="${libdir}" verbose="true" checksum="true" /> the script doesn't remove files ${libdir} doesn't exist in ${gitdir}. don`t want first remove hole directory , after copy files. should works take more time. know how can sync folders , remove nonexistent files? i found decision. use linux command that: <exec command="rsync -a --delete --exclude '.git' --exclude '.svn' ${gitdir} ${libdir}" checkreturn="true" />

android - How to retrieve daily running and walking steps from Google Fit API -

it newbie question have lost 1 day figure out w/o success. i'm using google fit api android app , need show of data running , walking daily steps. have managed show data in time unit (f.e running in x min). need show in steps unit. the snipped below code shows how retrieved data time unit (in milliseconds): datareadrequest readrequest = new datareadrequest.builder() .aggregate(datatype.type_activity_segment, datatype.aggregate_activity_summary) .bucketbytime(1, timeunit.days) .settimerange(start, end, timeunit.milliseconds) .build(); fitness.historyapi.readdata(client, readrequest).setresultcallback(new resultcallback<datareadresult>() { @override public void onresult(datareadresult datareadresult) { if (datareadresult.getbuckets().size() > 0) { display.show("bucket dataset.size(): " + datareadresult.getbuckets().size()); ...

javascript - Matching charset of HTTP Header Content-Type -

in javascript, want "charset" attribute of http header field name 'content-type' the regex i've seen far has been like: var charset = (/^charset=(.+)/im).exec(contenttype)[1]; with contenttype contain informations of content-type http header. but in testing, matched result 'null' edit: follow response @andris leduskrasts, var ctype = 'text/html; charset=utf-8'; var charset = new regexp('charset=.*?(?=$|\s|\;|\")').exec(ctype); system.stdout.writeline(charset); i 'charset=utf-8'. idea 'utf-8'. ? i experienced same problem. if need extract charset value arbitrary content-type header (which permits characters after charset assignment per rfc1341 ) can use following js regexp: var re = /charset=([^()<>@,;:\"/[\]?.=\s]*)/i; this works because matched group starts after = , excludes possible endings of charset specification given in link; namely ()<>@,;:\"/[]?.= , spac...

Invalid use of incomplete type for partial template specialization c++ -

i trying specialize class method foo() . works full template specialization. however, not work partial template specialization. here example code compiles fine on gcc , clang : #include <iostream> #include <string> template <typename key, typename value> struct simplekey { key key; value value; void foo() const { std::cout << "base" << std::endl; } }; /* // uncomment , won't work ! template<typename key> void simplekey<key, std::string>::foo() const { std::cout << "partial" << std::endl; } */ template<> void simplekey<int, std::string>::foo() const { std::cout << "full" << std::endl; } int main() { simplekey<double, std::string> key1{1.0,"key1"}; key1.foo(); simplekey<int, std::string> key2{1,"key2"}; key2.foo(); } the error on clang , gcc when uncommenting relevant code : ...

PDO MySQL and php like statement -

when execute query db: select * `task` `date_time_from` '%0000%' i few results, trying same pdo , can not manage results or errors. have done: $dbchain = 'mysql:host='.$globals['dbhost'].';dbname='.$globals['dbname']; try{ $dbh = new pdo($dbchain, $globals['dbuser'], $globals['dbpassword']); $sql = "select * task" . "where date_time_from concat('%', :datefrom, '%')"; $a = '0000'; $stmt = $dbh->prepare($sql); $stmt->bindparam(':datefrom', $a); $stmt->execute(); $total = $stmt->rowcount(); echo $total; while ($row = $stmt->fetch()){ var_dump($row); } } catch (exception $e){ echo 'error'.$e->getmessage(); } the result of $total = 0 . can tell me doing wrong? i have tried this: $sql = "select * task" ...

simple form - Rails - toggle boolean on click of a link -

i'm trying make app rails 4 , simple form. i have models separately called project, scope , finalise. finalise belongs scope. scope belongs project. project accepts nested attributes scope , finalise. scope accepts nested attributes finalise. i have attribute in finalise table called :draft. if user creates project , sets :draft true, display link, when clicked, change :draft false. i have following link in view: <%= link_to 'finalise draft', finalise_toggle_draft_path(@project.scope.finalise.id), method: :patch %> i have following method in controller: def toggle_draft @finalise = finalise.find(params[:finalise_id]) @finalise.draft = false @finalise.finalised = time.now @finalise.save redirect_to project_path(project.find(params[:project_id])) end when try this, error says: couldn't find project without id does know i've done wrong? my routes finalise are: finalise_toggle_draft patch /finalises/:finalise...

windows - Which toolbox does facebook app use -

Image
which toolbox that? i use listview now, if click it, looks choose it, not click it. so want change. your question unclear i'll share information listview. i don't know facebook app official facebook app (not beta) using listview afaik.you can customize listview's style , itemtemplate achieve that. theese 2 msdn articles listview you. https://msdn.microsoft.com/library/windows/apps/windows.ui.xaml.controls.listview.aspx https://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj709922.aspx

android - Google Play IAB: Unexpected response code 403 -

we trying implement android in-app billing in our game, made unity. plugin using seems work fine, , have been able access google's in-app billing service in older project. however, when try test purchase in our new project (using test account), getting error: "unexpected response code 403 https://android.clients.google.com/fdfe/preparepurchase ". i have searched similar cases on stackoverflow , google, none of solutions have seen fixes our problem. believe our settings should correct: - devices testing on have had main accounts added list of testers (on developer console) , not google developer accounts. - apk has been uploaded , released alpha, - in-app product testing has been activated. - permission com.android.vending.billing has been added manifest. and here our log: and here our log: d/finsky ( 3814): [407] inappbillingutils.getpreferredaccount: [our bundle id]: account first account - [j08vudqx0xyzqx40e-hxtcffleu] d/finsky ( 3814): [407] inappbillingu...

php - Why is laravel's updateOrCreate creating new records instead of updating? -

code entry::updateorcreate([ 'intern_id'=>$intern['id'], 'created_at'=>carbon::parse($input['date']) ],[ 'company_id'=>$intern['supervisor']['company']['id'], 'content'=>$input['text'] ]); i'm using code try updating/creating new record. it's suppose matche intern_id , create_at column first. if found, creates new one. however, seems creating new 1 , when creates new one, company_id , intern_id column set 0 instead of original value. note: intern_id or created_at not pk columns. note2: created_at date type, not datetime use code entry::updateorcreate(['intern_id'=>$intern['id']], [ 'created_at'=>carbon::parse($input['date']), 'company_id'=> $intern['supervisor']['company']['id'], 'content'=>$input['text'] ]); i belie...

rspec - difference between calling create and new() in ruby with rails -

suppose have class try . trying create object use in 1 of examples in rspec file. i tried writing let(:obj){obj = try.new()} , accessing in example gave error. when wrote llet(:obj){obj = try.create} , use obj , call functions without error. what difference when write try.create , try.new() in rspec file? from activerecord::base documentation: create(attributes = nil) {|object| ...} creates object (or multiple objects) , saves database, if validations pass. resulting object returned whether object saved database or not. new(attributes = nil) {|self if block_given?| ...} new objects can instantiated either empty (pass no construction parameter) or pre-set attributes not yet saved (pass hash key names matching associated table column names). in both instances, valid attribute keys determined column names of associated table — hence can‘t have attributes aren‘t part of table columns. create instantiates new object, validates it, , saves database. , new create...

android - FloatingActionButton with Multiple Actions -

i'm using floatingactionsbutton (fab) design support library (com.android.support:design:22.2.0). in application have 2 main functionalities first sync data every x minutes (which starts service , updates data every x minutes) , second sync once (which request data server , updates ui). i want use fab these main functionalities , wondering , how can make it: the first approach using 1 fab when clicked button show 2 new fabs 1 each functionality. the second approach displaying 2 fabs in ui sync every x minutes fab bigger update once fab. i interesting in first approach , wondering how can implement behaviour? looked around view new , couldn't find example. thanks. i using github library, simple , solved problems: https://github.com/clans/floatingactionbutton add dependency build.gradle: dependencies { compile 'com.github.clans:fab:1.6.4' } add beginning of xml: xmlns:fab="http://schemas.android.com/apk/res-auto" now add ...

Responsive Web Design Automatically Zoomed Some Times -

i made responsive web page media query. view on mobile device auto zoom though have not defined zoom. while used meta content "width=device-width" looks viewing on desktop browser after user have zoom out see actual view. use below meta tag in head <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

How can i set the tick text of x-axis between bar in a bar chart in c3.js or d3.js? -

js library, have problem: in graph each bar represents value produced between 2 hours, tick text below bar , want between bar ! my type of x-axis "type: 'category'" data = ['x', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00'] can me? thank in advance. i have : http://hpics.li/9fc4863 i want : http://hpics.li/1fb1090 you convert x axis timeseries , have values tagged actual midpoint of hour ranges (12.30, 1.30...) var chart = c3.generate({ data: { x: 'x', columns: [ ['x', new date('2013-01-01t00:30'), new date('2013-01-01t01:30'), new date('2013-01-01t02:30'), new date('2013-01-01t03:30')], ['data1', 30, 200, 100, 400] ], type: 'bar' }, axis: { x: { type: 'timeseries', ...

drupal - drush failing with autoload.php failed to open stream -

i searched whole drupal directory didn't find autoload.php file. see error when enabling modules using drush on command line. here exact error include(sites/all/modules/contrib/guzzle/vendor/autoload.php): failed open stream: no such file or directory composer_autoload.module:24 [warning] include(): failed opening 'sites/all/modules/contrib/guzzle/vendor/autoload.php' inclusion (include_path='.:/usr/share/php:/usr/share/pear') [warning] composer_autoload.module:24 i haven't seen error before, think it's telling you have install composer, requirement drush. see installation instructions drush: http://docs.drush.org/en/master/install/#composer-one-drush-for-all-projects .

objective c - Why can't I create an NSMutableArray of integers? -

is format not allowed in objective c? nsmutablearray arraya=[0,1,2,3,4,5]; is way adding 1 integer @ time? there 2 parts question: integers value-types , nsmutablearray can have object-types in it. as comment said, there's magic syntax: @1 which says "i know primitive, please oh mighty compiler auto-magically make object me." similarly, there's syntax: @[ ... ] which converts c-array objective-c nsarray [subclass]. so this: nsarray * array = @[ @1 , @2 , @3 , ... ] ; which give array of numbers. you'd have use them though: for ( nsnumber * number in array ) { nslog ( @"this value %i" , (int)number.intvalue ) ; // alternatively, exact same thing: nslog ( @"this value %i" , (int)[number intvalue] ) ; } if wanted make mutable: nsmutablearray * array = [ @[@1,@2,@3] mutablecopy ] ; other languages (like python) have syntax want built-in because own language , can internally represent object-t...

How to post additional parameters via JQuery with FullCalendar in Rails? -

i using fullcalendar library adam shaw rails project. currently, have when click on date, prompts input title event (and possibly other fields later down road) using select callback. to store events, using sqlite database model event . i post additional fields (such type:string model not default parameters eventobject in fullcalendar. for reason works: // js file associated calendar div $('#calendar').fullcalendar({ ... select: function(start, end, allday){ var title = prompt('event title:'); if (title){ var eventdata = { title: title, description: '', start: start.format(), end: end.format(), url: '' }; $.ajax({ url: '/events', type: 'post', data: { title: title, description: '', start: start.format(), end: end.format(), url: '', type: '' // <----...

regex - How to extract the last name in an array of a full name? -

suppose have full name in bash array, want robustly extract last name , non last name (the first name , middle name if exists). example, show following 3 examples indicate complexity of problem. x1=(john von neumann) x2=(michael jeffrey jordan) x3=(michael jordan) does have way extract last name , non last name? thanks. i'm assuming put every single name in separate array. more flexible way use regular expression. in plain english regex says: - either last name starts lowercase char followed number of alphabetic characters , spaces - or last name follows last space in string. take @ @ this: #!/bin/bash x1=(john von neumann) x2=(michael jeffrey jordan) x3=(michael jordan) x4=(charles-jean etienne gustave nicholas de la vallée-poussin) regex="[[:space:]]([a-z]+.*|[a-z][^[:space:]]+)$" in 1 2 3 4 eval name=\${"x"$i[@]} if [[ $name =~ $regex ]]; fullname=${bash_rematch[1]} echo $fullname fi done

Why does calling this Javascript function submit my form? -

i have form validation script. unless conditions met, ambiguous function associated form.onclick returns false (form doesn't submit). have function upon error append error message errorlog div. function adderror (msg) { msg = document.createtextnode(msg); br = document.createelement("br"); errorlog.append(msg); errorlog.append(br); alert("yes"); } if error found, calling function submits form. script doesnt enter function, submits data , refreshes. realize there error in function, cant seem figure out. edit: more of code form.onsubmit = function () { if (namecheck(fname, lname)) return true; return false; }; function checks if "name" field valid: function namecheck (fname,lname) { if (("/\d/").test(fname) || ("/\d/").test(lname)) { adderror('your name cannot contain numbers.'); valid = false; } } you're not stopping form submitting. ...

java - how do you download files via ant though proxy -

this question has answer here: ant task , proxy 2 answers i using ant uses build.xml file. command: java version : 1.8.0 ant version: 1.7.1 classpath=/app/hbase-0.94.27/lib/hadoop-core-1.0.4.jar cflags=-m64 cxxflags=-m64 ant compile-native tar it hangs here: buildfile: build.xml ivy-download: [get] getting: http://repo2.maven.org/maven2/org/apache/ivy/ivy/2.2.0/ivy-2.2.0.jar [get] to: /app/hadoop-lzo/ivy/ivy-2.2.0.jar i connection time out error: build failed java.net.connectexception: connection timed out @ java.net.plainsocketimpl.socketconnect(native method) @ java.net.abstractplainsocketimpl.doconnect(abstractplainsocketimpl.java:345) @ java.net.abstractplainsocketimpl.connecttoaddress(abstractplainsocketimpl.java:206) @ java.net.abstractplainsocketimpl.connect(abstractplainsocketimpl.java:188) @ ja...

javascript - Add to offsetHeight of entire class -

i have page elements in 1 class of variable heights based on size of text content of them. on page load need add 20px height of of them. var visibleposts = document.getelementsbyclassname("post-contain"); for(var =0; <= visibleposts.length; i++){ visibleposts[i].style.height = visibleposts[i].offsetheight + 20 + "px"; } that's code used. put inside of init() function runs on page load. however, i'm not sure how that's working since it's running on meteor server. have onload of body. so: <head> <script src="jquery-2.1.4.min.js"></script> <script src="main.js"></script> </head> <body onload="init();"> </body> <template name="fullfeed"> {{#each posts}} <!-- <a href="whenisay://{{adjective}}/{{noun}}/{{user}}/{{likes}}/{{date}}/{{_id}}">--> <a href="unliked.png"> <div class=...

javascript - Running into problems using React Datepicker with rails -

i using datepicker plugin react: https://github.com/hacker0x01/react-datepicker i keep getting following error: uncaught typeerror: this.props.moment not function in react-datepicker.min.js. i copied example code, , can see input field, whenever click on render calendar, keeps giving error above. know had issue in past? just resolved it, matter of not requiring "moment" js file in application.js. if use bundler install plug in sure add following gemfile: source "https://rails-assets.org" gem 'rails-assets-react-date-picker' gem "rails-assets-moment" end and require both in application.js in order: //= require "moment" //= require "react-date-picker"

entity framework - N to M relationship code first does not create the foreign key on the M-table -

a schoolclasscode can have many pupils. a pupil can belong many schoolclasscodes. this n m relation. i thought n m relation work in code first default. but explicitly create n m relation here: modelbuilder.entity<schoolclasscode>(). hasmany(c => c.pupils). withmany(p => p.schoolclasscodes). map( m => { m.mapleftkey("schoolclasscodeid"); m.maprightkey("pupilid"); m.totable("schoolclasscodepupil"); }); public class schoolclasscode { public schoolclasscode() { pupils = new hashset<pupil>(); tests = new hashset<test>(); } public int id { get; set; } public string schoolclasscodename { get; set; } public string subjectname { get; set; } public int color { ...

c++ - avoiding duplication in the assignment operator of a derived class -

consider assignment operators in classes parent , child , below. #include <iostream> class parent { public: parent(){}; virtual ~parent(){}; parent& operator=(const parent& other){mp = other.mp; return *this;}; void setp(double inp){mp = inp;}; double getp(){return mp;}; protected: double mp; }; class child : public virtual parent { public: child(){}; virtual ~child(){}; child& operator=(const child& other) { mc = other.mc; mp = other.mp;// line return *this; }; void setc(double inc){mc = inc;}; double getc(){return mc;}; protected: double mc; }; is here way avoid duplicate line mp = other.mp; ? the reason asking number of bases higher , inheritance structure gets more complicated, easy lose track of members. edit the reason need implement operator= needs check things before assignments. just call parent operator: child& operator=(const child& other) { mc = other.mc; paren...

multithreading - Python: Threading with wxPython -

i new threading , trying grip of. creating thread handle long running process separate main thread (which handles graphical user process). otherwise, have blocking gui not nice. the process keeps repeating itself, code in thread runs again instead of stopping alldone function, doesn't make sense me. no matter route code takes within run portion (whether finddomains function, searchandscrape function, or emailformat function), end @ emailformat function calling alldone function of myclass object of gui(called windowclass): class windowclass(wx.frame): def __init__(self, parent, title): super(windowclass, self).__init__(parent, title=title, size=(500, 364), style=wx.default_frame_style & ~wx.maximize_box ^ wx.resize_border) self.setbackgroundcolour('white') self.basicgui() def alldone(self, event): myclass.worker.stop() time.sleep(2) dlg = wx.messagebox("all done!", "ask alfred", wx.ok | wx.icon_inf...

python - Determining Longest run of Heads and Tails -

i have question fourth function, longestrun . want output longest run of heads , longest run of tails based on how many flips (n) user enters. have tried ton of different things, , doesn't seem work. can guys me out?: def longestrun(n): h = 0 t = 1 mylist = [] in range(n): random.randint(0,1) if random.randint(0,1) == h: mylist.append('h') else: mylist.append('t') i want next piece output 2 things. "the longest run of heads was: " , whatever longest run of heads was. "the longest run of tails was: " , whatever longest run of tails was. please me! thank guys! from itertools import groupby my_list = [1,1,0,0,0,1,1,1,1,0,0,1,1,1,1,1,1,0,1] max(len(list(v)) k,v in groupby(my_list) if k==1) is fun way group consecutive values , counts longest length of 1's, if use "h/t" instead change if condition @ end

coldfusion - application.cfc - conditionally turn on session and/or client management? -

i want reduce overhead of spider/crawler traffic. i'm not expecting catch of it, if can catch 90% of it's win. what's best way conditionally turn on/off session or client management in application.cfc ? i'm thinking along lines of this, i'm not sure if cgi scope defined , initialized when application.cfc instantiated. this.sessionmanagement = !isspiderrequest(); and: private boolean function isspiderrequest() { if (refindnocase("googlebot|msnbot|crawler|crawling|spider|wget|curl|baidu|robot|slurp|gigabot|ia_archiver|libwww-perl|lwp-trivial|mediapartners-google", cgi.http_user_agent)) return(true); return(false); } we set session timeout 10 seconds bots. don't errors, don't consume (much) memory. <!--- set app ---> <cfscript> this.name = "asdf"; this.applicationtimeout = createtimespan( 0, 0, 60, 0 ); this.setclientcookies = true; this.datasource = "asdf"; ...

android - This LinearLayout layout or its FrameLayout parent is useless -

i'm new @ this. me resolve warning. thanks. <linearlayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginleft="6dp" android:layout_marginright="6dp" android:layout_margintop="4dp" android:layout_marginbottom="4dp" android:padding="0dp" android:orientation="vertical" android:background="@drawable/background_card"> <textview android:id="@+id/txtproductdescription" android:layout_margintop="4dp" android:layout_width="match_parent" android:padding="6dp" android:layout_height="wrap_content" android:gravity="center" android:text="" android:textappearance="?android:attr/textappearancelarge" android:fontfamily...

java - Edit Maven Compiled Repository Source Code -

Image
i using maven repository here: https://github.com/cyberagent/android-gpuimage the dependency is: compile 'jp.co.cyberagent.android.gpuimage:gpuimage-library:1.2.3' and there bug in source code need fix. when open class, method pre-compiled code , can't change it. public void oninitialized() { /* compiled code */ } do know how can make changes locally (even if have point dependency path on computer thats fine, how that? update here github project folder structure when open in android studio. there library folder want turn aar. since source code available there no need mess around much. if cannot work around issue extending class can clone project: git clone https://github.com/cyberagent/android-gpuimage.git then change version in gradle.properties 1.2.3-agressorpatch1 (as example) distinguish artifact original one. change sources want have changed , compile project: gradle clean assemble the project apache licensed ok. the jar cre...

ruby on rails - Autofilling a form with visitor's country using IP address -

this first time i'm doing this. have form new users (investor model) , want once form loaded, based on visitor's ip, country field filled country. heard of geoip gem. don't know how use it. tried do. downloaded geoip.dat.gz http://www.maxmind.com/app/geolitecountry , extracted , put db folder of app. not sure if on right path. gemfile source 'https://rubygems.org' gem 'rails', '4.2.1' gem 'pg' gem 'sass-rails', '~> 5.0' gem 'uglifier', '>= 1.3.0' gem 'coffee-rails', '~> 4.1.0' gem 'jquery-rails' gem 'turbolinks' gem 'jbuilder', '~> 2.0' gem 'sdoc', '~> 0.4.0', group: :doc gem 'foundation-rails', '~> 5.5.2.1' gem 'foundation-icons-sass-rails' gem 'geoip', '~> 1.5.0' # use activemodel has_secure_password # gem 'bcrypt', '~> 3.1.7' # use unicorn app server #...

javascript - Why use Object.create inside this reduce callback? -

Image
so while working on #19 of fine tutorial - http://jhusain.github.io/learnrx/ , find exercise works without using object.create. (see commented-out lines) 1. point of creating copy of accumulatedmap? other showing possible... function() { var videos = [ { "id": 65432445, "title": "the chamber" }, { "id": 675465, "title": "fracture" }, { "id": 70111470, "title": "die hard" }, { "id": 654356453, "title": "bad boys" } ]; // expecting output... // [ // { // "65432445": "the chamber", // "675465": "fracture", // "70111470": "die hard", // "654356453": "bad boys...

regex - How can I redirect all visitors to a subdirectory but still have access to the root directory for development -

i'm start building site , i've set "under construction" site @ http://positivechange.cl i'd work directly on root directory during development don't have move files development subdirectory root directory, i'd redirect users http://positivechange.cl/maintenance after searching online know how redirect subdirectory using redirectmatch ^/$ /subdirectory/ on .htaccess file, doesn't allow me access root directory , check how site going. is there way this? you can use code in document_root/.htaccess file: rewriteengine on rewritecond %{request_filename} !-d rewritecond %{request_filename} !-f rewritecond %{query_string} !(^|&)dev=1(&|$) [nc] rewriterule !^maintenance\.html$ maintenance.html [l,nc] key use of query parameter dev=1 . without query parameter site show maintenance.html . if add ?dev=1 url can access development website.

java - When are Hadoop counters persisted? -

i have simple mapreduce job uses hadoop counters count unique ids in reduce phase of job. are counter changes persisted when increment java code, or after successful execution of task? the reason i'm wondering find out if should disable speculative execution in job, cause double counting unless counter changes happen after successful execution of task. , then, there race conditions if identical tasks succeed around same time?

how to avoid stack overflow when applying max to a large array in javascript? -

the following code var interval = function (a, b) { var i, list = []; (i = a; <= b; i++) { list.push(i); } return list; }, xs = interval(1, 500000); math.max.apply(null, xs); generates uncaught rangeerror: maximum call stack size exceeded. how overcome? note interval function quick way generate test data. i used math.max.apply method because described here: mozilla developer network this not acceptable solution because javascript has maximum number of arguments allowed function call, rocket hazmat pointing out, see answer more informations. the underscore.js library uses simple implementation max function, , believe appropriate solution include simple max implementation in codebase , use it. see @anotherdev answer more details the issue here line: math.max.apply(null, xs); you trying call math.max(1, 2, 3, 4, ..., 500000); . javascript doesn't calling function 500,000 parameters. see...

c# - how to stop old event when new event is occurs -

i have 2 button click events. void button1_click(...) { //do somethings foo(); } void button2_click(...) { //do somethings foo(); } the function foo() take more 1 minutes finished. when click on button1, , after click button2. how can stop foo() in button1_click , run foo() on button2_click? you should run foo on separate thread, , invoke update on ui thread once complete use cancelation token stop given operation @ time. similar post here how update gui thread in c#?

grails - Overriding Groovy's java.util.Date toString method -

i have grails (version 2.5.0 ; groovy version 2.4.3) application had custompropertyeditorregistry override date formats when using fieldvalue. i installed elasticserach grails plugin version 0.0.4.4 , after installation noticed custom property editor not working anymore. in attempt temporarily work around problem, decided override java.util.date's tostring() method using groovy's meta programming. i added bootstrap.groovy: date.metaclass.tostring = { return delegate.format("mm/dd/yyyy hh:mm") } however, when went grails console (using grails console plugin): new date("fri jun 12 12:36:02 edt 2015") string == "fri jun 12 12:36:02 edt 2015" new date("fri jun 12 12:36:02 edt 2015").tostring() == "06/12/2015 12:36" println(new date("fri jun 12 12:36:02 edt 2015")) // prints fri jun 12 12:36:02 edt 2015 println(new date("fri jun 12 12:36:02 edt 2015").tostring()) // prints 06/12/2015 12:36 any...