Posts

Showing posts from May, 2011

Cutting part of image and saving to file in MATLAB -

lets assume have image 'image.jpg'. want choose part of imrect function, , save new file 'newimg.jpg'. have idea how implement in simple way? thanks. use imcrop function cut out region, , imwrite save separate image.

php - Parsing Json in JQuery get error "ReferenceError: href is not defined" -

when try parse json connection.php , using jquery : <!doctype html> <html> <head> <script type="text/javascript" src="jquery-2.1.1.js"></script> <script type="text/javascript"> $("document").ready(function() { $.getjson('connection.php', { cid: href, format: 'json' }, function(data) { $.each(data, function(index, element) { /* mengisikan table dari hasil json */ $('#tabledata').find('tbody') .append($('<tr>') .append( '<td>' + data.sys + '</td>' + '<td>' + element.procid + '</td>' ) ); }); }); }); </script> </head> </html>...

java - Why does importing JFrame require inheritance but FlowLayout, JLabel, etc not? -

i started learning guis , watching tutorial "thenewboston" wrote this. don't understand why jframe import that's inherited? i'm not sure if 1 of cases has because java give error otherwise. import java.awt.flowlayout; import javax.swing.jframe; import javax.swing.jlabel; public class tuna extends jframe { private jlabel item1; public tuna(){ super("the title bar"); setlayout(new flowlayout()); item1 = new jlabel("this sentence."); item1.settooltiptext("this gonna show on hover"); add(item1); } } jframe not require inheritance. in fact should not use inheritance. look @ framedemo.java code swing tutorial on how make frames better design. also, java class names should start upper case character. stick swing tutorials instead of current tutorials looking at.

Receiving data from php curl to another php file -

i trying send data 1 php file on webserver webserver using curl, unsure how access data sent second webserver work. able access data before using $_post array curl being used send data no longer able use reason. can point me in right direction on how access data? function post_to_url($url, $data) { $fields = ''; foreach($data $key => $value) { $fields .= $key . '=' . $value . '&'; } rtrim($fields, '&'); //dl: ugh. $post = curl_init(); curl_setopt($post, curlopt_url, $url); curl_setopt($post, curlopt_post, count($data)); curl_setopt($post, curlopt_postfields, $fields); curl_setopt($post, curlopt_returntransfer, 1); $result = curl_exec($post); curl_close($post); } that code using curl post itself, here receiving end $username = $_post['email']; if using curl make sure post: curl_setopt($ch, curlopt_post, 1); curl_setopt($ch, curlopt_postfields, $array());

java - Why does my program print out the exception statement endlessly give bad user input? -

ive no idea if title made sense here code © import java.util.inputmismatchexception; import java.util.scanner; public class gussing { public static void thegame(scanner input){ int randomnum= (int)(math.random()*101);//randomizes number between 0-100 inclusive of both system.out.println(randomnum); //for debugging purposes int attemptcounter = 0; //counts how many attempts user make system.out.print("welcome guess-the number game! enter guess: "); while(true){ system.out.println("here bad input"); try{ system.out.println("here after bad input"); int userinput= input.nextint(); if (userinput==randomnum) //when usr input , generated random number equal print how many attempts { attemptcounter++; system.out.println("congrats made right guess after "+ attemptcounter + "...

c# - Entity Framework: Server did not respond within the specified time out interval -

Image
i trying access remote oracle database using vpn connection. using oracle sql developer tool able connect database. when use ado.net model , devart dotconnect oracle, gives me error server did not respond in specified timeout interval. any 1 has face issue? update: increases timeout 60s default 15s. getting error: ora-12154: tns:could not resolve connect identifier specified 1st issue quiet common server did not respond in defined time, increasing connection time should trick. append ;connection timeout = 60; (here time in seconds) connection string. 2nd after update looks tns not resolved properly: can check: do tnsping (db name in tns ora file). see should not error , connection should ok. if problem still persist check oracle home in registry have correct path in case have multiple client.

visual c++ - Creating a new "internal" process? -

i'm writing dll (in visual c++) , decided need move stuff happens in threads own process. because want support multiple instances of dll being loaded , running. however, need access same group of resources (i/o buffers com port) needs autonomously monitored long there @ least 1 instance of dll running. it seems need use createprocess(), i'm unclear on how should use lpapplicationname argument. in examples i've seen, name of existing program gets passed, isn't imagine need do. expected able start process specifying function, createthread(). process doesn't need compiled , output own executable, it? shouldn't used other dll. thanks. edit: okay, if createprocess() can start pre-existing program, how can work? if following happens: process loads dll dll starts port monitoring threads second process loads dll second dll establishes ipc access same data first dll first dll exit, , terminates monitoring threads second dll starts own monitoring threads ,...

How to limit permission of SDK in android? -

i want use library in project? not want lib have permission access files, database or download network in app. how can achieve aim ? the library provide others, need use function in it, not want has permission hack app. maybe need sandbox run lib, not know how achieve this? in library projects, can remove permissions manifest. in terms of jar lib, there no problem. because jar libraries going use app permissions only.

Implement seamless Compute function on SQL Server 2012 -

information : in process of testing our upgrade sql server 2005 sql server 2012 on staging. in reading documentation on features no longer supported, compute (transact-sql) going away going issue us. question: there way write out our own procedure take place of compute builtin on sql server 2012 make seamless when compute called function sql server 2005? alternative we need update sql files, udf's, triggers, , stored procedures use built in alternative code? note have never tried recreate built in function before information on helpful me , else trying in future. knowing if can done plus. clenup: if duplicate post indicate link below , remove post. compute by not function. don't see how it's effects (generating additional result sets) can replicated easily. replacing compute temp table , looping should kind of straight forward laborious task. it's better change application not depend on multiple result sets. i have made recommendation of m...

How to use php code in javascript alert in codeigniter -

i using code in controller , it's not working, showing parse error. can guys please me out. echo "<script> alert("<?php echo $v[$keys[$i+4]],"is going out of stock"; ?>"); </script>" ; thank you! you're not concatenating static text correctly. try this: echo "<script> alert('" . $v[$keys[$i+4]] . " going out of stock.'); </script>" ;

Return all possible combinations of values within a single column in SQL -

how return list of possible combinations of values within same single column of database 'x'? example have: col 1, 1 2 3 4 and return list of possible combinations like, 1,2 1,3 1,4 2,3, 2,4 3,4 .... you've not said rdbms using or whether want limit combinations 2 elements of set. here oracle answer using hierarchical queries: sql fiddle oracle 11g r2 schema setup : create table test ( col ) select level dual connect level < 5; query 1 : select substr(sys_connect_by_path(col, ','), 2) combination test connect prior col < col results : | combination | |-------------| | 1 | | 1,2 | | 1,2,3 | | 1,2,3,4 | | 1,2,4 | | 1,3 | | 1,3,4 | | 1,4 | | 2 | | 2,3 | | 2,3,4 | | 2,4 | | 3 | | 3,4 | | 4 | query 2 : select substr(sys_connect_by_path(col, ','), 2) combinatio...

python - Django ORM Array Field Error -

i got error when trying run migrate command file "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.programmingerror: operator class "varchar_pattern_ops" not accept data type character varying[] i have arrayfield in model. when removed arrayfield, worked fine i'm using django 1.8, python 3.4 , postgresql 9.4 models from django.db import models django.contrib.postgres.fields import arrayfield django.contrib.auth.models import user class post(models.model): author = models.foreignkey(user) title = models.charfield(max_length=512) slug = models.slugfield(unique=true, db_index=true) summary = models.textfield(blank=true, null=true) content = models.textfield() tags = arrayfield(models.charfield(max_length=256), blank=true, db_index=true) is_published = models.booleanfield(default=true) has_comments = models.booleanfield(defaul...

android - Bad data interpretation when scrolling of Listview -

i wrote code custom listview. in listview have textview hidden circumstances. works when scroll view down. however, when scroll view textvie hidden. know has setting tags elements. tried examples different sides, however, textview's disappear :( custom arrayadapter code: class wallpaperslistadapter extends arrayadapter<wallpaper> { private list<wallpaper> wallpaperscontainer; private imageloader imageloader; private displayimageoptions imageloaderoptions; public wallpaperslistadapter(context context, list<wallpaper> wallpaperscontainer) { super(context, r.layout.wallpaper_view, wallpaperscontainer); this.wallpaperscontainer = wallpaperscontainer; setimageloaderoptions(); } private void setimageloaderoptions() { imageloaderoptions = new displayimageoptions.builder() //.showimageonloading(r.drawable.place_holder) //.showimageforemptyuri(r.drawable.question) //.showimageonfail(r.drawable.big_prob...

powershell - Batch script to find file -

i need batch script recursively find folder particular file in. have below powershell script works fine can't run due execution policy hence wondering if can me convert batch file please? $val = get-itemproperty -path 'hklm:\software\microsoft\windows\currentversion\uninstall\{785a2e83-c8b2-46bb-8839-514de2243ead}' -name "displayname" -erroraction silentlycontinue if($val.displayname -ne 'internet explorer 11') { $ccmie11folders = @(get-childitem -path c:\windows\ccmcache -filter ie11-setup-full.msi -recurse) if($ccmie11folders.count -gt 0) { & "$($ccmie11folders[0].directoryname)\install.cmd" } } the script first looks registry item property. if not exist recursively finds file "ie11-setup-full.msi" under c:\windows\ccmcache folder. if found runs install.cmd resultant folder. if wanted know, deploying ie11 in enterprise using sccm small percentage of them failing unknown reason trying re-run installer usi...

c# - CSharp Enumerate through nullable Enums -

one piece of code worth thousand words... public enum entest { a, b, c } public void printenum<t>() { foreach (var e in enum.getvalues(typeof(t))) debug.writeline(e.tostring()); } printenum<entest>(); printenum<entest?>(); // cause failure in enum.getvalues() the above simplified larger problem illustrate failure. does know how can iterate through (or values inside) when passing me nullable enum? thanks in advance. how this? public static void printenum<t>() { type t = typeof (t); if (t.isgenerictype) { //assume it's nullable enum t = typeof (t).generictypearguments[0]; } foreach (var e in enum.getvalues(t)) console.writeline(e.tostring()); }

python - Don't Allow Website automated Redirect Scrapy -

i sorry if question incomplete or unhelpful. new @ this. i started using scrapy scraping data. issue facing @ moment is: when try scrape data, website redirect's me particular page. i intend stop website redirecting particular page. to honest not sure if it's possible or not. what have tried far is: following redirect , there using href link provided go desired page.the issue in case site follow's loop , redirects me same page. redirect_enabled = false in setting's. issue in case scrapper exit's , script stop's. any appreciated. thank you

Regex split and concatenate path base and pattern with filename deleting part of path between them -

i have url this: a) <a href=\"http://example.com/path-pattern-to-match/subpath/onemoresubpath/arbitrary-number-of-subpaths/somearticle1\"> or: b) <a href=\"http://example.com/path-pattern-to-match/somearticle2\"> i need split path pattern base url, start of <a> tag , concatenate iits somearticle . in between needs deleted. case 'b' remains untouched. case 'a' needs become: <a href=\"http://example.com/path-pattern-to-match/somearticle1\"> please answer regex, need. other solutions interesting if explained, using perl or bash script, please avoid suggest programming module or function parse regex not best solution , without real 1 solution. ps: need parse non multiline file. somearticle variable. if have look-behind support, use (?<=<a href=\\"http:\/\/example\.com\/path-pattern-to-match\/)(?:[^\/]+\/)*([^\/>"]*)(?=\\">) see demo explanation (?<=...

javascript - Two dimentional array in js -

i trying 2 dimensional array in javascript, have json , trying populate 2d array. code here: jquery.each(data.data, function(key,val){ survey_sec_id_arr.push(val.section_id); survey_question_id_arr.push(val.section_id); jquery.each(val, function(key1,val1){ if(key1!="section_id" && key1!="section_name"){ survey_question_id_arr[val.section_id].push(val1.question_id); } }); }); console.log(survey_question_id_arr); so here error in firebug is: typeerror: survey_question_id_arr[val.section_id] undefined what going wrong? you loop not correct. add of elements via push array looks survey_question_id_arr = array( [0] => val.section_id, [1] => val.section_id...) then try element of array via //returns undefined survey_question_id_arr[val.section_id] //should return value val.section_id[0] fix: survey_question_id_arr[val.section_id].push(val1.question_id...

sql server - Ajax MSSQL query using json and php returns undefined array -

i have problem when alert( data[i].name). result undefined if array returned. knows problem is? this javascript $('#plus').click(function(){ $.ajax({ type : 'post', url : 'jquerydbactionview.php', datatype : 'json', data: { }, success: function( data){ $.each( data, function(i, item) { alert( data[i].name); }); } }); }); and php $query = "select top (1) * "; $query .= "from maillist bolag = 'fal'"; $results = mssql_query($query); $result = array(); while($row = mssql_fetch_array($results)) { $result[] = array( 'id' => $row['id'], 'company' => $row['company'], 'name' => $row['name'], 'mail' => $row['mail'] ); } echo json_encode($result); please use json.parse(data) convert json encoded ...

javascript - jquery width increase/decrease with scroll -

i want increase , decrease width of div when scroll page . able increase width of div right after scroll down 150px , div width not decreasing when scroll before 50px coded . code increase var scroll_pos = 0; jquery(document).scroll(function() { scroll_pos = $(this).scrolltop(); if (scroll_pos > 100) { scroll_pos = 100; } jquery(".roadway-sec-1").animate({ width : (0+1*scroll_pos)+"%" }); }); code decrease jquery(document).scroll(function() { var current=jquery(".roadway-sec-1").width(); scroll_pos = $(this).scrolltop(); if (scroll_pos < 50) { scroll_pos = 50; } jquery(".roadway-sec-1").animate({ width : "-=50"+"%" }); }); why don't trick in 1 function? jquery(document).scroll(function() { scroll_pos = $(this).scrolltop(); if (scroll_pos < 100 && scroll_pos > 50) ...

python - Split a user input -

i'd take user input delimiter , use split data. thought line of code should this: my_delimiter = raw_input("write down delimiter of file(e.g. ','): ") line in file: line2 = line.split(my_delimiter) print line2 main_data.append(line2) then sample input should write down delimiter of file(e.g. ','): '\t' and output should like ['age', 'prescript', 'astigmatic', 'tearrate\n'] ['young', 'myope', 'no', 'reduced', 'no lenses\n'] but remains same. doesn't work. not delimited tab or comma hope be. please me figure out. if entering values '\t' in raw_input turns them str '\t' has 2 ascii characters. doesn't turn '\t' tab character want. if example, know going input '\t' , want turn tab character my_delimiter = my_delimiter.replace('\\t', '\t') this change actual tab character. have esca...

vb.net - Creating and Editing Excel Chart -

i trying create data analysis program using vb.net. data in excel file. x values in col a2, y values in b col b2. i able generate chart data. how format chart: add title change line color in chart specified color add trend line (polynomial) modify color of trend line add series(data set plot) chart edit series names x,y labels any other formatting tips appreciated. sorry ambiguous question. trying automate excel create charts using vb.net. i not sure how implement since new vb.net. able create micro in excel functions. not sure how code in vb.net. is there way convert vba excel micro vb.net? sub macro2() ' ' macro2 macro ' ' range("b1:b14").select activesheet.shapes.addchart.select activechart.charttype = xlxyscattersmoothnomarkers activechart.setsourcedata source:=range("sheet1!$b$1:$b$14") activechart.seriescollection(1).select selection.format.line .visible = msotrue .forecolor.o...

What is the best Mongodb Sharding key for my schema? -

i design mongodb collection can save statistic daily volume here db schema mongos> db.arq.findone() { "_id" : objectid("553b78637e6962c36d67c728"), "ip" : numberlong(635860665), "ts" : isodate("2015-04-25t00:00:00z"), "values" : { "07" : 2, "12" : 1 }, "daily_ct" : 5 } mongos> and here indexes mongos> db.arq.getindexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "query_volume.test" }, { "v" : 1, "key" : { "ip" : 1 }, "name" : "ip_1", "ns" : "query_volume.test" }, { "v" : 1, "key" : { "ts" : 1 }, ...

Python: using comprehensions in for loops -

i'm using python 2.7. have list, , want use loop iterate on subset of list subject condition. here's illustration of i'd do: l = [1, 2, 3, 4, 5, 6] e in l if e % 2 == 0: print e which seems me neat , pythonic, , lovely in every way except small matter of syntax error. alternative works: for e in (e e in l if e % 2 == 0): print e but ugly sin. there way add conditional directly loop construction, without building generator? edit: can assume processing , filtering want perform on e more complex in example above. processing doesn't belong 1 line. what's wrong simple, readable solution: l = [1, 2, 3, 4, 5, 6] e in l: if e % 2 == 0: print e you can have amount of statements instead of simple print e , nobody has scratch head trying figure out does. if need use sub list else (not iterate on once), why not construct new list instead: l = [1, 2, 3, 4, 5, 6] even_nums = [num num in l if num % 2 == 0] and iterate on ...

c++ - Implementing a simple, generic thread pool in C++11 -

i want create thread pool experimental purposes (and fun factor). should able process wide variety of tasks (so can possibly use in later projects). in thread pool class i'm going need sort of task queue. since standard library provides std::packaged_task since c++11 standard, queue std::deque<std::packaged_task<?()> > task_queue , client can push std::packaged_task s queue via sort of public interface function (and 1 of threads in pool notified condition variable execute it, etc.). my question related template argument of std::packaged_task<?()> s in deque. the function signature ?() should able deal type/number of parameters, because client can like: std::packaged_task<int()> t(std::bind(factorial, 342)); thread_pool.add_task(t); so don't have deal type/number of parameters. but what should return value be? (hence question mark) if make whole thread pool class template class, 1 instance of able deal tasks specific signature (l...

php - How to setup existing yii project in xampp on windows -

i have yii framework project in server running successfully. but let me know how setup xammp server(local) on windows. checked self in way: changed php.exe file path local server path. changed environmental variables also run http://127.0.0.1/html , http://localhost/html but says object not found please suggest procedure . check .htaccess file. default file content: rewriteengine on rewritebase /connect_donors rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule ^(.*)\?*$ index.php/$1 [l,qsa]

HTML form post method and auto-refreshing PHP page -

in html page, have php iframe gets variables form using post method. works fine. my problem this: php iframe auto-refresh (which does), , understandably, undefined index errors php first time iframe auto-refreshes. is there way (preferably using php/html) allow iframe hold on variables html form after first load of php iframe? isset doesn't seem answer problem here's simple way of accomplishing you're after: <?php // starts session session_start(); // gets variable via $_post if present , caches in $_session // if doesn't exist in $_post or $_session, return null function get_variable( $name ) { if( isset( $_post[$name] ) ) { $_session['cache_'.$name] = $_post[$name]; } return ( isset( $_session['cache_'.$name] ) ? $_session['cache_'.$name] : null ); } // these values form on cache $value_a = get_variable('field_name_a'); $value_b = get_variable('field_name_b'); $value_c = get_va...

objective c - iOS Guided Access: why does my app close overnight? -

i'm writing ios application enterprise deployment. use case is meant run in foreground in kiosk / guided access mode on ipads, , must never ever close long os running (the ipads mounted on wall , plugged power source). i've set ipad never go lock screen, , i've put in necessary idletimerdisable code. set guided access run app, , off goes. everything works charm during day. can leave ipad sitting there day app in foreground , behaves expected. time overnight, causes application close , when arrive work in morning, ipad sitting on home screen. i keep ipad connected mac console open, examining logs , console output doesn't reveal out of ordinary. i have exception handling , logging code in place, reviewing logs shows no exception being thrown either. the behavior consistent: can keep app open day without issue, next morning closed. can re-launch app guided access running, , trapped guided access on home screen preventing me re-launching app , have force ipad ...

python - Matplotlib date ticker - exceeds Locator.MAXTICKS error for no apparent reason -

when plot datapoints vs time, spanning on 2 days, , set datelocator 0 , 30 minutes. major tick each half hour, matplotlib throws error. consider example: from datetime import datetime import matplotlib.pyplot plt import matplotlib.dates mdates datapoints = 3600*24*2 #2 days, 1 datapoint/second data = range(datapoints) #anydata timestamps = [ datetime.fromtimestamp(t) t in range(datapoints) ] fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.xaxis.set_major_locator(mdates.minutelocator(byminute=[0,30])) plt.plot(timestamps,data) plt.show() then following error: runtimeerror: rrulelocator estimated generate 2879 ticks 1970-01-01 01:00:00+00:00 1970-01-03 00:59:59+00:00: exceeds locator.maxticks * 2 (2000) 2879 ticks amount of minutes in timespan, meaning estimate based on 1 tick every minute. locator should yield 1 tick every 30 minutes (2 ticks per hour in 48 hour = 96 ticks). why estimate , real value far eachother? a workaround raise maxticks value: lo...

javascript - How to sort a number with thousands separator -

i have tried sort number jquery datatables plug-in not working c# string number formats. i have tried: decimal value= 12345678.00 value..tostring("#,##.00"); value.tostring("##,##.##"); value.tostring("0,0.00", cultureinfo.invariantculture) but no luck because of comma. if there no comma works fine or numbers same count working i.e. 01,121,372.01 02,002,009.22 11,222,222,33 if below not working 1,111,111.11 222,191.00 32,222.00 for datatables 1.10 datatables 1.10+ has formatted number detection , sorting abilities built- in, there no coding needed. alternatively can set columns.type num-fmt force specific data type. see example below demonstration. $(document).ready(function() { $('#example').datatable(); }); <!doctype html> <html> <head> <meta charset="iso-8859-1"> <link href="//cdn.datatables...

Oracle EXECUTE IMMEDIATE Not doing what expected in stored procedure -

i have stored procedure has several checks in them following section gives me problems execute immediate for example when try compile procedure below statements complains table or view not exist. ... ... ... execute immediate 'create table mytable(col1 number, col2 number, col3 number)'; execute immediate 'insert mytable (col1,col2,col3) select a,b,c source_table' ; select count(*) c mytable; 6:18:22 [create - 0 row(s), 0.000 secs] {50:29} pl/sql: ora-00942: table or view not exist however, if remove select count(*) c mytable; it compiles , works. please advise on simple colution. thanks when oracle compiles stored procedure, checks existence of mytable . if mytable doesn't exist @ compilation time, give error. your options: create table ahead of time. you stuck performing select count(*) ... using dynamic sql ( execute immediate ) doing insert statement. note that, if decide go 2nd option, possible assign result of q...

Delete values from JavaScript array -

i have 2 javascript arrays (say newvalue , oldvalue ). these 2 arrays contain common values. want delete values present in oldvalue array newvalue . example:say newvalue has values 1,2,3,4 , oldvalue has values 2,3 want delete 2,3 newvalue , newvalue should have values 1,4 this has done in javascript. consider new value [ {"patentid":1, "geography":"china", "type":"utility", "assignee":"abc" }, {"patentid":2, "geography":"aus", "type":"utility", "assignee":"abc" }, {"patentid":3, "geography":"aus", "type":"utility", "assignee":"abc" }, {"patentid":4, "geography":"china", "type":"utility", "assignee":"xyz" } ] consider old value [{"patentid":3, "geography":"aus...

c# - ToList() throws an exception -

i try retrieve list data base. when call tolist() method throws , exception.knowing database not empty. var listeref = r in db.refanomalies select r; rapportanomalie rp = new rapportanomalie(); list<refanomalie> listerefference = listeref.tolist(); the exception : {"invalid column name 'rapportanomalie_code_rapport'."} this database tables: create table [dbo].[refanomalie] ( [code_anomalie] int identity (1, 1) not null, [libelle_anomalie] nvarchar (100) not null, [score_anomalie] int not null, [classe_anomalie] nvarchar (100) not null, constraint [pk_dbo.refanomalie] primary key clustered ([code_anomalie] asc) ); create table [dbo].[rapportanomalie] ( [code_rapport] int identity (1, 1) not null, [date_rapport] datetime not null, [etat] nvarchar (50) not null, [code_agence] int not null, constraint [pk_dbo.rapportanomalie] primary key clustered ([c...

javascript - Drawing multiple SVG lines side by side -

<!doctype html> <html> <head> <meta charset="utf-8"> <title>js bin</title> </head> <body> <svg width="250" height="250"> <line x1="0" y1="100" x2="0" y2="37" stroke="red" stroke-width="50"></line> <line x1="50" y1="100" x2="50" y2="37" stroke="blue" stroke-width="50"></line> </svg> </body> </html> i hoping code allow me display red bar , blue bar of equal widths side side. not, ideas why ? the line stroke grow both sides. in case think must use rect instead lines. <svg width="150" height="250"> <rect width="50" height="100" x="0" y="0" fill="red"/> <rect width="50" height="100" x="50" y="0...

android - Search widget doesn't integrate with toolbar, when calling onSearchRequested() -

Image
i created xml file in menu folder search item. <item android:id="@+id/action_search" android:title="@string/search_hint" android:icon="@drawable/ic_magnify_white_24dp" app:showasaction="collapseactionview|ifroom" app:actionviewclass="android.support.v7.widget.searchview" /> i setup menu search function @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu items use in action bar menuinflater inflater = getmenuinflater(); inflater.inflate(r.menu.menu_option, menu); // associate searchable configuration searchview searchmanager searchmanager = (searchmanager) this.getsystemservice(context.search_service); searchview searchview = (searchview) menu.finditem(r.id.action_search).getactionview(); searchview.setsearchableinfo( searchmanager.getsearchableinfo(getcomponentname())); ...

What html form control is used in adding multiple value field? -

Image
i have making simple jsp app , have many many relationship between song , genre. form field should use add multiple genres song. thinking of check boxes don't know if appropriate. here erd. if goal select multiple options, checkboxes best option. radio , <select> select one. w3 schools: <input> tag

Accessing custom jbake confing properties in asciidoc -

after time spent staring @ jbake code, figured out if declare own property in jbake.properties : ... foo=bar ... i can reuse in files go through template engine referencing ${config.foo} . i'd have substitution working on content lvl, i.e. files written in asciidoc, living inside content directory. is there non-trivial way achieve it? how can make templating engine proccess result of asciidoc parses engine, or make running before asciidoctor? i found answer myself. use property substitution in asciidoc files, add following jbake.properties : ... asciidoctor.attributes.export=true foo=world ... and reference variable in afile.adoc way: hello {foo}!

Ruby syntax error: unexpected tIDENTIFIER, expecting keyword_end -

error: /home/g3mini/desktop/management/app/controllers/user_controller.rb:3: syntax error, unexpected tidentifier, expecting keyword_end @users user.all ^ code: class usercontroller < applicationcontroller def index @users user.all end def create end def store @user = user.new(params.require(:user).permit(:userame,:password)) @user.save redirect_to '/' end end could please tell me going wrong? (total noob here) thanks, g3 the problem in use of is instead of = . should use: @users = user.all

ios - How to use a segmented control to change container views -

Image
i posted, re-asking give better concept. i'm trying use segmented control change through multiple views inside container view. i'm not sure how embed multiple views inside container view. saw tutorial how in objective-c, coding in swift. this perfect example of i'm looking for. there uitabbarcontroller on bottom, there segmented control alter between "tweets" "photos" , "favorites." how achieve this? thanks in advance!! i'm assuming have collection view or table view or below segmented control. if that's case, i've had luck using segmented control switch data sources (and delegates, if necessary) collection. if have views, can use segmented control show 1 , hide others. do have code or more specific questions?

javascript - Window scroll event fires multiple times -

i working marionette.js app fetches more data user scrolls down page. setupwindowscrolllistener: function() { var $window = $(window), $document = $(document), = this; $window.on('scroll', _.debounce(function() { var scrolltop = $window.scrolltop(), wheight = $window.height(), dheight = $document.height(), margin = 100; if(scrolltop + wheight > dheight - margin) { eventer.trigger('fetch:more:products'); } }, 500)); } the problem when user scrolls down bottom of page, eventer firing off multiple events instead of one. update code isloading check setupwindowscrolllistener: function() { var $window = $(window), $document = $(document), = this, isloading = false; $window.on('scroll', _.thro...

django - Aftership webhook tracking API -

i developing 1 e-commerce app project have track order status. use aftership webhook api. webhook provides tracking event updates our specified webhook url(defined in our server). read documentation dont know proper approach test api. , in documentation not defined. can tell or suggest me how can test or track updates. to test aftership api, first, can follow api reference api key. , tracking order webhook, need post /trackings https://api.aftership.com/v4 beforehand body like(you can add optional parameter request body): {"tracking": {"tracking_number": "<order tracking number>"} and can follow webhook documentation , add webhook url , configure types of updates want get. @ point, should able see tracking update http request coming webhook url. remember send callback request when there tracking status update. also, can use other tracking apis status, update tracking or delete now.

python - pylab scatter plot appears transposed -

Image
i have been playing various interpolation techniques - , particularly varieties shown in youtube video https://www.youtube.com/watch?v=_cjlvhdj0j4 however, scatter module plots points in wrong location. have transposed them below (example 5) make work, not work if area of interest not centred on origin (test_rbf). am mis-understanding fundamental, or problem in pylab scatter module? # example 5 # # https://www.youtube.com/watch?v=_cjlvhdj0j4 import numpy np scipy import interpolate import pylab py def func(x,y): return (x+y)*np.cos(-5.0*x + 4.0*y) x = np.random.uniform(-1.0, 1.0,size=50) y = np.random.uniform(-1.0, 1.0,size=50) fvals = func(x,y) newfunc = interpolate.rbf(x, y, fvals, function='multiquadric') xnew, ynew = np.mgrid[-1:1:100j, -1:1:100j] fnew = newfunc(xnew, ynew) true = func(xnew, ynew) py.figure() py.clf() py.imshow( fnew, extent=[-1,1,-1,1], cmap=py.cm.jet) # py.scatter( x, y, 30, fvals, cmap=py.cm.jet) py.scatter( y, -x, 30, fvals, cmap=py.cm...

registry - Powerbuilder 7 crashes while trying to insert OLE control -

i trying insert ole custom control dialog in powerbuilder 7. when choose corresponding tab 'insert control', powerbuilder 7 application crashes. upon research on topic, found quite few people have experienced behavior none of suggestions seems work me. 1 of relevant suggestion run process monitor , last registry entry pb7 crashes. http://codeverge.com/sybase.powerbuilder.general/pb8-crashes-when-selecting-to-ins/1030907 i tried doing , further looked ole object viewer unusual. ole object viewere crashed when selected ole objects--> bitmap objects. believe not understand concept of registries interpret results , appropriate solution. appreciate on regard. more info: os windows7 enterprise 64-bit earlier versions of pb (10 , under) abort if system has com control isn't installed correctly. com control installer didn't set registry setting supposed to. utility designed find , correct these sorts of issues.

c++ - Qt creator cannot find dependent library when running the app -

i have qt application project depends on qt library project. have following in application pro file include library. win32:config(release, debug|release): libs += -l$$pwd/../../commonlibs/build/debug/mylib/release/ -lmylib else:win32:config(debug, debug|release): libs += -l$$pwd/../../commonlibs/build/debug/mylib/debug/ -lmylib else:unix: libs += -l$$pwd/../../commonlibs/build/debug/mylib/ -lmylib includepath += $$pwd/../../commonlibs/mylib dependpath += $$pwd/../../commonlibs/mylib until today, application compiled , run, debug application through qtcreator. suddenly, though can compile application, cannot run through qtcreator. when try run it, qtcreator reports application exited if put breakpoint in main() , doesn't hit. if manually copy dependent library dll file directory application exe exists, can run through qtcreator. i checked build environment project setting in qtcreator , lib path exists in path variable. i cannot remember significant action did have c...

php - I mixed sql and sqli commands..but this gives errors..what is the correct code? -

this question has answer here: when use single quotes, double quotes, , backticks in mysql 10 answers there's error in piece of code..can care correct me? $user_list=mysqli_query("select 'id','username', 'users' "); while($run_user=mysqli_fetch_array($user_list)){ $user=$run_user['id']; $username=$run_user['username']; echo "<p><a href='send.php?user=$user'>$username</a></p>"; } from comments made below - mysqli_query() expects @ least 2 parameters, 1 given in d:\wamp\www\2\send.php on line 44 just replace quotes backtick mysqli_query need connection in first parameter $user_list=mysqli_query(pass_your_connection_variable,"select `id`,`username` `users`");

bash - Configure jenkins job: rm command not found -

i trying configure jenkins job , added following lines shell text area: path="/home/${user}/reportlogscomparator/"; result_file="target/result.txt"; #remove previous results cd ${path} rm -f ${result_file} but result is: + path=/home/build/reportlogscomparator/ + result_file=target/result.txt + cd /home/build/reportlogscomparator/ + rm -f target/result.txt /tmp/hudson6849808815020420288.sh: line 7: rm: command not found also, tried rm -f "$result_file" and path hardcoded, no success. path="/home/${user}/reportlogscomparator/" should path="$path:/home/${user}/reportlogscomparator" this way, you're appending directory current path instead of replacing $path entirely.

command line interface - Windows: Run script upon cd -

i've been using small set of bash scripts execute various actions upon changing directory (say, rebasing repositories, cleaning temps, rotating logs, reading mail, etc) , noticed not common thing on windows @ all. a cursory google search doesn't show much... possible? in bash accomplished writing small function called cd , having work on top of builtin cd. mechanism available on windows? if isn't, other alternatives might there be?

vb.net - Move cursor to the first character after reaching end the last character in textbox -

i have textbox max character length 3 digit , want user able input number in way cursor move first character after finish typing 3 digit. example: 000 -- default value 100 -- 1st digit input 120 -- 2nd digit input 123 -- 3rd digit input ---and after this, when user type new number 4, string 423 any appreciated. thanks make sure maxlength property of textbox set 3. declare global variable 'index'. , add code keypress event of textbox. to explain algorithm: have make sure key pressed digit or letter. keep track of index, increment 1 everytime press digit/letter key. if index exceeded 2, means have reset 0. if char.isletterordigit(e.keychar) dim str string = textbox1.text dim count integer = str.length if count = 3 select case index case 0 dim substr string = str.substring(1) dim newstr string = e.keychar & substr textbox1.text = newstr ...

mobile application - Phonegap and other native programming languages -

i building mobile app community, although of target group use android os, of them use ios, windows , blackberry. leaders use ios. now, time present mobile app limited. have finished building mobile app in native android platform. i have heard of phone gab, helps build app platforms. please confuse, should build app in native languages or use phone gap? as per knowledge phonegap better if going make application multiple platform.in phonegap using javascript,jquery,css n html can write code.and using phonegap can directly convert applications android,ios, windows , blackberry platforms.

I cannot get my printf statements to align in java -

i having spot of trouble printf statements. cannot them accurately. code snippet having trouble with. while(choice != 4){ if(choice == 1){ system.out.println("name id gpa\n"); for(j = 0; j < ;j++){ system.out.printf("%s", fullname[j]); system.out.printf("%10d", id[j]); system.out.printf("%15.2f\n", gpa[j]); } system.out.println(""); } it prints this. name id gpa hoffman caleb joseph 1 4.00 jones bob cray 2 3.80 mitten jose crush 3 1.53 how can line up? if add int name format statement align text: system.out.printf("%20s", fullname[j]); will print hoffman caleb joseph 1 4.00 jones bob cray 2 3.80 mitten jose crush 3 1.53 if want l...

javascript - Magnific Popup: error trying to invoke a YouTube iframe popup from an inline popup -

i'm using magnific popup show inline modal image , text. client wants add link inside inline modal watch video - video being inside new modal popup. we using video modal throughout site without problems, when link inside inline modal black overlay stays, inline modal goes away expected, no video modal appears. <a class="modal-youtube" href="https://www.youtube.com/watch?v=5r15iunwhl8">watch video</a> in console has error: error: syntax error, unrecognized expression: https://www.youtube.com/watch?v=5r15iunwhl8 for reference, here's javascript code - it's pretty standard stuff docs, though. $('.modal-youtube, .modal-vimeo, .modal-gmaps').magnificpopup({ disableon: 700, type: 'iframe', mainclass: 'mfp-fade', removaldelay: 160, preloader: false, fixedcontentpos: false }); $('.modal').magnificpopup({ type: 'inline', preloader: false, showc...

javascript - jQuery Validate: how do I validate based on other field's value? -

i have form. if select field set first option, have 2 radio groups must set. if select set other value, don't have set. the select: <div class="field grid_10"> <label for="severityid" class="grid_3">severity</label> <div class="grid_6"> <form:select id="severityid" path="severityid" items="${severitylist}" itemvalue="id" itemlabel="title" /> </div> <div class="clear"> </div> </div> the validation: function validate_eventreviewform() { jquery('#review-edit-form').validate ({ rules: { samplewaslost: {required: { depends: function(element){ return $("#severityid").val() == 1 }}}, backupsampleavail: { depends: function(element){ return $("#seve...

ruby - undefined method `to_sym' on nil:NilClass on rubysl/net/http/http.rb caused by Rails Geocoder -

so i've working on website on ruby on rails uses geocoder gem. here implementation: def user < activerecord::base before_save :geocode geocoded_by :address |usr, geocode_results| if geo = geocode_results.first usr.latitude = geo.latitude usr.longitude = geo.longitude usr.geocode_address = geo.address else usr.latitude = nil usr.longitude = nil usr.geocode_address = nil end end and on production works... in 2-3 days i'll error saying undefined method to_sym on nil:nilclass. on controller action calls @user.save i investigated further, , here stack trace: stacktrace (most recent call first): kernel/delta/kernel.rb:78:in `to_sym (method_missing)' rubysl/net/http/http.rb:576:in `start' key = $1.to_sym kernel/common/enumerable.rb:217:in `grep' kernel/bootstrap/array.rb:76:in `each' kernel/common/enumerable.rb:213:in `grep' rubysl/net/http/http.rb:575:in `start' http....

java - SBT import option not found: Idea Ultimate -

Image
i installed intellij idea 14.0 ide play framework. , when tried import play project, don't see option import sbt project. have missed here? thank you! i had open idea anyway , install scala plugin. after restarted idea , option there.

dataframe - Two equal max values in R -

i have dataframe numbers(score) , repeating id. want maximum value each of id. used function top = aggregate(df$score, list(df$id),max) this returned me top dataframe maximum values corresponding each id. but happens 1 of id, have 2 equal max value. function ignoring second value. is there way retain both max values.? for example: df id score 1 12 1 15 1 1 1 15 2 23 2 12 2 13 the above function gives me this: top id score 1 15 2 23 i need this: top id score 1 15 1 15 2 23 i recommend data.table chris mentioned (good speed, steeper learning curve). or if don't want data.table use plyr : library(plyr) ddply(df, .(id), subset, score==max(score)) # same ddply(df, .(id), function (x) subset(x, score==max(score)))

sql server - Best method to merge two sql tables toegether -

so have 2 tables. 1 tracking a persons location, , 1 has shifts of staff members. staff members have staffid, location, start , end times, , cost of shift. people have eventid, stayid, personid, location, start , end time. person have event multiple stays. what attempting mesh these 2 tables together, can accurately report cost of each location stay, based on duration of stay multiplied associated cost of staff covering location @ time. the issues have are: location stays not align staff shifts. i.e. person might in location between 1pm , 2pm, , 4 staff might on shifts 12:30 1:30, , 2 on 1:30 till 5. there lot of records. not staff paid same my current method expand both tables have record every single minute. stay between 1pm , 2pm have 60 records, , staff shift goes 5 hours have 300 records. can take staff working on location @ minute minute value based on cost of each staff member divided duration of shift, , apply value corresponding reco...