Posts

Showing posts from March, 2011

c# - How to select last record in a LINQ GroupBy clause -

Image
i have following simple table id , contactid , comment . i want select records , groupby contactid . used linq extension method statement: mains.groupby(l => l.contactid) .select(g => g.firstordefault()) .tolist() it returns record 1 , 4 . how can use linq contactid highest id ? (i.e. return 3 , 6 ) you can order items mains.groupby(l => l.contactid) .select(g=>g.orderbydescending(c=>c.id).firstordefault()) .tolist()

java - Best practices handling authentication data in a Spring web application -

i know question answered in subjective way, i'd know if there best practice handle authenticated user data in spring web application. i mean: need retrieve user id authenticated user in several classes of service layer of application. at moment i'm getting principal object autowired in controller methods: @requestmapping("/some/path", method = requestmethod.get) public string getbyid(@requestparam integer id, principal principal){ ... } and pass principal.getname() in every method invocation, example: // service class method public void dosomething(integer id, string username){ // retrieve user username app db } i know call: authentication auth = securitycontextholder.getcontext().getauthentication(); in service layer current authenticated user, i'm wondering if bad design application. what's common way handle authentication data? should retrieve need or should pass "through levels" of application? you can add po...

android - Unity Remote 4 is connected but Shows black screen -

when press play in editor scene runs both game view in editor , phone. but phone shows black screen. functions well. meaning can interact scene phone. can pan, zoom, click buttons blindly. the model gt-s7582. i'm using latest adb version. phone connected via usb , "usb debugging" enabled , "allow mock locations" enabled. unity version 5.4.0b18 on ubuntu 14.04 64 bit

r - Autocomplete history in rstudio -

a google search did not me out i'm hoping our community will... i'm new rstudio , while easy press button go sequentially through r commands when command looking few commands back, it's hard when command while back. i'm looking ctrl-r in linux environments type few letters , completes command based on history. is there in rstudio? you can try history() for e.g history(max.show = 50, reverse = f, pattern = "data.table::") this automatically open commands used in past .

How to record delete events in Google Spreadsheet -

i need record delete events in google spreadsheet using google apps script (delete cell or entire row) , cell number , user name. function onedit(e) triggers when cells edited , not when deleted. function onedit(e) { var range = e.range; logger.log(range.getrow()); logger.log(session.getactiveuser().getemail()); if (range.getrow() === 3.0) { var recipient = "user@example.com"; var subject = 'roster notification'; mailapp.sendemail(recipient, subject, "hello, roster has been updated. please check. thanks."); } } good news & bad news, i'm afraid. you can use installable change trigger notified row deletions. (the full list of changes edit, insert_row, insert_column, remove_row , remove_column, insert_grid, remove_grid, format, or other). the bad news event not tell what changed , if wish track changes roster, you'll need keeping track of changes yourself. related issues google's issue tracker: sp...

ios - Is SQLCipher needed anymore? -

now ios 8.3 , above, ios doesn't allow application folder access of app doesn't support itunes file sharing, necessary use sqlcipher or matter sort of encryption data, considering performance impact sqlcipher has. since ios 10 few months away, there high possibility can ditch ios 8 support in our apps. is sqlcipher needed anymore? well, suppose question should asked on case-by-case basis. permission changes, directories still visible end user out-of-the box. see ios 8.3 file sharing . is necessary use sqlcipher or matter sort of encryption data it depends on you're storing. if storing sensitive information private keys, bank accounts or personal information, continue secure data best possible. use jailbroken device potentially able reach unencrypted database on ios 8.3 , above, or hook database handle code , manually open database retrieve information.

git - changes are not reflecting pushing to main site -

Image
we using multiple devolopment sites , once changes in devolopment site ,we push changes main site. my changes not reflecting once push changes using below command : git push staging development edit my site site 1 , pushed site 4 . changes done working fine in site 1 , not reflecting in site4. code chnaged not moved site4. ex: if change code in form.html file, code not moving site 4. added normaal text, not copying site4. edit 2 - git config.file [core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true [remote "staging"] url = gituser@139.59.10.75:/var/www/sitename.repo fetch = +refs/heads/*:refs/remotes/staging/* [branch "development"] remote = staging merge = refs/heads/development even though pushed repository, haven't updated head pointer. you'll need checkout or reset on remote that. it's kind of did fetch. should setting git hook deployment automate task. ...

C# MySQL Query error handler -

i'm new in visual studio world , need little help. i'm writing program c# based , executes query when button pressed: private void button_login_click(object sender, eventargs e) { mysqldataadapter start_session; start_session = new mysqldataadapter("here update query", connection); } (the connection string on top of code). is there way check if query returned errors or not ? thank , sorry (i presume) trivial question. the way check if error or not "exception". example (for sqlserver, mysql same) : private void buttonloginclick(object sender, eventargs e) { try { using (var sqliteconnection = new sqliteconnection(connstring)) { sqliteconnection.open(); using (var sqlitecommand = new sqlitecommand(sql, sqliteconnection)) { sqlitecommand.executenonquery(); } } messagebox.show("success"); } ...

css - gulp-uncss error: unable to parse: -

having problem running gulp-uncss rid of unused code. mistake seems parsing of css. c:\wamp64\www\css-cleanup\node_modules\gulp-uncss\node_modules\uncss\node_modules\bluebird\js\release\async.js:48 fn = function () { throw arg; }; ^ error: uncss/node_modules/css: unable parse undefined: missing '{' near line 34:1 29: @import "components/_navbar"; 30: @import "components/_slick"; 31: @import "components/_slick-theme"; 32: @import "components/_slack"; 33: //@import "components/_landing"; 34: -> @ error (c:\wamp64\www\css-cleanup\node_modules\gulp-uncss\node_modules\uncss\node_modules\css\node_modules\css-parse\index.js:57:15) @ declarations (c:\wamp64\www\css-cleanup\node_modules\gulp-uncss\node_modules\uncss\node_modules\css\node_modules\css-parse\index.js:214:25) @ rule (c:\wamp64\www\c...

sql server - VS Database Project Primary Key Name -

i have database project in visual studio 2015. name primary key seems ignore attempts. naming default constraints though work. create table [dbo].[stock] ( [id] int constraint [pk_stock_id] not null primary key, [stockcode] nvarchar(6) not null, [createddate] datetime2 constraint [df_stock_createddate] default sysutcdatetime() not null ) go if click on primary key has name property readonly. got create script rather publish sql server , strips out word constraint , name on primary key. this work you: create table [dbo].[stock] ( [id] int not null, [stockcode] nvarchar(6) not null, [createddate] datetime2 not null ) go alter table dbo.stock add constraint df_stock_createddate default getdate() createddate go alter table dbo.stock add constraint pk_stock_id primary key clustered ( id ) go

spring - Spring4 internationalization multiple language -

Image
http://www.mkyong.com/spring-mvc/spring-mvc-internationalization-example/ trying follow online tutorial create multi language web application problem having don't think spring container finding / loading properties files. not sure wrong. file structure welcome.properties welcome.springmvc = happy learning spring mvc welcome.properties welcome.springmvc = \u5feb\u4e50\u5b66\u4e60 spring mvc index.jsp language : <a href="?language=en">english</a>|<a href="?language=zh_cn">chinese</a> <h2> welcome.springmvc : <spring:message code="welcome.springmvc" text="default text" /> </h2> current locale : ${pagecontext.response.locale} app-dispatcher-servlet: sure interceptors working because index.jsp ${pagecontext.response.locale} showing en/zh_cn internationalization: multi lang support resource: http://www.mkyong.com/spring-mvc/spring-mvc-internationalization-examp...

java - Jetty Session Clustering Using XML -

im trying configure jetty session clustering using database. there way change database name. dont want use default name "session". want change table name both sessionidtable , sessiontable having trouble setting configuration using xml. here code : <?xml version="1.0"?> <!doctype configure public "-//jetty//configure//en" "http://www.eclipse.org/jetty/configure_9_3.dtd"> <configure id="server" class="org.eclipse.jetty.server.server"> <!-- ===================================================================== --> <!-- configure sessionidmanager --> <!-- ===================================================================== --> <set name="sessionidmanager"> <new id="idmgr" class="org.eclipse.jetty.server.session.jdbcsessionidmanager"> <arg> <ref refid="server"/...

java - Error NullPointer Neuroph doOneLearningIteration -

i'm using neuroph 2.9 framework code ann predict housing prices. want every error every time run every epoch (to show improve of error on chart) cause error. // create multi layer perceptron system.out.println("creating neural network"); multilayerperceptron neuralnet = new multilayerperceptron( transferfunctiontype.sigmoid, inputscount, hiddentscount1, outputscount); // set learning parameters momentumbackpropagation learningrule = new momentumbackpropagation(); learningrule.setlearningrate(0.3); learningrule.setmomentum(0.5); learningrule.setneuralnetwork(neuralnet); learningrule.settrainingset(trainset); learningrule.doonelearningiteration(trainset); i this: exception in thread "main" java.lang.nullpointerexception @ org.neuroph.nnet.learning.momentumbackpropagation.updateneuronweights(momentumbackpropagation.java:72) @ org.neuroph.nnet.learning.backpropagation.calculateerrorandupdateoutputne...

angularjs - Does UWP app support ajax? -

i have windows 8 hybrid app , want migrate uwp. facing 2 issues , have been searching on internet quite few time. want know if uwp support ajax function. anchor tag in href not parsing. might reason. i want know if uwp support ajax function the answer yes, can use ajax in uwp application. there few things need notice when using ajax in uwp. if using ajax data remote server, please make sure internet(client) capability enabled in package.appmanifest . if want call ajax local server, make sure private networks(client & server) capability enabled. if using content security policy in app. make sure server address of ajax call included after default-src or connect-src in <meta> . details csp can refer this document . cross-origin should under concern when migrating. enable cors can refer add cors support server . my anchor tag in href not parsing. might reason. for safty reason, uwp doesn't support inline javascript. codes <a ng-click=...

ios - WebViewController - display -

i have created webviewcontroller view, displays websites in menu. have 2 cells, contact us, on click of cell shows web view contact , terms of use displays terms . my question how write code uses 1 of controller. // controller display web class webviewcontroller: uiviewcontroller { @iboutlet weak var webview: uiwebview! var urltoshow:string? override func viewdidload() { super.viewdidload() if let url = urltoshow { webview.loadrequest(nsurlrequest(url: nsurl(string: url)!)) } } } you should use sfsafariviewcontroller instead of webviewviewcontroller. if ([sfsafariviewcontroller class] != nil) { sfsafariviewcontroller *sfvc = [[sfsafariviewcontroller alloc] initwithurl:url]; sfvc.delegate = self; [self presentviewcontroller:sfvc animated:yes completion:nil]; } else { if (![[uiapplication sharedapplication] openurl:url]) { //nslog(@"%@%@",@"failed o...

java - Thread hangs while executing DNS query employing JNDI library -

below deadlock encountered result of thread getting locked while fetching txt record dns java.lang.thread.state: runnable @ java.io.fileinputstream.readbytes(native method) @ java.io.fileinputstream.read(fileinputstream.java:272) @ sun.security.provider.nativeprng$randomio.readfully(nativeprng.java:202) @ sun.security.provider.nativeprng$randomio.ensurebuffervalid(nativeprng.java:264) @ sun.security.provider.nativeprng$randomio.implnextbytes(nativeprng.java:278) - locked <0x00000004f3cd17b0> (a java.lang.object) @ sun.security.provider.nativeprng$randomio.access$200(nativeprng.java:125) @ sun.security.provider.nativeprng.enginenextbytes(nativeprng.java:114) @ java.security.securerandom.nextbytes(securerandom.java:466) - locked <0x00000004f111d290> (a java.security.securerandom) @ java.security.securerandom.next(securerandom.java:488) @ java.util.random.nextint(random.java:303) @ com.sun.jndi.dns.dnsclient.query(dnscl...

spring - Using integer as a parameter for POST HTTP request -

is possible use simple types, such integer, body http post request? have example: public void settimeout(@requestbody integer value) { storage.settimeout(value); } but unable send request trigger successfully. i think annotation need @modelattribute instead of @requestbody that public void settimeout(@modelattribute integer value) { storage.settimeout(value); }

c# - how to display date and time separately in grid view -

i have 1 column in sql table. name intime . data type nvarchar . stores both date , time. want date , time separately. i have tried query: select attendancedate, substring(convert(varchar,intime,113),1,11)[intime], substring(convert(varchar,intime,113),13,19)[intime], indeviceid, outtime, outtime, outdeviceid, dbo.minutestoduration(duration) duration, status dbo.attendancelogs employeeid=2938 order attendancedate desc but if pass same sql command in grid view not working. public void bind() { sqlcommand cmd = new sqlcommand("select attendancedate,substring(convert(varchar,intime,113),1,11) [intime],substring(convert(varchar,intime,113),13,19) [intime],indeviceid,outtime,outtime,outdeviceid, dbo.minutestoduration(duration) duration,status dbo.attendancelogs employeeid='" + empidtxt.text + "' , year(attendancedate)=" + ddlyear.selecteditem + " , month(attendanc...

php - WP Query, with ACF to NOT show posts with a date older than today -

morning all, i'm attempting loop through posts in specific category if custom field (event_date) (acf) older today. query i'm using is: $today = current_time('ymd'); $args = array( 'category' => 42, // events category 'post_status' => 'publish', // published 'posts_per_page' => '0', // unlimited posts per page 'meta_query' => array( array( 'key' => 'event_date', // loop through posts when event date 'compare' => '>', // greater $today, ie in future 'value' => $today, ) ), 'meta_key' => 'event_date', 'orderby' => 'meta_value', 'order' => 'asc', ); in acf, i've set saved date default (yymmdd) , i've set match $today var (ymd) yet it's still showing event 23rd june. the client wanted them listed show events in date order, not show past events. i'v...

msbuild - Gulp task to web deploy from Visual Studio -

i have not found concrete example on how publishing via gulp task. has idea? this how i'm trying @ moment. gulp.task("deploy-to-azure", function() { var targets = ["build"]; console.log("publishing azure"); return gulp.src(["./src/feature/accounts/code"]) .pipe(foreach(function (stream, file) { return stream .pipe(debug({ title: "building project:" })) .pipe(msbuild({ targets: targets, configuration: "azure", logcommand: false, verbosity: "verbose", stdout: true, erroronfail: true, maxcpucount: 0, toolsversion: 14.0, properties: { deployonbuild: "true", deploydefaulttarget: "web deploy", webpublishmethod: "filesystem", deleteexistingfiles: "false", _finddependencies: "false", ...

How to handle .net dll event in a web page? -

i have .net dll generates event. event returns number. want dynamicaly view number on web page, updating every time value changes. how can acomplish that? should use? html, ajax, javascript? which technology web site using ? asp .net ? if have server code listening event, expose web service query number using javascript periodically another way use signalr or websockets but need know how pages build first give advices

copy database structure from sql server to other -

i want copy database sql server another, want copy structure (views, stored procedures, tables, fields, indexes, etc), no rows. tried generate script sql server management script verbose (task menu > create as) follow below steps generate script : right click on database select task select generate script task follow steps finally finish complete process you can either use sql server management object api (see task "creating, altering , removing databases" ): c# code generate sql script : public string generatescript() { var sb = new stringbuilder(); var srv= new server(@"your database server name"); var db= server.databases["your database name"]; var scrpt = new scripter(srv); scrpt.options.scriptdrops = false; var obj= new urn[1]; foreach (table tbl in db.tables) { obj[0] = tbl.urn; if (tbl.issystemobject == false) { stringcollect...

java - Unit & Integration Testing with Couchbase -

i setup new project using spring-data-couchbase , stumped on how should approach unit , integration testing here. typically jpa can mock out repository somehow (assuming similar couchbase spring) , okay unit testing, jpa wire in memory database , have full integration testing suite. there way couchbase? also if don't mind mentioning tips here first major nosql project :) thanks! couchbase not run in-memory unfortunately. unit testing have mock couchbase's api. there couchbasemock project facilitate that: https://github.com/couchbase/couchbasemock there possibility use runner prior launching test. there maven plugin allow run couchbase or couchbase docker image.

php - How can names in an echoed html tags be used -

i have code abc.php want create array of check boxes if try accessing name or id, doesn't seem work.is there alternative way this? <html> <body> <form method="post"> <?php echo ""."<input type='checkbox' name='check[]' id='check[]' />" $c=0; if(isset($_post['check[$c]'])){ echo "checked"; } ?> </form> </body> </html> you have $_post['check[$c]'] in single quotes, not replaced value of $c . not mention multidimensional arrays not work way. to check $_post variable treat array: $checked = $_post['check']; // $checked[0] - first element // $checked[1] - second etc

javascript - calling Google analytics in scroll event in jquery -

i have following code in master page google analytics. <script type="text/javascript"> (function (i, s, o, g, r, a, m) { i['googleanalyticsobject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new date(); = s.createelement(o), m = s.getelementsbytagname(o)[0]; a.async = 1; a.src = g; m.parentnode.insertbefore(a, m) })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga'); ga('create', '@system.configuration.configurationmanager.appsettings["googleanalyticsid"]', 'auto'); ga('send', 'pageview'); </script> i need call google analytics in js scroll event how call google analytics function scroll event ? can please me how solve this. ? a guy worked here in company developed library use google analytics classic, took track scroll plugin , adapted fire universal google analytics...

url rewriting - Adding rewrite conditions to the existing ones -

we had out customer request redirect custom url specific page in webshop directory, setup rewrite rule rewrie condition shown below rewritecond %{http_host} abc.xxx.com$ [nc] rewriterule ^/$ /online/index.php3?shopid=111 [r] rewritecond %{https_host} abc.xxx.com$ [nc] rewriterule ^/$ /online/index.php3?shopid=111 [r] as shown in above rules , condition request coming abc.xxx.com redirected web page in webshop id 111 , worked successfully after few weeks same customer had request add url redirection differn webshop id 112 used similar rewrite rule , condition replacing new url , webshop id, , added below old rewrite condition , rules , restarted apache when tested new url redirecting shop id 111 instead of 112. rewritecond %{http_host} def.xxx.com$ [nc] rewriterule ^/$ /online/index.php3?shopid=112 [r] rewritecond %{https_host} def.xxx.com$ [nc] rewriterule ^/$ /online/index.php3?shopid=112 [r] later had work around , changed order,i put new rewrite rules , conditions f...

ajax - Detect Heap Overflow in Javascript -

i work on javascript project. in project detected application crash when send data in ajax request. in text shield, each time users write character or copy past something, send data patch request back-end. if want trigger crash, send 4 or 5 time 10000 'a' characters. how detect if crash triggered javascript heap overflow? , how protect memory corruption? do have example of javascript heap overflow exploit , protection?

appleevents - respond to Apple Events in Python without using pipe characters around keys in dictionary -

i use appscript , aemreceive in py2app bundled python 2.7 application accept incoming apple events , return app's output apple events external application communicates app. this works quite well, 1 exception: when return dictionary, keys surrounded pipe characters need keys without these characters. example: send response external app: {has description:true, folder:file "travellerhd:users:andre:desktop:mynewfile"} instead app sends this: {|has description|:true, |folder|:file "travellerhd:users:andre:desktop:mynewfile"} the event handler has been installed using code: aemreceive.installeventhandler(get_property, "coregetd", ('----', 'request_string', aemreceive.kae.typeaerecord), ) where "get_property" name of function gets invoked once external app requests location info item. function returns dictionary: return ...

rest - How can I fetch a value from response of web_custom_request in LoadRunner -

i have lr script , using make call on rest api download file. file gets downloaded need value of file size downloaded verification purpose. here see in loadrunner console. action.c(50): web_custom_request("getimage") successful, 2373709 body bytes, 528 header bytes, 99 chunking overhead bytes. how can value 2373709?? tried using below code size returns little bit different above mentioned , not solving purpose. httpdownloadsize=web_get_int_property(http_info_download_size); lr_output_message("file size %i", httpdownloadsize); any appreciated. in advance help. http_info_download_size property stores last http response total download size. includes total size of headers , bodies of responses, , possible communication overhead. 2373709 body bytes total body size of responses got in particular step, if there several requests/responses in custom request step, number greater actual file size. i'd suggest validating response body size. there n...

lua - C#: using OR (short circuited version) for assignment -

in lua there nice feature checking if result of statement nil or not , using short circuited version of or react situation; such as: text = gettextfromuser() or "default text" which translates assign return value of gettextfromuser() text , if gettextfromuser() returned nil , assign "default text" text which nice trick use short circuit evaluation of or operator assignment. i'm wondering if c# || operators has such capabilities or not. if no, shortest way achieve same behavior? ternary operator? if statement? maybe null-coalescing operator? https://msdn.microsoft.com/en-ie/library/ms173224.aspx string a; string b = ?? "default value"; so example become: string text = gettextfromuser() ?? "default text"

android - Unable to boot freshly built CyanogenMod 13 -

after playing around latest build of cm device (12.1), decided try , build first rom. got linux, synced sources 13, etc. (my device tree here. ) i had grapple few audio-related build errors before got build. (if makes difference, commits had revert related pcm audio offloading.) now, when try boot rom, reboots recovery without displaying boot animation. looking @ /proc/last_kmsg , problem seems selinux: ... [ 4.340084] init: (initializing selinux enforcing took 0.51s.) [ 4.349071] type=1400 audit(1468237723.015:4): avc: denied { fowner } pid=1 comm="init" capability=3 scontext=u:r:kernel:s0 tcontext=u:r:kernel:s0 tclass=capability permissive=0 [ 4.349387] init: selinux: not set context /init: operation not permitted [ 4.349506] init: restorecon failed: operation not permitted [ 4.349699] init: security failure; rebooting recovery mode... [ 4.350353] sysrq : emergency remount r/o (triggered init:1) [ 4.350581] emergency remount complete [ ...

android - How to create a custom user property for firebase? -

the section on firebase console says that firebase app can have 25 uniquely named user properties (case-sensitive). should use properties non-variable attributes, such “handedness=right”, “spender=true”. in firebase documentation property said set way mfirebaseanalytics.setuserproperty("favorite_food", mfavoritefood); does mean every user property named k , having value v , need create user property in console " k=v " , set in code setuserproperty(k,v) ? so, user property called "favorite_food" having possible values "pasta" , "pizza", 1 needs create 2 new user properties in console "favorite_food=pasta" , "favorite_food=pizza" , set by, say, setuserproperty("favorite_food","pasta")? for every user property named k , need register entry in "user properties" tab in firebase analytics. every user user property value k=v , need call setuserproperty(k,v) . after...

c# - The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[]', but this dictionary requires a model item of type '' -

here view viewmodel:- @model _24by7callandbpopvtltd.models.jobdetailandapplymodel <table class="table table-striped"> @foreach (var item in model.jobdetail) { <tr> <td> @item.job_title </td> <td> <a href="@url.action("edit", new { id = item.job_id })"><i class="glyphicon glyphicon-pencil"></i></a> <a href="@url.action("delete", new { id = item.job_id })"><i class="glyphicon glyphicon-remove" style="color:red"></i></a> ...

SoftLayer API: How to get RAM billing for virtual servers -

querying softlayer api on softlayer_account/getvirtualguests billingitem, can retrieve hourlyrecurringfee shows cost per hour softlayer charges virtual servers. unfortunately computing part, , ram not included there. there way ram cost well? if that's not case, i'd ram prices per location available when provisioning virtual server. there way through api? thanks , regards, markos you need see children property of billingitem, try request. get https://api.softlayer.com/rest/v3/softlayer_account/getvirtualguests?objectmask=mask[billingitem[children]] regards

excel - GeneralException if cell being edited -

i have js code in excel addin works fine while no cell in edit mode. if there's cell being edited call context.sync() fail generalexception 'invalid api call in current context.' excel.run(function (ctx) { //this line enough fail return ctx.sync(); }).catch(function (error) { }) is there way 'release' cell js? the fact edit-mode makes api call fail "known-issue", , not fixable -- vba exhibits same problem [most] of api calls. that said, idea of having js method explicitly un-cell-edit interesting thought. worry whether correspond users' intention, if corresponds developer feels they'd have. i'll run our team, though think best way track via "official" suggestion can file here: https://officespdev.uservoice.com/ at least, more helpful error message and/or specific error code. again, let me discuss team.

python - Built-in functions vs recursive functions -

i not mathematician, nor computer scientist - hobbyist programmer , trying teach myself python doing euler project problems. 1 of them requires use of factorial. wrote own calculation using recursive function , realised there built-in function use. having found thought see how quicker recursive function. surprise find slower. does surprise anyone? curious. i enclose code (and measure have included loop method comparison). import math import time x = 50 def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) secs = time.clock() print(math.factorial(x)) print ("the built-in function took {a:0.5f} seconds.".format(a = time.clock() - secs)) secs = time.clock() print (factorial(x)) print ("the recursive function took {a:0.5f} seconds.".format(a = time.clock() - secs)) secs = time.clock() factl = 1 in range (1,x+1): factl *= print (factl) print ("the loop method took {a:0.5f} seconds.".format(a = time.clo...

javascript - Jquery :How to store textbox value clientside and display? -

the below code update display value enter user in textbox when button clicked in code not preserve previous value enter user . <h1>type comment below </h1> <input id="txt_name" type="text" value="" /> <button id="get">submit</button> <div id="textdiv"></div> - <div id="datediv"></div> jquery(function(){ $("button").click(function() { var value = $("#txt_name").val(); $("#textdiv").text(value); $("#datediv").text(new date().tostring()); }); }); now want preserve value enter user , when user submit button show both value previous current. how achieve ? can below code preserve value var $input = $('#inputid'); $input.data('persist', $input.val() ); if yes how display value previous,current etc. when user click on button ? if got right, need? <h1...

c# - WPF application with Entity Framework, proper settings for app.config -

i have wpf program uses entity framework (db first approach). works fine on development laptop, crashes right @ beginning on other computers , it's because how can not connect db. but root of problem, read many things online, , although don't have answer seems has connection string , app.config in general. i use microsoft sql server management studio on development laptop , i've installed microsoft sql server on test unit. the whole scenario want publish application , user can download , install easily. here app.config : <?xml version="1.0" encoding="utf-8"?> <configuration> <configsections> <section name="entityframework" type="system.data.entity.internal.configfile.entityframeworksection, entityframework, version=6.0.0.0, culture=neutral, publickeytoken=b77a5c561934e089" requirepermission="false" /> </configsections> <st...

php - .htaccess password protected folder goes to 404 page -

i've stumbled upon strange issue. lets have folder in main domain directory: /myfolder when try access index of files in folder go to: myurl.com/myfolder , works without problems. when put .htaccess password protection in folder like: authuserfile /home/mywebsite/.htpasssomerandomname authtype basic authname "authentication required" require valid-user suddenly instead of asking me password when try access myurl.com/myfolder 404 wordpress template page. below .htaccess in main wordpress folder. <ifmodule mod_rewrite.c> rewriteengine on rewritebase / rewriterule ^index\.php$ - [l] rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule . /index.php [l] </ifmodule> any ideas might problem? i don't understand why seems adding below line .htaccess inside protected folder fixed issue: errordocument 401 "authorisation required" i've found fix online without explanation why works way. can add ex...

bash, non-blocking stdin/console input -

i write (using bash) while no_user_key_pressed { do_something.... } there few options using c++, java, ncurses , others o/s specific. want simple bash portable function. ^c interrupt should used kill remaining code. imagine like: 'press key stop test' you can use small timeout on read -t . the drawback user must press < return >, not "any key". for example: while ! read -t 0.01 echo -en "$(date)\r" done echo "user pressed: $reply" tested on bash 3.2 (os x) the ! because read returns failure (false) if timeout expires.

css - UI looks different in localhost and hosted website(GoDaddy) -

i hosted asp.net mvc website in godaddy, appearance looks little bit different. navigation bar black (the default of mvc 5), turns blue. , background image not showing. cause if this? please help. thank you. tried background image: background-image: url('image/bg30.png'); ---this 1 works in localhost, not in hosted website background-image: url('/content/image/bg30.png'); ------also works in localhost, not in hosted website background-image: url('../image/bg30.png'); --- 1 doesn't work in both your reference images in css file must relevant css file's location. might idea use absolute paths instead of relative paths. this article offers explanation of when , why use absolute paths. relative: /content/images/bg30.png absolute: http://www.example.com/content/images/bg30.png example: css file: example.com/content/styles.css bg image file: example.com/content/images/bg30.png background-image: url('images/bg30.png...

lotusscript - Lotus notes validation for role -

i new lotus notes development. problem is: in front page have created 1 hyperlink register. href=""><u><font size="5" color="#0000ff" face="arial">register</font></u></a> when click hyperlink go below url in hotspot. @urlopen("/htj.nsf/open") now have 2 url's 1 "/homr.nsf/close" , "/htj.nsf/open" , have 2 different roles admin , normal user .... task if role of particular user admin url has go @urlopen("/htj.nsf/open") and if normal user url has go @urlopen("/homr.nsf/close") wrote code in same hotspot if(role == "admin") { @urlopen("/htj.nsf/open") }else { @urlopen("/homr.nsf/close") } but not leaving me save code different kindly please me how can make role validation , open url. thanks , time change formula to @urlopen(@if(@userroles = "[admin]"; "/htj.nsf/open"; ...

python 3.x - Create os.DirEntry -

does have hack create os.direntry object other listing containing directory? i want use 2 purposes: tests api container , contained queried @ same time in python 3.5 os.direntry not yet exposed. details: https://bugs.python.org/issue27038 python 3.6 exposes os.direntry type, cannot instantiated. on python 3.5 type() on direntry object returns posix.direntry

How to view days of Hystrix metrics in a dashboard for monitoring -

hystrix dashboard shows metrics short period, 10 secs. there way can store , see metrics past week or so? i came across tools graphite, servo, etc. couldn't understand how these tools integrated hystrix stream. i'm looking how answer rather what use answer . thanks in advance. if you're using spring boot pretty easy send hystrix metrics -> statsd -> graphite. example export statsd .

java - Can I add jars to maven 2 build classpath without installing them? -

maven2 driving me crazy during experimentation / quick , dirty mock-up phase of development. i have pom.xml file defines dependencies web-app framework want use, , can generate starter projects file. however, want link 3rd party library doesn't have pom.xml file defined, rather create pom.xml file 3rd party lib hand , install it, , add dependency pom.xml , tell maven: "in addition defined dependencies, include jars in /lib too." it seems ought simple, if is, missing something. any pointers on how appreciated. short of that, if there simple way point maven /lib directory , create pom.xml enclosed jars mapped single dependency name / install , link in 1 fell swoop suffice. problems of popular approaches most of answers you'll find around internet suggest either install dependency local repository or specify "system" scope in pom , distribute dependency source of project. both of these solutions flawed. why shouldn't apply ...

How to hide titlebars and toolbars in javascript button -

how display pop on java script button using window.open() function without tiltebar , tool bars i had tried using window.open("/apex/pagename?id=parameters","_blank", 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left); it opens new window titlebar , tool bars.i want hide tool bars , title bar. can 1 suggest solution or alternate above question using code, toolbars , titlebars hidden me (in chrome, browser trying on?). if looking hide close buttons well, don't think that's possible due security issues, http://www.codeproject.com/questions/79625/how-to-hide-title-bar-in-javascript-popup (feature no longer supported) if specify trying achieve, maybe there other way around, , popups not preferred. maybe want modal

java - POST request returns 415 error -

i'm trying call post request (using jersey api rest) html form using angularjs v 1.5.8. have html form submit button calls rest serivce: <body ng-app="myapp" ng-controller="logincontroller"> ...... <form name="myform" nonvalidate ng-submit="login()"> ...... <div class="col-md-4 col-md-offset-4 col-sm-4 col-sm-offset-3 col-xs-6 col-xs-offset-3"> <button type="submit" class="btn btn-default" ng-submit="login()">submit</button> </div> </form> this logincontroller script: var app = angular.module ("myapp", []); app.controller("logincontroller", function($scope, $http){ $scope.username = ""; $scope.password = ""; $scope.login = function() { var transform = function(data) { return $.param(data); } $http( { url : 'http://loca...

php - Magento Submit an order based on all items in cart -

ive tried next can find, , nothing create order me. im wanting transfer cart quote order , sort of custom checkout , heres class: <?php ini_set("display_errors", 1); error_reporting(e_all); class mycompany_finance_indexcontroller extends mage_core_controller_front_action{ public function indexaction(){ $conn = mage::getsingleton('core/resource')->getconnection('core_read'); $conn->query("create table if not exists `v12_finance_sales` ( `sales_id` int(11) not null auto_increment, `sales_reference` varchar(50) not null unique, `customer_id` int(11) not null , `products` text not null , `total_price` varchar(255) not null , `status` varchar(4) not null , primary key(`sales_id`) )"); $this->loadlayout(); $block = $this->...

javascript - jQuery ID matching -

this toggle on mouseover event works fine: jquery(document).ready(function(){ jquery(".info").hide(); jquery(".trigger").mouseout(function(){ jquery(".info").slideup(200); }); jquery(".trigger").mouseover(function(){ jquery(".info").slidetoggle(); }); }); but have many objects if trigger trigger, shows me areas info class. easiest way adding id : <div class="trigger" id="1">details</div> <div class=" info" id="1"> <p> <b> projektbeschreibung </b> </p> <p> lorem ipsum one. </p> </div> <div class="trigger" id="2">details</div> <div class=" info" id="2"> <p> <b> projektbeschreibung </b> </p> <p> lorem ipsum two. </p> </div> so trigger triggering info witch belongs. i'm not...

c# - Adding a watermark to Microsoft Word Document -

i attempting add watermark microsoft word headers using vsto , shapes.addtexteffect , seems add correctly until check different first page , different odd & pages check-boxes in header , footer design. it seems adding odd page header, i'm not sure why i'm passing in different header types, find code below. private static void updatewatermark(comobjectwrapper<document> doc, string watermarktext, string watermarkname, style style) { foreach (section section in doc.resource.sections) { if (!watermarktext.isnullorempty()) { insertwatermark(section.headers[wdheaderfooterindex.wdheaderfooterprimary], section, watermarktext, watermarkname + (int)wdheaderfooterindex.wdheaderfooterprimary, style); if (section.pagesetup.differentfirstpageheaderfooter == -1) insertwatermark(section.headers[wdheaderfooterindex.wdheaderfooterfirstpage], section, watermarktext, watermarkname + (...