Posts

Showing posts from May, 2012

merge - Merging two sorted lists, one with additional 0s -

consider following problem: we given 2 arrays a , b such a , b sorted except a has b.length additional 0s appended end. instance, a , b following: a = [2, 4, 6, 7, 0, 0, 0] b = [1, 7, 9] our goal create 1 sorted list inserting each entry of b a in place . instance, running algorithm on above example leave a = [1, 2, 4, 6, 7, 7, 9] is there clever way in better o(n^2) time? way think of insert each element of b a scanning linearly , performing appropriate number of shifts, leads o(n^2) solution. some pseudo-code (sorta c-ish), assuming array indexing 0-based: pa = + len(a) - 1; pc = pa; // last element in while (! *pa) --pa; // find last non-zero entry in pb = b + len(b) - 1; while (pa >= a) && (pb >= b) if *pa > *pb *pc = *pa; --pa; else *pc = *pb; --pb; --pc while (pb >= b) // still bits in b copy on *pc = *pb; --pb; --pc; not tested, ,...

javascript - Hiding partly overflowing text in a multi-line div? -

Image
how remove or hide partly overflowing text row? example: html: <div>lot of interesting text in multi-line box how remove or hide last line</div> css: div { border: 1px solid black; height:65px; width:150px; overflow:hidden; } https://jsfiddle.net/7mudnnco/ edit: image of how want result: edit2: similar question has working solution looking solution lines hidden when no line visible. working solution: http://jsfiddle.net/4fpq2/9/ (change height 15px see why not working) if font size , box size known can design box contains 3 lines of text, 1 way be: div { border: 1px solid black; height:65px; width:150px; overflow:hidden; line-height: 22px; }

xml parsing - Identify and replace elements of XML using BeautifulSoup in Python -

i trying use beautifulsoup4 find , replace specific elements within xml. more specifically, want find instances of 'file_name'(in example below file name 'cyp26a1_atra_minus_tet_plus.txt') , replace full path document - saved in 'file_name_replacement_dir' variable. first task, bit i'm stuck on, isolate section of interest can replace using replacewith() method. the xml <parametergroup name="experiment_22"> <parameter name="data row oriented" type="bool" value="1"/> <parameter name="experiment type" type="unsignedinteger" value="0"/> <parameter name="file name" type="file" value="cyp26a1_atra_minus_tet_plus.txt"/> <parameter name="first row" type="unsignedinteger" value="1"/> there 44 experiments 4 different file names (so 11 file name 1, 11 file name 2 ...

javascript - Show Hide after clicking svg path -

so i've pretty figured out in way works. currently i'm using <set attributename="visibility" from="hidden" to="visible" begin="mali.click" end="mali.mouseout"></set> which works guess, there way end svg animation click? because when set end = mali.click makes nothing happens @ all. need nextclick or something.

vb6 - How can I find the difference between two times that have milliseconds -

using vb6 only... i have 2 times , need time between them. have file contains times in format "08:34:45:734" , need calculate time difference between 2 values. example: 08:34:12:744 08:34:45:734 i need output generate correct time, including milliseconds, between 2 times. tried convert double , subtract, can't seem way h:m:s:m time format need. this should work. vb dates not include number of ms strip ms off , calculate difference yourself. private function gettimediff(strdate1 string, strdate2 string) string dim fneg boolean dim dt1 date, dt2 date dim ms1 long, ms2 long ' assign earliest date dt1... if strdate1 <= strdate2 dt1 = left$(strdate1, 8) dt2 = left$(strdate2, 8) ms1 = right$(strdate1, 3) ms2 = right$(strdate2, 3) else dt1 = left$(strdate2, 8) dt2 = left$(strdate1, 8) ms1 = right$(strdate2, 3) ms2 = right$(strdate1, 3) fneg = true ...

mininet - get_all_link(self) outputting all possible LINKs for a topo -

i have topo 4 switches , 4 hosts. switches construct loop. goal learn topology of network when switches connected controller. problem function get_all_links() returns of possible links or @ least doesn't make sense. call function when port_modify event fired. here code use construct topo: <removed imports save space> class simple3pktswitch(topo): """simple topology example.""" def __init__(self): """create custom topo.""" # initialize topology topo.__init__(self) # add hosts , switches h1 = self.addhost('h1') h2 = self.addhost('h2') h3 = self.addhost('h3') h4 = self.addhost('h4') # adding switches p1 = self.addswitch('p1', dpid="0000000000000001") p2 = self.addswitch('p2', dpid="0000000000000002") p3 = self.addswitch('p3', dp...

Stanford CoreNLP Training Examples -

anyone know following files located: trainfilelist = /u/nlp/data/ner/column_data/muc6.ptb.train, /u/nlp/data/ner/column_data/muc7.ptb.train i following faq link http://nlp.stanford.edu/software/crf-faq.shtml#a if need provide file 2 columns consisting of tokens , class, work. curious train files listed in classifier property files. serializeto = english.muc.7class.caseless.distsim.crf.ser.gz java -mx1g -cp "$classpath" edu.stanford.nlp.ie.nerclassifiercombiner -textfile sample.txt -ner.model classifiers/english.all.3class.distsim.crf.ser.gz,classifiers/english.conll.4class.distsim.crf.ser.gz,classifiers/english.muc.7class.distsim.crf.ser.gz -outputformat tabbedentities -textfile sample.txt > sample2.tsv those files training data muc-6 , muc-7 tasks: http://cs.nyu.edu/faculty/grishman/muc6.html they not distributed stanford. see if can figure out distributed , update answer. update: ldc distributes files if want copy, have copyright issues have...

javascript - How do I create a variable that persists across reloads and code pushes? -

if write plugin requires large initialization (14 mb javascript takes 1 minute set up), how can make object persistent (for lack of better word) across javascript files used in meteor projects? after initialization of plugin, have object largeobject , when add file simple_todo.js , want use largeobject without taking minute load after every change. i cannot find solution. i tried making separate package store in package object, cleared after every change , reinitialized. what proper way of doing that? imagine there should internal in meteor survives hot code push. here 2 possible solutions i: cache of properties inside session cache of properties inside simple collection use stub in local environment. session can used client side. can use collection anywhere. session client example = function () { if(!(this.alotofdata = session.get('alotofdata'))) { this.alotofdata = computealotofdata() session.set('alotofdata', this.alot...

Use regex to find a substring with hyphen -

i'm new @ regex character matching , need regex not match substring sl-t , character t . regex character t cannot detect t character in substring sl-t . have looked @ other questions , nothing has helped me. close can before negating expression. (sl-t)|(t) any appreciated! edit using javascript regex. here small portion of data. lines except 1,4, , 6 need matched expression. t //1 w-r t-sb t //4 st sl-t //6 sl tsge sr st ^(?!(?:sl-)?t$) starting @ beginning of line, uses negative lookahead make sure string not consist of optional "sl-" , letter "t" followed end of string.

xml - Is there a wildcard for elements in XMLSchema validation? -

my xml file consists of general part, want validate, , special part, validated later (using different xsd file checks general part again ok since not change). how can tell xmlschema check element generalpart , not element specialpart? also, name specialpart should interchangible if possible. i'd replace <xs:element name="specialpart" minoccurs="0" maxoccurs="1"> <xs:anything/> ... <?xml version="1.0" encoding="iso-8859-1"?> <xs:schema xmlns:xs="http://www.w3.org/2001/xmlschema" elementformdefault="qualified" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"> <xs:element name="mymodule"> <xs:complextype> <xs:sequence> <!-- general part --> <xs:element name="generalpart" minoccurs="0" maxoccurs="1"> <xs:complextype> <xs:sequence> ...

cordova - Couchbase mobile replication through REST-API -

while trying integrate couchbase mobile (version 1.1.0) in our hybrid mobile app (ionic), ran issue push replication on ios. at point in application (after local database has been created , on) design document views created successfully. continuous push , pull replication created , started well. when polling push replication status noticed had stopped (not normal continous replication) shortly after had been started. couchbase mobile replied error (404) warning: cbl_pusher[http://server:4985/bucket-sync-gateway]: _bulk_docs got error: { error = "bad_request"; id = "_design/app"; reason = "invalid doc id"; status = 400; } the sync gateway logged similar error: bulkdocs: doc "_design/app" --> 400 invalid doc id (400 invalid doc id) this happens on ios. android version doesn't have issues replications (maybe design documents ignored?) why replication try sync design documents on ios , not on android? should d...

ember.js - ember-i18n : TypeError: app[initializerType] is not a function -

i've been installing ember-i18n on working ember project. ( https://github.com/jamesarosen/ember-i18n ) after registering initializer app/initializers/i18n.js : export default { name: 'i18n', after: 'ember-i18n', initialize: function(_, app) { app.inject('model', 'i18n', 'service:i18n') } }; and relaunching server, error in console : app[initializertype] not function do have idea ? ember version : "ember": "1.11.1" it looks format of initializer not correct. per this example ember guides , there 2 important parts. first, factory must registered (application.register) , must injected (application.inject). ember.application.initializer({ name: 'logger', initialize: function(container, application) { var logger = { log: function(m) { console.log(m); } }; application.register('logger:main', logger, { instantiate: false }); ...

php - How to fetch forms data submitted in a wordpress plugin file? -

i want submit form contains textarea wordpress plugin. don't know how. want plugin fetch $_post variable after submission of form create it. other idea setting fields. having setting fields save data in accessing them via plugin. in all, want able access setting form, input , textarea , other form elements values through wordpress plugin. know question sounds novice, couldn't find search result regarding question. i create function in plugin , add init action hook . great time intercept $_post data , wish. function intercept_post_data() { // things $_post array } add_action( 'init', 'intercept_post_data' ); however, have option post directly plugin changing form's action point plugin file handles form processing. (i recommend first option).

Find phrases from one text file in another text file with python -

i have 1 file list of phrases, 1 phrase on each line. other file not delimitated in way, it's 1 huge text file of words. want search phrases in second file , if found, print phrase. code have far. f = open("phrase.txt", "r") g = open("text.txt", "r") line in f: search=line.lower() word in g: if search in word: print(search) this not printing me, though. edit: changed code this: f = open('phrase.txt').readlines() f = [f.strip('\n').lower() f in f] g = open('text.txt').read() phrase in f: if phrase in g: print (phrase) now phrases match. of phrases have dashes (-) , more letters after them , not picked program if phrase before dash present in text.txt. way change this? if want search every phrase in file, have nest loops, currently, searching last phrase phrases = open("phrase.txt").readlines() phrase in phrases: search= phrase.lower() words = ope...

com - Passing string by ref to activex component in C# -

i'm trying activex api function pattern function(ref string returnvalue) in c#. api function modifies string. string returnvalue = string.empty; api.func(ref returnvalue); // disp_e_typemismatch ok, maybe that's because strings immutable. trying stringbuilder per this : stringbuilder returnvalue = new stringbuilder(128); api.func(returnvalue); this causes compile-time error type mismatch. how call function? i don't know if need marshal c# string bstr, , if so, don't know how pass ref api function. if func should change returnvalue , think code should changed this: string returnvalue = string.empty; api.func(ref returnvalue); you should init returnvalue before pass ref . upd: did try call this?: api.func(ref marshal.stringtobstr(string value));

pmml - Spark JPMML import Issue -

am trying import pmml model file, generated in r spark context , use predict scores. code used in spark. javardd<string> scoredata = data.map(new function<string, string>() { @override public string call(string line) throws exception { string[] row = line.split(","); pmml pmml; evaluator evaluator; filesystem fs = filesystem.get(new configuration()); fsdatainputstream instr = fs.open(new path("path_to_pmml_file")); source transformedsource = importfilter.apply(new inputsource(instr)); pmml = jaxbutil.unmarshalpmml(transformedsource); system.out.println(pmml.getmodels().get(0).getmodelname()); modelevaluatorfactory modelevaluatorfactory = modelevaluatorfactory.newinstance(); modelevaluator<?> modelevaluator = modelevaluatorfactory.newmodelmanager(pmml); system.out.println(modelevaluator.getsummary()); evaluator = (evaluator) modelevaluator;...

bulkinsert - For SQL Server 2014 - text using "bulk insert" -

sql server 2014: possible import .text file date in dd/mm/yyyy format, using bulk insert ? i'm getting error: msg 4864, level 16, state 1, line 56 bulk load data conversion error (type mismatch or invalid character specified codepage) row 1, column 14 (invoice_date). invoice_date of smalldatetime datatype. change default session date format prior executing bulk insert following t-sql statement: set dateformat dmy remember revert original session setting avoid misinterpretation of ambiguous date formats. ideally, change field format yyyymmdd work correctly regardless of dateformat setting.

go - Golang: declaring maps and slices with iota values -

i have go code: package main import "fmt" type basegroup int const ( foogroup basegroup = iota + 1 bargroup ) var groups = [...]string{ foogroup: "foo", bargroup: "bar", } var xgroups = map[basegroup]string{ foogroup: "foo", bargroup: "bar", } func main() { fmt.println("groups") k, v := range groups { fmt.println(k, v) } fmt.println("xgroups") k, v := range xgroups { fmt.println(k, v) } } if run code get: groups 0 1 foo 2 bar xgroups 1 foo 2 bar i'm wondering why different outputs? you're expecting range behave same on both types in first case it's ranging on array , have empty index 0. value being stored in k current index; 0, 1, 2. in second example you're ranging on map , getting key stored in k contains 1 , 2. you might wondering how happening? it's because this; var groups = [...]string{ fo...

ruby on rails - How to migrate from ActiveRecord's Serialize Array to Postgres Array datatype -

rails 4 supports postgres' array data type , , want start taking advantage of array types in postgres , how can migrate existing activerecord serialized array field new data type? serialize stores things inside database yaml documents in text column. yaml isn't easiest format work inside database straightforward approach to: add array column hold arrays. loop through each record in rails, let activerecord unserialize yaml, copy ruby arrays serialize column real array column 1 . remove serialize declaration model. drop old column serialize used. rename column 1 . set newly renamed column not null if desired. you parse yaml inside database using regex , string functions depend on sorts of things you're storing in yaml.

javascript - Create drop-down list from user input -

let me simplify question way. there 2 tables in document. 1st table requires input user. max length 8 characters. 2nd table readonly. contains selection 3 options. want this: user input in (1st table) cell1 = (2nd table) option1 in select element user input in (1st table) cell2 = (2nd table) option2 in select element user input in (1st table) cell3 = (2nd table) option3 in select element can't achieve this. errors? <!doctype html> <html> <head> <title>thermo analysis</title> <style type="text/css"> body {font-family: arial, verdana, helvetica,sans-serif; margin-left: 50px; max-width: 600px;} th {font-size: 14px; border: 1px; border-style: solid; border-colapse: colapse; border-spacing: 0px;} td {font-size: 14px; border: 1px; border-style: solid; margin: 0px; border-colapse: colapse; border-spacing: 0px;} input:focus {background-color: rgb(255,255,150);} </style> </head> <body> <table id=...

synchronization - Where is normal memory mappings? -

in description of qnx neutrino rtos , blackberry10 os ( here ) pthread_mutex_init() , said following: you should allocate synchronization objects in normal memory mappings. on processors (e.g. ppc ones), atomic operations such calls pthread_mutex_lock() cause fault if control structure allocated in uncached memory. i have defined mutex out of function , i'm getting 'memory fault' error while trying pthread_mutex_init() . so, i'm wondering "normal memory mappings" , "uncached memory" terms mean? should define mutex lock? considering using arm architecture. arm architecture supports 3 types of memory- 1 - ordered - non-cacheable 2 - device - non-cacheable ( memory mapped peripheral) 3 - normal - cacheable as per description, supposed allocate muxtex structure normal memory. normal program execution normal memory used. problem looks unrelated this. please check memory allocation function return value. for detaile...

multithreading - One Client just listening after a few messages: Client Server Chat with ArrayList sockets outputstreamwriter -

i have got problem broadcast method. did chat server , clients. each client runs 1 thread , has own socket output stream @ beginning works fine after few messages 1 client can send while other receiving messages..?! don't know why idea? @ beginning both can send , receive.. can't close outputstream because nullpointerexception maybe mistake? thankful every help! server: public static void broadcastjson(jsonobject jsonobject, arraylist<socket> socketlist)throws ioexception{ outputstreamwriter out = null; for(int i=0; i<socketlist.size(); i++){ out=new outputstreamwriter(socketlist.get(i).getoutputstream(), "utf-8"); out.write(jsonobject.tostring() + "\n"); out.flush(); } } client: public jsonobject receivejson()throws ioexception{ bufferedreader in = new bufferedreader(new inputstreamreader(client.socket.getinputstream(), "utf-8")); string obje = i...

r - ContrOptim Function- Error in Argument -

i'm trying replicate excel solver in r- constraint optimization problem i'm trying minimize cost per action total spend/ total actions equals below function few constraints. cpa function: (a+b+c+d)/((consta+(baln(a)))+ (constb+(bbln(b)))+(constc+(bcln(c)))+(constd+(bdln(d))) where unknown variables a , b , c , d , const* stands constant regressions , b* stand coefficient regression (so values have). here simplified filled in function i'm trying minimize: (a+b+c+d)/ (((69.31*ln(a))+(14.885*ln(b))+(21.089*ln(c))+(9.934*ln(d))-(852.93)) constraints: a+b+c+d>=0 a+b+c+d<=130000(total spend) a<=119000 (maxa) a>=272.56(mina) b<=11000(maxb) b>=2.04(minb) c<=2900(maxc) c>=408.16(minc) d<=136800(maxd) d>=55.02(mind) i'm doing using constraints optimization function. code below: g<-function(a,b,c,d) { (a+b+c+d)/((consta+(balog(a)))+ (constb+(bblog(b)))+ (constc+(bclog(c)))+ (constd+(bdlog(d)))) } gb<-function(a) g...

google cloud messaging - Make android device acting as a gcm servers -

one instance of application should communicate instance on different device. i'd not have own backend server. i'd turn android device server in order send message device. i'd use topics. are there limits (quotas per application) of: number of such servers @ given point of time number of topics number of active client devices connected gcm the gcm designed have 1 backend server. kind of strange behavior may observe having plenty devices acting server. using same key there no limit on number of servers (as long send via http) or devices. however, problem in approach you'll need put project's api key client app easy adversary find out decompiling binary. using api key, able spam users. it's huge security hole.

reporting services - ssrs-Pass Report parameter to DrillDown -

im building report, make group in ssrs (not in dataset), means group created in ssrs, now, how can pass values of group drill down? p.s - pseudocode: dataset (build in sql server 2008): alter.... select ...concat(x) myx ,documentid ,name ,age group documentid in ssrs group myx, myx - has values of 'x' grouped documentid. want pass values of myx drilldown. how can it? thanks i assume have parameter on drilldown report pass value to. on action sends drilldown set parameter's value expression be: =fields!myx.value

jquery - Seperate background image with repeat x -

i using bootstrap rating website http://plugins.krajee.com/star-rating . wondering if possible each of stars 1 one, , make animation when page loads. if example have 3 stars rating, when load page first star animate big smaller, second , third etc. in plugin background-image repeat-x used stars. question if possible percentage of background-image jquery maybe or css , make specific styling this. thanks in advance not really, looks of it. plugin's not set in 'hack-in-some-animation' friendly way. i've given fair go, it's bit choppy. starter 10 though, , can polish desired. check out fiddle here . var delayperstar = 500; var div = $('#rating').parent('div'); var siblingdiv = $('#rating').siblings('div'); var content = div.data('content'); div.attr('data-content', ''); var i=0; var fn = function(){ var cb = function(){ div.attr('data-content', div.attr('data-content')+co...

ms access - How to Intercept built-in Find Procedure? -

in access project have custom find procedure. now want eradicate built-in find procedure user doesn't try use that. so have 2 tasks acccomplish: intercept ctrl+f hotkey remove find button ribbon. on main form have key preview enabled, , know how detect keypresses , i'm not sure how detect ctrl key. now do? you can check if shift = 2 . shift value 1 if shift pressed, 2 if ctrl pressed, 4 if alt pressed, sum of values if 2 or 3 of buttons pressed or 0 if none of them pressed. if statement should this: if keycode = vbkeyf , shift = 2 keycode = 0 end if

import - best way to register all classes in a folder in python -

i working summer intern @ large company, me , intern has been tasked writing background service scratch in python(with given specifications). can't python expert try write code possible , follow practice. describe service in easy way receives messages buss (amqp atm) , matches them against patterns , preform actions depending on pattern, configurable json file. to down point, service suppose general , therefore developer should able add different inputs , outputs classes. structure have right now. service.py input __init__.py (includes .py files in __all__ variable) base.py amqp.py service.py from input import * import input #use input.base.sources input\base.py sources = {} def register_input(cls): sources[cls.input_name] = cls return cls class inputbase(object): action(self, params): ... input\amqp.py @register_input class amqpinterface(inputbase): input_name = "amqp" action(self, params): ... this works, doesn't nic...

C# Typed Dataset corrupts CommandText -

i need perform maintenance on old c# windows forms application (.net 3.5) using typed datasets. purpuse i'm bound using vs 2010. the issue follows, when 'touch' typed dataset, or after rebuilds, commandtext within datasets designer file getting corrupted. automatically cr+lf , whitespaces being placed, e.g. this._adapter.insertcommand.commandtext = "\r\n dbo.nameofastoredprocedure\r\n "; when performing search/replace rid of unwanted changes, works short while , issue reoccurs. any ideas on causing issue , how fix this? why think corrupted? should have no effect on behavior. anyways, output expect when embed text in xml. eg: <commandtext> dbo.nameofastoredprocedure </commandtext> if pedantic whitespace (that should ignored), following: <commandtext>dbo.nameofastoredprocedure</commandtext>

PHP + Mysql complicated SQL SELECT query -

i thought how make complicated (as think) select query table 3 kind of comments (first - positive comments, second - negative comments , third - neutral comments). using php select , diplay first negative comments, , right after negative comments diplay other type of comments. how diplay them 1 select query limit use separate pagination? example of table: id - unique id type - (value 1-positive, 2-negative, 3-neutral) text - value i thought first select * comments type='2' order id limit 0,100 while(){ ... } right after second select * commetns type!='2' order id limit 0,100 while(){ ... } but how use limit pagination if there 2 different select queries? use if statement in order clause change type 2 sort first:- select * comments order if(type = 2, 0, type) limit 1, 20 this give negative (type 2) comments first, followed other comments (whether positive or neutral). want add column sort consistency of display.

php - string not splitting using explode -

i trying split string below on <br> reason loop returns 1 giant string. swear im missing simple cant see it. thanks! if(file_exists("/home/pi/desktop/picontrol/status_log")) { $file = readfile("/home/pi/desktop/picontrol/status_log"); $arr= explode("<br>",$file); //$file=array_slice($file,count($file)-5); //$file=array_reverse($file); foreach($arr $f) { echo $f; echo "woo"; } fclose($file); } else { echo "no file found"; } contents of file: <br>light now: on 2015-06-01 03:32:42.902387<br>light now: off 2015-06-01 03:32:54.360173<br>light now: on 2015-06-01 03:33:07.781693<br>light now: off 2015-06-01 03:33:15.867386<br>light now: on 2015-06-01 03:34:42.683736<br>light now: off 2015-06-01 03:34:45.205557<br>light now: on 2015-06-01 03:36:18.037309<br>...

javascript - Angular - Controller with no HTML and broadcasted events -

i have weird situation. have controller want control when dialog opens. i'm using ngdialog in combination templates , directives. here dialogcontroller code: (function() { 'use strict'; angular.module('common').controller('dialogcontroller', dialogcontroller); dialogcontroller.$inject = ['$scope', 'ngdialog']; function dialogcontroller($scope, ngdialog) { $scope.$on('opendialog', open); function open(which) { ngdialog.open({ template: which, classname: 'newproductdialog' }); } } })(); this controller has no html associated - sole purpose open, close, etc ngdialog. here how try trigger dialog open ( vm.navigate called through ng-click) in homecontroller: function initnav() { /** * nav items array. * @type {{name: string, id: string, selected: boolean, icon: string}[]} */ ...

c++ - Why does this function change list value without pointer? -

if pass value function doesn't make copy of value if change within function doesn't change original unless instead pass address? stupid question, can't figure out why function changing value of list. void array_increment(int list[],int size) { (int i=0; i<size; i++) list[i] = list[i]+1; } int main() { int c[]={3,1,0,-5,1}; array_increment(c,5); (int = 0; < 5; ++) cout << c[i] << " "; cout << endl; } outputs 4 2 1 -4 2 there few issues @ play. plain arrays aren't copyable or assignable. function parameters such int a[] adjusted pointer int* a . array names can decay decay pointer first element that 2nd point means that void array_increment(int list[],int size) is really void array_increment(int* list,int size) and 3rd point means can pass array c first argument because can decay int* .

javascript - Disable only .(DOT) special charecter in input field -

i don't want allow user enter. (dot) in input field.. rest of required validation done already. function isnumberkey(evt) { var charcode = (evt.which) ? evt.which : event.keycode; if (charcode != 46 && charcode > 31 && (charcode < 48 || charcode > 57)) return false; return true; } <input type="text" class="form-control" name="contactnumber" maxlength="10" value="" id="contactnumber" title="enter number here" onkeypress="return isnumberkey(event)" required> $("#name").on("keypress", function(evt) { var keycode = evt.charcode || evt.keycode; if (keycode == 46) { return false; } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="name" /> working example here: jsfiddle ...

javascript - How can I save my custom width to a cookie? -

i'm working on width changer. use jquery this, i've problem. idea when user clicks button, width changes instantly. i'd save user's selection in cookie, don't know how can do. current jquery code: $(function() { $(".width-changer").on("click", function(e) { $(".wrapper").toggleclass("custom-width"); }); }); i use plugin cookie: <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.3.1/jquery.cookie.js"></script> it in index.html. the wrapper class global width. this solution worked me in i.explorer & firefox, chrome think should enable cookies : $(function() { if ($.cookie('custom_width')=='true') { //add true condition $(".wrapper").addclass("custom-width"); }; $(".width-changer").on("click", function(e) { $(".wrapper").toggleclass("custom-width"); ...

java - How to achieve separation of concerns without using any framework but Tomcat + Servlets? -

i have code works fine. important parts follows: my model class: package biz.tugay.sakila.model; /* user: koray@tugay.biz date: 25/06/15 time: 12:48 */ public class actor { private long id; private string firstname; private string lastname; // getters, setters... } my dao class: package biz.tugay.sakila.dao; /* user: koray@tugay.biz date: 25/06/15 time: 12:12 */ import biz.tugay.sakila.model.actor; import java.sql.*; import java.util.arraylist; import java.util.list; public class actordao { protected static final connection connection = dbconnector.getconnection(); public list<actor> getallactors() throws sqlexception { list<actor> allactors = new arraylist<actor>(); statement stmt = connection.createstatement(); string sql = "select * actor"; resultset rs = stmt.executequery(sql); while (rs.next()) { actor actor = new actor(); actor.setfirstname...

php - What are some reasons that I might be getting "0 rows affected" on this query? -

backstory: i'm trying create wordpress theme , working on setup part of theme. i've installed wordpress , mysql database on running named testdb . have file setup.php looks <?php error_reporting(-1); ini_set('display_errors', 'on'); $con = mysqli_connect('localhost', 'testadmin', 'something'); if ($con->connect_error) { die("connection failed: " . $conn->connect_error); } echo "<p>connected localhost successfully</p>"; if ($con->select_db("testdb")) { echo ("<p>connected database</p>"); } else { die($con->error); } if ($con->query("create table mems (id mediumint not null auto_increment primary key, name varchar (50), title varchar (20), bio varchar (500), sord int, picfn varchar (100))") === true) { echo("<p>created table team members.</p>"); } else { die($con->error);; } $con->close()...

java - Running android studio app on physical device "ERROR IN NETWORK CONNECTION" -

whenever try login, register, change password or reset password app says "error in network connection". i using strong internet connection, please advise have tried on wi-fi , 4g, still says same error. using wamp server connect phpmyadmin database. please , advise. login. java file public class login extends activity { button btnlogin; button btnregister; button passreset; edittext inputemail; edittext inputpassword; private textview loginerrormsg; /** * called when activity first created. */ private static string key_success = "success"; private static string key_uid = "uid"; private static string key_username = "uname"; private static string key_firstname = "fname"; private static string key_lastname = "lname"; private static string key_email = "email"; private static string key_created_at = "created_at"; @override pub...

c# - ASP.Net WebAPI JSON response does not serialize entity relationships -

i'm developing asp.net mvc5 application using web api 5, odata , entity framework 6. i've created repositories , used entity framework power tools generate entity models. i've turned off lazy loading , proxy generation on dbcontext. below how i'm writing linq queries in repository classes return entities relationships; return repository .query(i => i.istransaction == true) .include(i => i.subinventory) .include(c => c.contact) .orderby(q => q .orderby(i => i.itemfullcode)) .select(); further in odataconfig file i've set; config.formatters.jsonformatter.serializersettings.referenceloophandling = newtonsoft.json.referenceloophandling.ignore; config.formatters.jsonformatter.serializersettings.preservereferenceshandling = newtonsoft.json.preservereferenceshandling.objects; the issue i'm struggling ...