Posts

Showing posts from June, 2013

html - Change font in textarea -

i'm trying change font displayed in text area however, don't want use css in <head> tags. possible not use css @ since don't want in head tags? need import styling files? that unnecessary, can edit font using inline css: <textarea style="font-family:calibri"></textarea>

objective c - Network handling in ios Programming -

i new ios programming. now have model 'activity'. activity needs send , receive data server using afnetworking library. there server manager dealing networking methods. my idea create server manager instance when initialise each activity object, , receive data. therefore when need table of activities, have call instance repeatedly when create each activity + (servermanager*) instance { static servermanager *instance = nil; static dispatch_once_t oncetoken = 0; dispatch_once(&oncetoken, ^{ instance = [[servermanager alloc]init]; }); return instance; } it makes sense valid or appropriate repeatedly create server manager instance? or better call instance while loading ui , assigning every data in viewdidload? thank you there multiple ways want do, , depends on situation , amount of data want load. way is: rather extend activity class servermanager class, network methods available in serv

asp.net mvc - Redirect / show view after generated file is dowloaded -

i've got controller action downloads dynamically generated file: public actionresult downloadfile() { var obj = new myclass { mystring = "hello", mybool = true }; var ser = new xmlserializer(typeof(myclass)); var stream = new memorystream(); ser.serialize(stream, obj); stream.position = 0; response.clear(); response.addheader("content-disposition", "attachment; filename=myfile.xml"); response.contenttype = "application/xml"; // write data stream.writeto(response.outputstream); response.end(); return content("downloaded"); } just reference: public class myclass { public string mystring { get; set; } public int myint { get; set; } } this working, , file (myfile.xml) downloaded. however, message "downloaded" not sent browser. similarly, if replace return content("downlo

regex - Bash shell(grep) equivalent of this python regular expression? -

i have written regular expression match hyphenated word in python regexp = r"[a-z]+(?:-[a-z]+)*" it matches words 0 or more hyphens. e.g. abc,acd-def,x-y-y etc. however, can't find grouping operator ?: shell(for instance using grep). seems me feature of python regex not standard regex. can please tell me how write same regex in shell? (?:pattern) matches pattern without capturing contents of match. used following * allow specify 0 or more matches of contents of ( ) without creating capture group. affects result in python if used re.search() , matchobject not contain part (?: ) . in grep, result isn't return in same way, can remove ?: use normal group: grep -e '[a-z]+(-[a-z]+)*' file here i'm using -e switch enable extended regular expression support. output each line matching pattern - can add -o switch print matching parts. as mentioned in comments (thanks), is possible use back-references (like \1 ) grep refer previous c

php - Getting error (500 / 503) in heroku app, using laravel 5.1 and angularjs with GET/POST method -

i'm trying put webapp online using heroku. everything gone fine, until get/post method request. returns 500 or 503 error. when locally, works. when send request in heroku, doesn't. [obs.: i'm trying request postman too... same error!] is kind of permission, maybe? cross-domain request? i don't know much... 2015-07-23t18:58:33.476410+00:00 app[web.1]: 10.123.198.169 - - [23/jul/2015:18:57:48 +0000] "get /backend/public/index.php/api/excel http/1.1" 200 146079 "http://heinz.herokuapp.com/public/" "mozilla/5.0 (x11; linux x86_64) applewebkit/537.36 (khtml, gecko) chrome/44.0.2403.89 safari/537.36 2015-07-23t19:00:35.115264+00:00 heroku[router]: at=info method=get path="/backend/public/index.php/api/txt" host=heinz.herokuapp.com request_id=334dfd15-e371-4e2b-a455-9feabd33fc42 fwd="200.9.124.34" dyno=web.1 connect=2ms service=51ms status=500 bytes=4784 2015-07-23t19:00:35.107136+00:00 app[web.1]: 10.69.166.135 - -

c# - Error on the query string SQL -

im getting following error: "a first chance exception of type 'system.data.sqlclient.sqlexception' occurred in system.data.dll additional information: incorrect syntax near ')'. if there handler exception, program may safely continued." is syntax? cant figure out, can tell doing wrong? private void button2_click(object sender, eventargs e) { messagebox.show("a atualizar dados..."); bool check = true; { string connectionstring = @"data source=.\wintouch;initial catalog=bbl;user id=sa;password=pa$$w0rd"; string querystring = string.empty; using (sqlconnection connection = new sqlconnection(connectionstring)) { connection.open(); querystring = "update wgcdoccab set merc1 = merc1/2 numdoc = (select max(numdoc) wgcdoccab serie ='1' , tipodoc ='fss' , contribuinte ='999999990'

c - MSP430 Ram Overflow -

the msp430g2553 has 512 bytes of ram 16kb of flash memory. on microcontroller, static/global variables assigned in ram under .bss section. local variables assigned in ram under .stack section. dynamically allocated memory variables (malloc) assigned in ram under .sysmem section. i have need msp430 keep track of connected devices via wifi. have struct such: struct dev { char type[20]; char ipaddress[13]; char name[20]; char status[1]; }; this struct takes 54 bytes of memory each device. planning on having 20+ devices connected msp430 , need have 20 of these structs. 20 x 54 bytes = 1080 bytes. big 512 bytes of ram. is there way write these structs flash since have 16kb of memory use? understanding of flash variables read-only. these structs getting assigned read-write , not sure if possible. i don't quite understand why ti make device has 16 kb flash , 512 bytes of ram, when variables requiring read-write operations stored in ram. seems wast

timer that runs 2 of every 3 seconds c# -

is there way run program every 2 of 3 seconds? know can make timers run every n milliseconds, not every n of m seconds. basic example, pretend want have 2 functions both add integer value. 1 function run 2 of every 3 seconds , add 5 value. second function add 100 same value, run 1 second other 1 doesn't run. make sense? the simplest way keep internal representation of second on , switch based on different execution. private int counter = 0; private int whichsecond = 0; void runseverysecond() { if (whichsecond < 2) { counter += 5; whichsecond++; } else { counter += 100; whichsecond = 0; } }

“Unable to connect to gear” in scaled openshift app -

i'm having php-5.4 scaled app mysql-5.5. since it's scaled app mysql placed on separate gear app instances. since around 03/08/2015 i'm unable connect mysql gear, nor application. i've been trying following: restart apps , deps ctl_all. $ rhc ssh --gears -a loot ctl_all restart unable connect gear 556c74555973caffa300022c@556c74555973caffa300022c-honourforever.rhcloud.com (...) ssh connection mysql gear. $ ssh -vvv 556c74555973caffa300022c@556c74555973caffa300022c-honourforever.rhcloud.com openssh_6.6.1, openssl 1.0.1m 19 mar 2015 debug2: ssh_connect: needpriv 0 debug1: connecting 556c74555973caffa300022c-honourforever.rhcloud.com [54.166.94.12] port 22. debug1: connect address 54.166.94.12 port 22: attempt connect timed out without establishing connection ssh: connect host 556c74555973caffa300022c-honourforever.rhcloud.com port 22: bad file number check gear storage used percentage. $ rhc show-app loot --gear quota unable co

List all index columns (including filtered ones) in SQL Server -

how index columns including filtered columns? if object_id('dbo.ttestindex') not null drop table dbo.ttestindex; create table dbo.ttestindex (a int, b int, c int); create index x_ttestindex on dbo.ttestindex (a) include (b) c > 0; select i.name, i.filter_definition, c.name, ic.is_included_column sys.indexes inner join sys.index_columns ic on i.object_id = ic.object_id , i.index_id = ic.index_id left join sys.columns c on ic.object_id = c.object_id , ic.column_id = c.column_id i.object_id = object_id('dbo.ttestindex'); if object_id('dbo.ttestindex') not null drop table dbo.ttestindex; this example gives 2 rows instead of three. index_name | filter_definition | column_name | is_included_column -------------+-------------------+-------------+------------------- x_ttestindex | ([c]>(0)) | | 0 x_ttestindex | ([c]>(0)) | b | 1 you can use catalog view sys.sql_expression_dependencies find ou

ssh - error opening a port in Google Compute Engine -

i trying open port via ssh in vm instance in google compute engine keep getting error messages. here command: myname@instance-2:~$ gcloud compute firewall-rules create baasbox-console-port --allow tcp:9000 --source-range s=0.0.0.0/0 here error message: name network src_ranges rules src_tags target_tags error: (gcloud.compute.firewall-rules.create) requests did not succeed: - insufficient permission pls doing wrong? gcloud auth login go following link in browser: (cut , past link browser address bar) me (ubuntu 14.04) not return verification code on firefox, use chromium. should long string of characters verification code. cut , past terminal. see this: error: there problem web authentication.error: (gcloud.auth.login) invalid_grant after several tries of generating code , pasting it, copied code , trailing colon(:) worked

plugins - Adding library dependency in play 2.3.8 -

Image
i'm trying add apache commons email library play project , i'm having trouble. firstly have both build.sbt , plugins.sbt in project , i'm not sure 1 should putting import into, know? also, i'm not sure why there separate project module in project, intellij created part of project. explain purpose of 2 separate modules , why there? thanks! so, in sbt, have project. specified in build.sbt (or more correctly, *.sbt file in projects base directory). libraries applications code needs, example, if application needs send emails using commons email library, go in librardependencies seeing in here. but build.sbt scala code needs compiled, it's not part of applications runtime. in sbt, projects build project itself, 1 has compiled. has own classpath, consists of sbt plugins you're using, example, if need less compiler compile less files, that's not gets done @ runtime, don't want application code depending on that, goes project builds libr

javascript - parseFloat returns NaN -

i'm trying rid of currency sign in order calculate new price using parsefloat, returns nan reason. var priceperuser = "£19.99"; priceperuser = parsefloat(priceperuser) * 3; console.log(priceperuser); //returns nan parsefloat() work on string until finds non-numeric value. £ first character, hence there no number parse. need remove before call parsefloat() : var priceperuser = "£19.99"; priceperuser = parsefloat(priceperuser.replace('£', '')) * 3; console.log(priceperuser); if require 2dp precision, use tofixed(2) : console.log(priceperuser.tofixed(2));

android - AsyncTask doInBackground returns too soon -

i have asynctask connecting websocket. protected void doinbackground() { client.connect(); return null; } when it's finished attempting connection, want following happen (currently inside onpostexecute ): protected void onpostexecute() { if (socketconnected) { dootherthings(); } else { log("failed connect."); } i've tossed in following, probe of sorts (in websocketclient implementation): public void onopen() { log("opened successfully!"); socketconnected = true; } the onpostexecute method prints failure message , followed success message onopen . suggests doinbackground returning soon. there common reason might happen? yes, method client.connect() creates asynctask , leaves task continue executation, ending method , going onpostexecute. if thats case, api using should have methods listening async messages. api should have listener or callback fired @ thread. edit: searched webviewclient on internet , me

html - Button get disappeared in IE 9 while using disabled prop -

<button type="button" id="update">submit</button> <button type="button" id="updated">update</button> $("#updated").click(function(){ $("#update").prop('disabled',true); }) hi, i want disabled button,when using above works fine browser,except versions of ie ie 9,in ie 9 button disappeared when using above code. can me why happen. thanks, nandkishor

sql - Update query in Postgresql -

i have 2 tables in postgresql. 1 satetable having column statename , statecode , disttable having columns distname, statename , statecode. in disttable columns distname , statename populated. want update 'statecode' column in disttable. kindly help. create table statetable (statename varchar, statecode varchar); create table disttable (distname varchar, statename varchar, statecode varchar); insert statetable values ('new york','ny'), ('nebraska','nb'), ('alaska','al'); insert disttable values ('king','new york', null), ('salt lake','nebraska', null), ('hanlulu','al', null); corrcet me if wrong, think model should be: create table statetable (statename varchar, statecode varchar); create table disttable (distname varchar, statecode varchar); insert statetable values ('new york','ny'), ('nebraska','

forms - Delphi: Make the window draggable from a component -

i have custom form (custom shape , transparency) no borders ( borderstyle: bsnone ). has background image, normal timage component. want form draggable timage. possible? i'm using lazarus 1.2.6 (fpc ver.: 2.6.4). this custom form looks on empty desktop: image . here cross-platform solution: type tform1 = class(tform) image1: timage; procedure image1mousedown(sender: tobject; button: tmousebutton; shift: tshiftstate; x, y: integer); procedure image1mousemove(sender: tobject; shift: tshiftstate; x, y: integer); procedure image1mouseup(sender: tobject; button: tmousebutton; shift: tshiftstate; x, y: integer); var px, py: integer; mouseisdown: boolean; procedure tform1.image1mousedown(sender: tobject; button: tmousebutton; shift: tshiftstate; x, y: integer); begin if button = mbleft begin mouseisdown := true; px := x; py := y; end; end; procedure tform1.image1mousemove(sender: tobject; shift: tshiftstate; x,

ios - How to conditionally conform to delegate protocol? -

if including frameworks in ios project available in (for example) ios 9, still supporting ios 8, how conditionally conform delegate protocol depending on ios version? example, understand can include framework conditionally this: #import <availability.h> #ifdef __iphone_9_0 #import <something/something.h> #endif but if framework needs conform delegate protocol? @interface examplecontroller () <uitextviewdelegate, somethingdelegate> how include "somethingdelegate" if i'm on ios 9? thanks! well, in same manner: @interface examplecontroller () <uitextviewdelegate #ifdef __iphone_9_0 , somethingdelegate #endif > by way, not way should check if device running ios 9 - this checks if xcode supports ios 9 .

java - FatJar Temp Directory -

i have native dll(c++) in project. i'm using eclipse fatjar plugin create fatjar. native dll dependent other native dlls "libopencv_core247". know fatjar creating temp folder load dependent libraries folder. if can find set java library path folder. i can load library , i'm getting can not find dependent libraries error.

c++ - When I link two header files together, one does not recognize the other -

i'm making board game using c++ involves multiple classes. when include header file of piece.h in board.h , of piece's members being recognized board. when simultaneously link board.h piece.h , members of board not being recognized. here how linking them: -in piece.h #ifndef piece_h_ #define piece_h_ #include <iostream> #include "board.h" -in board.h #ifndef board_h_ #define board_h_ #include<iostream> #include "piece.h" i declared multiple piece members of board , piece type parameters of board functions, , work fine. yet declaring void function within piece takes board parameters, such: void horizontal (board b); void vertical (board b); void diagonal (board b); results in error saying "board has not been declared" including file tells preprocessor "copy file's content here". if both headers refer each other, have circu

sql - How to find Negative maximum and positive minimum in Oracle? -

i have column of type number . has both positive , negative values. need 4 values : positive maximum,positive minimum, negative maximum,negative minimum: a)to positive maximum : can use check out fiddle select max(cola) test; b)to negative minimum: can use check out fiddle select min(cola) test; i have 2 question here: 1)now i'm not sure how other 2 values. guide me that 2)meanwhile while trying got doubt. when have column of type varchar2 , has numbers value. i'm performing above operation in column. positive maximum same above. negative minimum quiet weird. check fiddle here .why there no proper implicit conversion taking place here. pls explain reason behind this? for question 1, can use case determine values min/max on. e.g.: select max(case when cola >= 0 cola end) max_positive, min(case when cola >= 0 cola end) min_positive, max(case when cola < 0 cola end) max_negative, min(case when cola < 0 cola end) min_n

java - How can I have a hashmap of form params coming in curl request in my jersey servlet? -

i making curl request like: curl -i -x post -d "debit_user_id=/customer/mobile_number:917827448775&recipient_id=/customer/mobile_number:9988776655/recipients/mobile_number:917526337452&pintwin=1234&amount=5000&currency=inr&customer_id=/customer/mobile_number:9988776655&agent_id=/agents/mobile_number:919987536699" http://localhost:8080/switch/apikongcall.do/transactions and getting these parameters in jersey servlet like: @post //@path("/transactions") @consumes("application/x-www-form-urlencoded") public void initiateposttransaction(@formparam("debit_user_id") string debit_user_id, @formparam("recipient_id") string recipient_id, @formparam("pintwin") string pintwin, @formparam("amount") string amount, @formparam("currency") string currency, @formparam("customer_id") string customer_id, @formparam("agent_id"

c++ - Creating a shared library with a global variable -

this question asked in g++ compiler context under windows. let's want create shared library, mylibrary.dll. mylibrary.h: #ifndef _mylibrary_h #define _mylibrary_h #ifdef mylibrary_dll_export #define mylibrary_api __declspec(dllexport) #else #define mylibrary_api __declspec(dllimport) #endif class mylibrary_api xyz{ public: double x; }; mylibrary_api extern xyz xyz; // correct, want declare, hence "extern" #endif mylibrary.cpp: #include "mylibrary.h" xyz xyz; // definition of xyz i compile 2 files, mylibrary.dll libmylibrary.a now, lets want use variable xyz in program link against import library (i.e. -lmylibrary), , include header mylibrary.h of course. i seem getting undefined reference when compile. undefined reference `__imp__zn2vx6................ how define "global" variable in shared library, i.e. variable exists in 1 copy , can shared among threads? edit: i turned out reason had declared variable xyz ins

ubuntu - Symlinks in shared folder of virtual box with Windows 10 host -

i running linux (ubuntu) system within virtual box container. used symlinks in shared directory, needed work described here: https://www.virtualbox.org/ticket/10085 this worked requirements running windows 8 host. now, switched windows 10 , symlinks not work more. still able create symlinks, correct path cannot resolved. using readlink, can see created symlink wrong. if create symlink with ln -s /media/data/jquery.js /media/data/test.js the returned value readlink is \media\data\jquery.js obviously, directory separator incorrect. if create symlink outside shared directory (to same file on shared directory), path correct. does have idea how fix incorrect directory separator? mathias

How is Google Analytics Measurement Protocol different? -

i checking ga measurement protocol send data ga backend.which working fine.url using is: https://www.google-analytics.com/collect?tid=ua-xxxxxxx-1&v=1&cid=9350&dp=home&t=pageview (please replace ua-xxxxxxx-1 own tracking id.) now have website ga enabled using javascript way.i checked in chrome inspect sends information google through url: https://stats.g.doubleclick.net/__utm.gif?utmwv=5.6.5dc&utms=4&utmn=1588741400&............ i can use url send information google backend. what's special , new in measurement protocol because using url can send data google analytics purposes? i need send data backend ga please guide. the measurement protocol "backbone" data collection universal analytics versions (web, mobile etc). unlike gif-method documented , can called every device/programming language can send http requests (it still return transparent gif, though). the main reason using measurement protocol else deprecated

Issue with date funciton in PHP -

this question has answer here: convert 1 date format in php 12 answers i have 1 issue date function below have put code. please check. have used jquery calender in joomla component echo $data['startpublish']; $data['startpublish'] = date('y-m-d', strtotime($data['startpublish'])); echo "?>>>>>>>>>>>".$data['startpublish']; exit; i have store date mm-dd-yy format. when store 01-02-2015 store data in db in (y-m-d) format , when store 01-28-2015 (28 janvary) convert 1970-01-01. please let me know issue . have added both screenshot well. issue ss : http://prntscr.com/812w0c correct ss : http://prntscr.com/812xbj this strtotime quirk text date representation , american illogical way of saying/writing dates used in conversion having either - or / or .

vb.net - Calling a windows forms application file in vb from a c++ project -

i have windows forms application file extracts data text file , stores in suitable variable lists. list needs accessed project file of mine in visual c++ . can done or need write 1 of codes again in same language? say form1 has list variable product of type string needs accessed project file software written in visual studio's c++ language code. want access product in software further usage. you should able add vb project reference of c++/cli project , classes should available use in c++/cli code. (right click on c++ project, select add, add references , projects).

python - ImportError: no module named urls but ROOT_URLCONF is correct -

i've read through similar questions find on google/so, , people had issue root_urlconf being incorrect or missing init .py. my project structure is djangotut/ polls/ static/ templates/ __init__.py manage.py settings.py urls.py my project called djangotut, , there's group level called user_myusername_xyz (my place of work has prefab code use project setup, , i've done many times without running problem). i've tried root_urlconf = 'user_myusername_xyz.djangotut.urls' (this our projects' settings.py files default to) root_urlconf = 'djangotut.urls' and root_urlconf = 'urls' i importerror every time, , know it's line because exceptionvalue changes string used there. (ex: "no module named user_myusername_xyz.djangotut.urls"). the urls.py file there, why can't settings.py see it? urls.py from django.conf.urls import include, patterns, url django.contrib import admin admin.a

rest - Stormpath API blocks user on attempt of login once or verify repeatedly(on refresh)? -

i using stormpath's api stores user details accessing application(backbone/require.js project).i integrated rest api(running on jetty server) stormapth's api valid user credential.on validating user credential(once or repeatedly).it seems stormpath not respone particular user within short span of time , server response connection refused or timeout.is there chance stormpath block user few hours on validating repeatedly. i work @ stormpath at moment not offer account locking feature, though on our roadmap future. in meantime, suggest storing timestamp or history of login attempts in account's custom data. on each login attempt application can @ custom data , make decision block user if they've tried many times. hope helps!

c# - Call to sybase stored procedure doesn't always return correct number of rows when using the data -

Image
i'm having simple application calling stored procedure in sybase using odbcconnection. think working inconsistent , can't tell why. after calling stored procedure put in list> , make result xml , save on disc. when running application , calling same stored procedure different results every once , while. stored procedure simple , should return 1800 rows. sp: select column1 ,column2 database..table call database: public list<dictionary<string, object>> getdatafromdb(string dbconnection, string sp) { var result = new list<dictionary<string, object>>(); using (var con = new odbcconnection(dbconnection)) { con.open(); using (var cmd = con.createcommand()) { cmd.commandtype = commandtype.storedprocedure; cmd.commandtext = sp; cmd.commandtimeout = 15; var reader = cmd.executereader(); result =

c# - How do I gain access to a repository in a custom ValidationAttribute? -

public class uniquenameattribute : validationattribute { private const string uniquenameviolationmessage = "this name taken. please select another."; protected override validationresult isvalid(object value, validationcontext validationcontext) { //return somerepo.isuniquename(name) //how access repo here? tried di autofac came out null } } i'm using dependency injection inject repositories web api. however, seems cannot inject validationattribute. comes out null if try inject. i'm using autofac di. there way can gain access repo? note using web api, not mvc, cannot use mvc dependencyresolver. builder.registertype<myrepository>().as<imyrepository>().instanceperrequest(); var container = builder.build(); globalconfiguration.configuration.dependencyresolver = new autofacwebapidependencyresolver((icontainer)container); ;

sql - "How do I use a variable in plpgpsql in a where clause?" -

i have function created in plpgsql. function has cursor called cursor_ , while fetch values of cursor, query performed inside loop. query uses condition data cursor. problem variable name_var empty when function perform query, in spite of changes values retrieved cursor. doign wrong?. here code: create or replace function fn_return_company_centers() returns table(company text, centers text) $body$ declare cursor_ cursor select c.name, m.location || '__' || m.storagekey center company c inner join monitor m on c.id = m.company_id order c.name; v_parent_rec record; name_var text :=''; _centros text := ''; pos int := 0; begin create temporary table if not exists tmp_company_center (company text, centers text); delete tmp_company_center; v_parent_rec in cursor_ loop if name_var = '' name_var := v_parent_rec.name; select a.centros _centros scheduler_

tsql - T-SQL Set (assign) Function Result in SELECT -

i need know how set return value function can used again in same query. the problem: select a.field1, a.field2, [thefunction](id,3.4,'test') sumofaverages, [thefunction2]([thefunction](id,3.4,'test'), 1,2)) summary ... you can see putting in function again in function2 parameter, set variable not need this. i have tried doing [thefunction](id,3.4,'test') sumofaverages, [thefunction2](sumofaverages, 1,2)) summary i don't mind doing in outer select not want join on inner select have fields acquire results. i appreciate help thanks you should able shifting first function separate select clause. typical ways achieve use cte, subquery, or apply . like: select a.field1, a.field2, t.sumofaverages, [thefunction2](t.sumofaverages, 1,2)) summary <existing tables> cross apply (select thefunction(id,3.4,'test') sumofaverages) t the reason within each select clause, system meant able evaluate column expressions in parall

c++11 - C++ Weird behavior on vector of pair containing reference -

i've found weird, check out code: #include <cstring> #include <cstdio> #include <utility> #include <vector> using namespace std; class { public: int n = 0; a(const char* p) { n = strlen(p); }; a(a const&) = delete; void operator=(a const&) = delete; }; void f(vector<pair<const char*, const a&>> v) { printf("f\n"); for(vector<pair<const char*, const a&>>::iterator = v.begin();it!=v.end();++it) printf(" '%s': %p %i\n", it->first, &it->second, it->second.n); }; int main(int, char**) { f({ { "a", "a" }, { "b", "bb" }, { "c", "ccc" }, { "d", "dddd" } }); }; now compile clang++ -std=c++11 -wall -wextra -wpedantic -o0 main.cc -o main , or similar (with optimization disabled). and should see output this:

multithreading - Need help on producer and consumer thread in python -

i wanted create consumer , producer thread in python simultaneously, producer thread append queue , consumer thread retrieves item stored in queue. , need start consumer thread along producer. consumer thread should wait till queue gets item. , should terminate when there no item in queue. new python, please on this. requirements: if there list of 10 numbers, producer thread should insert queue 1 item, , consumer thread should retrieve number. both thread should start simultaneously . from queue import queue import threading import time class producer(threading.thread): def __init__(self, list_of_numbers): threading.thread.__init__(self) self.list_items = list_of_numbers def run(self): in self.list_items: queue.put(str(i)) class consumer(threading.thread): def __init__(self): threading.thread.__init__(self) def run(self): while queue.not_empty: queue_ret = queue.get() print(&quo

haskell - Is it usual for interaction nets to leave piles of redundant fans? -

Image
i'm compiling lambda calculus terms interaction nets in order evaluate them using lamping's abstract algorithm. in order test implementation, used church-number division function: div = (λ b c d . (b (λ e . (e d)) (a (b (λ e f g . (e (λ h . (f h g)))) (λ e . e) (λ e f . (f (c e)))) (b (λ e f . e) (λ e . e) (λ e . e))))) dividing 4 4 (that is, (λ k . (div k k)) (λ f x . (f (f (f (f x))))) ), net: (sorry awful rendering. λ lambda, r root, d fan, e eraser.) reading term back, church number 1, expected. net inflated: has lot of fans , erasers serve no obvious purpose. dividing bigger numbers worse. here div 32 32 : this again reads one , here can see longer tail of redundant fan nodes. question is: is expected behavior of interaction needs when reducing particular term or possible bug on implementation ? if isn't bug, there way around that? yes, usual (but there techniques lessen presence) abstracting details of implementation interaction nets,

python - Django ORM Query - How to Subtract Time From Model Field? -

i have query returns max time model field. results = mymodel.objects.filter( id=pk, date__range=(start_time, end_time) ).values('my_id' ).annotate(max_time=max('my_date_time')) to point, works great. need subtract time (60 min) my_date_time field. the convenient me if can somehow subtract time directly in html template. filters available that? if not, there way use mysql subtime() function or python timedelta query? suggestions , feedback appreciated! if there similar asked/answered question, somehow missed , apologize! edit: yes, my_date_time field valid datetime model field. from datetime import timedelta results = mymodel.objects.filter( id=pk, date__range=(start_time, end_time) ).values('my_id' ).annotate(max_time=max('my_date_time')) result in results: result['max_time'] -= t

html - Select the last element in multiple containers with variable levels of nested children -

how can select last , deepest element in css? is there way improve css code? what solution proposed deep tree? (~15-25). i'm avoiding using javascript. sass solutions welcome.(maybe using @for?) /*level 1*/ div.case > ul:last-child > li.leaf:last-child > div { font-weight: bold; background: red; } /*level 2*/ div.case > ul:last-child > li.expanded:last-child > ul > li.leaf:last-child { font-weight: bold; background: blue; } /*level 3*/ div.case > ul:last-child > li.expanded:last-child > ul > li.expanded:last-child > ul > li.leaf:last-child { font-weight: bold; background: green; } /*level 4*/ div.case > ul:last-child > li.expanded:last-child > ul > li.expanded:last-child > ul > li.expanded:last-child > ul > li.leaf:last-child { font-weight: bold; background: yellow; } <div class="case"> <h1>case 0</h1> <ul> <li

how do i determine oracle database name of data source -

i've been searching around , haven't found on scenario understand: i have list of of oracle databases , corresponding servers company owns (about 80 servers 150 databases ). trying figure out 1 specific file being downloaded (from webpage). i mechanical engineer, not in software if eli5 helpful. specifically need sid name, figuring out server name helpful. your question kind of tricky here. if downloading file web application(i assuming java webapp), oracle database act either data store or report server can generate oracle reports directly in first case, need find out if kind of file downloading? pdf? excel file? or text file or anything? best idea check out file link , decide software generating file. software in end generate file like, poi(for generating excel file), or direct file link, not oracle @ all. also, in case, file generated @ backend server-let. need ask developer report or file generating engine employing. , if oracle database being u

c# - Directory.EnumerateFiles exception -

i have rare behaviour. i'm using windows 10 x64 , visual studio 2013 , when run code in 32 bits application directory.enumeratefiles(@"c:\windows\system32\winevt").count() i have exception of type system.io.directorynotfoundexception if open non admin cmd console , run dir c:\windows\system32\winevt the result list of folders in winevt folder. folder exists , has sub folders. any idea? thank you in x64 version - access system32 redirected c:\windows\systemwow64. try use variant access it: directory.enumeratefiles(@"c:\windows\sysnative\winevt").count()

What is the difference between access tokens and profiles in android facebook sdk? -

i developing android app make use of facebook login. can use 2 classes access user information. profile , accesstoken . difference between these? profile used store basic user information [ https://developers.facebook.com/docs/reference/android/current/class/profile/] access tokens give authority access information [ https://developers.facebook.com/docs/facebook-login/access-tokens] so basically, cannot read profile information without access token, , it's best monitor token using accesstokentracker, lets know when user changes access state. [ https://developers.facebook.com/docs/reference/android/current/class/accesstokentracker/]

Stretch and fill middle Layout Android -

Image
i have main relative layout(height,width=fill parent) has 3 layouts inside it: 1st: frame layout(width=fill_parent/height=wrap_content) 2nd: linear layout(width=fill_parent/height=wrap_content/layoutbelow 1st) 3rd: relative layout(height=wrap_content/width=fill parent/layout_alignparentbottom="true"/ layoutbelow 2nd) i want 3rd layout @ bottom of screen , 1st @ top of screen , 2nd fill space in between. how do this? followed link: android linearlayout fill-the-middle , tried setting layout_height="0px" , layout_weight="1" did not work. can please me this? thanks try : 1st: frame layout(width=fill_parent/height=wrap_content) 2nd: linear layout(width=fill_parent/height=wrap_content/layoutbelow 1st/layoutabove 3rd) 3rd: relative layout(height=wrap_content/width=fill parent/layout_alignparentbottom="true") for example : <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app=

javascript - Fixed Toggle Menu in One Page Website Issue -

how can stop menu items sliding in front of menu bar? menu items shouldn't sliding in front of menu bar, should drop down, or slide on back... doing wrong? thanks. here's fiddle js //------this slides menu contet down ------: $(document).ready(function(){ $("#menu-button").click(function(){ $("#menu-items").slidetoggle("slow"); }); //----this brings menu content when item clicked -----: $('#menu-items li a').on("click", function(){ $('#menu-items').slideup(); }); }); //----this adds smooth scrolling , negative space header compensation ----: $(document).ready(function () { $(window).scroll(function () { var y = $(this).scrolltop(); $('.link').each(function (event) { if (y >= $($(this).attr('href')).offset().top - 75) { $('.link').not(this).removeclass('active'); $(this).addclass('acti

roles - Wordpress - restrict access to certain post types -

i have wordpress site client wants set couple of users on, purely creating, editing , deleting blogs. want assign these users 'author' role , when log admin area, want them see post type 'posts'. not want them have access media or other custom post types. have ideas on please? user role editor plugin ( https://wordpress.org/plugins/user-role-editor/ ) has served me in cases that. as description says: user role editor wordpress plugin makes user roles , capabilities changing easy. edit/add/delete wordpress user roles , capabilities.

polymer - autofocus paper-input in a paper-dialog works only once? -

<paper-dialog> <h2>rename</h2> <div> <paper-input autofocus></paper-input> </div> <div class="buttons"> <paper-button dialog-dismiss>cancel</paper-button> <paper-button dialog-confirm on-click="_confirm">rename</paper-button> </div> </paper-dialog> this paper-dialog triggers autofocus on it's paper-input first time open it. how can trigger focus every time open dialog? to fix autofocusing on dialogs, had use event listener , manually focus element. for example: window.addeventlistener('iron-overlay-opened', function(event) { // grab autofocus input var input = event.target.queryselector('[autofocus]'); // switch because require special treatment switch(input.tagname.tolowercase()) { case 'input': input.focus(); break; case 'paper-textarea': ca

R and leaflet plot an incorrect circle radius? -

here's code: library(leaflet) library(geosphere) startloc <- c(-100, 45) #long/lat endloc <- c(-100, 42) #long/lat totaldist <- disthaversine(startloc, endloc) leaflet() %>% addtiles() %>% # add default openstreetmap map tiles addmarkers(lng=c(startloc[1],endloc[1]), lat=c(startloc[2], endloc[2]), popup = paste(totaldist)) %>% addcircles(lng = endloc[1], lat = endloc[2], radius = totaldist) as can see, top point not included in circle. think it's because "add circles" doesn't account curvature of earth? correct? if use 2 points closer together, better... this because web mercator not distance-preserving projection. leaflet drawing geometric circle on map, not finding points equidistant center. projection stretches distances go north, northern point outside geometric circle. if try startloc <- c(-103, 42) #long/lat endloc <- c(-100, 42) #long/lat then left-hand point on circle; if reverse original point

javascript - Facebook share not working in mobile fancybox -

updating issue: we have facebook share feature appears on page , in fancybox. desktop: works on both page , fancybox. mobile: when on page, opens fb popup unusable - e.g. has "login facebook" text no clickable button. when on fancy box (i.e. there popup), clicking share link nothing. thanks in advance ideas , help. <?php if ($this->is_facebook && $this->oauth_fb_key) { ?> <meta property="fb:app_id" content="<?php echo $this->oauth_fb_key; ?>"/> <meta property="og:site_name" content="<?php echo $this->site_name; ?>"/> <meta property="og:url" content="<?php echo $this->item['url']; ?>"/> <meta property="og:title" content="<?php echo $this->item['title']; ?>"/> <meta property="og:description" content="<?php echo $this->item['description'

node.js - Parameter in request of Elasticsearch using NodeJS -

can passe parameter in request ? query :p client.search({ index: 'name_index', type: 'name_type', body: { query: { filtered: { query: { query_string: { query: p , analyze_wildcard: true } } } .... } } help appreciated thank you

android - How to make Range_Seek_bar move in steps (not smooth) -

Image
i try library : https://github.com/anothem/android-range-seek-bar repository : compile 'com.yahoo.mobile.client.android.util.rangeseekbar:rangeseekbar-library:0.1.0' and need make seek bar move in steps library doesn't support steps movement there solution, or other libs issue this lib xml : <com.yahoo.mobile.client.android.util.rangeseekbar.rangeseekbar android:id="@+id/well_range" android:layout_width="match_parent" android:layout_height="wrap_content" rsb:paddingend="10dp" android:layout_margintop="22dp" rsb:activecolor="#a96b21" rsb:absoluteminvalue="0" rsb:absolutemaxvalue="10" rsb:alwaysactive="true" rsb:showlabels="false

Artifactory - ?trace finds artifact, gradle does not -

ughh, saga continues (my post yesterday - gradle not resolve dependency artifactory ). worked out solution (i'm still using hard-coded versions). but when gradle clean build project dependency on artifact in artifactory gradle fails find it. errors with: * went wrong: not resolve dependencies configuration ':compile'. > not find apircommon.jar (au.com.apir:apircommon:1.0). searched in following locations: http://devsvr:8090/artifactory/libs-release/au/com/apir/apircommon/1.0/apircommon-1.0.jar i can hit location browser or curl download artifact or have trace on it: http://devsrv/artifactory/libs-release/au/com/apir/apircommon/1.0/apircommon-1.0.jar?trace request id: 31810f1c repo path id: libs-release:au/com/apir/apircommon/1.0/apircommon-1.0.jar method name: user: admin time: 2015-07-24t11:07:22.236+10:00 thread: http-bio-8090-exec-21 steps: 2015-07-24t11:07:22.236+10:00 received request 2015-07-24t11:07:22.236+10:00 request source = 203.a.b.c

ios - AVAssetWriterInput appendSampleBuffer crashing -

i have audiowriterbuffer appending audio sample buffers follows func captureoutput(captureoutput: avcaptureoutput!, didoutputsamplebuffer samplebuffer: cmsamplebuffer!, fromconnection connection: avcaptureconnection!) { if cmsamplebufferdataisready(samplebuffer) <= 0 { return } if captureoutput == audiooutput && audiowriterbuffer != nil && audiowriterbuffer.readyformoremediadata == true { var audiotime = cmsamplebuffergetpresentationtimestamp(samplebuffer) audiowriterbuffer.appendsamplebuffer(samplebuffer) } } it works supposed to. every once in while, crashes following error: nsarray mutated while being enumerated. at: audiowriterbuffer.appendsamplebuffer(samplebuffer) i don't understand relevance of that, or how solve it. any clue?

c++ - Cause of unknown type name and undeclared identifier errors? -

i have header file that's linked others in project of mine. here code in file that's giving me error: #ifndef relation_h_ #define relation_h_ #include <set> #include <string> #include "scheme.h" #include "tuple.h" class relation { public: void select(); void project(); void rename(); private: std:string name; scheme scheme; std::set<tuple> tuples; }; #endif /* relation_h_ */ when compile, error follows: ./relation.h:25:2: error: unknown type name 'std' std:string name; ^ ./relation.h:25:6: error: use of undeclared identifier 'string' std:string name; i have checked circular dependencies (the 2 files included here have no other files included in them) , can see <string> class included. no errors occur std::set . might causing problem? update: measure, isolated file , 5 associated (the .cpp , 2 pairs included) , compiled. got same error.

Rutime calculation in mysql -

i hope fine , learning more. need advice on update statement populate 1 column on run table. using mysql 5.6.25-. please find below table , data scripts. create table test (symbol varchar(2), sym_date date, amount int, diff_amt int primary key (symbol,sym_date)) engine=innodb; insert test(symbol,sym_date, amount) values('a','2015-07-01',200); insert test(symbol,sym_date, amount) values('a','2015-07-02',100); insert test(symbol,sym_date, amount) values('a','2015-07-03',500); insert test(symbol,sym_date, amount) values('a','2015-07-04',800); insert test(symbol,sym_date, amount) values('b','2015-07-03',300); insert test(symbol,sym_date, amount) values('b','2015-07-05',500); insert test(symbol,sym_date, amount) values('b','2015-07-06',600); insert test(symbol,sym_date, amount) values('c','2015-07-09',100); insert test(symbol,sym_date, amount) values('c&