Search Results

Search found 19539 results on 782 pages for 'pretty print'.

Page 118/782 | < Previous Page | 114 115 116 117 118 119 120 121 122 123 124 125  | Next Page >

  • I need to make a multithreading program (python)

    - by Andreawu98
    import multiprocessing import time from itertools import product out_file = open("test.txt", 'w') P = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p','q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',] N = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] M = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] c = int(input("Insert the number of digits you want: ")) n = int(input("If you need number press 1: ")) m = int(input("If you need upper letters press 1: ")) i = [] if n == 1: P = P + N if m == 1: P = P + M then = time.time() def worker(): for i in product(P, repeat=c): #check every possibilities k = '' for z in range(0, c): # k = k + str(i[z]) # print each possibility in a txt without parentesis or comma out_file.write( k + '\n') # out_file.close() now = time.time() diff = str(now - then) # To see how long does it take print(diff) worker() time.sleep(10) # just to check console The code check every single possibility and print it out in a test.txt file. It works but I really can't understand how can I speed it up. I saw it use 1 core out of my quad core CPU so I thought Multi-threading might work even though I don't know how. Please help me. Sorry for my English, I am from Italy.

    Read the article

  • SFTP in Python? (platform independent)

    - by Mark Wilbur
    I'm working on a simple tool that transfers files to a hard-coded location with the password also hard-coded. I'm a python novice, but thanks to ftplib, it was easy: import ftplib info= ('someuser', 'password') #hard-coded def putfile(file, site, dir, user=(), verbose=True): """ upload a file by ftp to a site/directory login hard-coded, binary transfer """ if verbose: print 'Uploading', file local = open(file, 'rb') remote = ftplib.FTP(site) remote.login(*user) remote.cwd(dir) remote.storbinary('STOR ' + file, local, 1024) remote.quit() local.close() if verbose: print 'Upload done.' if __name__ == '__main__': site = 'somewhere.com' #hard-coded dir = './uploads/' #hard-coded import sys, getpass putfile(sys.argv[1], site, dir, user=info) The problem is that I can't find any library that supports sFTP. What's the normal way to do something like this securely? Edit: Thanks to the answers here, I've gotten it working with Paramiko and this was the syntax. import paramiko host = "THEHOST.com" #hard-coded port = 22 transport = paramiko.Transport((host, port)) password = "THEPASSWORD" #hard-coded username = "THEUSERNAME" #hard-coded transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport) import sys path = './THETARGETDIRECTORY/' + sys.argv[1] #hard-coded localpath = sys.argv[1] sftp.put(localpath, path) sftp.close() transport.close() print 'Upload done.' Thanks again!

    Read the article

  • Anything wrong with my cURL code (http status of 0)?

    - by Ilya
    Consistently getting a status of 0 even though if I copy and paste the url sent into my browser, I get a json object right back <?php $mainUrl = "https://api.xxxx.com/?"; $co = "xxxxx"; $pa = "xxxx"; $par = "xxxx"; $part= "xxxx"; $partn = "xxxx"; $us= "xxx"; $fields_string; $fields = array( 'co'=>urlencode($co), 'pa'=>urlencode($pa), 'par'=>urlencode($par), 'part'=>urlencode($part), 'partn'=>urlencode($partn), 'us'=>urlencode($us) ); foreach($fields as $key=>$value) { $fields_string .= $key . '=' . $value . '&' ;} $fields_string = rtrim($fields_string, "&"); $fields_string = "?" . $fields_string; $url = "https://api.xxxxx.com/" . $fields_string; $request = $url; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_TIMEOUT,'3'); $content = trim(curl_exec($ch)); $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); print $url; print $http_status; print $content; ?>

    Read the article

  • Celery Received unregistered task of type (run example)

    - by Echeg
    I'm trying to run example from Celery documentation. I run: celeryd --loglevel=INFO /usr/local/lib/python2.7/dist-packages/celery/loaders/default.py:64: NotConfigured: No 'celeryconfig' module found! Please make sure it exists and is available to Python. "is available to Python." % (configname, ))) [2012-03-19 04:26:34,899: WARNING/MainProcess] -------------- celery@ubuntu v2.5.1 ---- **** ----- --- * *** * -- [Configuration] -- * - **** --- . broker: amqp://guest@localhost:5672// - ** ---------- . loader: celery.loaders.default.Loader - ** ---------- . logfile: [stderr]@INFO - ** ---------- . concurrency: 4 - ** ---------- . events: OFF - *** --- * --- . beat: OFF -- ******* ---- --- ***** ----- [Queues] -------------- . celery: exchange:celery (direct) binding:celery tasks.py: # -*- coding: utf-8 -*- from celery.task import task @task def add(x, y): return x + y run_task.py: # -*- coding: utf-8 -*- from tasks import add result = add.delay(4, 4) print (result) print (result.ready()) print (result.get()) In same folder celeryconfig.py: CELERY_IMPORTS = ("tasks", ) CELERY_RESULT_BACKEND = "amqp" BROKER_URL = "amqp://guest:guest@localhost:5672//" CELERY_TASK_RESULT_EXPIRES = 300 When I run "run_task.py": on python console eb503f77-b5fc-44e2-ac0b-91ce6ddbf153 False errors on celeryd server [2012-03-19 04:34:14,913: ERROR/MainProcess] Received unregistered task of type 'tasks.add'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you are using relative imports? Please see http://bit.ly/gLye1c for more information. The full contents of the message body was: {'retries': 0, 'task': 'tasks.add', 'utc': False, 'args': (4, 4), 'expires': None, 'eta': None, 'kwargs': {}, 'id': '841bc21f-8124-436b-92f1-e3b62cafdfe7'} Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/celery/worker/consumer.py", line 444, in receive_message self.strategies[name](message, body, message.ack_log_error) KeyError: 'tasks.add' Please explain what's the problem.

    Read the article

  • Printing Images C# Overlapping Wrong

    - by Alen
    I have created a program much like Photoshop in the sense that you can place images (picture box) on a control, move them around, delete them, and so on... I have also managed to put together a method to print all the images on the control with no problems. But here is the weird part: When I click print, the program prints the image which was placed first, on top of the image which came second. On the screen the user can see the image which was placed second, on top of the first placed image (the way it should be) but when I print its opposite? I have no idea why it does this... I hope I've made my self as clear as possible, any help is appreciated! public void printToGraphics(Graphics graphics, Rectangle bounds) { graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; Bitmap bitmap = new Bitmap(newLabel.Width, newLabel.Height); newLabel.DrawToBitmap(bitmap, newLabel.DisplayRectangle); Rectangle target = new Rectangle(0, 0, bounds.Width, bounds.Height); target.Height = bitmap.Height; target.Width = bitmap.Width; graphics.PageUnit = GraphicsUnit.Display; graphics.DrawImage(bitmap,target); } void printDoc_PrintPage(object sender, PrintPageEventArgs e) { printToGraphics(e.Graphics, e.MarginBounds); }

    Read the article

  • How to check volume is mounted or not using python with a dynamic volume name

    - by SR query
    import subprocess def volumeCheck(volume_name): """This function will check volume name is mounted or not. """ volume_name = raw_input('Enter volume name:') volumeCheck(volume_name) print 'volume_name=',volume_name p = subprocess.Popen(['df', '-h'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) p1, err = p.communicate() pattern = p1 if pattern.find(volume_name): print 'volume found' else: print 'volume not found' While running i always got wrong result "volume found". root@sr-query:/# df -h Filesystem Size Used Avail Use% Mounted on rootfs 938M 473M 418M 54% / /dev/md0 938M 473M 418M 54% / none 250M 4.9M 245M 2% /dev /dev/md2 9.7M 1.2M 8.0M 13% /usr/config /dev/md7 961M 18M 895M 2% /downloads tmpfs 250M 7.9M 242M 4% /var/volatile tmpfs 250M 0 250M 0% /dev/shm tmpfs 250M 0 250M 0% /media/ram **/dev/mapper/vg9-lv9 1016M 65M 901M 7% /VolumeData/sp /dev/mapper/vg10-lv10 1016M 65M 901M 7% /VolumeData/cp** root@sr-query:/# root@sr-query:/# root@sr-query:/# python volume_check.py Enter volume name:raid_10volume volume_name= raid_10volume **volume found** root@sr-query:/# I enterd raid_10volume its not listed here please check the df -h command out put(only 2 volume there sp and cp) , then how it reached else part. what is wrong in my code? Thanks in advance. is there any other way to do this work ! ?

    Read the article

  • Python Beautiful Soup .content Property

    - by Robert Birch
    What does BeautifulSoup's .content do? I am working through crummy.com's tutorial and I don't really understand what .content does. I have looked at the forums and I have not seen any answers. Looking at the code below.... from BeautifulSoup import BeautifulSoup import re doc = ['<html><head><title>Page title</title></head>', '<body><p id="firstpara" align="center">This is paragraph <b>one</b>.', '<p id="secondpara" align="blah">This is paragraph <b>two</b>.', '</html>'] soup = BeautifulSoup(''.join(doc)) print soup.contents[0].contents[0].contents[0].contents[0].name I would expect the last line of the code to print out 'body' instead of... File "pe_ratio.py", line 29, in <module> print soup.contents[0].contents[0].contents[0].contents[0].name File "C:\Python27\lib\BeautifulSoup.py", line 473, in __getattr__ raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr) AttributeError: 'NavigableString' object has no attribute 'name' Is .content only concerned with html, head and title? If, so why is that? Thanks for the help in advance.

    Read the article

  • Why does my perl script return a zero return code when I explicitly call exit with a non-zero parame

    - by Tom Duckering
    I have a perl script which calls another script. The perl script should be propagating the script's return code but seems to be returning zero to its caller (a Java application) desipte the explicit call to exit $scriptReturnCode. It's probably something dumb since I'm by no means a perl expert. Code and output as follows (I realise that <=> could/should be != but that's what I have): print "INFO: Calling ${scriptDirectory}/${script} ${args}" $scriptReturnCode = system("${scriptDirectory}/${script} ${args}"); if ( $scriptReturnCode <=> 0 ) { print "ERROR: The script returned $scriptReturnCode\n"; exit $scriptReturnCode; } else { print "INFO: The script returned $scriptReturnCode.\n"; exit 0; } The output I have from my Java is: 20/04/2010 14:40:01 - INFO: Calling /path/to/script/script.ksh arg1 arg2 20/04/2010 14:40:01 - Could not find installer files <= this is from the script.ksh 20/04/2010 14:40:01 - ERROR: The script returned 256 20/04/2010 14:40:01 - Command Finished. Exit Code: 0 <= this is the Java app.

    Read the article

  • parsing python to csv

    - by user185955
    I'm trying to download some game stats to do some analysis, only problem is each season the data their isn't 100% consistent. I grab the json file from the site, then wish to save it to a csv with the first line in the csv containing the heading for that column, so the heading would be essentially the key from the python data type. #!/usr/bin/env python import requests import json import csv base_url = 'http://www.afl.com.au/api/cfs/afl/' token_url = base_url + 'WMCTok' player_url = base_url + 'matchItems/round' def printPretty(data): print(json.dumps(data, sort_keys=True, indent=2, separators=(',', ': '))) session = requests.Session() # session makes it simple to use the token across the requests token = session.post(token_url).json()['token'] # get the token session.headers.update({'X-media-mis-token': token}) # set the token Season = 2014 Roundno = 4 if Roundno<10: strRoundno = '0'+str(Roundno) else: strRoundno = str(Roundno) # get some data (could easily be a for loop, might want to put in a delay using Sleep so that you don't get IP blocked) data = session.get(player_url + '/CD_R'+str(Season)+'014'+strRoundno) # print everything printPretty(data.json()) with open('stats_game_test.csv', 'w', newline='') as csvfile: spamwriter = csv.writer(csvfile, delimiter="'",quotechar='|', quoting=csv.QUOTE_ALL) for profile in data.json()['items']: spamwriter.writerow(['%s' %(profile)]) #for key in data.json().keys(): # print("key: %s , value: %s" % (key, data.json()[key])) The above code grabs the json and writes it to a csv, but it puts the key in each individual cell next to the value (eg 'venueId': 'CD_V190'), the key needs to be just across the first row as a heading. It gives me a csv file with data in the cells like this Column A B 'tempInCelsius': 17.0 'totalScore': 32 'tempInCelsius': 16.0 'totalScore': 28 What I want is the data like this tempInCelsius totalScore 17 32 16 28 As I mentioned up the top, the data isn't always consistent so if I define what fields to grab with spamwriter.writerow([profile['tempInCelsius'], profile['totalScore']]) then it will error out on certain data grabs. This is why I'm now trying the above method so it just grabs everything regardless of what data is there.

    Read the article

  • How do I pass three arrays from on method to another?

    - by user2966716
    I have a method studentSummary, that scans the input and creates three arrays examMark,courseworkMark and courseworkWeight. I need these arrays passing over to a different method, so I can use them to calculate moduleResult. heres my code: public static int[] studentSummary(int[] courseworkWeight2, int [] examMark2 , int [] courseworkMark2){ int examMark[] = { 0, 0, 0, 0, 0, 0 }; int courseworkMark[] = { 0, 0, 0, 0, 0, 0 }; Scanner resultInput = new Scanner(System.in); int courseworkWeight[] = { 0, 0, 0, 0, 0, 0 }; for (int k = 1; k < 7; k++) { System.out.print("Please enter exam marks for module " + k + ":"); examMark[k - 1] = resultInput.nextInt(); System.out.print("Please enter Coursework marks for module " + k + ":"); courseworkMark[k - 1] = resultInput.nextInt(); System.out.print("Please enter Coursework weighting for module " + k + ":"); courseworkWeight[k - 1] = resultInput.nextInt(); } Calculator method: public static int[] markCalculator() { int[] courseworkWeight = new int [6]; int[] courseworkMark = new int [6]; int[] examMark = new int [6]; for (int i = 0; i < 6; i++) { computedModuleMark = ((courseworkMark[i] * courseworkWeight[i]) + (examMark[i] * (100 - courseworkWeight[i]))) / 100; if ((computedModuleMark) < 35) { if (examMark[i]<35){ } } moduleMark[i] = computedModuleMark; } computeResult(moduleMark); StudentChart.draw(moduleMark); StudentChart.printSummary(moduleMark); return moduleMark; }

    Read the article

  • For each loop not reading in the last item

    - by Gandalf StormCrow
    I'm trying to read in a multi line string then split it then print it .. here is the string : 1T1b5T!1T2b1T1b2T!1T1b1T2b2T!1T3b1T1b1T!3T3b1T!1T3b1T1b1T!5T1*1T 11X21b1X 4X1b1X When I split the string with ! I get this without the last line string : 1T1b5T 1T1b5T1T2b1T1b2T 1T2b1T1b2T1T1b1T2b2T 1T1b1T2b2T1T3b1T1b1T 1T3b1T1b1T3T3b1T 3T3b1T1T3b1T1b1T 1T3b1T1b1T5T1*1T 5T1*1T11X21b1X 11X21b1X Here is my code : import java.io.BufferedInputStream; import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner stdin = new Scanner(new BufferedInputStream(System.in)); while (stdin.hasNext()) { for (String line : stdin.next().split("!")) { System.out.println(line); for (int i = 0; i < line.length(); i++) { System.out.print(line.charAt(i)); } } } } } Where did I make the mistake, why is not reading in the last line? After I read in all lines properly I should go trough each line if I encounter number I should print the next char the n times the number I just read, but that is long way ahead first I need help with this. Thank you

    Read the article

  • How can I read and parse chunks of data into a Perl hash of arrays?

    - by neversaint
    I have data that looks like this: #info #info2 1:SRX004541 Submitter: UT-MGS, UT-MGS Study: Glossina morsitans transcript sequencing project(SRP000741) Sample: Glossina morsitans(SRS002835) Instrument: Illumina Genome Analyzer Total: 1 run, 8.3M spots, 299.9M bases Run #1: SRR016086, 8330172 spots, 299886192 bases 2:SRX004540 Submitter: UT-MGS Study: Anopheles stephensi transcript sequencing project(SRP000747) Sample: Anopheles stephensi(SRS002864) Instrument: Solexa 1G Genome Analyzer Total: 1 run, 8.4M spots, 401M bases Run #1: SRR017875, 8354743 spots, 401027664 bases 3:SRX002521 Submitter: UT-MGS Study: Massive transcriptional start site mapping of human cells under hypoxic conditions.(SRP000403) Sample: Human DLD-1 tissue culture cell line(SRS001843) Instrument: Solexa 1G Genome Analyzer Total: 6 runs, 27.1M spots, 977M bases Run #1: SRR013356, 4801519 spots, 172854684 bases Run #2: SRR013357, 3603355 spots, 129720780 bases Run #3: SRR013358, 3459692 spots, 124548912 bases Run #4: SRR013360, 5219342 spots, 187896312 bases Run #5: SRR013361, 5140152 spots, 185045472 bases Run #6: SRR013370, 4916054 spots, 176977944 bases What I want to do is to create a hash of array with first line of each chunk as keys and SR## part of lines with "^Run" as its array member: $VAR = { 'SRX004541' => ['SRR016086'], # etc } But why my construct doesn't work. And it must be a better way to do it. use Data::Dumper; my %bighash; my $head = ""; my @temp = (); while ( <> ) { chomp; next if (/^\#/); if ( /^\d{1,2}:(\w+)/ ) { print "$1\n"; $head = $1; } elsif (/^Run \#\d+: (\w+),.*/){ print "\t$1\n"; push @temp, $1; } elsif (/^$/) { push @{$bighash{$head}}, [@temp]; @temp =(); } } print Dumper \%bighash ;

    Read the article

  • Handling text menu in Python

    - by PulpFiction
    Hi all. I am trying to create a text based menu in Python. Here is the code: #!/usr/bin/env python def testcaseOutput(): print '1. Add. 2. Subtract. 3. Divide. 4. Multiply' try: answer = int(raw_input('Enter a value (1 - 4) >. ')) except ValueError: print 'Invalid input. Enter a value between 1 -4 .' testcaseOutput() if answer in range(1, 5): return answer else: print 'Invalid input. Enter a value between 1 - 4.' testcaseOutput() My question: When the user enters an invalid input, i.e. not a number, I want this function to get called again. So I used the recursive approach which I think is bad design. I use that approach again in the if answer in range(1, 5). Is there any other way to handle this? I need the prompt called again when there is an invalid input. Also, is there any way I can club the two constraints: check whether input is a number and check whether the number is in the range(1,5) together? As you can see, I am checking that individually.

    Read the article

  • Python script not working when run from browser directly

    - by splatterdash
    I'm trying to run this script: import re, os def build_pool(cwd): global xtn_pool, file_pool xtn, xtn_pool = re.compile('\\.[0-9a-zA-Z]{1,4}$'), [] file_pool = [files for files in os.listdir(cwd) if os.path.isfile(files) and xtn.search(files)] # Lists all the file extension in the folder for file in file_pool: if not xtn_pool.__contains__(xtn.search(file).group()): xtn_pool.append(xtn.search(file).group()) return xtn_pool.sort(), file_pool if __name__ == '__main__': import sys #if path is given, change working directory to path if len(sys.argv) >= 2: os.chdir(sys.argv[1]) build_pool(os.getcwd()) #if no path is given when running, do renaming in current folder else: build_pool(os.getcwd()) print('The folder contains the following extensions: ') for i in range(0, len(xtn_pool)): print(repr(i+1) + '. ' + xtn_pool[i][1:]) opt = int(input('Which one would you like to replace? ')) xtn_pick = xtn_pool[opt-1] # Lists all the file with the chosen extension xtn_file_pool = [file for file in file_pool if file.endswith(xtn_pick)] print('There are {0} files with the {1} extension.'.format(len(xtn_file_pool), xtn_pick)) xtn_new = input('Input replacement extension: ') # The actual renaming process for file in xtn_file_pool: os.rename(file, file[:-len(xtn_pick)+1] + xtn_new) directly from my file browser (Nautilus), but for some reason it's not working. When I run it from terminal (python3 scriptname.py) it works fine as intended. But when I just click the script file in Nautilus, choose 'Run in Terminal', it always stops after asking 'Input replacement extension: '. How can I make this script run without using the terminal?

    Read the article

  • How to implement the "System.out.println(ClassName::MethodName <then my message>)" of Eclipse in Netbeans?

    - by Sen
    I would like to know if there is the same feature as in eclipse to automatically generate and print the System.out.println(ClassName::MethodName <then my message>) functionality (which will print the class name and method name for debugging in the console) in Netbeans also. For example, in Eclipse Editor, Typing syst + Ctrl+ Space will auto generate a System.out.println(ClassName::MethodName ) type output in the console. Is such a method available in Netbeans? As of now, I have only two methods here in Netbeans: sout + Tab (System.out.println()) and soutv + Tab (System.out.println(prints the variable used just above the line)) automatically. Let me rephrase, instead of myMethod1, I want to get the enclosing method name. Eg. : public class X { public void myMethod1(int a) { System.out.println(X::myMethod1()); // This should be produced when I type the Code-Template abbreviation (example: syst) and press tab (or corresponding key). } } public class Y { public void myMethod2(int b) { System.out.println(Y::myMethod2()); // This should be produced when I type the Code-Template abbreviation (example: syst) and press tab (or corresponding key). } } Update: With the following code template: syst = System.out.println("${classVar editable="false" currClassName default="getClass()"}"); I am able to print the classname, but still no clue for the Method name.

    Read the article

  • Python client / server question

    - by AustinM
    I'm working on a bit of a project in python. I have a client and a server. The server listens for connections and once a connection is received it waits for input from the client. The idea is that the client can connect to the server and execute system commands such as ls and cat. This is my server code: import sys, os, socket host = '' port = 50105 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) print("Server started on port: ", port) s.listen(5) print("Server listening\n") conn, addr = s.accept() print 'New connection from ', addr while (1): rc = conn.recv(5) pipe = os.popen(rc) rl = pipe.readlines() file = conn.makefile('w', 0) file.writelines(rl[:-1]) file.close() conn.close() And this is my client code: import sys, socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = 'localhost' port = input('Port: ') s.connect((host, port)) cmd = raw_input('$ ') s.send(cmd) file = s.makefile('r', 0) sys.stdout.writelines(file.readlines()) When I start the server I get the right output, saying the server is listening. But when I connect with my client and type a command the server exits with this error: Traceback (most recent call last): File "server.py", line 21, in <module> rc = conn.recv(2) File "/usr/lib/python2.6/socket.py", line 165, in _dummy raise error(EBADF, 'Bad file descriptor') socket.error: [Errno 9] Bad file descriptor On the client side, I get the output of ls but the server gets screwed up.

    Read the article

  • Good C string libary

    - by chamakits
    Hello all. I recently got inspired to start up a project I've been wanting to code for a while. I want to do it in C, because memory handling is key this application. I was searching around for a good implementation of strings in C, since I know me doing it myself could lead to some messy buffer overflows, and I expect to be dealing with a fairly big amount of strings. I found this article which gives details on each, but they each seem like they have a good amount of cons going for them (don't get me wrong, this article is EXTREMELY helpful, but it still worries me that even if I were to choose one of those, I wouldn't be using the best I can get). I also don't know how up to date the article is, hence my current plea. What I'm looking for is something that may hold a large amount of characters, and simplifies the process of searching through the string. If it allows me to tokenize the string in any way, even better. Also, it should have some pretty good I/O performance. Printing, and formatted printing isn't quite a top priority. I know I shouldn't expect a library to do all the work for me, but was just wandering if there was a well documented string function out there that could save me some time and some work. Any help is greatly appreciated. Thanks in advance! EDIT: I was asked about the license I prefer. Any sort of open source license will do, but preferably GPL (v2 or v3). EDIt2: I found betterString (bstring) library and it looks pretty good. Good documentation, small yet versatile amount of functions, and easy to mix with c strings. Anyone have any good or bad stories about it? The only downside I've read about it is that it lacks Unicode (again, read about this, haven't seen it face to face just yet), but everything else seems pretty good. EDIT3: Also, preferable that its pure C.

    Read the article

  • Interpretation of range(n) and boolean list, one-to-one map, simpler?

    - by HH
    #!/usr/bin/python # # Description: bitwise factorization and then trying to find # an elegant way to print numbers # Source: http://forums.xkcd.com/viewtopic.php?f=11&t=61300#p2195422 # bug with large numbers such as 99, but main point in simplifying it # def primes(n): # all even numbers greater than 2 are not prime. s = [False]*2 + [True]*2 + [False,True]*((n-4)//2) + [False]*(n%2) i = 3; while i*i < n: # get rid of ** and skip even numbers. s[i*i : n : i*2] = [False]*(1+(n-i*i)//(i*2)) i += 2 # skip non-primes while not s[i]: i += 2 return s # TRIAL: can you find a simpler way to print them? # feeling the overuse of assignments but cannot see a way to get it simpler # p = 49 boolPrimes = primes(p) numbs = range(len(boolPrimes)) mydict = dict(zip(numbs, boolPrimes)) print([numb for numb in numbs if mydict[numb]]) Something I am looking for, can you get TRIAL to be of the extreme simplicity below? Any such method? a=[True, False, True] b=[1,2,3] b_a # any such simple way to get it evaluated to [1,3] # above a crude way to do it in TRIAL

    Read the article

  • need help with some basic java.

    - by Racket
    Hi, I'm doing the first chapter exercises on my Java book and I have been stuck for a problem for a while now. I'll print the question, prompt/read a double value representing a monetary amount. Then determine the fewest number of each bill and coin needed to represent that amount, starting with the highest (assume that a ten dollar bill is the maximum size needed). For example, if the value entered is 47,63 (forty-seven dollars and sixty-three cents), and the program should print the equivalent amount as: 4 ten dollar bills 1 five dollar bills 2 one dollar bills 2 quarters 1 dimes 0 nickels 3 pennies" etc. I'm doing an example exactly as they said in order to get an idea, as you will see in the code. Nevertheless, I managed to print 4 dollars, and I can't figure out how to get "1 five dollar", only 7 dollars (see code). Please, don't do the whole code for me. I just need some advice in regards to what I said. Thank you. import java.util.Scanner; public class PP29 { public static void main (String[] args) { Scanner sc = new Scanner (System.in); int amount; double value; double test1; double quarter; System.out.println("Enter \"double\" value: "); value = sc.nextDouble(); amount = (int) value / 10; // 47,63 / 10 = 4. int amount2 = (int) value % 10; // 47 - 40 = 7 quarter = value * 100; // 47,63 * 100 = 4736 int sum = (int) quarter % 100; // 4763 / 100 => 4763-4700 = 63. System.out.println(amount); System.out.println(amount2); } }

    Read the article

  • Can I make a derived class inherit a derived member from its base class in Java?

    - by Eric
    I have code that looks like this: public class A { public void doStuff() { System.out.print("Stuff successfully done"); } } public class B extends A { public void doStuff() { System.out.print("Stuff successfully done, but in a different way"); } public void doMoreStuff() { System.out.print("More advanced stuff successully done"); } } public class AWrapper { public A member; public AWrapper(A member) { this.member = member; } public void doStuffWithMember() { a.doStuff(); } } public class BWrapper extends AWrapper { public B member; public BWrapper(B member) { super(member); //Pointer to member stored in two places: this.member = member; //Not great if one changes, but the other does not } public void doStuffWithMember() { member.doMoreStuff(); } } However, there is a problem with this code. I'm storing a reference to the member in two places, but if one changes and the other does not, there could be trouble. I know that in Java, an inherited method can narrow down its return type (and perhaps arguments, but I'm not certain) to a derived class. Is the same true of fields?

    Read the article

  • How to match words as if in a dictionary, based on len-1 or len+1? Python

    - by pearbear
    If I have a word 'raqd', how would I use python to have a spellcheck, so to speak, to find the word 'rad' as an option in 'spellcheck'? What I've been trying to do is this: def isbettermatch(keysplit, searchword): i = 0 trues = 0 falses = 0 lensearchwords = len(searchword) keysplits = copy.deepcopy(keysplit) searchwords = copy.deepcopy(searchword) #print keysplit, searchwords if len(keysplits) == len(searchwords)-1: i = 0 while i < len(keysplits): j = 0 while j < lensearchwords: if keysplits[i] == searchwords[j]: trues +=1 searchwords.pop(j) lensearchwords = len(searchwords) elif keysplits[i] != searchwords[j]: falses +=1 j +=1 i +=1 if trues >= len(searchwords)-1: #print "-------------------------------------------------------", keysplits return True keysplit is a list like ['s', 'p', 'o', 'i', 'l'] for example, and the searchword would be a list ['r', 'a', 'q', 'd']. If the function returns True, then it would print the keyword that matches. Ex. 'rad', for the searchword 'raqd'. I need to find all possible matches for the searchword with a single letter addition or deletion. so ex. 'raqd' would have an option to be 'rad', and 'poted' could be 'posted' or 'potted'. Above is what I have tried, but it is not working well at all. Help much appreciated!

    Read the article

  • Python: Trouble with YACC

    - by Rosarch
    I'm parsing sentences like: "CS 2310 or equivalent experience" The desired output: [[("CS", 2310)], ["equivalent experience"]] YACC tokenizer symbols: tokens = [ 'DEPT_CODE', 'COURSE_NUMBER', 'OR_CONJ', 'MISC_TEXT', ] t_DEPT_CODE = r'[A-Z]{2,}' t_COURSE_NUMBER = r'[0-9]{4}' t_OR_CONJ = r'or' t_ignore = ' \t' terms = {'DEPT_CODE': t_DEPT_CODE, 'COURSE_NUMBER': t_COURSE_NUMBER, 'OR_CONJ': t_OR_CONJ} for name, regex in terms.items(): terms[name] = "^%s$" % regex def t_MISC_TEXT(t): r'\S+' for name, regex in terms.items(): # print "trying to match %s with regex %s" % (t.value, regex) if re.match(regex, t.value): t.type = name return t return t (MISC_TEXT is meant to match anything not caught by the other terms.) Some relevant rules from the parser: precedence = ( ('left', 'MISC_TEXT'), ) def p_statement_course_data(p): 'statement : course_data' p[0] = p[1] def p_course_data(p): 'course_data : course' p[0] = p[1] def p_course(p): 'course : DEPT_CODE COURSE_NUMBER' p[0] = make_course(p[1], int(p[2])) def p_or_phrase(p): 'or_phrase : statement OR_CONJ statement' p[0] = [[p[1]], [p[3]]] def p_misc_text(p): '''text_aggregate : MISC_TEXT MISC_TEXT | MISC_TEXT text_aggregate | text_aggregate MISC_TEXT ''' p[0] = "%s %s" % (p[0], [1]) def p_text_aggregate_statement(p): 'statement : text_aggregate' p[0] = p[1] Unfortunately, this fails: # works as it should >>> token_list("CS 2110 or equivalent experience") [LexToken(DEPT_CODE,'CS',1,0), LexToken(COURSE_NUMBER,'2110',1,3), LexToken(OR_CONJ,'or',1,8), LexToken(MISC_TEXT,'equivalent',1,11), LexToken(MISC_TEXT,'experience',1,22)] # fails. bummer. >>> parser.parse("CS 2110 or equivalent experience") Syntax error in input: LexToken(MISC_TEXT,'equivalent',1,11) What am I doing wrong? I don't fully understand how to set precedence rules. Also, this is my error function: def p_error(p): print "Syntax error in input: %s" % p Is there a way to see which rule the parser was trying when it failed? Or some other way to make the parser print which rules its trying?

    Read the article

  • Python OOP - object has no attribute

    - by user1744269
    I am attempting to learn how to program. I really do want to learn how to program; I love the building and design aspect of it. However, in Java and Python, I have tried and failed with programs as they pertain to objects, classes, methods.. I am trying to develop some code for a program, but im stumped. I know this is a simple error. However I am lost! I am hoping someone can guide me to a working program, but also help me learn (criticism is not only expected, but APPRECIATED). class Converter: def cTOf(self, numFrom): numFrom = self.numFrom numTo = (self.numFrom * (9/5)) + 32 print (str(numTo) + ' degrees Farenheit') return numTo def fTOc(self, numFrom): numFrom = self.numFrom numTo = ((numFrom - 32) * (5/9)) return numTo convert = Converter() numFrom = (float(input('Enter a number to convert.. '))) unitFrom = input('What unit would you like to convert from.. ') unitTo = input('What unit would you like to convert to.. ') if unitFrom == ('celcius'): convert.cTOf(numFrom) print(numTo) input('Please hit enter..') if unitFrom == ('farenheit'): convert.fTOc(numFrom) print(numTo) input('Please hit enter..')

    Read the article

  • Dynamic programming Approach- Knapsack Puzzle

    - by idalsin
    I'm trying to solve the Knapsack problem with the dynamical programming(DP) approach, with Python 3.x. My TA pointed us towards this code for a head start. I've tried to implement it, as below: def take_input(infile): f_open = open(infile, 'r') lines = [] for line in f_open: lines.append(line.strip()) f_open.close() return lines def create_list(jewel_lines): #turns the jewels into a list of lists jewels_list = [] for x in jewel_lines: weight = x.split()[0] value = x.split()[1] jewels_list.append((int(value), int(weight))) jewels_list = sorted(jewels_list, key = lambda x : (-x[0], x[1])) return jewels_list def dynamic_grab(items, max_weight): table = [[0 for weight in range(max_weight+1)] for j in range(len(items)+1)] for j in range(1,len(items)+1): val= items[j-1][0] wt= items[j-1][1] for weight in range(1, max_weight+1): if wt > weight: table[j][weight] = table[j-1][weight] else: table[j][weight] = max(table[j-1][weight],table[j-1][weight-wt] + val) result = [] weight = max_weight for j in range(len(items),0,-1): was_added = table[j][weight] != table[j-1][weight] if was_added: val = items[j-1][0] wt = items[j-1][1] result.append(items[j-1]) weight -= wt return result def totalvalue(comb): #total of a combo of items totwt = totval = 0 for val, wt in comb: totwt += wt totval += val return (totval, -totwt) if totwt <= max_weight else (0,0) #required setup of variables infile = "JT_test1.txt" given_input = take_input(infile) max_weight = int(given_input[0]) given_input.pop(0) jewels_list = create_list(given_input) #test lines print(jewels_list) print(greedy_grab(jewels_list, max_weight)) bagged = dynamic_grab(jewels_list, max_weight) print(totalvalue(bagged)) The sample case is below. It is in the format line[0] = bag_max, line[1:] is in form(weight, value): 575 125 3000 50 100 500 6000 25 30 I'm confused as to the logic of this code in that it returns me a tuple and I'm not sure what the output tuple represents. I've been looking at this for a while and just don't understand what the code is pointing me at. Any help would be appreciated.

    Read the article

  • How to limit a user to entering 10 keywords or less using PHP & MySQL?

    - by G4TV
    I'm trying to limit my users to entering at least 10 keywords and was wondering how would I be able to do this using PHP & MySQL with my current Keyword script? Here is the add keywords PHP MySQL code. if (isset($_POST['tag']) && trim($_POST['tag'])!=='') { $tags = explode(",", $_POST['tag']); for ($x = 0; $x < count($tags); $x++){ $mysqli = mysqli_connect("localhost", "root", "", "sitename"); $query1 = "INSERT INTO tags (tag) VALUES ('" . mysqli_real_escape_string($mysqli, strtolower(htmlentities(trim(strip_tags($tags[$x]))))) . "')"; if (!mysqli_query($mysqli, $query1)) { print mysqli_error($mysqli); return; } $mysqli = mysqli_connect("localhost", "root", "", "sitename"); $dbc = mysqli_query($mysqli,"SELECT id FROM tags WHERE tag='" . mysqli_real_escape_string($mysqli, strtolower(htmlentities(trim(strip_tags($tags[$x]))))) . "'"); if (!$dbc) { print mysqli_error($mysqli); } else { while($row = mysqli_fetch_array($dbc)){ $id = $row["id"]; } } $query2 = "INSERT INTO question_tags (tag_id, question_id, user_id, date_created) VALUES ('$id', '$question', '$user', NOW())"; if (!mysqli_query($mysqli, $query2)) { print mysqli_error($mysqli); return; } } }

    Read the article

< Previous Page | 114 115 116 117 118 119 120 121 122 123 124 125  | Next Page >