Posts

Showing posts from September, 2015

php - Cannot obtain page access token through an app that is granted the manage_pages permission -

i'm trying develop php application let me make new posts on pages automatically, through cronjob, while offline , not logged facebook @ all. i'm aware offline_access permission has long been gone, removal of offline_access permission article states following: scenario 5: page access tokens when user grants app manage_pages permission, app able obtain page access tokens pages user administers querying [user id]/accounts graph api endpoint. migration enabled, when using short-lived user access token query endpoint, page access tokens obtained short-lived well. exchange short-lived user access token long-lived access token using endpoint , steps explained earlier. using long-lived user access token, querying [user id]/accounts endpoint provide page access tokens not expire pages user manages. apply when querying non-expiring user access token obtained through deprecated offline_access permission. ... made me think automated php solu

angularjs - How do I pass and then access an object inside a directive template (directive uses isolate scope)? -

i have collection of navbaritems , presenting them this: <a data-role="button" data-iconpos="notext" ng-show="navbaritems['search'].show" ng-click="navbaritems['search'].click()" data-icon="{{navbaritems['search'].icon}}">{{navbaritems['search'].title}}</a> i'm repeating code , changing 'type', i'd create directive template , call this: <navbaritem type="search"></navbaritem> i've tried passing attribute isolated scope can't navbaritems once in directive. as mentioned in comment above, since isolate scope being used/created, other data isolate scope requires need passed directive via additional attributes on same element. in case navbaritems needs specified: <navbaritem type="search" items="navbaritems"></navbaritem> since navbaritems object (not string), = syntax should used in isolate

javascript - RegEx to match only numbers incorrectly matching -

i'm trying use regular expression in javascript match number or number containing decimal. regular expression looks [0-9]+ | [0-9]* \. [0-9]+ . however, reason '1a'.match(/^[0-9]+|[0-9]*\.[0-9]+$/) incorrectly finds match. i'm not sure part of expression matching a . the problem alternation. says: ^[0-9]+ # match integer @ start | # or [0-9]*\.[0-9]+$ # match decimal number @ end so first alternative matches. you need group alternation: /^(?:[0-9]+|[0-9]*\.[0-9]+)$/ the ?: optimisation , habit. suppresses capturing not needed in given case. you away without alternation well, though: /^[0-9]*\.?[0-9]+$/ or shorter: /^\d*\.?\d+$/

c - segmentation fault after waking a process -

hey i'm writing simple shell on getting sigstsp pause process , continue on getting more commands. saves suspended process in job list. when try waking suspended process segmentation fault, after (ex)suspended process deals sigcont signal. this signalhandler void signalhandle(int sig) { int i,pid,id; sigset_t mask_set; sigset_t old_set; signal(sigtstp,signalhandle); sigfillset(&mask_set); sigprocmask(sig_setmask,&mask_set,&old_set); //handle sigtstp **if (sig == sigtstp)**{ gpid=getpid(); pid=fork(); if (pid==-1){ perror("(ctrl-z)(signal error)(fork)"); } else if (pid==0){ susp_bg_pid=gpid; i=0; while (getpid(jobslist,i)!=-1){ i=i+1; } id=getid(&jobslist,gpid); if (id==-1){ insertelem(&jobslist, l_fg_cmd, i, gpid, 1); } else{ delpid(&jobslist,gpid); insertelem(&jobslist, l_fg_cmd, id, gpid, 1)

assembly - Compiling ASM with C and having result "NaN" or "-NaN". Square Root Function -

i had errors compiling earlier after working on them, got no errors/warnings. altho result given nan. here code: c: iclude <stdio.h> extern float wynik1 (int a, int b, int c); extern float wynik2 (int a, int b, int c); int = 2; int b = 2; int c = 2; int main () { float licz1 = 0; float licz2 = 0; licz1 = wynik1(a, b, c); licz2 = wynik2(a, b, c); printf("roots : %f oraz %f \n", licz1, licz2); return 0; } asm1: sysexit = 1 sysread = 3 syswrite = 4 stdout = 1 exit_success = 0 stdin = 0 .align 32 .data a: .int 2 b: .int 2 c: .int 2 buf: .float 0 x1: .float 0 cztery: .float 4 dwa: .float 2 .text .global wynik1 wynik1: xor %eax, %eax xor %ebx, %ebx xor %ecx, %ecx pushl %ebp movl %esp, %ebp movl 8(%ebp), %ecx movl 12(%ebp), %ebx movl 16(%ebp), %eax pushl %eax pushl %ebx pushl %ecx movl %eax, movl %ebx, b movl %ecx, c finit fld fld c deltaa1: fmulp fld cztery fmulp fld b fld b fmulp fsubp pierwiastek1: fsqrt fld b fchs fsubp fstp buf fld fld dwa

angularjs - Using a child controller from another module -

i've defined module , made main module app using ng-app directive. added 2 controllers main app using angular.module('myapp').controller(). 1 of controllers has page wide scope whereas other controller child controller. what i'm trying include controller belongs module (not main myapp module), can't figure out. not want globally namespace controllers. anyone know how this? here have far: <!doctype html> <html lang="en" data-ng-app='myapp' data-ng-controller='myapp.maincontroller'> <head> <meta charset="utf-8"> <title>untitled</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> $(function() { var app, module; //create 2 modules, 1 of used app base app = angular.module('myapp', []); module = angular.module('othermodule', []); //create main controller m

image uploading - pictures uploaded from android app to server aren't accessible from the browser (not consistent) -

i developing android app captures pic camera or gallery , uploads server while storing link url path in db. i using phonegap upload pics , see files ( jpg) uploaded server ( free web hosting) . , can view them managing consul of hosting web-server. the strange problem encountering that i cannot access of pics browser typing full path. this not consistent since noticed pics accessible through url path while others not ( pics in gallery taken devises camera) i cannot seem find reason the file names given 4032.jpg ( gallery) or longer 1123156984.jpg if loaded captured picture thought reasone might related digits ocationly said able view pic through browser. as amajoritu not able view pics typing url path . have mention if uploading pics pc ( localhost server) hosting server problem doesn't seem exist. the code using upload 1 taken zachary can 1 have idea seems problem ?

python - Prettytable 0.7.2 HTML Table Not Working -

so, trying prettytable 0.7.2 working html table. can't seem working. using following: from prettytable import from_html html = "<table><tr><th>h1</th></tr><tr><td>v1</td></tr></table>" table = from_html(html) print (table) which results in: [<prettytable.prettytable object @ 0x90556ec>] i can table work using other methods, can't seem tackle html table method. i'm not sure if doing wrong or missing something. if shed light on issue appreciated. the problem is, table isn't prettytable object, a list containing single prettytable object . calling from_html function return list containing 1 prettytable per table tag encountered in html string. you want do: print table[0] which returns: +----+ | h1 | +----+ | v1 | +----+

c# - automapper: skipping/ignoring nested types -

i'm trying create map between domain object , viewmodel support use case feels quite common. fact can't find solution makes me think i'm approaching problem incorrectly. here's psuedo code represents source , destination types: public class domainclass { public nesteddomainclass1 nesteddomainclass1{ get; set; } } public class nesteddomainclass1 { public nesteddomainclass2 nesteddomainclass2 { get; set; } } public class nesteddomainclass2 { public string propertya { get; set; } public string propertyb { get; set; } public string propertyc { get; set; } } public class domainviewmodel { public string propertya { get; set; } public string propertyb { get; set; } public string propertyc { get; set; } } as can see, domainviewmodel maps domainclass.nesteddomainclass1.nesteddomainclass2 . however, reasons aren't entirely relevant, can't create mappi

php - Trouble importing file with CakePHP -

i'm trying import phpquery 1 of controllers i'm getting errors. saved in vendors folder , plugins folder. i've tried adding following itemscontroller , none have worked include_once(__dir__.'/vendors/phpquery.php'); app::uses('phpquery', 'vendor'); app::import('phpquery', 'vendor'); all of result in either error of not finding method or error: application trying load file phpquery plugin i tried placing in plugins folder , i'm having luck. importing vendor files (especially if not stick regular conventions, one class per file ), requires variants of 'normal' app::import() this section in documentation describes variants: loading vendor files i tested one, , worked without problems; app::import('vendor', 'phpquery'); (loads 'app/vendor/phpquery.php')

error catastrophic failure installshield 2012 -

i using installshield le 2012 visual studio create installable file problem written in vb on .net. while problem requires third party driver installed first. added run custom action during installation "before first dialog". however, every time tried install it, shows "error: catastrophic failure", have no idea means. mean process of installing driver take time? or there resource collision problem between these two? how solve problem? needs help. the os using windows 7 ultimate. you need support third party driver vendor. custom action calling out of process code installshield has no control over. don't know driver vendor, name , version or how calling there's nothing can here. fwiw, installshield , windows installer has support using difx install drivers based on .inf files. isn't supported in crippled installshield limited edition.

facebook - Getting this error after months of no problems - redirect_uri not owned by application -

i had problem when started facebook integration of our site. after doing searching, found solution , fixed it. now, few months later, has stopped working. nothing changed in either javascript code or app settings on facebook developers site. once again set searching, , found same answers before: site url must match redirect_uri etc. i have app domain: "domain.com" , site url: "http://www.domain.com" error given: api error code: 191 api error description: specified url not owned application error message: redirect_uri not owned application. i'm @ loss has happened. has facebook changed api? (i did check documentation, , it's still same). any appreciated. javascript code below: var publish = { method: 'feed', redirect_uri: 'http://www.domain.com', link: 'http://www.domain.com', picture: 'http://pathtoimage/logo.png', name: 'name', caption: 'title', descript

c# - Multithreading a web scraper? -

i've been thinking making web scraper multithreaded, not normal threads (egthread scrape = new thread(function);) threadpool there can large number of threads. my scraper works using for loop scrape pages. for (int = (int)pagesmin.value; <= (int)pagesmax.value; i++) so how multithread function (that contains loop) threadpool? i've never used threadpools before , examples i've seen have been quite confusing or obscure me. i've modified loop this: int min = (int)pagesmin.value; int max = (int)pagesmax.value; paralleloptions poptions = new paralleloptions(); poptions.maxdegreeofparallelism = properties.settings.default.threads; parallel.for(min, max, poptions, =>{ //scraping }); would work or have got wrong? the problem using pool threads spend of time waiting response web site. , problem using parallel.foreach limits parallelism. i got best performance using asynchronous web requests. used semaphore limit number of concurrent requ

ruby on rails - how could i flash a message to users before a deploy? -

using capistrano deploys, possible flash message users on when deploy has started, or before know site slow , unresponsive few minutes? you can use capistrano hooks execute rails runner, hook application , globally display message. you need code global message logic application, , accesses via rails runner command @ appropriate hook points within capistrano.

html - Stylizing pages that have PHP -

i'm trying create user registration form sends confirmation email user after sign up, , when host site locally, works fine. however, when host on web (hostgator), following error: warning: session_start() [function.session-start]: cannot send session cache limiter - headers sent i know part has been answered many times before - , yes, have removed text area above php code , error goes away. however, if can't put above this, how can use code on site , still stylize page? want use css style sheet right can't use in or declare doctype without seeing error. i've tried creating stylized html file , using php include function include php code, doesn't work. what can stylize pages , still use php code on same page without errors? also, why code working on local server, not when upload on hostgator? below php code i'm using page that's causing errors. ideas? index.php <!doctype html> <html> <head> <meta charset="u

.net - How to Join multiline strings from left to right -

Image
i have array 3 entries. first entry of array multiline string: "my dog " second entry too: " dont " and hird entry too: " ... die! " now how can combine multiline strings obtain joined string left right this?: my dog dont that... die! what tried: richtextbox1.text = string.join(myarray(1), myarray(2)) well example more reallistic, need combine multiline strings (which ascii letters) stored in array, when try join obtain string joined down: the code i've used : richtextbox1.text = string.join(" ", characters(70), characters(77), characters(70), characters(76)) this should need. key creating list of lists , splitting on newline character on each item in original array. this should work arbitrary number of strings, each string must have same number of newline characters break on. for example: "yo \ndon't kill \nman!" "dude! \nme bro!

geolocation - Nokia HERE Map using Google Latitude -

i trying parse , add google latitude kml marker nokia here map. works locally on laptop in ie 9, doesn't add marker in safari 5.7, chrome 27 (locally or on web server). ideas? kml.parsekml("http://latitude.google.com/latitude/apps/badge/api?user=-1099057214648547758&type=kml"); if kml being loaded successful on browsers not others, due browser in question kindly trying prevent cross-scripting domain attack. you have three options host kml file in same domain javascript reading file - e.g. if own example.com , javascript should hosted on example.com , kml hosted on example.com set kml parser retrieve file example.com , use proxy solution such php example retrieve file elsewhere enable cors on server hosting kml file, , load kml using ajax followed parse() method shown in example if kml never loaded successfully, should check see whether file valid , , indeed whether html displaying map syntactically correct.

SQL Server : left join results in fewer rows than in left table -

i using sql server (i believe 2005). i have tablea has 2 columns , 439 rows (each row unique). +----------+ |id | name | +----------+ i have tableb has 35 columns , many hundreds of thousand rows (each row unique). +------------------------------------------------------------------------------+ |date | id | name | blah1 | blah2 | ... | hour1 | hour2 | hour3 | ... | hour24 | +------------------------------------------------------------------------------+ each row in tableb has hourly observations , other house keeping information. testing purposes interested in today's date i.e 4/19/2013. if do: select count(*) tableb date = '4/19/2013 12:00:00 am' i 10526, correct there 10526 distinct locations there hourly observation data each day. i want left join tablea , tableb on a.id = b.id , should produce result has 439 rows. unfortunately, result has 246 rows. how can be? isn't left join suppose return rows in tablea regardless of whether there m

Screen transition effects android -

i trying left right swipe transition of button click in screen 1 , right left transition screen 2 screen one. following codes screen 1: intent intent = new intent(customactivitytransitionactivity.this, secondactivity.class); overridependingtransition(r.anim.slide_in_right, r.anim.slide_out_left); startactivity(intent); screen 2: intent intent = new intent(secondactivity.this, customactivitytransitionactivity.class); overridependingtransition(r.anim.slide_in_left, r.anim.slide_out_right); startactivity(intent); the respective anims give below, slide_in_left <set xmlns:android="http://schemas.android.com/apk/res/android" android:shareinterpolator="false" > <translate android:duration="200" android:fromxdelta="-100%" android:fromydelta="0%" android:toxdelta="0%" android:toydelta="0%" /> </set> slide_out_left <set xmlns:android=&

Combine two MYSQL table with same column Name -

i have 2 table table 1 scheduletime id | edition | time | 1 | 1 | 9:23am | 2 | 2 | 10:23am| table 2 actualtime id | edition | time | 1 | 1 | 10:23am | 2 | 2 | 11:23am | i want result caption | edition | time | scheduleed | 1 | 9:23am | actual | 1 | 10:23am | scheduleed | 2 | 10:23am | actual | 2 | 11:23am | how can in mysql ? select caption, edition, time ( select 'scheduled' caption, edition, time scheduletime union select 'actual' caption, edition, time scheduletime ) subquery order edition, field(caption, 'scheduled', 'actual') sqlfiddle demo sqlfiddle demo ( without using field() , plain order by...desc ) output ╔═══════════╦═════════╦═════════╗ ║ caption ║ edition ║ time ║ ╠═══════════╬═════════╬

c++ - argument list for class template "Complex" is missing -

i have isequalto function comparison of several data types through use of templates. when first had in main.cpp file well, once split complex class it's header , it's cpp file i'm getting error stating, "argument list class template "complex" missing". of course check default constructor class complex , here is: **main.cpp** #include <iostream> #include <string> objects #include "complex.h" using namespace std; template <class t> class complex<t> bool isequalto(t a, t b) { if(a==b) { cout << << " equal " << b << endl; return true; } else cout << << " not equal " << b << endl; return false; } int main() { //comparing complex class complex<int> complexa(10, 5), complexb(10, 54), complexc(10, -5), complexd(-10, -5); //creating complex class objects cout << endl << endl << "

c++ - Cannot compile, Lvalue required, in function main -

i want compile this, gives me error, change quotes, there error in header file, please let me know #include<iostream.h> #include<conio.h> void main() { char st[20]; cin>>st; cout<<st<<endl; if (st = 'a') cout<<"this a"; if (st = 'b') cout<<"this b"; getch(); } if (st = 'a') if (st = 'b') in both above lines l-value(left value) 'st' point beginning of array , address cannot changed. that's why error l-value in compilation. change if conditions equality(==) operator instead of assignment(=) , dereference st value in beginning. if (*st == 'a') if (*st == 'b')

ios - RACSignal interval not work immediately -

i'm trying use racsignal class's interval method of reactivecocoa. following code works every second after 1 seconds. want works , every second. what's best way? @weakify(self); [[[racsignal interval:1.0] takeuntilblock:^bool(id x) { return [aclass count] == 0; }] subscribenext:^(id x) { dispatch_async(dispatch_get_main_queue(), ^{ @strongify(self); nsuinteger count = [aclass count]; self.title = [nsstring stringwithformat:@"%u", count]; }); } completed:^{ dispatch_async(dispatch_get_main_queue(), ^{ @strongify(self); self.title = @""; }); }]; i believe you're looking -startwith: . [[[racsignal interval:1] startwith:nsdate.date] takeuntilblock:^(id _) { // ...

c# - How to send a single quote to an input element with Selenium? -

when send single quote sendkeys() method, selenium sends 2 single quotes instead. using c# chrome driver. here code: iwebdriver driver = new chromedriver(); var element = driver.findelement(by.id("uid")); element.clear(); element.sendkeys("admin'--"); the textbox on tested web page receives following value: admin''-- how send single quote element? the code sample sent works me. i tried firefoxdriver: iwebdriver driver = new firefoxdriver(); driver.navigate().gotourl("http://www.google.com"); var element = driver.findelement(by.name("q")); element.clear(); element.sendkeys("one quote: ', double quote \""); and output in google search box is: one quote: ', double quote " try start simplest example, , insert 1 quote by: "'"

xcode - iPhone App Crashes When trying to play video -

i'm trying simple view based app play video, crashes, heres code, - (ibaction)playbutton:(id)sender { nsstring *stringpath = [[nsbundle mainbundle] pathforresource:@"1" oftype:@"mov"]; nsurl *url = [nsurl fileurlwithpath:stringpath]; mpc = [[mpmovieplayercontroller alloc]initwithcontenturl:url]; [mpc setmoviesourcetype:mpmoviesourcetypefile]; [[self view]addsubview:mpc.view]; [mpc setfullscreen:yes]; [mpc play]; } @end and here takes me in xcode when fails // // main.m // video_play // // created nathaniel harman on 20/04/2013. // copyright (c) 2013 machupicchumobile. rights reserved. // #import <uikit/uikit.h> #import "videoplayappdelegate.h" int main(int argc, char *argv[]) { @autoreleasepool { return uiapplicationmain(argc, argv, nil, nsstringfromclass([videoplayappdelegate class])); } } try , nsstring *audio=[[nsbundle mainbundle]pathf

How do I add javadocs for restlet using Maven? -

i've created maven project using m2eclipse plugin, i'am able import dependencies through following code, <repositories> <repository> <id>maven-restlet</id> <name>public online restlet repository</name> <url>http://maven.restlet.org</url> </repository> </repositories> <dependencies> <dependency> <groupid>junit</groupid> <artifactid>junit</artifactid> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupid>org.restlet.jse</groupid> <artifactid>org.restlet</artifactid> <version>2.1.2</version> </dependency> however, want configure javadocs downloaded dependecies can check documentation while working. how achieve object? after setting pom.xml, right click on project -> maven

Embedded Linux poll() returns constantly -

i have particular problem. poll keeps returning when know there nothing read. so setup follows, have 2 file descriptors form part of fd set poll watches. 1 pin high low change (gpio). other proxy input. problem occurs proxy input. the order of processing is: start main functions; poll; write data proxy; poll break; accept data; send data on spi; receiving slave device, signals wants send ack, dropping gpio low; poll() senses drop , reacts; infinite pollins :( if have no timeout on poll function, program works perfectly. moment include timeout on poll. poll returns continuously. not sure doing wrong here. while(1) { memset((void*)fdset, 0, sizeof(fdset)); fdset[0].fd = gpio_fd; fdset[0].events = pollpri; // pollpri - there urgent data read fdset[1].fd = proxy_rx; fdset[1].events = pollin; // pollin - there data read rc = poll(fdset, nfds, 1000);//poll_timeout); if (rc <

javascript - Grab Data From Website -

Image
i create javascript code grab data website , put .txt file, maybe if can converted xml file better if possible.? if not javascript else fine. i wish grab price , item name , i'm not sure on how that. website http://www.bigw.com.au/electronics/computers-office/computer-accessories/webcams if need read source help. rip website client-side browser , javascript? no problem. yahoo yql... (instead of php? proxy serverside script).. i have sneaky suspicion not own/control external link site, getting content different site, fall under cross-domain security restrictions (to modern browser). so in order regain 'power user', use http://query.yahooapis.com/ . example 1: using sql-like command: select * html url="http://stackoverflow.com" , xpath='//div/h3/a' the following link scrape newest questions (bypassing cross-domain security bull$#!7): http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20%0awhere%20url

c++ - how to write data TINYXML2 on IOS -

my test.xml this: <?xml version="1.0"?> <!doctype play system "play.dtd"> <data> <currentlevel>5</currentlevel> <bestscorelv1>1</bestscorelv1> <bestscorelv2>2</bestscorelv2> </data> <dict/> my code here: std::string fullpath = ccfileutils::sharedfileutils()->fullpathfromrelativepath("text.xml"); tinyxml2::xmldocument doc; doc.loadfile(fullpath.c_str()); tinyxml2::xmlelement* ele = doc.firstchildelement("data")->firstchildelement("bestscorelv2")->toelement(); ele->setattribute("value", 10); doc.savefile(fullpath.c_str()); const char* title1 = doc.firstchildelement("data")->firstchildelement("bestscorelv2")->gettext(); int level1 = atoi(title1); cclog("result is: %d",level1); but value of bestscorelv2 when output 2. how can change , write data xml? in tinyxml2 text r

outlook - HTML Emails: fallback for mso conditional? -

if you're me, eye twitching end of reading this. don't blame you. our client has requested develop responsive html email template, 2 specifications: using few images possible using many "fancy css-enabled features" possible. mostly, means rounded corners on boxes. this question executing rounded corners. gmail , apple support css rounded corners, , outlook requires vector graphics. remaining platforms, they're ok using square edges. here's how we're detecting , executing outlook: <!--[if mso]><v:shape>...</v:shape><![endif]--> works charm, outlook 2000. problem is, can't figure out how create fallback. intuition says this: <!--[if !mso]>...<![endif]--> but gets ignored outright comment other email clients, , corners missing boxes altogether. ask you, fine members of community: possible deploy markup platforms except mso? perhaps there's more clever way accomplish haven't considered? or

couchdb - Hanging replications on Cloudant -

in last months, we've been charged lot of http requests not expecting on cloudant. looking @ couchdb console locally, found out each continuous replication request issued every 5 seconds or so. i have stopped continuous replications find in futon , did same every cloudant accounts have. looking @ cloudant's dashboard, have seen reduction of requests (many thousands), did not went down reasonable level. there must continuous replications left, cannot find them. how can find , stop remaining replications? to identify continuous replications may hidden user, best way query curl command, invoke _active_tasks, , apply jq filter display tasks of type "replication". that say, in command line, run command of following form: curl 'https://username:password@username.cloudant.com/databasename/_active_tasks | jq 'map(select(.type == "replication"))' the same methodology can applied retrieve other active tasks (view_compaction, database

How to clear the system clipboard in Java? -

how can clear system clipboard in java? have tried toolkit.getdefaulttoolkit().getsystemclipboard().setcontents(null, null); but had thrown npe : exception in thread "awt-eventqueue-0" java.lang.nullpointerexception: contents @ sun.awt.datatransfer.sunclipboard.setcontents(sunclipboard.java:98) you can create special transferable explicitly contains no data, detailed in blog post : clipboard.setcontents(new transferable() { public dataflavor[] gettransferdataflavors() { return new dataflavor[0]; } public boolean isdataflavorsupported(dataflavor flavor) { return false; } public object gettransferdata(dataflavor flavor) throws unsupportedflavorexception { throw new unsupportedflavorexception(flavor); }

How can I instantiate and add to a class inside a foreach loop in C# -

i have code want use log error messages. made 2 classes hold messages: public class httpstatuserrors { public httpstatuserrors() { this.details = new list<httpstatuserrordetails>(); } public string header { set; get; } public ilist<httpstatuserrordetails> details { set; get; } } public class httpstatuserrordetails { public httpstatuserrordetails() { this.details = new list<string>(); } public string header { set; get; } public ilist<string> details { set; get; } } i think way not 100% sure , welcome suggestions. what in first class store header in example "validation messages". in detail object store header showed entity error , in details store validation errors. what confused on how should instantiate classes. have done far. think correct. how can add details need add: catch (dbentityvalidationexception ex) { var msg = new httpstatuserrors(); msg.header = "validat

php - reg exp match everything inside curly braces -

i have php code , want match inside curly braces {} $sentence= "this {is|or|and} {cat|dog|horse} {kid|men|women}"; preg_match("/\{.*?\}/", $sentence, $result); print_r($result); but output: array ( [0] => {is|or|and} ) but need result this: array ( [0] => is|or|and [1] => cat|dog|horse [2] => kid|men|women ) what regular expression should use? use preg_match_all instead? preg_match_all("/\{.*?\}/", $sentence, $result); if don't want braces, can 2 things: capture parts inside braces , use $result[1] them hamza correctly suggested: preg_match_all("/\{(.*?)\}/", $sentence, $result); print_r($result[1]); or use lookarounds (they might bit difficult understand however): preg_match_all("/(?<=\{).*?(?=\})/", $sentence, $result); print_r($result[0]); note can use [^}]* instead of .*? , considered safer.

ruby on rails - Is it possible to re-use sunspot searchable declarations from other models? -

i'm using sunspot fulltext searches in customized spree webshop project. there products, extensively indexed: class product searchable text :description ... lots of other declarations end end i need index orders, (via other models, don't think important), have_many products: class order has_many :products end the question is: want orders searchable via products, using same indexed attributes. want stay dry , not add variations of declarations on product new searchable block on order, rather "orders searchable via products". possible somehow ? docs sunspot don't mention this. edit: "apneadiving" suggested putting declarations in sort of shared module , re-using way. might mistaken, think can't work because sunspot dsl refers current model, declarations product not work on order. for example, if apply searchable block example above in order, instruct sunspot index order on description, doesn't have, , doesn't m

sql server - Distinct records from multiple queries -

this question has answer here: merge multiple queries excluding common results 1 answer data : --table 1 : id zonename ----------- -------- 20011 name1 10027 name1 20011 name1 20011 name1 20011 name1 20074 name1 20011 name2 20011 name2 10059 name3 20011 name2 query : select top 2 [id] table1 -- first query zonename = 'name1' union select top 1 [id] table1 -- second query zonename = 'name1' union select top 1 [id] table1 -- third query zonename = 'name1' result : id ----- 20011 expected result : 20011 10027 20074 from above query need 3 results each query not overlap each other, in case expected result should contain top 2 query 1 i.e. 20011 , 10027 , next top 1 should exclude 2 results , return 20074 query 2. note : have used singl

css - How do I change the position of an image without it affecting the text to it's left? -

code: <div class="container_bottom_tip"> <div class="container_bottom_desc">this text <img class="browser_button_img" src="images/something.png"> </div> </div> .container_bottom_tip { text-align: center; } .container_bottom_desc { color: #333; } using code above want move image bit. when margin-top on image drags text "this text" it. what can move image or down without affecting positioning of text "this text?" you this: .browser_button_img { position: relative; top: -10px; } relative positioning allow move element relative have been without affecting other elements' reflow. unlike absolute positioning, relative allows maintain normal space taken element.

Java: Difference between two dates spanning over months -

i have following code gets me difference between 2 days (in days, hours, minutes, seconds): simpledateformat format = new simpledateformat("yyyy-mm-dd hh:mm:ss"); date d1 = format.parse(starttime); date d2 = format.parse(endtime); long diff = d2.gettime() - d1.gettime(); long diffseconds = diff / 1000 % 60; long diffminutes = diff / (60 * 1000) % 60; long diffhours = diff / (60 * 60 * 1000) % 24; long diffdays = diff / (24 * 60 * 60 * 1000); system.out.println("start: " + starttime); system.out.println("end: " + endtime); system.out.println(diffdays + " days, " + diffhours + " hours, " + diffminutes + " minutes, " + diffseconds + " seconds"); however, not work when dates cross month, example: start: 2013-07-31 10:15:01 end: 2013-08-01 11:22:33 -29 days, -22 hours, -52 minutes, -28 seconds start: 2013-05-31 10:15:01 end: 2013-08-01 11:22:33 -29 days, -22 hours, -52 minutes, -28 seconds is possible intelli

c# - How to detect when Windows 8 goes to sleep or resumes -

i have app keeps connection alive server, if user walks away , tablet goes sleep, handle disconnect gracefully, , log in when user wakes tablet. i've tried in putting following code in connection class, never fired. application.current.suspending += this.onappsuspending; application.current.resuming += this.onappresuming;; for desktop apps, can use systemevents.powermodechanged event know if windows going sleep state. don't know if works tablets too, can try it... from msdn: • resume operating system resume suspended state. • statuschange power mode status notification event has been raised operating system. might indicate weak or charging battery, transition between ac power , battery, or change in status of system power supply. • suspend operating system suspended. systemevents.powermodechanged += onpowerchange; private void onpowerchange(object s, powermodechangedeventargs e) { switch ( e.mode ) { case powermodes.resume:

How to read 1 line of a text file in server with Android and save its content in a varable? -

i want when app opened check file in server example : mysite/last.txt and in file put last app version : 3.3 i want every time user opens app, first check file , check if app version lower version put in text file in server, show dialog or toast message user new version if app example : "a new version available" how can this? sorry english, english not native language! you download files content using normal http connection: how use simple http client in android? but why should want this? play store keeps track of versions , show message if theres update app!

c# - Regex: spliting first, last name into comma-separated list eg "john smith Jr." to "john", "smith", "Jr." -

i using c# (asp .net) , have text box accepts name entries performs query on db. i want use in clause obtain possible values in c# page 1 string e.g 'john smith' use regex break 'john','smith' string text1 = "'"+regex.replace(text,@"[^a-za-z0-9\-\.\']+","','")+"'"; however names 'john smith jr.' or 'bruce o'brien', fails (due special characters) what missing in regex? thanks regex not easiest way this. instead, i'd recommend string.split method , works defining whitespace characters between words are: string fullname = "bruce o'brien"; string[] names; char[] separators = new char [] {' '}; // space character, in case names = fullname.split(separators); once you've got array of names, it's easy turn csv string if that's need.

jdbc - Get the current date in java.sql.Date format -

i need add current date prepared statement of jdbc call. need add date in format yyyy/mm/dd . i've try with dateformat dateformat = new simpledateformat("yyyy/mm/dd"); date date = new date(); pstm.setdate(6, (java.sql.date) date); but have error: threw exception java.lang.classcastexception: java.util.date cannot cast java.sql.date is there way obtain java.sql.date object same format? a java.util.date not java.sql.date . it's other way around. java.sql.date java.util.date . you'll need convert java.sql.date using constructor takes long java.util.date can supply. java.sql.date sqldate = new java.sql.date(utildate.gettime());

html - javascript onclick() event not working in chrome for text within div container -

the following not working in chrome, works in ie , firefox: <div id="removefield" onclick="remove(0);" style="cursor: pointer;">-remove</div> the remove() function not called. idea why? remove member function of dom elements in chrome. in console, can see running: > document.createelement("div").remove function remove() { [native code] } in inline event handler, properties (including member functions) of element available top-level variables. inline code run inside with(thiselement) block. in context of inline event code, identifier remove refers remove method of element, not global-scope remove function. change function name doesn't collide method names of element, or use window.remove explicitly. ( modified this previous answer of mine handling similar case start method in ie. )

Copy object properties in JavaScript -

i have custom object definitions like: var class1 = function () { this.value = ''; }; var class2 = function () { this.data = ''; }; class1.prototype = { setobject: function () { (var prop in this){ if (typeof obj[prop] != 'undefined') this[prop] = obj[prop]; } } } class2.prototype = { setobject: function () { (var prop in this){ if (typeof obj[prop] != 'undefined') this[prop] = obj[prop]; } } } is there way have method setobject default clases? is better (simulate) inherit function object type in javascript or better use global function or define 1 one? if you're going using library such jquery or underscore, you'll have access resilient extend method (see $.extend , , _.extend ), there's no reason reinvent wheel on these custom object types. otherwise, can have class1 , class2 inherit common base class: functi

javascript - Three.js Particles of various sizes -

i'm new three.js , trying figure out best way add 1000 particles each being different size , color. texture each particle created drawing canvas. using particlesystem particles same color , size. creating particlesystem each particle inefficient. there efficient way handle this? the best way go this, in experience, create customized shader material; can include attributes, properties vary particle particle. shader code this: vertex shader: attribute vec3 customcolor; attribute float customsize; varying vec3 vcolor; void main() { vcolor = customcolor; // set color associated vertex; use later in fragment shader vec4 mvposition = modelviewmatrix * vec4( position, 1.0 ); gl_pointsize = customsize * ( 300.0 / length( mvposition.xyz ) ); gl_position = projectionmatrix * mvposition; } fragment shader: uniform sampler2d texture; varying vec3 vcolor; // colors associated vertices; assigned vertex shader void main() { // calculates color particle

c# - what is the type of TrackableCollectionOfMyObjectNamexSjLehPL coming from EF4(entity framework)- Mvvm-WPf -

Image
i have 2 objects, lets say, country , city- have 1 many relation, country --> id, name city--> id, countryid, city name in view model, country list( perfect), however, country.cities in type of trackablecollectionofcityxsjlehpl although service reference configuration, collection type set system.collections.generic.list. in user interface, there grid view shows list of countries binded to countrylist view model, , gridview binded selectedcountry.cities it working, when try add new city user clicks button , command in view model like: city newcity= new city(); selectedcountry.cities.add(newcity), notifyproperychanged(selectedcountry) i expect added in grid view, right?? no! not being add city grid view, when sort clicking column, refreshes , see newly added city! i think should implement collectionchanged- because changing part inside list of county, since trackablecollectionofcityxsjlehpl , can't that, , there no information type, comes not.... i don

Drupal Commerce KickStart : Disable Example Shipping method -

please tell me how remove example shipping method. if disable module, other shipping methods don't work. there no option disable or delete this. option 'configure component' go shipping services page (admin/commerce/config/shipping/services/flat-rate) , delete example shipping method(s).

html/jquery multiple step form - go to next step depending on which radio button was selected -

i'm new jquery , need form, single form broken in multiple steps (7). in first step (see code below) have 5 radio buttons: school, friends, home , health, , activity. i'm trying achieve if user selects radio button school , clicks "next" button show div containing questions related school, if chooses friends show div friends related questions, , on... subject specific divs hidden on document load. please nice, newbie here. on appreciated :) <div class="form"> <h2>what interests you? (select one)</h2> <label class="val" style="width:250px;color:red;">please select one</label><br> <input type="radio" id="school" name="path" value="school" /> school <br> <input type="radio" id="home" name="path" value="home" /> home <br> <input type="radio" id=&quo

html - Undefined index: image in C:\wamp\www\netupdate.php on line 21 -

i facing weird problem. here file upload snipped of form through trying upload image server <input type="file" name="image" id="image"> and getting error: undefined index: image in c:\wamp\www\netupdate.php on line 21 my upload script following // file upload scrpt $name= $_files['image']['name']; $tmp_name = $_files['image']['tmp_name']; $type = $_files['image']['type']; $size = $_files['image']['size']; $pathandname = "file:///c:/wamp/www/upload/networking/".$name; $moveresult = move_uploaded_file($tmp_name, $pathandname); now weird portion other parameters being accepted in php script other image, writing database , giving success message portion giving errors , weirder part similar script working in other mysql table guess there nothing wrong in php_ini. you missing enctype="multipart/form-data" on <form> element.