Posts

Showing posts from May, 2014

c# - String to byte[] and vice versa? -

possible duplicate: .net string byte array c# how convert string byte[] array , vice versa? need strings stored in binary storage. please show example in both directions. , 1 more thing: each string maybe bigger 90kb. if want use utf-8 encoding: // string byte[] byte[] bytes = encoding.utf8.getbytes(somestring); // byte[] string string anotherstring = encoding.utf8.getstring(bytes);

vb.net - Implementing timer states(Available,Busy,Away etc) in a chat application vb8 -

i developing chat application , trying include: various states, msn does, available, busy , away. if user doesn't touch keyboard 1 minute, state of user isto changed away. or similar these. i need program able play sound while running. can community aid me resources me implement , perhaps code if has experience similar application? to manage inactive state, can use timer paired global keyboard hook (the article c#, can translate vb.net). each time application receives keyboard message, timer reset inactivity interval. if timer runs out, can set status of application inactive.

Where to find BitTorrent source code? -

i have looked , looked , cannot seem find source code anywhere. every link find points official bittorrent page, slashdot says took source code down in 2007. believe incredibly widespread, open-source technology not found anywhere except in applications utorrent or transmission? there has place download current source code bittorrent. can point me magical place? fyi archived version of original bittorrent application (also known mainline, particularly developing other bt clients) available here, 3.9.1. http://download.bittorrent.com/dl/archive/ for example, can confirm bittorrent-3.9.1-1.noarch.rpm contains python source. rpm format can opened using common archive utilities. on osx, used keka unarchive cpio, keka again unarchive file structure (i can see python scripts common bt tasks under usr/bin/ , various code under usr/lib/python2.3/site-packages/bittorrent ) when switched utorrent codebase, code became closed. mentioned others, there many open source alterna

jsp - Empty EntityManager in Java EE bean on JBoss 5.1 -

i'm newbie in java ee. first project i'm trying , have problem can't solve. i've created 3 projects: slowka-beans (ejb), slowka-persistance (jpa) , slowka-web(jsf). after deploying them can't access persistence unit - entitymanager null. works fine - can create beans, inside them instantiate entity classes , show them on jsf page. how can store them in db? have mysql database configured on jboss site. the code have looks following: languagesmanager.java (in slowka-beans) @stateless public class languagesmanager implements languagesmanagerlocal { @persistencecontext(unitname="slowka-persistance") private entitymanager em; public languagesmanager() { system.out.println("languagesmanagerbean constructor"); } public string getworking() { if(em == null) { system.out.println("not working..."); return "not working..."; } else { system.out.pri

asp.net mvc - When I try to debug the project all the test auto run. How I stop this -

when debug project viewing , fixing design issue see test running well. how stop tests don't run while working on ui project? if have testing project (or project matter) in solution , don't want start up, right-click on solution in solution explorer , choose properties. click on common properties->startup project. you'll see "multiple startup projects" selected. if choose "none" in drop-down in action column test project(s), should stop them starting when debug solution. this vs2008 2005 , 2010 should similar.

validation - Rails 3: how to update only 1 attribute? -

how can update 1 attribute in database without having insert validations? e.g: i have password presence = true. when want edit database, have pass password. want edit 1 field without passing password. i've tried update_attribute, merge, none works. thanks. donald edit: validation, works on console, still puts password there. here's validation: def password_validation_required? encrypted_password.blank? || !@password.blank? end and when submit form without password field, on console: (it puts blank on encrypted_password field) sql (0.3ms) update "wsps" set "about" = 'gfg', "encrypted_password" = 'fcf538f9a588befec4ee2567754a42f05b3cd75f24919d49530426786491c3e1', "updated_at" = '2010-11-30 23:56:45.594168' ("wsps"."id" = 4) maybe controller isn't correct? have this: if @wsp.update_attributes(params[:wsp]) my form: <%= form_for(@wsp, :html => { :

binding - WCF IncludeExceptionDetailInFaults programmatically? -

i have following in config file, , trying find equivalent bits in c#, have service configured programmatically. class/property/method should for? thanks. <behaviors> <servicebehaviors> <behavior name="servicegatewaybehavior"> <servicemetadata httpgetenabled="true"/> <servicedebug includeexceptiondetailinfaults="true"/> </behavior> </servicebehaviors> </behaviors> if want in cases, use servicebehaviorattribute : [servicebehavior(includeexceptiondetailinfaults=true)] class myserviceimplementation : imyservice { /// ... } if want in cases, determined @ runtime.... //////////////////////////////////// // must include these @ top of file using system.servicemodel; using system.servicemodel.description; // ... ///////////////////////////////////////////////////////////// // inside whichever function initializes service host //

jquery - Passing Javascript Parameters Locally on IE -

sorry if terminology off. : ) "windows cannot find file" when browse locally. things messed on number 2. see below: 1: first click on link below <a href="page.html?parameter_here">test link</a> 2: searches file: page.html 3: targeted page detects whether or not "parameter_here" exists: var strreturn = ""; var strhref = location.href; var strquerystring = strhref.substr(strhref.indexof("?")).tolowercase(); var strquerystring2 = strquerystring.split('?'); if (strquerystring2[1] === somenames[x][1]) { alert(somenames[x][0]); }

objective c - After upgrading to xcode 3.2.5 can't connect to the network -

i use c++ library in application connects network (i suppose uses sockets). i've been using months , using xcode 3.2.4. now, had great idea of upgrading xcode 3.2.5, , found out application crashing error: if encountering problem running simulator binary within gdb, make sure 'set start-with-shell off' first. 3.2.5 ok, couldn't solve it, went 3.2.4, suggested somewhere. application not crashing anymore, library can't connect anymore network. tried rebuild (i didn't write library have sources) , use new library, nothing. still library can't connect network. tried every simulator. any idea there wrong , how may able solve this? can somehow delete manually related xcode , simulator , try start on again? thanks! i had similar problem version of libcurl built earlier os. solution rebuild library under ios 4.2 eliminate $unix2003 symbol decorations. (i wrote full details @ http://www.creativealgorithms.com/blog/content/building-libcurl-ios-42

php - how to execute a mysql query each time tail -f shows up a new line from a log file in linux -

i'm trying monitor log file tail -f , parse extract data grep , pass data mysql query. passing each new line detected tailf php script, don't know how that.. or simulate tailf php directly, how monitor file changes php? think having while , size , remember last position, seek , read till difference right? can give hints on what's better use? or simpler? i've heard named pipes solution don't know how grab data there logger nginx way.. thank you in shell can like: tail -f file.log|grep whatever-you-want|while read line; echo $line done just change line echo $line want - can call php or whatever want in line, $line the line tail/grep combination. take @ these soq more info: use bash read file , execute command words extracted bash script read file

firefox - How to let a sidebar execute javascript code from the main document? -

Image
i'm working on firefox sidebar loads webpage in main document. i'd call javascript function main document in response of pushed button on sidebar. how can sidebar cause main document execute 1 of javascript functions? far, i'm having variable containing javascript code, how can executed? (in context of loaded website?) dr.molle correct answer love working examples. console.log("opening new page @ http://example.com"); page = window.open('http://example.com'); console.log(page); console.log("calling alert on opened page"); page.alert("i opened , previous windows js called me!!!!"); console.log("called alert"); example page => [removed. see update below] results: note: had allow popups demo code work issue question. ; ) update: so doing page.alert() worked because didn't have wait page finish loading work. in order able call function script on loaded page have ensure script has finished

atl - CryptoAPI - export/import of keys between different versions of Windows -

on win 2003 32 bit, export privatekeyblob cryptexportkey call (dwflags=0). attempt import key blob on win server 2008 64 bit 64 bit executable, call cryptimportkey fails nte_bad_data . in both cases crypto provider initialized call cryptacquirecontext(&hprov, szcontainer, null, prov_rsa_aes, crypt_machine_keyset) the passwords export/import match. public key based on cryptderivekey of md5 hash of passwords identical in plain text represetnation. i'm not sure whether public keys end being equal in 2 systems. are different types of systems (win 2003 32 bit vs win 2008 64 bit) expected cause of failure, , there way of getting work? as conjectured public keys produced atl's ccryptderivedkey not equal on 2 systems. default settings of ccryptderivedkey must different in 2 versions of atl library. since had access both source , destination servers, reexported , imported key in consistent manner - specifying algorithm, key size , presence of

c - Simple question on threads and variable copying (with no need of syncing) -

if want pass char* various threads via pthread_create() , want them work independently what's simplest way safely? i notice unstable behavior if pseudo code: func1() { // part of loop create var.. func2(var); } func2(char* var) { // spawn thread pthread_create(.....,&func3,(void*)var); } func3(void* var) { work var // unstable behavior } there's no need data communication, threads var , ignore rest of program doing. work on var got. you don't show details of "create var..." part of program, christopher hunt correctly answered, if isn't declared static, go away when func1() returns. worse that, said "no need data communication" , if creating var once , accessing multiple threads having "data communication" whether mean or not (and coordination of parallel access var you). if want each thread have own copy can mess without disturbing other threads, duplicate before each call pthread_create().

How to incorporate C++ code in Objective-C project? -

i'd use c++ code in xcode project don't understand either language enough yet know how proceed. i've been @ obj-c while , have app on app store, still learning... the code want use has 2 files same name , .h , .c extensions. think correspond .h , .m files in obj-c, lack @interface , @implementation structure i'm familiar with. , there's main.c don't know with. looks it's main program - should try pull code out primary viewcontroller ? maybe link tutorial? maybe question's vague... fyi - code want use calculating sunrise , sunset times, , located at: http://www.risacher.org/sunwait/ thanks! edit: thanks suggestions - have more learning before this. made progress... in main.c (seems weird have file called that...) there function(?) this: int mainfunction(int argc, char *argv[]) { // bunch of function-y stuff } it called main changed mainfunction rid of error. compiles , can call compiler warns me thus: warning: implic

streaming - Is it possible to inject IDv3 into MP3 stream? -

i'd making relay audio stream server (like shoutcast relaying customization) in php. possible dynamicly add idv3 tag's every specified pack of data (maybe every second - every 64kb)? if it`s possible how it? idv3 tags occur @ beginning of mp3 mp3 series of frames due way it's possible cut them mp3splt without re-encoding stream idv3 tags followed mp3 data , repeat in same format next part of stream clearly i'm ignoring lot of details

XSLT combine multiple nodes into single node -

<rowset> <row> <location_long_desc>sydney office</location_long_desc> <location_code>sydney</location_code> <daypart_long_desc>peak night</daypart_long_desc> <daypart_code>peanig</daypart_code> <w_20050703_dlr>30849.3</w_20050703_dlr> <w_20050703_spots>9</w_20050703_spots> <w_20050710_dlr>16.35</w_20050710_dlr> <w_20050710_spots>19</w_20050710_spots> </row> </rowset> so, have xml need convert w_ nodes new single node. using xsl <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="node()"> <xsl:copy> <xsl:apply-templates select="node()"/> </xsl:copy> </xsl:template> <xsl:template match="*

c++ - Absolutely deathly wxWidgets Pain -

i've never used wxwidgets before, , i'd love try out, i've run million problems getting started. i using wxwidgets 2.9.1 on visual studio 2010. i've gone through batch build build every project in every configuration. i've added includes , lib references project. when try compile simple "hello, world!" program, error: error 1 error c1083: cannot open include file: '../../../lib/vc_lib/msw/wx/setup.h': no such file or directory i checked lib/vc_lib folder, , indeed, there no "msw" folder found. there "mswu", "mswud", "mswunivu" , "mswunivd". anyone know what's going on? :/ first off, might reconsider wx. used it, invested lot of time , code products based on it, , turned out not hot. the problem you're having due not having unicode flags turned on having unicode version. apparently anyway. go properties , change character set unicode. it's on general pro

c++ - Basic syntax question for shared_ptr -

i new shared_ptr. have few questions regarding syntax of c++0x shared_ptr below: //first question shared_ptr<classa>ptr(new classa()); //works shared_ptr<classa>ptr; ptr = ?? //how create new object assign shared pointer? //second question shared_ptr<classa>ptr2; //could tested null if statement below shared_ptr<classa> ptr3(new classa()); ptr3 = ?? //how assign null again ptr3 if statement below becomes true? if(!ptr3) cout << "ptr equals null"; shared_ptr<classa> ptr; ptr = shared_ptr<classa>(new classa(params)); // or: ptr.reset(new classa(params)); // or better: ptr = make_shared<classa>(params); ptr3 = shared_ptr<classa>(); // or ptr3.reset(); edit: summarize why make_shared preferred explicit call new : some (all?) implementation use 1 memory allocation object constructed , counter/deleter. increases performance. it's exception safe, consider function taking 2 shared_ptrs: f(shared_ptr

C# + Visio 2007 integration -

i using visio 2007 in order draw organization chart. working fine, have problem on how access , set properties of shape object in below namespace microsoft.office.interop.visio.shape any appreciated. it may not others too.. :) imports microsoft.office.interop.visio public class visiomain dim currentstencil document dim currentpage page private sub visiomain_load(byval sender object, byval e system.eventargs) handles me.load currentpage = dc.document.pages(1) setlandscape(currentpage) currentstencil = dc.document.application.documents.openex("rack-mounted equipment (us units).vss", visopensaveargs.visopendocked) dim stencilwindow window stencilwindow = currentpage.document.openstencilwindow stencilwindow.activate() end sub private sub button5_click(byval sender system.object, byval e system.eventargs) handles button5.click ''code individual property of shape...........! each objshape microsoft.office.interop.vi

javascript - Possible in HTML to make IE more forgiving of markup mistakes like extraneous tags? -

i defined jquery tabs element this: <div id="tabs"> <ul> <li><a href="#tabs-1">nunc tincidunt</a></li> <li><a href="#tabs-2">proin dolor</a></li> <li><a href="#tabs-3">aenean lacinia</a></li> </ul> <div id="tabs-1"> <p>proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. curabitur nec arcu. donec sollicitudin mi sit amet mauris. nam elementum quam ullamcorper ante. etiam aliquet massa et lorem. mauris dapibus lacus auctor risus. aenean tempor ullamcorper leo. vivamus sed magna quis ligula eleifend adipiscing. duis orci. aliquam sodales tortor vitae ipsum. aliquam nulla. duis aliquam molestie erat. ut et mauris vel pede varius sollicitudin. sed ut dolor nec orci tincidunt interdum. phasellus ipsum. nunc tristique tempus lectus.</p>

iphone - How to see logs from two different devices with "building and debugging" -

first time doing 2 player blue tooth stuff, , having issues. able see logs of both devices, rather one is there trick building , running on 2 devices in xcode? can't see anywhere. cheers have looked in organizer? can see device logs in there. in xcode -> window -> organizer. select device , click device log's tab. experience multiplayer bluetooth using 1 device , using xcode debugging another.

java - System.UnexpectedException: Got an unexpected error in callout : null -

i calling apex web service flex using execute() method , iam passing objects parameter , getting error this error (com.salesforce.results::fault)#0 context = (null) detail = (null) faultcode = "soapenv:client" faultstring = "system.unexpectedexception: got unexpected error in callout : null. contact support error id: 1835527547-14083 (-677061709) how solve .... any time see text contact support , error id, bug in salefsorce's code , there's nothing can work around it. the best can contact support team , log ticket. lot of times can find suitable workaround that'll work in meantime.

Repeater Control asp.net -

i have repeater control displays playlist users, control can hold 1000 or more songs. great feature, using jquery client side sorting, has limitations. implemented server side sorting works great, issue seeing when playlist long takes second or 2 before postback , sorting started. i have watched actions in firebug , done research , understand databound values not preserved, makes sence. question is, when watching in firebug, looks repeater control removes items in collection before starts postback? true have others experienced this? the repeater control ceases exist entirely between postbacks. repeater control called existance when make page request. populated, etc. rendered browser. once done, asp.net delete objects on page (or rather garbage collector them when required. either way, can't them more). when postback happens has re-create entire repeater on again. there mechanisms, such viewstate, try make seamless possible (i.e. recreating controls left them in

c++11 - How to simplify the tedious parameter declaration of lambdas in C++0x? -

the simplest code best asker: #include <vector> #include <algorithm> using namespace std; int main() { vector<int> coll; for_each(coll.begin(), coll.end(), [](vector<int>::value_type n) -> void {}); return 0; } here, vector<int>::value_type n tedious. want have auto-like utility deduce right type of n automatically; following: for_each(coll.begin(), coll.end(), [](auto_type n) -> void {}); to more greedy, want auto_type take argument used deduce right type of n. argument can (smart) pointer or reference container, or iterator of container. dear gurus, how implement that? you don't have declare void return in function. use decltype, like, decltype(coll[0]) . std::for_each(coll.begin(), coll.end(), [](decltype(coll[0]) value) { std::cout << value; }); edit: template<typename t> auto type(t&& t) -> decltype(*std::forward<t>(t).begin()) { return *t.begin(); } std::for_e

Set System propery to Null in Java -

in unit tests need set "workingdir" system property null. but can not somesing this, because give me nullpointerexception: system.setproperty("workingdir", null); how can it? you can't set property have actual null value - can clear it, this: system.clearproperty("workingdir");

Replicating Spinrite Animation Effect in C -

i replicate spinner effect spinrite displays in upper-right corner of screen indicate it's still running , hasn't frozen. can see example of here @ 2:18 - http://youtu.be/xrmdwvj5crm we debate efficacy of spinrite until cows come home there's no denying has decent ui considering runs on. i'll replicating effect in c on arm platform i'm looking general advice rather code, such how increment steps of animation. thanks in advance. that's old tech there, looks gibson has updated ui little. remember spinner being /\|- characters... digress. :) that in text mode , done hooking timer interrupt in dos , drawing every other tick of timer. a standard dos timer ticked every 55 milliseconds. you can draw directly screen in dos on x86 writing pointer 0xa0000 using goofy extended dos character set. (note old memory, it's been 15+ years since i've done of stuff :) in other words, draw letter 'a' @ first row/column of screen, you'

android - ProgressDialog loading animation stuck/frozen after 2-3 spins -

i've been trying set-up progressdialog (which works), seems freeze (the animation of little wheel thing) after 2-3 spins. data load, , progresssdialog gets dismissed - so, works fine, other fact freezes after 2-3 spins. here's snip of code: // setting loader summaryloader = progressdialog.show(summaryview.this, "", "loading summary...", false, true); // settings , starting helper thread that's going load summery data thread t = new thread() { @override public void run() { _populatesummary(); } }; t.start(); i'm running on entourage edge running android 1.6. i did read issues 1.6 , animation freezing, thought i'd give shot , see if here has ideas. i think though runs on thread still takes considerable amount of cpu usage.you can try setting priority thread before start , see if solves problem though have impact on execution speed. t.setpriority(thread.min_priority); else try using async task android async tas

java me - What simulator is used for the nokia 7230 phone? -

what simulator used nokia 7230 phone testing midp applications? basically nokia 7230 s40 series mobile. more info see link, nokia 7230

c# - Raised exception in the case of concurrent file access with StreamReader -

i found post talking handling concurrent file access streamwriter . the problem answers not manage scenario file being accessed multiple processes. let's tell shortly : i have multiple applications i need centralised logging system in database if database fail, need fallback on file system log there known concurrency scenario, multiple applications (processes) try write in file. can managed re-attempt writing after short delay. don't want ot reattempt if it's security error or filename syntax error. the code here : // true if access error occured bool accesserror = false; // number fo writing attemps int attempts = 0; { try { // open file using (streamwriter file = new streamwriter(filename, true)) { // write line file.writeline(log); // success result = true; } } /////////////// access errors /////////////// catch (argumentexception) { ac

Java: generic enum in method parameter -

correspondig following question: java: enum parameter in method i know, how can format code require enums generically. foo.java public enum foo { a(1), b(2); } bar.java public class bar { public bar(generic enum); } later on i'll have more enum classes "foo", can still create bar containing kind of enum class. have "jdk1.6.0_20" way... see methods in enumset reference, e.g. public static <e extends enum<e>> enumset<e> of(e e) (this method returns enumset 1 element given enum element e) so generic bounds need are: <e extends enum<e>> actually, make bar generic: public class bar<e extends enum<e>> { private final e item; public e getitem(){ return item; } public bar(final e item){ this.item = item; } } you may add factory method from , with etc. public static <e2 extends enum<e2>> bar<e2> with(e2 item){ retur

mod rewrite - More flexible SEO URLs in OSCommerce? -

new oscommerce user. i've been fiddling around chemo's ultimate seo add-on last few days. i've got working (minus 1 bizarre redirect loop category pages?) i'm little disappointed in limited options formatting urls. i'm seeing: http://www.website.com/category-awesomeproduct-p-1735.html when we'd more in line with: http://www.website.com/category/awesomeproduct what options? out of luck? i fear stock url parameters rigidly defined , there's no way hide less friendly ones. after researching quite awhile, , receiving no answers here, believe answer is: no the view controller expects data , can't omitted, customizations installed.

tsql - Lucene.Net Underscores causing token split -

i've scripted mssqlserver databases tables,views , stored procedures directory structure indexing lucene.net. of table, view , procedure names contain underscores. i use standardanalyzer. if query table named tir_ invoicebtnwtn01, example, recieve hits tir , invoicebtnwtn01, rather tir _invoicebtnwtn01. i think issue tokenizer splitting on _ (underscore) since punctuation. is there (simple) way remove underscores punctuation list or there analyzer should using sql , programming languages? yes, standardanalyzer splits on underscore. whitespaceanalyzer not. note can use perfieldanalyzerwrapper use different analyzers each field - might want keep of standard analyzer's functionality except table/column name. whitespaceanalyzer whitespace splitting though. won't lowercase tokens, example. might want make own analyzer combines whitespacetokenizer , lowercasefilter, or lowercasetokenizer. edit: simple custom analyzer (in c#, can translate java pretty easily

how to get text from a div in an iframe with jquery -

i have page uses iframe ajax style file upload. when upload completes i'm writing div iframe status of whether file uploaded or not. iframe not visible , i'm using target form. works fine except can't figure out how use jquery text within div. iframe has id of upload_target , div in iframe has id of uploadstatus. thought following work doesn't. know how can this? thanks. $("#upload_target").load(function () { alert($("#upload_target> #uploadstatus").text()); }); make sure iframe has name attribute set upload_target well, , use alert($("#uploadstatus", frames['upload_target'].document).text());

c# - Silverlight validation. Problem with email validation -

i have text box , want validate valid email in textbox on button "save" click. but standard validation have strange behaviour. when print new email error , wery annoing. want show error after button click , text box must become valid if got focus. there standard way in model-view-viewmodel. the default behavior changing bound value in textbox via lostfocus . need change updatesourcetrigger explicit. <textbox name="mytextbox" text="{binding path=firstname, updatesourcetrigger=explicit}" /> then in code behind have explicitly call updatesource via button click handler. bindingexpression = mytextbox.getbindingexpression(textbox.textproperty); be.updatesource();

MvcContrib Grid with Razor -

i have intersting question. i'm going use razor in asp.net mvc site. need create grid column render action. how can it? here code: @{ html.grid(model).columns(column => { column.for(x => x.deviceid).named("action").action(data => { @* place here? *@ }); } } i cannot close code block '}' because close body of inline expression: column.for(x => x.deviceid).named("action").action(data => {} @* place here? *@ @{} so, possible solve problem? solved. can use this: column.for(x => html.partial("mygridbuttons", x)).named("action");

C# Code Analyzer for C, C#, C++ and Java. -

please there tools available parse source code enumerate class , function dependency project (c, c#, c++ or java) , save in doc, xml or other format? thank you. use reflector: http://www.red-gate.com/products/reflector/ with add-in: http://code.google.com/p/xmi4dotnet/

javascript - how to handle copy/paste in iframe design mode? -

how can handle copy/paste events on iframe in design mode? need change text (reformat it, add proper tags, etc) before copy/paste. unless pop dialog containing area user paste into, need in hacky way involving redirecting paste off-screen div. i've written on stack overflow before: get html clipboard in javascript

javascript - pop on page close? -

this question has answer here: open custom popup on browser window/tab close 4 answers in effort reduce shopping cart abandonment, pop window offering 5% coupon code when user goes close shopping cart page. i've seen these, , yes can annoying, can't seem locate code doing this. there window event called onbeforeunload. can return string in event , echo string user , prevent window closing. can like: window.onbeforeunload = function( ) { return 'are sure want close window?'; }

c# - How to cache items within a filterAttribute -

how use caching maybe attribute along? not having make lot of calls container.getservice , getting user. put caching place cache identity key , planner value , up? public class adminsandprogrammanagersonlyattribute : filterattribute, iauthorizationfilter { public adminsandprogrammanagersonlyattribute() { order = 1; //must come after authenticateattribute } public void onauthorization(authorizationcontext filtercontext) { var userrepository = globalapplication.container.getservice<irepository<projectplannerinfo>>(); var identity = filtercontext.httpcontext.user.identity; var planner = userrepository.getall().whereemailis(identity.name); if (!planner.isinrole("db admin") || planner.programmanager == 1) { filtercontext.result = new redirecttorouteresult("error", new routevaluedictionary(new { controller = "error", action = "insufficientprivileges&quo

android - Populate BaseAdapter from web -

i've json array this: [{"usename":"user", "user_pic":"picture", "photo":"http://hfhfhfhhfh.jpg", "timestamp":"10-09-10"} {"username":"user2", ..........}] i've 10 jsonobject in array, , want use populate stream with: avatar - nickname photo timestamp stream of application, want have latest post of other user. how can populate stream? think use baseadapter correct? thank much! yes need baseadapter or arrayadapter depending on implementation. have overwritye default implementation show list items want them displayed. may check listview examples here. http://developer.android.com/resources/samples/apidemos/src/com/example/android/apis/view/index.html . basically might want in situation is. have progress dialog or other indicator before start downloading json. download json. parse , convert list of objects[probably arraylist] pass list on listview adapter

internet explorer - JQuery Change CSS Display not working -

i have working on chrome , firefox when user clicks on sub image changes main image altering it's display property hide show. here's img elements. <img id="lg1" src="http... <img id="lg2" style="display:none" src="http... <img id="lg3" style="display:none" src="http... and js looks this: $('#graph1').click(function() { $("#lg1").css("display","inherit"); $("#lg2").css("display","none"); $("#lg3").css("display","none"); }); $('#graph2').click(function() { $("#lg1").css("display","none"); $("#lg2").css("display","inherit"); $("#lg3").css("display","none"); }); $('#graph3').click(function() { $("#lg1").css("display","none"); $(&quo

WPF ValidationRule bug? Backspace is ignored. Is there a work around for this? -

my work mate having problem well, haven't had chance in way of investigation. steps reproduce problem in textbox in datagrid validation rule attached. enter illegal content in such way 1 backspace should return legal content. hit space - text box still showing error when shouldn't be hit backspace again , error clears has come across , know of work around? thanks in advance!

eclipse - Cannot view variables values from Java sources during debug -

while debugging java program, cannot view variables values in java source code, example in function integer.valueof(). try add variables in expressions or inspect, 'a cannot resolved' this known problem. typically can see argument values arg0, arg1 etc , member variables. if lhballoti right , problem jdk compiled without debug information try compile sources (src.zip). believe hard compile whole jdk think can compile interesting classes. push classes bootclasspath when running java program (using -xbootclasspath/p ). i hope work.

bash - How do I display RVM's current Ruby and gemset in the Terminal prompt? -

i'm using rvm-prompt . seems interpreter, version, patchlevel, , gemset should displayed default. if call prompt, accurately returns current ruby , gemset: $ rvm-prompt ruby-1.8.7-p302@rails125 but gemset isn't reflected in prompt: ruby-1.8.7-p302 macbook:~ subpixel$ i tried calling gemset explicitly in .bash_profile with: ps1="\$(~/.rvm/bin/rvm-prompt v p g) $ps1" but doesn't change prompt. if @ documentation rvm-prompt , @ bottom of page you'll find following: ps1_functions recently there has been pair programming session turned out useful bit of prompt setting code. resides in contrib/ can require in profiles follows after sourcing rvm itself. source "$rvm_path/contrib/ps1_functions" immediately after can customize prompt adding following line ps1_set there article , screen cast associated in community resources section. i copied ps1_functions file, changed suit needs , source in .bash_prof

eclipse - timezone in android emulator -

have tried change timezon in android-emulator doesn't work. write -timezone option in eclipse menu: window - preferences - android - launch - default emulator options: -timezone europe/stockholm found timezone info here . in stockholm add 1 hour british time. if computer clock e.g. 22.19 want time in android emulator 22.19 . show 21.19 . how shall give -timezone arg emulator inside eclipse works. use winxp , eclipse 3.5. , have restarted emulator after each change of timezone. emulator -timezone europe/stockholm should work (on linux). no quotes needed. try adb shell: # date thu dec 2 00:04:02 cet 2010 # date -u wed dec 1 23:04:05 gmt 2010

php - pagination of multi dimensional array -

a sample result api formatted follows. "limit" can set 500. i've tried various pagination classes parse results unsuccessful in attempts. provide option ["page"] => int(x) makes easy paginate. easy code gods maybe, not me. appreciated. $var = array(7) { ["errors"]=> array(0) { } ["warnings"]=> array(1) { [0]=> array(2) { ["code"]=> string(26) "api_class_update_available" ["msg"]=> string(58) "the api class available in version 1.6" } } ["data"]=> array(4) { [0]=> array(3) { ["url"]=> string(7) "http://" ["keyword"]=> string(7) "keyword1" ["price"]=> string(5) "23.99" } [1]=> array(3) { ["url"]=> string(7) "http://" ["

c# - Databinding in WPF -

i having trouble databinding in text block. what want whenever there exception occured in class want dispaly in text block reason not dispalying. main.xaml <window x:class="testingwpf.main" <window.resources> <objectdataprovider x:key="showerr" objecttype="{x:type local:errorlog}" methodname="geterror"/> </window.resources> <frame name="frame1" width="620"/> <button name="button1" click="button1_click"> <textblock name="txtblock6" text="{binding source={staticresource showerr}}"/> </window> main.xaml.cs namespace testingwpf { public partial class main : window { private void button1_click(object sender, routedeventargs e) { frame1.source =new uri("/page1.xaml", urikind.relative); }

ruby on rails - Restore after Terminate -

i'm using engine yard appcloud service. terminated instance. how can restore /data folder , databases? engine yard appcloud default snapshot /data volumes on app_master , /db volume on db_master. utility instances snapshot /data well. upon termination of environment snapshots created, , if boot environment should automatically select last snapshots available can select custom option when booting select particular snapshot if you'd like. for more information visit our documentation site.

Word VBA "Label Not Defined" If Bookmark exists command -

i new vba , learning. here's situation , problem: 1) created working userform text , comboboxes linking bookmarks 2) problem doesn't work if bookmarks don't exist (and project require this: form need run on documents not bookmarks present) 3) form stop giving me error messages if bookmarks arent there , fill out ones existing in particular ocument 4) here's code: private sub cmdok_click() application.screenupdating = false activedocument if .bookmarks.exists("cboyourname") .range.text = cboyourname.value else: goto 28 end if if .bookmarks.exists("cboyourphone") .range.text = cboyourphone.value else: goto 32 end if if .bookmarks.exists("cboyourfax") .range.text = cboyourfax.value else: goto 36 end if if .bookmarks.exists("cboyouremail") .range.text = cboyouremail.value else: goto 40 end if

apache - Prevent access to CGI scripts based on the source of the HTML form -

i have website, powered modx, centered around form. access webpage form restricted registered members (handled modx). user fills out few text entries, selects file upload, hits submit. specified action submit.py cgi script under /cgi-bin logs submitted information , saves file, , executes perfectly. the concern have any form (apparently), if specify right url <form> action attribute, seems able link form cgi script. meaning can write following on own page: <form action="http://my-site.com/cgi-bin/submit.py"> <!-- blah blah blah --> </form> and data sent cgi form , processed (undesirable behavior). my question this: there way restrict execution of script based on html form sent data? missing obvious? i've searched online , found related issue of csrf, if there's way apart token authentication prevent unauthorized use of cgi script, love hear it. you can make once use token must sent form ensure valid (this mentioned

performance - Gzipping content in Akamai -

i have few files served via content delivery network. these files not gzipped when served cdn servers. wondering if gzip content on servers' end, akamai first gzipped content , serve gzipped content once stores content on servers? akamai can fetch content origin without gzip, , serve content gzipped on end. store content unzipped in cache, , compress on fly browsers support it.

sql - Best way to INSERT autoincrement field? (PHP/MySQL) -

i have insert data 2 tables, items , class_items. (a third table, classes related here, not being inserted into). the primary key of items item_id, , it's auto-incrementing integer. aside primary key, there no unique fields in items. need know item_id match classes in class_items. this being done through php interface. i'm wondering best way insert items, , match item_id's class_items. here 2 main options see: insert each item, use mysql_insert_id() item_id class_items insert query. means 1 query every item (thousands of queries in total). get next autoincrement id, lock class_items table can keep adding $item_id variable. mean 2 queries (one items, 1 class_items) which way best , why? also, if have unlisted alternative i'm open whatever efficient. the efficient going to use parameterized queries. require using mysqli functions, if you're point of needing optimize kind of query should think being there anyway. no matter how cut it,

windows - Website w/SVN: Working Copy: Configuring Apache httpd.conf for local svn checkout - HOWTO? -

i have worked svn, , apache not together. my customer has live site @ 1 address, , svn repository on machine @ address. i have checked out whole 9 yards directory on local (windows xp) machine running apache/2.0.59. (there no problems configuring local sites.) i 3 directories in checkout: branches, tags, trunk which 1 should use documentroot ? thanks reading. you're checking out wrong directory. check out either trunk , or subdirectory of branches or tags . otherwise end checking out dozens of copies of code, in different versions. as document root, depends on how project organized. same directory checked out, or subdirectory. latter more likely, since project contain code shouldn't accessible web.

ruby - Call task more than once in Rails 3 generator -

i'm writing rails 3 generator creates 2 different models. here's simplified example of i'm trying do: def my_generator_task invoke "model", ["foo"] invoke "model", ["bar"] end the problem thor invoke method invokes task once, second call "model" task never happens , "bar" model never created. know elegant way accomplish this, preferably in way doesn't break ability run "rails destroy" generator? one more thought, way possible run multiple model generator without migration rails::generators.invoke("active_record:model", ["foo", "--no-migration" ]) rails::generators.invoke("active_record:model", ["bar", "--no-migration" ])

C# generic graph search framework -

i have coded various graph search (a*, dfs, bfs, etc..) algorithms many times over. every time, real difference actual search states searching over, , how new states generated existing ones. i faced yet search-heavy project, , avoid having code , debug general search algorithm again. nice if define search state class, including information generating successive states, heuristic cost, etc, , plug in kind of existing search framework can of heavy lifting me. know algorithms aren't particularly difficult code, there enough tricks involved make annoying. does exist? couldn't find anything. perhaps quickgraph of interest. quickgraph provides generic directed/undirected graph datastructures , algorithms .net 2.0 , up. quickgraph comes algorithms such depth first seach, breath first search, a* search, shortest path, k-shortest path, maximum flow, minimum spanning tree, least common ancestors, etc

eclipse where is args[] stored? -

Image
i know eclipse save entered args?(in file?) because these args entered -say- month ago remembered. see snapshot: i'd suggest save launch config shared file in project folder. find option in commons tab in screenshot. if open text-editor find following 2 tags <stringattribute key="org.eclipse.jdt.launching.program_arguments" value="your program arguments"/> <stringattribute key="org.eclipse.jdt.launching.vm_arguments" value="your vm arguments"/> i share projects launch config in company's scm.

ruby - Why was Pathname's chdir method obsoleted? -

why pathname's chdir method obsoleted since ruby 1.8.1? wrong it? this: dir = pathname('a') dir.chdir ... end is shorter , more readable this: dir = pathname('a') dir.chdir(dir) ... end nothing wrong it, pathname wasn't right place it. use dir.chdir instead. source: http://corelib.rubyonrails.org/classes/pathname.html#m000633 (click "[source]")

In Rails, how to have an /admin section, and then controllers within the admin section? -

i want have /admin section in application, , have routes within /admin section like: www.example.com/admin/ (only users have acess section) then have controllers in section like: /admin/users/{add, new, etc} what options this? (using rails 3) do in routes.rb: namespace :admin resources :users end see http://guides.rubyonrails.org/routing.html more detail. then in each admin controller you'll need before_filter: before_filter :authorized? def authorized? #check if authorized here. end

Is Ruby's code block same as C#'s lambda expression? -

are these 2 same thing? similar me. did lambda expression borrow idea ruby? ruby has 4 constructs extremely similar the block the idea behind blocks sort of way implement light weight strategy patterns. block define coroutine on function, function can delegate control yield keyword. use blocks in ruby, including pretty looping constructs or anywhere use using in c#. outside block in scope block, inverse not true, exception return inside block return outer scope. this def foo yield 'called foo' end #usage foo {|msg| puts msg} #idiomatic 1 liners foo |msg| #idiomatic multiline blocks puts msg end proc a proc taking block , passing around parameter. 1 extremely interesting use of can pass proc in replacement block in method. ruby has special character proc coercion &, , special rule if last param in method signature starts &, proc representation of block method call. finally, there builtin method called block_given? , return true if current

objective c - Expected specifier-qualifier-list before 'string' -

with latest version of xcode apple, have following problem. upon launching, , starting new project, no matter project, error. let's build "mac os x command line tool" of type "foundation". then, add new class, go file > add file > cocoa class > objective-c class (subclass of nsobject). next, in .h file of new class created, replace following code: // // newclass.h // untitled // #import <cocoa/cocoa.h> @interface newclass : nsobject { string username; } @property string username; @end and implementation following code: // // newclass.m // untitled // #import "newclass.h" @implementation newclass @synthesize username; @end and click "build & run" following errors occur: newclass.h:11: error: expected specifier-qualifier-list before 'string' newclass.h:14: error: expected specifier-qualifier-list before 'string' newclass.m:11: error: no declaration of property &#

hash - Unsafe JavaScript attempt to access frame -

am getting below error when try set hash value 1 server url page in iframe belongs server. unsafe javascript attempt access frame url "server 1 url" frame url ""server 2 url"". domains, protocols , ports must match. yes, avoid xss (cross-site scripting) vulnerabilities. normal security measure, , should avoid if you're developing professionally. had workaround before because own "server 1" , "server 2". workaround server 1 act proxy server , feed data server 2, allowed inject javascript iframe,

Zend framework compatiable twitter, facebook ,myspace API -

can 1 give me link api's post messages on twitter, facebook ,myspace social media using zend framework? there 1 twitter, http://framework.zend.com/manual/en/zend.service.twitter.html , have build others yourself

wmi - Registry Permission -

i want retrive registry permission of hklm/software/sybase using wmi. http://www.serverwatch.com/tutorials/article.php/1476871/managing-windows-registry-with-scripting-part-3.htm

google app engine - Final GAE vs AWS architectural decision -

i know has been asked 1 way or before, of main issues gae stability seem have been asked around end of 2008, 2009, or aren't directly related games @ scale (which i'm interested in). basically, have been arguing , forth business partner whether use gae or aws back-end of our social game engine, , it's crunch time. love gae (java) many reasons, , although used unstable, it's pretty now. main argument in favour of aws fact aws has proven multiple games running tens of millions of active users per day. obvious pin-up child aws zynga, farmville peaking @ 80+million dau. , that's 1 of hugely successful games running on aws infrastructure. remarkable achievement. so, 1 way or it's known work. gae on other hand doesn't have examples find doing these sorts of numbers. not close. so can trust it? there single example of large social game 2 million+ daily active users, using gae? the main considerations our social game back-end are: reliable cdn