Posts

Showing posts from August, 2013

python - Perform a reverse cumulative sum on a numpy array -

can recommend way reverse cumulative sum on numpy array? where 'reverse cumulative sum' defined below (i welcome corrections on name procedure): if x = np.array([0,1,2,3,4]) then np.cumsum(x) gives array([0,1,3,6,10]) however, get array([10,10,9,7,4] can suggest way this? this it: np.cumsum(x[::-1])[::-1]

xmlhttprequest - Mocking AngularJS XHR requests for testing using Jasmine -

ok, pretty sure weird behaviour - , have no idea going on... code below. i running jasmine spec on possibly simple angularjs controller ever, makes call function (getsuppliers) upon initialisation, in turn makes http request, have mocked out using $httpbackend. weirdness happens when run test. fails expected undefined equal 'list of suppliers' . so stuck in debugger; s (1 , 2) , ran spec in chrome. weird part. debugger 2 gets hit before debugger 1, meaning getsuppliers function returns value of undefined before mock has chance it's magic. record, when continue on , let debugger 1 come well, data has correct value of "list of suppliers" , if mock run in right place should sweet. have idea hell going on here? spec.js describe("supplier controller", function(){ ctrl = null; scope = null; httpbackend = null; suppliercontroller = null; beforeeach(inject(function($controller,$rootscope,$httpbackend) { scope = $rootsc

linux - Get process's timeslice in user mode -

how can value of process's timeslice in user mode? designed new scheduling policy, , want check if processes same policy (my policy) have same timeslice run. not real-time process. you can see in /proc/<pid>/stat 14th , 15th fields represent utime , stime respectively. utime time spent in user mode while stime represents time spent process in kernel mode.

c# - Delete folder on ftp -

hi want delete folder on ftp tried this: webrequest request = webrequest.create(strpath); request.method = webrequestmethods.ftp.removedirectory; request.credentials = new networkcredential(struusername,strupassword); using (var resp = (ftpwebresponse)request.getresponse()) { console.writeline(resp.statuscode); } webexception unhandled. (550)file not available strpath = ftp://192....../media in media other folders music, video ,.... why doesn't work? i've gotten error. try adding forward slash end of media like: strpath = ftp://192....../media/ still might agree comments, might need empty folder first.

c# - my jquery showing this error? -

i trying list of user data web service file called via ajax. here code : <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" /> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script type="text/javascript"> var param; var resultarr; $(document).ready(function () { param = document.getelementbyid('mainct_dtvjobvac_pic').value; // load countries initialize plugin: $.ajax({ type: 'post', contenttype: 'application/json;', data: '{keyword:' + json.stringify(param) + '}', datatype: 'json', url: 'svcaduser.asmx/getaduserlist', success: function (result) { //alert(result.d)

c# - Running newer exe on older version in dot net -

i have prepared c# console application using vs 2010 framework 4.0 , have done exe of same.i want run same exe on other server on vs 2005 (framework 2.0) installed.is there way same ? install .net 4.0 framework on target pc. that's practical option. also, why vs2005 on server? having ide on server seems "odd". without more uptodate version of visual studio, won't able develop/alter application easily, .net4 framework on machine you'll able run executable.

postgresql - PGSQL - inserting null values into table -

after executing following query: insert regiony (m_valid, m_validationreport, m_creation_timestamp, m_creation_user, m_modification_timestamp, m_modification_user, instance, kod_regionu, nazwa_gminy, kod_teryt) select distinct null, null, now(), 'abc', now(), 'abc', null, region_poch, export_gmina, replace(teryt, '|', '') source_table i following error: error: column "m_valid" of type boolean expression of type text i tried convert null value boolean (null::boolean), , worked boolean, instance column in target table (regiony) of type xml , pgsql refuses convert null xml. after converting null xml, get: error: not identify equality operator type xml any suggestions? of columns receiving null values allow null values , i'm running out of ideas. cheers, jan try rewriting without explicit null statements, letting pg handle them needed: insert regiony ( m_creation_timestamp, m_creation_user, m_modificati

php - mysql sort data result A-Z and split each section with lines -

i have few thousands of rows in mysql table after selecting records in ascending order want format each section of results in alphabetic order in format a ab abc abcd abcde abcdef ------------------------------------- b bab babc babcd babcdef ------------------------------------- c ca cab cabc cabcd cabcde cabcdef ------------------------------------- i need demacate each of sections of alphabet lines. in php (and other languages) strings infact arrays of characters. $string[0] hold first character of string. <?php $rows = get_rows_from_mysql(); $section = false; foreach ($rows $row) { if ($section != strtolower($row['name'][0])) { if ($section != false) echo "------------------------"; $section = strtolower($row['name'][0]); } echo $section['name']; } ?> above code not handle grouping of numbers or special characters !"#, should point.

android - Search View uses app icon instead of logo -

Image
android documents explain app logo used everywhere when defined. when search view expands, app icon used instead of app logo , can't find way show app logo when search view in expanded state. here relevant parts. manifest file <application android:name="myapp" android:allowbackup="true" android:icon="@drawable/app_icon" android:label="@string/app_name" android:logo="@drawable/app_logo" android:theme="@style/theme.mytheme" > searchable.xml (setting icon doesn't change anything) <searchable xmlns:android="http://schemas.android.com/apk/res/android" android:icon="@drawable/app_logo" android:label="@string/app_name" android:hint="@string/search_hint" > </searchable> menu.xml <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/menu_search&q

c - implementing list insert first in generic List -

listresult listinsertfirst(list list, listelement element) { null_arg(list, list_null_argument); node first = elementcopy(list, element); null_arg(first, list_out_of_memory); if(!list->size){ list->iterator = first; list->last = first; } first->next = list->first; list->first = first; list->size++; return list_success; } this code list insert first give me error "segmentation fault" when run in eclipse indigo. i've tried erase line: list->first = first; and didn't give me error. the function elementcopy works perfectly: creates new node data element , set next null . node elementcopy(list list, listelement e){ node tmp = malloc(sizeof(*tmp)); null_arg(tmp, null); tmp->data = list->copyelement(e); null_arg(tmp->data, null); tmp->next = null; return tmp; }

regex - Java Regular Expression not working (but does at Rubular) -

at rubular testing regular expression: (\d+).html test string: "/magnoliaauthor/services/services/07.html" just needed, returned "07" first match group. perfect. need regex in java environment, wrote piece of code: import java.util.regex.*; class main { public static void main (string[] args) { string jcrpath = "/magnoliaauthor/services/services/07.html"; pattern pattern = pattern.compile("(\\d+).html"); matcher matcher = pattern.matcher(jcrpath); system.out.println(matcher.group()); } } as explained here , added anothere \ regex. sadly me, when compiling , running code, following exception: java.lang.illegalstateexception: no match found does know why there aren't matches? you need apply pattern, too: pattern pattern = pattern.compile("(\\d+)\\.html"); // compiles regex matcher matcher = pattern.matcher(jcrpath); // creates matcher object if (matcher.find()) {

jquery - Image Slider Effect! Scroll on Top of Each Other -

quick question 1 know ideas how go creating effect images slide on top of each.. need pointers start me off havent got clue start.. http://denicler.eu/en/lookbooks/1 manged stack images using postion abosolute , z index cant images scroll on each other.. :s suggestions guys #lookbook img{ width: 100%; position: absolute; top: 0px; } img#image1 { z-index: 100; } img#image2 { top: 0px; z-index: 20; } img#image3 { z-index: 30; } img#image4 { z-index: 40; } img#image5 { z-index: 50; } img#image6 { z-index: 60; } img#image7 { z-index: 70; } img#image8 { z-index: 80; } img#image9 { z-index: 90; } defo need javascript in here make images fix when reaches top guys manged doesnt seem work any 1 lol $(document).ready( function() { $(window).scroll( function() { if ($(window).scrolltop() > $('#lookbook img').offset().top) $('#lookbook img').addclass('fixed'); else $('#lookbo

java - Coin game. How to make a player lose their next turn if they meet a certain criteria -

i'm making program has 4 players taking turns tossing 3 coins. first player earn 16 points wins. player earns points each time tosses coins. number of points earns equals number of heads tosses. if tosses no heads loses next turn . if flips 3 heads earns turn , tosses coins again. if tosses less 3 heads next player’s turn. player must earn 16 points win. if player has 14 points , tosses 2 heads wins if tosses n heads , goes on 16 points loses half of points , loses turn too. must have 16 points win. how player skipped next turn? each player goes in order. ex. tom, hank, hannah, tina. if hank rolls 0 heads or goes on 16 points should lose next turn making order tom, hannah, tina, tom, hank, hannah, tina. i've posted code , need figure out how edit nextplayer() method suit needs. believe logic , code did in computerstate() method correct lose_turn. appreciated. game class import java.util.random; public class game { private random randomizer; priva

debugging - 【SLOVED】Fatal exception in interrupt when booting Linux 3.3.7 on BeagleBoard -

i have tried implement new scheduling algorithm in linux kernel 3.3.7 , boot on beagleboard. however, throws errors "kernel panic - not syncing: fatal exception in interrupt". have enabled low level debugs functions , debug infos follows: [ 0.000000] ------------[ cut here ]------------ [ 0.000000] warning: @ kernel/lockdep.c:2592 do_vfp+0x8/0x20() [ 0.000000] modules linked in: [ 0.000000] [<c001c2ec>] (unwind_backtrace+0x0/0x130) [<c0045afc>] (warn_slow) [ 0.000000] [<c0045afc>] (warn_slowpath_common+0x4c/0x64) [<c0045b30>] (warn_) [ 0.000000] [<c0045b30>] (warn_slowpath_null+0x1c/0x24) [<c000f328>] (do_vfp+) [ 0.000000] ---[ end trace 1b75b31a2719ed1c ]--- [ 0.000000] error before arm_notify_die- gdem-upm [ 0.000000] internal error: oops - undefined instruction: 0 [#1] smp [ 0.000000] modules linked in: [ 0.000000] cpu: 0 tainted: g w (3.3.0-rc7-00008-g8bd3d32-dirty #5) [ 0.000000]

c# - How to unit test a thread safe queue -

i need simple data structure these requirements: it should behave queue, all enqueue operations should atomic. i have limited experience multithreading, came to: public class tickets { private concurrentqueue<uint> _tickets; public tickets(uint from, uint to) { initialize(from, to); } private readonly object _lock = new object(); public void initialize(uint from, uint to) { lock(_lock) { _tickets = new concurrentqueue<uint>(); (uint = from; <= to; i++) { _tickets.enqueue(i); } } } public uint dequeue() { uint number; if (_tickets.trydequeue(out number)) { return number; } throw new argumentexception("ticket queue empty!"); } } first question: code ok? secod question: how can unit test class (for instance 2 threads perfoming dequeue operation periodica

c# - Return from parent method inside of Action<string> -

i working inside of method performs series of validation checks , should of checks fail calls action<string> run common rejection code. set similar this: public void validationmethod() { action<string> rejectionroutine = (rejectiondescription) => { // reject description // other common code }; if (condition != requiredvalue) { rejectionroutine("condition check failed"); // have put `return` here following every failed check } // many more checks following } in system once 1 check has failed validation have no need validate rest, want run common rejection code inside action , exit method. return on next line following call rejectionroutine . i'm wondering if there's way can incorporate ability return or terminate execution of parent method inside action ? i know bit nit-picky feel better extensibility further down road if else needs add additional validation checks (they won't have con

Connect to a FTPS server within shell script -

i'm trying connect ftps (explicit tls ftp) server within shell script , i'm kinda confused. tried using regular ftp command, 534 error "policy requires ssl" , 504 "security mechanism not implemented" ftp -inuv myhost returns 504 then quote user myuser returns 534 i tried sftp "couldn't read packet: connection reset peer". damn peer making life nightmare since irc ;) sftp myuser@myhost:mydirectory/ -p21 connexion reset peer , says can't connect port 22, weird since specified port 21... thanks help there diference between ftps , sftp : sftp ftp on ssh, in case cannot use sftp. ftps ftp use ssl/tls you need ftp client manages tls, instance http://lftp.yar.ru/ (found on net)

javascript - Canvases in table, weird padding -

intro: i'm making website , want make <table/> <canvas/> es in it. what have done: i made <table/> <canvas/> es in can draw in them. <table> <tr> <td>item1</td> <td><canvas></canvas></td> </tr> <tr> <td>item2</td> <td><canvas></canvas></td> </tr> <tr> <td>item3</td> <td><canvas></canvas></td> </tr> </table> css: canvas { margin: 0; padding: 0; height: 50px; } table { margin: 0; padding: 0; width: 500px; border: 0; border-width: 0; border-spacing: 0; } tr { margin: 0; padding: 0; } td { margin: 0; padding: 0; border: 0; border-width: 0; border-spacing: 0; height: 50px; } to make canvases appear big box want them hit each other. made code example: ht

asp.net - Radgrid fire RowClick Event via Javascript or Just use EnablePostbackOnRowClick -

worth discussion what pro's / con's of firing rowclick event telerik radgrid following scenario's, work btw ;-) scenario 1: radgrid onselectedindexchanged="rg_selectedindexchanged" clientsettings.enablepostbackonrowclick="true" code behind protected void rg_selectedindexchanged(){} scenario 2: radgrid onitemcommand="rg_itemcommand" clientsettings.enablepostbackonrowclick="true" code behind protected void rg_itemcommand() { if(e.commandname == "rowclick") { } } scenario 3: radgrid onitemcommand="rg_itemcommand" clientsettings.clientevents.onrowclick="rg_rowclick" javascript function rg_rowclick(sender, eventargs) { var index = eventargs.get_itemindexhierarchical(); sender.get_mastertableview().firecommand("rowclick", index); } behind protected void rg_itemcommand() { if(e.commandname == "rowclick") { } } scenario 1 & 2: all events

opengl - GLSL Normal Mapping (Areas With 0.0 Lambert Gets Lit) -

when use model's normal , result fine ( there dark areas , lit areas , expect simple lambert diffuse shader ) but when use normal map , dark areas gets lit! i want use normal map , still correct diffuse lighting these examples here code , without normal mapping and here code uses normal map vertex shader varying vec3 normal,lightdir; attribute vec3 vertex,normalvec,tangent; attribute vec2 uv; void main(){ gl_texcoord[0] = gl_texturematrix[0] * vec4(uv,0.0,0.0); normal = normalize (gl_normalmatrix * normalvec); vec3 t = normalize (gl_normalmatrix * tangent); vec3 b = cross (normal, t); vec3 vertexposition = normalize(vec3(gl_modelviewmatrix * vec4(vertex,1.0))); vec3 v; v.x = dot (lightdir, t); v.y = dot (lightdir, b); v.z = dot (lightdir, normal); lightdir = normalize (v); lightdir = normalize(vec3(1.0,0.5,1.0) - vertexposition); gl_position = gl_modelviewprojectionmatrix*vec4(vertex,1.0); } fragment shader vec4 computediffuselight (const in vec3 direction, co

javascript - CORS on node subdomain -

i trying set api on sub domain , because of try set javascript api after web api. but unfortunally getting error after trying reach server on xmlhttprequest() . i have been trying set sub domain express server ways have found allowing cors, still same error. update : here files: app.js : var express = require('express'), http = require('http'), path = require('path'), fs = require('fs'), app = express(); app.configure(function(){ app.set('port', process.env.port || 8080); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.cookieparser('s5cret!')); 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'))); app.use(express.vhost('l

android - DVM instance creation per activity or application -

for android, each application has own instance of dvm or each activity of application has own dvm instance i.e. instance of dvm created based on application or activity? generally, each process has own dalvik vm. since each application runs in single process, activities share dalvik vm process. there more complicated scenarios (one app spread across n processes, n apps sharing 1 process), unusual in conventional android application development.

visualizing properties attributes in the webadmin interface of neo4j -

i have searched on internet not able find related this. is there way visualize properties attributes on edges(links) in neo4j webadmin interface? if yes please guide me how can that? if no please suggest me there tool or can in web interface. thanks if understand correctly, want see properties stored part of relationships. there many ways in admin web ui. for instance, in data browser, enter following cypher query see relationships in db, including properties: match ()-[r]->() return r; if know id of specific relationship interested in (let's 92), use: start r=rel(92) return r; i can give simplest answers. if have more complex question, please add more details.

writing a binary number in a txt file in matlab -

i have binary number , want save on txt file.my code : fid=fopen('rt.txt','w') fprintf(fid,'%d',00111111100000000000000000000000 ); fclose(fid); but saved value in file : 1.111111e+029 want save value same in binary format(32bit number wrote here) can me plssss 00111111100000000000000000000000 not binary number in matlab. can save string '00111111100000000000000000000000' , or if want convert binary string decimal number, can use bin2dec('00111111100000000000000000000000') . , convert decimal number binary string (which still array of characters), use dec2bin(33) .

c# - Keep the file open, don't lose data when the app crashes -

i need log info file around 1000-2000 times minute. need save info in case app crashes. currently here's i'm doing: using(streamwriter sw=new streamwriter(filename,true)) { sw.writeline(info); } this works, it's extremely slow. i'd doing this: static streamwriter sw=new streamwriter(file,true); .... public static void main(...) { ..... sw.writeline(....); } but when write code this, i'm afraid info store lost when app crashes. what can preserve info in file without having open , close time? you can call streamwriter.flush() after each write. public static void main(...) { ..... sw.writeline(....); sw.flush(); } but should use nlog or log4net !

IDLE for Python 3.3 doesn't start and does not give an error message -

i cannot start idle shortcut or start > programs > python 3.3 > idle (python gui) . when click on it, nothing happens. tried running administrator; nothing either... working fine few days ago. i can run if go c:\python 33\lib\idlelib\_main_ (however black python command line stays open , if close it, idle closes well.) i'm using 64-bit release of windows. did use othere mode file name instead of sys mode? ex. meet same issue, after check, there 1 'string.py' when test relative paths , absolute path, so, when idle start, load wrong 'string.py', after delete create myself, can work now.

deployment - Deploy my javafx 2 application on eclipse-SDK-4.2.1-win32-efx-0.8.0 -

i install eclipse-sdk-4.2.1-win32-efx-0.8.0 javafx developpement. make soe test , want deploy applicattion. firstly export ant , got ant file in projet <?xml version="1.0" encoding="utf-8" standalone="no"?> <!-- warning: eclipse auto-generated file. modifications overwritten. include user specific buildfile here, create 1 in same directory processing instruction <?eclipse.ant.import?> first entry , export buildfile again. --><project basedir="." default="build" name="newtest"> <property environment="env"/> <property name="eclipse_home" value="../../"/> <property name="debuglevel" value="source,lines,vars"/> <property name="target" value="1.7"/> <property name="source" value="1.7"/> <path id="j

flash - how to draw a 'circle' with 'dynamic angle' using action script 2? -

Image
i want have circle (maybe movieclip ) show timer change picture : and need access angle in run-time. example: function setangle(degree:number) any suggest ? give try: var circle:number = math.pi * 2; var degree:number = math.pi / 180; var radius:number = 30; var shape:movieclip = _root.createemptymovieclip("shape", _root.getnexthighestdepth()); shape._x = 100; shape._y = 100; shape._rotation = -90; function render(chunkangle:number):void { chunkangle *= degree; shape.clear(); shape.linestyle(1); shape.beginfill(0x6bb0ff); shape.lineto(radius, 0); for(var i:number = circle; > chunkangle; -= degree) { shape.lineto(math.cos(i) * radius, math.sin(i) * radius); } shape.lineto(0, 0); shape.endfill(); } render(45);

transactions - Clarification regarding journal_size_limit in SQLite -

if set journal_size_limit = 67110000 (64 mib) able to: work / commit transactions on value (somewhat unlikely) be able perform vacuum (even if database has 3 gib or more) the vacuum command works copying contents of database temporary database file , overwriting original contents of temporary file. when overwriting original, rollback journal or write-ahead log wal file used other database transaction. means when vacuuming database, as twice size of original database file required in free disk space . it's not entirely clear in documentation, , appreciate if tell me sure. the journal_size_limit not upper limit on transaction journal; upper limit inactive transaction journal. after transaction has finished, journal not needed, not deleting journal can make things faster because file system not need free data , reallocate next transaction. the purpose of setting limit size of unused journal data.

android - How can I change between language in a single IME? -

i trying make korean ime, can't find example. how can change between languages in single ime? i mean, in apple's ime, uses globe icon switch between languages. you can 1 of 2 ways. first way change keyboard layout. there's no rule says language on keyboard has match onscreen language. example of swype- allows chang language of keyboard without changing language of rest of ui, useful bilingual typers. totally internal app, need track keyboard language , show correct key layout. the other way set phone's locale. disadvantage change language used inside of app, , other apps. this, use locale locale = new locale(languagecode); locale.setdefault(locale); configuration config = new configuration(); config.locale = locale; getbasecontext().getresources().updateconfiguration(config, getbasecontext().getresources().getdisplaymetrics());

jquery - Can bootstrap modal dialog overlay another dialog? -

Image
<button class="btn" onclick="$('#firstmodal').modal('show');">first</button> <!-- modal --> <div id="firstmodal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="mymodallabel" aria-hidden="true"> <div class="modal-body"> <button class="btn" onclick="$('#secondmodal').modal('show');">second</button> </div> </div> <!-- modal --> <div id="secondmodal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="mymodallabel" aria-hidden="true"> <div class="modal-body"> error message goes here. </div> </div> everything works fine; problem first dialog displayed on overlay of second dialog. how can fix this? this how looks now:

How to get som jQuery Mobile Features in WordPress -

i'm trying integrate features found jquery mobile wordpress plugin. not targeting mobile devices specifically, of features in framework. problem having seems jquery mobile css taking on native wp css , changing styling. also, of jquery mobile features don't work properly. use wp_register_style , wp_enqueue_style load styles wp_enqueue_script load script this: wp_register_style( 'jquery-mobile-style', 'http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css'); wp_register_style( 'jquery-mobile-style', 'http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css'); wp_enqueue_script('jquery'); wp_enqueue_script('jq-script', 'http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js'); i working panel. inject panel code page this: jquery(document).ready(function($){ var s = '<div data-role="panel" id="mypanel" data-display="ove

wpf - Drawing with DirectX over a PowerPoint slideshow -

i need able draw directx content on powerpoint slideshow being played using powerpoint viewer in .net application using microsoft interop api. far have come idea of displaying wpf window full transparency on slideshow have rewrite drawing logic in wpf(which written , working fine directx), not practical me. way take snapshot of powerpoint window , draw in directx cost pn performance needs done @ least 30 times second. not found way draw texture keeping background transparent in directx. can suggest me better way so? powerpoint api gave way so? can work powerpoint 2013 if there support. suggestion great. in advance.

xcode - Dynamic cells vs static? -

i want create table view text fields in cells editable user. filling out form. want text fields have placeholders etc, , when tapping on cell want keyboard show edit text fields. table view in tab view. wanted use storyboards, , wanted know best project pick iphone , ipad, , wether use static cells or prototype cells best choice app? forward suggestions! static cells easier can create iboutlets cell directly in view controller class. down side not dynamic (big surprise) can hide , show views in cell. can not hide , show whole cells or sections. if form fields fixed use static if form need change need use dynamic cells. if use dynamic cells need subclass uitableviewcell create iboutlets.

jax ws - Using WSGEN to combine WSDLS and XSDS into 1 WSDL -

so working on project had had service definition. augmented add methods, however, when run following... "c:\program files\ibm\websphere\appserver\bin\wsgen.bat" -verbose -keep -cp . com.me.service.serviceclass -d c:\tmp\19 -wsdl it generates 2 wsdls , 4 xsds. if try loading serviceclass.wsdl usng soap ui (in folder itself) complains missing other wsdls , xsd documents. is there way can generate 1 wsdl file houses of information?

c# - How to make Distinct... More distinct? -

Image
ok, aside silly title. have query pulling distinct values including departmentid column instead of departmentname column distinct. makes me causes duplicates. viewbag.departmentlist = docs.select(m => new selectlistitem { value = sqlfunctions.stringconvert((double)m.departmentid).trim(), text = m.departmentname }) .distinct(); // fill viewbag unique list of 'department's table. here docs has inside it: image if helps @ all, departmentid primary key. departmentid 1 point same name , on. you can use iequalitycomparer class mycomparer<t> : iequalitycomparer<t> t : selectlistitem { public bool equals(t x, t y) { return x.value == y.value ; } public int gethashcode(t obj) { return obj.id.gethashcode(); } } then code viewbag.departmentlist = docs.select(m => new selectlistitem { value = sqlfunctions.str

c# - Why does ApiController require explicit Http verbs on methods? -

i'm using apicontroller . struggle understand why apicontrollers differ controllers in ways. take public class questioncommentcontroller : apicontroller { questioncommentcrud crud = new questioncommentcrud(); // api/questioncomment/5 [httpget] public string read(int id) i'm accustomed controller types allow me create method without specifying legal verbs via attributes: public class questioncommentcontroller : controller { questioncommentcrud crud = new questioncommentcrud(); // questioncomment/5 public string read(int id) in latter case can perform get/post without specifying httpgetattribute . find behavior confusing few reasons: there's 2 httpget : system.web.http.httpget , system.web.mvc.httpget system.web.http.httpge t required, system.web.mvc.httpget not required requests apicontroller requests require unique route /api/controller... controller 's allows me fall pit of success. newer apicontroller requi

viewmodel - ASP.NET MVC - How exactly to use View Models -

let's have page allows editing of user's details, have viewmodel this: public class userviewmodel { public string username { get; set; } public string password { get; set; } public int managerid { get; set; } public string category { get; set; } } so on edituser action can have passed model binder , can map domain model: public actionresult edituser(userviewmodel user) { ... however, page displays form needs details such list of managers , categories provide dropdowns fields. might display list of other users in sidebar can switch between different users you're editing. so have view model: public class viewuserviewmodel { public userviewmodel editinguser { get; set; } public ienumerable<selectlistitem> managers { get; set; } public ienumerable<selectlistitem> categories { get; set; } public ienumerable<selectlistitem> allusers { get; set; } } is correct way it? both view models? if so, there naming c

matlab - Weighted sampling with 2 vectors -

(1) have 2 column vectors. eg. x = [283167.778 *289387.207 289705.322] y = [9121643.314 9098348.666* 9099832.621] (2) i'd make weighted random sampling using these vectors: when i'll select element 289387.207 in vector x, i'll choose element 9098348.666 in vector y. (3) also, have weighted w vector each element in vector x , y. how can implement in matlab? thanks! for random selection: sel_idx= randi(3); outputx = x(sel_idx); outputy = y(sel_idx); for random weighing: w = rand(size(x)); w = w./sum(w); % normalize outputx = w(:)'*x(:); outputy = w(:)'*y(:);

Photoswipe close gallery button code -

i have tried close photoswipe screen gallery using history.go(-1); takes me previous screen gallery was. how can close photoswipe screen gallery using code staying in page call gallery? in advance. i managed line: window.code.photoswipe.activeinstances[0].instance.hide();

concurrency - How to add callbacks to Future in Scala? -

i saw example here : val fut = future { ... // body function } // body function starts here fut oncomplete { ... // callback } looks may add callback after completion of body function. still invoked ? anyway, prefer add callbacks future before function starts running. make sense ? how can ? if want control point of execution of future, chain promise . import scala.concurrent._ import executioncontext.implicits.global val initialpromise = promise[unit] // add computations val fut = initialpromise.future map { _ => println("my future") } // register callbacks fut oncomplete { _ => println("my callback") } // run initialpromise.success() using other unit allows feed computation arbitrary values.

multithreading - C# Multithreaded Mass Parse -

i'm sort of making 'web parser', except 1 website, parsing many different pages @ 1 time. currently, there may 300,000 pages need parse, in relatively fast manner (i'm grabbing tiny amount of information doesn't take long go through, every page takes ~3 seconds max on network). of course, 900,000 seconds days = 10 days, , terrible performance. reduce couple of hours @ most, i'm reasonable time amount of requests, still needs 'fast'. know can't 300,000 @ 1 time, or website block of requests, there have few seconds delay in between each , every request. i have processing in single foreach loop, not taking advantage of multithreading ever, know take advantage of it, i'm not sure path should take whether threadpools, or type of threading system or design. basically, i'm looking point me in right direction of efficiency using multithreading can ease time take parse many pages on end, sort of system or structure threading. thanks

asp.net mvc - mvc having issues consuming web service -

i created web service , published iis. consume web service mvc app. i'm trying call controller, added service reference mvc project, i'm not able create service1 object call web service. i'm new web services , mvc. can see issues config files? here config file web service: <system.servicemodel> <bindings> <wshttpbinding> <binding name="nosecurityplusrm"> <reliablesession enabled="true" /> <security mode="none" /> </binding> </wshttpbinding> </bindings> <client> <endpoint binding="wshttpbinding" bindingconfiguration="" contract="helloworldpracticeservice.iservice1" name="service1endpoint" /> </client> <services> <service name="helloworldpracticeservice.service1"> <endpoint address="" binding="wshttpbinding" bindingconfiguration="nosecur

jquery - Using map to get all but last in data array -

the following iterates on <th> elements , creates array of text, each array entry surrounded <span> tags. but, don't ever need content of last <th> element - there way omit function? var newcontent = $('#tablehead').find('th').map(function(){ return '<span>' + $(this).text() + '</span>'; }).get(); try using .slice(0, -1) var newcontent = $('#tablehead').find('th').slice(0, -1).map(function(){ return '<span>' + $(this).text() + '</span>'; }).get(); demo: http://jsfiddle.net/r6cpx/

git - How to .gitignore files recursively -

i'm trying avoid following pattern in .gitignore file. myprject/webapp/scripts/special/*.js myprject/webapp/scripts/special/*/*.js myprject/webapp/scripts/special/*/*/*.js myprject/webapp/scripts/special/*/*/*/*.js myprject/webapp/scripts/special/*/*/*/*/*.js myprject/webapp/scripts/special/*/*/*/*/*/*.js myprject/webapp/scripts/special/*/*/*/*/*/*/*.js we tried: myprject/webapp/scripts/special/**.js myprject/webapp/scripts/special/**/*.js this didn't work. git on windows. there more concise way without repeating things? as of git 1.8.2, this: myprject/webapp/scripts/special/**/*.js should work according this answer . works me in windows 7 using sourcetree 1.6.12.0 , version of git installs (1.8.4-preview20130916). to gitignore every file , folder under directory recursively: myprject/webapp/scripts/special/**

Adding/Removing border to TR using JQuery -

please see following jsfiddle: jsfiddle link my jquery: $('.tr1').addclass('addborder'); $('.tr2').removeclass('removeborder'); $('#bname').click(function() { $('.tr1').addclass('addborder'); $('.tr2').addclass('removeborder'); }); $('#bspecialty').click(function() { $('.tr2').addclass('addborder'); $('.tr1').addclass('removeborder'); }); it suppose make name row have double blue border , based on user selection radio button should make row have blue border , remove border row not selected. it's not working reason. i tried toggleclass(); removes existing class, won't work user should able click on same radio button multiple times , class should not change. should change if other radio button clicked. you should add border table cell not row. don't need add 2 different class.. instead can addclass adds border , removeclass

How do you determine the input type in Dart? -

i'd find radio buttons on form , leave other input types alone. code looks this: form.queryall("select, input").foreach((element el) { if (el radiobuttoninputelement) { print ('got radio button'); } else { print ('got other input type'); } } this results in input types other select being identified radio buttons. in fact, if @ el in then branch ("got radio button"), reported inputelement . you write query selector return radio buttons. list<radiobuttoninputelement> list = element.queryselectorall("input[type='radio']");

position - Converting mouse coordinates to label coordinates in Qt -

i'm in trouble such issue: need select area rect on label, i'm using qrubberband this, there 1 problem: need know coordinates of current rect on label, i'm in trouble it, because mouseevent->pos() give coordinates starts top left corner on mainwindow border, i've rotate standard coords on label (from top left bottom left corner, paint them usually). anybody knows how can translation? qpoint mappedpos = mylabel->mapfromparent(mywindow, mouseevent->pos()); also, qtransform provides number of map() functions should able point in rotated coordinates well. see: qwidget::mapfromparent() qtransform::map()

ruby on rails - Convert query from SQL to ActiveRecord -

how can same result using activerecord? select categories.* categories inner join levels on levels.id = categories.level_id levels.description <= "medium" it's hard precise without more details, should that: category.joins(:level).where('levels.description <= "medium"') i think should trick: category.joins(:level).where(level.arel_table[:description].lteq('medium'))

java - Proguard Error / Dalvik Error 1 When Signing Android App -

before start, wanted hi , reading this, i've had problem quite bit , appreciated! i've been working on project time, , has been testing fine. run , works on android tablet, no errors or anything. when tried release , go "android tools -> export signed application", returned dalvik error 1 . i tried enabling proguard, , left lot of unreferenced classes. such as: [2013-05-14 15:40:24 - mxltestapp] proguard returned error code 1. see console [2013-05-14 15:40:24 - mxltestapp] note: there 439 duplicate class definitions. [2013-05-14 15:40:24 - mxltestapp] warning: javax.ejb.ejbhome: can't find superclass or interface java.rmi.remote [2013-05-14 15:40:24 - mxltestapp] warning: javax.ejb.ejbobject: can't find superclass or interface java.rmi.remote [2013-05-14 15:40:24 - mxltestapp] warning: twitter4j.management.apistatisticsopenmbean: can't find superclass or interface javax.management.dynamicmbean [2013-05-14 15:40:24 - mxltestapp] warning: librar