Posts

Showing posts from June, 2010

xml - XSLT transformation: flattening nested node based on its attribute value -

i want flatten xml file using xslt. example (there number of node , edge nodes): input: <?xml version="1.0" encoding="utf-8"?> <graphml xmlns="http://graphml.graphdrawing.org/xmlns"> <graph> <node id="0"> <data key="label">a</data> <data key="tag1">0</data> <data key="tag2">0</data> </node> <edge id="0" source="0" target="1"> <data key="label">referenced_to</data> </edge> </graph> </graphml> desired output: <?xml version="1.0" encoding="utf-8"?> <graphml xmlns="http://graphml.graphdrawing.org/xmlns"> <graph> <node id="0" label="a"> <data key="tag1">0</data> <data key="tag2">0<

javascript - Dropdown on click of image -

i want open dropdown on click of image , display alert message of dropdown option being clicked . my html code : <div class="account_notification"> <a href="#"> <div class="notify_notification">click</div><!-- notify_notification close --></a> </div><!-- account_notification close --> <select class="select1" size="5" style="display:none"> <option name="test" value="" class="first">select</option> <option name="test" value="" class="">notification1</option> <option name="test" value="" class="">notification2</option> </select> what javascript code ? though found jquery on inernet dropdown display without showing option selected , know little jquery .so want code in javascript.please help jquery fo

Rcpp check if list has an element -

my program deals clustering. apart dataset user has specify details concerning clusters. there 2 ways approach that: specify number of clusters or prepare list of clusters' descriptions. args <- list(dataset=points, k=5) args <- list(dataset=points, clusters=list( list(type="spherical",radius=4), list(type="covariance",covmat=matrix) ) next call proper function (my program) in r args argument. classification <- cec(args) i prepare cec below sexp cec(sexp args) { rcpp::list list(args); arma::mat dataset = rcpp::as<arma::mat>(list["dataset"]); if(list.contains("k")) { //something } else if(list.contains("clusters")) { //something } } i cannot find api list or example how that. moreover, study headers of rcpp definition of list typedef vector<vecsxp> list ; hardly helpful. is ther

python - increasing NumPy memory limit -

i doing coding nn huge dataset, example mnist dataset (about 700*50000). when test it, code got memoryerror. have computer 12 gb ram, think python or numpy can't use of them. can push python or numpy use remaining available memory in pc ? os : windows 7 64-bit python : python(x, y) 2.7.60 thanks i believe python(x, y) distribution of python still 32-bit build (64-bit support still on roadmap) , limited 32 bits of address space though using 64-bit os. need install 64-bit build of python , numpy binaries access more memory.

c# - How can I edit and save correct OpenXML docx file? -

i parse document.xml(change file.docx name file.docx.zip , uznip it) file manually , put code: <w:r> <w:t>new text</w:t> </w:r> instead of <w:r> <w:t>text</w:t> </w:r> and save zip-archieve(and change file.docx.zip name file.docx) , try open docx msword 2013. error word - incorrect document. how fix ? thank you. why doing manually? used open xml sdk , worked smoothly. you have access whole xml tree can change want, exception library takes care of zipping , unzipping. the sdk has viewer can have better @ file, , i've found docx documents have internally multiple files zipped together. maybe missing 1 of them.

sql - Adding a Foreign Key to an existing Table -

i forgot add column foreign key. tried doing following: alter table gamestbl add console varchar(30) not null, index (console), foreign key(console) references consolestbl(consolename) on delete cascade on update cascade; edit: i tried adding field first , after constraint so: alter table gamestbl add column console varchar(30); add constraint console foreign key (console) references consolestbl(consolename); it seems want add missing column, index, , add foreign key constraint. afaik there isn't 1 single command all in 1 go. in smaller steps :) also, note if games table has data in it, not able add not null column without setting default. here's 1 way this, viz adding missing column null able, setting data, , changing not null : (i'm assuming mysql) alter table gamestbl add console varchar(30) null; alter table gamestbl add foreign key(console) references consolestbl(consolename) on delete cascade on update cascade; create index ix1_g

emacs - Refiling to new node in org-mode -

these setting in .emacs refiling in org-mode: (setq org-refile-targets (quote ((nil :maxlevel . 10) (org-agenda-files :maxlevel . 10)))) (setq org-refile-use-outline-path t) (setq org-outline-path-complete-in-steps nil) (setq org-refile-allow-creating-parent-nodes (quote confirm)) refiling existing path works should can't create new node , refile last line should allow me do. when refile path like: existing node"/new node" i error: please save buffer file before refiling supposedly means emacs can figure out target file target set org-refile-targets line what's wrong?

asp.net mvc - Javascript bundle obfuscation and Bundletransformer -

i trying obfuscate output of our javascript bundles on fly , came across bundletransformer (a bundling extension uses yui compressor), had no success implementing it! far reading provided documentation i've written following code in registerbundles method: var nullbuilder = new nullbuilder(); var csstransformer = new csstransformer(); var yuisettings = new bundletransformer.yui.configuration.yuisettings(); yuisettings.jsminifier.obfuscatejavascript = true; var jstransformer = new jstransformer(); var nullorderer = new nullorderer(); var scriptbundle = new customscriptbundle("~/jscbundle/").include( "~/assets/scripts/jquery.js", "~/assets/scripts/jquery-ui.js"); scriptbundle.builder = nullbuilder; scriptbundle.orderer = nullorderer; scriptbundle.transforms.add(jstransformer); bundles.add(scriptbun

My android application crashes when trying to send data to a webserver -

i want learn how send data android application webserver. have copied code tutorial when application tries send data crashes. logcat says: fatalexception:main i don't have webserver send data yet, don't think problem. application crashes before gets anything. before ask, yes have granted internet permissions. the program following: package com.example.helloworld; import java.io.ioexception; import org.apache.http.client.clientprotocolexception; import java.util.arraylist; import java.util.list; import org.apache.http.client.httpclient; import org.apache.http.client.methods.httppost; import org.apache.http.impl.client.defaulthttpclient; import org.apache.http.namevaluepair; import org.apache.http.client.entity.urlencodedformentity; import org.apache.http.message.basicnamevaluepair; // import need import android.app.activity; import android.os.bundle; import android.view.view; import android.widget.button; import android.widget.edittext; import android.widget.toas

numpy - python element wise add in list of list with other list -

i checked similar problem @ sum of n lists element-wise python but mine little bit more complicate cause adding list of list list of list my list looks below [[0 0.014285714 0.035600016] ,[0.014285714 0 0.038359389] ,[0.035600016 0.038359389 0]] [[0 0.014285714 0.035600016] ,[0.014285714 0 0.038359389] ,[0.035600016 0.038359389 0]] so adding these 2 results has 3 3 matrix how efficiently add these 2 lists? can solve using numpy: >>> = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] >>> b = [[4, 5, 6], [4, 5, 6], [4, 5, 6]] >>> numpy import array, sum >>> list(array(a) + array(b)) [array([5, 7, 9]), array([5, 7, 9]), array([5, 7, 9])] or >>> sum([a, b], axis=0) array([[5, 7, 9], [5, 7, 9], [5, 7, 9]]) >>>

php - Mobile app design -

i wanted ask design mobile app. the android app location based network 1 user can see his/her location & location of other users of choice. the map web-based (php) installed on server, while interface android based webview; using location manager app : -send user coordinates database on server (with each change in position resends) -the map fetch location database -stops when location not changing- i'm limited usage of php map (i wanted use google maps api on android project outlines state shouldn't). i having doubts & appreciate opinions.

javascript - Text select (ready to use clipboard operations) -

http://cdnjs.com/libraries/twitter-bootstrap/ in website when mouseover links given text selected(like mouse text select , not css styling). i tried check what's changing in inspect element found none. i tried find out if js or jquery has methods this. found .select() method of jquery usable on form elements , there no deselect() method in jquery definetely no that. so whats under hood? update: i found solution tried in jsfiddle works perfect. written in js dom node manupulations , looks greek , latin me. not able write jquery version of algorithm. html: <p id="selectable">hello</p> js: function fnselect(objid) { fndeselect(); if (document.selection) { var range = document.body.createtextrange(); range.movetoelementtext(document.getelementbyid(objid)); range.select(); } else if (window.getselection) { var range = document.createrange(); range.selectnode(document.getelementbyid(objid)); wind

c# - Remove unicode hex values using regex -

i need remove several different hex values string of product descriptions. example: " sale on coolitem&#x2122; watch " or " deal buster on rmkhoody&#8482; signed " &#x2122; &#8482; are few hex strings in large database. i need reg exp replace each empty string. result : " sale on coolitem watch " or " deal buster on rmkhoody signed " what reg exp find semi-col , select forward & , replace entire selection? update/solution-working code string s = "sale on coolitem&#x2122; watch" var cleanproductname = regex.replace(s, @"&#x?[^;]{2,4};", string.empty); cleanproductname = "sale on coolitem watch" string s = "deal buster on rmkhoody&#8482; signed" var cleanproductname = regex.replace(s, @"&#x?[^;]{2,4};", string.empty); cleanproductname = "deal buster on rmkhoody signed" you can use var cleanproductname = regex.replace(s, @&quo

Selenium Java. Finding an element with a complex Xpath -

i'm having trouble finding element in table. site finance.yahoo.com/q/ks?s=goog i'm trying find element named "market cap (intraday)" have id, need other elements in table , not. i've traced xpath think this //table[@id='yfncsumtab']/tbody/tr[2]/td[1]/table[2]/tbody/tr/td/table/tbody/td[1]/td[2]/span however, it's not spitting out amount. i'm getting no_such_element exception (it's not finding it) is xpath correct? or there more streamlined way find element? i can't technically go class names because can change stock you got typo. correct xpath is: //table[@id='yfncsumtab']/tbody/tr[2]/td[1]/table[2]/tbody/tr/td/table/tbody/tr[1]/td[2]/span your last part had td should have been tr. an easy way debug using chrome developer tools, see is there way xpath in google chrome?

c++ - SDL_renderer becomes null when creating -

i have annoying problem when create sdl_renderer in 1 of classes becomes nullptr when creating 1 in class functions normally. creating renderer in engine class, functions normally: m_window = sdl_createwindow("breakout", sdl_windowpos_centered, sdl_windowpos_centered, m_window_width, m_window_height, sdl_window_opengl); m_renderer = sdl_createrenderer(m_window, -1, sdl_renderer_accelerated); creating renderer in drawmanager class, renderer becomes nullptr: bool drawmanager::initialize(sdl_window *window, int width, int height) { m_renderer = sdl_createrenderer(window, -1, sdl_renderer_accelerated); if(m_renderer == nullptr) { return false; }; return true; }; the m_renderer variables created in each class respective header file. the window created in engine class sent drawmanager's initialize method , window not nullptr, renderer is. both classes have same sdl related includes. anyone has ideas what's w

binary - Two's Complement of a number and its negative number difference? -

so told two's complement used find complement of number , used complement positive numbers (i.e positve --> negative conversion) got example in book asks me following : express 23, -23, , -9 in 8-bit binary two’s complement form now mean? 23 means -23 in binary , -23 means 23 ? sorta confused on there 2's complement used represent negative numbers, in turn, can used subtraction. 23 = 00010111b to -23 (2's complement of 23), flip bits, , add 1: 11101000b + 1 =11101001b (-23) -9 2's complement of 9. 9 is 00001001b so -9 is 11110111b (flipping , add +1) see here

php - Codeigniter doesn't upload video files -

i have problem function upload video , images. can upload images not video don' know why. in , more code controller , form. code in user_models php: function newp($title,$post,$image,$video,$cat){ $id=$this->session->userdata('userid'); if($video!="") { $data=array( 'userid'=>$id, 'title'=>$title, 'forumpost'=>$post, 'categoryid'=>$cat, 'videourl'=>$video ); } image: else if($image!=""){ $data=array( 'userid'=>$id, 'title'=>$title, 'forumpost'=>$post, 'categoryid'=>$cat, 'imageurl'=>$image ); }else{ $data=array( 'userid'=>$id, 'title'=>$title, 'forumpost'=>$post, 'categoryid'=>$cat, );} $this->db->insert('forum',$data); } } form: <form method="post" enctype="mu

php Insert Query - Why Are There Two Connections to a Database? -

in script link page connects database : include "connect.php"; connect.php <?php error_reporting(e_error); /* allows php connect database */ // database variables $host = "myhost"; $user = "username"; $password = "password"; $dbname = "database"; // connect database $connect = mysql_connect($host, $user, $password) or die ("could not connect server ... \n" . mysql_error ()); mysql_select_db($dbname) or die ("could not connect database ... \n" . mysql_error ()); ? then in script have insert query: include "connect.php"; $link = mysql_connect($host, $user, $password); $query = "insert mytable values ('0','".mysql_escape_string($forename)."','".mysql_escape_string($surname)."', '".mysql_escape_string($username)."', '".mysql_escape_string($password)."', '".mysql_escape_string($email)."')&qu

SSH to multiple hosts at once -

i have script loops through list of hosts, connecting each of them ssh using rsa key, , saving output file on local machine - works correctly. however, commands run on each server take while (~30 minutes) , there 10 servers. run commands in parallel save time, can't seem working. here code (working): for host in $hosts; echo "connecting $host".. ssh -n -t -t $user@$host "/data/reports/formatted_report.sh" done how can speed up? you should add & end of ssh call, run on background. for host in $hosts; echo "connecting $host".. ssh -n -t -t $user@$host "/data/reports/formatted_report.sh" & done

c# - Insert a set of vertex within a convex polygon -

i want find out correct order of set of vertex in polygon given in unordered way. issue, develop algorithm based on computational geometry concepts. first, convex hull of set of vertex sorted in counterclockwise. then, keep remaining vertices sorted polar angle, starting pivot vertex lowest x coordenate, , insert using absolute value of cross product compute between vertex want add , 2 end points of edge in convex hull. information insert corresponding vertex between 2 point lowest absolute value on cross product, same explain above. here problem, heuristic not true , having problems sorted sequence of vertex of polygon. important keep in mind polygon complex polygon. want know if there algorithm allow me in more consistent way, or me improve algorithm explained above. here, snippet of code, if not enough ask me more, , using c# , .net 4.5: var ch = jarvismarch(p); // p set of unsorted vertex of polygon var v = (from v in p !ch.contains(v) select v).toarray();

How to share an canvas image to twitter? -

guys i've been searching examples , tutorials how tweet image canvas, have no luck in finding one. know how in facebook (i found example). can me? i figured out way post canvas images directly twitter using oauth. the canvas image needs converted base64 , base64 in binary. done using .todataurl() , postcanvastourl() , datauritoblob() it pretty fiddly process required piecing several answers, various blog posts , tutorials. i've created tutorial can follow walks through process . alternatively can fork project here

java - Tomcat NioBlockingSelector$BlockPoller many Updators causes OutOfMemoryError -

this issue happened twice during last 2 weeks. every time (after more 24 hours) process ram around 500mb , starts rise - in 10-15 minutes got 4g (xmx) , threw outofmemory. after tomcat became useless. the process runs on jdk 1.6.30 , tomcat 7.0.42 on ubuntu 12.04 using nio connector default settings. server implements async servlet request provide long polling (push) mechanism. from heap dump appears heap filled epollarraywrapper.updator instances coming blockpoller-1 thread. the code responsible adding updators updateregistrations understanding stops here. any on how debug / reproduce scenario or reference known issues on tomcat/java mailing lists appreciated.

linux - Apache access log for the most common IP address bash script -

so running bash script on apache log file can sort ip addresses , show common on shows @ bottom of page no top how show highest lowest this script far cat access_log.txt | awk '{print $1}'| uniq -c |sort -n -k 1| tail in txt file have 10.23.234.0 250.40.56.78 8.45.98.250 10.23.234.0 250.40.56.78 8.45.98.250 10.23.234.0 250.40.56.78 10.23.234.0 250.40.56.78 10.23.234.0 10.23.234.0 the output is 2 8.45.98.250 4 250.40.56.78 6 10.23.234.0 i want output 6 10.23.234.0 4 250.40.56.78 2 8.45.98.250 also want best way print out dns name next example 66.249.73.234 - - [12/fegb/2013:12:00:09 +1100] "get /java/tut/tut.sgml-065.html http/1.1" 200 752 "-" "mozilla/6.0 (compatible; googlebot/2.1; +http://www.google.com.html)" so be 66.249.73.234 - http://www.google.com.html thanks you can use this: awk '{a[$1]++} end {for (i in a) print a[i],i | "sort -rnk1"}' access_log.txt 5 10.23.234.0 4 250.40.56.

batch file - Run process in its own window -

i playing around batch on computer, , wanted run process in own window. figured out how run in own window, want window close when process ends. how can this? this code run python 2's python.exe in own window: @echo off start call "c:\program files\python27\python.exe" %* is there way can assign new window variable , check if has finished running process, exit new window? start via cmd /c, , window close once command ends. also, endoro said in comment, should not need call @start cmd /c "c:\program files\python27\python.exe" %*

php - WooCommerce Hide Prices When Inventory is set to '0' or 'out of stock' -

i know can use css property 'visibility:hidden', hide prices on product listing page (i have assigned specific page id, on sold items page. but on individual product page there piece of php can use says "if item out of stock/quantity set 0, hide price"? main sold out product listing: http://www.montagemodern.com/sold individual out of stock product page example: http://www.montagewestport.com/product/pair-of-glass-bubble-lamps/ try this: add_filter( "woocommerce_variable_sale_price_html", "theanand_remove_prices", 10, 2 ); add_filter( "woocommerce_variable_price_html", "theanand_remove_prices", 10, 2 ); add_filter( "woocommerce_get_price_html", "theanand_remove_prices", 10, 2 ); function theanand_remove_prices( $price, $product ) { if ( ! $product->is_in_stock()) { $price = ""; } return $price; } http://wwweb.jextensions.com/theanand.com/blog%252fhide

javascript - Updating Variable in HTML with JQuery -

i'm beginner programmer , i'm building game. whenever player clicks on gold image, should 1 gold. have following html piece of code: <li id="gold">gold: 0</li> that's starting gold, , through jquery update with: $('#gold-image').click(function() { gold++; $('#gold').replacewith('<li id="gold">gold: ' + gold + '</li>'); }); but don't feel that's best way update how gold player has. there way can write in html update variable whenever it's being changed or without having replace whole item? later in game there many functions running @ same time , increasing gold number, think replacing html code not optimal way. try existing div <div id="gold">gold: 0</div> : $('#gold-image').click(function() { gold++; $('#gold').html('gold: ' + gold); }); although above code work. not use jquery this. there other fram

ios - Loop an Array in order and repeat -

i creating local multiplayer text based game involve unlimited number of players. have created array hold players names inputed user on launch of app. having problems trying work out how display array index index , repeat on self such as player 1 turn player 2 turn player 1 turn player 2 turn player 1 turn and forth until questions have been asked (think of quiz game) so far have come not doing job int i; int count; (i = 0, count = [_players count]; < count; = + 1) { nsstring *element = [_players objectatindex:i]; self.turnlabel.text =( i, element); nslog(@"the element @ index %d in array is: %@", i, element); } previously when working without , array used simple if statement checked value of string , counted how many times been shown , added , and if value less previous string app determined other players turn. working array cant seem work out how this. basically how go showing each index in array in turn ,

linux - Unix vs BSD vs TCP vs Internet sockets? -

i reading linux programming interface , describes several different types of socket used on linux: unix domain berkeley tcp internet one of things book said if want communicate between remote hosts, couldn't use unix domain sockets because ipc on same host. have use "internet" sockets. however, still little confused how relates "tcp" sockets, berkeley sockets , other 2? relationship? why have internet socket tcp socket? in short trying understand (have missed out?) various different types of unix sockets , under circumstances use them? a socket abstraction. tag definition used on socket any: an endpoint of bidirectional inter-process communication flow. refers process flow on network connection, no means limited such. so major distinction sockets (1) use network , (2) sockets not. unix domain sockets not use network. api makes appear (mostly) same developer network socket communication done through kernel , sockets limited

Create Dynamic Function Name for Event Listeners in JavaScript -

i have code math game. have function button defines location , draws button specified in callback. the problem can create 1 of these, since event listeners are, baffling reason, referred function execute, rather other string name. unfortunately means writing lot of repetitive code instead. each function called eventlistener differ name of function particular button. how people work around problem? there no way name function (see: functanim & functclick) using string? function factsbutton(x, y, dofunction, contentcallback) { var getid = document.getelementbyid("canvas_1"); if (getid.getcontext) { var ctx = getid.getcontext("2d"); var btnw = 100; var btnh = 100; var cx = x - btnw/2; var cy = y - btnh/2; var left = cx; var right = cx + btnw; var top = cy; var bottom = cy + btnh; function functanim(event) { var mousepos = getmousepos(geti

angularjs - Get response header in then() function of a ngResource object's $promise property after resource resolved? -

i'm willing retrieve response header of resource request, cause i've put pagination information , else in rather response body, make rest api clear. though can success / error callback below: object.get({type:'foo'}, function(value, responseheaders){ var headers = responseheaders(); }); where 'object' resource factory service. further, when i'm trying make route change after required resources resolved, i've tried this: .when('/list', { templateurl: 'partials/list.html', controller: 'listctrl', // wait required promises resolved before controller instantialized resolve: { objects: ['object', '$route', function(object, $route){ return object.query($route.current.params).$promise; }] } }) and in controller, inject "objects" instead of object service, because it's resolved , filled in real data. but got problem when try headers info &

c# - Populate Textbox from Listbox Selection | Windows 7 Phone -

question: simply, best/most simple way pre-defined items in listbox (such "bob" ) to populated textbox in windows 7 phone enviroment? example: if select "bob" list box - "bob" should displayed in text box instantly (so user doesn't need type in username) ..and can instead use pre-made username list of usernames. problems: i've tried looking these little things , found no solutions. the solutions did find incredibly vague. many videos on youtube , elsewhere haven't covered windows 7 i fear windows 8 mobile different. right now, code fails populate textbox listbox selection. relatively new programmer, trying find feet in c# code: i don't know how this. i've tried using built in feature called selectionchanged no success. your class public class movie { public string actor { get; set; } public string name { get; set; } } create list of movie data . public class movielist : list<mo

javascript - Unwanted browser scrollbar change when overlaying DIV is displayed -

i have div following style: #dialog_overlay { width:100%; height:100%; background:#000000; opacity: 0.5; position:absolute; top:0; left:0; z-index:2000; display:none; } at bottom of page there link: <a href="#" onclick="test()">test</a> function test looks this: function test() { var overlay = $('#dialog_overlay')[0]; var body = document.body; var html = document.documentelement; var height = math.max( html.scrollheight, html.offsetheight, body.scrollheight, body.offsetheight, html.clientheight ); overlay.style.height = height + "px"; overlay.style.display = 'inline'; } i keep browser scrollbar position unchanged click link @ bottom of page. happens when div displayed, scrollbar pops up. know how keep scrollbar @ position before link clicked? you have use event.preventdefault(); function test(e) { e.preventdefault(); ... }

unix - Whether UDP packets received will pass to raw sockets and whether we can print UDP header using raw sockets -

this question raw sockets . in book given received udp , tcp packets never passed raw socket , cannot read udp , tcp headers in raw sockets , read udp , tcp header should read @ " data link layer " . i created raw socket using " sfd=socket(af_inet,sock_raw,ipproto_udp) " test whether receive udp packets not , tried print source port , destination port members of udp header. program printing out both ports i.e it's receiving udp packets , can read udp header. i didn't understand book say's , program printing out . plzz me wrong. i working on ubuntu os. socket created socket(af_inet,sock_raw,ipproto_udp) receive incoming udp packets. should notify packets not received method (see here ).

c# - WPF putting message -

i try put message using label on common form. regarding code below, i'd see messages, i'm trying put, see message after sleep(). lbstatus.content = "synchronizing customers"; thread.sleep(1000); lbstatus.content = "synchronizing estimates"; <label content="" height="28" name="lbstatus" margin="159,60,0,0" horizontalalignment="center" verticalalignment="top" width="207" fontsize="12" visibility="hidden" foreground="blue"/> thanks. issue sleeping on ui thread . after first line execution slept on ui thread it's ui thread responsibility refresh ui (ui thread refreshes ui on render dispatcher priority) . hence, see no update after first line execution because ui thread never gets time execute render priority items queued on dispatcher. ideally, should use dispatchertimer wait on ui thread interval of time , update once interval

mongodb - Trying to populate an array in mongo shell -

im trying populate array describe below results , output give me array 4 null elements "result" : [ { "maxtemp" : 83, "group_id" : "florida" }, { "maxtemp" : 57, "group_id" : "new mexico" }, { "maxtemp" : 81, "group_id" : "california" }, { "maxtemp" : 57, "group_id" : "vermont" } ], "ok" : 1 the code db.data.aggregate( { $group: { _id: "$state" , maxtemp: { $max :"$temperature"} } }, { $project: { _id: 0, group_id:"$_id", maxtemp: "$maxtemp&

java - How to convert a JOptionPane to a JDialog -

i need convert joptionpage jdialog, because need rid of quirky "ok" button. below code... joptionpane.showmessagedialog(null, interface, caption, joptionpane.warning_message, icon); interface gui, "caption" title, have warning message, have custom icon. this might not possible given info, need rid of ok. appreciated. why not create jdialog , put interface object contentpane, pack , display it. simple. you state: obviously joptionpane small, jdialog i'd have create window , more stuff. gui created, , can import joptionpane. can't jdialog believe. i'm confused. mean "the gui"? again, if jpanel, again, put jdialog. for instance if in actionlistener public void actionperformed(actionevent e) { // assuming being called within jframe named myframe jdialog dialog = new jdialog(myframe, "dialog title", modalitytype.application_modal); dialog.getcontentpane().add(interface); dialog.pack(); dialog.se

parsing - Create Regex that accept name but not Word "to" -

i working on parsing commentary of espncricinfo , want parse following of statements. example1 : yuvraj singh nasir jamshed example2 : kumar shoaib malik i write same regex both bowler , batsman name, regex : [a-za-z[-]*]*\s[a-za-z[-]*]*\s example1 parse facing problem in example2 like, "kumar to" consider bowler name... i need rid of word "to" bowler name. you can try following regex (?<=to |^).*?(?= to|$) it work in case of yuvraj singh nasir jamshed kumar shoaib malik string. ex. string[] names = regex.matches("yuvraj singh nasir jamshed kumar shoaib malik", "(?<=to |^).*?(?= to|$)") .cast<match>() .select(m => m.value) .toarray(); another option, since know every part of name starts capital letter, force rule ( to won't matched it, trailing whitespace will): ([a-z][\w-]*\s*)+

How to do NAT with PHP sockets -

i'm trying make peer peer app in php work in same kind of way skype works. works internal addresses, when try send data external address message never gets there. i'm missing address translation, i'm @ loss how php sockets. possible? this code have @ moment receive message, run first wait message: <?php $socket = socket_create(af_inet, sock_dgram, sol_udp) or die("could not create socket: " . socket_strerror(socket_last_error($socket))); socket_bind($socket, "0.0.0.0", 100) or die("could not bind socket: " . socket_strerror(socket_last_error($socket))); $ret = ""; $from_ip = ""; $from_port = 0; echo "waiting...\n"; socket_recvfrom($socket, $ret, 6, 0, $from_ip, $from_port); var_dump($ret, $from_ip, $from_port); socket_close($socket); and when waiting, run code send message: <?php $socket = socket_create(af_inet, sock_dgram, sol_udp) or die("could not create socket: " . socket_strerr

php - SOLVED: Why can't I count rows? -

solved: after fixing typo, didn't work how wanted it. fixed it. error in $ip2. since http_x_forwarded_for doesn't have input database recalled " " existing ip , didn't add new vote. fixed adding if ($ip2="") statement , adding votes. edit: changed typo, seems give me "you voted" page proxy change ip. edit 2: checked something: voted once , works gets added database, vote proxy gives ip1 still tells me voted already. can vote once. so have code, returns nothing: <?php $con = mysqli_connect("localhost","root","password","database"); $ip1 = $_server['remote_addr']; $ip2 = $_server['http_x_forwarded_for']; if (mysqli_connect_errno()) { echo "unable connect: " . mysqli_connect_error(); } $count1 = mysqli_num_rows(mysqli_query($con, "select * votes voteip1 = '$ip1'")); $count2 = mysqli_num_rows(mysqli_query($con, "select * votes voteip2 =

sql - ActiveRecord Joins -

ok, so, if user.joins(:session_users) , attributes of users table. how attributes of both tables in activerecord way, i.e., not sql? edit one ok, based on first answer, i'm trying have displayed. so, method written in users controller def blah @users = user.includes(:session_users) @users.each |user| user.session_users end end then have in users view blah.html.erb <%= @users.session_users %> and in routing section: match "/users/blah" => "users#blah" i think want includes instead of joins . see http://railscasts.com/episodes/181-include-vs-joins more info. should fetch columns both, users = user.includes(:session_users) users.each |user| user.session_users end note, still performs 2 sql queries. edit updated answer assumes user has_many :session_users routes: # config/routes.rb '/users/blah' => 'users#blah' controller: # app/controllers/users_controller.rb cl

I am trying to learn how to get the sum from a list of numbers in a file that represent currency in C# -

i trying sum of list of numbers file represents currency amounts. not work created array inside code , got working assignment way; still want know how program myself future reference. here copy of code did write , values of file sales.txt are: 1245.67 1189.55 1098.72 1456.88 2109.34 1987.55 1872.36 here copy of code: using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.threading.tasks; using system.windows.forms; using system.io; namespace lab7._2 { public partial class form1 : form { public form1() { initializecomponent(); } // readscore method private void readsales(list<decimal> saleslist) { try { // open file sales.txt streamreader inputfile = file.opentext("sales.txt"); // read sales list.

xml - JAXB : unmarshalexception - with linked exception: [java.io.IOException: Stream closed] -

i trying parse xml using sax ,i want use jaxb build map element name , value.i want override startelement , endelemnt have reached here until far , getting unmarshal exception.any appreciated!. jaxbcontext jaxbcontext = jaxbcontext.newinstance(my.class); unmarshaller jaxbunmarshaller = jaxbcontext.createunmarshaller(); unmarshallerhandler unmarshallerhandler = jaxbunmarshaller.getunmarshallerhandler(); saxparserfactory spf = saxparserfactory.newinstance(); saxparser sp = spf.newsaxparser(); xmlreader xr = sp.getxmlreader(); xr.setcontenthandler(unmarshallerhandler); inputstream inputstream = this.getclass().getresourceasstream("my.xml"); inputsource inputsource = new inputsource(inputstream); xr.parse(inputsource); jaxbelement element = (jaxbelement) jaxbunmarshaller.unmarshal(inputsource); //or if unmarahall specific class object still same exception. } catch (jaxbexception e) {

html - CSS Dropdown Menu - Sub Menu Hover Text Color Inheritance -

i've been working on css dropdown menu struggling sub menu text color. as expected, sub menu background color remains in hover color text reverts non-hover state. for example, when hovering item 9 need text in "menu, item 3 , item 6" same (white) item 9. i thinking inheritance issue can't seem figure out. here css .clearboth { margin: 0; padding: 0; clear: both; } #nav { font-family: sans-serif; font-size: 12pt; color: #666666; line-height: 1.0; } #nav { display: block; padding: 6px 8px; } #nav a:link { color: #666666; text-decoration: none; } #nav a:visited { color: #666666; text-decoration: none; } #nav a:hover { color: white; text-decoration: none; } #nav ul { margin: 0px; padding: 0px; list-style: none; left: -1px; } #nav ul ul { position: absolute; visibility: hidden; border: solid 1px gray; } #nav ul ul ul { position: absolute; visibility: hidden; le

Infinite loop when simulating a Program Counter design with Icarus Verilog -

i implementing simple program counter adder following prototype: module program_counter(input enable_count, input enable_overwrite, input[31:0] overwrite_value, output[31:0] out); when simulating icarus verilog, infinite loop @ first tick on overwriting disabled , count enabled, internal register being therefore feeded output of pc adder (pc + 4). i simplified issue basic piece of code d flip flop used 1-bit register: module register(input in, input set, output out); wire not_in; wire q0; wire not_q0; wire not_q; nand (q0, in, set); not (not_in, in); nand (not_q0, not_in, set); nand (out, q0, not_q); nand (not_q, not_q0, out); endmodule module test; reg clock; reg in; wire out; wire not_out; xor (x_out, out, 1); // add or (muxed_out, x_out, in); // mux register r(muxed_out, clock, out); i

Java: write method that accpets string object as argument and returns word count -

the assignment java write method accepts string objects argument , returns number of words contains. demonstrate method in program asks user input string , passes method. number of words should displayed in screen. know close there errors. public class wordcounter { //asks , gets users input here private static string getinput(scanner in) { string input; //imported scanner here scanner in = new scanner(system.in); //ask user enter string here system.out.println("enter string here: "); input = in.nextline(); //create if/else statment find out if user entered input if(input.length() > 0) { getinput(input); //get word count } else { system.out.println("error -- must enter string!"); system.out.println("enter string here: "); input = in.nextline(); } return input; } /

excel - PivotTable - Calculate value depending on combination of row labels -

Image
warning - using excel 2011 macs, inexperienced user hi all, i have sheet in excel bunch of categorical fields , numerical ones well. let's looks following: i make pivot table display average click rate ( avg_click_rate ) of unique combinations of [ year , region ], i.e. the combinations of fields in pivottable's rows section . for example, avg_click_rate of [ years =5] is: (0.5*10) / (10 +5 ) + (0.6*5) / (10+5) = 0.53 while avg_click_rate of [ region =north] is: (0.6*5) / (5+20) + (0.2*20) / (5+20) = 0.28 and avg_click_rate of [ years =5, region =south] is: (0.5*10)/10 = 0.5 i know have make custom calculated field this, life of me cannot figure out how code formula. seriously, appreciated. to clear, formula be: sum{ ( click_rate * number_members ) / sum{ number_members } } where numerator single value each row included in unique combination of [ year , region ], while denominator constant - total number_members unique combination of [ yea

java - Alphabetize List of Installed Apps -

i have list of users installed applications , want come out alphabetized (not on dividers or alphabetized) looked around haven't found (it has been dividers). feel should simple thing haven't been able figure out. here code: utilities.java: package com.example.awesomefilebuilderwidget; imports public class utilities { /* * installed application on mobile , return list * @param c context of application * @return list of installed applications */ public static list<resolveinfo> getinstalledapplications(context c) { intent intent = new intent(intent.action_main); intent.addcategory(intent.category_launcher); return c.getpackagemanager().queryintentactivities(intent, packagemanager.get_activities); } appinfoadapter.java: package com.example.awesomefilebuilderwidget; imports public class appinfoadapter extends baseadapter implements filterable { private context mcontext; private list<resolveinfo> mlistappinfo; private packagemanager