Posts

Showing posts from August, 2013

ember.js - computed property to collect hasMany data -

a route hasmany departuredates . i'd create computed property collects value attribute of departuredates , returns string comma separates them , adds end date (which departuredate.value + route.duration ) of each. examples: "01.01.2015 - 05.01.2015" "02.03.2016 - 12.03.2016, 02.04.2016 - 12.04.2016" how can this? , departuredates.@each.value correct property use? app/route/model.js import ds 'ember-data'; export default ds.model.extend({ name: ds.attr('string'), duration: ds.attr('number'), departuredates: ds.hasmany('departuredate', { async: true }), departuredatetext: ember.computed('departuredates.@each.value', function() { // ??? }) }); app/departuredate/model.js import ds 'ember-data'; export default ds.model.extend({ value: ds.attr('date') }); not tested should work: departuredatetext: ember.computed('duration', 'departuredates.@each.

c++ - Class Member Functions and Classes as Friends -

i've written 2 classes: function of first class cannot access private member of second class though function friend second class. found example msdn.microsoft.com there still error: cannot access private member declared in class b here code msdn : class b; class { public: int func1(b& b); private: int func2(b& b); }; class b { private: int _b; // a::func1 friend function class b // a::func1 has access members of b friend int a::func1(b&); }; int a::func1(b& b) { return b._b; }//the same error 1 below here int a::func2(b& b) { return b._b; } when write class a friend b there no error want have function want friend class b not whole class a is compiler fault or code wrong? i added declaration class b (called forward declaration of class ) @ top , compiles. need declare class b before use parameter in member functions of class a . here code -> #include<iostream> class b; class { public:

javascript - Rails 4 - Application.js contains merge conflicts, not sure how to resolve them -

i have rails app in application.js generated sprocket somehow got merge conflicts - , i'm not sure how remove them. in chrome the following error: uncaught syntaxerror: unexpected token << and can see included in file: [...] <<<<<<< head //= require turbolinks //= require jquery.turbolinks //= require chosen-jquery ======= >>>>>>> 9e6c961b13c6c09da1cb8cdc055c799b829ff824 //= require jquery.purr [...] but can't see merge conflicts in own application.js file (not generated one). i have tried both rake assets:clean , rake assets:precompile , rake assets:clobber without success. any ideas on how can rid of these errors? update clarification this how manual (not generated sprockets) application.js file looks like: //= require jquery //= require jquery.turbolinks //= require jquery_ujs //= require chosen-jquery //= require scaffold //= require jquery.purr //= require best_in_place //= require bootstrap-datepi

ruby - Rails scope ordered ascending not responding in view -

in model have: default_scope -> { order(created_at: :desc) } scope :ascending, -> { order(created_at: :asc) } in view: <ol class="notices comments"> <%= render notice.comments.ascending %> </ol> in model, when change default_scope -> { order(created_at: :desc) } default_scope -> { order(created_at: :asc) } , notices respond expected , display in ascending order instead of descending. however, when change scope :ascending, -> { order(created_at: :asc) } scope :ascending, -> { order(created_at: :desc) } , doesn't change anything. what's wrong code? when call order , adds component order clause. if have default scope , add ascending scope, end order by: order created_at desc, created_at asc the created_at asc ignored because unlikely there ties break created_at desc ordering. you want use reorder in scope replace order by: scope :ascending, -> { reorder(created_at: :asc) } this assumes ordering

html - how can solve floating issues -

i use css style aside. after applying style, aside moves left want @ right of page. want aside have height relational container. i.e. want bottom margin touch top of footer no matter height of container. style: aside { width:260px; float:right; border-left:1px dashed #aaa; padding-right:15px; padding-left:15px; text-align:center; position:absolute; overflow:auto; background-color:blue; border-radius:10px; box-shadow:0px 0px 7px rgba(0,0,0,0.5); } remove position: absolute; . if want keep position: absolute; can add right: 0; instead. html,body{ height: 100%; } aside { width:260px; float:right; border-left:1px dashed #aaa; padding-right:15px; padding-left:15px; text-align:center; overflow:auto; height: 100%; background-color:blue; border-radius:10px; box-shadow:0px 0px 7px rgba(0,0,0,0.5); } <aside>i'm @ right side</aside>

bitbucket - Git pull will not update local files -

i seem have issue using git pull on local branch. have cloned branch remote bitbucket repository, cloned user_home\branch directory on machine. want keep branch date remote branch. not make changes branch on machine. people on different machines commit changes branch in bitbucket, , want able files without having delete directory , git clone on again. here after have clone. git fetch && git checkout -b <branch> git pull <branch> <repo_url> git pull returns "you x commits behind origin/. performs git pull, if go directory branch located, none of files have been altered. doing git pull after returns "already date". so there disparity between actual folder files , git branch. new git , have missed something, although have tried many things , can't update files. ideas? i have tried: git fetch origin git reset --hard origin/master git pull --no-ff <repo_url> <branch> this easiest way achieve want: first, c

apache spark - Automatically including jars to PySpark classpath -

i'm trying automatically include jars pyspark classpath. right can type following command , works: $ pyspark --jars /path/to/my.jar i'd have jar included default can type pyspark , use in ipython notebook. i've read can include argument setting pyspark_submit_args in env: export pyspark_submit_args="--jars /path/to/my.jar" unfortunately above doesn't work. runtime error failed load class data source . running spark 1.3.1. edit my workaround when using ipython notebook following: $ ipython_opts="notebook" pyspark --jars /path/to/my.jar you can add jar files in spark-defaults.conf file (located in conf folder of spark installation). if there more 1 entry in jars list, use : separator. spark.driver.extraclasspath /path/to/my.jar this property documented in https://spark.apache.org/docs/1.3.1/configuration.html#runtime-environment

node.js - WebStorm Debugger for Node Stopping at Non Breakpoints -

in webstorm, have node application , hit debug , on load debugger stops on bunch of seemingly random lines in node_modules. can continue through 5 files until router/index.js file gets stuck on single line countless continues. i have no breakpoints in of node_modules files, obviously, , webstorm not show breakpoint. stops every time. solution has been mute breakpoints, wait app load, , unmute. sometimes, though, have re-add breakpoints if want checkbox check , able hit breakpoints. @ point have no issues. idea why it's getting stuck in node_modules no breakpoints? figured out workaround. chose "view breakpoints" , although points consistently stopped @ not listed, removed breakpoints, , can debug without stopping in random node_modules.

SQL Server Integration Services Package -

i have started using ssis , it's been great ride far. error message when attempting add existing package. guess packages created on original computer cannot globally accessed if have .dtsx file? below, link of image of error getting. http://imgur.com/b95pvg5 please give me help!

python - Tree algorithm and sum value of node -

i'm working on programming exercise @ hackerrank. made data structure code this. couldn't figure out plan how can implement program sum value of tree node. give me advice code? if have fault in data structure i've made, please tell me abount that. thank you. [hackerrank exercise] https://www.hackerrank.com/challenges/cut-the-tree [code] i wrote program , couldn't how can futher sum value of tree. class tree: """ original tree structure representing input """ def __init__(self, value, position): self.value = value self.position = position self.connection = [] def set_connection(self, connection): self.connection.append(connection) def set_value(self, value): self.connection = value def get_value(self, position): return self.value def get_sum(self): return self.value def get_position(self): return self if __name__ == "

Nil in Database for Ruby on Rails -

i'm extremely new, , going through basic ruby rails tutorial except tweaking add fields , renaming calls articles @ contacts. problem is, fine, except data being added in nil. here controller: class contactscontroller < applicationcontroller def index @contacts = contact.all end def show @contacts = contact.find(params[:id]) end def new end def create @contacts = contact.new(contact_params) @contacts.save redirect_to @contacts end end private def contact_params params.require(:contacts).permit(:first_name, :last_name, :phone_number, :notes) end my migrate file: class createcontacts < activerecord::migration def change create_table :contacts |t| t.string :first_name t.text :last_name t.text :phone_number t.text :notes t.timestamps null: false end end end and i'm looking in terminal , see this: started post "/contacts" 127.0.0.1 @ 2015-07-16 14:38:54 -0700 processing contactscon

ios - Ignore sibling order in Scene Kit overlaySKScene -

i using overlayskscene in scene kit. in skscene, using mask node crop skcropnode. mask node works when run on mac os x, when run on ios doesn't work. i think that's because ios ignoring sibling order , mask node shows behind skcropnode. when try set view.ignoresiblingorder = no; in skscene, crashes , says: [gameview setignoressiblingorder:]: unrecognized selector sent instance gameview subclass of scnview, understand scnview doesn't have property "ignoresiblingorder". how solve this? approaching wrong way? bug in scene kit when run on ios?

rest - Plivo: get SMS message content with pull api -

based on plivo docs messages (e.g. https://www.plivo.com/docs/api/message/#get-details-of-all-messages ) appears response rest api retrieving sms messages not include actual content of message. i want functionality testing purposes, curious why case -- if own number , plivo storing metadata texts, why can't contents of messages post-facto plivo's servers? privacy feature? or there way around short of piping own server , pulling myself? the api retrieving message details has meta-data of messages. matter of internal policy, content of sms or calls (unless explicitly recorded) not stored. if it's inbound message, text sent "message_url" , can stored there. if it's outbound message, can see contents of sent messages in debug logs found in plivo dashboard ( https://manage.plivo.com/logs/debug/?type=all ). 1 other way of storing content of outbound message, store details in db before sending message , update status of message later on. status of m

extjs - Work with associations on server side; table relationships -

i need this, on server side. http://dev.sencha.com/ext/5.1.0/examples/kitchensink/#binding-associations my code (when select 1 customers grid row): selectionchange: function(sm, grid, value, selected, eopts) { var storecustomers = grid.getstore(); var gridorders = ext.componentquery.query('#gridordersitemid')[0]; var storeorders = gridorders.getstore(); var id_customers = storecustomers.findrecord('id_customers', value); //it not work; return null console.log(id_customers ); //null console.log(value); //undefined storeorders.proxy.extraparams = { 'id_customers': id_customers }, storeorders.load(); } for reason can not value of id_customers when select grid record. result null. any idea how solve this? thanks in advance. edited: 06-07-2015 selectionchange: function(sm, grid, record, value, selected, eopts) { var storecustomers = grid.getstore(); var gridorders = ext.compon

Selenium-Webdriver-Object declaration -

what difference between below 2 statement? webdriver driver = new firefoxdriver(); firefoxdriver driver= new firefoxdriver(); this casting . with webdriver explicitly casting new instance of firefoxdriver() webdriver , same firefoxdriver .

android - How to Refresh listview with custom adapter -

i need little solution refreshing listview after delete data database. realized can delete data database function of activity : helper.delete(string.valueof(editid)); adapter.notifydatasetchanged(); break; and in dbhelper : public void delete(string id) { string[] args = {id}; getwritabledatabase().delete(table_name, "_id=?", args); getwritabledatabase().close(); this code works deleting database , item, adapter.notifydatasetchanged(); listview refresh when closed application opened again. need way how refresh listview instantly. people used adapter.remove(position); , refresh instantly, call .notifydatasetchanged(); . not worked custom adapter. i used kind of adapter : class listadapter extends cursoradapter{ @suppresswarnings("deprecation") listadapter(cursor c){ super(mainactivity.this, c); } @override public void bindview(view row, context ctxt, cursor c) { // todo auto-generated method stub

c - Remove element at a given index of a Stack that is a part of linked list of stacks -

i building stacklist. linked-list of stacknodes. each stack on stacknode of constant size (it int array). if stack full use malloc create new stacknode , append stacklist. i need implement function call int popat(int index); which should return element specified index. scenario: each stack has length = 10; stacklist has total of 5 stacks. number of elements in stacklist 10 per stack * 5 sets = 41 - 50 ( @ max can 50). want remove element @ index = 25. means @ 2ed stacknode of stacklist , 4th index in stacknode's stack. when remove 25th element, need push every element on top of down 1 element. my solution: copy elements on 2nd stack above 24th element 1 position down. { copy next stacknode->stack's first element end of current stacks //problem here select next stacknode } while ( linked list has stacknodes) problem: want shift elements in stack 1 position down. possible without iterating through array(a stack on each stacknode) because if hav

sql - Delete Across Tables MS Access -

i trying delete records in 2 different tables. error message: specify table containing records want delete. the table msshipment reference source records delete across both tables. delete msshipment.boxnumber msshipment_boxnumber, medicalsort.boxnumber medicalsort_boxnumber msshipment inner join medicalsort on msshipment.[boxnumber] = medicalsort.[boxnumber]; you should consider setting referential integrity cascade deletes between msshipment , medicalsort. this way when delete record msshipment, of detail records in medical sort deleted. this happen time throughout application.

ios - UITableView Search For Name In Object -

i trying search through array of objects retrieved parse display results in uitableview . tried using same method used in 1 of other apps, in case searching through array of strings. this code @ moment: func filtercontentforsearchtext(searchtext: nsstring) { let resultpredicate = nspredicate(format: "self beginswith[cd] %@", searchtext) //use either contains or beginswith searchresults = datamanager.sharedinstance.ridearray.name.filteredarrayusingpredicate(resultpredicate) } func searchdisplaycontroller(controller: uisearchdisplaycontroller!, shouldreloadtableforsearchstring searchstring: string!) -> bool { self.filtercontentforsearchtext(searchstring) return true } i understand why doesn't work, can't figure out solution problem. property want search within 'ride' object name. can me out? thanks! assuming ridearray array of parse objects have property name , predicate should be nspredicate(format: "name beginsw

c++ - Utilizing char to determine output isnt working -

i'm trying make when user inputs either r or p different portion execute reason it's not recognizing single character inputs. taking me first if statement saying don't have right value, executing r regardless of enter. why isn't working me? tried both letter , ascii number corresponding letters , each time same thing. not outputting final statement says invalid service code try again. program looks this. in advance time! #include <iostream> #include <iomanip> #include <string> using namespace std; int main() { char servicetype; int account; double minutes; double initialcharge; double overcharge; double day; double night; double dayrate; double nightrate; double balance; string service; cout << "please enter account number: "; cin >> account; cout << endl; cout << "please enter service code: "; cin >> servicetype; cout <<

What is the Best Practice to configure StackExchange.Redis with Autofac? -

in stackexchange.redis docs recommended create 1 , reuse connection redis. azure redis best practices recommends using following pattern: private static lazy<connectionmultiplexer> lazyconnection = new lazy<connectionmultiplexer>(() => { return connectionmultiplexer.connect("cachename.redis.cache.windows.net,ssl=true,abortconnect=false,password=password"); }); public static connectionmultiplexer connection { { return lazyconnection.value; } } but how should working autofac want configuration set in web/app config files? i have rediscacheprovider: private readonly connectionmultiplexer _connection; public rediscacheprovider(string config) { _connection = connectionmultiplexer.connect(config); } and in autofac config: builder.registertype<rediscacheprovider>().as<icacheprovider>().withparameter("config", "localhost"); my thinking is, should change rediscacheprovider take in connec

java - regex pattern is matching with one of the pattern i cant able to follow? -

i come across regex pattern , matching pattern strings, confused 1 of matched pattern target: .50 1.50 0.50 10.50 00.50 1.555 pattern: (0|[1-9]\d*)\.\d\d matches with: (4,7:1.50)(9,12:0.50)(14,18:10.50)(21,24:0.50)(26,29:1.55) what deduce pattern 2 digit after decimal, , before decimal group in first digit either 0 or digit between 1 9, followed empty string or number string... i think in last second match should 00.50. what missing?? i think in last second match should 00.50. what missing?? no, part of regex (0|[1-9]\d*)\. can rewritten (0\.|[1-9]\d*\.) , can accept one 0 , . or [1-9]\d* , . if want allow many zeroes before dot use (0+|[1-9]\d*)\.\d\d ^--one or more zeroes

ruby on rails - Prevent the double query? -

my goal pull data sql database , split 2 arrays (req of library) can graph data. problem process creating 2 database queries instead of one. in controller: def words_popular words = word.select(:word, :popularity).order(popularity: :desc).limit(100) @words = words.pluck(:word) @popularity = words.pluck(:popularity) end and resulting log: (1.9ms) select `dictionary`.`word` `dictionary` order `dictionary`.`popularity` desc limit 100 (2.0ms) select `dictionary`.`popularity` `dictionary` order `dictionary`.`popularity` desc limit 100 is problem double plucking? can array split in 1 line? also, in future, there way force query? in node mongoose, call exec() on relation cause run. try this: words, popularity = word.pluck(:word, :popularity).transpose and words contains array of words , popularity array of popularity.

json - Deserialization and serialization using newtonsoft c# -

my application binding rest api, returns me: { key: "xxxx-xxxx", fields: { customfield_10913: { value: "l2" } } } i'm using newtonsoft json serialize , deserialize , i've created these models make work: public class issue { [jsonproperty("key")] public string key { get; set; } [jsonproperty("fields")] public fields fields { get; set; } } public class fields { [jsonproperty("customfield_10913")] public customfield level { get; set; } } public class customfield { [jsonproperty("value")] public string value{ get; set; } } the application deserializing ok, using code: t model = jsonconvert.deserializeobject<t>(result); after lot of business logic, web api should return new json: protected t get() { return model; } and i've got json i've read api. so, need? i need read field custom_fieldxxx , can't retu

python - SQLalchemy mysql url connection string on cloud sql -

what's conncetion url mysql in sqlalchemy while connecting google app engine ?? i know it's mysql+gaerdbms:///<dbname>?instance=<my cloud instance name> but specify user, password , host. below error while connecting above string. 947, in makerequest raise _todbapiexception(response.sql_exception) operationalerror: (operationalerror) (1045, u"access denied user 'root'@'localhost' (using password: no)") none none the mysql+gaerdbms:// deprecated. please use mysql+mysqldb:// instead. format of connection uri is: mysql+mysqldb://root@/<dbname>?unix_socket=/cloudsql/<projectid>:<instancename> note above works in app engine prod. recommended way connect dev_appserver request ip , use connect. reference: http://docs.sqlalchemy.org/en/latest/dialects/mysql.html?highlight=appengine#module-sqlalchemy.dialects.mysql.gaerdbms

C# WinForms: populating datagridview with datasource from two different tables -

when have populate dgv 1 table it's ok, know how (list< entity > coming database datasource). when have table has fk one, don't know how show property of table (and not id, user wont understand). think i've done linq bad (btw i'm new linq, don't know if need it, @ least here). problem solution comes when try selected id dgv. private void loaddgv() { buildinglogic obuildinglogic; try { obuildinglogic = new buildinglogic(); societylogic osocietylogic = new societylogic(); list<building> listbuildings = obuildinglogic.getall(); list<society> listsocieties = osocietylogic.getall(); this.dgvbuildings.datasource = (from building in listbuildings join society in listsocieties on building.idsociety equals society.id select new { bui

bash - --line-regexp option with null data -

consider command: printf 'alpha\nbravo\ncharlie\n' | grep --line-regexp --quiet bravo grep sees 3 lines separated newline, , matches bravo line. consider command: printf 'alpha\0bravo\0charlie\0' | grep --line-regexp --quiet bravo my thinking tells me because have not used --null-data , grep should see 1 or 0 lines separated newline, , fail match bravo followed newline. not, succeeds first command, why this? this behavior was introduced grep 2.21: when searching binary data, grep may treat non-text bytes line terminators. can boost performance significantly. so happens binary data, non-text bytes (including newlines) treated line terminators. if want change behavior, can: use --text . ensure newlines line terminators use --null-data . ensure null bytes line terminators

android - HTTP Error when trying to connect to a channel in Pubnub -

i trying connect channel in pubnub using application in android studio. how fix this? subscribe : error on channel my_channel : [error: 103-1] : http error. please check network connectivity. please contact support error details if issue persists. its late answer , might else. pub nub uses internet , adding internet permissions manifest solved problem . not mentioned in pub nub documentation . <uses-permission android:name="android.permission.internet" />

Python 3.4 plistlib doesn't work (str vs bytes errors) -

so, started on new toy project , decided i'd use python 3 first time... in [1]: import plistlib in [2]: open("/volumes/thunderbay/current/music/itunes/itunes library.xml") itl: library = plistlib.load(itl) ...: --------------------------------------------------------------------------- typeerror traceback (most recent call last) <ipython-input-3-6459a022cb71> in <module>() 1 open("/volumes/thunderbay/current/music/itunes/itunes library.xml") itl: ----> 2 library = plistlib.load(itl) 3 /usr/local/cellar/python3/3.4.3_1/frameworks/python.framework/versions/3.4/lib/python3.4/plistlib.py in load(fp, fmt, use_builtin_types, dict_type) 984 fp.seek(0) 985 info in _formats.values(): --> 986 if info['detect'](header): 987 p = info['parser'] 988 break /usr/local/cellar/python3/3.4.3_1/frameworks/pytho

php - Site wont connect to DB after changing cPanel password -

i have client who's site on shared hosting platform. want desperatly change password of cpanel when site cannot connect database. site's database , cpanel share same password changed in code didn't fix problem. when reverted original password db connected fine. question is. when change cpanel password have take other measure? thanks. i think using cpanel user name , password in site mysql databases config , due getting issues, suggest please create new mysql user through cpanel , assigned full permission mysql user , update in site mysql databases config file when changed cpanel password not issues site.

sylius - Missing form fields for titles -

Image
i've installed sylius ( http://docs.sylius.org/en/latest/book/installation.html ) , form fields category , product title missing. missing html. please :)

localization - Android quantity strings - prevent Arabic numerals -

when following quantity string set textview : <plurals name="distance_mile"> <item quantity="one">%d ميل</item> <item quantity="other">%d ميل</item> </plurals> it rendered arabic numbers , e.g. 100 looks ١٠٠. there way (other replacing characters in resulting string) force european numerals ? (like adding special unicode symbol or that) thanks!

spring - Cannot query MongoDb on producer endpoint using direct component -

i have configured following route query local mongodb instance. instance running on localhost on port 27017 without authentication. the route is: from("direct:start") .to("mongodb:mongobean?" + "database=camel-source" + "&collection=racingevents" + "&operation=getdbstats") .convertbodyto(string.class) .to("file://e:/data/test.txt"); my mongobean defined in spring as: <bean id="mongobean" class="com.mongodb.mongo"> <constructor-arg name="host" value="localhost" /> <constructor-arg name="port" value="27017" /> </bean> the route starts fine no data sent file endpoint. if replace direct: component endpoint timer: component data written file endpoint: from("timer://foo?delay=1&repeatcount=1") .to("mongodb:mongobean?" + "database=cam

wcf - wsHttpsBinding Vs wsHttpBinding -

i have come across wshttpbinding when writing code wcf projects. however, have never used wshttp s binding . question : wshttp s binding exist in wcf or custom binding? if exists, why developer use wshttp s binding rather wshttpbinding ? wshttpbinding supports interoperability. binding, soap message is, default, encrypted. supports http , https. in terms of encoding, provides support text mtom encoding methods. supports ws-* standards ws-addressing, ws-security , ws-reliablemessaging. default, reliable sessions disabled because can cause bit of performance overhead. http://www.codeproject.com/articles/431291/wcf-services-choosing-the-appropriate-wcf-binding

r - Shiny - Are reactive environments possible? -

right now, have expression looks this: you can run directly app.r file. it's standalone, , demonstrates effect want. library(shiny) rval <- reactivevalues() rval$var <- new.env() rval$flag <- false isolate({ rval$var$a <- 1 rval$var$b <- "hello" rval$var$c <- c(1.2, 12.3, 123.0) rval$var$d <- list(1,2,"a") }) ui <- navbarpage('reactivetest', tabpanel('analysis', fluidrow( actionbutton("addvar", "add null var"), tableoutput('vars') ) ) ) core_variable_table <- eventreactive(rval$flag == true, { print(ls(rval$var)) rval$flag <- false df <- data.frame(ls(rval$var), sapply(ls(rval$var), function(x){ class(get(x, envir = rval$var))}), sapply(ls(rval$var), function(x){ y <- head(get(x, envir = rval$var)) if(is.null(y)) { return("n

serialization - Effecient way to serialize jagged arrays using BinaryWriter -

stackoverflowers. i wondering if has got tip on how should go on this. serializing regular primitive types using binarywriter (by length prefixing byte arrays). add entity primitivetypes dictionary have, want able serialize indefinite jagged array; doesn't matter if it's system.byte[][] or system.byte[][][][][][] i need way prefix arrays' lengths , way tell deserializer how many arrays of arrays there are. i thinking of way this, have been trying day. just snippet of have come (it's not complete @ all, maybe conceptional approach); private sub writearray(writer binarywriter, type byte, array array) writer.write(array.getlength(0)) 'writing length know how many arrays there are. dim current type = array.gettype() 'getting type of (jagged-)array if current.haselementtype andalso current.getelementtype.isarray 'checking whether it's jagged-array. writer.write(true) 'writing true; represents it's jagged-array.

java - do I need to use volatile if update to other thread'cache is not time-constraint -

i have singleton object 1 method: class static single { string static somefilecontent; public static void set(string str){somefilecontent=str;} public static string get(){return somefilecontent;} } and have 2 thread, one thread query content single.get() in operations, 100 times/sec. and thread monitor file update string set() method in period, if file modified,refresh content. it acceptable few operation use old string value. my question is: should need volatile ,because not time-constraint? if worst happen, whether read thread not update forever? i wondering happen use plain java? yes, read thread may read old value after value update. said, read old value few times acceptable. wondering whether old value stays forever in cpu cache. and vaspar's answer. better use reentrantreadwritelock , don't need use volatile variable. get call should readlocked shared, , set call should writelocked exclusive. changes updated in threads once res

c - Freeing up memory allocated for an arbitrary position at an array -

i writing code manage insertions , deletions array elements. know linked list or other data structure better suited this, i'm limited using array. extra memory array allocations managed use of realloc() function. however, deletions, must free memory allocated last element. this, tried using free (a + n) , n representing last element, however, ends giving crashes like: *** error in `./a.out': munmap_chunk(): invalid pointer: 0x000000000158f018 *** aborted (core dumped) i believe crashes expected, since os manages list of allocations heap, , while a has been allocated through malloc() , os not know allocations a + n , resulting in hard error. how should go around freeing last element stored in array? use realloc shrink allocation: array_size--; array = realloc(array, array_size);

Insert multiples table rows into a document with google script -

i developed code allow myself append several rows table under table row cursor inside of. var ui = documentapp.getui(); var answer = documentapp.getui().prompt("add rows", "insert number of rows want add in box below.\nmake sure have cursor placed in table want append rows to.", documentapp.getui().buttonset.ok_cancel); if(answer.getselectedbutton() == ui.button.ok) { var doc = documentapp.getactivedocument(); var pos = doc.getcursor(); var elementin = pos.getelement(); var tablecell = elementin.getparent(); var tablerow = tablecell.getparent(); var table = tablerow.getparent(); for(var = 0; < answer.getresponsetext(); i++) { var row = table.astable().inserttablerow(table.getchildindex(tablerow)+1); for(var j = 0; j < tablerow.getnumchildren(); j++) { row.inserttablecell(0); } } } doc.saveandclose(); the code executes fine, when try highlight rows created default googl

html - Javascript Motion Detection -

i looking plugin/library javascript can detect motion in video stream web camera. it needs have sort of callback like: motion.onmotion(function(){ // here }); that literally need do. there's library called reallygood javascript motion detection. please check it. motion can detected using code, you're looking for: $('#one').on('motion', function(){ console.log('touched one'); }); here's github .

c - Strings - Data Type -

i have learned how handle data types except, strings. so, can me strings? in declaration char surnm[4] = {'p', 'i', 'n', 'e', '\0'}; there 5 initializers 4 elements in array surnm . array not contain string because did not included terminating zero. should write either char surnm[5] = {'p', 'i', 'n', 'e', '\0'}; or char surnm[] = {'p', 'i', 'n', 'e', '\0'}; or char surnm[5] = { "pine" }; or char surnm[5] = "pine"; or char surnm[] = { "pine" }; or char surnm[] = "pine";

ios - Swift/Parse: findObjects()! changing other PFObject instances values? -

i've created 2 queries in viewdidload() : offlinequery = pfquery("dados").fromlocaldatastore() onlinequery = pfquery("dados") when app launches first time, local data store populated online data provided findobject()! method of onlinequery : let objects = onlinequery.findobjects()! as! [pfobject] pfobject.pinall(objects) when user clicks on refresh button perform search @ at local data store using findobject()! offlinequery : var objectsoff = offlinequery.findobjects()! as! [pfobject] then search online data: let objectson = onlinequery.findobjects()! as! [pfobject] the problem starts when try compare both arrays after ordering them, , result shows equal. decided print content of both, , equal. to solve problem had store values separated variables , regrouped them array of string. however, code became big. what happened here?

algorithm - What is the minimum number of items that must be exchanged during a remove the maximum operation in a heap of size N with no duplicate keys? -

Image
this question came across in sedgewick's book. , on website, says answer 2, can't understand how achieve 2, because remove maximum need first exchange max element last one, decrease n, , sink last 1 down top place, takes logn exchanges. so, how achieve 2? exchange & remove-max: then need sink, l node, means need logn more exchanges. here's example 15 nodes. idea is: have sons of root large (let left 1 larger), other left descendants smaller right ones. swap twice. 100 99 90 9 8 89 88 7 6 5 4 87 86 85 84 you'll switch 84, 100 99, 84 , you're done. 2 swaps. for n > 3 , after first swap, there no way neither of 2 sons of root won't larger new root (otherwise wasn't heap begin with). you'll have swap. author meant write swaps, not items.

user interface - iOS what element is most suitable for large texts eg text view -

i wonder ui element should use large sets of text. eg between 200 - 1000 characters. i place text inside scrollview doesn't have ve scrollable or editable etc, want display text. so should use between label / text view / text field? thanks in advance. text views texts varying lengths, have scroll view of own. may consider using normal uilabel , setting "lines" property 0. know sounds strange, setting 0 tells label multi-line label. can use auto layout establish width of uilabel. grow down based on amount of text in it. text fields inappropriate displaying texts in cases; better user input.

java - How to fill ListView with Adapters -

i'm aware simple question i'm newbie in android development please go easy on me. problem have in 1 of fragments (asynctask specifically) lays in main activity. asynctask sends out data php script returns according data in json format. processed , saved jsonlist array. until post execute works fine data downloaded, processed etc. when program reaches post execute problems start pop out. , i'm unable list out data jsonlist listview //setting array arraylist<hashmap<string, string>> jsonlist = new arraylist<hashmap<string, string>>(); //creating list view variable listview listview; //define work in progress dialog private progressdialog mprogressdialog; private class progresstask extends asynctask<string, void, boolean> { @override protected void onpreexecute() { super.onpreexecute(); // create progressdialog mprogressdialog = new progressdialog(getactivity(

Java - Jackson JSON Library and ObjectMapper.readValue -

i have following json data (patients.json): { "a" : { "name" : "tom", "age" : 12 }, "b" : { "name" : "jim", "age" : 54 } } using jackson json library, how can following: hashmap<string, ???> patients = objectmapper.readvalue(new file("patients.json"), ???); string aname = patients.get("a").get("name"); int aname = patients.get("a").get("age"); you create class map patients to; private static class patient { @jsonproperty("name") private string name; @jsonproperty("age") private int age; public patient() { } public string getname() { return name; } public int getage() { return age; } } then read json via jackson hashmap<string, patient> patients = objectmapper.readvalue(new file("patient

Does Dataflow support parallel Datastore reads of namespaced entities? -

according this question , answer march , bugs in datastoreio make impossible read namespaced entities in parallel within dataflow. have bugs been addressed since then? possible read namespaced entities in parallel datastore? parallel reading of namespaced entities supported in datastoreio of dataflow sdk java 1.2.0. see code , documentation here .

php - How can I get my dropdown to goto a page and display a selected record? -

first time poster , new mysqli, sorry if question not correct. have table (staff) id, staffname , profile. wish able edit/add records selecting staff member dropdown , after submit, go new page called add-edit-staff.php. i have created page add-edit-staff.php, , works perfectly. if put manually type "add-edit-staff.php" in address bar of browser form comes add new record. if manually type "add-edit-staff.php?id=1" in address bar of browser form comes edit record id 1. now issue, have page called view-staff.php. page has form dropdown displaying field "staffmember". want able select record dropdown , go corresponding record on add-edit-staff.php page based on id of record. when select record, comes straight mt add-edit-staff.php page. because view-staff.php page not sending id of record in url. i have attached code , appreciate advice on how resolve issue. said, new , have been trying adapt code suit goal cant seem head around it. thanks in adv

php - How to identify controller,view from url when using yii framework -

my questions how identify controller or view url? for example in codeigniter url -localhost/projectname/controller/index can identify controller , function that. how can identify when using yii framework? your url (if routing turned off): www.example.com/index.php?r=controller/action if routing turned on, default this: www.example.com/controller/action

Custom Listview(or Adapter) that allows updating a row instead of adding one. (Android) -

i have listview. now, i'm using switch-case, i'm comparing getview() method's position id obtained server in form of json response. suppose id myobjectarraylist.get(poisition).getidforcomparison . myadapter.java arraylist<myobject> myobjectarraylist; int counter = 0; @override public view getview(final int position, view convertview, viewgroup parent) { switch(myobjectarraylist.get(poisition).getidforcomparison){ case x: if (myobjectarraylist.get(position).getidforcomparison) == myobjectarraylist.get(nextposition).getidforcomparison){ "update same row concatenating new text exisiting" } else{ "insert next row" } } } so, need keep collecting information json object in same row until myobjectarraylist.get(poisition).getidforcomparison same current , next position. if not, want allow addition of new row. logic processing sho

javascript - Empty form with for statement -

i have for statement create 20 number of forms, after creating elements forms empty(but have input elements on it) , why cannot send objects post. <form method="post" ></form> this code : for($i= 1 ; $i<=$numtest ; $i++){ $mdata = $numtoword->towordfa($i); echo ' <li> <div class="questitle2 noselect"><a href="#">عنوان سوال '.$mdata.'</a></div> <div class="quescontent"> <input type="text" class="questitle byekan" name="tt'.$i.'" id ="tt'.$i.'" placeholder="عنوان سوال '.$i.'" onclick="select()" /><br/> <div style="text-align:right;margin-top:10px;" class="qkind">نوع سوال : <input type="radio" name="istest&

c# - Pass Type as parameter and check -

i want build method accepts parameter type like void m1(type t) { // check type } and call m1(typeof(int)); i have no idea how check type in method body. i have tried if (t double) but giving warning the given expression never provided type (double) please me checking type of parameter. if want check exact type, can use: if (t == typeof(double)) that's fine double , given it's struct, can't inherited from. if want perform more is-like check - e.g. check whether type compatible system.io.stream - can use type.isassignablefrom : if (typeof(stream).isassignablefrom(t)) that match if t system.io.memorystream , example (or if it's system.io.stream itself). i find myself having think work out way round call goes, target of call usually typeof expression.