Search Results

Search found 351 results on 15 pages for 'pseudocode'.

Page 12/15 | < Previous Page | 8 9 10 11 12 13 14 15  | Next Page >

  • Executing sequential stored procedures; works in query analyzer, doesn't in my .NET application

    - by evanmortland
    Hello, I have an audit record table that I am writing to. I am connecting to MyDb, which has a stored procedure called 'CreateAudit', which is a passthrough stored procedure to another database on the same machine called MyOther DB with a stored procedure called 'CreatedAudit' as well. In other words in MyDB I have CreateAudit, which does the following EXEC dbo.MyOtherDB.CreateAudit. I call the MyDb CreateAudit stored procedure from my application, using subsonic as the DAL. The first time I call it, I call it with the following (pseudocode): Result = CreateAudit(recordId, "Opened") One line after that, I call: Result2 = CreateAudit(recordId, "Closed") In my second stored procedure it is supposed to mark the record that was created by the CreateAudit(recordId, "Opened") with a status of closed. It works great if I run them independently of one another, but when they run in sequence in the application, the record is not marked as "Closed". When I run SQL profiler I see that both queries ran, and if I copy the queries out and run them from query analyzer the record gets marked as closed 100% of the time! When I run it from the application, about once every 20 times or so, the record is successfully marked closed - the other 19 times nothing happens, but I do not get an error! Is it possible for the .NET app to skip over the ouput from the first stored procedure and start executing the second stored procedure before the record in the first is created? When I add a "WAITFOR DELAY '00:00:00:003'" to the top of my stored procedure, the record is also closed 100% of the time. My head is spinning, any ideas why this is happening! Thanks for any responses, very interested in hearing how this can happen.

    Read the article

  • Help with java executors: wait for task termination.

    - by Raffo
    I need to submit a number of task and then wait for them until all results are available. Each of them adds a String to a Vector (that is synchronized by default). Then I need to start a new task for each result in the Vector but I need to do this only when all the previous tasks have stopped doing their job. I want to use Java Executor, in particular I tried using Executors.newFixedThreadPool(100) in order to use a fixed number of thread (I have a variable number of task that can be 10 or 500) but I'm new with executors and I don't know how to wait for task termination. This is something like a pseudocode of what my program needs to do: EecutorService e = Executors.newFixedThreadPool(100); while(true){ /*do something*/ for(...){ <start task> } <wait for all task termination> for each String in result{ <start task> } <wait for all task termination> } I can't do a e.shutdown because I'm in a while(true) and I need to reuse the executorService... Can you help me? Can you suggest me a guide/book about java executors??

    Read the article

  • Multiple WCF calls for a single ASP.NET page load

    - by Rodney Burton
    I have an existing asp.net web application I am redesigning to use a service architecture. I have the beginnings of an WCF service which I am able to call and perform functions with no problems. As far as updating data, it all makes sense. For example, I have a button that says Submit Order, it sends the data to the service, which does the processing. Here's my concern: If I have an ASP.NET page that shows me a list of orders (View Orders page), and at the top I have a bunch of drop down lists for order types, and other search criteria which is populated by querying different tables from the database (lookup tables, etc). I am hoping to eventually completely decouple the web application from the DB, and use data contracts to pass information between the BLL, the SOA, and the web app. With that said, how can I reduce the # of WCF calls needed to load my "View Orders" page? I would need to make 1 call get the list of orders, and 1 call for each drop down list, etc because those are populated by individual functions in my BLL. Is it good architecture to create a web service method that returns back a specialized data contract that consists of everything you would need to display a View Orders page, in 1 shot? Something like this pseudocode: public class ViewOrderPageDTO { public OrderDTO[] Orders { get; set; } public OrderTypesDTO[] OrderTypes { get; set; } public OrderStatusesDTO[] OrderStatuses { get; set; } public CustomerListDTO[] CustomerList { get; set; } } Or is it better practice in the page_load event to make 5 or 6 or even 15 individual calls to the SOA to get the data needed to load the page? Therefore, bypassing the need for specialized wcf methods or DTO's that conglomerate other DTO? Thanks for your input and suggestions.

    Read the article

  • javascript plugin - singleton pattern?

    - by Adam Kiss
    intro Hello, I'm trying to develop some plugin or/*and* object in javascript, which will control some properties over some object. It will also use jQuery, to ease development. idea This is in pseudocode to give you an idea, since I can't really describe it in english with the right words, it's impossible to go and use google to find out what I want to use (and learn). I will have plugin (maybe object?) with some variables and methods: plugin hideshow(startupconfig){ var c, //collection add: function(what){ c += what; }, do: function(){ c.show().hide().stop(); //example code } } and I will use it this way (or sort-of): var p = new Plugin(); p .add($('p#simple')) .add($('p#simple2')) .do(); note I'm not really looking for jQuery plugin tutorials - it's more like usage of singleton pattern in document in javascript, jQuery is mentione only because it will be used to modify dom and simplify selectors, jQuery plugin maybe just for that one little function add. I'm looking for something, that will sit on top of my document and call functions from itselft based on timer, or user actions, or whatever. problems I don't really know where to start with construction of this object/plugin I'm not really sure how to maintain one variable, which is collection of jQuery objects (something like $('#simple, #simple2');) I would maybe like to extedn jQuery with $.fn.addToPlugin to use chaining of objects, but that should be simple (really just each( p.add($(this)); )) I hope I make any sense, ideas, links or advices appreciated.

    Read the article

  • Subsonic, child records, and collections

    - by Dane
    Hi, I've been working with subsonic for a few weeks now, and it is working really well. However, I've just run into an issue with child objects with additional partial properties. Some of it is probably me just not understanding the .Net object lifecycle. I have an object - search. This has a few properties like permissions and stuff, and it links to a child table called search_options. In my Asp.Net app, it loops through these search options and creates controls. Then on postback, it grabs the values and assigns it back to a "value" property on the search_option. This value property is a simple string that's defined in a partial class. I then want to create a method on the search object, called PerformSearch. This then loops through the child search_options, and performs a custom query based on the "value" property. However, even though I assign the "value" property to the child search_option, when I access it later via the search.search_options collection, it is null. I'm guessing that maybe because it's accessing it in two different places, it performs another lazy load from the DB and the value is lost? Is there a way to tell the class that it's already loaded or something? or a way to access it so it's not reloaded from the DB? Code is below (shitty pseudocode, not full version) : ASP.Net page, loading back the values from postback : dim obj_search as search = new subsonic.query.select().......' retrieves the search object for each opt as search_option in obj_search.search_options opt.Value = Ctype(FindControl("search_option_" + opt.search_option_id),Textbox).Text debug.print(opt.Value) ' value is correct next for each opt as search_option in obj_search.search_options debug.print(opt.Value) 'this is nothing next Now, the partial class : public partial class search_option private m_value as string public property Value() as string get return m_value end get set( byval value as string) m_value = value end set end property end class

    Read the article

  • How to distinguish between two different UDP clients on the same IP address?

    - by Ricket
    I'm writing a UDP server, which is a first for me; I've only done a bit of TCP communications. And I'm having trouble figuring out exactly how to distinguish which user is which, since UDP deals only with packets rather than connections and I therefore cannot tell exactly who I'm communicating with. Here is pseudocode of my current server loop: DatagramPacket p; socket.receive(p); // now p contains the user's IP and port, and the data int key = getKey(p); if(key == 0) { // connection request key = makeKey(p); clients.add(key, p.ip); send(p.ip, p.port, key); // give the user his key } else { // user has a key // verify key belongs to that IP address // lookup the user's session data based on the key // react to the packet in the context of the session } When designing this, I kept in mind these points: Multiple users may exist on the same IP address, due to the presence of routers, therefore users must have a separate identification key. Packets can be spoofed, so the key should be checked against its original IP address and ignored if a different IP tries to use the key. The outbound port on the client side might change among packets. Is that third assumption correct, or can I simply assume that one user = one IP+port combination? Is this commonly done, or should I continue to create a special key like I am currently doing? I'm not completely clear on how TCP negotiates a connection so if you think I should model it off of TCP then please link me to a good tutorial or something on TCP's SYN/SYNACK/ACK mess. Also note, I do have a provision to resend a key, if an IP sends a 0 and that IP already has a pending key; I omitted it to keep the snippet simple. I understand that UDP is not guaranteed to arrive, and I plan to add reliability to the main packet handling code later as well.

    Read the article

  • Threading Practice with Polling.

    - by Stacey
    I have a C# application that has to constantly read from a program; sometimes there is a chance it will not find what it needs, which will throw an exception. This is a limitation of the program it has to read from. This frequently causes the program to lock up as it tries to poll. So I solved it by spawning the 'polling' off into a separate thread. However watching the debugger, the thread is created and destroyed each time. I am uncertain if this is typical or not; but my question is, is this good practice, or am I using the threading for the wrong purpose? ProgramReader { static Thread oThread; public static void Read( Program program ) { // check to see if the program exists if ( false ) oThread = new ThreadStart(program.Poll); if(oThread != null || !oThread.IsAlive ) oThread.Start(); } } This is my general pseudocode. It runs every 10 seconds or so. Is this a huge hit to performance? The operation it performs is relatively small and lightweight; just repetitive.

    Read the article

  • Emulating Dynamic Dispatch in C++ based on Template Parameters

    - by Jon Purdy
    This is heavily simplified for the sake of the question. Say I have a hierarchy: struct Base { virtual int precision() const = 0; }; template<int Precision> struct Derived : public Base { typedef Traits<Precision>::Type Type; Derived(Type data) : value(data) {} virtual int precision() const { return Precision; } Type value; }; I want a function like: Base* function(const Base& a, const Base& b); Where the specific type of the result of the function is the same type as whichever of first and second has the greater Precision; something like the following pseudocode: template<class T> T* operation(const T& a, const T& b) { return new T(a.value + b.value); } Base* function(const Base& a, const Base& b) { if (a.precision() > b.precision()) return operation((A&)a, A(b.value)); else if (a.precision() < b.precision()) return operation(B(a.value), (B&)b); else return operation((A&)a, (A&)b); } Where A and B are the specific types of a and b, respectively. I want f to operate independently of how many instantiations of Derived there are. I'd like to avoid a massive table of typeid() comparisons, though RTTI is fine in answers. Any ideas?

    Read the article

  • Using Doctrine to abstract CRUD operations

    - by TomWilsonFL
    This has bothered me for quite a while, but now it is necessity that I find the answer. We are working on quite a large project using CodeIgniter plus Doctrine. Our application has a front end and also an admin area for the company to check/change/delete data. When we designed the front end, we simply consumed most of the Doctrine code right in the controller: //In semi-pseudocode function register() { $data = get_post_data(); if (count($data) && isValid($data)) { $U = new User(); $U->fromArray($data); $U->save(); $C = new Customer(); $C->fromArray($data); $C->user_id = $U->id; $C->save(); redirect_to_next_step(); } } Obviously when we went to do the admin views code duplication began and considering we were in a "get it DONE" mode so it now stinks with code bloat. I have moved a lot of functionality (business logic) into the model using model methods, but the basic CRUD does not fit there. I was going to attempt to place the CRUD into static methods, i.e. Customer::save($array) [would perform both insert and update depending on if prikey is present in array], Customer::delete($id), Customer::getObj($id = false) [if false, get all data]. This is going to become painful though for 32 model objects (and growing). Also, at times models need to interact (as the interaction above between user data and customer data), which can't be done in a static method without breaking encapsulation. I envision adding another layer to this (exposing web services), so knowing there are going to be 3 "controllers" at some point I need to encapsulate this CRUD somewhere (obviously), but are static methods the way to go, or is there another road? Your input is much appreciated.

    Read the article

  • problem with fork()

    - by john
    I'm writing a shell which forks, with the parent reading the input and the child process parsing and executing it with execvp. pseudocode of main method: do{ pid = fork(); print pid; if (p<0) { error; exit; } if (p>0) { wait for child to finish; read input; } else { call function to parse input; exit; } }while condition return; what happens is that i never seem to enter the child process (pid printed is always positive, i never enter the else). however, if i don't call the parse function and just have else exit, i do correctly enter parent and child alternatingly. full code: int main(int argc, char *argv[]){ char input[500]; pid_t p; int firstrun = 1; do{ p = fork(); printf("PID: %d", p); if (p < 0) {printf("Error forking"); exit(-1);} if (p > 0){ wait(NULL); firstrun = 0; printf("\n> "); bzero(input, 500); fflush(stdout); read(0, input, 499); input[strlen(input)-1] = '\0'; } else exit(0); else { if (parse(input) != 0 && firstrun != 1) { printf("Error parsing"); exit(-1); } exit(0); } }while(strcmp(input, "exit") != 0); return 0; }

    Read the article

  • Is it legal to extend the Class class?

    - by spiralganglion
    I've been writing a system that generates some templates, and then generates some objects based on those templates. I had the idea that the templates could be extensions of the Class class, but that resulted in some magnificent errors: VerifyError: Error #1107: The ABC data is corrupt, attempt to read out of bounds. What I'm wondering is if subclassing Class is even possible, if there is perhaps some case where doing this would be appropriate, and not just a gross misuse of OOP. I believe it should be possible, as ActionScript allows you to create variables of the Class type. This use is described in the LiveDocs entry for Class, yet I've seen no mentions of subclassing Class. Here's a pseudocode example: class Foo extends Class var a:Foo = new Foo(); trace(a is Class) // true, right? var b = new a(); I have no idea what the type of b would be. In summary: can you subclass the Class class? If so, how can you do it without errors, and what type are the instances of the instances of the Class subclass?

    Read the article

  • Where should I put contextual data related to an Object that is not really a property of the object?

    - by RenderIn
    I have a Car class. It has three properties: id, color and model. In a particular query I want to return all the cars and their properties, and I also want to return a true/false field called "searcherKnowsOwner" which is a field I calculate in my database query based on whether or not the individual conducting the search knows the owner. I have a database function that takes the ID of the searcher and the ID of the car and returns a boolean. My car class looks like this (pseudocode): class Car{ int id; Color color; Model model; } I have a screen where I want to display all the cars, but I also want to display a flag next to each car if the person viewing the page knows the owner of that car. Should I add a field to the Car class, a boolean searcherKnowsOwner? It's not a property of the car, but is actually a property of the user conducting the search. But this seems like the most efficient place to put this information.

    Read the article

  • Generic callbacks

    - by bobobobo
    Extends So, I'm trying to learn template metaprogramming better and I figure this is a good exercise for it. I'm trying to write code that can callback a function with any number of arguments I like passed to it. // First function to call int add( int x, int y ) ; // Second function to call double square( double x ) ; // Third func to call void go() ; The callback creation code should look like: // Write a callback object that // will be executed after 42ms for "add" Callback<int, int, int> c1 ; c1.func = add ; c1.args.push_back( 2 ); // these are the 2 args c1.args.push_back( 5 ); // to pass to the "add" function // when it is called Callback<double, double> c2 ; c2.func = square ; c2.args.push_back( 52.2 ) ; What I'm thinking is, using template metaprogramming I want to be able to declare callbacks like, write a struct like this (please keep in mind this is VERY PSEUDOcode) <TEMPLATING ACTION <<ANY NUMBER OF TYPES GO HERE>> > struct Callback { double execTime ; // when to execute TYPE1 (*func)( TYPE2 a, TYPE3 b ) ; void* argList ; // a stored list of arguments // to plug in when it is time to call __func__ } ; So for when called with Callback<int, int, int> c1 ; You would automatically get constructed for you by < HARDCORE TEMPLATING ACTION > a struct like struct Callback { double execTime ; // when to execute int (*func)( int a, int b ) ; void* argList ; // this would still be void*, // but I somehow need to remember // the types of the args.. } ; Any pointers in the right direction to get started on writing this?

    Read the article

  • Find min. "join" operations for sequence

    - by utyle
    Let's say, we have a list/an array of positive integers x1, x2, ... , xn. We can do a join operation on this sequence, that means that we can replace two elements that are next to each other with one element, which is sum of these elements. For example: - array/list: [1;2;3;4;5;6] we can join 2 and 3, and replace them with 5; we can join 5 and 6, and replace them with 11; we cannot join 2 and 4; we cannot join 1 and 3 etc. Main problem is to find minimum join operations for given sequence, after which this sequence will be sorted in increasing order. Note: empty and one-element sequences are sorted in increasing order. Basic examples: for [4; 6; 5; 3; 9] solution is 1 (we join 5 and 3) for [1; 3; 6; 5] solution is also 1 (we join 6 and 5) What I am looking for, is an algorithm that solve this problem. It could be in pseudocode, C, C++, PHP, OCaml or similar (I mean: I woluld understand solution, if You wrote solution in one of these languages). I would appreciate Your help.

    Read the article

  • How to write this function as a pL/pgSQl function ?

    - by morpheous
    I am trying to implement some business logic in a PL/pgSQL function. I have hacked together some pseudo code that explains the type of business logic I want to include in the function. Note: This function returns a table, so I can use it in a query like: SELECT A.col1, B.col1 FROM (SELECT * from some_table_returning_func(1, 1, 2, 3)) as A, tbl2 as B; The pseudocode of the pl/PgSQL function is below: CREATE FUNCTION some_table_returning_func(uid int, type_id int, filter_type_id int, filter_id int) RETURNS TABLE AS $$ DECLARE where_clause text := 'tbl1.id = ' + uid; ret TABLE; BEGIN switch (filter_type_id) { case 1: switch (filter_id) { case 1: where_clause += ' AND tbl1.item_id = tbl2.id AND tbl2.type_id = filter_id'; break; //other cases follow ... } break; //other cases follow ... } // where clause has been built, now run query based on the type ret = SELECT [COL1, ... COLN] WHERE where_clause; IF (type_id <> 1) THEN return ret; ELSE return select * from another_table_returning_func(ret,123); ENDIF; END; $$ LANGUAGE plpgsql; I have the following questions: How can I write the function correctly to (i.e. EXECUTE the query with the generated WHERE clause, and to return a table How can I write a PL/pgSQL function that accepts a table and an integer and returns a table (another_table_returning_func) ?

    Read the article

  • SQLAlchemy Expression Language problem

    - by Torkel
    I'm trying to convert this to something sqlalchemy expression language compatible, I don't know if it's possible out of box and are hoping someone more experienced can help me along. The backend is PostgreSQL and if I can't make it as an expression I'll create a string instead. SELECT DISTINCT date_trunc('month', x.x) as date, COALESCE(b.res1, 0) AS res1, COALESCE(b.res2, 0) AS res2 FROM generate_series( date_trunc('year', now() - interval '1 years'), date_trunc('year', now() + interval '1 years'), interval '1 months' ) AS x LEFT OUTER JOIN( SELECT date_trunc('month', access_datetime) AS when, count(NULLIF(resource_id != 1, TRUE)) AS res1, count(NULLIF(resource_id != 2, TRUE)) AS res2 FROM tracking_entries GROUP BY date_trunc('month', access_datetime) ) AS b ON (date_trunc('month', x.x) = b.when) First of all I got a class TrackingEntry mapped to tracking_entries, the select statement within the outer joined can be converted to something like (pseudocode):: from sqlalchemy.sql import func, select from datetime import datetime, timedelta stmt = select([ func.date_trunc('month', TrackingEntry.resource_id).label('when'), func.count(func.nullif(TrackingEntry.resource_id != 1, True)).label('res1'), func.count(func.nullif(TrackingEntry.resource_id != 2, True)).label('res2') ], group_by=[func.date_trunc('month', TrackingEntry.access_datetime), ]) Considering the outer select statement I have no idea how to build it, my guess is something like: outer = select([ func.distinct(func.date_trunc('month', ?)).label('date'), func.coalesce(?.res1, 0).label('res1'), func.coalesce(?.res2, 0).label('res2') ], from_obj=[ func.generate_series( datetime.now(), datetime.now() + timedelta(days=365), timedelta(days=1) ).label(x) ]) Then I suppose I have to link those statements together without using foreign keys: outer.outerjoin(stmt???).??(func.date_trunc('month', ?.?), ?.when) Anyone got any suggestions or even better a solution?

    Read the article

  • Stop an executing recursive javascript function

    - by DA
    Using jQuery, I've build an image/slide rotator. The basic setup is (in pseudocode): function setupUpSlide(SlideToStartWith){ var thisSlide = SlideToStartWith; ...set things up... fadeInSlide(thisSlide) } function fadeInSlide(thisSlide){ ...fade in this slide... fadeOutSlide(thisSlide) } function fadeOutSlide(thisSlide){ ...fade out this slide... setupUpSlide(nextSlide) } I call the first function and pass in a particular slide index, and then it does its thing calling chain of functions which then, in turn, calls the first function again passing in the next index. This then repeats infinitely (resetting the index when it gets to the last item). This works just fine. What I want to do now is allow someone to over-ride the slide show by being able to click on a particular slide number. Therefore, if slide #8 is showing and I click #3, I want the recursion to stop and then call the initial function passing in slide #3, which then, in turn, will start the process again. But I'm not sure how to go about that. How does one properly 'break' a recursive script. Should I create some sort of global 'watch' variable that if at any time is 'true' will return: false and allow the new function to execute?

    Read the article

  • Given a main function and a cleanup function, how (canonically) do I return an exit status in Bash/Linux?

    - by Zac B
    Context: I have a bash script (a wrapper for other scripts, really), that does the following pseudocode: do a main function if the main function returns: $returncode = $? #most recent return code if the main function runs longer than a timeout: kill the main function $returncode = 140 #the semi-canonical "exceeded allowed wall clock time" status run a cleanup function if the cleanup function returns an error: #nonzero return code exit $? #exit the program with the status returned from the cleanup function else #cleanup was successful .... Question: What should happen after the last line? If the cleanup function was successful, but the main function was not, should my program return 0 (for the successful cleanup), or $returncode, which contains the (possibly nonzero and unsuccessful) return code of the main function? For a specific application, the answer would be easy: "it depends on what you need the script for." However, this is more of a general/canonical question (and if this is the wrong place for it, kill it with fire): in Bash (or Linux in general) programming, do you typically want to return the status that "means" something (i.e. $returncode) or do you ignore such subjectivities and simply return the code of the most recent function? This isn't Bash-specific: if I have a standalone executable of any kind, how, canonically should it behave in these cases? Obviously, this is somewhat debatable. Even if there is a system for these things, I'm sure that a lot of people ignore it. All the same, I'd like to know. Cheers!

    Read the article

  • Accept templated parameter of stl_container_type<string>::iterator

    - by Rodion Ingles
    I have a function where I have a container which holds strings (eg vector<string>, set<string>, list<string>) and, given a start iterator and an end iterator, go through the iterator range processing the strings. Currently the function is declared like this: template< typename ContainerIter> void ProcessStrings(ContainerIter begin, ContainerIter end); Now this will accept any type which conforms to the implicit interface of implementing operator*, prefix operator++ and whatever other calls are in the function body. What I really want to do is have a definition like the one below which explicitly restricts the amount of input (pseudocode warning): template< typename Container<string>::iterator> void ProcessStrings(Container<string>::iterator begin, Container<string>::iterator end); so that I can use it as such: vector<string> str_vec; list<string> str_list; set<SomeOtherClass> so_set; ProcessStrings(str_vec.begin(), str_vec.end()); // OK ProcessStrings(str_list.begin(), str_list.end()); //OK ProcessStrings(so_set.begin(), so_set.end()); // Error Essentially, what I am trying to do is restrict the function specification to make it obvious to a user of the function what it accepts and if the code fails to compile they get a message that they are using the wrong parameter types rather than something in the function body that XXX function could not be found for XXX class.

    Read the article

  • How to write this snippet in Python?

    - by morpheous
    I am learning Python (I have a C/C++ background). I need to write something practical in Python though, whilst learning. I have the following pseudocode (my first attempt at writing a Python script, since reading about Python yesterday). Hopefully, the snippet details the logic of what I want to do. BTW I am using python 2.6 on Ubuntu Karmic. Assume the script is invoked as: script_name.py directory_path import csv, sys, os, glob # Can I declare that the function accepts a dictionary as first arg? def getItemValue(item, key, defval) return !item.haskey(key) ? defval : item[key] dirname = sys.argv[1] # declare some default values here weight, is_male, default_city_id = 100, true, 1 # fetch some data from a database table into a nested dictionary, indexed by a string curr_dict = load_dict_from_db('foo') #iterate through all the files matching *.csv in the specified folder for infile in glob.glob( os.path.join(dirname, '*.csv') ): #get the file name (without the '.csv' extension) code = infile[0:-4] # open file, and iterate through the rows of the current file (a CSV file) f = open(infile, 'rt') try: reader = csv.reader(f) for row in reader: #lookup the id for the code in the dictionary id = curr_dict[code]['id'] name = row['name'] address1 = row['address1'] address2 = row['address2'] city_id = getItemValue(row, 'city_id', default_city_id) # insert row to database table finally: f.close() I have the following questions: Is the code written in a Pythonic enough way (is there a better way of implementing it)? Given a table with a schema like shown below, how may I write a Python function that fetches data from the table and returns is in a dictionary indexed by string (name). How can I insert the row data into the table (actually I would like to use a transaction if possible, and commit just before the file is closed) Table schema: create table demo (id int, name varchar(32), weight float, city_id int); BTW, my backend database is postgreSQL

    Read the article

  • Finding the width of a directed acyclic graph... with only the ability to find parents

    - by Platinum Azure
    Hi guys, I'm trying to find the width of a directed acyclic graph... as represented by an arbitrarily ordered list of nodes, without even an adjacency list. The graph/list is for a parallel GNU Make-like workflow manager that uses files as its criteria for execution order. Each node has a list of source files and target files. We have a hash table in place so that, given a file name, the node which produces it can be determined. In this way, we can figure out a node's parents by examining the nodes which generate each of its source files using this table. That is the ONLY ability I have at this point, without changing the code severely. The code has been in public use for a while, and the last thing we want to do is to change the structure significantly and have a bad release. And no, we don't have time to test rigorously (I am in an academic environment). Ideally we're hoping we can do this without doing anything more dangerous than adding fields to the node. I'll be posting a community-wiki answer outlining my current approach and its flaws. If anyone wants to edit that, or use it as a starting point, feel free. If there's anything I can do to clarify things, I can answer questions or post code if needed. Thanks! EDIT: For anyone who cares, this will be in C. Yes, I know my pseudocode is in some horribly botched Python look-alike. I'm sort of hoping the language doesn't really matter.

    Read the article

  • Copy and paste between sheets in a workbook with VBA code

    - by Hannah
    Trying to write a macro in VBA for Excel to look at the value in a certain column from each row of data in a list and if that value is "yes" then it copies and pastes the entire row onto a different sheet in the same workbook. Let's name the two sheets "Data" and "Final". I want to have the sheets referenced so it does not matter which sheet I have open when it runs the code. I was going to use a Do loop to cycle through the rows on the one data sheet until it finds there are no more entries, and if statements to check the values. I am confused about how to switch from one sheet to the next. How do I specifically reference cells in different sheets? Here is the pseudocode I had in mind: Do while DataCells(x,1).Value <> " " for each DataCells(x,1).Value="NO" if DataCells(x,2).Value > DataCells(x,3).Value or _ DataCells(x,4).Value < DataCells(x,5).Value 'Copy and paste/insert row x from Data to Final sheet adding a new 'row for each qualifying row else x=x+1 end else if DataCells(x,1).Value="YES" Loop 'copy and paste entire row to a third sheet 'continue this cycle until all rows in the data sheet are examined

    Read the article

  • DirectX: Game loop order, draw first and then handle input?

    - by Ricket
    I was just reading through the DirectX documentation and encountered something interesting in the page for IDirect3DDevice9::BeginScene : To enable maximal parallelism between the CPU and the graphics accelerator, it is advantageous to call IDirect3DDevice9::EndScene as far ahead of calling present as possible. I've been accustomed to writing my game loop to handle input and such, then draw. Do I have it backwards? Maybe the game loop should be more like this: (semi-pseudocode, obviously) while(running) { d3ddev->Clear(...); d3ddev->BeginScene(); // draw things d3ddev->EndScene(); // handle input // do any other processing // play sounds, etc. d3ddev->Present(NULL, NULL, NULL, NULL); } According to that sentence of the documentation, this loop would "enable maximal parallelism". Is this commonly done? Are there any downsides to ordering the game loop like this? I see no real problem with it after the first iteration... And I know the best way to know the actual speed increase of something like this is to actually benchmark it, but has anyone else already tried this and can you attest to any actual speed increase?

    Read the article

  • Website. VoteUp or VoteDown Videos. How to restrict users voting multiple times?

    - by DJDonaL3000
    Im working on a website (html,css,javascript, ajax, php,mysql), and I want to restrict the number of times a particular user votes for a particular video. Its similar to the YouTube system where you can voteUp or voteDown a particular video. Each vote involves adding a row to the video.votes table, which logs the time, vote direction(up or down), the client IPaddress( using PHP: $ip = $_SERVER['REMOTE_ADDR']; ), and of course the ID of the video in question. Adding votes is as simple as; (pseudocode): Javascript:onClick( vote( a,b,c,d ) ), which passes variables to PHP insertion script via ajax, and finally we replace the voteing buttons with a "Thank You For Voting" message. THE PROBLEM: If you reload/refresh the page after voting, you can vote again, and again, and again, you get the point. MY QUESTION: How do you limit the amount of times a particular user votes for a particular video?? MY THOUGHTS: Do you use cookies, and add a new cookie with the id of the video. And check for a cookie before you insert a new vote.? OR Before you insert the vote, do you use the IPaddress and the videoID to see if this same user(IP) has voted for this same video(vidID) in the past 24hrs(mktime), and either allow or dissallow the voteInsertion based on this query? OR Do you just not care? Take the assumption that most users are sane, and have better things to do than refresh pages and vote repeatedly.?? Any suggestions or ideas welcome.

    Read the article

  • Parsing data from txt file in J2ME

    - by CSFYPMAIL
    Basically I'm creating an indoor navigation system in J2ME. I've put the location details in a .txt file i.e. Locations names and their coordinates. Edges with respective start node and end node as well as the weight (length of the node). I put both details in the same file so users dont have to download multiple files to get their map working (it could become time consuming and seem complex). So what i did is to seperate the deferent details by typing out location Names and coordinates first, After that I seperated that section from the next section which is the edges by drawing a line with multiple underscores. Now the problem I'm having is parsing the different details into seperate arrays by setting up a command (while manually tokenizing the input stream) to check wether the the next token is an underscore. If it is, (in pseudocode terms), move to the next line in the stream, create a new array and fill it up with the next set of details. I found a some explanation/code HERE that does something similar but still parses into one array, although it manually tokenizes the input. Any ideas on what to do? Thanks Text File Explanation The text has the following format... <--1stSection--  /**   * Section one has the following format   * xCoordinate;yCoordinate;LocationName   */ 12;13;New York City 40;12;Washington D.C. ...e.t.c _________________________ <--(underscore divider) <--2ndSection--  /**   * Its actually an adjacency list but indirectly provides "edge" details.   * Its in this form   * StartNode/MainReferencePoint;Endnode1;distance2endNode1;Endnode2;distance2endNode2;...e.t.c   */ philadelphia;Washington D.C.;7;New York City;2 New York City;Florida;24;Illinois;71 ...e.t.c

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15  | Next Page >