Posts

Showing posts from May, 2014

smtplib - Email using Python with Excel attachment -

#!/usr/bin/env python3 import smtplib,email,email.encoders,email.mime.text,email.mime.base email.mime.multipart import mimemultipart email.mime.text import mimetext email import encoders email.message import message email.mime.audio import mimeaudio email.mime.base import mimebase email.mime.image import mimeimage email.mime.multipart import mimemultipart email.mime.text import mimetext msg = mimemultipart() # me == email address # == recipient's email address me = "sender@email.com" = "reciever@email.com " # create message container - correct mime type multipart/alternative. msg = mimemultipart('mixed') msg['subject'] = "msg" msg['from'] = me msg['to'] = # create body of message (a plain-text , html version). text = "hi\nthis text-only" html = """\ <html> email</html> """ part1 = mimetext(text, 'plain') part2 = mimetext(html, 'html') #attach exc

how to extract specific integers in a mixed string-integer line in c++ -

i reading text file in c++, example of lines in it: remove 1 2 cost 13.4 how disregard things except 2 integers after remove, "1" , "2" , put them in 2 integer variable? my incomplete code: ifstream file("input.txt"); string line; int a, b; if(file.is_open()) { while (!file.eof()) { getline (file, line); istringstream iss(line); if (line.find("remove") != string::npos) { iss >> >> b; // not work, not sure how // write code here } } } here few options: use stringstream created line find remove token , parse next 2 integers. in other words, replace this: if (line.find("remove") != string::npos) { iss >> >> b; // not work, not sure how // write code here } with this: string token; iss >> token; if (token == "remove") { iss >> >

excel - Formula entered in Cells by VBA gives 1004 -

i'm using code populate excel sheet field values (e.g. subject, sender, etc) outlook.msg files. outlook.msg files in same folder excel file. it convenient if can make hyperlink these messages in excel file. want hyperlink 'dynamic' in such way if move whole folder (with outlook.msg files , excel workbook) antother location link still works. i use code creating 'dynamic'hyperlinks: hyperlinkstring = "=hyperlink(mid(cell(""filename"");1;find(""["";cell(""filename""))-1))" & sname where sname outlook.msg file name populate cells in loop with worksheet("sheetname").cells(row, column).formula = hyperlinkstring this gives me 1004 run-time error. when put additional space before "="sign " =hyperlink(mid etc... code runs , cells filled , when remove space manually hyperlink works charm. why not working directly , there way? when using .formula need use

How to create a new image from another - ImageMagick -

i haven't been able find answers this, maybe i'm not looking in right place, thought check here. sure there simple answers (provided know them, of course). let's have image 1000x2000. want use imagemagick take region of image (starting @ 40x50, , of size 100x200) , create image, same dimensions region (i.e. 100x200). how do this? and then, if wanted resize original image 800x1600, command this? thanks! for cropping out region, try, ooh, don't know, maybe -crop ? (searching "imagemagick crop" take imagemagick crop page, http://www.imagemagick.org/usage/crop/ ) convert input.jpg -crop 100x200+40+50 +repage output.jpg here +repage ensure output image size of crop (as mentioned in above link). for resizing, try (want guess?) -resize or - scale (and again, googling "imagemagick resize" have brought http://www.imagemagick.org/usage/resize/ , , excellent resource)): e.g. convert input.jpg -resize 800x1600 output.jpg convert i

html - Using Beautiful soup to analyze table in python -

so i've got table: <table border="1" style="width: 100%"> <caption></caption> <col> <col> <tbody> <tr> <td>pig</td> <td>house type</td> </tr> <tr> <td>pig a</td> <td>straw</td> </tr> <tr> <td>pig b</td> <td>stick</td> </tr> <tr> <td>pig c</td> <td>brick</td> </tr> and trying return json string of table pairs so: [["pig a", "straw"], ["pig b", "stick"], ["pig c", "brick"]] however, code can't seem rid of html tags: stable = soup.find('table') cells = [ ] rows = stable.findall('tr') tr in rows[1:4]: # process body of table row = [] td = tr.findall('td') #td = [el.text el in soup.tr.finall('td')] row.append( td[0]) row.append( td

javascript - I can't make jquery scroll pane horizontal -

i have been using following code make vertical scroll bar scroll pane: function scrollpane(){ $('.custom-scroll').jscrollpane({ showarrows: true, verticaldragminheight : 0, verticaldragmaxheight : 100, mousewheelspeed: 120, wheelspeed: 120, contentwidth: '100px' }); } i trying make horizontal scrollbar, not working. here code: function scrollpane(){ $('.custom-scroll').jscrollpane({ showarrows: true, verticaldragminheight : 0, verticaldragmaxheight : 100, mousewheelspeed: 120, wheelspeed: 120, contentwidth: '100px' }); $('.horizontal_bar').jscrollpane({ showarrows: true, contentwidth: '100px' }); } and css have horizontal_bar: .horizontal_bar{ width: 100%; height: 200px; overflow: auto; } how make horizontal scroll pane?

c# - My Copy Directory Functions Fails Occasionally -

i'm having problems code below failing complete due not releasing file copying. wrap function in using statement, not sure how or if there better solution this. thanks. public static void copydirectory (string source, string destination) { if (!directory.exists (destination)) directory.createdirectory (destination); string [] sysentries = directory.getfilesystementries (source); foreach (string sysentry in sysentries) { string filename = path.getfilename (sysentry); string targetpath = path.combine (destination, filename); if (directory.exists (sysentry)) copydirectory (sysentry, targetpath); else file.copy (sysentry, targetpath, true); } // foreach (string sysentry in sysentries) }

ios - elements of array are null -

i'm working along bignerdranch ios app book. in first chapter makes little quiz app questions hardcoded code file. if application runs successfully, it's supposed displaying question: "what blah blah?" in console, when run app says displaying question: (null) in other words, (null) appearing instead of question array. no errors showing when compile. wonder if has fact xcode using main.storyboard file rather xib , nib files, combined fact view controller uses method seems expect nib file, namely - (id)initwithnibname:(nsstring *)nibnameornil bundle: any appreciated. code. iosquizviewcontroller.h #import <uikit/uikit.h> @interface iosquizviewcontroller : uiviewcontroller iosquizviewcontroller.h { int currentquestionindex; nsmutablearray *questions; nsmutablearray *answers; iboutlet uilabel *questionfield; iboutlet uilabel *answerfield; } - (ibaction)showanswer:(id)sender; - (ibaction)showquestion:(id)sender; @end

php - How to use Plivo call API -

i using plivo , have calls answered welcome.php welcome url . when call answered, pass conf_handler.php , enter conference: $conf_attr = array( 'callbackurl' => $host.'conf_handler.php', 'callbackmethod' => "post", ); $r->addconference($conf_name,$conf_attr); echo($r->toxml()); how can store both calluuid , call_duration (once hang up) variables within conf_handler.php ? posted page callbackmethod? or need somehow use them (how this?) http://plivo.com/docs/api/call/#call_detail you can both ways. 1) from hangup_url (within welcome.php ). when call answered, plivo sends post request set of parameters including two. can parse request there. (check out "request parameters" section @ http://plivo.com/docs/xml/request/ ) 2) from callbackurl (within conf_handler.php'). once set the conf_handler.php in the callbackurl`, plivo send set of parameters described @ http:/

php - XPath - text from elements turned to lowercase -

this xpath/php code checks see if text in of "name" elements in xml file contain string "desk". there way turn text retrieved "name" elements lowercase letters? (ie turn desktop desktop?). here xpath & php code: $xmldoc = simplexml_load_file("products.xml"); $query = $xmldoc->xpath('/products/product[contains(name,"desk")]'); foreach($query $products) { echo $products->name . " "; echo $products->price . "<br>"; } here xml file (named product.xml): <products> <product type="electronics"> <name>desktop</name> <price>499.99</price> <store>best buy</store> </product> <product type="hardware"> <name>hand saw</name> <price>99.99</price> <store>lowes</store> </product> </products> use strtolower ( string $str ) echo strtolower($products->

php - Remote mySQL connection error -

i posted question earlier provided link output instead of posting output here. additional details, trust there enough info. this script works locally on server when loaded on remote server error shown after code below given... can tell me why works locally , not remotely. % wildcard has been set allowed hosts. <?php $version_link = mysql_connect('gjinternetsolutions.com', 'gj_guest', 'password1'); mysql_select_db("gj_software", $version_link); if (mysql_errno()) { $error = "<p>mysql error ".mysql_errno().": ".mysql_error()."\n</p>"; die($error); } $version_query = "select * `versioncheck` `software`='redemptionfee'"; $version_result = mysql_query($version_query); $version_row = mysql_fetch_array($version_result); if (mysql_errno()) { $error = "<p>mysql error ".mysql_errno().": ".mysql_error()."\n<br>when executing:<br>\n

c# - the name "photoveiwmodel" does not exist -

i using this example , opened error error 1 name "photosviewmodel" not exist in namespace "clr-namespace:photohubsample.viewmodels". c:\users\mike\desktop\photohub - windows phone 8 xaml longlistselector grid layout sample\c#\photohubsample\mainpage.xaml 73 12 photohubsample as being example didn't expect errors when loading. still new making apps on windows phone, have no idea how fix this..

ios - Wikitude - Bad memory management / memory leaks -

Image
i'm using wikitude augmented reality mobile app project. problem dont know how manage app memory before , after resume app. test result on xcode5. every time resume app during preview world, memory usage keep increasing. why? you may have abandoned memory. take @ thread starting point. tips finding , debugging abandoned memory , heap growth

How to access attributes in freemarker liferay 6.2 -

i have request object contains complete url the structure +-portlet-session +-attributes +- complete_url i can access portlet-session using request['portlet-session'] how can access attribute complete_url i have tried - request['portlet-session']['complete_url'] but doesnt work any help? using liferay 6.2 figured out request["attributes"].current_complete_url

c - Can't printf ASCII value for scanf_s value of variable -

trying user-input value character, display ascii integer number. doesn't want it--as keep getting blank output. however, if manually assign character letter let works fine. #include "stdafx.h" #include <stdio.h> #define eps 8.85e-12 int main() { int x = 1, y = 2, z; float p = 2.5, q = 4.8; double = 2.5e-9, b; char let; z = 2 * y; printf(" x/(y+z) = %.1f \n", (float)x/(y + z)); printf(" alphabet "); scanf_s("%c", &let); printf("ascii value of alphabet %d\n", let); printf("insert value of b :"); scanf_s("%lf", &b); printf("value of eps/(a*b)= %8.2e\n", eps / (a*b)); return 0; } as per microsoft's documentation : unlike scanf , wscanf , scanf_s , wscanf_s require buffer size specified input parameters of type c , c , s , s , or string control sets enclosed in [] . the buffer size in characters passed additional parameter

javascript - Append table cells to select boxes in indexed order -

i having huge brain fart efficiency right now. the idea here if have static table (unfortunately formatted way data i've received), how appropriately append select option dropdown every value table categorized easily? i have working, seems if make more efficient current statement. have feeling dom manipulation have going on, if tried use on table thousands of items lag browser. let's code. js fiddle: http://jsfiddle.net/z2v2p/1/ html: <table id='data'> <tr> <td>item 1</td> <td>value 1</td> <td>prop 1</td> </tr> <tr > <td>item 2</td> <td>value 2</td> <td>prop 2</td> </tr> <tr > <td>item 3</td> <td>value 3</td> <td>prop 3</td> </tr> </table> <select id="item"></select> <select id="value"

css - Strange Issues with IIS and ASP.NET WebForms -

currently debugging external companies web portal product support, every few hours each day site 'breaks' side menu stops functioning properly, did comparisons of html when site functional , when site broken. when broken, html shows style sheets being applied 100s of times. <link href="../../app_themes/outlookmenu.css" type="text/css" rel="stylesheet" /> i suspect why page gets broken, without access code @ dead end, has ever experienced this? suspect session related or somehow related asyncpostback timeout. note: after iisreset normal again few hours. edit: did notice in event viewer around time occurs warning 1309 with stack trace containing load of system.web.ui.control.loadrecursive() system.web.ui.control.loadrecursive() system.web.ui.control.loadrecursive() system.web.ui.control.loadrecursive() system.web.ui.control.loadrecursive()

PHP array_merge order one value per array -

i'd 2 merge 2 array custom order: take 1 value array 1 , 1 array 2 following: $array1 = array('key1' => 'value_1_1', 'key2' => 'value_1_2'); $array2 = array('key1' => 'value_2_1', 'key2' => 'value_2_2'); //merge array custom order $array_result = array('key1' => array('value_1_1', 'value_2_1'), 'key2' => array('value_2_1', 'value_2_2') ) values different, keys same on both arrays. built-in function $result = array_merge_recursive($array1, $array2);

javascript - Code with a ship which shooting wrong -

i posted before question not right. why shoots not following ship shooting????? stays @ 1 position if move ship away.......i added guess.....out of ideas..any appreciated. function shoot(){ context.fillstyle = "black"; context.fillrect(x2, y2--, 5,10); context.fillstyle = "red"; context.fillrect(x2, y2, 5,10); if (y2>=0) { timer=settimeout(shoot(), 1); } else { context.fillstyle="black"; context.fillrect(x2, y2, 5,10); y2=320; context.fillrect(x+23, y2, 5,10); } } heres fiddle solution http://jsfiddle.net/yabh4/ changed shoot function use player.x. , commented below 2 lines // context.fillrect(x2, y2, 5,10); y2=320; // context.fillrect(x+23, y2, 5,10);

activerecord - When creating a new record in Rails 3 get the value of field in previous record -

i trying value of form field of previous record when creating new record. basically each record has text area notes. when creating new record, instead of notes field containing static value or being blank, pull value of field created record. for example parent model customer , child model called stickies. i have tried calling: @customer.stickies.last.notes when nil . assume because when calling in view assumes last record record saved. know how can accomplish this. try using @last_note = @customer.stickies.last.notes before creating new record , use value show last note.

javascript - Consistency of `element.style.width` across browsers -

if have html <div id="container"> <div class="foo" style="width:75%;">bar!</div> </div> and if write javascript (assuming jquery benefit of question) alert( $("#container .foo")[0].style.width ); it should alert "75%". output consistent in every "modern" browsers? if not, popular non-standard browsers (even ie) fail return correct value? ** edit ** please! there 2 statements question marks... questions! now, let me add may not mislead answers... i know element.style available across browsers. i know element.style.width available. using jquery 1.3.2, calling $("#container .foo").css('width') return "75%" which not true since @ least version 1.6.4 (we're beyond major release too); recent jquery version output width in pixels now. so, considering given html, getting element's style.width return true, declared size (ie. in percentage) a

c# - Error "Object Reference not set to an Instance of an object" on read from DataGrid -

ok did quick test see if code set read datagrid, , does, once finishes reading error "object reference not set instance of object" , i'm not sure it's referring to. because loop continues after rows has reached end of datagrid? public static void uploadfromextrernalsource(plantareacode_createview paccreate) { // each row in datagrid, , each column, stores information in string. (int rows = 0; rows < paccreate.datagridview1.rows.count; rows++) { (int col = 0; col < paccreate.datagridview1.rows[rows].cells.count; col++) { string value = paccreate.datagridview1.rows[rows].cells[col].value.tostring(); console.writeline(value + ","); } } } edit: when print console, prints each value on new line. why? problem1 : trying convert null value 1 of cells string . solution1 : before converting cell value string null check. problem 2: using console.writeline() method displ

sh - Shell script, how to process line by line for $@ -

i reading in inputs file in shell script: sh script_name.sh < file.txt i know $@ have content of file, want iterate through each line of file since file has new entries on every line. i tried this: for in $@ echo $i done but seems work.. note said echo $i in example, want other manipulation. i having issues accessing elements in $line below code while read line in $line: echo $i done done i saved in test.sh file , feed in following test.txt file: hello world time world food this got output: hello world: time good: world food: as can see there ":" @ end of second string while read line echo $line done regarding second requirement split each line on whitespace , process each field, need: while read line in $line echo $i done done you must have been writing python ;-), because you've accidentally got trailing : in example. you want: for

PHP - How to know if PHP script is being run via a Cron -

is there way can detect if script being run via cron job or via browser? there specific cron job http header or user agent? edit: trying make script can run directly (via url) , can scheduled cron job. whenever executed, want detect if script being run cron job , stuff in condition. there php_sapi_name() function that

How to count square matrix represented as vectors in clojure -

assume two-dimensional matrix represented vector of vectors, such innermost vectors each represent row in matrix . two-dimensional matrix square if number of rows equal number of columns. why loop-recur constraint? if can assume every row same size (regular structure), work: (defn is-square [m] (= (count m) (count (first m)))) if want check every row: (defn is-square [m] (apply = (count m) (map count m))) if really want use loop-recur reason: (defn is-square [m] (loop [[row & more] m] (if row (if (= (count row) (count m)) (recur more) false) true)))

spring - setting multiple request parameter Optional -

i stuck in big problem want ignore attributes of object not know how skip multiple attributes same request object here code testrequestinfo.java public class testrequestinfo extends basefilter { private string id; public string getid() { return id; } public void setid(string id) { this.id = id; } } basefilter.java public class basefilter { private paginginfo paging; public paginginfo getpaging() { return paging; } public void setpaging(paginginfo paging) { this.paging = paging; } } paginginfo.java @xmlrootelement(name = "paging") public class paginginfo { private integer totalnumofrows; private integer minrownumber; private integer maxrownumber; public paginginfo() { super(); } public paginginfo(integer totalnumofrows, integer maxrownumber, integer minrownumber) { super(); this.totalnumofr

python - How to send and receive data between flask framework web server and android app -

i unable communicate receive , send reply between web server(which uses flask framework) , android app code shown below. if possible can please post sample server end code might solve problem. package com.project.nsj; import java.io.ioexception; import java.io.unsupportedencodingexception; import java.util.arraylist; import java.util.list; import org.apache.http.httpresponse; import org.apache.http.namevaluepair; import org.apache.http.client.clientprotocolexception; import org.apache.http.client.httpclient; import org.apache.http.client.entity.urlencodedformentity; import org.apache.http.client.methods.httppost; import org.apache.http.impl.client.defaulthttpclient; import org.apache.http.message.basicnamevaluepair; import android.app.activity; import android.content.intent; import android.os.asynctask; import android.os.bundle; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.edittext; import android.widg

vector - How to check if a matrix is upper-triangular in clojure -

i want write function compute upper triangular nature of matrix. lets a_i_j number in i^th row , j^th column. matrix upper-triangular if a_i_j = 0 > j. try this: (defn is-upper-triangular [m] (->> (map-indexed vector m) (mapcat (fn [[r v]] (take r v))) (every? zero?))) the above code take 0 element first row, 1 element second row, , 2 elements third rows, etc... , checks taken elements zero. if zero, upper triangular. this code not check given matrix square. can add check if necessary.

java - Nested loop causing massive Garbage collection in android? -

i have piece of code in android, causing massive logs of gc // when turning frequency domain we'll need complex numbers: byte audio[] = out.tobytearray(); //approx size 827392 int amountpossible = 200; complex[][] results = new complex[amountpossible][]; // chunks: (int times = 0; times < amountpossible; times++) { complex[] complex = new complex[4096]; (int = 0; < 4096; i++) { // put time domain data complex number imaginary // part 0: complex[i] = new complex(audio[(times * 4096) + i], 0); } // perform fft analysis on chunk: results[times] = fft.fft(complex); } below few of logs d/dalvikvm(10602): gc_concurrent freed 805k, 88% free 3911k/31075k, paused 2ms+5ms d/dalvikvm(10602): gc_concurrent freed 1796k, 88% free 3957k/31075k, paused 1ms+2ms d/dalvikvm(10602): gc_concurrent freed 1811k, 88% free 3970k/31075k, paused 1ms+3ms d/dalvikvm(10602)

javascript - How to call a function inside of a variable inside of another function? -

for example: function x() { var = 'hello'; var b = y(a); /*how think work*/ document.getelementbyid("greet").innerhtml=b; } function y(bill) { var c = bill+' billy!'; return; } i can't figure out! i've seen in code, how i've written it, before think code beyond outdated. since written in like.... 2000 think? want variable = bill in function y , put bill+' billy' output saying. hello billy! actual code lot more complex , has lot going on fudges up. change to: function y(bill) { var c = bill+' billy!'; return c; }

c# - Adding motion effect in asp.net website -

i developing website in asp.net c#. i have plus sign going through center end of each side dividing whole page 4 parts in each part have different information displayed. i want code draw plus sign starting center , ending on 4 sides on page load event of home page of website. i know possible using flash want code implement without using flash using jscript or other way. have link http://daneden.github.io/animate.css/ since not able implement code given in link. css file #pnlup { background-color:aqua; position:absolute; vertical-align:bottom; display:none; margin-left:47.85%; bottom:300px; overflow:hidden; } #pnldown { position:absolute; vertical-align:bottom; margin-top:0px; margin-left:47.85%; bottom:5px; } #down { background-color:aqua; height: 20px; } #down1 { background-color:aqua;

javascript - How to set a radiobutton active in jQuery radiobutton group -

i trying set radiobutton active standart jquery function in demo if onclick event. http://jqueryui.com/button/#radio i wanna same onclick not on click, wanna in function called. tried not working right: function checkradio() { $("#labelradiovu").button("enable"); $('#radiovu').prop('checked', true); //alert($("input[name='']:checked").val()) document.getelementbyid("labelradiovu").style.color = "white"; document.getelementbyid("labelradiovu").style.backgroundcolor = "red"; //document.getelementbyid("radiovu").checked = true; }; you can trigger click on radio $('#radiovu').trigger('click') example: http://jsfiddle.net/nzleu/

"android:supportsRtl" isn't work -

i'm trying make app support rtl , ltr and i'm using "android:supportsrtl" in manifest , change layout properties new start/end equivalents. similar this link my android 4.2 layout ltr! when i'm using rtl languages on device how should fix layout rtl? because want have rtl layout rtl languages check version of android studio , update it!

postgresql - how to create backup of postgres database using java -

i want take backup of postgres database using java. using following code this not working , not generating dump. string pgdump = "c:\\program files\\postgresql\\9.2\\bin\\pg_dump"; string dumpfile = "d:\\test\\"+ tenant.gettenantastemplate()+".sql"; string sql = pgdump+" -h localhost -u postgres -p postgres " + tenant.gettenantastemplate()+" > "+dumpfile; process p = runtime.getruntime().exec(sql); int time = p.waitfor(); system.out.println("time "+time); if(time == 0){ system.out.println("backup created"); } else{ system.out.println("fail create backup"); } here getting time 1. this operating system dependent , need pg_dump . there other way generate backup of database without pg_dump? please reply soon. no, there no way generate database backup without pg_dump , using

performance - LoadRunner - Doubts on Requirements -

our team planning implement loadrunner performance testing.please clarify me on these requirement issues? in how many systems can install licensed loadrunner? or onto single system? for controller, virtul user generator , load generator, need seperate machines or can in single machine? you in midst of change in loadrunner licensing universe. first historical view , next view now. historical. prior 8.0 you purchase controller license includes single license vugen , analysis. you may install many load generators wish. the controller node locked single host , must deregistered moved new host, involves mercury support best practice says controller , load generators not same machine (this tool independent performance testing tools). it highly use vugen , analysis on machine other controller. additional copies of vugen , analysis available purchase in singles or groups of 5 , ten virtual users tied controller license monitors licensed individually 8.0 thr

html - Stop overriding from previous CSS properties -

for example, given these 2 rules p { color: red; background: yellow } p { color: green } paragraphs appear in green text. have yellow background however, because first rule not negated. value color property overridden second rule background-color not in conflict, still applies. so there anyway stop applying background color property? i requiring such method because first rule may have n no. of attributes don't know beforehand. looking forward positive reply. that's why can define classes in css. the style defined same element overwritten if there duplicated properties , inherited previous definition same element. try: css p.red { color: red; background: yellow } p.green { color: green } html <p class="green">some text</p> <p class="red">another text</p>

ruby - How to sort an array of class objects based on date? -

i have following array of hashes: @products = {#<productproxy:0xb486d148 @pa={"productavailabledatets"=>"2013-12-04t23:07:12.592z", "mprice"=>, "pstock"=>, "id"=>, "productid"=>, "productdesignerid"=>}>, #<productproxy:0xb4adf304 @pa={"productavailabledatets"=>"2013-1-04t23:07:12.592z", "mprice"=>, "pstock"=>, "id"=>, "productid"=>, "productdesignerid"=>}>, #<productproxy:0xb4adecec @pa={"productavailabledatets"=>"2013-15-03t23:07:12.592z", "mprice"=>, "pstock"=>, "id"=>, "productid"=>, "productdesignerid"=>}>, ... } i want sort array based on productavailabledatets value, in descending order. tried doing following: @products = @products.sort_by{ |k| -k['productavailabledatets'] } but d

Clear properly a java arraylist -

i trying create 2d arraylist 2d array. ve got temp arraylistand parse 2d arraylist in loop. trying find correct way clear temp arraylist in order pass every time, correct values mags arraylist. (int m = 0; m < m; m++) { (int n = 0; n < n; n++) { (int = 0; < gaborwavelet.length; i++) { temp.clear(); (int j = 0; j < gaborwavelet[0].length; j++) { sum = gaborwavelet[i][j][m][n][0] / (m * n); temp.add((int) (sum * 170)); } mags.add(temp); } } } in above code final indexed-i passed in temp m*n*i times. edit: (int m = 0; m < m; m++) { (int n = 0; n < n; n++) { (int = 0; < gaborwavelet.length; i++) { arraylist<integer> temp = new arraylist<integer>(); (int j = 0; j < gaborwavelet[0].length; j++) {

asp.net mvc - C# Order by in foreach -

i'm new mvc c#. here ready , working code (the part of working code). @foreach (var item in model) { <div style="height: 200px; "> @html.raw(@item.description) </div> } the problem description not displayed on page in proper order is. so, order of <div> s should different. how modify code works properly? the order of description field should ordered order column. use orderby extension method on ienumerable in system.linq namespace @foreach (var item in model.orderby(i => i.order)) { <div style="height: 200px; "> @html.raw(@item.description) </div> }

php - Can't insert links to DB -

i have code: if (!empty($_post['w1']) && !empty($_post['l1'])) { $str = "<a href='".$_post['l1']."'>".$_post['w1']."</a>"; $content = str_replace($_post['w1'],$str, $content); } $content = nl2br($content); echo "נוסף"; echo $content; mysql_query("insert `posts` values ('','".$_post['subject']."','$content','0')"); the php page doesn't return error. data isn't inserted db. know problem? if there mysql error thrown, not shown you. following see error: mysql_query("insert `posts` values ('','". mysql_real_escape_string($_post['subject']) . "','" . mysql_real_escape_string($content) . "','0')") or die mysql_error(); be aware of sql-injections!

java - Persistent No Class Def Found Error and external JAR issues -

Image
my code reads import android.os.bundle; import rita.wordnet.riwordnet; import java.util.*; import android.app.activity; import android.content.intentsender; import android.view.menu; import android.widget.textview; public class mainactivity extends activity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); textview strlab; strlab=(textview)findviewbyid(r.id.textview1); riwordnet wordnet = new riwordnet(); string word = "diode"; system.out.println("\nfinding parts of speech " + word + "."); string[] partsofspeech = wordnet.getpos(word); (int = 0; < partsofspeech.length; i++) { strlab.settext(""+partsofspeech[i]); } } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.main, menu); retu

django - Which of autoescape tag and safe filter is better to use? -

i looking way unescape html in variables written in django template , found answer here . so, there 2 ways of doing it: set autoescape off : {% autoescape off %}{{ myhtmlstring }}{% endautoescape %} using safe filter: {{ myhtmlstring | safe }} my question 1 more adequate use (and in context). feeling safe filter django specific, on contrary autoescape seems used in jinja2. but, own way of thinking ?

indexing - How to divide data from different index with gnuplot? -

i've not found way (maybe because there none?): i've got different set of data such : #index 1 1 4 2 8 3 12 4 16 5 20 #index 2 1 1 2 4 3 9 4 16 5 25 and i'd : plot using 1:($(index1:2)/$(index2:2)) i.e. dividing value of first set of second set (to normalize) is there way gnuplot? i can't in gnuplot level. try use join unix command.

java - How to make two separate frames disappear to make way for another one? -

i have 3 frames, let's call them frame welcome, frame main, frame sub. they're in separate classes. frame welcome has button makes frame main visible when clicked. frame main has button makes sub pop when clicked (sort of dialog box yeah has graphical design figured out put in separate frame, though i'm considering jpanel i'm not sure how that: how make pop when it's in jpanel, possibly setvisible havent tried yet might try later), there button in frame sub when clicked, should make frame main , frame sub invisible , display frame welcome instead. at moment, have code making sub disappear , make welcome appear, can't figure out how make main invisible too. public void actionperformed (actionevent e) { if (e.getsource() == btn) { framewelcome fw = new framewelcome(); setvisible(false); fw.setvisible(true); } } this makes frame sub invisible , frame welcome visible, how make frame main invisible (sub sort of inside main, because it's displayed wh

html - jQuery mouseleave and clearInterval not working -

i'm starting play svg images, i've made 2 gearwheels should turn on .mouseenter() , stop on .mouseleave(). turning made setinterval function. have strange problem because on linux chromium works well. on linux firefox , windows chrome , firefox gearwheels aren't stopping on mouseleave , speed on mouseenter. trying both .hover() , .mouseenter()/mouseleave() methods. my code: $(document).ready(function(){ var deg = 0; var rotate_right = $('#cog1 use'); var rotate_left = $('#cog2 use'); var interval; $("#cogs").hover( function(){ interval = setinterval(function(){ if(deg >= 360) deg = 0; deg += 1; rotate_right.attr('transform', 'rotate('+deg+',32,32)'); rotate_left.attr('transform', 'rotate('+-deg+',32,32)'); }, 10); }, function(){

java - Email validation using Regular expression -

this question has answer here: regular expression email validation in java 6 answers i didnot find kind of type of email id can please tell me how validate below email using regular expression email id - xyzabc@co.xyz-gordo.in.zs i using below pattern ^[_a-za-z0-9-\\+]+(\\.[_a-za-z0-9-]+)*@"+ "[a-za-z0-9-]+(\\.[a-za-z0-9]+)*(\\.[a-za-z]{2,})$ for email validation use apache commons email validator . simple use , don't need invent wheel ;-)

matlab - How I can create a movie from a bunch of plots -

i beginner make movie. need make movie bunch of plots. how can make it. have 8 plots , y versus x. want make movie based on x see how y change increasing x. please consider matlab file below: x=[1 1.2 1.4 2 3 4 5 7 9 10]; y1=[2.8 7.6 10.9 12.3 15.0 21 12.3 14.5 42.4 47.7]; y2=1e8.*[0.599e-7 0.607e-7 0.343e-7 0.3e-7 0.873e-8 0.578e-8 0.298e-8 0.725e-9 0.14e-8 0.478e-9]; y3=10.*[0.136 0.544 0.834 1.03 0.366 0.314 0.703 0.207 0.696 0.164]; y4=10.*[0.26 0.21 0.17 0.25 0.31 0.34 0.16 0.15 0.13 0.31]; y5=.... y6=... y7=... y8=[6 7.6 10.9 12.3 15.0 21 12.3 19.5 42.4 47.7 ]; plot(x,y1) hold on plot(x,y2) hold on plot(x,y3) hold on plot(x,y4) hold on plot(x,y5) hold on plot(x,y6) hold on ... plot(x,y8) i wrote following simple example not work: clc;clear all; x=[1 1.2 1.4 2 3 4 5 7 9 10]; y = zeros(4,10); y(1,:)=[2.8 7.6 10.9 12.3 15.0 21 12.3 14.5 42.4 47.7 ]; y(2,:)=1e8.*[0.599e-7 0.607e-7 0.343e-7 0.3e-7 0.873e-8 0.578e-8 0.298e-8 0.725e-9 0.14e-8 0.478e-9]; y(3,:)=10.*[0

java - IntelliJ unable to find variable in SPeL -

i trying add spring @cacheable annotation method @cacheable(value="targets", key="#url") public target decompose(string url) { return urlstylespecificdecomposer.decompose(url); } this compiles , works fine, intellij giving me warning on spel cannot resolve variable 'url' checks spring expression language (spel) problems is there problem way specifying this, or intellij bug can safely ignore , suppress? i have same warning intellij 14.0.2 , inline list key intellij show error key values: '}' expected got '#' @cacheable(value = "getarticles", key = "{#limit,#offset}", unless = "#result == null") public list<articles> getarticles(int limit, int offset) { } i think intellij issue.. https://youtrack.jetbrains.com/issue/dexp-22243

Javascript replace string which doesn't match? -

say have string: cat hates dog when replace : str = str.replace('cat', 'fish'); i "cat" replaced "fish" , how works this: "cat" replaced "fish" "other string"(else) replaced "goat" so new string: fish goat goat you can use regexp \b\w+?\b : "cat hates dog".replace(/\b\w+?\b/g, function(a) { return === 'cat' ? 'fish' : 'goat'; }); it match every word (sequence of word characters \w surrounded word boundary \b ) , pass match results in replace callback; output: fish goat goat

c# - write data to csv file sheet 2 -

i want write data datatable csv file starting sheet 2 in c#. please. have following function create csv file. public void createcsvfile(datatable dt, string strfilepath) { // create csv file grid data exported. streamwriter sw = new streamwriter(strfilepath, false); // first write headers. //datatable dt = m_dsproducts.tables[0]; int icolcount = dt.columns.count; (int = 0; < icolcount; i++) { sw.write(dt.columns[i]); if (i < icolcount - 1) { sw.write(","); } } sw.write(sw.newline); // write rows. foreach (datarow dr in dt.rows) { (int = 0; < icolcount; i++) { if (!convert.isdbnull(dr[i])) { sw.write(dr[i].tostring()); } if (i < icolcount - 1) { sw.write(&q

ios - counter inside enumerateObjectsUsingBlock -

i need iterate through nsarray calculate metrics (total height). here's code: __block cgfloat height = someinitialvalue; [messages enumerateobjectsusingblock:^(id obj, nsuinteger idx, bool *stop) { if (condition1) height += somevalue; if (condition2) height += somevalue; }]; each iteration starts height = someinitialvalue . want continually increase height . possible calculate total height block-enumeration or have use fast enumeration? you increasing height in code here. height marked __block identifier means can set within block. the nsuinteger idx block parameter counter loop (in case need that). there seems no reason use block enumeration in case.

sql server - sql query to insert received parameters from user, and Get records from a existing table and insert into another existing table -

anyone please me here stored procedure in sql server: alter procedure existingbook @title nvarchar(50), @author nvarchar(50), @number nvarchar(50) declare @sno int begin if exists(select * students title = @title) begin select @sno = count(*) teacher if (@author='proof') if (@number>'20') insert teacher(@sno+1, team, @title, getdate(), @number, pmname, comments, isbn, null, null) select team, pmname, comments, isbn students title = @title end end when execute above query error the name "team" not permitted in context. valid expressions constants, constant expressions, , (in contexts) variables. column names not permitted. i knew reason above query i tried in different way query execute records duplicated please 1 me insert query not formed correctly. i t

delphi - TIdTcpServer connection limiting -

i want restrict number of incoming connections tidtcpserver can take, rule need apply little complex, don't think maxconnections property work me. i have application running n servers, each using different protocol on different port. need limit total number of clients across n servers. example, 16 servers, , 16 clients allowed, allow 1 client on each, or 16 on single server. it's possible manipulate maxconnections dynamically fix (e.g. set them 0 when determine we're 'full', , 16 or whatever when we're not full, feels little tricksy. is there kind of virtual isconnectionallowed method can override own logic, or suitable place in connection process can raise exception if determine limit has been exceeded? create new component - tidtcpservercollection example - "owner" of server components. in component, declare thread-safe property stores available - unused - connection count. in server connect , disconnect logic, decrement /

not found message for wordpress custom taxonomy -

i created custom taxonomy named cancers , template file taxonomy named taxonomy-cancers.php when call url: http://localhost/cancers http://localhost/?tax=cancers wordpress shows page not found , doesn't use taxonomy template. code defining custom taxonomy: add_action( 'init', 'create_cancers_taxonomy', 0 ); function create_cancers_taxonomy() { // add new taxonomy, make hierarchical (like categories) $labels = array( 'name' => _x( 'سرطان‌ها', 'taxonomy general name' ), 'singular_name' => _x( 'سرطان', 'taxonomy singular name' ), 'search_items' => __( 'جستجو در میان سرطان‌ها' ), 'all_items' => __( 'تمامی سرطان‌ها' ), 'parent_item' => __( 'دسته اصلی' ), 'parent_item_colon' => __( 'دسته اصلی:' ), 'edit_item' => __( 'ویرایش سرطان' ), 'update_item' =>

forms - How to add class and diffrent paramter to every option in a dropdown in Zend Framework 2 -

the title clear , want add class , data-imagesrc using custom dropdown : but code wont $this->add(array( 'name' => 'require_course_id', 'type' => 'zend\form\element\select', 'attributes' => array( ), 'options' => array( 'label' => 'prerequisite', 'value_options' => array(array('label'=>'test','class'=>'test-class','data-imagesrc'=>'myimage')),//$this->getprerequisite(), ), )); if take @ zend\form\view\helper\formselect::renderoptions() able see how each <option> generated (and how supplied configuration merged produce final html string). provide option tag's 'specification' array attribute key (just select element itself). $this->add(array( 'name' => 'requi

How to call a class objects's method if it is not assigned to a variable in python? -

please see code below, how call getcurrentselection() method of choice() object below? choice() object not assigned variable. import wx class choiceframe(wx.frame): def __init__(self): wx.frame.__init__(self, none, -1, 'choice example', size=(250, 200)) panel = wx.panel(self, -1) samplelist = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'] wx.statictext(panel, -1, "select one:", (15, 20)) wx.choice(panel, -1, (85, 18), choices=samplelist) if __name__ == '__main__': app = wx.pysimpleapp() choiceframe().show() app.mainloop() if written way: choice_object = wx.choice(panel, -1, (85, 18), choices=samplelist) then do: choice_object.getcurrentselection() but has no variable names, how call getcurrentselection() method in original code above? yo

c# - Can I turn this into a lambda statement? -

i wondering if it's possible turn while loop lambda statement? know it's possible if or foreach loop, it's normal, plain while loop: while (path.substring(path.length - 4) != ".txt" || path.substring(path.length - 4) != ".xml") { console.writeline("file not .txt or .xml extension! enter file name:"); path = console.readline(); } if possible, how 1 transform loop such lambda statement? given comments on question suggest isn't lambdas, minimizing code, here small suggestions avoid code duplication: string[] validextensions = { ".txt", ".xml" }; { console.writeline("enter file name:"); path = console.readline(); if (!validextensions.contains(path.getextension(path))) { console.write("file not .txt or .xml extension! "); path = null; } } while (path == null); checking extension merely requires adding extension array, doesn't require dupl

php - Replacing the price tag "0.00" with "Call" -

am trying replace price tag has default price of "0.00" "call".they asked me insert code on line of code below. code below code in functions.php page. function get_listing_price(){ if(get_field("price_layout","options") == "right"){ echo number_format(get_field("price"), 2, '.', ',')." "; } echo the_field("currency_value","options"); if(get_field("price_layout","options") != "right"){ echo " ".number_format(get_field("price"), 2, '.', ','); } } sigh oh, alright then: function get_listing_price() { if(!get_field("price")) { echo "call"; } else { if(get_field("price_layout", "options") == "right"){ echo number_format(get_field("price"), 2, '.', ',')." "; }

ios - how to retrieve multiple images got from server and show them in UIImageView with swipe -

how add swipe gesture multiple images retrieved server. str=@"but1.jpg,but2.jpg" server.how show both these images stored in string swipe. single image showing server getting response server based on key "image_names" ,am storing in string.my code below url=@"http:.........."; str=[dict1 valueforkey:@"image_names"]; if (str!=nil) { strimg=[url stringbyappendingstring:str]; dispatch_async(dispatch_get_global_queue(0,0), ^{ nsdata *data = [[nsdata alloc] initwithcontentsofurl:[nsurl urlwithstring:strimg]]; if ( data == nil ) return; dispatch_async(dispatch_get_main_queue(), ^{ uiimage *img=[uiimage imagewithdata: data]; imgview.image=img; }); }); } i not getting question can add swipe gesture image below lines of code. uiswipegesturerecognizer *swipeleftgesture = [[uiswipegesturerecognizer alloc] initwithtarget:self action:@selector(swipeleftgesture:)]; uiswipegesturerecognizer *swiperigh

how to convert JSON characters like \\u00e1 to their original character in perl -

i using perl , got json format parsing.i used json::xs parsing json format in perl. want characters \u00e1 converted á .how do this? parsing json data will give character. perhaps need encode output? perl -mjson::xs -e'binmode(stdout, ":utf8");say shift json::xs::decode_json(q|["\u00e1"]|)'

ios - I couldn't draw fully gradient background on iPad -

Image
i drew gradient background layer on uicollectionview following code. cagradientlayer* collectionradient = [cagradientlayer layer]; collectionradient.bounds = self.collectionview.bounds; collectionradient.anchorpoint = cgpointzero; collectionradient.colors = [nsarray arraywithobjects:(id)[startcolor cgcolor],(id)[endcolor cgcolor], nil]; uiview* vv = [[uiview alloc] init]; self.collectionview.backgroundview = vv; [self.collectionview.backgroundview.layer insertsublayer:collectionradient atindex:0]; it works on iphone simulator. not ipad. below image that. background layer taking part of uicollectionview. i suggest creating subclass of uiview named gradientview or similar use background view. in implementation of gradientview need overload following class method: + (class)layerclass { return [cagradientlayer class]; } then, change code above following: uiview* backgroundview = [[gradientview alloc] initwithframe:self.collectionview.bounds]; backgroundview.

r - Remove spaces around bars in PDF output -

Image
i have bar plot: > data = c(1, 5, 3, 4) > barplot(data, space = 0, col = 'gray', border = 0) on os x, using default driver (quartz), looks this: notice how there no space between bars. however, when exporting figure pdf, either via quartz.save('file.pdf', type = 'pdf') or via pdf('file.pdf', type = 'pdf') followed barplot(…) the output looks this: there discernible lines between bars. unfortunately, in case more aesthetic nuisance: i’m plotting lot of pixel-thin bars, , space between bars big bars themselves, changes perception of plot drastically. is there way rid of lines in output? preferably when using pdf device rather pdf quartz output? this should work: barplot(data, space = 0, col = 'gray', border = 'gray') edit: extended answer. if define color of border same fill, should work. following code produces plot below: data = c(1, 5, 3, 4) pdf('file.pdf') barplot(da

java - Have System properties always values -

do system.getproperty("line.separator") , system.getproperty("os.name") have values? or need check return value in code null ? yes, inserted automatically jvm

show sales report to pass the parameter like month,date to Magento Soap api -

i fetching sales report magento store use soap api. working fine show sales report. want custom report pass specific month or date. how can possible code follow. $mage_url = 'https://domain.com/index.php/api/soap/index/wsdl/1'; $mage_user = 'mohammad'; $mage_api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; // initialize soap client $soap = new soapclient( $mage_url ); // login magento $session_id = $soap->login( $mage_user, $mage_api_key ); // start session make api requests $resources = $soap->resources( $session_id ); $products = $soap->call($session_id, 'sales_order.list'); this useful developers for completed orders $products = $soap->call($session_id, 'sales_order.list', array(array('status'=>array('eq'=>'complete')))); for specific period $thedate = date("y-m-d", strtotime("1 month ago")); $thesearch =array(array('updat