Posts

Showing posts from June, 2011

r - Save an plot to an image, then draw additional lines on plot and save again. -

Image
i'm trying draw stripchart in r, save png file, draw more stuff on , save again. attempts far ended in error plot.new has not been called yet . corresponding code is # draw without lines png(c(name, '.png'), width=480, height=240); stripchart(data, pch=4, method='jitter'); dev.off(); # draw with lines png(c(name, '_with_trim_points', '.png'), width=480, height=240); abline(v=points, untf = false, col='red'); abline(v=more__points, untf = false, col='green') dev.off(); just calling stripchart(data, pch=4, method='jitter'); second time not option, since jitter different , end different scatterplot. with seed , generated data #generate data data=data.frame(x=rnorm(40),y=rnorm(40)) points=c(-2,0) more__points=c(1,2) # draw without lines set.seed(123) png(paste0(name, '.png'), width=480, height=240); stripchart(data, pch=4, method='jitter'); dev.off(); # draw with lines set

javascript - How to make checkboxes checked at run time -

i constructing check boxes @ run time using ng-repeat check html code- div data-ng-repeat="data in cntrl.columndetailsonload"> {{data.displayname}} <input type="checkbox" id="{{data.id}}" data-ng-model="cntrl.check[data.id]" {{data.checked}}><br> object data has property "checked" :"checked" , not working . object structure -{ "id": "value.cyclestatus", "status": "1", "position": "1", "displayname": "status" }, you can bind value object ng-model="x" , , set value of x preferred check inside controller.

php - Route won't return view Laravel -

Image
i'm trying build api laravel. did projects framework never had kind of issue i'm dealing now. in picture see routes have build. the first 1 opens laravel welcome page, second returns users in json. but in last route want return view created, when visiting url blank white page no content, error message or log. i added new newuser.blade.php view in views folder. code help, although picture need move users/new route above users/{id} one. laravel passing 'new' $id parameter usercontroller@userbyid. changing order means recognise other route first. // above route::get('users/new', function() { // return view }); // below route::get('users/{id}', 'usercontroller@userbyid');

ios - removeFromSuperview() takes too long -

i try save object viewcontroller.swift core data after picking image imagepickercontroller. display view (dynamicview) spinner while saving. object saved in 1 or 2 seconds, dynamicview takes 7 or 8 seconds removed superview. func imagepickercontroller(picker: uiimagepickercontroller, didfinishpickingmediawithinfo info: [nsobject : anyobject]){ dismissviewcontrolleranimated(true, completion: nil) picture = info[uiimagepickercontrolleroriginalimage] as? uiimage view.addsubview(dynamicview) var newimagedata = uiimagejpegrepresentation(picture, 1) objecttosave?.photo = newimagedata progressbardisplayer("test", true) dispatch_async(dispatch_get_global_queue( int(qos_class_user_interactive.value), 0)) { self.save() } } func save() { var error : nserror? if(!managedobjectcontext!.save(&error) ) { println(error?.localizeddescription) }else{ println("no error, saved") self.dyna

c - Realloc Arguments -

i implementing stack using arrays below code #include<stdio.h> #include<stdlib.h> #include<string.h> struct stack{ int top; int capacity; int *array; }; struct stack *createstack() { struct stack *stack=malloc(sizeof(struct stack)); stack->top=-1; stack->capacity=1; stack->array=malloc(sizeof(sizeof(int)*stack->capacity)); } void doublestack(struct stack *stack) { stack->capacity=stack->capacity*2; stack->array=realloc(stack,stack->capacity); } void push( struct stack *stack , int data) { if(stack->top==(stack->capacity)-1) doublestack(stack); stack->array[++stack->top]=data; } my doubt is, when doublestack called once stack full, should use stack->array first argument of realloc() or stack first argument of realloc() ? well think stack->array should passed. need reallocate portion of memory. but accidentally passed stack , see

ruby - Generate a password string of fixed length with certain required criteria (Capitals, numbers, special characters) -

i'm trying generate secure passwords of length meet criteria. e.g. want (say) 10 letter password that: has @ least 1 capital letter has @ least 1 lower case letter has @ least 1 number has @ least 1 underscore (or other character, underscore due restrictions underscores accepted) i've tried securerandom.url_safebase64(10) but generates strings long , doesn't guarantee presence of each restriction. wondering if there's easy way... low = ('a'..'d').to_a = ('a'..'z').to_a num = ('0'..'9').to_a u = ['_'] = low + + num + u pw = (low.sample(1) + up.sample(1) + num.sample(1) + u.sample(1) + any.sample(6)).shuffle.join

python - Not receiving correct pattern from regex on PyPDF2 for a PDF -

i want extract instances of particular word pdf e.g 'math'. far converting pdf text using pypdf2 , doing regex on find want. example pfd when run code instead of returning regular expression pattern of 'math' returns string of whole page. please thanks #first change current working directory desktop import os os.chdir('/users/hussein/desktop') #file located on desktop #second pypdf2 pdffileobj=open('test1.pdf','rb') #opening file pdfreader=pypdf2.pdffilereader(pdffileobj) pageobj=pdfreader.getpage(3) #for test need page 3 textversion=pageobj.extracttext() print(textversion) #third regular expression import re match=re.findall(r'math',textversion) match in textversion: print(match) instead of getting instances of 'math' receive this: i n t r o d u c t o n etc etc the textversion variable holds text. when use for loop, give text character @ time have seen. findall

c# - What HttpStatusCode and ReasonPhase in Web API to return for defensive programming? -

when writing public function, follow practices of defensive programming, this. public long createsection(section section) { if (section == null) throw new argumentnullexception("section"); var entityid = section.entityid; if (entityid == 0) throw new argumentexception("to add section, entity must have been saved entityid", "section"); debug.assert(section.id == 0, "if give such section, don't minid save it."); ... return section.id; } i going wrap asp.net web api 2.x function. upon argumentexceptions, think need throw httpresponseexception httpstatuscode , reasonphase. what httpstatuscode should use? should overwrite default reasonphase value argument name missing? what best practice handle exceptions thrown in api controller function , tell clients? as per personal oppinion, i use 400 bad request. 500 should avoided cause should h

html - spacing in a word javascript -

i wrote code: $(document).ready(function(){ settimeout( function(){ if($("#site-type").length) { $(".typewrite span").typed({ strings: ["show case ", "projekt"], typespeed: 100, backdelay: 500, loop: false, fontcolor: "green", contenttype: 'html', // or text // defaults false infinite loop loopcount: false, [a-za-z']+( [a-za-z']+)*$ }); } }, 4000); }); } i want have space in this: hello (and here script typing) not this: hello(and here script typing) just guess: try replacing strings: ["show case ", "projekt"], strings: [" ", "show case ", "projekt"],

Selecting N rows in SQL Server -

following query return 1-10 in 10 rows. declare @range int = 10 ;with cte as( select top (@range) duration = row_number() over(order object_id) sys.all_columns order [object_id] ) select duration cte but when set @range 10000 returns 7374 rows. why query can't return more 7374 rows. update i found way achieve requirement following declare @start int = 1; declare @end int = 10; numbers ( select @start number union select number + 1 numbers number < @end ) select * numbers option (maxrecursion 0); without last line of code breaks error maximum recursion 100 has been exhausted before statement completion , found line specifying 0 infinite recursion. query seems little slower me. there faster way??? as commented earlier, it's because reached number of rows of sys.columns . here way generate list of numbers or others call numbers table or tally table . this uses cascaded cte s , said fastest way create tally table:

java - Tomcat MySQL Connection DataSource not working -

i hard coding db connection in app, , right trying make better. issue seems that's supposed done, , still fails. 1- download binary distribution appropriate platform, extract jar file, , copy "$catalina_home/lib" - done. 2- configure mysql database jndi resource. resource in application's context elemen , resource reference in application's "web-inf/web.xml" file. <resource name="jdbc/storagerdb" auth="container" type="javax.sql.datasource" username="root" password="admin" driverclassname="com.mysql.jdbc.driver" url="jdbc:mysql:/localhost:3306/storagerdb" maxactive="15" maxidle="3"/> <resource-ref> <description>mysql datasource example</description> <res-ref-name>jdbc/storagerdb</res-ref-name> <res-type>javax.s

JSON decoding in Go changes the object type? -

i trying build library can read multiple different types of objects out of json files (the actual library pulls them out of couchdb, purposes of it's loading them json). my library doesn't know concrete type of object being loaded, hence "createobject()" call below (which satisfied interface in real code). i'm having problem when try cast object created createobject() call concrete type (mytype in example) i'm getting panic: panic: interface conversion: interface map[string]interface {}, not main.mytype i'd know i'm going wrong here, or whether there's more go-like way should approaching problem. if doing in java i'd using generics , expect straightforward. note if comment out json.newdecoder... line code works (prints out blank line, expected). implies happening in decode operation. runnable example follows: package main import ( "encoding/json" "fmt" "strings" ) type mytype struct

php - Loop of outputted data only allowing changes to be made to the first record -

i have page made can accept/deny user. once user has been accepted, change group of membership grant permission levels , allow them login. reason though, if try change anyone's group level not firs outputted user loop, changes first person's data. so if had list this... -mike -bob -suzy if tried change bob's group, changes mike's. why be? here code in seeing can't see. $con2 = mysqli_connect("localhost", "", "", ""); $run2 = mysqli_query($con2,"select * user_requests order id desc"); $runusers2 = mysqli_query($con2,"select * users order id desc"); $numrows2 = mysqli_num_rows($run2); if( $numrows2 ) { while($row2 = mysqli_fetch_assoc($run2)){ if($row2['status'] == "approved"){ //var_dump ($row2); $approved_id = $row2['user_id']; $approved_firstname = $row2['firstname'];

javascript - How to not call the directive everytime i reload a page -

i have problem directive,help me solve this. directive changes css style, everytime when go page of these reloads, , not want this. directive('layoutsettings', function ($http) { return { restrict: 'a', link: function (scope, element, $rootscope) { $rootscope.selectedlayout = {}; $http.get('http://localhost/obp_shop/api/layoutsettings/getvalue').success(function(data) { $rootscope.selectedlayout = data; console.log($rootscope.selectedlayout); $(element).css({ 'background-color': $rootscope.selectedlayout[0].value }); $(element).css({ 'background-image': 'url(data:image/jpeg;base64,' + $rootscope.selectedlayout[1].value + ')' }); $('.btn-primary').css({ 'background-color': $rootscope.selectedlayout[2].value });

c# - How to send and receive push notifications for Windows Phone 8.1 -

i followed microsofts article sending , receiving push notifications on windows phone 8.0: https://msdn.microsoft.com/en-us/library/windows/apps/hh202967(v=vs.105).aspx it works fine, creating new windows phone 8.1 app , try rewrite same 8.0 code, classes not available in wp 8.1. please me how can implement these windows phone 8.1. here class use receiving push notifications , handling channeluri . call updatechanneluri method. channeluri updated if need , channeluriupdated event fired , same saved application data settings. if app running , receive notification, 1 of 4 methods notification content executed, determined notification type. public sealed class pushservice { private const string channelurikey = "channeluri"; private const string channeluridefault = null; private pushnotificationchannel _channel; private string _channeluri; /// <summary> /// initializes new instance of <see cref="services.pushservic

php - Symfony2 - The class 'X' was not found in the chain configured namespaces -

i've been searching forever solve problem. can't find solution. i error message when try open homepage: uncaught exception 'doctrine\common\persistence\mapping\mappingexception' message 'the class 'test\bundle\userbundle\entity\user' not found in chain configured namespaces ' in... the weird thing when have following url: http://localhost/ but when run on url don't error , page being displayed correctly: http://localhost/app_dev.php my configuration looks (config.yml): # doctrine configuration dbal: default_connection: default connections: default: driver: "%database_driver%" host: "%database_host%" port: "%database_port%" dbname: "%database_name%" user: "%database_user%" password: "%database_password%" charset: utf8 test: driver: "%database_driver2%" host: "%database_h

c++ - How to control #define directive in different projects ...? -

my question quite straight forward. intended know #define directive in c++ controllable on different project files? elaborately, have header file , cpp file 1 project. codes of files follows: myheader.h #ifndef __my_header_h__ #include <cstring> using namespace std; #ifdef _header_export_ #define header_api __declspec(dllexport) #else #define header_api __declspec(dllimport) #endif #ifdef __cplusplus extern "c" { #endif class header_api myheader { public: myheader(); ~myheader(); #ifdef _header_display_ void __cdecl parseheader(); #elif defined (_header_return_) string __cdecl parseheader(); #endif }; #ifdef __cplusplus } #endif #define __my_header_h__ #endif myheader.cpp #ifndef __my_header_h__ #include "myheader.h" #endif myheader::myheader() { } myheader::~myheader() { } #ifdef __cplusplus extern "c" { #endif #ifdef _header_display_ header_api void __cdecl myheader::parseheader() { fput

Force mongodb to output strict JSON -

i want consume raw output of mongodb commands in other programs speak json. when run commands in mongo shell, represent extended json , fields in "shell mode", special fields numberlong , date , , timestamp . see references in documentation "strict mode", see no way turn on shell, or way run commands db.serverstatus() in things do output strict json, mongodump . how can force mongo output standards-compliant json? there several other questions on topic, don't find of answers particularly satisfactory. the mongodb shell speaks javascript, answer simple: use json.stringify() . if command db.serverstatus() , can this: json.stringify(db.serverstatus()) this won't output proper "strict mode" representation of each of fields ( { "floatapprox": <number> } instead of { "$numberlong": "<number>" } ), if care getting standards-compliant json out, this'll trick.

Find text which is part of cell value in .Find function VBA excel -

i have code below, have problem, not know how can find row sometext included in cell value. if explanation not clear example: sometext = 1200 , want row index cell value follow: 1200.0 , 1200.1. in advance help. set cell1 = selection.find(what:=sometext, after:=activecell, lookin:=xlvalues, _ lookat:=xlwhole, searchorder:=xlbyrows, searchdirection:=xlnext, _ matchcase:=false, searchformat:=false) just change lookat:=xlwhole lookat:=xlpart set cell1 = selection.find(what:=sometext, after:=activecell, lookin:=xlvalues, _ lookat:=xlpart, searchorder:=xlbyrows, searchdirection:=xlnext, _ matchcase:=false, searchformat:=false)

php - Mockery: test if argument is an array containing a key/value pair -

how can use mockery , hamcrest assert when method of mock object called, 1 of arguments passed array containing key/value pair? for example, test code might this: $mock = m::mock('\jodes\myclass'); $mock ->shouldreceive('mymethod') ->once() ->with( arraycontainspair('my_key', 'my_value') ); i know write closure, wondering if there's way of making read better: $mock ->shouldreceive('mymethod') ->once() ->with( m::on(function($options){ return is_array($options) && isset($options['my_key']) && $options['my_key'] == 'my_val'; }) ); i found answer looking through hamcrest php code here , the function name given away in doc comment: * @factory hasentry so c

asynchronous - How to check whether a function in Node.js runs synchronously or asynchronously -

is there way know through memory analysis or way of application profiling? there no sure way check programmatically. either check documentation or source code absolutely sure if function name not have traditional sync suffix.

mysql - Modify column values to that they are in order -

Image
i got special problem i'd solve in sql. need make sure optionorder same questionid goes 0-[any number]. so example rows questionid = 18386 , optionorder right 1,2,3,4 . need 0,1,2,3 . also if rows 1,2,4 , needs 0,1,2 i'm sorry incorrect grammars. in mysql, can variables: set @rn := 0; set @q := -1; update table t set optionorder = (case when @q = questionid (@rn := @rn + 1) when (@q := questionid) not null (@rn := 0) else -1 -- should never happen end) order questionid, optionorder; because of order by , need set variables outside update .

sml - operator and operand don't agree [equality type required] -

this function calculate count element y in list fun func y xs=list.length(list.filter(fn x => x=y) xs); val countelement = fn : ''a -> ''a ?.list -> int func 1 [1,2,3,4]; val = 1 : int but, when write func 1.1 [1.1,2.1,3.1,4.1]; error: stdin:64.1-64.35 error: operator , operand don't agree [equality type required] operator domain: ''z operand: real in expression: countelement 1.1 how can solve problem ? real not equality type in sml 97. means cannot use = compare 2 real s.

batch file - Need a way to obtain total instances after finding using FINDSTR -

so have far , works finding specified string need echo total number of times it's found. findstr /c:"\"ma\"" %fn% thanks in advance. findstr has no counter, find has (but has no regex). also findstr /c: searches \"ma\" literally. should add /r (assuming search "ma" ). can combine both commands needs: findstr /r /c:"\"ma\"" %fn% | find /c /v ""

How can I expose a service in a node in kubernetes 1.0? -

i created docker local install of kubernetes , able create replicas , services bellow (this kubernetes 201 ): rc: apiversion: v1 kind: replicationcontroller metadata: name: nginx-controller spec: replicas: 2 # selector identifies set of pods # replication controller responsible managing selector: app: nginx # podtemplate defines 'cookie cutter' used creating # new pods when necessary template: metadata: labels: # important: these labels need match selector above # api server enforces constraint. app: nginx spec: containers: - name: nginx image: nginx ports: - containerport: 80 and service.yaml: apiversion: v1 kind: service metadata: name: nginx-service spec: ports: - port: 8000 # port service should serve on # container on each pod connect to, can name # (e.g. 'www') or number (e.g. 80) targetport: 80 protocol: tcp nodeport: 30000 type: l

maven - Forbid using certain packages in a Java project (especially unit tests) -

i'd prevent people team using testng asserts , instead use assertj. aware of solutions: maven plugin restrict specific packages being used unfortunately, neither (restrict-plugin , macker) of them checks test directory. i'd maven check both main , test source code.

html - JavaScript, a good way to represent a float as color in a plot -

Image
i trying create plot using javascript (d3.js) , in every second have new incomming point label, label float chosen randomly given interval. i need represent label (float) 1 given color points gradient colors, something like : i have tried far, don't give expected result. function float2color( label ) { var r = 255 - ( label / 8 * 255 | 0 ); g = label / 8 * 255 | 0; return '#' + ( r ? ( r = r.tostring(16), r.length == 2 ? r : '0' + r ) : '00' ) + ( g ? ( g = g.tostring(16), g.length == 2 ? g : '0' + g ) : '00' ) + '00' } result (not good)) it sounds want linear color scale. replace float2color function. var color = d3.scale.linear() .domain([min, max]) .range(['blue', 'yellow']); then color float, color(float_value); note 'blue' , 'yellow' can given hex representations well. see https://github.com/mbo

javascript - Call touch event on parent from iframe -

i'm trying call touch move event when user interacts iframe. this code @ top level page contains iframe. var myiframe = document.getelementbyid('iframe'); var myiframedoc = myiframe.contentwindow.document; myiframedoc.addeventlistener('touchmove', function(event){ console.log('iframe touched'); var e = document.createevent('touchevent'); //e.touches = [{pagex: 10, pagey: 10}]; //e.inittouchevent('touchstart', true, true); e.inituievent('touchstart', true, true); }, false); so when user touch moves on iframe call 1 of events below (also @ top level page). document.addeventlistener("touchmove", function(event){ alert('touchmove'); }); document.addeventlistener("touchstart", function(event){ alert('touchstart'); }); document.addeventlistener("touchend", function(event){ alert('touchend'); }); however touch events don't fire

c# - Avoiding errors when loading DLLs -

i trying use mef, however, noticed crash if .dll wrong interface present in directory being used. there way correct/avoid issue, beyond allowing correct .dlls present in plugin folder? edit error is: unable load 1 or more of requested types. retrieve loaderexceptions property more information.

Python and check if current datetime is in specific range -

i trying similar this , want specify start date , end date actual weekday names , times. example, want check if current datetime (datetime.datetime.now()) in between tuesday @ 4:30pm , thursday @ 11:45am. update weekly has tuesday/thursday mentality. i have thought how weekdays (but don't know how wrap time part it): timenow = datetime.datetime.now() if timenow.weekday() >= 1 , timenow.weekday() <= 3: #runcodehere any thoughts on how this? neatest way use amount of minutes elapsed in week: def mins_in_week(day, hour, minute): return day * 24 * 60 + hour * 60 + minute if (mins_in_week(1, 16, 30) < mins_in_week(timenow.weekday(), timenow.hour, timenow.minute) < mins_in_week(3, 11, 45)): ....

boolean - javascript, what this condition means? if(display || true){...} -

the display variable optional on actual function, don't understand means || true what checks condition? if(display || true){...} if(display || true){ $("#container").html(this.displayreport(this.tabdata, extrainfo || false)); } the || logical or operation, means display or true true. your code means if(true) {...} , , if quite redundant.

api - SQL Query pulling extra data -

i using query in soapui against our soap api. <soapenv:envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:del="http://tempuri.org/deltek.vision.webserviceapi.server/deltekvisionopenapiwebservice"> <soapenv:header/> <soapenv:body> <del:getprojectsbyquery> <!--optional:--> <del:conninfoxml><![cdata[<visionconninfo> <databasedescription>description</databasedescription> <username>username</username> <userpassword>password</userpassword> <integratedsecurity>y</integratedsecurity> </visionconninfo>]]></del:conninfoxml> <!--optional:--> <del:query>select wbs1,name,principal pr pr.wbs1='h15032.00'</del:query> <!--optional:--> <del:recorddetail>'project'</de

linux - superblock is in the future bios time -

sometimes, when reboot system, have error : /dev/sda1 "superblock last mount time in future /dev/sda1 "run fsck manually" to correct it, have go bios system , set date/time (generally it's 1 year later). after no problem pc reboot correctly. but cause of production condition, problem go bios change date/time. there way ignore error ? because don't understand why linux doesn't want start because bios date/time wrong ? see man e2fsck.conf : ... [options] stanza contains general configuration parameters e2fsck's behavior ... broken_system_clock e2fsck(8) program has heuristics assume system clock correct. in addition, many system programs make similar assumptions. example, uuid library depends on time not going backwards in order able make guarantees issuing universally unique id's. systems broken system clocks, well, broken. however, broken system clocks, particularly in embedded systems, exist. e2fsck attempt

SVN - How do I only get updated files from server but not commit any local changes I have made? -

i've made bunch of local changes don't want commit them. want updated files server i'm up-to-date else has. is there way this? in understanding, if 'svn update' commit changes i've made locally. doing svn update enough. doing no commit done, you're safe. may conflicts between you've changed , others have changed. in case of conflicts, you'll have merge changes. until commit, nothing sent server.

android - JavaScript: How to reload page when localstorage changes? -

i'm making series of javascript pages share information via localstorage. works fine, when change parameter in 1 of pages , move different one, need reload manually ctrl r changes become effective. succeeded @ doing refreshing automatic using onblur, but, alas, such function stops working when upload scripts android (the final destination of these scripts becoming android app). so i'm trying use addeventlistener storage event, nothing happens, still have refreshing manually. i've read lots of web sites , gone through lot of examples still don't it. here relevant code: window.addeventlistener("storage", handler); function handler() { location.reload(); } let me share more i'm trying do: have series of html pages, each of them form make calculation diet plan. example: first 1 asks body info , gives basal calory intake. a second page takes basal calory intake number, stored using localstorage, shows in screen, , asks in form introduce daily

sql - Removing Duplicate Rows in Employee Demographic Data Pull -

i doing data pull demographic information on employees. had issue missing employees because not has phone number (i don't know why) now have duplicates because people have primary , not-primary phone number. can listed mobile, home, work, etc... want if employee has primary phone number list it, if don't have number @ want listed "n/a". here query below. appreciate assitance. select distinct ejc.persontaxidno [ssn] ,ejc.empno [employee id] ,isnull(ejc.salutation, 'n/a') [salutation] ,ltrim(ejc.firstname) [first name] ,ltrim(ejc.lastname) [last name] ,isnull(ejc.namesuffix,'n/a') [suffix] ,vpa.personaddress1 [address] ,isnull(vpa.personaddress2,'') [address 2] ,vpa.personaddresscity [city] ,vpa.personaddressstateabbrev [state] ,vpa.personaddresspostalcode [zip] ,case when vph.personphoneprimaryind = 1 , (getdate() between vph.personp

Javascript: Data Object merging -

i wondering if there's way merge element in object if have same property. here mean: var dummy = { data: [ {name: 'a', info: '1'}, {name: 'b', info: 'a'}, {name: 'c', info: '2'}, {name: 'a', info: '2'}, {name: 'b', info: '2'} ] }; var expected_results = { data: [ {name: 'a', info: '1,2'}, {name: 'b', info: 'a,2'}, {name: 'c', info: '2'} ] } //todo if same name merge if not seperate var plugin = { unique: { list: [] }, merge: function(params) { var lists = plugin.unique.list; lists.push(params[0]); //first unique $.each(params, function(index, item) { if(index !== 0) { $.each(lists, function(index, list) { if(list.name === item.name) { list.info += ',' + item.info; } else { lists.push(item); } })

javascript - URL parameters for profile image sizing from Twitter API -

i'm using twitter api pull in single recent tweet user. result json object containing information user (name, profile image , on) plus tweet information. profile image comes through so: http://pbs.twimg.com/profile_images/xxxxxxxxx/xxxxxxx_normal.jpeg the size of pretty tiny. can made bigger changing end of filename so: http://pbs.twimg.com/profile_images/xxxxxxxxx/xxxxxxx_bigger.jpeg and can @ full 450px size removing part of filename entirely: http://pbs.twimg.com/profile_images/xxxxxxxxx/xxxxxxx.jpeg when use _normal or _bigger, image small, final example above (450px) big. need in between! there way choose size want, example url parameters this: http://pbs.twimg.com/profile_images/xxxxxxxxx/xxxxxxx.jpeg?w=200

android - Horizontally center TextView inside ImageView -

how horizontally center textview inside imageview? positioned in lower right corner of imageview. <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <imageview android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageview" android:background="@drawable/img" /> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textview" android:layout_alignbottom="@+id/imageview" android:layout_alignright="@+id/imageview" android:layout_alignend="@+id/imageview" />

Excel insert a value one cell down -

i have condition statement , when true, insert text or value 1 cell/row down. how can that? thank you. to insert row below active cell: activecell.offset(1).entirerow.insert it's vague answer vague question

orchardcms - how can i inject IContentManager in Timer callback (Orchard CMS) -

public models.manageduserspart getmanagedusers(int managedusersid) { return _cachemanager.get(managedusersid, ctx => { monitormanagedusersignal(ctx, managedusersid); timer = new timer(t => doupdate(_contentmanager,managedusersid), "c", timespan.fromminutes(2), timespan.frommilliseconds(-1)); var managedusers = _contentmanager.get<manageduserspart>(managedusersid); return managedusers; }); } and doupdate function: public void doupdate(icontentmanager contentmanager,int managedusersid) { var transation = _iworkcontext.createworkcontextscope().resolve<itransactionmanager>(); transation.requirenew(); var manager = getmanager(); var modifiemanageruser = manager.get<manageduserspart>(managedusersid); var modi = getmanagedusers(managedusersid); modifiemanageruser.invitedcount = modi.invitedcou

json - Swift2.0 - Create tableView from an array of tuples -

i have array of tuples created json. typealias tagandlocation = (tag: string, location: string) var resulttuples = [tagandlocation]() (_, subjson) in json { let tag = subjson["tag"].string! let location = subjson["location"].string! let tagloc = (tag: tag, location: location) resulttuples.append(tagloc) } then i'll use func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell { let cell = uitableviewcell(style: uitableviewcellstyle.default, reuseidentifier: "cellconcert") //problem here. want indexpath.row position of array of tupple cell.textlabel?.text = resulttuples.[indexpath.row][] return cell } basically want tableview have content of concerts. any idea? thanks

Change href in another PHP page using a variable -

i'm brand new , trying scab 2 different ideas. each of them work individually, i'm trying integrate them. i able upload , image (which creates list itme href="javascript:void(0). i can allow user input assign url existing text link. what i'm trying target dynamically created list item in upload.php page , change href="javascript:void(0) user specified variable index.php index.php code <!doctype html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>image upload</title> <link href="style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="jquery-1.8.3.min.js"></script> <script type="text/javascript" src="jquery.form.js"></script> <script type="text/javascript"> $(document).ready(function(){ $

asp.net mvc - Trouble when using C# .Distinct() -

i trying fill dropdown list of regions come database. regions coming table there can many rows same region, using .distinct() display 1 of each in dropdown. lets there 100 northwest 's in database. using .distinct() group them 1 northwest displayed in dropdown. i added ability disable , enable regions, don't want affect how viewed in dropdown, used other functionality. user has ability disable or enable of 100 in model (may not make sense, has purpose). enabled , disabled bit value in database. issue comes if there @ least 1 northwest enabled , 1 disabled. calling regionstate has true value , false value meaning displays twice in dropdown because distinct eachother. var context = new testcontext(); var viewmodel = new testviewmodel(); viewmodel.regions = context.select(r => new region { name = r.region, regionstate = r.regionstate }).distinct().orderby(r => r.name); viewmodel: public class testviewmodel { public ienumerable<re

swift - how to filter out/exclude some indexes from a CGPoint array -

i have array of cgpoints ( spritepositions ) , create skspritenode's selected number of positions (leaving specific indexes of out). please see code below: createsprite(missingindexes: [int]) { //for (index, value) in enumerate(spritepositions) filtering out/excluding missingindexes array { var sprite = skspritenode(imagenamed: "spriteimage") sprite.position = value addchild(sprite) } } you can use contains function on missingindexes array filter out indices. if index not contained in missingindexes process normal. if index containted in missingindexes, nothing. swift 1.2: for (index, value) in enumerate(spritepositions) { if !contains(missingindexes, index) { var sprite = skspritenode(imagenamed: "spriteimage") sprite.position = value addchild(sprite) } } swift 2.0 for (index, value) in spritepositions.enumerate() { if !missingindexes.contains(index) { va

ruby on rails - Require 'barby' not working. - cannot load such file -- barby -

i'm trying use barby gem installed, when gives me error. loaderror cannot load such file -- barby here's require methods in controller. require 'barby' require 'barby/barcode/ean_13' require 'barby/outputter/ascii_outputter' require 'barby/outputter/html_outputter' class palletscontroller < applicationcontroller -snip- end here's gem in gemfile. gem 'barby' any appreciated. you add require when dealing ruby project. in case( ruby-on-rails ), can remove lines. also, keep in mind should add gem s gemfile

linux - How to put process in background in Chef similar to Ctrl + Z from terminal -

i have command start particular service in prompts password, after entering password put in background using ctrl + z, now how can automate set of 50 commands using chef recipe or other script. i can manage enter password using expect utility how put in background using script ? you can put process in background putting & @ end of command. so: bash '/bin/something -f myflag &'

sorting - How can I sort a dictionary by key in Scala? -

it easy sort map keys or values in python ( this question example ). i same thing in scala, lets have dictionary like: val a= map(0 -> 1.0, 3 -> 5.0,2->7.0) i list of tuples correspond sorted map keys: val a_sorted= list((0,1.0),(2,7.0),(3,5.0)) thanks! map(0 -> 1.0, 3 -> 5.0,2->7.0).tolist.sortby(_._1) res1: list[(int, double)] = list((0,1.0), (2,7.0), (3,5.0))

xcode - How does swift infer that num1 and num2 are integers? -

i confused on how swift infers num1 , num2 integers. function accepting array of ints, true, how swift num1 , num2 related array of ints??? func mean4 (numbers: [ int ] ) -> double { let sum = numbers.reduce(0, combine: { num1, num2 in return num1 + num2 04: }) the reduce function defined as: extension sequencetype { public func reduce<t>(initial: t, @noescape combine: (t, self.generator.element) -> t) -> t } self.generator.element refers array element type, int. means num2 int. initial value 0 passed, can infer t int well.

Trying to get my Java IRC Bot to parse and write to an preexisting XML file -

i'm total java virgin, , i've been stumbling surely in developing irc bot friends. far, i've gotten of features in working order. but, i'm wracking brain on problem here, bot far can reply link, every week, have change link in java file manually , recompile whole thing. so, want able parse pertinent values xml file in same directory bot's java files in, , able update same values through irc client. import org.jibble.pircbot.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import org.xml.sax.*; import org.w3c.dom.*; public class modbot extends pircbot { static string inputfile = "./botdata.xml"; static string outputfile = "./botdata.xml"; public modbot() { setlogin("modbot"); this.setname("modbot"); setversion(" "); } public void onmessage(string channel, string sender, string login, string hostname, string mess

java - How to get the JOptionPane.showOptionDialog in the same monitor? -

i have working laptop 2 monitors connected it. run application on monitor 2 (which external monitor). in application calling joptionpane.showoptiondialog , problem dialog box appear on monitor 1 (which laptop screen) in spite of running , doing computation on application in monitor two. i tried getparent() method nothing worked, want pop jpanel through called. here sample of joptionpane.showoptiondialog: joptionpane.showoptiondialog(getparent() , jsr, //object "messages", joptionpane.yes_no_option, joptionpane.error_message, null, options, options[0]); scrollpane.setviewportview(textarea); validate(); repaint(); this annoying sometime thought application crashed there nothing in monitor 1 there dialog window poped in monitor one. edit: this new question, dont have problem in bringing dialog box on top, have used solution of getpa

How to switch a serial images in Android Activity -

i reach android issue , need helps. i need display serial of images in activity, and: i can switch images 1 one gesture. images not fixed in resource. since internet, cannot add them in advance. i can handle response in clicking "current image". mmm...so far don't have other ideas. search in webs, people using gallery, , others said gallery out of date, not recommended. , people used fragment, need display pictures. hope quick , easy way, appreciated in advance. as below: http://s3.amazonaws.com/img.tnt/ba47668/c487_l.jpg

javascript - Can't seem to get my div's label to overflow the way I want it to -

i have html: <div id="contentpanelheading" class="div"> <label id="originalnamelabel" class="label">thisisareallylongblockoftextthatwilloverflowtheparentdiv</label> </div> this css: .div { background-color: red; width: 100px; height: 100px; } an example jsfiddle available here . how can make text overflow block, follows: |bigwordsshould| |bealignedliket| |hisinsidemydiv| |andonlyoverflo| |wgoingdownward| slikethis,outs isdeofthedivfr omthebottom note how letters overflow div going down , how large word such gets broken down. how can this? have tried bunch of different tricks looked none seemed work me. you need specify css properity word-wrap: .label { word-wrap: break-word; } jsfiddle

how to launch an android app with custom url scheme -

i want launch app custom url scheme. checked deep links section on dev android , here snippet of code. doesnt seem fire though url looks : myapp://?host=myhost.com manifest : <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> <category android:name="android.intent.category.browsable" /> <data android:scheme="myapp" /> </intent-filter> in activity main activity, have : intent intent = getintent(); uri uri = intent.getdata(); if (uri != null) { string host = uri.getqueryparameter("host"); } the app not launch when have email has url hyperlink. also, way test ? try this, edit intentfilter <intent-filter> <action android:name="android.intent.action.view"></action> <category android:name="android.intent.category.default"></category&

c# - WPF How to Bind an Image to a DataGrid column as a property of the ItemsSource? -

Image
i'm creating wpf app using mvvm design pattern. i have datagrid 4 columns , want last column column of images. other 3 text columns bound properties of attributenode contained in list attributes , used itemssource . xaml <usercontrol.datacontext> <viewmodel:attributegridviewmodel /> </usercontrol.datacontext> ... <datagrid name="attributegrid" horizontalalignment="stretch" verticalalignment="stretch" itemssource="{binding attributes}" autogeneratecolumns="false"> <datagrid.columns> <datagridtextcolumn header="parameter" binding="{binding parameter}" minwidth="30" width="225" fontsize="15"/> <datagridtextcolumn header="value" binding="{binding value}" minwidth="30" width="*" fo

angularjs - Asynchronous access to an array in Firebase -

Image
here code: var userref = new firebase("https://awesome.firebaseio.com/users/"); var tokenref = userref.child(key+'/tokens'); tokenref.once('value', function(snapshot){ var usertokensync = $firebase(tokenref); var usertokens = usertokensync.$asarray(); console.log(usertokens); console.log(usertokens[0]); for(var i=0, len = usertokens.length; < len; i++) { console.log(usertokens[i]); } console.log('done'); }) this code gets tokens of user firebase, , want browse tokens array. here console gives me: as can see, cannot access array. have idea of how this? thanks in advance. welcome asynchronous loading 101. var usertokens = usertokensync.$asarray(); console.log(usertokens); console.log(usertokens[0]); for(var i=0, len = usertokens.length; < len; i++) { console.log(usertokens[i]); } console.log('done'); the first line of snippets starts loading data firebase. loading migh