Posts

Showing posts from August, 2013

How to only open an existing file in java -

this question has answer here: how check if file exists in java? 19 answers i know how open file in java writing, want open if exists already. possible? i've searched around , found 2 suggestions far both don't meet needs. 1 open file appending. problem there if file doesn't exist create it. second use file.exists() first. of course not valid solution file may exist when call file.exists() not exist when go open file. want similar windows api openfile() in can pass open_existing flag such call fail file doesn't exists. exist in java? only editing question because marked duplicate. not sure why. thought pretty specific other answers , why not sufficient. so i'll restate, want open file writing. want open fail if file doesn't exist. exists() returns true if file path valid directory if file isn't there. can around usi...

mysql - Getting error "1366 Incorrect integer value: '1'" when importing file -

i'm trying inline upload data stored in utf-8 text files, , have 2 problems. firstly, there's no primary key set on table, , it's not set auto-increment or forced null @ point; first column intended primary key once data loaded, , foreign keys added @ point. i received following error: 25 row(s) affected, 1 warning(s): 1366 incorrect integer value: '1' column 'idtable_file' @ row 1 records: 25 deleted: 0 skipped: 0 warnings: 1 when trying run this: load data local infile '/path' table sandr.table_file columns terminated ',' lines terminated '\n' (idtable_file, owner_id, folder_id, @modified_date, @created_date, size, filename) set modified_date = str_to_date(@modified_date,'%d/%m/%y %t'), created_date = str_to_date(@created_date,'%d/%m/%y %t') on table: create table `table_file` ( `idtable_file` int(11) default null, `owner_id` int(11) default null, `folder_id` int(11) default null,...

Python mutliprocessing: Timestamp of a process -

i using python multiprocessing module. need see timestamp @ process starts , timestamp @ process ends. if this: ... processes = [process(target=topo.func1, args=(host,servers,q)) x in range(1,i)] p in processes: p.start() print p <process(process-1, started)> p.join() print p <process(process-1, stopped)> it prints process number , status. how can print timestamp? import datetime module first , can print timestamp

spark streaming - Compile error while calling updateStateByKey -

Image
compile error : the method updatestatebykey(function2<list<integer>,optional<s>,optional<s>>) in type javapairdstream<string,integer> not applicable arguments (function2<list<integer>,optional<integer>,optional<integer>>) in simple word count example , mapping words 1 javapairdstream<string, integer> wordcounts = words.maptopair(s -> new tuple2<>(s,1)); and applying updatestatebykey on wordcounts javapairdstream<string, integer> finalcount = wordcounts.updatestatebykey(updatefunction); the updatefunction defined follows: final function2<list<integer>, optional<integer>, optional<integer>> updatefunction = new function2<list<integer>, optional<integer>, optional<integer>>() { @override public optional<integer> call(list<integer> values, optional<integer> state)...

html - Django CMS - customize the menu -

i setting djangocms, , using {% show_menu %} in order display menu items created page creator. i customize menu, similar this . in other words logo placed in middle of menu, , should scale responsively down 768px. how can render logo ul li while still using {% show_menu %} tag. point me in right direction?

sql - mysql query to search a table name from multiple databases -

i facing problem in searching particular table_name. have around 50 databases on server , wish search table_name x created in databases. there straight-forward find exact databases in x table found in mysql through phpmyadmin. any appreciated. you can query information_schema database this. below query return names of databases, contains table your_table_name . select `table_schema` `information_schema`.`tables` `table_name` = 'your_table_name' i hope looking for. according mysql documentation information_schema database, information_schema provides access database metadata. metadata data data, such name of database or table, data type of column, or access privileges. other terms used information data dictionary , system catalog.

google cloud messaging - GCM on iOS doesn't send data object for content_available notifications -

when send gcm message content_available=true flag set, userinfo dictionary in didreceiveremotenotification: callback null. here's callback in uiapplication delegate: - (void)application:(uiapplication *)application didreceiveremotenotification:(nsdictionary *)userinfo fetchcompletionhandler:(void (^)(uibackgroundfetchresult))handler { nslog(@"notification: %@", userinfo); [[gcmservice sharedinstance] appdidreceivemessage:userinfo]; handler(uibackgroundfetchresultnodata); } here's sample curl request works: curl --header 'authorization: key=…' --header 'content-type: application/json' -d '{ "registration_ids": ["…"], "data": { "test": "test test test" }}' https://android.googleapis.com/gcm/send i expected result: notification: {"collapse_key" = "do_not_collapse"; = …; test = "test test test";\^j} however, when add content_available...

python - How can I solve system of linear equations in SymPy? -

sorry, pretty new sympy , python in general. i want solve following underdetermined linear system of equations: x + y + z = 1 x + y + 2z = 3 sympy got new linear system solver: linsolve in sympy.solvers.solveset , can use follows: in [38]: sympy import * in [39]: sympy.solvers.solveset import linsolve in [40]: x, y, z = symbols('x, y, z') list of equations form: in [41]: linsolve([x + y + z - 1, x + y + 2*z - 3 ], (x, y, z)) out[41]: {(-y - 1, y, 2)} augmented matrix form: in [59]: linsolve(matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z)) out[59]: {(-y - 1, y, 2)} a*x = b form in [59]: m = matrix(((1, 1, 1, 1), (1, 1, 2, 3))) in [60]: system = a, b = m[:, :-1], m[:, -1] in [61]: linsolve(system, x, y, z) out[61]: {(-y - 1, y, 2)} note : order of solution corresponds order of given symbols.

javascript - jQuery column addition sequencing -

i trying apply visual cues user insert data in form field. red indicates input not valid, whilst green indicates content valid. code functioning, albeit in glitched manner. » issue one: "red state" flickers on event. » issue two: if manually insert correct (number) input in fields, 1 one, , then, in last field, press backspace, current input field empty string, sum total return nan. i suspect due parseint() javascript method, need computation can performed on pushed arrays. the specific reason why setup way, because on initial load, fields may populated , if so, want display green boxes , check mark visual queue that, section done. reason why entire block of code wrapped in setinterval() page scanning state should displayed , apply proper classes accordingly. html: staff information (for office locations) </center> </div><span class="mrquestiontext" style=""...

How do I get last record from a mysql column through php where several other query is running -

Image
im trying several user data (from voip calling card database) web portal multiple table login , name , registration date taken 1 table, last successful call date in table , current user balance , total duration in table. here demo screencap: my problem im not able last call date have query , last or latest date list of total call history filtering each user individually. codes given below: all of needed data in these 3 table "clientsshared, invoiceclients, calls," "clientsshared" holds login & balance data. "invoiceclients" holds name , account creation date. "calls" holds call duration , other call history <div> <table class="table table-striped table-bordered" cellspacing="0" width="100%"> <thead> <tr> <th>#</th> <th>login</th> <th>full name</th> <th>reg.date</th> ...

azure - Common list among web role -

i have 2 web roles. each maintains concurrent dictionary updates. there way make sure changes made 1 visible others. or in other words, n number of web role instances there should 1 copy of data (collection or object not db table). each instance of web role separate vm. so... whatever technique you'd use between 2 computers viable 2 vms. you mentioned no databases, rules out quite bit. cannot share collections or objects because, again, you're talking synchronization across 2 separate vms. note cloud services have cache role well, can consider sharing content between instances (and not ultimate answer; i'm pointing out cloud services provide out-of-the-box).

ruby on rails - Efficient way to query on children based on a parent filter mongo mapper -

here 2 models have: class parent many :children key name end class children belongs_to :parent key price key description end i want find children have parent particular name let's test. i with children.all.select{|a| a.parent.name == "test"} but define scope in children class possible using clause? i tried with scope :parent_name, where("parent.name" => "test") but not work.

sql - Coldfusion - Comma delimiter with comma inside value -

i building list using sql data , trying make each value of list as: 'value1',value2','value,4' , on. problem using code: ( select count(ns.ticket) ns_trade ns ns.[login]=mt.[login] , <cfif qgetcommentsaccounting.recordcount gt 0> ns.comment in ('#listchangedelims(qgetcommentsaccounting.list_comments, "','")#') <cfelse> 1=2 </cfif> )as no_of_tickets_accounting which works perfect except when value has comma inside 'value,4' . suggestions how solve that? if both queries work on same database, way more kiss put them together. usually, should try as possible within database. select count(ns.ticket) ns_trade ns ns.[login] = mt.[login] , ns.comment in ( select comment tbl_comment report_type = <cfqueryparam value="#arguments.type#...

java - Split zero in String -

guys have int value parse string [] , should write: if (first element == 0) split return value without 0 @ start. for example have 01, 02, 03, 04, 05, 06, 07, 08, 09, 10,... 20... 30.. so in return in split 0 value 0 first element, , return me next: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,... 20... 30.. actually need calendar, i've take date return me days 01, 02, 03 , on. here method code: public string setcurrentcalendarday() throws testexception, parseexception{ if (!getpage().getsession().canrun()) throw new testexception(page.invalidstatemessage); string currentdate = ""; date date = new date(); calendar cal = calendar.getinstance(); cal.settime(date); simpledateformat formatter = new simpledateformat("dd"); currentdate = formatter.format(date); return currentdate; } the first option use new simpledateformat("d") , not ("dd...

c++ - calling .cpp files from Objective-C class .m -

i have few classes written in c++ needs integrate ios project written in objective-c. got mac (c++) project client integrate project. need call methods in .cpp class objective-c class nsnotificationcenter or other way better it? if make file extension .mm can use both objective-c , c++ inside one. can messy try keep c++ touchpoints contains in few .mm files whole thing won't mix of objective-c , c++ , c code.

php - Doctrine2 - Generate From Database -

i generated entities existing mysql database, fail when trying generate repository classes. my doctrine.config.php $frapi_config = array( 'database' => array( 'driver' => 'pdo_mysql', 'user' => 'root', 'password' => 'root', 'dbname' => 'pizzavan', 'host' => 'localhost:3306' ), 'doctrine' => array ( // base path /src/frapi/ 'entitiesfolder' => "custom/application/model" ) ); my bootstrap.php //bootstrap.php use doctrine\orm\tools\setup; use doctrine\orm\entitymanager; require_once dirname(__file__) . "/../vendor/autoload.php"; require_once "doctrine.config.php"; // create simple "default" doctrine orm configuration annotations $isdevmode = true; $config = setup::createannotationmetadataconfiguration(array(__dir__ . "/../" . $...

android - Starting activity from fragment button click (intent) throws blank screen -

i'm trying start activity button placed in fragment, when run app (in emulator , in real device) , press button, activity doesn't start , blank screen whithout navigation bar appears. i've read lot this, , common error people had didn't declare activity or weren't inflating correct layout. idea appreciated, because don't right now. here code of manifest: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.isa.example" > <application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name=".mainactivity" android:label="@string/app_name" android:screenorientation="portrait" android:theme="@style/theme.customm...

Android accelerometer stability -

i trying use accelerometer detect flipping phone in 4 different angles face down (left, right, right side up, upside down) , whether done fast or slow. want stop checking after 30 degrees of flipping phone. my problem getting stability. work once in while , not work. @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); ... msensormanager = (sensormanager) getsystemservice(sensor_service); maccelerometer = msensormanager.getdefaultsensor(sensor.type_accelerometer); } @override protected void onresume() { super.onresume(); ... msensormanager.registerlistener(this, maccelerometer, sensormanager.sensor_delay_ui); } @override public void onsensorchanged(sensorevent event) { prets = ts; prex = x; prey = y; prez = z; realx = event.values[0]; realy = event.values[1]; realz = event.values[2]; x = math.abs(event.values[0]); y = math.abs(event.values[1]); z = math....

node.js - Node Express Mongoose MongoDB CORS failure -

i using node/express/mongoose/mongodb on debian vps webserver reason online cors request not firing. let me works on local server. when upload debian vps webserver cors request never goes through. know because debug logs never fire. mongodb server running , node/express server running. have npm reinstalled express/mongoose , cors addon many times , not think it's issue those... i have tested things on server curl -h w/ -origin flags. responses return correctly in console. leads me believe cors requests being blocked somehow (maybe browsers??) , express servers never reached. have tried starting browsers no security flags no avail also... 1 strange fact when responses return w/ curl, list different origins though specify 1 origin flag. confusing... i have tried changing access-origins many different times , ways. have tried allowing of them. have tried allowing ones specific requests... have tried using apache2 header mod , using .htaccess file allow cors. have ...

java - Maven and numerical performance -

i have maven project has custom machine learning classifier. using surefire plugin testing custom library, check border cases of classifier , stuff. want evaluate performance of algorithm data have. there maven plugin, or best practice run these "tests" (not unit tests, not integration tests, performance evaluations)? mean, i'm looking being able like mvn test >> tests run: 2, failures: 0, errors: 0, skipped: 0 mvn "lets-say-performance-test?" >> precision: 0.9, recall: 0.4, f-score: 0.55 i know create non-asserting pojo test surefire, prints metrics have, want know if there plugin want in more standardized way. if want print on console result of performance can use http://www.mojohaus.org/exec-maven-plugin/ execute classes have , attach build/test phase. but might more judicious have run real unit test example detect abnormal performance values...

arrays - Efficient bit shuffling of vector of binary numbers -

i have recorded data containing vector of bit-sequences, re-arrange efficiently. 1 value in vector of data this: bit0, bit1, bit2, ... bit7 i re-arrange bit-sequence order: bit0, bit7, bit1, bit6, bit2, bit5, bit3, bit4 if had 1 value work nicely via: sum(uint32(bitset(0,1:8,bitget(uint32(x), [1 8 2 7 3 6 4 5])))) unfortunately bitset , bitget not capable of handling vectors of bit-sequences. since have large dataset interested in efficient solutions. any appreciated, thanks! dec2bin , bin2dec can process vectors, can input numbers @ once , permute matrix: input=1:23; pattern = [1 8 2 7 3 6 4 5]; bit=dec2bin(input(:),numel(pattern)); if size(bit,2)>numel(pattern) warning('input numbers large pattern, leading bits cut off') end output=bin2dec(bit(:,pattern)); if available, use de2bi , bi2de instead.

JSON to JavaScript, SyntaxError: Unexpected token & -

i know question has been asked numerous times, don´t it. i creating site in mvc, , i'm creating json string model. want pass argument javascript function uses plot graph. here create json string. indeed creates valid json string, checked @ jsonlint . @{ var serializer = new system.web.script.serialization.javascriptserializer(); var weightsasjsonstring = serializer.serialize(enumerable.select(model, weight => new { date = weight.date, value = weight.value })); } further down create javascript variable , pass javascript function: var jsonstringtograph = @weightsasjsonstring; google.setonloadcallback(drawvisualization(jsonstring)); when run this, console prints 'syntaxerror: unexpected token &' @ line declare jsonstringtograph . googled around , concluded should put ' ' around @weightsasjsonstring , that. anyway, in drawvisualization, this: function drawvisualization(teststring) { ...

android - Navigation Drawer does not open when I use ViewPager as Fragment -

had scenario navigationdrawer not popup when use viewpager fragment launched when click 1 of navigationdrawer items.i using material design both navigationdrawer , viewpager both fragments. code b package com.andr.viewpager; import android.app.activity; import android.os.bundle; import android.support.v4.app.fragment; import android.support.v4.app.fragmentmanager; import android.support.v4.app.fragmentstatepageradapter; import android.support.v4.view.pageradapter; import android.support.v4.view.viewpager; import android.support.v4.widget.drawerlayout; import android.support.v7.widget.toolbar; import android.view.layoutinflater; import android.view.menuitem; import android.view.view; import android.view.viewgroup; import android.widget.toast; import com.andr.navdrawerdemo.fragmentdrawer; import com.andr.navdrawerdemo.friendsfragment; import com.andr.navdrawerdemo.homefragment; import com.andr.navdrawerdemo.messagesfragment; import com.andr.navdrawerdemo.r; public class vie...

c++ - Cin isn't waiting for input -

this program: #include <iostream> #include <string> #include <stdlib.h> using namespace std; int main(){ string strkingdom = ""; bool conquered_me;//see if conquered, going use on other program , true = game over. int gold; int food; int citizens; int soldiers; cout << endl <<"name of kingdom: "; cin >> strkingdom; cout << endl << "were conquered (true/false): "; cin >> conquered_me; cout << endl << "how many gold have?:"; cin>>gold; cout << endl << "how many food have?:"; cin >> food; cout << endl << "how many citizens have?:"; cin >> citizens; cout << endl << "how many soldiers have?:"; cin >> soldiers; return 0; } the problem when compile progam lets me insert first 2 variables , shows rest of questions (after compile): name of kingdom: steve were conquered (true/false...

node.js - Is it possible for a npm package to accept parameters -

is possible create npm package accepts parameters? e.g. npm install mypackage --save -**meaningoflife:42** thanks these cli options npm-install npm install (with no args in package dir) npm install <tarball file> npm install <tarball url> npm install <folder> npm install [@<scope>/]<name> [--save|--save-dev|--save-optional] [--save-exact] npm install [@<scope>/]<name>@<tag> npm install [@<scope>/]<name>@<version> npm install [@<scope>/]<name>@<version range> npm (with of previous argument usage) you can see more details with npm install

php - How to create users like students and professors on MySQL? -

i'm newbie php , mysql. project creating website online on can put school friend's grades , manage them. problem don't know how separate users students/teachers. i got idea still not clear. if in login page make radio button , add on this: "student or teacher". if choose teacher must test teacher's accounts login in them midify page. you should user/group/role pattern. you'll enter individuals groups , assign roles groups. you'll have decide if want 1 role per individual or many.

c++ - QtQml conversion for Non-QObject types -

since qtscript deprecated in qt5.5, have migrate qtqml js engine. can't find articles, how migrate painless. in old code value-based types (not derived qobject) possibility create wrapper, deriving qscriptable. in qtqml there no qscriptable. know, have similar conversion qml basic types , point <-> qpoint rectangle <-> qrect i think, should possible register value-type conversion functions wrapper , vice-verse. do know how achieve it?

ios - Get size of currently visible UIViewController from a UIView -

i've been looking @ same problem long i'm missing simple solution here. i created small library provide custom uiview sticks keyboard 1 imessage (aka doesn't hide keyboard): https://github.com/oseparovic/messagecomposerview basically problem i'm experiencing when user init's custom view want view following default rect initialized: cgfloat defaultheight = 44.0; cgrect frame = cgrectmake(0, [self currentscreensize].height-defaultheight, [self currentscreensize].width, defaultheight) this requires currentscreensize calculated within uiview. i've tried multiple implementations of have downsides. there doesn't seems solution due breaking principles of mvc. there lots of duplicate questions on assume have access rest of code base (e.g. app delegate) custom view not i'm looking self contained solution. here 2 leading implementations i'm using: nextresponder ...

node.js - webpack css-loader not finding images within url() reference in an external stylesheet -

i'm new whole node/npm/webpack world, apologies if obvious. i'm attempting build simple front-end project bundled webpack. i've got node installed, , have package.json file configured. if run "npm start" in root directory, no errors console, , i'm able go "localhost:3000" in browser , see "hello, world" output. my next task include stylesheet, contains reference image, this: .myimg {background: url(path/to/file.jpg);} with things set this, can view image via webpack-dev-server (by going localhost:3000 in web browser), if build project, path image wrong. have no idea i'm doing wrong, i'm throwing out stackiverse in hopes out there know stupid thing i'm doing. here's package.json file: { "name": "webpack-test1", "version": "0.0.1", "description": "my project wtf.", "private": true, "scripts": { "start": ...

c# - How Do I Open/Run A Class From A Separate Class? -

i'm making simple dos os c# on xamarin studio. thing i've made several programs doing thing can't on xamarin, in visual studio. as best can explain difficulties: have class named osbootup.cs , want class run, starts different class in project. there way that? , if not, way can it? my code: (osbootup.cs) using system; using system.io; using system.threading; namespace operatingsystemcore { public static class osbootup { public static void main (string[] args) { bool isstarting; start: isstarting = true; console.write ("starting syteraos "); thread.sleep (1000); console.write (". "); thread.sleep (1000); console.write (". "); thread.sleep (1000); console.write (". "); thread.sleep (1000); console.clear (); console.write ("starting sytera...

Java - toString Formatting (Formatting Doubles) -

the project working on requires bank account balance printed using tostring method. not allowed add methods current program, need format mybalance variable double goes 2 decimal places instead of one. in particular instance program should printing 8.03, printing 8.0. here tostring method: public string tostring() { return"savingsaccount[owner: " + myname + ", balance: " + mybalance + ", interest rate: " + myinterestrate + ",\n number of withdrawals month: " + mymonthlywithdrawcount + ", service charges month: " + mymonthlyservicecharges + ", mystatusisactive: " + mystatusisactive + "]"; } i new java still, know if there way implement %.2f string somewhere format mybalance variable. thank you! use string.format(...) this: @override public string tostring() { return "savingsaccount[owner: " + myname + ", balance: ...

java - Unable to install breakpoint :Eclipse Kepler -

Image
from last 1 week getting below exception in eclipse kepler when running server in debug mode but after exception breakpoints working fine , deleted breakpoint mentioned in error issue not resolved saw 1 question eclipse unable install breakpoint saying fixes why issue coming last 8years never got issue. any other quick fix this? if problematic class generated dynamically (e.g. spring framework), have consult documentation of framework how enable generation of debug information during compilation of these classes.

c# - Error when play is clicked:NullReferenceException: Object reference not set to an instance of an object -

i pretty new c# , unity,so question basic. has bugged me long, couldn't on after research on internet. anyway, here question, have got error nullreferenceexception: object reference not set instance of object achievementbutton.click()(at assets/scripts/achievementsystem/achievementbutton.cs:25) achievementmanager.start()(at assets/scripts/achievementsystem/achievementmanager.cs:30) when clicked on play or when click button view list of achievements. achievementmanager script: using unityengine; using system.collections; using unityengine.ui; public class achievemenetmanager : monobehaviour { public gameobject achievementprefab; public sprite[] sprites; public achievementbutton activebutton; public scrollrect scrollrect; // use initialization void start () { //here error logged activebutton = gameobject.find("streakbtn").getcomponent<achievementbutton>(); createachievement("s...

javascript - ng-dblclick missing second doubleclick when done in rapid succession -

with ng-dblclick on angular 1.4.3 when click 4 times in rapid succession 1 doubleclick registered. using html: <div ng-dblclick="incclicks();">double click me!</div> here plunker try it. tested in in firefox 39 , chromium 43 how can make every doubleclick count?

asp.net mvc - The following sections have been defined but have not been rendered for the layout page even though I have set required:false -

this question has been asked lot , answer has been set @rendersection("mysection", false) however in case not working. the error is: the following sections have been defined have not been rendered layout page "~/views/shared/kittenlayout.cshtml": "styles". my pages are: kitten.cshtml has layout = "~/views/shared/kittenlayout.cshtml"; kittenlayout.cshtml has 2 sections defined, @section stuff , section @otherstuff , , has layout = "~/views/shared/_kittenmasterlayout.cshtml"; _kittenmasterlayout.cshtml has @rendersection("styles", required: false) why getting error? i have fixed this, apparently there no inheritance, if have pages a->b->c main page, b master page, , c master-master-page, if define section on c , render on you'll error. have add b , pass through. adding page b fixed it: @section styles { @rendersection("styles", required: false) }

c# - How can I share constructor code with readonly class members? -

i have class, foobarset single "core" chunk of initialization logic. a foobar made of foo , bar . class foobarset initialized list of foobar . foobarset can also initialized separate parallel foo , bar lists. ideally, run this: public class foobarset { private readonly list<foobar> _list; // primary constructor. public foobarset(list<foobar> foobarlist) { // contracts , initialization... _list = foobarlist; } // secondary constructor. public foobarset(list<foo> foolist, list<bar> barlist) { // zip new list of new foobars var zipped = foolist.zip(barlist, (foo, bar) => new foobar(foo, bar)); // call primary constructor zipped list. this(zipped); } } this c#, not java, this(zipped) illegal. common solution, as in answer , pull core initialization common private method: public class foobarset { private r...