Search Results

Search found 70 results on 3 pages for 'andres cardona'.

Page 3/3 | < Previous Page | 1 2 3 

  • Documentation String Stub, Python

    - by Andres Orozco
    Well i'm learning Python cuz' i think is an awesome and powerful language like C++, perl or C# but is really really easy at same time. I'm using JetBrains' Pycharm and when i define a function it ask me to add a "Documentation String Stub" when i click yes it adds somethin like this: """ """ so the full code of the function is something like this: def otherFunction(h, w): """ """ hello = h world = w full_word = h + ' ' + w return full_word I would like to know what these (""" """) symbols means, Thanks. Ps.Data: Sorry for my bad english :D

    Read the article

  • How can I format Custom Data and display in autocomplete when source is an DB

    - by Andres Scarpone
    so I'm trying to get some info in the auto-complete widget like it's shown in the JQuery UI demo Demo, the only problem is they use a variable that they fill with the data they want to show, I instead want to access the data and the different description and stuff using a Data Base in MySQL, for this I have changed the source to use another php page that looks up the info. here is the code for the Auto-complete, I really don't understand the methods so I haven't changed it from the basic search. This is the JS: $(document).ready((function(){ $( "#completa" ).autocomplete({ source: "buscar.php", minLength: 1, focus: function (event, ui){ $("#completa").val(ui.item.val); return false; }; })); This is what I have in buscar.php: <?php $conec = mysql_connect(localhost, root, admin); if(!$conec) { die(mysql_error()); } else { $bd = mysql_select_db("ve_test",$conec ); if(!$bd) { die(mysql_error()); } } $termino = trim(strip_tags($_GET['term']));//Obtener el termino que envia el autocompletar $qstring = "SELECT name, descripcion FROM VE_table WHERE name LIKE '%".$termino."%'"; $result = mysql_query($qstring);//Solicitud a la Base de Datos while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//Realizar un LOOP sobre los valores obtenidos { $row['value']=htmlentities(stripslashes($row['name'])); $row_set[] = $row;//build an array } echo json_encode($row_set);//Enviar los datos al autocompletar en codificacion JSON, Altamente Necesario. ?

    Read the article

  • Traversable => Java Iterator

    - by Andres
    I have a Traversable, and I want to make it into a Java Iterator. My problem is that I want everything to be lazily done. If I do .toIterator on the traversable, it eagerly produces the result, copies it into a List, and returns an iterator over the List. I'm sure I'm missing something simple here... Here is a small test case that shows what I mean: class Test extends Traversable[String] { def foreach[U](f : (String) => U) { f("1") f("2") f("3") throw new RuntimeException("Not lazy!") } } val a = new Test val iter = a.toIterator

    Read the article

  • Delphi 6 storeproc on windows 7

    - by Andres
    I work with Delphi 6 and SQL Server 2008. With Windows Vista everything runs ok. But since i change my OS to Windows 7 all my projects started to show a message when i'm trying to compile them that says "Stored procedure (SPname). Doesn't found or doesn't exist in the server. I look my server and it has the Sp with the correct name. i used ODBC connection and try the SQL Server and the SQL Native client 10.0 but the problem continues. the projects connect to the D.B with no problem until i try to run a SP. if i run the same projects in a vista again they work fine. If any of you can help me i really appreciate.......

    Read the article

  • Create collage with multiple images

    - by Andres
    I'm having quite a challenge... I have a web page where the user clicks on images, those images have to be added together to create only one image and the user must be able to download that group of images as only one... I have no idea how to do this, any tip or info so I can start researching? Here is an example I found searching with google: In my case each of the squares of the image would be a totally different image but this Is what I have to achieve... Thanks!

    Read the article

  • Images from url to listview

    - by Andres
    I have a listview which I show video results from YouTube. Everything works fine but one thing I noticed is that the way it works seems to be a bit slow and it might be due to my code. Are there any suggestions on how I can make this better? Maybe loading the images directly from the url instead of using a webclient? I am adding the listview items in a loop from video feeds returned from a query using the YouTube API. The piece of code which I think is slowing it down is this: Feed<Video> videoFeed = request.Get<Video>(query); int i = 0; foreach (Video entry in videoFeed.Entries) { string[] info = printVideoEntry(entry).Split(','); WebClient wc = new WebClient(); wc.DownloadFile(@"http://img.youtube.com/vi/" + info[0].ToString() + "/hqdefault.jpg", info[0].ToString() + ".jpg"); string[] row1 = { "", info[0].ToString(), info[1].ToString() }; ListViewItem item = new ListViewItem(row1, i); YoutubeList.Items.Add(item); imageListSmall.Images.Add(Bitmap.FromFile(info[0].ToString() + @".jpg")); imageListLarge.Images.Add(Bitmap.FromFile(info[0].ToString() + @".jpg")); } public static string printVideoEntry(Video video) { return video.VideoId + "," + video.Title; } As you can see I use a Webclient which downloads the images so then I can use them as image in my listview. It works but what I'm concerned about is speed..any suggestions? maybe a different control all together?

    Read the article

  • Find a node in a Graph that minimizes the distance between two other nodes

    - by Andrés
    Here is the thing. I have a directed weighted graph G, with V vertices and E edges. Given two nodes in the graph, let's say A, and B, and given the weight of an edge A-B denoted as w(A, B), I need to find a node C so that max(w(A, C), w(B, C)) is minimal among all possibilities. By possibilities I mean all the values C can take. I don't know if it is completely clear, if it's not, I'll try to be more precise. Thanks in advance.

    Read the article

  • php function to make slug (url string)

    - by andufo
    function gen_slug($str){ # special accents $a = array('À','Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö','Ø','Ù','Ú','Û','Ü','Ý','ß','à','á','â','ã','ä','å','æ','ç','è','é','ê','ë','ì','í','î','ï','ñ','ò','ó','ô','õ','ö','ø','ù','ú','û','ü','ý','ÿ','A','a','A','a','A','a','C','c','C','c','C','c','C','c','D','d','Ð','d','E','e','E','e','E','e','E','e','E','e','G','g','G','g','G','g','G','g','H','h','H','h','I','i','I','i','I','i','I','i','I','i','?','?','J','j','K','k','L','l','L','l','L','l','?','?','L','l','N','n','N','n','N','n','?','O','o','O','o','O','o','Œ','œ','R','r','R','r','R','r','S','s','S','s','S','s','Š','š','T','t','T','t','T','t','U','u','U','u','U','u','U','u','U','u','U','u','W','w','Y','y','Ÿ','Z','z','Z','z','Ž','ž','?','ƒ','O','o','U','u','A','a','I','i','O','o','U','u','U','u','U','u','U','u','U','u','?','?','?','?','?','?'); $b = array('A','A','A','A','A','A','AE','C','E','E','E','E','I','I','I','I','D','N','O','O','O','O','O','O','U','U','U','U','Y','s','a','a','a','a','a','a','ae','c','e','e','e','e','i','i','i','i','n','o','o','o','o','o','o','u','u','u','u','y','y','A','a','A','a','A','a','C','c','C','c','C','c','C','c','D','d','D','d','E','e','E','e','E','e','E','e','E','e','G','g','G','g','G','g','G','g','H','h','H','h','I','i','I','i','I','i','I','i','I','i','IJ','ij','J','j','K','k','L','l','L','l','L','l','L','l','l','l','N','n','N','n','N','n','n','O','o','O','o','O','o','OE','oe','R','r','R','r','R','r','S','s','S','s','S','s','S','s','T','t','T','t','T','t','U','u','U','u','U','u','U','u','U','u','U','u','W','w','Y','y','Y','Z','z','Z','z','Z','z','s','f','O','o','U','u','A','a','I','i','O','o','U','u','U','u','U','u','U','u','U','u','A','a','AE','ae','O','o'); return strtolower(preg_replace(array('/[^a-zA-Z0-9 -]/','/[ -]+/','/^-|-$/'),array('','-',''),str_replace($a,$b,$str))); } Works great, but i've found some cases in which it fails: echo gen_slug('andrés'); returns andras instead of andres why? any ideas on the preg_replace parameters?

    Read the article

  • Uninstall Mongo DB completely

    - by Srikanth
    I followed the following steps to install MongoDb on my centos machine. http://andres.jaimes.net/876/setup-mongo-php-module-centos-6/ As mentioned at the end of the document, in the phpinfo() the mongoDb support was enabled. Now i need to undo all the actions i did. Till now i hve uninstalled remi-release-6.rpm which i had installed by following the link above. How to uninstall completely and undo all actions I did?

    Read the article

  • TFS 2010 and the missing Area & Iterations (stale data) Issue

    - by andresv
    The symptom is this: you change some area or iteration in a TFS Project, but the change is not reflected (or updated) in VS or any other TFS Client. Well, it happens that TFS now has some clever caching mechanisms that need to be updated when you make a change like this, and those changes are propagated by some scheduled jobs TFS is continuously running in the Application Tier.  So, you you get this behavior, please check (and possibly restart) the "Visual Studio Team Foundation Background Job Agent" service. In my case, this service was logging a very odd "Object Reference Not Set" into the Windows Event Log, and a simple restart fixed it. Hope this is fixed by RTM...   (we are using the RC version). And by the way, if the job agent is broken there are some other things that stops working like email notifications. Best regards, Andrés G Vettori, CTO, VMBC  

    Read the article

  • NightHacking Tour Continues - Don't Miss It!

    - by Tori Wieldt
    Java Evangelist Steven Chin (@steveonjava) has been motorcycling across Europe, dropping in on developers and Java User Groups to do some hacking. The visits he has already made are up on the Youtube/Java channel (including James Gosling, Ben Evans, Stephen Colebourne and Trisha Gee).  Steve will be at J-Fall in the Netherlands all day Wednesday, Oct 31. You can watch streaming live and join in on the conversation. (You mean you missed the discussion about long variable names?) Watch for #nighthacking on Twitter. Some upcoming stops on the tour include: Adam Bien (Java Champion and Author) - Friday Nov 2 at 11AM CEST (2AM PST) Andres Almiray (Griffon Founder and Author) - Sunday Nov 4 at 8PM CEST (11AM PST) In total, there will be over 20 different interviews, several JUG visits, and special coverage of J-Fall and Devoxx conferences.You can view the full schedule and watch streaming video at nighthacking.com.

    Read the article

  • NightHacking Tour Across Europe

    - by Tori Wieldt
    Java Evangelist Stephen Chin (@steveonjava) is motorcycling across Europe, and dropping in on developers and Java User Groups to talk about Java and do some hacking. What's cool is you'll be able to be a part of it too: watch via live streaming, and interact using #nighthacking on Twitter. The tour will kickoff stateside with a visit to James Gosling (Father of the Java Language) - Wednesday Oct 24 at 11AM  PST.  Some noteworthy stops on the tour include: Ben Evans (LJC Leader and Author) - Saturday Oct 27 at 8PM BST (12PM PST) Adam Bien (Java Champion and Author) - Friday Nov 2 at 11AM CEST (2AM PST) Andres Almiray (Griffon Founder and Author) - Sunday Nov 4 at 8PM CEST (11AM PST) In total, there will be over 20 different interviews, several JUG visits, and special coverage of J-Fall and Devoxx conference.You can view the full schedule and watch streaming video at nighthacking.com.

    Read the article

  • JCP activities at Devoxx 2013!

    - by Heather VanCura
    Devoxx 2013 has officially started! Looking forward to catching up with Java community member friends--old and new this week. Tuesday (today) the Hackergarten has returned to Devoxx!  There are Java EE 7 tables and Java SE 8 Lambda tables.  Kudos to Andres Almirey for organizing the event and to Arun Gupta and Stuart Marks for leading the activities -- awesome Adopt-a-JSR participation in action! Wednesday there is a JCP 'quickie' session How to Participate in the Future of Java Quickie at 13:35-13:50.  We will also have a chat with the OTN team afterward!  Wednesday evening at 21:00, join us for our BOF session with Martin Verburg and Johan Vos: JCP & Adopt-a-JSR Workshop BOF. 

    Read the article

  • Type patterns and generic classes in Haskell

    - by finnsson
    I'm trying to understand type patterns and generic classes in Haskell but can't seem to get it. Could someone explain it in laymen's terms? In [1] I've read that "To apply functions generically to all data types, we view data types in a uniform manner: except for basic predefined types such as Float, IO, and ?, every Haskell data type can be viewed as a labeled sum of possibly labeled products." and then Unit, :*: and :+: are mentioned. Are all data types in Haskell automatically versions of the above mentioned and if so how do I figure out how a specific data type is represented in terms of :*:, etc? The users guide for generic classes (ch. 7.16) at haskell.org doesn't mention the predefined types but shouldn't they be handled in every function if the type patterns should be exhaustive? [1] Comparing Approaches to Generic Programming in Haskell, Ralf Hinze, Johan Jeuring, and Andres Löh

    Read the article

  • [C++] Is it possible to use threads to speed up file reading ?

    - by Mister Mystère
    Hi there, I want to read a file as fast as possible (40k lines) [Edit : the rest is obsolete]. Edit: Andres Jaan Tack suggested a solution based on one thread per file, and I want to be sure I got this (thus this is the fastest way) : One thread per entry file reads it whole and stocks its content in a container associated (- as many containers as there are entry files) One thread calculates the linear combination of every cell read by the input threads, and stocks the results in the exit container (associated to the output file). One thread writes by block (every 4kB of data, so about 10 lines) the content of the output container. Should I deduce that I must not use m-mapped files (because the program's on standby waiting for the data) ? Thanks aforehand. Sincerely, Mister mystère.

    Read the article

  • Favorite moments of JavaOne

    - by Tori Wieldt
    There are so many events and sessions to attend at JavaOne, it's unfair to ask people to choose just one thing they liked, but here are some favorite moments: I loved meeting many open source contributors and friends I have not met in person before and seeing that projects like e.g. Hudson are alive and kicking and have a great future ahead of them. -Manfred Moser My "The Problem with Women" session. It had LOADS of interactivity from the audience, who really helped to make that session.  I came out if it with a real sense of optimism - we love our jobs, we love what we do, and we should be proud of telling everyone about it to attract different talent into the industry. (Read her blog JavaOne: The Problem With Women - A Technical Approach for details.) -Trish Gee My kudos to Oracle for making the presentation materials quickly available to the public. Some of them were already available during JavaOne. Lots of slide decks are already there, and in some cases you may even find the video recordings too. Go to http://www.oracle.com/javaone and select JavaOne Technical Sessions.  -Yakov Fain I loved that not only was James Gosling present at the Community Keynote (which felt more like the keynotes of old times [big space, big screens, fun and tech]) but he was also found wandering the halls of the Hilton the day prior. Bring back James! Add back the toys section in the Community Keynote. Let the t-shirt tossing begin anew. These are "small" things that really fire up the community. -Andres Almiray Seeing James Gosling at JavaOne was a real shot in the arm for Java.  He needs to be there every year. -Frank Greco +42 on having James and the T-shirt tossing. -Stephan Janssen The session "Integrate Java with Robots, Home Automation, Musical Instruments, and Kinect." Fabiane Nardon explained connecting Jenkins to jHome to a truck horn placed in their sysadmin's bedroom. She dubbed it "extreme feedback."  -Tori Wieldt The User Group Forum [on Sunday] was a success! Congratulations Bruno Souza and John Yeary and everybody that were involved. I believe it really helps to increase community participation! There were lots of interesting talks, and great discussion with JUG leaders and members. Thank you Oracle for supporting that! -Yara Senger What was your favorite moment? Please comment! 

    Read the article

  • Creative, busy Devoxx week

    - by JavaCecilia
    I got back from my first visit to the developer conference Devoxx in Antwerp. I can't describe the vibes of the conference, it was a developer amusement park, hackergartens, fact sessions, comic relief provided by Java Posse, James Bond and endless hallway discussions.All and all - I had a lot of fun, my main mission was to talk about Oracle's main focus for OpenJDK which besides development and bug fixing is making sure the infrastructure is working out for the full community. My focus was not to hang out at night club the Noxx, but that was came included in the package :)The London Java community leaders Ben Evans and Martijn Verburg are leading discussions in the community to lay out the necessary requirements for the infrastructure for build and test in the open. They called a first meeting at JavaOne gathering 25 people, including people from RedHat, IBM and Oracle. The second meeting at Devoxx included 14 participants and had representatives from Oracle and IBM. I hope we really can find a way to collaborate on this, making sure we deliver an efficient infrastructure for all engineers to contribute to OpenJDK with.My home in all of this was the BOF rooms and the sessions there meeting the JUG leaders, talking about OpenJDK infrastructure and celebrating the Duchess Duke Award together with the others. The restaurants in the area was slower than I've ever seen, so I missed out on Trisha Gee's brilliant replay of the workshop "The Problem with Women in IT - an Agile Approach" where she masterly leads the audience (a packed room, 50-50 gender distribution) to solve the problem of including more diversity in the developer community. A tough and sometimes sensitive topic where she manages to keep the discussion objective with a focus of improving the matter from a business perspective. Mattias Karlsson is organizing the Java developer conference Jfokus in Stockholm and was there talking to Andres Almires planning a Hackergarten with a possible inclusion of an OpenJDK bugathon. That would be really cool, especially as the Oracle Stockholm Java development office is just across the water from the Jfokus venue, some of the local JVM engineers will likely attend and assist, even though the bug smashing theme will likely be more starter level build warnings in Swing or langtools than fixing JVM bugs.I was really happy that I managed to catch a seat for the Java Posse live podcast "the Third Presidential Debate" a lot of nerd humor, a lot of beer, a lot of fun :) The new member Chet had a perfect dead pan delivery and now I just have to listen more to the podcasts! Can't get the most perfect joke out of my head, talking about beer "As my father always said: Better a bottle in front of me than a frontal lobotomy" - hilarious :)I attended the sessions delivered by my Stockholm office colleagues Marcus Lagergren (on dynamic languages on the jvm, JavaScript in particular) and Joel Borggrén-Franck (Annotations) and was happy to see the packed room and all the questions raised at the end.There's loads of stuff to write about the event, but just have to pace myself for now. It was a fantastic event, captain Stephan Janssen with crew should be really proud to provide this forum to the developer community!

    Read the article

  • JavaOne Tutorial Report - JavaFX 2 – A Java Developer’s Guide

    - by Janice J. Heiss
    Oracle Java Technology Evangelist Stephen Chin and Independent Consultant Peter Pilgrim presented a tutorial session intended to help developers get a handle on JavaFX 2. Stephen Chin, a Java Champion, is co-author of the Pro JavaFX Platform 2, while Java Champion Peter Pilgrim is an independent consultant who works out of London.NightHacking with Stephen ChinBefore discussing the tutorial, a note about Chin’s “NightHacking Tour,” wherein from 10/29/12 to 11/11/12, he will be traveling across Europe via motorcycle stopping at JUGs and interviewing Java developers and offering live video streaming of the journey. As he says, “Along the way, I will visit user groups, interviewing interesting folks, and hack on open source projects. The last stop will be the Devoxx conference in Belgium.”It’s a dirty job but someone’s got to do it. His trip will take him from the UK through the Netherlands, Germany, Switzerland, Italy, France, and finally to Devoxx in Belgium. He has interviews lined up with Ben Evans, Trisha Gee, Stephen Coulebourne, Martijn Verburg, Simon Ritter, Bert Ertman, Tony Epple, Adam Bien, Michael Hutterman, Sven Reimers, Andres Almiray, Gerrit Grunewald, Bertrand Boetzmann, Luc Duponcheel, Stephen Janssen, Cheryl Miller, and Andrew Phillips. If you expect to be in Chin’s vicinity at the end of October and in early November, by all means get in touch with him at his site and add your perspective. The more the merrier! Taking the JavaFX PlungeNow to the business at hand. The “JavaFX 2 – A Java Developer’s Guide” tutorial introduced Java developers to the JavaFX 2 platform from the perspective of seasoned Java developers. It demonstrated the breadth of the JavaFX APIs through examples that are built out in the course of the session in an effort to present the basic requirements in using JavaFX to build rich internet applications. Chin began with a quote from Oracle’s Christopher Oliver, the creator of F3, the original version of JavaFX, on the importance of GUIs:“At the end of the day, on the one hand we have computer systems, and on the other, people. Connecting them together, and allowing people to interact with computer systems in a compelling way, requires graphical user interfaces.”Chin explained that JavaFX is about producing an immersive application experience that involves cross-platform animation, video and charting. It can integrate Java, JavaScript and HTML in the same application. The new graphics stack takes advantage of hardware acceleration for 2D and 3D applications. In addition, we can integrate Swing applications using JFXPanel.He reminded attendees that they were building JavaFX apps using pure Java APIs that included builders for declarative construction; in addition, alternative languages can be used for simpler UI creation. In addition, developers can call upon alternative languages such as GroovyFX, ScalaFX and Visage, if they want simpler UI creation. He presented the fundamentals of JavaFX 2.0: properties, lists and binding and then explored primitive, object and FX list collection properties. Properties in JavaFX are observable, lazy and type safe. He then provided an example of property declaration in code.  Pilgrim and Chin explained the architectural structure of JavaFX 2 and its basic properties:JavaFX 2.0 properties – Primitive, Object, and FX List Collection properties. * Primitive Properties* Object Properties* FX List Collection Properties* Properties are:– Observable– Lazy– Type SafeChin and Pilgrim then took attendees through several participatory demos and got deep into the weeds of the code for the two-hour session. At the end, everyone knew a lot more about the inner workings of JavaFX 2.0.

    Read the article

  • How to count each digit in a range of integers?

    - by Carlos Gutiérrez
    Imagine you sell those metallic digits used to number houses, locker doors, hotel rooms, etc. You need to find how many of each digit to ship when your customer needs to number doors/houses: 1 to 100 51 to 300 1 to 2,000 with zeros to the left The obvious solution is to do a loop from the first to the last number, convert the counter to a string with or without zeros to the left, extract each digit and use it as an index to increment an array of 10 integers. I wonder if there is a better way to solve this, without having to loop through the entire integers range. Solutions in any language or pseudocode are welcome. Edit: Answers review John at CashCommons and Wayne Conrad comment that my current approach is good and fast enough. Let me use a silly analogy: If you were given the task of counting the squares in a chess board in less than 1 minute, you could finish the task by counting the squares one by one, but a better solution is to count the sides and do a multiplication, because you later may be asked to count the tiles in a building. Alex Reisner points to a very interesting mathematical law that, unfortunately, doesn’t seem to be relevant to this problem. Andres suggests the same algorithm I’m using, but extracting digits with %10 operations instead of substrings. John at CashCommons and phord propose pre-calculating the digits required and storing them in a lookup table or, for raw speed, an array. This could be a good solution if we had an absolute, unmovable, set in stone, maximum integer value. I’ve never seen one of those. High-Performance Mark and strainer computed the needed digits for various ranges. The result for one millon seems to indicate there is a proportion, but the results for other number show different proportions. strainer found some formulas that may be used to count digit for number which are a power of ten. Robert Harvey had a very interesting experience posting the question at MathOverflow. One of the math guys wrote a solution using mathematical notation. Aaronaught developed and tested a solution using mathematics. After posting it he reviewed the formulas originated from Math Overflow and found a flaw in it (point to Stackoverflow :). noahlavine developed an algorithm and presented it in pseudocode. A new solution After reading all the answers, and doing some experiments, I found that for a range of integer from 1 to 10n-1: For digits 1 to 9, n*10(n-1) pieces are needed For digit 0, if not using leading zeros, n*10n-1 - ((10n-1) / 9) are needed For digit 0, if using leading zeros, n*10n-1 - n are needed The first formula was found by strainer (and probably by others), and I found the other two by trial and error (but they may be included in other answers). For example, if n = 6, range is 1 to 999,999: For digits 1 to 9 we need 6*105 = 600,000 of each one For digit 0, without leading zeros, we need 6*105 – (106-1)/9 = 600,000 - 111,111 = 488,889 For digit 0, with leading zeros, we need 6*105 – 6 = 599,994 These numbers can be checked using High-Performance Mark results. Using these formulas, I improved the original algorithm. It still loops from the first to the last number in the range of integers, but, if it finds a number which is a power of ten, it uses the formulas to add to the digits count the quantity for a full range of 1 to 9 or 1 to 99 or 1 to 999 etc. Here's the algorithm in pseudocode: integer First,Last //First and last number in the range integer Number //Current number in the loop integer Power //Power is the n in 10^n in the formulas integer Nines //Nines is the resut of 10^n - 1, 10^5 - 1 = 99999 integer Prefix //First digits in a number. For 14,200, prefix is 142 array 0..9 Digits //Will hold the count for all the digits FOR Number = First TO Last CALL TallyDigitsForOneNumber WITH Number,1 //Tally the count of each digit //in the number, increment by 1 //Start of optimization. Comments are for Number = 1,000 and Last = 8,000. Power = Zeros at the end of number //For 1,000, Power = 3 IF Power 0 //The number ends in 0 00 000 etc Nines = 10^Power-1 //Nines = 10^3 - 1 = 1000 - 1 = 999 IF Number+Nines <= Last //If 1,000+999 < 8,000, add a full set Digits[0-9] += Power*10^(Power-1) //Add 3*10^(3-1) = 300 to digits 0 to 9 Digits[0] -= -Power //Adjust digit 0 (leading zeros formula) Prefix = First digits of Number //For 1000, prefix is 1 CALL TallyDigitsForOneNumber WITH Prefix,Nines //Tally the count of each //digit in prefix, //increment by 999 Number += Nines //Increment the loop counter 999 cycles ENDIF ENDIF //End of optimization ENDFOR SUBROUTINE TallyDigitsForOneNumber PARAMS Number,Count REPEAT Digits [ Number % 10 ] += Count Number = Number / 10 UNTIL Number = 0 For example, for range 786 to 3,021, the counter will be incremented: By 1 from 786 to 790 (5 cycles) By 9 from 790 to 799 (1 cycle) By 1 from 799 to 800 By 99 from 800 to 899 By 1 from 899 to 900 By 99 from 900 to 999 By 1 from 999 to 1000 By 999 from 1000 to 1999 By 1 from 1999 to 2000 By 999 from 2000 to 2999 By 1 from 2999 to 3000 By 1 from 3000 to 3010 (10 cycles) By 9 from 3010 to 3019 (1 cycle) By 1 from 3019 to 3021 (2 cycles) Total: 28 cycles Without optimization: 2,235 cycles Note that this algorithm solves the problem without leading zeros. To use it with leading zeros, I used a hack: If range 700 to 1,000 with leading zeros is needed, use the algorithm for 10,700 to 11,000 and then substract 1,000 - 700 = 300 from the count of digit 1. Benchmark and Source code I tested the original approach, the same approach using %10 and the new solution for some large ranges, with these results: Original 104.78 seconds With %10 83.66 With Powers of Ten 0.07 A screenshot of the benchmark application: If you would like to see the full source code or run the benchmark, use these links: Complete Source code (in Clarion): http://sca.mx/ftp/countdigits.txt Compilable project and win32 exe: http://sca.mx/ftp/countdigits.zip Accepted answer noahlavine solution may be correct, but l just couldn’t follow the pseudo code, I think there are some details missing or not completely explained. Aaronaught solution seems to be correct, but the code is just too complex for my taste. I accepted strainer’s answer, because his line of thought guided me to develop this new solution.

    Read the article

  • Asynchronous Streaming in ASP.NET WebApi

    - by andresv
     Hi everyone, if you use the cool MVC4 WebApi you might encounter yourself in a common situation where you need to return a rather large amount of data (most probably from a database) and you want to accomplish two things: Use streaming so the client fetch the data as needed, and that directly correlates to more fetching in the server side (from our database, for example) without consuming large amounts of memory. Leverage the new MVC4 WebApi and .NET 4.5 async/await asynchronous execution model to free ASP.NET Threadpool threads (if possible).  So, #1 and #2 are not directly related to each other and we could implement our code fulfilling one or the other, or both. The main point about #1 is that we want our method to immediately return to the caller a stream, and that client side stream be represented by a server side stream that gets written (and its related database fetch) only when needed. In this case we would need some form of "state machine" that keeps running in the server and "knows" what is the next thing to fetch into the output stream when the client ask for more content. This technique is generally called a "continuation" and is nothing new in .NET, in fact using an IEnumerable<> interface and the "yield return" keyword does exactly that, so our first impulse might be to write our WebApi method more or less like this:           public IEnumerable<Metadata> Get([FromUri] int accountId)         {             // Execute the command and get a reader             using (var reader = GetMetadataListReader(accountId))             {                 // Read rows asynchronously, put data into buffer and write asynchronously                 while (reader.Read())                 {                     yield return MapRecord(reader);                 }             }         }   While the above method works, unfortunately it doesn't accomplish our objective of returning immediately to the caller, and that's because the MVC WebApi infrastructure doesn't yet recognize our intentions and when it finds an IEnumerable return value, enumerates it before returning to the client its values. To prove my point, I can code a test method that calls this method, for example:        [TestMethod]         public void StreamedDownload()         {             var baseUrl = @"http://localhost:57771/api/metadata/1";             var client = new HttpClient();             var sw = Stopwatch.StartNew();             var stream = client.GetStreamAsync(baseUrl).Result;             sw.Stop();             Debug.WriteLine("Elapsed time Call: {0}ms", sw.ElapsedMilliseconds); } So, I would expect the line "var stream = client.GetStreamAsync(baseUrl).Result" returns immediately without server-side fetching of all data in the database reader, and this didn't happened. To make the behavior more evident, you could insert a wait time (like Thread.Sleep(1000);) inside the "while" loop, and you will see that the client call (GetStreamAsync) is not going to return control after n seconds (being n == number of reader records being fetched).Ok, we know this doesn't work, and the question would be: is there a way to do it?Fortunately, YES!  and is not very difficult although a little more convoluted than our simple IEnumerable return value. Maybe in the future this scenario will be automatically detected and supported in MVC/WebApi.The solution to our needs is to use a very handy class named PushStreamContent and then our method signature needs to change to accommodate this, returning an HttpResponseMessage instead of our previously used IEnumerable<>. The final code will be something like this: public HttpResponseMessage Get([FromUri] int accountId)         {             HttpResponseMessage response = Request.CreateResponse();             // Create push content with a delegate that will get called when it is time to write out              // the response.             response.Content = new PushStreamContent(                 async (outputStream, httpContent, transportContext) =>                 {                     try                     {                         // Execute the command and get a reader                         using (var reader = GetMetadataListReader(accountId))                         {                             // Read rows asynchronously, put data into buffer and write asynchronously                             while (await reader.ReadAsync())                             {                                 var rec = MapRecord(reader);                                 var str = await JsonConvert.SerializeObjectAsync(rec);                                 var buffer = UTF8Encoding.UTF8.GetBytes(str);                                 // Write out data to output stream                                 await outputStream.WriteAsync(buffer, 0, buffer.Length);                             }                         }                     }                     catch(HttpException ex)                     {                         if (ex.ErrorCode == -2147023667) // The remote host closed the connection.                          {                             return;                         }                     }                     finally                     {                         // Close output stream as we are done                         outputStream.Close();                     }                 });             return response;         } As an extra bonus, all involved classes used already support async/await asynchronous execution model, so taking advantage of that was very easy. Please note that the PushStreamContent class receives in its constructor a lambda (specifically an Action) and we decorated our anonymous method with the async keyword (not a very well known technique but quite handy) so we can await over the I/O intensive calls we execute like reading from the database reader, serializing our entity and finally writing to the output stream.  Well, if we execute the test again we will immediately notice that the a line returns immediately and then the rest of the server code is executed only when the client reads through the obtained stream, therefore we get low memory usage and far greater scalability for our beloved application serving big chunks of data.Enjoy!Andrés.        

    Read the article

< Previous Page | 1 2 3