Posts

Showing posts from March, 2011

Os Exec Sudo Command in Go -

in process of familiarizing myself go , goroutines have hit road block executing commands. format of these commands are: sudo find /folder -type f | while read i; sudo -s chmod 644 "$i"; done with code taken how execute system command in golang unknown arguments i'm trying execute command believe it's not executing due first argument being sudo, wrong. have 2 questions. when these commands fail run returned "exit status 1", there way more detailed error doing? question two, why getting "exit status 1" script? going on isn't supposed to? package main import ( "bufio" "fmt" "os" "os/exec" "strings" "sync" ) func execmd(cmd string, wg *sync.waitgroup) { parts := strings.fields(cmd) head := parts[0] // head @ point "sudo" parts = parts[1:len(parts)] out, err := exec.command(head,parts...).output() if err != nil {

c# - DataGridView, Get the value of the first column of the selected row -

i'm wondering efficient way value of first column in datagridview row. currently, i'm using code: list<string> selectedrows = new list<string>(); foreach (datagridviewrow r in dgv.selectedrows) { selectedrows.add(r.cells[0].value.tostring()); } int index = convert.toint32(selectedrows[0]); this works fine; however, there more efficient option this? "most efficient" subjective. don't know following code faster or shorter you've got, it's method prefer use. if you're trying list of values particular column, try this: var results = datagridview1.selectedrows .cast<datagridviewrow>() .select(x => convert.tostring(x.cells[0].value)); if allow 1 selected row @ time, , want convert particular cell, try this: var index = convert.toint32(datagridview1.currentrow.cells[0].value);

Oracle SQL, avoiding errror "table is mutating" (trigger) -

i need trigger check if updated worker can moved other team create table workers ( id_worker number(4,0), --fk id_team number(2,0) --fk ); my trigger looks like: create or replace trigger team_limit before insert or update of id_team on workers each row declare v_num number; begin select count(*) v_num worker id_team=:new.id_team; if v_num >= 5 raise_application_error(-20025,' error nr ... bleble'); end if; end; this generate error : "table %s.%s mutating, trigger/function may not see it" when row updated. how write statements not generate kind of error? you can use compound trigger, looks (not tested): create or replace trigger team_limit insert or update of id_team on workers compound trigger v_num number; type row_tabletype table of workers.id_team%type; affectedteams row_tabletype; before statement begin affectedteams := row_tabletype(); -- init table variable end before statement; -----------------

javascript - Communicate between content script and options page -

i have seen many questions , background page content script. summary my extension has options page, , content script. content script handles storage functionality ( chrome.storage manipulation). whenever, user changes setting in options page, want send message content script store new data. my code: options.js var data = "abcd"; // let data chrome.tabs.query({ active: true, currentwindow: true }, function (tabs) { chrome.tabs.sendmessage(tabs[0].id, "storedata:" + data, function(response){ console.log(response); // gives undefined :( }); }); content script js chrome.runtime.onmessage.addlistener(function(request, sender, sendresponse) { // not working }); my question: why isn't approach not working? is there other (better) approach procedure. 1) why isn't approach not working? you trying message yourself: options page on you're doing returned chrome.tabs.query({ active: true, currentwindow:

html - how to center the button inside a table cell -

i'm trying center button inside table : text-align: center however, seems doesn't work me. note: used display: table-cell combine vertical-align: middle center text of button. can see text of first button "aaaaaaa" in middle. can me center button without affecting text of button. thank in advance. here's example code: http://codepen.io/anon/pen/pacbx i do margin:auto; display:block; i guess @rhino answer works well. remember remove display:table-cell;

javascript - Mongoose .find with a req.params array? and res.json an array of each value and count? -

ideally user able enter multiple tags in search field, delinienated client-side (before .get call), sent on ajax each keypress. working on server-side (testing api postman), if .get serves variable tags array of [ 'tag1', 'tag2'], can req.params.tags array? if so, server - right now, getting response postman localhost:4200/api/v1/tag/tagname .. not /tag/tagname1+tagname2 or /tag/tagname1&tagname2 here's current api: router.route('/tag/:tags') // list of tags usergenerated tags (accessed @ http://localhost:4200/api/v1/tag/:tags) .get(function(req, res) { story.count( { tags: { $in: [ req.params.tags ] } }, function (err, count) { if (err) res.send(err); console.log('there is/are %d story/ies this/these tag(s)', count); if (count >= 1) { story.find( { tags: { $in: [ req.params.tags ] } }, 'tags', function(err, stories) {

jquery - Fill progress bar with php value -

i make progress bar link : http://www.metallicabyrequest.com/results.php?s=70 and have table 3 columns , progress bar should fill value third column : http://jsfiddle.net/metcastle/ensr2/ <table> <thead> <tr> <th>song name</th> <th>% ballots w/ song</th> <th># votes</th> </tr> </thead> <?php foreach($array $element) { ?> <tr> <td class="name"><?php echo $element['name']; ?></td> <td>progress bar 3 td value percent</td> <td><?php echo $element['votes']; ?></td> </tr> <?php } ?> </table> hope can understand try say, ! if have number of total votes ($totalvotes) work with, ,

java - Instantiating object only once upon multiple calls without using static -

all want instantiate object of list once upon multiple calls servlet. please without use of static keyword not allowed here. list<cart> list=new arraylist<cart>(); list.add(new cart(name, cost)); httpsession s=req.getsession(); s.setattribute("list",list); out.println("item added cart"); out.println("\n<a href=\'viewserv\'>view cart</a>"); out.println("\n<a href=\'item\'>view item</a>"); as storing session, need check weather there in session or not . httpsession s=req.getsession(); if(s.getattribute("list") !=null){ sessionlist =new arraylist<cart>();/create new }else { sessionlist = (list)s.getattribute("list"); sessionlist.add(.... }

How to get "picturebox.Handle.ToInt32" value in Windows to image control Value in ASP.net C# -

i have windows form code , want use in asp.net. in program,i use image control instead of pixture box dont access handle method , dont know, equivalent of picturebox.handle value in windows image control.properties value in asp.net c#. pic_film picturebox.initcam method in mycam class. should write instead of "pic_film.handle.toint32" ? mycam.initcam(pic_film.handle.toint32) i tested following code had error :unable cast object of type 'system.web.ui.webcontrols.image'to type 'system.iconvertible' mycam.initcam(convert.toint32(page.findcontrol("pic_film")));

php - WooComerce Annoying Description -

i'm using wordpress woocommerce. i have problem i'm trying figure out how remove short description or excerpt homepage/shop page. still want on when people go actual product can't figure out. site cheap vapor therapy dot com . don't want post domain since don't want domain crawled search engines please don't edit it. update - this remove product title - .product_item .product_details h5 { display:none; } now remove excerpt or summary on homepage? theme comes custom css add on css code can take care of this. you can override wocommerce files. please have @ this documentation see how overrides done in woocommerce. short decription

git - is there a way to get only required files in the working directory -

Image
i'm new git , trying use project has many (several hundreds) sources. problem have git extracting project's sources working directory when doing checkout. makes lot of mess have jump between files , can unintentionally change/corrupt files wasn't planning change. prefer extract sources i'm going modify , work them. so, there way tell git going work specific sources, , so, these sources extracted working directory? note, not partial checkout or this. i'm ok checkout whole branch. it's more organising working folder. thanks. if relevant sources in specific subfolder, can sparse checkout , in order checkout specific subfolder content (which declare in .git/info/sparse-checkout file, mention here ). if not, need move them folder (reorganization), or isolate them own repo (and add them main repo submodule ) the other alternative use ide support task-based context filtering. instance eclipse mylyn, mention in " eclipse - easy access used

go - Golang bitwise operations as well as general byte manipulation -

i have c# code performs bitwise operations on byte. trying same in golang having difficulties. example in c# byte a, c; byte[] data; int j; c = data[j]; c = (byte)(c + j); c ^= a; c ^= 0xff; c += 0x48; i have read golang cannot perform bitwise operations on byte type. therefore have modify code type uint8 perform these operations? if there clean , correct/standard way implement this? go can bitwise operations on byte type, alias of uint8 . changes had make code were: syntax of variable declarations convert j byte before adding c , since go lacks (by design) integer promotion conversions when doing arithmetic. removing semicolons. here go var a, c byte var data []byte var j int c = data[j] c = c + byte(j) c ^= c ^= 0xff c += 0x48 if you're planning bitwise-not in go, note operator ^ , not ~ used in other contemporary programming languages. same operator used xor, 2 not ambiguous, since compiler can tell which determining whether ^ used unary or b

apache spark - Efficient boolean reductions `any`, `all` for PySpark RDD? -

pyspark supports common reductions sum , min , count , ... support boolean reductions all , any ? i can fold on or_ , and_ seems inefficient. no underlying scala api doesn't have python 1 won't. don't think add either it's easy define in terms of filter . yes using fold inefficient because won't parallelelize. .filter(!condition).take(1).isempty mean .forall(condition) , .filter(condition).take(1).nonempty mean .exists(condition) (general suggestion: underlying scala api more flexible python api, suggest move - makes debugging easier have less layers dig through. scala means scalable language - it's better scalable applications , more robust dynamically typed languages)

detailsview - How to show a file in a Details view in asp.NET MVC4 web application? -

i working on asp.net mvc4 web application. have create view upload file (cv). succeeded upload file correctly need show (the cv) in details view , don't know how it. here's class : public class consultant { public int id { get; set; } public int cin { get; set; } public string nom { get; set; } public string prenom { get; set; } public string refcommercial { get; set; } [displayformat(dataformatstring = "{0:dd/mm/yyyy}", applyformatineditmode = true)] public string datenaissance { get; set; } public string fonction { get; set; } public string tel { get; set; } public string experience { get; set; } public string email { get; set; } public string cvurl { get; set; } the attribute cvurl contains file's name. want show file in details view of consultant. help? thanks

C++ mid-function hook: get register values and jump back [x86 assembly on windows] -

Image
there int value in register ebp , string in ebx . need values these registers in own function, operations on them , jump code below. i jmp @ 0x46aa17 function called jmphook . void jmphook() { char *mystring; _asm mov mystring, ebx printf("value: %s", mystring); _asm { jmp [0x46aa87] } } as can see, trying move string @ ebx mystring , @ end jump 0x46aa87 located lines below jmp jmphook . printf being called , mystring being output seems untidy in ollydbg. unable ebp it's being overwritten @ beginning of jmphook (saw in ollydbg). jmp @ end of jmphook not work: so question how jump own function, save 2 registers there in variables , after operations jump original code. thank you! you can value of last ebp stack. it first value pushed on stack when call function. if not mistaken @ [ebp]. as jump, can make instead of jumping hook, call it? after function returns code continue ne

ios - Ti.Barcode Rotation issue -

Image
i'm having issue ti.barcode module when device rotated barcode scanning screen rotates also, though device orientation set ti.ui.portrait in tiapp.xml file any appreciated. module: ti.barcode v1.8.3 titanium sdk: 3.2.2.ga image below:

c++ - Use QT on Visual Studio 2013 -

i have project(c++/dirent.h/opencv/tesseract) on visual studio 2013 (professional update 2) , want uses gui on project, , have questions: i can create gui on qt creator (drag , drop) , bind vs2013 project? qt visual studio add-in have drag , drop? is there other way create interfaces visual studio. i'm not sure mean "bind", can create .ui file in qt designer can incorporated c++ project in visual studio. there multiple ways of doing - can load .ui file dynamically code using quiloader , or can convert c++ code statically using uic tool , use generated code in project. the qt add-on visual studio automates of described above. can have .ui files in vs project , when double click them, load qt designer can edit gui using drag/drop tools. when build project, automatically run uic , moc tools project built correctly. yes, indicated marco a.'s comment, can use mfc create native c++ gui windows based. framework out of date , not recommended new projec

swift - How do you test functions and closures for equality? -

the book says "functions , closures reference types". so, how find out if references equal? == , === don't work. func a() { } let å = let b = å === å // not find overload === accepts supplied arguments here how catterwauls dealing this: multiclosures & equatable closures tests chris lattner wrote on developer forums: this feature intentionally not want support. there variety of things cause pointer equality of functions (in swift type system sense, includes several kinds of closures) fail or change depending on optimization. if "===" defined on functions, compiler not allowed merge identical method bodies, share thunks, , perform capture optimizations in closures. further, equality of sort extremely surprising in generics contexts, can reabstraction thunks adjust actual signature of function 1 function type expects. https://devforums.apple.com/message/1035180#1035180 this means should not try compare clos

pycharm - Increase Accuracy of float division (python) -

i'm writing bit of code in pycharm, , want division more accurate (40-50 numbers instead of 15). how can accomplish this? thanks. check out decimal module: >>> decimal import * >>> getcontext().prec = 50 >>> decimal(1)/decimal(7) decimal('0.14285714285714285714285714285714285714285714285714') if you're interested in more sophisticated operations decimal provides, can @ libraries bigfloat , or mpmath (which use, , lot.)

Problems adding and retrieving text with newlines in SQLite Android -

so can add data data base fine when try , add test sentence testing sentence two to data base retrieve i'm getting test sentence testing sentence two i'm adding test data string enter put in , there no way in code me ad \n since i'm pulling data textview string , saving database. well can try add \n. read each character of string , find location of return character. in new string copy contents before character, copy '\n' , copy rest of content of string. here's code: public void onclick(view arg0) { string s=ed.gettext().tostring(); int index=0; for(int i=0;i<s.length();i++){ if(s.charat(i)==10){ index=i; } } string temp=s.substring(0, index); temp=temp+'\n'; temp=temp+s.substring(index+1, s.length()); tv.settext(temp); }

java - Create an useful and scalable class for SQLite Android -

i developing new android application , want create new class manage sqlite, want know best practice this. so, have 3 or more resources in project: rss , fb , tweet , in future more resources.. every resources have 5 method getitems() , getfeed() , insert() , delete() , etc.. my actual class db manager have singleton , know not practice. don't want create god class method accessing database. :( how can setup new class? can have piece of pseudocode learning it? thanks! you may consider ormlite android . provides needs powerful daos classes: insert, update, delete. ormlite's features: setup classes adding java annotations. powerful abstract database access object (dao) classes. flexible querybuilder construct simple , complex queries. supports mysql, postgres, microsoft sql server, h2, derby, hsqldb, , sqlite , can extended additional databases relatively easily. provisional support db2, oracle, odbc, , netezza. contact author if database type not

php - cakephp session is not deleting without clearing cache -

upon logout, cakpphp session not being deleted.in logout function have logged out user facebook . after calling logout function logs out user facebook not website. log out site have click on logout button , clear cache (ctrk+r) logout working. can tell me wrong. function logout() { $this->session->delete("session_user"); $this->session->delete('logout'); $this->redirect(base_url); } try doing: function logout() { $this->session->destroy(); $this->redirect($this->auth->logout()); } and add (if not added) in beforefilter() method:: $this->auth->allow('logout');

c++ - Class of dynamic array -

i've been working on c++ exercise , unable figure out how correctly, let me explain it: i made class based on 1st question of exercise class cylinder { private: float height; float radius; char * label; public: cylinder(float, float, char *); cylinder(); cylinder(const cylinder &); ~cylinder(); }; the 2nd question was: create new class "form3d" contain cylinders (dynamic array of cylinder) how make default constructor & constructor parameters? this did: class forme3d { cylinder * tab; int tabsize; public: forme3d(); forme3d(cylinder * , int); ~forme3d(); }; forme3d::forme3d(cylindre * c, int t) { cylindre * tab = new cylindre[t]; (int = 0; < t; ++i) { tab[i] = c[i]; } } this cause error "operator=" not defined line "tab[i] = c[i];"

How to measure latency in a wifi network java android -

i developing mobile app, need parameters implement algorithm, , not know how measure latency in wifi network. people says using ping, not know how implement this. this first question, learning. thank you. please have @ this answer might after you might want try following code sample measure time string host = "172.16.0.2"; int timeout = 3000; long beforetime = system.currenttimemillis(); reachable = inetaddress.getbyname(host).isreachable(timeout); long aftertime = system.currenttimemillis(); long timedifference = aftertime - beforetime;

android - Long press on a view using AndroidViewClient -

how can simulate long press on view (for example button) using androidviewclient ? touch method of viewclient performs simple press on input (even if set type argument adbclient.down ) edit: touch method in adbclient.py has type argument, not used in method body. in monkeyrunner , when type down , performs longpress. def touch(self, x, y, eventtype=down_and_up): self.shell('input tap %d %d' % (x, y)) i find answer question right now. can use drag method simulate long pressing on views. sample code follow: buttontext = 'clme' button = vc.findviewwithtext(buttontext ) (x,y) = button.getxy() button.device.drag((x,y), (x,y), 2000, 1)

android - can't move minute hand on ontouch method of surfaceview -

i have tried many ways this.....and i'm able move minute hand on ontouch of view problem can move when not touch it. public boolean ontouchevent(motionevent e) { float x = e.getx(); float y = e.gety(); switch (e.getaction()) { case motionevent.action_move: //find approximate angle between them. log.i("test", "value x is"+x); log.i("test", "value y is"+y); /*float dx = x-cx; float dy = y-cy;*/ getrotationangle(x,y); float dx = x-cx; float dy = y-cy; double a=math.atan2(dy,dx); log.i("test",":: "+math.todegrees(a)); this.degree = math.todegrees(a); this.invalidate(); } return true; } protected void ondraw(canvas canvas) { super .ondraw(canvas); boolean changed = true; int availablewidth = getright() - getleft(); int availableheight = getbottom() - gettop(); int x = availablewidth / 2; int y = availableheight / 2; cx = x; cy = y; fina

ruby on rails - Password Confirmation with has_secure_password -

i'm using line has_secure_password in user model. looks this: class user < activerecord::base before_create :create_remember_token validates :name, presence: true, length: {minimum: 3, maximum: 22}, uniqueness: true #validates :password, presence: true, length: {minimum: 6, maximum: 22} valid_email_regex = /\a[\w+\-.]+@[a-z\d\-]+\.[a-z]+\z/i validates :email, :allow_blank => true, format: { with: valid_email_regex } has_secure_password validates :password, length: {minimum: 6} in user s new view, have this: <h1>sign up</h1> <div class="row"> <div class="col-md-6 col-md-offset-3"> <%= form_for(@user) |f| %> <%= f.label :name, 'username' %> <%= f.text_field :name %> <%= f.label :email, 'email (optional)' %> <%= f.text_field :email %> <%= f.label :password %> <%= f.password_fie

python - Calculate during merge using pandas -

is there way perform calculations between columns while merging pandas dataframes? example, have following 2 dfs, , want multiply data corresponding ids: df1 = dataframe({'id':['a','b','c'], 'data':[8,7,12]}) df2 = dataframe({'id':['b','a','c'], 'data':[3,2,1]}) the desired output be: id data 0 16 1 b 21 2 c 12 i know possible merging, , multiplying so: merged = pd.merge(df1, df2, how='left', on=['id']) merged['data'] = merged.data_x * merged.data_y merged[['id', 'data']] however, large numbers of columns, quite cumbersome, since merged column names have _x , _y suffixes. pandas equivalent of following sql: select a.id, a.data * b.data 'data' table left join table b on a.id = b.id in case, set index , multiply: >>> df1 = pd.dataframe({'id':['a','b','c'], 'data':[8,

override - Overriding default value of instance var -

given class obj , class obj: nsobject { var x = "x" } and subclass, obj1 , how change default value of var x ? simply setting new value make sense, seems error out... class obj1: obj { var x = "y" } ❗️ cannot override stored property 'x' define init() method as: init () { super.init() x = "y" } you'll want other initializers in obj1 invoke self.init() . apple documentation has long discussion on designated initializers , inheritance vis-a-vis initializers.

monitor - Monitoring a website that contains a defined string with Zabbix -

how can monitor website zabbix 2.2 contains defined string in title? example: https://stackoverflow.com/ contains 'stack overflow' in . now want email, if there string instead of 'stack overflow' in title. how can this? is required string in steps? thanks. there 2 main options: use web monitoring , put string "required string" field; use web.page.regexp[] item , put string <regexp> parameter. in both cases, can make trigger alert if string not there.

TM1 9.5.2 Java API function for Integrated Login -

i trying connect tm1 9.5.2 read data cubes in normal login mode , happens fine. however, when tm1 server configured integrated login, java code not connect api. in api documentation c, there separate function tm1systemserverconnectintegratedlogin connect tm1 in integrated security mode. however, java, not find such dedicated function. appreciated. based on looking @ .jar tm1 9.5.2 java api there methods connection via classic , cam methods. corresponding method tm1systemserverconnectintegratedlogin missing. might check available in 10.2 upwards java integration has been enhanced.

c# - wcf service with a custom username a password authentication -

i trying access wcf service custom username , password validator.. in case have win console app running in .net 2.0 , wcf service running in .net 4.0 after adding web reference service, can call method , print result in console. now want add security.. kind new authentication process of web/wcf services.. in first project made , using soap headers, in case both running in .net 4.0. i did find there ways of doing it, beginner want understand basic way, , in case sending username , passoword , seems easy way it.. in order need create new class extends usernamepasswordvalidator , override method validate public override void validate(string username, string password) { if (username != "teste") throw new securitytokenexception("unknown username or password"); } the problem having configure web config file of webservie use custom validator.. this web.config <?xml version="1.0"?> <confi

assembly - How to detect architecture in NASM at compile time to have one source code for both x64 and x86? -

i looking preprocessor functionality in nasm allow having 1 source code both x86 , x64 architectures. i mean in vein of ifdef some_constant. c preprocessor uses if wants detect if it's compiled on windows or linux. edit i know nasm flags. use them. want have same source code , expect preprocessor handle correctly based on flags. i'd use ifdef ... else stack operations , one, having core code same both architectures. nasm cannot detect architecture, can use output format (command line option: -felf,-felf32,-felf64,-fwin32 etc.) needs. read friendly manual .

python - Are sets internally sorted, or is the __str__ method displaying a sorted list? -

i have set , add items (ints) it, , when print it, items apparently sorted: a = set() a.add(3) a.add(2) a.add(4) a.add(1) a.add(5) print # set([1, 2, 3, 4, 5]) i have tried various values, apparently needs ints. i run python 2.7.5 under macosx. reproduced using repl.it (see http://repl.it/tpv ) the question is: documented somewhere (haven't find far), normal, can relied on? extra question: when sort done? during print? internally stored sorted? (is possible given expected constant complexity of insertion?) this coincidence. data neither sorted nor __str__ sort. the hash values integers equal value (except -1 , long integers outside sys.maxint range), increases chance integers slotted in order, that's not given. set uses hash table track items contained, , ordering depends on hash value, and insertion , deletion history. the how , why of interaction between integers , sets implementation details, , can vary version version. python 3.3 introduc

javascript - How to get the name of this file using formidable (NodeJs) -

i have form using nodejs + express jade file: form(method="post", action="/upload", enctype="multipart/form-data") input(type="file" name="image") button(type="submit") upload index.js not code necessary var formidable = require('formidable'), http = require('http'), util = require('util'); var fs = require('fs'); myproject.post('/upload',function(req, res){ var form = new formidable.incomingform(); form.parse(req, function(err, fields, files) { console.log(files); }); when use console.log(files) result this { iproducto: { domain: null, _events: {}, _maxlisteners: 10, size: 1262294, path: 'c:\\docume~1\\admini~1\\config~1\\temp\\556696bb1c0c6a54362b746c4445 45ca', name: 'dibujo.bmp', type: 'image/bmp', hash: null, lastmodifieddate: mon jun 09 2014 21:25:42 gmt-0100 (hora estándar de cabo verde), _writestream: { _writables

MIPS: Calculating Displacement -

working through problems , confused calculating displacement. some examples are: top: addi $s2, $s2, -1 addi $s1, $s1, 1 bne $s2, $0, top assume top has value of 0x1000 0008. top: bne $s1, $s2, end addi $s1, $s1, 1 end: j top assume top has value of 0x1000 0008. what displacement in bne instructions? can explain how calculate these? thanks. the absolute address doesn't matter. matters distance between jump , target. to calculate offset, calculate distance between jump target , instruction following bne . in first example distance 12 bytes because there 3 instructions between target label , instruction following bne , , each instruction 4 bytes in size. , since backwards jump has negative offset, i.e. -12. since instructions need word aligned (4 bytes), offset stored in instruction word shifted 2 bits right (since 2 least significant bits 00 anyway). arithmetic shift, meaning sign bit preserved. need take -12 , arithm

matlab - repmat function does not work properly -

let consider following situation,for instance have given matrix , want make 0 centered matrix in columns,so a=rand(4,3) = 0.6948 0.4387 0.1869 0.3171 0.3816 0.4898 0.9502 0.7655 0.4456 0.0344 0.7952 0.6463 now 2 method works properly a-repmat(mean(a),size(a,1),1) ans = 0.1957 -0.1565 -0.2553 -0.1820 -0.2137 0.0476 0.4511 0.1703 0.0035 -0.4647 0.1999 0.2042 and also bsxfun(@minus,a,mean(a)) ans = 0.1957 -0.1565 -0.2553 -0.1820 -0.2137 0.0476 0.4511 0.1703 0.0035 -0.4647 0.1999 0.2042 but somehow following method not work b=mean(a) b = 0.4991 0.5953 0.4421 a-repmat(b,1,4) ans = 0 0 0 0 0 0 0 0 0 0 0 0 i have tried transpose but a-repmat(b,1,4)' error using - matrix dimensions must agree. also have tried following a-repmat(b,1,3)' error using - matrix dimensions must agr

jQuery bind, unbind is not working -

i have written below code, not working expected. in chrome, alert not working , ie. alert('1'); in firefox or ie working fine,but if comment out alert('1') not working, has perplexed me long time. appreciate help. code: $(function() { createdynamictable(); bindevent(); function bindevent() { alert('1'); $("td.editable").unbind(); $("td.editable").bind("click", function(e) { $(this).unbind(); }); } }); the jquery .bind/.unbind methods deprecated of release 3.0 the new jquery methods attaching/unattaching event handlers .on/.off

Password History check in openldap -

password history check in openldap not working when using sha-256 password hashing in openldap. so sending clear text password java application openldap , storing sha-256 hashed form on own. whenever changing password, openldap storing previous password in pwdhistory. there no problem in when changing password same password used taking without throwing error. struggling make work few weeks. please me. environment details: openldap 2.4.38 rhel 6 following details mentioned in slapd.conf include ../etc/openldap/schema/ppolicy.schema password-hash {sha256} overlay ppolicy ppolicy_default "cn=default,ou=pwdpolicies,dc=my-domain,dc=com" ppolicy_hash_cleartext password policy: dn: cn=default,ou=pwdpolicies,dc=my-domain,dc=com objectclass: pwdpolicy objectclass: person objectclass: top cn: default sn: default pwdattribute: userpassword pwdminage: 0 pwdinhistory: 5 pwdfailurecountinterval: 0 pwdlockout: true pwdlockoutduration: 0 pwdallowuserchange: true pwdexpirewarning

ios - Enumerating array of objects -

i have array of objects , objects in have same value(for example user's guid). i want find object same guide , remove of rather first. what best way it? you can use nsmutablearray's removeobject method. notice object should implement isequal method appropriately. [nsmutablearray removeobject] as per description: this method uses indexofobject: locate matches , removes them using removeobjectatindex:. thus, matches determined on basis of object’s response isequal: message . if array not contain anobject, method has no effect (although incur overhead of searching contents).

asp.net - Export Gridview connected to MYSQL data to excel -

i have simple form created in visual studio (vb) has data gridview connected table in mysql (hosted in remote server). i have below code export grid view excel takes long time export (around 15 minutes). the table in mysql small (1000 rows , 60 columns). is there better way export complete mysql table excel? please help code: dim xlapp microsoft.office.interop.excel.application dim xlworkbook microsoft.office.interop.excel.workbook dim xlworksheet microsoft.office.interop.excel.worksheet dim misvalue object = system.reflection.missing.value dim integer dim j integer xlapp = new microsoft.office.interop.excel.application xlworkbook = xlapp.workbooks.add(misvalue) xlworksheet = xlworkbook.sheets("sheet1") = 0 datagridview1.rows.count - 1 j = 0 datagridview1.columns.count - 1 k integer = 1 datagridview1.columns.count on error resume next

c# - Only display dates after current date from database in datagridview -

so have database, , querying list of events , there dates. want change query return events have not occured. my query @ moment is: cmd.commandtext = "select eventid, eventdate, location events"; and inputs datagridview. i tried: cmd.commandtext = "select eventid, eventdate, location events eventdate > curdate()"; but didnt return dates. here have approach both mssql , mysql since did not specify dbms using. mssql: you can use getdate() . should give current date , time. cmd.commandtext = "select eventid, eventdate, location events eventdate > dateadd(dd, datediff(dd, 0, getdate()), 0)"; mysql: you can use now() function, , truncate time part casting date. cmd.commandtext = "select eventid, eventdate, location events eventdate > cast(now() date))";

javascript - Placeholder as an option -

when create dropdown using selectize, once select option, way select placeholder clicking input field & hitting backspace not intuitive. can have placeholder option similar how in native select element ? similar problem referenced in github issue i've written selectize plugin problem, appends placeholder element on click clear selection. selectize.define('selectable_placeholder', function( options ) { var self = this; options = $.extend({ placeholder: self.settings.placeholder, html: function ( data ) { return ( '<div class="selectize-dropdown-content placeholder-container">' + '<div data-selectable class="option">' + data.placeholder + '</div>' + '</div>' ); } }, options ); // override setup method add "click" handler self.setup = (function() {

javascript - Angular JS - $q.all() tracking individual upload progress -

i'm using angular-file-upload module danialfarid ( https://github.com/danialfarid/angular-file-upload ) , works great. i've been able integrate in wrapper service rest calls , can upload several images $q.all() , keeping track of progress. however, can't correctly identify single images i'm uploading, because file identifier gets continuosly changed loop. uploadphotos: function (files) { var deferred = $q.defer() var queue = [] (var = 0; < files.length; i++) { var file = files[i]; var = $upload.upload({ url: locationuri +'/photos', file: file, fileformdataname: 'image' }).then( function (data) { console.log(data) }, function (err) { console.log(err) }, function(evt) { // progress events console.log('percent: ' + parseint(

java - Is this a good method to make ImageView square? -

parent layout has specified width value (50dp), , height set match_parent . in layout adding few imageview widgets using java, , because parent layout has specified width , can set width , height of each imageview match_parent , using java can make imageview square setting height width . this code: public class icon extends imageview { public appicon(final context context) { super(context); } public appicon(final context context, final attributeset attrs) { super(context, attrs); } public appicon(final context context, final attributeset attrs, final int defstyle) { super(context, attrs, defstyle); } @override protected void onmeasure(final int width, final int height) { setmeasureddimension(width, width); } } is method make each imageview square? think it's simple, missing. p.s.: method works, need sure, fine. your code working 1 can enhanced. see code: updated c

java - String manipulation for VML Path -

hi trying parse vml path value using java string manipulation. want retreive commands in path moveto , lineto , curveto , rlineto (other commands) , corresponding x , y coordinates/parameters. here example data parse, each command has own x,y coordinates. 1. m1,1 l1,200,200,200,200,1 xe 2. m, l1,200,200,200,200,1 xe can suggest algorithm or code on retreiving commands , parameters each command? example in number 1. command = moveto 'm' command parameters = (x=1,y=1). ref: http://www.w3.org/tr/note-vml#_toc416858391 this weird tried using stringtokenizer stringtokenizer tokenizer = new stringtokenizer(path); a friend suggested using stringtokenizer , did near goal, gave me following data. maybe can utilize stringtokenizer suit needs. m1,1 l1,200,200,200,200,1 xe for #1, here ideal output. (pseudocode) string command_type = "m" list<string, string> parameters = add("1", "1") string command_type = "l

ios - how to change HTML value in UITextView -

i have description option in database , convert json format. after fetching database i'm displaying uitextview . it's showing below values. <p>table : 1</p><p>table : 2</p><div><p>table : 3</p><div><p>table : 4</p><div><p>table : 5</p><div><p>table : 6</p><p>table : 7</p><p>table : 8</p><div>&nbsp;</div></div></div></div></div> html decode: nsstring *decodestring = [self htmlentitydecode:productdescription]; txtt.text = decodestring; remove html tag html string -(nsstring *) stringbystrippinghtml { nsrange r; nsstring *s = [[self copy] autorelease]; while ((r = [s rangeofstring:@"<[^>]+>" options:nsregularexpressionsearch]).location != nsnotfound) s = [s stringbyreplacingcharactersinrange:r withstring:@""]; return s; }

How can I update a calculated column using Sharepoint Designer 2013? -

i'm new sharepoint designer , i'm having trouble task done. i've created list , each item of list should have specific code. here's example: **2014dem/000023**. i got format done creating column named "code" based on columns value , inserting following formula: *=concatenate(year(today());"dem/";format([id];"000000"))* this formula works fine, problem when new item being created, id zero, when user saves new item, code column value value returns **2014dem/000000**. if try edit code column formula, don't change anything, , click ok button, code values updated value supposed be. does know how can solve problem? update column values using sharepoint designer workflow? obs.: i'm using sharepoint designer 2013.

c - Explain this code in K&R 2-1 -

i'm trying determine range of various floating-point types. when read code: #include <stdio.h> main() { float fl, fltest, last; double dbl, dbltest, dblast; fl = 0.0; fltest = 0.0; while (fl == 0.0) { last = fltest; fltest = fltest + 1111e28; fl = (fl + fltest) - fltest; } printf("maximum range of float variable: %e\n", last); dbl = 0.0; dbltest = 0.0; while (dbl == 0.0) { dblast = dbltest; dbltest = dbltest + 1111e297; dbl = (dbl + dbltest) - dbltest; } printf("maximum range of double variable: %e\n", dblast); return 0; } i don't understand why author added 1111e28 @ fltest variable ? the loop terminates when fltest reaches +inf , @ point fl = (fl + fltest) - fltest becomes nan , unequal 0.0 . last contains value when added 1111e28 produces +inf , close upper limit of float . 1111e28 chosen reach +inf reasonably quickly;

java - Move and rename file in android -

i trying copy file folder in android, far, got no success. manage selected image , when taking photo, not files. i've read , tried several solutions passed community (searched on forum , internet), none of able solve problem when copying. first things first. added permissions manifest: <uses-permission android:name="android.permission.write_external_storage" /> <uses-permission android:name="android.permission.read_external_storage" /> after that, before copying file, print filepath , directory file path: 06-10 11:11:11.700: i/system.out(1442): /mimetype/storage/sdcard/misc/javascript erros submit , plan buttons in ie.doc 06-10 11:11:11.710: i/system.out(1442): /storage/sdcard/files/queue both exists: to copy file expected folder used fileutils: try { fileutils.copyfile(selectedfile, dir); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace();

Rails + Rspec: How to stub a record so that it's marked as invalid? -

i have purchase model method: def set_status_to_in_progress! self.update_attributes!(status: in_progress) end and failing rspec test: context "self invalid" "raises error" purchase = purchase.new purchase.stub(:valid?).and_return(:false) expect { purchase.set_status_to_in_progress! }.to raise_error end end which returns failures: 1) purchase#set_status_to_in_progress! self invalid raises error failure/error: expect { purchase.set_status_to_in_progress! }.to raise_error expected exception nothing raised # ./spec/models/purchase_spec.rb:149:in `block (4 levels) in <top (required)>' i thought stubbing valid? enough make activerecord update_attributes! method raise error? how make raise? try changing :false false purchase.stub(:valid?).and_return(false) or purchase.should_receive(:valid?).and_return(false) otherwise can stub instance of purchase purchase.any_instance.sh

arrays - C# Combobox show in suggest list if string includes -

private void form1_load(object sender, eventargs e) { string[] list = { "tomato", "banana", "apple" }; autocompletestringcollection mylist = new autocompletestringcollection(); mylist.addrange(list); combobox1.autocompletecustomsource = mylist; } when enter "ana" combobox want see banana in suggest list. i researched cannot find code doing this. thanks in advance. hello have post hope helps, it's wpf solution

Web scraping with scrapy -

from scrapy.spider import basespider scrapy.selector import selector scrapy.exceptions import closespider scrapy.http import request botg.items import botgitem url = "http://store.tcgplayer.com/magic/born-of-the-gods?pagenumber=%d" class myspider(basespider): name = "tcg" allowed_domains = ["tcgplayer.com"] start_urls = [url % 1] def __init__(self): self.page_number = 1 def parse(self, response): print self.page_number print "--------------------break-------------------------" sel = selector(response) titles = sel.xpath("//div[@class='magiccard']") if not titles: raise closespider('no more pages') title in titles: item = botgitem() item["cardname"] = title.xpath(".//li[@class='cardname']/a/text()").extract()[0] item["rarity"] = title.xpath(".//li[@href='/magic/born-of-the-gods']/text()").extract(

java - Why hibernate selects entities before persisting entities mapped by joined_subclass inheritance type? -

i have superclass person , 2 subclasses - parent , child. mapped joined_table inheritance type. parent , child have bidirectional one-to-many relationship. person.hbm.xml contains configuration: <hibernate-mapping> <class name="com.masterhibernate.simplehibernatedemo.person" table="person"> <cache usage="read-write" /> <id name="id" column="id"> <generator class="assigned" /> </id> <property name="name"> <column name="name" length="16" not-null="true" /> </property> <property name="surname"> <column name="surname" length="36"></column> </property> <property name="address"> <column name="address" length="22">

database - Loop/Iterate through a SQL query in Access (without VBA) -

i have rather unique problem sits between solution sets i've been able find. have database containing tables need iterative select queries updating input parameters. example, have equipment table contains pairing of technology sister tech, , mechanisms through communicate: table fields: techid1 techid1port techid2 techid2port example: radio communicates (through low/high band antenna) basestation (through antenna port) i have working sql code runs when users select techid1 combobox , combobox value filters statement. however, need add levels of interaction based on added combobox (values:1-n). end goal iterate query done here , without vba, solution needs replicated many access tables , seamlessly transferred oracle/sql server in medium-term. example of desired nth level results based on radio selection: list of techs directly interact radio (plus associated info), appended list of techs interact basestation , other 1st level results (no duplicates or tr