Search Results

Search found 5942 results on 238 pages for 'total starnger'.

Page 216/238 | < Previous Page | 212 213 214 215 216 217 218 219 220 221 222 223  | Next Page >

  • iPhone: Problems releasing UIViewController in a multithreaded environment

    - by bart-simpson
    Hi! I have a UIViewController and in that controller, i am fetching an image from a URL source. The image is fetched in a separate thread after which the user-interface is updated on the main thread. This controller is displayed as a page in a UIScrollView parent which is implemented to release controllers that are not in view anymore. When the thread finishes fetching content before the UIViewController is released, everything works fine - but when the user scrolls to another page before the thread finishes, the controller is released and the only handle to the controller is owned by the thread making releaseCount of the controller equals to 1. Now, as soon as the thread drains NSAutoreleasePool, the controller gets releases because the releaseCount becomes 0. At this point, my application crashes and i get the following error message: bool _WebTryThreadLock(bool), 0x4d99c60: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now... The backtrace reveals that the application crashed on the call to [super dealloc] and it makes total sense because the dealloc function must have been triggered by the thread when the pool was drained. My question is, how i can overcome this error and release the controller without leaking memory? One solution that i tried was to call [self retain] before the pool is drained so that retainCount doesn't fall to zero and then using the following code to release controller in the main thread: [self performSelectorOnMainThread:@selector(autorelease) withObject:nil waitUntilDone:NO]; Unfortunately, this did not work out. Below is the function that is executed on a thread: - (void)thread_fetchContent { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSURL *imgURL = [NSURL URLWithString:@"http://www.domain.com/image.png"]; // UIImage *imgHotspot is declared as private - The image is retained // here and released as soon as it is assigned to UIImageView imgHotspot = [[[UIImage alloc] initWithData: [NSData dataWithContentsOfURL: imgURL]] retain]; if ([self retainCount] == 1) { [self retain]; // increment retain count ~ workaround [pool drain]; // drain pool // this doesn't work - i get the same error [self performSelectorOnMainThread:@selector(autorelease) withObject:nil waitUntilDone:NO]; } else { // show fetched image on the main thread - this works fine! [self performSelectorOnMainThread:@selector(showImage) withObject:nil waitUntilDone:NO]; [pool drain]; } } Please help! Thank you in advance.

    Read the article

  • Python: Script works, but seems to deadlock after some time

    - by sberry2A
    I have the following script, which is working for the most part Link to PasteBin The script's job is to start a number of threads which in turn each start a subprocess with Popen. The output from each subprocess is as follows: 1 2 3 . . . n Done Bascially the subprocess is transferring 10M records from tables in one database to different tables in another db with a lot of data massaging/manipulation in between because of the different schemas. If the subprocess fails at any time in it's execution (bad records, duplicate primary keys, etc), or it completes successfully, it will output "Done\n". If there are no more records to select against for transfer then it will output "NO DATA\n" My intent was to create my script "tableTransfer.py" which would spawn a number of these processes, read their output, and in turn output information such as number of updates completed, time remaining, time elapsed, and number of transfers per second. I started running the process last night and checked in this morning to see it had deadlocked. There were not subprocceses running, there are still records to be updated, and the script had not exited. It was simply sitting there, no longer outputting the current information because no subprocces were running to update the total number complete which is what controls updates to the output. This is running on OS X. I am looking for three things: I would like to get rid of the possibility of this deadlock occurring so I don't need to check in on it as frequently. Is there some issue with locking? Am I doing this in a bad way (gThreading variable to control looping of spawning additional thread... etc.) I would appreciate some suggestions for improving my overall methodology. How should I handle ctrl-c exit? Right now I need to kill the process, but assume I should be able to use the signal module or other to catch the signal and kill the threads, is that right? I am not sure whether I should be pasting my entire script here, since I usually just paste snippets. Let me know if I should paste it here as well.

    Read the article

  • How to optimize this SQL query for a rectangular region?

    - by Andrew B.
    I'm trying to optimize the following query, but it's not clear to me what index or indexes would be best. I'm storing tiles in a two-dimensional plane and querying for rectangular regions of that plane. The table has, for the purposes of this question, the following columns: id: a primary key integer world_id: an integer foreign key which acts as a namespace for a subset of tiles tileY: the Y-coordinate integer tileX: the X-coordinate integer value: the contents of this tile, a varchar if it matters. I have the following indexes: "ywot_tile_pkey" PRIMARY KEY, btree (id) "ywot_tile_world_id_key" UNIQUE, btree (world_id, "tileY", "tileX") "ywot_tile_world_id" btree (world_id) And this is the query I'm trying to optimize: ywot=> EXPLAIN ANALYZE SELECT * FROM "ywot_tile" WHERE ("world_id" = 27685 AND "tileY" <= 6 AND "tileX" <= 9 AND "tileX" >= -2 AND "tileY" >= -1 ); QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------------------- Bitmap Heap Scan on ywot_tile (cost=11384.13..149421.27 rows=65989 width=168) (actual time=79.646..80.075 rows=96 loops=1) Recheck Cond: ((world_id = 27685) AND ("tileY" <= 6) AND ("tileY" >= (-1)) AND ("tileX" <= 9) AND ("tileX" >= (-2))) -> Bitmap Index Scan on ywot_tile_world_id_key (cost=0.00..11367.63 rows=65989 width=0) (actual time=79.615..79.615 rows=125 loops=1) Index Cond: ((world_id = 27685) AND ("tileY" <= 6) AND ("tileY" >= (-1)) AND ("tileX" <= 9) AND ("tileX" >= (-2))) Total runtime: 80.194 ms So the world is fixed, and we are querying for a rectangular region of tiles. Some more information that might be relevant: All the tiles for a queried region may or may not be present The height and width of a queried rectangle are typically about 10x10-20x20 For any given (world, X) or (world, Y) pair, there may be an unbounded number of matching tiles, but the worst case is currently around 10,000, and typically there are far fewer. New tiles are created far less frequently than existing ones are updated (changing the 'value'), and that itself is far less frequent that just reading as in the query above. The only thing I can think of would be to index on (world, X) and (world, Y). My guess is that the database would be able to take those two sets and intersect them. The problem is that there is a potentially unbounded number of matches for either for either of those. Is there some other kind of index that would be more appropriate?

    Read the article

  • How to generate and encode (for use in GA), random, strict, binary rooted trees with N leaves?

    - by Peter Simon
    First, I am an engineer, not a computer scientist, so I apologize in advance for any misuse of nomenclature and general ignorance of CS background. Here is the motivational background for my question: I am contemplating writing a genetic algorithm optimizer to aid in designing a power divider network (also called a beam forming network, or BFN for short). The BFN is intended to distribute power to each of N radiating elements in an array of antennas. The fraction of the total input power to be delivered to each radiating element has been specified. Topologically speaking, a BFN is a strictly binary, rooted tree. Each of the (N-1) interior nodes of the tree represents the input port of an unequal, binary power splitter. The N leaves of the tree are the power divider outputs. Given a particular power divider topology, one is still free to map the power divider outputs to the array inputs in an arbitrary order. There are N! such permutations of the outputs. There are several considerations in choosing the desired ordering: 1) The power ratio for each binary coupler should be within a specified range of values. 2) The ordering should be chosen to simplify the mechanical routing of the transmission lines connecting the power divider. The number of ouputs N of the BFN may range from, say, 6 to 22. I have already written a genetic algorithm optimizer that, given a particular BFN topology and desired array input power distribution, will search through the N! permutations of the BFN outputs to generate a design with compliant power ratios and good mechanical routing. I would now like to generalize my program to automatically generate and search through the space of possible BFN topologies. As I understand it, for N outputs (leaves of the binary tree), there are $C_{N-1}$ different topologies that can be constructed, where $C_N$ is the Catalan number. I would like to know how to encode an arbitrary tree having N leaves in a way that is consistent with a chromosomal description for use in a genetic algorithm. Also associated with this is the need to generate random instances for filling the initial population, and to implement crossover and mutations operators for this type of chromosome. Any suggestions will be welcome. Please minimize the amount of CS lingo in your reply, since I am not likely to be acquainted with it. Thanks in advance, Peter

    Read the article

  • Is there a scheduling algorithm that optimizes for "maker's schedules"?

    - by John Feminella
    You may be familiar with Paul Graham's essay, "Maker's Schedule, Manager's Schedule". The crux of the essay is that for creative and technical professionals, meetings are anathema to productivity, because they tend to lead to "schedule fragmentation", breaking up free time into chunks that are too small to acquire the focus needed to solve difficult problems. In my firm we've seen significant benefits by minimizing the amount of disruption caused, but the brute-force algorithm we use to decide schedules is not sophisticated enough to handle scheduling large groups of people well. (*) What I'm looking for is if there's are any well-known algorithms which minimize this productivity disruption, among a group of N makers and managers. In our model, There are N people. Each person pi is either a maker (Mk) or a manager (Mg). Each person has a schedule si. Everyone's schedule is H hours long. A schedule consists of a series of non-overlapping intervals si = [h1, ..., hj]. An interval is either free or busy. Two adjacent free intervals are equivalent to a single free interval that spans both. A maker's productivity is maximized when the number of free intervals is minimized. A manager's productivity is maximized when the total length of free intervals is maximized. Notice that if there are no meetings, both the makers and the managers experience optimum productivity. If meetings must be scheduled, then makers prefer that meetings happen back-to-back, while managers don't care where the meeting goes. Note that because all disruptions are treated as equally harmful to makers, there's no difference between a meeting that lasts 1 second and a meeting that lasts 3 hours if it segments the available free time. The problem is to decide how to schedule M different meetings involving arbitrary numbers of the N people, where each person in a given meeting must place a busy interval into their schedule such that it doesn't overlap with any other busy interval. For each meeting Mt the start time for the busy interval must be the same for all parties. Does an algorithm exist to solve this problem or one similar to it? My first thought was that this looks really similar to defragmentation (minimize number of distinct chunks), and there are a lot of algorithms about that. But defragmentation doesn't have much to do with scheduling. Thoughts? (*) Practically speaking this is not really a problem, because it's rare that we have meetings with more than ~5 people at once, so the space of possibilities is small.

    Read the article

  • Cannot figure out how to take in generic parameters for an Enterprise Framework library sql statemen

    - by KallDrexx
    I have written a specialized class to wrap up the enterprise library database functionality for easier usage. The reasoning for using the Enterprise Library is because my applications commonly connect to both oracle and sql server database systems. My wrapper handles both creating connection strings on the fly, connecting, and executing queries allowing my main code to only have to write a few lines of code to do database stuff and deal with error handling. As an example my ExecuteNonQuery method has the following declaration: /// <summary> /// Executes a query that returns no results (e.g. insert or update statements) /// </summary> /// <param name="sqlQuery"></param> /// <param name="parameters">Hashtable containing all the parameters for the query</param> /// <returns>The total number of records modified, -1 if an error occurred </returns> public int ExecuteNonQuery(string sqlQuery, Hashtable parameters) { // Make sure we are connected to the database if (!IsConnected) { ErrorHandler("Attempted to run a query without being connected to a database.", ErrorSeverity.Critical); return -1; } // Form the command DbCommand dbCommand = _database.GetSqlStringCommand(sqlQuery); // Add all the paramters foreach (string key in parameters.Keys) { if (parameters[key] == null) _database.AddInParameter(dbCommand, key, DbType.Object, null); else _database.AddInParameter(dbCommand, key, DbType.Object, parameters[key].ToString()); } return _database.ExecuteNonQuery(dbCommand); } _database is defined as private Database _database;. Hashtable parameters are created via code similar to p.Add("@param", value);. the issue I am having is that it seems that with enterprise library database framework you must declare the dbType of each parameter. This isn't an issue when you are calling the database code directly when forming the paramters but doesn't work for creating a generic abstraction class such as I have. In order to try and get around that I thought I could just use DbType.Object and figure the DB will figure it out based on the columns the sql is working with. Unfortunately, this is not the case as I get the following error: Implicit conversion from data type sql_variant to varchar is not allowed. Use the CONVERT function to run this query Is there any way to use generic parameters in a wrapper class or am I just going to have to move all my DB code into my main classes?

    Read the article

  • STDOUT can not return to Screen

    - by rockyurock
    STDOUT can not return to Screen Hello all below is the part of my code, my code enters "if loop" with $value =1 and output of the process "iperf.exe" is getting into my_output.txt. As i am timing out the process after alram(20sec) time,also wanted to capture the output of this process only. then after i want to continue to the command prompt but i am not able to return to the command promt... not only this code itself does not PRINT on the command prompt , rather it is priniting on the my_output.txt file (i am looping this if loop through rest of my code) output.txt ========== inside value loop2 ------------------------------------------------------------ Server listening on UDP port 5001 Receiving 1470 byte datagrams UDP buffer size: 8.00 KByte (default) ------------------------------------------------------------ [160] local 10.232.62.151 port 5001 connected with 10.232.62.151 port 1505 [ ID] Interval Transfer Bandwidth Jitter Lost/Total Datagrams [160] 0.0- 5.0 sec 2.14 MBytes 3.59 Mbits/sec 0.000 ms 0/ 1528 (0%) inside value loop3 clue1 clue2 inside value loop4 one iperf completed Transfer Transfer Starting: Intent { act=android.settings.APN_SETTINGS } ******AUTOMATION COMPLETED****** Looks some problem with reinitializing the STDOUT.. even i tried to use close(STDOUT); but again it did not return to STDOUT could sombbody please help out ?? /rocky CODE:: if($value) { my $file = 'my_output.txt'; use Win32::Process; print"inside value loop\n"; # redirect stdout to a file open STDOUT, '>', $file or die "can't redirect STDOUT to <$file> $!"; Win32::Process::Create(my $ProcessObj, "iperf.exe", "iperf.exe -u -s -p 5001", 0, NORMAL_PRIORITY_CLASS, ".") || die ErrorReport(); $alarm_time = $IPERF_RUN_TIME+2; #20sec print"inside value loop2\n"; sleep $alarm_time; $ProcessObj->Kill(0); sub ErrorReport{ print Win32::FormatMessage( Win32::GetLastError() ); } print"inside value loop3\n"; print"clue1\n"; #close(STDOUT); print"clue2\n"; print"inside value loop4\n"; print"one iperf completed\n"; } my $data_file="my_output.txt"; open(ROCK, $data_file)|| die("Could not open file!"); @raw_data=<ROCK>; @COUNT_PS =split(/ /,$raw_data[7]); my $LOOP_COUNT_PS_4 = $COUNT_PS[9]; my $LOOP_COUNT_PS_5 = $COUNT_PS[10]; print "$LOOP_COUNT_PS_4\n"; print "$LOOP_COUNT_PS_5\n"; my $tput_value = "$LOOP_COUNT_PS_4"." $LOOP_COUNT_PS_5"; print "$tput_value"; close(ROCK); print FH1 "\n $count \| $tput_value \n"; regds rakesh

    Read the article

  • Speeding up templates in GAE-Py by aggregating RPC calls

    - by Sudhir Jonathan
    Here's my problem: class City(Model): name = StringProperty() class Author(Model): name = StringProperty() city = ReferenceProperty(City) class Post(Model): author = ReferenceProperty(Author) content = StringProperty() The code isn't important... its this django template: {% for post in posts %} <div>{{post.content}}</div> <div>by {{post.author.name}} from {{post.author.city.name}}</div> {% endfor %} Now lets say I get the first 100 posts using Post.all().fetch(limit=100), and pass this list to the template - what happens? It makes 200 more datastore gets - 100 to get each author, 100 to get each author's city. This is perfectly understandable, actually, since the post only has a reference to the author, and the author only has a reference to the city. The __get__ accessor on the post.author and author.city objects transparently do a get and pull the data back (See this question). Some ways around this are Use Post.author.get_value_for_datastore(post) to collect the author keys (see the link above), and then do a batch get to get them all - the trouble here is that we need to re-construct a template data object... something which needs extra code and maintenance for each model and handler. Write an accessor, say cached_author, that checks memcache for the author first and returns that - the problem here is that post.cached_author is going to be called 100 times, which could probably mean 100 memcache calls. Hold a static key to object map (and refresh it maybe once in five minutes) if the data doesn't have to be very up to date. The cached_author accessor can then just refer to this map. All these ideas need extra code and maintenance, and they're not very transparent. What if we could do @prefetch def render_template(path, data) template.render(path, data) Turns out we can... hooks and Guido's instrumentation module both prove it. If the @prefetch method wraps a template render by capturing which keys are requested we can (atleast to one level of depth) capture which keys are being requested, return mock objects, and do a batch get on them. This could be repeated for all depth levels, till no new keys are being requested. The final render could intercept the gets and return the objects from a map. This would change a total of 200 gets into 3, transparently and without any extra code. Not to mention greatly cut down the need for memcache and help in situations where memcache can't be used. Trouble is I don't know how to do it (yet). Before I start trying, has anyone else done this? Or does anyone want to help? Or do you see a massive flaw in the plan?

    Read the article

  • Information Gain and Entropy

    - by dhorn
    I recently read this question regarding information gain and entropy. I think I have a semi-decent grasp on the main idea, but I'm curious as what to do with situations such as follows: If we have a bag of 7 coins, 1 of which is heavier than the others, and 1 of which is lighter than the others, and we know the heavier coin + the lighter coin is the same as 2 normal coins, what is the information gain associated with picking two random coins and weighing them against each other? Our goal here is to identify the two odd coins. I've been thinking this problem over for a while, and can't frame it correctly in a decision tree, or any other way for that matter. Any help? EDIT: I understand the formula for entropy and the formula for information gain. What I don't understand is how to frame this problem in a decision tree format. EDIT 2: Here is where I'm at so far: Assuming we pick two coins and they both end up weighing the same, we can assume our new chances of picking H+L come out to 1/5 * 1/4 = 1/20 , easy enough. Assuming we pick two coins and the left side is heavier. There are three different cases where this can occur: HM: Which gives us 1/2 chance of picking H and a 1/4 chance of picking L: 1/8 HL: 1/2 chance of picking high, 1/1 chance of picking low: 1/1 ML: 1/2 chance of picking low, 1/4 chance of picking high: 1/8 However, the odds of us picking HM are 1/7 * 5/6 which is 5/42 The odds of us picking HL are 1/7 * 1/6 which is 1/42 And the odds of us picking ML are 1/7 * 5/6 which is 5/42 If we weight the overall probabilities with these odds, we are given: (1/8) * (5/42) + (1/1) * (1/42) + (1/8) * (5/42) = 3/56. The same holds true for option B. option A = 3/56 option B = 3/56 option C = 1/20 However, option C should be weighted heavier because there is a 5/7 * 4/6 chance to pick two mediums. So I'm assuming from here I weight THOSE odds. I am pretty sure I've messed up somewhere along the way, but I think I'm on the right path! EDIT 3: More stuff. Assuming the scale is unbalanced, the odds are (10/11) that only one of the coins is the H or L coin, and (1/11) that both coins are H/L Therefore we can conclude: (10 / 11) * (1/2 * 1/5) and (1 / 11) * (1/2) EDIT 4: Going to go ahead and say that it is a total 4/42 increase.

    Read the article

  • Is the recent trend toward widescreen (16:9) computer monitors a plus or minus for programmers?

    - by DanM
    It's almost gotten to the point where you can't buy a conventional (4:3) monitor anymore. Pretty much everything is widescreen. This is fine for watching movies or TV, but is it good or bad for programming? My initial thoughts on the issue are that widescreens are a net negative for programmers. Here are some of the disadvantages I see: Poor space utiliziation One disadvantage of widescreens you can't argue with is that they offer poor space utilization for the amount of total pixels you get. For example, my Thinkpad, which I bought just before the widescreen craze, has a 15" monitor with a native resolution of 1600 x 1200. The newer 15.4" Thinkpads run at most 1680 x 1050. So (if you do the math) you get fewer pixels in a wider (but not shorter) package. With desktop monitors, you pay a price in terms of desk space used. Two 1680 x 1050 monitors will simply take up more of your desk than two 1600 x 1200 monitors (assuming equal dot pitch). More scrolling If you compare a 1680 x 1050 monitor to a 1600 x 1200 monitor, you get 80 extra pixels of width but 150 fewer pixels of height. The height reduction means you lose approximately 11 lines of code. That's less you can see on the screen at one time and more scrolling you have to do. This harms productivity, maybe not dramatically, but insidiously. Less room for wide panels Widescreens also mean you lose space for wide but short panels common in programming environments. If you use Visual Studio, for example, your code window will be that much shorter when viewing the Find Results, Task List, or Error List (all of which I use frequently). This isn't to say the 80 pixels of extra width you get with widescreen would never be useful, but I tend to keep my lines of code short, so seeing more lines would be more valuable to me than seeing fewer, longer lines. What do you think? Do you agree/disagree? Are you now using one or more widescreen monitors for development? What resolution are you running on each? Do you ever miss the height of the traditional 4:3 monitor? Would you complain if your monitors were one inch narrower but two inches taller?

    Read the article

  • My first c# app and first null object exception

    - by Fresheyeball
    Total noob here. This is my first c# attempt, its a console application that simulates a drinking game called 'Left Right Center'. In the console I receive the following: CONSOLE Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object at LeftRightCenter.MainClass.Main (System.String[] args) [0x00038] in /Users/apple/Projects/LearningC/LearningC/Main.cs:80 [ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object at LeftRightCenter.MainClass.Main (System.String[] args) [0x00038] in /Users/apple/Projects/LearningC/LearningC/Main.cs:80 C# using System; namespace LeftRightCenter { class Player { //fields private int _quarters = 4; public int Quarters { get{ return _quarters; } set{ _quarters += value; } } public Player (string name) { } } class Dice { Random random = new Random(); public int Roll () { random = new Random (); int diceSide; diceSide = random.Next (0, 6); diceSide = (diceSide > 2) ? 3 : diceSide; return diceSide; } } class MainClass { static int activePlayer = 0; static int theCup = 0; static Player[] thePlayers = { new Player ("Jessica"), new Player ("Isaac"), new Player ("Ed"), new Player ("Bella"), new Player ("Elisa"), new Player ("Fake RedHead"), new Player ("Linda"), new Player ("MJ"), new Player ("Irene"), new Player("Devin") }; static Dice[] theDice = new Dice[2]; private static void MoveQuarter (int direction) { int numberOfPlayers = thePlayers.Length - 1; switch (direction) { case 0: thePlayers [activePlayer].Quarters = -1; theCup++; break; case 1: thePlayers [activePlayer].Quarters = -1; int leftPlayer = (activePlayer == 0) ? numberOfPlayers : activePlayer - 1; thePlayers [leftPlayer].Quarters = +1; break; case 2: thePlayers [activePlayer].Quarters = -1; int rightPlayer = (activePlayer == numberOfPlayers) ? 0 : activePlayer + 1; thePlayers [rightPlayer].Quarters = +1; break; } } public static void Main (string[] args) { int cupEndPoint = thePlayers.Length * 4 - 1; while (theCup < cupEndPoint) { foreach (Dice rattle in theDice) { if (thePlayers [activePlayer].Quarters > 0) { MoveQuarter (rattle.Roll ()); // this line seems to be the problem } } Console.WriteLine ("{0} Quarters In the Cup", theCup); } } } } I have no idea what the problem is or why, and my googling have proven more use confusing than helpful.

    Read the article

  • Code golf - hex to (raw) binary conversion

    - by Alnitak
    In response to this question asking about hex to (raw) binary conversion, a comment suggested that it could be solved in "5-10 lines of C, or any other language." I'm sure that for (some) scripting languages that could be achieved, and would like to see how. Can we prove that comment true, for C, too? NB: this doesn't mean hex to ASCII binary - specifically the output should be a raw octet stream corresponding to the input ASCII hex. Also, the input parser should skip/ignore white space. edit (by Brian Campbell) May I propose the following rules, for consistency? Feel free to edit or delete these if you don't think these are helpful, but I think that since there has been some discussion of how certain cases should work, some clarification would be helpful. The program must read from stdin and write to stdout (we could also allow reading from and writing to files passed in on the command line, but I can't imagine that would be shorter in any language than stdin and stdout) The program must use only packages included with your base, standard language distribution. In the case of C/C++, this means their respective standard libraries, and not POSIX. The program must compile or run without any special options passed to the compiler or interpreter (so, 'gcc myprog.c' or 'python myprog.py' or 'ruby myprog.rb' are OK, while 'ruby -rscanf myprog.rb' is not allowed; requiring/importing modules counts against your character count). The program should read integer bytes represented by pairs of adjacent hexadecimal digits (upper, lower, or mixed case), optionally separated by whitespace, and write the corresponding bytes to output. Each pair of hexadecimal digits is written with most significant nibble first. The behavior of the program on invalid input (characters besides [a-fA-F \t\r\n], spaces separating the two characters in an individual byte, an odd number of hex digits in the input) is undefined; any behavior (other than actively damaging the user's computer or something) on bad input is acceptable (throwing an error, stopping output, ignoring bad characters, treating a single character as the value of one byte, are all OK) The program may write no additional bytes to output. Code is scored by fewest total bytes in the source file. (Or, if we wanted to be more true to the original challenge, the score would be based on lowest number of lines of code; I would impose an 80 character limit per line in that case, since otherwise you'd get a bunch of ties for 1 line).

    Read the article

  • xerces-c: Xml parsing multiple files

    - by user459811
    I'm atempting to learn xerces-c and was following this tutorial online. http://www.yolinux.com/TUTORIALS/XML-Xerces-C.html I was able to get the tutorial to compile and run through a memory checker (valgrind) with no problems however when I made alterations to the program slightly, the memory checker returned some potential leak bytes. I only added a few extra lines to main to allow the program to read two files instead of one. int main() { string configFile="sample.xml"; // stat file. Get ambigious segfault otherwise. GetConfig appConfig; appConfig.readConfigFile(configFile); cout << "Application option A=" << appConfig.getOptionA() << endl; cout << "Application option B=" << appConfig.getOptionB() << endl; // Added code configFile = "sample1.xml"; appConfig.readConfigFile(configFile); cout << "Application option A=" << appConfig.getOptionA() << endl; cout << "Application option B=" << appConfig.getOptionB() << endl; return 0; } I was wondering why is it when I added the extra lines of code to read in another xml file, it would result in the following output? ==776== Using Valgrind-3.6.0 and LibVEX; rerun with -h for copyright info ==776== Command: ./a.out ==776== Application option A=10 Application option B=24 Application option A=30 Application option B=40 ==776== ==776== HEAP SUMMARY: ==776== in use at exit: 6 bytes in 2 blocks ==776== total heap usage: 4,031 allocs, 4,029 frees, 1,092,045 bytes allocated ==776== ==776== 3 bytes in 1 blocks are definitely lost in loss record 1 of 2 ==776== at 0x4C28B8C: operator new(unsigned long) (vg_replace_malloc.c:261) ==776== by 0x5225E9B: xercesc_3_1::MemoryManagerImpl::allocate(unsigned long) (MemoryManagerImpl.cpp:40) ==776== by 0x53006C8: xercesc_3_1::IconvGNULCPTranscoder::transcode(unsigned short const*, xercesc_3_1::MemoryManager*) (IconvGNUTransService.cpp:751) ==776== by 0x4038E7: GetConfig::readConfigFile(std::string&) (in /home/bonniehan/workspace/test/a.out) ==776== by 0x403B13: main (in /home/bonniehan/workspace/test/a.out) ==776== ==776== 3 bytes in 1 blocks are definitely lost in loss record 2 of 2 ==776== at 0x4C28B8C: operator new(unsigned long) (vg_replace_malloc.c:261) ==776== by 0x5225E9B: xercesc_3_1::MemoryManagerImpl::allocate(unsigned long) (MemoryManagerImpl.cpp:40) ==776== by 0x53006C8: xercesc_3_1::IconvGNULCPTranscoder::transcode(unsigned short const*, xercesc_3_1::MemoryManager*) (IconvGNUTransService.cpp:751) ==776== by 0x40393F: GetConfig::readConfigFile(std::string&) (in /home/bonniehan/workspace/test/a.out) ==776== by 0x403B13: main (in /home/bonniehan/workspace/test/a.out) ==776== ==776== LEAK SUMMARY: ==776== definitely lost: 6 bytes in 2 blocks ==776== indirectly lost: 0 bytes in 0 blocks ==776== possibly lost: 0 bytes in 0 blocks ==776== still reachable: 0 bytes in 0 blocks ==776== suppressed: 0 bytes in 0 blocks ==776== ==776== For counts of detected and suppressed errors, rerun with: -v ==776== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 2 from 2)

    Read the article

  • Working with hibernate/DAO problems

    - by Gandalf StormCrow
    Hello everyone here is my DAO class : public class UsersDAO extends HibernateDaoSupport { private static final Log log = LogFactory.getLog(UsersDAO.class); protected void initDao() { //do nothing } public void save(User transientInstance) { log.debug("saving Users instance"); try { getHibernateTemplate().saveOrUpdate(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void update(User transientInstance) { log.debug("updating User instance"); try { getHibernateTemplate().update(transientInstance); log.debug("update successful"); } catch (RuntimeException re) { log.error("update failed", re); throw re; } } public void delete(User persistentInstance) { log.debug("deleting Users instance"); try { getHibernateTemplate().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public User findById( java.lang.Integer id) { log.debug("getting Users instance with id: " + id); try { User instance = (User) getHibernateTemplate() .get("project.hibernate.Users", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } } Now I wrote a test class(not a junit test) to test is everything working, my user has these fields in the database : userID which is 5characters long string and unique/primary key, and fields such as address, dob etc(total 15 columns in database table). Now in my test class I intanciated User added the values like : User user = new User; user.setAddress("some address"); and so I did for all 15 fields, than at the end of assigning data to User object I called in DAO to save that to database UsersDao.save(user); and save works just perfectly. My question is how do I update/delete users using the same logic? Fox example I tried this(to delete user from table users): User user = new User; user.setUserID("1s54f"); // which is unique key for users no two keys are the same UsersDao.delete(user); I wanted to delete user with this key but its obviously different can someone explain please how to do these. thank you

    Read the article

  • flickr.photos.search strange behavior with nested xml response

    - by JohnIdol
    I am querying flickr with the following request: view-source:http://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=MY_KEY&text=cork&per_page=12&&format=rest if I put the above url in the browser I get the following as I would expect: <rsp stat="ok"> <photos page="1" pages="22661" perpage="12" total="271924"> <photo id="4587565363" owner="46277999@N05" secret="717118838d" server="4029" farm="5" title="06052010(001)" ispublic="1" isfriend="0" isfamily="0" /> <photo id="4587466773" owner="25901874@N06" secret="32c5a1a57f" server="4002" farm="5" title="black wine cork 2 BW" ispublic="1" isfriend="0" isfamily="0" /> <photo id="4588084730" owner="25901874@N06" secret="b27eef5635" server="4032" farm="5" title="black wine cork 2" ispublic="1" isfriend="0" isfamily="0" /> <photo id="4587457789" owner="43115275@N00" secret="ae0daa0ab6" server="4034" farm="5" title="Matthew" ispublic="1" isfriend="0" isfamily="0" /> <photo id="4587443837" owner="49967920@N07" secret="2b4c1a58de" server="4066" farm="5" title="Two car garage" ispublic="1" isfriend="0" isfamily="0" /> <photo id="4588050906" owner="45827769@N06" secret="72de138f7e" server="4067" farm="5" title="Dabie Mountains, Central China" ispublic="1" isfriend="0" isfamily="0" /> <photo id="4587979300" owner="36531359@N00" secret="e5f8b30734" server="3299" farm="4" title="stroll" ispublic="1" isfriend="0" isfamily="0" /> <photo id="4587304769" owner="7904649@N02" secret="995062f550" server="4034" farm="5" title="IMG_4325" ispublic="1" isfriend="0" isfamily="0" /> <photo id="4587306827" owner="7904649@N02" secret="b92d7ff916" server="4050" farm="5" title="IMG_4329" ispublic="1" isfriend="0" isfamily="0" /> <photo id="4587311657" owner="7904649@N02" secret="bb1b34ccf8" server="4053" farm="5" title="IMG_4336" ispublic="1" isfriend="0" isfamily="0" /> <photo id="4587933110" owner="7904649@N02" secret="f733b1d482" server="3300" farm="4" title="IMG_4334" ispublic="1" isfriend="0" isfamily="0" /> <photo id="4587930650" owner="7904649@N02" secret="9bc202b3ed" server="4018" farm="5" title="IMG_4331" ispublic="1" isfriend="0" isfamily="0" /> </photos> </rsp> Now I've got something very simple PHP to query the exact same url, called from javascript through AJAX - it all works as I can see putting a breakpoint in my javascript function that handles the response: function HandleResponse(response) { document.getElementById('ResponseDiv').innerHTML = response; } Looking at response value in the snippet above I see what I expect (xml formed as above) - then the strangest thing happens: when I inspect the DOM instead of having photo elements all as children of photos they're all nested within each other. What amI missing - How is this possible in light of the fact that the response string is definitely formed as I would expect it to be?

    Read the article

  • Using PHP session_id() to Make Sure iframe is Generated by Our Server Dynamically

    - by Michael Robinson
    We use iframes to show ads on our site. Iframes are used to allow us to keep the ad generation code and other site modules separate. As we track ad views on our site, and need to be able to keep an accurate count of which pagetype gets what views, I must ensure that users can't simply copy-paste the iframe in which the ad is loaded onto another site. This would cause ad count to become inflated for this page, and the count would not match the view count of the page the iframe "should" be displayed in. Before anyone says so: no I can't simply compare the page view count with the ad view count, or use the page view count * number of ads per page, as # of ads per page will not necessarily be static. I need to come up with a solution that will allow ads to be shown only for iframes that are generated dynamically and are shown on our pages. I am not familiar with PHP sessions, but from what little reading I have had time to do, the following seems to be to be an acceptable solution: Add "s = session_id()" to the src of the ad's iframe. In the code that receives and processes ad requests, only return (and count) and ad if s == session_id(). Please correct me if I'm wrong, but this would ensure: Ads would only be returned to iframes whose src was generated alongside the rest of the page's content, as is the case during normal use. We can return our logo to ad calls with an invalid session_id. So a simple example would be: One of our pages: <?php session_start(); ?> <div id="someElement"> <!-- EVERYONE LOVES ADS --> <iframe src="http//awesomesite.com/ad/can_has_ad.php?s=<?php echo session_id(); ?>></iframe> </div> ad/can_has_ad.php: <?php session_start(); ?> if($_GET['s'] == session_id()){ echo 'can has ad'; } else{ echo '<img src="http://awesomesite.com/images/canhaslogo.jpg"/>'; } And finally, copied code with static 's' parameter: <!-- HAHA LULZ I WILL SCREW WITH YOUR AD VIEW COUNTS LULZ HAHA --> <iframe src="http//awesomesite.com/ad/can_has_ad.php?s=77f2b5fcdab52f52607888746969b0ad></iframe> Which would give them an iframe showing our awesome site's logo, and not screw with our view counts. I made some basic test cases: two files, one that generates the iframe and echos it, and one that the iframe's src is pointed to, that checks the 's' parameter and shows an appropriate message depending on the result. I copied the iframe into a file and hosted it on a different server, and the correct message was displayed (cannot has ad). So, my question is: Would this work or am I being a PHP session noob, with the above test being a total fluke? Thanks for your time! Edit: I'm trying to solve this without touching the SQL server

    Read the article

  • Mysterious constraints problem with SQL Server 2000

    - by Ramon
    Hi all I'm getting the following error from a VB NET web application written in VS 2003, on framework 1.1. The web app is running on Windows Server 2000, IIS 5, and is reading from a SQL server 2000 database running on the same machine. System.Data.ConstraintException: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints. at System.Data.DataSet.FailedEnableConstraints() at System.Data.DataSet.EnableConstraints() at System.Data.DataSet.set_EnforceConstraints(Boolean value) at System.Data.DataTable.EndLoadData() at System.Data.Common.DbDataAdapter.FillFromReader(Object data, String srcTable, IDataReader dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue) at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String srcTable, IDataReader dataReader, Int32 startRecord, Int32 maxRecords) at System.Data.Common.DbDataAdapter.FillFromCommand(Object data, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) The problem appears when the web app is under a high load. The system runs fine when volume is low, but when the number of requests becomes high, the system starts rejecting incoming requests with the above exception message. Once the problem appears, very few requests actually make it through and get processed normally, about 2 in every 30. The vast majority of requests fail, until a SQL Server restart or IIS reset is performed. The system then start processing requests normally, and after some time it starts throwing the same error. The error occurs when a data adapter runs the Fill() method against a SELECT statement, to populate a strongly-typed dataset. It appears that the dataset does not like the data it is given and throws this exception. This error occurs on various SELECT statements, acting on different tables. I have regenerated the dataset and checked the relevant constraints, as well as the table from which the data is read. Both the dataset definition and the data in the table are fine. Admittedly, the hardware running both the web app and SQL Server 2000 is seriously outdated, considering the numbers of incoming requests it currently receives. The amount of RAM consumed by SQL Server is dynamically allocated, and at peak times SQL Server can consume up to 2.8 GB out of a total of 3.5 GB on the server. At first I suspected some sort of index or database corruption, but after running DBCC CHECKDB, no errors were found in the database. So now I'm wondering whether this error is a result of the hardware limitations of the system. Is it possible for SQL Server to somehow mess up the data it's supposed to pass to the dataset, resulting in constraint violation due to, say, data type/length mismatch? I tried accessing the RowError messages of the data rows in the retrieved dataset tables but I kept getting empty strings. I know that HasErrors = true for the datatables in question. I have not set the EnableConstraints = false, and I don't want to do that. Thanks in advance. Ray

    Read the article

  • iPhone Image Resources, ICO vs PNG, app bundle filesize

    - by Jasarien
    My application has a collection of around 1940 icons that are used throughout. They're currently in ICO and new images provided to me come in ICO format too. I have noticed that they contain a 16x16 and 32x32 representation of each icon in one file. Each file is roughly 4KB in filesize (as reported by finder, but ls reports that they vary from being ~1000 bytes to 5000 bytes) A very small number of these icons only contain the 32x32 representation, and as a result are only around 700 bytes in size. Currently I am bundling these icons with my application and they are inflating the size of the app a bit more than I would like. Altogether, the images total just about 25.5MB. Xcode must do some kind of compression because the resulting app bundle is about 12.4MB. Compressing this further into a ZIP (as it would be when submitted to the App Store), results in a final file of 5.8MB. I'm aware that the maximum limit for over the air App Store downloads has been raised to 20MB since the introduction of the iPad (I'm not sure if that extends to iPhone apps as well as iPad apps though, if not the limit would be 10MB). My worry is that new icons are going to be added (sometimes up to 10 icons per week), and will continue to inflate the app bundle over time. What is the best way to distribute these icons with my app? Things I've tried and not had much success with: Converting the icons from ICO to PNG: I tried this in the hopes that the pngcrush utility would help out with the filesize. But it appears that it doesn't make much of a difference between a normal PNG and a crushed png (I believe it just optimises the image for display on the iPhone's GPU rather than compress it's size). Also in going from ICO to PNG actually increased the size of the icon file... Zipping the images, and then uncompressing them on first run. While this did reduce the overall image sizes, I found that the effort needed to unzip them, copy them to the documents folder and ensure that duplication doesn't happen on upgrades was too much hassle to be worth the benefit. Also, on original and 3G iPhones unzipping and copying around 25MB of images takes too long and creates a bad experience... Things I've considered but not yet tried: Instead of distributing the icons within the app bundle, host them online, and download each icon on demand (it depends on the user's data as to which icons will actually be displayed and when). Issues with this is that bandwidth costs money, and image downloads will be bandwidth intensive. However, my app currently has a small userbase of around 5,500 users (of which I estimate around 1500 to be active based on Flurry stats), and I have a huge unused bandwidth allowance with my current hosting package. So I'm open to thoughts on how to solve this tricky issue.

    Read the article

  • Java app makes screen display unresponsive after 10 minutes of user idle time

    - by Ross
    I've written a Java app that allows users to script mouse/keyboard input (JMacro, link not important, only for the curious). I personally use the application to automate character actions in an online game overnight while I sleep. Unfortunately, I keep coming back to the computer in the morning to find it unresponsive. Upon further testing, I'm finding that my application causes the computer to become unresponsive after about 10 minutes of user idle time (even if the application itself it simulating user activity). I can't seem to pin-point the issue, so I'm hoping somebody else might have a suggestion of where to look or what might be causing the issue. The relevant symptoms and characteristics: Unresponsiveness occurs after user is idle for 10 minutes User can still move the mouse pointer around the screen Everything but the mouse appears frozen... mouse clicks have no effect and no applications update their displays, including the Windows 7 desktop I left the task manager up along the with the app overnight so I could see the last task manager image before the screen freezes... the Java app is at normal CPU/Memory usage and total CPU usage is only ~1% After moving the mouse (in other words, the user comes back from being idle), the screen image starts updating again within 30 minutes (this is very hit and miss... sometimes 10 minutes, sometimes no results after two hours) User can CTRL-ALT-DEL to get to Windows 7's CTRL-ALT-DEL screen (after a 30 second pause). User is still able to move mouse pointer, but clicking any of the button options causes the screen to appear to freeze again On some very rare occasions, the system never freezes, and I come back to it in the morning with full responsiveness The Java app automatically stops input scripting in the middle of the night, so Windows 7 detects "real" idleness and turns the monitors into Standby mode... which they successfully come out of upon manually moving the mouse in the morning when I wake up, even though the desktop display still appears frozen Given the symptoms and characteristics of the issue, it's as if the Java app is causing the desktop display of the logged in user to stop updating, including any running applications. Programming concepts and Java packages used: Multi-threading Standard out and err are rerouted to a javax.swing.JTextArea The application uses a Swing GUI awt.Robot (very heavily used) awt.PointerInfo awt.MouseInfo System Specs: Windows 7 Professional Java 1.6.0 u17 In conclusion, I should stress that I'm not looking for any specific solutions, as I'm not asking a very specific question. I'm just wondering if anybody has run into a similar problem when using the Java libraries that I'm using. I would also gladly appreciate any suggestions for things to try to attempt to further pinpoint what is causing my problem. Thanks! Ross PS, I'll post an update/answer if I manage to stumble across anything else while I continue to debug this.

    Read the article

  • Generate a list of file names based on month and year arithmetic

    - by MacUsers
    How can I list the numbers 01 to 12 (one for each of the 12 months) in such a way so that the current month always comes last where the oldest one is first. In other words, if the number is grater than the current month, it's from the previous year. e.g. 02 is Feb, 2011 (the current month right now), 03 is March, 2010 and 09 is Sep, 2010 but 01 is Jan, 2011. In this case, I'd like to have [09, 03, 01, 02]. This is what I'm doing to determine the year: for inFile in os.listdir('.'): if inFile.isdigit(): month = months[int(inFile)] if int(inFile) <= int(strftime("%m")): year = strftime("%Y") else: year = int(strftime("%Y"))-1 mnYear = month + ", " + str(year) I don't have a clue what to do next. What should I do here? Update: I think, I better upload the entire script for better understanding. #!/usr/bin/env python import os, sys from time import strftime from calendar import month_abbr vGroup = {} vo = "group_lhcb" SI00_fig = float(2.478) months = tuple(month_abbr) print "\n%-12s\t%10s\t%8s\t%10s" % ('VOs','CPU-time','CPU-time','kSI2K-hrs') print "%-12s\t%10s\t%8s\t%10s" % ('','(in Sec)','(in Hrs)','(*2.478)') print "=" * 58 for inFile in os.listdir('.'): if inFile.isdigit(): readFile = open(inFile, 'r') lines = readFile.readlines() readFile.close() month = months[int(inFile)] if int(inFile) <= int(strftime("%m")): year = strftime("%Y") else: year = int(strftime("%Y"))-1 mnYear = month + ", " + str(year) for line in lines[2:]: if line.find(vo)==0: g, i = line.split() s = vGroup.get(g, 0) vGroup[g] = s + int(i) sumHrs = ((vGroup[g]/60)/60) sumSi2k = sumHrs*SI00_fig print "%-12s\t%10s\t%8s\t%10.2f" % (mnYear,vGroup[g],sumHrs,sumSi2k) del vGroup[g] When I run the script, I get this: [root@serv07 usage]# ./test.py VOs CPU-time CPU-time kSI2K-hrs (in Sec) (in Hrs) (*2.478) ================================================== Jan, 2011 211201372 58667 145376.83 Dec, 2010 5064337 1406 3484.07 Feb, 2011 17506049 4862 12048.04 Sep, 2010 210874275 58576 145151.33 As I said in the original post, I like the result to be in this order instead: Sep, 2010 210874275 58576 145151.33 Dec, 2010 5064337 1406 3484.07 Jan, 2011 211201372 58667 145376.83 Feb, 2011 17506049 4862 12048.04 The files in the source directory reads like this: [root@serv07 usage]# ls -l total 3632 -rw-r--r-- 1 root root 1144972 Feb 9 19:23 01 -rw-r--r-- 1 root root 556630 Feb 13 09:11 02 -rw-r--r-- 1 root root 443782 Feb 11 17:23 02.bak -rw-r--r-- 1 root root 1144556 Feb 14 09:30 09 -rw-r--r-- 1 root root 370822 Feb 9 19:24 12 Did I give a better picture now? Sorry for not being very clear in the first place. Cheers!! Update @Mark Ransom This is the result from Mark's suggestion: [root@serv07 usage]# ./test.py VOs CPU-time CPU-time kSI2K-hrs (in Sec) (in Hrs) (*2.478) ========================================================== Dec, 2010 5064337 1406 3484.07 Sep, 2010 210874275 58576 145151.33 Feb, 2011 17506049 4862 12048.04 Jan, 2011 211201372 58667 145376.83 As I said before, I'm looking for the result to b printed in this order: Sep, 2010 - Dec, 2010 - Jan, 2011 - Feb, 2011 Cheers!!

    Read the article

  • Populating a PHP array within a foreach loop

    - by patrick
    I am wanting to add each user into an array and check for duplicates before I do. $spotcount = 10; for ($topuser_count = 0; $topuser_count < $spotcount; $topuser_count++) //total spots { $spottop10 = $ids[$topuser_count]; $top_10 = $gowalla->getSpotInfo($spottop10); $usercount = 0; $c = 0; $array = array(); foreach($top_10['top_10'] as $top10) //loop each spot { //$getuser = substr($top10['url'],7); //strip the url $getuser = ltrim($top10['url'], " users/" ); if ($usercount < 3) //loop only certain number of top users { if (($getuser != $userurl) && (array_search($getuser, $array) !== true)) { //echo " no duplicates! <br /><br />"; echo ' <a href= "http://gowalla.com'.$top10['url'].'"><img width="90" height="90" src= " '.$top10['image_url'].' " title="'.$top10['first_name'].'" alt="Error" /></a> '; $array[$c++] = $getuser; } else { //echo "duplicate <br /><br />"; } } $usercount++; } print_r($array); } The previous code prints: Array ( [0] => 62151 [1] => 204501 [2] => 209368 ) Array ( [0] => 62151 [1] => 33116 [2] => 122485 ) Array ( [0] => 120728 [1] => 205247 [2] => 33116 ) Array ( [0] => 150883 [1] => 248551 [2] => 248558 ) Array ( [0] => 157580 [1] => 77490 [2] => 52046 ) Which is wrong. It does check for duplicates, but only the contents of each foreach loop instead of the entire array. How is this if I am storing everything into $array?

    Read the article

  • vim plugin to show current Perl subroutine

    - by Andrew
    I'm trying to make a vim plugin that will split the window on load and simulate a info bar at the top of my terminal. I've got it sorta working but I think I've either reached limits of my knowledge of vim syntax or there's a logic problem in my code. The desired effect would be to do a reverse search for any declaration of a Perl subroutine form my current location in the active buffer and display the line in the top buffer. I'm also trying to make it skip that buffer when I switch buffers with <C-R>. My attempt at that so far can be seen in the mess of nested if statements. Anyway, here's the code. I would greatly appreciate feedback from anyone. (pastebin pastebin.com/8cuMPn1Q) let s:current_function_bufname = 'Current\ Function\/Subroutine' function! s:get_current_function_name(no_echo) let lnum = line(".") let col = col(".") if a:no_echo let s:current_function_name = getline(search("^[^s]sub .$", 'bW')) else echohl ModeMsg echo getline(search("^[^s]sub .$", 'bW')) "echo getline(search("^[^ \t#/]\{2}.[^:]\s$", 'bW')) echohl None endif endfunction let s:previous_winbufnr = 1 let s:current_function_name = '' let s:current_function_buffer_created = 0 let s:current_function_bufnr = 2 function! s:show_current_function() let total_buffers = winnr('$') let current_winbufnr = winnr() if s:previous_winbufnr != current_winbufnr if bufname(current_winbufnr) == s:current_function_bufname if s:previous_winbufnr < current_winbufnr let i = current_winbufnr + 1 if i total_buffers let i = 1 endif if i == s:current_function_bufnr let i = i + 1 endif if i total buffers let i = 1 endif exec i.'wincmd w' else let i = current_winbufnr - 1 if i < 1 let i = total_buffers endif if i == s:current_function_bufnr let i = i - 1 endif if i < 1 let i = total_buffers endif try exec i.'wincmd w' finally exec total_buffers.'wincmd w' endtry endif endif let s:previous_winbufnr = current_winbufnr return 1 endif if s:current_function_buffer_created == 0 exec 'top 1 split '.s:current_function_bufname call s:set_as_scratch_buffer() let s:current_function_buffer_created = 1 let s:current_function_bufnr = winnr() endif call s:activate_buffer_by_name(s:current_function_bufname) setlocal modifiable call s:get_current_function_name(1) call setline(1, s:current_function_name) setlocal nomodifiable call s:activate_buffer_by_name(bufname(current_winbufnr)) endfunction function! s:set_as_scratch_buffer() setlocal noswapfile setlocal nomodifiable setlocal bufhidden=delete setlocal buftype=nofile setlocal nobuflisted setlocal nonumber setlocal nowrap setlocal cursorline endfunction function! s:activate_buffer_by_name(name) for i in range(1, winnr('$')) let name = bufname(winbufnr(i)) let full_name = fnamemodify(bufname(winbufnr(i)), ':p') if name == a:name || full_name == a:name exec i.'wincmd w' return 1 endif endfor return 0 endfunction set laststatus=2 autocmd! CursorMoved,CursorMovedI,BufWinEnter * call s:show_current_function() (pastebin pastebin.com/8cuMPn1Q) similar to VIM: display custom reference bar on top of window and http://vim.wikia.com/wiki/Show_current_function_name_in_C_programs

    Read the article

  • Writing to a xml file in java

    - by user243680
    import java.io.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import org.w3c.dom.*; public class CreatXMLFile { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); // System.out.print("Enter number to add elements in your XML file: "); // String str = bf.readLine(); int no=2; // System.out.print("Enter root: "); String root = "SMS"; DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder =documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element rootElement = document.createElement(root); document.appendChild(rootElement); // for (int i = 1; i <= no; i++) // System.out.print("Enter the element: "); // String element = bf.readLine(); String element ="Number"; System.out.print("Enter the Number: "); String data = bf.readLine(); Element em = document.createElement(element); em.appendChild(document.createTextNode(data)); rootElement.appendChild(em); String element1 ="message"; System.out.print("Enter the SMS: "); String data1 = bf.readLine(); Element em1 = document.createElement(element1); em1.appendChild(document.createTextNode(data1)); rootElement.appendChild(em1); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } } i am working on the above code and it gives the following output run: Enter the Number: 768678 Enter the SMS: ytu <?xml version="1.0" encoding="UTF-8" standalone="no"?><SMS><Number>768678</Number><message>ytu</message></SMS>BUILD SUCCESSFUL (total time: 8 seconds) Now i want to write the output generated(<?xml version="1.0" encoding="UTF-8" standalone="no"?><SMS><Number>768678</Number><message>ytu</message></SMS>) to a XML file on the hard disk.How do i do it?

    Read the article

  • JQuery $.ajax doesn't return anything, but only in Google Chrome!?

    - by Shawson
    Hi All, I'm hoping someone can help me with this as I'm at a loss. I'm trying to simply load a plain text file into a page at runtime using jquery- everything works fine in IE8 (8.0.7600.16385), Firefox 3.6.3, however in Google Chrome 5.0.375.55 the "data" comes back as nothing- i get an empty alert box. This is the code i'm using; <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Animation Test</title> <script type="text/javascript" language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" language="javascript"> $(document).ready(function () { $.ajax({ url: 'level1.txt', success: function (data) { alert(data); }, async: true, type: 'GET' }); }); </script> </head> <body> <canvas id="canvas" width="640" height="480"> Unsupported Browser </canvas> </body> </html> The file I'm loading in is a plain text file containing this; Central Cavern 100 O.........1.C....C...........1.O O................1.............O O..............................O O..............................O O......................B1..B...O O=============~~~~=~~~~========O O.............................1O O===...........................O O............A..OOO.B..........O O====...<<<<<<<<<<<<<<<<<<<<...O O............................==O O..............................O O..........B........OOO.....===O O....===============...........O O%............................XO O==============================O (Yes- it's the first level from Manic Miner! I'm making a javascript version using the html5 canvas to get my head around using it.) I'm at a total loss- it can't be the code because it runs in the other 2 browsers- is there an issue with jquery and this version of Chrome? Thanks for reading!! Shaw.

    Read the article

  • how to develop a program to minimize errors in human transcription of hand written surveys

    - by Alex. S.
    I need to develop custom software to do surveys. Questions may be of multiple choice, or free text in a very few cases. I was asked to design a subsystem to check if there is any error in the manual data entry for the multiple choices part. We're trying to speed up the user data entry process and to minimize human input differences between digital forms and the original questionnaires. The surveys are filled with handwritten marks and text by human interviewers, so it's possible to find hard to read marks, or also the user could accidentally select a different value in some question, and we would like to avoid that. The software must include some automatic control to detect possible typing differences. Each answer of the multiple choice questions has the same probability of being selected. This question has two parts: The GUI. The most simple thing I have in mind is to implement the most usable design of the questions display: use of large and readable fonts and space generously the choices. Is there something else? For faster input, I would like to use drop down lists (favoring keyboard over mouse). Given the questions are grouped in sections, I would like to show the answers selected for the questions of that section, but this could slow down the process. Any other ideas? The error checking subsystem. What else can I do to minimize or to check human typos in the multiple choice questions? Is this a solvable problem? is there some statistical methodology to check values that were entered by the users are the same from the hand filled forms? For example, let's suppose the survey has 5 questions, and each has 4 options. Let's say I have n survey forms filled in paper by interviewers, and they're ready to be entered in the software, then how to minimize the accidental differences that can have the manual transcription of the n surveys, without having to double check everything in the 5 questions of the n surveys? My first suggestion is that at the end of the processing of all the hand filled forms, the software could choose some forms randomly to make a double check of the responses in a few instances, but on what criteria can I make this selection? This validation would be enough to cover everything in a significant way? The actual survey is nation level and it has 56 pages with over 200 questions in total, so it will be a lot of hand written pages by many people, and the intention is to reduce the likelihood of errors and to optimize speed in the data entry process. The surveys must filled in paper first, given the complications of taking laptops or handhelds with the interviewers.

    Read the article

< Previous Page | 212 213 214 215 216 217 218 219 220 221 222 223  | Next Page >