Posts

Showing posts from February, 2014

deployment - Run rails app under subfolder -

i've been testing rails app on localhost:3000 , works fine. however, when deploying host, root url is: http://99.88.77.66/~username i not have domain name @ point. when point browser above url root not found for: /~username alternatively for http://99.88.77.66/~username/controller/index i route not found: /~username/controller/index i'm using rials 4.2.3 , ruby 2.0. how can make routes work kind of subfolder until can appropriate domain name? try setting config.relative_url_root in config/environments/production.rb : http://guides.rubyonrails.org/configuring.html#deploy-to-a-subdirectory-relative-url-root

.htpasswd - how do I use .htaccess in a two teir login -

i working on development site, has published production site. there new lead on site. work him. has asked me lock out development site via .htaccess. have done (testuser/testpass). on published production site, there no login necessary access homepage, on development site there is. simple enough. so here problem. on production website there password protected subdirectory "restricted" protected .htaccess (authuser/authpass). "testuser" re-authenticate when accessing "restricted" ~as~ "authuser". i not sure if .htaccess can because authorizes files , directories below it. an attempt visually describe below. homepage (for testuser) or 403 others ~including~ authuser |__ current events |__ more pages |__ calendar |__ other page |__ restricted (to authuser) or return homepage |__ contact the question is: possible? seems think should be, uncertain. i have tried obvious, .htaccess in webroot index.html testuser in it..

iphone - How to manipulate iOS conversation's streams? -

i found 2 useful topics here , here . need somehow change speaker/mic stream. example, apply effects or stop audio being played user @ all. question not recording, manipulation of audio in real. there way can achieve that? thanks.

sql - Django - Modify query based on user logged in -

i have database has 2 tables: 'installs' , 'installers'. 'install' table has field installer. installer able log in , see list of installs. for now, working sqlite use mysql production. how do this? thanks! models.py: from django.db import models django.core.urlresolvers import reverse class install(models.model): id = models.autofield(primary_key=true) name = models.charfield(max_length=45) address = models.charfield(max_length=60) city = models.charfield(max_length=45) state = models.charfield(max_length=15) zipcode = models.integerfield() email = models.emailfield(max_length=60, blank = true, null = true) phone= models.integerfield(blank = true, null = true) website = models.urlfield(max_length=90, blank = true, null = true) unit_model = models.charfield(max_length=30) serial = models.charfield(max_length=30) unit_installer = models.charfield(max_length=30) unit_dealer = models.charfield(max_l

Understanding "this" within anonymous function in JavaScript -

in post , lots of answers there discussing this keyword in javascript. however, still confuse this in anonymous function following // mymodule.js 'use strict'; (function(handler) { // export methods handler.b = b; handler.a = a; function a() { console.log(this); console.log('function invoked...'); } function b() { console.log(this); console.log('function b invoked...'); try { a(); this.a(); } catch (err) { console.log('exception ' + err); } } })(module.exports); // test.js var mymodule = require('mymodule.js'); mymodule.b(); output: (running under node.js) { b: [function: b], a: [function: a] } function b invoked... undefined function invoked... { b: [function: b], a: [function: a] } function invoked... the output indicates function a in 2 different scopes. right? why there 2 scopes function a ? as know, t

java - I can't identify the issue with my parallel run timer -

i have program applies median filter array of on 2 million values. i'm trying compare run times sequential vs parallel on same dataset. when execute program, 20 runs, every run timed, , average of 20 times outputted console. arraylist<double> times = new arraylist<>(20);//to calculate average run time (int run = 1; run < 21; run++) //algorithm run 20 times { long starttime = system.nanotime(); switch (method) { case 1: //sequential filt.seqfilter(); break; case 2: //forkjoin framework pool.invoke(filt); //pool forkjoin break; } double timeelapsed = (system.nanotime() - starttime) / 1000000.0; times.add(run - 1, timeelapsed); system.out.println("run " + run + ": " + timeelapsed + " milliseconds."); } times.remove(collections.max(times)); //there's slow outlier double timessum = 0; (double e : times) { timessum += e; } double aver

Perl: Passing by reference does not modify the hash -

my understanding in perl pass hashes functions reference consider following example, modify hash in modifyhash function #!/usr/local/bin/perl %hash; $hash{"a"} = "1"; $hash{"b"} = "2"; print (keys %hash); print "\n"; modifyhash(\%hash); print (keys %hash); print "\n"; sub modifyhash { $hashref = @_[0]; %myhash = %$hashref; $myhash{"c"} = "3"; print (keys %myhash); print "\n"; } the output of script is: ab abc ab i have expected be: ab abc abc ...as pass hash reference. what concept missing here passing hashes functions? that's because when my %myhash = %$hashref; , you're taking copy of dereferenced $hashref , putting %myhash same thing my %myhash = %hash; , you're not working on referenced hash @ all. to work on hash specified reference, try this... sub modifyhash { $hashref = $_[0]; $hashref->{"c"} = &

java - How do you use anonymous objects with the factory pattern? -

i have method so: public class foofactory { public foo createnewfoo(){ return new foo(); } } now if this: foofactory foofactory = new foofactory(); foo foo = foofactory.createnewfoo(); it'll work fine. however, if try : new foo() = foofactory.createnewfoo(); it doesn't seem work @ all. says "variable expected". i understand new foo() in itself, creates new foo object, if use factory, should override anonymous object new foo object. i've tried creating arraylist holds foo's , doing arraylist.add(new foo()); arraylist.get(0) = foofactory.createnewfoo(); it still says "variable expected". why saying that? foo foo = new foo(); foo otherfoo = foo; this works fine, don't understand why can't make factory work anonymous object. i tried searching online, got no search results, tells me i'm making ridiculous mistake/using factory pattern wrong. equals assignment operator . targetofmyassi

javascript - Calling RESTful webservices in Appcelerator Titanium Studio -

i'm new appcelerator titanium studio. please me out how call webservice (java based) in appcelerator titanium. you can use titanium.network.httpclient make restful calls. example requests var url = "http://www.appcelerator.com"; var client = ti.network.createhttpclient({ // function called when response data available onload : function(e) { ti.api.info("received text: " + this.responsetext); alert('success'); }, // function called when error occurs, including timeout onerror : function(e) { ti.api.debug(e.error); alert('error'); }, timeout : 5000 // in milliseconds }); // prepare connection. client.open("get", url); // send request. client.send(); example post requests var xhr = ti.network.createhttpclient(); xhr.onload = function(e) { //handle response, @ minimum http status code }; xhr.open('post','http://www.myblog.com/post.php'); x

python - Why does this pygame program freeze? -

below program using pygame updates histogram values change. however after few seconds of running, program freezes. can point out error? import random import pygame screen_size = screen_width, screen_height = 800, 600 frame_rate = 50 background_color = pygame.color("white") bar_color = pygame.color("black") bucket_cnt = 20 pygame.init() screen = pygame.display.set_mode(screen_size) screen.fill(background_color) buckets = bucket_cnt*[0] bar_w = screen_width / bucket_cnt clock = pygame.time.clock() background = pygame.surface(screen.get_size()) background.fill(background_color) while true: clock.tick(frame_rate) random.seed() idx = random.randrange(bucket_cnt) buckets[idx] += 1 # create rectangles representing bars in histogram. bars = [pygame.rect(i*bar_w, screen_height - buckets[i], bar_w, buckets[i]) in range(bucket_cnt)] # draw bars on background [pygame.draw.rect(back

python - Sort of dictionary values from keys in an ordered list -

say have following dictionary: fruitvalues={'banana':3, 'orange':4, 'apple':1} and have list of keys of dictionary in order want preserve: sortorder=['orange', 'apple', 'banana'] what efficient way of getting list of values dictionary in order of list? right approach following: orderedvalues=[] fruit in sortorder: orderedvalues.append(fruitvalues[fruit]) print orderedvalues [4, 1, 3] is there better / cleaner way of doing this? maybe using dictionary comprehension? use list comprehension: >>> [fruitvalues[i] in sortorder] [4, 1, 3]

javascript - How to dynamically change the slot values based on user view port? -

i have feedback popover towards right side of page fixed. user can open popover clicking on helpful text , provide feedback on different sections. use case 1) if user on top of page , if decides provide feedback, open popover , slot values one,two,three. 2) if user decides scroll main page further down , top visible section in main page five,six , seven... if decides provide feedback, open popover , slot values five,six,seven. ![slot values five,six,seven] http://imgur.com/9kznw1i how automatically update slot values based on user view port. using ng-repeat change slot values when clicked , down here plunker http://plnkr.co/edit/rr0tislmoliknnp3fyzf?p=preview this not perfect should give idea how improve it. right assuming have similar height items, can either constraint or calculate them on fly in formula. http://jsbin.com/xozoni/edit?html,js,output

javascript - Google Maps not rendering at all -

i've worked maps , i've never faced issue map doesn't render @ all. here's fiddle code implementation including request places api library http://jsfiddle.net/newtt/ljn1n6nh/ here's code sample: js: function initialize() { var elem = document.getelementbyid('map-dire'); var map = new google.maps.map(elem, { maptypeid: google.maps.maptypeid.roadmap, }); } google.maps.event.adddomlistener(window, 'load', initialize()); it's simplest form of maps it's rendering grey/beige box , if click anywhere says uncaught typeerror: cannot read property 'x' of undefined . understand error shows when dom element map isn't loaded. doesn't map trigger when window element loaded? **center , zoom required.** try send latitude , longitude dynamically, giving hard coded values reference function initialize() { var elem = document.getelementbyid('map-dire'); var mapoptions = {

Mysql update column on first occurrence of each username -

i'm trying mark first occurrence per day of each username. have concerning people marked dupe = 1. first day should set dupe = 2. like in layman's terms, if first entry of username day, mark column = 2. each day. based on question https://stackoverflow.com/a/12065956/1811162 can make this select * ( select * table dupe=1 order date desc ) x group date which returns 1 member of each duplicate i'm looking for, i'd set 1 = 2. having trouble making update statement. or work update statement? want first member set. the result want - select username, dupe dupe!= 0; day 1 bob - 2 kathy - 2 bob - 1 kathy - 1 kathy - 1 day 2 kathy - 2 kathy - 1 bob - 2 kathy - 1 what tried is update table set dupeflag=2 ( select * from ( select * table dupeflag=1 order date desc ) x group date ) but no luck. wrong i went new flag column this, plus had benefit of helping other question here . demo schema setup create ta

linux - Two TCP client application with virtual interface ip -

here requirement. 2 tcp client connection/emulation single eth port i created 2 virtual interface. ifconfig eth1:0 10.0.0.2 ifconfig eth1:1 10.0.0.3 is possible create tcp client code such particular interface used tcp client establishment. for example ./client_app eth1:0 - -- client ip 10.0.0.2 ./client_app eth1:1 -- client ip 10.0.0.3 to enumerate local interfaces , ip address associated these interfaces use system call getifaddrs() . then use bind() system call bind local side of connection local interface's ip-address.

python - OpenCV digit OCR -

Image
i trying build simple sudoku grabber scans sudoku image , extracts digits in order ( 0 blank). have extracted 81 box approximately. screen_shot of cells 9x9 code import cv2 import numpy np import cv2.cv cv import tesseract def rectify(h): h = h.reshape((4,2)) hnew = np.zeros((4,2),dtype = np.float32) add = h.sum(1) hnew[0] = h[np.argmin(add)] hnew[2] = h[np.argmax(add)] diff = np.diff(h,axis = 1) hnew[1] = h[np.argmin(diff)] hnew[3] = h[np.argmax(diff)] return hnew img=cv2.imread('sudoku.jpg') gray = cv2.cvtcolor(img,cv2.color_bgr2gray) gray = cv2.gaussianblur(gray,(5,5),0) thresh = cv2.adaptivethreshold(gray,255,1,1,11,2) contours,hierarchy = cv2.findcontours(thresh, cv2.retr_tree, cv2.chain_approx_simple) biggest = none max_area = 0 in contours: area = cv2.contourarea(i) if area > 100: peri = cv2.arclength(i,true) approx = cv2.app

java - Spring Data JPA (CrudRepository) - BeanCreationException: Could not autowire field -

i trying use spring data jpa - crudrepository use without implementation (all default options). with code having exception: exception in thread "main" org.springframework.beans.factory.beancreationexception: error creating bean name 'springjpacontactservice': injection of autowired dependencies failed; nested exception org.springframework.beans.factory.beancreationexception: not autowire field: private com.sample.hibernate.contactrepository com.sample.hibernate.repositorycontactserviceimpl.contactrepository; nested exception org.springframework.beans.factory.beancreationexception: error creating bean name 'contactrepository': invocation of init method failed; nested exception java.lang.abstractmethoderror: org.springframework.data.repository.core.support.repositoryfactorysupport.gettargetrepository(lorg/springframework/data/repository/core/repositoryinformation;)ljava/lang/object; @ org.springframework.beans.factory.annotation.autowiredannotat

mysql - Query takes long time on 'statistics' state -

one of query takes long time(more 300 seconds) executing simple query. , fails in statistics state. it happens while concurrent execution of same query. " select 1 <table_name> id = <value> update " even, have 'optimizer_search_depth' config 0 , buffer size has 14gb. select .... update sets read lock on rows returns until transaction done, therefor when call same query multiple times @ same time, other ones have wait locks released i guess using innodb engine table? please see innodb-locking-reads further information on locking "for update"

How to setup IntelliJ to recognize Scala's "???" method as a TODO -

i'd see occurrences of ??? in intellij todo list (or in other way able see list of unimplemented methods in scala project). seems adding pattern \b\?\?\?\b.* in todo settings doesn't work. intellij allows create custom todo patterns. in todo window click on filters icon > edit filters > add new pattern. once add new pattern intellij rescan project , add new todos list. official jetbrains todo example update: as per comments, did quick test , doesn't it's possible scan todos outside comments.

c# - Value cannot be null. Error -

i have error method below trying add data combobox datagrid , after add data want calculate total amount of 'itemsellingprice' , display amount in label. using (truckserviceclient tsc = new truckserviceclient()) { var item = cmbaddextras.selecteditem extradisplayitems; if (item != null) { var displayitem = new list<extradisplayitems> { new extradisplayitems { displayitems = item.displayitems, itemid = item.itemid, itemcode = item.itemcode, itemdescription = item.itemdescription, itemsellingprice = item.itemsellingprice, } }; dgaddextras.items.add(item); var subtotalextras = item.displayitems.sum(x => x.itemsellingprice.getvalueordefault(0)); //here lblsubtotalextrasamount.content = "r" + subtotalextras; } } the error is: value cannot null. does have ideas why

r - Create variable/column equal to another column/factor frequency -

the short i have x <- data.frame(animal = c("ant", "cat", "dog", "ant", "dog", "ant", "ant")) and want create add column freq x such that > x animal freq 1 ant 4 2 cat 1 3 dog 2 4 ant 4 5 dog 2 6 ant 4 7 ant 4 the long i have > x <- data.frame(animal = c("ant", "cat", "dog", "ant", "dog", "ant", "ant")) > x animal 1 ant 2 cat 3 dog 4 ant 5 dog 6 ant 7 ant i know that > table(x) x ant cat dog 4 1 2 or > count(x) animal freq 1 ant 4 2 cat 1 3 dog 2 and > subset(count(x), animal == "ant")$freq [1] 4 and that > subset(count(x), animal == x[1,1])$freq [1] 4 > subset(count(x), animal == x[2,1])$freq [1] 1 but i'm struggling put add column freq x such that > x animal freq

uitableview - Toolbar in a TableView (Swift) -

i have toolbar @ bottom of tableview in storyboard within viewcontroller. when run app, toolbar shows @ bottom of table view. how can make toolbar fixed navigation bar? need have tab bar controller? navigationcontroller?.settoolbarhidden(false, animated: true) and use storyboard customise toolbar

Run a program with administrative privilegies Cx_freezed Python 3 -

short story : 1 freezed program, need run native program requires administrative privilegies long story : currently, have installer prepares program , unpacks final destination. want installer configure program run service. this, use nssm (non s*cking service manager - sorry name, that's name) use command-line program start, create, edit, etc services. nssm requires administrative rights. pre-vista windows support not mandatory. i have no knowledge uac/windows permissions. (just linux permissions)

php - Why Dropzone.js not able to upload file bigger than 250MB -

i trying upload file bigger 250mb dropzone.js not able upload it. have checked server configuration , looks fine. here more details upload_max_filesize=1024m post_max_size=1024m its uploading file less 250mb. appreciated. put these in code sending file upload ini_set('post_max_size', '1000m'); ini_set('upload_max_filesize', '1000m'); this works me

How to add custom reactjs components (belle) to my rails app -

i want add custom react components ( belle ) rails app. i'm using react-rails 1.0.0 view layer write coffeescript. first of new reactjs , steps site bring commonjs asset pipeline moves browserify-rails installed browserify on github page , arkency blog. run npm install --save belle in console, added application.js : var belle = require('belle'); textinput = belle.textinput; at end added main component simple component belle '<textinput defaultvalue={update here , see how input grows} />' below sites.js.coffee file: @sites = react.createclass getinitialstate: -> sites: @props.data getdefaultstate: -> sites: [] render: -> react.dom.div classname: 'sites_wrapper' '<textinput defaultvalue={update here , see how input grows} />' site in @state.sites react.dom.div classname: 'col-md-4 text-center' react.createelement site, key: site.id, sit

ruby - gsub variable regardless of case -

i have following code set highlight parts of phrase word is. function regardless of case struggling syntax. believe need add /i somewhere, not know where. params.fetch('phrase').gsub(params.fetch('word'), '<span class="ko-highlight">' + params.fetch('word') + '</span>') this should trick params.fetch('phrase').gsub(/#{params.fetch('word')}/i, '<span class="ko-highlight">' + params.fetch('word') + '</span>')

How to use Boost C++ library with Omnet++ -

i trying use boost c++ library omnet++ project. installed boost library version 1_58_0 in windows. whenever try build omnet++ project shows error - cannot find -lboost_filesystem_mt cannot find -lboost_system_mt please let me know how resolve this. or perhaps may wrong in installing , linking boost omnet++. let me know correct way in windows. you should files libboost_system_mt.a , libboost_filesystem_mt.a on drive. if these files exist (for example in c:\boost_1_58_0\lib ), in omnet++ go project properties, omnet++ | makemeke | check directory sources | options | custom | makefrag , , add path *.a libraries, example: libs += -lc:/boost_1_58_0/lib note here should use / symbol in path.

windows - How can i run rundll32 64bit process from c# -

i need install driver system32\drivers, if i'm using default install rundll32 c#, driver installing syswow64. code: processstartinfo startinfo = new processstartinfo(); startinfo.verb = "runas"; startinfo.filename = "cmd"; startinfo.arguments = @"/c rundll32.exe setupapi.dll,installhinfsection defaultinstall 132 " + file; var process = process.start(startinfo); process.waitforexit(); how can run process 64bit process?

c# - YouTube API service account returns 'forbidden 403' when inserting playlist item -

i'm writing simple application takes new uploads subscribed channels , adds them specified playlist. service account type used following code: var certificate = new x509certificate2(certificatefilename, "notasecret", x509keystorageflags.exportable); var serviceinitializer = new serviceaccountcredential.initializer(serviceaccountemail) { scopes = new[] { youtubeservice.scope.youtube } }; var serviceinitializerinstance = serviceinitializer.fromcertificate(certificate); var credential = new serviceaccountcredential(serviceinitializerinstance); var youtubeservice = new youtubeservice(new baseclientservice.initializer { httpclientinitializer = credential, applicationname = applicationname }); i've succeeded in reading necessary information when try insert item playlist return error: error: google.apis.requests.requesterror access forbidden. request may not authorized. [403] errors [ message[access forbidden. request ma

c++ - Why can I have a std::vector<std::ofstream*> but not a std::vector<std::ofstream>? -

i have following test code in have parameter fs container of ofstream s: #include <fstream> #include <vector> #include <cstdlib> #include <cstdio> int main() { // container of ofstream(s) std::vector<std::ofstream> fs; // instantiate ofstream std::ofstream of("myfile.txt"); // push container fs.push_back(of); return 0; } this not compile @ all. whereas when change container of ofstream container of pointers ofstream s, code compiles: #include <fstream> #include <vector> #include <cstdlib> #include <cstdio> int main() { // container of ofstream(s) std::vector<std::ofstream*> fs; // instantiate ofstream std::ofstream * of = new std::ofstream("myfile.txt"); // push container fs.push_back(of); return 0; } why this?

android - Update NavigationView state when user goes back to previous fragment -

i'm using navigationview drawer in app. i'm trying go previous fragment if user press button. code works well: @override public void onbackpressed() { fragmentmanager fm = getsupportfragmentmanager(); fragment fr = fm.findfragmentbyid(r.id.flcontent); if (fm.getbackstackentrycount() > 0 ) { fm.popbackstackimmediate(); } else { finish(); } } but navigationview doesn't change. how can update navigationview state (check correct fragment, change title, , on), can reflect changes in app? you should implement navigation using addtobackstack method. take @ this .

ios - Swift: Is it possible to avoid Facebook SDK 4.x "You have already authorized this app" dialog on login? -

i have implemented facebook sdk in ios app, , can login / logout , display views according fb login success. however, there annoying dialog keeps showing past initial login - "you have authorized app". there way avoid this? this appears on simulator, not on device current implementation.

android - SQLite + Object oriented programming -

creating android financial manager application using of sqlite. question how deal database in terms of object oriented programming? want write information purchase database. should i: 1) user information edittexts, put object "purchase", contains fields: productname, ammount, price... , put information object database? 2) or put data edittexts directly straight database? 3) way? i've used many different frameworks available out there, sqlite ormlite. but, in terms of speed, there no alternative realm.io . can create data models , define them realm objects. rest easy, can read, write , query among data models created. if want know, better way use sqlite, can check this article

java - How to edit a content assist behavior in eclipse -

is there way edit content behavior or there plugin following ... ? i have jsf project the content assistant completes phrases attributes has getters/setters methods @managedbean(name = "mybean") @viewscoped public class viewscopedbean { string name; string age; public viewscopedbean() { } public string method() { return null; } public string getname() { return name; } public void setname(string name) { this.name = name; } } using ctrl+space in <h:commandbutton value="action listener" actionlistener="#{mybean.<ctrl+space>}" /> shows methods , name attribute, there away make show age attribute ?

c++ - error: expected ')' before '*' token in header -

i making program there hero has sword. have class both of those. in header error: expected ')' before '*' token on line sword(hero* h); in header of sword. here compete file (sword.h): #ifndef sword_h #define sword_h #include <hero.h> class sword { public: sword(hero* h); virtual ~sword(); }; #endif // sword_h hero.h in same directory hero.h, , i'm using code::blocks. i've looked through other posts , couldn't find helped, given appreciated. edit: here content of hero.h: #ifndef hero_h #define hero_h #include <string> #include <sdl.h> #include <sdl_image.h> #include <stdio.h> #include <sword.h> #include <sprite.h> #include <window.h> class hero : public sprite { public: hero(window* w); void update(); void event(sdl_event e); ~hero(); protected: private: bool up; bool right; bool left; bool down

python - Using pip with pip-installed mercurial -

so installed mercurial with: pip install mercurial now, when doing: pip install -r requirements.txt i get: > cannot find command 'hg' is there way make pip use c:\python27\scripts\hg.bat hg command? can run typing hg, assumed pip also. i did try using: mklink c:\windows\system32\hg.bat c:\python27\scripts\hg.bat and: mklink c:\windows\system32\hg.exe c:\python27\scripts\hg.bat neither affect. i have looked elsewhere on google, , every answer concerning hg assumes you've either used apt-get or installer mercurial installed. if there way use mercurial available pip, i'm thinking initial setup of windows development environment go quicker. i using windows 7 (32-bit python 2.7.10). thanks in advance help.

How can I generate a file in python with today's date? -

i have seen several post nobody answer question straight point. im creating file in python this: f = open('myfile.extension','w') what should add line add date file generated? im using import time , can current date in other part of script, dont know how add date... thank you assuming trying add date filename datetime import datetime datestring = datetime.strftime(datetime.now(), '%y/%m/%d_%h:%m:%s') f = open('myfile_'+datestring+'.extension', 'w') you can change format like. above print out datestring so: datetime.strftime(datetime.now(), '%y/%m/%d_%h:%m:%s') '2015/08/07_16:07:37' of course since filename may not want have / , recommend format following: datetime.strftime(datetime.now(), '%y-%m-%d-%h-%m-%s') '2015-08-07-16-07-37' here's full run of of above: >>> datetime import datetime >>> datestring = datetime.strftime(datetime.now(), &#

javascript - Unable to remove a class from an element once it has been added -

problem recreatable @ following url : http://streeten-new.streeten.co.uk/ click hamburger open navigation click "services" click "< services" inside submenu try , go back for reason, removeclass not removing 'submenuactive" class. know sure targeting right element, because adding test class works without issue. i have tried using pure javascript instead of jquery this, have tried changing css directly jquery, rather adding/removing class - in cases i'm unable undo changes make element when submenu first opens. it's frustrating because opening dev tools , highlighting <ul class="submenuactive"> then unticking .submenuactive { left: 0!important; } rule hides submenu want work, reason cannot working on click. html code added: <nav> <div class="navigation"> <ul > <li><a href="#">studio</a></li>

javascript - Keeping track and handling multiple Ajax calls -

imagine table 4 accordion tabs hidden on each row. when row clicked/expanded 4 ajax calls fired load data accordion tabs. tab 1 , 2 loads 3 , 4 takes lot longer time. when row expanded, same 4 ajax calls fired. if minimize other row want abort ongoing ajax calls specific row, still load in data new row. i have gotten working when working on 1 row @ time, if have ongoing calls , minimize row , ajax call 3 , 4 not done previous row, calls gets aborted on newly expanded row. simplified code: var openrows = []; var abort = false; var ajax1, ajax2, ajax3, ajax4; $(document).on("click", '.details-control', function (e) { var id = $(this).closest('tr').attr('id'); if ($.inarray(id, openrows) > -1) { openrows.splice(openrows.indexof(id), 1); abort = true; } else { openrows.push(id); abort = false; } if (abort) { console.log("aborting ajax"); if (ajax1 &&

node.js - Cannot get HotModuleReplace plugin with react-hot to be enabled in the browser, though file watching is working -

i'm trying use webpack's hot module replacement plugin. i've managed randomly working, still isn't doing quite hope to. basically, no messages in console it's active, though it's building without issue , file watching working, messages webpack: bundle valid , webpack: bundle invalid when update. webpack , webpack-dev-server , , react-hot installed locally. but in browser's console, thing see is: download react devtools better development experience: https://fb.me/react-devtools i'm using laravel update index file based on environment variable , working fine. here index.php file: <!doctype html> <html> <head> <title></title> </head> <body> <div id="content"></div> @if(env("app_hotreload")) <script src="http://localhost:8080/js/vendor.js"></script> <script src="http://lo

python - How to update my production database in a django/heroku project with a script -

i want update field in users table on django project hosted on heroku. is there way can run script(if where?) using what? that allows me update field in database? manually in django admin take way long there large number of users. any advice appreciated. i suggest update data in local make fixture, commit , push in heroku. load data using terminal update data (locally) make fixture (manage.py dumpdata) commit , push heroku login via terminal (heroku login) load data (heroku run python manage.py loaddata .json)

python - importError: no module named components.panel -

i have folder called python_udl . i've created there empty file called __init__.py , 2 files ui.idl , ui_parser.py . created folder components in same directory , put there __init__.py , panel.py . in end folder structure looks this python_udl\ __init__.py ui.idl ui_parser.py components\ __init__.py panel.py file ui_parser.py parse ui.idl , create object panel.py class. ui_parser.py looks this from bs4 import beautifulsoup components.panel import panel def parse_ui(): file_data = open('ui.idl').read() xml_data = beautifulsoup(file_data, 'html.parser') element in xml_data.find_all('element'): if (element['type'] == 'panel'): make_panel(element.color.get_text(), element.position.get_text()) def make_panel(color, position): p = panel(color, position) print 'formed [' + p.to_string() + '] object '; parse_ui() panel.py lo

Twitter username autocompletion -

i allow users on website nominate other twitter users in text input field. intend provide autocompletion feature similar twitter's mention typeahead when user enters @ in tweet. @jakeharding developed similar functionality in demonstration of typeahead.js . unfortunately, logic hidden in herokuapp. i grateful support can provide. looking @ response typeahead-js-twitter-api-proxy.herokuapp.com it's proxy get users/search . set server takes auto-complete text, wraps in oauth, , forwards twitter api. you'll have mindful of rate limits though. autocomplete burn through in no time.

rspec core Ruby on Rails -

hello i'm testing application rspec: this test file. require 'spec_helper' describe recipescontroller render_views describe "index" before recipe.create!(name: "spaghetti alla carbonara") recipe.create!(name: "spaghetti alle vongole e cozze") recipe.create!(name: "bistecca") recipe.create!(name: "fritto") xhr :get, :index, format: :json, keywords: keywords end subject(:results) { json.parse(response.body) } def extract_name ->(object){ object["name"] } end context 'quando la ricerca riporta dei risultati' let(:keywords) { 'spaghetti' } 'essere 200' expect(response.status).to eq(200) end 'deve ritornare due risultati' expect(results.size).to eq(2) en

ios - Encode with coder not being called on lower level object -

Image
i'm updating existing app follow mvc design. created top level data model class. in datamodel class archive , dearchive children array (self.children). array of child objects items property. items property array of babymilestone objects. both child class , babymilestone class take care of encode/decoding themselves. objects in child class being encoded , decoded. objects in babymilestone class not. encode coder not being called on babymilestone objects being called on child class. question : need special encode array of objects property of else? debugging suggestions welcome! the top level datamodel class handles saving , loading of .plist @implementation datamodel -(id)init { if ((self = [super init])) { [self loadbabymilestones]; } return self; } /////////////loading , saving methods//////////////// //path documentsdirectory loading , saving .plist file of babymilestone objects -(nsstring *)documentsdirectory { nsarray *paths = nssear

game physics - Force, acceleration, and velocity with Javascript -

i attempting make objects move on screen based on force on x-axis , y-axis. seems work when force applied object, when force no longer applied, instead of object continuing @ same velocity , direction, goes off in different direction different velocity. error in section of code? part can think problem. var update = function (modifier) { // rock going up/down wh if(rocks[i].y > 0 && rocks[i].y < worldsizey){ if(rocks[i] != null){ rocks[i].accelerationy = rocks[i].forcey/rocks[i].mass; rocks[i].velocityy += (modifier*1000)*rocks[i].accelerationy; rocks[i].y += (modifier*1000)*rocks[i].velocityy; } } // rock going right/left if(rocks[i].x < worldsizex && rocks[i].x > 0){ if(rocks[i] != null){ rocks[i].accelerationx = rocks[i].forcex/rocks[i].mass; rocks[i].velocityx += (modifier*1000)*rocks[i].accelerationx; rocks[i].x += (modifier*1000)*rocks[i]

php - MYSQL_ATTR_INIT_COMMAND error -

i'm new zend framework , i'm learning how create application following steps in framework.zend webpages. i have problem global.php page. my global.php is: return array( 'db' => array( 'driver' => 'pdo', 'dsn' => 'mysql:dbname=zf2tutorial;host=127.0.0.1;charset=utf8', 'driver_options' => array( pdo::mysql_attr_init_command => "set names 'utf8'" ), ), 'service_manager' => array( 'factories' => array( 'zend\db\adapter\adapter' => 'zend\db\adapter\adapterservicefactory', ), ), ); i'd know instruction pdo::mysql_attr_init_command => "set names 'utf8'" for, because gives me error if run application on localhost:8080. this error: fatal error: undefined class constant 'mysql_attr_init

MongoDB & ElasticSearch configuration -

mongodb showing me error message when insert data in collection. i trying configure elasticsearch mongodb, when realized replica. try add something, no results. mongo shell shows me same message: writresult({"writeerror":{"code":undefined,"errmsg":"not master"}}) this happens when not have 3 node replica set, , start replica in master-slave configuration , after master goes down or secondary goes down. since there not third node or arbiter elect new primary, primary steps down master , in pure read mode. way bring replica set create new server same repl-set name , add current stepped down master secondary it.

php - Set a session variables using twig -

i have question. have route on site put in session variable this: public function usercaptcha(){ $_session['isfacebookregistration'] = 0; } now have route witch render view : public function index(){ $this->session = $_session; return $this->render('template/index.twig'); } in index template : {{ dump(session.isfacebookregistration) }} {% set session = session|merge({'isfacebookregistration' : 3}) %} i access first route : usercaptcha() 1 time route index() 2 times, need see first time 0 , second 3. see 0 2 times. can me please? idea show first time 0 rest 3. thx in advance you cannot set php var on twig side. every time view reloaded, changes made variable lost. can try this: public function usercaptcha(){ $_session['isfacebookregistration'] = 0; } public function index(){ if (isset($_session['flag'])) { $_session['isfacebookregistration'] = 3; } $_session['fla

web services - Unit Test cases for Python Eve Webservices -

we have developed apis using python eve framework . there way can write unit test cases apis have developed in eve . there unit test case component bundled python eve .i need bundle them continuous integration setup. if yes please me steps how proceed it. you start looking @ eve's own test suite . there's 600+ examples in there. there 2 base classes provide lot of utility methods: testminimal , testbase . other test classes inherit either of those. want use testminimal takes care of setting , dropping mongodb connection you. provides stuff assert200 , assert404 etc. in general, use test_client object, flask itself. have @ testing flask applications , eve's running tests page.