Posts

Showing posts from February, 2011

java - Providing tests as part of a library -

suppose interface like: public interface fooer { void foo(); boolean isfooed(); } this part of java library i'm writing. users of library supposed implement interface , pass objects library. i want provide way users test their implementation hold invariants my library code assumes. following above example: fooer f = getusersfooer(); f.foo(); // f.isfooed() must return true is possible, , if so, feasible or acceptable provide such tests part of library? (i don't know whether these considered unit tests or integration tests ... test modifications made single method using getter methods or primitive non-mutating methods) sure, can write classes like public class testfooer { public static boolean test(fooer f) { // ... } } but there "standard way", using usual testing frameworks (junit, ...) ?

c# - WPF datagrid how to get access to the row click -

seems wpf application inherited has datagrid <datagrid x:name="datagrid" itemssource="{binding alltroublecalls}" selectedindex="{binding selectedindex}" i want end setting background color yellow if textbox contains text in it. the text appears when click on rows in datagrid it seems based upon "binding" {binding ... } i have textbox added name it <textbox tooltipservice.showduration="120000" tooltip="{binding threattext}" name="txtthreat" text="{binding threattext}" textwrapping="wrap" acceptsreturn="true" verticalscrollbarvisibility="visible" horizontalscrollbarvisibility="visible" margin="3" grid.row="8" grid.column="1" grid.columnspan="3" grid.rowspan="1" isreadonly="true" height="30"/>

ios - Fit a UIView to screen -

Image
i add portrait orientation application. there way shrink or fit uiview (created in xib) screen? i have landscape sized views in xib files , set them opposite of using interface builder stretching (the center block). or possible in code? in code, can use self.myview.frame = self.view.bounds; . make stick way, self.myview.autoresizingmask = uiviewautoresizingstretchablewidth | uiviewautoresizingstretchableheight;

javascript - Can I output JSON where the ID is the key rather than it being an array in ASP.NET MVC (C#) -

so in asp.net mvc have controller action this: public jsonresult people() { var people = db.people.tolist(); return json(people); } and when ajaxed return this: [ { "id": 1, "name": "john smith" }, { "id": 2, "name": "daryl jackson" } ] however, i'm looking not json array of records shown above, more json object ids of each record key , record nested value, so: { 1: { "name": "john smith" }, 2: { "name": "daryl jackson" } } my initial thought create dictionary in c# similar structure , pass json() method not know how handle dictionary objects. is there way achieve kind of structure in c#? i'm having resort restructuring on client-side or using loops find record id i'm searching for. it'd nicer if record id in javascript. going wrong? i'm new asp.net mvc environment. any suggestions appreciated. thank

ios - unrecognized selector sent to class. 'calling methods in ClientViewController.mm' -

i trying call method in clientviewcontroller.mm class , keep getting error: terminating app due uncaught exception 'nsinvalidargumentexception', reason: '+ [clientviewcontroller testmethod]: unrecognized selector sent class i have class implements interface. void applerecognitionstatusobserver::onrecognitionstatuschanged (recognitionstatus newstatus) { switch(newstatus) { case kinprogress: [clientviewcontroller testmethod]; break; ....etc } } how can call clientviewcontroller methods c++ class? client view controller.h //imports uikit etc @interface clientviewcontroller : uiviewcontroller <avaudiorecorderdelegate>{ iboutlet uibutton *recobutton; // other buttons } @end // , .mm //#imports.... @interface clientviewcontroller () @end @implementation clientviewcontroller -(void)testmethod{ outlabel.text = @"has been called!"; } you s

java - Printing BufferedImage on JPanel -

i trying display bufferedimage onto jpanel when run program doesn't display anything. i imagine problem creation of bufferedimage but, limited understanding of java, have no idea problem might be. appreciate more information paintcomponent method (what super.paintcomponent(g) mean?) main.java public class main { public static void main (string[] args) { window.windowmake("this window"); } } window.java import java.awt.image.bufferedimage; import java.awt.graphics; import java.awt.image; import javax.swing.jcomponent; import javax.swing.jframe; import javax.imageio.imageio; public class window extends jframe { public static void windowmake(string title) { jframe jf = new jframe(); jf.setdefaultcloseoperation(jframe.exit_on_close); jf.setsize(300,300); jf.setvisible(true); jf.settitle(title); jf.add(new paint()); } } paint.java import java.io.ioexception; import java.io.file; import java.awt.image.bufferedimage; import java.aw

ruby - How to read/write a collection of objects as json -

i have collection of user classes want save json file. users = [] users << user.new('john', 'smith', 55) file.open("users.json", "w") |f| f.write(json.pretty_generate(users) end the problem user isn't being json'ified, saving file like: [ "#<user:0x000000101010eff40>", .. ] also, how read json file collection? the problem is, users variable still array of activerecord objects. need convert them json. users = [] users << user.new('john', 'smith', 55) file.open("users.json", "w") |f| f.write(json.pretty_generate(users.to_json) end

How can I get output file names after a C# MSBuild completes? -

i using buildmanager.defaultbuildmanager.build() build visual studio solution contains many projects. code looks lot this . once build completes, i'd copy output (dlls in case) target folder. but don't see way retrieve file names of build output buildresult. i can scan sln file , infer output locations. error-prone , tedious. build() returns buildresult . far can tell, buildresult not contain actual output file names. how can output file names after build completes? you provide output path build. clear folder before build , work newly generated files. var solutionpath = "..."; var outputpath = "..."; var pc = new projectcollection(); var properties = new dictionary<string, string>(); properties.add("outputpath", outputpath); var request = new buildrequestdata(solutionpath, properties, null, new string[] { "build" }, null); var result = buildmanager.defaultbuildmanager.build(new buildparameters(pc), re

android - How to get a more specific result from a JSON object in volley -

Image
this question has answer here: sending , parsing json objects [closed] 11 answers i trying more specific result getting. here code: // request string response provided url. jsonobjectrequest jsobjrequest = new jsonobjectrequest (request.method.get, url, (string)null, new response.listener<jsonobject>() { @override public void onresponse(jsonobject response) { try { jsonobject city = response.getjsonobject("city "); mtextview.settext("" + city.tostring()); } catch (jsonexception e) { e.printstacktrace(); } } }, new response.errorlistener() { @override public void onerrorresponse(volleyerror error)

java - How to change the (displayed) selected item on a disabled JComboBox? -

i'd change displayed selected item on disabled jcombobox programmatically. tried enabling before invoking setselecteditem , disabling right after the former , invoking updateui before disabling it might isn't intended, save me work replace combobox jlabel , dirty hack answer appreciated well. well, seems work okay me... import java.awt.eventqueue; import java.awt.gridbagconstraints; import java.awt.gridbaglayout; import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.jbutton; import javax.swing.jcombobox; import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.uimanager; import javax.swing.unsupportedlookandfeelexception; public class test { public static void main(string[] args) { new test(); } public test() { eventqueue.invokelater(new runnable() { @override public void run() { try { uimanager.setlookandfeel(

c++ - GCC doesn't link static library dependency (makefile) -

i use static library, let's assume cityhash, i've build , installed /usr/local/lib. have file foo.cxx uses cityhash, example: // foo.cxx u64 get_hash(const std::string &s) { return cityhash64(s.data(), s.size()); } i build static library it: gcc -c foo.cxx => foo.o ar rcs libfoo.a foo.a => libfoo.a i have file, bar.cxx, uses foo.cxx , indirectly cityhash function. compile it, , link both libcityhash.a , libfoo.a following: gcc -c bar.cxx => bar.o gcc -l. -o bar bar.o -lcityhash -lfoo but doesn't work, linker complains cityhash64 undefined reference. wrong? when not make static library libfoo.a works fine. see this. need write linker args -lfoo -lcityhash . library needs symbol should go before 1 provides it. why order in libraries linked cause errors in gcc?

php - Slim Framework 3 Upload -

i have problem upload files through slim framework 3 slim\http\uploadedfile. my code: $app->post('/upload', function ($req, $res, $args) { $setting = $this->settings; $uploadpath = $setting['upload']['path']; $file = $req->getuploadedfiles()['img']; $file->moveto($uploadpath); return $res; }); result: slim application error application not run because of following error: details type: runtimeexception message: error moving uploaded file hss.png /home/xxx/web/slim3/app/../log file: /home/xxx/web/slim3/vendor/slim/slim/slim/http/uploadedfile.php line: 237 i found out answer. @akrabat <!doctype html> <html> <head> <meta charset="utf-8"> <title>slim 3</title> <link rel="stylesheet" href="http://yegor256.github.io/tacit/tacit.min.css"> </head> <body> <h1>uploa

javascript - How do I check if a username is taken with parse.com when all User ACL:Public read/write is disable? -

how check if username taken parse.com javascript sdk when acl:public read/write disable in users inside user's class? explanation: security reasons users in class/table user have private acl (access control list), or in other words acl public read/write disable, means authenticated users can read only own information. as can imagine query users empty non logged in users so there no way check if user taken using query on user class i manage work around singup new user , parse return 400 error information: {code: 202, error: "username test taken"} the problem approach i'm doing validation on real time while user typing on text area field: html angularjs: <form name="form"> <h3>e-mail</h3> <input class="form-control" name="email" placeholder="try john.doe@mail.com or bad@domain.com" type="email" required ng-model="email&quo

php - How to display/ retrieve all images from the database -

i want display image s database code here displays one. how can them , display in webpage. know need put loop wonder should be. here's php code far (without loop) include('../include/connect.php'); $query=ibase_query("select filedata archive file_type='image'"); $data=ibase_fetch_object($query); if($data){ header("content-type:image/jpeg || image/gif || image/png || image/pjpeg"); ibase_blob_echo($data->filedata); } each time use ibase_fetch_object gets next object so uset in while loop (php example) : header("content-type:image/jpeg || image/gif || image/png || image/pjpeg"); while ($data=ibase_fetch_object($query){ ibase_blob_echo($data->filedata); } edit : following this answer should have 2 separate files

ajax - How to implement image upload to the PageDown markdown editor? -

to implement image upload pagedown markdown editor, have modified code editor. markdown.editor.js var defaultsstrings = { imagedialog : "< input id='image' type='file' />" } when select picture , click ok button sent ajax request. can return image path. var okbutton = doc.createelement("input"); okbutton.type = "button"; okbutton.onclick = function () { var data = new formdata(); data.append('file', $( '#image' )[0].files[0] ); $.ajax({ url: 'uploadfile', data: data, processdata: false, contenttype: false, type: 'post', success: function ( data ) { alert(path); } }); return close(false);}; how preview image in editor preview area? this article provide useful method, e

javascript - Webpack Missing Module 'Module Not Found' -

i'm working on react webpack babel etc site , trying build first time. build successful, when open browser following error: uncaught error: cannot find module "/users/michael.nakayama/documents/development/jamsesh/node_modules/webpack/node_modules/node-libs-browser/node_modules/process/browser.js" this module exists. going actual url in browser shows file in question. cannot figure out why webpack cannot find it. don't know if babel6 issue or webpack issue, or neither. config file looks this: var webpack = require('webpack'); var cleanwebpack = require('clean-webpack-plugin'); var ignore = new webpack.ignoreplugin(new regexp("/(node_modules|ckeditor)/")) module.exports = { devtool: 'inline-source-map', entry: './lib/client/entry', output: { path: __dirname + '/public/js', filename: 'app.js', publicpath: 'http://localhost:8081/js/', }, plugins: [ ignore, ], resol

css - flexbox height adjust to content -

i use "full design" flexbox. have weird issue : have container takes remaining space , want in container child, flexbox, have height adjust content. here issue: body, html { width:100%; height:100%; display:flex; } .container { display:flex; flex:1; flex-wrap:wrap; } .icon { width:10vh; margin:10px; display:flex; flex-direction:column; } .img { width:10vh; height:10vh; display:flex; align-items:center; justify-content:center; background-color:red; } .text { text-align:center; } <div class="container"> <div class="icon"> <div class="img"> </div> <div class="text"> action 1 </div> </div> <div class="icon"> <div class="img"> </div> <div class="text"> action 2 </div> </div> <div class="icon"> <div class="img&qu

parsing - C source code lexical parser in Java -

i need lexical parser parse c source codes , have using java language. researched , saw antlr , javacc. of these parsers better use , why? or have other parser recommend? answers appreciated. thanks. a lexer breaks input stream tokens. don't count incomplete purpose of computing simple metrics. if want differentiate "functions" "variables" you'll need kind of parser check sequences of tokens determine represent (e.g., "a variable declaration, use, or function declaration"). can build ad hoc parser may satisfy counting needs @ price of making occasional mistakes, or can real parser , right. (parsing c variable declaration lot harder looks @ first glance; pretty arcane syntax). if homework, or real problem , don't care if answer wrong, lexer generator , ad hoc parsing code enough. if want accurately, you'll need preprocessor , parser, , you'd better (implicitly including lexer).

ios - In CloudKit, after adding a record, the new record will not appear in a query that is conducted right away. How to solve it? -

i developing ios app using cloudkit. have problem: after adding record using ckmodifyrecordsoperation , if query right away using ckqueryoperation records, newest record doesn't appear in query result. seems newest record appear in queries conducted several seconds after writing operation. so, how solve it? in app, when user add new record, app refresh list of records. in cases, list not have new record. after user refresh list later, record appear. get number of records before update then in code update, @ end of update, count of records. if count same count before update made, "wait" (swift has wait function) there till count 1 more preupdate count

function - Comparing two passwords for validation in C++ -

i trying compare 2 c++ strings. function passes old password compared new password. condition new password first half of new password , old password cannot same , second half of new password , old password cannot same. example, if old password abcdefgh , new password abcdyzyz, new password not accepted since first half of these passwords same. have come far , runs display doesn't show output statement. comparing them correctly? bool changepassword(string& password) { string newpw; int lengthnewpw; int lengtholdpw; float sizen; float half; { cout << "enter new password: "; getline(cin, newpw); lengthnewpw = newpw.length(); lengtholdpw = password.length(); if (lengthnewpw < lengtholdpw) { sizen = lengthnewpw; } else if (lengtholdpw < lengthnewpw) { sizen = lengtholdpw; } else sizen = lengtholdpw; half = sizen / 2; if (newpw.compare(0, half - 1, password) == 0 || newpw.co

android - Periscope Comments Animation -

Image
i trying achieve same animation in periscope comments . the way doing is: having listview . animation fade-out first visible child inside listview. not seems working. kindly give me suggestion on how achieve . thanks!

mysql - Looking for a better solution - long list of AND operator with a type String comparision -

i have search function search keywords in large mysql table, since need filter out bad words, have following type of , comparison in mysql, long list of banned words (over 500+) , due slow, select * keywords 1 , keyword not '%love%' , keyword not '%hope%' , keyword not '%caring%' , keyword not '%x%' , keyword not '%happiness%' , keyword not '%forgiveness%' , keyword not '%good%' , keyword not '%great%' , keyword not '%positive%' , keyword not '%sharing%' , keyword not '%awesome%' , keyword not '%fantastic%' any other better way of doing ? using like pattern-matching has terrible performance, because there's no way use index it. using regular expressions @fuzic suggests worse. you need use fulltext indexing solution if want performance. i cover , compare several solutions in presentation, full text search throwdown

node.js - Angular2 with TypeScript: Declaration expected compiler error after @component -

im getting kind of error despite of fact imported component angular2/core should source files not downloaded through npm install or node needs upgrade here file import {bootstrap} 'angular2/platform/browser'; import {component, view} 'angular2/core'; @component({ }) define class right after component. import {bootstrap} 'angular2/platform/browser'; import {component, view} 'angular2/core'; @component({ }) class myclass { } @component decorator contains metadata class. in other words defines stuff class in more elegant way. the @component function takes configuration object , turns metadata attaches component class definition. angular discovers metadata @ runtime , knows how "the right thing". read more here

java - How to solve error about implementing inherited abstract class method? -

code- new itemlistener() { public void itemstatechanged(itemevent event){ if(event.getstatechange()==itemevent.selected) pics.seticon(pic[box.getselectedindex()]); } } i getting error, the new type itemlistener(){} must implement inherited abstract class method itemlistener.itemstatechanged(itemevent) assuming anonymous implementation of java.awt.event.itemlistener , should implement method itemstatechanged(itemevent e) - note lowercase i in api specification opposed upper case i in implementation.

java - How can I render a JList inside a JTable cell? -

Image
in 3 of columns of jtable have set have list in each cell of column. i'm not sure start on possibly creating custom cell renderer class if that's best option? goal list group names each on own line in each cell, , expand cell height new lines added. each group have admtype , admitted entry, need figure out how add checkbox admitted column cell every new group entry. this below solution did not work me, worked person posted screen shot of success. problems may due how have tablemodel set up. https://stackoverflow.com/a/32793088/6867420

CmisInvalidArgumentException when downloading Private Working Copy from Alfresco via CMIS -

my open-source app downloads files of alfresco folder (by cmis ). algorithm simple: list content of folder folder.getchildren() download each document.getcontentstream() it works fine, except folders contain working copy of file, in case alfresco says: org.apache.chemistry.opencmis.commons.exceptions.cmisinvalidargumentexception: stream id invalid: workspace://spacesstore/8b9a58ba-652f-4a18-8d26-aba06df98d25;pwc @ org.alfresco.opencmis.cmisconnector.getcontentstream(cmisconnector.java:1199) @ org.alfresco.opencmis.alfrescocmisserviceimpl.getcontentstream(alfrescocmisserviceimpl.java:1795) @ sun.reflect.generatedmethodaccessor700.invoke(unknown source) the ;pwc means "private working copy", special case in cmis protocol. working copies created when alfresco share user clicks "edit offline" on document (aka check out/check in). is algorithm flawed? or bug in alfresco/opencmis? i'm not sure of details, don't paste here

How to filter dates in mysql? -

Image
i have start date (l_start_date), end date (l_end_date) , dates (l_date) in database. for example, user selecting start date 15-01-2016 , end date 30-01-2016. how can rows of date (l_date) contains date between user selected start date , end date? i got struck : in below image (l_date) 2016-01-29, 2016-01-30, 2016-02-01, 2016-02-02. here how can row too, because user range till 2016-01-30 end date (l_end_date) had stored 2016-02-02 ignoring. i tried: select l_date,l_start_date,l_end_date `dates` (l_end_date >= '2016-01-15' or l_end_date <= '2016-01-15') , (l_start_date >= '2016-01-15' or l_end_date <= '2016-01-15') , (l_end_date >= '2016-01-30' or l_end_date <= '2016-01-30') , (l_start_date >= '2016-01-30' or l_end_date <= '2016-01-30') you can use following logic: where l_end_date >= '2016-01-15' , -- input start date l_sta

php - Symfony form validation basic form -

i have user entity class this: namespace appbundle\entity; use doctrine\orm\mapping orm; use doctrine\orm\mapping\onetoone; use doctrine\orm\mapping\joincolumn; use symfony\component\validator\constraints assert; /** * @orm\entity * @orm\table(name="clients") */ class clients { /** * @orm\column(type="integer") * @orm\id * @orm\generatedvalue(strategy="auto") */ private $id; /** * @orm\column(type="string", length=255, nullable=false) * @assert\notblank( * groups={"registration"}, * message = "il campo nome non può essere vuoto." * ) */ private $name; then, have clientstype this: namespace appbundle\form; use symfony\component\optionsresolver\optionsresolver; use symfony\component\form\abstracttype; use symfony\component\form\formbuilderinterface; class clientstype extends abstracttype { public function buildform(formbuilderinterface $bui

android - Parsing char to vector<float> for hog.setSVMdetector(vector<float>) -

i have problem parsing float char in jni-android application.this sample data : 0.00618567 0.00224441 0.002006603 0.001813437 0.003761207 -0.001850192 -0.001011893 -0.00342476 0.003790586 0.002385935 0.002647488 0.004411637 0.005938921 0.00698391 0.004522655 0.001524881 -0.002673242 -0.0002569943 -0.002495839 0.00230171 0.000844161 0.006387557 0.008135659 0.005583601 0.002238941 -0.001932641 -0.003518643 -0.0006784072 0.001636732 0.001213515 0.0021472 0.004911256 0.003613603 0.001362842 -0.0002172031 -0.002115535 -0.0002000824 0.001085831 0.003149634 0.003899722 0.004865647 0.002436467 0.0001896242 -0.001678405 -0.001909177 -0.002954236 0.001802054 0.003751467 0.004150682 0.005844797 0.002612064 0.003680898 -0.0005450704 -0.002621638 -0.002253087 0.0005009398 0.004602027 0.003445318 0.00632045 0.002706638 -0.001308871 -0.002082631 -0.001821213 -0.0005696003 0.002069579 0.006264412 0.004593662 0.005836432 0.0009420562 -0.003753015 -0.004050847 -0.001744672 -0.002664186 0.00101941

sql - Define Data Integrity, specifically Intra Record Integrity when working with databases -

i'm wondering if can explain in simple enough terms intra-record integrity means when working databases? definition have "enforcing constraints on contents of fields linked data validation" hoping elaborate further?.. here 1 explanation depends heavily on word "intra-record". let's start example, lets have health record patient, has fields such as id gender age date_of_birth last_menstrual_date now if value of gender male , last_menstrual_date null or blank. similarly if have populated both fields age , date_of_birth, , lets have date_of_birth = january 1 1976 , age = 30, incorrect since if person born on january 1 1976 age should 40 or, if age in fact 30 date_of_birth should january 1 1986 . note: bad design include both age , date_of_birth columns in same table, above show case of data integrity so way fields within record i.e. intra-record valid , not violate data integrity. this 1 explanation of intra-record data integrity

java - IMAGE EXCEPTION -

jpegimageencoder encoder = jpegcodec.createjpegencoder(out); jpegencodeparam param = encoder.getdefaultjpegencodeparam(bi); jpegimagedecoder decoder = jpegcodec.createjpegdecoder(in);' when compile code above says com.sun.image.codec.jpeg.jpegcodec api may have been removed. how clear warning? using java version 6. simply use imageio reading/writing , maybe encoding. encoding parametrisation might not sun's implementation. and yes, not every jdk/jre goes sun classes. portability issue.

type conversion - How to convert variable into integer in python? like in php (int) -

i have variable value ="\x01" database, how can convert integer. have searched internet had no success in finding anything. anyone have idea? in php, there build-in module convert it. there similar module function in python? simple answer use ord() . >>> = '\x01' >>> ord(a) 1 but if performance looking refer @chepner's answer .

c# - Make texture2D readable in runtime/script Unity3D -

i have plugin allows me access pictures android phones gallery. gives me texture of texture2d type. want edit using getpixels function, not set readable default. how make texture readable can use getpixels on it? basically allowing user select picture phone , crop it. in following example pic picture cropped red rectangle. works if make texture readable beforehand. http://puu.sh/mxr3h/dfa81719b2.jpg if have files in project, can select texture in inspector, set texture type "advanced," set "read , write enabled" true. if not, can try using getrawtexturedata() on texture have, create new texture same width , height , call loadimage() on new texture data got old one, making sure marknonreadable false. should able want on new texture , display while user cropping image. http://docs.unity3d.com/scriptreference/texture2d.getrawtexturedata.html

vb.net - Removing or disable ComboBox item which is selected in another list -

i have 3 combo boxes on winform following: ___________________________ combobox list 1: |_______________________|___| ___________________________ combobox list 2: |_______________________|___| ___________________________ combobox list 3: |_______________________|___| each of these combo boxes have, @ design-time, list of "a", "b", "c". by default, list 1 1 active on form , list 2 , list 3 become active when predecessor given selection. what do, if user choose option c, have option c no longer available list 2 , 3. i know involve .selectedindexchanged event of combobox not know started coding. i found following answer on stackoverflow, how situation doesn't apply since i'm supplying items @ design time , not via import of file: vb.net change combobox options depending on selected item in 2 previous comboboxes this similar steve's answer, uses datasource . also, the

Clicking markers on Google Static Maps -

i have application downloads static images off google maps, markers placed want them (placed passing arguments google static maps url). however, need able click markers. figured convert x , y coordinate click lon/lat, , figure out way marker clicked, haven't found easy. i know dimensions of map in pixels, zoom level, , centre point of map in pixels , lon/lat, followed this blog post . unfortunately didn't work. does know how this, or know way figure out if marker has been clicked? i'm forced use static maps unfortunately, can't of javascript api see: http://home.provide.net/~bratliff/largetiles/ or http://home.provide.net/~bratliff/harbor/ it not doing demonstrate mercator projection conversions & cross-browser mouse events.

Null object reference Android Azure -

i have problem azure mobile services on android, see exmaple todoitem , create instance called user to save data. code public class user { @com.google.gson.annotations.serializedname("email") private string email; @com.google.gson.annotations.serializedname("password") private string password; @com.google.gson.annotations.serializedname("name") private string name; @com.google.gson.annotations.serializedname("lastname") private string lastname; @com.google.gson.annotations.serializedname("phone") private string phone; public user(){ } public user(string email, string password, string name, string lastname, string phone){ this.setemail(email); this.setpassword(password); this.setname(name); this.setlastname(lastname); this.setphone(phone); } public string getemail() { return email; } public string getpassword() { return password; } public string getname() { return name; } public string ge

oop - PHP - unique attribute for objects of a class -

i have class class myclass{ private $id; private $name; public function __construct ($id, $name){ $this->name = $name; } } $ob1 = new myclass(1, 'earth'); $ob2 = new myclass(2, 'sky'); $ob3 = new myclass(3, 'ocean'); i want objects $ob1, $ob2 , $ob3 have different attribute $id. example when make : $ob4 = new myclass(3, 'wood'); the code denies me create object thanks you need keep track of ids in static class property: class myclass { static private $ids = []; public function __construct($id) { if (in_array($id, self::$ids)) { throw new exception("object id $id constructed"); } self::$ids[] = $id; } } having said this, question usefulness of this. sounds recipe problems. should keep track of unique data part of business logic , database interaction, not enforced on language level.

javascript - Interrupting while() and finalizing gracefully Node.js -

i implementing random sampling / montecarlo heuristic travelling salesman problem. want perform maximum c iterations, while being able stop search when want ctrl + c or sending sigint process. i know has been asked before (related: quitting node.js gracefully ) given solution not working me. process doesn't exit when give ctrl + c , if kill it, finalizing code not executed. my code: var tsp = require("./tsp.js"); var data = tsp.load("./input/it16862.tsp"); var starting_point = data.splice(10927, 1)[0]; var c = 0; var cost = number.positive_infinity; var new_cost, solution, candidate_solution; var interrupt = false; var c = 0, interrupt = false; process.on('sigint', function() { interrupt = true; }); while(c < 1000000000) { if (interrupt) { break; } candidate_solution = shuffle(data); new_cost = tsp.cost(candidate_solution, starting_point); if (new_cost < cost) { cost = new_cost; solut

html - Get single-page website below navigation bar on bottom of browser -

okay, title might sound confusing, i'm not sure. i've got site i'm working on locally , have navigation bar start @ bottom of page , scroll , become fixed top of browser. issue i'm having, however, getting #pagecontent go below navigation bar. it's taking space both above and below it. please take @ codepen i've linked below see mean. http://codepen.io/anon/pen/dgvmvx note 1: ids of i'm trying below navigation bar #pagecontent , #pagecontentwrapper . can found @ bottom of css , contains of <br /><br /> in html. if i'm thinking correctly focus should on getting #pagecontent below navbar (since it's contains #pagecontentwrapper . note 2: while they're taking space above navbar, they're covering landing (or home) section of website. if comment out background colors you'll able see it. note 3: gave them backgrounds did it's easier on guys visually , can tell sections you're working apart rest. once they

c# - Dynamically set SQL connection string based on session -

session variable becomes null when called public partial class outside methods. if called inside methods value available. code initialize sql connection string not work intended. public partial class doctor_default : system.web.ui.page { sqlconnection con = new sqlconnection(session["connectionstring"].tostring()); protected void page_load(object sender, eventargs e) { } } maybe work you: string constring; sqlconnection con; protected void page_load(object sender, eventargs e) { constring = session["connectionstring"].tostring(); // check here constring == null, if necessary. con = new sqlconnection(constring); }

java - How to update the JAR file with original settings? -

i'm trying update kitchen.jar file, refuses work after update. here's did: $ jar xf kitchen.jar $ jar uf kitchen.jar com/package/toster.class all looks good. opendiff (as jar tf ) shows no difference , file size 1008 bytes different. binary compare shows 700 differences. , jar doesn't work more. as can see did not change files, did extraction , updated jar file original untouched class file. i've seen similar question on so, did not answer it, structure not changed. the original manifest has this: created-by: 1.7.0_05-b05 (oracle corporation) while have: $ javac -version javac 1.7.0_17 have (however not sure if relevant) jar file i'm trying modify part of eclipse ide plugin. i have 2 thoughts: this because i'm on mac while original jar created on different platform. this because there java runtime vars defined (jar`s -j option) while creating package. this makes me think either need find platform created , try packaging there,

java - SharedPreferences in my adapter -

null pointer exception error.. i'm trying access sharedpreferences in adapter don't know why showing nullpointerexception. here log , code. 01-16 21:20:05.546 15405-15405/com.adequatsol.hdwallpaper e/androidruntime﹕ fatal exception: main process: com.adequatsol.hdwallpaper, pid: 15405 java.lang.runtimeexception: unable instantiate activity componentinfo{com.adequatsol.hdwallpaper/com.adequatsol.hdwallpaper.fullimageactivity}: java.lang.nullpointerexception: attempt invoke virtual method 'android.content.sharedpreferences android.content.context.getsharedpreferences(java.lang.string, int)' on null object reference @ android.app.activitythread.performlaunchactivity(activitythread.java:2546) @ android.app.activitythread.handlelaunchactivity(activitythread.java:2758) @ android.app.activitythread.access$900(activitythread.java:177) @ android.app.activitythread$h.handlemessage(activitythread.java:1448) @ android.os.handler.dispat

java - What is a NullPointerException, and how do I fix it? -

what null pointer exceptions ( java.lang.nullpointerexception ) , causes them? what methods/tools can used determine cause stop exception causing program terminate prematurely? when declare reference variable (i.e. object) creating pointer object. consider following code declare variable of primitive type int : int x; x = 10; in example variable x int , java initialize 0 you. when assign 10 in second line value 10 written memory location pointed x. but, when try declare reference type different happens. take following code: integer num; num = new integer(10); the first line declares variable named num , but, not contain primitive value. instead contains pointer (because type integer reference type). since did not yet point java sets null, meaning "i pointing @ nothing". in second line, new keyword used instantiate (or create) object of type integer , pointer variable num assigned object. can reference object using dereferencing operator . (a dot

Android Keyboard showing resize activity -

i'm trying resize activity when edittext become first responder , keyboard showing. for have used android:windowsoftinputmode="adjustresize" in androidmanifest.xml . works great when keyboard showing can see previous activity in background. normal? both activities have white background i'm wondering doing wrong? my second activity xml: <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white"> <textview android:id="@+id/topview" android:background="@color/hwmmaincolor" android:textcolor="@color/white" android:layout_width="match_parent" android:layout_height="60dp" android:padding="6dip"/> <linearlayout xmlns:a

mongodb - how to find a property is exist or not in an array in a collection? -

this question has answer here: find document sub array? 2 answers what query document use in find() command return movies in video.moviedetails collection either won or nominated best picture? may assume award appear in "oscars" array if movie won or nominated. "awards" : { "oscars" : [ {"award": "bestanimatedfeature", "result": "won"}, {"award": "bestmusic", "result": "won"}, {"award": "bestpicture", "result": "nominated"}, {"award": "bestsoundediting", "result": "nominated"}, {"award": "bestscreenplay", "result": "nominated"} ], "wins" : 56,

sql - Creating an index for a complex geospatial query with many joins -

i've been reading creating postgres indexes day or 2 not getting results rather complex query. i've attached query below in case you're interested in seeing i'm dealing (code has been extracted source code): http://paste.ofcode.org/yv2kmnrw2bupungdgu6djb also here's explain response: http://paste.ofcode.org/eudmuutchgkhrgqpydfath i'm wondering tactic should take in planning index scheme. guidance/insight appreciated. thanks.

php - Checking for page templates in child theme -

i have simple problem i'm hoping can shed light on. have child theme custom page template , i'm trying check weather or not template in use. under normal circumstances, have used is_page_template function, doesn't seem working child themes. i've tried following if(is_page_template('template-custom-fullwidth.php')){ //do something.. } as if(is_page_template(dirname(get_bloginfo('stylesheet_url')).'/template-custom-fullwidth.php'){ //do something.. } neiter works , hoping there more elegant solution using $_server check urls. can't imagine there not being function seeing seems common task. believe problem difference between template , stylesheet directories. possible use wordpress check page templates located in child theme? thanks in advance! reference wp codex page: http://codex.wordpress.org/function_reference/get_stylesheet_directory_uri use get_stylesheet_directory_uri instead. should work: is_pa

oop - Domain Driven Design - Creating general purpose entities vs. Context specific Entities -

situation suppose have orders , clients entities in application. in 1 aggregate, order entity considered root want make use of client entity simple things. in client root entity , order entity touched ever lightly. an example: let's in order aggregate use client read details name, address, build order history , not make client client specific business logic. (like persistence, passwords resets , flips..). on other hand, in client aggregate use order entity report on client's buying habbits, order totals, order counting, without requiring advanced order functionality order processing, updating, status changes, etc. possible solution i believe better solution create entities each aggregate specific aggregate context, because making them full featured (general purpose) , ready situation , usage seems overkill , potentially become maintenance nightmare. (and potentially memory intensive) question what ddd recommended way of handling situation? take on matter?

vb.net - Removing and adding event handlers for different ComboBoxes where the ComboBox is passed as a parameter -

i have method takes combobox parameter , adds data it. when data added, selectedindexchangedevent fires. there way that, in called method, can remove above event handler whatever combobox passed parameter , add @ end of method? know how remove , add specific handlers, can't figure out how based on combobox passed. here's method.. private sub populatecombobox(byref cbobox combobox, byval itemsource string) 'remove handler cbobox 'do stuff otherwise cause event handler execute 'add handler cbobox end sub i have 4 comboboxes - easier remove 4 event handlers , add them again @ end of code? know if possible can possibly apply re-usable code in future the basic way go this: private sub populatecombobox(byref cbobox combobox, byval itemsource string) removehandler cbobox.selectedindexchanged, addressof combobox1_selectedindexchanged 'do stuff otherwise cause event handler execute addhandler cbobox.selectedindexchanged, addr

c# - Code contracts causing error due to potential side-effect -

i new code contracts may have done stupid here :) i getting error detected expression statement evaluated potential side-effect in contracts of method '##'. (did mean put expression requires, ensures, or invariant call?) i have following contracts contract.requires<argumentnullexception>(obj != null); contract.requires<argumentnullexception>(obj.id != null); it failing on second contract obj.id != null ( id guid ) now possible id null isn't allowed in method. code contracts raises above compile error. method self doesn't return needs no ensures either. i have removed contract can compile , placed standard if check. causing this? you need mark id property [pure] that tell code contracts analyser has no side-effects. code contracts don't calling methods have side-effects; code behave differently depending on whether had code contract checking enabled or not, bad thing. example: public guid id { [pure]