Posts

Showing posts from March, 2014

c# - Lock and do all work, or release and grab only when necessary? -

which of these 2 alternatives better one? locking outside loops? lock (_worklock) { foreach (var resultobject in getobjecttask.result) { foreach (var key in resultobject.keys) { string value = resultobject.getvalue(key); _lockedobject.dosomething(key, value); } } } or locking when locked object accessed? foreach (var resultobject in getobjecttask.result) { foreach (var key in resultobject.keys) { string value = resultobject.getvalue(key); lock (_worklock) _lockedobject.dosomething(key, value); } } there can potentially 5-10 simultaneous operations wanting @ same time. here's surrounding code: var tasks = provider in _objectproviders select task.factory.startnew(() => provider.objects) .continuewith(getobjecttask => { // 1 of operation bodies above go here }); var tasklist = task.whenall(tasks); tasklist.wait(); // us

python - Smooth screen transition using QT -

Image
i'm learning qt, , i'm wondering if it's possible create animation in ubuntu installer. as can see on screenshot, can switch between 'images' using left , right arrows. each time click on it, smooth transition executed. know if it's possible create kind of design qt, , if it's possible replace 'images' widget various controls inside. the main goal keep cross-platform compatibility (i'm coding using python), avoid using third -party library. regards, in ubuntu installer, use html, css , javascript, can same using qwebview . you can connect javascript functions qt events, need make slides pass every time press button or key on keyboard. an idea: make slides images, , build webpage shows images. can use javascript timer set time between slides. hav done add qwebview control render page. i don't want have images, widget controls in it... in case recommend take qt animation framework , powerful , easy use.

c# - Take the first half of a byte -

i'm looking more performant/elegant way taking first 4 bits of bytes. bytes in big endian var gpsfixstatus = (int)raw[28]; int[] remainder = new int[8]; (int = 0; < 7; i++) { remainder[i] = gpsfixstatus % 2; gpsfixstatus = gpsfixstatus / 2; } var gpsfix = byte.parse((remainder[7].tostring() + remainder[6].tostring() + remainder[5].tostring() + remainder[4].tostring())); the first half of byte b is b >> 4 assuming want shifted lower 4 bits. if want still in place, removing bottom half, it's just b & 240 // or "b & 0xf0" but looks code though former want.

ajax - How to $http Get call with identifer -

i need make call id identifier. have done angular resource, not $http. new understanding how $http works angular. angular controller $scope.emailpdf = function () { $http.get('/api/pdf/{id}').success(function () { $scope.printpreviewmodal(); }); } routing config.routes.maphttproute( name:"pdfapi", routetemplate: "api/{controller}/{id}", defaults: new {controller = "apigeneratepdf", id=routeparameter.optional} ); api controller public string get(int id) { jobdataadapter adapter = new jobdataadapter(); job job = new job(); job = adapter.getjob(id); if (job == null) { return string.empty; } try { error message {"$id":"1","message":"the request invalid.","messagedetail":"the parameters dictionary contains null entry parameter 'i

c# - Removing the code with preprocessor in .net -

i have .net c# application. in application have 2 set of code different client. we thinking of removing part of code through preprocessor. diabling part config file parameter not option us. we want simple setup like: #define debug //.... #if debug console.writeline("debug version"); #endif the issue is, our part of code distributed multiple files , multiple projects in solution. so want define globally preprocessor “debug” @ 1 place. preferably in project property or something. what best option us? look "conditional compilation symbols" on "build" page of project property dialog. can set per-build configuration.

IPC Pipe in Linux C -

it's simple code makes 2 child processes communicate: first 1 execute "ls" , pass output myfd[1]; second 1 receives output myfd[0], , execute "sort"(and shows result). parent process waits these 2 processes. but code doesn't work. gets stuck @ second child process. possible reason why? did use right "close" , "dump" in proper place? my code: #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> int main(void) { int pid; int wpid; int status = 0; int myfd[2]; printf("parent's pid: %d\n",getpid()); pipe(myfd); pid = fork(); if(pid == 0) // child 1 - execute "ls" { printf("child1's pid: %d\n",getpid()); close(1); dup(myfd[1]); close(0); close(myfd[0]); execlp("ls","child_process1",null); } else {

c# - How to add effect inside ItemContainerStyle -

i have effect use this: <image.effect> <effects:huebrightnesscontrastsaturationeffect hue="{binding hue}"/> </image.effect> now need apply effect inside itemcontainerstyle section. im trying add effect property "effect" not recognized or not accessible . something should work fine : <foo.itemcontainerstyle> <style targettype="image"> <setter property="effect"> <setter.value> <effects:huebrightnesscontrastsaturationeffect hue="{binding hue}"/> </setter.value> </setter> </style> </foo.itemcontainerstyle>

if statement - When to use "if" and "when" in Clojure? -

when 1 better other? 1 faster other or difference return of false or nil? use if when have 1 truthy , 1 falsy case , don't need implicit do block. in contrast, when should used when have handle truthy case , implicit do . there no difference in speed, it's matter of using idiomatic style. (if (my-predicate? my-data) (do-something my-data) (do-something-else my-data)) (when (my-predicate? my-data) (do-something my-data) (do-something-additionally my-data)) in if case, do-something run if my-predicate? returns truthy result, whereas in when case, both do-something , do-something-additionally executed.

java - deleting menu items remotely -

consider following code: mntmprofilesdelete.get(index).addactionlistener(new actionlistener(){ @override public void actionperformed(actionevent e) { jmenuitem emntm = (jmenuitem) e.getsource(); string text = emntm.gettext(); component[] mns = mndelete.getparent().getcomponents(); for(component mn : mns) { system.err.println((string)(((jmenu)mn).gettext())); if(mn instanceof jmenu && ((jmenu)mn).gettext().tolowercase().equals("open")) { system.err.println((string)(((jmenu)mn).gettext())); component[] mntms = ((jmenu) mn).getcomponents(); for(component mntm : mntms) { system.err.println((string)(((jmenu)mn).gettext())

java - Open/Closed Principle OO class design -

i'm trying figure out class design library operates on weighted graph. various algorithms may performed on graph, example, finding shortest distance between 2 nodes, longest distance between 2 nodes, number of paths of between 2 nodes distance less 10 (say), etc. my concern not how implement algorithm or data structures graphs know how this, rather on overall high-level class design. point being in future may want add other algorithms, solution should extensible. 1 option implementing write single class has methods implementing each of these algorithms. in future additional methods can added class new algorithms. public class graphcalculator { graph _graph; public int getlongestdistance(string startplacename, string endplacename) { } public int getshortestdistance(string startplacename, string endplacename) { } public int getnumberofpaths(int minimumdistance) { } //any new algorithms implemented new methods added class } my c

finance - Modifying a list of ticker symbols in sas by deleting the last few characters -

i have long list of time-series price data sorted ticker symbol , date. i'm looking delete last 4 characters on every ticker. ticker aaa.asx, end aaa match , merge data set. so far i've tried code: asx=tranwrd(asx,".asx",""); put asx; run; any advice appreciated i'm getting whole sas thing. to expand upon joe's answer slightly, scan includes . 1 of it's standard delimiters , third argument not strictly necessary (but it's practice explicit). data tmp; asx = "abc.def"; /* return first word, when seperated . */ asx1 = scan(asx, 1, "."); put asx1=; /* return first word, when seperated standard delimiters _ -,."' etc. */ asx2 = scan(asx, 1); put asx2=; /* return first 3 characters (if know 3 long) */ asx3 = substr(asx, 1, 3); put asx3=; /* return substring position 1 first occourance of . */ asx4 = substr(asx, 1, index(asx, ".") - 1

javascript - change innerHTML with text on squarespace -

i'm trying take "sold out" on this page , change "coming soon." right have following it's not working. window.onload = function() { document.getelementsbyclassname("product-mark sold-out").innerhtml = "coming soon"; }; window.onload = function(){ //this captures elements spec classes var solditems = document.getelementsbyclassname('product-mark sold-out'); //this changes each element 1 1 new text for(var i=0; i<solditems.length; i++){ solditems[i].innerhtml = "coming soon"; } } that should take care of it!

recursive grep skipping/excluding/ignoring all subdirectories -

this going dumbest question yet. i'm sure it's stupidly obvious, life of me, not find solution. i want search files in current directory pattern, ignoring subdirectories. things i've tried: grep "mytext" . -> complains . directory grep -r "mytext" . -> searches subdirectories grep "mytext" -> freezes (searching entire machine?) grep -rd skip "mytext" . -> skips current directory my last attempt on right track. figured i'd answer question posterity instead of deleting (which tempting since feel stupid having ask in first place). the solution use skip directories wildcard. i.e. grep -rd skip "mytext" ./*

javascript - hover on table to change another element style with jquery, works for only 1 mil second -

i want text underlined when hovering area of table. here's code, works 1 mil second , underline fades away though cursor inside table (tried both go , foo test): js: <script> $(document).ready(function(){ $(function(){ $('.foo').mouseenter(function(){ $(".vvv").addclass('altbg') }).mouseout(function(){ $(".vvv").removeclass('altbg') }); }); }) </script> css: .altbg { text-decoration:underline; } html: <div class="go"> <table border="1" class="foo"> <col style="width:115px;" /> <col style="width:280px;" /> <col style="width:125px;" /> <col style="width:145px;" /> <col style="width:125px;" /> <col style="width:230px;" /> <tr> <td>0</td> <td&

apache - How to redirect where my localhost points to? -

i have http://localhost/ pointing folder there's nothing in it. i'm assuming previous developer hosted there. i, on other hand, host xampp , websites in c:\xampp\htdocs . in order display sites have go http://localhost:39020/ instead. may not huge issue, wondering, how reset http://localhost/ points xampp location. you need find , kill whatever process listening on port 80, configure server listen on port 80.

How to write an array of doubles to a file very fast in C#? -

i want write file: filestream output = new filestream("test.bin", filemode.create, fileaccess.readwrite); binarywriter binwtr = new binarywriter(output); double [] = new double [1000000]; //this array fill complete for(int = 0; < 1000000; i++) { binwtr.write(a[i]); } and unfortunately code's process last long! (in example 10 seconds!) the file format binary. how can make faster? you should able speed process converting array of doubles array of bytes, , write bytes in 1 shot. this answer shows how conversion (the code below comes answer): static byte[] getbytes(double[] values) { var result = new byte[values.length * sizeof(double)]; buffer.blockcopy(values, 0, result, 0, result.length); return result; } with array of bytes in hand, you can call write takes array of bytes : var bytebuf = getbytes(a); binwtr.write(bytebuf);

guess who game in java variables errors -

import java.util.scanner; class cluedo2 { private static scanner clavier = new scanner(system.in); public static void main(string[] args) { system.out.print("pensez un personnage : mlle rose, "); system.out.println("le professeur violet, le colonel moutarde,"); system.out.println("le reverend olive ou mme leblanc.\n"); system.out.print("est-ce que votre personnage est un homme ? "); system.out.print("(true : oui, false : non) "); boolean homme = clavier.nextboolean(); if(homme){ system.out.print("votre personnage a-t-il des moustaches ? "); boolean moustaches = clavier.nextboolean(); system.out.print("votre personnage porte-t-il un chapeau ? "); boolean chapeau = clavier.nextboolean(); } else{ system.out.print("votre personnage porte-t-il des lunettes ? "); boolean lunettes = clavier.nextboolean(); } system

android - Tracking progress of multipart file upload using OKHTTP -

i trying implement a progress bar indicate progress of multipart file upload. i have read comment on answer - https://stackoverflow.com/a/24285633/1022454 have wrap sink passed requestbody , provide callback tracks bytes moved. i have created custom requestbody , wrapped sink customsink class, through debugging can see bytes being written realbufferedsink ln 44 , custom sink write method run once, not allowing me track bytes moved. private class customrequestbody extends requestbody { mediatype contenttype; byte[] content; private customrequestbody(final mediatype contenttype, final byte[] content) { this.contenttype = contenttype; this.content = content; } @override public mediatype contenttype() { return contenttype; } @override public long contentlength() { return content.length; } @override public void writeto(bufferedsink sink) throws ioexception { customsink customsink = n

user interface - "are you sure" exit prompt in python tkinter GUI -

this question has answer here: intercept tkinter “exit” command? 4 answers i have written first program on python 3.4, including gui using tkinter. (hooray!) have option save input (create text file , csv they've input), or people can x out of program without saving info. is there way bring "are sure want exit without saving?" prompt when people click x exit? use tkmessagebox maybe. here's example query tkinter askquestion dialog box .

javascript - Run code when page has loaded into the div -

i've got system, on need share true/false-value across several domains, using 3rd party cookie. running remote cookiefile directly (iframe), works - however, when invoked ajax (with , without jquery), cookie never set. thing; has done in plain javascript without jquery, because need keep file size minimum. i did experimenting , code did trick: document.write("<div id='dummy'>test</div>"); document.getelementbyid("dummy").innerhtml='<object type="text/html" data="http://stats.***.com/setcookie.php"></object>'; the remote file echoes "isvalid=true" or "isvalid=false" div, piece missing: i need process answer. @ moment, result displayed in div, need find out, when div named "dummy" changes value , react it. the listeners below not elegant solution, know... , doesn't work, show intentions. document.getelementbyid("dummy").onchange = function(e) {

datatable - Store More than 100 Millions Records in memory C# -

this question has answer here: total rows can add datatable 2 answers i using c# datatable store around 100 millions records . after storing 16 millions throws exception " out of memory " so can store 100 milions record in c# datatable or have alternative that. after storing data want perform linq queries on data. please provide me solution the maximum number of rows datatable can store 16,777,216. found on http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx alternate is, use dataset. create databale after each 16 million record , add in dataset.

excel vba - vlookup between values of different length -

Image
i'm trying vlookup() best match between 2 rows length of values different. 35799700000 1902718 x1 35796961001 3584570 x2 35796961001 3584573 x3 35799700000 3584575 x4 35795977777 3584576 x5 351309312001 3579 x6 35795977777 41 x7 417999838729 67572210124 320301120086 for example first number 35799700000 should bring me 3579 can me? i've made assumptions because haven't been descriptive in question the formula below resizes lookup table values same length lookup value. e.g. when comparing 35799700000 , lookup value 41 41000000000 in lookup table. once lookup table values have been scaled closest number lookup value calculated using min() , abs() , , corresponding x1 , x2 ... etc returned (i assumed setup above) {=index($e$1:$e$7,match(min(abs(($d$1:$d$7*(10^(len($a2)-len($d$1:$d$7))))-$a2)),abs(($d$1:$d$7*(10^(len($a2)-len($d$1:$d$7))))-$a2),0))} this array formu

nginx - Can't access docker over the internet -

i m going crazy trying docker accessible on internet. have created geoserver container on ubuntu 14.04 server using: sudo docker run -d -p 80:8080 -t eliotjordan/docker-geoserver but when try connect server through web browser connection times out. know server accessible through domain name because running web site on it, using nginx web server stopped try this. docker ps confirms running: $ sudo docker ps container id image command created status ports names 0e339661c232 eliotjordan/docker-geoserver:latest "/bin/sh -c /opt/tom 4 seconds ago 4 seconds 0.0.0.0:80->8080/tcp sad_morse and netstat shows port open: $ sudo netstat -tulnp active internet connections (only servers) proto recv-q send-q local address foreign address state pid/program name tcp 0 0 127.0.0.1:5432 0.0.0.0:* l

grails: keep list order when using findAllBy -

i want keep order of first list def mylist = [444,1111,33333,22222] but when use findallby order changed def mylist2 = mydomain.findallbyrmidinlist(mylist) => out : [1111, 22222, 33333, 444] there way desactivate order default? thanks if want keep order of list, can use dynamic finder 'getall()' (here documentation ) retrieves list of instances of domain class specified ids, ordered original ids list. if of provided ids null or there no instances these ids, resulting list have null values in positions. so try next code: def mylist2 = mydomain.getall(mylist) updated after comments you can use comparator that. little bit more tricky, should work. below you'll find example: def mylist = [444,1111,33333,22222] def mc = [compare: { a,b -> a.rmid == b.rmid ? 0 : mylist.indexof(a.rmid) < mylist.indexof(b.rmid) ? -1 : 1 } ] comparator def mylist2 = mydomain.findallbyrmidinlist(mylist) def results = mylist2.sort(mc) results.

sqlite - Debug sqllite in chrome -

hey i'm develeloping mobile app through phonegap, , i'm using db.transaction function handle storage. problem is, when try debug in chrome (outside of android emulator) error method not exist. how can overcome this, don't have recompile every little change make code? thank you use chrome remote debugging. gets access websql db's being used within application, console can see more errors in general.

linux - rsyslog EscapeControlCharactersOnReceive can't work in omfwd module? -

i'm using rsyslog omfwd log transfer , collect, "\t" has been changed "#011" rsyslog. tried use "$escapecontrolcharactersonreceive off" , saw omfile result of frontend server right, forward server can't process logline anymore(i can saw nic traffic in-flow keep still out-flow decrease 0). i have put "$escapecontrolcharactersonreceive off" both in centre server rsyslog.conf , restart it, no changes.

c# - Optimize the performance of using HttpClient and TPL to validate proxies -

i'm trying use httpclient , tpl validate proxy addresses. i'm using simple , i've set servicepointmanager.defaultconnectionlimit = 100; before start. the problem i've found result varies lot between consecutive runs. there can 4 valid proxies , run 1 second after give 194 valid proxies. i'm concerned maybe should handle task throttling. should myself here? or there other issues should try handle? internal class validator { private readonly concurrentdictionary<string, long> _validatedproxydic = new concurrentdictionary<string, long>(); private async task<tuple<bool, long>> validateproxy(tuple<string, string, string> tuple) { try { string proxy = tuple.item1; string url = tuple.item2; string pattern = tuple.item3; var handler = new httpclienthandler { cookiecontainer = new cookiecontainer(), automaticdecompr

windows - Cloud Computing Run an R script - easiest way to do it -

as have r script takes months run trough (in total) , out of time, looking cloud computing provider. tested slicify based on linux , tricky (in short time). have solution easy going? what have do: install r upload r script , .txt dataset install r packages (within r script) run r script the results should saved in same folder send via e-mail. what think best solution me?

bitmap - JPEG decompression from MemoryStream c# -

Image
in program, compress bmp jpeg this: private void convertbmptostreamjpg30(bitmap b, stream s) { s.flush(); encoderparameters encoderparameters = new encoderparameters(1); encoderparameters.param[0] = new encoderparameter(system.drawing.imaging.encoder.quality, 30l); b.save(s, getencoder(imageformat.jpeg), encoderparameters); } then function receiving jpeg in memorystream, transform bitmap doing bitmap b = new bitmap(stream); when display image, there lot of lines : what doing wrong, people? edit 1 here small visual studio solution showing problem: http://www.fast-files.com/getfile.aspx?file=79311 it beginning of screen sharing software. does: takes screenshots, compare them, compress difference , send part of program decompress , recompose image received. opens window displaying "sent" on left , recomposed image on right. three things come mind: try setting better quality 30 , see if helps; check ram (and possibly video ram, though dou

database - What MySQL case-sensitive collation to use for a multilingual website? -

the question says all: i have project needs multilingual , need case-sensitivity collation. the database isn't ms-sql! i switched utf8_bin utf8_unicode_ci provides way better ordering of cyrillic characters ut8_general_ci , better utf8_bin (ordering of cyrillic characters in utf8_bin wrong). as per following q&a: what's difference between utf8_general_ci , utf8_unicode_ci drawback of utf8_unicode_ci performance, if 1 doesn't work millions of rows, think he/she can ignore performance penalties because accuracy should way better.

swing - Set cursor for jTabbedPane's tab in java -

i have created custom jtabbedpane class extends basictabbedpaneui , have created desired jtabbedpane problem how can set hand cursor each tab in custom jtabbedpane ? i tried set cursor this tabbedpane.setui(new custommainmenutabs()); tabbedpane.setcursor(new cursor((cursor.hand_cursor))); this sets cursor whole of jtabbedpane want set cursor when mouse hovers on of tab in only. how can set hand cursor tabs in jtabbedpane? my code is import java.awt.color; import java.awt.graphics; import java.awt.graphics2d; import java.awt.geom.rectangle2d; import java.awt.geom.roundrectangle2d; import javax.swing.plaf.basic.basictabbedpaneui; public class haams { //my custom class jtabbedpane public static class custommainmenutabs extends basictabbedpaneui { protected void painttabbackground(graphics g, int tabplacement, int tabindex, int x, int y, int w, int h, boolean isselected) { graphics2d g2 = (graphics2d) g; color color; if (isselec

sorting - jQuery datatables execute code after onSort event -

i have code (which works): $('#rooms').datatable({ "bfilter": false, "bpaginate": false, "bautowidth": true, "binfo": false }); what's working user can sort html table clicking on column header. however, after sort complete, want execute code: $("#rooms tr:even").css("background-color", "#eeeeee"); $("#rooms tr:odd").css("background-color", "#ffffff"); how can so?

sms - Fortumo service not working in sandbox mode -

i made fortumo service , started test (in sandbox mode). in "edit" tab entered "to url payment req forwarded to?": http://mywebsite.com/sms when go "test" tab , trying test service don't http request on url ( http://mywebsite.com/sms ) service. i expected receive http request server data transaction. why not received request? please contact fortumo support @ support@fortumo.com quickest reply on technical issue. account id @ fortumo & backend notification url (assuming it's not http://mywebsite.com/sms ) needed check logs. most commonly, issue timeout on server side (request timeout 30 sec), certificate issue or request processing error.

How do you add rows retrieved from database to an arraylist (of objects?) in Groovy? -

selectstatement = 'select * table' try { // eachrow method iterator sql.eachrow( selectstatement ) { //need add results arraylist row row. each object in //arraylist must contain : id, description, code, isdefault. have //access values calling ${it.skill_id}, ${it.description}, //${it.skill_code}, ${it.is_default}. id int, description , code //strings , default bit } } catch (e) { } also if can me iterating on elements of arraylist until match code. thank you, wouldn't rows give want? now try query using rows: def rows = sql.rows("select * project name 'gra%'") assert rows.size() == 2 println rows.join('\n') with output this: [id:20, name:grails, url:http://grails.org] [id:40, name:gradle, url:http://gradle.org]

php - open csv in wordpress -

i have csv file contains user specific data load template on fly when user access's user area front end. the csv self gets managed outside of wordpress , gets uploaded via ftp specific directory in wordpress framework. as csv contains data required, didn't want create additional processes csv uploading database necessary. i call function within template read csv file , convert array can manipulate data wish. i have attempted following inserting following code template: $file = fopen(get_option('siteurl') . '/wp-content/csv/userdata.csv',"r"); while(! feof($file)){ print_r(fgetcsv($file)); } fclose($file); however doesn't seem work , after searching online cant seem figure out why. wordpress support trying do? if not, can achieve functionality. hope don't have outside of wordpress framework , include template via iframe. as using get_option('siteurl') http://yoursiteurl system send http request open file wo

ektron 8.6 - override mobile device for a single session -

a user can routed mobile template of existing desktop template based on device they're on -- no problems there. the difficulty i'm having when i'd route user template (the mobile version) template b (the desktop version). example of "view desktop version" link. is there way ask ektron ignore (for length of session) device routing? thanks. you can find answer question on ektron's customer portal. see article: how to: viewing "desktop" site on mobile device

android - NDK_ROOT not defined. Please define NDK_ROOT in your environment -

Image
i have problem regarding cocos2dx v3 setting android on mac. use video ( https://www.youtube.com/watch?v=2li1irrp_0w ) guide. in video doing fine on own eclipse, there's error shows under console tab. statement error found : "python /users/kirbyasterabadilla/desktop/oracleeye/proj.android/build_native.py -b release ndk_root not defined. please define ndk_root in environment". i tried installing ndk plugin inside eclipse ide still can't solve problem. please me one. should make error disappear? python /users/kirbyasterabadilla/desktop/oracleeye/proj.android/build_native.py -b release ndk_root not defined. please define ndk_root in environment it sounds should export ndk_root log in script. below os x 10.8.5 machine: $ cat ~/.bash_profile # macports installer addition on 2012-07-19 @ 20:21:05 export path=/opt/local/bin:/opt/local/sbin:$path # android export android_ndk_root=/opt/android-ndk-r9 export android_sdk_root=/opt/android-sdk export

How can i validate that a text field with time is entered in 15 minute increments using jquery? -

i trying validate user has entered time in text field in 15 minute increments. 8:00, 8:15, 8:30am or 8:45a valid. tried using :contains doesn't seem working using or comparison. here fiddle: http://jsfiddle.net/fuelishways/h0tmvqyc/4/ html: <form method="post"> <label>arrival time</label> <input type="text" id="arrivaltime"/> <br/> <label>event start time</label> <input type="text" id="eventstarttime"/> <br/> <label>event end time</label> <input type="text" id="eventendtime"/> <br/> <label>departure time</label> <input type="text" id="departuretime"/> <br/> <input type="submit"/> </form> jquery: $("form").submit(function(){ var arrivaltime = $('#arrivaltime').val(); var eventstarttime = $("#e

objective c - Custom UITableViewCells in iOS 8 and layoutMargin -

Image
i have several custom uitableviewcells in app, defined nibs. when moving ios 8 , xcode 6 margins on left , right incorrect. these cells interspersed in table view default cells. i made sample project, here margin issue i'm talking about: the thing i've been able find relates new property layoutmargins . uitableviewcells value seems change depending on device app running on: iphone 6 , below - layoutmargin: {8, 16, 8, 16} iphone 6 plus - layoutmargin: {8, 20, 8, 20} this seems line margins i'm seeing on standard cells. however, content custom cells inside cells contentview , has standard uiview layoutmargin of {8, 8, 8, 8} . means auto layout constraints bound container margin adding incorrect spacing. the way i've found fix adding following in cellforrowatindexpath: cell.contentview.layoutmargins = cell.layoutmargins; this doesn't seem solution going forward (especially since i'd need wrap in checks ios8 maintain compatibility). does ha

ajax - show success message on same page after adding recording without reloadin the site in cakephp 2.x -

i want add show sucess message using :- session->flash(); ?> in view , added message in controller :- session->setflash("record has been saved successfully."); ?> but donot want reload whole page. inserting new record using ajax.. , refreshing div having list of record. session->flash(); ?> works if reload whole page. how can show message once record saved using ajax. solutions (i recommend first one): create ajax method in controller return 200 code json/html record's data or other error code if sth goes wrong. in js do: $.ajax({ ... }).done(function( data ) { // success, show record , message $('#flash').text('success!').show(); // ... }).error( function() { // error $('#flash').text('error!').show(); }); refresh records list calling ajax method , return not view list of records, flash message (in same view). show or move using javascript.

Parsing the exact match in a text file using a PHP -

i’m new php , trying parse exact sentence in text file using php function preg_grep(). can see below prints out close not exactly. example “[40]=>will work?” prints out “?” isn’t in variable ‘$sta’ . how find , retrieve correct strings? $lines = file("{$dir}/status.txt"); $sta=”will work”; $data = preg_grep("/$sta/", $lines); print_r($data) ( [40] => s9477 work? 21/09/2014 [41] => s9487 work 21/09/2013 [42] => s9497 work 05/06/2002 ) )

php - where in clause and query multiple IDs using FuelPHP -

model_article::query()->where('id', 4); i'm using fuelphp. have query above. and have arrays of id's $ids = array(1, 2, 4, 8 ...); how apply array of id's write query using format? thanks lot! feed 'in' inside ->where() create in() clause: model_article::query()->where('field_name', 'in', array(1,2,3,4,5))->get();

java - Converting the required time to UTC -

i have string time in such format: 14:30 , , need convert utc correctly make selections database. here code current time in utc: simpledateformat dateformat = new simpledateformat("yyyy-mmm-dd hh:mm:ss"); dateformat.settimezone(timezone.gettimezone("utc")); system.out.println(dateformat.format(new date())); how convert 14:50 utc (not current time), if relates utc+6 timezone? i'm using sqlite , time('now') in database query. time returned function compared time got in first point? thank advice.

html - jQuery .keyup not working with my foreign object tag -

so want user enter text in input box , typed needs appear in area. i'm using svg here svg has no wrapping i've been informed need use foreign object tag access html's automatic wrapping. if keyup function no longer works. here input code. or fiddle - http://jsfiddle.net/ytktmo00/ <h3>your text:</h3> <input id="input" maxlength="30" type="text" name="text" value="max. 30 characters"> and svg version words besides wrapping issue. <text class="text" transform="matrix(2.4428 0 0 1.5 624.6 550.5599)" font-family="'comicsansms'" font-size="41.6368">your words here</text> if comment svg out , uncomment foreign object it. <foreignobject x="78" y="460" width="1100" height="200" style="color:white;text-align:center"> <body xmlns="http://www.w3.org/1999/xh

Need help for c# Regex -

i'm trying create regex named groups matches of 4 following strings: var club = "real madrid"; var city = "madrid"; var nation = "spain"; var string1 = club; var string2 = club + "," + city; var string3 = club + "(" + nation + ")"; var string4 = club + "," + city + "(" + nation + ")"; or in other words: string looks "club,city(nation)" city , nation optional optional whitespaces included. thanks help! regex aelor added "(" sign after "^(?[^," match string "real madrid(spain)" added code example too. var strings = new list<string>() { "real madrid", "real madrid,madrid", "real madrid(spain)", "real madrid,madrid(spain)" }; foreach (var str in strings) { var match = regex.match(str, @"^(?<club>[^,]+)(?:,(?<city>[^\(]+))?(?:\((?<nation>[^\)]+)\))?$");

static analysis - PMD gets in the way of CheckStyle -

i'm starting use static code analysis tools checkstyle, pmd , findbugs. pmd allows mark code reviewed, adding comment end of line: system.out.println("test"); // nopmd edward on 9/23/14 10:22 i don't trailing comments , checkstyle ("don't use trailing comments."). there way tell pmd specific code reviewed, without using trailing comments? another way of tackling configure checkstyle make exception trailingcomment rule suppression comments this: <module name="trailingcomment"> <property name="legalcomment" value="^nopmd .*"/> </module>

Mysql java executeUpdate error -

when use query have error exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.mysqlsyntaxerrorexception: have error in sql syntax; check manual corresponds mysql server version right syntax use near '12:04:44, 23-09-2014 12:04:44)' @ line 1 this code: simpledateformat sdf = new simpledateformat("dd-mm-yyyy hh:mm:ss"); // creo l'oggetto string datastr = sdf.format(new date()); system.out.println(datastr); // eseguo una query /*stmt.executequery("insert incomecalc(c_timestamp, parent_uid, uid, status, username, password, token, enable_webservices, " + "webservices_ip, name, mobile, email, sender, footer, address, city, state, country, zipcode, credit, datetime_timezone," + "lang uage_module, fwd_to_mobile, fwd_to_email, fwd_to_inbox, replace_zero, plus_ sign_remove, plus_sign_add, " + "send_as_unicode, local_length, register_datetime, lastupdate_datetime,) " */ stmt.exec

sql server - trigger with a select condition -

i want create trigger doesn't perform insert if insert column 2 exists in table , value column 1 in table different value inserted column 1. i've done create trigger tr1 on dbo.table after insert, update begin declare @col1 varchar(20) declare @col2 varchar(20) if ( exists( select column2 table column2='@col2' ) , @col1 <> select column1 table column2='@col2' ) begin raiserror('error', 16, 1); rollback end end i'm not sure i've understood tryng easy way check existing values triggers use transaction tables. inserted update , insert deleted delete 1. create table some_table(col1 int , col2 int) go 2. create trigger tr1 on dbo.some_table after insert, update begin declare @cnt int select @cnt = count(*) some_table t inner join inserted on t.col1 = i.col1 , t.col2 = i.col2 if isnull(@cnt,0) > 1 begin raiserror('error'

php - IasPager pager not working after ajax update on clistview -

yii infinite scroll extention: "iaspager pager" not working after ajax update on clistveiw. it's working fine before ajax call after ajax call when update listview it's not working. $this->widget('zii.widgets.clistview', array( 'id' => 'videolist', 'dataprovider' => $dataprovider, 'itemview' => '_view', 'template' => '{items} {pager}', 'pager' => array( 'class' => 'ext.infinitescroll.iaspager', 'rowselector'=>'.row', 'listviewid' => 'videolist', 'header' => '', 'loadertext'=>'loading...', 'options' => array('history' => false, 'triggerpagetreshold' => 2, 'trigger'=>'load more'), ) ) );

emacs - Two different buffers, same python shell -

i started using emacs, , installed python-mode.el, along few add-ins (following jess hamrick's setup in emacs python ide ). i find myself 1 tricky issue. want edit different buffers, want able send code both of them python shell. unfortunately, when try send code file buffer using c-c | , new python buffer opened it, , can't figure out how instruct emacs send original python shell buffer. any suggestions? a report @ https://bugs.launchpad.net/python-mode would useful, turns out there not test this. however, when checking works nice here. a reason using different output-buffer might different python-version in shebang. each python version connects own process , gets own output-buffer. , running dedicated open new process/buffer every time. what's python-mode.el version? setting py-split-windows-on-execute-p nil might help.

Safe API to transform HTML (Java) -

i'd take web page , add tags head. specifically, css link , javascript link. need programatically wide variety of web pages. now, hack out regex or two, i'd use more robust. what's way inject or transform html? i'm using scala, java or jvm work. you can use jsoup . example modifying content in html here

objective c - AssetsLibrary framework broken on iOS 8 -

i have run issue on ios 8 assets library framework appears bug in ios 8. if create album called 'mymedia' , delete it, when try create album again, chunk of code below returns 'nil' indicating album 'mymedia' exists though not because deleted using 'photos' app. __block alassetsgroup *mygroup = nil; __block bool addassetdone = false; nsstring *albumname = @"mymedia"; [assetslib addassetsgroupalbumwithname:albumname resultblock:^(alassetsgroup *group) { mygroup = group; addassetdone = true; } failureblock:^(nserror *error) { nslog( @"failed create album: %@", albumname); addassetdone = true; }]; while (!addassetdone) { [[nsrunloop currentrunloop] rununtildate:[nsdate datewithtimeintervalsincenow:0.05f]]; } return mygroup;

c++ - Why is vsnprintf safe? -

i have looked @ question these pdfs' 1 , 2 , page , pretty understand happens if printf(some_test_string) . not understand why ensuring size of buffer vsnprintf becomes safe compared vsprintf ? what happens in these 2 cases ? case 1 char buf[3]; vsprint(buf, "%s", args); case 2 char buf[3]; vsnprint(buf, sizeof buf, "%s", args); in case 1, if string you're formatting has length of 3 or greater, have buffer overrun, vsprintf might write memory past storage of buf array, undefined behavior, possibly causing havoc/security concerns/crashes/etc. in case 2. vsnprintf knows how big buffer contain result is, , make sure not go past that(instead truncating result fit within buf ).

ios - Maintaining scroll position after reload in tableView -

i've got tableview. when user taps 1 of records, check it's property , basing on i'm filtering results , showing similar results - need refresh tableview. the problem user can scroll up/down tableview. need scroll tableview cell @ same uitableviewscrollposition before refresh. obviously, i'm saving last tapped item - (void)tableview:(uitableview *)tableview didselectrowatindexpath:(nsindexpath *)indexpath { _lastselecteditem = [self itemforindexpath:indexpath]; } then after reloading tableview: nsindexpath *indexpath = [self indexpathforitem:_lastselecteditem]; if (_tableview.numberofsections > indexpath.section && [_tableview numberofrowsinsection:indexpath.section] > indexpath.row) { [_tableview scrolltorowatindexpath:indexpath atscrollposition:uitableviewscrollpositionmiddle animated:no]; _lastselecteditem = nil; } it but... user not finish @ uitableviewscrollpositionmiddle . have finish scrolling @ uitableviewscrollpositio

javascript - Rails and ajax: confusion about callback -

i'm confused ajax request in rails. i'm submitting form using ajax , fine. must handle callback, but... following tutorials hint add respond_to |format| format.js end to controler#create , place in views folder "create.js.erb" response. other tutorials suggest create js file in assets folder , handle callback js file. what's difference? , what's right way? both different ways handling callback of ajax request. suggest use js.erb file handle ajax callback because file can recognize both js ruby code , execute. for example, in controller, def create ... if @foo = true else @foo = false end in create.js.erb, can done want show/hide div based on @foo value, can write like, <% if @foo %> // js code <% else %> // else <% end %> while if create js file in assets folder not able write condition above because pure js file , creating js.erb easy way handle ajax response.

Convert excel format to C# TimeStamp like excel do so -

in app i'm reading data excel sheet , stucked in moment when want timestamp cell. in speciffic cell got value '1900-01-02 13:20:04' , in excel using format '[h]:mm:ss' formats value '61:20:04', correct beacuse cells showing hours worked employees. want achieve read data excel in same format it's formated in excel('61:20:04') , save string. problem how read this, or convert timestamp value ? edit.(the way doing now) i reading code excel using odbc select data need(like sql select) -> add data datatable , i'm doing dr["workedhours"].tostring() -(dr = datarow in datatable.rows) line returns '1900-01-02 13:20:04'. how can convert time excel does. some proof of concept: var timestamp = "1900-01-02 13:20:04"; var date = datetime.parse(timestamp); var stamp = date.subtract(new datetime(1900, 1, 1)); var result = string.format("{0}:{1:00}:{2:00}", 24 + stamp.days * 24 + stamp.hours, stam

php - FPDF page break in fpdf -

i using php , fpdf generate pdf list of items. problem is, item not goes second or third page. i want print next block of data in 2nd page of pdf. please me. have used setautopage break() not working. please help! <?php require('fpdf.php'); class pdf extends fpdf { function header() { $this->setfont('arial','b',10); $this->rect(50,30,100,30,'f'); $this->text(80,45,"3d"); $this->setxy(20,20); $this->cell(30,10,'a',1,0,'l'); $this->setxy(80,20); $this->cell(30,10,'b',1,0,'l'); $this->setxy(80,60); $this->cell(30,10,'c',1,1,'l'); $this->setxy(150,60); $

.net - C# LINQ storing int? as int -

i querying database contractorid field value, either return 1 value or null. need pass integer onto class method(int,int). apparently not matching methods best overload. suspect because int? contractorid value null , cannot converted integer. if remove ? , use int error single() method in linq int userid = new bussinesscomponent().logindetails.userid; using (var db = new datacontext()) { int? contractorid = db .users .where(x => x.userid == userid) .select(x => x.contractorid) .single(); ltloj.text = dashboardcomponent.getjobs(userid,contractorid ).tostring(); } indeed, need convert int? int because null cannot converted int. you can using 'getvalueordefault()` give default value. ltloj.text = dashboardcomponent.getjobs(userid, contractorid.getvalueordefault(0)) .tostring();