Posts

Showing posts from June, 2011

Linking two tables generated from "rails generate Scaffold" (New to Ruby on Rails) -

i save person's information education, address, etc database tables. if generate person table(with education) using scaffold - id automatically generated primary key. i generate table called address same person using scaffold. how can link id of address table id of person table? you want person have_many addresses -see rails guide more on associations http://guides.rubyonrails.org/association_basics.html#the-has-many-association you can scaffold doing rails g scaffold address person:references line1:string city:string etc this generate model, address, foreign key person_id person belongs to.

unknown database format in access database -

i have ms access database, have edited in both access 2007 , access 2010, worked great months , have alot of data in tables. application uses still works, can't open database manually more. error "unknown database format " , "the visual basic applications project in database corrupt" . when click ok on dialog access trys repair db , when done error " id not index in table" . at moment have tryed open copy of databas, since can't have original databas not working. how long application work? or problem when opening in access? , ofc, how solve it? use undocumented -decompile switch in command window. make backup first! access' native compact & repair not fix problem of time. http://support.microsoft.com/kb/819780 alternatively, can create new, empty db , copy tables, queries, forms, etc... it.

ruby - Using Google APIs from automated task with OAuth -

i have regular, automated task needs query user data within google analytics api. must able run without manual intervention. (details, details: i'm presently using ruby gems legato , oauth queries.) as best can tell, because want query user data on google analytics, must use oauth 2.0. yet access token acquire expires after 1 hour, , refresh token appears work in presence of valid access token(?). i've obtained long-living oauth 1.0a token twitter bot script runs daily cron job. it's been running daily several years nary problem. it appears google/oauth 2.0, have acquire token manually, have task refresh token occasionally, , re-acquire token manually if job ever die. have hard time believing case. missing? oh, hello, it's called service account . initial, cursory reading of google's docs had me thinking service accounts not access user data, turns out correct way it.

c# - SelectList with Dictionary, add values to the Dictionary after it's assigned to SelectList -

i have following code - dictionary<string, string> mydict = new dictionary<string, string>(); mydict.add("keya", "valuea"); mydict.add("keyb", "valueb"); ienumerable<selectlistitem> myselectlist = new selectlist(mydict, "key", "value") further down in program, want add values mydict . possible? if yes, how? want - myselectlist.mydict.add("keyc", "valuec"); if you're wanting add items mydict, possible, , changes reflected in of myselectlist 's enumerations long changes made before enumeration (e.g. using .tolist() ) generated. as worked example: dictionary<string, string> mydict = new dictionary<string, string>(); mydict.add("keya", "valuea"); mydict.add("keyb", "valueb"); ienumerable<selectlistitem> myselectlist = new selectlist(mydict, "key", "value&q

c++ - Connecting to remote services from multiple threaded requests -

i have boost asio application many threads, similar web server, handling hundreds of concurrent requests. every request need make calls both memcached , redis (via libmemcached , redispp respectively). best practice in situation make separate connection both redis , memcached each thread (effectively tripling open sockets on server, 3 per request)? or there way me build static object, single memcached/redis connection, , allow threads share single connection? i'm bit confused when comes thread safety of this, , needs asynchronous between threads, blocking each thread's individual request (so each thread has linear progression, many threads can in different places in own progression @ given time). make sense? thanks much! since memcached have syncronous protocol should not write next request before got answer prevous. so, no other thread can chat in same memcached connection. i'd prefer make thread-local connection if work in "blocking" mode.

qt - QCocoaColorPanelDelegate error while loading plugin in Maya 2013 -

i'm building plugin maya 2013 uses qt. have compiled , built gcc-4.8 , qt v4.7.1 , when load plugin maya, maya crashes , following errors: objc[24831]: class qcocoacolorpaneldelegate implemented in both /applications/autodesk/maya2013/maya.app/contents/macos/qtgui , /library/frameworks/qtgui.framework/versions/4/qtgui. 1 of 2 used. 1 undefined. objc[24831]: class qmacsounddelegate implemented in both /applications/autodesk/maya2013/maya.app/contents/macos/qtgui , /library/frameworks/qtgui.framework/versions/4/qtgui. 1 of 2 used. 1 undefined. objc[24831]: class qcocoapanel implemented in both /applications/autodesk/maya2013/maya.app/contents/macos/qtgui , /library/frameworks/qtgui.framework/versions/4/qtgui. 1 of 2 used. 1 undefined. objc[24831]: class qcocoaview implemented in both /applications/autodesk/maya2013/maya.app/contents/macos/qtgui , /library/frameworks/qtgui.framework/versions/4/qtgui. 1 of 2 used. 1 undefined. objc[24831]: class qcocoawindow implemented in both /

Cassandra 1.2 huge read latency -

i'm working on 4 node cassandra 1.2.6 cluster single keyspace, replication factor of 2 (3 originally, dropped 2) , 10 or column families. running oracle 1.7 jvm. has mix of reads , writes, 2 3 times many writes reads. even under small amount of load, seeing large read latencies, , quite few read timeouts (using datastax java driver). here example output of nodetool cfstats 1 of column families: column family: user_scores sstable count: 1 sstables in each level: [1, 0, 0, 0, 0, 0, 0, 0, 0] space used (live): 7539098 space used (total): 7549091 number of keys (estimate): 42112 memtable columns count: 2267 memtable data size: 1048576 memtable switch count: 2 read count: 2101 **read latency: 272334.202 ms.** write count: 24947 write latency: nan ms. pending tasks: 0 bloom filter false positives: 0 bloom filter false ratio: 0.00000 bloom filter space used: 55376 compacted row minimum size: 447 compact

generics - Why doesn't Java allow overloads based on type parameters? -

we can away in .net: interface i<a> {} interface i<a, b> {} ... in java, same code result in compilation error. that's interesting, given if type information gone @ runtime, 1 expect information number of type parameter still there. if limitation related type erasure, can explain why? it's not related type erasure ambiguity arise using raw type : i eye = null; // 'i' it? raw types allowed in order accommodate code written before generics introduced in jdk 5.0.

C++ How to create a large bitmap from a datalist stored in a deque? -

Image
i building first ever program in c++ on , on again. the program intended create picture, a gradient - parameters of height h , width l , in pixels, , 4 parameters of density da, db, dc, dd . gradient produced '1 bit' pixels: black or white - , simplest error-diffusion algorithm (so-called "naive" sometimes), >> push error on next pixel of line. after having performed optimization ( deque instead of vector allows bigger images created ex.), stuck problem cannot solve now: my pixel values being stored in deque , how transport them bitmap file? i tried understand easybmp library couldn't find solution. in code, can see line 33 tried (unsuccessfully) make .pbm header (portable bit map) actually, i'd copy values of deque <int> dequea; (line 30) .bmp file or other raster file-format, instead of in .txt file happens line 72! here's code, , nice picture of makes : #include <iostream> #include <fstream> #include

knockout.js - Knockout validation message based set in the validation function -

i want set message display in validation function of knockout similar whats going on here: knockout validation plugin custom error message without async. heres ive tried, no validation message displayed. this.name = ko.observable().extend({ validation: { validator: function (val) { return { isvalid:val === 'a', message: 'the value ' + val + ' not a' }; }, message: 'i dont want default message' } }); jsfiddle is there way this? close, validator should returning true/false if rule passed. couldn't message: display value (even setting function had undefined arguments) can inline error message if want display value user. this.name = ko.observable().extend({ validation: { validator: function (val) { if (val !== 'a') { this.message = 'the value ' + val + ' not a'; return false; } retu

FireBug's console.log() jams Eclipse PHP debugging session (XDebug) -

i noticed debug sessions in eclipse fail systematically when .htm javascript files contain calls console.log(...)... , fail @ line call is. like if console.log function producing conflicting eclipse/xdebug. am suppose declare use firebugs console.log() ? thanks !

sql - PHP simple function not working -

i can't make simple echo. i have admin.class.php public static function get_quota() { return self::find_by_sql("select * quota"); } public static function find_by_sql($sql="") { global $database; $result_set = $database->query($sql); $object_array = array(); while ($row = $database->fetch_array($result_set)) { $object_array[] = self::instantiate($row); } return $object_array; } and echo code in index.php <?php $admin = user::find_by_id($_session['user_id']); $admin_class = new admin(); $get_quota = admin::get_quota(); $sql = "select * quota"; $get_quota = admin::find_by_sql($sql); ?> . . . <?php echo $get_quota->daily_a; ?> so problem is, code not working. cannot echo data. can me, please? you have couple of problems here: <?php echo $get_quota->daily_a; ?> this line references $get_quota variable , searches member field daily_a . try this:

javascript - how to create windows 8 look and feel but with expanding divs? -

i'm trying create interactive ui puzzle game have set width container , within 6 square divs (each 150x150px). 1 div expand open on page load. 1 div can open @ time. if click div open div must close first divs slide on make room div clicked open , expand. when slide cannot overlap each other. when div expanded measure 300x300px any ideas on how started? tried using jquery .animate code got mess when went reverse actions of last click before proceeding actions of new click. sorry being abstract, lemme know if there clarification needed. here built far...(its lot of spaghetti code). i'm doing - $('.yellow, .blue, .black, .grey, .purple, .pmadbig, .pmadsmall, .cache').attr('style', ''); clear done , reset puzzle. need reverse instead of snapping place. <!doctype html> <html> <head> <style type="text/css"> .box { color: #222 }

objective c - Is there a vDSP function to do the following operation? -

sorry if obvious. i'm getting accelerate framework , trying go beyond simple stuff. i'm staring down vdsp reference i'm not sure how following phrased or might called in technical lingo. want following operation - what's best way vdsp? i'm having trouble finding it. (in pseudocode, i 0 n:) o[i]= + b * (sum of vector 0 i) thanks! to clarify: these both vectors of floats , speed critical. it turns out equivalent to: vdsp_vrsum(i, 1, &b, o, 1, n); vdsp_vsadd(o, 1, &a, o, 1, n);

Getting Undefined Reference to Perl on C++ -

well, first of all, sorry bad english! i'm new linux, g++ , perl, , i'm getting problems here. i have code in g++ calls perl .pl file return information. right now, i'm returning 1 or 0 perl .pl file tests , understand how works. problem i'm getting $make: sathlervbn spam c # make clean;make rm -f *.o g++ -wall -d_reentrant -d_gnu_source -ddebian -fstack-protector -fno-strict-aliasing -pipe -i/usr/local/include -d_largefile_source -d_file_offset_bits=64 -i/usr/lib/perl/5.14/core -c -o filedir.o filedir.cpp g++ -wall -d_reentrant -d_gnu_source -ddebian -fstack-protector -fno-strict-aliasing -pipe -i/usr/local/include -d_largefile_source -d_file_offset_bits=64 -i/usr/lib/perl/5.14/core -c -o main.o main.cpp main.cpp: in function ‘int main(int, char**, char**)’: main.cpp:112:41: warning: deprecated conversion string constant ‘char*’ [-wwrite-strings] main.cpp:112:41: warning: deprecated conversion string constant ‘char*’ [-wwrite-strings] g++ -l/usr/lib

How to use the Web Publishing Pipeline and Web Deploy (MSDEPLOY) to Publish a Console Application? -

i use web deploy publish visual studio "console" application folder on target system. i have had luck, , have been able produce similar need, not quite. i've added following console .csproj: added following projectname .wpp.targets file <import project="$(msbuildextensionspath32)\microsoft\visualstudio\v10.0\webapplications\microsoft.webapplication.targets" /> and i've added following projectname .wpp.targets: <project defaulttargets="build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" toolsversion="4.0"> <propertygroup> <deployasiisapp>false</deployasiisapp> <includesetaclproviderondestination>false</includesetaclproviderondestination> </propertygroup> <itemgroup> <filesforpackagingfromproject include="$(intermediateoutputpath)$(targetfilename).config"> <destinationrelativepath>bin\%(recursivedir)

how can i manage url using .htaccess in php? -

i want manage url of website right showing me www.computermall.co.in/product_details.php?prdid=34 but want www.computermall.co.in/product_details/34 how can it? i have tried this options +followsymlinks -multiviews rewriteengine on rewritebase /computermall # uri-path directly the_request variable rewritecond %{the_request} ^(get|head)\s/(.*)\.php [nc] # strip extension , redirect permanently rewriterule .* /%2 [r=301,l,nc] rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewritecond %{request_uri} !\.php [nc] # map internally original resource rewriterule ^(.*)$ $1.php [l,qsa] try this: rewriteengine on rewriterule ^product_details/prdid/([^/]*)$ /product_details?prdid=$1 [l] edit: removed leading slash

linux - How does JIT compilation in Java load dynamically compiled instructions into memory? -

in java, jvms (e.g. hotspot) capable of jit compilation , technique used speed execution compiling bytecode native code. question is, how technically happen? understanding modern processors mark memory areas sections read-only, , sections executable in order prevent malicious code executing. so, jvm can't write new "executable code" memory spaces has access (i.e. self modifying code). so, guessing jvm produces native code, writes file , uses operating systems services dynamically load native code memory, , maintains internal mapping table of addresses of native code (function) locations in memory after operating system has loaded dynamic code can branch out native instructions. i did see answer: how jit compiled code injected in memory , executed? , i'm confused why operating systems allow user programs read+execute memory regions. other operating systems i.e. linux etc offer similar in order jit work? can clarify understanding? in linux, memory segme

get ownerinfo in android settings programatically -

is there way devicename ownerinfo under secure settings of android. found way string devicename = settings.secure.getstring(getactivity().getcontentresolver(), settings.secure.lock_pattern_owner_info); but in devlopers site there no such constant available. deprecated? have googled not find appropriate answer. i using android 4.1 version use string ownerinfo = settings.secure.getstring(getcontentresolver(), "lock_screen_owner_info"); make sure catch settingnotfoundexception

Google Spreadsheet Formula to Use Current Row in Function -

i want calculate product of 2 different columns (e.g., & b) each row on spreadsheet. single row, work using =product(a1:b1) , can't figure out how function use current row instead of manually entered row. know can reference current row using row() , error when try product(arow():brow()) . if copy formula quoted row, or fill down using ctrl+d, automatically change reference row copying/filling to. called "relative reference". if use formula =product($a$1:$b$1) , called "absolute reference", not change if copied elsewhere. you can use following formula in row: =a:a*b:b which return product of 2 values in row formula invoked.

iis 7 - WCF message authentication with both username and certificate -

long story short: my wcf clients should able provide both username , certificate service hosted in iis, should use information validate requests using custom policies. complete story: i have need authenticate wcf clients verify if can execute operations. we have 2 kinds of clients: wpf applications , web application. following: the web application uses certificate trusted service recognized special user permissions (the web application verifies permissions , wouldn't touch now) the wpf clients authenticate username/password provided user in implementation of operations, verify if certificate provided (then recognize "super user"), otherwise fallback username/password authentication. services hosted in iis 7 , need use nettcpbinding. able implement username validation, problem authorizationcontext inspected service contains identity information, , not certificate. following code used on client side initialize creation of channels (from spike i'm us

Library to create and upload jar dynamically to maven repository -

i have service based environment in have create jar , upload dynamically maven repository , return dependency tree it. there library create jar file , upload jar file maven repository , return me dependecny of uploaded jar. right im creating maven goals in eclipse don't want that. thanks, if don't want use command line or ide, have looked @ maven api? there's 'undocumented' maven embedder project. below links may started, pick approach easier you, while meeting requirements: https://github.com/jenkinsci/lib-jenkins-maven-embedder/blob/master/src/main/java/hudson/maven/mavenembedder.java http://maven.apache.org/ref/3.0.2/maven-embedder/apidocs/org/apache/maven/cli/mavencli.html http://q4e.googlecode.com/svn-history/r819/trunk/plugins/maven/core/src/org/devzuz/q/maven/embedder/internal/eclipsemaven.java http://developers-blog.org/blog/def../2009/09/18/how-to-resolve-an-artifact-with-maven-embedder

c# - Richedit control htmltext table formatting -

i using richeditcontrol in c#. want display table(html) in control. did want change font size , color of celltext, did not work :/ here code: string htmlbilgi = "<table><tbody style=color:purple>"; htmlbilgi += "<tr><td font:5px>ad</td><td>deniz</td><td>soyad</td><td>eliacik</td></tr>"; htmlbilgi += "<tr><td>meslek</td><td>ogretmen</td><td>yas</td><td>28"</td></tr>"; htmlbilgi += "</tbody></table>"; recbilgi.htmltext = htmlbilgi; you can try use styles: <td style=\"font-size:5px\">

java - Nexus 7 Trusted Execution Environment for Storing Vital Information -

i researched samsung galaxy s3 having mobicore part of tee(trusted execution environment), wondering if there similar mobicore-like nexus 7 , there secure world app running nexus 7 use security purposes. please see link http://www.sensepost.com//blogstatic/2013/06/mobicore.png

performance - How to update the textview content display rapidly in android? -

i want update textview showing current photo number rapidly when long pressed shutter button activate burst shot in camera. know , burst shot in camera, system busy , maybe not refresh textview . have done operations this: using runnable + handler: post runnable when current photo number updated call textview.settext(number) in run() private runnable mshowburstnumberrunnable = new runnable() { public void run() { mburstshottextview.settext(mcurrentshotsnum); } } private picturecallback mcontinuousjpegpicturecallback = new picturecallback() { public void onpicturetaken(final byte[]data, android.hardware.camera camera) { ... mcurrentshotsnum++; mhandler.post(mshowburstnumberrunnable); ... } } but textview can't display number rapidly expected. using android 4.2. you should make sure mhandler posting mshowburstnumberrunnable attached on main thread. main thread change ui. you try this private picture

expandablelistview - Collapse all group except selected group in expandable listview android -

i'm developing android application using expandable list view. need is, i'm listing group, contains child. if select unexpandable group, should expand, after ll select second group @ time first group should collapsed. did google, couldn't find want. please me out. have current expanded group position stored in variable. in ongroupexpanded following. private int lastexpandedposition = -1; private expandablelistview lv; //your expandable listview ... lv.setongroupexpandlistener(new ongroupexpandlistener() { @override public void ongroupexpand(int groupposition) { if (lastexpandedposition != -1 && groupposition != lastexpandedposition) { lv.collapsegroup(lastexpandedposition); } lastexpandedposition = groupposition; } });

ios - Trouble changing background image of navigationbar back button -

Image
this question has answer here: customization of uinavigationbar , button 4 answers i believe have tried other solutions matter. i use following code change background image of navigationbar backbutton . uiimage *image = [uiimage imagenamed:@"standard_bt.png"]; [[uibarbuttonitem appearance] setbackbuttonbackgroundimage:image forstate:uicontrolstatenormal barmetrics:uibarmetricsdefault]; this makes button appear this: without code, appears this: now, background image first picture, backbutton shape of second picture . note: achieve without having modify image named "standard_bt.png" how do that? possible? you have done right thing. ios sdk doesn't provide convenience method change shape of uiimage object according standard backbutton's shape. that said, answer is: no, can not realize shaped backbu

c# - Moving a tab page to a different tab control -

i have window (amongst other things) 2 tab controls , allow user drag , drop tab pages 1 tab control other. when tab control empty, want hide , expand other 1 take place. is there easy way that? ideally, custom tab control tabpage drag , drop support (similar used modern browsers, ides, etc.)

deploy openbravo in tomcat -

i have tried deploy openbravo tomcat using web browser. it throws me java.lang.outofmemoryerror: permgen space exception i tried increase memory adding following parameters in java options space -xms512m -xmx2048m -xx:permsize=512m -xx:maxpermsize=1024 -xx:+useconcmarksweepgc -xx:+cmsclassunloadingenabled -dfile.encoding=utf-8 after adding above parameters, tomcat service not starting. showing me error. please let me know, how deploy openbravo tomcat in web browser. http://wiki.openbravo.com/wiki/installation/troubleshooting#out_of_memory to avoid “out of memory” complaints during building ob must add options '-xms384m -xmx1024m -xx:maxpermsize=256m' both ant_opts , catalina_opts environment variables. notes on editing environment variables to make changes in environment system-wide should put assignations file , place in /etc/env.d, checking precedence , possible overwritings. bulbgraph.png not forget run env-update after making changes /

dns - Public localhost - possible? -

is possible make localhost available everyone?, under domain? ( without external ip ) i grateful if describe step step ! it is, lot of depends upon local network , internet service provider: ideally, have static ip address isp. there workarounds using external dynamic dns services (see http://en.wikipedia.org/wiki/dynamic_dns ), workarounds rather proper solutions. if want under own domain, dynamic dns provider may support this, either directly or providing hostname can add cname in own domain's dns settings. if have static ip address, can added 'a' record instead. you have ensure isp allows connections port 80 external sources. have ask isp this, though; may not, discourage people doing you're trying do. your local firewall / router need know route port 80 local machine; steps depend upon model of router you're using. in all, unless know you're doing, it's worthwhile spending few pennies , using 'proper' hosting solution.

Haskell mongodb text search -

what status of text search haskell mongodb driver? there 'like' operator in mongo similar sql variants, best way search collection or whole db particular text string? i've read people referencing external tools can see text search implemented in 2.4 mongo version done through command interface. there should not problems doing console how haskell driver? found 'runcommand' function in driver apis , looks should possible send 'text' command server signature shows returns 1 document - not list of documents. how done correctly? how efficiently search word or sentence in collection or db returns list of documents containing word? possible without external tools using mongo 'text search' feature? should done in application level? thanks. the result type contains list of documents (that contain searched text). unfortunately, not test query on running database, have used runcommand run aggregation (before implemented haskell driver).

c# - Keeping the image in form -

i made 2 forms. form2 has button set background image. got : this.backgroundimage = new bitmap(properties.resources._1334821694552, new size(800, 500)); //_1334821694552 name of image how change background in forms button click stay way until picture chosen? if understand correctly, have form form2 contains buttons change background image on form form1 . i wonder why use this.backgroundimage in form2 change background image? change background image on form2 , not on form1 . you should passing reference form1 form2 , use form1.backgroundimage = ... . this bit vague - suggest edit question add information on how relation between form1 , form2 is. first of all, need pass instance of form1 form2 . done in constructor, example, assuming form2 opened in form1 . example this: code in form2 // in form2, there's member variable holds form1 reference private form1 m_form1instance; // constructor of form2 public form2(form1 form1instance) { ...

c# - Accented characters displayed as hex values in mail source file -

i have convert content of mail message xml format facing encoding problems. indeed, accented characters , others displayed in message file hex value. ex : é displayed =e9, ô displayed =f4, = displayed =3d... the mail configured sent iso-8859-1 coding , can see these parameters in file : content-type: text/plain; charset=iso-8859-1 content-transfer-encoding: quoted-printable notepad++ detects file "ansi utf-8". i need convert in c# (i in script task in ssis project) readable , can not manage that. i tried encoding in utf-8 in streamreader nothing. despite readings on topic, still not understand steps lead problem , means solve it. i point out outlook decodes message , accented characters displayed correctly. thanks in advance. ok looking on wrong direction. keyword here "quoted-printable". issue comes , have decode. in order that, followed example posted martin murphy in thread : c#: class decoding quoted-printable encoding? the

java - Change a .properties file inside a jar from within that jar -

i have runnable jar , change properties file inside runnable jar itself. main aim here when jar runs first time, communicates other modules using ipc , gets details other module, after getting details jar must persist values when runs again next time, must able use new details. if not possible, best way such thing storing these details temporary location may not way.

xaml - WinRT hardcoded ListViewItem vs. DataTemplate, why do they not look/work the same? -

i'm new winrt apologies if silly question. i've created following listview: <listview x:name="mylistview1" grid.row="1" margin="120,300,0,0" width="500" horizontalalignment="left"> <listviewitem background="dodgerblue"> <grid> <grid.columndefinitions> <columndefinition width="200" /> <columndefinition width="300" /> </grid.columndefinitions> <textblock text="hardcoded value 1" grid.column="0"></textblock> <textblock text="hardcoded value 2" grid.column="1"></textblock> </grid> </listviewitem> </listview> this looks way want look, , if click item select whole row. however, if move datatemplate doesn't same, , can no longer c

How to perform 'insert rows' instead of 'copy rows' using CopyFromRecordset(excel vba) -

i new excel vba. have requirement have copy table values sql server 2005 excel worksheet. have googled , written code above requirement (listed below). in excel sheet there fixed set of rows displays legends , dates. these rows should displayed after database/table values printed. using .copyfromrecordset copy records recordset excel sheet, rows displaying legend , dates overwritten database/table values. please let me know how perform insert of rows instead of copy. or there way achieve above. ---code------------ sub getsqlserverdata() dim cn adodb.connection dim server_name string dim database_name string dim user_id string dim password string dim sqlstr string dim userid string dim rs adodb.recordset set rs = new adodb.recordset userid = range("c1").value 'input form excel template. server_name = "" 'enter server name database_name = "" 'enter database name user_id = "" 'sql server user id password = "" sq

java - How to fix pmd violation "NullAssignment"? -

pmd report nullassignment of following code, best practice fix it? assigning object null code smell. consider refactoring. the following code not written me, have question on why creating temporary timer instance, assign instance timer? starttimer , stoptimer used in multithread context. private timer timer; private void starttimer() { if (timer == null) { timer atimer = timerservice.createtimer(default_timer_value, null); atimer.setlistener(this); timer = atimer; } } private void stoptimer() { if (timer != null) { timer atimer = timer; timer = null; atimer.cancel(); atimer.setlistener(null); } } public void start() { synchronized(..) { starttimer(); } } public void stop() { synchronized(..) { stoptimer(); } } this code written in false believe reference set null garbage collected faster. therefore message pmd false believe coded. this wrong assumption garbage colle

regex - How does this weird JavaScript function for primality check work? -

this question has answer here: how determine if number prime regex? 4 answers this function: var isprime = function(x) { return (!(/^,?$|^(,,+?)\1+$/.test(array(++x)))); }; it works small numbers, when number large, throws exception saying invalid array length. cannot understand what's going on here. regex test do? why code work? array(++x) first produces string of x commas. the regex now: ^,?$ // match 1 , or none | // or ... ^(,,+?)\1+$ // specific number of commas, elaboration below: the number of commas equal @ least 2 commas, repeat till end. it's attempting is: it first attempts match 2 commas ( ,+? matches @ least 1 , lazily), , use match multiples of 2, except 2 because backreference of \1 compulsory. multiples of 2 because ^(,,)\1+$ matches number of , . sidenote: \1 backreference , match first

sql - Why subquery returns <= Error Occurs -

my sql query is alter procedure [dbo].[proc_project_cat_d_list] @user_id bigint=null, @cat_id bigint=null, @dept_id bigint=null if(@cat_id > 0 ) begin select detail_id, detail_code, spec_1, spec_2, spec_3, spec_4, cat_id project_cat_details cat_id=@cat_id end else begin if(@dept_id null) select @dept_id=dept_id employee_master emp_id=@user_id create table #temp_dept ( dept_id bigint, dept_name varchar(100), parent_dept bigint ) insert #temp_dept ( dept_id, dept_name, parent_dept ) exec [dept_list] @dept_id, 1, @user_id select pcd.detail_id, pcd.detail_code,isnull(spec_1,'')+ ' ' +isnull(spec_2,'') specsfi, pcd.spec_1, pcd.spec_2, pcd.spec_3, pcd.spec_4, pcd.cat_id,p.project_name,pc.cat_name, p.project_id #temp_dept t, projects p, project_cat pc, project_cat_details pcd t.dept_id=p.dept_id , p.project_id=pc.project_id , pc.

can't get the category ID ( java/sql ) -

i have 2 tables: salon_stock categories the salon_stock table has fk column cat_id of categories table categories table have 2 columns cat_id & title in below code trying insert cat_id belong category name retrieved jcombobox along data of salon_stock table private void addstock() throws sqlexception,nullpointerexception { int catid = 0; string cat=cat_list.getselecteditem().tostring(); if (cat.equals("select category")) { resultset rs = con.createstatement().executequery("select * categories title=' default'"); if(rs.next()){ catid=rs.getint("cat_id"); } else{ throw new sqlexception("the 'default' category not found in categories table"); } } else{ resultset rs = con.createstatement().executequery("select * categories title=' "+cat+"'&q