Posts

Showing posts from April, 2013

SSIS Script Component Transformation C# Code Date Conversion -

i'm creating ssis packages import large fixed width text documents , need transform various fields. 1 such field represents dates , 8 characters wide. format "yyyymmdd" , this: somedatefield 20130415 20110122 19891023 however, fields have blank spaces, , have zeroes 00000000. cannot converted date should return null value. i'm not allowed substitute date 1/1/1900. after futilely trying convert date field expressions, turned c# script transformation. my input column called ssolddate , readonly. i've configured output called solddate of dt-dbdate data type. the code came works is: datetime vardate; bool isparsed; isparsed = datetime.tryparseexact(row.ssolddate, "yyyymmdd", cultureinfo.invariantculture, datetimestyles.none, out vardate); if (isparsed) { row.solddate = vardate; } else { row.solddate_isnull = true; } i follow other date fields 1 in text

entity framework 6 - What is the Windows overhead when using SQL Server varchar vs. nvarchar? -

i not have need foreign language characters or collation since data received pure ascii. my concern performance in application code, , though have read many arguments varchar performs better nvarchar, did not discuss overhead converting , forth between windows unicode , sql server non-unicode varchar data? what bigger impact in general - performance within sql server dealing varchar vs. nvarchar, or performance in application, converting , forth between unicode on windows side , non-unicode on sql server side? understand there scenarios 1 perform better other, main scenario simple text search , retrieval through couple million records. using entity framework 6.1.3 dal. this concern , love feedback on having experimented or knowledgeable on topic. articles discussing varchar vs. nvarchar act sql database totally isolated in respect performance , external software not come play. there in fact unicode impedance mismatch between windows native use of unicode , ascii in database,

imagemagick - RMagick crop! "bignum too big to convert into `long'" error -

i'm getting error rmagick 2.13.1 on rare occasions , error message doesn't make sense me. can shed insight? pagination = magick::imagelist.new pagination.from_blob(restclient.get(url)) pagination.each |f| f.crop!(magick::southwestgravity, 0, 20, 368, 358) end crop! raises rangeerror: bignum big convert 'long' prior calling crop! can inspect f , "png 550x366 550x366+0+0 directclass 16-bit 625kb". the code works , can't figure out causing break on image.

java - How to count number of nodes per depth in a breadth_first search in Neo4j -

i trying design mlm application. operates person sponsors 3 persons , b, c, d , each of b, c, , d sponsors 3 more , on. to calculate payouts, client wants graph traversed based on last person of 3, d , total payout based on number of people under d multiplied specific amount. challenge me constraint whereby each level, need count n-1 persons n maxes out @ 3 mlm strategy. i using embedded neo4j project far know can traverse based on relationship , perhaps bread_first search , current depth how count number of persons minus 1 each level in traversal? seems, may have implement custom method need pointed in right direction. well, long know depth you're at, can use depth index collection (an array example). every time visit node @ given depth, increment value @ index in collection. once you're finished traversal, can apply ever rules , constraints array of data.

jquery - Passing an attribute to input type in Jeditable -

i'm using jeditable edit , post changes different elements of page. i'd able specify whether edit type should text or textarea looking @ attribute in i'm editing, data-type_edit="textarea example. however, passing don't seem able pass value or attribute 2nd part of jeditable function specify type. why isn't type : $(this).attr('data-edit_type') working in code: $('.editable.edit-section').editable(function(value, settings) { var dbid = $(this).attr("data-db_id"); var dbtable = $(this).attr("data-db_table"); var dbcol = $(this).attr("data-db_col"); submitedit(value, dbid, dbtable, dbcol); // needed value correctedly displayed jeditable on page return(value); }, { type : $(this).attr('data-edit_type'), submit : "ok", cancel : "cancel", tooltip : "click edit...", onblur : "ignore" }); thanks! try doing.

php - Filter MySQL records between two tables by Join depending on a specific column value -

recently i've been working on php/mysql script reads information database user info , file info stored in 2 seperate tables. below schema's tables. table1 uid | username | permissionlevel 1 | first | 1 2 | next | 3 3 | more | 2 table2 fid | filename | filelevel | uploadusername 1 | file.txt | 2 | first 2 | hand.mp4 | 1 | first 3 | 1245.dds | 1 | next 4 | beta.sql | 3 | more for purpose of message have omitted passwords column , file title/description column, since play no part in result trying achieve. so far have come sql code select distinct table2.*, table1.* table2 join table2 on table2.filelevel <= table1.permissionlevel table2.uploadusername = table1.username order fid desc limit 7 this generates appropriate listing want, not filter level of content shown. any user permissionlevel of 1 should see files filelevel of 1. users permissionlevel of "2" can see files of filelevel of b

python - Celery is not working on my Heroku -

what on earth doing wrong? i have found awesome django template called django-skel . started project because made easy use heroku django. going great until tried celery working. no matter tried couldn't tasks run. started new bare bones app see if working without of other craziness preventing things. this bare-bones app. have , running on heroku. django admin working, have databases sync'd , migrated. using cloudamqp little lemur rabbitmq. see requests queued in rabbitmq interface, nothing happens. how queue tasks manually run in shell: from herokutest.apps.otgcelery.tasks import add result = add.delay(2,2) i make sure have 3 dynos running, , still nothing. also have working locally. i sure there tons of questions, , i'm willing give them. please ask. thank everyones help. there couple things ended doing wrong. first thing was importing task incorrectly. had was: from apps.otgcelery.tasks import add result = add.delay(2,2) celery pick

sql - in mysql trigger.. how to use insert into and update query -

i have product_price_log table. updated ever new price updated in product_price table. i using trigger: drop trigger if exists product_update; delimiter $$ create trigger product_update before update on w3xab_virtuemart_product_prices each row begin declare virtuemart_product_id int; declare old_product_price decimal(15,5) default 0; declare new_product_price decimal(15,5) default 0; declare price_update_date date; if (new.product_price <> old.product_price) insert product_price_log (virtuemart_product_id,old_product_price, new_product_price, price_update_date) values (new.virtuemart_product_id, old.product_price, new.product_price, curdate()) on duplicate key update old_product_price = values(old.product_price), new_product_price = values(new.product_price), price_update_date = curdate(); end if; end$$ delimiter ; now no error..but update not working when try update price... insert working i set virtuemart_product_id primay key dont know whats going

sql server 2008 r2 - Right after establishing a new connection to a DB need to execute a specific TSQL command. All is under EF5.0 (Model First) -

using entity framework 5.0, , ms sql server 2012. implementing cell level encryption functionality. requires specific set of actions encrypt/decrypt data: open encryption key (ex. executing open symmetric key tsql command) execute following select decryptbykey(key_guid, encrypteddate) sometable the question is: how, under entity framework 5.0 can run open key command right after new connection db established? after key opened, stay open until db session active. thank you maybe can subscribe connection's statechange event: this.database.connection.statechange += this.connection_statechange; // "this" dbcontext. private void connection_statechange(object sender, statechangeeventargs e) { if(e.currentstate == connectionstate.open) { // commands here using sender sqlconnection. } }

heroku - Rails 500 Error Visiting Resources -

this question has answer here: 500 internal server error in ruby on rails 3 answers on localhost, app works fine. on production server (heroku) when visit resources page: http://startupcrawler.com/startups 500 error. here's routes.rb: startupcrawlerruby::application.routes.draw resources :startups "home/index" root to: 'home#index' end and on production server, here's when run rake routes : prefix verb uri pattern controller#action startups /startups(.:format) startups#index post /startups(.:format) startups#create new_startup /startups/new(.:format) startups#new edit_startup /startups/:id/edit(.:format) startups#edit startup /startups/:id(.:format) startups#show patch /startups/:id(.:format) startups#update

Python Relative import does not work from command line gives ValueError -

my directory structure follows microblog/__init__.py urls.py views.py wsgi.py settings/__init__.py testing.py base.py local.py in testing.py have relative import from .base import * ... ...more code when try run testing.py command line in directory microblog/settings using python testing.py from .base import * valueerror: attempted relative import in non-package why not work. settings directory valid package init .py . not valueerror command line if change from .base import * to from base import * i trying understand why relative local import fails , gives valueerror when run "testing.py" package relative import in command line. the answer icyrock in this post clarifies didnt understand python "repl". in directory microblog/settings when run python testing.py it puts testing in package "main" , not know testing part of package

python - getting the opposite diagonal of a numpy array -

so in numpy arrays there built in function getting diagonal indices, can't seem figure out how diagonal starting top right rather top left. this normal code starting top left: >>> import numpy np >>> array = np.arange(25).reshape(5,5) >>> diagonal = np.diag_indices(5) >>> array array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]]) >>> array[diagonal] array([ 0, 6, 12, 18, 24]) so use if want return: array([ 4, 8, 12, 16, 20]) there in [47]: np.diag(np.fliplr(array)) out[47]: array([ 4, 8, 12, 16, 20]) or in [48]: np.diag(np.rot90(array)) out[48]: array([ 4, 8, 12, 16, 20]) of two, np.diag(np.fliplr(array)) faster: in [50]: %timeit np.diag(np.fliplr(array)) 100000 loops, best of 3: 4.29 per loop in [51]: %timeit np.diag(np.rot90(array)) 100000 loops, best of 3: 6.09 per loop

c - How to parallelize my n queen puzzle with Pthreads? -

i have following pthreads code n-queen puzzle. compiles successfully, wrong answer. whatever value type answer zero. guess have kind of logic error in code. guess problem happens somewhere in backtracking/recursion part. if suggest me solution, glad. #include <stdio.h> #include <stdlib.h> #include <time.h> #include <pthread.h> #include <assert.h> int nthreads, size; int *hist; int count = 0; int solve(int col, int tid) { int start = tid * size/nthreads; int end = (tid+1) * (size/nthreads) - 1; int i, j; if (col == size) { count++; } #define attack(i, j) (hist[j] == || abs(hist[j] - i) == col - j) (i = start; <= end; i++) { (j = 0; j < col && !attack(i, j); j++); if (j < col) continue; hist[col] = i; solve(col + 1, tid); } return count; } void *worker(void *arg) { int tid = (int)arg; solve(0, tid); } int main(int argc, char* argv[]) {

postgresql - Aggregating rows into JSON hash -

i have following table: roles id | name | person ---+-------+-------- 1 | admin | jon 2 | admin | fred 3 | user | alfred 4 | user | jon where name can vary value. i'd json hash so: {"admin": ["jon", "fred"], "user": ["alfred", "jon"]} using pl/pgsql i'm gonna assume name's can vary cause without it's no challenge. usins eval function : create or replace function eval(expression text) returns text $body$ declare result text; begin execute expression result; return result; end; $body$ language plpgsql we can create dynamic crosstab: select eval('select row_to_json(q) (select '||(select string_agg(distinct '"'||name||'"',',') roles)||' crosstab(''select 1,name,array_agg(person)::text[] roles group name; '') ct(row_name int,&#

angularjs - Angular switch in repeater -

given list such var list = ['one','two','three']; in angular, want iterate through list rendering items. like: <ul ng-controller="main"> <li ng-repeat="item in list" ng-switch on="item"> <span ng-switch-when="one">{{item}}</span> </li> </ul> and have output this: <ul> <li><span>one</span></li> </ul> instead, get: <ul> <li><span>one</span></li> <li></li> <li></li> </ul> i have tried ng-hide woefully inefficient since have large number of items , want display 1 or 2 , ng-hide renders of them , hides inactive ones css. problem because doing in jquery mobile app tries decorate list items, including hidden ones, killing performance. jsfiddle @ http://jsfiddle.net/ghendricks/mxu3a/ you correct ng-hide should not used here, job filters .

bitcoin - Coinbase address callbacks not working? -

i'm using coinbase api. app generates new receive addresses callbacks. however, when btc arrives @ of addresses, callbacks don't seem firing. i've verified callbacks indeed being created new addresses, , app respond correctly callbacks. instance, triggers desired functionality on server: curl --data "address=someaddress&amount=1.2" https://mydomain.com/callback?secret_token=mysecret alas, there no calls being made server whatsoever (any call show in logs, none do). anyone using coinbase address callbacks successfully? hints debugging this? have tried using json request php set callback url? if login , @ addresses section, see correct url in callback section? make sure there no typo. able few months ago have left project did this.

css - Making a large table base website mobile friendly -

we in process of making school website mobile friendly. http://as.sjsu.edu/ascr/index.jsp?val=fit_group site has lot of content different departments(hundreds of pages). content in tables. make mobile friendly i'm applying styles tables using max-width, min-width , float: left in order stack tables vertically when viewed in smaller screens. here example: http://as.sjsu.edu/cf/vaishak/responsivetables/table.html works well. however, site contains many different table layouts , have empty cells , columns being used create margins between cells content hard coded dimensions tables. use adobe contribute let different departments update content. need continue using contribute , supports tables editing. any suggestions on how efficiently import content responsive layouts or how possibly deal content without having manually change source code on every page? the process have in mind writing script rid of unnecessary cells , insert responsive css id/classes cells/tables content

Mkdir() permission denied C/linux programming -

when execute code, error couldn't create backup sub-directory: permission denied can't understand why since give full permisions , i'm using admin account on ubuntu. umask(0777); int folder_date_status = mkdir(filepath_w, 0777); if(folder_date_status == -1){ perror("couldn't create backup sub-directory"); return -1; } an admin account doesn't run full privileges default. programs run don't unexpectedly act privileged users (ie. must explicitly give permission). to give permission program create sub-directory in directory requires privileged access, try using sudo . if program name called myprogram , try running: sudo ./myprogram then type password if requested. note super-user access should required if trying make subdirectory in write-restricted directory (eg. restricted directory owned root, or user). ensure parent directory exists (otherwise throw error).

Sorting CSS code ascending -

Image
i triying sort css code, no luck. have css code of more 2000 lines, not possible sort them manually. for example want sort this: #sidebar{color:#aaa} body{font-size:20px} #sidebar .h3{color:#555} footer{border:solid 1px #eee} ... this: body{font-size:20px} footer{border:solid 1px #eee} #sidebar{color:#aaa} #sidebar .h3{color:#555} is there plugin notepad++ or online site doing this? you'll need plugin notepad++ if want sort: menu => plugins => plugin manager => show plugin manager available => textfx characters => press install , restart notepad++ when asked (save work). select text sorted menu => textfx tools => sort lines * (there's multiple options here) of course, proper editor have built-in ;)

javascript - Accessing angular directive (element)'s text inside the template -

so following this egghead.io tutorial on custom components, , came across problem. when declaring directive such as: angular.module('myapp', []) .directive('mydir', function(){ return { restrict: "e", controller: "mycontroller", link: function(scope, element, attrs) { scope.foo = element.text(); }, templateurl: "mydirtemplate.html" } }); and template being: <div>the value is: {{foo}}</div> and directive being used such follows: <html> ... <mydir>bar</mydir> ... </html> element in link function refers <div>the value is: {{foo}}</div> in template. if don't specify templateurl , element refers <mydir>bar</mydir> in main view, want. hoping directive take "bar" text , insert {{foo}}, giving final result of: <div>the value is: bar</div

3dsmax - Replace kinect avateering model -

i trying change dude model in kinect avateering have tryied many ways no 1 goes wright except when replaced tga files opened dude.fbx using 3d max , try import , re export it goes wrong , had errors in building have tried replace whoke dude.fbx file nother fbx human model file , same error "no input skeleton found more specific doing virtual dressing room using 3d models make more stable using video processing need create 3d human modeling using programmimng language used dude model please in that i'm doing virtual dressing room project , struggled damn dude. there tutorial same topic trying. http://mopred.blogspot.com/2012/11/changing-avateering-avatar-in-kinect.html but think best way create own models , turn, rotate , translating them easy. animating boned model hard.

javascript - Changing CSS with DOM getElementsByName -

i trying make changed css dom in js, have succeeded changing html attributes not css attributes. seems css not affected particular dom. code looks this... <style> #circle1{ width: 50px !important; height: 50px !important; position: absolute !important; top: 200px !important; left: 405px !important; background: black !important; border-bottom-left-radius: 50px !important; border-bottom-right-radius: 50px !important; border-top-left-radius: 50px !important; border-top-right-radius: 50px !important; z-index: 10 !important; visibility: hidden !important; } </style> </head> <body> <script type="text/javascript"> function showcircle(){ document.getelementsbyname ("circle").style.visibility="visible"; } </script> <div id="circle1" name="

bittorrent - Qt torrent example stuck at searching -

i have problem. i working on download-only bittorrent client. going well, but had pause 2 weeks, while changed nothing. program stuck @ searching. tried qt torrent example. same problem there on both pcs. linux/windows 7/windows 8 (all 64-bit). u know can cause problem? tried turn on/off firewall. no change. i have school project, im pretty scared making totally new code, if have 2 weeks finish it. here link of qt-example http://qt-project.org/doc/qt-4.8/network-torrent.html thanks martin

JavaScript passing coordinates from one function to another -

i having issues passing 2 coordinates 1 function another. don't know javascript, seems correct. please let me know error? <head> <script> var zoom = 12; // 18 mobile phones because geolocation more accurate function init() { // don't bother if web browser doesn't support cross-document messaging if (window.postmessage) { if (navigator && navigator.geolocation) { try { navigator.geolocation.getcurrentposition(function(ppos) { send(ppos.coords.latitude, ppos.coords.longitude); }, function() {}); } catch (e) {} } else if (google && google.gears) { // relevant if targeting mobile phones (some of may have google gears) try { var geoloc = google.gears.factory.create("beta.geolocation"); geoloc.getcurrentposition(function(ppos) { send

c# - Getting an InvalidCastException was Unhandled -

this take on experimental code @tim schmelter pointed me in correct direction towards earlier afternoon. majority of same worked earler, throwing invalidcastexception on last line or second last line, depending whichever try. cannot see why is. boolean test = false; string filepathstudent = system.io.path.getfullpath("studentinfo.txt"); datatable studentdatatable = new datatable(); studentdatatable.columns.add("id", typeof(int)); studentdatatable.columns.add("studentid"); studentdatatable.columns.add("firstname"); studentdatatable.columns.add("lastname"); studentdatatable.columns.add("streetadd"); studentdatatable.columns.add("city"); studentdatatable.columns.add("state"); studentdatatable.columns.add("zip"); studentdatatable.columns.add("choice1"); studentdatatable.columns.add("credithrs1"); studentdatatable.columns.add("choice2"); studentdatatable.columns.ad

ruby - DRYing up these helper methods -

i've got 3 methods this: def total_fat total = 0 meal_foods = current_user.meal_foods meal_foods.each |food| total += food.fat end return total end one fat, carbs, , protein. i'd dry up. i've tried method , didn't seem work passing in 'macro' string. def total_of(macro) total = 0 meal_foods = current_user.meal_foods meal_foods.each |food| total += food.macro end return total end how this? def total_of(marcro) current_user.meal_foods.map(&marcro).inject(:+) end this takes array(-like) collection of meal_foods , maps array of marcro value of meal_foods , , injects "+" between each of numbers. make sure pass argument symbol, e.g. total_of(:fat) .

Android:Google maps coordinates -

i have app coordinates , returned google maps. have 1 problem. when put coordinates,the pointer not correct. have 1 method think not job. sorry bad english. thanks in advance. touchedpoint=map.getprojection().frompixels((int) cord,(int) cord1); custompoint custom = new custompoint(d, maps.this); overlayitem overlayitem = new overlayitem(touchedpoint, null, null); custom.insertpoints(overlayitem); overlaylist.add(custom); please use google map v2. has been deprecated , key been lost on march. https://developers.google.com/maps/documentation/android/ and can find tutorial in http://www.vogella.com/articles/androidgooglemaps/article.html

cgal - How can I install MPFI library in Windows? -

there! i'd execute example program, surface_reconstruction_points_3. i think program needs additionally 3rd library, mpfi. so downloaded library http://mpfi.gforge.inria.fr/ . and unzipped @ proper folder , linked system path. after configurating example program using cmake-gui, i found error message, 'could not find mpfi (missing: mpfi_libraries)'. how can install mpfi library in window using visual studio 2008? since mpfi gnu library, supported on windows. cgal provides third-party libraries inside installation, windows has own replacement. i installed correctly visual studio, need uncheck third-party libraries cgal won't mess own windows replacements. maybe doing kind of installation isn't working sample codes inside installation, works fine development. used cgal without third-libraries voronoi , 2d , 3d triangulation , works fine. for clean installation, delete installed previously, make sure new installation isn't messin

asp.net mvc 4 - What is the best way to create dropdownlists in MVC 4? -

i want know,what best way create dropdownlists in mvc 4? viewbag or approach? i argue since items variable values within view belong in view model. view model not necessarily items coming out of view. model: public class somethingmodel { public ienumerable<selectlistitem> dropdownitems { get; set; } public string myselection { get; set; } public somethingmodel() { dropdownitems = new list<selectlistitem>(); } } controller: public actionresult dosomething() { var model = new somethingmodel(); model.dropdownitems.add(new selectlistitem { text = "mytext", value = "1" }); return view(model) } view: @html.dropdownlistfor(m => m.myselection, model.dropdownitems) populate in controller or wherever else appropriate scenario. alternatively, more flexibility, switch public ienumerable<selectlistitem> public ienumerable<mycustomclass> , do: @html.dropdownfor(m =>

xamarin - NuGet Package Restore in MonoDevelop on OSX/Linux -

Image
i'm trying compile visual studio project nuget package restore under monodevelop it's not working out of box. nuget should work on mono , there's support built nuget.targets, missing? based on issue tracked here: https://nuget.codeplex.com/workitem/3278 you must use xbuild projects should restore packages on build. monodevelop->preferences->build unix filesystems case-sensitive. breaks nuget.targets casing inside file assumed lower case whereas files added solution in .nuget folder cased "nuget". either fixup nuget.targets or change filenames in solutions .nuget folder lower case. requirerestoreconsent true default in nuget.targets. edit nuget.targets , change false. package restore puts package folder in weird location, $(solutiondir)/ /packages (yes, theres single whitespace folder in between). reason there's trailing whitespace in nuget.targets in after $(solutiondir) in <restorecommand>$(nugetcommand) install "$(pa

php - Different value in While loop -

i want 4 values while loop in different variables.for example want this $var1 = "value1"; $var2 = "value2"; $var3 = "value3"; $var4 = "value4"; here while loop while($rw = $oappl->row($rsimg)) { //get value here $var1 = $rw['thumb']; } but no value can repeatable,i have thumb returned. you cannot store more 1 value inside variable, can either echo while looping while($rw = $oappl->row($rsimg)) { //get value here echo $rw['thumb'] . '<br>'; } or create new array use values later $thumbs = array(); while($rw = $oappl->row($rsimg)) { //get value here $thumbs[] = $rw['thumb']; }

c++ - opengl 3.3 / glew 1.9 VBO support returns false -

i've built simple opengl window , checked it's support. support returned: glew: 1.9.0 opengl: 3.3.0 the problem i'm having due creating shapes (vbo). while creating shape based off of tutorial, couldn't image (a simple triangle) display screen. way other way achieve using immediate mode or basic vertex array. i inquired on checking vbo support glew, of suggestions i've found such as: if ( glewgetextension("gl_version_1_9") && glewgetextension( "gl_arb_vertex_buffer_object" )) { std::cout << "vbo supported." << std::endl; } else { std::cerr << "arb_vertex_buffer_object not supported!" << std::endl; } returned false. any suggestions may problem? stop checking arb_vertex_buffer_object . in fact, stop using arb_vertex_buffer_object. use the core functionality , not extension functionality. if you're as

c# - False positive for CA1801 in Release config only -

my method reads follows. public static void debug(this logger logger, string message) { logger.debug(() => message); } when run code analysis debug config, no warning. when run code analysis release config, get: ca1801 review unused parameters parameter 'message' of 'commonextensions.debug(this logger, string)' never used. remove parameter or use in method body. fakeiteasy commonextensions.cs 101 and ca1801 review unused parameters parameter 'logger' of 'commonextensions.debug(this logger, string)' never used. remove parameter or use in method body. fakeiteasy commonextensions.cs 101 this wrong. using both parameters in method body. if remove either of parameters code not compile. has else experienced similar? have discovered bug in code analysis? (i using same ruleset under both configurations.) update the logger.debug() signature follows: [conditional("debug")] public abstract voi

html5 - execCommand doesn't fire when called from keydown event in Windows Store apps -

i'm writing windows store app (html) includes simple rich-text editing. can apply bold selected using button fires document.execcommand("bold",false,null); however when bind keydown event ctrl+b, nothing happens. here's keydown code. document.addeventlistener("keydown", catchshortcuts, false); function catchshortcuts(e) { if (e.ctrlkey) { if (e.keycode == 66) // b document.execcommand('bold', true, null); } } } i know keydown code works fine because if replace document.execcommand line of code fires fine when press ctrl+b. seems execcommand has problem keydown event? turns out works fine if use keypress instead of keydown . in case else has same issue, that's workaround. still not sure why onkeydown doesn't work though. working code: document.addeventlistener("keypress", catchshortcuts, false); function catchshortcuts(e) { if (e.ctrlkey) { if (e.keycode == 6

java ee - Hibernate/JPA ManyToOne vs OneToMany -

i reading documentation of hibernate regarding entity associations , come accross little difficulty figure out things. has in essence difference between manytoone , onetomany associations. although have used them in real projects, cannot apprehend differnce between them. understanding, if table / entity has manytoone association another, association should other side onetomany . so, how should decide 1 choose based on specific case , how affect database/queries/results? there everywhere example? p.s.: reckon helpful due relevance question, if besides explain point of owner of association , difference between bidirectional , unidirectional association. suppose have order , orderline. can choose have unidirectional onetomany between order , orderline (order have collection of orderlines). or can choose have manytoone association between orderline , order (orderline have reference order). or can choose have both, in case association becomes bidirectional onetomany/man

oracle - Applet Java 7 update 21: Cannot set AWTKeyListener on default Toolkit -

in self-signed applet (that may possibly become ca-signed applet in near future) in have complex swing gui, need detect whenever user has shift- or control-key pressed. using in combination component-related mouseevents , mousemotionevents special mouse-event processing @ time. shortly: when recieve mouse-motion-event on distinct component need detect whether control or shift being held down (pressed). problem is, user press down shift/control before he/she moves mouse component of interest. real "usability" problem! prior java 7 update 21 able accomplish using jvm-global awtkeylistener added default toolkit. no longer allowed (due security requirements of java 7 update 21 - , in despite of, jnlp-launching applet in distinct , separate jvm, that's talk). so have: i have tried register keylistener "main" panel of applet, key-events seem "swallowed" (by whatever component in gui having keyboad focus). then have tried using key-bindings main

.net - Dependency property not set in OnOk -

if edit text in textbox , press enter in order fire click event of default key, don't correct value in click handler. how can value in handler? here xaml: <window x:class="wpfapplication1.defaultkeywindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" title="defaultkeywindow" height="300" width="300"> <stackpanel> <textbox text="{binding test}" /> <button click="onok" isdefault="true">ok</button> </stackpanel> </window> and here code behind: public partial class defaultkeywindow : window { public string test { { return (string)getvalue(testproperty); } set { setvalue(testproperty, value); } } // using dependencyproperty backing store test. enables animation, styling, binding, etc... public static readonl

ruby - How do I compare objects pointing to a different place in memory? -

i have array of objects: array = [ obj1, obj2, obj3 ] if query obj1 objects table: obj1 = objects.get(1) both obj1 , obj1 same objects, when compare them false : array[0].eql? obj1 # false what's best way compare 2 objects when not pointing @ same place in memory? actually, these kinds of comparisons of value possessed these same types of objects, need define own comparison operator <=> or whatever sign like, don't override default operators == . may lead problem. see " ruby equality , object comparison ."

Why does Gitlab do not show a project network graph and other graphs for my imported repo? -

Image
i have migrated cvs repo cvs2svn240 , git fast-import1834 git repository. have installed gitlab53 , imported git repo. can browse through files, add users , on. works fine. thing blank graph pages. system: rhel63, 65gb ram, 4 cpu cores. git-repo: 2,8 gb (bare). i have not yet create new commits on repo, still in after migration state. think should show graphs based on current repo data. where problem? this because of size of repo. there pending issue 4218 "large scale project graph problem" reports similar problem (lack of content in graphs) as geerlingguy add in comments , issue close, , geerlingguy opened ticket .

curl - Google PHP API Client: CA cert error -

i'm attempting interface google php api client , having issues certificate provided google: google error: ssl certificate problem, verify ca cert ok. retrying ca cert bundle google-api-php-client. php curl error: ssl certificate problem: unable local issuer certificate i had no problems whatsoever on linux box. these errors occuring on windows box. i've tried couple of different solutions: https://code.google.com/ http://richardwarrender.com/ but no avail. ps: curl_setopt($ch, curlopt_ssl_verifypeer, false); won't acceptable ... courtesy of rmckay @ webaware dot com dot au: please everyone, stop setting curlopt_ssl_verifypeer false or 0. if php installation doesn't have up-to-date ca root certificate bundle, download 1 @ curl website , save on server: http://curl.haxx.se/docs/caextract.html then set path in php.ini file, e.g. on windows: curl.cainfo=c:\php\cacert.pem turning off curlopt_ssl_verifypeer allows man

ios - Skitch like plugin for Phonegap -

Image
i trying find skitch plugin phonegap. have ability bring camera phonegap app , snap picture, want ability edit photo add freehand drawing/text/arrows, skitch has or of applications in app store. appreciated. heres photo of skitch looks like,

Private vs Public Javascript Functions -

can please explain difference between these 2 functions? (function(engine, $, undefined) { //hidden scope //public function below engine.init = function() { console.log("im public"); } //anonymous functions below function login() { console.log("im private"); } })( window.engine = window.engine || {}, jquery ); specifically, i'd know why engine.init() available in console login isn't. init property of engine object refers function. can access other property. login local variable within anonymous, "immediately invoked function expression" (iife); other local variables, name visible within declaring function

php - flush() doesn't work in Doctrine 2 -

i'm new in doctrine 2. have big problem on beginning, didn't find solution in google. want keep tree in db. found nestedset plugin ( https://github.com/blt04/doctrine2-nestedset ). downloaded it, , tried build tree. tried way (it's same in documentation): $config = new \doctrineextensions\nestedset\config($entitymanager, 'src\file'); $nsm = new \doctrineextensions\nestedset\manager($config); $mainfolder = new \src\file(); $mainfolder->setname('folder 1'); $nsm->createroot($mainfolder); but nothing. looked iside createroot() function, , figured out function flush() doesen't work: $this->getentitymanager()->flush() but don't know why. doesen't throw exception, , returns nothing. ideas? that extension found has 36 commits , updated year ago. might wanna check out extension https://github.com/l3pp4rd/doctrineextensions has 1312 commits , updated 2 days ago. can use build tree: https://github.

c# - ASP.NET MVC Simple Controller Unit Test -

i'm trying learn unit testing, , have super simple class, unit test: public class homecontroller : controller { public actionresult index() { return view(new homeviewmodel { logourl = this.url.content("~/images/product.png") }); } } [testmethod] public void index() { assert.isnotnull(new homecontroller().index() viewresult); } i'm getting null reference exceptions. it's related using this.url() without httpcontext in unit test, believe. how can unit test pass while still using this.url() ? i'm fine using moq. :) the answer can found here example (gist): https://gist.github.com/johnnyreilly/4959924 here relating stack overflow question: asp.net mvc: unit testing controllers use urlhelper both should on right tracks. it comes down mocking httprequestbase , httpresponsebase can mock actual httpcontextbase , being used urlhelper class.

javascript - CSS infinite animation -

this project working on required me build moving animation uses nothing other css , styled divs. a perfect working example of identical can found here (note blue background white moving squares): http://www.braintreepayments.com however, unlike demo above, design consists of 10 times more div shapes in animation , when animation timing expires, container becomes blank, makes looks poorly designed. my question is, how animation in above example create 'continuous / infinite effect' on website, little styled divs? have been trying formulate replicate effect no success. note: open using jquery / javascript solution well. by using anitmation-iteration-count property , using infinite value - have hard time finding matching selector css minified, rule exists somewhere in stylesheet.

How to find list of triggers that are existed on a table. I am using sybase ASE 15-2 -

how find list of triggers existed in table. using sybase ase 15-2 i tried exec sp_depends 'dbo.mytable' i getting errors.. 1- check sp_depends exists: use sybsystemprocs go sp_help sp_depends go 2- check version of sp_depends in installmaster corresponds ase version use master go sp_version -- @ version of installmasater go select @@version -- @ version of ase go -- if not same version, run installmaster script (check in test first) 2- run commands: use <dbname> go exec sp_depends 'mytable' or sp_depends mytable go

sql - use mysql dayname as a column name -

is possible use dayname output columname currently using this select *, left(thu,5) open1 ... ... but replace thu string dynamic current day(3 letters) , still use column name. the short answer no, can't done. column references (like identifiers) in sql statement static. identifiers can't replaced expressions determined @ runtime. the longer answer either need dynamically generate statement, or choose 1 of set of possible statements execute, based on whatever conditions. a third approach might want, referencing possible column names want select from, , making return column conditional based on day of week. something achieves same result: select left(case dayname(now()) when 'sunday' t.sun when 'monday' t.mon when 'tuesday' t.tue when 'wednesday' t.wed when 'thursday' t.thu when 'friday' t.fri when 'satur

javascript - Strange occurrences with controlling multiple keys being held down -

with below code, when key pressed keycode pushed keymap array if it's not there , when key let keycode taken out of array. when testing out shoving keymap array console, found strange things. var keymap = []; $(window).keydown(function(e) { if($.inarray(e.keycode,keymap) == -1) {keymap.push(e.keycode);} }); $(window).keyup(function(e) { for(i = 0;i < keymap.length;i++) { if(keymap[i] = e.keycode) {keymap.splice(i,1);} } }); setinterval(function() {console.log(keymap);},100); if hold down , d @ same time keycodes present in keymap, if hold down w 3 of keycodes present. when let go of w it's removed array, d though i'm still holding down d. i found can hold down a, w, , d , they'll put keymap, not put w, a, , s in keymap when hold them down. combination of 2 of these put in, third not. can tell me what's going on? your comparison assignment actually. change if(keymap[i] = e.keycode) to if (keymap[i] == e.keycode) //

algorithm - Not getting the correct orientation of the user with respect to Kinect -

i using microsoft kinect in project. 1 of task have accomplish find orientation of user w.r.t kinect sensor (when user turns, orientation changes) this, trying find angle line joining shoulders makes x axis of kinect. i have come following code, gives me small angle values, when turn 40 degrees. double vector_x=skel.skeletonpositions[nui_skeleton_position_shoulder_left].x-skel.skeletonpositions[nui_skeleton_position_shoulder_right].x; double vector_y=skel.skeletonpositions[nui_skeleton_position_shoulder_left].y-skel.skeletonpositions[nui_skeleton_position_shoulder_right].y; double vector_z=skel.skeletonpositions[nui_skeleton_position_shoulder_left].z-skel.skeletonpositions[nui_skeleton_position_shoulder_right].z; double len1=sqrtf(vector_x * vector_x + vector_y * vector_y + vector_z * vector_z); double vector_x1=1.0; double vector_y1=0.0; double vector_z1=0.0; double len2=sqrtf(vector_x1 * vector_x1 + vector_y1 * vector_y1 + vector_z1 * vector_z1);

java - Are simultaneous reads from an array thread-safe? -

i have array contains integer values declared this: int data[] = new int[n]; each value needs processed , splitting work pieces can processed separate threads. array not modified during processing. can processing threads read separate parts of array concurrently? or have use lock? in other words: work order thread-safe? array created , filled threads created , started thread 0 reads data[0..3] thread 1 reads data[4..7] thread 2 reads data[8..n] reading contents of array (or other collection, fields of object, etc.) multiple threads thread-safe provided data not modified in meantime. if fill array data process , pass different threads reading, data read , no data race possible. note this work if create threads after have filled array . if pass array processing existing threads without synchronization, contents of array may not read correctly. in such case method in thread obtains reference array should synchronized, because synchronized block forces memory upd

Why is git core.preloadindex default value false? -

can answer why core.preloadindex false default? there pitfalls? can't imagine performance penalty. why not default - well, introduced in 2008, , did improve performance on weak filesystems nfs, and... linus of opinion should made default - http://git.661346.n2.nabble.com/git-status-takes-30-seconds-on-windows-7-why-tp7580816p7580853.html i wonder if preloadindex shouldn't enabled default.. it's huge deal on nfs, , real downside expects threading work. potentially slows things down tiny bit single-cpu cases cached, isn't relevant case.

nservicebus - What does Particular Software Service Platform exactly is? -

someone told service platform: http://particular.net/ implementing soa oriented applications. i find bit confusing @ first glance, ask questions it: services soap or rest? how data contracts , service contracts specified? are services externalizable outside consumers via wsdl metadata endpoints? a service not implemented in .net (java, ruby) can inserted in service bus? which protocol used messaging? what general thoughts service platform? for full disclosure, i'm founder of particular service platform, i'll try keep answers objective possible: services soap or rest? while platform allows use of wcf expose endpoints consumption 3rd parties, focus on queuing - msmq, rabbitmq, etc. how data contracts , service contracts specified? contracts message-oriented philosophical perspective, in practice they're regular poco classes , interfaces. are services externalizable outside consumers via wsdl metadata endpoints? see wcf comment

java - How to execute query with union in hibernate? -

hibernate doesn't support union ,so run sql separately. how combine values ? string query ="select dp.productfamily,dp.productfamilydescr tabel1 dd, tabel2 dp dd.id = 00002 , dd.productfamily null union select dp.divnumber,dp.divdescr tabel1 dd, tabel2 dp dd.id = 00002 , dd.product not null , dd.productfamily not null"; public list<product> findmethod() { return findallbyquery(query); } please advise how execute 2 sql seperately , how combine values ? notice each select statement within union must have same number of columns. columns must have similar data types. also, columns in each select statement must in same order. if true add alias query: select dp.productfamily productfamily,dp.productfamilydescr productfamilydescr tabel1 dd, tabel2 dp dd.id = 00002 , dd.productfamily null union select dp.divnumber productfamily,dp.divdescr productfamilydescr tabel1 dd, tabel2 dp dd.id = 00002 , dd.product not null , dd.productfamily not null

hyperlink - How to verify whether a link read from file is present on webpage or not? -

i new @ automation. have write code follow i have read around 10 url's file , store 1 hashtable need read 1 one url's hashtable , while iterating through url need read 1 more file conataining 3 url's , search them on webpage . if present need click link i have written following code not getting logic checking whether link file present on webpage or not... please check code , me solve/improve it. main test script package com.samaritan.automation; import java.util.hashtable; import java.util.set; import org.junit.test; import org.openqa.selenium.webdriver; import org.openqa.selenium.firefox.firefoxdriver; public class firstscript { webdriver driver = new firefoxdriver(); string data; commoncontrollers commoncontroll = null; hashtable<string, string> recruiters = null; @test public void script() throws exception { commoncontrollers commoncontroll = new commoncontrollers(); recruiters = new hashtable<strin

vbscript - Installation of MSI File on remote machine from local machine -

here script install msi file on remote machine: const msifilename = "\\<ip addr>\c$\mysetup\<filename>" set wshshell = wscript.createobject( "wscript.shell" ) wshshell.run "msiexec /a " & msifilename & " /quiet /log c:\install.log", 1, true when run script local machine, file installs on machine running from. instead want installed on machine specified in msifilename . going wrong? you're running remote msi on local host. install remote executable on remote host, use wmi: host = "<ip addr>" setup = "msiexec /a ""c:\mysetup\<filename>"" /quiet ..." set wmi = getobject("winmgmts://" & host & "/root/cimv2") rc = wmi.get("win32_process").create(setup, , , pid) if rc = 0 wscript.echo "setup started pid " & pid & "." else wscript.echo "starting setup failed. (" & rc &

asp.net mvc 3 - How to properly set content caching for a .Net application running in IIS? -

in mvc3 project have following class-level attributes set on of controllers: [outputcache(location = system.web.ui.outputcachelocation.server, duration = 14400, varybyparam = "*")] duration = 4 hours. i used varybyparam = "*" there differing parameters controller's action methods, instead of varybyparam = "none" - correct use? in iis, on server level , in web.config files sites, set static caching 8 days. observing headers in fiddler, when go search result page, see following: http/1.1 200 ok cache-control: no-cache pragma: no-cache content-type: text/html; charset=utf-8 expires: -1 vary: accept-encoding server: microsoft-iis/7.5 x-aspnetmvc-version: 3.0 x-aspnet-version: 4.0.30319 x-powered-by: asp.net date: thu, 15 aug 2013 17:21:32 gmt content-length: 148842 for site scripts js files: http/1.1 200 ok cache-control: max-age=691200 content-type: application/x-javascript last-modified: thu, 15 aug 2013 05:35:35 gmt accept-range

git push is not pushing the changes to the repository -

i new git , trying understand commands do, installed git in windows system. i made 1 of folder git repository, running command "git init". created ".git" directory in folder. cd git-repo git init after tried clone repository, made seperate folder , went inside , ran "git clone ../git-repo" command. cloned git-repo. now did changes in cloned folder, , tried commit git-repo using commands : git add . git commit -m "test commit" git push origin branch1 but problem pushed changes not visible in git-repo. please me this. thanks you pushing none-bare repo. depending on git version (still) works, newer gits no longer work. you should pushing bare repo (that can function similar server in centralized version control) , pull there, i.e. make transfer indirect. read more bare repos: http://gitolite.com/concepts/bare.html

c# - Programmatically detect and convert “pixel format not supported” images -

when debug wpf apps first-chance exception on, got lot of notsupportedexception message “pixel format not supported”. if ignore exception, images work fine want fix them anyway chance @ other first-chance exceptions. currently looking callstack figure out file name, convert manually using image editor, , restart debugging catch next one. however, wonder if can automate small console app detect such images , convert them format wpf happy with. i've read references limited image knowledge unable understand exact problem wpf having these images, or how can program detect these images if they're loaded xaml, or how convert them programmatically format wpf happy with. there various file formats - png being 1 - several different image formats stored in same file. in case it's image depth (bits per pixel). .net doing trying open file common format first , when fails it's trying different formats until gets 1 works. as rare event it's sensible try open f

javascript - How to replace particular string from a multiline textarea using jQuery? -

when have string consists of single line, replace works fine. as type in text text area , press enter new line, replace won't work anymore. var currentvalue = $('#service-field').val(); $('#service-field').val(currentvalue.replace("particular string","")); what should do? try make sure capture occurrences, , not ones on first line: $('#service-field').val(currentvalue.replace(/particular string/g, "")); or variable: var t = "particular string"; $('#service-field').val(currentvalue.replace(eval("/" + t + "/g"), ""));