Posts

Showing posts from March, 2015

c - Can't link in libnanomsg for Windows MinGW, cross compiling using MXE -

i trying build nanomsg on mingw, cross compiling ubuntu using mxe. target host x86_64. built fine won't link. getting issues like undefined reference 'imp__nn_freemsg' i think it's static lib issue. built again using ./configure --enable-static --disable-shared ... same issue. there linker flags need put in gcc build line after link in libnanomsg.a? there many defines set if build vs, using cmake. located in src/nn.h, others scattered around. way, 'imp__**' issue failure link statically. passing these flags link it: -d_win32 -dnn_exports -dnn_have_mingw -dnn_have_windows -dnn_use_literal_ifaddr=1 -dstaticlib

JSP getting null values from Java servlet -

i trying pass values servlet jsp file. confirmed data going jsp servlet, not other way around. here java snippet //here list<string> of column names list<string> columns = dataaccess.getcolumns(query); //turn list<string> 1d array of strings for(int = 0 ; < numarrays ; i++) request.setattribute("rows["+i+"]", rows[i]); //set attribute key "columns" request.setattribute("columns", arcolumns); //launch result.jsp request.getrequestdispatcher("result.jsp").forward(request, response); there expecting have 1d array of strings linked key "columns". when jsp file, null . here how retrieve , confirm null: <% string[] columns = (string[])request.getparametervalues("columns"); if(columns == null){ system.out.print("columns null\n"); } int colnum = columns.length; //how many columns have %> in eclipse, when run code string "columns null" ont

web - Unnable to consume Webservice behind apache over HTTPS with Java -

good morning. i'm exposing webservice on jboss behind apache using https. can access wsdl without problem via browser. when test webservice using soapui works fine. when generate java client (using axis2) , try consume webservice, following exception: exception in thread "main" [info] unable sendviapost url[https://ws.vipid.net/services/atualizacaows.atualizacaowshttpsoap11endpoint/]org.apache.axis2.axisfault: connection has been shutdown: javax.net.ssl.sslhandshakeexception: sun.security.validator.validatorexception: pkix path building failed: sun.security.provider.certpath.suncertpathbuilderexception: unable find valid certification path requested target it known apache redirects http requests https. manually change client url http, , test it. in case exception following: [info] unable sendviapost url[http://ws.vipid.net/services/atualizacaows.atualizacaowshttpsoap11endpoint/] org.apache.axis2.axisfault: transport error: 302 error: found why work on soapui,

playframework 2.3 - Anorm's Row object no longer exists in Play 2.3 -

after upgrading play 2.3.0 compilation error on object row not found: value row i noticed row object no longer exists in play 2.3.0 (i've found row trait). looking @ documentation, pattern matching should still supported in play 2.3 http://www.playframework.com/documentation/2.3.x/scalaanorm see "using pattern matching" paragraph here's code: def findbyid(aid: long) = { db.withconnection { implicit conn => sql(byidstmt).on("id" -> aid)().map { case row(id:integer, some(userid:string), some(description:string), some(solrcriteria:string), some(solrcriteriahash:string), some(hits:integer), some(lastperformedutc:java.sql.timestamp), some(notify:boolean) ) => new userinquiry(id.tolong, userid, description, solrcriteria, solrcriteriahash, hits, lastperformedutc, notify) }.head } } how solve that? as said, pattern matching restored on play master https:/

c - Converting binary stored in 2 unsigned character to integer -

if have 2 variables: unsigned char var1, var2; var1 = 4a; // simplicity showing hex value 4a, 1 // byte of binary representing value 4a - 0100 1010 var2 = 3f; i want return function integer result given by: 3f4a in c this? int result; var2 << 8; // left shift var2 8 bits result = var1 + var2; return result; can "cast" binary stored in char variables int in manner? i.e result return integer 16202? although on platforms work use signed arithmetic, pedantically formally correct should use unsigned types computation of bit pattern. now, first of all var2 << 8; does not left shift var2 : it's expression computing result, that's discarded. that result of signed type int , because int highest common type of operands. you want unsigned computation, make sure @ least 1 operand of unsigned type, i.e. return static_cast<int>( var1 + (var2 << 8u) ); to entirely bit-level-ish, replace + bitlevel or, |

trac - Display ticket type progress in milestone -

just little question here: how can add different ticket types displayed in milestone description? bugs/feature requests on page: https://trac-hacks.org/wiki/groupticketfieldsplugin this question solved @rjollos. usage: [[ticketquery(component=groupticketfieldsplugin,group=type,format=progress)]]

javascript - Sails ReferenceError: Article "Model" is not defined -

i try access findone() through article model in controller, without success. i had error > error: sending 500 ("server error") response: > referenceerror: article not defined > @ object.module.exports.createarticle (c:\users\pisix\bizbiz\bizbizbackend\api\controllers\articlecontroller.js:16:9) > @ bound (c:\users\pisix\appdata\roaming\npm\node_modules\sails\node_modules\lodash\dist\lodash.js:729:21) > @ routetargetfnwrapper (c:\users\pisix\appdata\roaming\npm\node_modules\sails\lib\router\bind.js:179:5) > @ callbacks (c:\users\pisix\appdata\roaming\npm\node_modules\sails\node_modules\express\lib\router\index.js:164:37) > @ param (c:\users\pisix\appdata\roaming\npm\node_modules\sails\node_modules\express\lib\router\index.js:138:11) > @ param (c:\users\pisix\appdata\roaming\npm\node_modules\sails\node_modules\express\lib\router\index.js:135:11) > @ pass (c:\users\pisix\appdata\ro

python - List index out of range for random cayley table -

i'm trying write code produce random cayley table getting list index out of range error, can't work out why. here code: def randcaytab(n): if not n >= 0: return false table = [] in range(n): table.append([]) j in range(n): k in range(n): (table[j]).append(randint(0,(n-1))) return table i error on line: (table[j]).append(randint(0,(n-1))) any appreciated. table[i].append(randint(0,n-1)) (the parenthesis didn't harm diminish readibility)

JPA Mapping embedded fields with createNativeQuery -

i have entity has field represents composite primary key annotated embeddeid , field annotated embedded annotation. both of these fields not directly mapped the columns returned query passed createnativequery method. getresultlist returns me list of entities, 2 fields mentioned null in entities. public interface key{ public int hashcode() } @embeddable public class compositepk impements key{ private int empid; private date startdate; private date enddate; } @embeddable public class partitionkey implements key{ private string empname; } @entity public class employee { @embeddedid private compositepk id; @embedded private partitionkey name; @column(name="empid") private int empid; @column(name="empname") private string empname; @column(name="startdate") private date startdate; @column(name="enddate") private date enddate; } public class loader{ private static entitymanager em; public static void mai

metaprogramming - result of 'self' in ruby module -

module cnblog2jekyll class << self attr_accessor :username [:archive_links, :article_links].each |method_name| define_method method_name instance_value = instance_variable_get(("@" + method_name.to_s).to_sym) instance_value ? instance_value : send("get_" + method_name.to_s) # @archive_links ? @archive_links : get_archive_links end end binding.pry def test binding.pry end end end please ignore meaning of part code , mind place of 'binding.pry'. here comes question: type in 'self' in pry console @ place of 'binding.pry', , give result: from: /home/yanying/cnblog2jekyll/lib/cnblog2jekyll.rb @ line 20 : 15: instance_value = instance_variable_get(("@" + method_name.to_s).to_sym) 16: instance_value ? instance_value : send("get_" + method_name.to_s) 17: # @archive_links ? @archive_links : get_archive_li

javascript - Progress Bar using nprogress.Js -

i want make progress bar youtube bar progress, im using plugins nprogress.js, want start progress middle of page somthing like, youtube bar : start | ---------------------------------------------> | end that want : start | emtpyemptyemtpyemtpyempty--------------------> | end here nprogress website http://ricostacruz.com/nprogress/ on github : https://github.com/rstacruz/nprogress/ how can please, , ! taken http://ricostacruz.com/nprogress/ nprogress.set(0.4) — sets percentage if want go middle, set 0.5 o 50 or something... if not looking for, please excuse me, have bad english... also, if has 4 functions exposed, , none of them can work want, think solution adding nprogress code :p

Streaming data from Kafka into Cassandra in real time -

what's best way write date kafka cassandra? expect solved problem, there doesn't seem standard adapter. lot of people seem using storm read kafka , write cassandra, storm seems of overkill simple etl operations. we heavily using kafka , cassandra through storm we rely on storm because: there lot of distributed processing (inter-node) steps before result of original message hit cassandra (storm bolt topologies) we don't need maintain consumer state of kafka (offset) ourselves - storm-kafka connector doing when products of original message acked within storm message processing distributed across nodes storm natively otherwise if simple case, might read messages kafka , write result cassandra without of storm

Hiding Ip in JavaScript WebSocket -

i'm having javascript websocket variables - var server = new websocket('ws://xxx.xxx.xxx.xxx:9300'); var server2 = new websocket('ws://xxx.xxx.xxx.xxx:9301'); ("xxx.xxx.xxx.xxx" ips. ) problem that, ips viewable in "view source" browser option. don't want them vissible security reasons(ddos attacks , on...). there possible way can hide or crypt ips aren't usable or vissible @ client side(not in "view source" option)? i tempted downvote , joke, because question quite silly way put it. can't hide identity of server you're connecting to. if encrypt in source, trivial log connection (necessarily decrypted) ip. except if you're connecting through proxy. though doesn't solve problem. proxy attacked, or servers through it. there ways mitigate attacks such ddos nothing foolproof. i'm sure can find more @ serverfault asking right questions.

imagemagick - Apply and remove color profile with image magick -

i have tiff images embedded specific icc profiles. i want convert these means of imagemagick jpg-files. the jpg-files should use colorspace srgb (which default) , no embedded profile. in other words want apply profile image , want save without profile. when use simple convert command this convert source.tif target.jpg the icc-profile preserved in jpg file. can remove command convert source.tif +profile * target.jpg but not seem apply profile. a -colorspace rgb (or -colorspace srgb ?) should trick. combination have tried far not work. is there color management guru out there can give me hint? ` some iterations later come this convert source.tif -profile my_profile_path/srgb.icc +profile * target.jpg i used icc profile http://www.color.org/profiles/srgb_appearance.xalter

Excel VBA: How to copy entire range including hidden columns -

i'm looking vba macro export data csv. found this code after tweaking great job. however, when copying range, excel seems ignore hidden columns while want csv contain columns. has discovered concise way code this? here code have far: sub exportlistortable(optional newbook boolean, optional willnamesheet boolean, optional ascsv boolean, optional visibleonly boolean) 'sub copylistortable2newworksheet() 'works in excel 2003 , excel 2007. copies visible data. 'code source: https://msdn.microsoft.com/en-us/library/dd637097%28v=office.11%29.aspx 'improved by: tzvi ' - replaced new worksheet new workbook 'params: ' newbook: create new new sheet in current workbook or (default) in new workbook ' willnamesheet: offer user name sheet or (default) leave default names ' ascsv: not implemented - save csv ' visibleonly: filter out hidden columns - default false 'todo ' -add parameter list following options: ' - if table

ios - scale animation in UITableViewCell interferes with scrolling -

Image
i've created sample repo demonstrating issue: https://github.com/dementrock/scrollanimationtest/commit/8ec61e24cdfa298e8eaee8c303f847c07809e35b when building against initial commit, can see often, when scroll down , try scroll right after, scrollview ignores scroll touch events until decelerates. removing scale animations on red blocks solve issue. in second commit ( https://github.com/dementrock/scrollanimationtest/commit/c870b3900dbe5f95b81e469e53ba9a0df8100fdc ), fixed issue setting userinteractionenabled no on red blocks. however, don't know why fix issue, , don't know why scaling animations interfere scrolling. can give me hint? [update 1] issue exists both in simulator (ios sdk 8.2) , on real device (iphone 5s, ios 8.2) a screenshot:

c++ - Return node information during comparison -

i've had bit of make code. @ moment code print out id numbers of differences in files, i.e new compared old has been added, removed or stayed same. however want return information in node when appears in new.xml, not id (i.e title, location, date). my best guess can find google use (with no idea how implement): xpath->getancestor my current code #include <set> #include <string> #include <sstream> #include <iostream> #include <algorithm> #include "include/pugixml.hpp" #define con(m) std::cout << m << '\n' #define err(m) std::cerr << m << std::endl using str_set = std::set<std::string>; int main() { pugi::xml_document doc; str_set a; doc.load_file("old.xml"); // fill set ids file for(auto&& node: doc.child("site_entries").children("entry")) a.emplace(node.child("id").text().as_string()); str_set b; doc.

how to authenticate web service url in php(nusoap) -

i learn how create web service , consume using php , (nusoap) . confused on how authenticate web service url. for example have web service has url below <?php include_once './lib/nusoap.php'; $server = new nusoap_server(); //print_r($server); $server->register('abc'); function abc() { return 'welcoem'; } $server->service($http_raw_post_data); exit(); ?> localhost/nusoap/webservice91.php so give client. want know particular person using web service whom give them url. how know if person using our web service. there several options technically: http authentication soap-based authentication via soap headers. roll-your-own authentication username/password or token being embedded in soap body part of actual request.

collectd - How to multiply two series lists in Grafana / Graphite? -

i have data in graphite in following format: app.service.method_*.m1_rate (rate of calls per minute) app.service.method_*.avg_time (avg response time per minute) i graph total estimated time given method running per minute. in other words - multiply rate avg time can learn 1 graph calls taking most. if can going can limit (i know how :) ) top n results of such multiplication. neither rate not give me information (high rate of fast calls not problem) nor avg time (high average time on service called once per 5 minutes not problem). any suggestions? may multiplyseries you.

hadoop - Whats the Right way to mange Code deployement and management for AWS -

we on boarding new on aws emr's , we looking @ right code repositories , automated code deployment tools . there right tool doing these can manage end-to-end in terms of code deployments. primarily writing shell scripts, python scripts , hive scripts. any suggestions or pointers or examples appreciated. thanks sundeep i use script written http://capistranorb.com/ "ec2group" deploy autoscalling instances via asg here small info how integrate "ec2group" https://github.com/smart-gamma/aws-multiply-deploy

javascript - JQuery not displaying HTML data from ajax response -

howdie do, i have form takes username , email user. input sanitiazed via client , on server side. the script sending post no issue , it's returning data should i've checked in log. however, reason, data isn't being displayed in browser. code below , feel it's stupid item i'm overlooking, can't find anywhere <!doctype html> <head> <title>jeremy's form submit test </title> <script type="text/javascript" src="js/jquery-1.11.2.js"></script> <script> $(document).ready(function() { $("#formsubmit").click(function() //set click action on formsubmit button { var submit = true; $('#mainform input[type="text"]').each(function() //loop through input fields ensure data present { if($.trim($('#user').val()) == '') //remove whitespaces , check if field empty

tweepy error python 2.7 -

i keep getting error: tweepy.error.tweeperror: [{u'message': u'status duplicate.', u'code': 187 i have no clue why getting error have tried everything! my main code is: import socket urllib2 import urlopen, urlerror, httperror socket.setdefaulttimeout( 23 ) # timeout in seconds url = 'http://google.co.uk' try : response = urlopen( url ) except httperror, e: tweet_text = "raspberry pi server down!" textfile = open('/root/documents/server_check.txt','w') textfile.write("down") textfile.close() except urlerror, e: tweet_text = "raspberry pi server down!" textfile = open('/root/documents/server_check.txt','w') textfile.write("down") textfile.close() else : textfile = open('/root/documents/server_check.txt','r') if 'down' in open('/root/documents/server_check.txt').read(): tweet_text = "

Where's genymotion path for android studio in Arch Linux? -

i set /home/user/.genymobile/genymotion , android-studio still can't find it. i've googled , can't find people talking topic (linux). official guide said path /home/<user>/genymotion , don't have path. it? info: i'm running arch linux i don't know arch puts installed packages, suggest try find directory using find command in following places: find /opt/ -iname *genymotion* find /usr/ -iname *genymotion* find /home/ -iname *genymotion*

hadoop - Escape character while doing Sqoop export -

i'm trying export hive table oracle using sqoop export command. hive table have fields delimited '|' , escaped '\'.sqoop export jobs failing while parsing records delimiter escaped fields. tried setting 'escaped-by' option.it seems not working.is there way specify escape characters sqoop export. below command tried. sqoop export \ --connect jdbc:oracle:thin:@//testserver:1521/testschema \ --username user \ --password pwd \ --table test \ --direct \ --escaped-by \\ \ --fields-terminated-by '|' \ --input-lines-terminated-by '\n' \ --export-dir /user/etl/test/ your command has issue. should use --input-fields-terminated-by '|' instead of using --fields terminated '|'.

Codeigniter Pagination Links Error After ID -

sorry if question duplicate, have problem codeigniter pagination. url is: http://mysite/news/category/26/(page number), have 5 data , page limit 10, generated links active on page 3, believe because of id/26/ this model : function categpry($id){ $string_query = "select * news n join category c on n.category_id = c.id_category , n.category_id = $id order n.category_id desc"; $query = $this->db->query($string_query); $config['base_url'] = site_url('news/category/' . $id); $config['total_rows'] = $query->num_rows(); $config['per_page'] = '10'; $num = $config['per_page']; $offset = $this->uri->segment(4); $offset = ( ! is_numeric($offset) || $offset < 1) ? 0 : $offset; if(empty($offset)){ $offset = 0; } $this->pagination->initialize($config); $news = $this->db->query($string_query." limit $offset,$num"); return $nes; } the

XSLT 2.0 if then -

in xslt 2.0, can use if means no else clause. <employee><status><xsl:value-of select="if (tns:employee/tns:empid = 4) 'new' else 'old'"/></status></employee> here if don't want else clause, means if empid not 4, not populate status field. xslt? unless i'm reading question wrong, add empty string or empty sequence. example... if (tns:employee/tns:empid = 4) 'new' else '' or if (tns:employee/tns:empid = 4) 'new' else ()

Android outcoming call is taken listener -

i need run method, when outcoming call taken. in android possible? i test broadcastreceiver - phonestatelistener, work on outcoming call start, not on outcoming call taken. thanks. you can have @ telephonymanager . has phonestatelistener said in can listen phonestatelistener#oncallstatechanged(int, string) . in method states 3 listed in doc . call_state_idle call_state_ringing call_state_offhook the 1 looking call_state_offhook state for: device call state: off-hook. @ least 1 call exists dialing, active, or on hold, , no calls ringing or waiting.

javascript - Warning 1 The TypeScript Compiler was given no files for compilation, so it will skip compiling -

in visual studio professional 2013 when created new apache cordova project, warning: warning 1 typescript compiler given no files compilation, skip compiling. few weeks before working fine getting error. i re-install vs , tool apache cordova, still getting error. how solve error? solution? to fix warning ! open (your project name) .csproj texteditor tools ( notepad , editplus , etc.. ) remove line.. <import project="$(msbuildextensionspath32)\microsoft\visualstudio\v$(visualstudioversion)\typescript\microsoft.typescript.default.props" condition="exists('$(msbuildextensionspath32)\microsoft\visualstudio\v$(visualstudioversion)\typescript\microsoft.typescript.default.props')" /> save re open project. hope !

domain driven design - Do microservices break the bounded context? -

i bit confused. working in young banking company , decided implement ddd architecture break complexity. so, here question (it follows design suggestion made in team). let's have 3 different domains. d1, d2, d3, expose domain (web)services. each domain manipulates typed business entities, rely on same tables. in front of these domains, want microservice garantee data persisted in tables consistent, in centralized manner. d1, d2 , d3 ask microservice persist data conforming specific rules. want microservice act crud proxy tables. microservice provides specific dtos d1, d2 , d3 domains, obfuscating tables d1, d2, d3. does approach sound ? consider using microservices in ddd architecture manage crud , data consistency 1+ domains ? "cruding" , validating data microservice break bounded context ? best practices dealing microservices in ddd architecture, if ? many contribution, [edit] the following article helped me refine thoughts : http://martinfowler.com/bliki/m

Android: How to parse JSON file with Gson Library -

i have code parse json file in raw folder. encountering problem method parse_ssid(ssid) not being called , getting @ moment 0 in xml file?! i getting result ssid variable. since mapping variable in json file, have parse route_number value of it. this part of method. if (updatedresults.size() > 0) { string ssid = deliverbestaccesspoint(updatedresults); //retrieve data json string , parse it. int route_number = parse_ssid(ssid); // here getting in xml file 0 , cursor not being jumped "parse_ssid" method. textwifi.settext(string.valueof(route_number)); } parse_ssid method: private int parse_ssid(string ssid) { int route_number=0; inputstream raw = getresources().openrawresource(r.raw.ssid_number); reader rd = new bufferedreader(new inputstreamreader(raw)); gson gson = new gson(); wifijsonlist obj = gson.fromjson(rd, wifijsonlist.class); // iterate through list list<wifi

android - Adding ParseFile to JSONObject -

private void savepicture() { bytearrayoutputstream stream = new bytearrayoutputstream(); thumbnail.compress(bitmap.compressformat.png, 100, stream); final parsefile file = new parsefile("pic.png", stream.tobytearray()); file.saveinbackground(new savecallback() { @override public void done(parseexception e) { if (e != null) { toast.maketext(generatereportactivity.this, "couldn't save image", toast.length_long); } else { try { newitem.put("image", file); myreports.put(newitem); } catch (jsonexception ex) { utility.showmessage(ex.getmessage(), "json error picture", generatereportactivity.this); } } } }); imgtakenphoto.setimagebitmap(null); imgtakenphoto.destroydrawingcache(); } in metho

ocaml - Existentially quantified type parameter, recursive function and type error -

consider following piece of ocaml code: type mytype = : 'a list * 'a -> mytype let rec foo : int -> mytype = fun n -> if n < 0 my([], 2) else let my(xs, y) = foo (n - 1) in my(3::xs, y) the ocaml interpreter gives me error on last line of foo , saying: this expression has type a#1 list expression expected of type int list type a#1 not compatible type int i make code work adding type parameter mytype be type _ mytype = : 'a list * 'a -> 'a mytype let rec foo : int -> 'a mytype = ... but let's don't want change definition of mytype . write foo , assuming want preserve function's (intuitively understood non-working code) behaviour? also, explain root of problem, i.e. why initial code doesn't type-check? when pattern matching done on mytype value, there no way know type inside. thing is, typing system acts quite , doesn't try know mytype if comes recursive call (the t

angularjs - angular-translate inside loop -

i'm trying construct translated message looping on array of objects , adding new "message" property object containing translated string. see correct message output while inside $translate.then(); when assign message object undefined. correct way resolve promise returned $translate.then() , assign "message" property? //items.controller.js function getitems() { return itemsfactory.getitems() .then(function (response) { vm.items = inititemslist(response.activities); }); } function inititemslist(itemslist) { (var = 0; < itemslist.length; i++){ var activitytype = itemslist[i].activitytype; switch (activitytype){ case "history": { var itemname = itemslist[i].item.itemname; var itemversion = itemslist[i].item.itemversion; $translate('activity.'+activitytype, { itemname: itemname, itemversion: itemversion }).then(function(content){

java - Javafx Slider event listener being called before it snaps to the nearest tick -

i trying update information every time slider value changed, have code set this: int betamount = 0; slider betslider = new slider(); betslider.setminortickcount(4); betslider.setmajortickunit(250); betslider.setsnaptoticks(true); betslider.valuechangingproperty().addlistener((obs, waschanging, ischanging) -> { if (!ischanging) { betamount = (int) betslider.getvalue(); update(); //update method, not relevant problem } }); the problem having getvalue() method on slider being called before snaps nearest tick. because of this, getting incorrect value stored in betamount variable. wondering if there way slider's value after has finished snapping nearest tick. try using valueproperty() in place of valuechangingproperty() betslider.valueproperty().addlistener((obs, waschanging, ischanging) -> { betamount = newvalue.intvalue()); }); valuechanging -> provides notification value changing. value -> current value represen

go - Empty function in golang -

this question has answer here: function signature no function body 1 answer was looking @ source code go source code, below snippet sleep.go (package time): package time // sleep pauses current goroutine @ least duration d. // negative or 0 duration causes sleep return immediately. func sleep(d duration) // runtimenano returns current value of runtime clock in nanoseconds. func runtimenano() int64 how possible func sleep(d duration) doesn't have implementation? can find exact implementation of sleep function? edit: answer can found in 2 links provided @davec. please read comments below see explanation why empty function can't replaced go after bootstrapping go (1.5) considering sleep() (it deschedules golang thread given amount of time), can't express in go, it's implemented kind of compiler instrinsic. whoa, lots of downvotes here

python - Dictionary within a list using Counter -

i wanted write function lists counter of dictionary items appear @ least number of times df in other dictionaries. example: prune(([{'a': 1, 'b': 10}, {'a': 1}, {'c': 1}], min_df=2) [counter({'a': 1}), counter({'a': 1})] prune(([{'a': 1, 'b': 10}, {'a': 2}, {'c': 1}], min_df=2) [counter({'a': 1}), counter({'a': 2})] as can see 'a' occurs twice in 2 dictionaries gets listed in output. my approach: from collections import counter def prune(dicto,df=2): new = counter() d in dicto: new += counter(d.keys()) x = {} key,value in new.items(): if value >= df: x[key] = value print counter(x) output: counter({'a': 2}) this gives output combined counter. can see, term 'a' appears 2 times on whole , hence satisfies df condition , gets listed in output. now, can correct me desired output. i suggest: from coll

haskell - use BootstrapHorizontalForm in yesod -

i intend use bootstraphorizontalform, use how example guide , code: the form churchform :: maybe church -> aform handler (church,maybe fileinfo) churchform mc = (,) <$> (church <$> areq textfield (bfs msgname) (churchname <$> mc) <* bootstrapsubmit (bootstrapsubmit msgcreateaction "btn-default" [("attribute-name","attribute-value")]) the method getchurchnewr :: handler html getchurchnewr = (widget, enctype) <- generateformpost $ renderbootstrap3 (bootstraphorizontalform (colsm 0) (colsm 4) (colsm 0) (colsm 6)) (churchform nothing) defaultlayout $ msgaction = msgcreateaction actionr = churchnewr mpath = nothing $(widgetfile "church/church") but have error: handler/church.hs:63:67: not in scope: data constructor ‘colsm’ thanks help this looks missing import. check import cpmsm @ top of file. this import of form: import yesod.form.bo

Wordpress javascript in post -

how not accomplish very functionality should of been included in core not rendering inside of <code></code> tags. <code> <script type="text/javascript"> alert('why parsing this'); </script> </code> parsed wordpress. ok parse this: <script type="text/javascript"> alert('yea parse please'); </script> you apply esc_html content adding filter in functions.php file: add_filter('the_content', function($content){ return preg_replace_callback('~<code>([\s\s]*?)</code>~', function($matches){ return sprintf('<code>%s</code>', esc_html($matches[1])); }, $content); });

python - Return django object in json and inject it to another json -

i search everywhere can't find answer. how can example return news posts in django in format like: {'status': 1, data: here_django_posts} . can use serialize how add json object? when put serialized data json.dumps data converted json again. wish in php: $a = array(); $a['status'] = 1; $a['data'] = here_my_django_posts json_encode($a) ok i'm tired today. here working code: products = serializers.serialize("json", products_model) return jsonresponse(1, products) def jsonresponse(status, data=none): return httpresponse(json.dumps({'status': 1, 'data': json.loads(data)}), content_type="application/json")

regex - Replace [1-2] in to 1 in Python -

i replace [1-2] 1 , [3-4] 3 , [7-8] 7 , [2] 2 , , on. for example, use following strings: db[1-2].abc.xyz.pqr.abc.abc.com db[3-4].abc.xyz.pqr.abc.abc.com db[1].abc.xyz.pqr.abc.abc.com xyz-db[1-2].abc.xyz.pqr.abc.abc.com and convert them to db1.abc.xyz.pqr.abc.abc.com db3.abc.xyz.pqr.abc.abc.com db1.abc.xyz.pqr.abc.abc.com xyz-db1.abc.xyz.pqr.abc.abc.com you use regex like: ^(.*)\[([0-9]+).*?\](.*)$ and replace with: $1$2$3 here's regex does: ^ matches beginning of string (.*) matches character amount of times, , first capture group \[ matches character [ literally ([0-9]+) matches number 1 or more times, , second capture group .*? matches character amount of times, tries find smallest match \] matches character ] literally (.*) matches characters amount of times $ matches end of string by replacing $1$2$3 , replacing text in first capture group, followed text in second capture group, followed text in third captur

Properties of Entity sent from iOS are set to null when objectify is used to store the entity into datastore -

i send entity ios client , processed following backendapi method: @apimethod(name="datainserter.insertdata",path="insertdata",httpmethod="post") public entity insertdata(customentity userinput){ ofy().save().entity(userinput).now(); return userinput; } customentity defined within customentity.java follows: //import statements here @entity public class customentity { @id public string someid; @index string provideddata; } after above code runs, datastore contains following entry: id/name provideddata id=5034... <null> if add following lines method: customentity badsoup=new customentity(); badsoup.provideddata="i exhausted"; ofy().save().entity(badsoup).now(); i see following in datastore after run code: id/name provideddata id=5034... exhausted in post similar one, poster -- drux -- concludes "...assignments @in

javascript - Make Tabs Stick To Top Of Div -

ok i'm working on restaurant app design , want able stick tabs category names right below "now serving breakfast" block scroll down next category replace category name tab current one. similar how instagram have username tab while scrolling down newsfeed. http://codeclimb.com/menus2/index2.html any ideas on javascript can done? check out codepen here code: function stickytitles(stickies) { this.load = function() { stickies.each(function() { var thissticky = jquery(this).wrap('<div class="followwrap" />'); thissticky.parent().height(thissticky.outerheight()); jquery.data(thissticky[0], 'pos', thissticky.offset().top); }); } this.scroll = function() { stickies.each(function(i) { var thissticky = jquery(this), nextsticky = st

javascript - make animation with scrollTop -

animate = animate; desanimate = undo animate; friends, created function element animate or 'desanimate' depending on scroll of body or div is, it's working ok, how works? <li data-animation-time="[100, 800]" data-animation-position="right" class="list-item one"></li> the first value of data-animation-time array initial value, ie animator function should called when scrolltop pass value, second value end , 'desanimate' function should called when scrolltop pass value. everything working can see here -> codepen: http://codepen.io/celicoo/pen/ogkgep (you need scroll see animation happens). now want determine way animation happen , way should end, changed attr: data-animation-position="right-to-left" instead of right or left , , add ifs statements animation , 'desanimation' function: animate: var animate = function(target, position) { target.css('display', 'in

python - Custom legend in Pandas bar plot (matplotlib) -

Image
i have created bar plot pandas show how quantity change countries , set bar color according each country's continent. plot graph using following code. code based on second reply of this question : s = pd.series( listofquantities, listofcountiesnames ) ''' assign color each country based on continent ''' colormapping = {'af':'k','as':'r','eu':'g','oc':'r','na':'b','sa':'y'} colorstring = "" country in listofcountiesnames: continent = countrytocontinent[country] colorstring += colormapping[continent] pd.series.plot( s, kind='bar', color=colorstring, grid=false, ) i want create legend 1 show in attached image (the legend wasn't generated python, added manually). possible draw such custom legends pandas, or can achieve similar other graphing libraries? i'd appreciate suggestions alternative plot ty

javascript - dc.js x-axis will not display ticks as months, shows decimals instead -

i'm building bar chart using dc.js, , want x-axis list 12 months of year. so far, have rendering showing first tick time of day (06 pm), , subsequent ticks decimals (thousandths). i saw similar question ( https://stackoverflow.com/questions/21392997/dc-js-x-axis-hour-labels-appear-as-thousandths# = ), answer involved converting milliseconds larger units, isn't possible months (that know of). here code. in advance help. var parsedate = d3.time.format("%m/%d/%y").parse; data.foreach(function(d) { d.date = parsedate(d.weekstart); d.month = d.date.getmonth(); }); var monthdim = ndx.dimension(function(d) {return d.month;}); var milesbymonth = monthdim.group().reducesum(dc.pluck('miles')); //set range x-axis var mindate = datedim.bottom(1)[0].date; var maxdate = datedim.top(1)[0].date; var barchart = dc.barchart("#mybarchart"); barchart .width(800).height(200) .margins({top: 10, right: 10, bottom: 20, left: 60}) .dimen

c# - ServiceStack ORMLite Sql Server *optional filter -

i need sql in ormlite sql server: (if pass 0 in parameters remove filter, in sql: declare @departmentid int = 0; declare @projecttaskstatusid int = 0; select * projecttask t join project p on p.projectid = t.projectid (p.departmentid = @departmentid or @departmentid = 0) , (t.projecttaskstatusid = @projecttaskstatusid or @projecttaskstatusid = 0) i've created code below not working, best way in ormlite sql server? dbcon.loadselectasync(x => (x.project.departmentid == departmentid || departmentid == 0) && (x.projecttaskstatusid == projecttaskstatusid || projecttaskstatusid == 0)); i make work using code below (but using lambda , not straight in ormlite: var tasks = await dbcon.loadselectasync<projecttask>(x => x); return tasks.where(x => (departmentid == 0 || x.project.departmentid.equals(departmentid)) && (projecttaskstatusid == 0 || x.projecttaskstatusid.equals(projecttaskstatusid))); after of guys solution below,