Posts

Showing posts from May, 2010

caching - Service worker runtime cache -

i creating progressive web app using service workers , using service worker toolbox cache content. service worker code cache content : toolbox.router.get('/(.)', toolbox.fastest); toolbox.router.post('/(.)', toolbox.fastest); toolbox.router.get('/(.)', toolbox.fastest, {origin: 'https://example.cloudfront.net'}) toolbox.router.get('/(.)', toolbox.fastest, {origin: 'https://example.in'}) the code running fine not seeing error in console. how can check whether images cloudfront or url's configured above getting cached , rendered cache itself. you can check cache content in chrome devtools, in resources / application tab , cache storage. you check it's returned, in devtools network panel , '(from serviceworker)' in size column.

android - Is custom views context always an Activity? -

i have custom view inflated xml , has custom xml attributes. this view setup things in actionbar, if xml attribute has been set true. therefore need reference activities action bar. my question is: can assume context passed in constructor of class myview extends view { public myview(context context, attributeset attrs, int defstyle){ activity = (activity) context; } } i have tested different devices , different android versions, , seems t context activity. does know sure? no. if theme layout containing view end contextthemewrapper .

java - Try to reach a special position on 2D Array -

i have problem 2d-arry trying feld [1][4]=true, eclipse dows not go [1][4] position. below output 0 0 (0,0)__ 0 1 (0,1) 1 0 (1,0)__ 1 1 (1,1)__ 1 2 (1,2)__ 1 3 (1,3)__ 1 4 gefunden i dont know why 1 4 not work if?!? should go in , should errow because [1][5] not reachable... package maus; public class newmausbesser { public static void rekursivundzwarrichtig (boolean[][]feld2, int n, int m,int arraylänge) { boolean feld[][] = feld2; system.out.println(n + " " + m); //und or oder? if((n!=arraylänge-1) && (m !=arraylänge-1)){ //system.out.println(n + " " + m); if(feld[n][m]==true){ system.out.println("(" + n + "," + m + ")__"); rekursivundzwarrichtig(feld,n,m+1,arraylänge); } else if (feld[n][m]==false){ system.out.println("(" + n + "," + m + ")"); rekursivundzwarrichtig(feld,n+1,m-1,arraylänge); } }

c# - MVC BeginForm - passing parameters to controller using GET -

i implementing search filter 1 of application's views. struggle @ getting routevalues passed controller action using @html.beginform() , request. the action accepts following properties: public actionresult books(int id, string type, string search) { //rest of code } the view's search box looks this: @model ilookup<string, citylibrary.models.library.book> .... @using (html.beginform("books", "collections", new { id = model.first().first().collectionid, type = viewbag.booktype }, formmethod.get, null)) { <div class="input-group col-md-4"> @html.textbox("search", null, new { @class = "form-control form-control-fixed-width", @placeholder = "filter title..." }) <span class="input-group-btn"> <button class="btn btn-default" type="submit"> <span class="glyphicon glyphicon-search"></span&g

database - Replacing data of one table using another table in Mysql -

i have 2 table follows. table : city city_id city_name state_id 1 cachar 1 2 darrang 1 3 nicobar 1 table 2 : locality pincode address city 110020 loni nicobar 110021 debru cachar 110024 rogar cachar 110023 akura nicobar in table city have 1430 rows , containing different cities in india. , in table locality each city contains near 100 pincode . what want do? : want replace each city(column) in table : locality corresponding city_id in table : city . question : how can ? there fast way ? don't want use programming language i.e. php or java. there procedure, looping in mysql ? result should looks this: table 2 : locality pincode address city 110020 loni 3 110021 debru 1 110024 rogar 1 110023 akura 3 you can try this. update locality join city on locality.city = city.city_name set locality.city

c# - GridView RowIndex is 0 -

i have gridview on page , click on edit , displays editable text box when edit value , press update errors: the error suggests gridview2.datakeys null . i adding debugging by: int test = e.rowindex and gives me value of 0 my code below: can suggest why im getting: an exception of type 'system.argumentoutofrangeexception' occurred in mscorlib.dll not handled in user code additional information: index out of range. must non-negative , less size of collection. protected void gridview2_rowupdating(object sender, gridviewupdateeventargs e) { int datakeyvalue = convert.toint32(gridview2.datakeys[e.rowindex].value.tostring()); gridviewrow row = (gridviewrow)gridview2.rows[e.rowindex]; label lblid = (label)row.findcontrol("lblid"); textbox gvtxtnextstep = (textbox)row.cells[0].controls[0]; gridview2.editindex = -1; cobj.supportref1 = txtsupportref.text; cobj.nextstep1 = txtnextstep.text; bobj.microticke

javascript - next("some class") doesn't work -

html <div class="linksrtitle">lorem ipsum</div> <div class="linksrspace"></div> <div class="linksrwrap"> // div should slided <a class="linkr" href="volim-da-stoje.php">lorem ipsum</a> <a class="linkr" href="ova-salate-je-umrla.php">lorem ipsum</a> <a class="linkr" href="nova-rasa.php">lorem ipsum</a> </div> <div class="linksrspace"></div> js $(".linksrtitle").click(function(){ $(this).next(".linksrwrap").slidetoggle(); // doesn't work }); why click event doesn't work. console empty. use nextall() (with first() , if multiple sibling same class there) that. next() select immediate following sibling. $(".linksrtitle").click(function() { $(this).nextall(".linksrwrap").slidetoggle(); }); <script src="https://ajax.go

c# - AT commands hang up -

i have following snippet code using simulate call on pc dialer using @ commands. the problem have sometimes, random number dialled, though user clicks "hang up" button on windows form, call still continues dialing in background. the actual dial call code: serialport po = new serialport(); po.portname = configurationmanager.appsettings.get("modemport"); po.baudrate = int.parse("9600"); po.databits = convert.toint32("8"); po.parity = parity.none; po.stopbits = stopbits.one; po.readtimeout = int.parse("300"); po.writetimeout = int.parse("300"); po.encoding = encoding.getencoding("iso-8859-1"); po.open(); po.writeline("atd" + phonenumber + ";\r"); then when clicking hang button, have code: po.discardinbuffer(); po.discardoutbuffer(); po.close(); this keeps call dialing in background. i added following test out, still same result. po.writeline("ath" + "\r"); po.w

php - Is there anyway to code such that I can define or condition in middleware? -

i have 3 roles in application. have condition in 2 roles can access same page. write below code. in below code, sub plan1 , sub plan 2 roles. route::group(['middleware' => ['web', 'auth', 'subplan1', 'subplan2']], function () { route::get('/parent-1-info', '\contactinfocontroller@parent1info')); }); if sub plan1, tries access page, 404 error because mentioned both middleware in same group. is there anyway code such can define or condition in middleware? for role based authentication i'm using middleware: namespace app\http\middleware; use auth; use closure; use app\role; use illuminate\support\collection; class rolemiddleware { /** * handle incoming request. * * @param \illuminate\http\request $request * @param \closure $next * @return mixed */ public function handle($request, closure $next, $roles = null, $guard = null) { $roles = role::wher

python - Too many levels of symbolic links error when creating the virtual environment during the installation of OpenCV? -

i have been trying install opencv3 using installation guide: http://www.pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/ . error when try create virtual environment using mkvirtualenv cv . i using mac running on yosemite 10.10.5 the error given following: myuser = username of user im using in laptop new python executable in /users/myuser/.virtualenvs/cv/bin/python2.7 traceback (most recent call last): file "/usr/local/bin/virtualenv", line 11, in <module> sys.exit(main()) file "/usr/local/lib/python2.7/site-packages/virtualenv.py", line 708, in main symlink=options.symlink) file "/usr/local/lib/python2.7/site-packages/virtualenv.py", line 921, in create_environment site_packages=site_packages, clear=clear, symlink=symlink)) file "/usr/local/lib/python2.7/site-packages/virtualenv.py", line 1214, in install_python shutil.copyfile(executable, py_executable) file "/usr/local/cellar/python/2.7.11/fr

javascript - Execution time for successful search Binary Search algorithm -

i have implemented binary search algorithm using node.js. recording time taken algorithm search number in random generated array. able output time taken algorithm unsuccessful search . but not able figure out how measure time taken algorithm successfully search number in array. here code - function binarysearch(a,k) { var l = 0; // min var r = a.length - 1; //max var n = a.length; var time = process.hrtime(); while(l <= r) { var m = math.floor((l + r)/2); if(k == a[m]) { return m; } else if(k < a[m]) { r = m - 1; } else { l = m + 1; } } time = process.hrtime(time); console.log('%d',time[1]/1000000); return -1; } var randomlygeneratearray = function(size) { var array = []; (var = 0; < size; i++) { var temp = math.floor(math.random() * maxarrayvalue); array.push(temp); } return array; } var sortnu

java - How to launch an android app(not an activity) from the bottom of the screen to top? -

i have used overridependingtransition() already used open activity given transition not app. moreover works when having intent on clicking on button, won't work if use overridependingtransition() in oncreate() @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main2); intent = new intent(main2activity.this,mainactivity.class); startactivity(i); overridependingtransition(r.anim.slide_in_up,r.anim.slide_out_up); } before setcontentview use following code : overridependingtransition(r.anim.slide_in_from_bottom, r.anim.fade_out); and in finish() use following code : @override public void finish() { super.finish(); overridependingtransition(r.anim.fade_in, r.anim.slide_out_back_to_bottom); } and create anim folder , put these files : slide_in_from_bottom: <set xmlns:android="http://schemas.androi

json - PHP - Escaping doesn't work for me? -

i've been trying json in string, have escape double quotes.. here's line {\"assetid":".$assetid.", "floatvalue\":".$floatvalue.\"}, $data = [ 'assetid' => $assetid, 'floatvalue' => $floatvalue, ]; $result = json_encode( $data ); edited foreach($floatdone['result']['items'] $data) { $assetid = $data['id']; $floatvalue = $data['attributes']['2']['float_value']; $swag[] = //your mistake, guess, use $swag[] instead of $swag [ 'assetid' => $assetid, 'floatvalue' => $floatvalue, ]; } var_dump( json_encode($swag) );

yii2 - Nginx "Server not found" while no network connection -

i'm using lemp stack on ubuntu 14.04 , have trouble nginx/1.10.0., when have no network connection can't reach local sites see "server not found", there thing interesting localhost site still works fine in network state. have 5 local sites stock localhost works perfect in network state. try many settings combination of nginx, hosts file, rename site directory, given permissions www folder nothing helps, don't know else. notice if visit site while i'm online can use site while after go offline, if open browser console , set mode "no cache" in same second loosing connection site , see again "server not found", , last, in mode of networking off/lan/wlan local site address pings good, there no trouble. there no error message in logs, perfect clear. config files same sites, here is. my localhost nginx file server { charset utf-8; client_max_body_size 128m; listen 80; ## listen ipv4 #listen [::]:80 default_server ipv6

nginx - PHP-FPM doesn't write to custom error log specified in pool -

i've used ondrej/php repo setup wordpress sites running on php7, phpmyadmin won't except white-screen despite saying it's php7-compatible. clearly solution lies finding error php throwing, can't write fpm log. i've followed php-fpm doesn't write error log , php-fpm 1 error log file per pool , here's config based on answers offered: php/7.0/fpm/pool.d/phpma.conf user = phpma group = phpma listen = /run/php/phpma.sock listen.owner = www-data listen.group = www-data listen.mode = 0660 catch_workers_output = yes part of /etc/nginx/sites-available/phpmyadmin.conf: fastcgi_pass unix:/run/php/phpma.sock; access_log /var/log/nginx/phpmyadmin.access.log; error_log /var/log/nginx/phpmyadmin.error.log error; phpinfo shows: php version 7.0.7-2+donate.sury.org~wily+1 display_errors on error_log /var/log/php-fpm.phpma.log log_errors on log_errors_max_len 1024 the nginx access log being written fine , is: -

rust - How do I hold a collection of one struct in another where lifetimes are not predictable? -

i want manage collection of objects in object can't predict lifetime of elements in collection. i found example in syntax of rust lifetime specifier demonstrates can't do: struct user<'a> { name: &'a str, } // ... impls omitted struct chatroom<'a> { name: &'a str, users: hashmap<&'a str, user<'a>>, } chatroom holds map of user s. each user copy although name within user shared reference. user , chatroom have explicit lifetime when joined compiler enforces user s must live longer chatroom they're going into. but if user created after chatroom ? can't use lifetimes because compiler complain. if delete user before chatroom ? can't either. how can chatroom hold user s might created after or destroyed before it? vaguely suspect done boxes implement rust's box documentation quite poor not certain. in rust, types come in pairs: borrowed , owned counterpart. stri

javascript - program fails because readFile is asynchronous? -

i'm trying combine 2 lists. list1 has 681 french verbs, list2 has 681 translations. i'm using javascript, , node.js read files. here's attempt: var frenchwords, englishwords, combinedlist; fs = require('fs') // 1. read french file fs.readfile('frenchverbslist.txt', 'utf8', function (err,data) { if (err) { return console.log("error here!: " + err); } frenchwords = data.split('\n'); }); //read english file fs.readfile('englishverbslist.txt', 'utf8', function (err,data2) { if (err) { return console.log("error here!: " + err); } englishwords = data2.split('\n'); }); // 2. combine lists //*** fails here, i'm guessing it's because readfile operation hasn't finished yet. var combinedlist; for(i=0; i<frenchwords.length; i++){ combinedlist[i] = frenchwords[i] + ",,," + englishwords[i]; } /

aggregation framework - MongoDB Aggregate Slow Performance When Using Sort -

i have collection (tvshow episodes) more 1,200,000 document, here schema : var episodeschema = new schema({ imdbid: { type : string }, showid: {type : string}, episodeid: { type : string }, episodeidnumber:{ type : number }, episodetitle:{ type : string }, showtitle:{type : string}, seasonnumber:{type : number}, episodenumber:{type : number}, airdate : {type : string}, summary:{type : string} }); i created index episodetitle episodeidnumber seasonnumber episodenumber episodeid , showid now used mongodb aggregate group every tvshow episodes here aggregate query used : episode.aggregate( [ { $match : { showid : "scorpion" } }, {$sort:{"episodenumber":-1}}, { $group: { _id: "$seasonnumber", count: { $sum: 1 } , episodes : { $push: { episodeid : "$episodeid" , episodetitle: "$episodetitle" , episodenumber: "$epis

python - Detecting key combinations using pyhook -

i using pyhook capture keys using hook manager's keydown event. allows me capture single keys pressed on keyboard. however, haven't been able find way capture key combinations. example, event ctrl , alt , 5 pressed @ same time, or [ , ] @ same time, , on. is there way pyhook doesn't involve additional modules? example, i've found pyhk seems job, rather have few dependencies possible. (this question more generic version ( not duplicate ) of this one , accepted answer seems deal virtual key modifiers ctrl .)

How Does Groovy Support Adding Configuration in Gradle Configuration Script Block -

in gradle documentation when use configurations block in build.gradle file closure passed delegates configurationcontainer object. truncated form of example usage given below: configurations { //adding configuration: myconfiguration } i used calls inside closure being method calls on delegated object, here myconfiguration single word , know in groovy method no parameters must have parentheses can't method call. somehow putting single word in looks me should invalid groovy new configuration of myconfiguration added delegated configurationcontainer . how working? project.configurations(closure) calls configurationcontainer.configure(closure) , creates , adds named items container, declared in closure. because configurationcontainer extends nameddomainobjectcontainer , every item added should have name. in provided code sample name declared, myconfiguration item created , added, default field values. in case 1 needs configure item (change properties), con

javascript - Backbone get() returns undefined -

problem lies in postrouter var in app.js file. logging this.posts.tojson() returns data in db calling passing id returns undefined. routing works id passed in url , logged in function. using mongo store data , monk query db. my server file //configure app.configure(function(){ app.use(express.json()); //parses json requests being sent server app.use(express.static( path.join(__dirname, 'public') )); //serve files path given }); app.get("/posts", function(req, res){ var db = req.db; db.get("postscollection").find({}, function (err, results) { res.json(results); }); }); //create route using express rest api app.get('/*', function(req, res){ var db = req.db; db.get("postscollection").find({}, function (err, results) { res.render("index.ejs", { posts: json.stringify(results) }); //pass object of values use in template }); }); app.listen(3000); my app file //post var post

django - Calculated value (aggregation) displays in technical format -

after calculating field in model want display field in template model: def _get_total(self): inventory.models import inventory purchase.models import poproduct sales.models import soproduct # "returns total" return inventory.objects.filter(warehouse_bin__material_uom__uom__material=self.id ).aggregate(sum('quantity')) #- soproduct.objects.filter(product__material=self.id).aggregate(sum('quantity')) #poproduct.objects.filter(product__material=self.id).aggregate(sum('quantity')) total = property(_get_total) template: <div> <b>total on hand:</b> {{ data.material.total }}</div> however template displayed value in format instead of plain numeric value total on hand: {'quantity__sum': decimal('97.00000')} i trying add parameter , output_field = models.decimalfield() sum function getting error not understand

ember.js - How to highlight code in hbs template? -

i want introduce project code highlighted on pages (like index.hbs) i've searched libraries can , found tools highlight.js, unable use in ember project. can explain how import custom library highlight.js or can give me recomandation tool. i've tried use tool: ember-cli-eg-code-highlight , not specified how use it. ok have installed it, pasted {{highlight-js code=file lang=language haslinenumbers=haslinenumbers}} in index.hbs, not work. env.emberhighlightjs: { style: 'arta' } ;i have no ideea put it. tried put inember-cli-build.js not working. i have found markdown-code-highlighting . lost @ step: "in brocfile you'll need import css styling want highlighter. " brocfile in ember project? did restart ember server ? you can find example of using ember-cli-eg-code-highlight here: https://github.com/embergrep/ember-cli-eg-code-highlight/blob/master/tests/dummy/app/templates/application.hbs but looks addon buggy. worth check pr https://githu

java - Replace Unicode escapes with the corresponding character -

i'm trying convert code points, such \u00fc , character represents. import javax.swing.joptionpane; public class test { public static void main(string[] args) { string in = joptionpane.showinputdialog("write in here"); system.out.println("input: " + in); // before line string out = in; system.out.print("and now: " + out); } } an example explain mean: first console line: input: hall\u00f6 second console line: and now: hallö edit: because didn't work multiple unicodes in trombone willy's answer, here code fixed: public static string unescapeunicode(string s) { stringbuilder r = new stringbuilder(); (int = 0; < s.length(); i++) { if (s.length() >= + 6 && s.substring(i, + 2).equals("\\u")) { r.append(character.tochars(integer.parseint(s.substring(i + 2, + 6), 16))); += 5; } else { r.append(s.charat(i))

maven - Cyclic Reference Error from parent to children module reference -

Image
i'm referencing jar dependency generated module build by: <dependency> <groupid>org.hammerden</groupid> <artifactid>adapter</artifactid> <version>1.0-snapshot</version> <classifier>classes</classifier> </dependency> my module like: <parent> <groupid>org.hammerden</groupid> <artifactid>acacia</artifactid> <version>1.0-snapshot</version> </parent> <artifactid>adapter</artifactid> <packaging>war</packaging> <build> <plugins> <plugin> <artifactid>maven-war-plugin</artifactid> <version>2.6</version> <configuration> <attachclasses>true</attachclasses> </configuration> </plugin> </plugins> </build> when try build parent project error [info] scan

c# - Calculating the angle and converting it to degrees -

i having trouble getting accurate angle measurement , converting degrees. i first calculated distance with: double distance = math.sqrt(deltax + deltay); console.writeline("distance :" + math.round(distance, 3)); console.writeline(""); then tried calculate angle: double angle = math.atan2(deltay, deltax); double radiantodegree = (angle * 180 / math.pi); math.round((decimal)angle, 3); console.writeline("angle :" + angle) with inputs such x1=2, y1=2, x2=1, y2=1, angle should measure -135.000 degrees. the problem not using converted value of angle . you do: angle = (angle * 180 / math.pi); instead of defining radianttodegree never using it. happens right printing angle in radians.

xcode - iOS App Contains Developer Path Information -

Image
inspecting archived app, can see full path listed few source code files in app binary. not source code files listed. strings - the_binary_app | grep "\.m" reveals /users/bbarnhart/mypath/mypath/app/path/path/sourcecodefile.m as few others. can not determine how full paths few source code files embedded in app binary. remove them. ideas? build setting or project file corrupted? some belong lib , others files belong project. the __file__ macro expands full path current file. 1 way might getting paths executable. example, expansion of assert macro includes __file__ macro. look @ output of strings | grep pipeline. each of files, go project in xcode , open file. go related files doodad , choose “preprocess”: then search through preprocessor output file's path. find lots of false positives, because there lots of # line number/path directives. can ignore these, because produce debug output, not included in executable file (unless you&#

Compare string in c# for spaces in middle -

i want compare string in c# username duplicate.but problem how can compare strings having symbol , spaces in them.for example one username : ak-username second username : ak - username first without space , second space in middle along symbol. i cannot remove spaces compare user can [ak username] you can split string , rejoin it string str="ak username"; string str1 = "akusername"; string[] splittedstrings = str.split(" "); str = ""; for(int i=0; i<splittedstrings.length; i++) { str += spittedstrings[i]; } if(string.equals(str,str1,stringcomparison.ordinalignorecase)) { messagebox.show("equal"); } edit: saw comments below saying want "ak-username" , "ak - username" equal. refactoring code , writing below! string str="ak - username"; string str1 = "ak-username"; string[] splittedstrings = str.split("-"); str = ""; for(int i=0; i<splittedst

javascript - d3js throwing following error d3.v3.min.js:1 Uncaught TypeError: t.slice is not a function -

i trying pass data (stock infomration) flask d3js . following code. , able see when select different stocks, can see data passed flask html page using console.log function. know flask code works. beginner in java scripts. have hacked code different sources. flask code: from flask import flask, render_template, request, jsonify import os import json bokeh.plotting import figure bokeh.resources import cdn bokeh.embed import file_html, components import pandas pd app = flask(__name__) files_list = os.listdir("/users/kpatel/desktop/test2/data") @app.route('/') def index(): return render_template('index.html', files_list=files_list) @app.route('/stocks') def stocks(): = request.args.get('a', 0, type=str) data_df = pd.read_csv("/users/kpatel/desktop/test2/data/"+a) data_df["date"] = pd.to_datetime(data_df['date'], format='%y-%m-%d %h:%m:%s.%f') data_df.drop('date', axis

python - Regex to extract names from HTML -

i have 2 pieces of code below want extract names. code: ;"><strong>deanskyshadow</strong> ;"><strong><em>xavier</em></strong> the regex should extract names deanskyshadow , xavier . current regex: (?<=(;"><strong><em>)|(;"><strong>))[\s\s]+?(?=(</em></strong>)|(</strong>)) grabs names correctly if there no em tag in code; if there grabs opening em tag, this: <em>xavier . how can fix that? match not < character; cannot use variable-width look-behind version doesn't work @ all. use non-capturing pattern instead (?:;"><strong>(?:<em>)?)([^<]+?)(?=(?:</em>)?</strong>) demo: >>> import re >>> sample = '''\ ... ;"><strong>deanskyshadow</strong> ... ;"><strong><em>xavier</em></strong> ... ''' >>> re.find

rstudio - Unable to access bucket storage files from R Studio -

i have installed r-studio on google cloud platform compute instance. default working directory on r-studio is: /home/rstudio then mounted cloud storage bucket on compute instance. mounted image path is: /mnt/gcs-bucket but when try read files located in directory on r studio using: r<-read.csv("/mnt/gcs-bucket/trains.csv") i following error error in file(file, "rt") : cannot open connection in addition: warning message: in file(file, "rt") : cannot open file '/mnt/gcs-bucket/trains.csv': permission denied how can give permissions on files accessible r-studio. have tried: chmod 777 /mnt/gcs-bucket/trains.csv but still same error. reading file on r works fine. in r-studio unable change working directory: setwd("/mnt/gcs-bucket") error in setwd("/mnt/gcs-bucket") : cannot change working directory

Python Plus-Equals Syntax Error for Items in List -

why python code result in syntax error @ equal sign? can it? start_pos = [0, 0] direction = [1, 1] end_pos = [start_pos[0] += direction[0], start_pos[1] += direction[1]] i had expected instantiate end_pos , increment start_pos direction , in ruby. as @pm 2ring said, assignments don't return value in python. lists mutable. can define addition assignment returns result. for instance: >>> def add_assignment(a, b): ... a[0] += b[0] ... a[1] += b[1] ... return ... >>> start_pos = [0, 0] >>> direction = [1, 1] >>> end_pos = add_assignment(start_pos, direction) >>> print start_pos, end_pos [1, 1] [1, 1]

html - Pure javascript drag not smooth on iPad -

i trying drag div ( #drag ) in it's parent ( #container ) pure javascript only . ( only need work on ipad ). i wrote script work fine when use in chrome "emulate touch events" turned on, but on real ipad, start dragging little fast div stop following. i thought finger might out of element when move fast, so set addeventlistner on body instead of div, still same. anyone have idea why? , how make work smoothly on ipad? demo : http://jsfiddle.net/kxrez/ javascript var dom = { container: document.getelementbyid("container"), drag: document.getelementbyid("drag"), } var container = { x: dom.container.getboundingclientrect().left, y: dom.container.getboundingclientrect().top, w: dom.container.getboundingclientrect().width, h: dom.container.getboundingclientrect().height } var drag = { w: dom.drag.offsetwidth, h: dom.drag.offsetheight } target = null; document.body.addeventlistener('touchstart', hand

c# - When extending treeview, do I need to specify a control template or does it use the default control template -

starting make custom treeview , wondering why can't seem display. didn't change xaml except replacing treeview multiselecttreeview, yet doesn't display. if extend treeview, extended class inherit default control template of parent class? public class multiselecttreeview:treeview { #region data members private treeviewitem lastitem = null; private observablecollection<treeviewitem> selectedtreeviewitemslist = new observablecollection<treeviewitem>(); public observablecollection<treeviewitem> selectednodes { { return selectedtreeviewitemslist; } private set { selectedtreeviewitemslist.clear(); selectedtreeviewitemslist = value; } } public bool ctrldown { { return keyboard.iskeydown(key.leftctrl) || keyboard.iskeydown(key.rightctrl); } } public bool shiftdown { { return keyboard.iskeydown(key.leftshi

python - Textvariable not working with Entry (Tkinter) -

i'm having trouble entry widget tkinter in python 3.4.1 when running code, entry appears blank while expect display "var" : # -*- coding: utf8 -*- tkinter import * w = tk() v = stringvar() v.set("var") e = entry(w, textvariable = v) e.pack() w.mainloop()

php - Is the array returned by scandir() a countable object? -

i'm trying figure out why count(scandir("/dirname")); evaluates 0 when number of files in directory not 0. when person goes onto page, following script executes @ top of page: <?php setcookie("user", count(scandir("/players"))); ?> the directory contains 2 files. count(scandir("/dirname")); still evaluates 0. because array player0.json player1.json returned scandir() non countable object? assuming directory players located in same directory php file located, can pass 'players' scandir() or other function works directories. relative path , of times works. but, in order make sure code works, better use php magic constant __dir__ generated full path of players directory: scandir(__dir__.'/players') should return array contains names of files stored in players directory , passing array count() correctly return number of values contains (as now). to answer question in title, on

php - Passing Array through Post and Pulling data from db -

so i'm passing along information previous form via post array. when attempt pull information database, not finding records. yet data dump showing array "pre_fodder" has values. array 'item' coming empty. =( html <div> stuff here <br /> <input type="checkbox" name="pre_fodder[]" value="<? item[item_id} ?>" /> </div> <div> stuff here <br /> <input type="checkbox" name="pre_fodder[]" value="<? item[item_id} ?>" /> </div> <div> stuff here <br /> <input type="checkbox" name="pre_fodder[]" value="<? item[item_id} ?>" /> </div> php $i = 0; $a = count($_post['pre_fodder']); while ( $i < $a ) { print_r ($_post[pre_fodder][$i]); $_post[pre_fodder][$i] += 0; print_r ($_post[pre_fodder][$i]); $data = "select * items invento

c# - Parameterized Linq Query -Is there a better performance option? -

i using following parameterized linq query expression query approximately 100,000 records in sql server. there better way? public ilist<article> getarticles(string language, string category, string subcategory, bool exclusives, int pageindex, int pagesize = 200) { iqueryable<article> query; query = db.articles.where(t => t.isactive && t.articlestatus); if (exclusives) { query = query.where(t => t.isexclusive); } if (language.toupper() != "all") { query = query.where(t => t.language.toupper() == language); } if (category.toupper() != "all") { query = query.where(t => t.category.toupper() == category); } if (subcategory.toupper() != "all") { query = query.where(t => t.subcategory.toupper() == subcategory); } query = query.where(t => t.articledate <= datetime.now);

mysql - INSERT WHERE NOT EXISTS clause using python variables -

i attempting write sql query insert rows table when script run. have been able working whilst duplicating data, unable set insert can determine whether or not record unique. i have tried following these threads: most efficient way sql 'insert if not exists' python mysqldb / mysql insert ignore & checking if ignored currently, can system add records, due frequency script ran @ database being filled same records. current code: for post in r.get_subreddit("listentothis").get_new(limit=5): if 'youtube.com' in post.url or 'youtu.be' in post.url: print(str(post.title)) print(str(post.url)) sql = """insert listentothis2(title,url) values ('%s', '%s') not exists (select 1 listentothis2 url = '%s') """ % (post.title, post.url, post.url) try: cursor.execute(sql) db.commit() except: db.rollback() i have tried: sql = """insert ignore

qml - Saving JS Object (variant or var) in settings -

when write this: property bool token: false settings { property alias token: root.token } and change token somewhere in application true , next time when run application token true . but when write this: property var token: null settings { property alias token: root.token } and change token {'a': 'b'} example, next time run application token null settings doesn't save js object. idea what's wrong here? update: seems problem not saving js object {'a': 'b'} , qml saves successfully, problem null if change false works alright. guess it's related question storing data using settings element in qml don't understand why null being post processed, though using false instead of null default value property solves problem don't don't want false here, it's not appropriate morally, want null . update 2: found solution, setting no default value property (not false nor null ) seems solve issue , seem

php - How to wrap multiple blocks -

i need wrap custom number of blocks on page apply grid system them. i know setblockwrapperstart() , setblockwrapperend() , these applied after each block generated. let's have 12 blocks of given type , want wrap first 1 @ beginning <div class="row"> , after 4th 1 want append </div> . , next (5th block) want start <div class="row"> again... is there way implement concrete 5? use standard output right , couldn't figure out how add loop or implement approach: $b = new area('test block'); $b->display($c); i'm using concrete 5.6.3.4. thank you! i think might have use quick , dirty hack , add html blocks markup in them in between other blocks

java - Difference in rolling back a statement and a transaction in JPA -

jpa query javadoc (see http://docs.oracle.com/javaee/6/api/javax/persistence/query.html#executeupdate() ) says int executeupdate() execute update or delete statement. returns: number of entities updated or deleted throws: illegalstateexception - if called java persistence query language select statement or criteria query transactionrequiredexception - if there no transaction querytimeoutexception - if statement execution exceeds query timeout value set , statement rolled persistenceexception - if query execution exceeds query timeout value set , transaction rolled what's difference between rolling statemente , transaction? mean, rolling transaction pretty obvious, set transaction rollback , operations undone. if statement rolled (since it's update/delete/insert operation), won't whole transaction rolled in situation? was querytimeoutexception designed caught , allow user retry on timeout without affecting transaction? [a querytimeoutexcepti

graphics - How do I create an onClick drawLine function in swift? -

i need create function make line connecting 2 buttons when pressed. however, way can figure out how create line predetermined start , endpoint. func drawlinefrom(frompoint: cgpoint, topoint: cgpoint) { uigraphicsbeginimagecontext(view.frame.size) let context = uigraphicsgetcurrentcontext() cgcontextsetlinewidth(context, 3.0) /* setting line width: set let , width next (let, width) */ cgcontextsetstrokecolorwithcolor(context, uicolor.purplecolor().cgcolor) cgcontextmovetopoint(context, oldlocation.x, oldlocation.y) cgcontextaddlinetopoint(context, newlocation.x, newlocation.y) cgcontextstrokepath(context) uigraphicsendimagecontext() } when call function, in class, testing, have figured out entire thing runs, , oldlocation , newlocation have appropriate values create line. however, no line created (or @ least not visible). there command neglecting run, or else problem?

java - executable jar from eclipse unable to use images within packages... sometimes -

i have wrote swing application , works fine in eclipse when export runnable jar parts of application fail, when dealing images, line example; logo = getclass().getresource("/com/cogentautomation/logo.jpg").getpath(); eclipse packaging images in com.cogentautomation package , can see in .jar itself, have tried both export methods, extract required libraries , package required libraries, 1 says; filenotfoundexception com\cogentautomation\logo.jpg the other says; filenotfoundexception file:\c:\documents\hs.jar!\com\cogentautomation\logo.jpg i using library parse out pdf file, error occurring, works in eclipse , other images on disk aren't java resource. i've read other topics on problem nothing seemed help. edit: addressing in comments, require string variable library using requires string input read image; import org.pdfclown.documents.contents.entities.image; image image = image.get(logo); based on javadocs org.pdfclown.documents.conte