Posts

Showing posts from February, 2015

user interface - java- why is my "deposit" method not working for my ATM with gui? -

i'm making atm in user must first enter pin (1234), , once pin entered correctly, user can either withdraw 50, 100, or 200 dollars or make deposit under $1000. withdraw methods working, when run program , try make deposit, nothing happens after enter amount , try hit "enter" button. seems if enter button not working. here code used deposit method: if (event.getsource() == deposit) { instructionscreen.settext("enter amount deposit, click enter."); if (event.getsource() == enter) { savescreen = displayinput.gettext(); double add = double.parsedouble(savescreen); if (add <= 1000) { balance += add; instructionscreen.settext("your new balance $" + balance + "."); } else { instructionscreen.settext("the maximum amount can deposit $1000. please enter new amount."); displayinput.settext(""); if (event.getsource() == enter) {

python - Replacing minimum element in a numpy array subject to a condition -

i need replace element of numpy array subject minimum of numpy array verifying 1 condition. see following minimal example: arr = np.array([0, 1, 2, 3, 4]) label = np.array([0, 0, 1, 1, 2]) cond = (label == 1) label[cond][np.argmin(arr[cond])] = 3 i expecting label now array([0, 0, 3, 1, 2]) instead getting array([0, 0, 1, 1, 2]) this consequence of known fact numpy arrays not updated double slicing . anyway, can't figure out how rewrite above code in simple way. hint? you triggering numpy's advanced indexing chaining of indexing , assigning doesn't go through. solve this, 1 way store indices corresponding mask , use indexing. here's implementation - idx = np.where(cond)[0] label[idx[arr[idx].argmin()]] = 3 sample run - in [51]: arr = np.array([5, 4, 5, 8, 9]) ...: label = np.array([0, 0, 1, 1, 2]) ...: cond = (label == 1) ...: in [52]: idx = np.where(cond)[0] ...: label[idx[arr[idx].argmin()]] = 3 ...: in

Using Javascript to Alternate background color of HTML element -

so have practise test asks me change background color , text color of paragraph section id "fourth" black background , white text vise versa , reverse every 30 seconds preferably using if/else statements. reason if statement (and else statement) not work. the code have far this: html <html> <head> <link href="teststyle.css" rel="stylesheet" type="text/css"/> <script src="flash.js" type="text/javascript"></script> </head> <body> <div id="first"> mares eat oats </div> <h1 id="second"> , eat oats </h1> <p id="third"> , little lambs eat ivy </p> <p id="fourth"> mirthipan karunakaran </p> </body> </html> css #first { text-align: center; } #second { color: green; text-align: left; } #third { color: orange; text-align: right; } #fourth { color: white; background-

How can I implement Pencil Shades like hb, 2b, 4b, etc. to draw anything in Canvas of my Android Application? -

i need implement pencil shades 9b 9h list showing shades on pencil button click() , after clicking list item, pencil should change new shade. need eraser implementation on erase button click erase path drawn pencil. this code drawing fixed size pen on canvas without button click. , clearcanvas() method called on button click clears whole canvas. any appreciated. public class mainactivity extends appcompatactivity { private canvasview customcanvas; private toolbar toolbar; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); customcanvas = (canvasview) findviewbyid(r.id.custom_canvas); toolbar = (toolbar) findviewbyid(r.id.actionbar); setsupportactionbar(toolbar); assert getsupportactionbar()!=null; getsupportactionbar().sethomebuttonenabled(true); getsupportactionbar().setdisplayhomeasupenabled(true); }

java - for each loop with a second boolean parameter -

this question has answer here: java foreach condition 6 answers is there here know how this: boolean condition = true; for(int i=0; i<list.size() && condition; i++){ if (***) condition = false; } with each loop, that: boolean condition = true; for(string s : list && condition){ if (***) condition = false; } i know second loop not work, have same behaviour without using killing mortal ugly instruction "break". use break statement: for(string s: list) { if (....) { break; } } btw can kind of loop , imho preferable because more readable.

html parsing - Ignoring </span> tag and placing all closing tags before span opening tag in php -

my code in php is: while(preg_match('%(<span style="color: green;">)(?:\s+)?(</.*?>)%i', $result2)==1){ $result2 = preg_replace('%(<span style="color: green;">)(?:\s+)?(</.*?>)%i', '$2 $1', $result2); } right have input such as: <span style="color: green;"></p></i> and code whenever tag closing after span green tag, placed before span. output above input be: </p></i><span style="color: green;"> i want if there span tag closing after span green tag, should ignored , other closing tags should placed first.. example input: <span style="color: green;"></p></span></i> output: </p></i><span style="color: green;"></span> can me out in making change? in general regex implementations can use look-ahead mechanism, (?!</span>)(</.*?>) instead of (<

Calculating overlap (and distance measures) for categorical variables in R -

i trying calculate distance between rows (data points) on basis of categorical variables in columns. simplest method have seen calculate overlap. in other words in proportion of variables x , y take identical values. imagine have dataset follows; id = 1:5 dummy <- data.frame(country = c("uk", "uk", "usa", "usa", "usa"), category = c("private", "public", "private", "private", "public"), level = c("high", "low", "low", "low", "high")) and want calculate proportional overlap (as above) between pairs of rows. i define function this; calcoverlap <- function(id, df) { n <- length(id) results <- matrix(na, n, n) for(i in 1:n) { for(j in 1:n) { if(i > j) { results[i, j] <- length(which(df[i,] == df[j,])) / nc

python - Neat way of popping key, value PAIR from dictionary? -

pop great little function that, when used on dictionaries (given known key) removes item key dictionary , returns corresponding value. if want key well? obviously, in simple cases this: pair = (key, some_dict.pop(key)) but if, say, wanted pop key-value pair lowest value, following above idea have this... pair = (min(some_dict, key=some.get), some_dict.pop(min(some_dict, key=some_dict.get))) ... hideous have operation twice (obviously store output min in variable, i'm still not happy that). question is: there elegant way this? missing obvious trick here? you can define dictionary object using python abc s provides infrastructure defining abstract base classes . , overload pop attribute of python dictionary objects based on need: from collections import mapping class mydict(mapping): def __init__(self, *args, **kwargs): self.update(dict(*args, **kwargs)) def __setitem__(self, key, item): self.__dict__[key] = item def __getit

java - JMeter Not in GZIP format error -

im trying make test genexus web application (generates java) jmeter im getting error: java.io.ioexception: not in gzip format @ java.util.zip.gzipinputstream.readheader(unknown source) @ java.util.zip.gzipinputstream. (unknown source) @ java.util.zip.gzipinputstream. (unknown source) @ org.apache.jmeter.protocol.http.sampler.httpjavaimpl.readresponse(httpjavaimpl.java:269) @ org.apache.jmeter.protocol.http.sampler.httpjavaimpl.sample(httpjavaimpl.java:516) @ org.apache.jmeter.protocol.http.sampler.httpsamplerproxy.sample(httpsamplerproxy.java:74) @ org.apache.jmeter.protocol.http.sampler.httpsamplerbase.sample(httpsamplerbase.java:1146) @ org.apache.jmeter.protocol.http.sampler.httpsamplerbase.sample(httpsamplerbase.java:1135) @ org.apache.jmeter.threads.jmeterthread.process_sampler(jmeterthread.java:434) @ org.apache.jmeter.threads.jmeterthread.run(jmeterthread.java:261) @ java.lang.thread.run(unknown source) aparently known error acording genexus wiki: http://wiki.genexus.com

Grouping Content-Types Menu Bolt CMS -

i got project using bolt cms, relatively new cms related project, please spare me if question irrelevant or seems stupid. so, project has many data need inputed backoffice, this group menu - submenu 1 * create * read * update * delete - submenu 2 * create * read * update * delete group menu b - submenu 1 ... using bolt cms, these submenus can defined contenttypes , task relatively easy editing contenttypes.yml . @ bolt's backoffice these contenttypes appear separate menu, this content type 1 * view * add content type 2 * view * add ... so, question, possible group content types other content types in bolt cms? any ideas? in advance so, question, possible group content types other content types in bolt cms? short answer no. slightly longer answer, hierarchical contenttypes being worked on, have been prototyped, , land in 2.4.

javascript - Download file in Meteor Cordova application -

i made meteor "desktop" application , i'm migrating "android" one. no big deal, if i'm new cordova, works except 1 thing : cannot download files. the application provides files download pdf reports, csv archives or json raw files (i use nilsdannemann:pdfmake package or pfafman:filesaver ). i tried run application on chrome (on android device) , works fine. when use cordova meteor run android-device none of these download functions work anymore. i search how create file download cordova , found topic saying it's not supported. if point me in right direction, i'd appreciate it.

Start / stop Websphere Application Server (WAS) profile - Unix/Linux -

how can start and/or stop websphere application server profile on unix/linux using command line? starting profile was_install_dir/bin/startserver.sh server1 –profilename profile or profile_dir/bin/startserver.sh server1 stopping profile was_install_dir/bin/stopserver.sh server1 –profilename profile_name or profile_dir/bin/stopserver.sh server1

javascript - Click Actions works on second click -

this code works on first click. when repeated works on second click on same element. html <div id="monthly-table"> <a href="#" class="monthly active">monthly</a> <a href="#" onclick="subscriptiontable(this)" class="yearly">yearly</a> <h1>monthly</h1></div><div id="yearly-table" style="display:none"> <a href="#" onclick="subscriptiontable(this)" class="monthly">monthly</a> <a href="#" class="yearly active">yearly</a> <h1>yearly</h1></div> script function subscriptiontable(el) { $(el).on('click', function() { if ($('#yearly-table').is(':hidden')) { $('#yearly-table').show(); $('#monthly-table').hide(); } else { $('#yearly-table').hide(); $('#monthly-

php - I want only all array from phalcon translate object properties? -

when var_dump($t) output this $t = object(phalcon\translate\adapter\nativearray)[121] protected '_translate' => array (size=14) 'attendancelist' => string 'ယေန႕စာရင္း' (length=30) 'monthlylist' => string 'လစဥ္တက္ေရာက္စာရင္း' (length=54) 'bye' => string 'sayounara' (length=9) 'hi-name' => string 'bonjour %name%' (length=14) 'song' => string 'la chanson est %song%' (length=21) 'todaylist' => string '' (length=0) 'date' => string 'ရက္စြဲ' (length=18) 'username' => string 'နာမည္' (length=15) 'checkin' => string '' (length=0) 'late' => string 'ေနာက္က်ခ်ိန္' (length=36) 'checkout' => string '' (length=0) 'workingtime' => string 'အလုပ္ခ်ိန္' (length=30) 'overtime' => string 'အခ်ိန္ပို' (length=27) 'l

msp430 - Does MSP430G2553 takes care of interrupt re-entrancy or should I allocate stacks for each tasks in ISR? -

i @ present initializing stacks tasks need serviced upon receiving interrupt. example there 2 tasks gets called different periodicity, both tasks using same isr. task higher sample rate should interrupt lower sample rate task , enter same isr. @ present allocating stacks tasks , upon completion free stack memory. know if msp430 takes care of re-entrancy on it's own, not need create , delete stack, save , restore context. there's 1 (the current) hardware stack. so, in theory, long doesn't overflow, don't need create dedicated stacks , can handle interrupts on same stack.

python - Looking for a more Pythonic way to grab text from individual tweets -

i'm trying grab text of first 50 tweets word/hashtag taken input user. tried writing for-loops this, example: for in range(1,50): self.status_texts[i] = (statuses[i]) in range(1,50): self.tweets = self.status_texts[i]['text'] but comes keyerror . i'm looking way combine self.status_texts = (statuses[0]) action , action retrieves text, in return. is possible? can of give me tips on started? twitter_api = twitter.twitter(auth=auth) q = input('what search for?') q = str(q) count = 50 search_results = twitter_api.search.tweets(q=q, count=count) statuses = search_results['statuses'] f = open('twitter.txt', 'w') class tweeter(): def puretweets(self): self.status_texts = (statuses[0]) self.status_texts1 = (statuses[1]) self.status_texts2 = (statuses[2]) return self.status_texts['text'], self.status_texts1['text'], self.status_texts2['text'] as far

c++ - Are inline virtual functions really a non-sense? -

i got question when received code review comment saying virtual functions need not inline. i thought inline virtual functions come in handy in scenarios functions called on objects directly. counter-argument came mind -- why 1 want define virtual , use objects call methods? is best not use inline virtual functions, since they're never expanded anyway? code snippet used analysis: class temp { public: virtual ~temp() { } virtual void myvirtualfunction() const { cout<<"temp::myvirtualfunction"<<endl; } }; class tempderived : public temp { public: void myvirtualfunction() const { cout<<"tempderived::myvirtualfunction"<<endl; } }; int main(void) { tempderived aderivedobj; //compiler thinks it's safe expand virtual functions aderivedobj.myvirtualfunction(); //type of object temp points known; //does compiler still expand virtual functions? //i do

javascript - Reset/Render again element in polymer -

their option in polymer reset element/ custom element original state. render element again? i want inner variables values delete , element same load page. thanks i see ways: first 1 write 'reset' method resets vars bound ui gets initial state. the second 1 remove element polymer.dom(parent).removechild , create new 1 of same type document.createelement , put @ old element's place polymer.dom(parent).appendchild/insertbefore. i'd choose first 1 - seems more testable , confined lement.

python - Finding events that happened on the same day in Django -

i have person model , people can have jobs: class person(models.model): name = textfield() birth_date = datefield() class job(models.model): name = textfield() start_date = datefield() person = foreignkey('person') i want find people started work on birthday. now, if wanted find people started work on exact birthday, i'd use: from django.db.models import f person.objects.filter(birth_date=f('job__start_date')) but returns no one, because no 1 assigned job born (hopefully). i can find started work on april 1st: person.objects.filter(birth_date__month=4, birth_date__day=1) but, if try combine find people started work during birthday month: from django.db.models import f person.objects.filter(birth_date__month=f('job__start_date__month')) i get: fielderror @ /data/explorer/ cannot resolve keyword u'month' field. join on 'start_date' not permitted how can find people started work on birthday?

java - AppEngine Scheduled Task syntax for a task to run after X years -

Image
i have task needs run every 4 years in application. how can configure in cron.xml. know <schedule>1 of jan</schedule> run yearly there syntax running after x years <schedule>every 4 years 1 of jan</schedule> ? -srikanth the documented schedule format doesn't seem have support desire. you convert such long intervals in hours , use format instead (might tricky exact dates/times in cases - leap years, etc): every n hours i tried number of hours equivalent on 4 years, development server doesn't seem unhappy: another possible approach (which allows precise date/time specs) invoke task yearly mentioned, keep track inside app of last execution date or number of invocations , execute actual task's job in 1 out of 4 invocations , exiting without doing in other 3 invocations.

javascript - select2.js - How to align two items inside option element -

i want align 2 items inside <option> element using select2.js plugin. for example, here: <select id="myexample" class="pull-left"> <option value="1" class="pull-left"><span class="pull-left">item </span><span class="pull-right">company a</span></option> </select> i want item aligned on left , company aligned on right. how can achieve that? tried using css doesn't seem working. jsfiddle use delimiter string, on example used " ~ " , split after select2 escaped markup : $("select").select2({ escapemarkup : function(text){ text = text.split("~"); return '<span class="pull-left">'+text[0]+'</span><span class="pull-right">'+text[1]+'</span>'; } }); while on select, should use : <select id="myexample" class="pull-

c - Does the complement have any impact on Fletcher's checksum? -

the wikipedia article fletcher's checksum states: these examples assume two's complement arithmetic, fletcher's algorithm incorrect on one's complement machines. this question provides scan book says: addition performed modulo 255 (1's complement arithmetic) fletcher's checksum uses running sum, don't see need negative numbers, , aim identify differences, long same number system (one's complement, two's complement, neither) used on checking system matter? examples given on wikipedia page specify unsigned integer types too. i've tagged c examples given on wikipedia page in c perhaps has bearing in this. i'm not mathematician , barely competent programmer it's quite possible there blindingly obvious reason why complement have impact. any insight grateful received. the number system matters lot. although fletcher's checksum works using both two's complement arithmetic (integer computations modulo

Tomcat: java.lang.IllegalStateException: Unable to find match between the canonical context path and the URI -

my team ran across error other day while doing testing on our internal site, , haven't found documentation on it. full stack trace, naming information redacted, here: exception in logs: 26-oct-2015 12:19:09.894 severe [http-nio-8080-exec-12] org.apache.catalina.core.standardwrappervalve.invoke servlet.service() servlet [function] in context path [/warname] threw exception java.lang.illegalstateexception: unable find match between canonical context path [/warname] , uri presented user agent [ion=v5.201+avr+v241&] @ org.apache.catalina.connector.request.getcontextpath(request.java:1963) @ org.apache.catalina.connector.requestfacade.getcontextpath(requestfacade.java:783) @ org.apache.catalina.core.applicationdispatcher.wraprequest(applicationdispatcher.java:934) @ org.apache.catalina.core.applicationdispatcher.doforward(applicationdispatcher.java:364) @ org.apache.catalina.core.applicationdispatcher.forward(applicationdispatcher.java:318) @ package.path.to.serv

java - JPA: The column name DTYPE was not found in this ResultSet -

in spring application have entity called resource:: @entity public class resource { list<resource> list = em.createnativequery("select r.* ...", resource.class).getresultlist(); for 1 specific purpose, need few more fields added results. created subclass extendedresource: @entity public class arearesource extends resource { @column(name="extra_field") private integer field; list<extendedresource> list = em.createnativequery("select extra_field, r.* ...", extendedresource.class).getresultlist(); this works fine when query extendedresource, resource get: org.postgresql.util.psqlexception: column name dtype not found in resultset. is there way around this, without bothering discriminator column? guess mappedsuperclass solution, avoid making classes. thanks a trivial problem, no way around without coding :) other creating @mappedsuperclass (which, said, solution), or creating entity hierarchy (with dtype ),

firefox - Javascript try-catch error output truncated -

when attempting run following code: try{ document.getelementsbyclassname("aklsdjfaskldf")[0].outerhtml; }catch(err){ alert("function failed error dump <"+err.message+">"); } the error message displayed truncated: function failed error dump <document.getelementsbyclassname(...)[0] undefined> is there way error message displayed in full, i.e. display following message in firefox? chrome not display output, , therefore not issue current usage. function failed error dump <document.getelementsbyclassname("aklsdjfaskldf")[0] undefined> every browser handles error call stack differently, if on chrome wont see string. cannot invoke outerhtml function on undefined. better check value before invoking function on , show appropriate alert. or print error.stack if want hint location of code throwing error.

java - Hibernate Primary Foreign Key field -

Image
i have 2 simple tables in database. like: t1 t2 id number primary key id number primary key & foreign key t1 value varchar value varchar how hibernate entity t2 like? tried @embeddable class containing t1 mapped-class object doesn't work. thanks. upd: full use case when need such structure below: have business entities tables, containing data specific business users, , company table id , value fields too, , want create companytobentity table, containing data company can access object.(objects row of bus.entities). so think structure fits case. pic describing better: you can try unidirectional one-to-one association vi primary key association - t1 mapping @id @column(name="id") private integer id; t2 mapping @onetoone(cascade=cascadetype.all) @primarykeyjoincolumn private t1 t1; for more reference visit here , example based on hbm.xml

recursion - How would you generate a Sierpinski Triangle in C (recursively) -

Image
i'm wondering how generate sierpinski triangle of depth recursively in c. i wrote function generate triangle of height h made of * coordinates (x,y) of top point. void triangle(char display[100][100],int x, int y, int h) { (int row = y; row<=h-1+y; row++) { (int column = x; column<=2*(row+1-y)+x-2; column++) { display[row][column-(row+1-y)+1] = '*'; } } (int = 0 ; i<100 ; i++) { (int j = 0; j<100; j++) { if (display[i][j]=='\0') display[i][j]=' '; } } } using code can generate "manually" sierpinski triangle. i'd recursively, depth , height ( height divisible 2^(depth)). int main() { char display[100][100] = { {0} }; triangle(display, 20, 0, 5); triangle(display, 15, 5, 5); triangle(display, 25, 5, 5); triangle(display, 10, 10, 5); triangle(display, 30, 10, 5); triangle(display, 5, 15, 5); tr

omnet++ - send the reputation values of nodes to the neighbour nodes -

i want send reputation values of nodes neighbour nodes in omnet++ utilizing veins. have installed veins4a. have done tictoc , run veins successfully. can me on how send type of information in veins. should use message udp/tcp not supported in current version of veins. is possible send message using waveshortmessage.msg adding information (like extension in message)? the best way start might modify existing example, uses tracidemo11p application , waveshortmessage message exchanged between cars. feel free add new fields message class (just did in tic toc tutorial, in waveshortmessage.msg ) , implement new ways of how application reacts received messages (again, in tic toc tutorial, in tracidemo11p.cc ).

objective c - KeychainItemWrapper class getting error in ios 9 -

Image
i want save password , id in app. downloaded [keychainitemwrapper][1] https://developer.apple.com/library/ios/samplecode/generickeychain/introduction/intro.html and added keychainitemwrapper.h/m in project .when want use class getting issue. better use other wrapper library 1 apple fxkeychain or sskeychain because 1 apple not support arc, if u want use navigate project's build phase -> compile source -> change keychainitemwrapper.m compiler flag -fno-objc-arc a newer keychain lib 1 locksmith

android - IntDef through an intent -

any ideas in best way send intdef through intent? ps: if send int loose type check, main goal of having intdef your intdef not available @ runtime. way go encapsulate generation of intent in intent-receiving activity. public class myactivity extends activity { private static final string key_navigation_mode = "navigation_mode"; private @navigationmode int mnavigationmode; public static intent getstartintent(context context, @navigationmode string navigationmode) { intent intent = new intent(context, myactivity.class); intent.putextra(key_navigation_mode, navigationmode); return intent; } @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); //noinspection wrongconstant safe because saved in #getstartintent mnavigationmode = getintent().getintextra(key_navigation_mode, navigation_mode_your_default); } }

To list 12 months in a query Oracle SQL -

i need help, please. have query list pdas numbers , need sort in twelve months. query: select to_char(primeirodia_mes,'mm/yyyy') competencia, 'suporte' tipo, (select count(tipo) v_pdas_suporte_se to_char(primeirodia_mes,'mm/yyyy') = to_char(v_pdas_suporte_se.dt,'mm/yyyy') , tipo in ( 's','e') ) quantidade (select to_date( '01/' ||lpad(id,2,0) ||'/' ||to_char(sysdate,'yyyy') ,'dd/mm/yyyy') primeirodia_mes (select level id dual connect level <= 12 ) ) contador i need list , example, oct/2014 oct/2015. i assume looking this: with t (select add_months(trunc(sysdate, 'mm'), - level+1) primeirodia_mes dual connect level <= 13) select primeirodia_mes competencia, 'suporte' tipo, count(tipo) v_pdas_suporte_se right outer join t on primeirodia_mes = trunc(dt, 'mm') group primeirodia_mes;

Faster parsing with Python -

i'm trying parse data 1 web page. web page allows (according robots.txt) send 2000 requests per minute. the problem tried slow. response of server quite quick. from multiprocessing.pool import threadpool pool import datetime import lxml.html lh bs4 import beautifulsoup import requests open('products.txt') f: lines = f.readlines() def update(url): html = requests.get(url).content # 3 seconds doc = lh.parse(html) # 12 seconds (with commented line below) soup = beautifulsoup(html) # 12 seconds (with commented line above) pool = pool(10) line in lines[0:100]: pool.apply_async(update, args=(line[:-1],)) pool.close() = datetime.datetime.now() pool.join() print datetime.datetime.now() - as commented code - when try html = requests.get(url) 100 urls, time great - under 3 seconds. the problem when want use parser - preprocessing of html costs 10 seconds , more much. what recommend me lower time? edit: tried use soupstrainer - faster

Borders dont appear to NatTable Cells in Eclipse RCP application -

i have tried both : setting theme configuration , registering style border style in config registry. not seeing borders. there else missing? in postconstruct method initialising nattable follows : final themeconfiguration moderntheme = new modernnattablethemeconfiguration(imagerightup, imagetreerightdown); textpainter textpainter = new textpainter(true, false); imagepainter imagepainter = new imagepainter(threedots); cellpainterdecorator cellpainterdecorator = new cellpainterdecorator(textpainter, celledgeenum.right, imagepainter); configregistry.registerconfigattribute( cellconfigattributes.cell_painter, cellpainterdecorator, displaymode.normal, label_1); style style = new style(); style.setattributevalue( cellstyleattributes.background_color, guihelper.getcolor(44, 104, 125)); style.setattributevalue( cellstyleattributes.foreground_color, guihelp

html - alignment not showing up correctly on wordpress -

i having issue wordpress aligning logos using text widget. when build html , css locally or on jsfiddle, works when try replicate on wordpress comes out funny. here site logos on write hand side , here code using jsfiddle of code . could tell me need make same on wordpress on fiddle (i.e 2 columns of logos) <!doctype html> <html> <head> <title>put in title</title> <style> .association_logos_container_left { max-width:140px; float:right; } .association_logos_container_left .association_logos_left img { max-width:100px; float:left; margin: 5px; display:block; } .association_logos_container_right { max-width:140px; float:right; } .association_logos_container_right .association_lo

string - Python unicode errors while writing to file -

i'm using python 2.7 parse through bunch of webpages , content them, webpages include characters "" , ', both somehow converted ’. gives me file content looks (excluding quotes): "i think it’s important..." the strings print out fine in terminal using print() method, can't seem same effect using print >> file, string or file.write(string) . encoding issue, i've searched no success find way around this. i'm opening file this: file = codecs.open("file.txt","w+", encoding='utf-8') , i'm using beautifulsoup4's gettext() method assign strings values. there way solve this? try add below lines code in start of function, solve problem. import sys reload(sys) sys.setdefaultencoding('utf8')

sockets - Implementing Stop and wait with C & UDP, and what does cause 'resource temporarily unavailable'? -

i implementing stop&wait c , udp socket programming. simulate protocol, wrote 2 codes. this server.c file: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <unistd.h> #include <arpa/inet.h> typedef struct packet{ char data[1024]; }packet; typedef struct frame{ int frame_kind; //ack:0, seq:1 fin:2 int sq_no; int ack; packet packet; }frame; int main(int argc, char** argv) { int sockfd; int clilen; int state; int n; int sum; int recv_result; int frame_id = 0; packet packet; frame frame; frame recv_frame; char buffer[1024] = ""; struct timeval tv; struct sockaddr_in serveraddr, clientaddr; file* infile = fopen(argv[2], "r"); if(argc != 3) { perror("error! usage: $./server <port> filename\n&

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() getting runtime error in android -

getting runtimeexception in android : java.lang.runtimeexception: can't create handler inside thread has not called looper.prepare() getting run time error @ toast.maketext(this, latitude+""+longitude, 1).show(); in function updatelocation() . public class location_update extends service { double latitude; double longitude; gpslocation gps; boolean state=true; @override public ibinder onbind(intent intent) { // todo auto-generated method stub return null; } @override public void oncreate() { // todo auto-generated method stub super.oncreate(); timer timer = new timer(); timer.schedule(task, 0,1000*30); } timertask task=new timertask() { @override public void run() { // todo auto-generated method stub updatelocation(); } }; public void updatelocation() { gps = new gpslocation(mainactivity.dis); // check if gps enabled if(gps.cangetlocation()){ latitude = gps.getlatitud

Django - How to Save ImageField Even if Form is Not Valid -

i have standard model , form. have mandatory fields imagefield. when user choose image , doesn't field mandatory fields, image isn't saved , user needs 're-upload' again. as row in database exists (because form part of 'wizard'), don't mind saving picture in database if form isn't valid mandatory data. this have right in view, works when fill mandatory fields: def my_view(request): instance = mymodel.objects.get(user=request.user) form = myform(instance=instance) if request.post: form = myform(request.post, request.files, instance=instance) if form.is_valid(): new_instance = form.save(commit=false) if request.files , request.files['photo']: uploaded_photo = request.files['photo'] new_instance.photo = uploaded_photo new_instance.save() return httpresponseredirect(reverse('new_url')) return render_to_response

c# - Cannot Update SharePoint Publishing Page Image -

i trying update publishing page image url somehow after execute query command. value saved null clientcontext targetcontext = new clientcontext ("real url"); microsoft.sharepoint.client.file targetfile = targetcontext.web.getfilebyserverrelativeurl ("real url"); var targetpublishingpage = publishingpage.getpublishingpage (targetcontext, targetfile.listitemallfields); targetcontext.load (targetpublishingpage.listitem); targetcontext.executequery (); targetfile.checkout (); targetpublishingpage.listitem["publishingpageimage"] = "real url"; targetpublishingpage.listitem.update (); targetcontext.executequery (); publishing image field value expected specified in folliowing format: <img src='{imageurl}'> example using (var ctx = new clientcontext(weburi)) { var pagefile = ctx.web.getfilebyserverrelativeurl(pageurl); var pageitem = pagefile.

sailsjs: model email validation seems not to work -

on fresh sailsjs installation, i've got test model defined this: module.exports = { attributes: { username:{ type:'string' } ,email:{ type:'string' ,email:true } } }; and if navigate this: http://localhost:1337/user/create?username=stratboy1&email=test@wow.com i error: { "error": "e_validation", "status": 400, "summary": "1 attribute invalid", "model": "user", "invalidattributes": { "email": [ { "rule": "email", "message": "\"email\" validation rule failed input: 'test@wow.com'" } ] } } any of knows why? i've come across earlier don't quite remember cause. as quick fix, can substitute email: { type: 'string', email: true } with email: { type: 'email' }

Ranked returns in R -

returns <- data.frame(date = c('2015.01.01','2015.01.02','2015.01.03','2015.01.04'), asset1 = as.numeric(c('0.1','0.1','0.1','0.1')), asset2 = as.numeric(c('0.2','0.2','0.2','0.2')), asset3 = as.numeric(c('0.3','0.3','0.3','0.3'))) rank <- data.frame(date = c('2015.01.01','2015.01.02','2015.01.03','2015.01.04'), asset1 = as.numeric(c('3','3','3','3')), asset2 = as.numeric(c('1','1','1','1')), asset3 = as.numeric(c('2','2','2','2'))) i match rank 1 returns column 1 in new data frame. numbers , ranks can change quite bit moving column around won't work. think english didn't come out clear in first post. result

c# - How to get the line count in a string using .NET (with any line break) -

i need count number of lines in string . line break can character can present in string (cr, lf or crlf). so possible new line chars: * \n * \r * \r\n for example, following input: this [\n] string [\r] has 4 [\r\n] lines the method should return 4 lines. know built in function, or implemented it? static int getlinecount(string input) { // provide implementation method? // want avoid string.split since performs bad } note: performance important me, because read large strings. thanks in advance. int count = 0; int len = input.length; for(int = 0; != len; ++i) switch(input[i]) { case '\r': ++count; if (i + 1 != len && input[i + 1] == '\n') ++i; break; case '\n': // uncomment below include other line break sequences // case '\u000a': // case '\v': // case '\f': // case '\u0085': // case '\u2028': // case '\u2029'

javascript - How can I get all the github issues using github API? -

this question has answer here: github search api return 30 results 1 answer hi trying number of issues of repo using angular , github rest api, problem 30 issues though more issues there in repo. please me idea. use below rest api issues. https://api.github.com/repos/vmg/redcarpet/issues?state=all updated response if want number of issues think closest you'll get repo endpoint: get /repos/:owner/:repo the json response endpoint includes 2 relevant keys: has_issues , true or false , and open_issues_count , should give number of open issues. i'm not sure of way number of issues including ones aren't open. original response you'll need paginate : requests return multiple items paginated 30 items default. can specify further pages ?page parameter. resources, can set custom page size 100 ?per_page parameter. note t

c# - Improving performance of Dictionary using Arrays -

consider counting number of occurrences of particular letter in word. i came solution. string = "aabbcdc"; //output: a:2,b:2,c:2,d:1 var dict = new dictionary<char, int>(); foreach(var @char in a) { if(dict.containskey(@char)) dict[@char] = dict[@char] + 1; else dict.add(@char, 1); } foreach(var keyvaluepair in dict) console.writeline("letter = {0}, value = {1}", keyvaluepair.key, keyvaluepair.value); my friend argued solution can improved further using arrays better using above dictionary. i guess, dictionary lookup o(1) (arrays o(1), correct ?) . ideas how re-write program using arrays performs better? arrays o(1), correct arrays o(1) when accessing known offset. o(n) when have scan array find particular match. you not out-perform dictionary type of operation in general case. you can leverage accessing known offset caveat use arrays limited case. example, if know have input in range 'a'..'z', can

Create bash script with various alias? -

i'm creating script when run create various alias various scripts in other folders. script , other folders inside specific folder shown in image gonna executable when want too. assuming gonna execute on machine don't have change paths. i got in script runs perfectly, prints echo , alias isn't created. if same alias line out of script creates alias perfectly. this script i'm creating sh have influence on situation ? now want use alias because folder going stay in machine , i'm not going have other people running these. want able instead of going folders , run executables want script create alias can call them directly through prompt like $~ zenmap , runs. #!/bin/bash alias zenmap="/home/user/desktop/folder/nmap/zenmap/zenmap" echo "zenmap imported !" any clue on can happening ? from comments in jayant answer seems confusing when functions executed. little example: file_with_alias.sh alias do_this="do_some_function&

php - Mysql is not fetching all the data -

<?php include('config.php'); $isd=mysql_real_escape_string( $_get['q'] ); $sql=mysql_query("select zip zipcod abb='$isd' ") or ; while( $row=mysql_fetch_array( $sql, mysql_assoc ) ){ $zip=$row['zip']; echo '<option>'.$zip.'</option> '; } ?> this ajax <script> function showuser(str) { if (str=="") { document.getelementbyid("zzips").innerhtml=""; return; } if (window.xmlhttprequest) { // code ie7+, firefox, chrome, opera, safari xmlhttp=new xmlhttprequest(); } else { // code ie6, ie5 xmlhttp=new activexobject("microsoft.xmlhttp"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readystate==4 && xmlhttp.status==200) { document.getelementbyid("zzips").innerhtml=xmlh

pointers - lvalue required as left operand of assignment error when using C -

int main() { int x[3]={4,5,6}; int *p=x; p +1=p;/*compiler shows error saying lvalue required left operand of assignment*/ cout<<p 1; getch(); } when have assignment operator in statement, lhs of operator must language calls lvalue . if lhs of operator not evaluate lvalue , value rhs cannot assigned lhs. you cannot use: 10 = 20; since 10 not evaluate lvalue . you can use: int i; = 20; since i evaluate lvalue . you cannot use: int i; + 1 = 20; since i + 1 not evaluate lvalue . in case, p + 1 not evaluate lavalue . hence, cannot use p + 1 = p;

Amending .gitignore, removing files from git while keeping them locally -

all of developers have files should have been in .gitignore start of project, not. is there git command remove files git, while keeping them locally and keeping them locally on other developer machines, when git pull ? ideally should @ diff of .gitignore decide needs removed kept locally. at moment, considering following manual procedure: my machine: get full paths of files match new .gitignore , don't match old .gitignore add of files out-of-tree tar file git rm files commit , push origin master changes email tar file other developers every other developer's machine: git pull update .gitignore , remove local copies of files should ignored. untar tar file on top of local repo reinstate removed files this procedure has huge scope manual errors - there better way? i've looked at: remove file git without deleting them locally , remotely removing file versioning keeping locally? , http://gitready.com/intermediate/2009/02/18/temporar