Posts

Showing posts from May, 2011

java - Searching entire storage of phone and SD Card for Music Player -

back when started make music player , searching in sd card work , show music , player work properly. couple weeks ago, bought new phone , decided install app onto it, when loaded app, couldn't find music, need way change current code search every folder of phone, , micro sd card , file ends in ".mp3". main activity.java class mp3filter implements filenamefilter { public boolean accept(file dir, string name) { return (name.endswith(".mp3")); } } public class mainactivity extends listactivity implements oncompletionlistener { private static final string sd_path = new string(environment.getexternalstoragedirectory().getpath() + "/"); private static final string phone_storage = new string(environment.getrootdirectory().getpath() + "/"); private list<string> songs = new arraylist<string>(); private mediaplayer mp = new mediaplayer(); private view play; private view pause; private view stop; private view next; private

chat - How to save variable after closing mIRC? -

i'm new language , i'm trying code own bot. alredy got basics , manage use variables , aliases, looking forward mini-game in chat in have own pet, name , level up. i this, problem resides in @ end of day, close program , pets go away, , kind of destroys purpose of it. i wondering if there way in save these variables , reload them each time open program, maybe save them on .txt? any suggestion appreciated. i agree 1 of comments it's best go .ini files problem. an example of syntax, taken url linked above: writeini reminder.ini birthday jenna 2/28/1983 writeini reminder.ini birthday mike 10/10/1990 this produces following file: [birthday] jenna = 2/28/1983 mike = 10/10/1990 and read this: echo -a mike: $readini(reminder.ini, n, birthday, mike) echo -a jenna: $readini(reminder.ini, n, birthday, jenna) if want more flexibility define own data format, can revert plain text files. basic /write , $read functions have pretty neat functionality

coldfusion - Sessions w/CFWheels not sticking -

i having difficulty having session values stick when create them. default value exists @ times. below rudimentary login tool. the compare function works fine, when after cflock , redirect, session.userid , session.isloggedin still 0 , false, respectively. config/app.cfm <cfset this.name = "xxx"> <cfset this.sessionmanagement = true /> <cfset this.sessiontimeout= createtimespan(0,2,0,0) /> <cfset this.setclientcookies = false /> <cfset this.datasource = "xxx" /> events/onrequeststart.cfc <cfscript> if ( !structkeyexists(session, "userid") ) { session.userid = 0; session.isloggedin = false; } </cfscript> controllers/admin.cfc <cfcomponent extends="controller"> <cffunction name="init"> </cffunction> <cffunction name="login"> </cffunction> <cffunction name="main"> </cffun

php - Use DreamFactory SQL with SSL Connection -

just installed dreamfactory on server , have connecting correctly database. when trying send curl request, i'm receiving error: curl: (35) unknown ssl protocol error in connection [api.domain.net]. i'm not sure start work ssl connection database. incredible @ point because searching issue isn't helping much. are forcing ssl3? since dreamfactory docs "using ssl our api requires ssl3" may need use -3 or --sslv3 curl options, indicated on the curl man page . dreamfactory docs page of curl examples uses -3 option repeatedly. need ensure sslv3 support enabled in web server of choice, well. this answer indicates curl error message "unknown ssl protocol error" can caused using wrong ssl/tls protocol version, above resolution given details provided. you need ensure you've installed , enabled ssl cert. if deployed dreamfactory using bitnami, may want review their documentation on enabling ssl . if installed dreamfactory manually

ruby - I am not able to increment string contains integer value? -

how increment last string based on last integer ?for eg."foo" = "f001", "foo9" = "foo10", "foo99" = "foo100","foo001" = "foo002" one way this... def increment_string(string) old_digits = string.scan(/\d+$/).first || '' string.sub(/\d+$/,'') + (old_digits.to_i+1).to_s.rjust(old_digits.size, '0') end p increment_string("beep") => "beep1" p increment_string("beep5") => "beep6" p increment_string("beep99") => "beep100" p increment_string("beep004") => "beep005"

ruby on rails - How do I link my bids to posts? -

i'm having trouble linking bids posts. have created post_id column in bids table (via adding resources:posts in migration). i want able go /posts/:id/new_bid create new bid post. currently, can create new bid going /posts/2/new_bid (for example), still says 'post_id: nil' in database. routes root 'static_pages#home' 'add' => 'posts#new' 'posts' => 'posts#index' '/posts/:id/new_bid' => 'bids#new' resources :posts resources :bids bid controller class bidscontroller < applicationcontroller def new @bid = bid.new @post = post.find(params[:id]) end def show @bid = bids.find(params[:id]) end def index @bid = bids.all end def create @bid = bid.new(bid_params) @post = post.find(params[:post_id]) if @bid.save redirect_to root_path flash[:notice] = 'bid received!' else render 'new' end end def bid_params p

html - innerHTML and conditional (ternary) operator- "unexpected string" -

can please me? trying enable program load page numbers separated hr tag, except last number (#10). right there appears "unexpected string" in code block after if statement. i've tried several different permutations line, i'm stumped how working. thank in advance! var n = 1, str = "" while (n <= 10) { if (n % 2 === 0) { str += "<p class='even'>" + n + (n === 10 ? "" : "<hr>") "</p>" } else { str += "<p class='odd'>" + n + "</p><hr>" } n++ } document.queryselector("#target").innerhtml = str !doctype html> <html> <head> <style> .even { color:blue; } .odd { color:red; } </style> </head> <body> <div id="target"></div> </body> </html> don't need change: s

javascript - HTML5 canvas (videothumbnail) gives SecurityError -

i have read lost of threads on wasnt able find solution. situation. i've loaded video , created thumbnail html5 canvas. when try save canvas image =todataurl error: uncaught securityerror: failed execute 'todataurl' on 'htmlcanvaselement': tainted canvases may not exported. <video id="video" width="200" src="https://sportsquare.s3.amazonaws.com/2012030311_big_1.mp4" type="video/mp4" controls></video><br/> <canvas id="canvas"></canvas><br/> <script> window.setinterval(function(){ var canvas = document.getelementbyid('canvas'); var video = document.getelementbyid('video'); canvas.getcontext('2d').drawimage(video, 0,0,175,125); var dataurl = canvas.todataurl("image/png"); dataurl = dataurl.replace(/^data:image\/(png|jpg);base64,/, ""); }, 2000); </script>

How to update a table when its specified date is today in mysql? -

i have table in database has closing date column input user. want update column status when closing date today.. there suggestions on how can this? after searching answers found out there can create event in mysql. link should http://www.sitepoint.com/how-to-create-mysql-events/ .

c# - How do I generate an ID that is garunteed to be unique? -

this question has answer here: unique random string generation 11 answers i need garuntee uniqueness of id. if there's 1 in 1 trillion chance of there being dupe, cannot use it. but don't feel going ends of earth find solution either. have spent time looking this, , have found date isn't able garuntee me unique id. so thought use simple, this: public static string generateitemid() { string year = datetime.now.year.tostring(), month = datetime.now.month.tostring(), day = datetime.now.day.tostring(), hour = datetime.now.hour.tostring(), minute = datetime.now.minute.tostring(), second = datetime.now.second.tostring(), millisecond = datetime.now.millisecond.tostring(); return year + month + day + hour + minute + second + millisecond; } my logic h

javascript - How is this asynchronous? -

i'm new node.js , asynchronous js , i'm not sure if interpret correctly. i'm trying understand how chunk of code: var fs = require('fs') var filedir = process.argv[2] function donereading(err, filecontents) { var lines = filecontents.split("\n") console.log(lines.length-1) } function countlines(filedir) { fs.readfile(filedir, "utf8", donereading) } countlines(filedir) is asynchronous? because can call countlines function multiple times, each time different filedir argument, prints out length of file? mean.. how asynchronous? isn't how functions work? it asynchronous. not asynchronous because called countlines() multiple times. asynchronous because did asynchronous function call at: fs.readfile(filedir, "utf8", donereading); this function not going block process. called asynchronously. after call function, control not wait function finish synchronously continues remaining code. when file loaded, ca

oop - Java - Converting a generic class' instance to specialized class' instance -

i struggling fundamental concept of oop in java. class person {} class parent extends person {} all parents people, not people parents. person adam = new person(); adam = new parent(); // means variable 'adam' referencing new object. adam = (parent)adam; // java.lang.classcastexception how express idea of becoming subclass in java? 1 have write constructor subclass takes superclass object example... public class person { private string name; public person(string name){ this.name = name; } public string getname() { return this.name; } } and parent class like: public class parent extends person { public parent(person p) { super(p.getname()); } } output: public class run { public static <t> void display(t x) { system.out.println(x); } public static void main(string[] args) { person adam = new person("adam"); display(adam instanceof person); //

elasticsearch - How to configure logstash to make an request to APIGEE analytics API? -

i new elk stack , trying hit apigee analytics rest api, in form of url. response url json file. best approach go ahead implementation? i hope question still valid. if understand correctly want send logging data elk stack. why not send instead of retrieving it? below example of how policy works on apigee platform. need add api proxy , preferably @ postclientflow: .... </postflow> <postclientflow> <response> <step> <name>message-logging-policy1</name> </step> </response> </postclientflow> below policy. <?xml version="1.0" encoding="utf-8" standalone="yes"?> <messagelogging async="false" continueonerror="false" enabled="true" name="message-logging-1"> <displayname>message logging</displayname> <syslog> <message>{system.time.year}-{system.time.month}-{system.time.day

Installing haskell-mode into Emacs on Ubuntu 12 -

Image
i'm following these instructions install haskell-mode on ubuntu 12. when point of typing m-x customize-option ret pac emacs says: no match! customizable variables shown in picture below. any idea going wrong? go init.el file ( ~/.emacs.d/init.el ) , place there: (setq package-archives '(("gnu" . "http://elpa.gnu.org/packages/") ("original" . "http://tromey.com/elpa/") ("org" . "http://orgmode.org/elpa/") ("marmalade" . "http://marmalade-repo.org/packages/") ("melpa" . "http://melpa.milkbox.net/packages/"))) (package-initialize) and m-x package-refresh-contents , can install haskell-mode there. make sure emacs version >= 24 since package.el bundled higher version. if using older version, may have manually install package.

http - Connecting to a Website with Google Apps Script -

i've been trying use gas's urlfetchapp connect external website. however, website redirects me "select country" page http 302 error no matter web address use. var options = { 'mutehttpexceptions':true }; var response = urlfetchapp.fetch("http://www.idtdna.com/site/account", options); logger.log(response.getallheaders()); logger.log(response.getcontenttext()); var cookie = response.getallheaders()['set-cookie']+', cn=us&dateset=7/28/2015 5:48:55 pm; path=/; domain=www.idtdna.com'; logger.log(cookie); var header = {'cookie':cookie}; var o2 = { 'headers':header, 'mutehttpexceptions':true }; var r2 = urlfetchapp.fetch("https://www.idtdna.com/country.aspx", o2); logger.log(r2.getallheaders()); logger.log(r2.getcontenttext()); here code. i've been trying send cookie either i've formatted wrong or sending incorrectly because keep getting redirected reg

c# - How to specify that a combobox use a specific ComboBoxItem Template -

i have wpf comboboxitem template works fine. want applied specific comboboxes way of specific combobox style. don't know in combobox style should point combobox item style. suggestions <style targettype="comboboxitem"> <setter property="snapstodevicepixels" value="true"/> <setter property="overridesdefaultstyle" value="true"/> <setter property="horizontalcontentalignment" value="left" /> <setter property="verticalcontentalignment" value="center" /> <setter property="template"> <setter.value> <controltemplate targettype="comboboxitem"> <border name="border" padding="2" snapstodevicepixels="true" borderthickness="1"> <contentpresenter />

c# - Two validation groups -

i have following form: part one: form have fill anyway part two: checkbox if check checkbox see part 2 form if dont check checkbox ,part 2 form hidden at end of page have send button. the problem is: whenever not check checkbox , second form hidden doesnt send nothing because button , 2 forms have same validation groups , of course when form 2 hidden nobody fill fields , should cancle somehow validation of them (to stay validation of first form should fill anyway-with or without checkbox). what best solution/s? thanks !!! i'm not expert in best practices asp.net here's general advice can check if checkbox checked or not , validate second form if it's checked. sample pseudocode below: validate(form1, form2, checkbox) bool1 = validate(form1) if(checkbox.checked) bool2 = validate(form2) return bool1 && bool2 else return bool1 hope helped.

My workflow Tasks in liferay is empty every time -

i implementing custom portlet kaleo workflow in liferay 6.2 when save data, can see status=1 pending. nothing show in workflow tasks, pending or complete. i have 2 users, first one(let x) admin tries add data, other(let y) has content reviewer role can approve workflow. what missing: bellow code workflow handler class: public class bookworkflowhandler extends baseworkflowhandler{ public string getclassname() { return class_name; } public string gettype(locale locale) { return languageutil.get(locale, "model.resource." + class_name); } public object updatestatus(int status, map<string, serializable> workflowcontext) throws portalexception, systemexception { system.out.println("statu while updating in workflow handler"+status); long userid = getterutil.getlong(workflowcontext.get(workflowconstants.context_user_id)); long resourceprimkey = getterutil.getlong(workflowcontext.get(workflowcons

ios - Can I remove items from my UITableView data source and have my UITableView animate the row removal without specifying exact index paths? -

is such thing possible? basically data source uitableview binary tree. i'm going remove children of 1 of nodes in tree, , want table view automatically animate update, remove rows corresponding these children. i know can use beginupdates() , deleterowsatindexpaths() , endupdates() finding rows computational annoyance (it's far negligible). there way uitableview reload animation? this answer https://stackoverflow.com/a/13261683/1077601 suggests can put [self.tableview reloaddata]; inside uiview animation block.

EditText focus dont work(android) -

sorry english. have 3 edittext , and in scrollview. when click on 1 of edittext, scrollview descends down , focuses on edittext chose. if click edittext of 3 scroll down , focus edittext city no matter chose edittext. not know why, ask help this xml have 3 edittext city , adress , zip <linearlayout android:layout_weight="0.1" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginleft="5dp" android:layout_marginright="5dp"> <linearlayout android:layout_width="match_parent" android:layout_height="50dp" android:background="#26ffffff" a

OpenGL, C++ Cornered Box -

i have been working on gui menu game (school project) have engine template ready need make gui menu. me , friend teacher have managed make non filled box here function: void boxtest(float x, float y, float width, float height, float width, color color) { gllinewidth(3); glbegin(gl_line_loop); glcolor4f(0, 0, 0, 1); glvertex2f(x, y); glvertex2f(x, y + height); glvertex2f(x + width, y + height); glvertex2f(x + width, y); glend(); gllinewidth(1); glbegin(gl_line_loop); glcolor4f(color.r, color.g, color.b, color.a); glvertex2f(x, y); glvertex2f(x, y + height); glvertex2f(x + width, y + height); glvertex2f(x + width, y); glend(); } this how looks now: http://gyazo.com/c9859e9a8e044e1981b3fe678f4fc9ab the problem want this: http://gyazo.com/0499dd8324d24d63a54225bd3f28463d becuse looks better, me , friend has been sitting here couple of days no clue on how achive this. with opengl line primitives you'll have break down multiple lines. gl_line_loop makes a series of l

Kendo UI - stoping binding for part of the View -

i have complex view composed of different parts. need bind parts of manually viewmodel different 1 view itself. currently, kendo ui processing elements of view main binding - there way instruct skip elements knockout does? thanks, sam i don't know how unbind element can use kendo layout , many views want. each view can have own view-model. clear , flexible solution. <div id="app"></div> <script type="text/x-kendo-template" id="layout-template"> <h1 data-bind="text: heading"></h1> <div id="view1-container"></div> <div id="view2-container"></div> </script> <script type="text/x-kendo-template" id="sub-view1-template"> <p data-bind="text: text1"></p> </script> <script type="text/x-kendo-template" id="sub-view2-template"> <p data-bind="te

excel vba - VBA - Need to append to the end of a line in a large text -

i have system can read 50 column's worth of data table @ time. table has 150 columns need read. table has 1 million lines. what have been doing far read 1st 50 columns , write 1 millions lines text file. what need next, read next block of 50 columns , append lines 1 1 million existing text file have written to. this become stuck. i'm not sure how can write specific line in text file. hoping not have loop each line in existing text file row need append to. there way specify line need append without having loop text file find correct row? i use sql oledb , output data using recordset. might take time should work. try using limit , fetch in loop in case result won't load in single go. alternatively add loop sql statement , fetch records higher lower specific row id (if records id numeric not hash) e.g. where id > [old_id] , id <= [old_id] + 100 using sql oledb , recordset dim filename string, textdata string, textrow string, fileno integer fileno

java - repaint isn't working inside Action Performed -

i'm writing simple game application , i'm stuck on problem. pwait , pmain 2 panels frame main frame "create" button, inside pmain panel, , action performed when gets clicked: here code: // action: create new game create.addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { if(ua.alreadyopen()) { joptionpane.showmessagedialog(null,"already open game!"); return; } int n = 0; string nome = null; try { n = integer.parseint(joptionpane.showinputdialog(null, "give max number of guessers")); nome = joptionpane.showinputdialog(null, "give name of game"); if ( n < 1 || nome == null) system.out.println("maininterface: input problems"); // todo ... frame.setcontentpane(pwait); pwait.setvisible(true);

mysqli - PHP Query invalid result -

i apologise if title confusing, when run page code below , enter email not found in database, on webpage notice: trying property of non-object in c:\xampp\htdocs\testing\login.php on line 72 . instead of saying this, want give error email not registered. <?php session_start();//session starts here if(isset($_session['adminname'])||isset($_session['email'])){ header("location: welcome.php");//redirect login page secure welcome page without login access. } ?> <html> <head lang="en"> <meta charset="utf-8"> <link type="text/css" rel="stylesheet" href="bootstrap-3.2.0-dist\css\bootstrap.css"> <title>login</title> </head> <style> .login-panel { margin-top: 150px; </style> <body> <div class="container"> <div class="row"> <div class="col-md-4 col-md-offset-4&

c++ - CUDA error: expected constructor, destructor, or type conversion before 'void' -

i new cuda programing. practice, trying run simple program adds elements in 2 arrays , stores result in new array. organization purposes, trying separating code multiple files. thank in advanced! i keep getting error when try compile it: "hello.cpp:6: error: expected constructor, destructor, or type conversion before ‘void’" here code: hello.cpp #include <simple.h> #include <stdlib.h> #include <stdio.h> #define n 100 __global__ void add(int *a, int *b, int *c) { int tid = blockidx.x; if (tid < n) { adding(a, b, c, tid); } } int main() { int a[n], b[n], c[n]; int *dev_a, *dev_b, *dev_c; cudamalloc((void **) &dev_a, n*sizeof(int)); cudamalloc((void **) &dev_b, n*sizeof(int)); cudamalloc((void **) &dev_c, n*sizeof(int)); // fill arrays (int = 0; < n; i++) { a[i] = i, b[i] = 1; } cudamemcpy(dev_a, a, n*sizeof(int), cudamemcpyhosttodevice); cudamemcpy(dev_b, b, n*sizeof(int), cud

How to do a sum of previous rows in mysql a sum of previous rows -

this question has answer here: create cumulative sum column in mysql 6 answers first of sorry english i try find requete calculate sum of values in different rows : row1 result 2 2 5 7 7 14 assuming first row defines ordering, can correlated subquery: select r.row1, (select sum(t2.row1) requete r2 r2.row1 <= r.row1) cumesum requete r; for larger table, might inefficient, , variables improve performance: select r.row1, (@sum := @sum + r.row1) cumesum requete r cross join (@sum := 0) params order r.row1; note in both cases column used ordering rows not need same column cumulative sum calculation.

ruby - How to update has_many :through association with strong parameters in Rails 4 -

i try update has_many :through association strong parameters in rails 4 without success. model : user has_many :group_owner, :class_name => "group" has_many :group_memberships has_many :memberships, :through => :group_memberships, :class_name => "group" end group belongs_to :owner, :class_name => "user", :foreign_key => "user_id" has_many :user_members has_many :members, :through => :user_members, :class_name => "user" end in group view (create/edit) <%= form_for(:group, :url => {:action => 'update', :group_id => @group.id}) |f| %> <th>new participant</th> <td><%= f.collection_select(:members, @users, :id, :first_name) %></td> <%= submit_tag("update group") %> <% end %> then, in controller, try use strong parameters save new member in db: def groupe_params params.require(:grou

c++11 - std::move a non-copyable object into a vector -

consider this: struct a{}; struct b { // make object non-copyable b ( const b & ) = delete; b & operator= ( const b & ) = delete; b(){}; std::unique_ptr<a> pa; }; int main() { b b; std::vector<b> vb; vb.push_back(std::move(b)); return 0; } error: ../src/sandbox.cpp:24:27: required here /usr/include/c++/4.7/bits/stl_construct.h:77:7: error: use of deleted function ‘b::b(const b&)’ who calling deleted copy constructor? trying move object not copy since has unique_ptr member. as suggested commentators: i tried implement move constructor: b ( const b && rhs_ ) { pa = std::move(rhs_.pa); // error below } and replaced push_back(std::move(b)) emplace_back(std::move(b)) i got error ../src/sandbox.cpp:17:25: error: use of deleted function ‘std::unique_ptr<_tp, _dp>& std::unique_ptr<_tp, _dp>::operator=(const std::unique_ptr<_tp, _dp>&) [with

arrays - Vanilla Javascript equivalent for lodash _.includes -

i'm using lodash includes function check if target value exists in array... _.includes(array, target) and hoping find equivalent in es5 (or es6) did miss something? there no es5 array.prototype equivalent? or option use indexof ? es7: array.prototype.includes() [1, 2, 3].includes(2); // true es5: array.prototype.indexof() >= 0 [2, 5, 9].indexof(5) >= 0; // true [2, 5, 9].indexof(7) >= 0; // false if prefer function: function includes (array, element) { return array.indexof(element) >= 0 } and use as: includes([2, 5, 9], 5); // true

c++ - Need work around for limitation: abstract class cannot be used for return types -

i have c++ class implementation wish hide using pimpl pointer. of work done, , everything's ok except operator '+=' returns object of same class. operator function required in class. problem when made abstract class, no member functions can return object of class, '+=' isn't allowed. i asking advice on dealing limitation. i'd prefer way doesn't require changing existing code uses class. if way doesn't exist, else can done? here's simplified version of class wish make abstract: class aclass { public: aclass( int x0, int y0); ~aclass(void); void operator=(const aclass &a2); aclass operator+(const aclass &a2); void operator+=(const aclass &a2); protected; int x; int y; }; aclass aclass::operator+(const aclass &a2) { aclass aout(a2); aout += a2; return aout; } aclass aclass::operator+=(const aclass &a2) { this->x += a2.x; this->y += a2.y; } // 'operator+' necessary perf

How to set application insights TelemetryClient timeout? -

i sending application insights metric event client app (.net) , wondering if can set timeout telemetryclient.flush() since synchronous call. (the app exit when operation done need enforce flush call ensure metric got sent). flush method implementation depends on channel use. if use webtelemetrychannel default web sdk ( https://www.nuget.org/packages/microsoft.applicationinsights.web.telemetrychannel/ ) flush async. if use persistencechannel default devices sdk ( https://www.nuget.org/packages/microsoft.applicationinsights.persistencechannel/ ) flush sync. izik mentioned no overrides available.

c - failed to process http post,get,put and delete request from cc3200 launchpad to local server or http server -

//i using define get_request_uri "get /ms/v_updated.php?id=9,9,9& qty=9,9,9/http/1.1\r\nhost:127.0.0.1\r\naccept: / \r\n\r\n" for v_updated.php file on localserver using cc3200 launchpad //and wanted know correct syntax using request in cc3200 ![on console got following outpt] [1] sta connected ap: [2]ip acquired : [3]connection server created http begin: failed send http request http post failed http end: and want know json parser being used.. it possible local server declining requests cc3200. try configuring local server. if using xampp, go config > httpd.conf , open it. search allowoverride . find following settings (or similar ), <directory /> allowoverride none options none order allow,deny allow none </directory> change none all . should `<directory /> allowoverride options order allow,deny allow </directory>`

debugging - Cannot see Swift variable contents using AppCode -

i'm using appcode-eap 3.2, i've tried appcode 3.1.7. when stopped in debugger, can see local variables, e.g. fromjson = [] self = [] however, if move 1 of these watches window examine contents, this: self = cannot evaluate expression language swift i can't believe isn't possible see values of variable or property. can guide me i'm failing do? current appcode versions (stable 3.1 , 3.2 eap) don't support swift debugging. should included final 3.2 release however: https://youtrack.jetbrains.com/issue/oc-11626

delphi - Creating a transparent custom bitmap brush -

Image
problem definition i trying create custom bitmap brush transparency doesn't seem working expected. if @ example. add code , hook paint, create , destroy events. type tform3 = class(tform) procedure formdestroy(sender: tobject); procedure formcreate(sender: tobject); procedure formpaint(sender: tobject); private fbitmap: tbitmap; end; // implementation function createblockbitmap(const apencolor: tcolor): tbitmap; begin result := tbitmap.create; result.transparent := true; result.canvas.brush.color := clwhite; result.canvas.brush.style := bsclear; result.pixelformat := pf32bit; result.setsize(20, 20); result.canvas.brush.color := apencolor; result.canvas.brush.style := bssolid; result.canvas.fillrect(rect(0,0,10,10)); end; procedure tform3.formdestroy(sender: tobject); begin fbitmap.free; end; procedure tform3.formcreate(sender: tobject); begin fbitmap := createblockbitmap(clred); end; procedure tform3.formpaint(sender: tobjec

javascript - $http PUT request is slow and unsuccesful no status code, no errors -

when user submits form, server should receive put request updates poll database. what's odd in dev console, can see callback poll.update called immediately, put request takes 120000 ms. , though dev console shows successful put request, database isn't updated, , .success callback never called. updated [object object] put /api/polls/5599725069753a7711fd4274/0 200 120083ms in browser see put request without status code. don't see error messages. the routes poll controller: var express = require('express'); var controller = require('./poll.controller'); var router = express.router(); router.put('/:id', controller.update); module.exports = router; the mongoose poll controller: exports.update = function(req, res) { var update = {$set: {'poll_name': 'poll has been updated'}}; poll.update(req.params.id, update, function(err, num, doc) { if(err) console.log(err); else { console.log('updated &

this - How do I animate a element when clicking a button with jQuery? -

i learning jquery , trying workout how add class span when clicks inside 1 text input field in form, , doesn't apply class of spans when 1 of inputs clicked. at moment have code, add class, when click inside 1 of text input fields adds .active class of inputs. $(".form input").click(function(){ $("span").addclass("active"); }); i understand have use $(this), can't quite figure out syntax isn't clicking yet. thanks help edit sorry should have included more of code. have added link website trying achieve. when click on 1 of inputs in form label input moves can enter text. have noticed if don't enter label moves down again. website: website link thanks replies far currently learning jquery , trying workout how add class input when button clicked $(".form input[type=button]").click(function(){ $(this).addclass("active"); });

string - Why does javascript localeCompare sort underscores before periods? -

i'm trying compare strings sorting purposes, , want sort periods before underscores (because follows ascii table). suggestions / explanations why localecompare doesn't way? as example, want tester.java come before tester_1.java "apple".localecompare("tomatoe") returns -1 because apple smaller "tester.java".localecompare("tester_1.java") returns 1 when want return -1 i think mean .localecompare() right (this mispelled in question)? way ordering being done? possibly have them wrong way around: var array = [ "_a", ".b" ] array.sort() // returns [ ".b", "_a" ] array.sort(function(a,b) { return a.localecompare(b) }) // returns [ ".b", "_a" ] array.sort(function(a,b) { return b.localecompare(a) }) // returns [ "_a", ".b" ] looking @ under hood: var str1 = "_a", str2 = ".b"; str1.localecompare(str2)

data passing and using json data from alamofire with swift -

i integrated alamofire, got 1 problem use data within server communication. before tell problem show code: class viewcontroller: uiviewcontroller, uitableviewdatasource, uitableviewdelegate { @iboutlet weak var mainviewtable: uitableview! @iboutlet weak var sidesopen: uibarbuttonitem! @iboutlet weak var groupbutton: uibutton! var apps:[sample] = [sample]() override func viewdidload() { super.viewdidload() sidesopen.target = self.revealviewcontroller() sidesopen.action = selector("revealtoggle:") self.view.addgesturerecognizer(self.revealviewcontroller().pangesturerecognizer()) self.setupsample() } override func didreceivememorywarning() { super.didreceivememorywarning() // dispose of resources can recreated. } func setupsample() { alamofire.request(.get, "http://{url}").responsejson{ (request, response, data, error) in var json = json(data!) var index = 0; index < json["store"].c