Posts

Showing posts from April, 2010

What is the way to set ipython notebook server parameters when running notebook with django-extensions? -

i using following command run ipython notebook server django: ./manage.py shell_plus --notebook the server functions expected. however, set port , not launch browser when starting server. if running ipython notebook server without django use following: ipython notebook --port=9999 --no-browser i checked documentation here , tried setting options using ipython_arguments = [ '--ext', 'django_extensions.management.notebook_extension', '--port=9999', '--no-browser, ] these arguments loaded after server has started , not change notebook server settings can gather. how can set notebook server settings when launching notebook server django using ./manage.py shell_plus --notebook ? thank in advance. i had same problem, , solved creating new file called ipython_config.py in same folder manage.py following content: c = get_config() # notebook server config below # kernel config c.ipkernelapp.pyla...

c# - Access performance counter programmatically in Microsoft Azure web app -

is possible access cpu, ram , asp.net requests performance counter web app via api? when call using system.diagnostics.performancecounter.nextvalue method exception: access registry key 'global' denied. i have seen examples web roles, nothing websites. according this microsoft article not supported on azure websites: windows performance counter collection isn’t supported on azure website you can monitor cpu usuage , memory working set using monitor tab in old management portal or directly on website "blade" using new portal. maybe can these data out programatically using microsoft.windowsazure.management.websites

java - How do I use reflection to get data out of a hibernate object? -

here example of issue having using reflection. simple case, need dynamically build method name on fly... simple case can not work! client1 cdata = (client1) session.get(client1.class, 1); int ctype = cdata.getclienttype(); int ctype2 = -1; method method[] = null; method getctypemethod = null; try { method = cdata.getclass().getmethods(); (method m : method){ system.out.println(m.getname()); // displays getclienttype } getctypemethod = cdata.getclass().getmethod("getclienttype", int.class); if (getctypemethod != null){ ctype2 = (int) getctypemethod.invoke(cdata, int.class); } } catch (exception e) { e.printstacktrace(); } assertequals(ctype, ctype2); the line: getctypemethod = cdata.getclass().getmethod("getclienttype", int.class); always throws exception: java.lang.nosuchmethodexception: client1.getclienttype(int) the method getmethod receives param classes, not return type, getclienttype receive int? if...

sql - Group by similar string field -

a table logs files have been generated every report type in application. determine last time each report generated. files named numbers_reportname-day-time.xml. i make query groups file names according what's between first sequence of numbers , time stamps, regex do. is possible sql / sybase? filename generationdate 456879_report-one-20150409-164652.xml 2015/04/09 789456_report-two-20150409-131534.xml 2015/04/09 123458_report-two-20150510-121055.xml 2015/04/10 784111_report-three-20150510-100652.xml 2015/04/10 to filename generationdate report-one 2015/04/09 report-two 2015/04/10 report-three 2015/04/10 select regexp_substr( filename , '((report-)([a-za-z]*))' ) reportname , generationdate x group reportname; this should work regardless of how long re...

c# - What the Exception? InvalidCastException -

in legacy application, have sqldatareader . following field creates invalidcastexception bit field. public static t getvalueornull<t>(this idatareader reader, string column) { int ordinal; if(!string.isnullorempty(column) && !reader.isdbnull(reader.getordinal(column))) if(int.tryparse(reader.getordinal(column).tostring(), out ordinal)) return (t)reader.getvalue(ordinal); return default(t); } what odd, (t)reader.getvalue(ordinal) assign valid type. assigns false , error still occurs. i'm not entirely sure why. if perform gettype(); indeed show boolean type. i've checked ensure threadsafe. the reason code fail on bit field , correlated boolean due inferred type. underlying data type wasn't bool rather bool? . once model reflected nullable boolean, code worked intended.

python - Firefox sees element where PhantomJS does not when using Selenium-Webdriver -

i have been looking around quite long time find solution problem, hope here can think of help. i have working selenium script (in python) working firefox driver connect on website. when using phantomjs driver, doesn't work anymore. the form generated javascript , on https website. here code of user input : <script language="javascript1.2"> document.writeln("<input class=\"textform\" type=\"text\" id=\"user\" name=\"user\" size=\"" + size + "\" tabindex=1 onfocus=\"hadfocus(true)\">"); </script> here part of script looking : (working on firefox not phantomjs) from selenium import webdriver selenium.webdriver.common.keys import keys selenium.webdriver.common.by import selenium.webdriver.support.ui import webdriverwait selenium.webdriver.support import expected_conditions ec import time driver = webdriver.firefox() driver.get([my url]) print driver.page_source ...

How can I hide a span if an input field is valid with AngularJS? -

i can this: <span ng-show="form.size.$error.integer">problem</span> but have number of different possible errors there way can hide span if field valid? you can use $valid property of form. <span ng-show="form.size.$error.integer && ! form.size.$valid">problem</span> but im not sure why need this. if there no error, form.size.$error.integer should false , should hidden anyways.

php - With memcache, redis throw exception:read error on connection -

in project, want use redis while using memcached(it's old system , donnot want outright replace memcached).but when try push element list in redis, meet exception "read error on connection". find if connecting memcached before connecting redis, throw exception, connecting redis firstly can avoid problem. environment: nginx + php-fpm + php 5.3.3 + redis 2.8.19 use connect instead of pconnect can fix exception. perfer use pconnect. here code: $memcache = new memcached ('client'); $memcache->addserver('127.0.0.1', '8022'); $memcache->set ('mckey', 1); echo $memcache->get('mckey'); $redis = new redis(); $redis->pconnect('127.0.0.1', '6379', 1000); $redis->setoption(redis::opt_read_timeout, -1); try { $redis->lpush('mykey', 1, 2); echo 'ok'; } catch (exception $e) { echo $e->getmessage(); } any problem of code here?

ios - Black screen when launching my app on iPhone -

i wanted disable launch screen view when app launched deleted "launch screen interface file base name" line in 'info'. since did it, black screen whenever launch app. how can fix it? i have found solution - in general > main interface > main.storyboard. reason wasn't selected.

ios - MailCore2 - Fetch message content without downloading images or attachments? -

i want provide preview of user's messages, don't wish download attachments in order that. the information need is: subject date sender information (display name if available, email address) plain-text message by calling method fetchmessagesbynumberoperationwithfolder: request kind mcoimapmessagesrequestkindheaders , date , subject, it's slow return if of messages have attachments. calling request kind mcoimapmessagesrequestkinduid , returns quickly, uid (and current date, placeholder). there, still need subject, date , sender. now i'm still trying information, while avoiding downloading message attachments. calling fetchparsedmessageoperationwithfolder: or fetchmessageoperationwithfolder: both download message attachments, , slow return. because fetchmessageoperationwithfolder: completes nsdata object, checking size of given object reveals size of regular message, plus its' attachment. what can information need, without downloading attac...

IOS/Swift: Open PDF from a local path into a Web View -

i used below code open dummy pdf, testing purpose, , actual project have load pdf based on table cell clicked give exact path of pdf @ local path. self.termspath = nsbundle.mainbundle().pathforresource("demoform", oftype: "pdf")! let url = nsurl(fileurlwithpath: termspath!) let pdfrequest = nsurlrequest(url: url!) pdfwebview.loadrequest(pdfrequest) pdfwebview.scalespagetofit = true now have thisvariable docpath passed prepareforsegue when table cell clicked, tried use variable in place of demoform gives below error thread 1: exc_bad_instruction (code=exc_1386_invop, subcode=0x0 where i'm going wrong here? can me.thanks edit: way docpath refers ".../.../.../.../referral.pdf"

python - IOError [Errno 13] when using numpy.loadtext? -

i have function polls folder new files, loads them using numpy.loadtext when shows up. function called while loop runs 30 seconds. function works of time, files, seemingly @ random, error ioerror: [errno 13] permission denied: 'myfilename1.txt'. here content of function: before = dict([(f, none) f in os.listdir(mydir)]) while 1: after = dict([(f, none) f in os.listdir(mydir)]) added = [f f in after if f not in before] # new file if added: raw = numpy.loadtxt(mydir + added[0]) return raw any idea on why happening? polls , reads text files incoming, spits error , can't find systematic reason why. update: has using full path loadtxt. when change working directory directory files are, no longer permissions error. have tried opening file read only, may conflict if file accessed application (or still being created). # new file if added: open(mydir + added[0], 'r') f: raw = numpy.loadtxt(f) you try form...

JavaScript - Popups not working -

i tried using alert() , confirm() in javascript. <!doctype html> <html> <head> <title> website </title> </head> <body> <br/> <br/> <br/> <br/> <h2 align=center>my website</h2> <p align=center> <button onclick=“myfunction()”>click enter</button> </p> <script type=text/javascript> function myfunction() { alert(“u sure?”); } </script> </body> </html> before point out, no, quotation marks glitch out on website. tried similar on computer , worked. computer? the problem double quotes. “ should " : function myfunction() { alert("u sure?"); } <p align=center> <button onclick="myfunction()">click enter</button> </p>

javascript - Display progress bar percentage using jquery -

i trying display percentage of progress .so, i've given span class percentage display there , id of progress bar "progressbar". js code is, $("#progressbar").progressbar({ value: 50 }); $(document).ready(function() { $("#progressbar").progressbar({ value: 0 }); var progress = setinterval(function() { var currentval = $("#progressbar").progressbar("value"); var nextval = currentval + 1; $('#percentage').text(currentval); if (nextval > 90) { clearinterval(progress); } else { $("#progressbar").progressbar({ value: nextval }); } }, 100); }); now how can display percentage @ #percentage thanks in advance. isn't var currentval = $("#progressbar").progressbar("option", "value"); supposed var currentval = $("#progressbar").progressbar("value"); these should checkpoints i...

asp.net mvc 5 - SyntaxError: An invalid or illegal string was specified (jquery in mvc 5) -

i have mvc 5 project code works good. have modified project , not work. not call action here jquery code : <script type="text/javascript"> $(function () { $(document).ready(function () { var url='@url.action("loadroles", "account")'; $.post(url, function (data) { //do whatever u waht response "data" }); $.ajax({ type: 'post', cache: false, contenttype: 'application/json; charset=utf-8', url: '@url.action("loadroles", "account")', datatype: 'text/javascript', data:'', success: function (roles) { // not process section var items = '<option value="' + "0" + '">' + "type" + '</option>'; $.each(roles, function (i, role) { ...

amazon web services - Chef reciepe update route53 records -

i have recipe running in chef server gets ec2 node hostname , public dns , creates cname point hostname.mydomain.com easier access. i'm moving vpc , there no more public dns sense in private network , uses private ip address in class a. need have chef create record instead of cname pointing private ip address. here recipe: aws=hash.new aws['aws_access_key_id'] = node[:base][:aws [:access_key_id] aws['aws_secret_access_key'] = node[:base][:aws][:secret_access_key] if node[:base][:aws][:route53][:update_cname_records] == true cnames = [] cnames << "#{node.name}" unless node[:base][:aws][:route53][:additional_cnames].nil? node[:base][:aws][:route53][:additional_cnames].each |n| cnames << n end end cnames.each |cname| cname_fqdn = "#{cname}.#{node[:base][:aws][:route53][:management_zone_name]}" log ("updating route53 cname record #{cname_fqdn}") { level :warn } aws_route53_record "create route53 cname record #...

unix - *NIX CLI: Filter, Query XML Attribute and Display -

given file: /// @file test.xml <xml-fragment> <string name="foo" value="bar"/> </xml-fragment> the path xml-fragment/string , attribute&value name="foo" filter on, , attribute value query on, how should "bar" ? using xmlstarlet , have this: xmlstarlet sel -t -m '/xml-fragment/string[attribute::name="foo"]' \ -v 'attribute::bar' test.xml which appears work, i'm wondering if there better way? i don't require using xmlstarlet ; tried xmllint , xsltproc , , xpath , couldn't work. i'm not sure if "better", use -v entire xpath. use @ abbreviated syntax . example (tested in windows; quotes might need changed) xmlstarlet sel -t -v "/xml-fragment/string[@name='foo']/@value" test.xml any of other tools listed should work well. if you're getting value, xsltproc might overkill. long you're not using re...

autolayout - UILabel with linebreak and auto layout -

so i've been having issue while. have uilabel has constraint auto layout. label text long parts of text appears off screen. i've tried setting number of line both within storyboard settings , thru code: label.numberoflines = 0; the code works charm until add constraint label. any ideas on how fix this? add code.. _lable.numberoflines=0; _lable.preferredmaxlayoutwidth = 300.0; //add width uilabel documentation

Getting the indexes of duplicate elements in arrays (Ruby) -

i have array in ruby has duplicate elements. e.g.: fruits = ["apples", "bananas", "apples", "grapes", "apples"] when following: fruits.index("apples") # returns 0 i first occurrence of "apples" is, in case, fruits[0] . there way can run similar above code , indexes of other occurrences of "apples" ? if can't run similar above code, how else can indexes of duplicate elements? taking page procedural languages, write: fruits.each_index.select { |i| fruits[i]=="apples" } #=> [0, 2, 4]

jquery - Dynamically load a modal containing iframe on click? -

i need modal containing iframe (which complete external page) populate bootstrap modal window, problem page large don't want load until modal event fired. possible jquery/bootstrap? yep set src attribute: $("#youriframe").attr("src", url); although if possible preload iframe (as mentioned in comments) before modal clicked open reduce time user has wait. if want clear iframe when modal closed set src attribute "about:blank".

sql - Google Bigquery: Remove rows where column value is distinct (count = 1) without referencing table -

given table, wish remove rows column value distinct. so if want column2 on matrix c1 c2 c3 = |1 2 4 | |1 2 5 | |1 1 6 | yields c1 c2 c3 = |1 2 4 | |1 2 5 | this can done by select * table c2 in (select c2 table group c2 having count(*) > 1) unfortunately, in middle of subquery, don't have data stored in table , don't want create view need filtering in 1 query. any ideas on how can still filter out distinct rows respect single column without referencing table in subquery? the solution should of form: select <something goes here> <the subquery outputs goes here> <anything want here legal bigquery - e.g. can't reference a> and there no table reference. bigquery supports window functions, might able this: select t.* (select t.*, count(*) on (partition col2) cnt table t ) t cnt >= 2; this still references table in subquery, reference table.

c - Programatically Determining the File System Block Size -

this code i'm using time how time takes read file varying amount of bytes read. for(int = 0; < trials; i++){ fd = open(argv[1], o_rdonly); //set file offset random position on file //but still multiple of current current test block size, //simulating jumps of given test block size //trying avoid prefetch lseek(fd, test_block * rand() % (fs / test_block), seek_set); //how time takes read `test_block` bytes clock_gettime(clock_monotonic, &ts_ini); ssize_t bytes_read = read(fd, buffer, test_block); clock_gettime(clock_monotonic, &ts_end); if(bytes_read > 0){ accum += (((double)(ts_end.tv_sec - ts_ini.tv_sec)) + (ts_end.tv_nsec - ts_ini.tv_nsec)/nano_to_sec) / trials; } //closing file after each trial release resources close(fd); } now, if run program ...

winforms - Saving files with name read from text box. C# -

i have created code saves work text file, wondering there way when click 'save' can read in text richtextbox1 and set default file name, still 'txt' default file extension. e.g. when click 'save' folder dialog comes , asks name file, if using word example, want box have text richtextbox1 in. thanks. private void savetoolstripmenuitem_click(object sender, eventargs e) { savefiledialog save = new savefiledialog(); save.initialdirectory = "c:\\to-do-list"; save.filter = "text files (*.txt)|*.txt"; save.defaultext = ".txt"; dialogresult result = save.showdialog(); if (result == dialogresult.ok) { using (streamwriter sw = new streamwriter(save.filename)) { sw.writeline(richtextbox1.text); sw.writeline(richtextbox2.text); sw.writeline(richtextbox3.text); sw.writeline(richtextbox4....

java - Background image for a jPanel not working -

i new making guis decided try the windows builder eclipse, , while great have doubts. have been searching cannot seen find way add background image "menu". example tried this: public menu() { setdefaultcloseoperation(jframe.exit_on_close); setbounds(50, 50, 300, 250); //dimensiones contentpane = new jpanel() { //imagen de fondo public void paintcomponent(graphics g) { image img = toolkit.getdefaulttoolkit().getimage( menu.class.getresource("/imgs/rotom.jpg")); g.drawimage(img, 0, 0, this.getwidth(), this.getheight(), this); } }; and adding following classes: import java.awt.graphics; import java.awt.image; import java.awt.toolkit; but no avail window remains dull grey color, far code standard 1 windowsbuilder cooks plus 4 buttons doubt they're of importance here. shouldn't code added override paintcomponent() method of jpanel , draw image in it? the class menu in package ...

C++ Dereferencing pointer to object -

i'm having trouble dereferencing pointer. priority_queue<node*, vector< node*>, comparator>* pqueue = null; pqueue = h->addtoqueue(m); while (!pqueue->empty()) { cout << (*pqueue)->top() << endl; pqueue->pop(); } addqueue(m) returns pointer priority queue, when try print i'm getting memory address values. any ideas why? thanks.. you have overload << operator node class like: ostream& operator<<(ostream& os, const node& nd) { os << nd.anyvalue; return os; } also have dereference pointer like cout << *pqueue->top()<< endl; look @ example here: https://msdn.microsoft.com/de-de/library/1z2f6c2k.aspx or here: http://www.tutorialspoint.com/cplusplus/input_output_operators_overloading.htm

java - How to process two files in Hadoop Mapreduce? -

i have process 2 related files in hadoop environment using mapreduce. first file huge log files has been logging user's activity. , second file relatively small file contains details users. both .txt files. first file(log file) has format of: userid | logintime | logouttime | roomnum | machineid this file huge(couple of tb). the second file(user file small file 20mb) is: userid | userfname | userlname | dob | address i have find out frequency of users's usage of lab machines, frequent user , list names. i know how process 1 file if in there. since user details in other folder becoming hard me process it. new mapreduce seeking , advices here. problems similar joining 2 table in rdbms foreign key me. you can use distributed cache save small file. distributed cache stored in memory , distributed across clusters running map reduce tasks. add file distributed cache in following way. configuration conf = new configuration(); distributedcache.addcachefile...

mysql - Database Tables for User management -

i advice best practices in user role management. i create application user register , have different roles. obvious thing is, create users table , save user data there this: users id useruuid username role but think separated tables different groups. like: admins id useruuid (-> foreign key users table) accessright1 accessright2 subscribers id useruuid (-> foreign key users table) etc does make sense? should users, regardless of role in 1 database? , specific information different roles? thanks! if roles going change work. but, should plan change, , more flexible option allowing add roles without needing change database schema this: users: uid user info... roles: rid name userroles: uid (fk user table) rid (fk roles table) in code check userroles table determine if user has given role , therefore should allowed whatever. additionally, if want mix , match permissions actions across multiple roles (i.e. both ...

validation - ASP.Net MVC 5 -Attempt by security transparent method 'WebMatrix.WebData.SimpleMembershipProvider.ValidateUser to access security method failed -

Image
i using simplemembership in asp.net web api project. when try validate user using below code, error(error 1) if (!membership.validateuser(username, password)) { throw new validationexception("username or pwassword incorrect."); } error 1: attempt security transparent method 'webmatrix.webdata.simplemembershipprovider. validateuser(system.string, system.string)' access security critical method 'system.web.webpages.stringextensions.isempty(system.string)' failed. earlier got similar error(error 2) resolved installing these packages: install-package microsoft.aspnet.webhelpers install-package microsoft.aspnet.webpages.data error 2: attempt security transparent method 'webmatrix.webdata.preapplicationstartcode.onconnectionopened( system.object, webmatrix.data.connectioneventargs)' access security critical method 'system.web.webpages. httpcontextextensions.registerfordispose(system.web.h...

c# - loop returns despite break -

i running loop cycle through entries in database. every time loop runs compare user's answer value in database. table rows named answer2, answer3...etc concatenate string: ("answer" + (i)) , use string database.queryvalue(string) put value database variable. (in case variable caltansx) eventually loop returns null value. want loop terminate before runs again. try load queried value object , comparing dbnull.value try exit loop break; still comparing 2 strings. i.e. uans.tolower() == cans.tolower(). code returns error since cannot convert null value string. exit these loops once query loads null value (and before script can attempt convert string). i have tried using break , return end string, still same problem. if (!request.querystring["uanswer"].isempty()) { uans = request.querystring["uanswer"]; if (uans.tolower() == cans.tolower()) { anbool = true; } else //should cycle through ...

java - difference between 2 types of downcasting -

public class { main() { // different implications of these 2 down casts superclass trefvar = new subclass(); // down cast example 1 subclass avar = (subclass) trefvar; // down cast example 2 ((subclass) trefvar).somemethodinsubclass(); } } implications, wise, differences between example 1 cast, , example 2 cast? there virtually no difference. first example creates new local variable, , second example doesn't. that's it. to peek under hood bit , verify that, let's consider simple class, 2 methods you're doing in example: public class downcasts { public int stringlength1(object o) { string s = (string) o; return s.length(); } public int stringlength2(object o) { return ((string) o).length(); } } the bytecode these methods (which can see javap -c downcasts ) are: public int stringlength1(java.lang.object); code: 0: aload_1 1: checkcast #2 ...

.net - How are denormalized floats handled in C#? -

just read fascinating article 20x-200x slowdowns can on intel cpus denormalized floats (floating point numbers close 0). there option sse round these off 0, restoring performance when such floating point values encountered. how c# apps handle this? there option enable/disable _mm_flush_zero ? there no such option. the fpu control word in c# app initialized clr @ startup. changing not option provided framework. if try change pinvoking _control87_2() not going last long; exception cause control word reset again exception handling implementation inside clr. written deal aspect of fpu control word, allows unmasking floating point exceptions. detrimental other managed code not expect global state changed that. having no direct control on hardware implied restriction when run code in virtual machine. not @ easy in native code either, libraries tend misbehave when expect fpu have default initialization. particularly problem exception masking flags, dlls created bo...

io - C++ file input with mixed delimiters and data types -

i trying input data text file: line format follows... string|string|int double example: bob|oranges|10 .89 i can line in string using getline(infile, line) i don't understand how break line distinct variables string variable. thanks for start write old fashioned c code using strchr. or use string.find / find_first_of if using std::string http://www.cplusplus.com/reference/string/string/find_first_of/

xml - VBA DOM Variable Attribute in XPath -

i have program searches , gathers (via array) specific author , 'booktype' , 'booktitle' trying learn how use author's name - i've stored in array - variable in xpath 'store location'. the biggest obstacle location uses author's last name. can split string , all, how feed xpath? below you'll see <publishedauthor id='lastname'> opposed full name, cannot put athr in xpath time. keep getting object error. <?xml version="1.0"?> <catalog> <book id="adventure"> <author>gambardella, matthew</author> <title>xml developer's guide</title> <price>44.95</price> <misc> <publisher id="5691"> <publisherlocation>los angeles</publisherlocation> </publisher> <publishedauthor id="gambardella"> <storelocation>store b</storelocation> ...

Using PDO PHP and MySql -

alright peeps, first question on stack overflow , should easy 1 @ since cannot figure out right words trying making incredibly difficult me search it. i using pdo db connection. anyways, trying query database , set $fname string, know how set array while ($fname = $name->fetch()){} how can set $fname string instead? the snippet of code , link can read more appreciated. you mean this? while ($fname = $name->fetch()) { echo "{$fname['fieldname']}"; }

In my C# XAML Windows 8.1 app, how can I iterate over my ListView? -

i'm new windows 8.1 development, xaml, , c#, if question rudimentary, please forgive me. i've got <page> in app contains <listview> , so: <listview itemssource="{binding mode=twoway}" x:name="listview_statistical"> <listview.itemtemplate> <datatemplate> <stackpanel orientation="horizontal"> <textblock style="{staticresource subheadertextblockstyle}" width="100" margin="10,20"> <run text="x/y " /> <!--<run text="{binding source={staticresource thispage}, path=i}" />--> </textblock> <textbox horizontalalignment="left" text="{binding xval}" placeholdertext="x" inputscope="number" fontsize="28" width="100" margin="0,10,10,10" /> ...

Can't move my cursor when visual studio starts -

Image
all i installed vs 2013 , started using it. however, after lauched it, mouse cursor couldn't move. i'm sure there no problem mouse... could plz give me help? cheers! open task manager , close wisptis.exe :

python - Return letter based on percent chance -

i trying figure out how use percent chance in order output letter. how program works user enter whole numeric value between 1 , 100, program converts decimal value. user enters amount of iterations loop occur in next step. the next step involves outputting either x or y based on probability entered in first step, if user entered 70, there 70% (0.7 probability) chance of x being outputted during z amount of iterations. right trying figure out how program use user entered probability in order determine how many x's should output. thanks in advance, not sure if made sense (newbie programmer here..) run following code. output x 70% chance: >>> import random >>> 'yx'[random.randrange(100)<70] 'x' how works: import random this imports module need. random.randrange(100) this generates random integer 0 99. random.randrange(100)<70 this generates false (0) or true (1) 'yx'[random.randrange(100)<70] ...

Python imitate class's constructor only using function dynamically -

this little bit weird. want dynamic initialize part of function's parameters before call it. don't want use class reason. let's have function: def inner(a,b,c): "a,b,c something" return result before formally call it, i'd initialize somewhere: partinitalabc=inner(,b,c) then i'll use as: result=partinitialabc(a) please notice want dynamically. when initial class using constructor, decorator may not appropriate @ time... any 1 have idea? it sounds you're looking functools.partial : return new partial object when called behave func called positional arguments args , keyword arguments keywords . if pass arguments partial positional arguments, they'll appear @ beginning of argument list, isn't want. keyword arguments give more control on parameters passed: partinitialabc = functools.partial(inner, b=b_value, c=c_value);

django - Python - How to access variable data that was set by methods -

i taking django course on udemy , have decided add on i've learned changing layout of form if statement. basically, want see if booleanfield variable for_you set true (or if check box in gui checked), having trouble figuring out how access if boolean field set false. can point me in right direction? class signup(models.model): for_you = models.booleanfield(default=true, verbose_name="is purchase you? if so, check box.") if for_you: i think need tell bit more context you're trying access for_you . i'm not sure if helpful you, here's how access for_you depending on in relation signup class. inside method of signup: class signup(models.model): def my_method(self): if self.for_you: # stuff outside signup: my_sign_up = signup() if my_sign_up.for_you: # stuff

Exception handling in Protocol Buffers C++ -

i don't find in protocol buffers documentation exception handling in c++. in javadoc has defined ones invalidprotocolbufferexception, not in c++. sometimes ran program , crashes when finds missing fields in thinks valid message, stops , throws errors this: [libprotobuf fatal google/protobuf/message_lite.cc:273] check failed: isinitialized(): can't serialize message of type "xxx" because missing required fields: yy, zz unknown file: failure c++ exception description "check failed: isinitialized(): can't serialize message of type "xxx" because missing required fields: yy, zz" thrown in test body. the source code of message_lite.cc wrapped around "google_dcheck" or "initializationerrormessage"... my application not allow exceptions halt program (not sure term in c++ no uncheckedexceptions), need way catch these, log errors, , return gracefully, in case messages got severely corrupted. there anyway doing that? w...

Rails 4: Eager load entire table -

in rails app, have categories table has around 10 rows. there association whereby post belongs category. rather eager loading categories every single post query, since it's small table there way eager load whole table once when application starts , thereby avoid additional queries when calling post.category association method? i think can achieve similar effect using global variable nice able use standard 'category' association.

python - Opening a file and selecting specific column in file -

hello new python , need help i have set of data below large values column 1 , xx.x column 2 19600110 28.6 19600111 28.9 19600112 29.2 19600113 28.6 19600114 28.6 19600115 28.4 19600116 28.6 19600117 28.6 stored station.txt i trying python present first column of data (19600115 etc) labelled dates.i opened file , using loop try open 1st column. not sure going wrong appreciated def load_dates(stations): """loads station dates , excludes station temperature data""" f = open(stations[0] + '.txt', 'r') #create loop , open first column of data dates #close file , return body of dates dates = [] line in f: dates.append(lines(7)) f.close() return dates dates = [] line in f: dataitem = line.split() #split while space default, list date = dataitem[0] #index 0 first element of dataitem list dates.append(date) f.close() in summary, need split line string first, choose date

android - How to export AAR including its dependencies? -

i have android studio library project uses library.aar , library.jar . when export mylib.aar , use new aar different app/project, cannot find classes defined in library.aar , library.jar . my build.gradle looks this: apply plugin: 'com.android.library' android { compilesdkversion 21 buildtoolsversion "21.1.2" defaultconfig { minsdkversion 15 targetsdkversion 21 versioncode 1 versionname "1.0" } } dependencies { compile filetree(include: ['*.jar'], dir: 'libs') compile project(':library_dot_aar') compile project(':library_dot_jar') } i imported aar , jar files in android studio using new -> module -> import .jar or .aar package , add them dependencies in project structure -> module settings -> dependencies -> add module dependencies . when unzipped mylib.aar 25kb (considering library.aar on 300kb, assume mylib.aar 's size in same r...

mp3 - How to use mpg123.exe in a Python script -

i trying use mpg123 in python script convert .mp3 file .wav file. how download , use mpg123.exe ? using mac. here snippet of code see how it's being used: mpg123_command = '..\\mpg123-1.12.3-x86-64\\mpg123.exe -w "%s" -r 10000 -m "%s"' out_file = 'temp.wav' cmd = mpg123_command % (out_file, mp3_file) temp = subprocess.call(cmd) you can try mac osx port: http://sourceforge.net/projects/mosx-mpg123/

javascript - How to return the response from an asynchronous call? -

i have function foo makes ajax request. how can return response foo ? i tried return value success callback assigning response local variable inside function , return one, none of ways return response. function foo() { var result; $.ajax({ url: '...', success: function(response) { result = response; // return response; // <- tried 1 } }); return result; } var result = foo(); // ends being `undefined`. -> more general explanation of async behavior different examples, please see why variable unaltered after modify inside of function? - asynchronous code reference -> if understand problem, skip possible solutions below. the problem the a in ajax stands asynchronous . means sending request (or rather receiving response) taken out of normal execution flow. in example, $.ajax returns , next statement, return result; , executed before function passed success callback ...

ios - UITableView updates for correct number of managedObjects, but won't display values -

i have tableviewcontroller displays "add" (static) cell @ top , want list attributes of objects (dynamic cells) pulled managedobjectcontext . found this post helpful in getting "add" cell working, i've saved objects to managedobjectcontext , i've discovered doesn't display attributes of objects in managedobjectcontext . to "see" what's going on, made "dynamic" cells orange. when add categories managedobjectcontext , # of orange cells updates properly, can't attribute of managedobject (an nsstring ) display in cell. i threw breakpoint in after fetchrequest completed see if there locationcategories (my nsmanagedobject ) in array--there are. categorytvc.h @property (nonatomic, strong) nsmanagedobjectcontext *managedobjectcontext; @property (nonatomic, strong) locationcategory *category; categorytvc.m #define number_of_static_cells 1 // can updated // sets array dump locationcategories @property (...

sql - full outer join matching on multiple criteria -

two tables trying join: tablea : table contains of leads won bid , source , date. bid amount = tablea.price, source = tablea.lead_source_id, date = tablea.time tableb : table contains of leads lost bid , source , date. bid amount = tableb.cost, source = tableb.lead_source_id, date = tableb.bid_at i able return number of bids won , lost bid , source , date. times there records in 1 table or other (we won bids or lost bids), appears outer join needed. ideal output grouped lead_source_id, bid amount, , time such: lead source id, date, bid amount, won, lost 1, 1/1/2015, $20, 5, 0 1, 1/1/2015, $25, 0, 9 5, 1/1/2015, $30, 1, 1 10, 1/2/2015, $50, 0, 1 10, 1/2/2015, $55, 1, 0 try following query. ;with tmp ( select lead_source_id, [time] [date], price, count(*) won, 0 lost tablea group lead_source_id, [time], price union select lead_source_id, bid_at [date], cost price, 0 won, count(*) lost tableb group lead_source_id, bid_at, cost) select lead_source_i...

java - Which part of the equals() general contract does my equals() not satisfy -

i'm new java , trying head around understanding @override of equals() , hashcode() methods. know equals method correct needs be: reflexive: a.equals(a) symmetric: a.equals(b) then b.equals(a) transitive: a.equals(b) && b.equals(c) then a.equals(c) not null: ! a.equals(null) i struggling pinpoint of above properties , not satisfying when writing overide of equals method. i aware eclipse can generate these me, haven't yet gotten concept fully, writing out helps me learn. i have written out think correct way it, when check eclipse generated version seem 'missing' aspects. example: public class people { private name first; //invariants --> !null, !=last private name last; // !null, !=first private int age; // !null, ! <=0 ... } what wrote: public boolean equals(object obj){ if (obj == null){ return false; } if (!(obj instanceof people)){ return false; } people othe...

xcode - iOS Swift Error - Objective C method ... provided by method -

Image
what error mean? code compiled fine previous week. noticed when change func parser func something , there no compilation errors, method, obviously, not work @ runtime , shows no output. any ideas? **error :** objective-c method 'parser:didstartelement:namespaceuri:qualifiedname:attributes:' provided method 'parser(_:didstartelement:namespaceuri:qualifiedname:attributes:)' conflicts optional requirement method 'parser(_:didstartelement:namespaceuri:qualifiedname:attributes:)' in protocol 'nsxmlparserdelegate' if @ docs or headers, see how declare method: func parser(parser: nsxmlparser, didstartelement elementname: string, namespaceuri namespaceuri: string?, qualifiedname qualifiedname: string?, attributes attributedict: [nsobject : anyobject]) as can see, types different types using. need fix yours match these exactly .