Posts

Showing posts from February, 2014

sql - How do I identify Interaction in a column and take sum based on values in two other columns? -

i have 3 tables- table 1 customer id | date | score | score factor ------------+------------+-------+------------- 100 | 2014-10-10 | 15 | .25 100 | 2014-12-12 | 25 | .35 100 | 2014-08-08 | 35 | .65 100 | 2014-09-08 | 45 | .55 100 | 2014-01-10 | 15 | .25 100 | 2014-12-12 | 75 | .85 100 | 2014-08-08 | 85 | .65 100 | 2015-09-08 | 45 | .55 200 | 2014-10-10 | 45 | .25 200 | 2014-12-12 | 55 | .35 200 | 2014-08-08 | 35 | .65 200 | 2014-09-08 | 45 | .55 200 | 2014-01-10 | 55 | .25 table 2 score | group# | group label -------+--------+-----------+ 10 | 1 | superior | 15 | 1 | superior | 25 | 1 | superior | 35 | 2 | mediocre | 55 | 2 | mediocre | 65 | 3 | poor | 75 | ...

javascript - How to do an HTTP request from Parse (Parse Cloud Code)? -

i trying http request parse heroku server. getting error xcode console when calling function "savetodatabase": myapp[1400:88895] [error]: uncaught init failed:not supported argument (code: 141, version: 1.7.5) parse cloud function failed called generate token error: optional(error domain=parse code=141 "uncaught init failed:not supported argument" userinfo=0x7fd2a2d5abf0 {code=141, originalerror=error domain=nsurlerrordomain code=-1011 "the operation couldn’t completed. (nsurlerrordomain error -1011.)", temporary=0, error=uncaught init failed:not supported argument, nslocalizeddescription=uncaught init failed:not supported argument}) parse.cloud.define("savetodatabase", function(request, response) { var userinformation = { id: 1003 }; var userjson = json.stringify(userinformation); var plz = "success"; return parse.cloud.httprequest({ url: 'https://myapp.herokuapp.com/saveusertodatabase...

android - Im trying to display album art within the listview, but having issues -

im able display album art on playing screen, not through listview using same code, difference really, being run through adapter class, artist name , title display each item in list listview class public void getsonglist() { //query external audio contentresolver musicresolver = getcontentresolver(); // uri musicuri = android.provider.mediastore.audio.media.external_content_uri; string selection = mediastore.audio.media.is_music + "!=0"; string sortorder = mediastore.audio.media.default_sort_order; cursor musiccursor = musicresolver.query(urimusicshow, null, selection, null, sortorder); //iterate on results if valid if (musiccursor != null && musiccursor.movetofirst()) { //get columns int titlecolumn = musiccursor.getcolumnindex (android.provider.mediastore.audio.media.title); int idcolumn = musiccursor.getcolumnindex (android.provider.mediastore.audio.media._id); ...

regex - Regular Expressions to Update a Text File in Python -

i'm trying write script update text file replacing instances of characters, (i.e. 'a', 'w') word (i.e. 'airplane', 'worm'). if single line of text this: a.function(); a.callmethod(w); e.aa(w); i'd want become this: airplane.function(); airplane.callmethod(worm); e.aa(worm); the difference subtle important, i'm changing 'a' , 'w' it's used variable, not character in other word. , there's many lines in file. here's i've done far: original = open('original.js', 'r') modified = open('modified.js', 'w') # iterate through each line of file line in original: # search character 'a' when not part of word of sort line = re.sub(r'\w(a)\w', 'airplane', line) modified.write(line) original.close() modified.close() i think re pattern wrong, , think i'm using re.sub() method incorrectly well. appreciated. if you're concerned...

qt - Getting a Box2D body created in C++ to collide with Box2D bodies in QML -

i using qml-box2d library. create box2d body fixtures in c++ , use in qml. unfortunately, time create b2body object , create fixtures object app crashes. if use box2dbody object, comes qml-box2d library, doesn't show in qml. i need box2d body fixtures in c++ collide box2d bodies in qml. proper way this? pay attention - box2dbody not visual item since derived qobject . adds physical properties target . anyway, think easiest way create physical bodies in qml . if still want in c++ can use code below. suppose, have scene in main.qml qml rect item: window { width: 800 height: 600 visible: true world {} rectangle { objectname: "rect" width: 100 height: 100 x: 350 y: 50 color: "green" } rectangle { id: floor height: 50 anchors { left: parent.left right: parent.right bottom: parent.bottom } col...

Using PHP Array in Foreach -

i have 2 arrays: $users[] , $types[] with return result this: users = array ( [0] => 1 [1] => 1 [2] => 1 ) types = array ( [0] => 0 [1] => 1 [2] => 0 ) how can call them $user['0] , $types['0] in foreach ? want return them this: 1,0 1,1 1,0 foreach ($users $index => $code) { // return users first number echo $code; // want here return type first number of array aswell? } thanks, it's easy: foreach ($users $index => $code) { echo $users[$index].', '.$types[$index]; } if it's possible, each array contains different number of elements (or better don't know, how many items each array contains), should check, if particular element exists in second array: foreach ($users $index => $code) { echo $users[$index].', '.(isset($types[$index]) ? $types[$index] : 'doesn\'t exist'); } you can use example for loop: // array indexes start 0, if they're not set explicitly el...

algorithm - Sort alphabet letters using a Binary tree -

i came across interview question states: how represent letters a , b , c , d , e , f , g in sorted order using binary tree representation? it's stumped me. if take g root of tree left child e , right child f right subtree "greater than" left subtree. node e, left child , right child b , f 's left child c , right child d . is correct or else have different answer? the binary tree described binary heap , used implement priority queue. instead, use binary search tree , keeps keys in sorted order.

Ansible multiple include with multiple tasks? -

i have ansible playbook includes file twice , passes in parameter change behavior: site.yml: --- - tasks: - include: test.yml parm=aaa - include: test.yml parm=bbb the include file prints parameter value: test.yml: - debug: msg="dbg 1 {{ parm }}" the inventory file set run on localhost: inventory: localhost ansible_connection=local the result expect, include file runs twice, once parm=aaa , once parm=bbb: >ansible-playbook -i inventory site.yml play *************************************************************************** task [setup] ******************************************************************* ok: [localhost] task [include parm=aaa] ******************************************************** included: test.yml localhost task [debug msg=dbg 1 {{ parm }}] ********************************************** ok: [localhost] => { "changed": false, "msg": "dbg 1 aaa" } task [include parm=bbb] **********...

ruby on rails - How to do integration tests without controllers? -

i've done integration (aka "feature") tests rspec , capybara, i'm building complex piece of functionality combines various ruby classes , rails models , there no controller or ui involved really. i'd perform series of tests touches these various classes , models make sure work expected. this doesn't seem unit testing these tests require multiple objects work together. it doesn't seem traditional rails "integration" tests, since i'm not navigating ui or hitting controllers. so these , how can build , organize them in rails app? you're not limited rails' 'out of box' set of folders or test types. can add additional folders , organise them want. if you're getting started , don't have many, i'd put them in spec/objects or spec/poros (plain old ruby objects) , test them there. number of them grows, you'll want break them folders - decide on convention makes sense, , follow it. once go beyond s...

php - Why isn't the image being displayed? -

i'm trying static image bing maps pushpins , showing location of individuals. i'm using imagery api bing supplies , using simple example code i'm getting ";?> instead of image. <html> <head> <title>driver locations</title> </head> <body> <?php $latitude = "40.59507828"; $longitude = "-73.78302689"; $key = ""; $imagerybaseurl = "http://dev.virtualearth.net/rest/v1/imagery/map"; $pushpins = "&pp="; $mapsize = "?mapsize=800,600"; $ppstyle = ";47;"; $imageryset = "road"; $juliecp = $latitude.",".$longitude; $juliepp = $juliecp.$ppstyle."julie"; $zoomlevel = "15"; $latitude = "40.90421779"; $longitude = "-73.86591633"; $markcp = $latitude.",".$longitude; $markpp = $markcp.$ppstyle."mark"; //http://dev.virtuale...

ios - QRCode scanner issue with react-native-camera -

i use reactnative develop ios app,to realize qrcode scanner function,i took react-native-camera component provide barcode scanner function project.everything goes right,but when had succeed in recognizing qrcode,next time use model,the screen got frozen,seems app goes crashed. interesting screen frozen,and once model cancelled left button of navigation,the module can work properly. i'm not sure whether it's inner bug of navigatorios,or bug of react-native-camera itself. here qrcode component code: 'use strict'; var react = require('react-native'); var dimensions = require('dimensions'); var { stylesheet, view, text, touchableopacity, vibrationios, navigator, } = react; var camera = require('react-native-camera'); var { width, height } = dimensions.get('window'); var qrcodescreen = react.createclass({ proptypes: { cancelbuttonvisible: react.proptypes.bool, cancelbuttontitle: react.proptypes.string, ...

Syntax: Applying IF to a cell range in Excel -

i've been trying write formula summarise in 1 cell presence/ absence of values in different range of of cells in excel so in 1 table , worksheet, wrote =if(b1:f1=1,1,0) formula 1 which supposed mean if of values in cells b1:f1 equal 1, note 1, otherwise not 0. but somehow syntax isn't working. i've applied "" , ; , brackets right left , centre, no avail. i'm pretty sure done before , pretty simple when hit upon right synstax, how , fell through colander brain today :-? additionally want ask formula apply condition output cell =if (a1 = value n or values, 1, 0) formula2 column has numerically coded ordinal values 0-9, aexample of teh 1 conditions might of values 1, 2 or 9 in column, should produce 1 in result cell in formula 1 , 2 written. so result cell contain somelike =formula1_or_formula2_contain_certain_values, 1, 0) formula 3 systax of formulas 2 , 3 awol, write demonostrate formulae intended purposes. the easiest way mak...

python - Error installing "Contextify" module in node.js in windows 8 -

i installed jsdom 3.1.2 module has dependency on contextify. trying install contextify show error in cmd: key error: "c:\program files (x86)\microsoft visual studio 2012.0\vc\bin i installed python 2.7 , set environment variable name "pythonpath" , values "c:\python27". installed ms visual studio 2013 desktop , set environment variable: variable name "gyp_msvs_version" , variable values "c:\program files (x86)\microsoft visual studio 2012.0\vc\bin" can tell me problem? thank you. gyp_msvs_version should set version, not path. in case command set gyp_msvs_version=2013 .

sql server - Best way to solve SQL if Condition -

i have problem table item item |begin | in01 | in02 | ..| in12 | out01 | out02 |..|out12 | balance | 100 | 10 | 20 | ..| 10 | 5 | 10 |..| 5 | 110 item have begin qty 100 @ first month, , balance qty @ month 12 = 110 balance updating every month i need call procedure data every month report sample report month 01 beginning| in | out | balance 100 | 10 | 5 | 105 sample report month 02 beginning| in | out | balance 105 | 20 | 10 | 115 sample report month 12 beginning | in | out | balance balance month 11 | xx | xx | 11 + in - out so beginning value = balance last month way make stored procedure simple? not using lot of 'if' it's better using case ? need idea.. thanks u can used case statement avoid if statement select case when beginning value = balance 1st option else 2nd option test tbltest

javascript - AngularJS: Model Not Updating On ng-change? -

i have angular app has text input box takes number. box bound using ng-model packstoreplenish . has ng-change calls updateallcalculations() . idea being when enter number in text field, model updates, , updateallcalculations executes. problem is, far can tell model never updates, instead staying @ 0, regardless of enter box. because of this, console.log shows 0 output of bound model, , logic fails due inaccurate data. can tell me how fix this? here pertinent code snippets: html <input type="number" class="form-control" ng-model="packstoreplenish" ng-change="updateallcalculations()" required> javascript (in app , controller of course - omitted save space) $scope.packstoreplenish = 0; $scope.samples = []; //populated elsewhere $scope.updateallcalculations = function () { (var = 0; < $scope.samples.length; i++) $scope.updatecalculations(i); } $scope.updatecalculations = function(idx) { console.log(...

Android WebView - Youtube videos not playing within the application -

i have activity displaying web page using webview. within page, there link youtube video (so it's not video can or need embed). the problem video won't play - when click on play button, error page appears saying " webpage not available webpage @ vnd.youtube:svf8ghl6d8xx might temporarily down , blah blah blah !!!" please answer if know want! have gone through related posts on stackoverflow there no need of references other posts/question. mainactivity.java @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); // add custom view action bar webview = (webview) findviewbyid(r.id.webview1); webview.getsettings().setjavascriptenabled(true); if(build.version.sdk_int < build.version_codes.jelly_bean_mr2) webview.getsettings().setpluginstate(websettings.pluginstate.on); //helps flash run on device ...

inheritance - In C#, if A implements IX and B inherits from A , does it necessarily follow that B implements IX? -

in c#, if implements ix , b inherits , follow b implements ix? if yes because of lsp ? there differences between : 1. interface ix; class : ix; class b : a; and 2. interface ix; class : ix; class b : a, ix; ? is there terminology associated b implementing ix though chain of inheritance or b implementing ix directly? ps: assuming in both cases interface implemented implicitly, not explicitly. patterns utilize on 1 , not work if implemented in 2? from msdn : a class inherits interface implementations provided base classes. without explicitly re-implementing interface, derived class cannot in way alter interface mappings inherits base classes. however, goes on if base class implements interface method virtual, can overridden derived class. implicit implementation can overridden in derived class explicitly.

automation - Central git to push changes automatically to multiple git repos in different servers -

i have following scenario: server main server developers pushing code , merging master line. particular git line synched across multiple servers server b/c/d/e need repo synched. is there automative technique same? kindly suggest. thanks!

java - LibGDX bytecode reader/writer -

i working on mapeditor game. , need way save map. i'm working libgdx. , use android , desktop backends. the maps 2d , should contain: shape / body data (vertices/radius/type...) box2d. texture/particle pos/filepath. questions: how read/write bytecode in libgdx. how make example format .map? ( hills.map ) all want files in libgdx can achieve using filehandle libgdx mechanism. it's simple: filehandle file = gdx.files.local("file.txt"); this code creates handle file (whatever existed or not - created new) can use make operations on file. writing , reading bytes can achieved using: void writebytes(byte[] bytes, boolean append) byte[] readbytes() then in situation should like filehandle filehandle = gdx.files.local("mymap.map"); filehandle.writebytes(yummybites, false); you can read file handling (and ...local() means) here: https://github.com/libgdx/libgdx/wiki/file-handling i'm not sure mean saying ...

c# - How to approach building an expression/condition evaluator GUI? -

i have winforms application connected database contains huge amount of measurement data of different datapoints. data gets updated every few seconds, old values go archive table etc. i'm using ef6 data access. now need build gui offers functionality follows: the user should able define conditions and/or expressions @ runtime trigger actions when true. example in pseudo-code: if ([value of datapoint 203] >= 45 , (timestamp of datapoint 203 < "07:00am") , (([value of datapoint 525] == 1]) or ([value of datapoint 22] < 0)]) set [value of datapoint 1234] ([value of 203]/4) //or call method alternatively or simpler example in natural language (differs above): if cold , raining, turn on machine xy where cold , raining values of datapoints , turn on machine method given parameter xy . these expressions need saved , evaluated in regular intervals of minutes or hours. did not face such requirement before , hardly know start. best practice? there maybe...

windows - Using XAudio2 in C -

i working on c program using visual studio 2015 on windows 10. when include xaudio2.h few hundred compiler errors, believe errors stem one: error c2485 'uuid': unrecognized extended attribute is there anyway xaudio2 working c application? in short, latest versions of xaudio2 (xaudio 2.8 in windows 8.x sdk, xaudio 2.9 in windows 10 sdk) don't support c, c++. the older xaudio 2.7 deprecated directx sdk builds c, although it's had no testing c. in fact, directx usage c rather c++ hasn't been tested or supported in very, long time. midl compiler used generating com interface headers still has lot of c-related support macros , elements when c usage first-class citizen, stuff in "as is" state gets little no test coverage. you can continue frustrate yourself, can wrap c++ code in own c callable wrapper, or start using c++. see this post , this post important information using vs 2015 legacy directx sdk.

scala - Derive multiple columns from a single column in a Spark DataFrame -

i have df huge parseable metadata single string column in dataframe, lets call dfa, colmna. i break column, colmna multiple columns thru function, classxyz = func1(colmna). function returns class classxyz, multiple variables, , each of these variables has mapped new column, such colmna1, colmna2 etc. how such transformation 1 dataframe these additional columns calling func1 once, , not have repeat-it create columns. its easy solve if call huge function every time add new column, wish avoid. kindly please advise working or pseudo code. thanks sanjay generally speaking want not directly possible. udf can return single column @ time. there 2 different ways can overcome limitation: return column of complex type. general solution structtype can consider arraytype or maptype well. import org.apache.spark.sql.functions.udf val df = seq( (1l, 3.0, "a"), (2l, -1.0, "b"), (3l, 0.0, "c") ).todf("x", "y", "z...

javascript - Better way to rewrite this .each() function -

this code works fine, i'm guessing there better way rewrite in either jquery or vanillajs. the main goal is: to clone specific child elements parent element create new elements cloned child elements append newly created elements new container. $('.grid-block').each(function(){ var slide = $('<div class="slide"></div>'); $(this).find('.asset-holder img') .clone() .appendto(slide); $(this).find('.asset-tools') .clone() .appendto(slide); slide.appendto('.gallery-slider'); });` i don't know need iteration, combine calls find() : var slide = $('<div class="slide"></div>'); $('.grid-block').find('.asset-holder img, .asset-tools').clone().appendto(slide); slide.appendto('.gallery-slider');

unable to start app in node.js getting the following error -

welcome git (version 1.9.5-preview20150319) run 'git git' display index. run 'git ' display specific commands. $ npm start nodeauth@1.0.0 start c:\users*****\desktop\nodeauth node ./bin/www c:\users***\desktop\nodeauth\node_modules\express\lib\application.js:206 throw new typeerror('app.use() requires middleware functions'); ^ typeerror: app.use() requires middleware functions @ eventemitter.use >>...> //app.js var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var expressvalidator = require('express-validator'); var cookieparser = require('cookie-parser'); var session = require('express-session'); var passport = require('passport'); var localstrategy = require('passport-local').strategy; var bodyparser = require('body-parser'); var multer = req...

node.js - Connect to MongoDB with authentication using Node JS -

i trying connect mongodb user/password , did far: var mongoclient = require('mongodb').mongoclient; // connect db mongoclient.connect("mongodb://${host}:27017/${db}", function(err, db) { if(!err) { console.log("successfully connected database"); }else{ console.log("error on connecting... aborting , exiting"); return console.dir(err); throw err; } db.authenticate('username', 'password', function(err, res) { console.log("reached here"); }); }); now trying login inside data base in order able inside mongo database's collections, how can that? thanks! you can perform curd operations following: var mongoclient = require('mongodb').mongoclient; // connect db mongoclient.connect("mongodb://${host}:27017/${db}", function(err, db) { if(!err) { console.log("successfully connected database"); //here can perform ope...

.net - Google Drive Query issue with single quote and back slash -

we have implemented several applications interacting google drive through google drive sdk v2 . we facing problem "single quote" , "back slash" the problem in google drive able create files , folders containing special characters, if going pass same file or folder name using api giving error, invalid query. we know kind of scenarios recommended use escape characters or encoding pass value problem , google not understand escape character or encoding expects string query. example: title = 'hello dev's 1\2\3' slash found answer adding \ before single quote, still figuring out . i wondering if knows how resolve this, or if known behavior. thanks, i have found answer this, pretty simple, somehow there not enough documentation it, when using google drive api, in order pass special characters google, required use "back-slash" before special character. so example going set search query this, 'title = martin's pap...

view flip (calender flip) 3d animation android -

i trying have calendar flip animation on view. have looked many examples got more confused. i need create animation - flip view , show one. if want implement calendar flip animation in flip card manner, should try using library. https://github.com/emilsjolander/android-flipview it gives general way it. can extend further finer implementations.

javascript - JQuery: How to detect mobile width and change my css to it's with using jquery? -

how detect mobile width , change css it's current window width using jquery? for example .page { box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; float: left; margin: 40px 0; max-width: 480px; min-height: 720px; height: auto; min-width: 360px; padding: 10px; width: 100%; } and have function not sure if it's working. function responsivefn() { width = $(window).width(); document.getelementbyid('widthid').innerhtml = width; jquery('.page').css({ max-width: width }); } thanks answer in advance! :) no need of using javascript/jquery, check below points. suggestions: use width in percentages so, when resized it'll auto adjust use media queries resolution specific styles when setting properties javascript, use quotes around property name or use camelcase. ex. maxwidth, or 'max-width' example: @media (max-width: 600px) ...

objective c - How does the web version of Whatsapp work on iOS devices considering the OS shuts apps in 30 seconds? -

now don't know, can go https://web.whatsapp.com/ , sync whatsapp chats exchanging qr code , chat via web extension of app. i not interested in how have initial handshake( might communicating whatsapp servers) nor how sync data fast chatting (might using open sockets directly device client). i curious how app works in background on ios . afaik running background intent service pretty simple. not ios. ios allows 30 seconds after app shut down normally. 1) tried crashing app(swipe up) (still web version running normally) 2) disabled background app refresh web version didn't stop. 3) disable notifications still web version worked normally. 4) not have blue bar likes when google maps giving directions indicates app running in bg 5) using dummy geo fencing keep them alive? (but d require bg app refresh too) is new feature on ios 8 introduced , not aware of just side note, apple introduced notification service extension point in ios 10, can used a...

scala - How call function which is return from another one? -

i trying call function marshal httpresponse spray . unmarshal function described here . response httpresponse consider 3 code variants: first val func = unmarshal[mytype] func(response) second unmarshal[mytype].apply(response) third unmarshal[mytype](response) why third code variant not compile while first 2 works? compiler returns: [error] found : spray.http.httpresponse [error] required: spray.httpx.unmarshalling.fromresponseunmarshaller[mytype] [error] (which expands to) spray.httpx.unmarshalling.deserializer[spray.http.httpresponse,mytype] [error] unmarshal[mytype](response) is there way call function returned unmarshal more elegant create temp variable or direct call apply method? the signature of function (from link): def unmarshal[t: fromresponseunmarshaller] so t needs implicit evidence there's such fromresponseunmarshaller it. signature compiles like: def unmarshal[t](implicit evidence$1: fromresponseunmars...

websphere - Can not connect to IBM content navigator web administration -

when tried connect navigator web administration, receive message "the desktop can not opened" , require defining desktop id. http://imgur.com/jnkelpy how fix problem or define desktop id? i can't remember if after installation default desktop admin or if have set manually. url ?desktop=admin @ end working ( https://ecm.filenet.com:9443/navigator/?desktop=admin )? if does, create desktop , set default. if doesn't, should take @ log (systemout.log) see error is.

sql server 2008 - Fetch SQL data? -

i want fetch data table when run powershell script. have written following script. reason displaying field counts , not actual data. my script: add-pssnapin sqlserverprovidersnapin100 add-pssnapin sqlservercmdletsnapin100 $db = get-content c:\users\riteshthakur\desktop\test.txt | select -index 0 $table = get-content c:\users\riteshthakur\desktop\test.txt | select -index 1 $sqlconnection = new-object system.data.sqlclient.sqlconnection $sqlconnection.connectionstring = "server=.;database=$db;integrated security=true" $sqlconnection.open() $sqlcmd = new-object system.data.sqlclient.sqlcommand $sqlcmd.commandtext = "select * $table" $sqlcmd.connection = $sqlconnection $x = $sqlcmd.executereader() write-output $x $sqlconnection.close() once created reader need read data : $x = $sqlcmd.executereader() while ($x.read()) { $x.getvalue(0) $x.getvalue(1) ... } $x.close() or use sqldataadapter instead of reader: $sqlcmd = $sqlconnection.cr...

javascript - Open New Tab and Close the Current Tab -

is there easy work around close current tab , open new tab javascript? try below : window.open('http://www.google.com','_blank');window.settimeout(function(){this.close();},1000)

hadoop - headnodehost in Azure HDInsights -

what headnodehost in azure hdinsights? setup hbase cluster. there headnodes in hbase cluster. when rdp cluster , open hadoop name node status weblink desktop, opens web browser link set headnodehost:30070. headnodehost same headnodes? hostname command in rdp gives me "headnode0" rather "headnodehost". each hdinsight cluster has 2 headnodes high availability. documented in https://azure.microsoft.com/en-us/documentation/articles/hdinsight-high-availability/

groovy - Set grails domain object property without calling the setter method -

domain person has property name . setter method has been overridden store name embedded inside internationalization object within person object as: internationalization: { name: { en: engilshname, fr: frenchname } } therefore piece of code: def person = new person() person.setname('merhawi', new locale('en')) person.setname('frenchmerhawi', new locale('fr')) person.save() would store name inside mongo database as: { _id: numberlong(1), internationalization: { name: { en: "merhawi", fr: "frenchmerhawi" } } } invoking getname on person return correct name depending on current locale of environment. now trying is: person json data want field name contains correct name depending on current locale of environment besides other fields. trying set person.name = person.getname() before returning person grails.converters.json call setter method , d...

vector - Perpendicular line java -

hello need find perpendicular line another. have 1 initial point(x,y), 1 final point(x, y) , measure de perpendicular line. have tried in various ways i've seen on page i'm doing wrong. whenever line perpendicular axis y o axis x instead of line. know tell me i'm doing wrong? some links have been looking @ are: calculate perpendicular offset diagonal line how calculate end points of perpendicular line segments? calculate point normal line thank much. canvas.addpaintlistener(new paintlistener() { public void paintcontrol(paintevent arg0) { ////pruebas con arcos ///pruebas con perpendiculares point centro = new point(0, 0); point director = new point(0, 0); point normalizado = new point(0, 0); point escalado = new point(0, 0); point rotado = new point(0, 0); point resultadomas = new point(0, 0); ...

javascript - Values of a dictionary in a dropdown -

my models.py follows: class sellermarketplaces(models.model): id = models.integerfield(db_column='id',primary_key=true) # field name made lowercase. seller_id = models.foreignkey('sellerdetails',db_column='seller_id') # field name made lowercase. mk_id = models.foreignkey('marketplace',db_column='mk_id') # field name made lowercase. username = models.charfield(db_column='username', max_length=100, blank=true, null=true) i have following code in views def marketplaces(request): seller = request.get.get('seller', '') allmarketplaces = sellermarketplaces.objects.filter(seller_id = seller).values('mk_id__marketplace') in range(len(allmarketplaces)): print allmarketplaces[i]['mk_id__marketplace'] return render_to_response(request,'soumi1.html',{'marketplaces':marketplaces}) i getting values (flipkart & snapdeal) print allmarketplaces[i]['mk_id__marketplaces] ...

node.js - Splitting production/development databases -

i'm working on mongodb backed expressjs app. i've used express generator create it. i work on development database through mongolab, , deploy heroku (which backed mongolab database). what best practices splitting these 2 when start app in development mode uses development mongo instance, , when deploy heroku in production mode use production db? thanks! heroku's 12factor architecture document great job of explaining both best practices of config management, , rationale behind them: http://12factor.net/config the tldr is, "pull in config environment variables , use explicit configuration instead of named environments 'development' or 'production.'" heroku provide environment variables need connecting mongolab db, have sort out providing same variables app locally. 1 common solution .env file: https://devcenter.heroku.com/articles/heroku-local#copy-heroku-config-vars-to-your-local-env-file this file don't check i...

twitter bootstrap - Video background in PHP for index page -

i trying video background on index page works fine on html page doesn't work on php. <div class="header-container"> <div class = "video-container"> <video preload = "true" autoplay = "autoplay" loop= "loop" volume = "0" poster = "pic.jpg"> <source src = "mp4/fa.mp4" type="video/mp4" > </video> </div> </div> .header-container { width:100%; height: 900px; border-left: none; border-right: none; position: relative; padding: 20px; } .video-container { position: absolute; top: 0%; left: 0%; height: 100%; width: 100%; overflow: hidden; } video { position: absolute; z-index: -1; opacity: 0.78; width: 100%; } i want make work on php. i not able figure out why isn't playing on localhost, although displays text content perfectly. video playback not visible.

c# - WCF service - Return int from "Method = 'DELETE'" -

Image
i'm trying sort of exception control in service (returning simple integers , handling these in gui), i've stumbled upon difficulty. in of post , , put return either 1 or -1 (depending on exception receive), can't seem return integer delete method. this approach: iservice.cs [operationcontract] [webinvoke(method = "delete", uritemplate = "/logins/delete/{stringid}")] int deletelogin(string stringid); service.cs /// <summary> /// deletes login given stringid /// </summary> /// <param name="stringid"></param> public int deletelogin(string stringid) { try { var id = int32.parse(stringid); var dblogin = dao.hourreginstance.login.singleordefault(x => x.id == id); dao.hourreginstance.login.remove(dblogin); dao.hourreginstance.savechanges(); return 1; } catch(exception e){ return -1; } } don't waste time explaining me catch specific exce...

build.gradle - how to run shell script from Gradle and wait for it to finish -

i'm running shell script gradle, issue shell script running prerequisites need run before gradle continues. i tried following seems gradle opening child process shell script sleep.sh echo 'hi1' sleep 1 echo 'hi2' sleep 10 echo 'bye' gradle: task hello3(type: exec) { println 'start gradle....' commandline 'sh','sleep.sh' println 'end gradle....' } result: start gradle.... end gradle.... :hello3 hi1 hi2 bye your problem println statements executed when gradle parses build.gradle file, not when executes task. you should move println statements dofirst , dolast follows make things clear: task hello3(type: exec) { dofirst { println 'start gradle....' } commandline 'sh','sleep.sh' dolast { println 'end gradle....' } } i believe, gradle waits script finish before doing else, not need special make wait. gradle start shell script in child process. ...

java - Spring RESTFUL web Service how to handle inorder to remove null objects in json response -

i have spring webservice returns json response using spring. the format json returned in is: {"data": { "bidprice": 26.8, "fundnames": null, "offerprice": 27.4, "fundid": "123456789", "funddescription": "high risk equity fund", "lastupdated": "2015-08-25t15:48:57" }} i want remove null objects(fundnames) returned response looks like {"data": { "bidprice": 26.8, "offerprice": 27.4, "fundid": "123456789", "funddescription": "high risk equity fund", "lastupdated": "2015-08-25t15:48:57" }} my beans.xml <?xml version="1.0" encoding="utf-8"?> <mvc:annotation-driven/> <context:component-scan base-package="com.blog" /> <bean class="org.springframework.web.servlet.mvc.annotation.defaultannotationhandlermapping" />...

Convert wstring to const *char in c++ -

i have got wstring , want convert const char in order write write function of fstream library. tried following: std::ofstream out("test.txt", std::ios::out | std::ios::app | std::ios::binary); char mbstr[11]; std::wcstombs(mbstr, strvalue.c_str(), 11); //strvalue wstring out.write(mbstr, 11); ... // have got 4 wstring. i not sure did, result text file weird: 0.100693 ÌÌ0.000000 ÌÌ0.004094 ÌÌ0.360069 ÌÌ0.086034 any idea how can write wstring in file? you're converting correctly, you're not writing correctly. out << mbstr; . you're writing 11 bytes in array no matter what's in there, , strange characters see random junk after area written wcstombs . of course, better way might use wofstream in first place. can insert wide string directly.

linux - Find and execute the existing batch command -

i trying restart gui following bash script (under mint + cinnamon): if ! type gnome-shell > /dev/null; gnome-shell --replace elif ! type cinnamon > /dev/null; cinnamon --replace fi i got error message, gnome-shell not exist. there way write script multi-platform? what want is type gnome-shell &> /dev/null the &> redirects both stdout , stderr (bash only). redirected stdout, therefore still error messages. you're interested in return value of type, not output. also, negation doing there? call gnome-shell if not exist? in case checked return value $?, remember 0 true, 1 false in shells: type gnome-shell echo $? # prints '0', indicating success / true, or '1' if gnome-shell not exist the return value, or rather exit code / exit status, ($?) evaluated if statement. a little bit nicer: function cmdexists() { type "$1" &> /dev/null } function echoerr() { echo "$1" 1>&2 } ...

php error occured by not confirm what error is behind -

i wrote php script , working fine getting error in not sure causing error in script because defined custom message in function this: $error_display = "<div class='errormsgbox'>an error occured. please try again</div>"; is there way error getting little detail u can fix possible here script <?php // check empty errors $sucess = null; $error_display = null; $slug_title = null; if (isset($_post['formsubmitted'])) { $error = array(); //check video title if (empty($_post['video_title'])) { $error[] = 'you must enter video title'; } else { $vid_title = $_post['video_title']; //create slug using name function create_slug($string){ $string = preg_replace( '/[^a-za-z0-9\. ]/', '', $string ); $string = strtolower($string); $slug=preg_replace('/[^a-za-z0-9-]+/', '-', $string); return $slug; ...