Posts

Showing posts from January, 2014

utf 8 - Read file with UTF-8 in Haskell as IO String -

i have following code works fine unless file has utf-8 characteres : module main import ref main = text <- getline theinput <- readfile text writefile ("a"++text) (unlist . proc . lines $ theinput) with utf-8 characteres this: hgetcontents: invalid argument (invalid byte sequence) since file i'm working has utf-8 characters, handle exception in order reuse functions imported ref if possible. is there way read utf-8 file io string can reuse ref 's functions?. modifications should make code?. in advance. i attach functions declarations ref module: unlist :: [string] -> string proc :: [string] -> [string] from prelude: lines :: string -> [string] this can done ghc's basic (but extended standard) system.io module, although you'll have use more functions: module main import ref import system.io main = text <- getline inputhandle <- openfile text readmode hsetencoding inputhandle u

node.js - npm install express-generator not installing express -

i'm following mean stack tutorial requires me have express installed: i run this: npm install -g express-generator and results: username@username-inspiron-3521:~$ npm install -g express-generator /home/username/npm/bin/express -> /home/username/npm/lib/node_modules/express-generator/bin/express express-generator@4.13.1 /home/username/npm/lib/node_modules/express-generator ├── sorted-object@1.0.0 ├── mkdirp@0.5.1 (minimist@0.0.8) └── commander@2.7.1 (graceful-readlink@1.0.1) but when do express --ejs flapper-news the program 'express' not installed. can install typing: sudo apt-get install node-express what doing wrong? thanks time. edit when npm install username@username-inspiron-3521:~/documents/mean/flapper_news$ npm install npm err! install couldn't read dependencies npm err! linux 3.16.0-51-generic npm err! argv "/home/username/local/bin/node" "/home/username/local/bin/npm" "install" npm err! node v4.2.1 n

json - Using filter with each on lodash -

i have json string [ { uri : '/someuri/one', title : 'title 1', displaylocation : 'action_menu', masterdata : 'location', iconclass : 'icon-class-1' }, { uri : '/someuri/two', title : 'title 2', displaylocation : 'action_menu', masterdata : 'location', iconclass : 'icon-class-2' }, { uri : '/someuri/three', title : 'title 3', displaylocation : 'action_menu', masterdata : 'job', iconclass : 'icon-class-3' }, { uri : '/someuri/four', title : 'title 4', displaylocation : 'summary', masterdata : 'location', iconclass : 'icon-class-4' } ] i converting to [ { iconclass : 'icon-class-1', id : 'anythingunique', text : 'title 1' }, { iconclass : 'icon-class-2', id : 'any

javascript - Wait for asyn call to finish - too late -

i have dialog button. once clicked button calls async method returns true or false depending on whether posted data valid or not. click event calls method below. now, problem closedialog called before callback function executed!! how can make work? thanks close: function (srccmd) { var closeresult = true; asyncthing(function(result) { if (result) closeresult = true; else closeresult = false; }); if (closeresult !== false) { this.closedialog(); } }, the function withing asyncthing called when(whenever might be) asynchronous call finished. not interpreted line-by-line. move latter if question callback function , fine. close: function (srccmd) { var closeresult = true; asyncthing(function(result) { if (result) closeresult = true; else closeresult = false; if (closeresult !== false) { this.closedialog(); } }); },

JavaScript Promises - reject vs. throw -

i have read several articles on subject, still not clear me if there difference between promise.reject vs. throwing error. example, using promise.reject return asyncispermitted() .then(function(result) { if (result === true) { return true; } else { return promise.reject(new permissiondenied()); } }); using throw return asyncispermitted() .then(function(result) { if (result === true) { return true; } else { throw new permissiondenied(); } }); my preference use throw because shorter, wondering if there advantage of 1 on other. there no advantage of using 1 vs other, but, there specific case throw won't work. however, cases can fixed. any time inside of promise callback, can use throw . however, if you're in other asynchronous callback, must use reject . for example, new promise(function() { settimeout(function() {

microcontroller - UART in LPC1778 not working -

i trying send byte using uart1 in lpc1778 (i'm using keil simulator). however i'm not able send byte; after detailed debugging, came conclusion data not getting written in uart1->thr register. this code snipped transmission: void uart1_tra(uint8_t x) { lpc_uart1->thr=x; //after line ,irrespective of value of x, uart1->thr remains @ value equal 0 while(1) { if(lpc_uart1->lsr&(1<<5)) { break; } } } initialization code: void uar1_init(void) { lpc_sc->pconp|=1u<<4; lpc_sc->pclksel|=1u; lpc_uart1->lcr|=1u<<7; lpc_uart1->dll|=0x05; //set baud rate lpc_uart1->fdr|= 0x21; //end of baud rate calculations lpc_uart1->lcr&=~(1u<<7);//disable dlab lpc_uart1->lcr|=3u;//8-bitcharacter length lpc_uart1->fcr|=1u; //enable fifo reg lpc_uart1->fcr|=(0x03<<1);//reset rxbuffers //lpc_uart

view - mysql subtract row by row -

i have 2 mysql (5.6) views. 1 view contains 1 value in 1 row on column. let's column , in single row have value 5000. i have second view 3 columns: item (varchar), date (obviously containing dates) , value (decimal). second view has 4 rows looks this: item date value 'lectii de pian', '2015-11-09', '101.88' 'microsoft office','2015-11-11', '7.00' 'belasting', '2015-11-15', '524.00' 'netflix', '2015-11-18', '8.99' what want create in view column let's call "b" , subtract first value in column value value in view , result subtract next value , on looks this item date value b 'lectii de pian', '2015-11-09', '101.88' '4898.12' 'microsoft office','2015-11-11', '7.00' '4891.12' 'belasting'

android - PhoneGap AJAX request not working -

i using latest phonegap version, , doing ajax calls. $.ajax({ type : 'post', url : 'http://example.com/path api', data : {d1: v1, d2: v2}, datatype : 'json', success : function(data) { console.log(data); }, error : function(){ alert('error'); } }); when test app on desktop browser or mobile phonegap developer app, works fine, after building application (.apk), ajax requests not work , fall on failure rather success. have done configurations mentioned include: <access origin="*" /> <plugin name="cordova-plugin-whitelist" version="1" /> <allow-navigation href="*" /> <allow-intent href="http://*/*" /> <allow-intent href="https://*/*" /> also added

node.js - MongoDB/Mongoose: updating two different fields in Mongoose model -

is possible this: var updatedata = { "$set": { content: 'foo' }, "$push":{ versions: { some: 'bar' } } }; model.update({},updatedata, {}); or need 2 or more separate updates? there 1 update of course , mongoose has nothing it, , passes through operation directly. reading documentation $set should shed bit more light on in general. your syntax bit off , should be: model.update({},updatedata,function(err,numaffected) { }); and of course if wanted affect multiple documents , not first match ( default here ), pass in "multi": model.update({},updatedata,{ "multi": true },function(err,numaffected) { }); the suggestion of .find() , .save() shown not happens here , wrong way this. operation sequence means "two" operations touch database, , importantly possible data change in between .find() operation , changes committed in .save() can overwrite dat

Unity3d perpendicular vector3 -

Image
i trying perpendicular vector3 vector3. know how can that? maybe rotate vector3 90 degrees or somthing, there vector3 function can that? *edit *edit this want, want bottom part of object facing surface(or single point) how can achieve that? tried quaternion.lookrotation , transform.lookat both use forward vector of object. know can define world vector in functions problem don't have one. this perpendicular vector in 3d space not unique. however, given vector, can obtain new vector perpendicular both of them. vector3 v1; vector3 v2; vector3 v3 = vector3.cross(v1, v2);

mysql - Repeating Results PHP Query While Loop -

i'm retrieving data mysql ajax , php without refreshing , issue results displayed duplicate . want 1 instance of username display . the table contains username has unique index set not allow duplicate names (i think) while statement believe causing results duplicate how can please ? correct display once instance of each username . sorry in advance don't know hopeful can . <?php include('..\db.php'); $con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname); $q1 = mysqli_query($con,"select * tbl1 username"); $data=""; // if search true if(isset($_post['search'])) { // $var = $_post['search']; if($query = mysqli_query($con,"select username fromtbl1 username '%$var%'")) { // possible creating duplicate results while($row = mysqli_fetch_array($query)) { $data .= $data . '<div>' . $row['username'] . '</div>';

ios - Xcode export/upload error: Your session has expired. Please log in -

i trying release app xcode try uploading app store or exporting in fashion, once checks signing itunes connect, receive error your session has expired. please log in. i have made sure can log account on itunes connect , signing certificates , provisioning profiles current developer center. i came across similar issue last week: xcode 6.4 export adhoc "session has expired" issue seems different. using xcode 7.1 time, crash observing last week may indicate problem different. the session of 1 of accounts (not 1 trying use) had session expired. seems new. had re-sign in errant account in xcode > preferences > accounts.

android - Quickblox Initialize framework from token cause crash -

i'm trying initialize quickblox android framework. documentation it's possible initialize sdk existent quickblox token. can interesting in cases when build big system , have custom server side generates quickblox tokens . want because, security reason, don't want keep auth_secret , auth_key in app code. when do baseservice.createfromexistenttoken(token, expirationdate); i java.lang.runtimeexception: applicationid null. must call qbsettings.getinstance().init(context, string, string, string) before using quickblox library. bit contradictory me. generated token server-side , not expired can point me right direction? possible log-in user in quickblox without auth_secret , auth_key stored in app? base on docs, have initialize quickblox first before using it. http://quickblox.com/developers/android#initialize_framework static final string app_id = "961"; static final string auth_key = "pbzxxw3wggztfzv"; static final string auth_sec

dictionary - Reading intricated dictionaries in depth Python -

i have big dictionary smaller dictionaries inside, , i'm trying values inside aren't dictionaries (but strings, lists or integers), "path". tried use dfs (depth first search) techniques, without success. here sample of big dictionary : { 'visplanesection': { 'valuemode': 'single section', 'origininput': '[0.4, 1.3877787807814457e-17, -8.4350929019372245e-16] m,m,m', 'orientationinput': '[1.0, 0.0, -3.3133218391157016e-16] m,m,m', 'coordinatesystem': 'laboratory->reference', 'inputpartsinput': '[region]', 'valueindex': '-1', 'vissinglevalue': { 'valuequantityinput': '0.0 m' } }, 'childrencount': '2' } the data need : visplanesection.valuemode = 'single section' visplanesection.valuemode = 'single section

Retrieving a boolean value in a function using php -

function sample($number){ if ($number % 2 == 0){ echo "even"; }else{ echo "odd"; } sample(3); when replace echo return nothing happens? how know if returns something? below sample concerns me. in advance! function sample($number){ if ($number % 2 == 0){ return true; }else{ return false; } sample(3); something definetly happens. aren't catching result. // return true or false @ random function trueorfalse() { return (rand(1, 10) > 5) ? true : false; } // going check being returned print_r(trueorfalse()); // true print_r(trueorfalse()); // false print_r(trueorfalse()); // false print_r(trueorfalse()); // true you can use return value in if statements , such: if (trueorfalse() == true) { echo "it true time"; } the php manual tells us values returned using optional return statement. type may returned, including arrays , objects. causes function end execution , pass

Mule Http Listner getting url parameter values -

<flow..> <http:listener-config name="http_listener_configuration" host="${http.hostname}" port="${http.port}" basepath="${http.base.path}" doc:name="http listener configuration"/> <http:listener config-ref="http_listener_configuration" path="store/*" doc:name="http"/> old http end point <!-- <http:inbound-endpoint address="http://${http.hostname}:${http.port}/${http.base.path}/store" doc:name="http" exchange-pattern="request-response"> <object-to-string-transformer /> </http:inbound-endpoint> --> <apikit:router config-ref="store-api-config" doc:name="apikit router" /> </flow> <flow name="get:/rates/search:smartstore-api-config"> <logger message=" #[message.inboundproperties['referencedate']]" level="info" doc:name

ios - After scrolling table cell image display previous images in swift. Though the image url display correct -

i have problem in cell image. describe in bellow. screen having table containing 1000 cells. each cell consist of a) image b) labels. image , labels data comes json. using of afnetwork purse json , bind label , image. problem in image. labels bind. json image url come correctly. display previous cell images when scrolling started. 1st time when scrolling not start image display perfectly. after scrolling problem start , show previous cell image. code: func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell { if self.arrpostimage![indexpath.row] as! string == "" { let cell1: cellnewnoimage = tableview.dequeuereusablecellwithidentifier("cell2") as! cellnewnoimage return cell1 } else { let cell1: cellformyactivitymaintableview = tableview.dequeuereusablecellwithidentifier("cell") as! cellformyactivitymaintableview cell1.title.text = self.ar

JAVA program for 2 or more text files comparing -

i want compare 2 or more text files find duplicate entry. o/p should lines in files matched or not. i want compare each of file 1 lines lines of file 2 (ie., comparing file 1's line-1 lines of file 2). when run below code compares line 1 of file 1 lines of file 2, program got terminated. note : tried danail alexiev 's idea (see answer) loop running infinitely , (also not jumped 2 line of file 1, infinite loop on file 1's line 1 lines of file 2) files below file 1: content 21321sc231231a23d1a32df1adfsdfsdfsd fsdfs4dfs dfsdf 3sd1f sdfs4df3s df0 sd4f sdf sdf1 3sdf sdfs4df6s fs1df 3sdfsd fs.d1f s3d1 sdf1s df1 sdf1sdf file 2: content 21321sc231231a23d1a32df1adfsdfsdfsd fsdfs4dfs dfsdf 3sd1f sdfs4df3s df0 sd4f sdf sdf1 3sdf sdfs4df6s fs1df 3sdfsd fs.d1f s3d1 sdf1s df1 sdf1sdf code: while ((scurrentline1 =file1.readline()) != null ) { while ((scurrentline2 =file2.readline()) != null ) { if(scurrentline1.equalsignorecase(sc

bash - Deleting first row of each csv file using sed -

i trying delete first row of each of .csv files in dir folder using sed: dir=/home/results filename in "$dir"; sed 1d filename.csv done however, doesn't work. new bash scripting , thankful if tells me how fix this. just do: for f in /home/results/*.csv; sed -i '1 d' "$f"; done the glob pattern /home/results/*.csv matches .csv files in /home/results/ directory , for construct iterate on files, sed in place removal of first row each file.

oracle - Sysdate in text sql -

i´ve got problem, want have sysdate in text, where-statement looks this: where optxt_text '%mahnstufe 2 29.06.2016%' , (reverse(rpad(reverse(optxt_belnr),3))) in ('kag','kre','ksr') ; is there way replace "29.06.2016" sysdate? sorry bad english. this should trick: where optxt_text '%mahnstufe 2 '+convert(nchar, getdate(), 104)+'%'

javascript - How to set 3 date in my protractor test? -

i have 3 dates field in row, , i'm trying include randomly date on it, but, protractor fast , set like: first data: 01/08/1990 (correct) second data: 01/09/0009 (invalid) last data : 01/10/0007(invalid) so, used browser.sleep(200) , it's works, but, there way do? correct way? var datapublicacao = element(by.xpath("//label[. = 'data de publicação*']/following-sibling::input")); datapublicacao.sendkeys(retornadataaleatoria()); browser.sleep(200); var datainicio = element(by.xpath("//label[. = 'inicio vigência*']/following-sibling::input")); datainicio.sendkeys(retornadataaleatoria()); browser.sleep(200); var fimvigencia = element(by.xpath("//label[. = 'fim vigência']/following-sibling::input")); fimvigencia.sendkeys(retornadataaleatoria()); i try splitting date string components , sending keys in "batches". implementation in quite broad fo

javascript - convert function with multiple .get() inside jQuery .each to q promise -

i'm using excellent answer question convert svg images inline html. the function looks through container or body, finds each .svg image , converts them inline html. however, uses $.get() call retrieve svg files makes function asynchronous. i'd convert function promise can wait complete before running other things (like adding or removing classes new inline html etc) my current attempt looks this: util.convertsvgimages = function(container) { var deferred = q.defer(); container = typeof container !== 'undefined' ? container : $("body"); var getstocomplete = jquery('img.svg', container).length; // total number of $get.() calls complete within $.each() loop var getscompleted = 0; // current number of $get.() calls completed (counted within $get.() callback) jquery('img.svg', container).each(function(index) { var img = jquery(this); var imgid = img.attr(&

scala - Apache spark - java.lang.NoClassDefFoundError -

i have maven based mixed scala/java application can submit spar jobs. application jar "myapp.jar" has nested jars inside lib folder. 1 of "common.jar". have defined class-path attribute in manifest file class-path: lib/common.jar . spark executor throws java.lang.noclassdeffounderror:com/myapp/common/myclass error when submitting application in yarn-client mode. class(com/myapp/common/myclass.class) , jar(common.jar) there , nested inside main myapp.jar. fat jar created using spring-boot-maven plugin nest other jars inside lib folder of parent jar. prefer not create shaded flat jar create other issues. anyway spark executor jvm can load nested jars here? edit spark (jvm classloader) can find classes flat inside myapp.jar itself. i.e. com/myapp/abc.class, com/myapp/xyz.class etc. edit2 spark executor classloader can find classes nested jar throws noclassdeffounderror other classes in same nested jar! here's error: caused by: org.apache.spark.sparkexc

cloud - OpenStack Alarm Engine -

what best architecture development of openstack alarm engine? should ceilometer architecture used or better manually monitoring , alarm triggering part using mechanism log monitoring or snmp? considering contribute project aodh ( https://launchpad.net/aodh ), split ceilometer project ?

ios9 - How to show “Done” button on iPhone number pad in ios 9 -

- (void)keyboardwillshow:(nsnotification *)note { // create custom button uibutton *donebutton = [uibutton buttonwithtype:uibuttontypecustom]; donebutton.frame = cgrectmake(0, 163, 106, 53); donebutton.adjustsimagewhenhighlighted = no; //[donebutton setimage:[uiimage imagenamed:@"donebuttonnormal.png"] forstate:uicontrolstatenormal]; //[donebutton setimage:[uiimage imagenamed:@"donebuttonpressed.png"] forstate:uicontrolstatehighlighted]; [donebutton settitle:@"完成" forstate:uicontrolstatenormal]; [donebutton settitlecolor:[uicolor blackcolor] forstate:uicontrolstatenormal]; [donebutton addtarget:self action:@selector(donebutton:) forcontrolevents:uicontroleventtouchupinside]; uiview *foundkeyboard = nil; uiwindow *keyboardwindow = nil; keyboardwindow = [[[uiapplication sharedapplication] windows] lastobject] ; keyboardwindow.userinteractionenabled = yes; if (!keyboardwindow) return; (__str

symfony - Form Theming doesn't work witn templates rendred by pugxmultiuserbundle -

i'm using symfony3. have separate template theming forms , works in forms in templates doesn't work forms inside templates rendered pugxmultiuserbundle i have created action test , have rendred etudiant.form.html.twig form theming , works , have said above , if rendred pugxmultiuserbundle theme doesn't work template: {% form_theme form ':frontend/form:fields.html.twig' %} {{ form_start(form, {'method': 'post', 'action': path('etudiant_registration'), 'attr': {'class': 'fos_user_registration_register'}}) }} {{ form_widget(form) }} <div> <input type="submit" value="{{ 'registration.submit'|trans }}"/> </div> {{ form_end(form) }} config pugx_multi_user: users: etudiant: entity: class: appbundle\entity\etudiant registration: form: type: appbundle\form\user\registrationetu

html - The last couple scroll lines are hidden behind the footer. Is there a simple way to fix this? -

i have data in tables require scrolling. have fixed footer @ bottom of display. last few items in table hidden behind footer when scrolling bottom of table. there simple way limit bottom of scroll falls outside footer when scrolling last items in table? the application responsive display on computer, iphone , ipad. relevant code application.html.erb: <body> <%= render 'layouts/header' %> <div class="main-container" > <%= yield %> <%= render 'layouts/footer' %> <!--%= debug(@horses) if rails.env.development? %--> </div> </body> relevant css code - main-container: body > .main-container { overflow:auto; padding: 60px 15px 0em; margin-bottom: 80px; background-color:#b0bd92; position:fixed; width:100%; height:100%; } relevant code - footer.html.erb <nav class="navbar navbar-inverse navbar-fixed-

android - NoSuchMethodError after including two libraries using ProGuard -

i'm trying include 2 libraries ( panframe , indoo.rs ) android project using gradle 2.1.2. both using proguard presumably obfuscate private methods. since both libs use same obfuscation pattern, call static method indoo.rs worker service in onbind() leads ambiguity classloader: java.lang.nosuchmethoderror: no static method a(ljava/lang/object;)ljava/lang/object; in class lcom/a/a/a/g; or super classes (declaration of 'com.a.a.a.g' appears in /data/data/com.companytest/files/instant-run/dex/slice-panframe-1.9_e8c65b231b25083f170d9dc622b9f9f514e9ecef-classes.dex) @ com.a.a.h.a.j$a.(sourcefile:449) @ com.a.a.h.a.j.a(sourcefile:411) @ com.customlbs.service.worker.onbind(sourcefile:184)

shopping cart - PHP While Loop Summing -

i making standard ecommerce shopping cart, have set items display in shopping cart looping onto table database. table class="large-16" style="margin-top: 20px;"> <tr> <th>action:</th> <th>product:</th> <th>price:</th> <th>size:</th> <th>color:</th> <th>quantity:</th> <th>price total:</th> </tr> <?php while ($row = mysqli_fetch_array($result)) { ?> <tr> <td> <a href="delete-product-handler.php?id=<?php echo $row['product_id']; ?>" onclick="return confirm("are sure want remove product shopping cart?")"> <img src="img/delete.png" alt="delete button">remove</a> </td> <td><?php echo $row['product_name']; ?></td> <td><?php echo $ro

for loop - Creating a cumulative distribution within a column of a matrix in R -

i have situation there c probability distributions. each distribution has r possiblities. can model (r x c) matrix c'th column represents c'th probability distribution. element @ [r,c] represents probability of getting r'th possibility c'th probability distribution. name matrix probdist. i want generate cumulative probability distribution matrix, each element @ [r,c] in matrix sum of elements [1,c] [r-1,c]. i coding in r. currently, code follows: cumprobdist <- probdist for(c in 1:ncol(probdist)) cumprobdist[c] <- cumsum(probdist[c]) which works correctly, aware function frowned upon in r code due being inefficient. how may rewrite chunk of code utilize *apply family of functions (or efficient) instead? cumprobdist = apply(probdist,2,cumsum)

android - What's the difference between getDefaultSharedPreferences() and getPreferences()? -

i'm taking "developing android apps" udacity course. in "lesson 3: new activities , intents > use sharedpreferences" segment, instructor asked me dig around android developer site how user preferences sharedpreferences . however, found different between official documentation , course's solution. the udacity course's solution says, grab sharedpreferences instance preferenceactivity , should call: sharedpreferences prefs = preferencemanager.getdefaultsharedpreferences(getactivity()); (where getactivity() context here because it's called inside fragment .) while the official documentation on android developer site indicates should call: sharedpreferences prefs = getactivity().getpreferences(context.mode_private) so what's difference between preferencemanager.getdefaultsharedpreferences(context context) , activity.getpreferences(int mode) ? please note: question not involve getsharedpreferences() requires file name. it&

java - How to generate normals in GLSL -

Image
i have created randomly generated terrain using simplex noise. code looks this: float [ ] vertices = new float [ size * size * 3 ]; short [ ] indices = new short [ ( size - 1 ) * ( size - 1 ) * 2 * 3 ]; ( int x = 0 , index = 0 ; x < size ; x ++ ) { ( int z = 0 ; z < size ; z ++ ) { vertices [ index ++ ] = x; vertices [ index ++ ] = ( float ) simplexnoise.noise ( x , z ); vertices [ index ++ ] = z; } } ( int = 0 , index = 0 ; < ( size - 1 ) ; ++ ) { int offset = * size; ( int j = 0 ; j < ( size - 1 ) ; j ++ ) { indices [ index ++ ] = ( short ) ( j + offset ); indices [ index ++ ] = ( short ) ( j + offset + 1 ); indices [ index ++ ] = ( short ) ( j + offset + 1 + size ); indices [ index ++ ] = ( short ) ( j + offset + 1 + size ); indices [ index ++ ] = ( short ) ( j + offset +

Swift leave out .self to invoke a function which needs metatype? -

here code write: func printtype<t: any>(one: t.type) { print(one) } func printtype2<t: any>(one: t.type, name: string) { print(one) } printtype(set<int>) printtype2(set<int>.self, name: "name") i wonder why printtype(set<int>) can work. , in printtype2(set<int>.self, name: "name") , can not leave out .self make work. edit: i want know rule imply when can omit .self . had tried find in apple official references, failed. edit: i test codes in xcode version 7.1 (7b91b). i ask in apple official forum, , answer there: this famous undocumented feature of swift, since 1.0 (or former > betas, cannot confirm). when calling method or function single type argument, can omit > .self . guess feature included swift make sizeof-like functions > neat, not sure. https://forums.developer.apple.com/thread/24980

python - How would you put back a list that you've split and transformed back to the original file? -

i trying isolate date date/time column in original csv file. i've isolated column , change date having tough time putting original file: def isolatedate(csv_file): file_in = open(csv_file, "ru") reader = csv.reader(file_in) next(file_in,none) line in reader: date = line[3] date = date.split() new_date = date[0] return new_date how go putting new_date variable line[3] in original file you need read in rows file, modify 4th column (index 3) , rewrite file: with open(csv_file, "r") file_in: reader = csv.reader(file_in) header = next(reader) rows = [row[0:3] + [row[3].split()[0]] + row[4:] row in reader] # ^^^modified date^^^ open(csv_file, "w") file_in: writer = csv.writer(file_in) writer.writerow(header) writer.writerows(rows)

How to open source an android application -

i finished android application put on play store. wish put on github / bitbucket in case interested it. there ad banner, stored public key in strings.xml file. how should handle ? i added "flavour" in order able generate apk without ads. additionally kind of similar precautions should take before releasing in wild ? you should not upload api keys or alike github repository since it's going against of terms , conditions of lot of providers, including github think. to solve this, put placeholder in place people should put own api key , upload file repository, example: <resources> <string name="google_maps_api_key">put api key here</string> </resources> you should start thinking licensing code . open source licenses licenses comply open source definition — in brief, allow software freely used, modified, , shared. approved open source initiative (also known osi), license must go through open source initiati

windows - Python 3 - tkinter , ignore socket.herror and continue -

i try resolve hosts using socket module via gui made using tkinter here part of code , main issue error receive while resolving routers name for line in p.stdout: fiw = open("1.txt", '+a') line = str(line) if "received = 1" in line: hostad = socket.gethostbyaddr(ip3 +str(i)) if hostad: try: print(hostad) except socket.herror: print(hostad) fiw.write("received reply " + ip3 +str(i)+"\n") print("received reply " + ip3 +str(i)+"\n") print(socket.gethostbyaddr(ip3 +str(i))) the error : socket.herror: [errno 11004] host not found script won't run further used print here example tried pass tried except socket.herror err: print(err) pass also tried using pass in method

JSON.parse() is not converting my PHP string to a JavaScript object -

i have used json_encode() echo associative array php javascript through $.post method: $.post("php/myfile.php", {}, function(data){ exercises = data; //exercises = json.parse(data); // console -> uncaught referenceerror: json not defined alert(typeof exercises); // alerts -> string alert(exercises); // alerts -> {"1":"bench press","2":"squat","3":"deadlift"} alert(json.stringify(exercises)); // console -> uncaught referenceerror: json not defined }); for reason can't convert string javascript associative array using json.parse() . what's issue? you can pass json datatype ajax call jquery pass converted value $.post("php/myfile.php", {}, function (exercises) { alert(typeof exercises); // alerts -> string alert(exercises); }, 'json'); in code problem case of json , should json.parse() not json.parse

c - Inserting newNode in ascending order into LinkedList -

i have problem when trying insert newnode linked list in ascending order. here code: void insertsortedlinkedlist(linkedlist *l, int x) { listnode* newn; listnode *cur, *previous; if (l->head == null) { l->head = malloc(sizeof(listnode)); l->head->item = x; l->head->next = null; } else { newn = malloc(sizeof(listnode)); newn->item = x; cur = l->head->next; previous = l->head; while (cur!= null && cur->item < x) { previous = cur; cur= cur->next; } newn->next = cur; previous->next = newn; } l->size++; } with these code, entered input 1,3,5,7,9,6 , managed output 1,3,5,6,7,9 in ascending order. however, when tried 3,2,1 , output 3,1,2 . 3 first input not shift. any idea how fix this? thanks in advance. you'e close. problem code can never insert new node head in list has element. here's 1 idea reorganizing: void insertsortedlinke

c++11 - g++ faulty optimization with specialized template -

i'm having problem g++ (4.9.2) optimization produces faulty code puzzling me. , faulty, mean code output fundementally different between optimized (-o1, -o2 or -o3) , non-optimized (-o0) compilation. and, of course, optimized code wrong. i have class similar <bitset> , info stored @ bit-level , instantiated number of bits, has specialized template bits <= 8 bits. #include <iostream> using namespace std; // generalized class bits, uses array of specialized, 1-byte bits template <unsigned int bits=8, bool _=(bits>8)> class bits { bits<8,false> reg[(bits+7)>>3]; public: void set(int pos) { reg[pos>>3].set(pos%8); }; void clr(int pos) { reg[pos>>3].clr(pos%8); }; bool get(int pos) { reg[pos>>3].get(pos%8); }; }; // specialized, 1-byte bits (flag stored in char) template <unsigned int bits> class bits<bits,false> { char reg; public: bits() : reg(0) {}; bits(int r) : reg(r)

sql - Trying to create a variable out of a column argument -

i trying create variable value in sql. i getting error "exact fetch returns more requested number of rows" here sql trying run declare title varchar2(1) := 'n'; begin select title_flag title control.title title_flag=title; end; declare title varchar2(1) := 'n'; begin select title_flag title control.title title_flag=title , rownum = 1; end; you need use sort of condition 1 row returned query error means getting more 1 record doesn't know assign

c++ - Qt - invoke slot only when both signals are emitted -

i have 3 processes: a , b , final . final depends on both a , b , can/must updated when both a , b updated. there signal datachanged updates both a , b (and final well). slots update_a , update_b invoked other signals. mainwindow::mainwindow(qwidget* parent) : qmainwindow(parent), pa(false), pb(false) { ... connect(this, &mainwindow::xchanged, this, &mainwindow::update_a); connect(this, &mainwindow::ychanged, this, &mainwindow::update_b); connect(myobj, &myclass::datachanged, this, &mainwindow::update_a); connect(myobj, &myclass::datachanged, this, &mainwindow::update_b); connect(this, &mainwindow::a_updated, this, &mainwindow::update_final); connect(this, &mainwindow::b_updated, this, &mainwindow::update_final); ... } void mainwindow::update_a() { if (!this.pa) { // } this.pa = true; emit a_updated; } void mainwindow::update_b() { if (!this.pb) { // } this.pb = true; emit b_updated;

kubernetes - How does Kubectl connect to the master -

i've installed kubernetes via vagrant on os x , seems working fine, i'm unsure how kubectl able communicate master node despite being local workstation filesystem. how implemented? kubectl has configuration file specifies location of kubernetes apiserver , client credentials authenticate master. of commands issued kubectl on https connection apiserver. when run scripts bring cluster, typically generate local configuration file parameters necessary access cluster created. default, file located @ ~/.kube/config .

python - Customizing Accounting and finance module in odoo? -

Image
i working on accounting , finance module, want modifications hiding fields , hiding chart of taxes. can me out? please tell me procedure hide left side menu item (chart of taxes). also want know view_id hide taxes invoice sheet , @ bottom tax (update). please let me know external ids hide them unable find them linked other models. invoice/taxes field: field_id:tax_id object: type:many2many relation:account.tax first of activate odoo developer mode , can external ids of objects. activate odoo developer mode how know external id of object open form , can see 1 drop down field on top of page if developer mode active. and select option "edit form view" drop down , can see details of form view model name, external id of view , many more. in case inherit form use "account.invoice_supplier_form" external id of form, see image. to know external id of menu items , go settinsgs => technical => user interface => menu

Reuse a case class inside an object in scala -

i have object contains 1 or more case classes , associated methods. reuse case class within object (which has similar characteristics object differentiating methods). private object abc { /* ... */ case class xyz(..) { def somefunc(){} } object xyz { def apply() {} } } private object extendabc { // how reuse case class xyz here? } if want access can use kind of code . private object abc { case class xyz() { def somefunc(){} } object xyz { } } private object extendabc { val = new abc.xyz() a.somefunc() } you need call way because xyz nested member of object abc . here . also please note cannot define apply method in companion object of case class provides exact same apply() method (with same signature.

acts as taggable on - (Rails 4, acts_as_taggable_on): Using dynamic context in controller -

acts_as_taggable_on great , easy work when using static contexts. i'm trying store tags selected user in context depends on 1 of model's attributes. the model ingredient , has attribute center_id . i'd user able select tags , context string based on center_id . i need getting right code controller , view. model: class ingredient < activerecord::base belongs_to :center helper: module ingredientshelper def get_all_tags_for_center return ingredient.tags_on(get_tags_context) end def get_tags_context "c#{@ingredient.center_id}_ingredient" end end view - tried this, may not right thing dynamic contexts: <%= f.association :tag_list %> <%= f.select :tag_list, options_for_select(get_tags, @ingredient.tag_list_on(get_tags_context)), {}, {class: 'doselect2', multiple: true } %> <% end %> controller - needed. solved. future readers: controller: @ingredient.set_tag_list_on get_tags_context

oracle - the right command to select the number of products of every client that had a purchase in the last month -

oracle question i've go table com (clientnumber,productnumber,dateofpurchase ) ; want know how compare dates using sysdate , date of purchase know 1 happened last month i think 1 can solve problem select * com dateofpurchase between trunc((trunc(sysdate,'mm')-1),'mm') , trunc(sysdate,'mm')-1 trunc((trunc(sysdate,'mm')-1),'mm') --> last_month_fist_day trunc(sysdate,'mm')-1 --> last_month_last_day

button - TextButton hover option, or something similar? -

as know, there 3 types of buttons in libgdx: textbutton , imagebutton , imagetextbutton i need create button own background , own text , of course, need hover option. the hover available in imagebutton, imagebutton doesn't have label can't assign text it. there third option, imagetextbutton, it's not normal button, it's button , label set next (which unacceptable, cause need text on button). is there option achieve this?

captions - Chromecast VTT not showing -

i creating chromecast app streams video , uses out of stream vtt captions. have managed load ttml require load vtt have following code this.player.enablecaptions(true, 'vtt', 'http://some_file.vtt'); this fails within mediaplayer.js tyhe following error uncaught typeerror: cannot read property 'parse' of null this looks in code load individual cues has come across problem? you need add (text/audio) track(s) information mediainfo , set active track. take @ guide . aware having tracks, when media mp4, require cors.

python - Getting Uploaded filename Extension in Django View? -

im working through alex pale's minimal django file upload example django 1.8 - https://github.com/axelpale/minimal-django-file-upload-example/tree/master/src/for_django_1-8/myproject/myproject/myapp i know how file extension in form, how can in view. i'm aware can access file thru - docfile=request.files['docfile'] view - from django.shortcuts import render_to_response django.template import requestcontext django.http import httpresponseredirect django.core.urlresolvers import reverse myproject.myapp.models import document myproject.myapp.forms import documentform def list(request): # handle file upload if request.method == 'post': form = documentform(request.post, request.files) if form.is_valid(): docfile=request.files['docfile'] # redirect document list after post return httpresponseredirect(reverse('myproject.myapp.views.list')) else: form = documen

android - Google Play services Adds up additional process and causes additional memory consumption -

i using google gcm in app , working fine , problem adds additional process (see screenpic shows 2 process ) , named google play services (com.google.android.gms) consumes 20mb adds app usage 28mb issue screenshot of app settings view note: not using android:process anywhere in androidmanifest.xml even after closing app still shows 1 service , 2 process where come additional process ? tested in multiple devices (kitkat,lollipop) <receiver android:name=".gcm.services.simple.gcmbroadcastreceiver" android:permission="com.google.android.c2dm.permission.send" android:exported="true"> <intent-filter> <action android:name="com.google.android.c2dm.intent.receive" /> <action android:name="android.net.conn.connectivity_change" /> <action android:name="android.intent.action.boot_completed" /> <action android:name="an

java - What is a NullPointerException, and how do I fix it? -

what null pointer exceptions ( java.lang.nullpointerexception ) , causes them? what methods/tools can used determine cause stop exception causing program terminate prematurely? when declare reference variable (i.e. object) creating pointer object. consider following code declare variable of primitive type int : int x; x = 10; in example variable x int , java initialize 0 you. when assign 10 in second line value 10 written memory location pointed x. but, when try declare reference type different happens. take following code: integer num; num = new integer(10); the first line declares variable named num , but, not contain primitive value. instead contains pointer (because type integer reference type). since did not yet point java sets null, meaning "i pointing @ nothing". in second line, new keyword used instantiate (or create) object of type integer , pointer variable num assigned object. can reference object using dereferencing operator . (a dot

c++ - Server with libpion crashing at request handling -

i use following versions of libraries: libpion-dev 5.0.6 libboost-all-dev 1.58.0 in internet found simple example of asynchronous http-server, falls in processing of requests handler described. in addition, non-existent resources correctly returns 404 response. server code:i use following versions of libraries: libpion-dev 5.0.6 libboost-all-dev 1.58.0 in internet found simple example of asynchronous http-server, falls in processing of requests handler described. in addition, non-existent resources correctly returns 404 response. server code: #include <boost/bind/arg.hpp> #include <boost/bind/bind.hpp> #include <boost/bind/placeholders.hpp> #include <boost/smart_ptr/shared_ptr.hpp> #include <pion/http/parser.hpp> #include <pion/http/request.hpp> #include <pion/http/response_writer.hpp> #include <pion/http/server.hpp> #include <pion/tcp/connection.hpp> #include <unistd.h> struct fake_server { void start() {