Posts

Showing posts from January, 2013

c# - Check if Listbox contains a certain element -

i know question posted here multiple times i've read threads , nothing works me decided ask here. i want check if string in listbox. i've tried listbox.items.contains("stringtomatch") but nothing. i tried foreach (var item in form1.filtertypelist.items) { if (item.tostring() == "stringtomatch") { break; } he doesn't find anything. why? how can solve that? try using way... findbytext strig tomatch = "stringtomatch"; listitem item = listbox1.items.findbytext(tomatch); if (item != null) { //found } else { //not found }

Countdown Timer is not showing in javascript -

i new in javascript, want create countdown timer localstorage starts given time , end 00:00:00, it's not working, when running code showing value "1506". here code <script type="text/javascript"> if (localstorage.getitem("counter")) { var currenttime = localstorage.getitem("counter"); } else { var hour = 3; var minute = 25; var second = 60; var currenttime = hour.tostring() + ":" + minute.tostring() + ":" + second.tostring(); } function countdown() { document.getelementbyid('lblduration').innerhtml = currenttime; second--; if (second == -1) { second = 59; minute--; } if (minute == -1) { minut

numbers - How can I have all the integers in a string that has a combination of alphanumeric characters using RegEx -

for example have: 1|2|3,4|5|6,7|8|10; how can output this: a: 1 2 3 b: 4 5 6 c: 7 8 10 and how can this: array = {1,2,3} array b = {4,5,6} array c = {7,8,10} var reg = /(\d+)\|(\d+)\|(\d+)[,;]/g; var str = "1|2|3,4|5|6,7|8|10;"; var index = 0; str.replace(reg,function myfun(g,g1,g2,g3){ var ch = string.fromcharcode(65 + (index++)); return ch+": "+g1+" "+g2+" "+g3+"\n"; }); the second case should update myfun return string: "array "+ch+" = {"+g1+","+g2+","+g3+"}\n";

Generating stanford semantic graph with nodes storing lemma -

i trying generate semanticgraph , use semgrex find specific node. use lemma 1 of node attribute in semgrex. saw relevant question , answer here: corenlp semanticgraph - search edges specific lemmas it mentioned that make sure nodes storing lemmas -- see lemma annotator of corenlp (currently available english, only). i current can use pipeline generate desired annotation generate semantic graph. properties props = new properties(); props.put("annotators", "tokenize, ssplit, pos, lemma, parse"); stanfordcorenlp pipeline = new stanfordcorenlp(props); however, after searching relevant information, find deprecated function @ here: https://github.com/chbrown/nlp/blob/master/src/main/java/edu/stanford/nlp/pipeline/parserannotatorutils.java public static semanticgraph generatedependencies(tree tree, boolean collapse, boolean ccprocess, boolean includeextras, boolean lemmatize, boolean threadsafe) { semanticgraph deps = sema

mysql - Copy last N characters of SQL column in another column (AKA I messed up!) -

i messed big time: added 2000 images phoca gallery , instead of leaving "title" field empty, use filenames title, wrote name of category... renaming each 1 manually pita, i'm sure can done in sql, except don't know how. what have is: (15574, 1379, 0, 'thursday, 25.6.', 'thursday-25-6', 'competitions/hrprvprj/25.6/120/vucemilo_filip/_mg_5545.jpg', 1, null, '2015-07-01 16:55:11', 0, '', '', 0, '', 0, null, 0, 212111, 1, 1, 0, '0000-00-00 00:00:00', 13, null, null, null, null, null, null, '', 0, '', '', '', '', '', '', '*'), and i'd need is: (15574, 1379, 0, '_mg_5545.jpg', '_mg_5545.jpg', 'competitions/hrprvprj/25.6/120/vucemilo_filip/_mg_5545.jpg', 1, null, '2015-07-01 16:55:11', 0, '', '', 0, '', 0, null, 0, 212111, 1, 1, 0, '0000-00-00 00:00:00', 13, null, null,

python - Why wont this pickle? -

i trying run process multiprocessing, when starting thread pickler falls on , can't work out stopping pickling. i've tried commenting out socket code , message obj code, still not working - doing wrong? class transmitthread(process): def __init__(self, send_queue, reply_queue, control_pipe, recv_timeout=2, buffer_size=4096): """ init function called when thread created. function calls process class init function, , stores class vars. """ # call process class init process.__init__(self) # store class vars self.send_queue = send_queue self.reply_queue = reply_queue self.control_pipe = control_pipe self._recv_timeout = recv_timeout self._buffer_size = buffer_size def run(self): """ main function called when thread started. function loops forever, waiting send message in queu

oauth - How does GetExternalLoginInfoAsync() work? (MVC5) -

i have simple question, time of googling didn't give me answer. i'm using mvc 5 project , using owin oauth features facebook login. i'm using recommended way first creating challange result: return new challengeresult(provider, url.action("externallogincallback", "account", new { returnurl = returnurl })); and in callback function capturing var logininfo = await authenticationmanager.getexternallogininfoasync(); now question is, method (getexternallogininfoasync) works? need access info (logininfo) provided callback later on, should write db, etc or there better way?

Change string to hash with ruby -

i have ugly string looks this: "\"new\"=>\"0\"" which best way converting hash object? problem "\"new\"=>\"0\"" not hash. first step should manipulate hash: "{" + + "}" # => "{\"new\"=>\"0\"}" now once have hash looking string can convert hash this: eval "{" + + "}" # => {"new"=>"0"} however there still 1 issue, eval is not safe , inadvisable use . lets manipulate string further make json-like , use json.parse : require `json` json.parse ("{" + + "}").gsub("=>",":") # => {"new"=>"0"}

sql server - SSISDB - Deploy project using T-SQL -

i trying deploy ssis project ssisdb using t-sql. in case of error while deploying, error messaged got logged catalog.operation_messages view. now if execute same deploy statement in explicit sql transaction , if error occurs @ time of deployment not able find error logged catalog.operation_message. ex. begin begin try begin tran tran1 declare @folder_id bigint exec ssisdb.catalog.create_folder @folder_name='test1', @folder_id=@folder_id output select @folder_id exec ssisdb.catalog.set_folder_description @folder_name='test1', @folder_description='test1' --deploy declare @projectbinary varbinary(max) declare @operation_id bigint set @projectbinary = (select * openrowset(bulk 'c:\test\myproject.ispac', single_blob) binarydata) exec ssisdb.catalog.deploy_project @folder_name = 'test1', @project_name = 'abc', @project_stream = @projectbinary, @operation_id = @operation_id out commit tran tran1 end try begin catch select error_m

yii - how to serve the CSS as a result of a controller action in yii1 -

i want users have feature users can select color, font ,font size, font color etc. below theme.php file php file containing css. <?php header('content-type:text/css'); ?> <style> .btn-default.btn-icon.btn-lg i{padding:10px 10px;font-size:<?php echo $size; ?>;line-height:1.33;border-radius:3px;color:<?php echo $color; ?>} </style> how call this, values of $color, $size can taken database. have table called templates fields parameter name , parameter value. want use values table. in controller or view file, can add: $css = <<<eof .btn-default.btn-icon.btn-lg i{padding:10px 10px;font-size:{$size};line-height:1.33;border-radius:3px;color:{$color}} eof; yii::app()->getclientscript()->registercss('your-color', $css);

angularjs - Calculation on binding in angular -

i using ng-repeat , have array of object. so according 1 of parameter want resize image. duration contains time in milliseconds. want change in minutes , set pixel style="width:{{albumitem.duration}} try below code:- ng-style="{{setwidth(albumitem.duration)}}" controller:- $scope.setwidth=function(millis){ var minutes = math.floor(millis / 60000); return{ "width":minutes+"px" } } plunker hope :)

css - Image responsive in bootstrap to fill column -

i have bootstrap column defined follows: <div class="col-md-4 limit"> <img id="myimage" src="" class="img-responsive"/> </div> <style> .limit { max-height:500px; overflow:hidden; } </style> the source of image obtained programatically not know in advance height or width of image. want image in column height limited appear inside of div. img-responsive class have achieved image horizontally fill column, however, class sets height auto, of time causes image overflow , hidden. not want image overflow in way. so, lets column measures: width: 300px (defined bootstrap) height: 500px (.limit) and image dimensions are: width: 600px height: 1500px the current configuration makes image shrink 300px x 750px. container set 500px, causes last 250px lost inside overflow. image instead resized 200px x 500px in order containing div how can this? thanks! try this: &

go - How to create many http servers into one app? -

i want create 2 http servers 1 golang app. example: package main import ( "io" "net/http" ) func helloone(w http.responsewriter, r *http.request) { io.writestring(w, "hello world one!") } func hellotwo(w http.responsewriter, r *http.request) { io.writestring(w, "hello world two!") } func main() { // how create 2 http server instatce? http.handlefunc("/", helloone) http.handlefunc("/", hellotwo) go http.listenandserve(":8001", nil) http.listenandserve(":8002", nil) } how create 2 http server instance , add handlers them? you'll need create separate http.servemux instances. calling http.listenandserve(port, nil) uses defaultservemux (i.e. shared). docs here: http://golang.org/pkg/net/http/#newservemux example: func main() { r1 := http.newservemux() r1.handlefunc("/", helloone) r2 := http.newservemux() r2.ha

javascript - After using the tab key, can’t scroll to the top -

when using tab key or next button on device keyboard scroll seems out off sync. use following steps reproduce this: 1.have form more fields fits screen tab through fields until field not visible gets focus. 2.now try reach the top of page mouse keeps scrolling wrong position. to make easier forked existing codepen , edited show problem. link: codepen this happens on devices have. android 4.4.3 , android 5.0.1. tested @ latest v1.0.0-rc.0 off ionic . i can't see codepen share solution used on application, should add $ionicscrolldelegate controller, here example: angular.module('myapp').controller('myctrl', function($scope, $ionicscrolldelegate) { ... $ionicscrolldelegate.scrolltop(); ... }

javascript - Generate HTML Canvas from AngularJS Template -

Image
i trying render html element on canvas using html2canvas js. using angularjs data binding on html page , dynamic data not rendered on generated canvas these html elements. example, have html element this: <table class="table table-striped table-bordered table-hover"> <tr> <th>name</th> <th>uri</th> <th>is default</th> <th>action</th> </tr> <tr ng-repeat="printer in printers"> <td>{{printer.name}}</td> <td>{{printer.url}}</td> <td>{{printer.default}}</td> <td><button ng-click="printtestpage(printer.url)">print test page</button></td> </tr> </table> but can see dynamic data not rendered on canvas: suggestions regarding how properly, or without using html2canvas js??? when call html2canvas? should call function after d

Add static field to grouped data in Mongodb -

how add static field result using group operation in mongodb. query looks like: db.sales.aggregate({ $group : { _id: { year: { $year: '$date' }, }, amount: { $sum: 1 } } }); than result: { "result" : [ { "_id" : { "year" : 2013 }, "amount" : 43433 }, ... ] "ok" : 1 } i need add field called type value 'year' in each object of result. i need add project operation literal 'year'. query looks like: db.sales.aggregate([ { $group : { _id: { year: { $year: '$registrationdate' } }, amount: { $sum: 1 } }, }, { $project: { type: { $literal: 'year' }, } } ]);

Message - Cannot find installed version of python-django or python3-django -

i'm new ubuntu, , love far. have been trying install django website development project. in terminal, when start python interpreter , type import django django.version i face no issues , get (1, 8, 2, 'final', 0) then, start project, typed django-admin startproject trialsite and got message saying cannot find installed version of python-django or python3-django i installed django using pip install django==1.8.2 , installed django-admin package before using via apt-get. also, have been following django book guide through whole process. can tell me issue is? my /usr/local/lib/python2.7/dist-packages , site-packages both empty. don't know if important. according django book, django-admin should be. use following command , solved. sudo apt-get install python-django

Installing cassandra on RHEL using docker -

i trying install cassandra on rhel-7 source code using docker. have done following steps inside container: 1 - yum install -y git java-1.8.0-openjdk-devel ant 2- export java_home=/usr/lib/jvm/java-1.8.0 3- export path=$path:$java_home/bin 4- export ant_home=/usr/share/ant 5- export path=$path:$ant_home/bin 6- export java_tool_options=-dfile.encoding=utf8 7 -git clone https://github.com/apache/cassandra.git 8 -cd cassandra && ant the build successful. when try start cassandra server inside container getting following error: a fatal error has been detected java runtime environment: internal error (cppinterpreter_zero.cpp:812), pid=836, tid=4397984807184 error: unimplemented() any idea?

java - Like search in Elasticsearch -

i using elasticsearch filtering , searching json file , newbie in technology. little bit confused how write query in elasticsearch. select * table_name 'field_name' 'a%' this mysql query. how write query in elasticsearch? using elasticsearch version 0.90.7. i highly suggest updating elasticsearch version if possible, there have been significant changes since 0.9.x. this question not quite specific enough, there many ways elasticsearch can fulfill functionality, , differ on overall goal. if looking replicate sql query in case use wildcard query or prefix query. using wildcard query: note: careful wildcard searches, slow. avoid using wildcards @ beginning of strings. get /my_index/table_name/_search { "query": { "wildcard": { "field_name": "a*" } } } or prefix query get /my_index/table_name/_search { "query": { "prefix": { &

java - XML Parser : How to avoid null pointer exception -

when given key not exist throws npe . string nodevalue = eelement.getelementsbytagname(key).item(0).gettextcontent(); if (nodevalue == null || nodevalue.isempty()) return null; return nodevalue;` try string nodevalue=null; if(eelement!=null && eelement.getelementsbytagname(key)!=null && eelement.getelementsbytagname(key).item(0)!=null ){ nodevalue = eelement.getelementsbytagname(key).item(0).gettextcontent(); } return nodevalue;

c# - Create folder on SharePoint document library using client object model -

i want create folder on sharepoint document library using client object model (c#). below code that. contenttypecollection listcontenttypes = list.contenttypes; clientcontext.load(listcontenttypes, types => types.include (type => type.id, type => type.name, type => type.parent)); var result = clientcontext.loadquery(listcontenttypes.where(c => c.name == "folder")); clientcontext.executequery(); contenttype foldercontenttype = result.firstordefault(); listitemcreationinformation newiteminfo = new listitemcreationinformation(); newiteminfo.underlyingobjecttype = filesystemobjecttype.folder; newiteminfo.leafname = foldername; listitem newlistitem = list.additem(newiteminfo); newlistitem["contenttypeid"] = foldercontenttype.id.tostring(); newlistitem["title"] = foldername; ewlistitem.update(); clientcontext.load(list); clientcontext.executequery(); now hav

c++ custom sorting a vector -

not going go deep doing because homework , don't need done me but, need help. need able specify part of vector<vector<string>> gets sorted first , under parameters. currently doing works calling sort ( v.begin(), v.end() ); if write out vectors like: 5 2 4 6 12 2 5 22 51 2 5 72 1 and might need sort in descending order 2nd column , if 2nd column same sort next specified column. called ./sort 2,4 would sort second column , 4th. i looked around , apart writing own sorting algorithm don't know how customize sort. std::sort() has second form takes compare functor third parameter. lets control ordering of sort without having write sort algorithm yourself. the function provide given 2 objects, , must return true if first object should ordered before second ("less than") , false otherwise. e.g.: std::sort(v.begin(), v.end(), [](const vector<string>& v1, const vector<string>& v2) { // return true if

c# - Replace list value by reference -

i have class looks this: public class organization { public list<ijob> jobs { get; set; } public ijob bigboss { get; set; } public organization() { bigboss = new doctor(); jobs = new list<ijob> { bigboss, new doctor(), new doctor() }; } } if set bigboss property new value, value updated in list well. after bigboss pointing new, first item in list should well. know following code won't in c# because of way c# works references: static void main(string[] args) { var test = new organization(); test.bigboss = new developer(); //test.jobs[0] still pointing doctor, not developer console.writeline(test.jobs[0]); } is there other clean way of doing this? jobs[0] reference bigboss = new doctor(); when call constructor new organization(); when change: test.bigboss = new developer(); bigboss refer developer jobs[0] still

android notification background color is not white on lollipop -

as known android lollipop force set notification background color white, can set style of textview according different sdk version putting style.xml in folder values-v21. so here comes question, on third party roms, example, emui developed huawei tech co., background of notification not white(nearly black), setting style to android:textappearance.material.notification.title the color of text black, result, cannot see text clearly. had been searching internet 2 days find nothing helps. i trying color of notification background , set text color dynamically, don't know how accomplish this. need help, lot. ok, use official api set notification info, inflate default notification layout ( status_bar_latest_event_content.xml )instead of custom layout. rom changed default background , text-color of status_bar_latest_event_content.xml , wouldn't (or can't) change custom layout. mbuilder.setlargeicon(combinebitmap).setcontenttext(notifystring).setsubtext(&quo

java - how to refresh the content of the jtable if you're using notepad to putting data in the jtable -

public void readcar() { string choice = string.valueof(car_combo1.getselecteditem()); int ctr = 0; string filename = null; if (choice.equals("state-description")) { filename = text_car1.gettext(); ctr = 12; } else if (choice.equals("discas-camera")) { filename = text_car2.gettext(); ctr = 3; } else if (choice.equals("discas-car(for removal)")) { filename = text_car3.gettext(); ctr = 11; } else if (choice.equals("discas-par(for removal)")) { filename = text_car4.gettext(); ctr = 9; } else if (choice.equals("closing cas chg w/ customer initiated")) { filename = text_car5.gettext(); ctr = 11; } try { file file = new file(filename); filereader fr = new filereader(file.getabsolutefile()); bufferedreader br = new bufferedreader(fr); (int = 0; < ctr; i++) { datacar[i] = b

Keep getting unauthorized when registering devices in Azure Notification Hubs -

i have followed every example 't' , cannot azure notification hubs return other following 401 message: "malformedtoken: credentials contained in authorization header not in wrap format." i have tried namespace access keys , notification hub keys no avail. have followed examples here: https://msdn.microsoft.com/en-us/library/azure/dn495630.aspx , have been unable work. changed account specific settings namespace, notification hub name , authorization key. var registrationxml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<entry xmlns=\"http://www.w3.org/2005/atom\">" + "<content type=\"application/xml\">" + "<gcmtemplateregistrationdescription xmlns:i=\"http://www.w3.org/2001/xmlschema-instance\" xmlns=\"http://schemas.microsoft.com/netservices/2010/10/servicebus/connect\">" +

vb.net - Arrays in visual basic (Related to program that deals with driving distance) -

i have assignment must create project looks driving distance between 2 cities. use 2 drop-down lists contain names of cities. label 1 list “departure” , other “destination”. use button calculate distance. store distances in two-dimensional table. i started doing it, noticed having repeat code many times , know there better way it. that's need help. is there way use loop in problem , if so, how it? option strict on public class form1 dim distance(,) long = {{0, 1004, 1753, 2752, 3017, 1520, 1507, 609, 3155, 448}, {1004, 0, 921, 1780, 2048, 1397, 919, 515, 2176, 709}, {1753, 921, 0, 1230, 1399, 1343, 517, 1435, 2234, 1307}, {2752, 1780, 1230, 0, 272, 2570, 1732, 2251, 1322, 2420}, {3017, 2048, 1399, 272, 0, 2716, 1858, 2523, 1278, 2646}, {1520, 1397, 1343, 2570, 2716, 0, 860, 1494, 3447, 1057}, {1507, 919,

numpy - Python - Recreate Minitab normal probability plot -

Image
essentially same question asked here , want in python. have used scipy stats probplot, want recreate confidence interval curves , i'm not sure how proceed. can point me in direction?? this i'm at: this want be: i have answer first part of task not sure how minitab calculates confidence interval. none of definitions found yield similar. here code base plot , fit: import numpy np import scipy.stats stats matplotlib import scale mscale matplotlib import transforms mtransforms matplotlib.ticker import formatter, locator class ppfscale(mscale.scalebase): name = 'ppf' def __init__(self, axis, **kwargs): mscale.scalebase.__init__(self) def get_transform(self): return self.ppftransform() def set_default_locators_and_formatters(self, axis): class percformatter(formatter): def __call__(self, x, pos=none): # \u00b0 : degree symbol return "%d %%" % (x*100)

python - Attaching plt.plot() on a panel created with wx.Panel -

i using wxpython , matplotlib create splitter window supports commands on 1 window , plots data on other. how plt.plot() attach plot on plotting window? i popup window when run plt.plot() , not accept parent window argument. need use plt.plot() instead of backend modules such wxagg because has zoom , save file features , code looks simpler. so "attach" mean doing similar following: self.figure = figure(figsize = (5,7), dpi = `100) self.ax = self.figure.add_subplot(111) t = arange(0.0,3.0,0.01) s = sin(2*pi*t) self.ax.plot(t,s) self.canvas = figurecanvas(panel2,-1,self.figure) sizer = wx.boxsizer(wx.vertical) sizer.add(self.canvas,1,wx.all | wx.align_center | wx.expand) panel2.setsizer(sizer) panel2.fit() self.canvas.draw() where when create figurecanvas instance can specify (panel2,...) in arguments, indicating want reside within panel. not worried making specific example work in general possible specify panel want pyplot.plot()? have used variables , class defini

bash - How do I count multiple overlapping strings and get the total occurences per line (awk or anything else) -

i have input file this: 315secondbin x12121321211332123x 315firstbin 3212212121x 315thirdbin 132221312 316firstbin 121 316secondbin 1212 what want count how many instances of few different strings (say "121" , "212") exist in each line counting overlap. expected output be: 6 5 0 1 2 so modified awk thread use or operator in hopes count meets either condition: { count = 0 $0 = tolower($0) while (length() > 0) { m = match($0, /212/ || /121/) if (m == 0) break count++ $0 = substr($0, m + 1) } print count } unfortunately, output this: 8 4 0 2 3 but if leave out or counts perfectly. doing wrong? also, run script on file ymaz.txt running: cat ymaz.txt | awk -v "pattern=" -f count3.awk as alternate approach tried this: { count = 0 $0 = tolower($0) while (length() > 0) { m = match($0, /212/) y = match($0, /121/) if ((m == 0) && (y == 0)) break count++ $0 = substr($0,

osx - Seeking key event library for C++ on Mac -

i'm new c++ programmer moving on java , python. fun first project decided have go @ simple snake game. application has no gui: instead, print state of board console once per second. what i'm looking way make snake turn arrow keys. thought simple; however, i'm working on mac, , libraries i've found handle mac input events objective-c libraries rather c++ ones. does know of way capture key input events in c++ on mac? for console applications ncurses way go handling key input.

d3.js - D3 force layout approach towards repetitious links -

my question when d3.layout.force().start() being called, not when 1 appends links svg. need know if algorithm removes repetitious links or considers of them when calculating layout. i asking because need find way apply weights links between nodes on circumstances (when members of same cluster), , can think of apply links between nodes satisfy condition. it mention there different link/relationships types in context, node , b might have link because have relationship type of type ii. therefore strength of gravity between these 2 nodes should more compared not have latter relationship. with being said, there way of appending weights each link, can dynamically modify attribute instead of adding more links? your appreciated.

Rails named route & helper (/controller/:id/randomname) -

i'm trying following routing work: get 'items/:id/pictures' => 'pictures#show' what kind of helper method should use ? using <%= link_to pictures_item_path %> following error: undefined local variable or method `pictures_item_path' #<#<class:0x007fa2c6181710>:0x007fa2c40ba7c0> i've tried using get 'items/:id/pictures' => 'pictures#show', as: 'items/:id/pictures' , following error: invalid route name: 'items_:id_pictures' your route correct. if you're going use helper, have use named routes . routes can named passing :as option, allowing easy reference within source name_of_route_url full url , name_of_route_path uri path: # in routes.rb '/login', to: 'accounts#login', as: :login # render, redirect_to, tests, etc. redirect_to login_url i hope helpful.

cordova - PhoneGap external site displaying in browser for Android -

i having issue phonegap/cordova. trying app display content on external site. need wrapper app, need means access phone resources like, camera etc. placing external site in content tag in config.xml phonegap opening site in external browser rather in phonegap app. works fine in ios , before start ripping apart framework make work wondering if else has workaround solve problem. have build app before in android know works older version of phonegap. version using phonegap 3.6.3 here config.xml file; <widget xmlns = "http://www.w3.org/ns/widgets" id = "io.cordova.hellocordova" version = "2.0.0"> <!-- preferences android --> <preference name="loglevel" value="debug" /> <content src="https://myexternalsite.com/" /> <allow-navigation href="*" /> <access origin="*" /> from official docs var ref = window.open(url, target, options); ref

lua - Setting __index of current environment in Roblox -

in roblox studio, have modulescript object implements analogous class 1 shown in chapter 16 of 1st edition of programming in lua, shown below: local h4x0r = { } local function setcurrentenvironment( t, env ) if ( not getmetatable( t ) ) setmetatable( t, { __index = getfenv( 0 ) } ) end setfenv( 0, t ) end setcurrentenvironment( h4x0r ); h4x0r.account = { }; setcurrentenvironment( h4x0r.account ); __index = h4x0r.account; function withdraw( self, v ) self.balance = self.balance - v; return self.balance; end function deposit( self, v ) self.balance = self.balance + v; return self.balance; end function new( ) return setmetatable( { balance = 0 }, h4x0r.account ) end setcurrentenvironment( h4x0r ); end end return h4x0r i attempted use following script access account class, assuming of members of 2nd do-

jquery - PHP input type file field being submitted, file isnt -

i have following form. <form action="picture.php" method="post" class="pic_form"> <span class="picture_box"> <input type="file" accept="image/*" name="pic_upload" class="picture_upload_input" /> <p class="upload_info">only file types of extensions gif, jpg, png , svg allowed. maximum file size 15mb. if file larger 15mb, not upload.</p> </span> <input type="hidden" name="uid" value="<?php echo $_session['userid']; ?>" /> <input type="button" name="upload_button" value="upload" class="upload_button" /> </form> i validate file set , it's of correct type , size using jquery. when submit form (using jquery), field posted $_post['pic_upload'] this returns true. however, file isn't posted $_files['custom_pic_upload'] this retur

gulp - Using Webpack for hot-loader and generating a physical file w/ ReactJs ES6 -

i have reactjs es6 (ie 'import' keywords) app uses gulp generating physical build file , webpack hot-loading changes virtual file. wanted combine 2 services npm start (which current loads webpack, not gulp). server.js file var webpack = require('webpack'); var webpackdevserver = require('webpack-dev-server'); var config = require('./webpack.config'); new webpackdevserver(webpack(config), { publicpath: config.output.publicpath, hot: true, historyapifallback: true }).listen(3000, 'localhost', function (err, result) { if (err) { console.log(err); } console.log('listening @ localhost:3000'); }); webpack.config.js file var path = require('path'); var webpack = require('webpack'); module.exports = { devtool: 'eval', entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './src/index.js' ],

php - Select value where multiple columns -

this question has answer here: when use single quotes, double quotes, , backticks in mysql 10 answers i'm not entirely sure how write select query select value table 2 particular values found in same row. select value table id=1 , field=2 what's correct syntax? select * table_name id=1 , name='any' add quotes string value only

sockets - Using packets gotten from devices connected to an android device's hotspot interface -

i created vpn using android's vpnservice class. now, want vpn handle packets device's hotspot interface. in vpnservice builder, called addroute("0.0.0.0",0). made sure got outgoing packets including hotspot. the problem facing when packets redirected hotspot, packets seem still have ips hotspot network. 192.168.43.... both in source field , destination fields of ip packets , payload doesn't seem contain tcp packet either. my questions are: why hotspot packet receive vpn interface not have same source ip of vpn interface created vpnservice class? is there layer packets hotspot packaged since can't seem remote address real request in ip headers? is vpninterface setup wrongly? my interface setup correctly. apparently, getting dhcp packets. dhcpoffer packets android's local dhcp servers. even though android's vpn interface setup outgoing packets on device, doesn't seem broadcast packets reason, gets replies broadcast packets.

Images randomly missing from Amazon S3, possible CORS issue -

we use s3 store our images wecora.com. have bucket setup called cdn-production , have using s3's ability interpret cname cdn-production.wecora.com avoid cors issues. lastly, using html5 canvas in our application display images. with said, getting daily reports random users using chrome safari ipads , android reporting images not loading on html5 canvas! cannot duplicate these issues locally when try load saved canvases, send on screen shots shot images missing! it's driving nuts! the thing can think it's weird cors issue cannot replicate. below our cors , bucket policy. has else seen type of intermittent missing image behavior (possibly access denied, possibly else) our cors policy follows: <?xml version="1.0" encoding="utf-8"?> <corsconfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <corsrule> <allowedorigin>*</allowedorigin> <allowedmethod>get</allowedmethod>

html - Moving/nudge text down but not and the image -

hello gurus: trying don't theory...i have 1 main div , inside of are: paragraph text , 1 image (both of these nested inside own divs) (hopeful did correctly!) for easy visualization.... both @ top of html page , image styled float: right; text can styled that's hung-up. ----- want move text position; downward top of page 50px----- when styled text padding or margin, takes everything; text , image, , moves down together....how can leave image currently, , move text downward leaving white space @ top above text , not image? is positioning style? or thinking wrong? thank kindly help!! html: <div class="wrapper"> <div><img src="blah" class="img-right" /></div> <div><p>some text</p></div> </div> css: .wrapper div p { position: absolute //can relative, depending on needs top: 50px } .img-right { float: right } position can relative or absolute depending

python - PyGTK 3 (gi.repository) PangoCairo changing color between drawing text and line -

i'm having problems in changing colors between text , lines in pangocairo drawingarea . both come out same color. here simple python code: from gi.repository import gtk, pango, pangocairo class bug(gtk.drawingarea): def __init__ (self): gtk.drawingarea.__init__(self) def do_draw_cb(self, widget, cr): cr.translate ( 10, 10) layout = pangocairo.create_layout (cr) desc = pango.font_description_from_string ("sans 14") layout.set_font_description( desc) cr.set_source_rgba(0.0, 1.0, 0.0, 1.0) layout.set_text("it not easy being green", -1 ) cr.move_to(40, 20) cr.line_to(70, 20) cr.set_source_rgba(0.0, 0.0, 0.0, 1.0) # messes previous set_text cr.stroke() pangocairo.show_layout (cr, layout) def destroy(window): gtk.main_quit() window = gtk.window() window.set_title ("green?") app = bug() app.set_size_request (300, 200) window.add(app

Conditional Join SQL Server -

i have scenario below: source1 column1 column2 source2 column1 column2 output - need view; all records in source1 column2 not empty must in view. all records in source1 column2 empty must joined source2 (on column1, reference between both tables). wherever finds match column2 of source2 should included in view. any pointers please.. the easiest way see union of both queries: select * source1 column2 not null union select s2.* source1 s1 inner join source2 s2 on s1.column1 = s2.column1 s1.column2 null

javascript - variable keeps getting updated without any code that says to -

i have 2 variables in sandbox based game. blocks (array) and blockssave (also array) but have these functions: var game = { blocksave: function() { blockssave = blocks; blockserasedsave = blockserased; }, blockload: function() { blocks = blockssave; blockserased = blockserasedsave; }, blockreset: function() { blocks = []; blockserased = 0; } } if call blocksave once, keeps getting saved until reset if save keep building load, loaded world after saved , builded more. if reset, though, stops saving until game.blockload(). tried functions being defined inside button onclick. i have looked through code , save function called when button pressed. (i tested that) the clue function being called on , on run game. (save not inside it) blockssave = blocks not copy array. points blockssave reference same blocks array. if elements of array primitives, can make shallow copy of blocks array th

apply - R: Trying to determine which decile each data point is in, for all variables in a data frame -

i have data containing information on prices consumers willing pay services. i'm trying find deciles each response falls into, several services using cut function. for (i in 2:13){ x<-quantile(data1[,i],c(0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1),na.rm=true) data1[paste(names(data1[i]), "deciles", sep="_")] <- cut(data1[,i], breaks=x, includ) } however, have 2 problems: there variables 2 deciles same value (e.g. 0 =0, .1=0), cut function not accept. also, initial columns code work, actual decile , not decile number (for example "(1.99,2.56]" instead of .2. if has ideas, appreciate it. for first problem: can use unique breaks , pass cut . second, convert factor integer , use integer index in probs vector pull out appropriate quantile break. ## sample data, third column fail `cut` set.seed(0) data1 <- data.frame(x=rnorm(100), y=rnorm(100), z=sample(0:5, 100, rep=t)) qs <- seq(0, 1, by=0.1)

Reading Authorization header for JWT Token using Laravel 5, CORS, and JWTAuth -

i'm having hard time figuring out. using jwtauth on laravel 5 api , i'm having problem token being read. know , tried: i have set cors configuration allow headers api path: return array( 'defaults' => array( 'supportscredentials' => false, 'allowedorigins' => array(), 'allowedheaders' => array(), 'allowedmethods' => array(), 'exposedheaders' => array(), 'maxage' => 0, 'hosts' => array(), ), 'paths' => array( 'api/*' => array( 'allowedorigins' => array('*'), 'allowedheaders' => array('*'), 'allowedmethods' => array('*'), 'maxage' => 3600, ), '*' => array( 'allowedorigins' => array('*'), 'allow

c# - How to stream live audio via microphone in Unity3D? -

here's part of main code far(the networking done separately): void update() { if (network.connections.length > 0) { audiofloat = new float[audioinfo.clip.samples * audioinfo.clip.channels]; audioinfo.clip.getdata (audiofloat, 0); networkview.rpc("playmicrophone", rpcmode.others, tobytearray(audiofloat), audioinfo.clip.channels); } } [rpc] void playmicrophone(byte[] ba, int c) { float[] flar = tofloatarray (ba); audio.clip = audioclip.create ("test", flar.length, c, 44100, true, false); audio.clip.setdata (flar, 0); audio.loop = true; while (!(microphone.getposition("") > 0)) {} audio.play(); } void onconnectedtoserver() { audioinfo.clip = microphone.start(null, true, 100, 44100); } // when server , client connected void onplayerconnected(networkplayer player) { audioinfo.clip = microphone.start(null, true, 100, 44100); } public byte[] tobytearray(float[] floatarr

Python: deleting/removing class instances with none unique names -

for bit of context, looking create class called peasant game making in python. these workers have many attributes. created name , given id. since names have chance not unique id called delete class. think going instantiation wrong should id creating them unigue id giving them name? class peasant: peasantcount = 0 def __init__(self, name): ... peasant.id += 1 self.id = peasant.id peasant.peasantcount += 1 def died(self, hp): if hp <= 0: peasant.peasantcount -=1 del self the def died method kill peasants if can make work, instance not deleted when instance.died(0) called.

javascript - window.print(); does not work in Safari -

the print method not work on window when using onclick link safari. alternative have webpage print, in safari via onclick code placed on button? odd behavior that's occurring when try , close window, print dialog native browser appears.

c# - Return information about found user Active Directory -

i making active directry managment tool having trouble getting somethings working. while made class want find specific user , return als information(name,fullname,cn,...). can find information when don't know best way return values class. here code use far: directorysearcher search = new directorysearcher(ldapconnectie); search.filter = "(cn=" + username + ")"; searchresult result = search.findone(); if (result != null) { list<string> listldapfields = new list<string>(); list<object> listldapvalues = new list<object>(); resultpropertycollection fields = result.properties; foreach (string ldapfield in fields.propertynames) { listldapfields.add(ldapfield); foreach (object mycollection in fields[ldapfield]) { listldapvalues.add(mycollection); } }

benchmarking - What is the maxium replication rate of Couchbase XDCR -

we using couchbase data caching , there talk of doing cross-data center replication it. however, need 1000 documents replicated multiple locations every second. documents between 2 , 64k each. is there out there xdcr experience can tell me whether feasible, or if have use other means replicate data @ speed. "benchmark" in documentation @ couchbase implies rate of xdcr 100tps. (149 ms replicate 11 documents.) the replication rate of xdcr limited network bandwidth , latency first, cpu , disk io. assuming have enough bandwidth between datacenters , clusters provisioned properly, couchbase replicate hundreds of thousands of documents per second, or more. it's pretty simple experiment run, set xdcr between 2 singles node clusters , use 1 of load generator tools come couchbase create traffic. (cbworkloadgen in couchbase bin folder or cbc-pillowfight comes libcouchbase.) there several config settings can play optimize throughput, such increasing batch size, chan

javascript - Force street address with Google Places Autocomplete? -

i know can restrict google places api return addressers using option types: ['address'] . wondering if possible force user give street address including street number, "drottninggatan 100" , not "drottninggatan"? if cannot force behaviour, way of validating user has selected "drottninggatan 100" , not "drottninggatan"? (btw i'm using javascript api , angularjs) well.. can use javascript match function regex check format of input... following example check if address contains @ least number. var resultbox = document.getelementbyid("ifvalid"); function textboxchanged(){ var address=document.getelementbyid("address").value; if (address.match(/[0-9]/i)==null){ resultbox.style.color="red"; resultbox.innerhtml="not valid"; } else { resultbox.style.color="green"; resultbox.innerhtml="valid";

php - Why session doesn't recognise manual change of cookie? -

i trying understand sessions, , conducted test: my code is: test.php <? @session_start(); if(isset($_session['test'])) { echo "test success"; } ?> when enter cookie manually browser using addon as: phpsessid test it not recognise it. $_session "superglobal" (available everywhere) array tied cookie using unique session id. if you're wanting reference cookie values you've set you'll need use $_cookie superglobal array. you can read more superglobals here: http://php.net/manual/en/language.variables.superglobals.php and how $_session , $_cookie works here: http://php.net/manual/en/reserved.variables.cookies.php http://php.net/manual/en/reserved.variables.session.php you cannot set values in session using browser that. php place you'll able set 'test' key value, true or false. session_start(); // assign based on value of cookie $_session['test'] = true; if ($_session['test'])

javascript - Equality comparison between Date and number doesn't work -

according ecma script standard, following code should return true, doesn't: d = new date() ; d.settime(1436497200000) ; alert( d == 1436497200000 ) ; section 11.9.3 says: if type(x) either string or number , type(y) object, return result of comparison x == toprimitive(y). then, section 8.12.8 says toprimitive retuns result of valueof method. means last line in example above should equivalent to: alert( d.valueof() == 1436497200000 ); which return true , indeed. why first case not return true ? if @ spec @ section 8.12.8 , find text near end of section: when [[defaultvalue]] internal method of o called no hint, behaves if hint number , unless o date object (see 15.9.6), in case behaves if hint string . (emphasis mine) now, in step 8 / 9 of the abstract equality comparison algorithm [ 11.9.3 ] , toprimitive(x) , toprimitive(y) called without hint parameter. the lack of hint parameter, above text, means toprimitive met

java - Your content must have a ListView whose id attribute is 'android.R.id.list' when extending ListActivity -

this question has answer here: your content must have listview id attribute 'android.r.id.list' 6 answers logcat 06-02 15:53:34.742: e/trace(1188): error opening trace file: no such file or directory (2) 06-02 15:53:36.682: d/dalvikvm(1188): gc_for_alloc freed 49k, 7% free 2539k/2708k, paused 483ms, total 484ms 06-02 15:53:36.712: i/dalvikvm-heap(1188): grow heap (frag case) 3.666mb 1127536-byte allocation 06-02 15:53:36.782: d/dalvikvm(1188): gc_for_alloc freed 1k, 5% free 3639k/3812k, paused 69ms, total 69ms 06-02 15:53:36.902: d/dalvikvm(1188): gc_concurrent freed <1k, 5% free 3639k/3812k, paused 15ms+42ms, total 123ms 06-02 15:53:37.672: i/choreographer(1188): skipped 49 frames! application may doing work on main thread. 06-02 15:53:37.705: d/gralloc_goldfish(1188): emulator without gpu emulation detected. 06-02 15:53:40.412: d/androidruntime(1188):