Search Results

Search found 5192 results on 208 pages for 'random forests'.

Page 70/208 | < Previous Page | 66 67 68 69 70 71 72 73 74 75 76 77  | Next Page >

  • Trouble with C# array

    - by Biosci3c
    Hi, I am writing a card playing program as a way of learning C#. I ran into an issue with an array going out of bounds. Here is my code: namespace Pcardconsole { class Deck { public Deck() { // Assign standard deck to new deck object int j; for (int i = 0; i != CurrentDeck.Length; i++) { CurrentDeck[i] = originalCards[i]; } // Fisher-Yates Shuffling Algorithim Random rnd = new Random(); for (int k = CurrentDeck.Length - 1; k >= 0; k++) { int r = rnd.Next(0, k + 1); int tmp = CurrentDeck[k]; CurrentDeck[k] = CurrentDeck[r]; CurrentDeck[r] = tmp; // Console.WriteLine(i); } } public void Shuffle() { // TODO } // public int[] ReturnCards() // { // TODO // } public int[] originalCards = new int[54] { 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x50, 0x51 }; public int[] CurrentDeck = new int[54]; } class Program { static void Main(string[] args) { // Create a Deck object Deck mainDeck = new Deck(); Console.WriteLine("Here is the card array:"); for (int index = 0; index != mainDeck.CurrentDeck.Length; index++) { string card = mainDeck.CurrentDeck[index].ToString("x"); Console.WriteLine("0x" + card); } } } The hexidecimal numbers stand for different cards. When I compile it I get an array index out of bounds error, and a crash. I don't understand what is wrong. Any help would be much appreciated.

    Read the article

  • Rot13 for numbers.

    - by dreeves
    EDIT: Now a Major Motion Blog Post at http://messymatters.com/sealedbids The idea of rot13 is to obscure text, for example to prevent spoilers. It's not meant to be cryptographically secure but to simply make sure that only people who are sure they want to read it will read it. I'd like to do something similar for numbers, for an application involving sealed bids. Roughly I want to send someone my number and trust them to pick their own number, uninfluenced by mine, but then they should be able to reveal mine (purely client-side) when they're ready. They should not require further input from me or any third party. (Added: Note the assumption that the recipient is being trusted not to cheat.) It's not as simple as rot13 because certain numbers, like 1 and 2, will recur often enough that you might remember that, say, 34.2 is really 1. Here's what I'm looking for specifically: A function seal() that maps a real number to a real number (or a string). It should not be deterministic -- seal(7) should not map to the same thing every time. But the corresponding function unseal() should be deterministic -- unseal(seal(x)) should equal x for all x. I don't want seal or unseal to call any webservices or even get the system time (because I don't want to assume synchronized clocks). (Added: It's fine to assume that all bids will be less than some maximum, known to everyone, say a million.) Sanity check: > seal(7) 482.2382 # some random-seeming number or string. > seal(7) 71.9217 # a completely different random-seeming number or string. > unseal(seal(7)) 7 # we always recover the original number by unsealing.

    Read the article

  • Shouldn't prepared statements be much faster?

    - by silversky
    $s = explode (" ", microtime()); $s = $s[0]+$s[1]; $con = mysqli_connect ('localhost', 'test', 'pass', 'db') or die('Err'); for ($i=0; $i<1000; $i++) { $stmt = $con -> prepare( " SELECT MAX(id) AS max_id , MIN(id) AS min_id FROM tb "); $stmt -> execute(); $stmt->bind_result($M,$m); $stmt->free_result(); $rand = mt_rand( $m , $M ).'<br/>'; $res = $con -> prepare( " SELECT * FROM tb WHERE id >= ? LIMIT 0,1 "); $res -> bind_param("s", $rand); $res -> execute(); $res->free_result(); } $e = explode (" ", microtime()); $e = $e[0]+$e[1]; echo number_format($e-$s, 4, '.', ''); // and: $link = mysql_connect ("localhost", "test", "pass") or die (); mysql_select_db ("db") or die ("Unable to select database".mysql_error()); for ($i=0; $i<1000; $i++) { $range_result = mysql_query( " SELECT MAX(`id`) AS max_id , MIN(`id`) AS min_id FROM tb "); $range_row = mysql_fetch_object( $range_result ); $random = mt_rand( $range_row->min_id , $range_row->max_id ); $result = mysql_query( " SELECT * FROM tb WHERE id >= $random LIMIT 0,1 "); } defenitly prepared statements are much more safer but also every where it says that they are much faster BUT in my test on the above code I have: - 2.45 sec for prepared statements - 5.05 sec for the secon example What do you think I'm doing wrong? Should I use the second solution or I should try to optimize the prep stmt?

    Read the article

  • Understanding CSRF - Simple Question

    - by byronh
    I know this might make me seem like an idiot, I've read everything there is to read about CSRF and I still don't understand how using a 'challenge token' would add any sort of prevention. Please help me clarify the basic concept, none of the articles and posts here on SO I read seemed to really explicitly state what value you're comparing with what. From OWASP: In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session and is utilized for each subsequent request until the session expires. If I understand the process correctly, this is what happens. I log in at http://example.com and a session/cookie is created containing this random token. Then, every form includes a hidden input also containing this random value from the session which is compared with the session/cookie upon form submission. But what does that accomplish? Aren't you just taking session data, putting it in the page, and then comparing it with the exact same session data? Seems like circular reasoning. These articles keep talking about following the "same-origin policy" but that makes no sense, because all CSRF attacks ARE of the same origin as the user, just tricking the user into doing actions he/she didn't intend. Is there any alternative other than appending the token to every single URL as a query string? Seems very ugly and impractical, and makes bookmarking harder for the user.

    Read the article

  • Is a red-black tree my ideal data structure?

    - by Hugo van der Sanden
    I have a collection of items (big rationals) that I'll be processing. In each case, processing will consist of removing the smallest item in the collection, doing some work, and then adding 0-2 new items (which will always be larger than the removed item). The collection will be initialised with one item, and work will continue until it is empty. I'm not sure what size the collection is likely to reach, but I'd expect in the range 1M-100M items. I will not need to locate any item other than the smallest. I'm currently planning to use a red-black tree, possibly tweaked to keep a pointer to the smallest item. However I've never used one before, and I'm unsure whether my pattern of use fits its characteristics well. 1) Is there a danger the pattern of deletion from the left + random insertion will affect performance, eg by requiring a significantly higher number of rotations than random deletion would? Or will delete and insert operations still be O(log n) with this pattern of use? 2) Would some other data structure give me better performance, either because of the deletion pattern or taking advantage of the fact I only ever need to find the smallest item? Update: glad I asked, the binary heap is clearly a better solution for this case, and as promised turned out to be very easy to implement. Hugo

    Read the article

  • about Quick Sort

    - by matin1234
    Hi I have written this code but it will print these stack traces in the console please help me thanks! (Aslo "p" and "q" are the first and last index of our array ,respectively) public class JavaQuickSort { public static void QuickSort(int A[], int p, int q) { int i, last = 0; Random rand = new Random(); if (q < 1) { return; } **swap(A, p, rand.nextInt() % (q+1));** for (i = p + 1; i <= q; i++) { if (A[i] < A[p]) { swap(A, ++last, i); } } swap(A, p, last); QuickSort(A, p, last - 1); QuickSort(A, last + 1, q); } private static void swap(int[] A, int i, int j) { int temp; temp = A[i]; **A[i] = A[j];** A[j] = temp; } public static void main(String[] args){ int[] A = {2,5,7,3,9,0,1,6,8}; **QuickSort(A, 0,8 );** System.out.println(Arrays.toString(A)); } } the Stack traces : run: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -3 at JavaQuickSort.swap(JavaQuickSort.java:38) at JavaQuickSort.QuickSort(JavaQuickSort.java:22) at JavaQuickSort.main(JavaQuickSort.java:45) Java Result: 1 BUILD SUCCESSFUL (total time: 2 seconds) I also bold those statements that cause these stack traces. like == ** ...**

    Read the article

  • CONFUSING : CGAffineTransform - rotation on uibutton resizes buttonimage ?! (iPad)

    - by Michael
    hi there, i've got a strange problem using uibuttons, type custom. i'm placing 4 of those buttons on a scrollview, rotating each button by a random angle using CGAffineTransform. now it seems, that the buttons itself change size depending on the angle of rotation. can't get this problem solved :( UIGraphicsBeginImageContext(tempCtxSize); [cookbookImage drawInRect:CGRectMake(imgOffsetX, imgOffsetY+frmOffsetY, cookbookImage.size.width, cookbookImage.size.height)]; [cookbookFrame drawInRect:CGRectMake(0.0f, frmOffsetY, cookbookFrame.size.width, cookbookFrame.size.height)]; UIImage *combinedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); ... ... UIButton *cookbookViewButton = [UIButton buttonWithType:UIButtonTypeCustom]; [cookbookViewButton setFrame:CGRectMake(0.0f, 0.0f, combinedImage.size.width, combinedImage.size.height)]; [cookbookViewButton setBackgroundColor:[UIColor clearColor]]; [cookbookViewButton setBackgroundImage:combinedImage forState:UIControlStateNormal]; CGAffineTransform rotation = [cookbookViewButton transform]; rotation = CGAffineTransformRotate(rotation, angle); // some random angle [cookbookViewButton setTransform:rotation]; thx for your help in advance!

    Read the article

  • Unexpected performance curve from CPython merge sort

    - by vkazanov
    I have implemented a naive merge sorting algorithm in Python. Algorithm and test code is below: import time import random import matplotlib.pyplot as plt import math from collections import deque def sort(unsorted): if len(unsorted) <= 1: return unsorted to_merge = deque(deque([elem]) for elem in unsorted) while len(to_merge) > 1: left = to_merge.popleft() right = to_merge.popleft() to_merge.append(merge(left, right)) return to_merge.pop() def merge(left, right): result = deque() while left or right: if left and right: elem = left.popleft() if left[0] > right[0] else right.popleft() elif not left and right: elem = right.popleft() elif not right and left: elem = left.popleft() result.append(elem) return result LOOP_COUNT = 100 START_N = 1 END_N = 1000 def test(fun, test_data): start = time.clock() for _ in xrange(LOOP_COUNT): fun(test_data) return time.clock() - start def run_test(): timings, elem_nums = [], [] test_data = random.sample(xrange(100000), END_N) for i in xrange(START_N, END_N): loop_test_data = test_data[:i] elapsed = test(sort, loop_test_data) timings.append(elapsed) elem_nums.append(len(loop_test_data)) print "%f s --- %d elems" % (elapsed, len(loop_test_data)) plt.plot(elem_nums, timings) plt.show() run_test() As much as I can see everything is OK and I should get a nice N*logN curve as a result. But the picture differs a bit: Things I've tried to investigate the issue: PyPy. The curve is ok. Disabled the GC using the gc module. Wrong guess. Debug output showed that it doesn't even run until the end of the test. Memory profiling using meliae - nothing special or suspicious. ` I had another implementation (a recursive one using the same merge function), it acts the similar way. The more full test cycles I create - the more "jumps" there are in the curve. So how can this behaviour be explained and - hopefully - fixed? UPD: changed lists to collections.deque UPD2: added the full test code UPD3: I use Python 2.7.1 on a Ubuntu 11.04 OS, using a quad-core 2Hz notebook. I tried to turn of most of all other processes: the number of spikes went down but at least one of them was still there.

    Read the article

  • Authenticated user cannot log in, "The user does not exist or is not unique."

    - by Aquinas
    This is a weird one. I have a WSS3 site, no MOSS, with a custom membership and role provider that authenticates against CRM. All the users have also been added to the site user list so once logged in they have correct display names. On dev and stage everything works fine, but on UAT the users can't get past the login screen. The login screen is working, in that if you type an incorrect password for a user it comes back with the right message, meaning the custom provider is working fine. If you fill the login form in correctly you are immediately redirected straight back to the login screen, with the IIS logs showing that the login screen sent the authenticated user to the site and then was sent back. Setting the site to allow anonymous access shows that the user is not logged in on the site side after authenticating correctly. The ULS logs show: The user does not exist or is not unique. Found 1 trusted forests nzct.local. Found 0 trusted domains Adding logging code to the site I have verified that the membership provider is correctly set, and can find the user when asked. Also, when accessing the site user list, I can find the SP user with the right name. It just refuses to set the current user to be the authenticated user. Weird.

    Read the article

  • Fastest way to generate delimited string from 1d numpy array

    - by Abiel
    I have a program which needs to turn many large one-dimensional numpy arrays of floats into delimited strings. I am finding this operation quite slow relative to the mathematical operations in my program and am wondering if there is a way to speed it up. For example, consider the following loop, which takes 100,000 random numbers in a numpy array and joins each array into a comma-delimited string. import numpy as np x = np.random.randn(100000) for i in range(100): ",".join(map(str, x)) This loop takes about 20 seconds to complete (total, not each cycle). In contrast, consider that 100 cycles of something like elementwise multiplication (x*x) would take than one 1/10 of a second to complete. Clearly the string join operation creates a large performance bottleneck; in my actual application it will dominate total runtime. This makes me wonder, is there a faster way than ",".join(map(str, x))? Since map() is where almost all the processing time occurs, this comes down to the question of whether there a faster to way convert a very large number of numbers to strings.

    Read the article

  • Passing youtube video id from video feed to flash

    - by Grant Anderson
    I'm working on a flash web application (Actionscript 2.0) for my honours project but am having trouble embedding youtube videos. Basically the user selects symbols which queries the youtube api with certain tags depending on the symbols chosenand a random video is then picked from the first 30 videos. I have this working using the following code: on (release) { url="http://gdata.youtube.com/feeds/api/videos?q=danger+passion&orderby=published&start-index="+random(30)+"&max-results=1&v=2" getURL(url); } but this just displays a webpage with a link to the youtube video. This is the code I'll be using as the foundations for the player: // create a MovieClip to load the player into var ytplayer:MovieClip = _root.createEmptyMovieClip("ytplayer", 1); // create a listener object for the MovieClipLoader to use var ytPlayerLoaderListener:Object = { onLoadInit: function() { // When the player clip first loads, we start an interval to // check for when the player is ready loadInterval = setInterval(checkPlayerLoaded, 250); } }; var loadInterval:Number; function checkPlayerLoaded():Void { // once the player is ready, we can subscribe to events, or in the case of // the chromeless player, we could load videos if (ytplayer.isPlayerLoaded()) { ytplayer.addEventListener("onStateChange", onPlayerStateChange); ytplayer.addEventListener("onError", onPlayerError); clearInterval(loadInterval); } } function onPlayerStateChange(newState:Number) { trace("New player state: "+ newState); } function onPlayerError(errorCode:Number) { trace("An error occurred: "+ errorCode); } // create a MovieClipLoader to handle the loading of the player var ytPlayerLoader:MovieClipLoader = new MovieClipLoader(); ytPlayerLoader.addListener(ytPlayerLoaderListener); // load the player ytPlayerLoader.loadClip("http://www.youtube.com/v/pv5zWaTEVkI", ytplayer); can anyone help me on how to get the id of the video (for example: pv5zWaTEVkI) from the feed? Or how to send a query from flash which will return the video url/id as opposed to the url of a feed. Any help would be much appreciated as my hand in rather soon. Thanks

    Read the article

  • How to return proper 404 for google while providing user friendly content to the user?

    - by Marek
    I am bouncing between posting this here and on Superuser. Please excuse me if you feel this does not belong here. I am observing the behavior described here - Googlebot is requesting random urls on my site, like aecgeqfx.html or sutwjemebk.html. I am sure that I am not linking these urls from anywhere on my site. I suspect this may be google probing how we handle non existent content - to cite from an answer to the linked question: [google is requesting random urls to] see if your site correctly handles non-existent files (by returning a 404 response header) We have a custom page for nonexistent content - a styled page saying "Content not found, if you believe you got here by error, please contact us", with a few internal links, served (naturally) with a 200 OK. The URL is served directly (no redirection to a single url). I am afraid this may discriminate the site at google - they may not interpret the user friendly page as a 404 - not found and may think we are trying to fake something and provide duplicate content. How should I proceed to ensure that google will not think the site is bogus while providing user friendly message to users in case they click on dead links by accident?

    Read the article

  • Radix Sort in Python [on hold]

    - by Steven Ramsey
    I could use some help. How would you write a program in python that implements a radix sort? Here is some info: A radix sort for base 10 integers is a based on sorting punch cards, but it turns out the sort is very ecient. The sort utilizes a main bin and 10 digit bins. Each bin acts like a queue and maintains its values in the order they arrive. The algorithm begins by placing each number in the main bin. Then it considers the ones digit for each value. The rst value is removed and placed in the digit bin corresponding to the ones digit. For example, 534 is placed in digit bin 4 and 662 is placed in the digit bin 2. Once all the values in the main bin are placed in the corresponding digit bin for ones, the values are collected from bin 0 to bin 9 (in that order) and placed back in the main bin. The process continues with the tens digit, the hundreds, and so on. After the last digit is processed, the main bin contains the values in order. Use randint, found in random, to create random integers from 1 to 100000. Use a list comphrension to create a list of varying sizes (10, 100, 1000, 10000, etc.). To use indexing to access the digits rst convert the integer to a string. For this sort to work, all numbers must have the same number of digits. To zero pad integers with leading zeros, use the string method str.zfill(). Once main bin is sorted, convert the strings back to integers. I'm not sure how to start this, Any help is appreciated. Thank you.

    Read the article

  • How close can I get C# to the performance of C++ for small intensive tasks?

    - by SLC
    I was thinking about the speed difference of C++ to C# being mostly about C# compiling to byte-code that is taken in by the JIT compiler (is that correct?) and all the checks C# does. I notice that it is possible to turn a lot of these functions off, both in the compile options, and possibly through using the unsafe keyword as unsafe code is not verifiable by the common language runtime. Therefore if you were to write a simple console application in both languages, that flipped an imaginary coin an infinite number of times and displayed the results to the screen every 10,000 or so iterations, how much speed difference would there be? I chose this because it's a very simple program. I'd like to test this but I don't know C++ or have the tools to compile it. This is my C# version though: static void Main(string[] args) { unsafe { Random rnd = new Random(); int heads = 0, tails = 0; while (true) { if (rnd.NextDouble() > 0.5) heads++; else tails++; if ((heads + tails) % 1000000 == 0) Console.WriteLine("Heads: {0} Tails: {1}", heads, tails); } } } Is the difference enough to warrant deliberately compiling sections of code "unsafe" or into DLLs that do not have some of the compile options like overflow checking enabled? Or does it go the other way, where it would be beneficial to compile sections in C++? I'm sure interop speed comes into play too then. To avoid subjectivity, I reiterate the specific parts of this question as: Does C# have a performance boost from using unsafe code? Do the compile options such as disabling overflow checking boost performance, and do they affect unsafe code? Would the program above be faster in C++ or negligably different? Is it worth compiling long intensive number-crunching tasks in a language such as C++ or using /unsafe for a bonus? Less subjectively, could I complete an intensive operation faster by doing this?

    Read the article

  • Visual Studio 2008 project file does not load because of an unexpected encoding change.

    - by Xenan
    In our team we have a database project in visual Studio 2008 which is under source control by Team Foundation Server. Every two weeks or so, after one co-worker checks in, the project file won't load on the other developers machines. The error message is: The project file could not be loaded. Data at the root level is invalid. Line 1, position 1. When I look at the project file in Notepad++, the file looks like this: ??<NUL?NULxNULmNULlNUL NULvNULeNULrNULsNULiNULoNULnNUL ... and so on (you can see <?xml version in this) whereas an normal project file looks like: <?xml version="1.0" encoding="utf-16"?> ... So probably something is wrong with the encoding of the file. This is a problem for us because it turns out to be impossible to get the file encoding correct again. The 'solution' is to throw away the project file an get the last know working version from source control. According to the file, the encoding should be UTF-16. According to Notepad++, the corrupted file is actually UTF-8. My questions are: Why is Visual Studio messing up the encoding of the project file, apparently at random times and at random machines? What should we do to prevent this? When it has happened, is there a possibility to restore the current file in the correct encoding instead of pulling an older version from source control? As a last note: the problem is with one single project file, all other project files don't expose this problem.

    Read the article

  • Rebol Multitasking with Async: why do I get Invalid port spec

    - by Rebol Tutorial
    I tried http://www.mail-archive.com/[email protected]/msg19437.html (I just changed to www.reboltutorial.com) : do http://www.rebol.it/giesse/async-protocol.r handler: func [port [port!] state [word! error!] /local tmp cmd] [ if error? :state [print mold disarm state return true] switch state [ connect [ ; do HTTP request insert port {GET /files/2009/10/word.png HTTP/1.0^M^JHost: www.reboltutorial.com^M^J^M^J} false ] read [false] write [false] close [ ; get data data: copy port close port ;print copy/part data find data "^M^J^M^J" data: to binary! find/tail data "^M^J^M^J" other/image: attempt [load data] other/text: "" show other false ] ] ] port: open async://www.reboltutorial.com:80 port/awake: :handler view layout [ across me: box 100x100 random 255.255.255 0:00:00.5 feel [ engage: func [f a e] [ if a = 'time [ me/color: random 255.255.255 show me ] ] ] other: box 100x100 255.255.255 "Downloading image..." Return Area 208x100 "You can type here while downloading." ] ] But I'm getting this error: >> port: open async://reboltutorial.com:80 ** Access Error: Invalid port spec: async://reboltutorial.com:80 ** Near: port: open async://reboltutorial.com:80 >> port/awake: :handler ** Script Error: port has no value ** Near: port/awake: :handler

    Read the article

  • Debugging a HTTP Handler from Visual Studio

    - by O.O.
    I am trying to debug a HTTP Handler in Visual Studio and the break point is not getting hit. Does anyone have an idea on how to go about debugging HTTP Handlers in Visual Studio? I am using VS 2010 Premium, .NET 4.0 on a Windows 7 machine. In my Web Application I have a HTTP Handler in /HTTPHandler/TrackingHandler.cs The following is in my web config file: <system.webServer> <handlers> <add name="TrackingHandler" path="/tx/*" verb="*" type="ProjectNamespace.TrackingHandler" resourceType="Unspecified" preCondition="integratedMode" /> </handlers> </system.webServer> My HTTP Handler looks like below namespace ProjectNamespace { public class TrackingHandler : IHttpHandler { public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext context) { //Breakpoint on the very first line below string tracker = Path.GetFileName(context.Request.PhysicalPath); ....... } } } I start my Web Application using any random page in Visual Studio Debug using the builtin Web Server. I then maually edit the URL to point to the /tx/ directory and some random string after it. For e.g. my current URL looks like http://localhost:53699/tx/sdfs. I thought this should pull up the breakpoint on the first line of ProcessRequest() but it does not. I’d be grateful for any ideas. O. O.

    Read the article

  • What kinds of problems are most likely to occur? (question rewritten)

    - by ChrisC
    If I wrote 1) a C# SQL db app (a simple program consisting of a gui over some forms with logic for interfacing with the sql db) 2) for home use, that doesn't do any network communication 3) that uses a simple, reliable, and appropriate sql db 4) whose gui is properly separated from the logic 5) that has complete and dependable input data validation 6) that has been completely tested so that 100% of logic bugs were eliminated ... and then if the program was installed and run by random users on their random Windows computers Q1) What types of technical (non-procedural) problems and support situations are most likely to occur, and how likely are they? Q2) Are there more/other things I could do in the first place to prevent those problems and also minimize the amount of user support required? I know some answers will apply to my specific platforms (C#, SQL, Windows, etc) and some won't. Please be as specific as is possible. Mitch Wheat gave me some very valuable advice below, but I'm now offering the bounty because I am hoping to get a better picture of the kinds of things that I'm most reasonably likely to encounter. Thanks.

    Read the article

  • With regards to urllib AttributeError: 'module' object has no attribute 'urlopen'

    - by Matt
    import re import string import shutil import os import os.path import time import datetime import math import urllib from array import array import random filehandle = urllib.urlopen('http://www.google.com/') #open webpage s = filehandle.read() #read print s #display #what i plan to do with it once i get the first part working #results = re.findall('[<td style="font-weight:bold;" nowrap>$][0-9][0-9][0-9][.][0-9][0-9][</td></tr></tfoot></table>]',s) #earnings = '$ ' #for money in results: #earnings = earnings + money[1]+money[2]+money[3]+'.'+money[5]+money[6] #print earnings #raw_input() this is the code that i have so far. now i have looked at all the other forums that give solutions such as the name of the script, which is parse_Money.py, and i have tried doing it with urllib.request.urlopen AND i have tried running it on python 2.5, 2.6, and 2.7. If anybody has any suggestions it would be really welcome, thanks everyone!! --Matt ---EDIT--- I also tried this code and it worked, so im thinking its some kind of syntax error, so if anybody with a sharp eye can point it out, i would be very appreciative. import shutil import os import os.path import time import datetime import math import urllib from array import array import random b = 3 #find URL URL = raw_input('Type the URL you would like to read from[Example: http://www.google.com/] :') while b == 3: #get file name file1 = raw_input('Enter a file name for the downloaded code:') filepath = file1 + '.txt' if os.path.isfile(filepath): print 'File already exists' b = 3 else: print 'Filename accepted' b = 4 file_path = filepath #open file FileWrite = open(file_path, 'a') #acces URL filehandle = urllib.urlopen(URL) #display souce code for lines in filehandle.readlines(): FileWrite.write(lines) print lines print 'The above has been saved in both a text and html file' #close files filehandle.close() FileWrite.close()

    Read the article

  • What is causing my HTTP server to fail with "exit status -1073741819"?

    - by Keeblebrox
    As an exercise I created a small HTTP server that generates random game mechanics, similar to this one. I wrote it on a Windows 7 (32-bit) system and it works flawlessly. However, when I run it on my home machine, Windows 7 (64-bit), it always fails with the same message: exit status -1073741819. I haven't managed to find anything on the web which references that status code, so I don't know how important it is. Here's code for the server, with redundancy abridged: package main import ( "fmt" "math/rand" "time" "net/http" "html/template" ) // Info about a game mechanic type MechanicInfo struct { Name, Desc string } // Print a mechanic as a string func (m MechanicInfo) String() string { return fmt.Sprintf("%s: %s", m.Name, m.Desc) } // A possible game mechanic var ( UnkillableObjects = &MechanicInfo{"Avoiding Unkillable Objects", "There are objects that the player cannot touch. These are different from normal enemies because they cannot be destroyed or moved."} //... Race = &MechanicInfo{"Race", "The player must reach a place before the opponent does. Like \"Timed\" except the enemy as a \"timer\" can be slowed down by the player's actions, or there may be multiple enemies being raced against."} ) // Slice containing all game mechanics var GameMechanics []*MechanicInfo // Pseudorandom number generator var prng *rand.Rand // Get a random mechanic func RandMechanic() *MechanicInfo { i := prng.Intn(len(GameMechanics)) return GameMechanics[i] } // Initialize the package func init() { prng = rand.New(rand.NewSource(time.Now().Unix())) GameMechanics = make([]*MechanicInfo, 34) GameMechanics[0] = UnkillableObjects //... GameMechanics[33] = Race } // serving var index = template.Must(template.ParseFiles( "templates/_base.html", "templates/index.html", )) func randMechHandler(w http.ResponseWriter, req *http.Request) { mechanics := [3]*MechanicInfo{RandMechanic(), RandMechanic(), RandMechanic()} if err := index.Execute(w, mechanics); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func main() { http.HandleFunc("/", randMechHandler) if err := http.ListenAndServe(":80", nil); err != nil { panic(err) } } In addition, the unabridged code, the _base.html template, and the index.html template. What could be causing this issue? Is there a process for debugging a cryptic exit status like this?

    Read the article

  • CSS styles are not applied to elements added to JavaFX component tree

    - by pazabo
    I have applied CSS style to JavaFX components and it looks like everything is working fine except one situation: when I add JavaFX components to component tree on-the-fly their CSS styles are not applied. For example following code: package test; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.shape.Rectangle; import javafx.scene.input.MouseEvent; import javafx.util.Math; import javafx.scene.paint.Color; function getRect(): Rectangle { return Rectangle { x: 230 * Math.random() y: 60 * Math.random() width: 20, height: 20 styleClass: "abc" } } def stage: Stage = Stage { scene: Scene { width: 250, height: 80 stylesheets: "{__DIR__}main.css" content: [ Rectangle { x: 0, y: 0, width: 250, height: 80 fill: Color.WHITE onMouseClicked: function (evt: MouseEvent): Void { insert getRect() into stage.scene.content; } } getRect() ] } } with following stylesheet: .abc { fill: red; } in main.css file (both in test package) display red square on white background, but after clicking the main rectangle black (not red) squares are added to scene. I noticed that: Components added dynamically look just like style information was not applied. If you set their style in JavaFX code then everything works fine. After changing stylesheets property (so that it points to another valid stylesheet) the objects already added render properly. Does anyone know the solution to this problem? I could of course put all the properties into JavaFX code or provide another stylesheet (for every existing stylesheed) that would contain the same data and change stylesheet right after adding any component, but I would like to find some elegant solution. Thanks in advance.

    Read the article

  • How to map coordinates in AxesImage to coordinates in saved image file?

    - by Vebjorn Ljosa
    I use matplotlib to display a matrix of numbers as an image, attach labels along the axes, and save the plot to a PNG file. For the purpose of creating an HTML image map, I need to know the pixel coordinates in the PNG file for a region in the image being displayed by imshow. I have found an example of how to do this with a regular plot, but when I try to do the same with imshow, the mapping is not correct. Here is my code, which saves an image and attempts to print the pixel coordinates of the center of each square on the diagonal: import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) axim = ax.imshow(np.random.random((27,27)), interpolation='nearest') for x, y in axim.get_transform().transform(zip(range(28), range(28))): print int(x), int(fig.get_figheight() * fig.get_dpi() - y) plt.savefig('foo.png', dpi=fig.get_dpi()) Here is the resulting foo.png, shown as a screenshot in order to include the rulers: The output of the script starts and ends as follows: 73 55 92 69 111 83 130 97 149 112 … 509 382 528 396 547 410 566 424 585 439 As you see, the y-coordinates are correct, but the x-coordinates are stretched: they range from 73 to 585 instead of the expected 135 to 506, and they are spaced 19 pixels o.c. instead of the expected 14. What am I doing wrong?

    Read the article

  • Error trying to use rand from std library cstdlib with g++

    - by Matt
    I was trying to use the random function in Ubuntu compiling with g++ on a larger program and for some reason rand just gave weird compile errors. For testing purposes I made the simplest program I could and it still gives errors. Program: #include <iostream> using std::cout; using std::endl; #include <cstdlib> int main() { cout << "Random number " << rand(); return 0; } Error when compiling with the terminal sudo g++ chapter_3/tester.cpp ./test ./test: In function _start': /build/buildd/eglibc-2.10.1/csu/../sysdeps/i386/elf/start.S:65: multiple definition of_start' /usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crt1.o:/build/buildd/eglibc-2.10.1/csu/../sysdeps/i386/elf/start.S:65: first defined here ./test:(.rodata+0x0): multiple definition of _fp_hw' /usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crt1.o:(.rodata+0x0): first defined here ./test: In function_fini': (.fini+0x0): multiple definition of _fini' /usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crti.o:(.fini+0x0): first defined here ./test:(.rodata+0x4): multiple definition of_IO_stdin_used' /usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crt1.o:(.rodata.cst4+0x0): first defined here ./test: In function __data_start': (.data+0x0): multiple definition ofdata_start' /usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crt1.o:(.data+0x0): first defined here ./test: In function __data_start': (.data+0x4): multiple definition of__dso_handle' /usr/lib/gcc/i486-linux-gnu/4.4.1/crtbegin.o:(.data+0x0): first defined here ./test: In function main': (.text+0xb4): multiple definition ofmain' /tmp/cceF0x0p.o:tester.cpp:(.text+0x0): first defined here ./test: In function _init': (.init+0x0): multiple definition ofinit' /usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crti.o:(.init+0x0): first defined here /usr/lib/gcc/i486-linux-gnu/4.4.1/crtend.o:(.dtors+0x0): multiple definition of `_DTOR_END' ./test:(.dtors+0x4): first defined here /usr/bin/ld: error in ./test(.eh_frame); no .eh_frame_hdr table will be created. collect2: ld returned 1 exit status

    Read the article

  • .NET proxy detection

    - by Ziplin
    I am having an issue with .NET detecting the proxy settings configured through internet explorer. I'm writing a client application that supports proxies, and to test I set up an array of 9 squid servers to support various authentication methods for HTTP and HTTPs. I have a script that updates IE to whichever configuration I choose (which proxy, detection via "Auto", PAC, or hardcode). I have tried the 3 methods below to detect the IE configuration through .NET. On occassion I notice that .NET picks up the wrong set of proxy servers. IE has the correct settings, and if I browse the web with IE, I can see I am hitting the correct servers via wireshark. WebRequest.GetSystemWebProxy().GetProxy(destination); GlobalProxySelection.Select.GetProxy(destination); WebRequest.DefaultWebProxy Here are the following tips I have: My script sets a PAC file on a webserver, and updates the configuration in IE, then clears IE's cache .NET seems to get "stuck" on a certain proxy configuration, and I have to set another configuration for .NET to realize there was a change. Occasionally it seems to pick some random set of servers (I'm sure they're not random, just a set of servers I used once and are in some cached PAC file or something). As in, I will check the proxy for the destination "https://www.secure.com" and I may have IE configured for and thus expect to get "http://squidserver:18" and instead it will return "http://squidserver:28" (port 18 runs NTLM, 28 runs without authentication). All the squid servers work. This does not appear to be an issue on XP, only Vista, 2003, and windows 7. Hardcoding the proxy servers in IE ALWAYS works Time always solves the issue - if I leave the computer for about 20 or 30 minutes and come back, .NET picks up the correct proxy settings, as if a cached PAC script expired.

    Read the article

  • Password hashing, salt and storage of hashed values

    - by Jonathan Leffler
    Suppose you were at liberty to decide how hashed passwords were to be stored in a DBMS. Are there obvious weaknesses in a scheme like this one? To create the hash value stored in the DBMS, take: A value that is unique to the DBMS server instance as part of the salt, And the username as a second part of the salt, And create the concatenation of the salt with the actual password, And hash the whole string using the SHA-256 algorithm, And store the result in the DBMS. This would mean that anyone wanting to come up with a collision should have to do the work separately for each user name and each DBMS server instance separately. I'd plan to keep the actual hash mechanism somewhat flexible to allow for the use of the new NIST standard hash algorithm (SHA-3) that is still being worked on. The 'value that is unique to the DBMS server instance' need not be secret - though it wouldn't be divulged casually. The intention is to ensure that if someone uses the same password in different DBMS server instances, the recorded hashes would be different. Likewise, the user name would not be secret - just the password proper. Would there be any advantage to having the password first and the user name and 'unique value' second, or any other permutation of the three sources of data? Or what about interleaving the strings? Do I need to add (and record) a random salt value (per password) as well as the information above? (Advantage: the user can re-use a password and still, probably, get a different hash recorded in the database. Disadvantage: the salt has to be recorded. I suspect the advantage considerably outweighs the disadvantage.) There are quite a lot of related SO questions - this list is unlikely to be comprehensive: Encrypting/Hashing plain text passwords in database Secure hash and salt for PHP passwords The necessity of hiding the salt for a hash Clients-side MD5 hash with time salt Simple password encryption Salt generation and Open Source software I think that the answers to these questions support my algorithm (though if you simply use a random salt, then the 'unique value per server' and username components are less important).

    Read the article

< Previous Page | 66 67 68 69 70 71 72 73 74 75 76 77  | Next Page >