Posts

Showing posts from May, 2010

Can Golang multiply strings like Python can? -

python can multiply strings so: python 3.4.3 (default, mar 26 2015, 22:03:40) [gcc 4.9.2] on linux type "help", "copyright", "credits" or "license" more information. >>> x = 'my new text long' >>> y = '#' * len(x) >>> y '########################' >>> can golang equivalent somehow? it has function instead of operator, strings.repeat . here's port of python example: package main import ( "fmt" "strings" "unicode/utf8" ) func main() { x := "my new text long" y := strings.repeat("#", utf8.runecountinstring(x)) fmt.println(y) } note i've used utf8.runecountinstring(x) instead of len(x) ; former counts "runes" (unicode code points), while latter counts bytes. in case of "my new text long" , difference doesn't matter since characters 1 byte, it's habit of specif

apache - YII (PHP Framework) and OSX (El Capitan) -

Image
after upgraded mac osx development environment stopped working. not sure if related apache provided apple, happening when try access application complains of required files not found. i have following .htaccess: rewriteengine on rewriterule ^install\/ ./index.php?r=install/main/index [l,qsa] # if directory or file exists, use directly rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d # otherwise forward index.php rewriterule . index.php directoryindex index.php adddefaultcharset utf-8 code here at httpd.conf enabled php , rewrite modules. i've set allowoverride in directory sector in httpd.conf. these error getting when trying access: also, when try access other url mapped on yii, same error 404 not found. any idea? thanks in advance , regards, edu you don't have mod_rewrite enabled in apache settings. make sure line not commented out in /etc/apache2/httpd.conf : loadmodule rewrite_module libexec/apache2/mod_rewrite.so

c++ - Does a port of the C library need to be implemented in C? -

i'm working on kernel. 1 of tasks in writing kernel c library must ported. functions such memcmp , strlen , on have rewritten. of time see code written in c, , wrapped in extern "c" . however, complicates build process because there's lot of files written in c, , lot of files written in c++, must linked , it's headache. nice if entire thing written in c++. would make sense?

Firebase security rules based on userId attribute -

please see data structure "errands" : { "-k0dgrao6vsqkhrwiajq" : { "name" : "milk", "permissions" : [ { "userid" : "ca8d19cb-f1d7-4bfd-9471-fb88c469b6ca" }, { "userid" : "ef4bacad-d713-47ac-853e-b3ec3e4bf684" } ], "store" : "coscto" }, "-k0dhstsyrfm3uzjptnn" : { "name" : "milk", "permissions" : [ { "userid" : "ca8d19cb-f1d7-4bfd-9471-fb88c469b6ca" }, { "userid" : "ef4bacad-d713-47ac-853e-b3ec3e4bf684" } ], "store" : "coscto" } } i trying provide access based on userid attribute. says access denied. ".read": "root.child('errands').child('permissions').child('userid').val() === auth.uid ",

curl - How to make a https post in Java? -

hello being developer beginning in world of java want know how write equivalent of curl in java. curl -x post \ -h "authorization:basic sisi" \ -d "grant_type=client_credentials" \ "https://api.orange.com/oauth/v2/token" you can use apache httpclient implement in java. one example - string url = "https://api.orange.com/oauth/v2/token"; httpclient client = httpclientbuilder.create().build(); httppost post = new httppost(url); post.setheader("authorization", "basic sisi"); httpresponse response = client.execute(post); bufferedreader rd = new bufferedreader(new inputstreamreader(response.getentity().getcontent())); stringbuffer result = new stringbuffer(); string line = ""; while ((line = rd.readline()) != null) { result.append(line); } //print result read more here - http://www.mkyong.com/java/apache-httpclient-examples/

python - pandas join data frames on similar but not identical string using lower case only -

i need join data frames on columns similar not identical. fortunately, lowercase letters identical between columns. trying isolate lowercase letters each column, create new columns join on. df1 = pd.dataframe({'alpha': ['1', '2', '3'], 'beta': ['jrleparoux', 'bjhernandez,jr.','sxbridgmohan'],}) df2 = pd.dataframe({'alpha': ['1', '2', '3'], 'gamma': ['leparoux r', 'hernandez,b, jr.','bridgmohan s x'], 'zeta': ['17', '23','116'],}) this have tried def joinnames(df): filelist = [] c in df: if c.islower(): filelist.append(c) return filelist df1['joinhere'] = df1['beta'].apply(joinnames) df2['joinhere'] = df2['gamma'].apply(joinnames) pd.merge(df1,df2, how ='left', left_on = 'joinhere', right

tree - GIven a level order FInd BST -

given bst level-order traversal is: 99 65 53 80 22 62 98 21 49 82 36 51 what tree if make tree following level order traversal? here's how arrived @ bst present @ bottom. the main governing rule 1 has apply bst: if "order" elements, every node in left subtree of node has considered "before" node, , every node in right subtree has considered "after" node. since list numbers, , nothing more rules ordering, numerical ordering assumed. as such, when placing nodes have find correct location of each node given following procedure: decide if can find place on current level (if there room more nodes there). find find places place if didn't care bst rule. check each such position see if legal position. there should one. if find such place, place there, if not, go next level , place in leftmost legal position there. when placing more nodes on existing level, go left right. so here's runthrough of given numbers: the firs

c# - How can I add a new custom standard value token for sitecore branch templates? -

sitecore comes several standard custom value tokens when creating branch templates (i.e. $name name of new item, $parentid , id of parent). is there anyway add new variables? specifically want variable allow me access items path when added? there sitecore blog post add custom standard values tokens in sitecore asp.net cms tbh, it's wrong (not sure why sitecore insist on producing " untested prototype(s) " time in these posts?!). for reason guy jumping though various hoops decompile source , recreate (apart form fact makes code fragile should default behaviour change), unnecessary. you can add new variable in few lines of code: public class newvariablesreplacer : mastervariablesreplacer { public override string replace(string text, item targetitem) { //still need assert these here sitecore.diagnostics.assert.argumentnotnull(text, "text"); sitecore.diagnostics.assert.argumentnotnull(targetitem, "target

binding mysql database to dropdown list vb.net -

i need binding mysql database dropdown list. here's how connect database dim connectionstring string = configurationmanager.connectionstrings("dbstring").connectionstring dim connectme odbcconnection = new odbcconnection(connectionstring) dim odbcdataset dataset = new dataset() dim sqlquery string = "select * treconcalculation fid = " & request.querystring("id") connectme.open() dim odbcdataadapter odbcdataadapter = new odbcdataadapter(sqlquery, connectme) odbcdataadapter.fill(odbcdataset, "treconcalculation") connectme.close() make1 = odbcdataset.tables("treconcalculation").rows(0).item(1) model1 = odbcdataset.tables("treconcalculation").rows(0).item(2) cc1 = odbcdataset.tables("treconcalculation").rows(0).item(3) below2 = odbcdataset.tables("treconcalculation").rows(0).item(4) below3 = odbcdataset.tables("treconcalculation&q

css - Redactor image upload set inline style -

i using redactor v10.0.9 allow users create custom posts web app. these posts rendered in iframe in modal, , need images uploaded have max-width of 100%. have tried maintain outside stylesheet append iframe contains img { max-width: 100% !important; } } but doesn't seem working @ all. add style="max-width: 100%" inline style img tag when it's inserted, can't seem find image inserted post after image upload. any ideas on how force these images in iframe max-width: 100% ? thanks edit 1: i using imagemanager plugin upload images redactor. forgot mention that. edit 2: the content contained in iframe dynamically created html, not content domain. figured out how this! instead of appending sort of style img tag on insertion, when render custom posts retrieving of images in iframe in javascript, , applying css attr of "max-width: 100%" on each one.

javascript - Find the last item in array in mongo document and check if its field is a certain value -

i got document: { _id: "zaphzeqw98uhwqaey", borrowerid: "dmgqyqenbnt4ebmia", isseenbyother: 1, lenderid: "jsjyvseqiiazgxruq", messages: [{ date: sun oct 25 2015 19:40:25 gmt+0100 (cet), from: "jsjyvseqiiazgxruq", text: "hi there" },{ date: sun oct 25 2015 19:40:35 gmt+0100 (cet), from: "dmgqyqenbnt4ebmia", text: "hey!" }] } what i'm trying boolean value stating whether or not value of field from of the last object item in array: messages current user. i have tried lot of different mongodb projections such $slice , $position inserts in beginning of array not ideal case. you can use underscore's _.last() function follows: var doc = mycollection.findone({ _id: "zaphzeqw98uhwqaey" }); var lastelement = _.last(doc.messages); if ( lastelement.from === meteor.userid() ){ ... thing }

elastic beanstalk - Django Elasticbeanstalk: Cannot access static files when Debug = False -

my static files served no issue when debug = true. have read documentation on https://docs.djangoproject.com/en/1.8/howto/static-files/deployment/ still cannot work when debug = false. these settings (works fine when debug = true): base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) static_url = 'myapp/static/' static_root = os.path.join(os.path.dirname(base_dir),"myapp","static","static-only") staticfiles_dirs = ( os.path.join(os.path.dirname(base_dir),"myapp","static"), ) i have edited config file be: container_commands: collectstatic: command: "myapp/manage.py collectstatic --noinput" option_settings: "aws:elasticbeanstalk:application:environment": django_settings_module: "myapp.settings" pythonpath: "/opt/python/current/app/myapp:$pythonpath" "aws:elasticbeanstalk:container:python": wsgipath: "

How to config SharedPreferences for the first run activity in the Android? -

i have 3 activity: 1- splashscreensactivity 2- introactivity 3- mainactivity i need do, @ first launch appliation start introactivity else mainactivity after splashscreenactivity . edited: i wrote code did not work , after showing splash screen, mainactivity started , introactivity never start. plese let me know problem. intro.java: sharedpreferences settings=getsharedpreferences("prefs", 0); final boolean firstrun=settings.getboolean("firstrun",false); if(firstrun==false) { sharedpreferences.editor editor=settings.edit(); editor.putboolean("firstrun",true); editor.commit(); intent i=new intent(intro.this,intro.class); startactivity(i); finish(); } else { intent a=new intent(intro.this,mainactivity.class); startactivity(a); finish(); } splashscreeactivity.java: public class splashscreensactivity extends activity { private imagev

javascript - How to display Json Data getting [object object]? -

$.getjson('data.json', function (data) { $.each(data.questions, function (index, data) { console.log(data); }); }); // getjson data json: { "questions": [ { "qset": { "q1": "template 1 question1", "q2": "template 1 question2", "q3": "template 1 question3", "q4": "template 1 question4", "q5": "template 1 question5" } }, { "qset": { "q1": "template 2 question1", "q2": "template 2 question2", "q3": "template 2 question3", "q4": "template 2 question4", "q5": "template 2 question5" } }, ] }

axapta - Connector for Microsoft Dynamics: Setting owner to team in CRM (instead of user) -

Image
the connector microsoft dynamics between ax , crm default sets ownership of records in crm integration user (or maps specific users if has been configured). how make connector set team owner in crm? you can have connector set owner in crm team doing following: open connector microsoft dynamics. open map want configure (e.g. customer service account ). expand owning user , remove mapping. expand owning team , add team name in dynamics integration key , either constant or mapping. note should name of team (not integration key, if have configured team entity integration). save changes , wait integration run. in end map should following:

regex - Java : Checking if 2 text-paragraphs are different giving error at delete sentence -

i working on java application note-taking. now, whenever user edits text in note, want find difference between oldtext , newtext can add history of note. for dividing each paragraph multiple strings splitting them @ dot. comparing sentences in string-list using diff-match-patch. as of works fine add, edit in text, delete sentence, gives problem. situation old text : sentence1, sentence2, sentence3, sentence4 new text : sentence1, sentence3, sentence4. but because of that, comparator sees sentence2 replaced sentence3, sentence3 sentence4 , so-on , so-forth. this not desired behaviour, don't know how remedy situation. post code, kindly let me know how can differences between them properly. groupnotehistory object in saving oldtext , newtext changes only. hope code understandable. // below list of oldtext , newtext splitted @ dot. list<string> oldtextlist = arrays.aslist(mnotes1.getmnotetext().split("(\\.|\\n)")); list<string&

model view controller - MVC JavaFx methods -

if want add example mouse event "setonmouseentered" code , have viewer, controller, model , main. put method in? because if search examples, methos written in start-method. in case in main class? have kind of scene styler in viewer. thanks! do search this? https://github.com/stefanheimberg/javafx8-spielwiese/tree/master/example-fullscreen-fade/src/main/java/example/menubar . in menubar.fxml (view) used onaction="#handleimage2longrunningaction" , fx:controller="example.menubar.menubarpresenter" (controller) then on presenter called service (model / business logic)...

Powershell 3.0: Returning a list of file names with last write times within the past 24 hours -

i writing script checks, recursively, folders , file names in directory, , returns names , last write times text file. want names of files , folders have been added within past twenty 4 hours. $date = get-date get-childitem 'r:\destination\path' -recurse | where-object { $_.lastwritetime -lt $date -gt $date.adddays(-1) } | select lastwritetime, name > 'c:\destination\path\lastwritetime.txt' | clear-host invoke-item 'c:\destination\path\lastwritetime.txt' the .txt file invoked blank, which, based on test conditions have set should not case. doing wrong? you missing logical and . change: where-object { $_.lastwritetime -lt $date -gt $date.adddays(-1) } to where-object { $_.lastwritetime -lt $date -and $_.lastwritetime -gt $date.adddays(-1) } even better use parenthesis, if have used them syntax not have been parsed missing and : where-object { ($_.lastwritetime -lt $date) -and ($_.lastwritetime -gt $date.adddays(-1)) }

php - Assigning values to variable on the fly in WHILE loop condition -

i've piece of code $limit = 100; $offset = 0; while (array() === ($contactidlist = $this->getdata($limit, $offset))) { $count = count($contactidlist); //using $count , $contactidlist doing logging stuff $offset += $limit; } $this->getdata($offset) //returns array of results query in set $limit, $offset when results been fetched returns empty array , while conditions end. my question i'm assigning array results in $contactidlist in while condition save 1 line $contactidlist = $this->getdata($limit, $offset) inside while condition. right way? this looks fine me. 1 suggestion, can use empty() if using php 5.5.0 , later check empty array $limit = 100; $offset = 0; while(!empty($contactidlist = $this->getdata($limit, $offset))) { $count = count($contactidlist); //using $count , $contactidlist doing logging stuff $offset += $limit; }

sitecore8 - Sitecore 8.1 Upgrade Media section broken -

Image
i upgraded sitecore 7.0 8.1. real problem have ran media section broken , images appear broken on site itself. the weird part , can upload , download media items. broken in both chrome , firefox. thanks ] 1 update <encodenamereplacements> <replace mode="on" find="&amp;" replacewith=",-a-," /> <replace mode="on" find="?" replacewith=",-q-," /> <replace mode="on" find="/" replacewith=",-s-," /> <replace mode="on" find="*" replacewith=",-w-," /> <replace mode="on" find="." replacewith=",-d-," /> <replace mode="on" find=":" replacewith=",-c-," /> </encodenamereplacements> it looks problem sitecore media protection (included first time in sitecore 7.5). you can read more in adam blog post "do

r - I'm getting an error when I try to replace NA with 0 -

mergedata large matrix, trying replace na 0 did "googling" , found code below not work because mergeddata[is.na(mergeddata)] <- 0 warning message: in `[<-.factor`(`*tmp*`, thisvar, value = 0) : invalid factor level, na generated further research had me doing for loops i'm still not getting it. recommendations on how this?

iOS Code Signing Fails Only For Jenkins -

i'm trying build xamarin touch project jenkins build fails @ code signing phase. my certificates , keys in system keychain should accessible jenkins. have no code signing issues when build project: using xamarin studio. using /bin/bash , xbuild logged in jenkins user. using /bin/sh , xbuild logged in jenkins user. the time code signing issue seen when jenkins build itself. the error "user interaction not allowed", i'm @ loss explain going wrong jenkins build when working jenkins user when run same command shell. you try importing credentials in jenkins credentials area. from here : allowing jenkins stage developer profile plugin builds on top of credentials plugin allow store apple developer profile (*.developerprofile) file. file contains code signing private key, corresponding developer/distribution certificates, , mobile provisioning profiles. can create file xcode. to upload developer profile jenkins, go "ma

c++ - DirectX Game LPD3DX9Sprite Rendering Slow -

hey trying build 2d engine in c++ can handle thousands of sprites @ time using directx sdl. heard lpd3dx9sprite efficient , coming xna style familiar me. doing performance testing, batching multiple sprites (same texture , settings) in 1 time. however, there seems issues performance , idk why. void draw() { graphics::direct3d_device->clear(1, null, d3dclear_target, d3dcolor_argb(255, 0, 0, 0), 0, 0); graphics::direct3d_device->beginscene(); graphics::spritebatch->begin(d3dxsprite_alphablend); string fs = std::to_string(fps); (int = 0; < 1000; i++) test.draw(); drawtextstring(32, 64, fs.c_str()); graphics::spritebatch->end(); graphics::direct3d_device->endscene(); graphics::direct3d_device->present(null, null, null, null); } this draw code calls function calls drawmethod of lpd3dx9sprite object. nothing else going on in game drawing code. according fps counter getting 4fps. vsync enabled slowdown occurs regardless. there can this? i find odd

Swift UISlider that gets its values from an array of numbers -

i'm newbie swift , believe me i've searched , searched answer already. want create uisliders values array of numbers in swift. camera app example array should obvious. @ibaction func isovaluechanged(sender: uislider) { let isoarray = ["24", "32", "50","64","80","100","125","160","200","250","320","400","500","640","720","800","1000","1250","1600","1800"] // available iphone 6s iso settings believe let currentvalue = // need? isotext.text = "\(currentvalue)" } even harder representing shutter speeds 1/1000 - 32! see out there not easy 1 because there no mathematical representation calc array. possible? i'm not quite sure understand want i'm guessing right. // global variable or (accessible multiple functions) let isoarray = ["24&

How can i add javascript files into an existing web page with firefox add on sdk -

i toying around firefox sdk add on right now, , want add javascript files existing website - adding jquery existing website. how do that? there solutions that. 1 example following: var tabs = require("sdk/tabs"); var data = require("sdk/self").data; tabs.on('ready', function(tab) { var worker = tabs.activetab.attach({ contentscriptfile: [ data.url("jquery.min.js") ] }); }); where jquery.min.js in data folder of extension , attached active tab. one other solution use pagemod allow determine in web pages js attached. in following example attached mozilla.org.: var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contentscriptfile: data.url("my-script.js") });

node.js - Mongoose Query Nested Data Multiple Word Key -

i cannot find example of how build query property name of nested property multiple words. var student = { name: 'kevin', address: { 'street 1': '123 main', 'street 2': 'apt 2' city: 'chicago' }; // works. var query = student.find({ 'address.city': 'chicago' }); i cannot figure out how query street 1. // tried this. did not work. var query = student.find({ 'address["street 1"]': '123 main' }); use same dot notation syntax, should work: // tried this. works. var query = student.find({ 'address.street 1': '123 main' });

java - Getting error when using BeanUtils.copyProperties(dest, src) -

i have 2 form classes public class form1{ int id, string name, datetime lastmodified; //setters , getters } public class form2 { int id, string name, date lastmodified; //setters , getters } ie., 1 of form has same variable name lastmodified date type , other 1 joda datetime type i trying copy form1 values form2 form1 form1 = dao.getform1(); form2 form2 = new form2(); beanutils.copyproperties(form2,form1) but giving me error org.apache.commons.beanutils.conversionexception: dateconverter not support default string 'date' conversion. i tried solution given in https://stackoverflow.com/a/5757379/1370555 but giving me error org.apache.commons.beanutils.conversionexception: error converting 'org.joda.time.datetime' 'date' using pattern 'yyyy-mm-dd hh:mm:ss.0 z' i think can solved apache convertutils not getting how done can 1 me solve this? beanutils.copyproperties(form2,form1) copies property valu

Is there a simple simulation of the law of large numbers in r? -

Image
i understand law of large numbers, can't find simple example simulating in r. can give me example of law in r? this question closed, perhaps suffice: die <- 1:6 roll <- function(n) { mean(sample(die, size = n, replace = true)) } plot(sapply(1:1000, roll), type = "l", xlab = "# of dice", ylab = "average") abline(h = 3.5, col = "red")

javascript - Nav/Hamburger menu won't open on mobile -

i've got responsive site/app running html i'm trying push through phonegap , i've included nav menu here . nav menu works fine through browser can't work on mobile devices, nokia 920 running windows mobile 8.1 , samsung galaxy s6 on android. can guide me why menu won't work on phone? here's fiddle sample i've never tried before today hope works. and jic here's html. <body> <div class="shy-menu"> <a class="shy-menu-hamburger"> <span class="layer top"></span> <span class="layer mid"></span> <span class="layer btm"></span> </a> <div class="shy-menu-panel"> <ul> <li><a href="index.html">home</a></li> <br/> <li><a href="#">about</a></li> <br/> <li><a href="#"&g

open magnificPopup Ajax popUp with jQuery -

i'm using ajax popup magnificpopup . open popup within jquery click event don't how to that. $('.popup').click(function() { var id = $(this).attr('rel'); url = '/test-ajax.php?id=' + id; alert("url" + url); //this shows url popup should load }) the "normal" magnific popup class looks so: $('.simple-ajax-popup-align-top').magnificpopup({ type: 'ajax', aligntop: true, overflowy: 'scroll' }); thanks help. assuming ajax call produces html string, can try this: $('.popup').click(function() { var id = $(this).attr('rel'); url = '/test-ajax.php?id=' + id; $.ajax({ type: "post", url: url, success: function(result) { $('.simple-ajax-popup-align-top').magnificpopup({ aligntop: true, overflowy: 'scroll', items: {

java - If we are using Factory Pattern should we hide products from user? -

let have animalfactory class produces dog, cat , fish . using animalfactory makes things incredibly simpler , fine. my question is there rule or good practice suggests hide dog, cat , fish being used directly? mean dog mydog = new dog(); forbidden in code. if there is, how can hide them properly? yes, if objects should created through factory, should try avoid possibility of skipping rule. in c#, if consumers of dog, cat , fish on different assemblies, can make constructors internal, way factory, implemented in same assembly "animals" can create them. i'm sure there's similar in java.

charts - How to hide a bar if Value is null? -

how remove empty gap on chart if chart value null (or 0)? see example: http://jsfiddle.net/x13o8lgj/ you can see empty space on "mon 21 oct". how remove white gap? google.load("visualization", "1.1", {packages:["bar"]}); google.setonloadcallback(drawchart); function drawchart() { var data = google.visualization.arraytodatatable([ ['day', 'bmw', 'ford', 'toyota'], ['mon 19 oct', 4, 8, 3], ['mon 20 oct', 11, 4, 7], ['mon 21 oct', 6, null,6], ['mon 22 oct', 10, 5,2] ]); var options = { chart: { title: 'statistics', subtitle: 'car', }, }; var chart = new google.charts.bar(document.getelementbyid('columnchart_material')); chart.draw(data, options); it seems feature not supported consider following solution remove empty gap in bar group. idea move remain

php - redirect after sign up -

i have made script after sign have error, not redirect me index page here code insertuser.php include("/pages/classes.php"); $user = new user(); if( isset($_post['username']) && isset($_post['usermail']) && isset($_post['userpassword'])){ $user->setusername($_post['username']); $user->setusermail($_post['usermail']); $user->setuserpassword(sha1($_post['userpassword'])); $user->insertuser(); header("location: ../index.php?success=1"); } here public function public function insertuser(){ include "conn.php"; $req=$bdd->prepare("insert users(username,usermail,userpassword) values (:username,:usermail,:userpassword)"); $req->execute(array( 'username'=>$this->getusername(), 'usermail'=>$this->getusermail(), 'userpassword'=>$this->getuserpassword() )); } and link sign is http://demo

topology - storm spout didn't emit & result file empty -

Image
i'm new storm submitted different topologies form github storm-starter , others after problem faced of spout didn't emit ! is right ? or there problem ? where can find result after submitting topology ? guessed in result file in storm folder it's empty ! this have in bolt "one of them " there no explicit "result" file in storm. topology responsible handling/storing results wherever/whenever need to. can check log files each worker logs (system.out calls or logger bindings) or can have sink bolt writes whatever result need locally file on machine being executed or can have hdfsbolt write results hdfs file or can have external server receives results via sockets last bolt, etc... the list endless, you.

ios - How to constrain view's width to device width in interface builder? -

Image
i have view hierarchy i want content grow vertically in content view not horizontally. want constrain contentview's width same device's width. how can in interface builder ? note: image's width in image view bigger device's width, right contentview's size grows both vertically , horizontally just add constraints content view leading space,trailing space,top space,bottom space along fix content view width constraint constant , create outlet width constraint value , in view controller side write method as -(void)viewdidlayoutsubviews { _scrollviewcontentviewwidthconstraint.constant = self.view.frame.size.width; }

c# - Improve WPF rendering performance using Helix Toolkit -

i rendering large number of meshes loaded stl , added viewport helixviewport3d object. meshes static in environment. // in mainwindow.xaml <helixtoolkit:helixviewport3d x:name ="viewport" zoomextentswhenloaded="true" margin="250,-15,0,15"> // in mainwindow.cs constructor this.viewport = new helixviewport3d(); foreach(string path in meshpaths){ modelvisual3d meshmodel = loadmesh(path); viewport.children.add(meshmodel); } since number of meshes high, rendering performance quite low (it freezes during rotations, hard zoom in...). how can make scene easier rotate , manipulate?

python - The submitted form is not saved in sql - dJango -

i have searched posts issue still not find solution. after clicking "submit", page redirect page. sql database doesn't show submitted information. thanks in advance suggestion. views.py @csrf_exempt def input(request): if request.method == 'post': form = inputform(request.post or none, request.files or none) if form.is_valid(): company = form.cleaned_data['company'] region = form.cleaned_data['region'] uom= form.cleaned_data['uom'] start_date= form.cleaned_data['start_date'] end_date= form.cleaned_data['end_date'] add_input=input.objects.create(company=company,region=region,uom=uom,start_date=start_date,end_date=end_date) add_input.save() return redirect('resut') else: print(form.errors) else: form = inputform(initial={'company':'coco','uom&#

android - Login Facebook - Xamarin -

i'm developing app user use login access facebook. returning error , researched , apparently key problem, key in manifest. the following excerpt manifest <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/stg_app_nome" android:theme="@style/apptheme"> <activity android:name="com.facebook.loginactivity" android:theme="@android:style/theme.translucent.notitlebar" android:label="@string/stg_app_nome" /> <meta-data android:name="com.facebook.sdk.applicationid" android:value="xxxxxxx"/> </application> in layout <com.facebook.login.widget.loginbutton android:id="@+id/login_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_margintop="30dp" android:l

Testing Rails Shopify App with Capybara & Cucumber (upgrading Shopify plan in test causes authentication error) -

i have shopify rails app , trying test of functionality of "pro" plan, having trouble updating test shop plan. can login no problem, when try update shops plan via capybara, redirected login page. i've done troubleshooting, have no idea issue stemming because works fine when try manually in browser. maybe database_cleaner or caching issue? here's cucumber steps (basically login app, choose plan): background: given logged in user when on pro plan capybara: when "i logged in user" step "i visit login page" step "i supply shopify url" step "i taken app index page" end when /^i on (.+) plan$/ |plan| click_link_or_button "settings & notifications" click_link_or_button "edit plan" choose("shop_plan_#{plan}") click_link_or_button "update plan" click_link_or_button "approve charge" end the driver authenticates app, visits edit plan page, visit

c# - MVC4 Foreign Key property is null -

i have expenses , categories tables. have seeded tables few entries, when pulled db category property null. expect automatically populated entries category table. missing? model: public class expense { public int expenseid { get; set; } [datatype(datatype.currency)] public decimal amount { get; set; } [foreignkey("categoryid")] public category category { get; set; } [required(errormessage = "you must select category!")] public int categoryid { get; set; } } public class category { public int categoryid { get; set; } public string description { get; set; } public virtual icollection<expense> expenses { get; set; } } view: @foreach (var item in model) { <tr> <td> @html.displayfor(modelitem => item.amount) </td> <td> @item.categoryid </td> <td> @item.category.description //nullreferenceexcept

python - Move to python3 asyncio from python2 gevent -

i'm looking on python3 asyncio , looks pretty awesome, i'm coming gevent. however, i'm still trying figure out how everything. let's i'm trying simple service connects redis queue , pops items it. things out of hand pretty quickly: i'll need context manager close redis connection when object gets destroyed, i'll need async redis driver, , i'll need catch sigint , sigterm signals. import asyncio import asyncio_redis class agent(object): def __init__(self, name): print("hello, i'm %s" % name) self.name = name self.running = true # self.redis should become instance of asyncio_redis.connection def shutdown(self): self.running = false def __enter__(self): return self def __exit__(self): print("%s cleaned up" % name) self.redis.close() def loop(self): print("%s started looping" % name) while self.running:

.htaccess to remove .php extenssion in not working -

before posting here i've tried solutions url1 , url2 not fixed yet. .htaccess code this: rewriteengine on rewritecond %{request_filename} !-f rewriterule ^([^\.]+)$ $1.php [nc,l] in application $_get , $_post used , file structure in htdocs this: shopping ->(main folder) css(folder) images(folder) js(folder) .htaccess file1.php file2.php : : file9.php so how can rid removing .php in url check .htaccess applied in first place — see here ; make sure configuration allows overriding @ least fileinfo in .htaccess files (you may allowoverride all ): <directory "/var/www/html"> allowoverride fileinfo </directory> see this question details.

linux - How to display groupID (GID) correctly in C? -

i'm trying display userid , groupid through 1 of functions in c program. userid displaying correctly (501) groupid isn't. when check groupid using command "id -g" 20 when run through program using function value 1. this code. int registerpw(char **args){ register struct passwd *pw; register uid_t uid; int c; register gid_t gid; register struct group *grp; grp = getgrgid(gid); uid = geteuid(); pw = getpwuid(uid); if (pw) { printf("%d,",uid); // userid printf("%d,", gid); //groupid puts (pw->pw_name); puts(grp->gr_name); } else{ printf("failed\n"); } return 1; } my output 501,1,username daemon your code merely declared & defined variable of gid , left value uninitialized. shall assign correct value it: register gid_t gid; gid = getgid(); or simply: register gid_t gid = getgid();

r - how to split columns by certain category? -

my data this: dd gg site 5 10 7 8 5 6 b 7 9 b i want split column of site according a , b .desired output is: dd gg site gg_b 5 10 6 7 8 9 your request seems strange in way values site treated differently b values. using data: xx = structure(list(dd = c(5l, 7l, 5l, 7l), gg = c(10l, 8l, 6l, 9l ), site = structure(c(1l, 1l, 2l, 2l), .label = c("a", "b"), class = "factor")), .names = c("dd", "gg", "site"), class = "data.frame", row.names = c(na, -4l)) we can "spread" columns long wide format using tidyr::spread . eliminates site column , treats , b values of same: library(tidyr) (xx = spread(xx, key = site, value = gg)) # dd b # 1 5 10 6 # 2 7 8 9 adding gg_ prefix names: names(xx)[2:3] = paste("gg", names(xx[2:3]), sep = "_") xx # dd gg_a gg_b # 1 5 10 6 # 2 7 8 9 i prefer data in above for

java - NoSuchMethodException: main while running TestNG test on Spring application -

Image
i trying write test calling rest api using testng. try run using intellij idea, , following error: exception in thread "main" java.lang.nosuchmethodexception: test.api.testhospitals.main([ljava.lang.string;) @ java.lang.class.getmethod(class.java:1670) @ com.intellij.rt.execution.application.appmain.main(appmain.java:125) this test class. what's wrong it? why java need main method in it? lost. package test.api; import com.example.backend.entity.postgres.user; import com.example.backend.utils.jsonutils; import com.example.mainserver.service.rest.callbacklocalservice; import org.springframework.beans.factory.annotation.autowired; import org.springframework.test.context.contextconfiguration; import org.springframework.test.context.testng.abstracttestngspringcontexttests; import org.testng.annotations.test; import test.all.loginfabric; import test.all.patientpersonfabric; @contextconfiguration(locations = {"classpath:spring-test-config.xml"

playframework - What happens if WSRequest has too many get() parameters? -

i have rather bizarre question , not find answer anywhere. building wsrequest request in play! 2.4.3 , adding query params using setqueryparameter() request. after that, send them server using request.get() , retrieving result. everything works fine, curious, happen if parameters exceed limit of get(). need check , make 2 individual requests? handled somewhere or return exception? thanks i did not see numbers in documentation, know - there no limit query string in standards, it's depend realisation. what maximum possible length of query string? . pretty sure server can stuck in problem long query string before server. my proposed solution check simple code: package controllers; import javax.inject.inject; import play.*; import play.mvc.*; import play.libs.ws.*; import play.libs.f.promise; public class application extends controller { @inject wsclient ws; public promise<result> index() { wsrequest request = ws.url("http://httpbin

sockets - Jmeter Error: Java.net.SocketException: Connection reset at java.net.SocketInputStream.read(Unknown Source) at -

jmeter environment details performing jmeter testing on microsoft azure cloud. have created on vm(virtual machine) on same cloud , there hitting application server on same cloud environment. in case there no network latency. problem statement: trying run load test 300 users 30 mins , after 5 mins script started failing, because of socket connection refused error . my analysis based on information available on net: i have read somewhere problem because of limited socket connection limit on server, when run same test vm scripts run's fine. not server's issue. can please me resolve issue? there settings needs done in jmeter, increase socket connections? actual screenshot of error enter image description here most likely: looks situation described @ connection reset since jmeter 2.10 ? wiki page. if you're absolutely sure nothing wrong server, can follow next recommendations: switch http request samplers "implementation" "httpclient4

oauth 2.0 - How to decode the OAuth2 access token to get the username by Resteasy -

i beginner use resteasy provide oauth2 service. much! when use grant_type of client_crdentials, 1st step: requesting access token username , password. 2nd step: put access token authorization header call api. my question is, @ 2nd step, @ server side, how decode access token username used request access token in 1st step? because, want know calling api. much!

c# - why does it show me error that cost is an unassigned variable? -

console.writeline("enter sirial number of followin bevrege want buy"); console.writeline("beverge cost"); console.writeline("1.ness cafe 2.25"); console.writeline("2.black coffe 2.25"); console.writeline("3.tea 1.30"); console.writeline("4.hot choclate 2.50"); console.writeline("5.soup 3.10"); console.writeline("6.coca cola 3.30"); console.writeline("7.orange juice 3.20"); int sirial; sirial = int.parse(console.readline()); double mouny, cost; console.writeline("enter how ouny enterd machine "); mouny = double.parse(console.readline()); if (sirial == 1 || sirial == 2) cost = 2.25; if (sirial == 3) cost = 1.30; if (sirial == 4) cost = 2.50; if (sirial == 5) cost = 3.10; if (sirial == 6) cost

Extracting text from HTML file using Python -

i'd extract text html file using python. want same output if copied text browser , pasted notepad. i'd more robust using regular expressions may fail on poorly formed html. i've seen many people recommend beautiful soup, i've had few problems using it. one, picked unwanted text, such javascript source. also, did not interpret html entities. example, expect &#39; in html source converted apostrophe in text, if i'd pasted browser content notepad. update html2text looks promising. handles html entities correctly , ignores javascript. however, not produce plain text; produces markdown have turned plain text. comes no examples or documentation, code looks clean. related questions: filter out html tags , resolve entities in python convert xml/html entities unicode string in python html2text python program pretty job @ this.

java - How to compare two CSV file? -

i have 2 csv file 1st 1 ip geo-location csv file , second 1 have date time , ip address how compare both file , make new csv file have date time ip address , ip location(country name).how make in java? 1st file 18102015 11:35:59 93.178.13.37:2065 18102015 11:36:00 93.178.13.37:2078 18102015 11:36:21 93.178.13.37:7251 18102015 11:37:05 222.35.153.160:502 18102015 11:37:05 222.35.153.160:5050 2nd file 93.178.0.0 93.178.63.255 1571946496 1571962879 sa saudi arabia 93.178.64.0 93.178.127.255 1571962880 1571979263 ru russian federation 222.16.0.0 222.95.255.255 3725590528 3730833407 cn china i want result: 18102015 11:35:59 93.178.13.37 2065 sa saudi arabia 18102015 11:36:00 93.178.13.37 2078 sa saudi arabia 18102015 11:36:21 93.178.13.37 7251 sa saudi arabia 18102015 11:37:05 222.35.153.160 5029 cn china 18102015 11:37:05 222.35.153.160 5050 cn china hints: think of dotted ip address 4 octets of 32 bit n

ionic framework - ionicPopup doesnt close only hides. -

in code, when trigger ionicpopup, upon button tap, triggers ionicpopup should close previous ionicpopup. however, in implementation, while close final ionicpopup, initial ionicpopup doesnt close rather hides causes app freeze. there way make sure ionicpopups closed or @ least close each ionicpopup upon button tap. codepen of code http://codepen.io/anon/pen/dyvdjv $scope.showpopup = function() { $scope.data = {} $ionicpopup.show({ title: ' session terminated!', scope: $scope, template:' logged device/browser. pls log out other device/browser!', buttons: [ { text: '<h6 style="text-transform: capitalize;">cancel</h6>', type: 'button-positive' }, { text: '<h6 style="text-transform: capitalize;">verify me</h6>', type: 'button-positive', ontap: function(e) { $scope.verifyme();