Posts

Showing posts from September, 2015

R - Plot: How to format in 10-base scientific notation and put it text, mtex, title etc functions? -

i have numeric variable, k=3.5e-5 (its values calculated throughout script). want write value somewhere (title, text in plot, etc) in plot as: k_{root} = 3.5 10^{-5} cm /d i have tried functions bquote , substitute , no 1 worked. let's put question in examples. have tried following: 1) png("exp_1.png") kroot = 3.5e-5 plot(1:10,1:10, text(4,9,bquote(italic(k[root])~"="~.(kroot)~"cm/d"))) dev.off() try favorite function, paste(). plot(1:10,1:10, text(4,9,gsub("e",paste("k[root]=",format(k,scientific=true),"cm/d",sep=" "),replacement=" 10^"))) you can replace "e" here using function gsub. i've edited answer include this. the output: > k=.0000035 > k [1] 3.5e-06 > gsub("e",paste("k[root]=",format(k,scientific=true),"} cm/d",sep=" "),replacement=" 10^{ ") [1] "k[root]= 3.5 10^{ -06 } cm/d"

geolocation - Windows Phone 8 - Keeping background location tracking active beyond four hours -

i'm in process of developing wp8 app makes use of background location tracking abilities provided os. idea monitor users position , notify them when near types of places. so far seems work fine , when running location tracking works expect. the problem is, seems phone times out background apps after around 4 hours, stopping location tracking. i can understand why microsoft did it, preserve battery life etc. there's not point having background location tracking app has manually restarted every 4 hours! if user chooses run app , made aware of potential battery hit, surely should able run indefinitely - point of course, if system runs out of resources or similar that's fair enough. does have experience this? there must hundreds of others apps in store have run issue have thought? , presumably there must way of keeping location tracking running? i've tried periodically updating live tile (using dispatchertimer) while tracking running doesn't seem enough ke

validation - How to pass paramaters like unix into windows batch file -

i need pass various parameters .cmd file unix format file.cmd -configuration=value -source=value -flag but, try this: startlocal @echo off cls setlocal set cmdline=%* set configuration= set source= set badargs= set validation= goto main :splitargs echo splitargs(%*) if "%*" neq "" ( /f "tokens=1,2,* delims== " %%i in ("%*") call :assignkeyvalue %%i %%j & call :splitargs %%k ) goto :eof :assignkeyvalue echo assignkeyvalue(%1, %2) if /i %1==-configuration ( set configuration=%2 ) else if /i %1==-source ( set source=%2 ) else ( rem append unrecognised [key,value] badargs echo unknown key %1 set badargs=%badargs%[%1, %2] ) goto :eof :validate echo validating set validation=fail if defined configuration ( echo -configuration ok if defined source ( echo -source ok if not defined badargs ( set validation=success ) ) ) goto :eof :main cl

c# - How to make tooltips show up when mouse hovers over data point -

i've been searching sort of tutorial focusing on how tooltips work, have not had luck. i have test project render line chart 5 data points. when instantiate chart object set ismapenabled = true . when define series try set tool tip. private void defineseries() { var series = new series(); series.tooltip = "#valy"; series.postbackvalue = "#index"; var x = new[] {0, 1, 2, 3, 4, 5}; var y = new[] {0, 4, 5, 3, 7, 2}; ( int = 0; < x.length; i++ ) { series.points.add( new datapoint( x[ ], y[ ] ) ); } series.charttype = seriescharttype.line; defineseriesstyle( series ); chart_.series.add( series ); } the chart renders expected, tooltip not display when mouse hovers on data point. missing step somewhere, have no idea is. edit: code shows action method , constructor chart view model , subsequent function call. public actionresult causedoutpoint() { var causedout = new causedoutvi

Line ending issue with Mercurial or Visual Studio -

i seem have strange issue caused either visual studio or mercurial. localised single project, i'm guessing in project configuration causing issue. at difficult specify point, when perform action in visual studio, update every line ending in given file, means when @ file in sourcetree, every line has changed. i can replicate using nuget add package dependency; packages.config entirely replaced. if commit changes, including line endings, later same issue occur. workaround have shelve changes , reapply them, whereupon lines written correctly. i'm not sure application blame here. did make mistake of allowing sourcetree change mercurial configuration, issue have fixed, i'm not sure if has persisted. i thought might issue mercurial.ini files or hgrcs don't seem contain untoward. here's mercurial.ini [ui] username = .... [auth] bb.prefix = https://bitbucket.org/ bb.username = .... bb.password = .... [extensions] mq = rebase = [web] allow_push = * push_s

Uncaught TypeError: Cannot read property 'parentNode' of null javascript -

this code should make element disappear list when dropped on element (called cookiemonster) addevent(cookiemonster, 'drop', function (e) { if (e.stoppropagation) e.stoppropagation(); var el = document.getelementbyid(e.datatransfer.getdata('text')); el.parentnode.removechild(el); return false; }); create auxiliar variable this addevent(cookiemonster, 'drop', function (e) { if (e.stoppropagation) e.stoppropagation(); var el = document.getelementbyid(e.datatransfer.getdata('text')); var aux = el.parentnode; aux.removechild(el); return false; });

ruby on rails - Is it the correct way to implement belongs_to relation with factory girl? -

i have realy easy model. user have role_id depends of role table (id, name) role reference. i want create users of types on rspec test, factory girl. my first idea factory :role name "guest" factory :role_admin name "admin" end factory :role_supervisor name "supervisor" end etc... have lot different roles end factory :user email password '123456' password_confirmation '123456' association :role, factory: :role factory :admin association :role, factory: :role_admin end factory :supervisor association :role, factory: :role_supervisor end etc... have lot different roles end in model have simple method : def is(role_name) return self.role.name == role_name end it's correct way to? realy need create factory role? can make stub function in factory girl each role? i realy new test stuff, thanks. factories should reflect models. class user has_many :products en

python - Django dynamic embedded/nested models -

i have application knows type of entity @ creation time. because of don't know how link associated models see like have type embedded json field attribute entity have relation between 'fixed' tables (see bellow) the e_type field simple charfield, based on value has, query type_a or type_b. this how looks django class entity(models.model): name = models.charfield(max_lenght=64) e_type = models.charfield(max_lenght=1) class type_a(models.model): entity = models.onetoonefield(entity) attribute = models.charfield(max_lenght=64) class type_b(models.model): entity = models.onetoonefield(entity) attribute = models.charfield(max_lenght=64) what suggest ? thanks edit: in response of why multiple tables - each e_type referees different table structure. example type_a has 4 fields, type_b has ten fields , on. having json field simple since can store data no need have multiple tables each it's own structure. different option can see use eav

performance - Optimization of algebraic computation -

using mathematica, can compute mathematical representation of function want code in c++. say like: f=log[2*x+3*y]+sin[4*x+6*y] it makes sense in case computation: temp=2*x+3*y f=log[temp]+sin[2*temp] is there way expression reduce execution time / number of operations / size of expression or metric given more complex mathematical expression? although doesn't work simple example, can try following in mathematica experimental`optimizeexpression[{log[(2*x^3 + 3*y)^2] + sin[2 (2*x^3 + 6*y)^2]}] as result get experimental`optimizedexpression[ block[{compile`$3, compile`$4}, compile`$3 = x^3; compile`$4 = 2 compile`$3; {log[(compile`$4 + 3 y)^2] + sin[2 (compile`$4 + 6 y)^2]}]]

javascript - Class and Object confusion within Ember.js -

this basic question i'm little bit confounded. understanding convention dictates class definitions capitalised object instances not. when following: app = require("app"); module.exports = app.authmanager = ember.object.extend({ apikey: null, // load current user if cookies exist , valid init: function() { this._super(); var accesstoken = $.cookie('access_token'); var authuserid = $.cookie('auth_user'); if (!ember.isempty(accesstoken) && !ember.isempty(authuserid)) { this.authenticate(accesstoken, authuserid); } }, // ... } i assume defining authmanager's class definition. if this: module.exports = app.applicationroute = ember.route.extend({ init: function() { this._super(); app.authmanager = app.authmanager.create(); } }); my understanding app.authmanager = app.authmanager.create(); instantiates instance , applicationrouter pretty first thing executed in ember app.

linux - default: command not found -

im new linux when when im facing problem first choice search on google, in these couple days still got no results. when im run script on new instalation return "default: command not found". if im running script on machine run fine , playing videos scrolling text. here's code: #!/bin/bash source /etc/atv.conf export display=:0 sleep 5 default $default & while true; sleep 1 now=$(date +"%t") while read line set -- "$line" ifs="#"; declare -a array=($*) if [ ${array[0]} == $now ]; duration=${array[1]} filename=${array[2]} filetype=${array[3]} default $filetype $filename $duration & fi done < $playlist done this script run video file exist playlist using mplayer on ubuntu dekstop 12.04 lts what default @ "default $default &" line refer to? $default on file.conf $default=screen for atv.conf #atv configuration #host host=/home/atv #media me

Using a variable name as the key name in a hash (Perl) -

this question has answer here: how can use variable variable name in perl? 2 answers i have block of perl code want simplify. it's part of subroutine, series of arguments added values hash of hashes. $user{$account_num}{'item0'} += $item0; $user{$account_num}{'item1'} += $item1; $user{$account_num}{'item2'} += $item2; $user{$account_num}{'item3'} += $item3; $user{$account_num}{'item4'} += $item4; $user{$account_num}{'item5'} += $item5; $user{$account_num}{'item6'} += $item6; you can see variable names same key names. seem remember watching friend kind of thing in 1 line once. like: [looping through input arguments]: $user{$account_num}{'variable_name'} += $variable_name; does know of way this? you're on thinking it. i can tell because of time: me : if make device can vi

sql server - Converting a string to a date time in SQL -

i'm importing data different system , datetime stored string in format: 20061105084755es yyyymmddhhmmss(es/ed) es est , ed edt. i have query table last 30 days. i'm using conversion query: select convert( datetime, left(cdts, 4)+'-'+substring(cdts, 5,2)+'-'substring(cdts, 7,2)+' '+substring(cdts, 9,2) +':'+substring(cdts, 11,2)+':'+substring(cdts, 13,2) dt tb1 dt < getdate()-30 i'm looking more efficient query reduce time taken. table has around 90 million records , query runs forever. no calculation @ runtime going speed query if performing calculation , need filter against result of calculation - sql server forced perform table scan. main problem you've chosen store dates string. variety of reasons, terrible decision. string column indexed @ least? if so, may data last 30 days: declare @thirtydays char(8); set @thirtydays = convert(char(8),dateadd(day,datediff(day,0,getdate()),0)-30,112);

objective c - Xcode build failure "Undefined symbols for architecture x86_64" -

Image
an xcode beginner's question: it first experience xcode 4.6.3. i trying write simple console program, searches paired bt devices , prints them nslog. it builds following error: undefined symbols architecture x86_64: "_objc_class_$_iobluetoothdevice", referenced from: objc-class-ref in main.o ld: symbol(s) not found architecture x86_64 clang: error: linker command failed exit code 1 (use -v see invocation) i searched crazy. common problem should reference file, of header files imported , no implementation (*.m-file) found linker. iobluetooth library however, standard framework foundation framework. what missing in above statement? i have tried building 32-bit machine (build fails again). linker error, have no idea, relates, except there issue finding implementation iobluetoothdevice, on both x86 , x64 architecture, while header files standard included framework, called iobluetooth? for information main code "main.m" being: #import &l

ASP.NET MVC Navigational Property -

i'm looking add navigational property 'registration' class, can access parent 'person'. ideally, able add public overrideable property parentperson person , can't seem work complains principle end of association. public class person <required()> public property id integer <required()> <stringlength(150)> public property firstname string <required()> <stringlength(150)> public property lastname string public overridable property registration registration end class public class registration <required()> public property id integer public property registrationdate date public overridable property sessions list(of registrationsession) end class

Excel VBA: Select Case if ActiveCell like "*string*" -

i'm working on macro takes current value of activecell , changes value based on select case. however, unable determine if activecell contains wild card string. not sure if syntax correct. how can select case compare? select case activecell.value case activecell.value "*string*" activecell.value = "contains string" end select it possible use wildcards. keep these 2 things in mind: first, string comparison expressions evaluate boolean data type (true/false); second, per developer reference select...case statement, case expression(s) must "implicitly convertible" same data type of select case test expression . demonstrate, let's use code original post above. select case activecell.value '-->activecell.value test expression case activecell.value "*string*" '-->(activecell.value "*string*") case expression. activecell.value = "contains string"

vba - Creating an array variable with a variable number of elements -

i want define array variable have variable number of elements depending on m number of results returned search. error "constant expression required" on: dim cmodels(0 m) string here complete code dim foundrange range dim rangetosearch range set rangetosearch = selection set foundrange = rangetosearch.find(what:="lights", after:=activecell, lookin:=xlvalues, lookat:= _ xlpart, searchorder:=xlbyrows, searchdirection:=xlnext, matchcase:=false _ , searchformat:=false) 'first occurrence m = worksheetfunction.countif(selection, "lights") dim secondaddress string if (not foundrange nothing) dim count integer: count = 0 dim targetoccurrence integer: targetoccurrence = 2 dim found boolean z = 1 dim cmodels(0 m) string until z = m z = z + 1 foundrange.activate set foundrange = rangetosearch.findnext(foundrange) if not foundrange.next nothing z(m)

javascript - Is is safe to use function reference as an object property/key -

this question has answer here: are functions valid keys javascript object properties? 2 answers are there reasons why should not use function reference property/key of object ? code works in chrome, firefox, & ie8, "just because works..." var x = {} var = function() { return 'a' }; var b = function() { return 'b' }; x[a] = 1 x[b] = 2 x[a] === x[a] // returns true x[a] === x[b] // returns false x[b] === x[b] // returns true x[a] // returns 1 x[b] // returns 2 object keys string. used in x[a] in fact x[a.tostring()] . this means function key same key string : x[a] === x["function () { return 'a' }"] so yes, might consider both unsafe , unreasonable. it's hard imagine context in useful or efficient.

json - Unsupported url in JSONP request -

my web app loads localhost/alpha/ , following error message browser (chrome or safari) when performs jsonp request : get localhost:5000/iseeyou/webservice/login.php?email=b&pwd=b&callback=ext.data.jsonp.callback1&_dc=1377281924940 unsupported url i using sencha touch , code : ext.data.jsonp.request({ url: iseeyou.url+'/iseeyou/webservice/login.php', params:{ email: email, pwd: pwd }, success: function(response){} }); when copy/paste url displayed in error directly in browser works well. it needed "http://" @ beginning.

c++ - On platforms where pthread_t is numeric, is 0 guaranteed to be an invalid value? -

this question has answer here: is there invalid pthread_t id? 5 answers pthread_t (as returned pthread_self() ) opaque type, on platforms numeric, example typedef ed unsigned long . on these platforms, 0 invalid pthread_t value? -1 ? if wanted value either pthread_t or invalid, i'd use boost::optional<pthread_t> or std::optional<pthread_t> c++1y. this has little overhead (bytes), expresses want (this value may or may not pthread_t ), , doesn't rely on platform-specific behavior.

jquery - Alert() does not fire from the second page of datatable -

i have datatable returned backend using jquery , datatables plugin. need select order number in datatable , alert it. alert , console works in first page of data table not fire anymore second page. googled .live() deprecated , suggested answer .on() seems not work. jquery: $(document).ready(function () { $.ajax({ type: "post", //url: "orderdetail.asmx/helloworld", url: "order.aspx/getorder", data: "{'id':'273440'}", contenttype: "application/json; charset=utf-8", datatype: "json", success: function (msg) { $('#order').append(msg.d); //alert(msg.d); console.log(msg); $('#ordertable').datatable({ // "sscrolly": "100px", "bautowidth": false, "bdeferrender": true //"bpaginate": false }); // click order number detail

java - Make code read-only in NetBeans -

Image
i trying figure out trying in reverse: i know how netbeans makes matisse-generated code read-only. in picture below, code in grey generated gui-builder , not editable. portion of code same way. purpose of prevent careless editing of module making code harder change. any netbeans experts out there know how (if can done) ?

benchmarking - Which method for handling conditions inside a function would be the most practical? -

what's fastest, safest, , practical way of handling conditions inside function condition match must passed before function can proceed code @ all? below have function returns on condition failure, , function checks condition success: function x() { if ( !condition ) return; [code] } or function y() { if ( condition ) { [code] } } mccabe's cyclomatic complexity punishes functions more 1 return statement. guess provide formalism supports structured programming (one entry point each function/ "goto statement considered harmful" ) taken extreme, i.e. 1 exit point each function. reducing number of return statements in function reduces number of break-points insert in debugging situation final values of function local variables inspected. if development method involves frequent use of debugger argue using y() approach.

jquery dialog fire open event twice -

i have problem jquery-ui. i bind click event open dialog, dialog's open function fires twice. the click event fires once, open function opens 2 dialog this code: <div id="modalwindow">cargando...</div> <script> $(document).ready(function () { var ventana = $("div#modalwindow"); ventana.dialog({ autoopen: false, show: "slow", hide: "slow", width: 500, resizable: false, draggable: false, modal: true, closeonescape: true, ok: function () { $(this).dialog("close").html("cargando..."); }, close: function () { $(this).html("cargando..."); } }); $("div.imagen_perfil img").click(function (evt) { //...some code ventana.dialog({

Android - displaying text in center of progress bar -

i have made horizontal progress bar , works perfectly. display textview or similar right in middle of showing countdown bar loading. keep in mind not progress dialog, progress bar resides inside activity , shows countdown timer. can me out, whats best way , how can accomplish this? if progressbar , textview inside relativelayout can give progressbar id, , align textview progressbar using that. should show on top of progressbar . make sure background transparent can still see progressbar for example: <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <progressbar android:layout_width="match_parent" android:layout_height="match_parent" // other attributes android:id="@+id/progress_bar" >

in node.js express, how to tell the HTTP request is application/json or html on the content negoition in jquery -

i want node.js server send different content based on request's content type, server code if(req.accepts('text/html')){ console.log("accepts('text/html')"); locals.page = 'posts'; res.render('question.ejs', locals.questions); } else if(req.accepts('application/json')){ console.log("'application/json'"); res.json(200,locals.questions); } there similar post android client in node.js express, how tell http request application/json or html on content negoition this jquery code $.ajax({ type: "get", url: "/course/abc/questions", contenttype:"application/json; charset=utf-8", datatype:"json", success: function(data){ console.log(data.length,data); } }); for reason, set content type on appication/json, node.js server side sti

jquery ui - jqgrid and datepicker control giving error for new records -

i binded jqgrid json returned ajax. json has date in following format 11/1/2013 12:00:00 in colmodel have specified following { name: 'datecol', index: 'signdate', width: '200', jsonmap: 'cell.signdate', editable: true, sorttype: 'date', editable: true, formatter: 'date', formatoptions: { srcformat: 'm-d-y h:i:s', newformat: 'y-m-d' }, editoptions: { datainit: initdateedit }, initdateedit = function(elem) { settimeout(function() { $(elem).datepicker({ formatter: 'date', formatoptions: { srcformat: 'm-d-y h:i:s', newformat: 'yy-m-d' } autosize: true, showon: 'button', // dosn't work in searching dialog

ruby on rails - Accessing an instance method in an active record query -

given following 2 models: class wheel belongs_to :car def self.flat where(flat: true) end and class car has_many :wheels def flats self.wheels.flat end def has_flats? flats.count > 0 end i need query cars flat tires. i'm wondering why isn't working in cars model?: def self.with_flats where(:has_flats?) end or def self.with_flats where(:has_flats? == true) end this isn't returning correct records. ideas? define scope in car model: class car has_many :wheels scope :having_flat_wheels, joins(:wheels).where("wheels.flat=?", true).uniq ...... end then cars flat tires: car.having_flat_wheels

Best Practice for Cookies -

there 2 approaches i've been thinking storing data in cookies. 1 way use 1 cookie data , store json string. the other approach use different cookies each piece of data. the negatives see first approach it'll take more space in headers because of json characters in cookie. i'll have parse , stringify json take little processing time. positive 1 cookie being used. there other positives missing? the negatives see second approach there more cookie key value pairs used. there 15-20 cookies storing. expires date same each cookie. from understand max number of cookies per domain around 4000. not close number yet. are there issue overlooking? approach best? edit - these cookies managed javascript. if hand out data storage users (which cookies do), should encrypt data, or @ very least sign it. this needed protect data tampering. at point, size considerations way off (due padding), , performance overhead of parsing json (encryption cause greater overhea

android - OutOfMemory when loading large Background Image -

i using android:background give background image android layout. after putting images exception : 08-24 00:40:19.237: e/dalvikvm-heap(8533): out of memory on 36000016-byte allocation. how can use large images backgrounds on android? can expand application heap memory? or not ? please have @ related question: high resolution image - outofmemoryerror try minimize memory usage of application keeping background image small possible. this can done via: cropping image fits screen compress image further (use e.g. photoshop) before using in app use below method load bitmap recycle bitmap no loger need it make sure not keep multiple instances of in memory set reference null after using bitmap make sure images set background loaded (e.g. cropped in size, example fit screen size) , released memory no longer needed. make sure have 1 instance of bitmap in memory. after displaying it, call recycle() , set reference null. this how load images: public stati

Python/Django: How to convert utf-16 str bytes to unicode? -

fellows, i unable parse unicode text file submitted using django forms. here quick steps performed: uploaded text file ( encoding: utf-16 ) ( file contents: hello world 13 ) on server side, received file using filename = request.files['file_field'] going line line: for line in filename: yield line type(filename) gives me <class 'django.core.files.uploadedfile.inmemoryuploadedfile'> type(line) <type 'str'> print line : '\xff\xfeh\x00e\x00l\x00l\x00o\x00 \x00w\x00o\x00r\x00l\x00d\x00 \x001\x003\x00' codecs.bom_utf16_le == line[:2] returns true now , want re-construct unicode or ascii string "hello world 13" can parse integer line. one of ugliest way of doing retrieve using line[-5:] (= '\x001\x003\x00' ) , construct using line[-5:][1] , line[-5:][3] . i sure there must better way of doing this. please help. thanks in advance! use codecs.iterdecode() decode object on fly: from codecs imp

sip - Direct call to extension -

i new asterisk , seem bit stuck in looking for. goal setup telephone server receives calls , directs them different extensions. extensions different messages played, possibly option press key reception or key leave message. these extension should easy manageable though database (adding or deleting them, , choosing message should played). the main problem can't seem find answer if can dail directly extension. e.g. if buy phonenumber +46812349999 , extension 12345, user able call +468123999912345 , directly hear message assigned extension. possible? if so, how , need? currently have both asterixnow , asterix setup completed in 2 different vms testing. if buy number +46812349999 can call nunber, in asterisk can redirect number extensions ! you need direct inward dialing service allows range of numbers provided operator used address internal extensions, making possible extension receive external call directly.

Jquery very sensitive "onchange" method -

is there way optimize "onchange" method text input field? let's if use microphone enter value input field, never use mouse change content inside text field, doesn't give me response, unless put pointer in textfield , out again. html: <input type="text" class=".target" /> jquery: $( ".target" ).change(function() { alert( "handler .change() called." ); }); the input event you're looking -- it's change , except fires every time text changed, without waiting until loses focus. $( ".target" ).on("input", function() { alert( "handler .change() called." ); }); fiddle

python - Allow greek characters in Django usernames -

i allow users register using greek characters. i added in admin.py file following code. regular expression correct ( regex=r'^[\w\p{greek}-]+$', ) ? allow greek , english characters from django.contrib.auth.models import user django.contrib.auth.admin import useradmin django.contrib.auth.forms import usercreationform, userchangeform class myusercreationform(usercreationform): username = forms.regexfield( label='username', max_length=30, regex=r'^[\w\p{greek}-]+$', help_text = 'required. 30 characters or fewer. alphanumeric characters (letters, digits, hyphens , underscores).', error_message = 'this value must contain letters, numbers, hyphens , underscores.') class myuserchangeform(userchangeform): username = forms.regexfield( label='username', max_length=30, regex=r'^[\w\p{greek}-]+$', help_text = 'required. 30 characters or fewer. alphanumeric characters (letters, digits, hyp

jquery - Transitions on IE10 do not work on two absolutely positioned elements (With example) -

basically have 2 divs absolutely positioned in same spot, , slide through them opacity controls. using modernizr check css transition support , rely on jquery fades ie8 , ie9, ie10 have transitions doesnt fall that, , plain doesnt work there. the following example tested on chrome , ie10 http://jsfiddle.net/ycheg/ i avoid heavy html/css changes on structure, , javascript fallback decent enough if didnt have sniff it. html <div class="opaque"></div> <div class="opaque green active"></div> <button> toggle</button> enter code here css .opaque { position: absolute; left: 200px; width:100px; height:100px; background-color:red; transition: opacity 1s ease-in-out; opacity:0; } .opaque.green { background-color: green; } .opaque.active { opacity: 1; } js $("button").on("click", function(){ $(".opaque").toggleclass("active"); }) try code :

Modify item order in select field with javascript -

i have this: <select name="repeat_period"> <option value="24">daily</option> <option value="168">weekly</option> </select> and goal remove/hide daily item force chose weekly. solution invert item order , set "readonly". in both case don't know how do. precision: don't have access html of page. can use javascript try make modification , don't know javascript. any clue ? fortunately found solution in forum people more disposed newbie me. if guru coder, not need ask help. <script type="text/javascript"> function removeit(){ var sel=document.getelementsbyname('repeat_period')[0]; sel.options.remove(0); } removeit(); </script> http://jsfiddle.net/ygpw4/

How do I return a Null Pointer in a function C++ -

i working on bit of code search within vector of type person (which have defined in code , show if needed). if finds person, returns name. working, if not find person, supposed return null pointer. problem is, cannot figure out how make return null pointer! keeps either crashing program every time. code: person* lookforname(vector<person*> names, string input) { string searchname = input; string foundname; (int = 0; < names.size(); i++) { person* p = names[i]; if (p->getname() == input) { p->getname(); return p; //this works fine. no problems here break; } else { //not working person* p = null; <---here error happening return p; } } } you use std::find_if algorithm: person * lookforname(vector<person*> &names, const std::string& input) { auto = std::find_if(names.begin(), names.end(), [&input](person* p){

mysql - select statement return a section of result -

ex: @productname varchar(50), @pagestart int, @pageend int, @result varchar(max) set @result = select * products productname '%@productname%' return select @result section between @pagestrat @pageend this how imagine ,if correct? or there 1 statement can result declare @productname varchar(50), @pagestart int, @pageend int, @result varchar(max) select * (select *,row_number() on (order id) row products productname @productname) a.row between @pagestart , @pageend

java - Checking if parent node has specific child -

i need find parents in xml file contain specific tag, , need parse strings parents , children java object, or array (could use advice on best way store xml info strings). <task> <task id=483492> <project id=484383> <date>2003/23/03</date> <name> project name example </name> </task> <task> <task id=483492> <name> task name example </name> </task> <task> <task id=483492> <project id=484383> <date>2003/23/03</date> <name> project name example </name> </task> <task> <task id=483492> <project id=484383> <date>2003/23/03</date> <name> project name example </name> </task> <task> <task id=483492> <name> task name example </name> </task> so, if <task> parent has <project> child, need put data each

database - ODBC with jBASE -

i want use jbase database on new web-application. seems have use jbase basic (jbc) interact database. know jedi does, don't know how use it. 1 know, how can perform crud on jbase php page using odbc or jedi? i'm newbie on jbase, appreciated. thanks. it doesn't out there in terms of samples, you'd have figure out 1 on own after downloading drivers. if have luxury of picking technologies, recommend not using particular combo. if figure out how things working -- you're going run snags , there isn't going out there in ways of helping you. i'd recommend picking server language has documentation/examples db, or pick db , migrate over.

asynchronous - Stream audio from shockwave player into c# voice recognition api -

so have no code present here because don't know if possible. i have shockwave player link grabbed local website. transmits live audio. i want take live audio , pipe c# voice recognition api , process being said runs. is possible?

Java sandbox for running multiple JVM platform languages -

i evaluating feasible of project build small web application provides repl programming environment similar of tryruby , codeacademy , have been looking @ possible solutions evaluate user submitted code safely, regarding server side solution have read jvm provides best sandboxing environment has built in security measures . i read javatm scripting api , can used evaluate code on various script engines/ interpreters such rhino(javascript), jruby, jython , quercus(php). possible have single server running jvm evaluate user code in serval different languages? @ efficient? if not other options have? would possible have single server running jvm evaluate user code in serval different languages? yes feasible. would @ efficient? i'm not sure why efficiency particular concern. strikes me running small examples remote users not require efficiency. either way, take should efficient enough . however, real concern here kind of service invites various kinds

c# - How to access to file that have been added as content in a separated assembly? -

i have project put reports files it,now want refrence them in ptoject,i tried code: stireport.load(new uri("pack://application:,,,/goldaccountingsystem.reports;component/stimulreports/tbank.mrt") .localpath); but error: could not find part of path 'e:\goldaccountingsystem.reports;component\stimulreports\tbank.mrt'. goldaccountingsystem.reports assembly name of reports,but don't know why it's lookin in e assembly although right address e:\projects\goldaccountingsystem\goldaccountingsystem.reports . and think it's because reports added project content not resource.any idea? you should try relative uri : stireport.load(new uri("/goldaccountingsystem.reports;component/stimulreports/tbank.mrt") .localpath); and absolute uri should work: stireport.load(new uri("pack://application:,,,/goldaccountingsystem.reports;component/stimulreports/tbank.mrt", urikind.absolute)

php - How could I able to open whole website into particuler div? -

i working on website there requirement open website particular div. had try below mentioned code not able output proper appearance. <div style="overflow-x: hidden; overflow-y: scroll; height:300px; width:100%" > <?php echo $url ?> </div> i have use div. no i-frame nothing else. belowmention code use. , class name of function scraper function getpagepost($url, $data = array(), $proxy='', $userpass='', $header = array()) { $ch = curl_init(); if(!empty($header)){ curl_setopt($ch, curlopt_httpheader, $header ); curl_setopt($ch,curlopt_encoding , "gzip"); } curl_setopt($ch, curlopt_url, $url); if($this->usecookie) curl_setopt ($ch, curlopt_cookiejar, $this->ckfile); curl_setopt($ch, curlopt_returntransfer, 1); curl_setopt($ch, curlopt_followlocation, true); if(!empty($proxy)) curl_setopt($ch, cu

gradle - how to debug product flavor in android studio? -

i have 2 product flavor, free , pro. the launcher activity both different. but android studio expects launcher activity in androidmanifest.xml under src/main/. gradle building both flovors correctly ide not able pick correct androidmanifest.xml respective product flavor src/free or src/pro. this happening after choosing correct build variant freedebug or prodebug. this post has answer want. [ what product flavor android studio build default in build.gradle? you can click in bottom left hand corner , open box called "build variants" select flavor (variant) wish work with.

php - EDEN Framework together with Zend Framework: Cannot redeclare class Eden_Class -

iam trying integrate eden php link page zend framework 1.10.x application. have moved files folder other librarys located. in index.php: /** zend_application */ require_once 'zend/application.php'; require_once 'eden.php'; application.ini: autoloadernamespaces.6 = "eden_" when try create instance of eden class with: $fbauth = eden('facebook')->auth('$key','$secret','http://yourwebsite.com/auth'); i following error? cannot redeclare class eden_class in /applications/mamp/htdocs/page/library/eden/class.php on line 27 any ideas? (php version 5.3.6) solution (working me) added bootstrap.php /** * setup eden framework * http://eden.openovate.com/ * * @return void */ public function _initeden() { eden()->setloader(false); }

jsp - EL syntax error is en -

the following statement in jsp page encounters error near first equals occurence.what reason , how can solve problem.please rectify me possible ${(fn:length(updatestock.todaydimensionstones)==i.count) && (!dimensionstones.status.equals('new')||!dimensionstones.isinspected.equals('no'))} page loaded successfully.but in jboss visual studio editor says multiple annotations found @ line:- encountered "(" @ line 1, column 86. expecting 1 of: "." ... ">" ... "gt" ... "<" ... "lt" ... "==" ... "eq" ... "<=" ... "le" ... ">=" ... "ge" ... "!=" ... "ne" ... ")" ... "[" ... "+" ... "-" ... "*" ... &quo

compiler construction - Massive ERP system using Scala language -

after reading slow compiler , martin odersky's response , worried kick start massive erp product (which heavily funded targets specific industry) using scala language. edited based on below responses : splitting different modules option. how 1 should doing/planing in large projects. cant solution us. martin himself admitted (please see above link) java compiler 10 times faster scala (almost 2 years ago). scary us, cant afford waiting hours while builds (e.g when clean build) on dev's machine. martin said not expect miracles in future. our option using continuous compilation. our intended ide intellij idea. i not sure how going affect developer's machine/ide's performance? also when click save, try compile code file busy writing? some guidance appreciated. thanks mk compilation speed not 1 of scala's strengths, can potentially limit how affects structuring large project set of smaller ones tree-like dependency (e.g. core utilities; core

mysql - Get count of ids from a table grouped by a some range of values -

i have table this ------------------- id | rating ------------------- 1 | 1.2 ------------------- 2 | 1.3 ------------------- 3 | 2.3 i want result rating row ------------ 1 0 2 2 3 1 4 0 5 0 as row rating less 1 0 row rating greater 1 , less 2 2 row rating greater 2 , less 3 1 row rating greater 3 , less 4 0 row rating greater 4 , less 5 0 i totally blank how make query me please select table.*, ceil(rating) integer_rating table order rating asc ceil() rounds number larger x.0 integer (x+1) . problem 0.2 return 1 , not 0 like. can quick comparison outside of sql change zero. this return: id rating integer_rating ---------------------------- 1 1.2 2 2 1.3 2 3 2.3 3

Making a switch statement on my partials angularjs -

i'm having problem, i'm unable ng-switch work on partials. i'm trying upload image before upload must first check if included image size doesn't reach 25kb. here controller code: $scope.validateavatar = function(files) { var fd = new formdata(); $scope.filesize = files[0].size; $scope.filemaxsize = 25; //take first selected file fd.append("file", files[0]); $scope.uploadavatar = function() { api.uploadavatar($scope.main.user.email, fd) .then(function(result) { console.log(result.data); }, function(result) { console.log(result); }) }; }; and partials code: <form data-ng-submit="uploadavatar()"> <input type="file" name="file" onchange="angular.element(this).scope().validateavatar(this.files)"/> <div ng-switch on="filesize / 1024 < filemaxsize"> <div ng-switch-when="true">

multithreading - How to properly implement RabbitMQ RPC from Java servlet web container? -

i'd incoming java servlet web requests invoke rabbitmq using rpc approach described here . however, i'm not sure how reuse callback queues between requests, per rabbitmq tutorial linked above creating new callback queue per every request inefficient (rabbitmq may not cope if using queue ttl feature ). there 1-2 rpc calls per every servlet request, lot of servlet requests per second. i don't think can share callback queues between threads, i'd want @ least 1 per each web worker thread. my first idea store callback queue in threadlocal, can lead memory leaks. my second idea store them in session, not sure serialize , sessions not replicated/shared between web servers, imho not solution. my infrastructure tomcat / guice / stripes framework. any ideas robust/simple solution is? am missing in whole approach, , over-complicating things? note 1- question relates overall business case described here - see option 1. note 2 - there seemingly related quest

sql - select query with Not IN keyword -

Image
i have two tables below.. tbpatientencounter tbvoucher when execute select query below select encounteridp,encounternumber tbpatientencounter it returens me 180 rows. and select voucheridp,encounteridf tbvoucher above query returns me 165 rows. but want execute select query returns me data encounteridp not in tbvoucher, have tried below select query... select * tbpatientencounter pe pe.encounteridp not in (select v.encounteridf tbvoucher v ) it doesn't returns row. in first image shows encounteridp 9 in tbpatientencounter , not inserted in tbvoucher have tried select query select * tbvoucher encounteridf = 9 it returns me 0 rows. my question what wrong above not in query.? in likelihood, problem null values in tbvoucher . try this: select * tbpatientencounter pe pe.encounteridp not in (select v.encounteridf tbvoucher v v.encounteridf not null

fatal error when I run this php code -

i want connect php tpl. but gives me fatal error when try run. i added smarty php show data on tpl file still has problem. <?php include('developer.php'); if( $xml = simplexml_load_file(url)) { foreach($xml->campaign $campaigns) { $camp_name = $campaignsl->name; $camp_dec= $campaigns->description; $camp_payout= $campaigns->payout; $camp_url= $campaigns->url; $smarty->assign( 'camp_name', $camp_name); $smarty->assign( 'camp_dec', $camp_dec); $smarty->assign( 'camp_payout', $camp_payout); $smarty->assign( 'camp_url', $camp_url); $smarty->display('link.tpl'); } } ?> and tpl file (link.tpl). <table width="100%" class="widget-tbl"> <tr class="titles"> <td align="center">name</td> <td align="center">description</td> <td align="center">amount</td> <td align="center">link

Codeigniter Ajax dropdown -

controller(user.php) <?php class user extends ci_controller { public function __construct() { parent::__construct(); $this->load->model('country_model'); } public function index() { $this->load->view('register'); } public function register() { $data['countries'] = $this->country_model->get_countries(); $this->load->view('post_view', $data); } public function get_cities($country) { $this->load->model('city_model'); header('content-type: application/x-json; charset=utf-8'); echo(json_encode($this->city_model->get_cities($country))); } } city_model <?php class city_model extends ci_model { public function __construct() { $this->load->database(); } function get_cities($country = null) { $this->db->select('id, city_name'); if ($count

python - How to map identical items in two dictionaries and produce a list of values of their corresponding keys -

my goal map small dictionary large 1 , return list of values in large dictionary bears corresponding keys small dictionary. x={'red':0.25, 'yellow':0.05, 'pink':0.35, 'brown':0.22, 'blue':0.13} y={'red':2, 'blue':3, 'yellow':1} my code keeps giving me list of full values of large dictionary. for b in x.keys(): if b in y.keys(): k=y.values() print k output: [0.35, 0.22, 0.13, 0.05, 0.25] desired output: [0.25,0.13,0.05] any suggestions? thanks. something this? assume order not matter since these dictionaries. also, assuming since seem iterating on x.keys() , then, there may values in y not present in x , don't want them mapped. >>> x={'red':0.25, 'yellow':0.05, 'pink':0.35, 'brown':0.22, 'blue':0.13} >>> y={'red':2, 'blue':3, 'yellow':1} >>> [val elem, val in x.items() if elem in y] [0.13, 0.

python - What's the error in this pygame program? -

i'm making pong game in pygame isn't complete yet. names of variables, classes , other things in code in portuguese think that's easy know wich 1 does. code should make 2 paddles move when user wants displays background , paddles. don't error message. here's code: import pygame,sys,os,time pygame.locals import * pygame.init() janela=pygame.display.set_mode((800, 533),0,32) pygame.display.set_caption("pong!") superficie=pygame.display.get_surface() clock=pygame.time.clock() fundoficheiro=os.path.join("imagens","fundo2.png") fundoimagem=pygame.image.load(fundoficheiro).convert() barraficheiro=os.path.join("imagens","barra.png") barraimagem=pygame.image.load(barraficheiro).convert_alpha() def imprimirbarra(x,y): janela.blit(barraimagem,(x,y)) class barra(): y=1 x=1 velocidade=1 def subir(self): self.y-=self.velocidade def descer(self): self.y+=self.velocidade

How to substitute an empty string (or null) with a default string concisely in Scala -

i have method returns string. want substitute default value such "<empty>" if returns empty string or null . let's assume name getsomestring , expensive operation can call once, , can't change return type option[string] . now, i'm doing following: val mystr = { val s = getsomestring if (s == null || s.isempty) "<empty>" else s } is there simpler way achieve same thing? given expensive function: scala> def s(i: int): string = match { case 0=>null case 1=>"" case 2=>"hi" } s: (i: int)string i think easy read , free of overhead, cf this in wild : scala> def q(i: int) = s(i) match { case ""|null => "<empty>" case x => x } q: (i: int)string scala> q(0) res3: string = <empty> scala> q(1) res4: string = <empty> scala> q(2) res5: string = hi to eyes, not expressive, minimalist punctuation: scala> option(s(0)) filternot (_.i