Posts

Showing posts from April, 2013

php - Error in SQL syntax when I try a query -

i've big (and stupid) problem simple sql insert query (mysqli), i've used format without errors, didn't work.. please me find problem.. //get admin form details $a_user = $_post["a_user"]; $a_pass = $_post["a_pass"]; $a_pin = $_post["a_pin"]; if($a_user == "$admin_username" && $a_pass == "$admin_password" && $a_pin == "$admin_pin"): $keygen = md5(microtime().rand()); $mysqli->query("insert keys (keygen) values ('$keygen')") or die(mysqli_error($mysqli)); $mysqli->close; else: header("location: ?page=admin&error=1"); endif; here error: error: have error in sql syntax; check manual corresponds mysql server version right syntax use near 'keys (keygen) values ('85faa7f618e433819d7e5ca57076377c')' @ line 1 keys mysql reserved word http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html either wrap in bac...

ios - CBManager state always unknown -

i trying check if bluetooth of device on or off. code i've written far cbcentralmanager *cbmanager = [[cbcentralmanager alloc] initwithdelegate:self queue:nil options: [nsdictionary dictionarywithobject:[nsnumber numberwithint:0] forkey:cbcentralmanageroptionshowpoweralertkey]]; [cbmanager scanforperipheralswithservices:nil options: [nsdictionary dictionarywithobject:[nsnumber numberwithint:0] forkey:cbcentralmanageroptionshowpoweralertkey]]; if (cbmanager.state==cbcentralmanagerstatepoweredoff) { //do stuff } - (void)centralmanagerdidupdatestate:(cbcentralmanager *)central { nsstring *statestring = nil; s...

xcode - How to let the controller handle a gesture added in the view? iOS -

i got card draw custom view. want add swipe gesture every card flip , being chosen. since every card view needs gesture, choose add gesture in method initwithframe: of view. however,i want leave controller handle gesture when recognized because choosing card method in controller. here code: [self addgesturerecognizer:[[uiswipegesturerecognizer alloc] initwithtarget:self action:@selector(swipe:)]]; actually need target my controller , want call method named swipe in controller. target self leave handling of gesture view itself. maybe can't controller replace target.can tell correct way solve problem? your view should not know controller is. (this increase coupling , decrease cohesion, bad.) a common solution problem view declare delegate protocol. view controller can set view's delegate. view's swipe: method call delegate method. for example code, see this question .

mysql - sql update statement for two tables -

i using mysql 5.5 , have 2 tables, inventory_items , menu_items. both have bin_number string , location_id integer. menu_items invetory_item_id | location_id | bin_number inventory_items id | location_id | bin_number i'd update menu_items inventory_item_id id of inventory_items table equal on bin_number , location_id. go through each this: update menu_items set inventory_item_id=(select id inventory_items bin_number='7060' , location_id=37) bin_number='7060' , location_id=37; is there way update menu_items bin_number , location_id same between menu_items , inventory_items? thx you can use join in update : update menu_items mi join inventory_items ii on mi.bin_number=ii.bin_number , mi.location_id=ii.location_id set mi.inventory_item_id = ii.id

java - I am getting Null Pointer Exception in GridView Android -

i getting null pointer exception in fragment using gridview . code is public class homefragment extends fragment { gridview grid; string[] web = { "bata", "service", "puma", "hush" }; int[] imageid = { r.drawable.shoesmall, r.drawable.shoe1, r.drawable.shoe3, r.drawable.shoe4 }; public homefragment(){} @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view rootview = inflater.inflate(r.layout.fragment_home, container, false); // viewgroup root = (viewgroup) inflater.inflate(r.layout.fragment_home, container); customgrid adapter = new customgrid(getactivity().getapplicationcontext(), web, imageid); grid = (gridview) getview().findviewbyid(r.id.gridview); grid.setadapter(adapter); grid.setonitemclicklistener(new adapterview.onitemclicklistener() { @override public...

coldfusion - Why does HttpHeader X-Original-URL not exist on some pages? -

my site using url rewrite make seo friendly urls. makes self-posting form same page little tricky. however in coldfusion form's action attribute: <form name="formsortby" method="post" enctype="multipart/form-data" action="#structfind(gethttprequestdata().headers, 'x-original-url')#"> </form> the important part here #structfind(gethttprequestdata().headers, 'x-original-url')# gets me url of page. however x-original-url key doesn't exist on pages error coldfusion saying: cannot find x-original-url key in structure. specified key, x-original-url, not exist in structure. this happening when click go homepage of section in. x-original-url exists if go http://www.sitename.com/products/gaming won't exist if go http://www.sitename.com/products is there anyway around or make work need to? sounds there issue between rewrite rules , cf. but, there easy fix - can form post not specif...

ruby - getting started with rails guide: how do you create the files -

i using getting started rails guide , stuck @ point. creating new html.erb file within app/views/articles. how create new file. u in command prompt or script editor? any way really. can in command prompt if more comfortable or can create in script editor.

java - Adding an SSL Certificate to JRE in order to access HTTPS sites -

context: so i'm trying access https site java code not able due ssl handshake issues between localhost , server. seems reason issues url trying access has no valid certificate issued authorized ca. so after research, i'm going try import offending ssl certificates jre, way can validated. question: what mac equivalent of command using keytool importing certificates: keytool -import -alias mycertificate -keystore ..\lib\security\cacerts -file c:\mycert.cer reference: http://www.jyothis.co.in/2011/11/12/javax-net-ssl-sslhandshakeexception/ any or assistance appreciated, thank you you should able import server (self-signed?) ssl certificate onto localhost using command specified. more complete, can try $java_home/bin/keytool -import -alias mycertificate -keystore path_to_keystore -file certificate_file where $java_home on mac /system/library/frameworks/javavm.framework/home/ path_to_key_sotre $java_home/lib/security/cacerts certificate_file ...

php - mysql Join produces an error -

i have code, , cant find error. public function show(){ $x=null; $owner = $_session['uid']; $sql = "select kunde.name n1, rechnung.rechnr rnr `rechnung`as rr inner join `kunde` on rr.kid = kunde.kid owner = ? "; $stmt = $this->mysqli->prepare($sql); $stmt->bind_param("i", $owner); $stmt->execute(); $result = $stmt->get_result(); while ($obj = $result->fetch_object()) { $x[] = $obj; } return $x; } without join result join got these message don t know why: call member function bind_param() on non-object thx reading. you've got rewrite sql statement , use alias name field rechnr too. instead of rechnung.rechnr you've got use rr.rechnr instead: $sql = "select kunde.name n1, rr.rechnr rnr `rechnung` rr inner join `kunde` on rr.kid = kunde.kid owner = ? "; because didn't use alias name, preparing of statement did fail.

mysql - SQL: How to sum up count for many decades? -

i learning sql queries , have question below "a decade sequence of ten consecutive years, e.g. 1982, 1983... 1991. each decade, compute total number of publications in dblp in decade." i have come temporary table count of each year select count(id) cnt, year publication group year so next step sum cnt year decade. after research, found use between operator. however, still need specify range 1 one. there better way this? (the year range 1900 - 2015) thank much. after research, find group , left() can lot. select left(year, 3) decade , sum(cnt) (select count(id) cnt, year publication group year) t1 group left(year, 3) ; the result decade cnt null 6 193 55 194 139 195 1066 196 8066 197 28449 198 93203 199 359628 200 1249767 201 947365 do please give suggestions if there better ways it. thank you.

python - Configuring nose tests for different test targets -

i have set of nose tests use test piece of hardware. example, test below concerned testing alarm each mode on system: import target modes = ("start","stop","restart","stage1","stage2") max_alarm_time = 10 # generate tests testing each mode def test_generator(): m in modes: yield check_alarm, m, max_alarm_time # test alarm mode def check_alarm(m, max_alarm_time): target.set_mode(m) assert target.alarm() < max_alarm_time most of tests have appearance testing particular function modes on system. i wish use same set of tests test new piece of hardware has 2 modes: modes = ("start","stop","restart","stage1","stage2","stage3","stage4") of course, want tests still work old hardware also. when running automated test need hardcode, test environment, hardware connected to. i believe best way create paramaters.py module follows: def...

Spring messageSource only works as xml (not as Spring-Java-Config) -

i have working spring mvc project , want migrate application context configuration xml java-config. works fine except messagesource bean. following works fine : config class gets imported config class: package gmm; import org.springframework.context.annotation.configuration; import org.springframework.context.annotation.importresource; @configuration @importresource({"classpath:applicationcontext.xml"}) public class i18nconfiguration { } referenced applicationcontext.xml file: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemalocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-...

xbee wifi tcp socket keep alive -

i new digi's product. have arduino yun runs tcp socket server , listens connections. have xbee wifi s6b module , want use connect server. use xctu program setup network connection xbee. point fine. then, realize that, xbee never connects server automatically, connects when send terminal auto close connection right away. can confirm nature of xbee , there anyway solve issue (probably there setting in xctu dont know 1 is)? also, know if there way program xbee cause want xbee set digital output pin high or low under circumstances. need know way accomplish this. thanks.

java - How to set Image fix XY in ImageView without stratch Using Universal Image Loader? -

when uisng image set image stretch, image size large why stretch, when uisng fit xy stretch,how solve issue i think image stretched because imageview , image have different aspect ratio. fitxy means use aspect ration of imageview, image stretched due has different aspect ratio. you can solve problem giving same aspect ratio imageview image. or, can use centercrop instead of fitxy, won't stretch image show part of image if has different aspect ratio imageview.

android - EditText on the bottom of Relative Layout overlays views under it -

Image
linearlayout edittext on bottom overlays content of scrollview, filled programmatically. how avoid please? have simplified xml in vain in first version of message. have added full code now i'd keep edittext height expandable. <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/backnormal" android:orientation="vertical" > <include layout="@layout/adview" android:layout_alignparenttop="true" /> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_...

apache - Installing Laravel while there are 2 php packages installed -

i have install laravel 4 on old server has ubuntu 10.04 server installed lamp (php v5.3.10). have ran following commands; sudo add-apt-repository ppa:ondrej/php5-oldstable sudo apt-get update sudo apt-get upgrade sudo apt-get install php5 sudo apt-get install php5-mysql php5-json php5-mcrypt curl -ss https://getcomposer.org/installer | php5 sudo mv composer.phar /usr/local/bin/composer composer create-project laravel/laravel --prefer-dist problem 1 laravel/framework v4.2.9 requires php >=5.4.0 -> no matching package found. i have uninstalled , reinstalled different commands no avail. know laravel installer referring lamp's installed php package. checking versions; php -v php 5.3.10 suhosin-patch (cli) (built: mar 5 2012 18:10:34) copyright (c) 1997-2012 php group zend engine v2.3.0, copyright (c) 1998-2012 zend technologies php5 -v php 5.4.33-1+deb.sury.org~lucid+1 (cli) (built: sep 19 2014 11:21:37) copyright (c) 1997-2014 php group zend engine v2.4.0, copyright...

NetLogo: Subtract One Patch-set From Another -

im trying create patch-set without having define each patch in list individually. however, in order need subtract 1 patch-set another. in model, patches own o2. have few selected patches in value o2 should not change. create patch-set patches pxcor = max-pxcor exclude these patches should hold o2 constant. have tried subtracting patch-sets, got error message saying -expected input number, got patch agentset instead. have tried setting patch-set lists, , using remove command modify list. however, presents problem when ask list perform something, error ask expected agent or agentset, got list instead . below relevant code try build patch-set: set ns1 (patch-set patch -8 -5 6 patch -8 -5 -5 patch -8 6 6 patch -8 6 -5 patch 8 -5 6 patch 8 -5 -5 patch 8 6 6 patch 8 6 -5) set ns2 (patch-set patch -8 0 6 patch -8 0 -5 patch 8 0 6 patch 8 0 -5 ) set ns3 (patch-set patch -4 -5 6 patch -4 -5 -5 patch 4 -5 6 patch 4 -5 -5 patch -4 6 6 patch -4 6 -5 patch 4 6 6 patch 4 6 -5) ...

sql server - Tally database synchronization with c# Application -

i want make application sync tally sales order , sales invoice tally our sql database. testing purpose using tally erp 9 educational version . i have created sales orders in tally , need order details tally using tally odbc sql query uptil per research, getting few sales order details voucher number , order date ,'voucher type'.. etc. tally odbc table companyvoucher . few details came empty, although related data exist in tally order. reference , party name ... etc. also, unable find tally odbc table few other sales order related data item name, item number , item quantity, rate , order total, order no etc. can suggest sql query or tally odbc table can find these order related data. not sure, if can not access these details due educational version , , limitations on educational version on access of these details. so please suggest me on this. synchronisation process of replicating data between 2 or more computers using tally.erp 9 in client – se...

Return value of a promise to a function in AngularJS -

Image
i have problem outputting values of promise function. $scope.getteacher = function(teacherabr) { var promise = dataservice.getteacher(teacherabr); var testje = promise.then(function(payload) { return payload; }); return testje; // outputs d object, not direct payload values }; the output of controller function this: however, when i'm doing testje.$$state returns undefined . how can output value object? can't output payload variable in new $scope, because data dynamic. here simplified version of on plunker . you should change way think things when work asynchronous code. no longer return values, instead use promise or callback patterns invoke code when data becomes available. in case factory can be: .factory('dataservice', function($http, $log, $q) { return { getteacher: function(teacher) { // jsonp request ('/teacher/' + teacher) return $http.get('http://echo.jsontest.com/key/valu...

c# - Invalid operation exception in context.SaveChanges() with oracle entity framwork 5 -

Image
i use oracle ef 5.0 provider. oracle 11g database. here database schema: table has id primary key. each table in database there trigger, fires on insert new record , ef primary key after insert sequence. sequences created each table. in edmx file each id column has storegeneratedpattern="identity" attribute set. my code is: using (var context = new entities()) { var title = new title { title_number = 4000001, is_draft = "n", registry_date = datetime.now }; var titlename = new title_name { name = "title name" }; title.title_name.add(titlename); context.set<title>().add(title); context.savechanges(); } when context.savechanges() executed, there exception thrown: the changes database committed successfully, error occurred while updating object context. objectcontext might in inconsistent state. inner exception message: acceptchanges cannot continue because object...

asp.net mvc 4 - A specified Include path is not valid. The EntityType '' does not declare a navigation property with the name '' -

i wonder if help. above error when call .include() . breaks when include tblmemberships . this.dbcontext.configuration.lazyloadingenabled = false; list<tblcustomerinfo> customers = this.dbcontext.tblcustomerinfoes.include("tblusers").include("tblmemberships").tolist(); the reason because navigation property between tblcustomerinfo , tblmemberships not exist. tblusers link between other 2 tables. customer -- 1:* -- user -- 1:* -- membership (sorry, can't include image reputataion < 10). my questions are: what need in order have tblmemberships included? is recommended way of retrieve data or should break 2 queries? or design totally rubbish? i using ef5, asp .net mvc 4 kindly advise. thank you. when write code this: db.parenttable .include("childtable") .include("childofchildtable"); you saying include entries childtable keyed parenttable , include entries childofchildtable keyed paren...

java - Lucene 4.10 Date Range Query Api -

i want build range query date field programmatically in lucene 4.10, didn't find anyway that. pseudocode be: new daterangequery(datelowerbound, dateupperbound); is idea use org.apache.lucene.document.datetool class transform , use numericrangequery ? i'd pick 1 of 2 possibilities: 1 - use datetools obtain string representation indexing: string indexabledatestring = datetools.datetostring(thedate, datetools.resolution.minute); doc.add(new stringfield("importantdate", indexabledatestring, field.store.yes)); ... topdocs results = indexsearcher.search(new termrangequery( "importantdate", new bytesref(datetools.datetostring(lowdate, datetools.resolution.minute)), new bytesref(datetools.datetostring(highdate, datetools.resolution.minute)), true, false )); ... field datefield = resultdocument.getfield("importantdate") date retrieveddate = datetools.stringtodate(datefield.stringvalue()); 2 - skip date tools, , i...

c# - Saving Bitmap to File - Xamarin, Monodroid -

i trying save bitmap image directory (gallery) inside phone. app being developed in xamarin code c#. i cant seem figure out how make directory, , save bitmap. suggestions? public void createbitmap(view view){ view.drawingcacheenabled = true; view.builddrawingcache (true); bitmap m_bitmap = view.getdrawingcache(true); string storagepath = android.os.environment.externalstoragedirectory.absolutepath; java.io.file storagedirectory = new java.io.file(storagepath); //storagedirectory.mkdirs (); //save bitmap //memorystream stream = new memorystream (); //m_bitmap.compress (bitmap.compressformat.png, 100, stream); //stream.close(); try{ string filepath = storagedirectory.tostring() + "appname.png"; fileoutputstream fos = new fileoutputstream (filepath); bufferedoutputstream bos = new bufferedoutputstream(fos); m_bitmap.compress (bitmap.compressformat.png, 100, bos); bos.flush(); ...

javascript - Using Fade Scroll jQuery-effect on 2-column floated gallery -

http://jsfiddle.net/mqhes/23/so found neat jquery, fade scroll code here: change opacity based on elements current offset . noticed works in 1 column. if 1 has 2 columns floated items, items in left column effected function (see jsfiddle). have solution this? http://jsfiddle.net/mqhes/23/ html: <img src="http://lorempixel.com/640/480/food/1" /> <img src="http://lorempixel.com/640/480/food/2" /> <img src="http://lorempixel.com/640/480/food/3" /> <img src="http://lorempixel.com/640/480/food/4" /> <img src="http://lorempixel.com/640/480/food/5" /> <img src="http://lorempixel.com/640/480/food/6" /> <img src="http://lorempixel.com/640/480/food/7" /> <img src="http://lorempixel.com/640/480/food/8" /> <img src="http://lorempixel.com/640/480/food/9" /> <img src="http://lorempixel.com/640/480/food/10" /> css: img {width: a...

javascript - Get specific info out of json -

this question has answer here: php values json encode 2 answers how can "coords" data out of json object in jquery? , each object own coords? example of returned json php shown in console: [ { "id":"7", "name":"example", "address":"example adress", "coords":"96.0,17.0" }, { same here etc. } ] edit: problem can't access json object in way recommended. if type object[0] "[" if type object[1] "{" other characters in sequence '"', "i", "d", etc. i console log in sucessfull ajax call so: .done(function(data) { console.log(data[2]); }); and php returns data so: echo json_encode($mydata); your data coming string, need 1 of 2 things json format: in .ajax call, set ...

junit - I run a unit test with Arquillian, but the console shows me an error -

i run test: @runwith(arquillian.class) public class greetertest { @inject greeter greeter; @deployment public static javaarchive createdeployment() { javaarchive jar = shrinkwrap.create(javaarchive.class) .addclass(greeter.class) .addasmanifestresource(emptyasset.instance, "beans.xml"); system.out.println(jar.tostring(true)); return jar; } @test public void should_create_greeting() { assert.assertequals("hello, earthling!", greeter.creategreeting("earthling")); greeter.greet(system.out, "earthling"); } } package com.teste; import java.io.printstream; public class greeter { public void greet(printstream to, string name) { to.println(creategreeting(name)); } public string creategreeting(string name) { return "hello, " + name + "!"; } } my pom.xml http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com teste 0.0.1-sn...

classpath - Not able to add the Spring jars into EAR under Tomcat Server. note :i added those in WEBINF/lib -

i have added jars webinf/lib not added ear, when add ear tomcat server seeing 1 jar, webinf/lib: spring jars, tomcat v7.0 ->myspringexampleear ->only 1 jar so getting below exception java.lang.classnotfoundexception: org.springframework.web.context.contextloaderlistner in eclipse-jee-kepler-sr2-win32. i have tried using deplyoment assembly.still getting same exception currrently not able attach image. can please me resolve issue? there solution other maven deploy this? please read .war vs .ear file tomcat not handle .ear files, .war files. if using maven create web app intended deployed tomcat, not use maven ear plugin.

How to read ToggleSwitch value in WinJS -

i want read if 1 value selected or (1 or 0, true or false) in winjs using toggleswitch: code html: <div id="toggleswitchdocformat" class="toggleswitchdocformat" data-win-control="winjs.ui.toggleswitch" data-win-options="{labelon:'guardar documento como: tiff', labeloff:'guardar documento como: pdf', checked:true}"></div> code javascript: app.onloaded = function () { getdomelements(); toggleswitchdocformat = document.getelementbyid("toggleswitchdocformat").wincontrol; console.log("the value of toggleswitch: " + toggleswitchdocformat.checked); } message: el código de biblioteca de javascript está punto de detectar la excepción. en línea 119, columna 9 en ms-appx://.../js/default.js 0x800a138f - error en tiempo de ejecución de javascript: no se puede obtener la propiedad 'tostring' de referencia nula o sin definir si hay un con...

sql - Import Selected Columns to Excel from Access Table using VBA -

i trying import selected data access table. table has 4 columns , want want columns 2 , 3. in excel , want them listed in order: column 3, column 2 (reverse how in access). additionally want select rows (from access table) based on date referenced in excel spread sheet (which refer rpdate in code). in access, "date" first column. need please. thanks. sub adoimportfromaccesstable() dim dbfullname string dim tablename string dim targetrange range dim rpdate range dbfullname = "c:\documents\database.mdb" tablename = "datatable" targetrange = range("c5") rpdate = range("b2").value dim cn adodb.connection, rs adodb.recordset, intcolindex integer set targetrange = targetrange.cells(1, 1) ' open database set cn = new adodb.connection cn.open "provider=microsoft.jet.oledb.4.0; data source=" & _ "c:\documents\database.mdb" & ";" set rs = new adodb.recordset rs ...

json - AngularJS routes and Ajax data on route change -

i failing understand angular way following... i have router configured, once route changed, , templateurl supplied make ajax call fetch json data. notice that, not want wait fetch template , use controller fetch json data because 2 serial http calls. want fetch json data in parallel fetching template. there known pattern this? correct me if wrong... now, understand should use resolver in call "data provider", fire http call json data. data available controller. this... app.config(['$routeprovider', 'data', function( routeprovider, dataprovider ) { routeprovider. when('/reports/:reportname', { templateurl: function( urldata ) { return "/some/url/" + urldata.reportname + "/content"; }, resolve: { reportdata: function() { return dataprovider.getdata(); } }, controller: 'reportroutingctrl' }); ...

How to Learn MFC C++ 2013 -

i used develop application android windows phone. i have grip on .net(c#) , php but, have develop application using mfc c++ on visual studio 2013 . i'm not c++ so, had read books like: * ivor horton's beginning visual c++ 2012 * professional c++, 3rd edition. but there isn't detailed guideline mfc classes , mfc application development life-cycle. so, wanna know there way learn mfc 2013 most of books on mfc old, @ least ones. first thing don't feel bad age of books out there , reason wouldn't find book vs2013 or vs2010. here best choices. programming windows charles petzold programming windows mfc jeff prosise no-1 not about mfc including 'nice read or reference' because mfc wrapper of windows apis makes easier understand (if want go in-depth) wraps.

asp.net mvc - Enabling MVCBuildViews based on Conditional Compilation Symbols -

is possible add conditional steps build check custom conditional compilation symbol , enable mvcbuildviews. i've found way based on build configuration <propertygroup condition=" '$(configuration)|$(platform)' == 'release|anycpu' "> <mvcbuildviews>true</mvcbuildviews> </propertygroup> but not sure how access compilation symbols instead. the plan add symbol under project settings > build > conditional compilation symbols controls mvcbuildviews assuming using c# need configure compiler use eg .test symbol when building views , need override configuration in web.config using following: <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" type="microsoft.csharp.csharpcodeprovider, system, version=2.0.3600.0, culture=neutral, publickeytoken=b77a5c561934e089" compileroptions="/d...

c - Bitwise multiplication to achieve result -

is there general set of rules achieve number multiplying known , unknown number. e.g. suppose x = 13 , z = 9 is there way find y such x * y = z => 13 * y = 9 i don't want utilize them mathematical integers, rather in terms of bits. so, want keep z int. obviously, there overflow in bit representation, i'm unsure how find z without brute forcing values in 32-bit machine. think y small number, negative. note: isn't or hw assignment, change x , y whatever, these examples. first, find modular multiplicative inverse of x (13) mod 2 32 . there several ways it, many people recommend extended euclidean algorithm, not simplest case. see hacker's delight chapter 10 (integer division constants) simpler algorithm. anyway, once know modular multiplicative inverse of 13 mod 2 32 0xc4ec4ec5 , multiply number z y . 0xc4ec4ec5 * 9 = 0xec4ec4ed so y = 0xec4ec4ed , , 0xec4ec4ed * 13 indeed 9. note if x even, has no inverse. if it's "a...

php - check associative array contains value -

array ( [0] => array ( [questionid] => 47 [surveyid] => 51 [userid] => 31 [question_title] => choose one? [question_type] => dropdown [response] => 1.android 2.windows 3.blackberry [required] => 0 [add_time] => 0 ) [1] => array ( [questionid] => 48 [surveyid] => 51 [userid] => 31 [question_title] => it? [question_type] => bigbox [response] => yes no [required] => 1 [add_time] => 0 ) [2] => array ( [questionid] => 129 [surveyid] => 51 [userid] => 31 [question_title] => select [question_type] => single [response] => dfg hbk ghck hk ...

How to improve Nginx, Rails, Passenger memory usage? -

Image
i have rails app set on digital ocean vps (1gb ram) trough cloud 66. problem being vps' memory runs full passenger processes. the output of passenger-status : # passenger-status version : 4.0.45 date : 2014-09-23 09:04:37 +0000 instance: 1762 ----------- general information ----------- max pool size : 2 processes : 2 requests in top-level queue : 0 ----------- application groups ----------- /var/deploy/cityspotters/web_head/current#default: app root: /var/deploy/cityspotters/web_head/current requests in queue: 0 * pid: 7675 sessions: 0 processed: 599 uptime: 39m 35s cpu: 1% memory : 151m last used: 1m 10s ago * pid: 7686 sessions: 0 processed: 477 uptime: 39m 34s cpu: 1% memory : 115m last used: 10s ago the max_pool_size seems configured correctly. the output of passenger-memory-stats : # passenger-memory-stats version: 4.0.45 date : 2014-09-23 09:10:41 +0000 ------------- apache processes ---------...

r - filtering data.frame based on row_number() -

update: dplyr has been updated since question asked , performs op wanted i´m trying second seventh line in data.frame using dplyr . i´m doing this: require(dplyr) df <- data.frame(id = 1:10, var = runif(10)) df <- df %>% filter(row_number() <= 7, row_number() >= 2) but throws error. error in rank(x, ties.method = "first") : argument "x" missing, no default i know make: df <- df %>% mutate(rn = row_number()) %>% filter(rn <= 7, rn >= 2) but understand why first try not working. the row_number() function not return row number of each element , can't used want: • ‘row_number’: equivalent ‘rank(ties.method = "first")’ you're not saying want row_number of. in case: df %>% filter(row_number(id) <= 7, row_number(id) >= 2) works because id sorted , row_number(id) 1:10 . don't know row_number() evaluates in context, when called second time dplyr has run out of things f...

vba - Excel - Copy contents of a many cells to multiple worksheets based on the name of the activesheet -

in sheet1 there is, among other things, list of students student id , grade level. in workbook there separate worksheet each student. worksheets named according student id. need copy grade level each student specific worksheet. must done students. for example column aa contains student id's, column ab contains grade levels each student. need copy student 12345, grade 4 worksheet 12345 cell f1. need move next student , same thing until have no more students. i have tried many methods, keep getting stuck. i've found examples close, miss 1 key thing make work i'm hoping able me started. feel should easy, hasn't proven be. edit: i looking @ trying figure out in steps. on simple test file tried: dim long = 1 sheets.count worksheets(i).activate workbooks("studata.xlsm").sheets(i).range("f1").value = workbooks("studata.xlsm").sheets("sheet1").cells(i, 2) next then tried: dim sheetname string sub activatesheet...

if statement - Dangers/side-effects of using PHP's ternary operator as a control structure -

a coworker uses php's ternary operator control structure, rather rhs of expression. 1 such example: list==''?list=val:list=list+','+val; (in example, statement called in loop add values string, ensuring comma separator doesn't appear if there's 1 item.) in essence, relies on expression evaluation work, , throws away expression result. aside fact it's hard on eyes, there reason avoid construct? it's syntactically legal; , executes correctly. i'm ternary operator wasn't designed used in manner, , wonder if there consequences doing so. it work fine, , don't see problem apart readability. if think it's hard on eyes, replace loop , line call implode function.

java - Testing a Spring WebListener -

i have class annotated @weblistener, extending servletcontextlistener class i'm testing relies on having executed. when test manually (i.e. running in tomcat) works, within junit test @weblistener class never executed. i'm assuming need add configuration execute, i'm not sure what. or need run manually in the test? edit: here's basics of class @weblistener public class mylistener implements servletcontextlistener { @override public void contextinitialized(servletcontextevent event) { // retrieve spring application context servletcontext servletcontext = event.getservletcontext(); springcontext = webapplicationcontextutils.getwebapplicationcontext(servletcontext); ... } ... } i've added test class: @before public void mockinit() { mockservletcontext mockcontext = new mockservletcontext(); new mylistener().contextinitialized(new servletcontextevent(mockcontext)); } but springcontext variable in contextinitialized null. ...

javascript - SimpleModal content only appears on page resize -

i'm using simplemodal pop modal on page. i'm hiding modal content on page load display:none. have simplemodal-container styled properly, , pops fine. content that's supposed in container, though, remains undisplayed; unless resize page. when resize it, content appears want to. how content appear without resizing page? here code looks like, in phtml file: <div id="div_for_simplemodal" style="display:none"></div> <script type="text/javascript"> *script generates content* </script> then, in separate js file: $("#div_for_simplemodal").modal({overlayclose:true}); and css: #simplemodal-container { height: 600px; width: 1200px; color: #bbb; background-color: #333; border: 4px solid #444; padding: 12px; } again, simplemodal-container appears fine, without content javascript supposed generate. content appears on page , in conta...

perl - XML::Compile maxOccurs="1" seems unbounded -

i having trouble understanding output perl schema complier, appears in cases maxoccurs indicator ignored. if try use complex element more once, first reference seems correct, subsequent references output arrays when maxoccurs indicator set "1". started playing xml schemas, understanding limited. i have following schema (sorry, tried cut down as possible): <?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/xmlschema"> <xs:element name="top"> <xs:complextype> <xs:sequence> <xs:element ref="foo" minoccurs="0" maxoccurs="1"/> <xs:element ref="bar" minoccurs="0" maxoccurs="1"/> </xs:sequence> </xs:complextype> </xs:element> <xs:element name="foo"> <xs:complextype> <xs:sequence> ...

Line breaks using dlmcell in Matlab - shows up in Notepad++ but not Notepad -

Image
i using function dlmcell in matlab output text. want text on new line each time append using dlmcell. when open written document in notepad++, each snippet of text on new line want it. however, opening in notepad comes windows, on same line. can tell me why is, , how fix it? i'm assuming you're using string \n declare new line in output. notepad++ sufficient, because interprets new line \n . windows editor need include carriage return also: substitute: \n \r\n this way not new line created, tells editor continue on next line. to illustrate mean, open output file notepad++ , activate view > show symbol > characters , see like: i wrote notepad++ , automatically adds cr (carriage return) , lf (line feed) @ end of every line. matlab doesn't if don't tell it. output file contains lf without above mentioned substitution. i've had dlmcell , fex-function. in current version \r\n implemented actually. have newest version of func...

expressionengine - Importing PHP string with quotes -

so i'm importing expressionengine fields php array. want display 1 field, called {gearboxx_body}, unless field has more 300 characters, in case want display field called {article_blurb}. i'm pretty sure there isn't way in expressionengine fields , conditionals, tried php, i'm starting learn: <?php $info = array('{gearboxx_body}','{article_blurb}'); if(mb_strlen($info[0]) <= 300) echo($info[0]); } else { echo($info[1]); } ?> so works well, there's problem. if tag includes apostrophes or quote marks, ends string , page won't load. can this? i've tried replace quote marks in string, have have loaded string fields first, , page broken. hopefully made sense. suggestions? i recommend handle in ee plugin rather in template: faster render (because don't need overhead of php in templates) more secure , reliable faster develop once basics of ee development down which useful life skill all aro...

SQL Server: How to use Update statement with xml input -

i use sql server 2008 , have stored procedure 1 input parameter formatted xml. xml list of names, 1 word each without spaces. for each of these names want check if exist in table, if no should added table, if yes should updated there. so far have part add them if don't exist yet works intended can't figure out how realise updating part. can here me ? just demonstration update part stand-alone (if have 1 input instead of xml): update rc_permissionsusers set ntid = @ntid, departmentid = @departmentid, role = @role ntid = @ntid the rest of procedure insert part (working): begin set nocount on; begin transaction; begin insert rc_permissionsusers ( ntid, departmentid, [role] ) select paramvalues.ntid.value('.', 'varchar(255)'), @dep...

node.js - Phonegap Pushnotification + node-gcm: group notifications -

i have in node app: var sender = new gcm.sender("xpto"); var registrationids = ["whatever"]; ... var message = new gcm.message({ data: { avatar: body_data.avatar, message: body_data.message } }); sender.send(message, registrationids, 4, function (err, result) { console.log("success"); }); it works fine, notification arrives , goes tray if app if not opened. if send new notification same registrationid, old notification "updated" (or removed) , new 1 shows. if add random integer parameter notid message.adddata("notid", parseint(math.random() * 25)); the notifications kept in tray, tray start show multiple notifications. there way group notifications? android devices group same kind of notifications. if set set different collapsekey each kind of notification, won't grouped others. can have @ 4 different collapsekey @ same time visible user in tray.

java - Google GeoCode Co-ordinate vary over a period of time -

i had geocoded around 40k address 3 months ago using google geocode api. http://maps.googleapis.com/maps/api/geocode/json due limitation on number of requests per day had processed 2500 records every day. out of 40k records 10k records processed location type approximate . but today if process same 10k records again location type changed rooftop different lat , long . there no changes in records had ‘rooftop’ , range_interpolated i.e. if process rooftop record – there no change in lat , long , location type. couldn't understand why there change in approximate location type records. please guide me. thanks, indy it's not allowed store these data more 30 calendar days ( https://developers.google.com/maps/terms#section_10_1_3 ) approximate means approximate , it's fine when results become more precise

XML Schema that allows anything (xsd:any) -

i need example of xml schema allow , everything. it might sound weird this, need debug current schema. thing have complex object use in function (part of dll have no control over) along schema, , functions returns me xml. function throws exception because there's error while validating schema, there shouldn't one. so, want blank schema, schema not cause validation error, can see xml outputted function. i tried take current schema, , keep xs:schema tag create empty schema, didn't work. xml schema cannot specify document valid regardless of content. however, if you're able specify root element, can use xs:anyattribute , xs:any allow attributes on root element , xml under root: <?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/xmlschema"> <xs:element name="root"> <xs:complextype> <xs:sequence> <xs:any processcontents="ski...