Posts

Showing posts from August, 2014

c# - XAML:Specified element is already the logical child of another element. Disconnect it first -

Image
i building custom modal box in wpf this i want users add modal children control element xaml using custom modal element. since cannot create child window inside main window. doing indirectly using xaml , c#. here sample code implementing modal mainwindow.xaml <local:modalwindow> <border background="red" width="400" height="400"> <button width="110"></button> </border> </local:modalwindow> mainwindow.xaml.cs class modalwindow : stackpanel { public modalwindow() { stackpanel mygrid = this; this.height = 400; this.width = 400; window mywindow = new mywindow(this); } class mywindow : window { public mywindow(object x) : base() { this.windowstate = windowstate.maximized; this.allowstransparency = true; this.windowstyle = windowstyle.none; this.opacity = 0.7; this.background

android - HAXM not working on Linux -

here go gingerbread : http://software.intel.com/en-us/blogs/2012/03/12/how-to-start-intel-hardware-assistedvirtualization-hypervisor-on-linux-to-speed-up-intel-android-x86-gingerbread-emulator/ any updates icecream sandwich or kitkat ? helpful answers highly appreciated!! haxm needed on windows , os x. on linux, need have kvm installed. see "configuring vm acceleration on linux" section on: http://developer.android.com/tools/devices/emulator.html#accel-vm just download x86 based system images in sdk manager, start avd, kvm auto-detected , used automatically if machine/system supports it.

jquery - can some one help to show the next div using the same calss -

<span class="s1">show me</span> <div class="show">hello world</div> <span class="s1">show me</span> <div class="show">hello world</div> i tried not working jquery(document).ready(function ($) { $(".s1").click(function () { $(this).next('div').slidetoggle(); }); }); if click s1 thei need show next div i prefer add target selector @ <span> can check demo here

training data - Can we use Tesseract 2.x trained files in Tesseract 3.02 -

i have set of trained files "micr" characters on tesseract 2.04 platform. there way can use same trained data files in tesseract 3.02 version? i've tried use "combine_tessdata" function on available data files, failed. , understand there major api changes going 2.x version 3.x version. i'd thankful know whether have train characters again or there exist method use current trained data files. thank valuable time. the language data between tesseract 2.x , 3.x versions not compatible. have retrain them. box files can reused after adding 6th, page number column.

c# - Autoresize textbox control vertically -

in c# form, have panel anchored sides, , inside, textbox, anchored top/left/right. when text gets loaded textbox, want auto expand vertically don't need scroll textbox (scroll panel @ most, if there more text doesn't fit panel). there way textbox? (i'm not constrained use control if there's control fits description, feel free mention it) i'll assume multi-line text box , you'll allow grow vertically. code worked well: private void textbox1_textchanged(object sender, eventargs e) { size sz = new size(textbox1.clientsize.width, int.maxvalue); textformatflags flags = textformatflags.wordbreak; int padding = 3; int borders = textbox1.height - textbox1.clientsize.height; sz = textrenderer.measuretext(textbox1.text, textbox1.font, sz, flags); int h = sz.height + borders + padding; if (textbox1.top + h > this.clientsize.height - 10) { h = this.clientsize.height - 10 - textbox1.

java - Is this method O(log N) or constant time? -

i have method inserts elements priority queue. want know performance time has. i believe can o(1) if element being inserted can place @ bottom of queue. however, runs on o(log n) time, if element inserted new minimum , percolated way root. is reasoning correct? here method insertion method: /** * insert priority queue, maintaining heap order. * duplicates allowed. * @param x item insert. */ public void insert( anytype x ) { if( currentsize == array.length - 1 ) enlargearray( array.length * 2 + 1 ); // percolate int hole = ++currentsize; for( array[ 0 ] = x; x.compareto( array[ hole / 2 ] ) < 0; hole /= 2 ) array[ hole ] = array[ hole / 2 ]; array[ hole ] = x; } i "no" in answer question "is reasoning correct?" typically o() notation taken indication of worst-case complexity of algorithm. can used average-case complexity, best-case complexity. (see here example when might use it.) have argued

File not found on iOS device, but found in Simulator -

when run application on simulator found path of file using following code: { nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes); nsstring *basepath = ([paths count] > 0) ? [paths objectatindex:0] : nil; nslog(@"%@",basepath); } simulator output: file:///users/username/library/application support/iphone simulator/7.0.3/applications/e7816ff6-7e6a-4606-917e-e74cdb574ec8/documents/images/20140306113538.png and same code when run in device found output with: device output: file:///var/mobile/applications/2d86a03f-c239-4b57-849f-019bcdca8543/documents/images/20140306114536.png and when checked, file store in documents. when load url in browser path of simulator(which simulator output) loaded in browser. path of device(which device output) showing error in browser file not found. like: firefox can't find file @ /var/mobile/applications/2d86a03f-c239-4b57-849f-019bcdca8543/documents/imag

sql server - How to loop the variables in t-sql -

i have t-sql have loop variables. declare @empno nvarchar(max),@tablehtml nvarchar(max) ; set @empno = (select employee_no emptemp active = 'yes'); set @tablehtml = n'<h2>additions</h2>' + n'<table border="1">' + n'<th>ename</th>' + n'<th>sal</th>' + '<tr>' + cast ( ( select td=ename,'',td=sal,'' emp empno = @empno) xml path('tr'), type ) nvarchar(max) ) + n'</table>' ; exec msdb.dbo.sp_send_dbmail @recipients=someone@gmail.com, @subject = emp , @body = @tablehtml , @body_format = 'html', @profile_name = 'sql profile' the emptemp table looks like id empno active 1 245 yes 2 124 yes 3 255 yes 4 224 no i have send individual mail based on data in emp table that how cursor like: declare @empno nvarchar(max) declare @tablehtml nvarchar(max) ; declare @id int; declare curs c

javascript - Get JSON object from AJAX call -

i'm new ajax , javascript . in project, have json object in javascript file. i've used spray-json , shows me json object in url. http://localhost:8081/all-modules { "status": "s1000", "description": "success", "results": ["module1", "module2", "module3"] } my ajax call $.ajax({ url: 'http://localhost:8081/all-modules', datatype: 'application/json', complete: function(data){ alert(data) }, success: function(data){ alert(data) } it returns alert [object object] . issue in here? try following; var data = '{"name": "john","age": 30}'; var json = json.parse(data); alert(json["name"]); alert(json.name); you can check out link: how access json object in javascript

javascript - how to get users online status jsp -

i want web application users logged list possible flows unexpected shutdown (power cut), force closed browser , whatever in flow. want show online users status text. find solutions but,they solutions take server lot of memory update login table last_logged column current time every 20 seconds client side server side , check last_logged time less 20 seconds takes status offline. need perfect solution out heavy work load server. simply, want gmail chat list flows working fine on gmail chat. don't know these concept new concept. may find solution if know solution type of concept please share knowledge. it, must helpful developers , appreciate effect. thanks spending valuable time reading post :) why think updating table takes "a lot of memory"? or why think "heavy work load server"? nothing. there no solution other using database described, because browsers don't implement kind of messages when user leaves site. you've got track updating tab

android - Moto G mobile doesn't show in the devices List of Eclipse -

i trying connect moto g mobile eclipse in windows 7 32-bit machine doesn't show on devices list. this, first connected device machine via usb cable , chose ptp mode , checked "usb debugging" option in devices settings. after few seconds says "drivers installed unsuccessfully". @ time, had uninstalled device drivers in device manager of machine , disconnected , connected again. said "drivers installed successfully" , updated drivers in device manager , set drivers(google-drivers sdk).but doesn't show in devices list. did wrong here? hopefully able find 1 solution issue. download ' adb driver installer ' here http://adbdriver.com/downloads/ after connect moto g , start adbdriverinstaller.exe list device , press install. hope works ! * note : * it worked me on windows 7 not on windows 8 edit this link http://dl.xda-developers.com/attachdl/3b2765b7b77976f98576f76f7f549956/532c41bc/2/4/8/0/3/9/6/howto_driver.zip h

activex - Reading xls or xlsx file using javascript -

i reading 1 xls file through java script. function upload1() { var controlcn = new activexobject("adodb.connection"); var conn = "provider=microsoft.jet.oledb.4.0;data source = c:\\test.xls;persist security info=false;extended properties=excel 8.0;"; controlcn.open(conn); var rs = new activexobject("adodb.recordset"); var sql = "select * [sheet1$]"; rs.open(sql, controlcn); if(rs.bof) { document.write('no data avaliable'); } if(!rs.bof) { rs.movefirst() while(!rs.eof) { for(var i=0; i!= rs.fields.count; ++i) { document.write(rs.fields(i).value + ", "); } document.write("<br />"); rs.movenext() } } rs.close(); controlcn.close(); } in third line giving path of xls file want read. possible dynamically fetch ex

c# - Difference Between DLL Reference's? And Uses? -

please 1 explain this. question helps understand common things question: what difference between when 'add dll reference 1 project project via browse option , add dll reference solution project project , copy-paste 1 project project'? i have found answer on google answer: adding project reference adds local project's dll project references it, , every time solution compiles, updated dll project gets copied other project. when go through build process, if have 5 projects, each 1 rebuilds dll, , copies dll references. but: i don't know process , difference when copy-paste 1 project project? when copy paste 1 project another, dependent project add reference of file have paste in project solution directory when copy paste dll of 1 project other project's directory , add reference browsing directory have pasted dll. vs add reference , copy dll bin folder , show (allows you) method , properties contains. if change in source proj

wpf - TabControl - Align TabItems correctly if free space dominates -

i have customized tabcontrol: <window x:class="wpfapplication2.mainwindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" title="mainwindow" height="350" width="525"> <window.resources> <style targettype="tabcontrol"> <setter property="background" value="transparent" /> <setter property="borderthickness" value="0" /> <setter property="tabstripplacement" value="bottom" /> <setter property="template"> <setter.value> <controltemplate targettype="tabcontrol"> <grid> <grid.rowdefinitions> <rowdefinition height="*"/>

ado.net - DbCommand , Must Declare a variable error -

this code. have added db parameter still shows me error (on execution). must declare scalar variable dbcommand command; stringbuilder query = new stringbuilder( @"select isnull(upsellservice_oid,'') upsellservice_oid," + environment.newline + " isnull(servicename,'') servicename," + environment.newline + " isnull(servicedescription,'') servicedescription," + environment.newline + " isnull(create_by,'') create_by," + environment.newline + " isnull(create_date,'') create_date," + environment.newline + " isn

swing - Disable Windows Auto Update Using Java -

try { final string reg_add_cmd ="cmd /c reg add \"hkey_local_machine\\software\\"+ "microsoft\\windows\\currentversion\\windowsupdate"+ "\\auto update\" /v auoptions /t reg_dword /d 1 /f"; process objprocess; //objprocess cmd /c = runtime.getruntime().exec(new string[] //{"reg add \"", " hkey_local_machine\\software\\microsoft\\windows //\\currentversion\\windowsupdate\\auto update"," /v auoptions /t reg_dword /d 1 /f"}); objprocess = runtime.getruntime().exec(reg_add_cmd); system.out.println("reg_add_cmd:::"+reg_add_cmd); bufferedreader reader=new bufferedreader(new inputstreamreader(objprocess.getinputstream())); string line=reader.readline(); system.out.println("windows auto update::::"+line); final int exitstatus = objprocess.waitfor(); int exitval = objprocess.exitvalue();

ios - How to identify the IAP Allready subscribed alert -

i doing 1 application.in using iap concept.in that,once user finish subscription,i calling proidecontent method. , if user again try subscribe before end of subscription need call providecontent method. in time getting alert apple "already subscribed" ok button. unable identify alert belongs "already subscribed". how can identify alert.

javascript - Using ng-init and ng-model together -

hi have situation have format values using ng-init have ng-model 2 way binding in input field value can changed , saved. <div ng-repeat="ab in ablist"> <div class="col-sm-3"> <input type="text" ng-init="item.ab=fn(item.ab)" ng-model="item.ab" /> </div> </div> the above code doesnt work. not show formatted value. can let me know how can change can display formatted value using ng-init keep ng-model binding edited value on submit. in case have use directive. ng-init used when want set default or initial value control. directive can keep display value , model value in separate formats. here directive formatting integers commas. app.directive('formattednumber', function () { return { link: function (scope, element, attrs, ctrl) { element.bind('blur', function (blurevent) { if (element.data('old-value') !== elem

c# - Adding multiple reminder - windows phone -

i have learned on how create reminder application website http://www.c-sharpcorner.com/uploadfile/f397b9/reminder-application-in-windows-phone-mango/ here allows add 1 reminder. make new reminder, previous overrided. how make able accept multiple reminders. below code: void btnsave_click(object sender, routedeventargs e) { datetime _date = rdate.value.value; timespan _time = rtime.value.value.timeofday; _date = _date.date + _time; string _content = titletbox.text; if (_date < datetime.now) messagebox.show("your time not match !\nplease enter again !"); else if (string.isnullorempty(_content)) messagebox.show("your task can't empty !\n please enter task !"); else { scheduledaction _oldreminder = scheduledactionservice.find("todoreminder"); if (_oldreminder != null) scheduledactionservice.remove(_oldreminder.name);

Accessing string representations of constant field values in java -

i using imported class has constant field values set using: public static final int blue = 1; public static final int green = 2; etc. is there way of getting string representation of constant field value int value? i.e. given value 2 want string of green. p.s. isn't class can't use enums if can change class contains these constants, better make enum value() method. otherwise, suggest building map<integer, string> once using reflection, , doing map lookups: map<integer, string> valuetostringmap = new hashmap<>(); (field field : foo.class.getfields()) { int modifiers = field.getmodifiers(); if (field.gettype() == integer.class && modifier.ispublic(modifiers) && modifier.isstatic(modifiers)) { valuetostringmap.put((integer) field.get(null), field.getname()); } }

c# - Entity Framework Pagination Performance Considerations -

Image
i'm unfamiliar complex queries in entity framework 6, had question associated pagination. the scenario follows: have project have described data model in own form , using t4 templates, generates appropriate entity, high fidelity change tracking companion entity, complex dynamic search query entity used ask questions associated model (eg. entity.searchnamecriterium = "t"; entity.searchnametype = stringsearchtype.startswith, ui built around enable user powerful search tool.) into this, have part pagination used drop down list of constituent elements: when insert using insert button, if overflows next page (at 'x' number of items each time, defined in constant -- later move setting) use following code: this.context.savechanges(); int offset = searchcuritemlstcriteriaskip - 1; var querybase = this.querycuritemlstformcontainer; int idfind = newdatacontext.identifier; while (querybase.any()) { querybase = querycuritemlstformcontainer.skip((++offset) * se

dynamics ax 2012 - AX2012 R2 CU7 : VSProject node compilation issues -

i creating build ax using tfs activities. of steps in there , of works on simple scenario couple dummy xpo's in tfs vcs. need full scenario of building our codebase , i'm experiencing compilation issues visual studio project nodes. this regarding code import/compilation: import label files import xpo of code. import visual studio projects using systreenodevsproject\importproject method when run full compilation, there still compiler errors regarding code in need of resulting assemblies of vsprojects in aot. this caused output of projects still being empty. when selecting them , hitting compile, still no result. selecting them 1 one , compiling them. output of projects generated in aot , depending classes can compiled directly. compiling them separately cause comiler detect vsproject node , kernel call export , build functionality on vsprojects resulting in output being generated. the real question here is: build have create autorun file compile vsproject nod

c# - Web browser does not show web pages properly in Windows Phone 8 application -

Image
i have been struggling displaying web content in web browser control on windows phone 8 application. the actual problem web browser control not showing web page (html file) @ correct size. here images show problem: web page shown in windows phone 8 web browser control: other devices android mobiles, iphone , ipod & other devices show web page this: my html this., <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>highest runs 2013</title> <link rel="stylesheet" type="text/css" href="css/orange.css"> </head> <body bgcolor="#a31947"> <div class="contenedor"> &

php - List Dir not functioning as expected -

i have used usercake make login system, altering suit needs. originally list dir setup on page show of "help files" within specific folder. worked fine not secure , view. have changed security having few problems code: //links logged in user if(isuserloggedin()) { //links permission level 3 (bof) if ($loggedinuser->checkpermission(array(3))){ if ($handle = opendir('cd500/')) { while (false !== ($file = readdir($handle))) { if ($file != '.' && $file != '..'){ $thelist .= '<a href="/cd500/'.$file.'' target='_blank' >'.$file.'</a></br>'; } } closedir($handle); } echo " <div id='output'> list of files:</div> <div id='list'> $thelist this whole completed package. wondering if simple many if statements? it not parse, html loads , images

java - Trigger a function when three consecutive wrong password tries -

i beginner in android development. android device have password use. password may numeric or pattern. want trigger function when tries 3 consecutive wrong password inputs. not making password app. password app security app chosen device user. when ever try security app password assess device function trigger. app trigger when other security app password accessed thanks in advance have class variable called passwordretrycount = 0; then everytime user types password, if wrong, following: passwordretrycount++; if (passwordretrycount == 3) { //trigger function }

c# - How to get my current location using Bing Maps SOAP Services? -

i making c# program in wpf. basing codes here: http://msdn.microsoft.com/en-us/library/dd221354.aspx . currently, done doing geocoding , reverse geocoding. want know how can use know current location automatically without inputting latitude , longitude. those services response input of either address or coordinate. service won't able tell without providing information. in wpf application need make use of location platform in windows access users location device. location platform users location using 1 of several methods such as; gps, wifi triangulation, ip address lookup. provide coordinate (latitude/longitude) of approximately. if want address information send coordinate reverse geocoding service. can find information on how use location platform in wpf here: http://www.codeguru.com/csharp/.net/article.php/c16973/using-the-windows-7-sensor-and-location-platform-from-c.htm

jquery plugins - How can I set focus on a form input inside jScrollPane? -

an outsourcer implemented jscrollpane on our project time ago , discovered preventing me setting focus on form text inputs inside it. if remove jscrollpane can set focus with: $("#myfield").focus(); i've been through jscrollpane time afternoon can't find cause of problem. thanks @anurupr, solved me. made me realize jscrollpane not being called javascript file. found call in main php file , able set focus after jscrollpane fixed it. i've answered own question in order mark thread answered.

php - How to search for all points in a given radius of a zipcode? -

i want have search form 2 fields, 1 zipcode , other distance in miles(radius). whenever enter zipcode , radius, should search zipcodes in radius of zipcode. e.g if enter zipcode 10001 , distance 3miles form should search zipcodes around 3 miles radius of 10001. thanks this example might you. http://gmaps-samples.googlecode.com/svn../trunk/fusiontables/circle_example.html regards, arunraj.

Unpack tar.gz folder to part of filename -

i have file dagens_130325.tar.gz containing folder dagens . in 1 folder have hundreds of these daily info. unpack dagens_130325.tar.gz/dagens 130325 files inside. 130326 etc. is there way it? not sure right stack ask kind of question, try with tar -zxvf dagens_130325.tar.gz -c /tmp/130325 dagens this way, folder dagens archive dagens_130325.tar.gz going extracted /tmp/130325 . however, note target folder must exist, otherwise command fail so, supposedly have 4 archives in form dagens_1.tar.gz , dagens_2.tar.gz , ... , can write extract.sh file containing #!/bin/bash in {1..4} mkdir /tmp/$i file="dagens_$i.tar.gz" tar -zxvf $file -c /tmp/$i dagens done having file execute permission, being in same folder archives , executing should produced result asked.

php - output buffering ob_get_contents not returning anything -

i trying generate static html php however, cannot output $page, ideas? cheers ob_start(); $pageident = $tempdbid; include 'newpagegenerator.php'; $page = ob_get_contents(); ob_end_clean(); you need output using echo statement. ob_start(); $pageident = $tempdbid; include 'newpagegenerator.php'; $page = ob_get_contents(); echo $page;//<----- echo here ob_end_clean();

r - How to find a merge the specific data with the name? -

i'm trying find name of specific gene in data. that's did far: gnames = unique(data_rd[,1]) gnames= gnames[2:length(gnames)] gnames contain of genes have find name. gdata = lapply(list_of_data,function(x) x[3:nrow(x),1,9]) gdata set of genes names in different files , of them might repeated in few files. that's how created list_of_data: tbl = list.files(pattern="*.csv") list_of_data = lapply(tbl, read.csv) so let's explain on example: gnames: gene1 gene2 gene3 gene4 gene5 gene6 gene7 gdata: gene1 nameofgene1 gene5 nameofgene5 gene7 nameofgene7 gene2 nameofgene2 gene6 nameofgene6 gene3 nameofgene3 gene4 nameofgene4 i want r find name of of genes gnames looking list_of_data. > head(gnames) [1] "zz_fgczcont0025" "zz_fgczcont0099" "zz_fgczcont0126" "zz_fgczcont0146" [5] "at1g19570" "zz_fgczcont0158" > head(gdata) ## edited, big. [[1]] x 3 zz

google cast - ChromeCast TTML Closed Captioning with Smooth Streaming and PlayReady -

hy! i create application supports ttml typed closed captions. my ism/manifest file contains ttml based closed caption, ask how can use it? i found site, https://developers.google.com/cast/docs/player described following: segmented ttml & webvtt use segmented ttml smooth streaming , webvtt - web video text tracks hls. to enable: protocol_.enablestream(streamindex, true); player_.enablecaptions(true); but can't find example problem. have enable after creating host @ receiver side? there sample app this? update #1 here's code: window.onload = function() { var mediaelement = document.getelementbyid('video'); //video html video tag var mediamanager = new cast.receiver.mediamanager(mediaelement); var url = "http://playready.directtaps.net/smoothstreaming/sswss720h264/superspeedway_720.ism/manifest"; //just sample url var host = new cast.player.api.host({ 'mediaelement': mediaelement, 'url': url }); win

c# - Deploy with files from bin\Release -

i´m deploying project in c# windows forms project, have file in bin\release folder needed run correctly app(it has configurations use of dll). when run app ok. if try deploy using visual studio, , add file apllication folder, doens´t work. (no error messages, happens exactilly same if take file bin\release folder) how can deploy project correctlly ? config files dlls not used in deployed applications. if need tweak configuration of dll, copy corresponding sections exe config file. only main assembly configuration taken.

How to deal with flag variables in embedded system -

i doing project on embedded system changing flag variable 'x_flag' upon interrupt. flag variable global , accessed in other source files check state of condition of events too. i know troubles dealing global variables, ask how can access current state of 'x_flag' in other source files? in c-file can define like volatile int x_flag; void myisrfunction(void) { x_flag = 1; } and in header file add declaration extern volatile int x_flag; then need include header file other c-file able access x_flag but there should disable interrupt when accessing/modifing flag. #include "myisr.h" void somefunc() { int local_x_flag; disableinterrupts(); local_x_flag = x_flag; x_flag = 0; enableinterrupts(); if ( local_x_flag ) dosomething(); } note if flag hardware register, may need more careful, disabling interrupts not stop hardware altering value of flag , clearing explicitly may or may not allowed. in case, you'll nee

c# - Is this strategy pattern? -

Image
a little background: in system developing, there various types of csv files read , saved contents in different database tables. since changing behavior based on inputs, studies decorator, , strategy patterns , came following solution system. first created following interfaces. icdrmapper reads each line given csv file , maps object after running validations/modifications (if any). there many concrete implementations each cdr type. icdrreader takes input csv file , reads each line , pass mapper. each reader implementation decorated mef metadata icdrengine can locate correct 1 on fly. interface has many implementations each cdr type. icdrengine implementation uses mef metadata locate matching icdrreader implementation. has 1 implementation. then, have created abstractcdrreader , abstractcdrmapper , used decorator pattern delegate specific implementations different concrete classes. abstractcdrreader selects correct icdrmapper implementation based on mef metadat

Issue with Google Cloud Storage resumable upload URL from App Engine -

we use resumable upload mechanism in google cloud storage upload files app engine described on: https://developers.google.com/storage/docs/json_api/v1/how-tos/upload#resumable nice feature it's possible make gcs generate upload urls app engine uploadid making possible use url directly client without need sign url. works when adding gae service account gcs api project member. this mechanism worked long time, since today stopped working following error (http 403): "domain": "usagelimits", "reason": "accessnotconfigured", "message": "access not configured. please use google developers console activate api project." so we're little bit lost now. related gcs incident (incident report gcs error rate spike march 4th)? find below important part of code we're using make first post (which working before): string url = " https://www.googleapis.com/upload/storage/v1beta2/b/ "+bucketname+

c# - Is it possible run python in .net application? -

in .net application possible save c# code in text file or database string , run dynamically on fly. method useful in many case such business rule engine or user defined calculation engine , etc. here nice example: using system; using system.collections.generic; using system.linq; using microsoft.csharp; using system.codedom.compiler; class program { static void main(string[] args) { var csc = new csharpcodeprovider(new dictionary<string, string>() { { "compilerversion", "v3.5" } }); var parameters = new compilerparameters(new[] { "mscorlib.dll", "system.core.dll" }, "foo.exe", true); parameters.generateexecutable = true; compilerresults results = csc.compileassemblyfromsource(parameters, @"using system.linq; class program { public static void main(string[] args) { var q = in enumerable.range(1,100) % 2 =

c - An elegant way to find a power of 2 -

my question quite similar fastest way of computing power "power of 2" number used? : giving x=2^y input want output y . difference i'm coding in c, not c++ , know sure there 1 bit set in input i'm wondering if there more efficient ways solve this. here try: unsigned int get_power_of_two(unsigned int x) { unsigned int y=0; for(unsigned int input=x; input>0; input=input>>1) { if(input & 1u) { break; } y++; } return y; } what efficiency compared proposed lookup table in @dave's answer ? (again, i'm coding in c don't have iterators functions lower_bound ) in case since know 1 bit set, it's enough count trailing zeros. can done without hardware instruction quickly. check out answer , that's code below comes (i'm not 1 tamper perfection... sometimes). unsigned v; // number 1 bit set unsigned r; // becomes exponent in v == pow(2, r) static const uns

javascript - Email Blacklist and verification -

i'm new angular , try make easy blacklist check. @ moment have 2 texts can show , hide ng-show. first 1 should shown when mail-pattern wrong , hidden when correct and/or on blacklist. my problem don't have clue how model must implemented. @ moment simulated checkbox. maybe has hint. <div class="controls"> <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/> <input type="email" id="inputemail" placeholder="email" ng-model="email" required> <div class="hint"> <h4 name="mailvalidator" ng-if="checked" ng-show="true">invalid email</h4> <h4 name="checkblacklist" ng-if="!checked" ng-show="true">email not allowed</h4> </div> here fiddle-demo i create jsfiddle problem. jsfiddle view: <div ng-controller="myctrl"&

java - base class for all exception in PHP -

i wanted know base class exception in php, have exception class in java , classes inherited it,the reason want know while working on facebook app in php , want catch fbapiexception in class object, try { $accesstoken = $facebook->getaccesstoken(); $userdata= $facebook->api('/me', 'get' ,array ('access_token' => $accesstoken)); $email= $facebook->api('/me?fields=email', 'get' ,array ('access_token' => $accesstoken)); } catch(exception $e) { return false; } so if exception occur , catch that.

javascript - JQM How to remove DOM of the previous page with changepage -

i'm have issue code. when call changepage method on jquery mobile, page stay in dom. i want remove that, didn't find answer on internet , stackoverflow. i tried $().remove() manually page, when keep page, doesn't display anything. anyone have solution ? time. this may fix issue: $('div[data-role="page"]').on('pageshow',function(event, ui){ $(ui.prevpage).remove(); });

php - Extract data from a text -

i have text : begin_general 8 lastline 20130801000028 136606 57288915 25883895742573 firsttime 20130701130426 lasttime 20130731235941 lastupdate 20130802015823 1 0 0 0 0 totalvisits 360 totalunique 246 monthhostsknown 0 monthhostsunknown 454 end_general i want extract totalvisits & totalunique try: preg_match('/^totalvisits ([0-9]{4}) /ms', $awstats, $matches); $data= $matches; print_array($data); it render me empty array! why ? thanks call this: preg_match('/totalvisits\s([0-9]{3})/', $awstats, $matches); outputs: array (size=2) 0 => string 'totalvisits 360' (length=15) 1 => string '360' (length=3)

Django, error when trying to add search fields in the admin interface -

i trying add search field in admin interface userprofile class. this models.py : class userprofile(models.model): user = models.foreignkey(user, default=none, null=true, related_name='profile') # don't judge me. had use null=true registered = models.booleanfield(default=false) activated = models.booleanfield(default=false) activation_key = models.charfield(max_length=128) receive_notifications = models.booleanfield(default=false) email = models.charfield(max_length=80, default='') def __unicode__(self): return self.email and admin.py : from main.models import userprofile django.contrib import admin class userprofileadmin(admin.modeladmin): search_fields = ['email'] admin.site.register(userprofileadmin) when try run server error: 'mediadefiningclass' object not iterable @ line register userprofileadmin . what doing wrong? this admin.site.register(us

c# - How can I use independent instances of one class, its methods and variables encapsulated in several threads/tasks? -

there datatable showing name of different algorithms , underlying=symbol has traded: id - symbol - algoname eurusd azur usdcad azur eurusd blue gbpusd blue each algorithm represented name (azur or blue) shall different class. alorithms=classes imply variety of variables, lists , methods calculate trading signals. the "strategy" id=1 uses algorithm "azur" on eurusd , strategy id=2 uses algorithm "azur" on usdjpy. each algorithm represented algoid unique means uses own data stored in list , values in variables. each algorithm has method start() receives unique variety of parameters , calls 1 furhter method import historical price date , store in several lists. after start sequence each strategy addressed realtimeprice event calls further method inside algorithm class: public void ontickupdate() . method needs use separately values of variables , lists have been generated "strategy-wise" before. how approach

android - Show "left time" until the alarm start -

i whould create alarm (alarmmanager) in android. alarm must show left time until finish. so user click on "set alarm @ 11 pm" , see in textview "alarm in xy hours/minuts/seconds". how can achieve this? thanks. try calendar calendar = calendar.getinstance(); long pretime = calendar.gettimeinmillis(); // set alarm after 5 minute calendar.add(calendar.minute, 5); long posttime = calendar.gettimeinmillis(); long delay = posttime - pretime; alarmmanager manager = (alarmmanager) getsystemservice(context.alarm_service); manager.set(alarmmanager.rtc_wakeup, posttime, null); countdowntimer timer = new countdowntimer(delay, 1) { @override public void ontick(long millisuntilfinished) { final int seconds = (int) (millisuntilfinished / 1000) % 60; final int minutes = (int) ((millisuntilfinished / (1000 * 60)) % 60); runonuithread(new runnable() {

java - Does a thread invoking, synchronized method, pre-empt another thread using same object but in a non synchronized manner? -

in java, thread invoking, synchronized method, pre-empt thread using same object in non synchronized manner? also, when thread invoking synchronized method or synchronized block, thread explicitly owns entire object? in java, thread invoking, synchronized method, pre-empt thread using same object in non synchronized manner? no, 1 thread (assuming no data-races/race-conditions) knows nothing thread doing outside of synchronization. also, when thread invoking synchronized method or synchronized block, thread explicitly owns entire object? if own mean mutual exclusion, no, has ownership synchronized regions.

Default select option for select list in Rails -

here code checked: f.select :engine_type_id, options_for_select(association_select_items(enginetype), selected: f.object.engine_type.id) this code works good, if f.object.engine_type nil (for example, when object being created) got error "undefined method `id' nil:nilclass". how can fix it? thanks. if it's new record or doesn't have engine type can't .id hence error. assuming it's belongs_to association have engine_type_id column. so make it selected: f.object.engine_type_id or if using form_for , it's @car object can do selected: @car.engine_type_id

jsf 2 - how to find out validation error in jsf2 -

i have 1 .xhtml file in have 2 form s 1 updating another, when submit 2nd form having id allofficeslink_form form not submitting didn't error, dont know error? <!-- p:message outside form --> <p:messages id="globalid_messages" autoupdate="true" /> <!-- p:message outside form --> <h:form > //this not actual code //some input fields //ajax command button updating id="allofficeslink_form" <p:commandbutton update=":#{p:component('companyid_select')} :#{p:component('alloffices_link')} :#{p:component('allofficeslink_form')}"> </p:commandbutton> </h:form> <h:form id="allofficeslink_form"> <h:commandlink id="alloffices_link" styleclass="link_general" disabled="#{budgetscenarioformationbudgetallocationaction.budgetfinancialyearbean.modbean != 'of'}" value="[all offices]" > <f:ajax listener="#{budge

php - how to remove magento notification widget -

i'm new magento,i'm trying hide notification widget, widget contains latest messages , notifications extensions, know how hide latest messages can't find way hide extensions messages, can 1 tell me can find widget how control it? in advance. to disable admin notifications: navigate system > configuration in sidebar, click advanced > advanced open disable modules output section select "disable" mage_adminnotification click "save config" keep in mind disabling notifications disable ability navigate "inbox" going system > notifications .

QT: signals from QMenu and QAction -

my problem make menu load files. here's code: qstringlist filenamelist; filenamelist << "file1" << "file2" << "file3"; qmenubar *menubar = new qmenubar(); qmenu *menu = menubar->addmenu("file"); qmenu *load = menu->addmenu("load"); foreach (qstring filename, filenamelist) { qaction *loadfile = new qaction(filename, this); load->addaction(loadfile); connect(load,signal(triggered(qaction*)),this, slot(load(qaction*))); } and slot: void mainwindow::load(qaction* action) { qdebug() << action->text(); } after click action button, qdebug shows: "file1" "file1" "file1" but need run action once! qaction not have signal can name. how solve this? thank you! the problem create same connection tree times in loop. need, doing once: [..] foreach (qstring filename, filenamelist) { qaction *loadfile = new qaction(filename, this); lo

tsql - The best practice for creating a stored procedure in sql -

i had problem once, creating procedure , when want alter used drop first re-create again. thought taking lot of time. had find better way! which best way, ease time. , incase need alter later?? its interesting found can using 1 procedure. divide procedure 2 parts: first part creates empty/dummy stored procedure/stub if stored procedure specified name in specified schema not exist. useful initial setup, when creating stored procedure in new environment. the second part of above script, alters stored procedure – whether it’s created in first step or existed before. so, every time need make changes in stored procedure, change alter procedure section (second part) of above script , entire script can executed without worrying whether stored procedure exists or not. sample code: use adventureworks go if object_id('dbo.uspgetemployeedetails') null -- check if sp exists exec('create procedure dbo.uspgetemployeedetails set nocount on;') -- create d

perl regex: replace placeholder with variable content in template -

i have template string , variables. example following: my $template = " text <--name--> other text <--age--> ..."; $age = 15; $name = "heinz"; what correct regex replace template placeholder strings corresponding perl variable? i tried $template =~ s/<--(.*?)-->/eval('$' . lc($1))/sge; but not work. placeholder replaced empty string. hope has idea. in advance. use hash, my $template = " text <--name--> other text <--age--> ..."; %hash = (age => 15, name => "heinz"); $template =~ s/<--(.*?)-->/$hash{"\l$1"}/g;

javascript - RXJS draw line on html5 canvas -

i'm trying achieve same effect i'm posting here using reactive extensions javascript (rx-js). i'm bit puzzled on how it. here page: <!doctype html> <html> <head> <title>drag , drop</title> </head> <style type="text/css"> canvas { border:1px solid steelblue; background-color: whitesmoke; } </style> <body> <canvas id="canvas" width=300 height=300></canvas> <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript"> $(function() { var canvas = document.getelementbyid("canvas"); var ctx = canvas.getcontext("2d"); var canvasoffset = $("#canvas").offset(); var offsetx = canvasoffset.left;