Posts

Showing posts from February, 2013

Android's spinner text align right -

Image
i has spinner contains 3 items:"english", "simplified chinese", "traditional chinese". if select "english", spinner show below picture. means after select , show selected one, not items list below: layout.xml below: <relativelayout android:layout_width="match_parent" android:layout_height="match_parent" > <spinner android:id="@+id/spinner1" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_alignparentright="true" android:layout_centervertical="true" android:background="@drawable/spinner_selector" android:gravity="right" /> </relativelayout> i want set text align right. width see

mysql - How should I write case statement depend of parameters key? -

for example have index action: def index if params[:query] @pharmaceutics = pharmaceutic.where("name ?", params[:query]) elsif params[:code] @pharmaceutics = pharmaceutic.where("barcode ?", params[:code]) else @pharmaceutics = pharmaceutic.all end end and when send 2 params: code , query filter pharmaceutics using both of them. have mysql database. i use scoped method, this: def index scope = pharmaceutic.scoped # pharmaceutic.all if use rails 4 scope = scope.where('name ?', params[:query]) if params[:query].present? scope = scope.where('barcode ?', params[:code]) if params[:code].present? @pharmaceutics = scope end you can write custom scopes , replace where(...) them make code clearer.

javascript - Fetching values from user entered data -

i have made dynamic addition of rows containing text fields , drop downs . want fetch values user has entered in text input field , drop down , have display in table format. code fetching values function fetch(){ var myname = document.getelementbyid("name"); var type = document.getelementbyid("type"); var table = document.getelementbyid("mytabledata"); var rowcount = table.rows.length; var row = table.insertrow(rowcount); row.insertcell(0).innerhtml=myname.value; row.insertcell(1).innerhtml= type.value; row.insertcell(2).innerhtml= '<input type="button" value = "delete" onclick="javacsript:deleterow(this)">'; } by above line of codes trying fetch values enterd user in dynamically added rows , below code add rows dynamically function addrow(tableid) { var table = document.getelementbyid(tableid); var rowcount = table.rows.length; var row = table.insertrow(ro

php - Check JSON file when uploading -

i creating upload function want upload json file. my json string inside file : {"name":"john"} my php code: $filetype = $_files['uploaded']['type']; if ($filetype != "application/json") { print 'not valid json file'; } also tried: $filetype = $_files['uploaded']['type']; if ($filetype != "text/json") { print 'not valid json file'; } when trying upload json file shows me 'not valid json file' error. plz me wrong code. there no explicit file type set when creating *.json files. instead files mime-type going application/octet-stream , binary file, typically application or document has opened in application. check array $_files['uploaded'] type.

function - Jquery centering div on page and chopping off the top -

i using following jquery script center container div in middle of window. problem comes when user has resolution smaller container, when site loads top of div chopped off. how can set function trigger if browser size or resolution bigger container div ?. <script> $(window).load(function(){ var positioncontent = function () { var width = $(window).width(); // window width var height = $(window).height(); // window height var containerwidth = $('.container').outerwidth(); // container div width var containerheight = $('.container').outerheight(); // container div height $('.container').css({position:'absolute', left: ($(window).width() - $('.container').outerwidth())/2, top: ($(window).height() - $('.container').outerheight())/2 }); }; //call when window first loads $(document).ready(positioncontent);

Java foreach using reference to replace items won't work -

in exercice must replace object within loop. solution use "listiterator". colleague try use foreach syntax , play reference solution won't work. // doesn't work ( growable growable : growables ) { growable = growable.grow(); // return object (seed -> sprout, ..) } // (final listiterator<growable> = growables.listiterator(); it.hasnext();) { it.set(it.next().grow()); } from documentation[1], can read foreach not suitable replacement because don't have reference iterator. the program needs access iterator in order remove current element. for-each loop hides iterator, cannot call remove. therefore, for-each loop not usable filtering. not usable loops need replace elements in list or array traverse it. but have reference iterated object. wrong ? can explain me why "foreach" solution isn't working ? thanks [1] http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html in first snippet, take element gro

java - How do I change the text of a paragraph using servlet? -

i have paragraph id = story , want change text dynamically using servlet. how do this? i'm new , using getwriter().println() seems create new document instead of appending existing one. thanks simple answer - can't. server-side code cannot change response has been sent client. change text inside html tag, use javascript on browser. see http://www.w3schools.com/ajax/

sql server - Delete multiple rows by sql statement "delete from tableName" whereas TRIGGER "After Delete" had applied on that -

i have applied "after delete" trigger on 1 table, below script: alter trigger [dbo].[ondelete_n_ur] on [dbo].[notification_unread] after delete begin set nocount on; declare @roid int set @roid=(select reachoutid deleted(nolock) deleted.notificaiontype='reachoutlike') update cache_reachout set cache_reachout.likecount=(select [dbo].[getreachout_notification_count](@roid,'like') ) cache_reachout.reachoutid=@roid end now trying delete rows in bulk using following sql statement: delete notification_unread notification_id=**** and it's giving me error subquery returned more 1 value. not permitted when subquery follows =, !=, <, <= , >, >= or when subquery used expression." how can delete multiple rows using above delete statement when delete trigger applied on . try 1 - alter trigger [dbo].[ondelete_n_ur] on [dbo].[notification_unread] after delete begin set nocount on; declare

jQuery & Phonegap issues with preloading DOM -

i've been diving google , stackoverflow before, didn't find solution this. my issue following: i'm using phonegap (cordova 3.0) , jquery mobile 1.3.1 android. before first view loads i'm experiencing white screen, guess dom initializing before images loaded on top. i changed background black, 1 still white. what want achieve? when view not loaded completely, background should black user has experience of "the app hasn't started yet". update 1: javascript code in onload , deviceready: <body onload="onload()"> <script type="text/javascript"> function onload() { document.addeventlistener("deviceready", ondeviceready, false); } function ondeviceready() { ... code } <script> </body> unfortunately no changes. i found out amount of time white screen displayed minimized after second app launch because of caching. my architectu

android - Issue setting AlertDialog -

i trying display alertdialog, compile error of (ambiguous) on following line: alertdialog.setbutton(dialoginterface.button_positive, "ok", null); how should set button? alertdialog.builder dlgalert = new alertdialog.builder(this); dlgalert.setmessage(getresources().getstring(r.string.err_connection)); dlgalert.settitle(getresources().getstring(r.string.err_connection_header)); dlgalert.setpositivebutton(getresources().getstring(r.string.ok), new dialoginterface.onclicklistener() { public void onclick(final dialoginterface dialog, final int which) { finish(); } }); dlgalert.setcancelable(true); dlgalert.create().show();

c# - Serializing multiple DateTime properties in the same class using different formats for each one -

i have class 2 datetime properties. need serialize each of properties different format. how can it? tried: jsonconvert.serializeobject(obj, formatting.none, new isodatetimeconverter {datetimeformat = "mm.dd.yyyy"}); this solution doesn't work me because applies date format properties. there way serialize each datetime property different format? maybe there attribute? newtonsoft.json has structure that's bit difficult understand, can use following custom converter want: [testmethod] public void conversion() { var obj = new dualdate() { dateone = new datetime(2013, 07, 25), datetwo = new datetime(2013, 07, 25) }; assert.areequal("{\"dateone\":\"07.25.2013\",\"datetwo\":\"2013-07-25t00:00:00\"}", jsonconvert.serializeobject(obj, formatting.none, new dualdatejsonconverter())); } class dualdate { public datetime dateone { get; set; } public datetime

python - Why doesn't daemon thread die when its environment is destroyed? -

i have python script starts thread thread. learning exercise realise ability kill python thread , have use in application writing. ignoring red herring, thread firstthread starts thread secondthread our purposes caught in loop , has no resources release. consider: import threading import time class firstthread (threading.thread): def run(self): b = secondthread() b.daemon = true b.start() time.sleep(3) print("firstthread going away!") return true class secondthread (threading.thread): def run(self): while true: time.sleep(1) print("secondthread") = firstthread() a.daemon = true a.start() print("waiting 5 seconds.") time.sleep(5) print("done waiting") although firstthread print "firstthread going away!" after 3 seconds expected, secondthread continues print "secondthread" stdout. expected secondthread destroyed firstthre

c++ - Copy control for pointers in string -

so have test , while studying came following question don't understand (nor question or answer) i know coding, don't understand nonsense try teach us. question is: q: class string has pointers array of char. of 3 copy control solutions pointers, class must define? a: value_like semantics i know string array of chars, don't know "copy control solutions", i'm not sure copy control (copy constructor maybe??) , value_like semantics?? hope question makes sense, translated hebrew. thanks :) "copy control solutions" refers implementation strategies copy constructor , copy assignment. assume textbooks @ point list 3 solutions pointers, given peculiarly specific wording of question. therefore, them , understand about. knowing how implement copying resource-managing objects 1 of essential language-specific skills c++ programmer.

python - Regular expression to search only websites names from random text -

i want create regular expression search , return website names text. e.g. "hello, total description of deals below: mango: maangobar22.com total deals : 0 apple: myapplesite22.com total deals : 3 berrymine22.com total deals : 0 hope hear soon" i want search websites name , store them in different variable. i created following re since new re, unable think start. import re import sys text = "hello, total description of deals below: mango: maangobar22.com total deals : 0 apple: myapplesite22.com total deals : 3 berrymine22.com total deals : 0 hope hear soon" num = re.match(r'+..com', "", text) print('phone num : ', text) a1 = num.group() a2 = num.group(1) a1 = num.group(2) a2 = num.group(3) any highly appreciated. you use following example: import re websites = re.findall(r'(\s+[.]com)', text) # ['maangobar22.com', 'myapplesite22.com', 'berrymine22.com']

asp.net - How to generate a dropdown list from another? -

i want generate drop down list drop down list. have dropdown of countries. when selecting country,another dropdown must come values states of specific country. how in asp.net using c#? for each country have, add new list item drop down list, text country , value id of country. on second drop down list, set auto post property true , add event on selected item change. in event code, selected item , second ddl. try it! tip: add hidden field on page, , on selected item changed event first ddl, set value of hidden field, selected value. on page_load event, verify if value string.empty , if id in value. if is, bind second ddl.

java - Accessing private field in a subclass -

i'm creating class extends propertychangesupport . want override firepropertychange() : firepropertychange implemented in propertychangesupport: public void firepropertychange(string propertyname, object oldvalue, object newvalue) { if (oldvalue == null || newvalue == null || !oldvalue.equals(newvalue)) { firepropertychange(new propertychangeevent(this.source, propertyname, oldvalue, newvalue)); } } my intended override of firepropertychange : public void firepropertychange(string propertyname, object oldvalue, object newvalue) { if (oldvalue == null || newvalue == null || !oldvalue.equals(newvalue)) { firepropertychange(new joystickpropertychangeevent(this.source, propertyname, oldvalue, newvalue)); //compile error: source not visible } } joystickpropertychangeevent class created , extends properychangeevent . the problem intended implementation not compile because source private , has no getters in propertychangesupport , subclass

internationalization - Wrong Java resource bundle loaded -

in application, i'm using java resource bundle translation of labels. have 2 files: resources.properties labels in english (default language) resources_fr.properties labels in french then, load bundle properties following command: resourcebundle.getbundle(resource_bundle_name, locale); ... locale user's locale. when i'm working french web browser, that's ok, i'm getting messages in french, locale correctly set fr. when switch browser english us, they're still in french! the locale variable correctly set en_us locale, getbundle method returns me bundle fr locale instead of returning default bundle... is normal behaviour? i'm surprised, expecting english values of resources.properties used when locale has no specific resource bundle attached (like french)... this might clarify question: http://docs.oracle.com/javase/tutorial/i18n/resbundle/propfile.html these locale objects should match properties files created in pre

php - __clone method is not making copy of class object -

i want use __clone() making copy of class object , after want print copy object. here code: <?php class test { public static $counter = 0; public $id; public $other; public function __construct(){ $this->id = self::$counter++; } public function __clone() { $this->other = $that->other; $this->id = self::$counter++; } } $obj = new test(); $copy = clone $obj; print_r($copy); ?> instead of $copy = $obj->__clone(); you should use $copy = clone $obj; the __clone() method called when call clone

html - How can I read a specific line of TXT file in my computer using Javascript? -

i have database.txt in c:\ containing data line line. how can specific nth line of txt embed texts between lines data? example of database.txt : real madrid barcelona bayern munich manchester united what want write : haha 1 real madrid hoho haha 2 barcelona hoho haha 3 bayern munich hoho haha 4 manchester united hoho can specific line embedding given text specific pattern?? thanks. you cannot javascript browser since not allow read files disk. can making xmlhttprequest aspx or ashx returns file string. split string on newline \n , take line want index.

c# - In WPF, a property should be changed by its name or by use of binding -

i new wpf , question arose in mind while developing app. assume have textbox defined below <textbox x:name="mytextbox" /> then in c# code, can change string shown in textbox using following command mytextbox.text = "hello!"; however, there way have same behavior use of binding when in xaml have <textbox x:name="mytextbox" text="{binding content}" /> and in c# have public class mytext : inotifypropertychanged { public event propertychangedeventhandler propertychanged; private string _content; public string content { { return _content; } set { _content = value; propertychanged(this, new propertychangedeventargs("content")); } } } mytext txt = new mytext(); mytextbox.datacontext = txt; txt.content = "hello!"; obviously second option needs more coding, result of both of them same. however, in second case not have care execu

javascript - Overriding inherited prototype method and calling the original one inside the new one -

in following piece of code, how can access a.prototype.log inside of b.prototype.log ? function a() {} a.prototype.log = function () { console.log("a"); }; function b() {} b.prototype = object.create(a.prototype); b.prototype.constructor = b; b.prototype.log = function () { //call a.prototype.log here console.log("b"); }; var b = new b(); b.log(); i know write a.prototype.log.call(this) thought maybe there more elegant way, lets me call in relative way, "call method 'log' of next higher instance in prototype chain". possible? you use object.getprototypeof ... b.prototype.log = function () { object.getprototypeof (b.prototype).log.call(this) console.log("b"); }; ... b.log(); //a b note: object.getprototypeof ecmasript 5, see compatibility there non standard , deprecated __proto__ property ( compatibility ) references same object internal [[prototype]] and allow call a s' l

jquery - Primefaces - custom component for live filtering in dataTable -

primefaces has done filter p:datatable. great ux site, because filter field in column header, there's no doubt filtering, , it's working live - data changes type (well, if make short pause, it's in opinion user expects). now i'd place custom in header act filter. so, idea place component in header facet: <p:column ...> <f:facet name="header"> <some:mycomponent onkeydown="filteraction()"/> </f:facet> </p:column> the problem filteraction must not update whole datatable component (because component user typing in re-created), must update table body. i've thought can primefaces selectors (based on jquery selectors), according topic how update data rows using selector datatable? not possible. , datatable.js contains specialized ajax call achieve (line: 839 in primefaces 3.5, release): options.onsuccess = function(responsexml) { var xmldoc = $(responsexml.documentelement), upda

wpf - How to get PathFigureCollection bounding rectangle -

is possible find bounding rectangle of pathfigurecollection object, in c# ? (i know how using frameworkelement that's not want) try include pathfigurecollection in pathgeometry object, , can access bounding rectangle via bounds property. example var geometry = new pathgeometry { figures = new pathfigurecollection() }; var boundingrect = geometry.bounds;

java - How to make a Thread from its ExecutorService communicate with a Runnable? -

i'm using executorservice parsing files: executorservice service = executors.newfixedthreadpool(10); and later: service.submit(new fileparser(file)); however tools used parse files require initialization takes quite long. i'd perform initialization once per thread (not once because initialization parameters not thread-safe), , perform parsing in submitted runnable. i saw threadfactory can used provide own threads executor, initialize parameters way: public class mythreadfactory implements threadfactory { public thread newthread(runnable r) { return new mythread(); // initialization part inside constructor } } however have no idea on how provide new file parse thread... idea? thanks you can use threadlocal variable initialization. during each execution, can check if have executed initialization current thread , use storing whatever need.

highcharts - Delay after addpoint when y-axis with opposite: true -

i want make chart adding many points series.addpoint( [xtime, yvalue], true, true); works fine, if chart big whole container filled , use opposite:true y-axis, last point missing shown, when next point has been added. without opposite:true can see points correctly added, have put y-axis right. tried increase offset, didn't solve problem. how can show last point? here jsfiddle: http://jsfiddle.net/charissima/tfheu/1/ in right corner, actual y value displayed. can see, chart displayed correctly until reaches right margin. afterwords chart 1 step behind. var prevy = 0; var data = []; var time = (new date()).gettime(), i; // getting first data, show diagonals (i = -19; <= 0; i++) { data.push({ x: time + * 1000, y: math.round(math.random() * 11) }); } $(function () { $(document).ready(function() { highcharts.setoptions({ global : { useutc : false }, lang: { month

select - sql LIKE statement combined from three "like"`s -

how combine sql query 3 statements? i`m trying this: select * mytable (name '%somechars%' , (city '%somechars%' , type like'% somechars%') ); it doesn`t work, can me please ? the query correct except fact type sql keyword, try putting between bracket that: select * [mytable] ([name] '%somechars%' , ([city] '%somechars%' , [type] '%somechars%')); ps: parenthesis not needed

vb.net - Asp.net control with custom event -

i have control has custom event. currently define other event public event contentchanged eventhandler but today found article had totally different way of handling it shared readonly contentchangedkey new object() public custom event contentchanged eventhandler addhandler(value eventhandler) me.events.addhandler(contentchangedkey, value) end addhandler removehandler(value eventhandler) me.events.removehandler(contentchangedkey, value) end removehandler raiseevent(sender object, e eventargs) dim contentchangeddelegate eventhandler = _ me.events(contentchangedkey) contentchangeddelegate(sender, e) end raiseevent end event the second way seems overly complicated first example doesn't?? it has overcomplication :) in other words can add in there other kind of processing needs done when envent happens or bound to. since controlling actions taken when event handler added, removed or raised, can

internet explorer 10 - Clearing javascript cache in ie10 not working, can no longer debug javascript changes -

Image
now have upgraded ie10, it's difficult javascript changed files recognized. in ie9, use 'clear cache' button in develepor panel , see javascript changes. this no longer works (apparently) -- there other way ie10 dump cache? brutal! on windows 7, using vs2010 , upgraded ie10. i think found out answer... appears ie10 either added (or added default) setting 'preserve favorites website data' ... checked (by default) , although havent thoroughly tested it, think why js files not being purged.

C++ open source console program -

i looking c++ console open source program, uses inheritance , virtual functions, polymorphism test cryptographic software on it. mainly, how handle virtual functions etc. far tested on c programs, appreciated. know, there google , bit off-topic believe me, googled lot of days, yet not find console c++ program. ones found had gui - not test them automaticly. i think, can find need in wikipedia http://en.wikipedia.org/w/index.php?title=category:free_software_programmed_in_c%2b%2b f/e rtorrent: http://en.wikipedia.org/wiki/rtorrent

How to capture specific strings from a file and dump it to diff file in perl -

i have log file contains results of various test conditions. looks like starting testcon1 msg1:criteria result:pass msg2:criteria result:fail starting testcon2 msg1:criteria result:fail msg2:criteria result:pass starting testcon3 msg1:criteria result:pass i want create subroutine picks out "msg have failed along testcon belong to.this dumped summary file showing--> msg failed ,the result , testcon belongs to i have no clue start ,can give me idea start with read file, use regex , variables. #!/usr/bin/env perl $testcon; $msg; while (<stdin>) { if (/^starting (.+)$/) { $testcon = $1 } elsif (/^msg(\d+:\s*.+)$/) { $msg = $1 } elsif (/^result:\s*fail$/) { print "$testcon\t$msg\n" } }

Insert new rows into Google Spreadsheet via cURL/PHP - HOW? -

is there script or tutorial on how this? how implement inserting of data php application google spreadsheet? i've looked @ api ( https://developers.google.com/google-apps/spreadsheets/ ) , there no php codes/examples. i've tried zend library implementation, seems outdated approach getting silly errors on simple row insert. i don't think can use google apps script ( https://developers.google.com/apps-script/reference/spreadsheet/ ) don't see how can code , trigger php script. anything else? isn't there workable api can use , tap into? i don't think can use google apps script don't see how can code , trigger php script sure can. can create web service using google apps script, can receive , process service requests. it's simple pass parameters web service, done using curl, instance. the following example simple spreadsheet 2 columns. can add further rows by: curl -l <script url>?col1='value column 1'&col2=

android - Barcode Fragment (Zxing library) -

i've been trying this library work in android app, can't work successfully. have fragment showing , camera shows fine, doesn't seem scan (qr, barcodes etc). i've implemented call interface , still nothing happens. if give small example of how set library scan product codes (code 128) massive help! also, i've looked @ other related questions ( here , here ) , still can't work. thanks i've released library that. it's inspired library mentioned, needed compatibility android 2.1+. hope helps. link: https://github.com/welcu/zxingfragmentlib

c# - Fluent NHibernate multiple table with the same schema -

Image
i have 100 tables same schema. best solution fluent nhibernate situation? mean mapping(s) should create? in advance! see pict.: ps. every table contains huge amount of data. if only want map tables reading purposes, can creating sql view performs union all query on tables. then, map sql view map single table. take answer previous question (and similar too).

How to make paraview read datafiles automatically? -

i'm not sure if ask in right place. simulation generates datafiles @ each time step on time line. want paraview can load new datafile @ current time step automatically whenever new datafile generated simulation. paraview have function or need write customised script? ahead! sadly have write customized script. there uservoice suggestion suggests wish. planned since 2010 , there still no progress. don't know difficult. uservoice suggestion top voted btw.

android - text view bounding box overly sized in table row -

Image
this scroll view contains table layout. when place text view inside table row, default bounding box of text view consumes available width. result when try placing other views inside same table row, placed outside layout. in images below, first row contains 2 textviews , 2 edittexts can see, 3 of views placed outside due 1st text view. help? <scrollview xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scrollview1" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".mainactivity" > <tablelayout and

c# - Recieve names and versions of installed MSI packages -

this question has answer here: getting list of installed products c# 1 answer i need names , versions of installed msi packages on local machine c# project. ideas? thank you. i'd take @ microsoft.deployment.windowsinstaller namespace found in windows installer xml (wix) deployment tools foundation (dtf). has: public static ienumerable<productinstallation> getproducts( string productcode, string usersid, usercontexts context ) productcode (string) productcode (guid) of product instances enumerated. instances of products within scope of context specified usersid , context parameters enumerated. parameter may set null enumerate products in specified context. usersid (string) specifies security identifier (sid) restricts context of enumeration. sid value other s-1-1-0 considered user sid , restricts e

rest - HTTP statuscode to retry same request -

is there http status code instruct client perform same request again? i facing situation server has "wait" lock disappear when processing request. time lock disappears, requests might close timeout limit. instead, once lock clears, instruct client perform same request again. the best come http 307 same location, i'm worried browsers might not buy (redirect loop detection). the correct response, when server unable handle request, 503 service unavailable . when condition temporary, in case, can set retry-after header let client know how long should wait before trying again. however, not force browser perform request again - need handle in javascript. example, here how might perform retrying ajax post request in jquery: function postdata() { $.ajax({ type: 'post', url: '503.php', success: function() { /* whatever need here when successful. */ }, statuscode: { 503: function(jqxhr) {

c# - List Sorting numbers in Descending Order -

i have list not sorting @ all. used .sort , not working. want numbers sort in descending order. 9,6,4,3,2 list<string> tem = new list<string>(); using (sqlconnection cs = new sqlconnection(connstr)) { cs.open(); (int x = 0; x < length; x++) { sqlcommand select = new sqlcommand("spticketissuance_gettransactions", cs); select.commandtype = system.data.commandtype.storedprocedure; select.parameters.addwithvalue("@transdesc", transtype[x]); sqldatareader dr = select.executereader(); while (dr.read()) { tem.add(dr["transtime"].tostring()); //adds transaction in multiline textbox , adds them list translist } dr.close(); } tem.sort(); //not sorting cs.close(); } you you're sorting numbers, list contains strings. sorting numerical values in string

c++ - Passing parameters to a functions -

i created test function: void test(double** matrix); i want pass function variable double matrix[2][2] = {{1,2},{2,3}}; . evil compiler writes: cannot convert «double (*)[2]» «double**» argument «1» «void test(double**)» . what need do? the types of arguments , parameters have agree (or @ least compatible). here, have double[2][2] , , want pass double** . types unrelated: array of arrays not array of pointers (which convert pointer pointer). if want pass double [2][2] , you'll have declare parameter double (*matrix)[2] , or (better yet), double (&matrix)[2][2] . of course, if you're using c++, you'll want define matrix class, , use it.

java - Is there a JAXB annotation to do this? -

im using jaxb serialize java model, in jaxb can choose between @xmlelement or @xmlattribute my model looks like: public class link { string rel; string href; } if annotate properties in link class @xmlattribute link like <link rel="self" href="http://mycompany.com/resource?param=blah" /> if annotate properties @xmlelement link like: <link> <rel>self</rel> <href>http://mycompany.com/resource?param=blah</href> </link> i have requirement make xml this, sort of mix, don't want href tags around url using @xmlelement href won't work: <link rel="self">http://mycompany.com/resource?param=blah</link> is there way using jaxb? you can use @xmlvalue use case. @xmlaccessortype(xmlaccesstype.field) public class link { @xmlattribute string rel; @xmlvalue string href; } for more information http://blog.bdoughan.com/2011/06/jaxb-and-co

php - How to use a href while using htmlspecialchars -

let's if have code $text = "please visit <a href="http://example.com">site</a>." $text = htmlspecialchars($text); echo $text; so it's output please visit <a href="http://example.com">site</a>. want it's output please visit site . there way see if it's href somthing? thanks. only escape url itself: $text = 'please visit <a href="' . htmlspecialchars('http://example.com') . '">site</a>.' notice switching between single , double quotes.

c# - CompanyName spaces replaced with underscore in AppData Folder -

all. i'm getting weird issue appdata folder. i'm trying access user.config in appdata\local\[company name]\... folder. [company name] set in assemblyinfo.cs assemblycompany attribute , contains spaces . lets "my company name". would expect path user config contain appdata\local[ my company name ]... folder, instead appdata\local[ my_company_name ]... (spaces replaced underscore). why happening? how can correct location of user settings? i cannot use application.userappdatapath property because i'm on console application, need build path manually. any appreciated. p.s. os win 7 x64

c# - Modal form does dismiss upon close -

i have modal form form1. there button, when users click it, modal form shows formchild. if there error, want dismiss formchild , display messagebox. use following code. however, see messagebox displays on top of formchild. how make formchild disappear/close? formchild.dialogresult = dialogresult.cancel; formchild.close(); messagebox.show(error, "error", messageboxbuttons.ok, messageboxicon.stop); why not put "if" statement before call formchild? //some codes here: if (!error) formchild.showdialog(); else messagebox.show("error has occured."); or if that's not possible, try putting if statement in formchild.load. private void formchild_load(object sender, eventargs e) { //some codes here: if (error) { messagebox.show("error has occured."); this.close(); } }

Java JNA call to C++ dll works from Netbeans but not when .jar is invoked from command line -

my java program calls dll compiled in c++ using jna. dll receives java int , double values arguments. works fine when run netbeans, when invoke java .jar program command line, c++ program receives rubbish: i.e. int equal 1 received 64562352. when program run repeatedly sending int 1 java, c++ dll receives different numbers: 65631824, 66011704,.... i use windows 7, netbeans 7.0.1, java 1.7.0_01, microsoft visual c++ 2008, jna 3.3.0 (b0). the relevant code is: java: public interface cliblp extends library { enter code here`public double vectorc (int tipoprob, int nvar, double numero); } public class llamadorlp { public static void main(string[] args) { int tipoprob = 1; int nvar = 1000; double numero = 1.5; double total = clib.vectorc(tipoprob, nvar, numero); } c++: extern "c" __declspec(dllexport) double vectorc (int tipopro

c - Stops working when trying to `longjmp` from a signal handler -

here's code: #include <stdio.h> #include <setjmp.h> #include <signal.h> jmp_buf buf; void handler(int s); int main(int argc, char **argv) { signal(sigint, handler); if (setjmp(buf)) { printf("back again!\n"); return 0; } else { printf("first here.\n"); } (;;) {} } void handler(int s) { longjmp(buf, 1); } i compile under vs 2012 on windows 8 64bit. every time press control+c, program doesn't reboot expected stops working. me? from current c standard: if signal occurs other result of calling abort or raise function, behavior undefined if signal handler refers object static or thread storage duration not lock-free atomic object other assigning value object declared volatile sig_atomic_t, or signal handler calls function in standard library other abort function, _exit function, quick_exit function, or signal function first argument equal signal number corresp

Using reflection in C# -

following this answer, i'm trying replicate , iterate on customermodel properties. customermodel pippo = new customermodel(); type customer = pippo.gettype(); fieldinfo[] fields = customer.getfields(bindingflags.public | bindingflags.instance); when using debugger, fields has count = 0 customermodel has lot of public properties i'd see in fields. how can that? here's extract of properties declared i'd see. [datamember] public string id { get; set; } [datamember] public string loginname { get; set; } [datamember] public string password { get; set; } [datamember] public string creationdate { get; set; } perhaps binding flags incorrect? i'm new use of reflection. those properties, not fields. use getproperties instead of getfields . in c#: public class foo { // field: private string _name; // property: public string name { get; set; } // property: public string somethingelse { {

objective c - Should I Add Something To The Header File? -

i'm writing app , getting error. not sure how go fixing it. thank you. the error undeclared identifier 'collectionview' and header file being imported. header: #import <uikit/uikit.h> nsmutabledata *content; @interface amcollectionviewcontroller : uicollectionviewcontroller @property (weak, nonatomic) iboutlet uibarbuttonitem *tagbutton; - (ibaction)tagbuttontouched:(id)sender; @end implementation error occurring - (void)collectionview:(uicollectionview *)collectionview didselectitematindexpath:(nsindexpath*)indexpath { if(shareenabled){ //determine selected items using indexpath nsstring *selectedphotos = [tagimages[indexpath.section] objectatindex:indexpath]; //add selected image array [selectedphotos addobject:selectedphotos]; } } thanks lot guys i use collectionview multiple times in same .m file - (nsinteger)collectionview:(uicollectionview *)collectionview numberofitemsinsection:(nsinteger)secti

visual studio 2012 - Juice UI Slider Doesnt Work With JQuery UI 1.10.3 -

as far can tell juice ui slider doesn't work jquery ui 1.10.3. i following: create new project in visual studio. update packages using nuget (this takes jquery ui 1.10.3); add juice ui using nuget. create page following html in main placeholder: <asp:updatepanel runat="server" id="update0"> <contenttemplate> <div class="sliderholder"> <juice:slider id="slider1" runat="server" cssclass="hslider" max="100" min="50" onvaluechanged="slider1_valuechanged" autopostback="true"/> </div> <asp:label runat="server" id="lb0" text="current:"></asp:label> <asp:label runat="server" id="lbvalue"></asp:label> </contenttemplate> </asp:updatepanel> and following in code behind: protected void slider1_valuecha

ios - Core Data: Can a NSPredicate in fetchResultsController return multiple objects for each row, into my Table View? -

Image
in other words, can fetchedresultscontroller return array of arrays? or array of nssets? code bellow example, of i'm trying do. possible? - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { //... nsset *objects = [_fetchedresultscontroller objectatindexpath:indexpath]; //... } the reason i'm doing this, is: if user swipes cell, , deletes it. need objects row deleted. , need display data on cell, calculation made on clocks day/row. here's core data model: each row must contain clock objects, given day, based on it's clockin property. clockin nsdate object. 1 row should represent 1 day. could figuring out predicate this? possible? also, i'm using sections in table view. these out of question. there 1 solution rather no go for, wich create year, month , day, entities. fix. seems odd need that, considering clockin property should give me need... thank you! you can accompl

Backup zip and transfer to FTP Backup Server an SQL-Server Express Database every hour -

i need backup sql-server express database, zip , transfer ftp server every hour. so far i'm able create backup, i'm not able zip (i tried 7z) , transfer command line: the script.sql file: declare @pathname nvarchar(512) set @pathname = 'c:\prd-db-backup-' + replace(replace(replace(convert(varchar(19), getdate(), 126),'-',''),'t',''),':','') + '.bak' backup database [database] disk = @pathname noformat, noinit, name = n'database-full database backup', skip, norewind, nounload, stats = 10 the bat file: sqlcmd -s sqlserver -u user -p password -i script.sql problem1: 7z -tzip c:\prd-db-backup-%date%%time%.zip -i! c:\prd-db-backup-%date%%time%*.bak ftp transfer: ? thanks. depending on locale setting might have adjust date/time parsing rem last 10 chars in either dd-mm-yyyy or mm-dd-yyyy set dtm=%date:~-10% rem last 4 year set yyyy=%dtm:~-4% set mm=%dtm:~4,2% set dd=%dtm:~1,2%

hadoop - override default jvm reuse value -

we have mapred.job.reuse.jvm.num.tasks setting -1(i.e have jvm reuse no limit) in hadoop's mapred-site.xml . want override property in 1 of mapred job. possible override value 1 1 job. you can override property not marked final in respective configuration.xml file. this pass commandline argument -d property_name=value . or configuring in mapred job by configuration.set("property_name", "value");

iphone - Xcode Rotate image torwads a CGPoint without transform -

i made app: got image , follows finger ever moving it. want rotate towards cgpoint . i tested things , when tried @ first transform image jumped original position, rotated , continued following finger. how rotate without transform (or if know how fix said it's good) ? my code = //this called every 0.01 seconds cgpoint center = self.im.center; if (!cgpointequaltopoint(self.im.center, i)) { x = center.x; y = center.y; double distance = sqrtf(powf(i.x - x, 2) + powf(i.y - y, 2)); float speedx = (2 * (i.x - x)) / distance; float speedy = (2 * (i.y - y)) / distance; //float degree = (angle) % 360; //self.im.center = cgpointmake(center.x+speedx, center.y+speedy); cgaffinetransform translate = cgaffinetransformmaketranslation(center.x+speedx, center.y+speedy); cgaffinetransform rotate = cgaffinetransformmakerotation(angle); [self.im settransform:cgaffinetransformconcat(rotate, translate)]; } -(void)touchesmoved:(nsset *)touches

java - Control Image with Arrow Keys -

i trying image move across screen based on arrow keys use. right not respond key press. testing purposes have tried implementing use of right arrow key. how image respond when key pressed? have far: import java.applet.applet; import java.awt.graphics; import java.awt.event.actionevent; import java.awt.event.actionlistener; //import java.awt.event.actionevent; //import java.awt.event.actionlistener; import java.awt.event.keyevent; public class ec extends applet{ /** * */ private static final long serialversionuid = 1l; int x=50; int y=50; int dx,dy; public void keypressed(keyevent e) { int keycode = e.getkeycode(); if(keycode==keyevent.vk_right) { dx=1; x+=dx; } } public void keyreleased(keyevent e) { int keycode = e.getkeycode(); if(keycode==keyevent.vk_right) { dx=0; } } public void paint(graphics g) { g.dra

Get Image Dimensions from Url in Python -

i want image dimensions seen viewer on website. i'm using beautiful soup , image links this: links = soup.findall('img', {"src":true}) the way image dimensions using: link.has_key('height') height = link['height'] and width well. however, links have 1 of these attributes. tried pil gives actual image size if downloaded. is there other way of finding image dimensions seen on website? your main issue searching html source references height , width. in cases (when things done well), images don't have height , width specified in html, in case rendered @ height , width of image file itself. to height , width of image file, need query , load file, check height , width using image processing. if want, let me know, , i'll work through process. import urllib, cstringio pil import image # given object called 'link' site_url = "http://www.targetsite.com" url = site_url + link['src'] # here'

r - How to remove outliers from a list of vectors? -

i have list of vectors : tdatm.sp=structure(list(x3co = c(24.88993835, 25.02366257, 24.90308762 ), x3cs = c(25.70629883, 25.26747704, 25.1953907), x3cd = c(26.95723343, 26.84725571, 26.2314415), x3csd = c(36.95250702, 36.040905, 36.90475845 ), x5co = c(25.44123077, 24.97585869, 24.86075592), x5cs = c(25.71570396, 26.10244179, 25.39032555), x5cd = c(27.67508507, 27.18985558, 26.93682098), x5csd = c(36.26528549, 34.88553238, 33.97910309 ), x7co = c(24.7142601, 24.08443642, 23.97057915), x7cs = c(24.55734444, 24.56562042, 24.7589817), x7cd = c(27.14260101, 26.65704346, 26.49533081), x7csd = c(33.89881897, 32.91091919, 32.79199219 ), x9co = c(26.86141014, 26.42648888, 25.8350563), x9cs = c(28.17367744, 27.27400589, 26.58813667), x9cd = c(28.88915062, 28.32597542, 28.2713623), x9csd = c(34.61352158, 35.84189987, 35.80329132)), .names = c("x3co", "x3cs", "x3cd", "x3csd", "x5co", "x5cs", "x5cd", "x5csd&qu

php - Returning many columns in a function call -

although works fine, i want learn (i read on web , looked examples couldn't find anything) if ask below possible. can see in function, concatenate 3 columns return 1 single string , explode in php code use them. can return 3 columns individually in 1 go without using concat_ws() , not use explode in php? thanks my mysql function: drop function if exists function_institute_university; delimiter $$ create function function_institute_university (in_partnership_id integer(11)) returns varchar(250) deterministic begin declare inscode_uniid_unicode varchar(250); select concat_ws('~', upper(institute.code), university.id, upper(university.univacronym) ) inscode_uniid_unicode partnership left join institute on institute.id = partnership.iid left join university on university.id = partnership.uid partnership.id = in_partnership_id , partnership.active = '1' li

SQL Select distinct values from multiple tables -

so here's setup have 2 tables old , new following (simplified) schemas old [manname] [mannumber] new [manager_name] [manager_number] i'm looking craft sql query returns following in 4 columns in 1 query opposed 2 queries 2 columns each select distinct manname, mannumber old select distinct manager_name, manager_number new so ideal result set have 4 columns: manname mannumber manager_name manager number thanks! have tried join statement: select distinct * old join new b on a.manname = b. manager_name , a. mannumber = b. manager_number