Posts

Showing posts from February, 2015

c# - Inserting spaces between chars of two strings modify their order -

this question has answer here: unexpected behavior when sorting strings letters , dashes 2 answers i have 2 strings of same length. assuming (probably wrongly) inserting space between each character of each string not change order. var e1 = "12*4"; var e2 = "12-4"; console.writeline(string.compare(e1,e2)); // -1 (e1 < e2) var f1 = "1 2 * 4"; var f2 = "1 2 - 4"; console.writeline(string.compare(f1,f2)); // +1 (f1 > f2) if insert other characters (_ x instance), order preserved. what's going on ? thanks in advance. if use ordinal comparison, right result. the reason ordinal comparison works evaluating numeric value of each of chars in string object, inserting spaces make no difference. if use other types of comparisons, there other things involved. documentation: an operation uses w...

c# - Show result of nested cursors as a single table in SQL Server -

in stored procedure shown below, have 5 cursors scroll data in several tables select information need while go through 1 of tables, using parameters of selection various columns of initial query shown in first cursor. at end execute query result of cursors. final query shows result split in tables divided code of record identified id. although records belong same entity procedure shows divided tables , need impression shown single table able pass result asp.net gridview c#. procedure created in sql server 2012. await comments , thank you. alter proc [dbo].[sp_presing] @ident int set nocount on declare mi_cursor cursor select p.idlinea, p.identidad, n.capitulo cap, n.nombre, p.anio, p.idingreso, c.tipo, c.conceptoobj, c.cuenta, c.subcuenta, c.auxiliar, c.descripcion descaux, p.idotorgante, isnull(e.nombre, '') otorg, isnull(e.capitulo, '') capotor, p.idfuente, f.fuente, p.idespecifica, t.fuenteespecifica claespecifica, t.descr...

Programmatically clicking a link in android browser using Javascript -

i'm trying click on dynamically created click-to-call link in android browser, nothing happen. create element: var link = document.createelement('a'); link.href = "tel:+1-303-499-7111"; then event , fire click: var evt = new mouseevent("click"); link.dispatchevent(evt); or even link.click(); it works fine on chrome's mobile mode , ios device, doesn't work in android browser. if create element in html <a href="tel:+1-303-499-7111">+1 (303) 499-7111</a> , click manually, working

sql server - How can I save INT in NVARCHAR column database -

i have stored procedure saves int parameter nvarchar column. if do declare @valore int set @valore = 90 insert table (valore) values(@valore) so if select valore database can see this 90.0000 insert table (valore) values(cast(@valore varchar(10))

am new to python, please share logic for below concept -

eg: ece_student_list = [['section-1', [["sai",'science'], ["rama",'maths']]], ['section-2', [["seetha",'science'], ["ravana",'maths']]]] i have print student name , subject passing key section name. for eg : if key 'section-1' first student should print "sai",'science' second student ,then should print "rama",'maths' please share logic in python. won't share code directly. have learn , experiment on own. although can tell can expect output. you can create dictionary in python , add section-1, section-2 keys , list of students value each key. your dictionary structure this: { 'section-1' : [ {'sai':'science'}, {'rama':'math'} ], 'section-2':[ {'sai':'science'}, {'rama':'math'} ] }

ios - How to detect which button user clicked on SKStoreReviewController? -

it easier keep track of data , optimize reviews based on how performed on skstorereviewcontroller prompts. but how detect button user clicked? not now? 1* 4* 5*? submitted review? you can't. if read docs skstorereviewcontroller , requestreview , you'll see doesn't expose results, ui, or whether prompt shown.

ionic3 - How to control ion-backdrop in Ionic 3? -

i have search in api docs , components list , have not found info regarding how use ion-backdrop component. if append component of own gets showed opacity set @ 0.1 , not sure if have put kind of manual timeout change or if there better way control using component itself. does knows can find docs or how show in correct way?

ios - Using 3rd party framework (Alamofire) in my sub-project (CocoaTouch framework) -

Image
i using xcode 8 + swift 3. i created fresh ios project named " myapp ". then, create cocoa touch framework project, named "mysubproject". (the idea have myapp project accessing mysubproject code.) i added mysubproject myapp project, linked mysubproject framework. in xcode project navigator looks this: myapp > mysubproject.xcodeproj everything works fine. code in myapp can access code in mysubproject . now, need add alamofire mysubproject . followed instruction in alamofire offical website manually add alamofire mysubproject , project structure looks this: myapp > mysubproject.xcodeproj > alamofire.xcodeproj so, mysubproject has dependency on alamofire framework. looke under mysubproject target--> general : after that, can access alamofire in mysubproject code, no compile error. myapp built successfully. however, when run app in emulator, got run-time error: dyld: library not loaded: @rpath/libswiftswif...

php - Updating users login time -

i have login script , want insert last login members table , update every time member logins in having issues. lastlogin not being inserted everytime user logins in. here code if(isset($_post['submit'])){ $username = $_post['username']; $password = $_post['password']; if($user->login($username,$password)){ $_session['username'] = $username; try{ $stmt = $db->prepare("update admin set login_date = now() adminid = $adminid "); $stmt->execute(); $stmt=null; } catch (pdoexeception $e){ $error[] = $e->getmessage(); } header('location: index.php'); exit; } else { $error[] = '<div class="alert alert-danger fade in text-center"> <a href="#" class="close" data-dismiss="alert">&times;</...

database - AWS Elasticache Redis failover -

i using redis on elasticache node application , today node went down means our app stopped working. took 20 minutes new node provisioned. from reading documentation seems can set cluster automatically promotes slave primary in case of failure. big gotcha seems have set client write primary node , read slave nodes. this means in case of failure, have reconfigure app point newly created 'read' nodes. takes few minutes slave promoted primary. is there no way set if primary fails, slave automatically take on read/write operations? i'm not storing data in redis , low read/write operations, required run app (live video sessions!). if can't have seamless failover in redis, there can use provides functionality? i'm hoping don't have move traditional dbms works need able handle failure well. thanks multi az's should automatically switch on minimal downtime. once have created 1 of these instances, endpoint cluster. amazon point dns entry prope...

python - count an occurrence of a string in a bigger string -

i looking understand can make code work. learning concept unlock lot in programming understanding. trying count number of times string 'bob' occurs in larger string. here method: s='azcbobobegghakl' in range(len(s)): if (gt[0]+gt[1]+gt[2]) == 'bob': count += 1 gt.replace(gt[0],'') else: gt.replace(gt[0],'') print count how refer string instead of having work integers because of using for in range(len(s)) ? try this: def number_of_occurrences(needle, haystack, overlap=false): hlen, nlen = len(haystack), len(needle) if nlen > hlen: return 0 # no occurrences n, = 0, 0 while < hlen: consecutive_matching_chars = 0 j, ch in enumerate(needle): if (i + j < hlen) , (haystack[i + j] == ch): consecutive_matching_chars += 1 else: break if consecutive_matching_chars == nlen: n += 1...

reactjs - setState doesn't apply changes to component state -

i use react v16.0.0-alpha.6 , react-native v0.44.2 . i've encountered weird situation. state changed code below. expected result. it's ok. // current this.state.searchinputvalue 'q' // coming searchinputvalue 'a' _handlesearchinputvaluechanged = (searchinputvalue) => { this.state.searchinputvalue = searchinputvalue // here searchinputvalue of state 'a' } state changed code below. expected result too. it's ok. // current this.state.searchinputvalue 'q' // coming searchinputvalue 'a' _handlesearchinputvaluechanged = (searchinputvalue) => { settimeout(()=>this.setstate({ searchinputvalue })) // after running settimeout , async setstate methods // searchinputvalue of state 'a' } however normal usage of setstate doesn't work // current this.state.searchinputvalue 'q' // coming searchinputvalue 'a' _handlesearchinputvaluechanged = (searchinputvalue) => { ...

c# - Reset and Dispose observable subscriber, Reactive Extensions -

suppose have : public class uploaddicomset { public uploaddicomset() { var cachcleantimer = observable.interval(timespan.fromminutes(2)); cachcleantimer.subscribe(checkuploadsetlist); //start subscriber } void checkuploadsetlist(long interval) { //stop , dispose subscriber } public void adddicomfile(sharedlib.dicomfile dicomfile) { //renew subscriber, call checkuploadsetlist 2 minutes later } } 1- in checkuploadsetlist want dispose or finish observable 2- in adddicomfile want reset as comment in methods. update: i can timer as: public class uploaddicomset : importbaseset { timer _timer; public uploaddicomset() { _timer = new timer(checkuploadsetlist, null, 120000, timeout.infinite); } void checkuploadsetlist(object state) { logging logging = new logging(logfile); try { _timer.dispose(); //stop subscription ...

android - What's with the "read Tango-specific data to external storage" permission? -

Image
(that's not typo way, permission asks "reading to storage".) i'm making google tango app in unity export, upload, download , import adf (area description) files , tango. somewhere along process of downloading , importing adf files, following permission dialog: (app name anonymized privacy.) i haven't been able find specific permission is, nor it's doing. questions following: why come repeatedly every file download/import? both in 1 session , after app restarts, permission dialog comes every file download , import. thought if grant app permission, have permission on? is there specific identifier permission add androidmanifest.xml ? make appear once? have <uses-permission android:name="android.permission.write_external_storage" /> <uses-permission android:name="android.permission.read_external_storage" /> in there. what allow/deny? i've tried put in print statements along download , save flow see stops me, s...

gfortran - Is there any way to call Fortran subroutine from character variable (which holds name of subroutine) instead of name of actual subroutine -

i have fortran subroutine sample . call inside program. looking way call character variable, not call sample() following program calculate character(97) :: ii='sample' call ii() ! call sample subroutine end program subroutine sample print 'something' end subroutine sample

jquery - Using .val().length != 0 to show textbox -

i working survey, note section after every question. notes should come after pressing end or f10 first time. after skipping ahead question 2, , going question 1, note section question 1 should again hidden if there no notes. however, if there writing in notes section @ all, want them remain visible after returning question 1 question 2. i trying accomplish using .val().length != 0 display notes if there 1 character written. i'm not sure if issue here .val().length or preventdefault command, want prevent default action in case not display notes. <style> #[% questionname() %]_div {display:none} </style> <script> $(document).keydown(checknote); function checknote(f){ f = f || window.event; if (f.keycode == '121' || f.keycode == '35'){ f.preventdefault(f); $("#[% questionname() %]_div").css('display', 'block'); } } function displaynote(d){ d = d || window.event; if ($("#[% questionname()...

html - Keep background-color while overlapping a picture -

how can overlap <p style="background-color:red; width:168px; padding:10px; margin-top:-168px;" class="kasten"> this p tag on picture , keep background-color:red? because background gets transparent when overlaps picture... thanks answers! cheers, till instead of margin-top, try using: position: relative; top: -168px; see: https://codepen.io/anon/pen/prvwvo

apache - Symfony 2.8 can't write in /var/lib/php/sessions/ -

good day! i'm bit confused here in symfony functionality terms. have website wich supossed write sessions in /var/lib/php/sessions/ . i'm confused right there, because in /var/www/html/myproject/ recursively property of www-data:www-data (yes, i'm using apache). owner of /var/lib/php/sessions/ root , when apache tries write there, 500 server error regarding writing permissions in directory. i have divided opinions here. people advice me modify config.yml manage sessions inside project directory, while other people bad practice. but, how targeting /var/lib/php/sessions/ without file permission error? here's via apache url: oops! error occurred server returned "500 internal server error". broken. please let know doing when error occurred. fix possible. sorry inconvenience caused. here's via php development webserver: warning: sessionhandler::read(): open(/var/lib/php/sessions/sess_u3eg1842nlpkbm0rvddrq37dc2, o_rdwr) failed: permission d...

reference - De-referencing a JavaScript property from inside an array -

this question has answer here: javascript closure not working 1 answer i'm trying de-reference property on javascript object, not getting expected result. i have array of knockout view-models (i don't think problem knockout-specific), each of has observable, selected . add subscription observable function, crossselecttargetlangs called when value of selected changed. furthermore, add subscription inside for... loop. var tl = 0, tlmax = alllangvms.length, vmlang, selectedcode; // each 'vmlang' view-model in 'alllangvms' array... (; tl < tlmax; tl++) { // local variable context view-model vmlang = alllangvms[tl]; // add subscription observable vmlang.selected.subscribe(function() { // de-reference vmlang.code property selectedcode = (function(code) { return code; ...

android - react-native-nfc can't detect Mifare DESfire -

i'm working https://github.com/novadart/react-native-nfc detect nfc tag. unfortunately, can't detect, it's able detect when using nfc tools (downloaded @ playstore) here's information nfc tools: tagtype iso 14443-4 nxp mifare desfire / nxp mifare desfire ev1 isodep, nfca serial number xxxxxx atqa 0x0344 sak 0x20 i have follow tutorial & curious why can't detect. guide please. thanks.

python - How to filter fields in embedded objects with Alignak backend client -

i trying limit fields embedded object in alignak, documentation alignak backend not go detail on how combine 2 functionalities. using alignak_backend_client ( http://alignak-backend-client.readthedocs.io/en/latest/index.html ). right have: params = { "projection": { "name": 1, "ls_last_check": 1, "host":1 }, "embedded": { "host": 1 } } backend = alignak_backend_client.client.backend(alignak_backend_url) backend.login(alignak_admin_userid, alignak_admin_password) backend.get_all("service", params=params) this returns entire host object embedded returned dict, want few fields. looked mogodb serves db alignak , in theory uses dot notation limit returned fields, using: params = { "projection": { "name": 1, "ls_last_check": 1, "host.name":1 ...

reactjs - react-select: Do we need CSS as well just to display a normal select list? -

i have following code displays normal select list. working fine logically , able log when change happens. problem is, small box being displayed instead of text box adequate show options.and placeholder being displayed normal text. when click on placeholder, values being displayed. import select 'react-select; class selectlist extends component { onchange() { console.log("value changed"); } render() { var select = require('react-select'); var options = [ { value: 'one', label: 'india' }, { value: 'two', label: 'singapore' }, { value: 'three', label: 'iceland' } ]; return( <select name="select list" value="one" options={options} onchange={this.onchange.this(bind}} /> ); } do need css things here....

Calculating median - javascript -

Image
i've been trying calculate median still i've got mathematical issues guess couldn't correct median value , couldn't figure out why. here's code; class statscollector { constructor() { this.inputnumber = 0; this.average = 0; this.timeout = 19000; this.frequencies = new map(); (let of array(this.timeout).keys()) { this.frequencies.set(i, 0); } } pushvalue(responsetimems) { let req = responsetimems; if (req > this.timeout) { req = this.timeout; } this.average = (this.average * this.inputnumber + req) / (this.inputnumber + 1); console.log(responsetimems / 1000) let groupindex = math.floor(responsetimems / 1000); this.frequencies.set(groupindex, this.frequencies.get(groupindex) + 1); this.inputnumber += 1; } getmedian() { let medianelement = 0; if (this.inputnumber <= 0) { ...

python - Print decision tree and feature_importance when using BaggingClassifier -

obtaining decision tree , important features can easy when using decisiontreeclassifier in scikit learn. not able obtain none of them if , bagging function, e.g., baggingclassifier. since need fit model using baggingclassifier, can not return results (print trees (graphs), feature_importances_, ...) related decisiontreeclassifier. hier script: seed = 7 n_iterations = 199 dtc = decisiontreeclassifier(random_state=seed, max_depth=none, min_impurity_split= 0.2, min_samples_leaf=6, max_features=none, #if none, max_features=n_features. max_leaf_nodes=20, criterion='gini', splitter='best', ...

How to sort HTML Table in ReactJS -

i have array of objects , add data html table . need sort data version. how can in react ? render() { return ( <div> <div> <label> got {this.state.count} elements in our database. </label> </div> <div> <table hover striped bordered responsive size="sm" > <thead> <tr> <th>version</th> <th>date</th> <th>uuid</th> </tr> </thead> <tbody> {this.state.results.map(result => <tr key={result.fileid}> <td>{result.version}</td> <td>{result.origin}</td> <td>{result.uuid}</td> </tr> )} </tbody> </table> ...

javascript - Closures and ClickEvent Listener inside Iterator -

i know method of wrapping anonymous function in parentheses , calling right away called iife (immediately-invoked function expression, pronounced "iffy"). the script below iterate on cats object , dynamically allocate cat images,names , number of clicks on every image inside container. var cats = [{ path: "img/cat.jpg", name: 'lazy cat', click :0 }, { path: "img/cat.jpg", name: 'shy cat', click :0 } ] (var = 0; < cats.length ; ++) { //generating container every cat var containerid = "cat-container"+ i; //caching property value every cat var catname = cats[i].name; var imgpath = cats[i].path; var clickid = "click"+i; var imageid = "cat"+i; //append these property in dom $('.left-container').append('<div id ="'+containerid+'">'); $('#'+containerid+...

css - insert an element before the number in an ol in html -

Image
is possible create ordered list (could nested), in there html elements left of each number? here rough example: i've played around :before in css realized can't insert html content there. possible organically or have resort "hack" in order achieve this. you had positioning, need use absolute instead of relative . check out fiddle

selenium - Writing on browser with Java -

i've looked solution 2 days without getting working answer. that's point: made program information html of website, needed make math calculation in order resolve captcha. tried make use of output result selenium , seems work (i handled popups, changes of question , everything). yesterday output not accepted anymore. website says "invalid security answer", while answer it's correct. think browser opened selenium has been someway detected not blocked. so.. there other working ways write on browser textbox result java program? or there way try making selenium browser more "human"? thank in advance! p.s. i'm on windows 10 chrome well, whole point of captcha check whether user human or computer. your question proof captcha working correct seperate humans computers, more info: https://en.wikipedia.org/wiki/captcha

python - Access Workplace (Internal facebook) data through API -

i trying access our company's workplace (internal facebook) data through api call. have created access token , trying api call, accesses company's public facebook page. rather, need access internal workplace (facebook) page. this api call trying with: https://graph.facebook.com/v2.4/company_name/feed/?access_token=fhdsfkjhaslkfhaskjfhdskf14987294mcjiyrwiqwrwqmnmbvmv

neo4j - match a branching path of variable length -

Image
i have graph looks this: here link graph in neo4j console: http://console.neo4j.org/?id=av3001 basically, have 2 branching paths, of variable length. want match 2 paths between orange node , yellow nodes. want return 1 row of data each path, including traversed nodes. want able include different clauses on different intermediate nodes. at end, need have table of data, this: a - b - c - d neo - morpheus - null - leo neo - morpheus - trinity - cypher how that? have tried using optional match, can't 2 rows separately. i have tried using variable length path, returns 2 paths doesn't allow me access , filter intermediate nodes. plus returns list, , not table of data. i've seen question: cypher - matching 2 different possible paths , return both it's on same subject example complex, more generic solution simpler problem i'm looking for. you can define end node using where statement. in case end node has no outgoing r...

Angular 4 resetting form after update - keeping ngModel values (using ngForm) -

Image
i feel should simple can't find (at least without lot of overhead coding) particular use case. have update profile page not modal. once user updates, want form reset original state , current values, in case user wants more edits. i'm using ngform's reset() (also tried resetform() ). resets pristine, etc., removes of values in inputs. on each of inputs i'm using [(ngmodel)]="userrecord.phone" , etc. userrecord still correct. is there simple way keep or model values after reset? onsubmit(event, profileform: ngform) { event.preventdefault(); const mytempvar = this.userrecord; this.userrecord.put() .catch((e) => { this.isprocessing = false; return observable.of(false); }) .subscribe((response) => { this.displayconfirmation = 'profile has been updated successfully.' this.isprocessing = false; this.userrecord = mytempvar; }, (err) => { console.log('there error saving...

javascript - Chrome Extension only hitting my main.js upon page reload -

i creating chrome extension trello which, @ basic start, adds button top of trello header. i following code: manifest.json { "name": "trello item linker", "version": "1", "manifest_version" : 2, "description": "creates links every item number referenced in trello card.", "background" : { "page" : "background.html", "persistent": false }, "page_action" : { "default_icon": { "19": "icons/19.png", "38": "icons/38.png" } }, "content_scripts": [ { "matches": ["https://trello.com/b/*"], "js": [ "lib/jquery-2.1.1.min.js", "scripts/main.js" ], "run_at": "document_...

android - How to add build.gradle dependency for both local and instrumented tests in a single line? -

to add library dependecy both local , instrumented unit tests need add 2 lines of code build.gradle : testcompile "org.mockito:mockito-core:${mockitoversion}" androidtestcompile "org.mockito:mockito-core:${mockitoversion}" is possible in single line? i'm looking like: bothtestcompile "org.mockito:mockito-core:${mockitoversion}" you can let configurations extend other configurations. code below creates new configuration, testcompile , androidtestcompile extend from. way, each dependency of new configuration dependency of these configurations. configurations { // create new configuration bothtestcompile // let both configurations extend 'bothtestcompile' testcompile.extendsfrom(bothtestcompile) androidtestcompile.extendsfrom(bothtestcompile) } now can use new configuration in dependencies closure did in example.

How to speed up planar to packed/interleaved graphics in C++? -

i'm trying program arduino due pwm led matrix. need ready data before drawing each line, inner loop in process slow. screen flickers. loop should finish below 500us. arduino has 84mhz cortex-m3 arm processor. this concept of how need reassemble bits output: 5-bit color data: r1=12, g1=4, b1=7, r2=0, g2=2, b2=27 the next step create 32-bit stream of consecutive 1s. number of 1s given color value: r1 = 0b00000000000000000000111111111111 g1 = 0b00000000000000000000000000001111 b1 = 0b00000000000000000000000001111111 r2 = 0b00000000000000000000000000000000 g2 = 0b00000000000000000000000000000011 b2 = 0b00000111111111111111111111111111 the last step reassemble every n-th bit of 10 pixels (total of 30 color values) 32-bit integer: pack1 = 0b00 ... 111011 pack2 = 0b00 ... 111011 pack3 = 0b00 ... 111001 pack4 = 0b00 ... 111001 pack5 = 0b00 ... 101001 ... this code: // in case scanwidth 64*2 (64 width of led matrix , 2 lines scanned @ once) ( i=0; i<scanwidth/5;...

SharePoint 2010 Rolling Three Months Calendar -

hi i'm trying develop 3 month rolling calendar view inserting 3 calendar webparts in page , inserting below code in cewp. the calendars should roll previous or next respectively clicking on button 'prevmonth' , 'nextmonth'. it seems working roll wrong. can me ? < script type = "text/javascript" > $(document).ready(function() { window.settimeout(setcal, 1000); }); var currentdate = new date(); function setcal() { $("#prevmonth").click(prevmonth); $("#nextmonth").click(nextmonth); movetodate((currentdate.getmonth() + 2).tostring() + '\u002f' + currentdate.getdate().tostring() + '\u002f' + currentdate.getfullyear().tostring(), 'wpq3'); movetodate((currentdate.getmonth() + 1).tostring() + '\u002f' + currentdate.getdate().tostring() + '\u002f' + currentdate.getfullyear().tostring(), 'wpq2'); movetodate((currentdate.getmonth()).tostring(...

.htaccess - Apache2 RewriteRule on Subdomain for FCGI Script -

i have fcgi-script on main domain: fcgi-bin/app.fcgi this accessible this: https://example.com/fcgi-bin/app.fcgi because url doesn't pretty, use different path: https://example.com/app so write following line .htaccess : rewriterule ^app/(.*)$ /fcgi-bin/app.fcgi/$1 [qsa,l] this works pretty well! want use different subdomain: subdomain.example.com/ what have write .htaccess ?

angular - How to limit HTTP requests to every 2 seconds -

i'm using ionic 2 (angular 2) , have autocomplete makes api request every time word typed. change every 2 seconds unable using throttletime , debouncetime service.ts search(keyword): observable<any> { let url = `${this.api}/products/${keyword}`; return this.authservice.refreshtoken() .flatmap(() => this.authhttp.get(url) .throttletime(10000) .debouncetime(10000) .map( (response: response) => { return response.json().products; }, (error: response) => { console.log(error); }) .share(); } searchbar.html <ion-searchbar [showcancelbutton]="true" [placeholder]="'search product'" [autocomplete] = "on" (input)="onsearch($event)"> </ion-searchbar> component.ts onsearch(event) { let keyword = event.target.value; this.searchproductsservice.search(keyword) .subscribe( (products:...

MySQL query to return unique values in one column and sorted by id to get a PHP array -

i have following simplified table: (note skipped 2nd exam in exam_id ) +----+---------+-------+ | id | exam_id | score | +----+---------+-------+ | 1 | 1 | 15 | | 2 | 1 | 20 | | 3 | 1 | 68 | | 4 | 3 | 92 | | 5 | 3 | 10 | +----+---------+-------+ i want write $sql , php (i'm using wordpress, , can use $wpdb ) able following: $exam[3]=10 $exam[1]=68 not when there multiple exams, take score entry corresponds largest id , $exam[2] empty. in words, i'd save last ever exam user attempted , show score. i've tried using group , try this select * exams exams.id in ( select max(id) exams group exam_id );

c# - Parse Microsoft Word Text Add it To OneNote File -

i have came following code: static void main(string[] args) { microsoft.office.interop.word.application word = new microsoft.office.interop.word.application(); object miss = system.reflection.missing.value; object path = @"c:\\users\\t-aaalle\\documents\\testerwordaddin.docx"; object readonly = true; microsoft.office.interop.word.document docs = word.documents.open( ref path, ref miss, ref readonly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss); string totaltext = ""; (int = 0; < docs.paragraphs.count; i++) { totaltext += "\r\n" + docs.paragraphs[i + 1].range.text.tostring(); } console.writeline(totaltext); console.readline(); docs.close(); word.quit(); } currently reads text in microsoft word file, , want able take variable 'totaltext' , have value stored in onenote file. there...

java - Running out of system resources -

i have method take resultset , create list of object[] each row reads. 1 of queries put on server gets on 4million rows back. however, each row (at max) 40 characters. even though 4million rows poop ton, plus 40 chars per row shouldn't cause me run out of resources, alas does. resultsetmetadata rsmd = someresultset.getmetadata(); int columncount = rsmd.getcolumncount(); someresultset.last(); int totalrows = someresultset.getrow(); list<object[]> result = new arraylist(totalrows); list<string> columnnames = new arraylist(); list<object> addrow = new linkedlist(); double somevalue = 0d; (int x = 0; x < columncount; x++) columnnames.add(rsmd.getcolumnname(x+1)); numberformat nf = numberformat.getinstance(); someresultset.beforefirst(); while (someresultset.next()) { addrow.clear(); (int x = 0; x < columnnames.size(); x++) { if (someresultset.getobject(x + 1) instanceof double...

wolframalpha - Evaluate a function in several points -

how can evaluate function in several points, when have function f(x) = x^2 , compute f(10) - f(9) ? know can evaluate function in each point evaluate x^2 @ x=10 , possible evaluate function in several points? this do: evaluate x^2 @ x in {9,10}

Overload Methods in Python (Workarounds) -

a simplified version of problem: want write method in python takes in 1 parameter, either list of strings or custom object holds list of strings. return size of list. method user call want simple user (essentially don't want 2 methods doing same exact thing except single line of code , don't want import non python standard libraries) i realize overloading not possible in python in java. what way go this/what standard way? solutions have thought of are: write 2 different methods. write 1 method 2 parameters , defaults, check defaults move accordingly. write 1 method 1 parameter, check kind of object passed in, move accordingly (not entirely sure if type checking possible) from design perspective if statements each type of object want handle not seem great in long run, don't see other solutions (besides separate methods) thank suggestions! in python, use single dispatch function establish single method different implementations based on argument type (...

Text-Based Game in Java. Need advice with Inventory Implementation and general coding advice -

i'm having trouble figuring out how deal inventory text based java game. finished data structures , algorithms, figured project resume. currently, create inventory in constructor of player class. instantiate inventory 3 potion items, item class. try in player constructor, can't figure out why not working. my question is, how should go instantiating every character 3 potions in his/her inventory? player class: package projectmoria; import java.util.arraylist; import java.util.list; public class player { private final string name; private final string description; private final int maxhitpoints; private int hitpoints; private final int mindamage; private final int maxdamage; private final int defense; private double critchance; private int currx; private int curry; private room currroom; private list<item> inventory; public player(string name, string description, int maxhitpoints, int m...

regex - Regular Expression - Not matching certain characters and position of characters -

solution: solved using regex provided gary_w below , simple powershell command uses discussed replacement function. there no need use built in regex activity in software use. here´s ps: "100,000.00" -replace "([,.]\d{2}$)|[,.]","" regular expressions freaking me out. cannot used logic. however, think current re problem quite simple 1 bur cannot make work :( so here´s want achieve: want re match digits before last 2 decimal places. thus, re must ignore "." , "," , last 2 digits. > examples: > 1.000.000,00 --> 1000000 > 123,456.00 --> 123456 > 100.000,00 --> 100000 > 10.000,00 --> 10000 > 10,000.00 --> 10000 > 1.000,00 --> 1000 > 100,00 --> 100 > 99.88 --> 99 > 99,88 --> 99 > 1,23 --> 1 > ... any ideas how working? here's how in oracle, it's worth. maybe regex used here give idea. read regex "look match of comma or decimal followed 2...

office365api - Outlook Office365 API Multiple Scope Issue -

i'm having trouble adding more 1 office365 resource scope. initial app using these 2 scopes , working great https://login.microsoftonline.com/common/oauth2/v2.0/authorize?response_type=code&client_id={myclientid}&scope=https://outlook.office.com/mail.readwrite+offline_access i wanted have access read , write on outlook calendars went ahead , appended scope existing scopes. &scope=https://outlook.office.com/mail.readwrite+https://outlook.office.com/calendars.readwrite+offline_access this when started getting screen right after click sign in i unable find additional information on why these 2 scopes don't work together. after doing more testing able scopes working individually once isolated them, however, not able use 2 office365 resource scopes together.

python - Why is this loop so slow in Cython? -

this code rearranges bits in 534x713 rgba4 texture. cpdef bytes toddsrgba4(bytearray data): cdef bytes new_data = b'' cdef int pixel cdef int red cdef int green cdef int blue cdef int alpha cdef int new_pixel cdef int in range(len(data) // 2): pixel = int.from_bytes(data[2*i:2*i+2], "big") red = (pixel >> 12) & 0xf green = (pixel >> 8) & 0xf blue = (pixel >> 4) & 0xf alpha = pixel & 0xf new_pixel = (red << 8) | (green << 4) | blue | (alpha << 12) new_data += (new_pixel).to_bytes(2, "big") return new_data it's fast it's python equivalent, this: def toddsrgba4(data): new_data = b'' in range(len(data) // 2): pixel = int.from_bytes(data[2*i:2*i+2], "big") red = (pixel >> 12) & 0xf green = (pixel >> 8) & 0xf blue = ...

PHP finding file where post INCLUDES portion of filename -

i posting variable php process in attempt find file in directory. the problem filename longer user submit. submit voyage number looks this: 222ine whereas filename this: cmdu-ymunicorn-222ine-23082016.txt so need php able directory, find file has matching voyage number, , confirm it's existence (i need able download said file, that'll different question if can't figure out). anyways, here php process takes posted variable: <?php if($_post['voyage'] == true) { $voyage = mysqli_real_escape_string($dbc, $_post['voyage']); $files = glob("backup/................."); // <-this voyage go // should // $files = glob("backup/xxxx-xxxxxxxx-222ine-xxxx.txt"); if(count($files) > 0) { foreach($files $file) { $info = pathinfo($file); echo "file found: " . $info["name"]; } } else { echo "file doesn't exist"; }...

elixir - `Task.async` times out on query inside `Ecto.Multi` in tests -

i'm struggling perform async operation inside 1 of steps in ecto.multi . here i'll present minimal version describe problem: defmodule mymodule my_function(repo \\ repo) ecto.multi.new() |> ecto.multi.run(:example, &perform_example(&1, repo)) |> repo.transaction() end def perform_example(_changes_so_far, repo) task.async(fn -> repo.all(datamodule) end) |> io.inspect() # 1. |> task.await() # 2. |> io.inspect() end end mymodule.my_function(repo) 1. seems working correctly yealds task struct: %task{owner: #pid<0.352.0>, pid: #pid<0.354.0>, ref: #reference<0.2903625078.3861118978.56327>} 2. unfortunately raises error: ** (exit #pid<0.352.0>) exited in: genserver.call(#pid<0.353.0>, {:checkout, #reference<0.2903625078.3861118978.56400>, true, 15000}, 5000) ** (exit) time out strangely enough, i've tried perform same code outside multi , wor...

kie - How to create and add kjar for Drools KieScanner? -

the goal add new rules existing session. can accomplished using kiescanner, update kiecontainer higher version based on "kjar" , update session without need create new 1 , re-establish fact base. now question how 1 create kjars , add these local maven repository artifacts resolvable , accessible kiescanner. the examples in official drools repo sadly of no geared towards own needs , of greater complexity. nothing found on topic , not documentation provides details or gives more information mentioning should possible without providing concrete example. so how working , still compact/general example use of drools kiescanner including creation , adding of kjars like?

javascript - How can I use Google Maps geocoder in an angularJs datatable without Exceeding the quota limit -

i have datatable in whch need find city name based on lat , lng. i'm trying use google maps geocoder in order reverse coding latitude , longitude city name. created function i'm getting limit rate exceeded since have lot of rows in datatable. is there way call geocoding function current active pagination ? the geocoding api has rate limit of 50 requests per second , 2,500 per day, calculated sum of client-side , server-side queries. what should add delay or interval between geocoding requests in javascript. maybe few milliseconds. enough not exceeding 50 requests per second.

swing - Drawing erases after while loop in Java paint method -

i'm working on little program draw stacking cups using paint method controlled nested loops. have working, except when outer while loops finishes, drawing erases. the program consists of 2 while loops. first incrementing row of drawing , second draws cups in row. watching program in debug mode, after final execution of outer while loop, outer while statement evaluated (while (baselength > 0) false, program goes line int counter2 = 0, drawing disappears , program exits. i tried building loops instead of while, , same effect. once outer loop evaluated false, drawing disappears. it seems paint(g) method don't quite understand that's causing drawing erase. ideas? import javax.swing.jframe; import java.awt.graphics; import java.awt.color; public class cups1 extends jframe { /* * declaring instance variables. startx , starty represent top left coordinates * of first cup block in bottom row. cupwidth , cupheight represent width * , height of e...

python - trouble with using list comprehensions & input() -

trying write list comprehension can iterate through string input() , create list each character of string having it's own index. in essence, want function this: x = ["00.00"[h] h in range(len("00.00"))] print(x) > ['0', '0', '.', '0', '0'] when putting actual string ("00.00") in there, python want do. refuses take input() same way: >>> x = [input()[h] h in range(len(input()))] > traceback (most recent call last): file "<stdin>", line 1, in <module> file "<stdin>", line 1, in <listcomp> indexerror: string index out of range the word "what" in there inputted, same else i've put in. i'm not sure what's different input() changes how indexes work. it? you produced rather long-winded spelling of list() . there no need use list comprehension here: list(input()) what goes wrong expression @ front of list compr...

c# - Xamarin.Forms Deleting Files at Runtime iOS -

i need store byte[] in memory. need access later. byte[] represents video. following code allow file written memory, accessed memory. when remove method shown below called, can still accessed later. i have checked pathname same. public void storevideo(byte[] video, string filename) { var documents = environment.getfolderpath(environment.specialfolder.mydocuments); var directoryname = path.combine(documents, "videos"); directory.createdirectory(directoryname); var path = path.combine(directoryname, filename); file.writeallbytes(path, video); } public void removevideo(string filename) { var documents = environment.getfolderpath(environment.specialfolder.mydocuments); var directoryname = path.combine(documents, "videos"); var path = path.combine(directoryname, filename); file.delete(filename); } pu...