Tuesday 15 September 2015

How to show please wait while ajax request process in complete -



How to show please wait while ajax request process in complete -

this code working fine, want create ajax please wait while still requesting information: here code.

function products(){ if (document.getelementbyid('date').value.length == 0) { alert("please pick date"); document.getelementbyid('date').focus(); homecoming false; } var ajaxrequest; // variable makes ajax possible! try{ // opera 8.0+, firefox, safari ajaxrequest = new xmlhttprequest(); } grab (e){ // net explorer browsers try{ ajaxrequest = new activexobject("msxml2.xmlhttp"); } grab (e) { try{ ajaxrequest = new activexobject("microsoft.xmlhttp"); } grab (e){ // went wrong alert("your browser broke!"); homecoming false; } } } // create function receive info sent server ajaxrequest.onreadystatechange = function(){ if(ajaxrequest.readystate == 4){ var ajaxdisplay = document.getelementbyid('sum'); ajaxdisplay.innerhtml = ajaxrequest.responsetext; } } var usr = document.getelementbyid('usr').value; var date = document.getelementbyid('date').value; var querystring = "?usr=" + usr + "&date=" + date; ajaxrequest.open("get", "ajax_prom.php" + querystring, true); ajaxrequest.send(null); }

in page, add together div id - divajaxrequestinprogress. add together text want show while ajax request in progress div. have animated gif well. now, show when start ajax processing , hide 1 time request complete. function products(){ if (document.getelementbyid('date').value.length == 0) { alert("please pick date"); document.getelementbyid('date').focus(); homecoming false; } $("#divajaxrequestinprogress").show(); var ajaxrequest; // variable makes ajax possible! try{ // opera 8.0+, firefox, safari ajaxrequest = new xmlhttprequest(); } grab (e){ // net explorer browsers try{ ajaxrequest = new activexobject("msxml2.xmlhttp"); } grab (e) { try{ ajaxrequest = new activexobject("microsoft.xmlhttp"); } grab (e){ // went wrong alert("your browser broke!"); homecoming false; } } } // create function receive info sent server ajaxrequest.onreadystatechange = function(){ if(ajaxrequest.readystate == 4){ var ajaxdisplay = document.getelementbyid('sum'); ajaxdisplay.innerhtml = ajaxrequest.responsetext; } $("#divajaxrequestinprogress").hide(); } var usr = document.getelementbyid('usr').value; var date = document.getelementbyid('date').value; var querystring = "?usr=" + usr + "&date=" + date; ajaxrequest.open("get", "ajax_prom.php" + querystring, true); ajaxrequest.send(null); }

i have added 2 lines code - 1 show , 1 hide div.

ajax

android - Create SOS signal using Java.Util.Timer -



android - Create SOS signal using Java.Util.Timer -

i want create android app performs sos signal using flashlight on phone , know how command flash light.

this want flash lite do:

1) flash lite on 1 sec 2) flash lite off 1 sec 3) flash lite on 1 sec 4) flash lite off 1 sec 5) flash lite on 1 sec 6) flash lite off 1 sec 7) flash lite on 3 seconds 8) flash lite off 1 sec 9) flash lite on 3 seconds 10) flash lite off 1 sec 11) flash lite on 3 seconds 12) flash lite off 1 sec 13) flash lite on 1 sec 14) flash lite off 1 sec 15) flash lite on 1 sec 16) flash lite off 1 sec 17) flash lite on 1 sec 18) flash lite off 1 sec

how can accomplish using timer class in java?

the best approach create class definitions of alphabet , equivalent in morse code. numbers can added well. way can come in text, not sos.

if sos goal, creating class might overkill still practice.

have @ docs timer class

http://docs.oracle.com/javase/7/docs/api/java/util/timer.html << updated link

this method used timer class in illustration below. sos quite possible add together forloop run sequence many seconds, , command led light.

public void schedule(timertask task, long delay, long period)

//usage of timer

import java.util.*;

public class timerdemo {

public static void main(string[] args) { // declare , create task timertask tasknew = new timertask() { // runs our task @override public void run() { system.out.println("timer running..."); } }; // declare , create timer timer mytimer = new timer(); /* schedule timer (task scheduled, delay in ms before task * execution, period in ms between successive tasks executions */ mytimer.schedule(tasknew, 500, 1000); }

}

i hope gives improve example.

java android timer led

How to configure Apache Hadoop Vaidya -



How to configure Apache Hadoop Vaidya -

as i'm looking tuning hadoop map-reduce jobs improve performance optimal resource utilization, i'm unable start can 1 tell me how configure apache hadoop vaidya. next apache blog hadoop vaidya, has described how utilize it. in blog found path

$hadoop_home/contrib/vaidya/bin/

which not nowadays in machine i'm assuming have install/configure apache hadoop vaidya.

any help appreciated!!

apache hadoop

objective c - How to create UICollectionView with alternating cell amount layout? -



objective c - How to create UICollectionView with alternating cell amount layout? -

i developing ipad app uses uicollectionview display list of products company. cells layout want utilize alternating between rows 1 image , 2 images, first row 1 image, sec row 2 images, 3rd row 1 image... , on, can't figure out how in code.

so can help me one?

hey guys manage working code:

- (nsinteger)collectionview:(uicollectionview *)view numberofitemsinsection:(nsinteger)section { homecoming 2; } - (nsinteger)numberofsectionsincollectionview: (uicollectionview *)collectionview { homecoming 30; } - (uicollectionviewcell *)collectionview:(uicollectionview *)cv cellforitematindexpath:(nsindexpath *)indexpath { cells *cell; if (indexpath.row %2) { nslog(@"%li", indexpath.row); cell = [cv dequeuereusablecellwithreuseidentifier:@"one" forindexpath:indexpath]; cell.label.text = @"one"; cell.backgroundcolor = [uicolor bluecolor]; homecoming cell; } else { nslog(@"%li", indexpath.row); cell = [cv dequeuereusablecellwithreuseidentifier:@"two" forindexpath:indexpath]; cell.labela.text = @"two"; cell.labelb.text = @"two"; cell.backgroundcolor = [uicolor redcolor]; homecoming cell; } }

objective-c ios7 uicollectionview uicollectionviewcell

Execute java class in PHP -



Execute java class in PHP -

i want phone call java programme , fetch it's output in stdout. followed suggestions in stackoverflow. doesn't work.

i have add together class file classpath. , can execute command in cmd correctly follows:

in php file phone call programme

exec("java hello", $output); print_r($output);

it yields nil but:

array()

what problem? how can prepare this?

ps: hello demo program, programme want phone call much more complicated might take 2 or more seconds in machine(i5 4g).

i recommend using java/php bridge found here: http://php-java-bridge.sourceforge.net/pjb/ it's quite easy install , works well.

also, recommend using next link download it. (it's same 1 link in downloads->documentation)

http://sourceforge.net/projects/php-java-bridge/files/binary%20package/php-java-bridge_6.2.1/php-java-bridge_6.2.1_documentation.zip/download

the file javabridge.war. you'll want utilize tomcat java ee container. 1 time tomcat set up, set file in webapps folder , it's installed.

if want regularly utilize java classes in php best method know of , have tried lot of them. resin worked, didn't play nice mail service server.

java php

Inno Download Plugin - Compiler error -



Inno Download Plugin - Compiler error -

i have been using idp plugin quite time now, after installing latest v1.4.0 next compiler error.

compiling [code] section compiler error! file: c:\program files (x86)\inno download plugin\idp.iss line 54: column 55: unknown type 'int64'

i using inno setup 5.5.2 (u). can please assist? thanks.

the int64 info type introduced in unicode version 5.5.3 must download more recent version of unicode inno setup. what's new list mentions (emphasized me):

5.5.3 (2013-01-30)

unicode inno setup: has int64 type, supported inttostr. added new strtoint64, strtoint64def, , getspaceondisk64 back upwards functions.

plugins inno-setup inno-download-plugin

c# - Trying to change BorderThickness in DataGrid ColumnHeader -



c# - Trying to change BorderThickness in DataGrid ColumnHeader -

im using bundle called mahapps metro, i'm trying alter style of datagrid alter default borderthickness of columnheader.

the mahapps metro datagrid command can found here: https://github.com/mahapps/mahapps.metro/blob/master/mahapps.metro/styles/controls.datagrid.xaml

the part i'm trying access custom style is:

<border x:name="backgroundborder" borderthickness="0,0,0,3" grid.columnspan="2" background="{templatebinding background}" borderbrush="{templatebinding borderbrush}" />

currently have:

<style targettype="datagridcolumnheader" x:key="geledigdheader" basedon="{staticresource metrodatagridcolumnheader}"> <setter property="horizontalcontentalignment" value="right"/> <setter property="borderbrush" value="#953735"/> </style>

this changes color want alter thickness, using property="borderthickness" not work, obviously..

well if @ style there given no explicit access borderthickness via binding. since have style can add together line

<border x:name="backgroundborder" borderthickness="0,0,0,3" grid.columnspan="2" background="{templatebinding background}" borderbrush="{templatebinding borderbrush}" borderthickness="{templatebinding borderthickness}"/>

c# wpf xaml datagrid

java - anonymous class extending an abstract class -



java - anonymous class extending an abstract class -

i'm looking schedule task @ specified time starttime, , when time comes, want run method rrun(boolean param1, object someobj).

rrun() method in class, someclass.

and, within someclass again, have method m1() part of code:

timer starttimer = new timer(); starttimer.schedule(new timertask() { public void run() {rrun(false, this);} }, starttime);

to this, i'm getting error

incompatible types: <anonymous timertask> cannot converted someclass

what's wrong i'm doing?

tia.

//===============================

edit:

i'm using jdk 8 -- latest one

inside anonymous inner class, this reference current timertask anonymous subclass, not enclosing class.

to refer enclosing class, qualify this:

public void run() {rrun(false, someclass.this);}

java anonymous-types

java - load a jsp in a dialog and div -



java - load a jsp in a dialog and div -

i know might duplication question, couldn't find reply simple question. want load new jsp file in dialog , div.

structure: -webcontent -jsp -viewfolder -helloworld.jsp -helloworldedit.jsp -newworld.jsp

let's have helloworld.jsp loaded request dispatcher. want load newworld.jsp in div tag in helloworld.jsp.

<div id="result"></div> $('#result').load('/jsp/viewfolder/newworld.jsp');

tried above code, didn't work.

i have tried load jsp page dialog , 1 has failed too.

<button id="button">button</button> <div id="dialog"></div> $('#button').on("click", function() { $('#dialog').load('/jsp/viewfolder/helloworldedit.jsp').dialog(); });

the question have is, right way phone call jsp page or have load page request dispatcher using ajax.

to test if path correct, tried set calendar.gif in same folder , able reach context.

http://localhost:port/.projectcontext/jsp/viewfolder/calendar.gif.

you have wait dom ready event:

$(document).ready(function() { $('#button').on("click", function() { $('#dialog').load('/.projectcontext/jsp/viewfolder/helloworldedit.jsp').dialog(); }); });

java javascript jquery jsp

html - Resize an image to take up all of a -



html - Resize an image to take up all of a <div> -

how can constrain image in container whole container filled much image possible?

for illustration (i not know size images be, example) - if have image container of 100x100 , image of 600x400, next conditions need met.

the image should displayed @ 150x100 the image should centred in container the overflow of image (25px left , right in example) should hidden.

please note - images of greater height width, solution needs work images of sizes, centreing both horizontally , vertically.

sadly, solution has work ie9 (as browser owners of intranet working on use), html5/css3 solutions not work.

here couple of visual examples -

i've tried various css styles -

if nest <img> within of <div> container image if absolutly place <img> on <div> unable centre vertically if wider tall (i.e. 600x400).

any suggestions gratefully received.

since mentioned has work ie9: background-size: cover that. can't utilize image img element have assign background image container.

i made jsfiddle here

html css

asp.net - SQL timeouts at 3 minutes past full hour -



asp.net - SQL timeouts at 3 minutes past full hour -

i have problem has puzzled me while now. 1 time in while, 4-5 times week timeouts database @ hh:03 (or hh:02 think). i've been digging scheduled tasks on server investigate if there puts server it's knees in performance without findings.

i've gone fas i've made watchdog application when query has 1 seconds left of it's max query time checks processlist database , emails me. process list contains 1 entry , that's entry timeout exception.

to farther add together complexity have many customers application it's 1 of customers timeout. customers run same code have different databases, different application pools different application pool identities.

the application asp.net application. database microsoft sql 2008 r2 express edition.

has heard of this? can give me pointers investigate in order resolve issue?

kind regards

sql asp.net .net sql-server sql-server-2008

c++ - Why would clang++ fail to compile on a Mac, under Mavericks, except with sudo? -



c++ - Why would clang++ fail to compile on a Mac, under Mavericks, except with sudo? -

after recent software update on mac, i'm not able compile , link c++ hello world programme without sudo.

the programme (helloworld.cpp):

#include <iostream> int main(){ std::cout << "hello world\n"; homecoming 0; }

the invocation:

clang++ helloworld.cpp

fails error:

ld: can't write output file: a.out architecture x86_64 clang: error: linker command failed exit code 1 (use -v see invocation)

but if under sudo,

sudo clang++ helloworld.cpp

there's no problem.

what might causing this, , how might able resolve this?

edit, again: reply turned out not working directory permissions, couple of people suggested, permissions associated output file, a.out, of hello world program. credit petesh solution.

you must sitting in directory not writable user. @ pwd , ls -ld . see , permissions there. seek creating empty file touch foo.txt in same directory ran clang.

c++ osx clang xcode6

networking - ip rule does not seem to be invoked -



networking - ip rule does not seem to be invoked -

i have 2 connections on local machine, 1 via eth0 (has static ip, allow 10.10.10.10), via ppp0 (has dinamic ip, illustration 10.20.30.40). both have access internet. have remote server (let's assume has ip 1.2.3.4) want connect local machine in such way packets having source address 10.10.10.10 (eth0) should go through eth0, while having 10.20.30.40 (ppp0) source address should go through ppp0.

preliminary deleted ip rule main route table in order prevent packets beingness treated rule.

after that, created 2 route tables, 1 eth0 (named eth) , ppp0 (named ppp). added routes these tables follows:

ip route add together default dev ppp0 table ppp ip route add together default dev eth0 table eth

then added ip rules followings:

ip rule add together 10.10.10.10 lookup eth ip rule add together 10.20.30.40 lookup ppp

and doesn't work. however, when utilize ip rule add together all instead of pointing specific ip works (sure, packets go through 1 interface in case). so, seems ip rule not invoked when specify ip.

what reason of such unusual behavior?

does have ideas?

i found reason. cause of problem programme (written usage of qt qtcpsocket::bind()) binds socket appropriate interface, not routing settings. not unknown reason. tried using native linux socket functions , runs clockwork.

networking iptables

How to use Verdana Font in Stamper (iText PDF) -



How to use Verdana Font in Stamper (iText PDF) -

i want utilize verdana font while stamping pdf file itext pdf. original file uses verdana, isn't alternative in class basefont.

here function create font right now:

def standardstampfont() { homecoming basefont.createfont(basefont.helvetica, basefont.winansi, false) }

i'd alter verdana font, exchanging part basefont.helvetica "verdana" doesn't work.

any idea? in advance!

as documented, itext supports standard type 1 fonts, because itext ships afm file (adobe font metrics files). itext has no thought font metrics of other fonts (verdana isn't standard type 1 font). need provide path verdana font file.

basefont.createfont("c:/windows/fonts/verdana.ttf", basefont.winansi, basefont.embedded)

note alter false basefont.embedded because same problem have on side, occur on side of person looks @ file: pdf viewer can render standard type 1 fonts, may not able render other fonts such verdana.

caveat: hard coded path "c:/windows/fonts/verdana.ttf" works me on local machine because font file can found using path on local machine. code won't work on server host itext site, though (which linux server doesn't have c:/windows/fonts directory). using hard coded path way of example. should create sure font nowadays , available when deploy application.

pdf itext

MySQL dynamic loop through table and delete rows based on condition -



MySQL dynamic loop through table and delete rows based on condition -

is possible loop through tables , delete rows based on status can tables this:

select table_name information_schema.tables table_schema = 'mytables'

is possible loop through them , perform query similar this:

delete table now() > columnname

loop through statement selects tables , every table_name execute:

begin set @s = concat('delete from',table_name,' now() > columnname'); prepare stmt @s; execute stmt; deallocate prepare stmt; end

mysql

javascript - Improving code quality/organization of event-heavy riot applications -



javascript - Improving code quality/organization of event-heavy riot applications -

i building application using riot.js , jquery. works expected, code grows, worry triggering , handling events (.trigger/.on) in random/unexpected places in code doing nil maintain code organized , understandable.

my questions are:

(1) maintain code such application clean , streamlined (event namespaces 1 thing comes mind) ,

(2) maintain events on model separated events on dom in presenter. how can accomplish these goals in riot.js based application

thank you.

you @ functional reactive programming approach. here solutions may insterested in:

rx.js - reactive extensions javascript microsoft bacon.js - popular frp library kefir.js - less popular insteresting frp library

javascript jquery riot.js

character encoding - convert database from latin1_swedish_ci to utf8 -



character encoding - convert database from latin1_swedish_ci to utf8 -

i have vbulletin database , wont convert latin1_swedish_ci utf8_unicode_ci can 1 know command convert database or script or php file create charset utf8 give thanks u

there many ways this. here one: dump database , open suitable text editor , save encoding utf8.

character-encoding

java - JFreeChart Candlestick pointer -



java - JFreeChart Candlestick pointer -

i have jfreechart this:

and want add together mouse pointer chart similar highcharts uses:

here variation of code shown here creates jfreechart:

import org.jfree.data.xy.abstractxydataset; import org.jfree.data.xy.defaultohlcdataset; import org.jfree.data.xy.*; import org.jfree.chart.*; import org.jfree.chart.axis.*; import org.jfree.chart.plot.xyplot; import org.jfree.chart.renderer.xy.candlestickrenderer; import java.awt.*; import java.io.*; import java.net.url; import java.text.*; import java.util.*; public class chartohlc extends chartpanel { public chartohlc() { super(dajgraf()); setmaximumdrawheight(2000); setmaximumdrawwidth(3000); } public static jfreechart dajgraf() { // premenne string stocksymbol = "aapl"; final dateaxis domainaxis = new dateaxis("date"); numberaxis rangeaxis = new numberaxis("price"); candlestickrenderer renderer = new candlestickrenderer(); xydataset dataset = getdataset(stocksymbol); xyplot mainplot = new xyplot(dataset, domainaxis, rangeaxis, renderer); //do setting up, see api doc renderer.setseriespaint(0, color.black); renderer.setdrawvolume(false); rangeaxis.setautorangeincludeszero(false); //now create chart , chart panel jfreechart chart = new jfreechart(null, null, mainplot, false); mainplot.setdomainpannable(true); mainplot.setrangepannable(true); homecoming chart; } private static abstractxydataset getdataset(string stocksymbol) { //this dataset going create defaultohlcdataset result; //this info needed dataset ohlcdataitem[] data; //this go data, replace own info source info = getdata(stocksymbol); //create dataset, open, high, low, close dataset result = new defaultohlcdataset(stocksymbol, data); homecoming result; } private static ohlcdataitem[] getdata(string stocksymbol) { arraylist<ohlcdataitem> dataitems = new arraylist<ohlcdataitem>(); seek { string strurl = "http://ichart.yahoo.com/table.csv?s=" + stocksymbol + "&a=2&b=1&c=2014&d=3&e=1&f=2014&g=d&ignore=.csv"; system.out.println(strurl); url url = new url(strurl); bufferedreader in = new bufferedreader(new inputstreamreader(url.openstream())); dateformat df = new simpledateformat("y-m-d"); string inputline; in.readline(); while ((inputline = in.readline()) != null) { stringtokenizer st = new stringtokenizer(inputline, ","); date date = df.parse(st.nexttoken()); double open = double.parsedouble(st.nexttoken()); double high = double.parsedouble(st.nexttoken()); double low = double.parsedouble(st.nexttoken()); double close = double.parsedouble(st.nexttoken()); double volume = double.parsedouble(st.nexttoken()); double adjclose = double.parsedouble(st.nexttoken()); ohlcdataitem item = new ohlcdataitem(date, open, high, low, close, volume); dataitems.add(item); } in.close(); } grab (exception e) { e.printstacktrace(system.err); } //data yahoo newest oldest. reverse oldest newest collections.reverse(dataitems); //convert list array ohlcdataitem[] info = dataitems.toarray(new ohlcdataitem[dataitems.size()]); homecoming data; } }

is possible add together mouse pointer candlestick jfreechart?

java jfreechart candlestick-chart

php - Cpanel cron jobs not working using magento? -



php - Cpanel cron jobs not working using magento? -

anyone please help me

domain: godaddy

hosting: vps server

name server: mns01.domaincontrol.com

name server: mns02.domaincontrol.com

below test case scenarios did , got result

for cron.php file gave permission 777

minutes hr day month weekday set * * * * *

test 1:

/home/domain/public_html/cron.php

result: /home/domain/public_html/cron.php: line 1: ?php: no such file or directory /home/domain/public_html/cron.php: line 2: syntax error near unexpected token `dirname' /home/domain/public_html/cron.php: line 2: `chdir(dirname(__file__));'

test 2:

/usr/bin/php -q /home/domain/public_html/cron.php

result: nil display

test 3:

php -q /home/domain/public_html/cron.php

result: nil display

test 4:

/usr/bin/php /home/domain/public_html/cron.php

result: x-powered-by: php/5.4.33 content-type: text/html

test 5:

get https://www.domain.com/cron.php

result: lwp back upwards https urls if lwp::protocol::https module installed.

test 6:

get http://www.domain.com/cron.php

result: nil display

test 7:

i replaced above test cron.php replaced cron.sh , tested. got same result.

test 8:

/home/domain/public_html/test.php

code: <?php echo "hello world";?> result: /home/domain/public_html/cron.php: line 1: ?php: no such file or directory hello world

you should using cron.sh file on command line (not get), , specify sh path

/bin/sh /home/domain/public_html/cron.sh

php magento cron cpanel magento-1.8

dataset - Converting cross-sectional data into an adjacency matrix in R -



dataset - Converting cross-sectional data into an adjacency matrix in R -

i trying convert cross-sectional info adjacency matrix, want analyze how variables nowadays social network analysis. in case empirical examples help logic, it's analogous presenting 4 people selection of 3 objects; can take 0 3 of objects. i'd analyze how commonly different objects chosen , visualize network of preferences.

the info set cross-sectional data, below:

id1 <- c(1,0,0) id2 <- c(1,0,1) id3 <- c(1,1,1) id4 <- c(0,0,0) ids <- c("1","2","3","4") df <- data.frame(rbind(id1, id2, id3, id4)) df <- cbind(ids, df) colnames(df) <- c("id", "var1", "var2", "var3")

i'd create weighted adjacency matrix var1, var2 , var3, each cell containing total number of times 2 variables occur among observations.

so basic procedure thinking create separate matrix each row (each id number) 1 or 0 each cell indicating whether or not both variables nowadays id. , add together these matrices together, final matrix gives total number of joint appearances.

i've been looking around , haven't quite gotten right. thought of using outer, it'd need work each column in sequence. reply pretty close, wasn't sure how adding values. ended list of matrices, values didn't correspond initial data- convert categorical info in info frame weighted adjacency matrix. , reply close, although seemed have different type of data. gave me adjacency matrix based on ids- http://r.789695.n4.nabble.com/conversion-to-adjacency-matrix-td794102.html

here messy code manually create matrix 1 observation, sense i'm going (using vector representing first id observation)

id1 <- c(1,0,0) var1 <- id1[[1]] var2 <- id1[[2]] var3 <- id1[[3]] onetwo <- var1 * var2 onethree <- var1 * var3 twothree <- var2 * var3 oneone <- var1 * var1 twotwo <- var2 * var2 threethree <- var3 * var3 rows1 <- rbind(oneone, onetwo, onethree) rows2 <- rbind(onetwo, twotwo, twothree) rows3 <- rbind(onethree, twothree, threethree) df2 <- cbind(rows1, rows2, rows3)

this not ideal, actual dataset has 198 observations , 33 variables, looping or utilize of apply functions inefficient.

i can't tell if i'm making more hard needs be, or if i'm trying forcefulness info wasn't meant do. if has run sort of task before, please allow me know. there way create desired adjacency matrix directly? should transfer border list first, , there way that? there code create first step(creating matrix each row of dataframe) more efficient?

thanks help,

i'm not sure if understand question, want?

nc=33 nr=198 m3<-matrix(sample(0:1,nc*nr,replace=true),nrow=nr) df3<-data.frame(m3) m3b <-matrix(0,nrow=nc,ncol=nc) for(i in seq(1,nc)) { (j in seq(1,nc)) { t3<-table(df3[,i],df3[,j]) m3b[i,j] = t3[2,2] # t3[2,2] contains count of df3[,i] = df3[,j] = 1 # or # t3 = sum(df3[,i]==df3[,j] & df3[,i] == 1) # m3b[i,j] = t3 } }

or, if want sum of product, gives same result if 1 or 0

m3c <-matrix(0,nrow=nc,ncol=nc) for(i in seq(1,nc)) { (j in seq(1,nc)) { sv=0 (k in seq(1,nr)) { vi = df3[k,i] vj = df3[k,j] sv=sv+vi*vj } m3c[i,j] = sv } }

r dataset adjacency-matrix

floating point - How to display float value on LCD 16x2 -



floating point - How to display float value on LCD 16x2 -

i want display float value on lcd. have using avr5.1 compiler , using function snprintf convert float value ascii. gives output on proteus "?".

here code using; have include library of printf_flt:

temp1=adch; // measuring voltage temp=(temp1*19.53)*2.51; lcd_goto(1,1); snprintf(buffer,6, "%2.2f", temp); lcd_data1(buffer); lcd_data1("mv"); percent=(temp-11500); lcd_goto(2,2); snprintf(buffer1,4, "%2.2f", percent); lcd_data1(" "); lcd_data1(buffer1); lcd_data1("%");

here image of output:

many development tools have multiple versions of printf , related functions, back upwards differing levels of capabilities. floating-point math code bulky , complicated, including features aren't used waste lot of code space.

some tools automatically seek figure out options need included, aren't , require programmer explicitly select appropriate printf version using command-line arguments, configuration files, or other such means. may necessary create compiler include version of printf-related functions supports %f specifier, or else utilize other means of formatting output. own preferred approach convert value scaled integer (e.g. 100x desired value) , write method output digits, least-significant first, , insert period after outputting number of digits. like:

uint32_t acc; uint8_t divmod10() { uint8_t result = acc % 10; acc /= 10; } // output value in acc using 'digits' digits, decimal point shown after dp. // if dp greater 128, don't show decimal point or leading zeroes // if dp less 128 greater digits, show leading zeroes void out_number(uint8_t digits, uint8_t dp) { acc = num; while(digits-- > 0) { uint8_t ch = divmod10(); if (ch != 0 || (dp & 128) == 0) out_lcd(ch + '0'); else out_lcd(ch); if (--dp == 0) out_lcd('.'); } }

since lcd modules can configured receive info right-to-left, outputting numbers in form can useful simplification. note seldom utilize "printf"-family functions on little microcontrollers, since code above much more compact.

floating-point digital floating-point-conversion circuit circuit-diagram

Python OpenCV Error -



Python OpenCV Error -

simple code used identify playing cards through cam have been trying run code maintain getting error when attempting utilize of methods

typeerror: src not numpy array, neither scalar

import sys import numpy np sys.path.insert(0, "/usr/local/lib/python2.7/site-packages/") import cv2 ############################################################################### # utility code ############################################################################### def rectify(h): h = h.reshape((4,2)) hnew = np.zeros((4,2),dtype = np.float32) add together = h.sum(1) hnew[0] = h[np.argmin(add)] hnew[2] = h[np.argmax(add)] diff = np.diff(h,axis = 1) hnew[1] = h[np.argmin(diff)] hnew[3] = h[np.argmax(diff)] homecoming hnew ############################################################################### # image matching ############################################################################### def preprocess(img): grayness = cv2.cvtcolor(img,cv2.color_bgr2gray) blur = cv2.gaussianblur(gray,(5,5),2 ) thresh = cv2.adaptivethreshold(blur,255,1,1,11,1) homecoming thresh def imgdiff(img1,img2): img1 = cv2.gaussianblur(img1,(5,5),5) img2 = cv2.gaussianblur(img2,(5,5),5) diff = cv2.absdiff(img1,img2) diff = cv2.gaussianblur(diff,(5,5),5) flag, diff = cv2.threshold(diff, 200, 255, cv2.thresh_binary) homecoming np.sum(diff) def find_closest_card(training,img): features = preprocess(img) homecoming sorted(training.values(), key=lambda x:imgdiff(x[1],features))[0][0] ############################################################################### # card extraction ############################################################################### def getcards(im, numcards=4): grayness = cv2.cvtcolor(im,cv2.color_bgr2gray) blur = cv2.gaussianblur(gray,(1,1),1000) flag, thresh = cv2.threshold(blur, 120, 255, cv2.thresh_binary) contours, hierarchy = cv2.findcontours(thresh,cv2.retr_tree,cv2.chain_approx_simple) contours = sorted(contours, key=cv2.contourarea,reverse=true)[:numcards] card in contours: peri = cv2.arclength(card,true) approx = rectify(cv2.approxpolydp(card,0.02*peri,true)) # box = np.int0(approx) # cv2.drawcontours(im,[box],0,(255,255,0),6) # imx = cv2.resize(im,(1000,600)) # cv2.imshow('a',imx) h = np.array([ [0,0],[449,0],[449,449],[0,449] ],np.float32) transform = cv2.getperspectivetransform(approx,h) warp = cv2.warpperspective(im,transform,(450,450)) yield warp def get_training(training_labels_filename,training_image_filename,num_training_cards,avoid_cards=none): training = {} labels = {} line in file(training_labels_filename): key, num, suit = line.strip().split() labels[int(key)] = (num,suit) print "training" im = cv2.imread(training_image_filename) i,c in enumerate(getcards(im,num_training_cards)): if avoid_cards none or (labels[i][0] not in avoid_cards[0] , labels[i][1] not in avoid_cards[1]): training[i] = (labels[i], preprocess(c)) print "done training" homecoming training if __name__ == '__main__': if len(sys.argv) == 6: filename = sys.argv[1] num_cards = int(sys.argv[2]) training_image_filename = sys.argv[3] training_labels_filename = sys.argv[4] num_training_cards = int(sys.argv[5]) training = get_training(training_labels_filename,training_image_filename,num_training_cards) im = cv2.imread("test") width = im.shape[0] height = im.shape[1] if width < height: im = cv2.transpose(im) im = cv2.flip(im,1) # debug: uncomment see registered images #for i,c in enumerate(getcards(im,num_cards)): # card = find_closest_card(training,c,) # cv2.imshow(str(card),c) # cv2.waitkey(0) cards = [find_closest_card(training,c) c in getcards(im,num_cards)] print cards else: print __doc__

here entire error message

traceback (most recent phone call last): file "<pyshell#15>", line 1, in <module> preprocess("test.jpg") file "c:\users\don ellison\desktop\class programs\csc 490 project\cards\python\playing-card-recognition-master\card_img.py", line 43, in preprocess grayness = cv2.cvtcolor(img,cv2.color_bgr2gray) typeerror: src not numpy array, neither scalar

you passing in wrong argument preprocess function, guess calling python shell.

you not suppose pass in image file name, rather numpy array. seems called proprocess function , passed in "test.jpg" in python shell. if want test preprocess function, do

test_img = cv2.imread("test.jpg") preprocess(test_img)

python opencv numpy

authentication - Ember Simple-Auth with API for LDAP -



authentication - Ember Simple-Auth with API for LDAP -

i want authenticate on client don't have manage session on server. seems possible ember-cli-simple-auth, don't know first thing how create custom authenticator pass login credentials backend api (spring java). couple months ember , ember-cli well, flood of things larn has been daunting.

there's plenty of stuff authenticating oauth2 , such, that's not need. intranet application, need pass credentials server, server authenticates ldap, , has homecoming (what, i'm not sure, that's else need know) simple-auth can recognize user authenticated or not.

again, sorry if have phrased better. i'm @ stage hardly know how inquire question, why i'm asking here.

authentication ember.js ldap ember-cli ember-simple-auth

ios - Tokenize an NSString for filtering data (search) -



ios - Tokenize an NSString for filtering data (search) -

i'm trying implement search filtering info source used populate uitableview.

basically, i'm trying allow people set in multiple words , split 1 string tokens , iterate through each object in datasource see if can find of search tokens anywhere in object's properties or sub-properties.

if user types in multiple words separated spaces, trivial case of using -componentsseparatedbystring:.

i'm trying, however, solve case user might set in comma-separated list of items.

so, easy entry tokenize this:

"word1 word2 word3"

i want able tokenize this:

"word1, word2, word3"

the problem see that, because don't assume user come in commas, can't replace/remove white space.

i see kludgy ways implement want, consists of splitting first on white space, iterating array, splitting on commas, iterating overall array, removing "empty" tokens. think work, hoping more elegant way this, since might decide add together 3rd delimiter @ point, create solution exponentially more complex.

so far, i'm intrigued using nscharacterset in combination -componentsseparatedbycharactersinset. i'm having problem method, though.

here's i'm trying far:

nsmutablecharacterset *delimiters = [nsmutablecharacterset charactersetwithcharactersinstring:@","]; [delimiters addcharactersinstring:@" "]; nsarray *tokens = [searchtext componentsseparatedbycharactersinset:delimiters];

the problem i'm encountering this:

suppose searchtext (above) "word,". in case, tokens array becomes this:

[@"word", @""]

so, trying out, appear (at first glance) still have iterate tokens array remove empty items. again, possible, have feeling there's improve way.

is there improve way? misusing nscharacterset?

use enumeratesubstringsinrange:options:usingblock:, , pass nsstringenumerationbywords option. separate string individual words, , strip out spaces, commas, semicolons, etc. instance, code,

- (void)viewdidload { [super viewdidload]; nsmutablearray *words = [nsmutablearray new]; nsstring *text = @"these , some, words commas; semi colons: colons , period."; [text enumeratesubstringsinrange:nsmakerange(0, text.length) options:nsstringenumerationbywords usingblock:^(nsstring *substring, nsrange substringrange, nsrange enclosingrange, bool *stop) { [words addobject:substring]; }]; nslog(@"%@", words); }

gives output,

2014-10-22 11:13:25.728 gettingwordsfromstringproblem[859:270592] ( these, are, some, words, with, commas, semicolons, colons, and, period )

ios objective-c nsstring tokenize

Sorting arrays manually in php without using sort() -



Sorting arrays manually in php without using sort() -

help. stucked in logic , procedures in printing sorted array lists without using sort().

<?php $item = array(2, 1, 3); $item_length = count($item); ($counter = 0; $counter < $item_length; $counter++) { if ($item[$counter] <= $item[$counter + 1]) { print $item[$counter]; // should do?? } } ?>

here solution using bubble sort

<?php $item = array(2, 1, 4,3,5,6); $item_length = count($item); ($counter = 0; $counter < $item_length-1; $counter++) { ($counter1 = 0; $counter1 < $item_length-1; $counter1++) { if ($item[$counter1] > $item[$counter1 + 1]) { $temp=$item[$counter1]; $item[$counter1]=$item[$counter1+1]; $item[$counter1+1]=$temp; } } } //you can print array using loop print_r($item); ?>

php sorting

c# - The type or namespace name 'BundleCollection' could not be found (are you missing a using directive or an assembly reference?) -



c# - The type or namespace name 'BundleCollection' could not be found (are you missing a using directive or an assembly reference?) -

so, have mvc 4 project in c# , using visual studio web 2012 express.

i cannot compile projecto due error: type or namespace name 'bundlecollection' not found (are missing using directive or assembly reference?)

normally, mean library missing. after making quick search on net used nuget install microsoft.aspnet.web.optimization, still did not work.

what makes intriguing me bundlecollections should known application deafult. can imagine have added dependency messed up, can't know sure.

how can prepare problem? missing here?

code:

using system; using system.web; using system.web.optimization; namespace dockis { public class bundleconfig { // more info on bundling, visit http://go.microsoft.com/fwlink/?linkid=254725 public static void registerbundles(bundlecollection bundles) { iitemtransform cssfixer = new cssrewriteurltransform(); bundles.add(new scriptbundle("~/bundles/jquery").include( "~/scripts/jquery-{version}.js")); //... } } }

edit

after checking references folder tried running command install-package system.web.optimization, cannot install package. next error:

install-package : 1 or more errors occurred. @ line:1 char:16 + install-package <<<< system.web.optimization + categoryinfo : notspecified: (:) [install-package], aggregateexception + fullyqualifiederrorid : nugetcmdletunhandledexception,nuget.powershell.commands.installpackagecommand

what odd, fact running install-package system.web.optimization.less works, , fixes depencie problems, not of them. believe need first command work.

what doing wrong?

there no clear reply question. managed prepare project re-creating it, , downloading dlls in different order, closing , re-opening visual studio several times while doing it.

aparently there conflict between of packages, impossible guess until had re-created project scratch again.

running install-package microsoft.aspnet.web.optimization did solve problem after clean install however, recommend it.

i give thanks help.

c# .net asp.net-mvc-4 visual-studio-2012 nuget

Which Android Gradle Plugin version should I use in my project? -



Which Android Gradle Plugin version should I use in my project? -

which version should utilize in project?

i have:

buildscript { repositories { mavencentral() } dependencies { classpath 'com.android.tools.build:gradle:0.12.2' } } allprojects { repositories { mavencentral() } }

i`m using sdk 21 , android build tools 21.0.2.

0.13.3 latest version of android gradle plugin. can find release notes (including version numbers) here: http://tools.android.com/tech-docs/new-build-system

android android-gradle

ggplot2 - R ggsave save thumbnail size (200 x 200),scaled image -



ggplot2 - R ggsave save thumbnail size (200 x 200),scaled image -

i trying plot simple x,y line plots info in loop. code generate hundreds of such plots , thought save these plots in thumbnail size image (something 200 x 200 pixels, dpi wont matter) , embed in excel file along data. when plot through ggplot2 looks fine when want save it, either cropped image showing part of image or narrow plot mismatched sizes of labels/texts. if set scale 2 looks right not fit criteria.

my info frame looks this.

drug=c("a","a","a","a","a","a") con=c(10,100,1000,10,100,1000) treatment=c("dox","dox","dox","pac","pac","pac") value=c(-3.8,-4.5,-14.1,4,-4.6,3.5) mat_tbl=data.frame(drug,con,treatment,value) p=ggplot(data=mat_tbl,aes(x=con,y=value,colour=treatment,group=treatment))+geom_point(size = 4)+geom_line()+labs(title="drug a",x="concentration",y="value") + scale_y_continuous(limits=c(-25,125),breaks=seq(-25,125,by=25)) + theme_bw() ggsave(filename = "curve_drug.png",plot=p,width=2,height=2,units="in",scale=1)

any suggestions parameters need work on?

r ggplot2

swift - Change Spacing Between UIBarButtonItems in iOS 8 -



swift - Change Spacing Between UIBarButtonItems in iOS 8 -

i have uinavigationitem on view controller, , trying cut down spacing between 2 rightbarbuttonitems. here of code:

// create 2 uibarbuttonitems allow item1:uibarbuttonitem = uibarbuttonitem(customview: view1) allow item2:uibarbuttonitem = uibarbuttonitem(customview: view2) var fixedspace:uibarbuttonitem = uibarbuttonitem(barbuttonsystemitem: uibarbuttonsystemitem.fixedspace, target: nil, action: nil) fixedspace.width = -20.0 // add together rightbarbuttonitems on navigation bar viewcontroller.navigationitem.rightbarbuttonitems = [item2, fixedspace, item1]

as can seen, using fixedspace uibarbuttonitem, not changing spacing reason. have thought subclassing either uinavigationitem or uibarbuttonitem can set spacing accordingly, couldn't seem find methods override alter spacing between items.

any insight on how solve problem appreciated!

thanks @fogmeister's help, figured out width of view1 , view2 objects, uibuttons, large. why there abnormal spacing between them. here final code:

// first button's image var view1img:uiimage = uiimage(named: "image1")! // create first button var view1:uibutton = uibutton(frame: cgrect(x: 0, y: 0, width: view1img.size.width, height: view1img.size.height)) // sec button's image var view2img:uiimage = uiimage(named: "image2")! // create sec button var view2:uibutton = uibutton(frame: cgrect(x: 0, y: 0, width: view2img.size.width, height: view2img.size.height)) // create 2 uibarbuttonitems allow item1:uibarbuttonitem = uibarbuttonitem(customview: view1) allow item2:uibarbuttonitem = uibarbuttonitem(customview: view2) // set 26px of fixed space between 2 uibarbuttonitems var fixedspace:uibarbuttonitem = uibarbuttonitem(barbuttonsystemitem: uibarbuttonsystemitem.fixedspace, target: nil, action: nil) fixedspace.width = 26.0 // set -7px of fixed space before 2 uibarbuttonitems aligned border var negativespace:uibarbuttonitem = uibarbuttonitem(barbuttonsystemitem: uibarbuttonsystemitem.fixedspace, target: nil, action: nil) negativespace.width = -7.0 // add together rightbarbuttonitems on navigation bar viewcontroller.navigationitem.rightbarbuttonitems = [negativespace, item2, fixedspace, item1]

i create background image first uibutton , utilize size create frame uibutton. perform same actions sec uibutton. then, create uibarbuttonitems 2 uibuttons. after that, create 26px of fixed space , -7.0px of fixed space. purpose of former create amount of space between 2 buttons. purpose of latter move uibarbuttonitems on right. then, add together of uibarbuttonitems rightbarbuttonitems in particular order want.

it works great now! of help, fogmeister!

ios swift ios8 uinavigationitem spacing

vba - Outlook.MailItem, Object variable or With block variable not set -



vba - Outlook.MailItem, Object variable or With block variable not set -

first time have programming in outlook vba 2007.

i can save info email excel file.

i think problem in outlook.mailitem.

i'm running code:

alternative explicit sub copytoexcel() dim olitem outlook.mailitem dim xlapp excel.application dim xlwb object dim xlsheet object dim vtext, vtext2, vtext3, vtext4, vtext5 variant dim stext string dim rcount long dim bxstarted boolean dim enviro string dim strpath string enviro = cstr(environ("userprofile")) 'the path of workbook strpath = enviro & "\documents\test1.xlsx" on error resume next set xlapp = new excel.application if err <> 0 application.statusbar = "please wait while excel source opened ... " set xlapp = createobject("excel.application") bxstarted = true end if on error goto 0 'open workbook input info set xlwb = xlapp.workbooks.open(strpath) set xlsheet = xlwb.sheets("test") ' process message record 'find next empty line of worksheet rcount = xlsheet.range("b" & xlsheet.rows.count).end(-4162).row rcount = rcount + 1 stext = olitem.body '<------ error dim reg1 regexp dim m1 matchcollection dim m match set reg1 = new regexp ' \s* = invisible spaces ' \d* = match digits ' \w* = match alphanumeric reg1 .pattern = "((boa tarde \w*))" end if reg1.test(stext) set m1 = reg1.execute(stext) each m in m1 vtext = trim(m.submatches(1)) vtext2 = trim(m.submatches(2)) vtext3 = trim(m.submatches(3)) vtext4 = trim(m.submatches(4)) vtext5 = trim(m.submatches(5)) next end if xlsheet.range("b" & rcount) = vtext xlsheet.range("c" & rcount) = vtext2 xlsheet.range("d" & rcount) = vtext3 xlsheet.range("e" & rcount) = vtext4 xlsheet.range("f" & rcount) = vtext5 xlwb.close 1 if bxstarted xlapp.quit end if set xlapp = nil set xlwb = nil set xlsheet = nil end sub

but, have error: line:

stext = olitem.body

some help?

you haven't set olitem reference anywhere in code, you've declared on line dim olitem outlook.mailitem. missing assignment somewhere?

vba outlook-2007

firefox addon - Open page from main.js and pass data to it -



firefox addon - Open page from main.js and pass data to it -

i trying create simple test addon 1 thing: open html page (located in info folder) main.js, pass generated json can display. i've figured out complex way using message-passing , cloning unsafewindow.options, there must simpler way?

ps. i'm happy utilize 'addon-page' module if right way it...

a simple template opening tab, when tab ready, attach content scripts, pass parameters, , setup message handlers:

in addon module:

var resourceurl=require("sdk/self").data.url; require("sdk/tabs").open({ url:resourceurl("index.html"), onready:function(tab){ var worker=tab.attach({ contentscriptfile:["support.js","content.js"].map(resourceurl), contentscriptoptions:{}, //parameters passed content script }); worker.port.on("ready",function(msgin){ worker.port.emit("acknowledge",msgout); }); } });

and in content script; send "ready" message , recieve "acknowledge" message:

self.port.on("acknowledge",function(msgin){}); self.port.emit("ready",msgout);

there might changes handling of parameters url and/or contentscriptfile, such relative paths allowed without need require("sdk/self").data.url. not sure if speculation/proposal or if it's implemented; haven't checked.

also think addon-page depreciated , hasn't worked since upgrade australis ui (i.e. navigation bar no longer hidden special uris about:addons).

firefox-addon firefox-addon-sdk

opencl - Difference between two ways of measuring kernel execution times -



opencl - Difference between two ways of measuring kernel execution times -

i have n separate opencl kernels run synchronously in sequential fashion. sec kernel uses results first kernel, 3rd kernel uses sec kernel, , etc.

i measured total "execution" time kernels in 2 different ways:

1) associate each kernel individual event , measure time each kernel separately subtracting start time end time of each event. total time computed adding times events of kernels. in case, event wait method called after executing each kernel.

2) in 1), associate each kernel event (n kernels , n events). then, phone call event wait methods @ end after executing kernels (namely, event wait calls followed series of kernel calls). total execution time obtained subtracting start time of first event end time of lastly event.

the difference between total times 1) , 2) quite significant: ~20% of total execution time. 20% lost? associated (en)queuing multiple kernels?

how go reducing "overhead"? cut down overhead write larger kernel cramming kernels single big kernel restructuring kernels?

thanks!

opencl pyopencl

C++ Perincrement Undefined Operation vs C -



C++ Perincrement Undefined Operation vs C -

i have line of code:

front = (++front) % size;

in c no warnings in c++ warning operation on front end may undefined [-wsequence-point]. how preincrement usage cause undefined behavior? in mind, line unambiguous , interpreted as:

increment front mod front end size assign new value front.

is compiler throwing blanket warning?

p.s. understand warning if doing front = front++; or heaven forbid front = front++ + front++;.

edit: warning produced in codeblocks on windows 64 using gcc (tdm-1) 4.6.1

the old sequencing rules had border cases order of operations defined still technically undefined behavior. c++11 , c11 has been fixed replacing sequence point requirements 'sequenced-before' , 'sequenced-after' relations.

your illustration happens such case. if you're getting warnings in c11 or c++11 mode warning hasn't been updated new rules yet. in before c , c++ modes warning correct. if you're not getting warnings in before modes weren't implemented, , that's okay 'no diagnostic required'.

at same time, line can written more , right under old rules:

front = (front + 1) % size;

c++

acumatica - Filtering on Customer Screen does not use more than one filter -



acumatica - Filtering on Customer Screen does not use more than one filter -

i using ar303000 screen search customer. if add together more 1 filter first filter applied. also, results set not include generalinfomainaddress lines. may why filter not working.

ar303000content ar303000 = context.ar303000getschema(); context.ar303000clear();

list<command> cmds = new list<command>(); cmds.add(ar303000.customersummary.servicecommands.everycustomerid); cmds.add(ar303000.customersummary.customerid); cmds.add(ar303000.customersummary.customername); cmds.add(ar303000.generalinfomainaddress.addressline1); cmds.add(ar303000.generalinfomainaddress.city); cmds.add(ar303000.generalinfomainaddress.state); cmds.add(ar303000.generalinfomainaddress.postalcode); list<filter> filters = new list<filter>(); filters.add(new filter() { field = new field() { fieldname = ar303000.customersummary.customername.fieldname, objectname = ar303000.customersummary.customername.objectname }, status = filtercondition.contain, value = "doe, john", operator = filteroperator.and }); filters.add(new filter() { field = new field() { fieldname = ar303000.generalinfomainaddress.addressline1.fieldname, objectname = ar303000.generalinfomainaddress.addressline1.objectname }, status = filtercondition.contain, value = "255", operator = filteroperator.and }); var ar303000export = context.ar303000export(cmds.toarray(), filters.toarray(), 0, false, false); homecoming ar303000export[0][0];

the web services can filter on fields of primary view of screen, in case ar303000.customersummary. if seek filter on else, scheme doesn't throw exception, instead silently discards filter.

if need able filter information, suggest create generic enquiry joins on tables need, , utilize gi screen through web services other enquiry screen.

acumatica

c - Correct Hystersis -



c - Correct Hystersis -

i have temperature reading fluctuates. logic chain below right prevent boundary switching on , off?

if (temp > 50) { ac = 100% } else if (temp > 40 && temp < 50) { null; // alter nil } else if (temp > 30 && temp < 40) { ac = 50% } else if (temp > 20 && temp < 30) { null; } else if (temp > 10 && temp < 20) { ac = 25%; } else if (temp < 5) { ac = 0%; }

what null macro here? leave if body empty or write ; (like did).

if you, include such temperatures 40, 30, 20 , 10. isn't clear why omit temperatures 5, 6, 7, 8 , 9.

with little change, logic must correct:

say, if temp 27, discard <50, <40, <30 , when discards <20, figures out 27 in range [20 .. max]. there's no need in these && temp < 50 - have verified temp if more 50 , got negative result 27 (in previous if condition), don't heave again.

if (temp >= 50) { ac = 100% } else if (temp >= 40) { ; // alter nil } else if (temp >= 30) { ac = 50% } else if (temp >= 20) { ; } else if (temp >= 10) { ac = 25%; } else { // temp may -1, take consideration. ac = 0%; }

c if-statement

db2 luw - Summing and counting across multiple tables in SQL -



db2 luw - Summing and counting across multiple tables in SQL -

i have 3 tables need select , summarize data.

table: thought reference sl 128 sl1 200 sl1 201 sl2 205 sl3 table: acct1 idea_ref accts 128 5 128 2 200 3 205 4 table: acct2 idea_ref accts 201 3 205 4 205 3

what need pull summary sorted sl totals accts field of both tables.

here sql using far:

select i.sl sl, count(distinct i.reference) no, sum(case when a1.idea_ref=i.reference a1.accts else 0 end) acct1, sum(case when a2.idea_ref=i.reference a2.accts else 0 end) acct2 thought left bring together acct1 a1 on a1.idea_ref=i.reference left bring together acct2 a2 on a2.idea_ref=i.reference a2.idea_ref in i.reference or a1.idea_ref in i.reference grouping i.sl

the problem finding when there multiple values in acct1 , acct2 tables reference thought table. here results query:

sl no acct1 acct2 sl1 2 10 0 sl2 1 0 3 sl3 1 8 7

the sl3 line adds acct1 , acct2 values 2 times. can't seem find right way add together them appropriate number of times.

the desired output is:

sl no acct1 acct2 sl1 2 10 0 sl2 1 0 3 sl3 1 4 7

any help much appreciated.

you hare asking 3 separate aggregates, you're trying compute them in single query.

to no (count of distinct items) can do

select sl, count(*) no thought grouping sl

to acct1 item can do:

select sl, sum(accts) acct1 thought bring together acct1 on idea.reference = acct1.idea_ref grouping sl

in manner can acct2

select sl, sum(accts) acct2 thought bring together acct2 on idea.reference = acct2.idea_ref grouping sl

then, need bring together these aggregate queries on sl result set. because have missing entries in of aggregates, need left in left join , coalesce() items.

sql fiddle

here's on query

select q.sl, no, coalesce(acct1,0) acct1, coalesce(acct2,0) acct2 ( select sl, count(*) no thought grouping sl ) q left bring together ( select sl, sum(accts) acct1 thought bring together acct1 on idea.reference = acct1.idea_ref grouping sl ) r on q.sl = r.sl left bring together ( select sl, sum(accts) acct2 thought bring together acct2 on idea.reference = acct2.idea_ref grouping sl ) s on q.sl = s.sl

the result looking for:

| sl | no | acct1 | acct2 | |-----|----|-------|-------| | sl1 | 2 | 10 | 0 | | sl2 | 1 | 0 | 3 | | sl3 | 1 | 4 | 7 |

see how works? have each aggregate separately.

if you're using dbms doesn't know join ... using() syntax, set in on q.sl = r.sl or appropriate on clause instead. see edit, , see fiddle: http://sqlfiddle.com/#!2/63aa1/3/0

sql db2-luw

php - issues: Google Tag Manager not applied to all pages in WordPress and meta description not showing -



php - <head> issues: Google Tag Manager not applied to all pages in WordPress and meta description not showing -

i looked @ source code on applicable webpages both issues , here's i'm finding:

1) i'm using wordpress , i've installed google tag manager in header.php right after opening body tag. tag appears published on pages posts not homepage nor other pages created. looks theme uses uses get_header(); load header single.php , page template, wouldn't know where. , google webmaster tools can't verify.

2) added meta description in header.php file homepage

that's not showing either.

any suggestions? thanks.

header.php should called in every page-*.php, index.php, template-*.php single-*.php, archive-*.php, etc.

if want have special header specific page, need create header-home.php , phone call using function get_header('home')

hope helps

php wordpress meta google-webmaster-tools google-tag-manager

Launch external app from java - and NOT have it tied to the VM -



Launch external app from java - and NOT have it tied to the VM -

there times when big java app needs launch external program. can pretty runtime.getruntime().exec("app name");

the problem launched app seems tied java process, gets terminated when java app exits. want leave other app running.

edit: made error above description. launched app not terminated.

the problem after original app exits, can not start 1 time again until launched app terminates. original app (and launched app) both launch4j generated .exe's.

so, how can maintain launched app preventing total exit original app?

(oh, , throw monkeywrench it, launched app uses 32bit jvm, while original app running in 64bit jvm.)

while shell command trick might work, did find easier way.

desktop.getdesktop().open("app name");

apparently launches app in way not remain tied original program.

java launch

javascript - generate java script file from template -



javascript - generate java script file from template -

i want generate java script templates illustration give varible , params , generate function,something simliar t4template in c#.

click:function(test){ var = "test"; };

which tool should use,i want open source , when google didnt find anthing helpful, please assist. want utilize open source easy use. illustration helpful

thanks!

javascript jquery code-generation

javascript - just one of the ng-bind-html in page work -



javascript - just one of the ng-bind-html in page work -

i write angularjs application , have block of code first html-bind-html works me

<div ng-bind-html='newstitle'> <div ng-bind-html='newsdetail'></div> </div>

when alter priority :

<div ng-bind-html='newsdetail'> <div ng-bind-html='newstitle'></div> </div>

it shows newsdetail value. how many ng-bind-html per page can declare? why sec value doesn't show?

i guess understand problem.

<div ng-bind-html='newstitle'> <!-- replace content of div $scope.newstitle --> <div ng-bind-html='newsdetail'> <!-- won't appear, because has been removed ng-bind-html='newstitle' --> </div> </div>

look comments in code. if set newsdetails in first place, binded html ($scope.newsdetail) replace current content aswell.

in word, ng-bind-html replace current content of element binded html provide. shouldn't set html in elements.

you have :

<div class="news"> <div ng-bind-html='newstitle'></div> <div ng-bind-html='newsdetail'></div> </div>

some docs ngbindhtml directive : https://docs.angularjs.org/api/ng/directive/ngbindhtml

javascript angularjs bind

Silverstripe 3 - Unable to implement controller access security from CMS -



Silverstripe 3 - Unable to implement controller access security from CMS -

good afternoon,

i'm still new silverstripe , i'm trying figure out simple tasks.

currently, i'm trying implement security restrictions page controller function created within dataobject , configured via cms.

however, whether or not grant user access view object, user sees anyhow.

see illustration below:

class mycomponent extends dataobject implements permissionprovider{ ///>... snippet not total class ... ///>@override public function canview($member = null){ homecoming permission::check('component_view'); }//canview /** * \brief rest of permission functions follow same format above * i.e: canedit, candelete, cancreate */ ///>@override function providepermissions(){ homecoming array( 'component_view' => 'can view component object', 'component_edit' => 'can edit component object', 'component_delete' => 'can delete component object', 'component_create' => 'can create component object', ); }//providepermissions }//class

okay, class above works great; can toggle permissions on|off within grouping user cms admin section.

here's problem at, see code below:

///>controller class snippet class my_controller extends page_controller{ public function listmycomponents(){ $components = mycomponent::get()->filter(array('status' => 'enable')); ///>note: how can check see if user has access view component??? ///> i've tried, member::canview(member::currentuser()); doesn't work! homecoming $components; }//listmycomponents }//class ///>ss template file snippet <% if listmycomponents %> <% loop listmycomponents %> $title <% end_loop %> <% end_if %>

thanks assistance.

i've figured out. basically, can permission::check within controller well. see below code solution:

public function listmycomponents(){ $components = null; if(permission::check('component_view')){ $components = mycomponent::get()->filter(array('status' => 'enable')); } homecoming $components; }//listmycomponents

thanks though, may have been researching solve this.

security controller content-management-system silverstripe

php - Custom Select Query by meta key and cat id -



php - Custom Select Query by meta key and cat id -

i have custom query expiry date of post , orders post that. how amend list category id e.g. '20'

$querystr = " select wposts.* $wpdb->posts wposts, $wpdb->postmeta wpostmeta wposts.id = wpostmeta.post_id , wpostmeta.meta_key = 'es_ape_expiry' order wpostmeta.meta_value asc "; $pageposts = $wpdb->get_results($querystr, object);

many !

try next query , replace $cat_id 20

select wposts.* $wpdb->posts wposts, $wpdb->postmeta wpostmeta bring together $wpdb->term_relationships tr on (p.id = tr.object_id) bring together $wpdb->term_taxonomy tt on (tr.term_taxonomy_id = tt.term_taxonomy_id) bring together $wpdb->terms t on (tt.term_id = t.term_id) wposts.id = wpostmeta.post_id , wpostmeta.meta_key = 'es_ape_expiry' , tt.taxonomy = 'category' , t.term_id = $cat_id order wpostmeta.meta_value asc

php sql wordpress codex

javascript - What is causing my weird graphical glitch with my dojo GridX? -



javascript - What is causing my weird graphical glitch with my dojo GridX? -

i dealing odd glitch display of gridx rows. when grid info updated after initial info load, entire gridx doesn't display, found if move mouse around rows triggers rest (hidden rows) pop out , displayed. see screenshots:

edit: seems discovered when mouse enters header, when pops out. how solve issue?

after mouse moves on grid in random motions:

code:

require([ //require resources. "dojo/dom", "dojo/store/memory", "dijit/form/button", "gridx/core/model/cache/sync", "gridx/grid", "gridx/modules/cellwidget", "dojo/domready!" ], function(dom, memory, button, cache, grid){ //use dojo/store/memory here store = new memory({ data: [ { id: 1, feedname: 'feed4', startstop: 0, pause: '', config: ''}, { id: 2, feedname: 'feed5', startstop: 0, pause: '', config: ''} ] }); // todo: don't know for: //we using memory store, synchronous. var cacheclass = "gridx/core/model/cache/sync"; var construction = [ { id: 'feedname', field: 'feedname', name: 'feed name', width: '110px' }, { id: 'startstop', field: 'startstop', name: 'start/stop', width: '61px', widgetsincell: true, navigable: true, alloweventbubble: true, decorator: function(){ //generate cell widget template string homecoming [ '<div style="text-align: center"><button data-dojo-type="dijit.form.button" ', 'onclick="onstartstopbuttonclick();" ', 'data-dojo-attach-point="btn" ', 'class="startstopbuttonplay" ', 'data-dojo-props="iconclass:\'startstopbuttonplayicon\'" ', '></button></div>' ].join(''); }, setcellvalue: function(data){ //"this" cell widget this.btn.set('label', data); } }, { id: 'pause', field: 'pause', name: 'pause', width: '61px', widgetsincell: true, navigable: true, alloweventbubble: true, decorator: function(){ //generate cell widget template string homecoming [ '<div style="text-align: center"><button data-dojo-type="dijit/form/button" ', 'onclick="onpausebuttonclick();" ', 'data-dojo-attach-point="btn2" ', 'class="pausebutton" ', 'data-dojo-props="iconclass:\'pauseicon\'" ', '></button></div>' ].join(''); }, setcellvalue: function(data){ //"this" cell widget this.btn2.set('label2', data); } }, { id: 'config', field: 'config', name: 'config', width: '61px', widgetsincell: true, navigable: true, alloweventbubble: true, decorator: function(){ //generate cell widget template string homecoming [ '<div style="text-align: center"><button data-dojo-type="dijit/form/button" ', 'onclick="onconfigbuttonclick();" ', 'data-dojo-attach-point="btn3" ', 'class="configbutton" ', 'data-dojo-props="iconclass:\'configicon\'" ', '></button></div>' ].join(''); }, setcellvalue: function(griddata, storedata, cellwidget){ //"this" cell widget cellwidget.btn3.set('label3', data); } } ]; //create grid widget. grid = grid({ id: 'grid', cacheclass: cache, store: store, structure: structure, autoheight: true, columnwidthautoresize: false }); //put dom tree. grid.placeat('compactwidgetgrid'); //start up. grid.startup(); updategriddata(memory, store); }); function updategriddata(memory, store){ grid.model.clearcache(); newstore = new memory({ // todo: replace info here actual feed info received picte server! data: [ { id: 1, feedname: 'testingthis1', startstop: 0, pause: '', config: ''}, { id: 2, feedname: 'testingthis2', startstop: 0, pause: '', config: ''}, { id: 3, feedname: 'testingthis3', startstop: 0, pause: '', config: ''}, { id: 4, feedname: 'testingthis4', startstop: 0, pause: '', config: ''}, { id: 5, feedname: 'testingthis5', startstop: 0, pause: '', config: ''}, { id: 6, feedname: 'testingthis6', startstop: 0, pause: '', config: ''}, { id: 7, feedname: 'testingthis7', startstop: 0, pause: '', config: ''} ] }); // reset store grid.setstore(newstore); // update grid info grid.model.store.setdata(newstore); // refresh gridx grid.body.refresh(); }

removing autoheight: true, solved problem.

javascript dojo dojo.gridx

Trouble with binary string in javascript above character code 128 -



Trouble with binary string in javascript above character code 128 -

so i'm trying create , save binary file locally in javascript using library: https://github.com/eligrey/filesaver.js/

it bit tricky because using gamemaker studio, , ways can interact javascript bit limited, here's setup.. other actual filesaver.js github repo, js code this:

var ildablob = new array(); toarray = function(argument0, argument1) { ildablob[argument0] = string.fromcharcode(argument1); homecoming 1; } save = function(argument0) { var blob = new blob(ildablob, {type: "application/octet-stream"}); saveas(blob, argument0); homecoming 1; }

basically, thought first fill array individual bytes using character codes create binary string, made blob , saved. works binary values below 128, not above, because of charset issue.. how can prepare this?

for example, if seek filling array incrementing 0-255, content of resulting binary file, can see after 128 bytes characters create 2 bytes each, not one, , it's wrong:

00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f 60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 71 72 73 74 75 76 77 78 79 7a 7b 7c 7d 7e 7f c2 80 c2 81 c2 82 c2 83 c2 84 c2 85 c2 86 c2 87 c2 88 c2 89 c2 8a c2 8b c2 8c c2 8d c2 8e c2 8f c2 90 c2 91 c2 92 c2 93 c2 94 c2 95 c2 96 c2 97 c2 98 c2 99 c2 9a c2 9b c2 9c c2 9d c2 9e c2 9f c2 a0 c2 a1 c2 a2 c2 a3 c2 a4 c2 a5 c2 a6 c2 a7 c2 a8 c2 a9 c2 aa c2 ab c2 ac c2 advertisement c2 ae c2 af c2 b0 c2 b1 c2 b2 c2 b3 c2 b4 c2 b5 c2 b6 c2 b7 c2 b8 c2 b9 c2 ba c2 bb c2 bc c2 bd c2 c2 bf c3 80 c3 81 c3 82 c3 83 c3 84 c3 85 c3 86 c3 87 c3 88 c3 89 c3 8a c3 8b c3 8c c3 8d c3 8e c3 8f c3 90 c3 91 c3 92 c3 93 c3 94 c3 95 c3 96 c3 97 c3 98 c3 99 c3 9a c3 9b c3 9c c3 9d c3 9e c3 9f c3 a0 c3 a1 c3 a2 c3 a3 c3 a4 c3 a5 c3 a6 c3 a7 c3 a8 c3 a9 c3 aa c3 ab c3 ac c3 advertisement c3 ae c3 af c3 b0 c3 b1 c3 b2 c3 b3 c3 b4 c3 b5 c3 b6 c3 b7 c3 b8 c3 b9 c3 ba c3 bb c3 bc c3 bd c3 be

instead of using string, you'd improve off using uint8array (meaning array of unsigned bytes in range 0–255); see https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/uint8array. example:

ildablob[argument0] = new uint8array(1); ildablob[argument0][0] = argument1; ... var blob = new blob(ildablob, {type: "application/octet-stream"});

also, incidentally — argument0 , argument1 terrible variable-names. mention you're constrained gamemaker; reason this? seems there should way prepare that.

javascript character-encoding binary blob

scala - Method that add and remove an element from a List -



scala - Method that add and remove an element from a List -

i'm writing method take list: list[(string, int)] , x:(string, int) , n: int parameters , homecoming list[(string, int)] list parameter represents input list, x element represents element add together list, n represents maximum dimension of list.

the method has next behavior:

first of check if list has n elements. if list has less n elements, method add together x elements list. otherwise if list contain elements less x, method remove minimum element list, , add together x element list.

i've implemented method following:

def method(list: list[(string, int)], x: (string, int), n: int) = { if(list.size < n) list :+ x else { var index = -1 var min = 10000000//some big number for(el <- 0 list.size) { if(list(el)._2 < x._2 && list(el)._2 < min) { min = list(el)._2 index = el } } if(index != -1) { val newlist = list.drop(index) newlist :+ x } else list } }

exist way express behavior in more clean way??

first, corrected version of posted (but appears, not intended)

def method(list: list[(string, int)], x: (string, int), n: int) = { if(list.size < n) list :+ x else { var index = -1 for(i <- 0 until list.size) { val el = list(i) if(el._2 < x._2) index = } if(index != -1) { val (before, after) = list.splitat(index) val newlist = before ++ after.tail newlist :+ x } else list } }

and tests

val l1 = list(("one", 1)) val l2 = method(l1, ("three", 3), 2) //> l2 : list[(string, int)] = list((one,1), (three,3)) val l3 = method(l2, ("four", 4), 2) //> l3 : list[(string, int)] = list((one,1), (four,4)) val l4 = method(l2, ("zero", 0), 2) //> l4 : list[(string, int)] = list((one,1), (three,3))

neater version (but still not meeting spec mentioned in comment op)

def method(list: list[(string, int)], x: (string, int), n: int) = { if (list.size < n) list :+ x else { val (before, after) = list.span(_._2 >= x._2) if (after.isempty) list else before ++ after.tail :+ x } }

another version removes minimum, if that's less x.

def method(list: list[(string, int)], x: (string, int), n: int) = { if (list.size < n) list :+ x else { val smallest = list.minby(_._2) if (smallest._2 < x._2) { val (before, after) = list.span(_ != smallest) before ++ after.tail :+ x } else list } }

and test results

val l1 = list(("one", 1)) val l2 = method(l1, ("three", 3), 2) //> l2 : list[(string, int)] = list((one,1), (three,3)) val l3 = method(l2, ("four", 4), 2) //> l3 : list[(string, int)] = list((three,3), (four,4)) val l4 = method(l2, ("zero", 0), 2) //> l4 : list[(string, int)] = list((one,1), (three,3))

but in comment, improve utilize method processes whole sequence of xs , returns top n.

list scala collections

php - Gmail Oauth API get messages count -



php - Gmail Oauth API get messages count -

the new gmail api allows message count total emails , unread emails within label. can't work , tried lots of things. it's connected oauth correctly can't count work. i'm using below code:-

$labelall = $service->users_labels->listuserslabels('me'); $labels = $labelall->getlabels(); foreach ($labels $label) { print 'label id: ' . $label->getid() . ', number of messages:'.$label->getmessagestotal().'<br/>';}

can help? lists labels correctly message count returns null.

thanks!

not fields set list() response--in case, have labels.get() on label care counts.

php google-oauth gmail-api

android - Sony Smartwatch 2 manage vibration on receiving notification -



android - Sony Smartwatch 2 manage vibration on receiving notification -

i'm using sony addon sdk develop notification app on smart watch 2.

i've managed work (watch vibrates when phone gets notification), havn't got way modify vibration length.

is there way manage vibration on receiving notification? in shorter vibration, longer vibration, etc..

the default vibration seem bit long, want modify it's length.

any help appreciated.

short answer: there no possibility configure vibration of standard notification, using notification api.

you can create custom vibration pattern, in smartwatch2 extension using command api. available after user starts extension, not notification purpose. start vibration pattern running extension, can use: controlextension.startvibrator(int onduration, int offduration, int repeats)

android sony sony-smartwatch

ruby - Puppet stdlib "range()" is not working as expected -



ruby - Puppet stdlib "range()" is not working as expected -

according puppet stdlib docs, range() supposed homecoming array of values. however, not appear working properly:

class rangetest { $r1 = range(1,5) $r2 = [1,2,3,4,5] if $r1 == $r2 { notify { "same" : } } else { notify { "not same" : } } }

the result of above test returns "not same". trying utilize function, difference(), takes 2 arrays arguments when seek this:

difference($r1,$r2) - assuming $r1 , $r2 have values above illustration

it returns: difference(): requires 2 arrays).

ruby node.js puppet

javascript - No result from a getJSON in cordova -



javascript - No result from a getJSON in cordova -

i have problem cordova app. have php page mini rest service json output , want utilize result in app.

php page:

<? header("content-type:application/json"); function response($status, $status_message, $data){ header("http/1.1 $status $status_message"); echo $data; } $link = mysqli_connect("db4free.net", "luigi", "nzor4csv4", "usl5"); if (mysqli_connect_errno()) { response(400, "failed connect mysql", mysqli_connect_error()); } if( !empty($_get['prestazioni']) ){ //make response using database $result = mysqli_query($link,"select distinct `ppasez_descrizione` `prestazioni`"); $arr = array(); while($obj = mysqli_fetch_assoc($result)) { $arr[] = $obj; } $message= json_encode($arr); response(200, "lista prestazioni", $message); } else { //invalid request response(400, "invalid request", null); } ?>

html page:

<html> <head> <meta charset="utf-8" /> <script type="text/javascript" src="cordova.js"></script> <link rel="stylesheet" href="js/libs/jquery-mobile/jquery.mobile.css" /> <script type="text/javascript" src="js/libs/jquery/jquery.js"></script> <script type="text/javascript" src="js/libs/jquery-mobile/jquery.mobile.js"></script> <script type="text/javascript" src="js/mainjs.js"></script> <script> $(document).ready(function(){ $.support.cors=true; $.mobile.allowcrossdomainpages = true; $("button").click(function(){ $.getjson('http://www.****.it/provaluigi/index.php?prestazioni=""',function(data){ $.each(data, function(i, dat){ $("ul").append("<li>"+dat.ppasez_descrizione+"</li>"); }); $('ul').listview('refresh'); //if $("list") $("list").listview("refresh); }); }); }); </script> <title> prestazioni </title> </head> <body> <section id="page1" data-role="page" data-fullscreen="true"> <div class="content" data-role="content"> <ul data-role="listview" data-filter="true" data-filterplaceholder="cerca prestazione"> </ul> </div> </section> </body>

this code work perfect on local domain can't see outcome 1 time inserted in cordova.

as can see insert:

$.support.cors=true; $.mobile.allowcrossdomainpages = true;

and

<access origin="*"/>

in config.xml permit cross domain request.

also when test in chrome "ripple extension" notice 2 error:

failed load resource http://localhost:8383/centri%20usl/config.xml

and.

failed load resource: net::err_empty_response http://localhost:8383/centri%20usl/cordova.js

so there errors in linking of cordova bundle utilize netbeans it's automatic. can help me find error?

thanks everyone

according phonegap documentation

the whitelisting rules found in res/xml/cordova.xml

try adding rule res/xml/cordova.xml

javascript php jquery json cordova

git - How do I get commits from a merged and reverted PR into a new one? -



git - How do I get commits from a merged and reverted PR into a new one? -

to create long story short, in next situation:

a feature branch created, worked on while collecting 30 commits, , merged master. merge reverted through github's web interface (by creating new pr reverted effects of old one).

now, have fixed problems caused revert merge, , i'd create new pr both of 30 or commits original pr , couple of more fix.

i've based feature-fix branch on (unmerged) head of feature branch, committed couple of times more , pushed create pr - reason, pr picks new commits, not old ones.

how include old commits in new pr?

i have force access repo (we're using shared repo model) operations don't require force-push master ok.

simplified git history:

* [feature-fix] <-- branch want pull | * [master] | * [merge revert pr] * |\ | | * [revert pr] * |/ <-- first commit included in new pr github | * [merge pr] |/| * | [feature] <-- original pr came | | * | <-- want these commits, included in old pr, included * | in new pr too. | | * | <-- started work on feature here. first commit want include. \| * <-- mutual ancestor between `feature-fix` , `master`, far can see

if understanding correctly need following.

git checkout master git revert sha_of_merge_revert_pr git merge feature-fix

the key step reverting commit reverted merge. sha removed changes, preserved merge history why seeing new commits.

you can read more linus himself here

git github merge pull-request

android - Socket.io client on Google Glass -



android - Socket.io client on Google Glass -

im trying allow google glass , android phone connect nodejs server im running on computer, can send messages android phone google glass.

for im using koush's androidasync library, works great on android phone , have absolutely no problem connecting phone nodejs server library.

however, same code doesnt seem work on google glass. google glass connect, because on connection eventhandler of nodejs server triggered, doesnt seem trigger of connectcallback functions on google glass.

here code im using in google glass app:

socketioclient.connect(asynchttpclient.getdefaultinstance(), "http://192.168.1.229:5000", new connectcallback() { @override public void onconnectcompleted(exception ex, socketioclient client) { log.i("socket", "connection completed"); if (ex != null) { ex.printstacktrace(); return; } client.setstringcallback(new stringcallback() { @override public void onstring(string string, acknowledge acknowledge) { log.d("socket", string); } }); client.setjsoncallback(new jsoncallback() { @override public void onjson(jsonobject jsonobject, acknowledge acknowledge) { log.d("socket", jsonobject.tostring()); } }); client.on("event", new eventcallback() { @override public void onevent(jsonarray jsonarray, acknowledge acknowledge) { log.i("data: ", jsonarray.tostring()); gson gson = new gson(); } }); mclient = client; } });

}

as can see, im trying log "connection completed" in "onconnectcompleted" function, never fires , nil ever logged.

i find rather strange, same code work on android phone , "connection completed" logged when run bit of code on android phone. strangest thing node server picks google glass on connection event triggered on server when glass connects.

so, can help me find out why google glass apparently connecting nodejs server, not triggering events when connects. (not triggering connectcallback functions, "connection completed" never logged)?

thanks in advance,

bram

i facing same issue here , noticed although glass showed connected wifi network, wasn't. tried adb shell netcfg on , surprise wlan0 interface had no ip assigned. reconnected wifi network 1 time again , started work fine.

the weird thing though expecting sort of error logged (even though using different socket.io client). believe case timeout didn't expire (connection/socket timeout) still attempting connect , didn't fail in time see log entry. guess these libraries have relatively high connection timeout set default, wouldn't see error before many seconds go by.

android node.js socket.io google-glass androidasync-koush

c# - HelloWorld example for sending an object over RabbitMQ via EasyNetQ between two different applications -



c# - HelloWorld example for sending an object over RabbitMQ via EasyNetQ between two different applications -

hi attempting send simple object through rabbitmq via easynetq. i'm having issues deserializing object on subscription side. able show me sample of how works. maintain in mind object beingness sent defined in it's own project , not shared among publisher , subscriber. here sample, , perhaps can tell me wrong it?

program a:

class programa { static void main(string[] args) { using (var bus = rabbithutch.createbus("host=localhost")) { console.writeline("press key send message"); console.readkey(); bus.publish(new messagea { text = "hello world" }); console.writeline("press key quit"); console.readkey(); } } public class messagea { public string text { get; set; } } }

program b:

class programb { static void main(string[] args) { using (var bus = rabbithutch.createbus("host=localhost")) { bus.subscribe<messageb>("", handleclusternodes); console.writeline("press key quit"); console.readkey(); } } private static void handleclusternodes(messageb obj) { console.writeline(obj.text); } [queue("testmessagesqueue", exchangename = "easynetqsample.programa+messagea:easynetqsample")] public class messageb { public string text { get; set; } } }

here error i'm receiving:

debug: handlebasicdeliver on consumer: f9ded52d-039c-411a-9b9f-5c8ee3301854, deliverytag: 1 debug: received routingkey: '' correlationid: 'ec41faea-a0c8-4ffd-8163-2cbf85d45fcd' consumertag: 'f9ded52d-039c-411a-9b9f-5c8ee3301854' deliverytag: 1 redelivered: false error: exception thrown subscription callback. exchange: 'easynetqsample.programa+messagea:easynetqsample' routing key: '' redelivered: 'false' message: {"text":"hello world"} basicproperties: contenttype=null, contentencoding=null, headers=[], deliverymode=2, priority=0, correlationid=ec41faea-a0c8-4ffd-8163-2cbf85d45fcd, replyto=null, expiration=null, messageid=null, timestamp=0, type=easynetqsample.programa+messagea:easynetqsample, userid=null, appid=null, clusterid=null exception: system.aggregateexception: 1 or more errors occurred. ---> easynetq.easynetqexception: cannot find type easynetqsample.programa+messagea:easynetqsample @ easynetq.typenameserializer.deserialize(string typename) @ easynetq.defaultmessageserializationstrategy.deserializemessage(messageproperties properties, byte[] body) @ easynetq.rabbitadvancedbus.<>c__displayclass19.<consume>b__18(byte[] body, messageproperties properties, messagereceivedinfo messagereceivedinfo) @ easynetq.rabbitadvancedbus.<>c__displayclass1e.<consume>b__1d(byte[] body, messageproperties properties, messagereceivedinfo receviedinfo) @ easynetq.consumer.handlerrunner.invokeusermessagehandler(consumerexecutioncontext context) --- end of inner exception stack trace --- ---> (inner exception #0) easynetq.easynetqexception: cannot find type easynetqsample.programa+messagea:easynetqsample @ easynetq.typenameserializer.deserialize(string typename) @ easynetq.defaultmessageserializationstrategy.deserializemessage(messageproperties properties, byte[] body) @ easynetq.rabbitadvancedbus.<>c__displayclass19.<consume>b__18(byte[] body, messageproperties properties, messagereceivedinfo messagereceivedinfo) @ easynetq.rabbitadvancedbus.<>c__displayclass1e.<consume>b__1d(byte[] body, messageproperties properties, messagereceivedinfo receviedinfo) @ easynetq.consumer.handlerrunner.invokeusermessagehandler(consumerexecutioncontext context)<---

what need able deserialize messagea?

as far know, default setting of easynetq requires type of serialized object consistent between applications. example, can send known .net type string:

bus.publish<string>("excellent.");

and happy on both projects.

you can utilize own message if set common library (dll). since specially mentioned reside in different projects, i'd suggest serialize , cast objects yourself.

easynetq uses interally newtonsoft json.net serialize objects this. can see, message has been serialized as:

message: {"text":"hello world"}

to yourself, still need add together reference json.net because easynetq hides reference using ilrepack.

this should work:

bus.publish<string>(jsonconvert.serializeobject(new messagea { text = "hello world" }));

and

bus.subscribe<string>("", handleclusternodes); private static void handleclusternodes(string obj) { var mymessage = (messageb)jsonconvert.deserializeobject<messageb>(obj); console.writeline(mymessage.text); }

but you'll lose attribute based routing , might want modify methods.

if want maintain using basic methods, can set topic this:

bus.publish<string>(jsonconvert.serializeobject(new messagea { text = "hello world" }), "topic.name"); bus.subscribe<string>("", handleclusternodes, new action<easynetq.fluentconfiguration.isubscriptionconfiguration>( o => o.withtopic("topic.name")));

but have complete control, need utilize advanced api;

var yourmessage = new message<string>(jsonconvert.serializeobject(new messagea { text = "hello world" })); bus.advanced.publish<string>(new exchange("yourexchangename"), "your.routing.key", false, false, yourmessage);

and on subscriber part:

iqueue yourqueue = bus.advanced.queuedeclare("anothertestmessagesqueue"); iexchange yourexchange = bus.advanced.exchangedeclare("yourexchangename", exchangetype.topic); bus.advanced.bind(yourexchange, yourqueue, "your.routing.key"); bus.advanced.consume<string>(yourqueue, (msg, info) => handleclusternodes(msg.body));

which same original rabbitmq c# client api.

detailed analysis:

the main problem exception:

easynetq.easynetqexception: cannot find type easynetqsample.programa+messagea:easynetqsample

this thrown easynetq because cannot find special class on endpoint.

if @ source code of typenameserializer.cs, see

var type = type.gettype(nameparts[0] + ", " + nameparts[1]); if (type == null) { throw new easynetqexception( "cannot find type {0}", typename); }

this tried find easynetqsample.programa.messagea type on second project, while knows easynetqsample.programb.messageb.

alternatively, can roll out own custom iserializer or set itypenameserializer default serializer haven't tried this.

c# rabbitmq easynetq