Posts

Showing posts from August, 2014

bit manipulation - Manipulating Bit-wise Operations -

there puzzle question of creating equivalent bit-wise & | , ~ operators. i've been doing brute force combinations of | , ~ using 6 (0110) , 5 (0101) trying 4 (0100), still cannot answer. the maximum number of operation can used 8. can please give me hints? what helps here de morgan's law , says: ~(a & b) == ~a | ~b thus can negate , get: a & b == ~(~a | ~b) //4 operations and looking @ truth table (and in fact, god bless simplicity of binary logic, there 4 possible combintations of inputs generate appropriate outputs for) can see both equivalent (last 2 columns): a | b | ~a | ~b | ~a or ~b | ~(~a or ~b) | , b --|---|----|----|----------|-------------|-------- 0 | 0 | 1 | 1 | 1 | 0 | 0 1 | 0 | 0 | 1 | 1 | 0 | 0 0 | 1 | 1 | 0 | 1 | 0 | 0 1 | 1 | 0 | 0 | 0 | 1 | 1

javascript - I made a simple chat room with sockets.io, how do I prevent XSS attacks? -

as title says made simple chat room sockets.io, problem have no xss protection , buddies keep putting infinite loops usernames, can imagine how trolly getting :p. app.js /** * module dependencies. */ var express = require('express') , routes = require('./routes') , user = require('./routes/user') , http = require('http') , path = require('path'); var app = express(); // environments app.set('port', process.env.port || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyparser()); app.use(express.methodoverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development if ('development' == app.get('env')) { app.use(express.errorhandler()); } app.get('/', routes.index); app.get('/users', user.list

change python to ruby, very basic -

i not familiar ruby, , want change python code ruby art project, here broken ruby script, know "split" function same, , not sure how 1 part of array in ruby. feel appreciated if can me out right now. new = line.split(" ") lala = [w w in new if len(new)>=4] newone = lala[1..6].join(" ") + "\n" + lala[6...].join(" ") the initial python code new = line.split(" ") lala = [w w in new if len(new)>=4] newone = (" ").join(lala[1:6]) +"\n" +(" ").join(lala[6:]) words = line.split(" ") s = words.select {|w| words.length >=4} result = s[1...6].join(" ") + "\n" + s[6..-1].join(" ")

javascript - jquery.extend(true, [], obj) not creating a deep copy -

jsfiddle here . if deep copying worked, output "curious george" , not "ender's game". how can make deep copy? answer this question indicates $.extend(true, [], obj) creates deep copy. yet example shows doesn't. function person(){} person.prototype.favorite_books = []; var george = new person(); george.favorite_books = ["curious george"]; var kate = new person(); kate.favorite_books = ["the da vinci code", "harry potter"]; var people = [kate, george]; var people_copy = $.extend(true, [], people); people_copy[0].favorite_books[0] = "ender's game"; $('#text').text(people[0].favorite_books[0]); solution i updated jsfiddle. turns out need deep copy each object in array individually if object custom object (that is, $.isplainobject returns false). and here real answer: at moment jquery can clone plain javascript objects, while you're using custom ones. , that's obvious, si

ruby on rails - Setting a child attribute from parent in FactoryGirl -

how set dependent attribute depends on in factorygirl? factorygirl.define factory :line_item quantity 1 price 30 # want price come product association: self.product.price cart order product end end i tried didn't work: factory :line_item |f| f.quantity 1 f.cart f.order f.product after_build |line_item| line_item.price = line_item.product.price end end try this: factorygirl.define factory :line_item quantity 1 price { product.price } cart order product end end

c# - NServiceBus message removed from queue w/o a trace -

Image
i created new nservicebus azure worker role. the configuration simply: nservicebus.configure.with(busassemblies) .log4net() .license(config.default.nservicebus_license) .defineendpointname(endpointname) .unitybuilder(servicebusdiconfiguration.container) .azureconfigurationsource() .azuresagapersister() .azuresubcriptionstorage() .azuredatabus() .jsonserializer() .azureservicebusmessagequeue() .unicastbus() .loadmessagehandlers() .createbus() .start() the client configuration identical above except addition call .donotautosubscribe() . client uses bus.send(message) input queue of listener. azure bus queue reported messages being sent input que

javascript - Getting location data from an image (Instagram/JS) -

i've been working on side project , have hit roadblock. can search through tags , display picture results fine, i'd put details below each picture, location information. i'm doing in javascript, , commented out lines believe need adjusted, comment marks removed not pictures show up. tips? json object printed call instagram returns data: object - data: array[20] - 0: object + caption: object + comments: object created_time: "1334402906" filter: "nashville" id: "169306311223447303_5913362" - images: object + low_resolution: object - standard_resolution: object height: 612 url: "http://distilleryimage7.instagram.com/f3f8d7b2862411e19dc71231380fe523_7.jpg" width: 612 + thumbnail: object + likes: object link: "http://instagr.am/p/jzfzfqti8h/" location: object tags: array[1] ty

python - Pandas Shaping Data for Covariance -

i need conduct simple covariance analysis in time series. raw data comes in shape this: week_end_date title_short sales 2012-02-25 00:00:00.000000 "bob" (ebk) 1 "bob" (ebk) 1 2012-03-31 00:00:00.000000 "bob" (ebk) 1 "bob" (ebk) 1 2012-03-03 00:00:00.000000 "sally" (ebk) 1 2012-03-10 00:00:00.000000 "sally" (ebk) 1 2012-03-17 00:00:00.000000 "sally" (ebk) 1 "sally" (ebk) 1 2012-04-07 00:00:00.000000 "sally" (ebk) 1 as can see, there duplicates. unless i'm missing something, need data become set of vectors each title, can use numpy.cov. question: how find duplicates in date , name , aggregate them sum? i've been trying use pandas groupby week_end_date , tittle_short comes out indexed in way don't

html - How do I deal with designing for screens of different resolutions, and/or my webpage becoming distorted when zooming in? -

i'm web-design novice, , haven't found way deal how pages morphs if were zoom in, or use different resolution screen. tips dealing this? here's example of page working guys can provide directed advice well. that page looked this when designed. how deal designing screens of different resolutions? look using css3 media queries : "a media query consists of media type , 0 or more expressions check conditions of particular media features. among media features can used in media queries ‘width’, ‘height’, , ‘color’. using media queries, presentations can tailored specific range of output devices without changing content itself." examples: @media screen , (min-device-width: 768px) , (max-device-width: 1024px){ /* media query targetting tablets */ } @media screen , (min-device-width: 560px) , (max-device-width: 1136px) , (-webkit-min-device-pixel-ratio: 2) { /* media query target iphone 5 */ } of course it's better p

javascript - Stringifyed onClick event does not work -

i have event parses string contains button name , url. than assign data button. , add on click event suppose open url in new window. on click event doe not work. window not show up. if url wrong open window , prompt mistake. but in case when click botton not react. wrong on click event here: onclick=\"mywindow = window.open('partarray[1]', '', 'width=300,height=300');\" . can't understand what. here code <script> ... var checktype = partarray[0].split("+"); outputs = outputs + " <input type='button' class='worddoctype' name='" + partarray[0] + "' value='" + partarray[0] + "' onclick=\"mywindow = window.open('partarray[1]', '', 'width=300,height=300');\" /> &nbsp;&nbsp;" document.getelementbyid("demo").innerhtml=outputs; </script> <body> ... <div id="demo&

fopen - I need to find a way to edit XML files when a user submits a form using PHP -

so have web page displays data of xml file. have form should ideally able change data. figured best way accomplish use fopen function in php , edit specific line of text. string won't long, 4 words max. how use fopen , series of functions open, read , write files find line of code , replace it? i think should following: match name of input tags in html nodes in xml (this suggestion have code more organized) when post data server, in php code, using simplexml can following giving following xml file <root> <config id="1"> <name>old name</name> <category>old category</category> </config> <config id="2"> <name>old name</name> <category>old category</category> </config> </root> //load xml file $xml = simplexml_load_file('path xml file'); //update values want update foreach($xml->root->config $confi

Code to end one batch file with another-can anyone assist? -

i have small batch program made run few batch files. have set run files. quick question: have prep file files ready next batch file. however, prep file runs in loop. made run in loop customize per-machine. want loop 10 seconds , close. want main batch file opens prep batch file, runs 10 seconds, closes it, , runs next batch file in sequence. there way this? see example below more. thanks! example: launcher folder/prep.bat @echo off start prep.bat //wait 10 seconds, close prep.bat start launch.bat in prep.bat add this @echo off title prep.bat and in controlling batch file add this start "" prep.bat ping -n 10 localhost >nul taskkill /f /im cmd.exe /fi "windowtitle eq prep.bat"

ruby on rails - Controller testing Show page with Rspec, it gives an error nil & and render empty page -

i'm new tdd on rails, , i'm trying test videos_controller book "everyday rails testing rails" simple show page gives me error 'nil' & render empty, follows. don't know i'm doing wrong. please advise me. thank help. spec/controllers/videos_controller_spec.rb require 'spec_helper' describe videoscontroller describe "get show" before {@video1 = video.create!(title: 'family guy', description: 'some description')} "assigns requested video @video" :show, id: @video1 assigns(:video).should == @video1 end "render show tempalte" :show, id: @video1 response.should render_template :show end end end app/controllers/videos_controller.rb class videoscontroller < applicationcontroller before_filter :require_user def show @video = video.find(params[:id]) end end error got in terminal: failures: 1) videoscontroller show assign

android - Eclipse shows error icon to me but do not tell me what the errors are -

Image
can see errors cross enclosed red rectangular don't know problem is. tried run app see errors , couldn't run. there anyway show errors are? in advance~ i'm not familiar eclipse try clean project, project -> clean... -> clean projects. there times when copy paste, or alter xml files project need cleaned.

Python Tkinter Notebook widget -

using this python recipe , have created notebook widget on tk window. works fine until tried add image each tab. when add image tab, text set no longer shown. wondering if can make text (in case "tab one") show right below image.the following current code: from tkinter import * class notebook(frame): def __init__(self, parent, activerelief = solid, inactiverelief = solid, xpad = 4, ypad = 4, activefg = 'black',activebg='green',inactivebg='grey',bd=1,inactivefg = 'black', **kw): self.activefg = activefg self.activebg=activebg self.bd=bd self.inactivebg=inactivebg self.inactivefg = inactivefg self.deletedtabs = [] self.xpad = xpad self.ypad = ypad self.activerelief = activerelief self.inactiverelief = inactiverelief self.kwargs = kw

python - Using VLC capturing the video, and saving the frame as jpeg, how? -

how video stream 1 frame , saved samp.jpeg (keep overwriting on same file 1 frame), can use in python canvas or gui rendering jpeg , in browser. following test not work with. #!/bin/bash ps aux | grep vlc | awk '{print $2}' | xargs kill -9; vlc -i dummy --no-audio --video-filter=scene --start-time=1 --stop-time=1 --scene-format=jpeg --scene-ratio=24 --scene-prefix=exec samp.jpeg vlc://quit does not work works: there entry @ wiki.videolan.org/how_to_create_thumbnails : vlc c:\video\to\process.mp4 --rate=1 --video-filter=scene --vout=dummy --start-time=10 --stop-time=11 --scene-format=png --scene-ratio=24 --scene-prefix=snap --scene-path=c:\path\for\snapshots\ vlc://quit if ffmpeg option, take @ http://ffmpeg.org/trac/ffmpeg/wiki/create%20a%20thumbnail%20image%20every%20x%20seconds%20of%20the%20video i think vlc wrong vehicle creating image, guess 1 come solution based on mjpeg streaming.

faceted search - RavenDB facet on list values -

is faceting on values of list possible? can query off of them in index doesn't facets returning values. here test: https://gist.github.com/svickers/5a29a4e32a24b1576ae3#file-ravenfacets see answer in mailing list. http://groups.google.com/group/ravendb/browse_thread/thread/6e7b4e8393536d1f/2f10ab3a63b86148?lnk=gst&q=faceting+on+list+values#2f10ab3a63b86148

sql - select TOP n Rows from table where n is in another table? -

how can achieve without using dynamic sqlquery? i have query, select top n mytable id = @id to value of n, select ncount myanothertable id = @id can use row_index() this? try this....but make sure select ncount return single row.....if not select top row ncount select top(select top 1 ncount myanothertable id = @id) * mytable id = @id sqlfiddle: http://www.sqlfiddle.com/#!3/75c76/1

php - Running CodeIgniter Project -

Image
i have whole web site project based on codeigniter framework. problem don't know how run project on local mamp server. have set mamp , run latest version of codeigniter. but how can run whole project using codeigniter found in localhost folder. first experience cms framework. open application/config folder first go config.php file , point base url correct location $config['base_url'] = ''; than goes database.php , provide correct database parameters $db['default']['hostname'] = 'localhost'; $db['default']['username'] = 'user'; $db['default']['password'] = 'password'; $db['default']['database'] = 'dbname'; thats basic changes u have do.... now if want redirect specific controller default go routes.php file in config directory , change vairable $route['default_controller'] = "yourcontrollername"

xslt 2.0 - XSL grouping by group-starting-with -

i have problem xsl. have xml documents (similar docbook) have transformed xsl. of documents contains sect2-title, , next sibling part of tags. starting xml has following structure: <?xml version="1.0" encoding="utf-8"?> <book> <part> <article role="content" title="contenidos"> <sect1 title="1. concepto y características de juego"> <para>el juego es una ...</para> <sect2-title>1.1. el modelo lúdico:</sect2-title> <para>sin embargo, sí existe un hecho ...</para> <sidebar> <sidebar-role>vocabulario</sidebar-role> <sidebar-para>de ahí el origen de ....</sidebar-para> </sidebar> <imageobject> <imagedata fileref="../../media/img/ud01_7151_inl02.jpeg" /> <

Take input from mobile in matlab -

i making project , in want take input mobile matlab on computer. plz me this. at-least tell me if can happen or not or there alternate way so. using android phone samsung note-2. i working on long time ago. if looking cheap (read free) way of doing it, have news you. there 2 tried , worked not satisfactorily. mobile => sms => facebook => pc you might aware of facebook option send messages through mobile itself. need activate mobile notification option , receive new messages sms's in mobile. there option reply. send message facebook yourself. you'll notification. use libcurl , write code monitor conversation thread (with in facebook) pc. need create app in facebook , authenticate access inbox. there technicalities oauth , other things. there lot of examples online. just type matlab command , script should save command file. file should monitored matlab , must execute command. output of command stored in file , file accessed libcurl script , sends

extend - extending logical volume in ubuntu -

i have following problem. ' ve added 20gb ubuntu machine (from 20 40gb). fdisk -l command : disk /dev/sda: 42.9 gb, 42949672960 bytes 255 heads, 63 sectors/track, 5221 cylinders, total 83886080 sectors units = sectors of 1 * 512 = 512 bytes sector size (logical/physical): 512 bytes / 512 bytes i/o size (minimum/optimal): 512 bytes / 512 bytes disk identifier: 0x000881a0 device boot start end blocks id system /dev/sda1 * 2048 499711 248832 83 linux /dev/sda2 501758 41940991 20719617 5 extended /dev/sda5 501760 41940991 20719616 8e linux lvm disk /dev/mapper/zabbix-root: 20.1 gb, 20124270592 bytes 255 heads, 63 sectors/track, 2446 cylinders, total 39305216 sectors units = sectors of 1 * 512 = 512 bytes sector size (logical/physical): 512 bytes / 512 bytes i/o size (minimum/optimal): 512 bytes / 512 bytes disk identifier: 0x00000000 disk /dev/mapper/zabbix-root doesn't contain valid partiti

ios - Symbol not found: ABAddressBookCreateWithOptions -

i've been working on iphone app can brings contacts iphone device app , i've read addressbook privacy control , ios6 need abaddressbookcreatewithoptions , , working in ios6 if i'm running app in ios5 , below i'm getting error : objective c symbol not found: abaddressbookcreatewithoptions , please provide me solution run app in ios6 , below versions ... ... a cleaner approach check symbol @ runtime: -(bool)isabaddressbookcreatewithoptionsavailable { return &abaddressbookcreatewithoptions != null; } take @ this answer full ios 5/6 compatible approach reading contacts address book.

c++ - Reading multiple lines from keyboard as input -

for code, had read multiple lines keyboard. code have here job. here code: #include <iostream> using namespace std; int main() { string input; string line; cout<< "enter input line" << endl; while (getline(cin, line)) { if (line == "^d") break; input += line; } cout<< "the input entered was: "<<endl; cout<< input<< endl; } the output after running this. enter input line hello world ! input entered was: helloworld ! the problem: see, getline give white space when printing hello world. how make sure gets printed "hello world !" rather "helloworld !" happens when there n newline. concatenated previous line string , printed. try this, while (getline(cin, line)) { if (line == "^d") break; input += " " + line; }

Oracle Database Encryption without ASO -

the situation can use oracle standard edition. however, need encrypt fields (or maybe whole tablespace). is there way can encrypt database / fields still able wildcard search, e.g. select * enc_table enc_col 'j%' the requirement not strict have use like, use function select * enc_table search_like(enc_col, 'j%')

open source - where can find beautiful and simple opensource android app? -

i know apps-for-android . simple not petty. can use learn usage of android api. opensource resources can guide beginner develop beautiful app? yeah there couple of tutorial sites can learn scratch.as beginner , moderated approach prefer visit link , download tutorials.its useful have idea on how build apps , understand basic things regarding android. http://www.youtube.com/course?list=ec2f07dbcdcc01493a

javascript - AJAX/JQuery and PHP to send prompt without reload for a contact form -

full website: http://adamginther.com i've used 2 separate tutorials build this, 1 php , 1 ajax. goal build contact form check errors. if there no errors prompt users message saying message has been sent without refreshing page. when website run locally not display errors until button pressed, when run on server errors displayed on entering page. when contact button pressed loads php , page goes blank. html <form action="contact.php" method="post"> <label name="firstname">name: </label> <input type="text" name="firstname" id="firstname"> <label class="error" for="firstname" id="name_error">i need name.</label> <br id="namebreak"> <br> <label name="email" for="email" id="email_label">e-mail address: </label> <input type="text" name="email" id="email">

javascript - Nested viewmodels and json in knockout.js -

i have seen questions , answers here resembles question here, either way more advanced implementation, or different direction. the thing is, receive json string has nested information so: {"studentbasedata":{ "studentguid":123456, "firstname":"my name", "lastname":"my last name", "email":"email@email.com", "password":123456, "birthdate":"01-01-1986", "picture":null, "mobilephone":"123456789", "gender":"hr."}, "primaryeducation":{ "name":"something", "institution":"something", "studystartdate":"2011-12-01", "graduationdate":"2013-12-01", "thesissubject":"something"}, "maddress":{ "street":"a road", "streetnr":&q

Returning an object but not using the new keyword, Javascript? -

i trying create object gets returned without new keyword in javascript? my code structure far; mylib.func = (function() { "use strict"; function func() { this._init(); }; func.prototype._init = function() { this.somevar = 5; }; return func; })(); this works when using new keyword; new mylib.func(); how can make can do; var func = mylib.func(); but still return object same first example? what have tried mylib.func = (function() { "use strict"; function func() { if (window === this) { return new mylib.func(); } else { this._init(); } }; func.prototype._init = function() { this.somevar = 5; }; return func; })(); this not work learned example on slide 25 of john resig's tips on building library, http://ejohn.org/blog/building-a-javascript-library/ i know there existing frameworks, rolling own make me learn

arrays - PHP: implode() Invalid arguments passed -

i using codeigniter , validation rules - custom callback validation. anyway, seems not ci related think. i've got function return string … function array_implode($a) { return implode(',', $a); } … message implode(): invalid arguments passed but var_dump() shows me this: array(2) { [0]=> string(10) "first item" [1]=> string(11) "second item" } what wrong? why? why write function, calls std function? why not write implode(',', $array); instead of adding overhead of function call? also: var_dump puts out array? dump of $a inside array_implode function? sure $a going array, , insist on keeping array_implode function, edit code this: function array_implode(array $a) {//type hinting: function work if $a array return implode(',',$a); }

c# - Generating framework with NHibernate for Complex reports -

i'm developing application wpf, fluent nhibernate , mysql,we need generate complex reports. can me out find best framework implement report generation @ database level. i need help, how should report manager manage filter criteria , expression creation. should create sql statements , query data session ? need support designing framework same. thanks, after long search on google, best way implement framework querying database reports. found thing detachedcriteria complex queries solves problem. reference : http://ayende.com/blog/1900/complex-searching-querying-with-nhibernate

python - Check if items in a list exist in dictionary -

my question might little complicated understand here's thing. have nested dictionary looks this: dict_a = {'one': {'bird':2, 'tree':6, 'sky':1, 'total':9}, 'two': {'apple':3, 'sky':1, 'total':4}, 'three': {'tree':6, 'total':6}, 'four': {'nada':1, 'total':1}, 'five': {'orange':2, 'bird':3, 'total':5} } and list: list1 = ['bird','tree'] newlist = [] how can check items in list1 whether in nested dictionary of dict_a , append newlist? output should this: newlist = ['one','three','five'] since bird , tree happened in nested dictionary of one, 3 , five. what can think of is: for s,v in dict_a.items(): s1,v1 in v.items(): item in list1: if item == s1: newlist.append(s) make list1 se

form control in PHP -

i form in html little website, want users subscribe php control seems not work , don't know why! javascript control works php doesn't... source: <!-- html --> <form action="inscriptionsucces.html" method="post" name="inscription" onsubmit="return verif(this);"> <h2>identifiants</h2> <ul> <li>pseudo* : <input type="text" name="pseudo" id="pseudo" size="30" /></li> <li>mot de passe* : <input type="password" name="pass" id="pass" size="30" /></li> <li>veuillez retaper votre mot de passe* : <input type="password" name="pass2" id="pass2" size="30" /></li> <li>adresse mail (valide)* : <input type="text" name="mail" id="mail" size="30" value="" />@ <s

android - Make app installer downloadble from a server -

make app installer downloadble server hi, while developing android app realized app should have own google market structure in have custom application installed on custom platform should installed in android. sorry being unable express correctly hope understand willing say my scenario app available free on google market when user installed app download files server , built content app new update in code of application automatically update download content such images,video,audio application server

sql - MySQL: Return table names without using any of "show tables from database_name" or "select table_name from information_schema.tables" queries -

i trying return table names without using "show tables database_name" or "select table_name information_schema.tables" queries reason of that: i can't use "show tables database_name" query because returns row set of table names fixed field name "tables_database_name" , not acceptable in code when database name long -i using dbexpress on delphi , column name can't longer 31 character-. i can't use "select table_name information_schema.tables" query because not supported old mysql think older 5.1 please if body knows : how change resulted fixed column name of "show tables database_name". or any other query returns table names inside specific database. how change resulted fixed column name of "show tables database_name". seems show tables separate statement fixed syntax: show [full] tables [{from | in} db_name] [like 'pattern' | expr] http://dev.mysql.com/doc/r