Posts

Showing posts from January, 2010

sql server - Saving to a Database using C++ -

i developing c++ application , have problem when comes save ta database. using visual studio 2010 , database using microsoft sql server database. can please achieve task since beginner in c++? if you're working ms tools, want use sql server native client

c - How to clean the Array after write some information -

i first declare pointer array int q,k; char ***scharray; scharray = malloc(sizeof(char**)*1000); for(q = 0; q < 1000; q++) { scharray[q] = malloc(sizeof(char*)*100); for(k = 0; k < 1000; k++) { scharray[q][k] = malloc(sizeof(char)*100); } } char buf[80]={0}; then read data pipe put in buf , copy pointer array strcpy(scharray[commandnum][0], buf); after that, want clean content of pointer array. use following code. scharray[commandnum][0]=null; after that, cannot write data scharray[commandnum][0] code strcpy(scharray[commandnum][0], buf); is there mistake in code above? i think want set first character of allocated string '\0' . you'd using scharray[commandnum][0][0] = '\0'; your current code replaces (and leaks) pointer buffer allocated malloc(sizeof(char)*100) as aside, , before pulls me on it, note sizeof(char) guaranteed 1 malloc can simplified malloc(100) .

java - Display online users from server to all connected clients -

i'm building simple socket server-client application consisting of: server project (which creates new client handler thread when socket accepted) , client project (which establishing connection server , displaying gui message thread open). so far i'm able connect using multiple clients , chat no problems. i've set command called !getusers should display connected users requesting client. when so, i'm unable continue , chat, client stuck, connected users list though. as request here entire client code: import java.io.*; import java.net.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; import static java.lang.system.out; import java.util.logging.level; import java.util.logging.logger; public class chatclient extends jframe implements actionlistener { string uname; printwriter pw; bufferedreader br; jtextarea tamessages, tauserlist; jtextfield tfinput; jbutton btnsend, btnexit; socket client; public chatclient(string uname, string servern

cocoa - Ligatures not do not work in UILabel/NSAttributedString in iOS 6 -

Image
i trying turn on ligatures ( nsligatureattributename ) nsattributedstring displayed uilabel . i targeting ios 6.1 , running in ipad simulator. my set of test words are: aeciospore coeliac halfheaded cliffhanging aufkommender snuffkin domineesbriefjes offtrack dahinraffte coffins my test code simple, loops through list of words , display 1 in uilabel using text property: self.normallabel.text = words[i]; and other using attributedtext property, after creating nsattributedstring (see brandon campbell's answer more info on value of nsligatureattributename ): nsdictionary *attrs = @{ nsfontattributename : [uifont systemfontofsize:74.0], nsligatureattributename : @1, //@2 not supported in ios nsbackgroundcolorattributename : [uicolor redcolor]}; self.attr.attributedtext = [[nsattributedstring alloc] initwithstring:words[i] attributes:attrs]; as can see i'm setting nsligatureattribut

java - what is the meaning of 1.3.6.1.2.1.43.11.1.1.5.1.1 3 ) in snmp? -

i wrote snmp application test printer status. when give 1.3.6.1.2.1.43.10.2.1.15 check printer status got ( 1.3.6.1.2.1.43.11.1.1.5.1.1 3 ) output. newvars = cominterface.getmibentry(itemids); if knows, please me. not sure library use perform above operation. if can convert java code sequence of operations can repeat step step on mib browser, should able interpret meaning. for example, 1.3.6.1.2.1.43.10.2.1.15 column named prtmarkerstatus in prtmarkertable, defined in printer-mib (original rfc http://tools.ietf.org/html/rfc3805 ), http://www.oidview.com/mibs/0/printer-mib.html because column, hardly understand mean "when give 1.3.6.1.2.1.43.10.2.1.15 check printer status got (1.3.6.1.2.1.43.11.1.1.5.1.1 3) output". snmp request on wire? next, bulk, or another? meaningless send 1.3.6.1.2.1.43.10.2.1.15 that's invalid. the proper way manage printers, digest rfc 3805, documents tables defined in it, , columns mean. once understand how mib docu

asp.net - Adding Subscribe Button for a RSS URL -

i have rss url website , have make people directly subscribe url clicking on image home page. image click must have functionality similar "subscribe" button found in header of rss page. if declare rss html links ( how tell web browsers atom feeds ) many browsers show 'subscribe' buttons. however, there's no general way cause subscription single link; you're better off linking feed , relying on browser offer add new subscription. (you may able better specific aggregators, i'm assuming you're after using browser's subscription mechanism here.)

actionscript 3 - removing instance after excecuted 2 -

got parameter child must non-null error code can ? for (i=1; i<=4; i++) { this["box" + i].addeventlistener(event.enter_frame, move); this["box" + i].addeventlistener(mouseevent.click, action); } function move(e:event):void { e.target.y -= 6; if (e.target.y <= 56) { movieclip(e.target).removeeventlistener(event.enter_frame, move); removechild(getchildbyname(e.target.name)); comment.text = "miss"; miss += 1; score += 0; } } function action(event:mouseevent):void { if ((event.target.hittestobject(bts1))&&(event.target.hittestobject(bts2))&&(event.target.hittestobject(bts3))&&(event.target.hittestobject(bts4))) { movieclip(event.target).removeeventlistener(mouseevent.click, action); removechild(getchildbyname(event.target.name)); comment.text = "perfect"; perfect += 1; score += 10000; } else

pyqt4 - How to raise traceback of other class in main class in python -

i coding in python , added trace-backs error handling. for better understanding, lets have 3 classes. c1 = main class traceback = other class my main class import other classes (traceback) , create instances of these class , proceeds coded. error handling imported traceback module in 3 classes , updated code within try: except: working fine desired. now got idea, keep traceback in main class. other classes imported in main class. my c1.py looks below import traceback traceback import c3 class tracebacktest(): def __init__(self): try: self.c3_inst = c3(1,0) self.c3_inst.sub() except exception ex: tracebk = traceback.format_exc() print 'error raised trace back\n%s' % tracebk if __name__ == '__main__': import sys pyqt4 import qtgui app = qtgui.qapplication(sys.argv) win = tracebacktest() sys.exit(app.exec_()) my traceback.py looks below f

Modify batch script to conditionally write files -

i have batch file below copied internet. need it. batch takes output command or other batch , echos output both console , specified file. echoing console fine there way write file when condition met? may if echoed text contains string "logmessage". if 2 messages echoed command or batch, message 1: "hello, how you?" message 2: "logmessage thanks, good." the message 1 should displayed on console , message 2 should displayed both on console , in file. @echo off :: check windows version if not "%os%"=="windows_nt" goto syntax :: keep variables local setlocal :: check command line arguments set append=0 if /i [%1]==[-a] ( set append=1 shift ) if [%1]==[] goto syntax if not [%2]==[] goto syntax :: test invalid wildcards set counter=0 /f %%a in ('dir /a /b %1 2^>nul') call :count "%%~fa" if %counter% gtr 1 ( set counter= goto syntax ) :: valid filename seems have been specified set file=%1

file - changing folder name, matlab -

i want set path text file programmatically. e.g., file = 'h:\user4\matlab\myfile.txt'; [pathstr, name, ext] = fileparts(file) pathstr = h:\user4\matlab name = myfile ext = .txt i want write file in h:\user4\myfile . how can name. i want newfilepath=strcat(pathstr,'myfile'). obviously gives h:\user4\matlab\myfile don't want. how can write code. get parent path manually: islashes = strfind(pathstr,filesep()); newfilepath=fullfile(pathstr(1:islashes(end)),'..','myfile') which uses fullfile , filesep , strfind . fullfile nice concatenate strings while working files , paths. or use '..' matlab understand , refer parent directory of preceding directory: newfilepath=fullfile(pathstr,'..','myfile')

Adding Values In a Stochastic Simulation using R -

here i've managed extract extract time in discrete form such 1,2,3...,50 each simulation of users. but, since there no value interval 20-21 , more, there coding such can add value inside myself? because, if there no reading time interval, means readings same until next interval. coding used below: library(gillespiessa) parms <- c(beta=0.591,sigma=1/8,gamma=1/7) x0 <- c(s=50,e=0,i=1,r=0) <- c("beta*s*i","sigma*e","gamma*i") nu <- matrix(c(-1,0,0, 1,-1,0, 0,1,-1, 0,0,1),nrow=4,byrow=true) set.seed(12345) out <- lapply(x=1:1,fun=function(x) ssa(x0,a,nu,parms,tf=50)$data) out a<-as.data.frame(out) idx <- diff(ceiling(a$v1)) == 1 a[idx,] ## change ==1 >0 idx <- diff(ceiling(a$v1)) > 0 ## discrete time series discrete.data <- a[idx,] ## last time step value end.time <- ceiling(tail(discrete.data$v1,1)) ## create empty data frame time steps new.df <- data.frame(t=0:end.time, s=0, e=0, i=0, r=0

c# - Create my own Unique ID -

i trying create own unique id in c# each document in nosql database not sure how that? my example uid ######.entitytype@######.contextname.worldname the hashes alphanumeric characters. making assumptions here, generate guid, split guid on hyphen, use parts of guid in user name. use string builder concatenate all. here's bit of sample code give idea (untested): guid g = guid.newguid(); string[] parts = g.tostring().split('-'); stringbuilder sb = new stringbuilder(); sb.append(parts[0]); sb.append("entitytype@"); sb.append(parts[1]); sb.append(".contextname.worldname"); string id = sb.tostring(); this won't globally unique, should give range of uniqueness scenario. to match hash lengths above this: string gstring = guid.newguid().tostring().replace("-",""); stringbuilder sb = new stringbuilder(); sb.append(gstring.substring(0,6)); sb.appe

ios - Prevent UITableViewCell selection when dragging a subview -

i have uitableviewcell subclass , have added uiview contentview property. in order enable dragging subview, have implemented uiresponder appropriate methods: - (void)touchesmoved:(nsset *)touches withevent:(uievent *)event { uitouch *touch = [touches anyobject]; cgpoint currentlocation = [touch locationinview:self.superview]; if (currentlocation.x >= self.rootframe.origin.x) { return; } cgrect frame = self.frame; frame.origin.x = currentlocation.x; self.frame = frame; } - (void)touchesended:(nsset *)touches withevent:(uievent *)event { self.frame = self.rootframe; // rootframe copy of initial frame } - (void)touchescancelled:(nsset *)touches withevent:(uievent *)event { [self touchesended:touches withevent:event]; } the subview can dragged without problem, cell being selected well, -tableview:didselectrowatindexpath: being called. how can prevent cell becomes selected when subview being dragged? -[uitableviewcell setselectionstyle: uit

register eventhandler for Office 2013 event in vs 2010 by reflections in C# -

i have outlook 2010 add-in project written in c# using visual studio 2010. since add-in overall working in outlook 2013 want make slight modification, prevent problems new inlineresponse feature in outlook 2013. i want register eventhandler inlineresponse event without upgrading vs 2012 (because of removed installer project). read using reflections new events. i don't exceptions, event doesn't trigger handler (oninlineresponse not called). public partial class thisaddin { outlook.explorer _explorer; private void thisaddin_startup(object sender, system.eventargs e) { _explorer = application.activeexplorer(); addinlineresponsehandler(); } private void addinlineresponsehandler() { var einfo = _explorer.gettype().getevent("inlineresponse", bindingflags.public | bindingflags.instance); if (einfo != null) { var handler = delegate.createdelegate(einfo.eventhandlertype, this, this.gettype().getmethod(

Cassandra Scrub - define a destination directory for snapshot -

in c* 1.2.4 setup, have ssd drive of 200gb data , rotational drive commit logs of 500gb. i had unpleasant surprise during scrub operation fill in ssd drive snapshots. made cassandra box unresponsive kept status when doing nodetool status . i wondering if there way specify target directory snapshots when doing scrub. otherwise if have ideas workarounds? can column family @ time , copy snapshots folder, open smarter solutions. thanks, h snapshots in cassandra created hard links existing data files. means @ time snapshot taken, takes no space. however, causes old files remain if delete or update data, old version still there. this means snapshots must taken on drive stores data. if don't need snapshot more, delete 'nodetool clearsnapshot' (see nodetool output how decide snapshots delete). if want keep snapshot can move elsewhere. start using disk space after while, keep until happy scrub didn't delete important data delete snapshot.

php - if/else for non-duplicate of data -

im having problem, seems codes incorrect. want prevent duplication of data. in array submit form result, if user have kind of row, can insert data not in table. current code not insert data. if remove if else statements, data within loop can inserted. if(isset($_post['submit'])) { $var_emp_id = $_post["emp_id"]; $var_task_id = $_post["task_id"]; $var_weight = $_post['weight']; $submit=$_post['submit']; ($i = 0; $i <= count($var_emp_id); $i++) { $sql=mysql_query("select emp_id,task_id peval_tbl emp_id = '$var_emp_id[$i]' , task_id = '$task_id[$i]'"); while($row=mysql_fetch_assoc($sql)) { $emp_id = $row['emp_id']; $task_id = $row['task_id']; if ($var_emp_id[$i] == $emp_id && $var_task_id[$i] == $task_id){ mysql_query("inser

php - Loading a resource model in Magento- failed to open file -

i trying ues resource model , following when try load it: warning: include(mage\core\resource\model.php): failed open stream: no such file or directory in c:\xampp\htdocs\magento\lib\varien\autoload.php on line 93 my controller action looks like: $blogpost = mage::getmodel("test/blogpost"); $blogpost->load(1); my config.xml looks like: <?xml version="1.0"?> <config> <modules> <lock_test> <version>1.0.0</version> </lock_test> </modules> <global> <models> <test> <class>lock_test_model</class> <resourcemodel>test_resource</resourcemodel> </test> <test_resource> <class>lock_test_model_resource</class> </test_resource> </models> </global> <frontend> <routers> <

sql - Is it possible Looping in trigger -

my trigger on table affected here: update table_name set value = @value now execute above query means trigger execute now trigger after update begin . . update table_name set value = @value . . end now 2nd update query execute means again trigger execute or not question. maybe in sql server, "direct trigger recursion" this controlled 2 things "nested triggers" option @ server level controls trigger recursion. see msdn: http://msdn.microsoft.com/en-gb/library/ms178101.aspx recursive_triggers @ database level controls direct recursion. see http://msdn.microsoft.com/en-us/library/bb522682.aspx for full details, see create nested triggers on msdn note loop until @@nestlevel reaches 32

android twitter login Looper.prepair -

i'm making login android application using twitter api dialog contains web view component this error come logcat "can't create handler inside thread has not looper.prepare() " solution of error ? code of oauthrequesttokentask.java class import com.noqwerty.m.loginactivity; import oauth.signpost.oauthconsumer; import oauth.signpost.oauthprovider; import android.content.context; import android.os.asynctask; import android.os.looper; import android.util.log; public class oauthrequesttokentask extends asynctask<void, void, void> { final string tag = getclass().getname(); private context context; private oauthprovider provider; private oauthconsumer consumer; public oauthrequesttokentask(context context, oauthconsumer consumer, oauthprovider provider) { this.context = context; this.consumer = consumer; this.provider = provider; } @override protected void doinbackground(void... params) {

asp.net - My specific web.x.config file is not used -

i working on asp.net mvc projet running on windows azure. upgraded packages of project , seems web.x.config not loaded anymore. to more precise, i've got 3 different configuration : - development - staging - production each 1 has web.x.config x replaced 1 of these names. when running project suprised database connection string pretty dull (.\sqlexpress) instead of connection azure. after long time searching on web, tried move web.development.config : <add name="databasecontext" connectionstring="server=tcp:xxx.database.windows.net,1433;database=<database>;user id=<login>;password=<pass>;trusted_connection=false;encrypt=true;" providername="system.data.sqlclient" xdt:transform="insert"/> to web.config, removing transform : <add name="databasecontext" connectionstring="server=tcp:xxx.database.windows.net,1433;database=<database>;user id=<login>;password=&l

c - Segmentation fault on mcrypt (probably something to do with the buffer) -

i'm trying build own crypter in c using aes encrypt shellcode. i've made poc of crypter in 1 program can found below: #include <stdio.h> #include <stdlib.h> #include <string.h> /* * mcrypt api available online: * http://linux.die.net/man/3/mcrypt */ #include <mcrypt.h> #include <math.h> #include <stdint.h> #include <stdlib.h> int encrypt( void* buffer, int buffer_len, /* because plaintext include null bytes*/ char* iv, char* key, int key_len ){ mcrypt td = mcrypt_module_open("rijndael-128", null, "cbc", null); int blocksize = mcrypt_enc_get_block_size(td); if( buffer_len % blocksize != 0 ){return 1;} mcrypt_generic_init(td, key, key_len, iv); mcrypt_generic(td, buffer, buffer_len); mcrypt_generic_deinit (td); mcrypt_module_close(td); return 0; } int decrypt( void* buffer, int buffer_len, char* iv, char* key, int key_len ){ mcrypt td = mcrypt_mod

c# - Sorted list in NHibernate without sequential numbers -

i have sorted list in class foo. read index column have sequential , start in 0 , 1, 2, 3, 4, 5... in case, in order column have 0, 1, 2, 5. foo objects have list length of 6. positions 3 , 4 null. this map <list name="bars" cascade="all-delete-orphan"> <key column="foo_id" /> <index column="order" /> <one-to-many class="bar" /> </list> how can rewrite map in order remove null positions? i had similar situation due legacy concept adopted in our tables: our index column starts in 1 , remaining nasty null value in position 0 when retrieve collection list. the solution our case use these collections iset instead. to keep order, put order-by attribute in our mappings , , control index persistence ourselves. using example, become: <set name="bars" cascade="all-delete-orphan" order-by="order"> <key column="foo_id" />

php - oci_execute identifier must be declared ORA-06550 -

the procedure: function f_exists ( p_pidm gobansr.gobansr_pidm%type, p_num gobansr.gobansr_num%type, p_rowid gb_common.internal_record_id_type default null) return varchar2 -- type queryone_ref ref cursor; lv_cursor queryone_ref; lv_tempout varchar2(1) := 'n'; begin -- -- assign cursor variable appropriate cursor -- if p_rowid not null open lv_cursor select 'y' gobansr rowid = p_rowid; else open lv_cursor select 'y' gobansr gobansr_pidm = p_pidm , gobansr_num = p_num; end if; fetch lv_cursor lv_tempout; close lv_cursor; return lv_tempout; end f_exists; php code run/query stored procedure: $conn = oci_connect($username, $password, $db); $sql = 'begin "gb_pin_answer"."f_exists"(:p_pidm, :p_num); end;'; $stmt = oci_parse($conn, $sql); if (!$conn) exit("db did not connect."); $p_pidm =

internet explorer - Competing X-UA-Compatible meta tags -

one of our websites run offsite company. noticed had following meta tag default on of our pages: <meta content="ie=8" http-equiv="x-ua-compatible" /> when asked them update this, added meta tag <meta content="ie=edge,chrome=1" http-equiv="x-ua-compatible" /> beneath it. when pull in ie9 or ie10 still defaults ie8. (i did check see if setting in version of ie, , other websites display correctly.) intuition meta tags competing. know if case? additionally, if have them remove ie=8 tag, render correctly? yeah, there's no reason have both tags. 1 used , if it's first 1 second pointless. reason ie=8 1 there in first place if there issues in ie9 , 10. it's not bad have ie=8 1 in there. if site works , there no speed issues in ie more trouble it's worth have them solve problems caused them use ie8 compatibility mode.

java - Object id's in jstack -

i ran deadlock in system, , here excerpts 2 jstacks taken few minutes apart jstack 1 found 1 java-level deadlock: ============================= "com.mchange.v2.async.threadpoolasynchronousrunner$poolthread-#2": waiting lock monitor 0x00007f1ad075d2e8 (object 0x00007f1aed690ff8, com.mysql.jdbc.jdbc4resultset), held "com.mchange.v2.async.threadpoolasynchronousrunner$poolthread-#1" "com.mchange.v2.async.threadpoolasynchronousrunner$poolthread-#1": waiting lock monitor 0x00007f1ad075d390 (object 0x00007f1aed4ca6c8, com.mysql.jdbc.jdbc4connection), held "com.mchange.v2.async.threadpoolasynchronousrunner$poolthread-#2" jstack 2 found 1 java-level deadlock: ============================= "com.mchange.v2.async.threadpoolasynchronousrunner$poolthread-#2": waiting lock monitor 0x00007f1ad075d2e8 (object 0x00007f1aec62c8a8, com.mysql.jdbc.jdbc4resultset), held "com.mchange.v2.async.threadpoolasynchronousrunner$poolthrea

Scheduling C# app throughts Webclient exception -

i have developed c# application download zip file site, when manually run app, job , exits, when schedule run automatically using task scheduler in windows, throws web client exception error. please me regarding this the part of code downloading file is webclient wc = new webclient(); wc.downloadfile(<site>, "feed.zip"); system.diagnostics.processstartinfo pinfo = new system.diagnostics.processstartinfo("extract.bat"); system.diagnostics.process process = new process(); pinfo.createnowindow = true; pinfo.workingdirectory = directory.getcurrentdirectory(); process.startinfo = pinfo; process.start(); process.waitforexit(); the batch file extracts zip file. i see these possible problems: if run application directory.getcurrentdirectory() result in different path. directory.getcurrentdirectory() set bin -folder, in production environment, can point every, depending how process executed (for example: if create shortcut on de

Android store bitmap in internal directory -

i'm trying save file in internal memory android application can't manage correctly! here's method store bitmap: private void storebitmapinmemory(string id) throws ioexception { url newurl = new url(pictureurl); bitmap bm = bitmapfactory.decodestream(newurl.openconnection().getinputstream()); // openfileoutput() method creates file on phone/internal storage in context of application final fileoutputstream fos = context.openfileoutput(prefix + id +".jpeg", context.mode_private); // use compress method on bitmap object write image outputstream bm.compress(compressformat.jpeg, 100, fos); } everything looks fine when execute method, in nothing save... when try read file memory method: private bitmap getstoredbitmapfrommemory(int idavatar) { file cachedir = context.getcachedir(); file f = new file(cachedir, prefix + integer.tostring(idavatar) + ".jpeg"); fileinputstream fis = null; try {

data binding - Find a WPF Combobox item using SelectedValue from Binded Combobox -

can me find combobox item using value property. combobox binded dataset. here code. xaml code combobox grid.column="0" grid.row="3" height="23" horizontalalignment="left" margin="12,23,0,0" name="cbxdesignation" verticalalignment="top" width="120" itemssource="{binding}" selectedvaluepath="desig_code" selecteditem="desig_name" c# code behind. //populate designation <i> strsql = "select desig_code, desig_name desig_master"; dscommon = cdtier.returndataset(strsql); cbxdesignation.datacontext = dscommon.tables[0].defaultview; cbxdesignation.displaymemberpath = dscommon.tables[0].columns["desig_name"].tostring(); cbxdesignation.selectedvaluepath = dscommon.tables[0].columns["desig_code"].tostring(); if (dscommon.tables[0].rows.count > 0) cbxdesignation

c++ - Errors when compiling with include files (Own classes) -

information:microsoft visual studio 2012 ultimate, windows 8 professional, c++. have problem... qiclassstringoperations.hpp #include "q.hpp" class qiclassstringoperations { public: virtual void fromstring(const qstring& str) = 0; virtual qstring tostring() = 0; }; q.hpp #include "qstring.hpp" qstring.hpp template <typename type> class cstring { //... }; typedef cstring<char> qstring; in compiling have error: c:\...\qiclassstringoperations.hpp(13): error c4430: missing type specifier - int assumed. note: c++ not support default-int problem line: virtual void fromstring(const qstring& str) = 0; sorry bad english :). can me? looks qstring in not reconized type? declare qstring?

android - findViewById inside a Static Method -

i have static method: public static void displaylevelup(int level, context context) { layoutinflater inflater = (layoutinflater) context .getsystemservice(context.layout_inflater_service); view layout = inflater.inflate(r.layout.custom_level_coast, (viewgroup) findviewbyid(r.id.toast_layout_root)); // row textview text = (textview) layout.findviewbyid(r.id.toasttext); text.settext("this custom toast"); toast toast = new toast(context); toast.setgravity(gravity.center_vertical, 0, 0); toast.setduration(toast.length_long); toast.setview(layout); toast.show(); toast.maketext(context, string.valueof(level), toast.length_short) .show(); } however, can't figure out how first findviewbyid play nice says non-static method. understand why says that, there must workaround? passed context method couldn't work them out together. one thing can make view class wide variable , use

algorithm - Finding all pairs of sequences that differ at exactly one position -

i need data structure representing set of sequences (all of same, known, length) following non-standard operation: find 2 sequences in set differ @ 1 index. (or establish no such pair exists.) if n length of sequences , m number of sequences, there obvious o(n*m*m) algorithm. wonder if there standard way of solving more efficiently. i'm willing apply pre-processing if needed. bonus points if instead of returning pair, algorithm returns all sequences differ @ same point. alternatively , interested in solution can check efficiently whether particular sequence differs @ 1 index sequence in set. if helps, can assume in set, no 2 sequences have property. edit: can assume n reasonably small. this, mean improvements such o(log(n)*m*m) not useful use case. for each sequence , each position in sequence, calculate hash of sequence without position , add hash table. if there entry in table, have found potential pair differs in 1 position. using rolling hashe

jni - Eclipse Folder is transparent/grayed out. What does it mean? -

Image
my jni folder in eclipse looks this: it grayed out , has diagonal line across it. mean? can still edit native c++ code in folder , see changes test application. it means directory being filtered source locations. seems can use exclude files not source source folder, although i've never used it. i got rid of irritation in eclipse indigo cdt by: (project) properties ->c/c++ general ->paths , symbols ->source location tab ->edit filter... ->remove

Save variable value in python -

is there way save value of variable (say integer) in python? problem involves calling (entering , exiting) multiple times same python script (python file, not python function) in end creates txt file. i'd name txt files depending on number of times python code called: txt1.txt,..., txt100.txt example. edit: question not related save parameter in fortran. mistake. note: i'm assuming mean by: calling (entering , exiting) multiple times same python code is want call whole python script multiple times, in case need serialize counter in way external python interpreter, make available next time. if you're asking calling same function or method several times within 1 python session, can variety of ways , i'd point mgilson's answer . there plenty of ways serialize things, implementation doesn't have language. want store in database? write value file? or enough retrieve appropriate value context? instance, code new file each time called, based

angularjs - How to run two separate Angular js apps in the same page -

new angular. feel i'm missing obvious: shouldn't able run separate angularjs apps (modules) in same html page? this: <section ng-app="helloworldapp" ng-controller="helloworldcontroller"> hello {{name}}! </section> <br /> <section ng-app="mynameisapp" ng-controller="mynameiscontroller"> name {{firstname}} {{lastname}}! </section> javascript: var helloworldapp = angular.module('helloworldapp', []); helloworldapp.controller('helloworldcontroller', function($scope) { $scope.name = 'world'; }); var mynameisapp = angular.module('mynameisapp', []); mynameisapp.controller('mynameiscontroller', function($scope) { $scope.firstname = 'john'; $scope.lastname = 'smith'; }); this runs first module, while second doesn't appear anything. want can build reusable, encapsulated directives multiple pages don't have name modules

How can I assign a multiple-field-function result on PostgreSQL updates -

i'm looking optimized method in postgresql that: update table1 set (a,b)=(somecomplexfunction(table1.something),2*somecomplexfunction(table1.something)) ... this calculates somecomplexfunction(table1.something) twice, i'd that: update table1 set (a,b)=somecomplexvectorfunction(table1.something) ... but update syntax not support multiple field functions. ideas? update table1 set = somecomplexfunction(table1.something), b = * 2 ...

date - How to find a lifespan of a name in MySQL? -

i have sql table containing series of ids , dates that id registered in system. 1 id can registered several time. table below : id date 3 16/6/2009 4 2/4/2010 7 4/9/2012 3 12/6/2009 7 2/8/20011 3 16/12/2009 etc.. from table like extract ids lifespan (i want subtract firstseen date , lastseen date).ids can have same date , id can registered in different days. do knows query should use required result below? id date(week) 3 2/4/2009-16/6/2009 4 2/4/2010 7 2/8/20011-4/9/2012 select x.id , x.start ( select id , min(date) start my_table group id ) x left join ( select id , max(date) end my_table group id ) y on y.id = x.id , y.end > x.start;

c++ - calculate length of a string without using standard library funcions(like strlen) or indexing operator [] -

i have started learn c++. want clear no homework question, stuck on. i going through assignment questions on mit website, , have pasted question here; write function returns length of string (char *), excluding final null character. should not use standard-library functions. may use arithmetic , dereference operators,but nottheindexing operator([]). i don't know how without array. any appreciated!! this did: #include<iostream> #include<conio.h> #include<string> using namespace std; int stringlength (char* numptr); int main() { char *mystring; cout<<"enter string \n"; cin>>mystring; cout<<"length "<<stringlength(mystring); getch(); } int stringlength (char* numptr) { int count=0; for(;*numptr<'\0';*numptr++) { count++; } return(count); } had done before asked u problem. got me answer of zero. if in function change *numptr

wordpress - Redirect subdirectory of old domain to root folder of new domain via htaccess -

i have gone through several domain iterations on wordpress blog , want old links redirected new domain. blog in olddomain.com/blog/ now blog @ root level of newdomain.com the old domain set domain alias of new domain, not forwarded. if visits site olddomain.com/blog/ i need redirect newdomain.com/ thanks help. just create .htaccess file , put in folder want redirect e.g put in /blog folder. add following lines .htaccess file. rewriteengine on rewritecond %{server_port} 80 rewritecond %{request_uri} blog rewriterule ^(.*)$ http://www.newside.com/newblog/ $1 [r,l]

cocoa - NSTableView Delete Row by clearing text -

i want simple table 1 string column adds new line using return key. want delete row if user clears text on particular row too. i've managed add new line return key method: -(bool)control:(nscontrol*)control textview:(nstextview*)textview docommandbyselector:(sel)commandselector{ if (commandselector == @selector(insertnewline:)) { [self returnkey]; return yes; } else if(commandselector == @selector(moveup:)){ [self tablemoveup]; return yes; } else if(commandselector == @selector(movedown:)){ [self tablemovedown]; return yes; } else{ nslog(@"%@", nsstringfromselector(commandselector)); } return no; } the problem deleting row when user clears text on row , hits return key. method being called before actual changes on table saved data source. i've tried getting datacell on column this: nstextfieldcell *cell = [self.tableview.tablecolumns[0] datacell]; nslog(@"%@",cell.stringvalue); but stringvalue not accurate. ideas

Google Cloud Endpoints linking iOS client issues -

this problem arises fact don't understand static libraries in ios , docs google seem little sparse. i trying use google cloud endpoints mobile backend. i generate .m , .h files client library. created new project(ownitapi), dragged libgtltouchstaticlib.a static library gtl.proj new project. add generated files .m , .h files project. add .m files compile sources , header files copy files. in build settings add "-objc -all_load" other linker flags item. update: forgot mention copied headers gtl.proj ownitapi project. these include files gtlbase64.h, gtlbatchquery.h, gtlbatchresult,h, etc. think had because build failing without them. without headers, get: error "'gtlobject.h'file not found." on import statement. then take static library generated project , add main project target iphone app. test if api working, added app delegate #import "ownitapi/gtlserviceownit.h" #import "ownitapi/gtlqueryownit.h" #import "owni

c++ - Error: object of abstract class "Sphere" not allowed. and Error: no operator "=" matches these operands -

i've been trying resolve error last day or , can't seem work through. it's kind of error fix easy :s tried search similar questions fixes don't apply. main.c int main(int argc, char *argv[]){ int width, height; std::vector<obj*> world; world.push_back(new sphere(vec(0, 0, -22), 2, vec(0.2, 0.2, 0.2), true)); (...) return 0; } the error found when try create sphere. relevant classes obj.h class obj { public: vec color; bool culling; virtual bool intersect(const vec &ray_orig, vec &ray_dir, float *t0 = null, float *t1 = null) = 0; }; sphere.h class sphere: public obj { public: vec center; float radius, radius2; sphere(vec center, float radius, vec color, bool culling); bool intersect(const vec &ray_orig, vec &ray_dir, float *t0 = null, float *t1 = null); }; sphere.c sphere::sphere(vec center, float radius, vec color, bool culling){

sql - Run a DELETE statement certain table names stored in a table -

i have table stores names of tables - tablenames . i'd run delete statement on of tables (deleting rows tables represent, not removing them tablenames ). thought do delete (select tablename tablesnames ...) deletetables but keep getting incorrect syntax error. thought iterating through table in while loop , storing using variable, i'm hoping there's more simpler way. specifically, microsoft sql you cannot way because inner select set you're deleting from. basically you're creating table of table names , telling db delete it. iterating through them won't work without dynamic sql , exec do need automate process? what i've done in past this select 'delete ' + tablename tablenames [conditions] your output this: delete mytablename1 delete mytablename2 delete mytablename3 and copying results of query out of window , running them. if need automate in sql can concatenate output strings in result , send them parame

asp.net - Extending @Html.DropDownListFor -

i use following code extending @html.dropdownlistfor helper. controller gets list, , adding default value ienumerable in view model. don't want write of every time want dropdown default value. extending helper seems logical. public class sitegetsitesviewmodel { public string selectedsiteid { get; set; } public ienumerable<selectlistitem> sitelistitems { get; set; } } public actionresult getsites() { list<sitedto> sites = _siteservice.getsites(); const string defaulttext = "select site"; const string defaultvalue = "-1"; var sitegetsitesviewmodel = new sitegetsitesviewmodel { sitelistitems = enumerable.repeat(new selectlistitem { selected = true, text = defaulttext, value = defaultvalue }, 1).concat(sites.select(s => new selectlistitem { text = s.sitename,

c# - One generic type parameter, different generic for return type? -

so 2 different namespaces, have class record. i'd return appropriate 1 based off type being passed in. try , this, i've attempted this, "t2" incorrect. how can achieve this? public t2 getgeneratedtype<t1>(string name) t1 : class t2 : class { var type = typeof(t1); var generatedname = type.assemblyqualifiedname.replace(type.name, name); return (t2)activator.createinstance(type.gettype(generatedname)); } i haven't tested (won't compile, obviously), how make work if pass namespace1.someclass in, namespace1.record , in case pass in namespace2.someotherclass, namespace2.record (so long name == "record"). i attempted t , didn't give error messages, want make sure input , output types allowed different types. edit: i may've not explained entirely. i'm creating data annotation forked record (technically, 3 people need able assigned record @ given time due 3 distinct processes being performed on them. they're reconc

java - How do I get a specific child entity from the parent agg in JPA where there could be many children -

i have 2 part question: i have root agg has children entities , there large number of them. looking efficient way specific one. right way load them in memory , through them. want them index out of db. there way through class directly without having load children entities? in trying around q1 made repository method it, apparently didn't name correctly spring automated generation. i'm using jpa/spring , have following repository: public interface foobarrepository extends crudrepository<foobar, long>{ someentitythatisachildentityoftherootaggfoobar finditembyfoobarandotheritem(foobar foobar, otheritem otheritem); } the problem doesn't work, spring throws exception stating can't property called foobar factorybean threw exception on object creation; nested exception org.springframework.data.mapping.propertyreferenceexception: no property order found type com.bla.foobar.foobar i've tried using 'this' , 'id' , hoping worked, neither

javascript - Nested JSON Objects Within JSON Object -

i'm trying build menu dynamically , i'm going output data json object of following form. "link 1": { "href":"#", "sub link 1": { "href":"#" }, "sub link 2": { "href":"#", "sub sub link 1": { "href":"#" }, "sub sub link 2": { "href":"#" } } } firs of all, i'd know if that's design link hierarchy. on other hand, when i'm iterating on array, i'm able name "link 1" not of properties underneath link hierarchy. the loop i'm using following one: for(var item in jsonmenu) { console.log(item) } it outputs: link 1, link 2, link 3 want able access other json objects inside object. i tried nesting loop numbers : 0, 1, 2, 3 suspect length of string. i tried using: item.hasownprope