Posts

Showing posts from July, 2011

r - Add datapoints to existing scatterplot -

Image
i have existing ggplot2 scatterplot shows results of parameter against normal database. want add 2 additional points graph pass command line arguments script script age value1 value2 . show these points red r , l geom_text above each point. have following code far not know how add finishing touches pkgload <- function(x) { if (!require(x,character.only = true)) { install.packages(x,dep=true, repos='http://star-www.st-andrews.ac.uk/cran/') if(!require(x,character.only = true)) stop("package not found") } } pkgload("ggplot2") #load current normals database df<-data.frame(read.csv("dat_normals.txt", sep='\t', header=t)) args<-commandargs(true) #specify each argument age <- args[1] rsbr <- args[2] lsbr <- args[3] # run regression , append prediction intervals lm_fit = lm(sbr ~ age, data = df) sbr_with_pred = data.frame(df, predict(lm_fit, interval='prediction')) p <- ggplot...

tfs - Team Foundation Server 2015 git repo with submodules on external git servers -

Image
i've got team foundation server 2015 installed. working great expect 1 thing. i working 2 main git repositories (created team projects). build first repository works great build second repository has problems. the first has sub-modules live on tfs git server itself. build works great here. the second has sub-modules live on different git server. when build runs tfs fails obtain submodules: ****************************************************************************** starting: sources ****************************************************************************** syncing repository: my_app (git) checking out dbab6... c:\tfsbuildagents\agent-utp120w-1\_work\5\s submodules object not found - no matching loose object (f8334...) prepare repository failed exception. (i've abbreviated sha's here simplicity) the sha starts f8334... submodule lives on external git server. guess error: object not found - no matching loose object actually has credenti...

ios - NSURLSession gets the data properly, but returns nothing after Task.resume() -

this question has answer here: returning data async call in swift function 4 answers i trying connect http server data in json format. connects , gets data properly. able print data before task.resume() but, doesn't print after task.resume() also, function returns empty object. i tried saving global variable before task.resume() . so, can use getter method data, still returns empty. can please tell me doing wrong here. in advance func getticketinfo(rdate: string, rname: string) -> nsdictionary { var obj = nsdictionary() let request = nsmutableurlrequest(url: nsurl(string: self.host)!) request.httpmethod = "post" let poststring = "&drivername=\(self.username);&password=\(self.password);&function=getticketprintinvoiceinfo;&routename=\(rname);&routedate=\(rdate);"; request.httpbody = poststring....

Building and Running on a device from Android Studio -

to run application on device think have ensure app. debuggable setting android:debuggable attribute of <application> element true in build.gradle file, (as says in doc. http://developer.android.com/tools/building/building-studio.html ) how file looks like: // top-level build file can add configuration options common sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.2.3' // note: not place application dependencies here; belong // in individual module build.gradle files } } allprojects { repositories { jcenter() } } you targeting wrong build.gradle (top level). need in lower level build.gradle in android block: android { //... buildtypes { debug { debuggable true } customdebuggablebuildtype { debuggable true } release { debuggable ...

ios - How should I tidy UIViewControllers when they need to be destroyed -

i'm starting write second version of our iphone app , i'm trying tidy previous mistakes (as it's first attempt @ objective-c). question related "things need when uiviewcontroller destroyed", there seem few contradictory answers out there , want make sure understand correctly. couple of constraints: this code use ios 5 , ios 6 devices i don't wish register , deregister nsnotifications on viewwillappear , viewwilldisappear because uiviewcontrollers need receive notifications if can't seen user. i'm using storyboard rather separate nib files. so considering above constraints, following statements true? iboutlets connecting storyboard uiviewcontrollers should weak, strong reference created behind scenes. because iboutlets weak shouldn't need nil them out in low memory situations i shouldn't use viewdidunload because it's being deprecated instead should use didreceivememorywarning. in situation need nil out strong properties (...

python - Getting logged in User's Profile in Django without repeating request.user a lot? -

the application writing in django requires me userprofile model object (which has one-to-one relationship standard django user object) in lot of views. user's profile, end repeating quite bit in different views: user_profile = userprofile.objects.get(user=request.user) or user_profile = userprofile.objects.get(user=self.request.user) i know software engineering principles don't repeat (dry), wondering if there way encapsulate code above in separate method or if it's fine keep way is. thanks in advance help! add related name userprofile in models.py class userprofile(models.model): user = models.onetoonefield(user, related_name='profile') = models.textfield(default='') then in views.py , reference with request.user.profile.about = 'abc' request.user.profile.save() or make shorter p = request.user.profile p.about = 'abc' p.save()

when startKey is unknown how to implement strategy for couchdb/pouchDb -

numerous readings indicate skip should avoided when doing pagination. in link cite using startkey , limit way go. after first page know startkey of page, lastkey of page , total entries. if have pagination control page numbers buttons , user selects page 3, how there? have no idea startkey of page3. perhaps, simple view front go start keys each page. this page nicely describes pagination: http://docs.couchdb.org/en/1.6.1/couchapp/views/pagination.html so, can't have "go page 298", have links previous , next 5 pages, can larger number of preceeding , following documents , generate links accordingly. example, if have 10 posts per page, 50 following keys , take every 10th one. as making "go page x", perhaps background script generates somesort of cache?

vb.net - Visual Studio Button code error -

this first time using visual studio , i'm running error tax calulator application. problem visual studio saying multiplication line using "*" , "+" can not done due variables being text boxes. question community, should change text box else? or in code did mess up. public class form1 private sub btncalc_click(byval sender system.object, byval e system.eventargs) handles btncalc.click if (isnumeric(txtsale) , isnumeric(txtsalestaxrate)) lbltax = txtsale * txtsalestaxrate lbltotal = txtsale + lbltax else msgbox("please enter valid numbers, thank you!") end if end sub end class if need me give full layout of application, ask. i can see multiple problems in code. explain how "vs" works.the textboxes you've made controls. you can't take value simple.they have many property , 1 of them .text allows take value inside them. another mistake you've made ...

c# - Event Handler issue -

i found code online c#. used telerik code converter convert vb.net. getting error below code closed declared 'public closed(sender object, e system.eventargs)' in class. same error happens shown well. have ideas fix? #region "events" public event closed eventhandler public event shown eventhandler protected overridable sub closed(e eventargs) dim handler eventhandler = closed raiseevent handler(me, e) end sub protected overridable sub shown(e eventargs) dim handler eventhandler = shown raiseevent handler(me, e) end sub #end region here c# code converted vb. #region events public event eventhandler closed; public event eventhandler shown; protected virtual void closed(eventargs e) { eventhandler handler = closed; if (handler != null) handler(this, e); } protected virtual void shown(eventargs e) { eventhandler handler = shown; if...

ruby - "Remember me" option - how do I implement it? -

i have simple authentication system in sinatra application. it's set session[:user_id] user's id when user enters correct login , password , that's it. enough now , won't use solutions. what need make "remember me" option. how can simple solution? can't figure out. the way i've done (we're using omniauth authentication , mongoid user storage - login form uses ajax reply json). html field corresponds "remember me" checkbox called "remember": post '/auth/identity/callback' u = user.find(env['omniauth.auth']['uid']) session[:user] = u session.options[:expire_after] = 2592000 unless params['remember'].nil? # 30 days [200, {:msg => 'user logged in'}.to_json] end the key here sessions.options[:expire_after] line. if don't set :expire_after, cookie automatically deleted when browser quits. once set it, cookie becomes persisten across browser restarts, , kept nu...

iphone - How Do I Switch Views With PageControl & UIScrollView? -

i'm noob iphone development (3rd day in xcode) , trying implement pagecontrol , scrollview users can swipe between various pages. i'm using this tutorial , can't figure out how load/switch views nib files opposed changing background color of view. appreciated. my code modification of pagecontrolexampleviewcontroller.m renamed newsclass2 // creates color list first time method invoked. returns 1 color object list. + (uicolor *)pagecontrolcolorwithindex:(nsuinteger)index { if (__pagecontrolcolorlist == nil) { __pagecontrolcolorlist = [[nsarray alloc] initwithobjects:[uicolor redcolor], [uicolor greencolor], [uicolor magentacolor], [uicolor bluecolor], [uicolor orangecolor], [uicolor browncolor], [uicolor graycolor], nil]; } // mod index list length ensure access remains in bounds. return [__pagecontrolcolorlist objectatindex:index % [__pagecontrolcolorlist count]]; } //changing views instead of colors, not working + (uiview *)pa...

facebook graph api - Getting all commets for an event with FQL -

i trying list comments event created page. getting eid for event multiquery this: { 'eids':' select eid, uid event_member uid = 64565465464 'events':' select eid, name, venue, location, start_time, creator event eid in (select eid #eids) , creator = 64565465464 order start_time asc'} i totally clueless how comments event eid. does know how? you use stream fql table. source_id on table relates eid of event table. example query via above multi-query: select message stream source_id in (select eid #eids) docs: https://developers.facebook.com/docs/reference/fql/stream

html - Django forms with custom bootstrap layout -

i'm running django 1.9 bootstrap. use pure django, without crispy forms etc. time ago struggling forms customization under bootstrap. friend proposed me solution. it's working, me looks heavy. is there other, simpler way make use of django , bootstrap forms? need, populate values in form , send them successfuly django backend. <div class="form-group row"> <label for="price" class="form-control-label col-md-3">price</label> <div class="col-md-9"> <input type="number" class="form-control" value="{{ form.price.data|default:'' }}" name='price' id='price' placeholder="price"> </div> </div> you can render {{ form }} each field in html form, whith bootstrap classes in example: <form action="" method="post"> <div class="row"> ...

swift - RealmSwift and watchos2 -

Image
using realmswift-0.97.0 , watchos2, have following error when trying run watchkit-app first time: dyld: library not loaded: @rpath/realm.framework/realm referenced from: /users/.... reason: image not found what mistake ? i using following podfile incorporate realmswift project : xcodeproj 'isquash.xcodeproj' workspace 'isquash.xcworkspace' platform :ios, '9.0' inhibit_all_warnings! source 'https://github.com/artsy/specs.git' source 'https://github.com/cocoapods/specs.git' use_frameworks! link_with 'isquash', 'isquash watchkit extension' def shared_pods pod 'realm' pod 'realmswift' end target 'isquash' shared_pods end target 'isquashtests' shared_pods end target 'isquash watchkit extension' platform :watchos, '2.0' shared_pods end the same podfile have used bevore (with watchos1.2 , earlier version of realmswift...) appreciated ! ! ...

Get screenshot of surfaceView in Android -

in application have view buttons , surfaceview. must take screenshot of view, in place of surfaceview black field. try solutions found on stackoverflow, don't work me. this code usualy take screenshots: file folder = new file(environment.getexternalstoragedirectory().getpath() + "/folder"); if (!folder.exists()) { folder.mkdir(); } string path = folder.getabsolutepath() + "snapshot.png"; file file = new file(path); file.createnewfile(); view view = this.findviewbyid(android.r.id.content).getrootview(); view.setdrawingcacheenabled(true); bitmap drawingcache = view.getdrawingcache(); bitmap bitmap = bitmap.createbitmap(drawingcache); fileoutputstream fos = null; try { fos = new fileoutputstream(file); bitmap.compress(compressformat.png, 100, fos); } { bitmap.recycle(); view.setdrawingcacheenabled(false); if (fos != null) { try { fos.close(); } catch (ioexception e) { log.e(tag, e.getmessage(...

android - Adding header to ListView not matching parent in width -

Image
the individual layout files fine ( match_parent fills parent), when try set header of listview , behaves differently. the way see is: button's width, matching parent layout's width, not sure why doesn't work. actual: expected: i couldn't code formatting here work here pastebin links them. header_layout.xml <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".mainactivity"> <linearlayout and...

c# - Use LINQ to find duplicated rows (with list of specified columns) -

i use code below duplicated rows 3 columns: string, date, money. wonder if there general method can input dynamic list of column name in linq find duplicated rows? datatable allduplicates = dt.asenumerable() .groupby(dr => new { field1 = dr.field<object>("string"), field2 = dr.field<object>("date"), field3 = dr.field<object>("money"), }) .where(g => g.count() > 1) .selectmany(g => g) .tolist().copytodatatable(); } how custom arrayequalitycomparer<t> type (such 1 listed here ): string[] colstoconsider = ... var allduplicates = dt.asenumerable() .groupby(dr => colstoconsider.select(dr.field<object>) .toarray(), new arrayequalitycomparer<object>()) .where(g => g.count() > 1) .sel...

c# - Null reference error while inflating a textview -

i'm adding textview header listview, in xamarin android app. following instructions in ericosg's answer this question , put textview in separate axml file, , tried add header list view. running app gets following error @ line activity tries inflate textview: [monodroid] unhandled exception: [monodroid] android.content.res.resources+notfoundexception: exception of type 'android.content.res.resources+notfoundexception' thrown. . . . [monodroid] --- end of managed exception stack trace --- [monodroid] android.content.res.resources$notfoundexception: resource id #0x7f050006 type #0x12 not valid [monodroid] @ android.content.res.resources.loadxmlresourceparser(resources.java:2250) etc. here code: in activity .cs file: mylistview = findviewbyid<listview>(myapp.resource.id.mylist); android.views.view myheader = this.layoutinflater.inflate(myapp.resource.id.questiontext, mylistview); mylistview.addheaderview(myheader); ...

ecmascript 6 - TypeScript Importing from libraries written in ES5 vs. ES6 -

i weird errors when running transpiled typescript code depends on external libraries such uncaught typeerror: es5_lib_1.default not function what's wrong? the es6 module spec differ commonjs, described here . introduces compatibility issues exasperated in typescript. typescript tries guess correct way transpile import/require statements based on 2 inputs the module property in tsconfig.json how export statement written in corresponding .d.ts file in tsconfig.json file, can set module format transpiled output use. example, module: 'es6' what choose here have impact on kind of importing syntax typescript allow. impacted how corresponding .d.ts shape files written. if importing from commonjs library , our output module targets commonjs, must use //tsconfig.json module: "commonjs" //.d.ts declare module 'foo' { exports = foo; } // app.ts import foo = require('foo'); if importing from commonjs library , o...

How can the argument to a batch file be intrun passed onto a powershell script? -

i trying call powershell script through bat file such below; bat file name script .bat , current cuntents below; powershell -sta -windowstyle hidden script.ps1 i passing argument bat file how can pass on powershell script in bat file? please let me know if questions or confirmations needed. in shell script (batch file), can write: powershell -file script.ps1 %1 %1 replaced shell script's first command-line argument, passed first argument script.ps1. bill

mysql - how to group by multi-index(including initial number index and other columns) in python dataframe? -

i working on groupby in python's pd.dataframe. task in code want group data because want make sure no matter how many times query , output data mysql, won't mess raw data. df1=pd.dataframe(df) #this dataframe multiple different lines of 'open' 1 'symbol' df2=pd.read_sql('select * 6openposition',con=conn) df2=df2.append(df1) df2=df2.groupby(['symbol']).agg({'open':'first'}) df2.to_sql(name='6openposition', con=conn, if_exists='replace', index= false, flavor = 'mysql') #example raw data: symbol open 0 10 1 aa 20 2 aa 30 3 aaa 40 4 aaa 50 5 aaa 50 #after query data multiple times(i appended): symbol open 0 10 1 aa 20 2 aa 30 3 aaa 40 4 aaa 50 5 aaa 50 0 aa 30 1 aaa 40 2 aaa 50 3 aaa 50 4 aaa 60 #how code ended with: symbol open 0 10 1 aa 20...

java - Need to Remove From List at Specified Multiple Indices, without new-size problems -

this question has answer here: remove multiple elements arraylist 16 answers i have array of indices @ elements must removed list, e.g.: (4), (7), (8). the problem is: 1) can't use for-loop, size changes after each delete ( arraylist.remove(i) ) 2) can't use iterator updated counter, counter not work anymore ( iterator.remove() ). found nice solution here: remove multiple elements arraylist collections.sort(indices, collections.reverseorder()); (int : indices) strs.remove(i); that seems fast , simple solution. reverse-sort first, go through indices , remove.

javascript - Jasmine shared specs scoping issues with coffeescript -

i'm attempting dry jasmine tests extracting out shared examples. @sharedexamplesforthing = (thing) -> beforeeach -> @thingy = new thing "is neat", -> expect(@thingy.neat).tobetruthy() describe "widget shared behavior", -> sharedexamplesforthing(-> new widget) this works nicely when defined in 1 file. problems i'm encountering occur when try move sharedexamples separate file. can't find variable: sharedexamplesforthing ... so in interest of debugging, tried following: describe "widget shared behavior", -> "is acting meany", -> console.log sharedexamplesforthing expect(false).tobetruthy() sharedexamplesforthing(-> new widget) in is acting meany block, log shows sharedexamplesforthing [function] still can't find variable outside it . feel might have scoping issue outside of current experience, wrong that. missing here? (using rails, jasminerice, guard-jasmine...

ios - Apple Store review guidelines, capabilities -

my app uses remote push notifications , works fine in app. app dosent have crashes or using push notifications (from parse.com). can see @ 1:18 . i have followed tutorial on parse setting push notifications . have developer provisioning profiles , enabled push notifications on app id. need set remote notifications , push notifications on in capabilities, before sending in review? you should go , send app review! if have push notification these things apple can reject app for: apps provide push notifications without using apple push notification (apn) api rejected apps use apn service without obtaining push application id apple rejected apps send push notifications without first obtaining user consent, apps require push notifications function, rejected apps send sensitive personal or confidential information using push notifications rejected apps use push notifications send unsolicited messages, or purpose of phishing or spamming rejected apps cannot use p...

ruby - download a pdf file with webcrawler -

i'm beginning use ruby programming language. have ruby script crawl pdf files on page anemone: anemone.crawl("http://example.com") |anemone| anemone.on_pages_like(/\b.+.pdf/) |page| puts page.url end end i want download page.url using gem ruby. gem can use download page.url? no need gem, try this require 'anemone' anemone.crawl("http://www.rubyinside.com/media/",:depth_limit => 1, :obey_robots_txt => true, :skip_query_strings => true) |anemone| anemone.on_pages_like(/\b.+.pdf/) |page| begin filename = file.basename(page.url.request_uri.to_s) file.open(filename,"wb") {|f| f.write(page.body)} puts "downloaded #{page.url}" rescue puts "error while downloading #{page.url}" end end end gives downloaded http://www.rubyinside.com/media/poignant-guide.pdf and pdf fine.

php - Designing a service container: SRP, choosing the right creational pattern and avoiding tight coupling -

i'm writing own implementation of laravel service container practice design patterns , later make private microframework. the class looks right now: class container implements containerinterface { /** * concrete bindings of contracts. * * @var array */ protected $bindings = []; /** * lists of arguments used class instantiation. * * @var array */ protected $arguments = []; /** * container's storage used store built or customly setted objects. * * @var array */ protected $storage = []; /** * returns instance of service * * @param $name * @return object * @throws \reflectionexception */ public function get($name) { $classname = (isset($this->bindings[$name])) ? $this->bindings[$name] : $name; if (isset($this->storage[$classname])) { return $this->storage[$classname]; } return $this->make($...

Preload WebView in Xamarin Forms on iOS -

i have webview in contentpage instantiating , setting url webview in constructor. later showing contentpage pushmodalasync. thing is, webview doesn't seem attempting load until push. there way have preload in background instead of waiting until shown? you can fetch content using httpclient , load webview html data webview.source = new htmlwebviewsource() { baseurl = urlpreloaded, html = httpclientdata} in way, html data pre-loaded.

android - Xamarin Forms QR code scanner blank screen -

i have xamarin forms 2.0 application uses zxing.net.mobile , zxing.net.mobile.forms version 2.0.3.1. i'm trying build simple qr code scanner, whenever launch zxingscannerpage on android can see default overlay (with text , red line) don't see output of camera can't scan anything. have listed camera permission in androidmanifest: <uses-permission android:name="android.permission.camera" /> i tried sample code readme: https://github.com/redth/zxing.net.mobile samples/forms project. have code: private async void onscanqrclicked(object sender, eventargs e) { _scannerpage = new zxingscannerpage(); _scannerpage.onscanresult += handlescanresult; await navigation.pushasync(_scannerpage); } private void handlescanresult(result result) { _scannerpage.isscanning = false; device.begininvokeonmainthread(() => { navigation.popasync(); displayalert("scanned code", result.text, "ok"); }); } ...

Javascript regex replace is not working sometimes -

i using regex search words same , replace same ones. replaced word changes original word time time. i'm not sure why. here code. function censor(word, string){ var newstring = ''; var replacestring = ''; var rand = math.floor(math.random() * 10) + 1; for(var x = 0 ; x < word.length ; x++){ switch (rand) { case 1: replacestring += '!'; break; case 2: replacestring += '@'; break; case 3: replacestring += '#'; break; case 4: replacestring += '$'; break; case 5: replacestring += '%'; break; case 6: replacestring += '^'; break; case 7: replacestring += '&'; break; case 8: replacestring += '*'; break; case 9: replacestring += '('; break; ...

javascript - What are the best practices to get React JS private methods? -

when set component or element callback event, tutorials , documentation show code this: 'use strict'; import react 'react'; let foocomponent = react.createclass({ handleclick(args) { ... }, render() { return <div> <h1>some title</h1> <button onclick={this.handleclick}>click me!</button> </div> } }; export default foocomponent; but handleclick method can accessed out of component, if i'd use foocomponent on component , assign reference can access handleclick other component. 'use strict'; import react 'react'; import foocomponent './foocomponent'; let barcomponent = react.createclass( handlebarcomponentclick(e) { this.refs.foocomponent.handleclick(null); }, render() { return <div> <foocomponent ref="foocomponent" /> <button onclick={this.handlebarcomponentclick}>other click</button> </div> } )...

mysql - Unable to delete database "Waiting for table metadata lock" Error -

i copying db rds server, using phpmyadmin copy, same server, 1 table contains huge number of records, , after approximately hour still not completed, killed copy process, unable delete database, whenever try delete table or drop target database,query stops responding , when fetch process list, "waiting table metadata lock" state there.

python - GPS Daemon on Raspberry Pi -

i'm trying implement sample script adafruit provides 1 of gps units designed raspberry pi. code follows: ============== import gps # listen on port 2947 (gpsd) of localhost session = gps.gps("localhost", "2947") session.stream(gps.watch_enable | gps.watch_newstyle) while true: try: report = session.next() # wait 'tpv' report , display current time # see report data, uncomment line below # print report if report['class'] == 'tpv': if hasattr(report, 'time'): print report.time except keyerror: pass except keyboardinterrupt: quit() except stopiteration: session = none print "gpsd has terminated" ============== so add "#!/usr/bin/python -tt" top of "gps.py" file , "chmod u+x /home/pi/gps.py" upon runnin...

certificate - Getting PKCS7 signer chain in python -

i have pkcs7 message signed. contains data , signing certificate (with whole chain of trust). i have code uses m2crypto certificate out of it. bio = bio.memorybuffer(pkcs7message) p7 = smime.pkcs7(m2.pkcs7_read_bio_der(bio._ptr())) sk = x509.x509_stack() certstack = p7.get0_signers(sk) it works. however, certstack returns 1 certificate (instead of returning whole chain of certificates. two questions: am missing (may there option let know need whole chain) are there other methods how whole chain (may using pyopenssl)? i guess making confusion between signers , certificate chain of signer. pkcs7_get0_signers return list of signers. in order building pkcs7 message 2 signers, can use following steps: build key , certificate first signer: openssl genrsa -out key1.pem openssl req -new -key key1.pem -subj "/cn=key1" | openssl x509 -req -signkey key1.pem -out cert1.pem build key , certificate second signer: openssl genrsa -out key2.pem openssl req...

swift - Cannot change the size of a popover -

i've been trying create own code, copy , paste examples, popover seems fill entire screen. code looks below, said, i've tried @ least 2 other examples (some cgsizemake(), sourcerect, sourceview), , results same. class tableview: uitableviewcontroller, uipopoverpresentationcontrollerdelegate { let popover = uiviewcontroller() func somebutton() { popover.modalpresentationstyle = .popover popover.preferredcontentsize = cgsize(1, 1) let menu = popover.popoverpresentationcontroller menu!.delegate = self menu!.barbuttonitem = someothercorrectbutton self.presentviewcontroller(popover, animated: true, completion: nil) } } what's problem? try below code popover.modalpresentationstyle = .popover var popupheight:cgfloat = 542 let popupwidth = 400 cgfloat popover.preferredcontentsize = cgsizemake(400,popupheight) let window = uiapplication.sharedapplication().delegate!.window!! ...

arrays - Exception : java.lang.ArrayIndexOutOfBoundsException -

i getting error: exception in thread "main" java.lang.arrayindexoutofboundsexception: 2 @ javaproject.main(javaproject.java:70) here code: try { printwriter writer = new printwriter("gamer report data.txt"); writer.println("player: " + gamername); writer.println(); writer.println("-------------------------------"); string[] report = gamerreport.split(gamerreport, ':'); writer.println("game:" + ", score=" + report[1] + ", minutes played=" + report[2] + report[3]); writer.close(); } catch (ioexception e) { system.err.println("file not exist!"); } i believed related for loop, have had no luck changing around. import java.util.scanner; import java.io.filewriter; import java.io.ioexception; import java.util.arrays; import java.io.printwriter; public class javaproject { private static char[] input; @suppresswarnings("null") pub...

javascript - How to reset bootstrap modal to its original contents on close? -

p.s not in javascript , know question has been asked solutions not apply problem ask question again. i'm stuck problem , haven't find solution yet. wanted clear things happened modal after close. my modal form modal, whenever click submit, codeigniter validation messages show use of ajax on <div style="font-size:10px;width:50%;" id="info"></div> . whenever close modal, validation messages stays when re-open it. should done in order clear out after closing modal? this function called ajax: public function addcomp () { $this->load->library('form_validation'); $this->load->helper('security'); $this->form_validation->set_rules('comp_name','computer name','trim|required|callback_pc_exist'); $this->form_validation->set_rules('status','status','trim|required'); $this->form_validation->set_rules('location','location','t...

Authenticate with OneDrive SDK in Xamarin Android App -

i use onedrive sdk in cross plattform app. on windows authentication works via onedriveclientextensions.getclientusingwebauthenticationbroker. now i'm trying login on android. tried this: onedriveclient = onedriveclient.getmicrosoftaccountclient( appid: msa_client_id, returnurl: return_url, scopes: scopes, clientsecret: msa_client_secret); await onedriveclient.authenticateasync(); but error no valid token received. have implement own authenticationprovider inhereting webauthenticationbrokerauthenticationprovider shows browser oauth? or way go here? i solved using xamarin auth component. heres code calls webview login: private const string return_url = @"https://login.live.com/oauth20_desktop.srf"; private void showwebview() { var auth = new oauth2authenticator( clientid: msa_client_id, scope: string.join(...

vba - Can we continue doing work while macro is running on another MS-WORD instance? -

is possible run microsoft word instance while macros running in of document? not able run asking for. my code overview below. with activedocument.range if .hyperlinks.count > 0 url = .hyperlinks(1).address ie .visible = false .navigate url until .readystate = 4: doevents: loop ie.execwb 17, 0 '// selectall ie.execwb 12, 2 '// copy selection end paste , formate the problem above code .readystate = 4, not able work. there solution problem? edit after having knowledge comments, add. i have saved vba in word module. can run macro asynchronously anywhere else opening specific document, , still continue working on other document of word. tried excel still not able open other word instance.

javascript - Angular how to submit and validate form with <a> -

<!doctype html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- <link rel="stylesheet" type="text/css" href="login.css"> --> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-messages.min.js"></script> </head> <body ng-app="loginapp"> <div class="container"> <div class="login_logo"> </div> <div class="form_container" ng-controller="loginctrl" > <div class="error_msg" ng-if="form_login.username.$dirty" ng-messages="form_login.username.$error"> <div class="alertmsg" ng-message="required"...

git - Print percentage of dissimilarity -

sometimes when drastically change file, triggers rewrite: yes | head -256 > pa.txt git add . git commit -m qu truncate -s128 pa.txt yes n | head -64 >> pa.txt git commit -am ro result: [master 79b5658] ro 1 file changed, 128 insertions(+), 256 deletions(-) rewrite pa.txt (75%) however not happen smaller changes: yes | head -128 > pa.txt git add . git commit -m qu truncate -s64 pa.txt yes n | head -32 >> pa.txt git commit -am ro result: [master 88ef937] ro 1 file changed, 32 insertions(+), 96 deletions(-) can run command show percent change regardless of amount? looked git diff-tree , again seems show when change drastic. git diff -u10000 | awk ' /^i/ {getline; next} /^-/ {pa += length} /^ / {qu += length} end {printf "%.0f%\n", pa/(pa+qu)*100} ' force full context -u10000 filter out --- lines filter in deletions , context lines count bytes each

swift2 - Adding a failable initializer with the same signature as super class's convenience initializer (Swift) -

i know why cant define init?() subview . compiler warms me failable initializer 'init()' cannot override non-failable initializer . understanding convenience init not treat override in subclass compile warm me if add override init?() initializer not override designated initializer superclass . my expectation subview.init?() should not treat override view.init() subview should not have convenience initializer inherited subview.init() in first place. import foundation import uikit class view { convenience init() { self.init(frame: cgrectzero) } init(frame: cgrect) { } required init?(coder adecoder: nscoder) { } } class subview: view { private var value: string! init?() { super.init(frame: cgrectzero) } required init?(coder adecoder: nscoder) { fatalerror("init(coder:) has not been implemented") } } see 'self explanatory' example class base { var i:int init...

php - How to do this multiple IF statement in MySQL -

i have table: scanner name | maxwidth | maxlength ==================================== scanner | 50 | 100 scanner b | 60 | 120 in php have: $paperw = 70; $paperl = 55; how mysql query result return: scanner name ============ scanner b the idea find scanner fits paper size. although paper width 70 , length 55, , printer b have max width of 60, can rotate paper orientation paper width becomes 55 , length becomes 70 fit scanner b. in pseudo-code check if scanner fits paper this: if (paperw <= maxwidth && paperl <= maxlength) return true else{ if (paperw > maxwidth){ if (paperw <= maxlength && paperl <= maxwidth) return true; else return false; } else return false; } i have no idea transalte mysql query.. appreciated. just rectangle area in php. rectarea = width * length; and use rectarea in clause. select scanner_name, max_width, max_length, (max_width ...

java - Robot and keyPress -

what sort of code need passed javafx robot when using keypress method? for example, example below enters 1 , not a , suppose there mapping somewhere. robot robot = com.sun.glass.ui.application.getapplication().createrobot(); robot.keypress(((int) 'a'); note: javafx robot, not awt one. codes defined constants in javafx.scene.input.keycode. with glass robot, can use deprecated method impl_getcode : robot robot = com.sun.glass.ui.application.getapplication().createrobot(); robot.keypress(keycode.a.impl_getcode()); you can use fxrobot, takes keycodes parameters: fxrobot robot = fxrobotfactory.createrobot(scene); robot.keypress(javafx.scene.input.keycode.a);

sql server - Normalize or denormalize varbinary in large table? -

i developing system involving 500 gb sql server database. query performance , storage complexity of concern in scale. question: table of records contains varbinary(1500) field null 90% of time. better normalize field separate table or keep as-is? performing actual test take lot of time, hoping save time asking here first.

asp.net - Could not find default endpoint element error in web application referencing own service -

i have created wcf service using asp.net 4 , trying connect inside own web application project , gives me "could not find default endpoint element" error. none of answers similar question seem me, since seem deal external project references service , missing configuration file. the service works when methods used directly (ex: js calls). any ideas? please view servicemodel section below: <system.servicemodel> <behaviors> <servicebehaviors> <behavior name="metadatabehavior"> <servicemetadata httpgetenabled = "true"/> </behavior> </servicebehaviors> <endpointbehaviors> <behavior name="webhttpbehavior"> <webhttp /> </behavior> </endpointbehaviors> </behaviors> <bindings> <webhttpbinding> <binding name="webhttpbindingwithjsonp" crossdomainscriptaccessenabled="tr...

ios - CoreData - xcode7 reference not found -

i have project using coredata written in xcode6. when make amendments entities , re-generate files 2 new files have +coredataproperties @ end. have added new entity table when try , reference error in code saying object dosent exist though when debug managed object @ run time can see object in returned list. for(products *product in data){ //set deleted true product.awaitingdelete = [nsnumber numberwithbool:true]; product.awaitingupload = [nsnumber numberwithbool:true]; } product.awaitingdelete comes error saying not found on products object. in .h file looks this.. #import "products+coredataproperties.h" @implementation products (coredataproperties) @dynamic awaitingdelete; @dynamic awaitingupload; @dynamic jobid; @dynamic ordernumber; @dynamic productguid; @dynamic productid; @dynamic productnotes; @dynamic roomname; @dynamic tobedeleted; @dynamic windowguid; @dynamic windowid; ...

algorithm - Optimize strategy results in R -

i have strategy s results of ws (the weight matrix) %*% rets (the returns of assets strategy trading). clear: pnl = cumsum(rets %*% ws) the pnl of strategy need satisfy requirements: - 0 correlation market - min weight each security xl - max weight each security xh - more assuming have optimizer able satisfy constraints above, input should put optimizer ? if put simple returns, rets , i'm not considering strategy. tried use rets * ws , i.e. securities returns multiplied respective weights of strategy, pnl after optimizer looks worse before optimizer. right way ? advice appreciated. second question: far used optimizer portfolioanalytics "deoptim" algorithm (super slow) , parma (much better, still bit slow , doesn't give documentation constraints need). used fportfolio years ago no great satisfaction. suggestion in r or should move on commercial optimizers ? thanks everyone!

cordova - ionic run android is not working -

Image
i want run android application in device,i tried commands ionic build android , ionic run android .but no error message showing. system ionic configuration is, please me?thanks in advance by changing nodejs v5.0.0 v4.2.0 resolved issue.

autocomplete - rlcompleter2 code completion in an embedded Python Interpreter? -

Image
i took this code starting point, , auto complete rlcompleter2 , there 2 problems in following code, import xxx yyy auto complete on yyy doesn't work the locals() not copied interactiveinterpreter, tried use code in autodesk maya, eg, run x=3 in maya script editor, , run x in pyqt interpreter, says nameerror: name 'x' not defined . if not use maya, error can reproduced external python interpreter well, first define variable, launch ui, variable not copied interpreter in ui. import os import re import sys import code pyqt4.qtgui import * pyqt4.qtcore import * class myinterpreter(qwidget): def __init__(self, parent): super(myinterpreter, self).__init__(parent) hbox = qhboxlayout() self.setlayout(hbox) self.textedit = pyinterp(self) # how pass in locals interpreter self.textedit.initinterpreter(locals()) self.resize(850, 400) # self.centeronscreen() hbox.addwidget(self.textedit)...