Posts

Showing posts from August, 2011

mongoid3 - Best strategy for picking random documents in Mongoid -

i need pick random document out of database , wanted know better strategy ruby shuffle method less resource intensive large databases. add "random" field , have default value set proc returns random float. whenever need pull random document, type model.where(:random.gt => rand).first

mysql - Wordpress SQL Query to combine column data for all rows -

i have wordpress plugin allows users save favorite posts. in wordpress mysql database, table looks following: id | user_id | post_id -------+---------+------------ 1 | 1 | 3,4,5,6,7,8 2 | 2 | 5,7,8,10 3 | 5 | 3,6,8,10 i'm looking take post_id numbers, , combine them variable can foreach them find how many matches there current post i'm reading. for example, if i'm reading post id 10, want able see there 2 people have saved favorites. i've tried $data = $wpdb->get_var("select post_id $table_name"); , var_dump($data); returns my favorite posts, not all favorite posts. although did play devils advocate in comments regarding normalization, table layout seem pretty braindead. however, if unable normalize database tables , have work have, can technically ask rather hacky sql statement: select count(user_id) totalwishes table_name ( (post_id 'n,%') or (post_id '%,n,%') or (p

vb.net - Random Numbers to Text in Label -

public class mainform private sub exitbutton_click(byval sender object, byval e system.eventargs) handles exitbutton.click me.close() end sub private sub gueststextbox_keypress(byval sender object, byval e system.windows.forms.keypresseventargs) handles gueststextbox.keypress ' allows numbers , backspace key if (e.keychar < "0" orelse e.keychar > "9") andalso e.keychar <> controlchars.back e.handled = true end if end sub private sub mainform_load(byval sender system.object, byval e system.eventargs) handles mybase.load 'fills list box , selects first item typelistbox.items.add("kid's birthday") typelistbox.items.add("21st birthday") typelistbox.items.add("40th birthday") typelistbox.items.add("other birthday") typelistbox.selectedindex = 0 end sub private sub calcbutton_click(byval sender object, byval e system.eventargs) handles calcbutt

Php PDO wrong row count -

can explain me when echo $rows_affected variable, why 1 when should getting 2 based on db records? more half hour trying figure out , still cant solve it.. still noob on pdo. any other advices welcome. $sql1 = "select title page id=?"; $stm = $db->prepare($sql1); $stm->execute(array($id)); $row1 = $stm->fetch(pdo::fetch_assoc); $sql2 = "select id,title,pg_title page title=? order id asc"; $stm = $db->prepare($sql2); $stm->execute(array($row1['title'])); $rows_affected = $stm->fetchcolumn(); if (count($rows_affected) > 0) { for($i=0; $i <= $rows_affected; $i++) { $row2 = $stm->fetch(pdo::fetch_assoc); if($row2['id']==$id){ echo '<a href="javascript: void(0)"><b>'.$row2['pg_title'].'</b></a>&nbsp;&nbsp;'; }

sungridengine - Silently submit a job with qsub to SGE -

i have bash script submits hundreds of jobs using qsub responding sge queue (it takes second each job id show up). in order bypass time consuming process , not kill script when quit shell, run script background job appending & . while saves me half hour @ times, job id's still appear , mess command prompt. i wondering if possible suppress display of job id's or in way silently submit jobs queue. though, link talks of -z argument, doesn't work nor there mention of on qsub man page. thanks! better solution: instead of using '&' use gnu screen create session, submit job , leave session: http://www.gnu.org/software/screen/ . then, @ time, can create new (full-screen) windows other programs in them (including more shells), kill current window, view list of active windows, turn output logging on , off, copy text between windows, view scrollback history, switch between windows, etc. windows run programs independent of each oth

python - Why does recursive sequence not work correctly? -

i'm totally new python , i'm trying print solution recursive sequence: #input sequence variables = float(raw_input("type in = ")) n0 = int(raw_input("type in n_0 = ")) n1 = int(raw_input("type in n_1 = ")) y0 = float(raw_input("type in y_0 = ")) #define function y_n (forward iteration) def yn(n): if (n==0): return y0 else: return (1/n)-a*yn(n-1) #backward iteration def yn_back(n): return (1/a)*((1/n)-yn(n-1)) if(n1>=n0): in range(n0,n1+1): print(yn(i)) else: in range(n0,n1+1): print(yn_back(i)) but if run script a=5 , n0=1 , n1=30 , y0=log(5/6)=0.182322 solutions high (from 0.08839 3.29e+18 ) , values negative n. solution right n=1 . other n , (1/n) in definition of yn(n) seems ignored. can me? thanks lot! n integer, 1/n returning 0 n greater 1: >>> 1/1 1 >>> 1/2 0 >>> 1.0/2 0.5 to make sure you're using float divi

jquery - "If default.html exists within folder then" function -

is there easy way script function based off file existing or not in particular folder? perhaps running 404 test against folder? for example: if default.html exists in child directory preview, ... else ...? thanks help. you this: function exists(url) { var request = $.ajax({ type: 'head', async: false, url: url }); return request.status === 200; } i wouldn't use this, however. it's blocking call , momentarily lock browser. use error callback of ajax function , make request asynchronous: $.ajax({ type: 'head', url: url }).fail(function(request, status, error) { // error }).done(function(data, status, request) { // success }); better yet, don't @ all.

c++ - std::make_heap equivalent in Java? -

stl has useful function. there equivalent in java? write custom implementation useful not reinvent wheel. std::make_heap makes binary heap, used priority-queue , called priorityqueue in java. correction : there isn't standard binary-heap class in java, suggested 2 in comment below.

postgresql - How would I go about writing the SQL for the attached report? -

Image
we're moving data system another. i'm having rewrite reports new system has custom reporting module can write query , paste window , push out end user. have 1 report of users have been requesting can't figure out how write it. it breaks down school population grade level, gender , race. see attached below. i wrote breaks down population grade level not sure go here. select gl.title grade, count (s.student_id) students s, student_enrollment se, school_gradelevels gl s.student_id = se.student_id , se.school_id=gl.school_id , se.grade_id=gl."id" , se.syear =2012 , se.end_date null , se.school_id =10 group gl.title order grade; for reference gender s.gender , race s.race. i'm wondering if going have purchase reporting software crystal reports. there no data example presum gender , race information captured against student. what want initial table that: gradelevel | category | numofstudents -------------------------------------

Can't get jquery to work on mouseover -

i sure there simple solution problem can't find it. have images 'gold' trying have move on mouseover jquery transit. under larger image 'cabin1' has transparent areas. clicking on button, can work fine want have images move on mouseover. have created hotspots on larger image can't figure selector should mouseover function work. maybe hotspots not way go. anyhow, code working button version follows. question how work mouseover instead of button. new help. "http://ricostacruz.com/jquery.transit/jquery.transit.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("#gold2").transition({y:'-25px'}); }); }); </script> <body> <div id="container"><button>start animation</button> <img src="cabin1.gif" alt="cabin2" name="cabin" width="715" h

C++ No matching constructor -

recently, i've begun studying c++, , first c++ program - not work. error message: no matching constructor initialization of "document". the ide use xcode. class document { private: int doc_id; int lan_id; std::vector<int>::size_type n_total; std::vector<int> words; std::vector<int> counts; inline int doc_type(){return (counts.empty() && !words.empty())? 1:0;}; public: document(int docid) { doc_id = docid; n_total = 0; } document(int docid, int lanid) { lan_id = lanid; doc_id = docid; n_total = 0; } inline void add(int word, int count) { words.push_back(word); counts.push_back(count); } inline void add(int word) { words.push_back(word);} inline int word(int i) { return words[i]; } inline int cou

jquery - Giving Namespace in javascript file when a assignment statement is present -

i have piece of javascript code want add namespace. in code there assignment operation taking place outside functions. please tell me how put in namespace? code given below. var mynamespace={ canvaspanel:{}, stage:{}, someshape:{}, drawlinegraph:function(datalist,color,basey) { //create shape this.datalist=datalist; this.index=0; this.currentday=1; }, mynamespace.drawlinegraph.prototype = new createjs.shape(); //getting problem here mynamespace.drawlinegraph.prototype.constructor = drawlinegraph; //getting problem here** , drawlegend:function(){ } }; you can wrap function , subsequent assignments in function, call immediately, this: drawlinegraph: (function() { var f = function(datalist, color, basey { // create shape ... function code ... }; f.prototype = new createjs.shape(); ... more assignments ... return f; // assigned drawlinegraph })(),

Can't get Azure TableEntity etag on CreateQuery -

i'm doing query entities table, changing them, doing replace operation. replace operation fails because etag property on etag null. checked, , etag null when entity createquery() call, populated when retrieve(). there way etag manually? ienumerable<myentity> query = e in servicecontext.createquery<myentity>(tablename) e.id == queryid select e; myentity entity = query.firstordefault(); // update myentity object var replaceoperation = tableoperation.replace(entity); mycloudtableclient.gettablereference(tablename).execute(replaceoperation); // exception thrown here etag value null the problem stems fact mixing 2 different components. servicecontext.createquery<myentity>(tablename) is using system.data.services.client namespace. in model entity not track etag, context you. mycloudtableclient.gettablereference(tablename).execute(replaceoperation) is using table

c++ - ostream << istream and testing EOF on an empty file, alternatives for getting characters from istream -

this first post on stackoverflow, if i'm doing wrong, please let me know. have final exam intro c++ programming on wednesday next week, , have no way of checking answers prof's practice questions. i'm concerned checking see if input file empty before copying it's contents output file. also, grabbing characters input file. here's question , code below: suppose have following enumerated type list possible file i/o errors: enum fileerror { nofileerror, // no error detected openinputerror, // error opening file input openoutputerror, // error opening file output unexpectedfileend, // reached end-of-file @ unexpected spot in program emptyfileerror, // file contained no data }; provide appropriate implementations 3 following file handling routines: fileerror openinputfile(ifstream& infile, char *filename); // open named file input, , return opening status fileerror openoutputfile(ofstream& outfile, char *filename); //

html text tag running into the next line on mobile -

my code follows <div data-role="content" id="div1" align="top" style="padding:3 !important;" > <table border="0" align="center" cellspacing="0" width="100%" style="vertical- align: text-bottom;" > <tr> <td></td> <td> <div id="question1" class="question"> <input type="text" id="question" /> <style> #question{ font:5px; font-family:verdana; } </style> </div> </td></tr><tr> <td width="50"><img id="img2" width="40" height="36" style="float:right; margin-top: 0px;" ></td> <td style="text-align:center;&q

java - Hibernate One To One Bidirectional Not working -

i trying make code have bidrectional relationship(one one) apparently code not working. here's first class. public class user { @onetoone(cascade = cascadetype.all) @joincolumn(name = "user_profile_fk") private userprofile userprofile; //accessor methods , other stuff } and second class @entity @table(name ="user_profile") public class userprofile{ @onetoone(mappedby="userprofile") private user user; //accessor methods } now when run code exception error occurs unknown mappedby in: org.test.myapp.user, referenced property unknown: org.test.myapp.user.userprofile the field @ other side of association named userprofile , not userprofile , mappedby attribute must set userprofile .

javascript - AngularJS - Why have more than one controller -

what reasons there have multiple controllers in angularjs application? i've built few angular apps , i've never encountered problem thought multiple controllers make things easier me. i'm still bit of n00b, have never written unit test , code isn't manageable i'm sure it's ignorance. , i've heard other people have multiple controllers. put way: how 1 know should create new controller? from i've seen of angular application should have separate controllers separate scopes. instance, applications have user data. you'll want have data attached user model, inside user controller: function userctrl ($scope) { $scope.user = { name: "bmorrow", lastlogin: "4/16/2013" }; } and template (our view) inside specific portion of applications structure. right side of navigation bar example, or on user details page. establish portion assigning controller using ng-controller . creates scope of said contr

python - search by ObjectId in mongodb with pymongo -

i need search objectid python using pymongo error. ideas how search? import pymongo pymongo import mongoclient pymongo import objectid gate = collection.find({'_id': objectid(modem["dis_imei"])}) print gate traceback (most recent call last): file "c:\users\gerswin\documents\proyectos\demonio py\test.py", line 2, in <module> import pymongo file "c:\python27\lib\site-packages\pymongo\__init__.py", line 80, in <module> pymongo.connection import connection file "c:\python27\lib\site-packages\pymongo\connection.py", line 39, in <module> pymongo.mongo_client import mongoclient file "c:\python27\lib\site-packages\pymongo\mongo_client.py", line 45, in <module> pymongo import (auth, file "c:\python27\lib\site-packages\pymongo\database.py", line 22, in <module> pymongo.collection import collection file "c:\python27\lib\site-packages\pymongo\collection

python - SqlAlchemy: Convert inherited type from one to another -

let's have 2 different types both on same database table (single table inheritance): class employee(db.model): id = db.column(db.integer, primary_key = true) name = db.column(db.string, nullable = false) discriminator = db.column('type', string) __mapper_args__ = {'polymorphic_on': discriminator} class manager(employee): __mapper_args__ = {'polymorphic_identity': 'manager'} division = db.column(db.string, nullable = false) role = db.column(db.string, nullable = false) class worker(employee): __mapper_args__ = {'polymorphic_identity': 'worker'} title = db.column(db.string, nullable = false) (yes, i'm using flask-sqlalchemy , not plain vanilla) how might go converting 1 declarative model another. is, if "worker" promoted "manager?" how do that? have write raw sql that? sorry if has been asked before couldn't find googles. please note, contrived example.

c - Using realloc to shrink the string inside struct -

i have small question using realloc function. assuming have: typedef struct { char* location; int temp; int numberofrec; }temp; then declare pointer struct in main , allocate memory: int main() { temp* data = xcalloc (1, sizeof(temp)); //wrapper function data->location = xcalloc (20, sizeof(char)); //wrapper function } now if reallocate memory data->location in function. need return address of temp* data? int main() { somefunction(data); // use function or... //data = somefunction(data); ... } void somefunction(temp* data) { ... data->location = xrealloc (data->location, 10 * sizeof(char)); } no. don't. because data pointer structure. whenever access element of structure through data using '->' operator, first de-referencing pointer. for example, data->location ==> (*data).location also, when do, data->location = xrealloc (data->location, 10 * sizeof(char)); if realloc fails, leaking memory

authentication - Can't login with cakephp -

i can't login using auth in cakephp. there similar posts 1 on stackoverflow, answers seem not work me. i have create similar register form , works auth logging in, $this->auth->login(); returns false in userscontroller. auth uses correct usermodel , username field changed email. (note: when use username instead of email everywhere, doesn't work either). database has table user holds email , password field. password field hashed/encrypted use of: authcomponent::password() // appcontroller class appcontroller extends controller { public $helpers = array('html', 'form'); public $components = array( 'session', 'auth'); public function beforefilter() { $this->auth->usermodel = 'user'; $this->auth->fields = array('username' => 'email', 'password' => 'password'); $this->auth->loginaction = array('controller' =&

javascript - Get the time show animation how much duration is currntly running -

in jquery use following code: j=-(i) if(j%2==1) { $("#caption1").hide(); $("#caption1").fadein(1000); $('#main_div').hide(); $('#main_div').show(5000); } } if(i%2==0) { $("#caption1").hide(); $("#caption1").fadein(1000); $('#main_div').hide(); $('#main_div').show(5000); } while show animation want duration of animation completed? for example: i set show animation 5secs. show animation started. 2 secs animation completed[ 3secs remaining] in case need completed duration[2secs] on button click?? mark down time when animation started: var animationstarted = new date(); $('#main_div').show(5000); .... when need show how time has passed, take current time , subtract time saved in previous step. var = new date(); var elapsed = ( now.gettime() - animationstarted.gettime() ) / 1000; demo: http://jsfiddle.net/nzgu6/

visual studio 2010 - Not getting use HTML5 sementic markup -

i using visual studio 2010 professional , while creating mvc3 application after selecting internet template not getting 'use html5 semantic markup' checkbox option. you need sp1 option. can still use html5 markup, regardless. correction: need mvc3 tools update option you're looking for: http://haacked.com/archive/2011/04/12/introducing-asp-net-mvc-3-tools-update.aspx - install after installing sp1. sp1 gives intellisense support majority of new html5 , css3 updates, , tools update adds features project templates.

android - error (1, -2147483648) Cannot Play this Video -

i trying play .mp4 video file, have added in raw folder. result error (1, -2147483648) in logcat. after research notice caused unsupported codec/format. last 2 days rendered video in adobe premiere according http://developer.android.com/guide/appendix/media-formats.html ? in supportd formats , many more.the result same: error , "can't play video." when app launches. my java code this: public class mainactivity extends activity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); getwindow().setflags(windowmanager.layoutparams.flag_fullscreen, windowmanager.layoutparams.flag_fullscreen); getwindow().addflags(windowmanager.layoutparams.flag_keep_screen_on); videoview vv = (videoview) findviewbyid(r.id.videoview); string filename = "//biolab/res/raw/sequence"; vv.setvideouri(uri.parse(file

java - How to read color of a pixel on SWT canvas at mouse pointer? -

i wrote small program read colour of pixel @ mouse pointer location. not getting colour @ mouse pointer, rgb {0, 0, 0} printing on console. please fix/correct program below prints colour of pixel @ mouse pointer. import org.eclipse.swt.swt; import org.eclipse.swt.events.mouseevent; import org.eclipse.swt.events.mousemovelistener; import org.eclipse.swt.events.paintevent; import org.eclipse.swt.events.paintlistener; import org.eclipse.swt.graphics.color; import org.eclipse.swt.graphics.gc; import org.eclipse.swt.graphics.image; import org.eclipse.swt.graphics.imagedata; import org.eclipse.swt.graphics.palettedata; import org.eclipse.swt.graphics.point; import org.eclipse.swt.graphics.rgb; import org.eclipse.swt.layout.filllayout; import org.eclipse.swt.layout.griddata; import org.eclipse.swt.layout.gridlayout; import org.eclipse.swt.widgets.canvas; import org.eclipse.swt.widgets.composite; import org.eclipse.swt.widgets.display; import org.eclipse.swt.widgets.shell; public class

php - Passing post value with ajax -

i have code in index.php: $('#whois').click(function () { //console.log("button clicked"); $('#whois_content').html(""); $('#fade').fadeout('slow', function () { urllinkas(); }); }); i want pass post value test.php inside script, so: $('#whois').click(function () { //console.log("button clicked"); $.ajax({ type: "post", url: "test.php", data: info, success: function(){ //dont know write here } $('#whois_content').html(""); $('#fade').fadeout('slow', function () { urllinkas(); }); }); and call post value in test.php $_post['info'] maybe understand im saying. this better $.post("test.php", { info: "something", moreinfo: &qu

python 2.7 - Fish swim in pygame -

i want use python pygame module make 2d "fishtank". basically load jpg image background , load gif animated image depicting fish swimming , make move. i know how make static image move how make gif image move while image animated. i have pil installed, sure if need use it. if not work, can break apart gif file several static frames , cyclically make each of them show on screen. when latter 1 posted, former 1 needs removed, how remove ? here class used in name pygame animation work: class animation(pygame.sprite.sprite): def __init__(self, img, fps = 6): # call parent class (sprite) constructor pygame.sprite.sprite.__init__(self) # slice source image array of images self.images = self.loadsliced(img) # track time started, , time between updates. # can figure out when have switch image. self._start = pygame.time.get_ticks() self._delay = 1000 / fps self._last_update = 0

Supersized and codeigniter connection fails -

i have odd problem using codeigniter , supersized. plugin works fine , i'm able load root dir, when use in mvc workflow doesn't seem load image. the image correctly linked , can see code supposed there. thing see though, black screen. my code standard core example, nothing more/nothing less. linked still no dice. controller function test(){ $data['img'] = base_url()."../_data/images/bg.jpg"; $data['main_content'] = 'core_view'; $this->load->view('/includes/templatepop_view',$data); } html ... <link rel="stylesheet" href="<?=base_url();?>../_data/css/supersized.core.css" type="text/css" media="screen" /> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script> <script type="text/javascript" src="<?=base_url();?

Javascript merge two Arrays -

i want merge 2 arrays in javascript this: ['first', 'third', 'fifth', 'seventh', 'ninth'] ['second', 'fourth', 'sixth', 'eigth'] => ['first', 'second', 'third', 'fourth',...] also 1 array can have more elements one. example: ['e1', 'e2', 'e3'] ['e4'] => ['e1', 'e4', 'e2', 'e3'] what easiest way this? i don't have in idea how this. note: have underscorejs available. with underscore: var a1 = ['first', 'third', 'fifth', 'seventh', 'ninth']; var a2 = ['second', 'fourth', 'sixth', 'eigth']; var result = _.compact(_.flatten(_.zip(a1, a2)));

Form submission checkscript() javascript -

i want able submit form if 'my val 2' option selected. if option selected , submit button pressed, want cannot submit it. also, if submit it, want go submission page says submitted. here form: <form action="formsub.php" method="post" name="myform" onsubmit="return checkscript()"> <select name="test_select"> <option value="1">my val 1</option> <option value="2">my val 2</option> <option value="3">my val 3</option> <option value="4">my val 4</option> </select> <input type="submit" value="submit" name="test_button" onclick="submitform(test_select.value)"> </form> here javascript functions function submitform(val) { var obj = val;; alert("value = &

compiler construction - Executing a java program having input statements through another java program -

hi trying make online java compiler. as initial poc able compile , run program having no input statements dont'd know if there input statements also. i using runtime.getruntime().exec compile , run input java program. sample program having input statements trying run , execute : public class helloworld { public static void main(string[] args) { system.out.println("hello world.................."); scanner sc = new scanner(system.in); system.out.println("enter name"); string name = sc.nextline(); system.out.println("you entered " + name); sc.close(); } } problem when compile , run above program through code compiles , runt getting "enter name" of system.out.println("enter name"); in helloworld.java after nothing happens.

Output post for second wordpress editor -

i added new editor pages , posts admin area wordpress 3.3 new feature add_action( 'edit_page_form', 'my_second_editor' ); function my_second_editor() { // , set $content somehow... wp_editor( $content, 'mysecondeditor' ); } my question how output enter in second editor on website/page? need make custom loop? codex not helpful unfortunately. thanks you'll need get_post_meta() , use like: echo get_post_meta(get_the_id(), 'mysecondeditor'); read more: http://codex.wordpress.org/function_reference/get_post_meta to save data entered in second editor you'll need code in functions.php file: add_action( 'save_post', 'save_post', 10, 2 ); function save_post( $post_id, $post ) { if ( !current_user_can( 'edit_post', $post_id ) ) return $post_id; update_post_meta( $post_id, 'mysecondeditor', stripslashes( $_post['mysecondeditor'] ) ); } so after he's full code secon

java - Conversion from prefix to infix: Null Pointer exception -

i trying convert expression infix postfix. i've tried debugging code keep getting null pointer exception when variable popped. input error : (=> (not (award)) (badgrade)) the output after error (not award) please tell me if need edit q post lesser code/ add more comments/ provide more information. thanks! public class toinfix1 { stack<string> symbol = new stack<string>(); stack<string> variable = new stack<string>(); stack<string> operator = new stack<string>(); static string inputfile = "kb2.txt"; arraylist<string> infix = new arraylist<string>(); public void toprefix1() { try { file f = new file(inputfile); filereader fr = new filereader(f); bufferedreader bf = new bufferedreader(fr); string str; string kb = ""; while ((str = bf.readline()) != null) { pattern pattern = pattern.compile("[(]|[)]|<=>|=>|\\w+|^\\s+&quo

jsf 2 - p:dataExporter NOT working -

i trying write simple pdf export functionality using primefaces p:dataexporter. code below my development environment jsf-2.0, primefaces-3.4.2, eclips- juno, glassfish xhtml page <?xml version="1.0" encoding="utf-8" ?> <!doctype html public "-//w3c//dtd xhtml 1.1//en" "http://www.w3.org/tr/xhtml11/dtd/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.org/ui" > <h:head> <title>pdf export</title> </h:head> <h:body> <h:form id="myform" > <p:datatable id="tableid" var="car" value="#{tablebean.carssmall}"> <p:column headertext="model"> <h:outputtext value="#{car.mode

dynamic data - Java - Find the class name and the methods in that class also find the arguments available for the method -

i have package have find class available in package , methods available particular class , arguments methods available in method. like : package com.test.dynamic; public class test{ public testmethod(int test, string strargument){ //some implementation } } in if give package name must able class name : test , method name testmethod , arguments test , strargument if possible types also. how in java. best regards go through reflection api in java there many methods getname(), getinstance()..etc you: http://www.roseindia.net/java/reflect/class.shtml

Possible alternatives to speed up reads from a text file in c? -

i working on machine learning application features stored in huge text files. way have implemented data input reads, way slow practical. each line of text file represents feature vector in sparse format. instance, following example contains 3 features in index:value fashion. 1:0.34 2:0.67 6:0.99 12:2.1 28:2.1 2:0.12 22:0.27 26:9.8 69:1.8 3:0.24 4:67.0 7:1.9 13:8.1 18:1.7 32:3.4 following how making reads now. dont know length of feature string before hand, read suitably large length upper bounds length of each string. once, have read line file, use strtok_r function split string key value pairs , further process store sparse array. ideas on how speed highly appreciated. file *fp = fopen(feature_file, "r"); int fvec_length = 0; char line[1000000]; size_t ln; char *pair, *single, *brkt, *brkb; svector **fvecs = (svector **)malloc(n_fvecs*sizeof(svector *)); if(!fvecs) die("memory error."); int j = 0; while( fgets(line,1000000,fp) ) { ln = strlen(l

c - How does toggling a call to printf within a function determine whether my code doesn't crash? -

i writing simple function creates new node @ beginning of linked list. when try execute file windows command error window comes saying "a.exe has stopped working." what mystery me when add printf call within body of insertnewnodeatfront , code executes without above error box. ideas? here source file: #include <stdio.h> typedef struct nodetag{ const char* airport; struct nodetag * link; } nodetype; void insertnewnodeatfront(nodetype *, const char*); void insertnewnodeatfront(nodetype * l, const char* str){ nodetype * n; n = l; nodetype * newfirst; newfirst->airport = str; newfirst->link = n; l = newfirst; //printf("l->airport: %s\n",l->airport); <---this line magically makes work. } int main(){ nodetype * myitinerary; insertnewnodeatfront(myitinerary,"ont"); return 0; } as hmjd has said, crash caused using uninitialised memory. reason do

yii - EJuiDateTimePicker value is not saved to database -

i using ejuidatetimepicker extension date , time picker in yii framework. have downloaded ejuidatetimepicker , placed under protected\extensions\jui views: $this->widget( 'ext.jui.ejuidatetimepicker', array( 'model' => $model, 'attribute' => 'todo_datetime', 'value' => $model->todo_datetime, 'options' => array( 'dateformat' => 'dd-mm-yy', 'timeformat' => 'hh:mm:ss',//'hh:mm tt' default ), ) ); action: if(isset($_post['todo'])) { $model->attributes=$_post['todo']; if($model->save()) $this->redirect(array('view','id'=>$model->id)); } pro

update query using SQLQuery in Hibernate -

i have this: suppose: int posterid=100; int userid=5; sqlquery query=session.createsqlquery("update poster set userid='"+userid+"' posterid='"+posterid+"' "); query.executeupdate(); it not working, if write: sqlquery query=session.createsqlquery("update poster set userid=:userid posterid=:posterid "); query.setparameter("userid",userid); query.setparameter("posterid",posterid); query.executeupdate(); is not working too. session.begintransaction(); sqlquery query=session.createsqlquery("update poster set userid='"+userid+"' posterid='"+posterid+"' "); query.executeupdate(); session.gettransaction().commit();

linux - How to wake up a user mode sleep process in kernel? -

i want wake user-mode process in kernel . process blocked calling sleep() in user mode . called function wake_up_process() in kernel , process did not wake after wake_up_process() call. not know why . know how wake user-mode sleep process in kernel ? thank . if process called sleep() , wake either when time comes, or when gets signal. wake_up_process cause kernel test if time has come, , go sleep again. so send signal.

javascript - Passing variable issue -

i have livescore website , making widget out of site live results use @ client side tow lines of javascript: <div id="widget-container" class="my_widget" width="800px"></div> <script src="http://example.com/mywidget/widget.js" type="text/javascript"></script> i have id each user should use id proper css. server side code "widget.js": (function() { // localize jquery variable var jquery; /******** load jquery if not present *********/ if (window.jquery === undefined || window.jquery.fn.jquery !== '1.8.3') { var script_tag = document.createelement('script'); script_tag.setattribute("type","text/javascript"); script_tag.setattribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"); var script_tag1 = document.createelement('script'); script_tag1.setattribute("type","

android - "IOException: Try again" while using LocalServerSocket -

does have more helpful information on exception "try again"? i'm sending bitmaps between apps using localserversocket , localsocket : output: socket = new localsocket(); socket.connect(new localsocketaddress(socket_name)); fos = new dataoutputstream(socket.getoutputstream()); ... public void onevent() { fos.writeint(width); fos.writeint(height); fos.writeint(newbuffer.length); fos.write(newbuffer); } input: server = new localserversocket(socket_name); socket = server.accept(); socket.setsotimeout(60); while(true) { int width = fis.readint(); // io exception being thrown here int height = fis.readint(); int length = fis.readint(); byte[] bytes = new byte[length]; fis.read(bytes); } [try/catch etc removed clarity] 04-18 09:19:11.664: w/system.err(1268): java.io.ioexception: try again 04-18 09:19:11.664: w/system.err(1268): @ android.net.localsocketimpl.readba_native(native method) 04-18 09:19:11.664: w/system.e

extjs4 - How to specify static ID for "available" and "selected" panel of item-selector? -

i need know, how specify static id "available" , "selected" panel of itemselector? reason is, based on "available" item selected value, need restore "selected" panel value(but not selected value display, entire new storevalue). please provide ideas???

java - Comparison method violates its general contract Exception -

below block of code results in exception indicated, code : collections.sort( arraylist, new comparator() { public int compare( object o1, object o2 ) { typeadaptersort tas1 = ( typeadaptersort ) o1; typeadaptersort tas2 = ( typeadaptersort ) o2; if ( tas1.order < tas2.order ) return -1; else return 1; } } ); exception : java.lang.illegalargumentexception: comparison method violates general contract! @ java.util.timsort.mergelo(timsort.java:747) @ java.util.timsort.mergeat(timsort.java:483) @ java.util.timsort.mergeforcecollapse(timsort.java:426) @ java.util.timsort.sort(timsort.java:223) @ java.util.timsort.sort(timsort.java:173) @ java.util.arrays.sort(arrays.java:659) @ java.util.collections.sort(collections.java:217) when run same code standalone program, issue never occurs. issue compara

java - No runtime coverage using emma, junit and ant -

i have following project structure: src/com/dummy/abc.java src_tests/come/dummy/abctest.java build.xml i need check coverage of code done tests using emma. reading emma + junit examples came conclusion report need following: compile 'src' compile 'src_tests' instrument compiled 'src_tests' => 'instrumented_src_tests' run junit on 'instrumented_src_tests' additional jvmarg the problem step 4 should return kind of file used 'report' command should create report. i'm getting emma-report: [report] processing input files ... [report] 1 file(s) read , merged in 67 ms [report] nothing do: no runtime coverage data found in of data files ~ edit i'm attaching build.xml <?xml version="1.0" encoding="utf-8"?> <project name="hell scream" default="all" basedir="."> <property name="build.sources.dir" location="${basedir}/sr

javascript - Upload button will not fire programmatically -

i have button want use "upclick"-plugin uploading files <script type="text/javascript" src="~/scripts/upclick-min.js"></script> <input type="button" id="uploader" value="upload" > <script type="text/javascript"> var uploader = document.getelementbyid('uploader'); upclick( { element: uploader, action: '/path_to/you_server_script.php', onstart: function(filename) { alert('start upload: '+filename); }, oncomplete: function(response_data) { alert(response_data); } }); now button works in , opens "open file"-dialogue, cannot seem fire "click"-event on programmatically. ive tried different ways of writing syntax-wise: if (ui.draggable.hasclass('ui-dragdrop-picelement')) { //$("uploader").trigg

Change Windows password using Python -

i developing little password manager tool using python. allows central password manager , single use passwords, therefor nobody ever know password of server , won't need change passwords when employee goes other employer. anyway, design of software phone-home (and elimiate lot of firewall/natting issues) , run service. can sync users of system, verify if passwords got correct. resetting of password after logging in struggling @ moment. win32.net netuserchangepassword seemd have want. (i thought) called "net user *". after testing figured out called netuserchangepassword feature of msvc libs. issue doesnt work when enter old-password none. the process runs full-admin. , should able change user passwords without knowing old (disclaimer: unix background, root (superadmin) can everything, ciorrect me if wrong windows os). so, how can super-admin change password localusers without knowing old password using python scripting language? thanks! update: def se