Posts

Showing posts from April, 2013

python - Reading and writing an array in a file using C functions in cython -

i instantiating class in cython . want declare 1 of instance array of float values once computing given function , save in binary file using c functions. further call of class if input file exist, instance declared reading array file otherwise compute again. import numpy np cimport numpy np cimport cython libc.stdio cimport file, fopen, fwrite, fscanf, fclose, fseek, seek_end, ftell, stdout, stderr cdef extern "math.h": double exp(double) nogil double log(double) nogil cdef class hit(object): cdef public double[::1] zs, da cdef char* path def __cinit__(self, zs=none, path=none): if path none: raise valueerror("could not find path file contains table of distances") else: self.path=path if zs none: raise valueerror("you must give array contains steps!") self.zs=zs cdef py_ssize_t i, n n=len(self.zs) cdef file *ptr_fr cdef file *ptr_

c# - deployable database on CD -

i have microsoft sql database connected winforms c# application, works fine on single computer, usable on cd user. i tried putting in localdb reason database duplicated , put bin folder, causes multiple issues in recording data, instances save user id 5 saves in bin never makes changes real database. next go create it, user id changes 7 user 6 not visible in either 2 databases (yes auto incremented 1) any suggestions or best methods on making database useable , readable via cd if winform application on cd i have not tried self, according documentation sqlite supports read-only databases. if file read-only (due permission bits or because located on read-only media cd-rom ) sqlite opens database reading only. entire sql database stored in single file on disk. additional temporary files may created during execution of sql command in order store database rollback journal or temporary , intermediate results of query. see https://www.sqlite.org/c_interface.html .ne

iphone standalone web app - On screen rotation iOS webapp changes viewport and crashes -

i've created mobile webbased game , use "add homescreen" feature allow users add app ios devices. however, started malfunctioning. has worked without problem started acting possibly after ios 8.3 update. code in head, has not been changed should not problem: <meta name="viewport" content="width=590px, user-scalable=0"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> when login screen works without problem, after logging in in landscape there margins left , right. if log in in portrait there no margins. if rotate phone landscape margins portrait displays normally, if rotate margins increase lot , if try rotate device again crashes. i have taken screens show problem: http://i.imgur.com/o2jr8af.png http://i.imgur.com/q6zoxuj.png http://i.imgur.com/7bgoc42.png http://i.imgur.com/mh8hsml.png

While converting xml to xslt values are not mapping -

hi new xslt transformation trying convert following xml using xslt not getting value of title in result xml. input xml: <exam:orderreq> <exam:item> <exam:title>r</exam:title> </exam:item> </exam:orderreq> xslt: <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform" xmlns:exam="http://www.jboss.org/bpel/examples" xmlns:prod="http://www.jboss.org/bpel/examples/product"> <xsl:template match="/"> <prod:productorderreq> <prod:product xmlns:prod="http://www.jboss.org/bpel/examples/product"> <xsl:for-each select="exam:orderreq"> <prod:name><xsl:value-of select="exam:title"/></prod:name>

java - Implement cancelRequest -

i implementing cancelrequest ongoing call. try send request once session established. cancel function worked first time implemented says transaction exists. how fix it? else if(currentresponse.equals("session progress")){ system.out.println("------------------- status code: "+ statuscode+ "--------------------------"); system.out.println(responseevent.getresponse()); try { request cancelrequest; cancelrequest = invitetid.createcancel(); clienttransaction canceltid = sipprovider.getnewclienttransaction(cancelrequest); canceltid.sendrequest(); system.out.println("cancel requst:" + cancelrequest); } catch (sipexception e) { // todo auto-generated catch block e.printstacktrace(); } } response: -----------statuscode:100---------------------------- -----------curr

Haxe: how to declare "static" methods in an Interface? -

this question has been asked (and answered) in old haxe forums on babble ... appears that entire forum system no longer functions. therefore, i'm asking here: in haxe, need declare "interface" class includes static function, "instance()." when so: you can't declare static fields in interfaces so remove word "static" public function instance() [...] , , this: field instance needed [...] missing. apparently "catch-22." there must easy solution. it? as stated language doesn't allow static fields on interfaces. choice intentional. thing doesn't exist inheriting static fields. there several ways structure code avoid such usage in point of view doesn't give many advantages. factory pattern or di approach (i suggest minject library ) seems obvious. given comment below go typedef instead of interface: typedef getinstance = void -> void; you can pass typedef around same interface advantage can us

c# - Debug.WriteLine(string, params object[]) is a method but is used like a type -

i'm working on to-do list project , @ ending stages of development, syntax outputting debug seems incorrect, i'm not sure error , appreciated. as shown above, error cs0118 : 'system.diagnostics.debug.writeline(string, params object[]) method used type' #define testing using system; using system.collections.generic; using system.diagnostics; #if(testing) public static string[] tempstringarr = new string[5] { "hey", "greetings", "hello", "hi", "example" }; public static string tempkey = "hello"; public static int linearsearchtitletest(string titlekey, string[] titlearr) { (int = 0; < titlearr.length - 1; i++) { if (titlekey == titlearr[i]) { return i; } } return -1; } int testresult = linearsearchtitletest(tempkey, tempstringarr); debug.writeline(convert.tostring(testresul

ios - PHAsset fetchAssetsWithLocalIdentifiers returning assetFetchResults in localIdentifier order -

i cannot find issue addressed in apple documentation, apple forums, or stackoverflow. have attempted create code , @ results various options. it appears if sort descriptor not provided call [phasset fetchassetswithlocalidentifiers] returns assets in local identifier order. using technique of passing "nil" options, can replicate sort order of existing phasset collections. self.assetsfetchresults = [phasset fetchassetswithlocalidentifiers:self.selectionlist options:nil]; in developer documentation, cannot find option sort descriptor phasset override default action meet needs. loading assetsfetchresults transientassetcollection limits addition , deletion of assets (per apple documentation). self.assetcollection = [phassetcollection transientassetcollectionwithassetfetchresult:self.assetsfetchresults title:self.albumname]; is there way fetchassetswithlocalidentifiers return assets in order of local identifiers in array supplied on call? if call return as

javascript - How to add jQuery if statement inside a set of plugin options? -

i'm trying calendar plugin (fullcalendar) display different number of days depending on whether user viewing site on mobile, tablet, or desktop breakpoints. this, need calendar display normal week on desktop , 3 days on mobile. normal plugins, init element , pass options. i've tried couple of things so. the working code follows: $('#calendar').fullcalendar({ timeformat:'h(:mm)a', header:{ left:'prev', center:'title', right:'next' }, height: 650, views: { basicthreeday: { type: 'basic', duration: { days: 3 }, buttontext: '3 day' }, }, defaultview: 'basicthreeday', titleformat: { week: 'mmmm yyyy' }, columnformat: { week: 'dddd m/d', day: 'ddd m/d' }, this

java - What role does hashCode play when comparing two objects? -

i've decided study primary documentation in java. i've started object class , looking @ equals method. know equals using hashcode method. although, hashcode returns int there limited number of unique hashcodes can generated. what happen when try compare 2 diffrent objects have same hashcode ? posible? yes. 2 objects can have same hashcode. however, hashcode plays no role when comparing 2 objects. if want check if 2 objects of class equal , override equals , define when 2 objects of class should considered equal. if want compare if 1 object of class less than/greater other (usually while sorting collection), implement comparable , override compareto method. (you can implement comparator ) if ever want store object in hashset or use key in hashmap , make sure override hashcode method or objects hashset or keys in hashmap stored in single bucket. don't forget override equals in classes create. if don't this, 2 references object of class equ

uml - Ternary association - multiplicity between two classes -

Image
suppose have following diagram (i can't post images directly) - ternary association between classes a, b, c what should added diagram ensure objects of class can associated maximum of 50 b objects? you can't way. must draw association lines between each class , specify cardinality.

cabal - "Could not find module ‘Test.HUnit’" Error when executing Haskell's unittest (HUnit) in CodeRunner -

Image
i have simple unit test code haskell's hunit. use mac os x 10.10, , installed hunit cabal install hunit . module testsafeprelude import safeprelude( safehead ) import test.hunit testsafeheadforemptylist :: test testsafeheadforemptylist = testcase $ assertequal "should return nothing empty list" nothing (safehead ([]::[int])) testsafeheadfornonemptylist :: test testsafeheadfornonemptylist = testcase $ assertequal "should return (just head) non empty list" (just 1) (safehead ([1]::[int])) main :: io counts main = runtesttt $ testlist [testsafeheadforemptylist, testsafeheadfornonemptylist] i can execute runhaskell testsafeprelude.hs results: cases: 2 tried: 2 errors: 0 failures: 0 counts {cases = 2, tried = 2, errors = 0, failures = 0} however, when run in code runner , have error message can't find hunit module. coderunner launches test on different shell environment, , seems issue. if

objective c - iOS - Playing Tock sound for custom keyboard -

i trying play tock sound custom keyboard. what have tried: [[uidevice currentdevice] playinputclick]; and nsstring *path = [[nsbundle bundlewithidentifier:@"com.apple.uikit"] pathforresource:@"tock" oftype:@"aiff"]; systemsoundid soundid; audioservicescreatesystemsoundid((cfurlref)[nsurl fileurlwithpath:path], &soundid); audioservicesplaysystemsound(soundid); audioservicesdisposesystemsoundid(soundid); and audioservicesplaysystemsound(0x450); and nsstring *soundfilepath = [[nsbundle mainbundle] pathforresource:@"test" oftype: @"mp3"]; nsurl *fileurl = [[nsurl alloc] initfileurlwithpath:soundfilepath ]; myaudioplayer = [[avaudioplayer alloc] initwithcontentsofurl:fileurl error:nil]; myaudioplayer.numberofloops = 1; [myaudioplayer play]; this gave me error: audiosessionclient: couldn't connect com.apple.audio.audiosession couldn't connect com.apple.audio.audioqueueserver; audioqueue not usable and loo

ruby - gsub for removing brackets and \ from string -

i have issues using gsub remove [] , \" string. here string: "[\"this word ect\", \"char2\", \"another grooup\", \"char4\"]" i want returned value be: "this word ect, char2, grooup, char4" can point me in right direction? just out of curiosity: str = '["this word ect", "char2", "another grooup", "char4"]' require 'json' json.parse(str).join(', ') #⇒ "this word ect, char2, grooup, char4"

objective c - Unexpected behaviour for isKindOfClass: on NSManagedSubclasses created by mogenerator -

i have entity in object model called book class attribute xyzbook . mogenerator creates 2 classes: _xyzbook xyzbook , inherits _xyzbook . so far good. if create instance on xyzbook : xyzbook *b = [xyzbook insertinmanagedobjectcontext:context]; sending class b, returns xyzbook expected. [b class] --> xyzbook however, sending ismemberofclass:[xyzbook class] returns no!!! [b ismemberofclass:[xyzbook class]] --> no it returns yes if use _xyzbook super class: [b ismemberofclass:[_xyzbook class]] --> yes so, on earth going on???? btw, create these clases using custom base class (with --base-class option mogenerator). in case has this...

c# - Change an image dpi without changing it's pixal format -

every time try change image's dpi, pixel format (color scheme - rgb, cmyk , such...) seems change. time did succeed in saving pixel format, dpi, on debug mode, seems change, after process complete, changed it's original settings. the code tried followed: using (var ms = new memorystream()) { using (var bmpinput = image.fromfile(path) bitmap) { using (var bmpoutput = (bitmap)bmpinput.clone()) { foreach (var id in bmpinput.propertyidlist) bmpoutput.setpropertyitem(bmpinput.getpropertyitem(id)); if (doresize) bmpoutput.setresolution(dpi, dpi); bmpoutput.save(ms, bmpinput.rawformat); return ms.toarray(); } } } application.doevents(); try before saving image in code.

Can't get Spring Security OAuth2 login to trigger -

i writing restful web service ( jersey running on tomcat ) needs authenticate users' email address, , possibly access google calendar. plan users redirected login google via oauth2 . my web service protected spring security . works fine basic authentication (i.e. hard-wired list of users , passwords.) if try access of protected resources prompted login. now trying wire in spring security oauth2 . understanding redirect google if try access protected resource. however, no matter try can't seem oauth fire. there no console errors logged, , resources protected (i error "full authentication required access resource"). something wrong; config, understanding, or both. suggestions appreciated. web.xml (partial): <servlet-mapping> <servlet-name>jersey rest service</servlet-name> <url-pattern>/v1/*</url-pattern> </servlet-mapping> <listener> <listener-class> org.springframework.web.context.cont

python - Time complexity of recursive permutation printer -

while trying explain recursive algorithms generate permutations in lexicographic order , provided simple algorithm: def permute(done, remaining): if not remaining: print done return sorted_rem = sorted(remaining) l = len(sorted_rem) in xrange(0, l): c = sorted_rem[i] # move c done portion. done.append(c) remaining.remove(c) # permute remaining permute(done, remaining) # put c back. remaining.append(c) # remove done. del done[-1] def main(): permute([], [1,2,3,4]) if __name__ == "__main__": main() first question: seems bit wasteful me , wonder time complexity has, given pythonic implementation this? note optimal time complexity o(n * n!) , need print n! permutations of size n. i guessing because of sorted (which presume o(n log n) in python), additional log n factor added (which suppose practically negligible n can use program for). the second part of question optimize bit. second qu

How to print button text value on console in Kivy -

my app have 1 button , text random number 1 9. want print button text on console on on_press. actually, have minimized problem, want compare value variable, if button.text=5, else do_something_else. my attempt: #!/usr/bin/kivy import kivy kivy.require('1.7.2') random import random random import choice kivy.app import app kivy.lang import builder kivy.uix.screenmanager import screenmanager, screen kivy.uix.gridlayout import gridlayout kivy.uix.button import button kivy.properties import stringproperty builder.load_string(""" <highest>: gridlayout: cols: 1 button: text: root.r1c2 on_press: root.new() """) class highest(screen): r1c2 = stringproperty(str(int(random()*10))) def new(self): print self.text # create screen manager sm = screenmanager() sm.add_widget(highest(name='highest')) class testapp(app): def build(self): return sm if __name__ == '

python - how do I abort a query in py2neo? -

i'm developing web app gui neo4j dataset have here @ organization. app in python (i'm using flask+tornado) , i'm using py2neo connect neo4j. things work fine, query take long execute , continues executing if user closes tab or browser (or clicks button stops loading page). so, how can have query aborted when user closes tab or browser or clicks stop button? long running queries - can set following 2 parameters in neo4j.properties: - execution_guard_enabled=true # milliseconds org.neo4j.server.webserver.limit.executiontime=20000 as of not see option available in py2neo directly kill request, except setting http timeouts in py2neo libs

algorithm - Python - Stratified Sampling with MiniBatch k-means -

i'm trying cluster million objects, each have varying length of datapoints, less 100. features date of observations , id value of each object(let's runner's(name) , times in different races). want run minibatch k-means on data, want algorithm take stratified samples based on third feature, let's u.s. state runner from. there way implement such sampling within minibatchkmeans function? if not, there way take stratified samples , pass them function somehow? thought this, seems if took stratified samples , passed them base k-means algorithm, wouldn't able aggregate samples , 1 label each object. advice?

java - Put Image above Video and save video in android -

i'm writing application must put image above video , save video. in general application opens video file, after user select image transparent background , put image above video, after user press save button new video image above video. can please provide me information or hints how that. so per question, looking video editor kind of solution achieve task.. i think scenario: ** have video in application ** open bitmap resource (image file where) ** overlay bitmap @ bottom of movie (video) on frames in background ** save video on external storage for ffmpeg support overlaying functionality or android mediacodec stuff . ffmpeg has various filters 1 of them overlay filter. understand want overlay image (i.e. png) on video, ffmpeg surely useful framework job. can set output format can set co-ordinates of image overplayed. e.g: ffmpeg -i input.avi -i logo.png -filter_complex 'overlay=10:main_h-overlay_h-10' output.avi above command adds overlay

javascript - ExtJS sort grid column of string as float -

Image
i have grid column renders float record field string. so, when sort column, it's sorted string format , therefore, in wrong way: i've tried different solutions. 1 understand should works use of sorttype function. haven't bee able far... these important pieces of code. my model load grid data: ext.define('ama.model.assetmodel', { extend: 'ext.data.model', fields: [ {name: 'account', type: 'string'}, {name: 'altlabel'}, {name: 'amortizable', type: 'int'}, {name: 'amortizationsvnc', type: 'float', convert: function(value,model){ return parsefloat(math.round(value * 100) / 100).tofixed(2); } }, {name: 'assetsaccountingprice', type: 'float', convert: function(value,model){ return parsefloat(math.round(value * 100) / 100).tofixed(2); } }, ..... my grid columns affected: it

excel - How do I get vba loop result to populate a combobox? -

problem: need search list of worksheets in active workbook , return name of every worksheet has cell value matches search input. names of these worksheets need populate userform combobox duplicates. partial solution: i've been able reverse-engineer piece of code of above. however, worksheet names populate msgbox duplication. how make result populate combobox instead? i've been experimenting outputting collection writing results new worksheet, these option still in conceptual phase, have no code post. update (some code): public sub finddate() 'find date data on sheets dim ws worksheet dim rngfind range dim mydate string dim firstaddress string dim addressstr string dim findnum integer dim sheetarray(299) integer dim arrayindex integer mydate = inputbox("enter date find") if mydate = "" exit sub each ws in activeworkbook.worksheets 'do not search following sheets ws if ws.name = "cm chapters" goto mynext

Python: Convert hex to string -

a value 0x0f or 0x05 has given function string without 0x @ beginning 0f or 05 . if use str(hex(0x0f))[2:4] f . crucial missing 0 still present in application. how can that? you'd use str.format : in [1]: '{:02x}'.format(0x0f) out[1]: '0f' in context {:02x} equivalent {0:02x} . preceding colon 0 tells python apply first argument of str.format ( 0x0f in example). 02 sets minimum field width 2 , preceding width field 0 ('0') character enables sign-aware zero-padding numeric types x 1 of available integer presentation types: hex format. outputs number in base 16, using upper- case letters digits above 9. both quotes format specification mini-language .

css - Why does iOs Safari show full size of background-image? -

i'm working on site have boxes background-images thumbnails. have use background-image because cms working on pretty old-dated , client won't change (mon€y main-problem). i figured out strange behavior in ios safari on ipad2 & iphone5 (latest ios) , don't know why. here's code: a img, .thumb, figcaption, a:hover .thumb { -webkit-transition: .3s; -moz-transition: .3s; -ms-transition: .3s; -o-transition: .3s; transition: .3s; } .thumb { height: 250px; margin-bottom: 28px; overflow: hidden; background-size: 100% 100%; background-position: center; background-repeat: no-repeat; } figcaption { background-color: #b61910; background-color: rgba(182, 25, 16, .85); position: absolute; height: 39px; bottom: 35px; color: white; width: calc(100% - 30px); } figcaption h3 { font-style: normal; position: absolute; bottom: 5px; margin-top: 0; margin-bottom: 0; padding: 10px 0 0 5px; tra

javascript - unable to recieve success message from php to Ajax, jQuery || SOLVED -

Image
i working jquery/ajax need php send me success, error message upon status of form receiving. have done bit of googling still unable receive message. using json_encode. js code: $(function() { $("#loginbtn").click(function(e) { var array = []; var username = $("#login").val(); var passwrd = $("#password").val(); var flag = false; alert("log in alert"); if(username == '' || passwrd == '') { alert("username or password cannot empty"); flag = false; } else { array.push(username); array.push(passwrd); alert(array); flag = true; } if(flag == true) { alert("going ajax"); $.ajax({ url:"http://localhost/login.php", data: { username: array[0], passwrd: array[1], }, type:"post",

vba - Switching from ODBC to OLEDB and getting "Object Required" -

i have been tasked modifying vba code switch using odbc connection using oledb connection can code username , password subroutine. i'm not experienced think i'm managed proper connection string new oledb connection. i've tested connection string in standalone test sub , worked fine. i'm attempting replace previous odbc connection strings in code i'm starting "run-time error '424' object required" here sub trying work: sub getdata() dim tablename string dim tablerecords new adodb.recordset dim cnxn2 adodb.connection tablename = "table_name" set cnxn2 = new adodb.connection 'old connection string using odbc 'cnxn2.connectionstring = "data source='datasource';" '& "integrated security = sspi;" 'new connection string using oledb cnxn2.connectionstring = "provider=sqloledb;data source=server\instance;user id=user;password=password;" cnxn2.connectiontimeout = 30 cnxn2