Monday 15 April 2013

how can I define functions in haskell using uppercase letters? -



how can I define functions in haskell using uppercase letters? -

this question has reply here:

how name haskell variables in physics uppercase 3 answers

for example, how can define function generate fibonacci numbers using uppercase letters this: fib n need phone call function terminal using uppercase letters this: fib 7

you can't. functions in haskell must start lowercase unicode characters or underscore. symbols origin upper case letter reserved types , constructors.

why need phone call function terminal using upper case letters? seems rather arbitrary constraint.

if really wanted read stdin , process that, suggest writing this

import system.io import text.read (readmaybe) import control.monad (forever) info operation = fib integer | fac integer | add together integer integer deriving (read) -- read instance of import here fib :: integer -> integer fib 0 = 1 fib 1 = 1 fib n = fib (n - 1) + fib (n - 2) eval :: operation -> integer eval (fib n) = fib n eval (fac n) = product [1..n] eval (add b) = + b repl :: io () repl = forever loop parseresponse :: string -> string parseresponse resp = case readmaybe resp of op -> show $ eval op nil -> "invalid operation" loop = putstr "> " resp <- getline putstrln $ parseresponse resp main :: io () main = hsetbuffering stdin linebuffering hsetbuffering stdout nobuffering repl

this allows user type in exact name of info constructor, interpret info constructor (yes, entire code simple interactive scripting language can fibs, factorials, , addition) result. if invalid operation typed in, respond invalid operation. can quit interpreter ctrl-c.

function haskell

algorithm - Matching an element from a set of abstracts to an element in set of titles -



algorithm - Matching an element from a set of abstracts to an element in set of titles -

suppose have 2 sets,

a = {"this title", ...} b = {"this short description of title a", ...}

what best way find best match in set b element in set a, or vice versa. approach tried create tf-idf handbag of words vector space using tokens of b, , finding cosine similarity. given a, pair (a,b) selected if cosine similarity higher other element b. not accurate.

are there improve methods this? how can improve accuracy?

from sklearn.feature_extraction.text import tfidfvectorizer sklearn.metrics.pairwise import cosine_similarity # titles , abstracts arrays of strings tfidf = tfidfvectorizer(stop_words='english', analyzer='word') vec = tfidf.fit_transform(abstracts) def predict(title): titlevec = tfidf.transform([title]) sim = cosine_similarity(titlevec,vec) homecoming np.argmax(sim) i, title in titles: index = predict(title) print "title: {0}\nabstracts:{1}".format(title,abstracts[index])

algorithm machine-learning nlp information-retrieval tf-idf

c# - Twilio Test Credentials: WaitingForActivation when I try to purchase a number? -



c# - Twilio Test Credentials: WaitingForActivation when I try to purchase a number? -

i have next code:

public void purchasenumber(string username, string phonenumber) { var twilio = new twiliorestclient(accountsid, authtoken); var options = new phonenumberoptions { voiceurl = "", phonenumber = "+15005550006" }; var number = twilio.addincomingphonenumber(options); console.writeline(number.id); // sid not available return; }

two issues - number.sid not available, samples display, , number.status shows "waitingforactivation". doing wrong?

update: happens 'unavailable' number, not 'valid , available' one. usage of magic numbers available trial accounts? am using sid , token https://www.twilio.com/user/account/developer-tools/test-credentials page.

this happens if alter 1 of characters of sid - seems sid invalid, despite grabbing straight off of /developer-tools page.

final update - because using prerelease version of twilio nuget package. uninstalled , installed non-prerelease version , sid became available , started working.

final update - because using prerelease version of twilio nuget package. uninstalled , installed non-prerelease version , sid became available , started working.

c# twilio

bash - Use tr to remove line breaks in multiple files? -



bash - Use tr to remove line breaks in multiple files? -

i have set of several hundred .txt files analyzing (ngram analysis using nsp), , need remove line breaks each file. can 1 @ time using tr:

$ tr -d "\n\r" < input1.txt > output1.txt

how can entire directory of files @ once?

this add together -out before .txt. haven't specified filenames like, other .txt, don't have input files named foo-out.txt, etc.

for f in *.txt tr -d "\n\r" < $f > $(basename $f .txt)-out.txt done

bash for-loop newline tr file-manipulation

java - IResourceChangeEvent - how to identify a project delete/rename -



java - IResourceChangeEvent - how to identify a project delete/rename -

how can distinguish, within iresourcechangelistener added via resourceplugin.getworkspace().addresourcechangelistener(...) project deleted / renamed?

through trying things out, seem iresourcechangeevent.getdelta() -> iresourcedelta answer.

from eclipse api:

after-the-fact batch reports of arbitrary creations, deletions , modifications 1 or more resources expressed hierarchical resource delta. event type post_change, , getdelta returns hierarchical delta. resource delta rooted @ workspace root. these events broadcast interested parties after set of resource changes , happen whether or not autobuilding enabled. workspace closed alter during notification of these events. delta reported in event cycle identical across listeners registered type of event.

edit: adding findings far

so, event.gettype() post_change , there needs either

a delta contains kid iresourcedelta has getkind() == removed deletion, , delta getresource().gettype() == project know it's project ( iresourcedelta should not have children )

a getdelta() contains 2 children iresourcedelta have getkind() == removed , getkind() == added, getresource().gettype() == project, , iresourcedelta contain no children deltas (i've observed when file renamed/deleted, iproject resource belongs 1 on first row of children of parent delta...)

can confirm supposition? if necessary tree depth search children realize if event of project rename/delete or file/folder?

you need add together resource alter listener via resourceplugin.getworkspace().addresourcechangelistener(listener, iresourcechangeevent.post_change)

in listener, utilize iresourcedeltavisitor visit changes in delta via event.getdelta().accept(...)

the visitor should projects removed

if expecting project removed , created same name (as happens files & folders during build events), in add-on removed, replaced in delta

java eclipse eclipse-rcp eclipse-plugin

fortify - HP WebInspect command line interface ( CLI) -



fortify - HP WebInspect command line interface ( CLI) -

can please guide me webinspect cli .

i need invoke dynamic code analyzer:webinspect ( penetration testing ) teamcity (tc) .

once know command line invocations webinspect , write in wrapper script , invoke wrapper script tc before build step.

thanks, vishal

there 2 ways access command line switches drive cli behavior. first alternative invoke wi.exe "-?" argument , see explanations of each switch. sec alternative open webinspect help file (webinspect.chm) , type next text in search tab text entry field: "wi.exe"

the help file can launched hitting f1 within running webinspect ui or windows start menu under "all programs > hp > hp webinspect > help > webinspect"

fortify

servlets - JavaMail: inline images generated incorrectly -



servlets - JavaMail: inline images generated incorrectly -

i coded servlet below generates response email in .eml format (using javamail). browser detects mime type , opens email app (microsoft live in case) when response received. "x-unsent" set "1" when email opened can edited , sent.

the email content html image inline. when open generated email can see content no issues. when come in address , seek send email message "one or more images not found, want continue?". send anyways , when check business relationship of email recipient email received instead of having image inline, attached. seems wrong way inline images generated. ideas?

protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { response.setcontenttype("message/rfc822"); response.setheader("content-disposition", "attachment; filename=\"email.eml\""); printwriter out = response.getwriter(); string eml = null; seek { message message = new mimemessage(session.getinstance(system.getproperties())); message.addheader("x-unsent", "1"); message.setsubject("email inline image"); // mail service has 2 parts, body , embedded image mimemultipart multipart = new mimemultipart("related"); // first part (the html) bodypart messagebodypart = new mimebodypart(); string htmltext = "<h1>this image: </h1><img src=\"cid:image\">"; messagebodypart.setcontent(htmltext, "text/html"); multipart.addbodypart(messagebodypart); // sec part (the image) messagebodypart = new mimebodypart(); string filepath = "c:/image.png"; datasource fds = new filedatasource(filepath); messagebodypart.setdatahandler(new datahandler(fds)); messagebodypart.setheader("content-type", "image/png"); messagebodypart.setheader("content-id", "image"); messagebodypart.setdisposition( mimebodypart.inline ); // add together image multipart multipart.addbodypart(messagebodypart); // set message.setcontent(multipart); bytearrayoutputstream os = new bytearrayoutputstream(); message.writeto(os); eml = new string(os.tobytearray(),"utf-8"); } grab (messagingexception e) { e.printstacktrace(); } grab (ioexception e) { e.printstacktrace(); } out.print(eml); out.flush(); out.close(); }

try simpler version might prepare problem:

// first part (the html) mimebodypart messagebodypart = new mimebodypart(); string htmltext = "<h1>this image: </h1><img src=\"cid:image\">"; messagebodypart.settext(htmltext, null, "html"); multipart.addbodypart(messagebodypart); // sec part (the image) messagebodypart = new mimebodypart(); string filepath = "c:/image.png"; messagebodypart.attachfile(filepath, "image/png", "base64"); messagebodypart.setcontentid("<image>"); // add together image multipart multipart.addbodypart(messagebodypart);

servlets javamail

java - Jar cron job not running (runs manually) -



java - Jar cron job not running (runs manually) -

first time using cron jobs , im relatively new linux , cant seem work, works fine if manually run in command line not cron job.

i set this:

contrab -e insert mode */3 * * * * root (cd /home/ec2-user/; java -jar feedpuller-1.jar) (every 3 minutes test) save , quit it says has created new cron job tab

now when crontab -l job there, , when simple command "cd /home/ec2-user/; java -jar feedpuller-1.jar" runs , when check cron log in /var/log/ has

oct 10 00:30:34 ip-172-31-29-33 crontab[28934]: (root) begin edit (root) oct 10 00:33:25 ip-172-31-29-33 crontab[28934]: (root) replace (root) oct 10 00:33:25 ip-172-31-29-33 crontab[28934]: (root) end edit (root) oct 10 00:33:48 ip-172-31-29-33 crontab[28937]: (root) list (root) oct 10 00:34:01 ip-172-31-29-33 crond[28932]: (root) bad file mode (/etc/cron.d/0hourly) oct 10 00:34:01 ip-172-31-29-33 crond[28932]: (root) bad file mode (/etc/cron.d/update-motd) oct 10 00:36:01 ip-172-31-29-33 crond[28942]: (root) cmd (root (cd /home/ec2-user/; java -jar feedpuller-1.jar)) oct 10 00:39:01 ip-172-31-29-33 crond[28949]: (root) cmd (root (cd /home/ec2-user/; java -jar feedpuller-1.jar)) oct 10 00:42:01 ip-172-31-29-33 crond[29041]: (root) cmd (root (cd /home/ec2-user/; java -jar feedpuller-1.jar))

so means running right? when check local database (that jar should writing to) nil beingness written (if run jar cd /home/ec2-user/; java -jar feedpuller-1.jar writes database no problem)

apologies, lack of understanding of cron jobs , linux in general causing me create basic error.

in cron tab ive changed to

*/30 * * * * java -jar /home/ec2-user/feedpuller-1.jar

and working fine

java jar amazon-ec2 cron

ios - Topview Controller for UITabBar -



ios - Topview Controller for UITabBar -

i have table view displays parent folder details. when select row want display contents of corresponding kid folder has 2 windows using tab bar controller - 1 display table of details , 1 display graph.

the issue code have found @ topviewcontroller uitabbar not able display contents @ selected index path rather fixed index of 0 or whatever number manually input. may wrong affecting result of displaying, not sure.

my code works fine displaying right content in immediate window sec window linked tab bar controller doesn't display @ all. have swapped windows , same issue - first window displays, sec not.

this prepare segue code:

-(void)prepareforsegue:(uistoryboardsegue *)segue sender:(id)sender{ if ([[segue identifier] isequaltostring:@"showfiledetails"]){ uinavigationcontroller * navigate = segue.destinationviewcontroller; //create reference index path nsindexpath * indexpath = [self.tableview indexpathforselectedrow]; filedetailsvc * filedetails = (filedetailsvc *)[navigate.viewcontrollers objectatindex: 0]; //create reference parent folder beingness selected parentfile * selectedfile = (parentfile*)[self.fetchedresultscontroller objectatindexpath:indexpath]; //reference the next view filedetails.selectedfile = selectedfile; } }

i have tried utilize "indexpath" in [navigate.viewcontrollers objectatindex: ]; , changed objectatindex objectatindexpath gives error message of "incompatible pointer integer..." , "no visible @interface 'nsarray' declares selector 'objectatindexpath'".

hopefully it's nil hard solve. thanks.

segue's destination controller uitabbarcontroller rather uinavigationcontroller. didn't set datasource view controller in other tab, don't see anything.

uitabbarcontroller * tabbarcontroller = segue.destinationviewcontroller; viewcontrollerfortabitem2 * controller = (viewcontrollerfortabitem2 *)[tabbarcontroller.viewcontrollers objectatindex:1]; controller.datasource = selectedfile;

ios objective-c iphone ipad

foreign keys - 3NF Normalization justification -



foreign keys - 3NF Normalization justification -

3nf. trying justify normalization process. have unique identifiers/ dummy keys (as pk) tables, foreign keys on many side of 1 many relationships. these fks, have dependent on pk qualify 3nf note: other non-key attributes dependent on pk

student {@student_id, student_name, teacher*} teacher {@staff_no, teacher_name, subject} lecture {@lecture_no, start_date, motivation, staff_no*, student_id*}

taking lecture entity example, other attributes dependent on "@lecture_no".

do foreign keys (staff_no , student_id) need dependent on pk qualify 3nf?

thanks

foreign-keys database-normalization 3nf

php - Yii Can't Run Well After hosted -



php - Yii Can't Run Well After hosted -

anyone can help me? create website yii, when run in localhost runs well, after upload using different server yii::app()->request->baseurl; , command of yii can't read. example: localhost type yii::app()->request->baseurl;, can result project name. show /coretankuyii../images/fahrudin.jpg. when utilize different server name of project can't read, results ../images/fahrudin.jpg. whats cause?

php yii

algorithm - Fibonacci algortihm to find if a number(or a close neighbour) is the difference between 2 fibonacii numbers -



algorithm - Fibonacci algortihm to find if a number(or a close neighbour) is the difference between 2 fibonacii numbers -

i hope can help me. given number n(which not necessary fibonacci number), must find if number equal difference between 2 fibonacci numbers, if not must homecoming closest number n, let's phone call m(which not necessary fibonacci number), difference between 2 fibonnaci numbers.

i not looking exact algorithm implementation pointers at.

thank in advance

assume without much loss of generality n > 0. since 1 = 1 - 0 = fib(1) - fib(0), result m positive well. allow 0 ≤ < j , consider fib(j) - fib(i). have bounds

fib(j-2) = fib(j) - fib(j-1) ≤ fib(j) - fib(i) ≤ fib(j).

therefore, each n, possibilities fib(j-2) ≤ n ≤ fib(j) need considered. in fact, can tighten fib(j-2) < n ≤ fib(j), since can write fib(j) - fib(j-1) fib(j-2) - fib(0). compute logarithm/use binary search find 2 valid settings of j. each setting of j, find best value of i same way.

algorithm math fibonacci

vba - Does point have value properties -



vba - Does point have value properties -

when searching, recognized previous post: change point color in chart excel vba. said can value of point in chart using this: .points(pointnumber).value. point have value property? time , help.

no, see http://msdn.microsoft.com/en-us/library/office/aa174283(v=office.11).aspx?query=point+object+vba

what want values or xvalues of series, see http://msdn.microsoft.com/en-us/library/office/ff840677(v=office.15).aspx

vba point

string - Java \n line separator not working -



string - Java \n line separator not working -

i creating application has info log. build info string add together everytime application receives info , display in edittext box. problem having display info without new lines. basic illustration of code:

string logtext; edittext etlog; logtext = info + "\n" + logtext; etlog.settext(logtext);

know can utilize nl = system.getproperty("line.separator"); new line i'm puzzled why "\n" not working when i've used in different apps i've created before. thanks

not overly keen on answering own question solved changing inputtype of edittext textmultiline in xml code. xml code:

android:inputtype="textmultiline"

allows edittext create utilize of "\n" within string.

java string performance syntax newline

binding - BIRT report, how to bind currency property on a dataset to the number formatting of a label -



binding - BIRT report, how to bind currency property on a dataset to the number formatting of a label -

i creating bill in birt. have created template already, , have played around having column , heading indicate currency.

however have currency part of row formatting, in other words this:

$ 120,000.00

the currency ($) read database, , have part of dataset can used parameter. problem - not know if parameter can somehow bound formatting of label?

kind regards, harriet

this quite straight building dynamic number format. in eclipse designer, click info element containing currency number formatted -> script tab -> oncreate

for example, come in script (assuming dataset column containing currency named "currency"):

this.getstyle().numberformat=row["currency"]+" ###,##0.00 ";

binding report currency birt number-formatting

prevent a method from returning null java -



prevent a method from returning null java -

i have greetingloop called on switch case in main(), , if returns null, user input asked 1 time doesnt anything. trying avoid greetingloop() returning null, set homecoming variable userinput in if statement, isnt recognized eclipse "this method must homecoming type of int."

any hints appreciated, thanks.

public static int greetingloop(){ int userinput=0; try{ system.out.println("please come in desired operation:"); system.out.println("1.insert, 2.delete, 3.edit, 4.show, 5.list, 6.volume, 7.exit\n"); userinput=integer.parseint(joptionpane.showinputdialog("please come in desired operation:")); } grab (numberformatexception ne){ system.out.println("your input " + userinput + " not valid. please seek again...\n"); } if(userinput >= 1 && <= 7){ homecoming userinput; } }

this because not returning in case if status predicate false

add return userinput; after } of if statement

at rate, cannot ever homecoming null in current method because homecoming type primitive int , homecoming int value.

so, in case if add together return userinput; lastly line in method, homecoming initialized value 0

java methods null return

c++ - Stack.Pop() using LinkedList -



c++ - Stack.Pop() using LinkedList -

just know homework problem , have spent hours trying figure little thing out. pop() won't work. current code pop():

stackelement stack::pop(){ position temp; temp = stack.currententry(); stack.delete(); homecoming temp;}

i using delete() linked list based delete() function goes this:

void linkedlist::delete(){ if (current == first && atend()){ // remove memory allocation element's info delete &current->data; // reset values of linked list original (null) state current = null; pred = null; first = null; } else // checks if current element first node in lists if (current == first){ // create new first element next element first = current->next; // remove memory allocation element's info delete &current->data; // new current entry successor of deleted node. current = first; } // when element you're deleting not first node in list else{ assert(!empty()); // temporary node prevent current beingness marroned node *tempnode = current->next; pred->next = tempnode; // remove memory allocation element's info delete &current->data; current = tempnode; } }

when compile, throws me error right here:

unhandled exception @ 0x003e5f79 in program5_test.exe: 0xc0000005: access violation writing location 0xf495ee12.

any help appreciated.

you didn't show currententry, bet returns pointer instead of making total copy. delete original leaving pointer pointing @ nothing. crashes when utilize pointer returned pop.

c++ linked-list stack pop

PHP - Recalling information stored in database using sessions -



PHP - Recalling information stored in database using sessions -

i've got problem when using sessions recall info stored in mysql database. code:

the login page simple, input username , password kind (i know password still plaintext, plan alter later).

<?php $host="localhost"; $user="root"; $pass=""; $db_name="proyek"; $tbl_name="murid"; mysql_connect("$host", "$user", "$pass")or die("cannot connect sql."); mysql_select_db('$db_name'); ?> <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title></title> </head> <body> <div id="header"> logo <h1 align="center">title</h1> </div> <br/> <div id="login"> <form id="loginform" name="loginform" method="post" action="checklogin.php"> <table border="0" align="center"> <tr> <td>nis</td> <td></td> <td><input type="text" name="nislogin" id="nislogin"/></td> </tr> <tr> <td>password</td> <td></td> <td><input type="password" name="pwdlogin" id="pwdlogin"/></td> </tr> <tr> <td colspan="3" align="center"><input type="submit" name="loginbutton" id="loginbutton" value="login"/></td> </tr> </table> </form> </div> </body> </html>

and code login check page:

<?php session_start(); $host="localhost"; $user="root"; $pass=""; $db_name="proyek"; $tbl_name="murid"; mysql_connect("$host", "$user", "$pass")or die("cannot connect sql."); mysql_select_db('$db_name'); $nis=($_post['nislogin']); $pwd=($_post['pwdlogin']); $sql="select * murid nis='$nis' , password='$pwd'"; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count==1) { $_session['nislogin']=$nis; $nama=$result['nama']; $_session['nama']=$nama; header("location:index.php"); homecoming true; exit; } else { echo("wrong nis or password."); homecoming false; } ?>

i have entered dummy info in database testing purposes; id, password, name. how can recall database while user login username/id?

i'd display 'hello, name' in next page. help appreciated.

edit: i've edited code based on feedbacks , produces blank; 'hello,' no name.

first of all, since running query on login check page, utilize value session rather post data. also, whenever redirecting, exit script.

edit:

since in development stage, need display error if query fails know why. realized need homecoming associative array access row. seek this.

$sql="select * murid nis='$nis' , password='$pwd'"; $result=mysql_query($sql); if (!$result) { die('invalid query: ' . mysql_error()); } $count=mysql_num_rows($result); if($count==1) { $data=mysql_fetch_assoc($result); // since accessing 1 row, // otherwise set in loop build array. session_start(); $_session['nislogin']=$data['nis']; header("location:index.php"); homecoming true; exit; }

i see session on login page, don't see ever created , don't see purpose.

if(isset($_session['nama'])) { unset($_session['nama']); }

basically need here, start session on index.php , output it.

index.php

session_start(); if(isset($_session['nislogin'])) { $name = $_session['nislogin']; } else { $name = "stranger"; } <body> welcome, <?=$name?> </body>

php session

excel - Create named range with cells where value matches? -



excel - Create named range with cells where value matches? -

i have table 2 columns:

employee company 970423-4829 vete 970212-2398 alfalaval 970212-2398 delaval 970423-4829 verktyg 970423-4829 verktyg 960822-7587 arla 970423-4829 test3 961225-7590 test 970911-1287 kamel 970911-1287 kanel

i want create named range contains company lines employee.

if "employee" 970212-2398, want range be

alfalaval delaval

if "employee" 970911-1287, want range be

kamel kanel

is possible using excel and/or vba?

there seems dissenting comments suggest improve off solution looked ideal sub scripting.dictionary object , work them here go.

sub create_employee_named_ranges() dim n long, r long, vemp variant dim demps new scripting.dictionary demps.comparemode = textcompare activesheet r = 2 .cells(rows.count, 1).end(xlup).row if not demps.exists(.cells(r, 1).value) demps.add key:=.cells(r, 1).value, _ item:=chr(39) & .name & chr(39) & chr(33) & .cells(r, 2).address else demps.item(.cells(r, 1).value) = _ demps.item(.cells(r, 1).value) & chr(44) & chr(39) & .name & chr(39) & chr(33) & .cells(r, 2).address end if next r end activeworkbook n = 1 .names.count if left(.names(n).name, 4) = "enr_" _ .names(n).delete next n each vemp in demps .names.add name:="enr_" & replace(vemp, chr(45), chr(95)), _ refersto:=chr(61) & demps.item(vemp) next vemp end demps.removeall: set demps = nil end sub

you have go vbe's tools, references , add together microsoft scripting runtime list. note not utilize actual employee identifier dashes illegal characters in name of named range (probably due utilize in subtraction) replaced them underscores.

excel vba excel-vba

javascript - Adding a service to a controller in angular -



javascript - Adding a service to a controller in angular -

i've tried build service returns formatted date, works when set in controller need in lot of places thought i'd build service. when seek inject service in controller gives me unknown provider issue..

unknown provider: dateprovider <- date <- displaydate

current code:

services.js

angular.module('starter.services', []) .factory('displaydate',['date','$filter', function(date, $filter) { var actiondate = new date(date); var today = new date(); if(today.getdate() == actiondate.getdate()){ var hourssince = today.gethours() - actiondate.gethours() var minutessince = today.getminutes() - actiondate.getminutes() var secondssince = today.getseconds() - actiondate.getseconds() if(hourssince > 0){ date = hourssince+'u'; }else if(minutessince > 0){ date = minutessince+'m'; }else{ date = secondssince+'s'; } }else{ var oneday = 24*60*60*1000; // hours*minutes*seconds*milliseconds var diffdays = math.round(math.abs((today.gettime() - actiondate.gettime())/(oneday))); if(diffdays > 28){ var identifier = actiondate.getmonth(); date = $filter('date')(actiondate,"d "+ maandarray[identifier] + " yy " + " hh:" + "mm"); }else{ date = diffdays+'d'; } } homecoming date; }]);

controller.js

angular.module('starter.controllers', ['google-maps'.ns(),'starter.services']) .controller('volgendctrl', function($scope, displaydate) { var date = displaydate(value[4]); })

app.js

var starter = angular.module('starter', ['ionic','starter.services', 'starter.controllers' ,'ngcordova']) starter.config(function($stateprovider, $urlrouterprovider,$httpprovider, $ionicconfigprovider) { $ionicconfigprovider.prefetchtemplates(true); $urlrouterprovider.otherwise('/tab/volgend'); $stateprovider // setup abstract state tabs directive .state('tab', { url: "/tab", abstract: true, templateurl: "templates/tabs.html" }) .state('tab.volgend', { url: '/volgend', views: { 'volgend': { templateurl: 'templates/volgend.html', controller: 'volgendctrl', } } }) // home states , nested views ======================================== }); starter.run(function($ionicplatform) { $ionicplatform.ready(function() { // hide accessory bar default (remove show accessory bar above keyboard // form inputs) if(window.cordova && window.cordova.plugins.keyboard) { cordova.plugins.keyboard.hidekeyboardaccessorybar(true); } ionic.platform.isfullscreen = true }); })

can explain me why it's not working expected?

if 'date', thing inject in displaydate in fact seek , phone call displaydate in controller, , not service, should not inject way do. should inject $filter , mill function homecoming function takes 'date' parameter , in function calculation.

angular.module('starter.services', []) .factory('displaydate',['$filter', function($filter) { homecoming function (date){ var actiondate = new date(date); var today = new date(); if(today.getdate() == actiondate.getdate()){ var hourssince = today.gethours() - actiondate.gethours() var minutessince = today.getminutes() - actiondate.getminutes() var secondssince = today.getseconds() - actiondate.getseconds() if(hourssince > 0){ date = hourssince+'u'; }else if(minutessince > 0){ date = minutessince+'m'; }else{ date = secondssince+'s'; } }else{ var oneday = 24*60*60*1000; // hours*minutes*seconds*milliseconds var diffdays = math.round(math.abs((today.gettime() - actiondate.gettime())/(oneday))); if(diffdays > 28){ var identifier = actiondate.getmonth(); date = $filter('date')(actiondate,"d "+ maandarray[identifier] + " yy " + " hh:" + "mm"); }else{ date = diffdays+'d'; } } homecoming date; } }]);

javascript angularjs service ionic-framework

Find given day of supplied date's week in Excel -



Find given day of supplied date's week in Excel -

i have dates in column, , to, using dates in column i.e produce first column, based on in second

week starting date 01/11/2009 01/11/2009 01/11/2009 02/11/2009 01/11/2009 03/11/2009 01/11/2009 04/11/2009 01/11/2009 05/11/2009 01/11/2009 06/11/2009 01/11/2009 07/11/2009 08/11/2009 08/11/2009 08/11/2009 09/11/2009 08/11/2009 10/11/2009 08/11/2009 11/11/2009 08/11/2009 12/11/2009 08/11/2009 13/11/2009 08/11/2009 14/11/2009 15/11/2009 15/11/2009 15/11/2009 16/11/2009 15/11/2009 17/11/2009 15/11/2009 18/11/2009 15/11/2009 19/11/2009 15/11/2009 20/11/2009 15/11/2009 21/11/2009 22/11/2009 22/11/2009 22/11/2009 23/11/2009 22/11/2009 24/11/2009

is there formula this?

weekday returns index number day of week, can utilize next start of week:

=b1-(weekday(b1)-1)

excel

python - Using Django CBV's without overriding get_context_data -



python - Using Django CBV's without overriding get_context_data -

is there anyway can take advantage of django's default cbv's without resulting super calls on get_context_data send pieces of info.

for instance, have site cbv's handle 99% of work on own, i'd send minor bits of static info such page titles , seems unnecessary utilize get_context_data accomplish this.

i'm aware can following:

class page(detailview): model: mymodel template_name: 'something.html' title: 'some page title'

and reference title in template view.title. i'd page title attribute of model. i'm able through following:

get_context_data(self, **kwargs): context = super(page, self).get_context_data(**kwargs) context['title'] = 'page title | %s' % (self.get_object().title) homecoming context

is possible me reference individual model beingness called in detail view without running query or using get_context_data can model's title attribute , utilize access view.title in template?

i can't see reason define method title. whole point of detailview have access object in template, via {{ object }}. why not {{ object.title }}?

python django

How to make 2D scatter plot in Matlab with colors depending on values? -



How to make 2D scatter plot in Matlab with colors depending on values? -

i have 3 vectors of same lenght: x, y, , cls. want create 2d plot of x , y each point should have color corresponding value of cls.

i thought using scatter function can chage color of whole plot, not of particular elements. ideas?

i in example, when cls has elements of 3 values:

from help of scatter:

scatter(x,y,a,c) specifies circle colors. plot circles same color, specify c single color string or rgb triplet. utilize varying color, specify c vector or three-column matrix of rgb triplets.

you can build c

c=zeros(size(x),3); c(cls==1,:)=[1 0 0]; % 1 reddish % ... scatter(x,y,1,c)

however, dont know how background. did apply machine learning algorithm clasify data? maybe can equations plot background there, depends on method.

matlab plot

html - Can't set initial value of input element with type="time" in Chrome -



html - Can't set initial value of input element with type="time" in Chrome -

i chrome gives masking/format automatically when utilize type="time" attribute/value. can't seem set initial value control.

this:

<input type="time" value="05:00 pm" />

just renders blank (with masking) in chrome. , when form submitted, submits blank.

i'm guessing has format of string setting in value. don't know right format (and why format used wouldn't work - seems reasonable time format me).

here's jsfiddle play in case want it.

any suggestions?

try like:

<input type="time" value="17:00:00" />

read this.

html html5 google-chrome html-input

sql - How to copy data from binary CSV file to local Access Database without saving file on computer? -



sql - How to copy data from binary CSV file to local Access Database without saving file on computer? -

i'm new adodb objects. not sure if possible should possible, have medium-sized csv file automatically download url , upload selected local access database.

i can store csv info in adodb.stream object, how proceed upload local access database, create new table , insert info , delimit data?

my code far

dim httpreq xmlhttp60: set httpreq = new xmlhttp60 dim adobstream adodb.stream: set adobstream = new adodb.stream temp = http://ichart.finance.yahoo.com/table.csv?s=alfa.st&a=4&b=24&c=2010&d=9&e=27&f=2013&g=d&ignore=.csv` httpreq.open "get", temp, false httpreq.send until httpreq.readystate = 4 doevents loop dim splitticker() string: splitticker = split(stock, ".") ' splits ticker name dim xpath string: xpath = "c:\**path***" & splitticker(0) & date & ".csv" ' import straight access database delimits , adds primary keys info ' no need save file on computer in case adobstream .open .type = adtypebinary .write httpreq.responsebody .savetofile (xpath) ' create error handling specified c:\ generates error .close end set httpreq = nil set adobstream = nil

sql vba csv access-vba

c - OpenCL Kernel for String Concatenation -



c - OpenCL Kernel for String Concatenation -

i haven't found much literature or examples of performing operations on strings gpu. specifically, have 2 arrays of strings , need concatenate elements of 2nd array corresponding elements of 1st array. cannot figure out how write kernel this.

an illustration of concatenation in c be:

#include <stdio.h> void concatenate_string(char*, char*, char*); int main() { char original[100], add[100], result[100]; printf("enter source string\n"); scanf("%s", original); printf("enter string concatenate\n"); scanf("%s", add); concatenate_string(original, add, result); printf("string after concatenation \"%s\"\n", result); homecoming 0; } void concatenate_string(char *original, char *add, char *result) { while(*original) { *result = *original; original++; result++; } while(*add) { *result = *add; add++; result++; } *result = '\0'; }

below opencl host code containing kernel. kernel follows same flow concatenate_string function above. programme executes successfully, gives me no output.

#include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef __apple__ #include <opencl/cl.h> #else #include <cl/cl.h> #endif #include <ocl_macros.h> #include <iostream> #include <string> //common defines #define vendor_name "amd" #define device_type cl_device_type_gpu #define vector_size 1024 using namespace std; //opencl kernel run every work item created. //the below const char string compiled runtime complier //when programme object created clcreateprogramwithsource //and built clbuildprogram. const char *concat_kernel = "__kernel \n" "void concat_kernel( \n" " __global uchar *d, \n" " __global uchar *e, \n" " __global uchar *f) \n" "{ \n" " //get index of work-item \n" " int index = get_global_id(0); \n" " while(d[index]) \n" " { \n" " *f[index] = *d[index]; \n" " d[index]++; \n" " f[index]++; \n" " } \n" " while(e[index]) \n" " { \n" " *f[index] = *e[index]; \n" " e[index]++; \n" " f[index]++; \n" " } \n" " *f[index] = '\0'; \n" "} \n"; int main(void) { cl_int clstatus; //keeps track of error values returned. // platform , device info cl_platform_id * platforms = null; // set platform. take @ macros used in file. // these defined in common/ocl_macros.h ocl_create_platforms( platforms ); // devices list , take type of device want run on cl_device_id *device_list = null; ocl_create_device( platforms[0], device_type, device_list); // create opencl context devices in device_list cl_context context; cl_context_properties props[3] = { cl_context_platform, (cl_context_properties)platforms[0], 0 }; // opencl context can associated multiple devices, either cpu or gpu // based on value of device_type defined above. context = clcreatecontext( null, num_devices, device_list, null, null, &clstatus); log_ocl_error(clstatus, "clcreatecontext failed..." ); // create command queue first device in device_list cl_command_queue command_queue = clcreatecommandqueue(context, device_list[0], 0, &clstatus); log_ocl_error(clstatus, "clcreatecommandqueue failed..." ); // allocate space vectors d, e, , f string *d = (string*)malloc(sizeof(string)*vector_size); string *e = (string*)malloc(sizeof(string)*vector_size); string *f = (string*)malloc(sizeof(string)*vector_size); for(int = 0; < vector_size; i++) { d[i] = ".25_numstring"; } for(int = 0; < vector_size; i++) { e[i] = "string_2"; f[i] = "0"; } // create memory buffers on device each vector cl_mem d_clmem = clcreatebuffer(context, cl_mem_read_only, vector_size * sizeof(string), null, &clstatus); cl_mem e_clmem = clcreatebuffer(context, cl_mem_read_only, vector_size * sizeof(string), null, &clstatus); cl_mem f_clmem = clcreatebuffer(context, cl_mem_write_only, vector_size * sizeof(string), null, &clstatus); // re-create buffer d , e device. blocking write device buffer. clstatus = clenqueuewritebuffer(command_queue, d_clmem, cl_true, 0, vector_size * sizeof(string), d, 0, null, null); log_ocl_error(clstatus, "clenqueuewritebuffer failed..." ); clstatus = clenqueuewritebuffer(command_queue, e_clmem, cl_true, 0, vector_size * sizeof(string), e, 0, null, null); log_ocl_error(clstatus, "clenqueuewritebuffer failed..." ); // create programme kernel source cl_program programme = clcreateprogramwithsource(context, 1, (const char **)&concat_kernel, null, &clstatus); log_ocl_error(clstatus, "clcreateprogramwithsource failed..." ); // build programme clstatus = clbuildprogram(program, 1, device_list, null, null, null); if(clstatus != cl_success) log_ocl_compiler_error(program, device_list[0]); // create opencl kernel cl_kernel kernel = clcreatekernel(program, "concat_kernel", &clstatus); // set arguments of kernel. take @ kernel definition in concat_kernel // variable. first parameter constant , other 3 buffers. clstatus |= clsetkernelarg(kernel, 0, sizeof(cl_mem), (void *)&d_clmem); clstatus |= clsetkernelarg(kernel, 1, sizeof(cl_mem), (void *)&e_clmem); clstatus |= clsetkernelarg(kernel, 2, sizeof(cl_mem), (void *)&f_clmem); log_ocl_error(clstatus, "clsetkernelarg failed..." ); // execute opencl kernel on list size_t global_size = vector_size; // process 1 vector element in each work item size_t local_size = 64; // process in work groups of size 64. cl_event concat_event; clstatus = clenqueuendrangekernel(command_queue, kernel, 1, null, &global_size, &local_size, 0, null, &concat_event); log_ocl_error(clstatus, "clenqueuendrangekernel failed..." ); // read memory buffer f_clmem on device host allocated buffer c // task invoked after completion of event concat_event clstatus = clenqueuereadbuffer(command_queue, f_clmem, cl_true, 0, vector_size * sizeof(string), f, 1, &concat_event, null); log_ocl_error(clstatus, "clenqueuereadbuffer failed..." ); // clean , wait comands complete. clstatus = clfinish(command_queue); // display result screen for(int = 0; < vector_size; i++) printf("%s + %s = %s\n", d[i].c_str(), e[i].c_str(), f[i].c_str()); // release opencl objects , release host buffers. clstatus = clreleasekernel(kernel); clstatus = clreleaseprogram(program); clstatus = clreleasememobject(d_clmem); clstatus = clreleasememobject(e_clmem); clstatus = clreleasememobject(f_clmem); clstatus = clreleasecommandqueue(command_queue); clstatus = clreleasecontext(context); free(d); free(e); free(f); free(platforms); free(device_list); homecoming 0; }

i don't think see much of gain offloading concat operation gpu, here how it:

__kernel void concat_kernel(__global uchar *d,__global uchar *e,__global uchar *f, const int dsize, const int esize) { int gid = get_global_id(0); int globalsize = get_global_size(0); int i; for(i=gid; i< dsize; i+= globalsize){ f[i] = d[i]; } for(i=gid; i< esize; i+= globalsize){ f[i+dsize] = e[i]; } if(gid == globalsize-1){ //using lastly work item here because //idle when (dsize+esize) % globalsize != 0 f[dsize + esize -1] = '\0'; } }

you need pass in sizes of strings want concatenate, instead of searching null value. kernel work number of work items, , different-sized d , e inputs. usual, f needs big plenty hold dsize+esise+1 chars.

each work item re-create (dsize+esize)/globalsize chars output.

room improvement:

try different global work sizes find optimal value device , input size the global memory access should pretty good, if want seek single work grouping , utilize local memory, help, bound global read speed.

c string algorithm opencl gpgpu

matrix - Linear or Nonlinear Regression of Multiple matrices with R? -



matrix - Linear or Nonlinear Regression of Multiple matrices with R? -

hello r friends , statistics thinkers !

hope question not stupid, wondering heal ignorance experiences or modeling knowledge. have many matrices of quantitative variables, allow me start 3 matrices of proportions. variabilities between samples, observe variables correlation between "contents m1", "variables m2" , "chemical m3" comparing these matrices. problem have 6 samples, tried sparse compositional model r package, not work because have little sample number n <10.

could please help me model selection , adequate r packages? should start iterative process trying little number of variable each matrice?

example of 3 matrices :

matrice 1

content1 content2 content3 content4 .... content150 sample1 sample2 sample3 sample4 sample5 sample6

matrice 2

v1 v2 v3 v4 ... v20 sample1 sample2 sample3 sample4 sample5 sample6

matrice 3

chemical1 chemical1 chemical1 .... chemical30 sample1 sample2 sample3 sample4 sample5 sample6

r matrix model regression sparse-matrix

php - Symfony2 + SonataAdmin + VichUploaderBundle - Image Upload Field -



php - Symfony2 + SonataAdmin + VichUploaderBundle - Image Upload Field -

spent lastly days trying, newcomer symfony find solution on integrating image upload field in existing entity in sonata admin. i've been googling , next guides available unfortunately cannot figure out.

setup specified in headline

symfony2 sonataadmin vichuploaderbundle

im stuck next error:

"catchable fatal error: argument 1 passed beautify\beautiesbundle\entity\beauty::setimagefile() must instance of symfony\component\httpfoundation\file\uploadedfile, instance of symfony\component\httpfoundation\file\file given, called in /users/gmf/symfony/vendor/symfony/symfony/src/symfony/component/propertyaccess/propertyaccessor.php on line 438 , defined in /users/gmf/symfony/src/beautify/beautiesbundle/entity/beauty.php line 75 "

the image upload field renders correctly , receive error after submitting.

this line 75:

/** * if manually uploading file (i.e. not using symfony form) ensure instance * of 'uploadedfile' injected setter trigger update. if * bundle's configuration parameter 'inject_on_load' set 'true' setter * must able take instance of 'file' bundle inject 1 here * during doctrine hydration. * * @param file|\symfony\component\httpfoundation\file\uploadedfile */ public function setimagefile(uploadedfile $image = null) { $this->imagefile = $image; if ($image) { // required @ to the lowest degree 1 field changes if using doctrine // otherwise event listeners won't called , file lost $this->updatedat = new \datetime('now'); } }

hers's other closely related files:

entity file:

<?php // src/beautify/beautiesbundle/entity/beauty.php namespace beautify\beautiesbundle\entity; utilize doctrine\orm\mapping orm; utilize symfony\component\httpfoundation\file\uploadedfile; utilize vich\uploaderbundle\mapping\annotation vich; /** * @orm\entity * @orm\table(name="beauties") * @orm\haslifecyclecallbacks * @vich\uploadable */ class beauty { /** * @orm\column(type="integer") * @orm\id * @orm\generatedvalue(strategy="auto") */ protected $id; /** * @orm\column(type="string", length=100) */ protected $name; /** * @orm\column(type="text") */ protected $content; /** * @vich\uploadablefield(mapping="beauty_image", filenameproperty="imagename") * @var file $imagefile */ protected $imagefile; /** * @orm\column(type="string", length=255, nullable=true, name="image_name") * @var string $imagename */ protected $imagename; /** * @orm\manytoone(targetentity="category", inversedby="beauties") * @orm\joincolumn(name="category_id", referencedcolumnname="id") */ protected $category; /** * if manually uploading file (i.e. not using symfony form) ensure instance * of 'uploadedfile' injected setter trigger update. if * bundle's configuration parameter 'inject_on_load' set 'true' setter * must able take instance of 'file' bundle inject 1 here * during doctrine hydration. * * @param file|\symfony\component\httpfoundation\file\uploadedfile */ public function setimagefile(file $image = null) { $this->imagefile = $image; if ($image) { // required @ to the lowest degree 1 field changes if using doctrine // otherwise event listeners won't called , file lost $this->updatedat = new \datetime('now'); } } /** * @return file */ public function getimagefile() { homecoming $this->imagefile; } /** * @param string $imagename */ public function setimagename($imagename) { $this->imagename = $imagename; } /** * @return string */ public function getimagename() { homecoming $this->imagename; } public function __tostring() { homecoming ($this->getname()) ? : ''; } /** * id * * @return integer */ public function getid() { homecoming $this->id; } /** * set name * * @param string $name * @return beauty */ public function setname($name) { $this->name = $name; homecoming $this; } /** * name * * @return string */ public function getname() { homecoming $this->name; } /** * set content * * @param string $content * @return beauty */ public function setcontent($content) { $this->content = $content; homecoming $this; } /** * content * * @return string */ public function getcontent() { homecoming $this->content; } /** * set category * * @param \beautify\beautiesbundle\entity\category $category * @return beauty */ public function setcategory(\beautify\beautiesbundle\entity\category $category = null) { $this->category = $category; homecoming $this; } /** * category * * @return \beautify\beautiesbundle\entity\category */ public function getcategory() { homecoming $this->category; } }

#admin file

<?php // src/beautify/beautiesbundle/admin/beautyadmin.php namespace beautify\beautiesbundle\admin; utilize sonata\adminbundle\admin\admin; utilize sonata\adminbundle\datagrid\listmapper; utilize sonata\adminbundle\datagrid\datagridmapper; utilize sonata\adminbundle\form\formmapper; utilize knp\menu\iteminterface menuiteminterface; utilize beautify\categorybundle\entity\category; class beautyadmin extends admin { // fields shown on create/edit forms protected function configureformfields(formmapper $formmapper) { $formmapper ->with('general') ->add('name', 'text', array('label' => 'name')) ->add('content', 'textarea', array('label' => 'content')) ->add('imagefile', 'file', array('label' => 'image file', 'required' => false)) ->end() ->with('category') ->add('category', 'sonata_type_model', array('expanded' => true)) ->end() ; } // fields shown on filter forms protected function configuredatagridfilters(datagridmapper $datagridmapper) { $datagridmapper ->add('name') ->add('content') ->add('category') ; } // fields shown on lists protected function configurelistfields(listmapper $listmapper) { $listmapper ->addidentifier('name') ->add('content') ->add('category') ->add('_action', 'actions', array( 'actions' => array( 'show' => array(), 'edit' => array(), 'delete' => array(), ) )) ; } } **#services file** report.listener: class: beautify\beautiesbundle\entity\beauty tags: - { name: doctrine.event_listener, event: prepersist } - { name: doctrine.event_listener, event: preupdate } **#config.yml** # other blocks vich_uploader: db_driver: orm mappings: beauty_image: uri_prefix: /images/beauties upload_destination: %kernel.root_dir%/../images

any help appreciated , create me happy

you missed use statement file class: use symfony\component\httpfoundation\file\file;

php symfony2 sonata-admin symfony-sonata vichuploaderbundle

arrays - C# program problems[Sorting two massives into one] -



arrays - C# program problems[Sorting two massives into one] -

i need sort 2 arrays one,but 0000000 happens in middle of output. whats problem? cant find mistake, in bubble sort? here code

'consoleapplication5.vshost.exe' (clr v4.0.30319: consoleapplication5.vshost.exe): loaded 'c:\windows\microsoft.net\assembly\gac_msil\system.data.datasetextensions\v4.0_4.0.0.0__b77a5c561934e089\system.data.datasetextensions.dll'. skipped loading symbols. module optimized , debugger alternative 'just code' enabled. 'consoleapplication5.vshost.exe' (clr v4.0.30319: consoleapplication5.vshost.exe): loaded 'c:\windows\microsoft.net\assembly\gac_msil\microsoft.csharp\v4.0_4.0.0.0__b03f5f7f11d50a3a\microsoft.csharp.dll'. skipped loading symbols. module optimized , debugger alternative 'just code' enabled. 'consoleapplication5.vshost.exe' (clr v4.0.30319: consoleapplication5.vshost.exe): loaded 'c:\windows\microsoft.net\assembly\gac_32\system.data\v4.0_4.0.0.0__b77a5c561934e089\system.data.dll'. skipped loading symbols. module optimized , debugger alternative 'just code' enabled. 'consoleapplication5.vshost.exe' (clr v4.0.30319: consoleapplication5.vshost.exe): loaded 'c:\windows\microsoft.net\assembly\gac_msil\system.xml\v4.0_4.0.0.0__b77a5c561934e089\system.xml.dll'. skipped loading symbols. module optimized , debugger alternative 'just code' enabled. 'consoleapplication5.vshost.exe' (clr v4.0.30319: consoleapplication5.vshost.exe): loaded 'c:\windows\microsoft.net\assembly\gac_msil\mscorlib.resources\v4.0_4.0.0.0_ru_b77a5c561934e089\mscorlib.resources.dll'. module built without symbols. thread 0x1264 has exited code 259 (0x103). thread 0xc4c has exited code 259 (0x103). thread 0xdc4 has exited code 0 (0x0). thread 0x16f4 has exited code 259 (0x103). 'consoleapplication5.vshost.exe' (clr v4.0.30319: consoleapplication5.vshost.exe): loaded 'c:\users\vas\documents\visual studio 2013\projects\consoleapplication5\consoleapplication5\bin\debug\consoleapplication5.exe'. symbols loaded. programme '[1112] consoleapplication5.vshost.exe: programme trace' has exited code 0 (0x0). programme '[1112] consoleapplication5.vshost.exe' has exited code -1073741510 (0xc000013a).

using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; namespace consoleapplication2 { class programme { static void main(string[] args) { int[] array1 = new int[20]; int[] array2 = new int[20]; int[] array = new int[40]; int k = 0; random rnd = new random(); console.writeline("Исходный массив №1:"); (int = 0; < 20; i++) { array1[i] = rnd.next(-100, +100); console.write("{0} ", array1[i]); } console.writeline(); console.writeline("Исходный массив №2:"); (int = 0; < 20; i++) { array2[i] = rnd.next(-100, +100); console.write("{0} ", array2[i]); } console.writeline(); (; k < 20; k++) { array[k] = array1[k]; } (; k > 20; k++) { array[k] = array2[k - 20]; } console.writeline("Отсортированный массив:"); bubblesort(ref array); (int = 0; < 40; i++) { console.write("{0} ", array[i]); } console.readkey(); } static void bubblesort(ref int[] a) { (int = 0; < a.length; i++) { (int j = + 1; j < a.length; j++) { if (a[j] < a[i]) { var temp = a[i]; a[i] = a[j]; a[j] = temp; } } } } } }

this should be:

(int k = 0; k < 20; k++) { array[k] = array1[k]; } (int k = 0; k < 20; k++) { array[k + 20] = array2[k]; }

you

(int k = 0; k < 20; k++) { array[k] = array1[k]; array[k + 20] = array2[k]; }

but due memory pipeline caching, 2 loops faster.

c# arrays sorting

ios - UICollectionViewCell dynamic sizing for 4.4 and 5.5 inch -



ios - UICollectionViewCell dynamic sizing for 4.4 and 5.5 inch -

i have uicollectionview cells in storyboard. size of each cell set 145x145.

they on iphone 4 - 5s, size doesn't increment proportionally on iphone 6 , 6+. rather manually setting different cell size each device, how can dynamically?

see examples here: iphone 5s: http://prntscr.com/55vy7q, iphone 6: http://prntscr.com/55vyy2

if want cells adjust width, you'll need calculate flow layout's itemsize based on view width.

if cells same size, can set flow layout's itemsize property:

#define kcellsperrow 2 uicollectionviewflowlayout *flowlayout = (uicollectionviewflowlayout*)self.collectionview.collectionviewlayout; cgfloat availablewidthforcells = cgrectgetwidth(self.collectionview.frame) - flowlayout.sectioninset.left - flowlayout.sectioninset.right - flowlayout.minimuminteritemspacing * (kcellsperrow - 1); cgfloat cellwidth = availablewidthforcells / kcellsperrow; flowlayout.itemsize = cgsizemake(cellwidth, flowlayout.itemsize.height);

if need calculate per-cell sizes, can in collectionview:layout:sizeforitematindexpath: delegate.

recalculate itemsize when device orientation changes , update layout:

redraw layout without animation:

[self.collectionview.collectionviewlayout invalidatelayout]

animate layout changes:

[self.collectionview performbatchupdates:nil completion:nil]

ios objective-c iphone autolayout uicollectionviewcell

Change Soap Request Header from text/xml to soap/xml for asmx webservice in C# -



Change Soap Request Header from text/xml to soap/xml for asmx webservice in C# -

i need phone call webservice. generated proxy , invoked method. keeps failing. because api expecting soap/xml in header whereas proxy client generated in visual studio sending text/xml in header.

question: possible alter value of content-type header generated proxy client?

wcf - content type text/xml; charset=utf-8 not supported service

this mismatch in client/server bindings, message version in service uses soap 1.2 (which expects application/soap+xml) , version in client uses soap 1.1 (which sends text/xml). wshttpbinding uses soap 1.2, basichttpbinding uses soap 1.1.

it seems wshttpbinding on 1 side , basichttpbinding on other.

you can alter configuration on client side wshttpbinding uses soap 1.2 , impact content type header.

c# xml web-services soap

c - Do I need to use volatile keyword for memory access in critical section? -



c - Do I need to use volatile keyword for memory access in critical section? -

i writing code single processor 32 bit microcontroller using gcc.

i need consume time-stamped objects linked list. part of code asynchronous (maybe in isr) adds them list.

the critical section implemented turning interrupts off , using barrier() function.

i'm confused gcc optimization break code cacheing pointers list items (next recent item remove, list head, or free list). dont want within while loop cached previous time around loop. memory barrier protect me compiler deciding load pointer 1 time @ start of function , never reload again? these list pointers might modified in critical section of producer code (not shown). trying understand if pqueue_first should volatile pointer, example.

presumably, if there no loop (which case adding list), ok if code in function in critical section?

please don't point me generic article volatile or critical sections because have read bunch of them, having problem seeing how apply specific code. understand volatile ensures compiler reload variable every time referenced. don't understand scope of optimization , interaction memory barriers.

typedef struct { ev_eventqueueentry_t *pqueue_alloc; // allocation (never changes) ev_eventqueueentry_t *pqueue_head; // head of active queue (isr can alter it) ev_eventqueueentry_t *pqueue_free; // head of free list (isr can alter it) ev_eventqueueentry_t *pqueue_first; // soonest item in queue (isr can alter it) ev_eventqueueentry_t *pqueue_first_prev; // pointer soonest item (isr can alter it) ev_uint_t max_event_count; } ev_eventqueue_t; void runloop(ev_eventqueue_t *pev) { while(not timeout) { // come in critical section disable_interrupts(); barrier(); // item recent timestamp // can changed isr add together queue operation ev_eventqueueentry_t *pfirst = pev->pqueue_first; if(pfirst!=null && ev_portisfuturetime(pfirst->event.timestamp, ev_portgettime())) { // re-create out message ev_event_t e = pfirst->event; // remove event queue if(pev->pqueue_first_prev != null) pev->pqueue_first_prev->pnext = pfirst->pnext; else pev->pqueue_head = pfirst->pnext; // set event on free list pfirst->pnext = pev->pqueue_free; pev->pqueue_free = pfirst; pfirst->event.message.type = ev_message_null; // find next soonest message process after 1 pev->pqueue_first = ...; pev->pqueue_first_prev = ...; // pointer // exit critical section barrier(); enable_interrupts(); // dispatch message ... } else { // exit critical section barrier(); enable_interrupts(); // waste time ... } } }

c++11 has standard feature this: std::atomic_signal_fence. c11 has similar feature, without namespace qualifier. suitable if programme uses single thread , trying stop compiler moving loads/stores across fence. utilize std::atomic_signal_fence(memory_order_acquire) before critical section , std:atomic_signal_fence(memory_order_release) after critical section.

if you're not using c++11 or c11, using gcc or compiler understands gcc asms, can utilize __asm__ __volatile__ ("": : :"memory") compiler barrier. asm says can't removed , threatens modify memory in mysterious ways, hence compiler won't able move loads/stores on it.

c volatile producer-consumer critical-section memory-barriers

ruby on rails - Testing for FactoryGirl Results -



ruby on rails - Testing for FactoryGirl Results -

i'm trying test see if items array exist after create factory.

spec/models/thing_spec.rb

require 'rails_helper' rspec.describe thing, :type => :model let(:thing) { array.new(3) {factorygirl.create(:thing) } } "should sort items in order" expect(thing).to include(ordering:1, ordering:2, ordering:3) end end

spec/factories/things.rb

factorygirl.define mill :thing, :class => 'thing' name "item_name" sequence(:ordering) end end

below results received.

results

1) things should sorted in order failure/error: expect(thing).to include(ordering:1, ordering:2, ordering:3) expected [#<thing id: 1, name: "item_name", create_date: "2014-11-07 04:18:17", modified_date: "2014-11-14 04:18:17", ordering: 1>, #<thing id: 2, name: "item_name", create_date: "2014-11-07 04:18:17", modified_date: "2014-11-14 04:18:17", ordering: 2>, #<thing id: 3, name: "item_name", create_date: "2014-11-07 04:18:17", modified_date: "2014-11-14 04:18:17", ordering: 3>] include {:ordering => 2} diff: @@ -1,2 +1,19 @@ -[{:ordering=>2}] +[#<thing:0x007fb96217cc30 + id: 1, + name: "item_name", + create_date: fri, 07 nov 2014 04:18:17 utc +00:00, + modified_date: fri, 14 nov 2014 04:18:17 utc +00:00, + ordering: 1>, + #<thing:0x007fb9621cfca0 + id: 2, + name: "item_name", + create_date: fri, 07 nov 2014 04:18:17 utc +00:00, + modified_date: fri, 14 nov 2014 04:18:17 utc +00:00, + ordering: 2>, + #<thing:0x007fb96221eda0 + id: 3, + name: "item_name", + create_date: fri, 07 nov 2014 04:18:17 utc +00:00, + modified_date: fri, 14 nov 2014 04:18:17 utc +00:00, + ordering: 3>]

you can't way. you'll have check each record individually this

it "should sort items in order" expect(thing[0].ordering).to eq(1) expect(thing[1].ordering).to eq(2) expect(thing[2].ordering).to eq(3) end

or this:

it "should sort items in order" expect(thing.map(&:ordering)).to eq([1, 2, 3]) end

you can utilize include check if array includes element whole, this:

expect(thing).to include(thing[0])

ruby-on-rails ruby testing rspec factory-girl

android - How to receive NFC tag data with my activity not foregound -



android - How to receive NFC tag data with my activity not foregound -

i'm developing nfc application turn wifi on , connect specific network when nfc tag tapped. far, i've understood nfc activity should on foreground nfc info android system. but, uncertainty whether understanding right or not, since i've seen operation of nfc tasks(https://play.google.com/store/apps/details?id=com.wakdev.nfctasks). although application not activated on receiving nfc data, launching corresponding task , turning wifi on successfully.

i'd know how possible. there can explain operation?

thanks in advance.

logcat on tapping nfc tag made 'nfc tools' : i/nfcdispatcher(822): matched aar ndef : e/soundpool(822): don`t play soundpool when not normal mode : e/nfcservice(822): applyalternativehandler::unknown message received : i/activitymanager(553): start {act=android.nfc.action.ndef_discovered typ=w1/33 pkg=com.wakdev.nfctasks cmp=com.wakdev.nfctasks/.nfcactivity (has extras) u=0} pid 822

logcat on tapping nft tag made application : i/nfcdispatcher(822): matched aar application launch : e/soundpool(822): don`t play soundpool when not normal mode : e/nfcservice(822): applyalternativehandler::unknown message received : i/activitymanager(553): start {act=android.intent.action.main cat=[android.intent.category.launcher] flg=0x10000000 pkg=com.farraf.digitalsignage cmp=com.farraf.digitalsignage/.main.digitalsignageactivity u=0} pid 822 : i/activitymanager(553): start proc com.farraf.digitalsignage activity com.farraf.digitalsignage/.main.digitalsignageactivity: pid=10160 uid=10008 gids={3003, 1015, 1028}

besides receiving nfc tag events trhough foreground dispatch scheme (see foreground dispatch system), can register activities launched upon , receive nfc events through androidmanifest.xml of app (see filtering nfc intents). e.g. if nfc tag contains uri http://www.example.com/, create intent filter this:

<activity ...> <intent-filter> <action android:name="android.nfc.action.ndef_discovered"/> <category android:name="android.intent.category.default"/> <data android:scheme="http" android:host="www.example.com" /> </intent-filter> </activity>

android android-intent nfc launcher ndef

angularjs - Angular Watch and ng-click sequence of events -



angularjs - Angular Watch and ng-click sequence of events -

i have code within angular directive, , i'm finding $watch behavior bit confusing. updateselect called in "ng-click":

scope.updateselect = function (type) { scope.selectionctrl.activelist = scope.seedlists[type]; scope.selectionctrl.activelistkey = type; scope.selectionctrl.activeselection = scope.selection[type]; scope.selectionctrl.staged = []; scope.selectionctrl.stageremove = []; if (type !== scope.activetab) { scope.activetab = type; } console.log("update"); }; scope.$watch('selectionctrl.activelist', function(newvalue, oldvalue) { console.log("watch"); }, true);

when click on button (triggering updateselect), , watch console, see "update" , "watch". first thing happens within function selectionctrl.activelist set, expect see "watch" , "update".

shouldn't watch trigger array has changed?

the function has finish first javascript single threaded.

because function called via ng-click directive, angular run digest cycle. part of digest cycle run through watch list , resolve changes may have occurred since cycle lastly ran.

in illustration give, selectionctrl.activelist changed in updateselect subsequently results in watch callback beingness called.

angularjs

javascript - Open a URL in a new Tab -



javascript - Open a URL in a new Tab -

this question has reply here:

focus tab or window 10 answers

i want open url in new browser tab javascript or jquery. , if it's been opened, tab selected.

i utilize function open.

function openinnewtab(url) { var win = window.open(url, '_blank'); win.focus(); }

what should if tab open?

see here:

how alter browser focus 1 tab another

and here:

detect if browser tab has focus

both of previous stack overflow posts.

it's possible know when on tab, , when user moves away (using new page visibility api)

but it's not possible switch tab using javascript.

you (which much uncertainty applies in case) write external programme operating scheme communicate browser application , switch way, straight web page, it's non starter , huge security risk.

javascript jquery

html - Scalable, Centered Image Link -



html - Scalable, Centered Image Link -

i'm using html & css seek create centered image, when click it, gives total size version. image scalable on smaller devices scales down. right not worrying bandwidth of client. i'm having issue clickable area outside of image makes theres sort of invisible link.

here mean.

all areas have arrows user can click - doesn't create sense. want image clickable. can work, have utilize inline block on tag, ruins scaling depending on width of screen.

here html part.

<a class="image_link" href="/images/guides/wavelist_editing/fullsize/wave3.jpg"><img class="scalable_image popout_image centered" src="/images/guides/wavelist_editing/wave3.jpg"></a>

and css.

.content a:link.image_link { /*not overqualified - overrides stuff on main.css. gets rid of underline*/ border-bottom: 0px none transparent; text-decoration: none; display:block; } .content .popout_image { display: block; margin-left: auto; margin-right: auto; box-shadow: 8px 8px 10px #555; margin-bottom: 10px; max-width: 100%; min-width: 100px; } .content .scalable_image { min-width: 100px; max-width: 100%; height: auto; width: auto\9; /* ie8 */ }

to verify info here computed values link , image respectively in firefox (the first image incorrectly shows inline-block, took image in testing, it's block - both values introduce error, no-scaling or big clicking):

i sense missing obvious here. can't google because "image link" seems pretty generic.

you accomplish this:

jsfiddle - demo

html:

<div class="content"> <a class="image_link" href="/images/guides/wavelist_editing/fullsize/wave3.jpg"><img class="scalable_image popout_image centered" src="http://placehold.it/350x150"></a> <div>

css:

.content { text-align: center; /* add together */ } .content a:link.image_link { border-bottom: 0px none transparent; text-decoration: none; display: inline-block; /* add together */ } .content .popout_image { display: block; box-shadow: 8px 8px 10px #555; margin-bottom: 10px; max-width: 100%; min-width: 100px; } .content .scalable_image { min-width: 100px; max-width: 100%; height: auto; width: auto\9; }

html css image

php - prolem in getting particular value from json string -



php - prolem in getting particular value from json string -

i want first element of json. data.first getting nothing.although alert(data) print total json string please help me out of this

<?php include_once '../con_db.php'; $rf = $_post['rf']; $rid = $_post['tid']; $data = array("first" => "one","seconed"=> "two"); echo json_encode($data); ?>

jquery code ajax request below

$('.fbased').focusin(function(){ var rf = $(this).attr('id'); var tid = $("#test_id").val(); $.ajax({ type:'post', url:'functions/ftable.php', data: 'rf='+rf+'&tid='+tid, datatype: "json", success : function(data){ $("#"+rf).val(data); } }); });

success : function(data){ var parsed = json.parse(data); $("#"+rf).val(parsed.first); }

php jquery json

java - Thread is not acquiring monitor after notify calls -



java - Thread is not acquiring monitor after notify calls -

i made 1 producer , 1 consumer thread. when list empty consumer went waiting state, producer insert item in list , calls notify() invoke consumer thread consumer not invoking. remains in waiting state.

code have tried is:

package xs; import java.util.arraylist; import java.util.date; import java.util.list; public class testmain { public static void main(string[] args) { product pro = new product(); producer produce = new producer(pro); consumer consume = new consumer(pro); thread thr1 = new thread(produce, "producer"); thread thr2 = new thread(consume, "consumer"); thr1.start(); thr2.start(); } } class product{ list<date> list; public product() { list = new arraylist<date>(); } public void produce(date i){ list.add(i); } public date consume(){ homecoming list.remove(0); } } class producer implements runnable{ product product; @override public void run() { while(true){ synchronized (this) { while(product.list.size() == 2){ seek { wait(); } grab (interruptedexception e) { // todo auto-generated grab block e.printstacktrace(); } } product.produce(new date()); system.out.println("produced "+product.list.size()); notify(); } } } public producer(product product) { this.product = product; } } class consumer implements runnable{ product product; @override public void run() { // todo auto-generated method stub while(true){ synchronized (this) { notify(); while(product.list.size() == 0){ seek { system.out.println("going wait..."+ product.list.size()); wait(); } grab (interruptedexception e) { // todo auto-generated grab block e.printstacktrace(); } } system.out.println("consumed"+ product.consume()); } } } public consumer(product product) { this.product = product; } }

output it's giving:

going wait...0 produced 1 produced 2

as can see consumer not coming in action after wait() call.

please help!

your producer , consumer each synchronizing, waiting , notifying their own monitor. need give them shared monitor utilize synchronization etc.

for example:

object monitor = new object(); product pro = new product(); producer produce = new producer(monitor, pro); consumer consume = new consumer(monitor, pro);

change both producer , consumer constructors take parameter (of type object) , save in field, alter synchronized(this) synchronized(monitor), wait() monitor.wait() , notify() monitor.notify() , well.

(you could utilize product synchronize on, prefer utilize object only used synchronization, or object of thread-centric class designed this.)

also, note code feels un-java-like due class names, should product, producer , consumer follow normal java naming conventions.

java multithreading

magento - Fixed Amount Discount Code not working when two different items added to cart -



magento - Fixed Amount Discount Code not working when two different items added to cart -

i using magento , trying apply coupon code discounts fixed amount of £5 off order on value of £149. code working fine until 2 different items added cart. if value on £149, there 2 or more different items code discounting seemingly random amounts such £2.33 or £1.21. amount seems vary number of items in cart sec item added.

the code configured 'fixed amount discount whole cart' , did work previously, i'm not sure why glitch occurring now. able advise please? in advance.

select rule , update shopping cart rule setting follow:

actions => 'stop farther rules processing' = 'no'.

this might help prepare issue

magento shopping-cart

php - Entity class mapping is invalid -



php - Entity class mapping is invalid -

hi trying create onetomany relationship between page , block tables getting next error on validating schema:

[mapping] fail - entity-class 'mypath\entity\block' mapping invalid: * association mypath\entity\block#pages refers inverse side field mypath\entity\page#blocks not exist. [mapping] fail - entity-class 'mypath\entity\page' mapping invalid: * association mypath\entity\page#block refers owning side field mypath\entity\block#page not exist.

following page , block entities

page:

/** * @orm\onetomany(targetentity="block", mappedby="page") */ private $block;

block:

/** * @orm\manytoone(targetentity="page", inversedby="block") * @orm\joincolumn(referencedcolumnname="id") */ private $pages;

i not sure wrong seems related annotations. please help, !!!

in annotation, phone call properties "blocks , "page", they're called "block" , "pages" in actual code.

page:

/** * @orm\onetomany(targetentity="block", mappedby="page") */ private $blocks;

block:

/** * @orm\manytoone(targetentity="page", inversedby="blocks") */ private $page;

php symfony2

sql - converting a column to be empty -



sql - converting a column to be empty -

i have 2 tables in 1 table has datecolumn , other not have, have main union fetch entries both table

so of successful, empty fields showing invalid date 1900-01-01, want should dispayed null, cast varchar

i trying

select [orderid],cast('' [cancelleddate] char(20)) [cancelleddate] ,'' [cancelledtime]

the above throwing error

and doing way effect performance

select orderid, cancelleddate, cancelledtime table1 union select orderid, null, null table2

sql

encryption - Using Openssl to decrypt AES 128 bits CBC based64 text -



encryption - Using Openssl to decrypt AES 128 bits CBC based64 text -

i trying utilize openssl decrypt next aes 128 bits cbc based64 text (not padded) contained in input.txt

bzxchmwf+kvmumkb6rxtjq0803fpyyxgdtz8/nvc0fc=

the first 16bytes iv. encryption key h4ckth1sk3yp4d16

i tried using command:

openssl enc -aes-128-cbc -d -base64 -k 6834636b746831736b33797034643136 -iv 627a7843484d57462b4b564d756d4b62 -in input.txt -out result.txt

in input.txt, remove first 16 bytes of encrypted text when running above command.

but kept getting error:

bad decrypt 3073874120:error:0606506d:digital envelope routines:evp_decryptfinal_ex:wrong final block length:evp_enc.c:532:

can tell what's wrong here? thanks!

encryption cryptography openssl

javascript - Express + node.js API filtering -



javascript - Express + node.js API filtering -

i developing node api. have endpoint get /messages

this wll homecoming messages. want have pagination on endpoint like

get /messages?filter=my_filter_string&limit=10&offset=10

the filter statement this

{fieldname1}={fieldvalue1}&...{fieldnamen}>{fieldvaluen}. operations can =, > or <. < , > operations number, integers , dates

i using sequelize orm , postgresql db. question how can parse my_filter_statement , convert search criteria object sequelize. if phone call api like

get /messages?filter="id=10&contentlength>20"&limit=10&offset=10

it not working

can have, example:

get /messages?greater=1&less=5&limit=10&offset=10

and in node:

var url = require('url'); var url_parts = url.parse(request.url, true); var query = url_parts.query;

and match query parameters, such greater/less (which shortened "gt" , "lt"), symbols need in statement?

javascript node.js postgresql rest express

aop - How do i assign a member instance of a class using aspect in aspectj? -



aop - How do i assign a member instance of a class using aspect in aspectj? -

class="lang-java prettyprint-override">public class myclass { private int amemeber; public void mymethod(anotherclass aclass) { amember = aclass.amethod(); } } class="lang-java prettyprint-override">class anotherclass{ public int amethod(){ homecoming 9; } }

how refactor above 2 classes in aspectj?

aop aspectj

matlab - plot elements of array with different colors -



matlab - plot elements of array with different colors -

i have vector of integers vary 1 4.

a=[1 2 3 4 2 3 2 1 2 3 4 4]

i plot different colors each value... vertical line links a(1) a(2) should have color of first value (in case 1).

is possible?

and how handle case of nan nowadays in vector? should plot against time vector

a = [1 1 1 nan 4 4 4 nan 2 2 3 3]; time = [1 2 3 4 5 6 7 8 9 10 11 12];

suppose have next set of colors:

col = hsv(4);

you set order of colors based on values of a:

figure(); set(gca, 'colororder', col(a,:), 'nextplot', 'replacechildren');

then, can plot each line in desired color:

n = numel(a); plot(hankel(0:1,1:n-1),hankel(a(1:2),a(2:n)))

this results in:

edit: hankel approach bit shooting bazooka kill mosquito, in netherlands. anyway, learned few questions ago - liked utilize it. see post of dan simpler alternative plotting. still, setting right colors can done in above.

matlab colors plot

java - How to use Vaadin SQLContainer when I already have a JDBC connection pool -



java - How to use Vaadin SQLContainer when I already have a JDBC connection pool -

vaadin 7 offers sqlcontainer implementation. book of vaadin says utilize either of implementations of jdbc connection pool. using tomcat jdbc connection pool implementation. having 1 pool draws pool seems bad thing.

to go on using tomcat pool, implemented com.vaadin.data.util.sqlcontainer.connection.jdbcconnectionpool interface. interface requires 3 methods:

reserveconnectioni homecoming connection drawn tomcat pool. releaseconnectioni nothing. tried calling close on connection, closed connection rather returning tomcat pool. apparently sqlcontainer called close 1 time , sec phone call close closes downwards connection. getting runtime errors saying connection not open. destroyi nothing. supposedly method workaround issue postgres (which i'm using), seems irrelevant given using tomcat pool.

➜ implementing interface right approach?

➜ if implementing interface way go, did properly? other issues should address?

my tomcat pool available via jndi, i'm not sure if should using vaadin class j2eeconnectionpool.

you should in fact able utilize j2eeconnectionpool, described in own reply above. have used used j2eeconnectionpool freeformquery know works. unfortunately there apparently bug in vaadin's tablequery implementation caused "connection has been closed" error saw. see: http://dev.vaadin.com/ticket/12370

the ticket proposes code change, in case replaced offending tablequery freeformquery.

java database-connection vaadin connection-pooling vaadin7

Mips and cisc assembly langue -



Mips and cisc assembly langue -

does have simple programme source code run in both assembly langue mips , cisc explan mips run less cpu cycle cisc ?

simple programme not require big one

thank you

a simple illustration comparing 2 strings against each others:

mips

; string pointers in $a0 , $a1 more: ld $r0,($a0) ld $r1,($a1) add together 1, $a0 add together 1, $a1 cmp $r0,$0 je eos cmp $r1,$0 je eos cmp $r0,$r1 je more eos: cmp $r0, $r1 ; cmp result defines whether a0 < a1, a0 == a1, a0 > a1

cisc (intel)

; start strings in edi , esi more: cmps (edi), (esi) loopnz more ; cmps result defines whether a0 < a1, a0 == a1, a0 > a1

i not guarantee validity of code. however, can see cisc same thing mips in 2 instructions (although initialization may require more code in cisc...). however, taking same amount of time.

assembly mips cpu cycle

visual studio - VB.net - Set timer interval between two user defined values -



visual studio - VB.net - Set timer interval between two user defined values -

very new programming , stackoverflow. in vb.net, have timer interval set inserted value in text box. have 2 text boxes values (ex. 30000 , 40000) , timer interval set random number between 2 values (ex. between 30 , 40 seconds). have number recalculated each time timer ticks. give thanks you.

the closest thing find : setting random timer intervals in vb did not deal user defined values.

maybe work improve you?

option strict on alternative explicit on imports system.timers public class form1 private withevents time new timer private randnum new system.random private sub form1_load(sender object, e eventargs) handles mybase.load me.textbox1.text = "30000" me.textbox2.text = "40000" time.interval = 1000 ' enable timer when form loads time.start() end sub private sub time_elapsed(sender object, e elapsedeventargs) handles time.elapsed ' code (below) assumes valid info against textbox1 , textbox2 time.interval = randnum.next(cint(me.textbox1.text), cint(me.textbox2.text)) debug.writeline(time.interval.tostring) end sub end class

vb.net visual-studio timer

Regex to parse and replace img src in C#/.NET? -



Regex to parse and replace img src in C#/.NET? -

ahoy,

i have problem, see; have strings like:

<img width="594" height="392" src="/sites/it_kb/siteassets/pages/exploding%20the%20vdi%20vdesktop/vdi3.png" alt="" style="margin:5px;width:619px;height:232px" />

they not consistently formatted.

i need parse strings this, , homecoming following:

<img width="594" height="392" src="/exploding%20the%20vdi%20vdesktop-vdi3.png" alt="" style="margin:5px;width:619px;height:232px" />

changes:

remove except immediate directory in image file lay. instead of directory beingness subdirectory, prepend onto file name.

so if file in /blabla/bla/blaaaaah/pickles/pickle.png

then want img src attribute pickles-pickle.png

now, i've been trying regex, after 3 hours, i've discovered myself... awful @ regex. @ weeks, , i'd never anywhere.

thus, asking wonderful community 2 things:

how this? regex right answer? need able parse src attributes within img tags (whether or not have height/width or other attributes). what resources recommend me larn regex .net?

now problem @ hand, suppose string.replace i....

find img tag, , indexes of surrounding '<' , '>' find index of 'src=' , ' ' (space) between 2 instances find lastly index of '/' between src , space indexes find sec lastly index of '/' between src , space indexes replace... er no, remove... before sec lastly instance of '/'... ...string.replace remaining '/' '-'. ....i.. think that'd it?

but damn ugly. regex much prettier, don't think?

any advice?

note: tagged 'homework', it's not homework. i'm volunteering work after-hours save company 200k. literally lastly piece of incredibly convoluted (to me) puzzle. of course, don't see penny of 200k, doing it.

to tag, suggest using htmlagilitypack. it's safer regex on entire html page.

use image nodes:

htmldocument doc = new htmldocument(); doc.loadhtml(html); var imgs = doc.documentnode.selectnodes("//img");

use get/set attributes:

foreach (var img in imgs) { string orig = img.attributes["src"].value; //do replacements on orig new string, newsrc img.setattributevalue("src",newsrc); }

so, kind of replacements should do? agree using regex much more elegant. things these it's after all!

something should trick:

string s = @"/sites/it_kb/siteassets/pages/exploding%20the%20vdi%20vdesktop/vdi3.png"; string n = regex.replace(s,@"(.*?)\/([^\/]*?)\/([^\/]*?)$",@"/$2-$3");

some resources can utilize larn c# regexing:

dotnetperls regex.match

msdn: regex.match method

msdn regex cheat sheet

c# regex image expression

jquery - Change form autofill background yellow color -



jquery - Change form autofill background yellow color -

i found topic google chrome form autofill , yellowish background

i have same problem reason solution doesn't work in website develop.

i new jquery appreciate help.

the website @ http://anaxshipping.com/cms/demo2/

for instance instead of yello background trasparent.

i have changed $ jquery nil changed.

thanks in advance.

here described solution of question remove forced yellowish input background in chrome

jquery css forms google-chrome autofill

java - Apache camel,RabbitMQ how to send messages/objects -



java - Apache camel,RabbitMQ how to send messages/objects -

i hope can provide help on matter.

i using camel rabbitmq , testing purpose trying send message queue, i'm trying display in rabbitmq interface , read back.

however can't working.

what believe works created, in exchange tab of rabbitmq management interface, new exchange. in java code send message exchange. when code executed, can see spike in web interface showing has been received can't see has been received. when seek read, can't read , next errror: < in route: route(route2)[[from[rabbitmq://192.168.59.103:5672/rt... because of route route2 has no output processors. need add together outputs route such to("log:foo").

can provide me practical illustration on how send message,see in web interace , read it? tutorial showing process appreciated.

thank you

================= sec part

the error i'm getting following:

caused by: com.rabbitmq.client.shutdownsignalexception: channel error; reason: {#method<channel.close>(reply-code=406, reply-text=precondition_failed - cannot redeclare exchange 'rhsearchexchange' in vhost '/' different type, durable, internal or autodelete value, class-id=40, method-id=10), null, ""} @ com.rabbitmq.utility.valueorexception.getvalue(valueorexception.java:67) @ com.rabbitmq.utility.blockingvalueorexception.uninterruptiblegetvalue(blockingvalueorexception.java:33) @ com.rabbitmq.client.impl.amqchannel$blockingrpccontinuation.getreply(amqchannel.java:343) @ com.rabbitmq.client.impl.amqchannel.privaterpc(amqchannel.java:216) @ com.rabbitmq.client.impl.amqchannel.exnwrappingrpc(amqchannel.java:118) ... 47 more

i have next settings:

i error, believe i’m doing wrong uri , have define parameters i’m missing exchange of direct type queue of durable type , uri : rabbitmq://192.168.59.105:5672/rhsearchexchange?username=guest&password=guest&routingkey=rhsearchqueue

any input on this?

thanks

so able figure out yesterday, had same (or @ to the lowest degree similar) problems having.

the options have in rabbitmq uri must match options exchange created with. example, in configuration, had exchange called tasks direct type, durable, , not configured autodelete. note default value autodelete alternative in rabbitmq camel component true. additionally, wanted messages routing key camel. means rabbitmq uri needed like:

rabbitmq:localhost:5672/tasks?username=guest&password=guest&autodelete=false&routingkey=camel

additionally, wanted read existing queue, called task_queue rather have rabbitmq camel component declare it's own queue. therefore, needed add together additional query parameter, rabbitmq uri

rabbitmq:localhost:5672/tasks?username=guest&password=guest&autodelete=false&routingkey=camel&queue=task_queue

this configuration worked me. below, added java code snippets code configures exchange , queue , sends message, , camel route configuration.

exchange , queue configuration: rabbitconnfactory = new connectionfactory(); rabbitconnfactory.sethost("localhost"); final connection conn = rabbitconnfactory.newconnection(); final channel channel = conn.createchannel(); // declare direct, durable, non autodelete exchange named 'tasks' channel.exchangedeclare("tasks", "direct", true); // declare durable, non exclusive, non autodelete queue named 'task_queue' channel.queuedeclare("task_queue", true, false, false, null); // bind 'task_queue' 'tasks' exchange routing key 'camel' channel.queuebind("task_queue", "tasks", "camel"); sending message: channel.basicpublish("tasks", "camel", messageproperties.persistent_text_plain, "hello, world!".getbytes()); camel route: @override public void configure() throws exception { from("rabbitmq:localhost:5672/tasks?username=guest&password=guest&autodelete=false&routingkey=camel&queue=task_queue") .to("mock:result"); }

i hope helps!

java spring apache-camel rabbitmq