Posts

Showing posts from April, 2014

LINQ OrderBy on inner object's property -

below hierarchies , required function public class friend { public string name { get; set; } public list<message> messages { get; set; } } public class message { public string text { get; set; } public datetime time { get; set; } } now required function: public list<string> whatsapp(list<friend> friends) { throw new notimplementedexception(); } i need list of friend names in descending order of there message time stamp. whats app or other im matter. i getting feeling can done in 1 or 2 lines using linq since new linq, unable drill down problem. thanks in advance help. if idea order last (i.e. max) message timestamp, following should job: return friends.orderbydescending(f => f.messages.max(m => (datetime?)m.time)) .select(f => f.name) .tolist(); casting datetime? needed avoid exception when there no messages friend. in general when need order parent having multiple children based on chi

php - Using loop for creating row in formatted email -

i want create formatted email. in email's body, need add loop creating table's row. don't know how make work. loop looks <tbody> <?php $total = 0; for($i=0; $i<3; $i++) { ?> <tr> <td style="padding: 8px; line-height: 20px;">col 0</td> <td>col 1</td> <td>col 2</td> <td>col 3</td> </tr> <?php }?> </tbody> it works in normal html page. when tried make email's body , pass code string this, $body = "<tbody> <?php $total = 0; for($k=0; $k<3; $k++) { ?> <tr> <td style='padding: 8px; line-height: 20px;'>1</td> <td>asd</td> <td>ert</td> <td>qwe</td> </tr> <?php }?> </tbody>"; send($to, $subject, $body); in email, doesn't create row @ all. advice? main advice learn php sy

java - How to know which variable is the culprit in try block? -

in try block, have 2 string variables cause numberformatexception when user integer.parseint(string1) and integer.parseint(string2) . question is, if catch exception, how know string troublemaker? need troublemaker's variable name. here example code: public class test { public static void main(string[] args) { try { string string1 = "fdsa"; string string2 = "fbbbb"; integer.parseint(string1); integer.parseint(string2); } catch (numberformatexception e) { e.printstacktrace(); } } } and method e.printstacktrace() doesn't tell me variable name; tells me content of troublemaker. java.lang.numberformatexception: input string: "fdsa" @ java.lang.numberformatexception.forinputstring(numberformatexception.java:65) @ java.lang.integer.parseint(integer.java:580) @ java.lang.integer.parseint(integer.java:615) @ test.main

html - disable audio from keeping playing after lock screen or press home button in safari -

i'm working on project , in case need play audio using tag in web. found out audio won't stop after lock screen or press home button. keeps playing. there way disable that? btw tried simplest way audio won't stop. here's code: <html> <body> <audio src="./movies/1.mp3" controls="controls"> browser not support audio element. </audio> </body> </html> maybe. can listen event hitting home button or lock screen , pause()? don't know if possible. make use of loop, check if user on webpage. store time. here code jquery: var lastseen var loop = function (){ lastseen = date.now() settimeout(loop, 50) } loop() var media = $('audio, video') media.each(function () { this.addeventlistener('timeupdate', function () { if(date.now() - lastseen > 100) { this.pause() } }, false) }) source: stop html5 audio looping when ios saf

c - Why my free() wrapper function doesn't work? -

this question has answer here: c programming: malloc() inside function 8 answers why should use pointer pointer in saferfree(void**) function when want free memory inside function? why below code does'n free ip pointer? #include <stdio.h> #include <stdlib.h> #include <stdint.h> void saferfree(void *); int main() { int *ip; ip = (int*) malloc(sizeof(int)); *ip = 5; saferfree(ip); return 0; } void saferfree(void *pp){ if((void*)pp != null){ free(pp); pp = null; } } above code doesn't free pp pointer below code double pointer works properly.i want know why? #include <stdio.h> #include <stdlib.h> #include <stdint.h> void saferfree(void **); int main() { int *ip; ip = (int*) malloc(sizeof(int)); *ip = 5; saferfree(&ip); printf("%p", ip

ios - Changing playback rate of AVPlayer produces choppy Audio -

i using avplayer in app. app supports change of speed of playback of audio , video. initializing player follows. avplayeritem * playeritem= [avplayeritem playeritemwithurl:self.audiourl]; playeritem.audiotimepitchalgorithm = avaudiotimepitchalgorithmspectral; self.player = [avplayer playerwithplayeritem:playeritem]; self.player.allowsexternalplayback= yes; [self.player.currentitem addobserver:self forkeypath:@"status" options:0 context:nil]; and when have change playback rate of audio follows self.player.rate = 2.0f; it working fine. when change rate property of avplayer start producing choppy voice. have set audiotimepitchalgorithm avaudiotimepitchalgorithmspectral but still producing choppy voice. can tell me doing wrong, or have avoid choppy voice , produce smooth sound.

python - Best way to avoid copy-paste and hardcoding -

' hello, community. problem: have many regex patterns, such as r'to.*school', r'built.*in' and etc. in every case, should execute code, varies situation situation. example: if pattern 'to.*school', want find verb before 'to' , that's why write like: for num, part in enumerate(sentence): if part == 'to': result = sentence[num-1] if pattern 'built.*in', want find time , that's why write like: for num, part in enumerate(sentence): if part == 'in': result = sentence[num+1] so there's problem - how can avoid copy-pasting code, if there's on 500 patterns , each pattern has own way result? my thoughts: understand should kind of database, stores patterns , solutions, how execute solution, if it's string? i'm totally lost. if there sufficient regularity in code need write function accepts sentence , other things determine it. called parametrisation. examp

Windows App and Asp.Net Encryption -

i developed asp.net webservice xamarin app. used encryption class based on system.security.cryptography library now want develop universal app version, need use windows.security.cryptography library i know different libraries, there way encrypt , decrypt in same way? or if not, there common library? thanks take @ pclcrypto . can use same library different project types. library doesn't implement cryptographic algorithms relies on platform specific implementations, it's safe use you're doing now.

regex - Java regular expressions for specific name\value format -

i'm not familiar yet java regular expressions. want validate string has following format: string input = "[name1 value1];[name2 value2];[name3 value3];"; namei , valuei strings should contain characters expect white-space. i tried expression: string regex = "([\\s*\\s\\s*];)*"; but if call matches() false string. what's best regular expression it? this trick: (?:\[\w.*?\s\w.*?\];)* if want match 3 of these, replace * @ end {3} . explanation: (?: : start of non-capturing group \[ : escapes [ sign meta-character in regex. allows used matching. \w.*? : lazily matches word character [a-z][a-z][0-9]_ . lazy matching means attempts match character few times possible, in case meaning when stop matching once finds following \s . \s : matches 1 whitespace \] : see \[ ; : matches 1 semicolon ) : end of non-capturing group * : matches number of contained in preceding non-capturing group. see link demonstration

ruby on rails - Location of a sound file used by gem -

i tinkering around gem ruby on rails, upon executable want play sound wave file, seem not work thought, ones gem installed... far have cmd = ("afplay 'sound/activated.wav'") exec cmd with file located und lib/sound/activate.wav, within gem folder, if use gem can't find file... there particular location have store files? thanks if run that, afplay looking @ sound/activated.wav current directory, not gem directory. in ruby 2.x can find directory script located in __dir__ . (with precautions taken): require 'shellwords' file = file.join(__dir__, 'sound', 'activated.wav') escfile = shellwords.escape(file) cmd = "afplay #{escfile}" if need make compatible older rubies, file.dirname(file.realpath(__file__)) same thing __dir__ . note exec replace ruby process new afplay process, terminate ruby code. in cases rather want system .

sql - 1 minute difference in almost identical PostgreSQL queries? -

i have rails application ability filter records state_code. noticed when pass 'ca' search term results instantly. if pass 'az' example take more minute though. i don't have ideas why so? below query explains psql: fast one: explain analyze select accounts.id "accounts" left outer join "addresses" on "addresses"."addressable_id" = "accounts"."id" , "addresses"."address_type" = 'mailing' , "addresses"."addressable_type" = 'account' "accounts"."organization_id" = 16 , (addresses.state_code in ('ca')) order accounts.name desc; query plan --------------------------------------------------------------------------------------------------------------------------------------------------------- sort (cost=4941.94..4941.94 rows=1 width=

c++ - Where is the return value of int main() is stored? -

this question has answer here: what should main() return in c , c++? 19 answers in program below, value of return 0 stored , mean? #include <iostream.h> int main() { cout<<"hello world"; return 0; } the return value of main() typically return value of process (e.g. if called command line). exact storage location , transfer mechanism calling shell (or parent process) defined platform being targeted. a return of 0 ( exit_success ) typically means program completed without error. non-zero values in turn indicate error - program define exact meaning each value be.

c# - Can I cancel selecting text in console? -

i'm making console application in c# , wonder if it's possible disable selecting text while holding shift , pressing arrows. i tried using console.cancelkeypress doesn't work in case. try use these methods: [dllimport("user32.dll", charset = charset.auto, setlasterror = true)] private static extern intptr setwindowshookex(int idhook, lowlevelkeyboardproc lpfn, intptr hmod, uint dwthreadid); [dllimport("user32.dll", charset = charset.auto, setlasterror = true)] [return: marshalas(unmanagedtype.bool)] private static extern bool unhookwindowshookex(intptr hhk); and in hook method: private static intptr hookcb(int ncode, intptr wparam, intptr lparam) { if (ncode >= 0 && wparam == (intptr)wm_keydown) { int keycode = marshal.readint32(lparam); string keyname = ((keys)keycode).tostring(); //there can define key pressed , react accordingly }}

Python third party Module global import -

i'm learning bit of python , want import paperclip third party module python file. yes, installed pyperclip module pip install pyperclip . if create file on desktop, error says traceback (most recent call last): file "test.py", line 1, in <module> import pyperclip importerror: no module named pyperclip however if put test.py in python folder, runs. the question is, there way make installed modules available on global scope ? want have file e.g. on desktop , run without having import issues. thank you. greetings edit: i'm working on mac, maybe leads problem found problem. the pip install automatically used pip3.5 install whereas python test.py didn't use python3.5 test.py thank @bakurìu is there way can define python3.5 as python ?

asp.net - Visual Basic 2015 project for VB.NET to work in XP -

apologies lack of knowledge not have experience. i have created vb.net application using visual basic 2015 however, when tried run application on xp professional version 2002 sp3 follow error message. i have life of me not know how fix this. .net framework application created in 4.5.2. the application works on windows 7 , windows 10. however, issues on xp platform version info windows : 5.1.2600.196608 (win32nt) common language runtime : 4.0.30319.269 system.deployment.dll : 4.0.30319.1 (rtmrel.030319-0100) clr.dll : 4.0.30319.269 (rtmgdr.030319-2600) dfdll.dll : 4.0.30319.1 (rtmrel.030319-0100) dfshim.dll : 4.0.31106.0 (main.031106-0000) sources deployment url : file:///c:/documents%20and%20settings/rwuser/desktop/disk%20cleanup%20toolkit/drive_cleanup.application error summary below summary of errors, details of these errors listed later in log. * activation of c:\documents , settings\rwuser\

python - Can you extend SQLAlchemy Query class and use different ones in the same session? -

i using sql alchemy orm , have classes/tables each of may have custom queries. let's say, want add table fruit filtering possibility called with_seed giving me fruits seeds, , table cutlery filtering method is_sharp giving me sharp cutlery. want define these filters extensions query object, , want use them in same transaction: def delete_sharp_cutlery_and_seedy_fruits(session_factory): session = session_factory() session.query(fruit).with_seed().delete(synchronize_session='fetch') session.query(cutlery).is_sharp().delete(synchronize_session='fetch') session.commit() is possible? this related question here . solution there requires different sessions created different query classes. you can pass session query constructor customquery(entities=[fruit], session=session).with_seed().delete(synchronize_session='fetch')

while true loop doesn't work inside another in python -

i have while true loop (code below) within loop. want check if clicked on button , if so, change cursor image have imported before. tried hiding cursor , let image follow it. when run this, hides cursor draws image was, doesn't move cursor. while true: event in pygame.event.get(): if event.type == mousebuttonup: mousex, mousey = pygame.mouse.get_pos() if mousex > 100 , mousex < 200 , mousey > 50 , mousey < 100: # button on screen pygame.mouse.set_visible(false) while true: mousex, mousey = pygame.mouse.get_pos() displaysurf.blit(cursorimg, (mousex,mousey)) pygame.display.update() can tell me doing wrong please? change code this: while true: event in pygame.event.get(): if event.type == mousebuttonup: mousex, mousey = pygame.mouse.get_pos() if mousex > 100 , mousex < 200 , mousey &g

flash - swf to source code for editing and back to swf -

i haven't touched code quite time , knowledge dealing flash , haxe believe. possible go swf source code, edit code , swf revised code? wanted take simple flash game , edit character looks like. wanted remove different modes game keep simple. knowledge game written in haxe. if provide info on appreciated. in advance! there tools available can decompile swf file underlying actionscript 3 source code. note, however, @ no point deal haxe source code. as3 code received through decompilation code generated haxe compiler. code includes "shims" haxe-specific features not native target language, these should easy identify , ignore. compiling as3 swf not involve haxe either. you'll have find tool that, such flex sdk.

c# - Aspose.Pdf Polish Characters -

why pdf don't display polish character? memorystream ms = new memorystream(); pdf pdf = new pdf(ms); section section = pdf.sections.add(); var txt = new text("aąbcćde"); txt.textinfo.fontname = "calibri"; section.paragraphs.add(txt); pdf.close(); byte[] bytes = ms.toarray(); return bytes; those special characters unicode characters, have make sure font supports them , call pdf.setunicode(); before pdf.close .

linux - Write Apache Redirect Rule? -

how write apache redirect rule in apache http://www.example.com/8484/sdsdsd or http://www.example.com/8484/test should redirect www.example.com like this: rewriteengine on rewriterule ^/8484/(.*)$ http://www.example.com [r,l] the rewriteengine on needed once per virtualhost in order activate redirections

python - Tkinter canvas animation flicker -

i wrote python program tkinter makes ball bounce around screen. works great, except 1 problem: outermost edges of ball flicker ball moves. i understand tkinter automatically double buffering, thought shouldn't having problems tearing. i'm not sure error coming from. ideas on how can rid of it? code below. here's gist of it: class ball extends tk , gets created when program run. sets game, encapsulating in gmodel. gmodel runs game run() , loops on , over, calling update(). import threading time import sleep, clock tkinter import * tkinter import ttk speed = 150 # pixels per second width = 400 height = 500 rad = 25 pause = 0 # time added between frames. slows things down if necessary class gmodel: # contains game data. def __init__(self, can): # can canvas draw on self.can = can self.circ = can.create_oval(0,0, 2*rad, 2*rad) # position , velocity of ball self.x, self.y = rad, rad self.dx, self.dy =

html - How to align the first line of a paragraph center to an image. And the other lines and the first line are the same indentation? -

i have image , paragraph. want 'css' image on left , paragraph on right. , first line of paragraph has display center image. , other lines have indent same first line. can css that? hope can teach me way achieve that. thank in advanced! html : <div class="parent"> <img src="http://jsfiddle.net/img/logo.png"> <div class="child"> bottom of element aligned bottom of parent element's font. bottom of element aligned bottom of parent element's font. bottom of element aligned bottom of parent element's font. </div> </div> css : img { display: inline; } .child { display: inline; } here jsfiddle: https://jsfiddle.net/qn4bh8ht/ don't work @ all. :( try these: jsfidle . i use display: table .parent class table-cell children + vertical-align: top on .child class. .parent { display: table; } .parent > * { display: table-cell; } .child { vertical-align: to

Importing nunit results into teamcity with cake -

Image
i using cake build script , teamcity ci. having cake run unit tests nunit , teamcity pulling in results 'xml report processor'. as can see importing file, 'test' tab missing can't see test output. am missing step? my cake task testing , tests report tab appears nunit3(testsdir.tostring() + "/*tests.dll", new nunit3settings { noresults = true, noheader = true, framework = "net-4.0", workers = 5, timeout = 10000 }); do need report xml?

Streaming video with PHP Html5 -

i have videos on website, , display them streming php , html5. i tri follow tutorial ( http://codesamplez.com/programming/php-html5-video-streaming-tutorial ) of streaming video creation php class. <?php /** * description of videostream * * @author rana * @link http://codesamplez.com/programming/php-html5-video-streaming-tutorial */ class videostream { private $path = ""; private $stream = ""; private $buffer = 102400; private $start = -1; private $end = -1; private $size = 0; function __construct($filepath) { $this->path = $filepath; } /** * open stream */ private function open() { if (!($this->stream = fopen($this->path, 'rb'))) { die('could not open stream reading'); } } /** * set proper header serve video content */ private function sethe

java - Jms session.commit() throws exceptoin when I run my application in Jboss server -

i using activemq v5.11.1 managed beans on jboss eap v6.3 server exception when perfrom jms session.commit() or rollback() (activemq session task-1) javax.jms.illegalstateexception: not transacted session but when run java application gives no exception why ? because of version mismatch ?please help. read here . if jms resource controlled jta, can't commit or rollback manually

javascript - Windows.Forms.WebBrowser loading page with local SVG file -

i have html page generating in c# project. works, when open page in ie. <!doctype html> <meta http-equiv='x-ua-compatible' content='ie=10' /> <html lang='en'> <head> <title>templatesvg</title> <script type='text/javascript' src='interfacesvg.js'></script> </head> <body style='margin: 0; overflow: hidden;'> <div class="page-content"> <object id='idsvg' type='image/svg+xml' data='d:\examples\examplefla.svg'></object> </div> </body> </html> i loaded getting text in web browser if (webbrowser.document == null) { webbrowser.documenttext = thehtmltext; } else { webbrowser.document.opennew(true); webbrowser.documenttext = thehtmltext; } but file interfacesvg.js isn't find. when give full path js file src=

nginx Reverse Proxy with plesk -

i've seen answers on here , none of solutions seem work. i have domain.com wordpress install , script running on domain.com:6000 i want able have script.domain.com show what's on domain.com:6000 now other big issue plesk. (it gets lot of hate people using website ui.) here's i've done/tried new folder , file in /var/www/vhosts/domain.com/conf file : vhost_nginx.conf , what's in server { listen 80; server_name script.domain.com; location / { proxy_pass http://domain.com:6000; } } also having tried location /script/ { proxy_pass http://domain.com:6000/; } to try , have domain.com/script show different. any suggestions? right in plesk 12.5 there no way override "location /" via plesk, because custom conf files added @ end of nginx's server section after default "location /" derectives. you can create or change hosting type of subscription forwarding in answer https://serverfault

sql - C# cant populate datagridview -

i had similar problem , shown how fix it, tried post on same thread limited. i have method private void filllevyroll(), put method in button on click event fill datagridview dgvlevyroll problem when run not getting error , dgv remaining empty.im lost confused tried no avail. the query works in sql management studio private void filllevyroll() { try { datatable datatablesource = new datatable(); sqlcommand command = new sqlcommand("select refrence" + ", max(case when accnumber = '1010000' amount end) opening" + ", max(case when accnumber = '1010000' amount end) electricity" + ", max(case when accnumber = '1045000' amount end) water" + ", max(case when accnumber = '1000000' amount end) levy" + ", max(case when accnumber = '2750000' amount end) interest"

java - What are alternatives to JUnit's assertEquals() method in order to see in the test report which fields of objects differed on comparison? -

i have lot of automated tests written in java on junit , use assertequals(java.lang.string message, java.lang.object expected, java.lang.object actual) . if compare primitive types in case of assert failure visible in test report values different, e.g. in case of 2 integers comparison. when compare 2 complex objects output of test can quite cluttered. if have override tostring() method list fields values output long. imagine having class: public class invoice { private localdate invoicedate; private string invoicenumber; private invoicetype invoicetype; private invoicestatus invoicestatus; private string mediaplanner; private string yourreference; private string responsibleperson; private brand advertiser; private mediaagency mediaagency; private set<invoicerow> invoicerows; ..... the invoicerow quite complex object lot of own fields. if put these fields tostring() implementation , assert fails junit output quite long messag

c# - UWP - scaled image is damaged -

Image
i have problem place image down-scale. image rasterized , don't know find way place correctly. is possible place picture without losing quality ? code: public async task<bitmapimage> bitmaptransform(string filepath, uint width) { storagefile file = await storagefile.getfilefrompathasync(filepath); if (file == null) return null; // create stream file , decode image var filestream = await file.openasync(windows.storage.fileaccessmode.read); bitmapdecoder decoder = await bitmapdecoder.createasync(filestream); // create new stream , encoder new image inmemoryrandomaccessstream ras = new inmemoryrandomaccessstream(); bitmapencoder enc = await bitmapencoder.createfortranscodingasync(ras, decoder); double ration = enc.bitmaptransform.scaledwidth = width; enc.bitmaptransform.scaledheight = (uint)(((double)decode

javascript - Adding values contained in an array of objects -

how go adding values within object? for example amoutpay": ["4222","1000"] give me 5222 this object: { "amoutpay": [ "4222", "1000" ], "amtpending": [ "778", "4000" ], "totalcost": [ "5000", "5000" ], "coursename": [ "office automation", "ajaba" ] } what want add values variables. use split? var = var b = var c = you can use array.prototype.reduce() shown below: var obj = { "amoutpay": [ "4222", "1000" ], "amtpending": [ "778", "4000" ], "totalcost": [ "5000", "5000" ], "coursename": [ "office automation", "ajaba" ] }, = obj.amoutpay.reduce(function(prevval, curval, curind) { return +prevval + +curval; }), b = obj.amtpending.red

Changing value of a field in javascript for a form submitted in lotus notes -

i have form, has notes , web sub form. on web, on click on button save, value field "test" must updated 1. when click on save form submitted on web side value of field gets updated, when try click on save (on web side) form originated on notes side, value doesn't updated. have used document.forms[0].testfield.value= "1"

Catch an error from command line Python -

i need catch error command line without print error message on screen. when occurs need give command run. this now: hyst_cmd = "si viewhistory ..." process = subprocess.popen(hyst_cmd, stdout=subprocess.pipe) hyst = process.stdout.read().splitlines() when projects receive error message, on screen. sorry english! according official document, common exception popen in subprocess oserror . to catch error, can try following approach: hyst_cmd = "si viewhistory ..." try: process = subprocess.popen(hyst_cmd, stdout=subprocess.pipe) hyst = process.stdout.read().splitlines() except oserror: <write_log_file or other action.> for more information, can check link below: subprocess exception

api - why I am getting http 404 after heating http://localhost:3636/RestSwagger/rest/swagger.json -

hi while trying acess swagger.json rest api http://localhost:3636/restswagger/rest/swagger.json why getting http 404 response. below providing whole code please follow pom.xml ---------- <dependency> <groupid>com.sun.jersey</groupid> <artifactid>jersey-server</artifactid> <version>1.8</version> </dependency> <dependency> <groupid>io.swagger</groupid> <artifactid>swagger-jaxrs</artifactid> <version>1.5.8</version> </dependency> web.xml --------- <servlet> <servlet-name>jersey-serlvet</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.servletcontainer</servlet-class> <init-param> <param-name>com.sun.jerse

google container engine - Deploying service to GKE/Kubernetes leading to FailedSync error -

when deploying service kubernetes/gke kubectl describe pod indicates following error (as occurring after image pulled): {kubelet <id>} warning failedsync error syncing pod, skipping: failed "startcontainer" "<id>" crashloopbackoff: "back-off 20s restarting failed container=<id>" {kubelet <id>} spec.containers{id} warning backoff restarting failed docker container. i have checked various log files (such /var/log/kubelet.log , /var/log/docker.log ) on node pod executing did not find more specific? what error message indicate, , how can further diagnose , solve problem? the problem might in relation mounting pd. can both docker run the image cloud shell (without pd) , mount pd after adding gce vm instance. apparently it's neither caused image nor pd in isolation. the root cause apparently pd did not contain directory target of symbolic link required application running inside image. cause application term

ios - UIDatePicker crashing application -

in app have textfield form want populated date picker, have assigned date picker input view textfield , datepickervaluechanged func change text of textfield when picker changed. issue when clicking off data picker in app, whole app crashes 'terminating uncaught exception of type nsexception' any ideas? here code: @iboutlet var startdatepickerfield: uitextfield! override func viewdidload() { let startdatepicker:uidatepicker = uidatepicker() startdatepicker.datepickermode = uidatepickermode.dateandtime startdatepickerfield.inputview = startdatepicker startdatepicker.addtarget(self, action: #selector(popovertableviewcontroller.datepickervaluechanged(_:)), for: uicontrolevents.valuechanged) } func datepickervaluechanged(_ sender: uidatepicker) { let dateformatter = dateformatter() dateformatter.datestyle = dateformatter.style.long dateformatter.timestyle = dateformatter.style.short startdatepickerfield.text = dateformatter.strin

Searching in Google with Python -

i want search text in google using python script , return name, description , url each result. i'm using code: from google import search ip=raw_input("what search for? ") url in search(ip, stop=20): print(url) this returns url's, how can return name , description each url? thanks! i assume using this library mario vilas because of stop=20 argument appears in code. seems library not able return urls, making horribly undeveloped. such, want not possible library using. i suggest instead use abenassi/google-search-api . can do: from google import google num_page = 3 search_results = google.search("this query", num_page) result in search_results: print(result.description)

javascript - String() Function error - Uncaught SyntaxError: missing ) after argument list -

i have function in js <script> var currentlocation = window.location.href; function addcardtotrello() { trello.addcard({ url: currentlocation, name: string({{ soproduct.product }}), due: {{ soproduct.required_date|date:"short_date_format" }} }); } </script> that gives me error uncaught syntaxerror: missing ) after argument list this how looks when parsed <script> var currentlocation = window.location.href; function addcardtotrello() { trello.addcard({ url: currentlocation, name: string(1 4343rfcdc 54446), due: 07/30/2016 }); } </script> the error in line name: string(1 4343rfcdc 54446), when value id (numeric) works ok , not getting error. what problem? this error happens because javascript engine doesn't know '1 4343rfcdc 54446' string, need wrap quotes. , if so, wont need string constructor because string. trello.addcard({ url: currentlo

django - Migrating from abstract model to proxy models -

right now, have abstract model several models inherits fields. have discovered power of proxy models, , want implement them app. picture now: class basemodel(models.model): field_1 = models.charfield(max_length=10) field_2 = models.charfield(max_length=10) field_3 = models.charfield(max_length=10) class meta: abstract = true class model1(basemodel): pass def __unicode__(self): return self.field_1 class model2(basemodel): pass def __unicode__(self): return self.field_1 and want: class basemodel(models.model): field_1 = models.charfield(max_length=10) field_2 = models.charfield(max_length=10) field_3 = models.charfield(max_length=10) class model1(basemodel): pass class meta: proxy = true def __unicode__(self): return self.field_1 class model2(basemodel): pass class meta: proxy = true def __unicode__(self): return self.field_1 the problem when

How to convert Json to Java object using Gson -

this question has answer here: parse json file using gson 3 answers suppose have json string {"userid":"1","username":"yasir"} now have class user class user{ int userid; string username; //setters , getters } now how can convert above json string user class object try this: gson gson = new gson(); string jsoninstring = "{\"userid\":\"1\",\"username\":\"yasir\"}"; user user= gson.fromjson(jsoninstring, user.class);

javascript - How to show upload indicator during upload? -

i'm using ng-file-upload upload image, can't find way add upload animation instead of image during upload process. there way it? i suggest using bootstrap or other css library has progress bar component. have these animations built in , easy set up. (see link above bootstrap's progress bar). you can find similar stack overflow post angularjs , bootstrap progress bars here . change bootstrap progress-bar width angularjs

retrieve data from json using javascript -

json: var obj = { "usa": { "latitude": 37.0902, "longitude": 95.7129 }, "japan": { "latitude": 36.2048, "longitude": 138.2529 } } how retrieve country , latitude , longitude data json , store them in different array(countryarr , latarr , longarr) this simple question. perhaps read here - http://www.w3resource.com/json/introduction.php var = obj.usa.latitude; alert(a)

Qt - H.264 video streaming using FFmpeg libraries -

i trying ip camera stream in qt widget application. first, connect udp port of ip camera. ip camera streaming h.264 encoded video. after socket bind, on each readyread() signal filling buffer received datagrams in order full frame. variable initialization: avcodec *codec; avcodeccontext *codecctx; avframe *frame; avpacket packet; this->buffer.clear(); this->socket = new qudpsocket(this); qobject::connect(this->socket, &qudpsocket::connected, this, &h264videostreamer::connected); qobject::connect(this->socket, &qudpsocket::disconnected, this, &h264videostreamer::disconnected); qobject::connect(this->socket, &qudpsocket::readyread, this, &h264videostreamer::readyread); qobject::connect(this->socket, &qudpsocket::hostfound, this, &h264videostreamer::hostfound); qobject::connect(this->socket, signal(error(qabstractsocket::socketerror)), this, slot(error(qabstractsocket::socketerror))); qobject::connect(this->socket, &qudp

arrays - Looping through filtered column cells: Excel VBA -

i have table of data headers going across top , left side. filtering each column, 1 @ time(starting @ column 2). want assign value(the header left) array each of rows still present after filtering. code, however, not pull filtered range, unfiltered range. ex: filtered range rows 1,4,8,9 , excel pulls 1,2,3,4. ideas how can modify code? constant = 0: = 1: o = 1 application.visible = true set ws_prods_with = sheets.add z = 3 lstcol1 ra_counter = 0: cp_counter = 0: counter = 0 redim prodwith(1 1) prodwith(1) = "" 'clearing out array ws_sel if (.autofiltermode , .filtermode) or .filtermode .showalldata 'turning off previous filter end if on error resume next .range(.cells(1, 1), .cells(counter, lstcol1)).autofilter field:=z, criteria1:="yes" set rngfilter_yes = intersect(.usedrange, .usedrange.offset(1), _ .columns(2)).specialcells(xlcelltypevisible) lstrow_yes = .cells(.rows.count, "a").end(xlup).row - 1 'l

html - Disable :hover CSS on Mobile -

i have following css defined on img elements on page. .my-image { width: 100% !important; height: auto; -webkit-transition: .5s ease; -moz-transition: .5s ease; -ms-transition: .5s ease; transition: .5s ease; } .my-image:hover { -webkit-transform:scale(1.5); -moz-transform:scale(1.5); -ms-transform:scale(1.5); transform:scale(1.5); } for reason, hover class activating on iphone anytime scroll past (that is, move finger along images scroll past them). there way can disable hover css mobile only? @media handheld { .my-image:hover { -webkit-transform: none; -moz-transform: none; -ms-transform: none; transform: none; } }

java - Prevent mouseExited from being called when exiting into a Popup -

i'm trying implement own tooltip. timer , mouse listeners (for moved , exited ). when mouse moved, timer reset, popup shows when mouse has been still. when mouse exits component, popup hidden. however, when popup shown @ cursor, mouse inside popup, mouseexited called. popup disappears, but, if mouse remains still, happens again, causing popup flicker. can prevented moving popup 1px over, mouse isn't in popup, doesn't solve whole problem, because moving mouse on popup makes disappear. my mcve : private static timer timer = new timer(100, new actionlistener() { @override public void actionperformed(actionevent e) { jpanel pop = new jpanel(new gridlayout(0, 3)); pop.setbackground(color.blue); // calculations similar happening, // because otherwise flicker fast demonstrate on screen (double = math.random() * 12; < 40; i++) { bufferedimage img = new bufferedimage(32, 32, bufferedimage.type_int_argb_pre);

jquery - How to check specific checkbox is checked or not -

i have below code need check if first 2 checkbox checked or not. i need check against id's. like how check if first 2 checkbox checked or not. <input type="checkbox" name="check1" id="check1id" tabindex="1" value="test" /> <input type="checkbox" name="check2" id="check2id" tabindex="2" value="test" /> <input type="checkbox" name="check3" id="check3id" tabindex="3" value="test" /> var boxes = $('.checkbox input'); if(boxes.length > 0) { if( $(':checkbox:checked').length < 1) { if($("#error-select").length == 0){ $("#error-checkbox").show(); } return false; } else{

woocommerce rest api - How to use rest_url_prefix filter in wordpress -

how can modify wordpress rest api endpoint custom api endpoints only? i'm using wc api 2.6 , not want modify endpoint them. want change request endpoints custom api. my api built on wc_rest_controller further extends wp_rest_controller class.

swift - How to move to the selected cell in UiCollectionView -

i'm newbie in swift , please bear me. i have created uicollectionview scrolls horizontally, question is: how can move selected icon programmatically? i have used didselectedpath , whats next? you need call scrolltoitematindexpath function: scrolls collection view contents until specified item visible. func scrolltoitematindexpath(_ indexpath: nsindexpath, atscrollposition scrollposition: uicollectionviewscrollposition, animated animated: bool) parameters indexpath the index path of item scroll view. scrollposition an option specifies item should positioned when scrolling finishes. list of possible values, see uicollectionviewscrollposition . animated specify true animate scrolling behavior or false adjust scroll view’s visible content immediately. check uicollectionview class reference more info.

HTML5 input type date disable dates before today -

is there way disable dates before today in html5 <input type="date"> ? tryed with: <input type="date" min="<?php echo $today; ?>"> works on desktop browsers...safari mobile still allow scrolling dates before. input date must in iso format (which supported mobile browsers). there no possible way pure html5 . but javascript, can like: <input name="settodaysdate" type="date"> and; var today = new date().toisostring().split('t')[0]; document.getelementsbyname("settodaysdate")[0].setattribute('min', today); this little script change min today's date in iso format. live example here: jsfiddle

Process Multiple date format in apache-pig -

i having muliple dates in different formats in pig like mm/dd/yyyy hh:mm:ss.sss aa mm-dd-yyyy hh:mm:ss.sss aa can more.. for single date tried , works fine. tounixtime(todate(dateandtime,'mm/dd/yyyy hh:mm:ss.sss aa'))as unix_datetime is there way in pig can solve muliple date formats? or have write java udf i referring how parse dates in multiple formats using simpledateformat udf.

swift - Dequeueing TableViewCells from Storyboard Prototype cells? -

i have defined tableview in code within main viewcontroller class. have added main view , defined custom tableviewcell in swift file. have setup basic app displaying datasource information in single textlabel comes default subclassed uitableviewcell . however, want design more complicated ui in interface builder. viewcontroller defined in main storyboard. how sync pre-existing tableviewcell prototype cell view element in storyboard? filling in cell identifier , custom class class, calling dequeuereusablecellwithidentifier identifier , casting result custom type not seem give me cell properties loaded in storyboard. can show code using? it should like: func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell { let cell = tableview.dequeuereusablecellwithidentifier("reuseidentifier", forindexpath: indexpath) as! customcell return cell }