Posts

Showing posts from June, 2014

RSA Encryption process in PHP -

Image
in effort understand asymmetric encryption process outlined simple php script encrypt , decrypt simple numbers. noticed after while given numbers encrypt/decrypt algorithm fail, in decrypted , initial numbers didn't match. put loop in see how algorithm perform when ecrypting , decrypting 100 numbers , after number 32 process fell apart. is because p*q = 33? <?php # test encrypto algo // choose prime keys $p = 47; $q = 71; // compute n = pq $n = $p*$q; // choose e such 1 < e < f(n) , e , n coprime $e = 79; // compute value d such (d * e) % f(n) = 1 $d = 1019; // compute f(n) = (p-1)(q-1) $z = ($p - 1)*($q - 1); // create public , private keys $pubk = array('n' => $n, 'e' => $e); $privk = array('n'=> $n, 'd' => $d); // boundary loop $l = 100; // perform encypt/decrypt on 1..100 for($i = 1; $i <= $l; $i++) { $enc = enc($i, $pubk); $dec = dec($enc, $privk); print "encrypted <b>$i</b> = $enc

wix - Custom Bootstrapper created using wix3.6 is not unistalling the msi -

i'm installing msi package (my.msi) custom managed bootstrapper created using wix3.6 burn, bootstrapper first installs few prerequisite packages , installs my.msi. the installation working , there issue uninstallation. on uninstallation bootstrapper closes without uninstalling anything, on checking logs bootstrapper logging plan as: [1c10:2d80][2013-05-14t16:22:26]i201: planned package: my , state: present, default requested: absent, ba requested: absent, execute: uninstall, rollback: install, cache: no, uncache: yes, dependency: unregister i'm calling bootstrapper.engine.plan(launchaction.uninstall) in managed code uninstalling application. im not seeing other relevant information in log file. does 1 have suggestions? thanks. i've found solution link http://windows-installer-xml-wix-toolset.687559.n2.nabble.com/how-to-uninstall-burn-bundle-td7579345.html i've specified exitcode behavior=”schedulereboot” 1 of pre-requiiste packages.

c# or VB.net About casting an object into a datatype -

is there way able cast object depending on whats datatype written string after instanciating through relfection? example: string datatype = "list<genericclassname>"; list<genericclassname> o = (datatype)dynamicallyinstantiateclass("namespace.classname"); of course can : dynamic d = activator.createinstance("assemblyname","typename"); d.dosomthing(); to find assembly name right click on projects own's class in application tab can find type assembly name

c# - WebRequest GetResponse stuck with default proxy -

i have following code private bool isonline() { try { var wr = webrequest.createhttp("http://www.google.com"); wr.keepalive = false; wr.credentials = credentialcache.defaultcredentials; using (wr.getresponse()) { return true; } } catch { return false; } } when execute it remains stuck on getresponse line forever. thanks responses found problem in default proxy. in fact if construct new proxy in following way works var registry = registry.currentuser.opensubkey("software\\microsoft\\windows\\currentversion\\internet settings", false); var proxy = (string)registry.getvalue("proxyserver"); var isproxyenabled = (int)registry.getvalue("proxyenable"); if (isproxyenabled > 0) { wr.proxy = new webproxy(proxy, true, null, system.ne

c# - Implicit transaction with explicit implementation -

as framework developper, provide implicit transaction scope environment works across threads. this imply committabletransaction created existing ambiant transaction if any. could create commitabletransaction ambiant transaction ? i'll try implement new transactionscope using concept explained here .

c++ - How to deallocate an element in a vector of pointers? -

so have vector of pointers so: vector<example*> ve; i fill vector pointers this example* e = new example(); ve.push_back(e) but when want remove them, how assure deallocated? enough? ve.erase(ve.begin() + 1) delete ve[1] you have other way round, of course: delete ve[1]; ve.erase(ve.begin() + 1); however, it's vastly more preferable use smart pointers (such std::unique_ptr ) instead of raw pointers when expressing ownership.

jquery - Error callback doesnt have the details in IE -

i calling ajax call in app , error callback doesn't have error details in internet explorer, other browsers working fine app.api.remoteupload(datacall, url, function (data, status) { alert(data); }, function (error, status) { alert(error); }); alert(error) empty object in ie error condition, others browsers working fine. thoughts ? thanks,

java ee - How to create Soap based Web Service using Ecllipse and Tomcat 6.0? -

how create soap based web service using ecllipse galilio , tomcat 6.0 generally people on expect googling, , post specific questions once run specific problems tutorials find. soap xml specific set of elements: http://webdesign.about.com/od/soap/a/what-is-xml-soap.htm try create web services without using eclipse's tools: http://www.mkyong.com/webservices/jax-ws/jax-ws-hello-world-example/ try create web services eclipse's tools: http://javapapers.com/web-service/java-web-service-using-eclipse/ after read , try these examples, come , ask specific questions tripping up.

symfony - InvalidArgumentException: The service definition "security.encoder_factory.responses" does not exist -

i have strange error in symfony 2 installation. worked fine until ran error. cache cannot cleared because of error, preventing me checking/updating dependencies composer. invalidargumentexception: service definition "security.encoder_factory.responses" not exist i tried manually clear cache (removing folder, recreating , setup permissions again) without succes. error persists , result of every request when new cache build. is there suggestion look, or how solve problem? the proposed grep of pazi (see comments) gave no results, zero. it seemed magic dependency error. after clearing vendor/ directory, removing composer.lock file , installing vendors scratch (with update ) works again. maybe not correctly updated autoloader composer or not complete deleted vendor after removing composer.json. sometime magic happens :)

c# - How can I get Control Inside DatGridView columns -

how can controls checkbox in datagridviewcheckboxcell combobox in datagridviewcomboboxcell ? foreach (datagridviewrow row in dgvperformance.rows) { datagridviewcheckboxcell chk = (datagridviewcheckboxcell)row.cells[6]; //i need find checkbox in chk } you can't checkbox control datagridviewcheckboxcell , can value: foreach (datagridviewrow row in dgvperformance.rows){ datagridviewcheckboxcell chk = row.cells[6] datagridviewcheckboxcell; if(chk != null && (bool)chk.value){ //checked, } }

php - How to pass a 2 dimensional array value in a swift mailer setTo function -

i getting 2 dimensional array value result after loop.the value $chunk[$i][$j] .and when passed value setto function, error showing as warning: preg_match() expects parameter 2 string, array given in h:\xampp \htdocs\sngmarket\vendor\swiftmailer\swiftmailer\lib\classes\swift\mime\headers \mailboxheader.php line 350 . how solve this?.here code $query = $em->createquery("select distinct u.emailaddress acmeregistrationbundle:userlist u"); $grp_emails[] = $query->getresult(); $chunk = array_chunk($grp_emails, 10); $get_chunk_count = count($chunk); for($i=0;$i<$get_chunk_count;$i++) { $count_inside_count = count($chunk[$i]); for($j=0;$j<=$count_inside_count;$j++) { $mails=$chunk[$i][$j]; $message = \swift_message::newinstance() ->setsubject('hello email') ->setfrom('marketplace@socialnetgate.com') ->setto($mails) ->setreturnpath('gowth

javascript - How to pass 2 parameters through RegisterStartupScript? -

i have javascript function "initialize (latitude, longitude)" , when click on button want pass value textbox something. protected sub btnlat_click(byval sender object, byval e system.eventargs) dim latit textbox = formview.findcontrol("nr_latitudetextbox") dim longit textbox = formview.findcontrol("nr_longitudetextbox") page.clientscript.registerstartupscript(me.gettype(), "initialize", "initialize(" & latit.text, longit.text & ");", true) end sub but when try e error overload resolution failed because no accessible "registerstartupscript" accepts number of arguments. you have implemented code wrongly. change to. if initialize function expects string variables use code; page.clientscript.registerstartupscript(me.gettype(), "initialize", "initialize('" & latit.text & "','" & longit.text & "');", true

c++ cli - WinDBG debugging a C++ /CLI module -

i'm trying use windbg debug c++/cli module loaded in application (autodesk revit). problem breakpoints set in unmanaged class methods not hit. have class : class nativegeometryshape { public : nativegeometryshape() : width_(10), height_(12) {} int getarea() const; private : int width_; int height_; }; examining symbol gives following info : 0:000> x addon_revit2014!native* <msil:58bd350c > addon_revit2014!nativegeometryshape::getarea (void) <msil:58bd1264 > addon_revit2014!nativegeometryshape::nativegeometryshape (void) 58bd3500 addon_revit2014!nativegeometryshape::getarea (<no parameter info>) 58bd3520 addon_revit2014!nativegeometryshape::getarea (<no parameter info>) 58bd1258 addon_revit2014!nativegeometryshape::nativegeometryshape (<no parameter info>) so i'm using bm command setup breakpoints : 0:000> bm addon_revit2014!native* 1: <msil:58bd350

knockout.js - knockoutjs - Ajax Form Submit and update viewModel in success callback -

i'm building huge page has 10 different sections on , using knockout event binding, etc. each sections contains form it's own viewmodel it's fields , validation properties, etc. patterned after reading this post regarding multi-view models. i have masterviewmodel imports lots of subviewmodels. working fine , can set observable elements auto-populate upon field input, etc. i binding form submit function in viewmodel below. after validate , save form fields (via ajax post), want put section read-only mode, don't know how handle on viewmodel in ajax call's success callback. <form action="webservice.php" method="post" data-bind="submit: contactinformation.validatesubmit"> this.validatesubmit = function(formelement){ var result = ko.validation.group(this, {deep: true}); if (!this.isvalid()) { result.showallmessages(true); return false; } //actually save stuff, call ajax, submit form

d3.js - D3 convert geojson to topojson syntax -

i following syntax convert geojson topojson described here https://github.com/mbostock/topojson/wiki/command-line-reference i want make sure properties on generated topojson file can access info later on in code. problem none of getting generated topojson code. missing? topojson -o zone1994topojson.json -p w6id,w_name,ease_wored,ease_z4id,ease_zonen,region_nam,region_r2i,area_km 2,lat_hi,long_hi,lat_low,long_low zone1994.json

Using a new cultureinfo currency in Visual Studio 2010 C# -

thanks answering previous question, have new one: writing program output monetary values/data, want know how make program format value in other currency not presently listed in vs 2010 nigerian naira, ghana's cedis... question how create new cultureinfo language , currency symbol you can create new cultureinfo via cultureandregioninfobuilder class. @ docs examples.

javascript - Angularjs scope update issue -

i new angularjs. facing problem below markup like: <div class="data-list"> <ul ng-repeat="client in clients | orderby:orderprop | filter:query"> <li><a ng-click="update(client)" data={{client.id}} href="#">{{client.name}}</a></li> </ul> </div> <div class="clientid"> {{clientid}} </div> and controller like: function clientlistctrl($scope, $http) { $http.get('/dummy-data/clients.json', { cache: false }).success(function (data) { $scope.clients = data.clients; }); $scope.activeclient = {}; $scope.update = function (selectedclient) { $scope.activeclient = angular.copy(selectedclient); console.log($scope.activeclient); } console.log("after click"); console.log($scope.activeclient); // sorting list $scope.orderprop = '-numberofusers'; } i want when use

symfony - Million ManyToMany Entries - Memory Problems -

i develope type of "statistics-web". for example have blog entries , each visitor statistic entry. example blog entity: /** * @orm\manytomany(targetentity="statistic", inversedby="blogid") * @orm\jointable(name="blog_statistics") */ private $statistics; example statistic entity: /** * @orm\manytomany(targetentity="blog", mappedby="statistics") */ private $blog; in entity statistic have more fields "time, user, ip". in blog entity have fields "text, title, time". at beginning had 1 entry. working / good. a week later, had 5.000 entries (db) 2 blog entries. (2.500 per blog entry) php memory problems. i think doctrine tries load 2.500 entries ram/cache. need last 1 "last visited" information. rest of entries if needed them. (statistics overview) whats best "limit" entries? current call: "repository->fetchall" the solution pretty obvious:

java - Mixing Solr range function with additional parameters -

i have range function in solr fq works expected: {!frange l=1 u=2}sum(termfreq(tags,'twitter'),termfreq(tags,'facebook'),termfreq(tags,'pinterest')) however, if try further refine adding additional parameter end: {!frange l=1 u=2}sum(termfreq(tags,'twitter'),termfreq(tags,'facebook'),termfreq(tags,'pinterest')) , (region:"us") i error: org.apache.solr.search.syntaxerror: unexpected text after function: , (region:"us") if try prepend additional parameter: (region:"us") , {!frange l=1 u=2}sum(termfreq(tags,'twitter'),termfreq(tags,'facebook'),termfreq(tags,'pinterest')) i error: org.apache.solr.search.syntaxerror: expected ')' @ position 27 in 'sum(termfreq(tags,'twitter'' i've tried wrapping range portion in additional parenthesis still having no luck. how can combine range function additional query parameters? ok got solved need

mysql - Join returning zero elements where it should not -

the below sql statement looks friendship between 2 user elements, querying friendship table using users' profile_id#s, line added working statement left outer join block_user_filters blockedusers on blockedusers.profile_id_1 = 'abcde2' want see if user abcde2 has blocked anyone, , if want filter these friendships tableon clause left outer join block_user_filters blockedusers on blockedusers.profile_id_1 = 'abcde2' have block table populated block row of user abcde2 friended user element, whole statement returning 0 rows. please me fix if can. thank you select users1.username firstusername, users2.username secondusername, users1.profile_id firstprofid, users2.profile_id secondprofid, users1.picup firstpicup, users2.picup secondpicup `users` left outer join `friendship` on friendship.profile_id_1 = users.profile_id or friendship.profile_id_2 = users.profile_id left outer join users users1 on users1.profile_id = friendship.profil

ios - UISearchBar Cancel Button Not Working -

i have uisearchbar on mkmapview i'm going use search annotations. i'm having trouble getting cancel button work. create search bar in viewdidload method this: uisearchbar *searchbar = [[uisearchbar alloc] init]; searchbar.frame = cgrectmake(0, 0, 320,44); searchbar.showsbookmarkbutton = no; searchbar.showscancelbutton = yes; [self.view addsubview:searchbar]; and i've implemented method cancel button: - (void)searchbarcancelbuttonclicked:(uisearchbar *)searchbar { [searchbar resignfirstresponder]; } what doing wrong? you haven't assigned search bar delegate. searchbar.delegate = self

jquery ui - jQueryUI autocomplete response data -

scenario i have jqueryui autocomplete in page. data retrieved through ajax call. working fine. question as jqueryui api , source property setter. is there autocomplete property exposing retrieved data? in other term, if re-focus autocomplete bound input , still contains previous searched terms, can show autocomplete results without re-excuting ajax call? i have searched similar questions . sirderpington , succeed in re-opening result menu. still, ajax call re-processed. $('myselector').autocomplete().on("focus", function () { $(this).autocomplete("search"); }) so question remains. if understood right want show same results if user re-focusses input? in jsfiddle seems work i'm not sure if trigger ajax call. anyway see did: $('#autocomplete').autocomplete({ source: availabletags, minlength: 0 }).focus(function () { var $this = $(this); var inputval = $this.val(); //

Querying multiple linked classes in Rails -

i want query multiple tables. example in posts table there user_id linked users id. while showing every post, want display picture of user. approach this, there problem. @user.picture method undefined. <% @programs.each |post| %> <%= @user = user.where("id = post.user_id") %> <li class="one-third column"> <div class="wrapper"> <div class="postthumb"><img src="<%= @user.picture %>" /></div> <div class="postdetails"> <%= link_to "#{ post.title.upcase! }".html_safe, all_posts_path, :class => "posttitle" %> <p><%= truncate post.details, :length => 90 %></p> </div> </div> </li> <% end %> program controller: class programcontroller < applicationcontroller def index @programs = program.all end user model: class user < activerecord::base attr_acc

java - Which Algorithm to choose in pattern matching time serie? -

i 've got multiple time series represented multiple list of integers (in main memory, not in database). need perform fast search, among series, find specific pattern. example, detect pattern [ (0,1), (3,2), (4,1) ] (x,y) x = time, y = # series. i've googled pattern detection, pattern matching, seems there thousand of algorithms, , don't quite see relation problem of time. first idea coming head, ,for every point,checking distance next point on specific train according pattern, , on. i need directions on start, because i'm confused among theses researcher publications ! thank much nico specification : make multiple pass, jitter associated. example, let's take pattern define above. first pass, i'll need match exact pattern. second pass, need match pattern jitter of 1 -> [ (0,1), ( 3 +- 1, 2) (4 +- 1, 1) ], second pass -> [ (0,1), (3 +- 2, 2) (4 +- 1, 1) ] etc. jitters go five. first "event" (time,# serie) "constant" @ t

c++ - accept() in message queues IPC UNIX -

for (;;) { if (msgrcv(msqid, &flag, sizeof(struct flags) - sizeof(long), 1, ipc_nowait)>0) break; } msgsnd(msqid, &message , sizeof(struct messages) - sizeof(long), 0); is there accept() function in sockets ipc, message queues ipc? server should wait client connection , when client connected send data it. special send client useless data , check data in infinity loop(that means client connected, know stupid algorithm). no, there nothing directly analogous. message queues more connectionless datagram sockets connection-oriented stream sockets (which support accept() , forth). some implementations (z/os?) expose number of processes blocked on msgrcv , similar looking for, not portable. as see it, have 2 easy options. first, doing don't ipc_nowait in server's msgrcv . no point in spinning in loop if you're not doing anything. block until client announces itself. (and use different message types communication client-to

Populating Factory using Metaclasses in Python -

obviously, registering classes in python major use-case metaclasses. in case, i've got serialization module uses dynamic imports create classes , i'd prefer replace factory pattern. so basically, this: data = #(generic class based on serial data) modulename = data.getmodule() classname = data.getclass() amodule = __import__(modulename) aclass = getattr(amodule, classname) but want this: data = #(generic class based on serial data) classkey = data.getfactorykey() aclass = factory.getclass(classkey) however, there's hitch: if make factory rely on metaclasses, factory learns existence of classes after modules imported (e.g., they're registered @ module import time). populate factory, i'd have either: manually import related modules (which defeat purpose of having metaclasses automatically register things...) or automatically import in whole project (which strikes me incredibly clunky , ham-fisted). out of these options, registering classes direct

java - Network on Main Thread exception while trying to send e-mails in Android without user intervention -

this question has answer here: how fix android.os.networkonmainthreadexception? 44 answers i tried implement sending of emails without user intervention explained in post that's open issue: sending email in android using javamail api without using default/built-in app did not send e-mails. following error: "networkonmainthreadexception" can help? pd. don´t put comment in post because don't leave, guess closed. thank you. you can not perform network operation in main thread.. use asynctask instead

android - SubMenu getItem don't work -

i have created menu submenu , try set event on each last event. it worked excepted last itération of submenu(each submenu can have submenu or not, it's random). i've add sys.out show itemid , itemtitle each submenu iteration, worked submenu exepted last iteration (fourth submenu) public class tab3 extends activity { layoutinflater inflater; xmlparser parser = new xmlparser(); arraylist<hashmap<string, string>> menubase=menutest.menubase; arraylist<hashmap<string, string>> menu1=menutest.menu1; arraylist<hashmap<string, string>> menu2=menutest.menu2; arraylist<hashmap<string, string>> menu3=menutest.menu3; document doc3=menutest.doc3; arraylist<integer> idfin; static final string key_category_2="category_2"; static final string key_name_3="name_3"; static final string key_category_4="category_4"; static final string key_name_5="

osx - What happens if dispatch_main gets called from outside of the main thread? -

the dispatch_main function used make main thread start processing blocks dispatched main queue. so, dispatch_main kind of run loop, doesn't return and, after processing already-queued blocks, waits other blocks submitted main queue. so, happens if dispatch_main gets called outside of main thread? if main thread processing function, interrupted in order allow main thread process queued blocks? allowed call dispatch_main outside of main thread? dispatch_main() asserts when called outside of main thread , aborts process, must called main thread. dispatch_main() nothing other pthread_exit() in disguise (see implementation ): turns main queue ordinary serial dispatch queue , terminates main thread. the main queue serviced on-demand workqueue thread point on, other dispatch queue.

java - JavaFX built with netbeans on my 64 bit Mac won't run on 32 bit Linux -

i'm little perplexed. have javafx program i'm working on (hobby) , builds , runs fine on mac. (i have latest oracle java 7). when run jar file built on mac (in latest netbeans), on 32-bit linux system (also latest oracle version) gives me following error: java.lang.reflect.invocationtargetexception file:/home/me/afolder/someone/saved/something.jar!/something/mainwindow.fxml @ javafx.fxml.fxmlloader.load(fxmlloader.java:2186) @ javafx.fxml.fxmlloader.load(fxmlloader.java:2028) @ javafx.fxml.fxmlloader.load(fxmlloader.java:2744) @ javafx.fxml.fxmlloader.load(fxmlloader.java:2723) @ javafx.fxml.fxmlloader.load(fxmlloader.java:2709) @ javafx.fxml.fxmlloader.load(fxmlloader.java:2696) @ javafx.fxml.fxmlloader.load(fxmlloader.java:2685) @ something.something.start(something.java:33) @ com.sun.javafx.application.launcherimpl$5.run(launcherimpl.java:319) @ com.sun.javafx.application.platformimpl$5.run(platformimpl.java:215) @ com.sun.javafx.applic

jsf - Liferay with PrimeFaces, display image -NOT using Path - -

i'm developing liferay portlet, using primefaces. several pages feature datatable elements, 1 of columns have image thumbnail. how can present image pf components, if can't use image path ? searching tutorials , available pf controls, see components , loads image stored in tomcat directory, using it's relative path value. but happens if take image stored documents , media, or in remote database blob/bytearray/text ? how suggest me load images in datatable column? using primefaces 3.5 , liferay 6.1.0 ce ga1 thank you..

json - Returning gzipped content on a Sinatra app -

i have sinatra app inside ror3 app. i defined sinatra module , added following redirect in ror3 routes match '/v2', mysinatramodule, :anchor=>false my sinatra app serving services within /v2/* not being gzipped. tried adding "use rack:deflater" in config.ru since passes through ror3 not working. json service, returns string. i tried using gzip::zlibwriter , compresses output, not interpreted gzipped on other side. any help? there's 2 things come mind try. firstly, instead of using ror router, let rack handle it. there several ways instead, easiest probably: # config.ru require 'sinatra_module' require 'rails_app' map "/" run railsapp end map "/v2" use rack::deflater # might want put in sinatra app. run mysinatramodule end the other thing might try setting content-encoding header "gzip" , or, if doesn't work try setting content-type header "application/x-gzip" (i&

ruby - Chain should_receive Possible? -

is there more terse way write rspec code? mailer = double adminmailer.should_receive(:request_failed).with(@request).and_return(mailer) mailer.should_receive(:deliver) i'm envisioning this: adminmailer .should_receive(:request_failed) .with(@request) .should_receive(:deliver) i don't think it's possible, if is, wouldn't recommend it. specs should show expecting of code, , first example quite succinctly!

jquery dynamically form elements and autocomplete -

i have code adds 2 fields , make inputs have autocomplete function: $("#addelem").click(function () { var new_id = new date().gettime(); var content = '<div id="fields"><input type="hidden" name="softwareperasset.index" value="' + new_id + '" />' + '<select name="softwareperasset[' + new_id + '].name" id="softwareperasset[' + new_id + '].name"> <option value="1">visio</option><option value="2">painter</option></select>&nbsp;&nbsp;&nbsp;' + '<input type="text" name="softwareperasset[' + new_id + '].serial" id="softwareperasset[' + new_id + '].serial">&nbsp;&nbsp;&nbsp;<a id="test" href="#">

Regex for fixed length string, starting with multiple words -

i'm trying make regex (js flavor) matches string 17 alphanumeric characters in length , must start either "ab, "de" or "gh". after these 3 possibilities, alphanumeric character accepted. match: ab163829f13246915 det639601ba167860 ghf1973771a002957 don't match xyz63829f13246915 aaa639601ba167860 bbc1973771a002957 so far have regex i'm testing on http://regexpal.com/ ^(ab|)[a-za-z0-9]{17}$ not sure why pipe character required match first example, or why fails when add "de" after pipe. anyone? use this: ^(ab|de|gh)[a-za-z0-9]{15}$ the first 2 characters take two, need 15 more alphanumeric characters after that. http://rubular.com/r/rawmiy4xeh

java - Control order in Swing -

so i'm creating little java program netbeans' gui builder. have whole bunch of labels (that happen icons) on screen - , sent same exact location. how make sure label got sent last, displays ontop on pile of labels? make sure mousepress event comes top label, not 1 of ones underneath? this 3rd day learning java, excuse me if it's dumb question :d use cardlayout setlayout. can stack things on another. let's assume using jpanel every "card" of cardlayout, on place jlabel. need make jpanel transparent: jpanel.setopaque(false); i believe jlabel transparent.

What is the best way to iterate over a python list, excluding certain values and printing out the result -

i new python , have question: have checked similar questions, checked tutorial dive python , checked python documentation, googlebinging, similar stack overflow questions , dozen other tutorials. have section of python code reads text file containing 20 tweets. able extract these 20 tweets using following code: with open ('output.txt') fp: line in iter(fp.readline,''): tweets=json.loads(line) data.append(tweets.get('text')) i=0 while < len(data): print data[i] i=i+1 the above while loop iterates , prints out 20 tweets (lines) output.txt . however, these 20 lines contain non-english character data "los ladillo los dos, soy maaaala o maloooooooooooo" , urls "http://t.co/57ldpk" , string "none" , photos url "photo: http://t.co/kxpaaaaa (i have edited privacy) i purge output of (which list ), , exclude following: the none en

ruby on rails 3 - Create an association between one model that has two foreign_keys to another model -

struggling association, have 2 models: figure , market, market can trade toy figure else. figure class figure_id:integer name :string image_url:string market class market_id:integer figure_you_want_to_trade_id :integer #this should associated figure_id figure_you_want_from_someone_else_id:integer #this should associated figure_id how go making association? i'm thinking: market.rb has_many :figure_to_trade, :class_name => figure, :foreign_key => figure_id has_many :figure_you_want, :class_name => figure, :foreign_key => figure_id figure.rb belongs_to :figure_you_want_to_trade, :class_name => market belongs_to :figure_you_want_from_someone_else, :class_name => market this error i'm receiving when try output this: <%= market.figure_to_trade %> sqlite3::sqlexception: no such column: figures.figure_id: select "figures".* "figures" "figures"."figure_id" = 1 figu

python - How can I identify when a Button is released in Tkinter? -

i'm using tkinter make gui , drive robot. i have 4 buttons: forward , right , backward , left . want make robot move long button being pressed, , stop when button released. how can identify when button released in tkinter? you can create bindings <buttonpress> , <buttonrelease> events independently. a starting point learning events , bindings here: http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm here's working example: import tkinter tk import time class example(tk.frame): def __init__(self, *args, **kwargs): tk.frame.__init__(self, *args, **kwargs) self.button = tk.button(self, text="press me!") self.text = tk.text(self, width=40, height=6) self.vsb = tk.scrollbar(self, command=self.text.yview) self.text.configure(yscrollcommand=self.vsb.set) self.button.pack(side="top") self.vsb.pack(side="right", fill="y") self.text

python - Decoding nested JSON with multiple 'for' loops -

i'm new python (last week), , have reached limit. spent 3 days on this, of time in stackoverflow, cannot work out how go further! the json has multiple nested arrays. contain 3 (as example below (json.txt) does), or 30. need loop through each, drill down 'innings' , value of 'wickets'. it's last step i'm confused by. can advise? yours in total desperation will import os, json,requests print 'starting' url = 'https://dl.dropboxusercontent.com/u/3758695/json.txt' # download json string json_string = requests.get(url) print 'downloaded json' # content the_data = json_string.json() print 'the_data has length ', len(the_data) index in range(len(the_data)): print 'now working on index ', index wicket in the_data[index]: print 'wicket equals ',wicket # ok - can see innings. now, how inside # , obtain 'wickets'? first of all, do

java - IndexOutOfBoundsException when removing ArrayList element -

i have code right here (using lwjgl should moot) try , pause game when pressing esc key. use arraylist keys keep track of pressed , isn't. public list<integer> keys = new arraylist<integer>(); public void get() { if (iskeydown(key_escape) && !keys.contains(key_escape)) { keys.add(key_escape); keyescape(); } } public void rem() { if (!iskeydown(key_escape) && keys.contains(key_escape)) keys.remove(key_escape); } private void keyescape() { screen.paused ^= true; } this called loop, get() , rem() 1 right after in loop, in order. gives me awesome java.lang.indexoutofboundsexception: index: 1, size: 1 @ keys.remove(key_escape); when let go of esc. anyone have insight share? what value of key_escape? it might int value 1 instead of removing object value, remove object @ position 1 apparently not exist.

duplicate image slideshow in fancybox -

di have set fancybox opened using hotspot. there 3 images have slideshow when i've done first image appears 3 times. sequence of slideshow photo1, photo1, photo1, photo2, photo3. <script type="text/javascript"> $(document).ready(function(){ $(".fancybox5") .attr('rel', 'gallery') .fancybox(); }); </script> <a class="fancybox5" href="#inline5"><area shape="poly" coords="704,113,688,262,835,286,859,132" href="#" alt="pics" /> <div id="inline5" style="width:100%;display: none;"> <a class="fancybox5" href="media/photo1.jpg"><img src="media/photo1.jpg" width="400" height="500" /></a> <div class="hidden"> <a class="fancybox5" href="media/photo2.jpg"><img src="media/photo2.jpg" width="400&qu

ruby on rails - How to search an integer field in ActiveRecord? -

i want users able search database using function: def self.search(query) new_query = (query.to_d * 100).to_i where("price_in_cents ?", new_query) end the problem prices stored in database integers , if searches "10.99" should actually search "1099". the function above doesn't work, though, , wonder doing wrong. thanks help. why use "like" number comparison? should use either "=" or ">=" etc. def self.search(query) new_query = (query.to_d * 100).to_i where("price_in_cents = ?", new_query) end

windows - Is Visual Studio 2012 suitable for C (not C++) professional programming? -

i've develop service windows7 in c. i've use few c libraries (gnu scientific library among others) , i'm wondering ide adopt. with c#, i'm used both visual studio 2012 , monodevelop 4, i'm not sure concrete usability c (not c++). not toy project or learning tool: i've productive enough pay bills. is vs2012 suitable kind of project? common features can't use plain c development? serious limitations in ms c compiler? gcc/gdb supported? professional alternative (free or not)? edit note i've few c libraries link support windows. 1 developed in 2006 (with vs 2005). visual studio no longer supports c separate language. can write unmanaged c++, satisfactory writing windows services. gsl includes "extern c" decls linking c++, won't problem. compile gsl libraries vs, , you'll go. cygwin , mingw provide alternatives vs, vs gold standard working in windows; in particular, if writing service, ability attach , detach process

java - all possible combination of n sets -

i have n sets. each set has different number of elements. write algorithm give me possible combinations sets. example: lets have: s1={1,2}, s2={a,b,c}, s3={$,%,£,!} a combination should like c1={1,a,$} c2={1,a,%} .... , on number of possible combination 2*3*4 = 24 please me write algorithm in java. many in advance recursion friend: public class printsetcomb{ public static void main(string[] args){ string[] set1 = {"1","2"}; string[] set2 = {"a","b","c"}; string[] set3 = {"$", "%", "£", "!"}; string[][] sets = {set1, set2, set3}; printcombinations(sets, 0, ""); } private static void printcombinations(string[][] sets, int n, string prefix){ if(n >= sets.length){ system.out.println("{"+prefix.substring(0,prefix.length()-1)+"}"); return; } fo

cuda - Grid of thread blocks and Multiprocessor -

the cuda programing guide states: the cuda architecture built around scalable array of multithreaded streaming multiprocessors (sms). when cuda program on host cpu invokes kernel grid, blocks of grid enumerated , distributed multiprocessors available execution capacity. threads of thread block execute concurrently on 1 multiprocessor, , multiple thread blocks can execute concurrently on 1 multiprocessor. thread blocks terminate, new blocks launched on vacated multiprocessors. does mean if have video card of 2 multiprocessor x n-cuda cores , if launch kernel like mykernel<<<1,n>>>(sth); one of multiprocessors idle, since i'm launching single block of n threads? you correct. in currect cuda architectures, block ever scheduled , run on single multiprocessor. if run 1 block on device more 1 multiprocessor, 1 of multiprocessors idle.

java - Strange NullPointer Exception in main -

i'm trying exercise java book. code comes , have not added code besides setting path database. i'm on osx, had install apache derby. everytime build , run program this: derby has been started. product list: bvbn murach's beginning visual basic .net $49.50 cshp murach's c# $49.50 java murach's beginning java $49.50 jsps murach's java servlets , jsp $49.50 mcb2 murach's mainframe cobol $59.50 sqls murach's sql sql server $49.50 zjcl murach's os/390 , z/os jcl $62.50 exception in thread "main" java.lang.nullpointerexception first product: @ dbtesterapp.printproduct(dbtesterapp.java:117) @ dbtesterapp.printfirstproduct(dbtesterapp.java:66) @ dbtesterapp.main(dbtesterapp.java:16) java result: 1 build successful (total time: 2 seconds) i'm confused why exception keeps happening. don't

c++ - Exception Handling : But do not end up in the catch block -

i'm getting unhandled exception in function. function called many times. try { unsigned char* b1 = new unsigned char[length]; //<---here unsigned char* b2 = new unsigned char[length]; //do stuff doesn't seem throw exception...then @ end delete[] b1; delete[] b2; } catch (...) { cout<< "error..." <<end; } thing is, unhandled exception occurs @ random times. breaks on first statement. , other issue is: why isn't caught? visual studio halts , i'm in new.cpp. and third question/issue is: how can track down problem? length never uninitialized amount; around 512. seems cout << ... requires memory allocation, cannot it. configure debugger break execution when exception thrown (as other people suggest) , see thrown , @ point. btw, sutter writes shouldn't try catch memory allocation exceptions @ - it's quite hard needed error reporting without memory allocations, , these fail, why bother. (and maybe not th

multithreading - IronPython: StartThread creates 'DummyThreads' that don't get cleaned up -

Image
the problem have in ironpython application threads being created never cleaned up, when method run has exited. in application start threads in 2 ways: a) using python-style threads (sub-classes of threading.thread in run() method), , b) using .net 'threadstart' approach. python-style threads behave expected, , after 'run()' exits cleaned up. .net style threads never cleaned up, after have exited. can call del, abort, whatever want, , has no effect on them. the following ironpython script demonstrates issue: import system import threading import time import logging def do_beeps(): logging.debug("starting do_beeps") t_start = time.clock() while time.clock() - t_start < 10: system.console.beep() system.threading.thread.currentthread.join(1000) logging.debug("exiting do_beeps") class pythonstylethread(threading.thread): def __init__(self, thread_name="pythonstylethread"): super(pythonsty

html - Including a javascript file? -

i'm having little trouble including javascript file. have following code block on page, , want move separate file called cart.js. problem is, whenever move script file stops working on page. have tried wrapping entire code block on document ready didn't work. i'm loss on how include this. edit: found error advice of looking @ console. turns out, leaving call jquery in cart.js causing issue. current_fin = "none"; current_mat = "pine"; current_col = "red"; current_size = "36"; jquery(document).ready(function($) { $("#dropdownthree").hide(); }); // pass current selection variable use. function getmaterial() {// function checks material , if plastic hides/shows boxes var mat = document.getelementbyid("dropdownone"); current_mat = mat.options[mat.selectedindex].text; if (current_mat == "plastic") { var col = document.getelementbyid("dropdownthree"); current_fin = col.options[

c# - table isn't showing up in VisualStudio 2012 -

Image
i used visual studio 2010 , returning use 2012 , book using based 2010, few things different far instructions, not much. however, my problem have created table, , saved dbo.table "person" , asks location save .sql file. i've tried saving in different locations table still doesn't appear under server explorer -> tables. any appreciated. --edit even if save dbo.people, location save in show under visual studio's tables? you need run table creation script on database server vs connected not save it.

php - Laravel 4 eloquent pivot table -

i have 3 tables: users, items , user_items. user has many items , item belongs many users. the tables: users id username password items id name equipable user_items id user_id item_id equipped the models: class user extends eloquent { public function items() { return $this->belongstomany('item', 'user_items') ->withpivot('equipped'); } } class item extends eloquent { public function users() { return $this->belongstomany('user', 'user_items'); } } in pivot (user_items) table i've important column named "equipped". i've form users can equip, unequip , throw items. form has hidden field pivot (user_items) table row id. so, when user tries equip item, system checks if item equipable. so, want object pivot data , item data, based on item_id pivot table, can send handler (where logic handled). so i've first access pivot table , access

delegates - C# Actions and GC -

i using actions in c# , wondering if need set instance of action null once wish gc collect objects properly? here example: public class { public action a; } public class b { public string str; } public class c { public void dosomething() { aclass = new a(); b bclass = new b(); aclass.a = () => { bclass.str = "hello"; } } } inside main method have this: public void main(...) { c cclass = new c(); cclass.dosomething(); console.writeline("at point dont need object or b anymore gc collect them automatically."); console.writeline("therefore giving gc time letting app sleep"); thread.sleep(3000000); console.writeline("the app propably sleeping long enough gc have tried collecting objects @ least once not sure if , b objects have been collected"); } } please read console.writeline text understand asking here. if apply understanding of gc example gc never collect objects since cannot destroyed because holds