Search Results

Search found 15187 results on 608 pages for 'boost python'.

Page 21/608 | < Previous Page | 17 18 19 20 21 22 23 24 25 26 27 28  | Next Page >

  • How to change a Linux user password from python

    - by Vaulor
    I'm having problems with changing a Linux user's password from python. I've tried so many things, but I couldn't manage to solve the issue, here is the sample of things I've already tried: sudo_password is the password for sudo, sudo_command is the command I want the system to run, user is get from a List and is the user who I want to change the password for, and newpass is the pass I want to assign to 'user' user = list.get(ANCHOR) sudo_command = 'passwd' f = open("passwordusu.tmp", "w") f.write("%s\n%s" % (newpass, newpass)) f.close() A=os.system('echo -e %s|sudo -S %s < %s %s' % (sudo_password, sudo_command,'passwordusu.tmp', user)) print A windowpass.destroy() 'A' is the return value for the execution of os.system, in this case 256. I tried also A=os.system('echo %s|sudo -S %s < %s %s' % (sudo_password, sudo_command,'passwordusu.tmp', user)) but it returns the same error code. I tried several other ways with 'passwd' command, but whithout succes. With 'chpasswd' command I 've tried this: user = list.get(ANCHOR) sudo_command = 'chpasswd' f = open("passwordusu.tmp", "w") f.write("%s:%s" % (user, newpass)) f.close() A=os.system('echo %s|sudo -S %s < %s %s' % (sudo_password, sudo_command,'passwordusu.tmp', user)) print A windowpass.destroy() also with: A=os.system('echo %s|sudo -S %s:%s|%s' % (sudo_password, user, newpass, sudo_command)) @;which returns 32512 A=os.system("echo %s | sudo -S %s < \"%s\"" % (sudo_password, sudo_command, "passwordusu.tmp")) @;which returns 256 I tried 'mkpasswd' and 'usermod' too like this: user = list.get(ANCHOR) sudo_command = 'mkpasswd -m sha-512' os.system("echo %s | sudo -S %s %s > passwd.tmp" % (sudo_password,sudo_command, newpass)) sudo_command="usermod -p" f = open('passwd.tmp', 'r') for line in f.readlines(): newpassencryp=line f.close() A=os.system("echo %s | sudo -S %s %s %s" % (sudo_password, sudo_command, newpassencryp, user)) @;which returns 32512 but, if you go to https://www.mkpasswd.net , hash the 'newpass' and substitute for 'newpassencryp', it returns 0 which theoretically means it has gone right, but so far it doesn't changes the password. I've searched on internet and stackoverflow for this issue or similar and tried what solutions exposed, but again,without success. I would really apreciate any help, and of course, if you need more info i'll be glad to supply it! Thanks in advance.

    Read the article

  • how to load files in python

    - by Alvaro
    I'm fairly new to python and would like some help on properly loading separate files. My codes purpose is to open a given file, search for customers of that file by the state or state abbreviation. However, i have a separate function to open a separate file where i have (name of state):(state abbreviation) Thanks. def file_state_search(fileid, state): z=0 indx = 0 while z<25: line=fileid.readline() data_list = ("Name:", "Address:", "City:", "State:", "Zipcode:") line_split = line.split(":") if state in line: while indx<5: print data_list[indx], line_split[indx] indx = indx + 1 elif state not in line: z = z + 1 def state_convert(fileid, state): line2=in_file2.readline() while state in line2: print line2 x=1 while x==1: print "Choose an option:" print print "Option '1': Search Record By State" print option = raw_input("Enter an option:") print if option == "1": state = raw_input("Enter A State:") in_file = open("AdrData.txt", 'r') line=in_file.readline() print in_file2 = open("States.txt", 'r') line2=in_file2.readline() converted_state = state_convert(in_file2, state) print converted_state state_find = file_state_search(in_file, state) print state_find x=raw_input("Enter '1' to continue, Enter '2' to stop: ") x=int(x) By the way, my first import statement works, for whatever reason my second one doesn't. Edit: My question is, what am i doing wrong in my state_convert function.

    Read the article

  • Moving to an arbitrary position in a file in Python

    - by B Rivera
    Let's say that I routinely have to work with files with an unknown, but large, number of lines. Each line contains a set of integers (space, comma, semicolon, or some non-numeric character is the delimiter) in the closed interval [0, R], where R can be arbitrarily large. The number of integers on each line can be variable. Often times I get the same number of integers on each line, but occasionally I have lines with unequal sets of numbers. Suppose I want to go to Nth line in the file and retrieve the Kth number on that line (and assume that the inputs N and K are valid --- that is, I am not worried about bad inputs). How do I go about doing this efficiently in Python 3.1.2 for Windows? I do not want to traverse the file line by line. I tried using mmap, but while poking around here on SO, I learned that that's probably not the best solution on a 32-bit build because of the 4GB limit. And in truth, I couldn't really figure out how to simply move N lines away from my current position. If I can at least just "jump" to the Nth line then I can use .split() and grab the Kth integer that way. The nuance here is that I don't just need to grab one line from the file. I will need to grab several lines: they are not necessarily all near each other, the order in which I get them matters, and the order is not always based on some deterministic function. Any ideas? I hope this is enough information. Thanks!

    Read the article

  • Replacing a word in a text file with a value using python

    - by Jamde Jam
    I have been trying to replace a word in a text file with a value (say 1), but my outfile is blank.I am new to python (its only been a month since I have been learning it). My file is relatively large, but I just want to replace a word with the value 1 for now. Here is a segment of what the file looks like: NAME SECOND_1 ATOM 1 6 0 0 0 # ORB 1 ATOM 2 2 0 12/24 0 # ORB 2 ATOM 3 2 12/24 0 0 # ORB 2 ATOM 4 2 0 0 4/24 # ORB 3 ATOM 5 2 0 0 20/24 # ORB 3 ATOM 6 2 0 0 8/24 # ORB 3 ATOM 7 2 0 0 16/24 # ORB 3 ATOM 8 6 0 0 12/24 # ORB 1 ATOM 9 2 12/24 0 12/24 # ORB 2 ATOM 10 2 0 12/24 12/24 # ORB 2 #1 #2 #3 I want to first replace the word ATOM with the value 1. Next I want to replace #ORB with a space. Here is what I am trying thus far. input = open('SECOND_orbitsJ22.txt','r') output=open('SECOND_orbitsJ22_out.txt','w') for line in input: word=line.split(',') if(word[0]=='ATOM'): word[0]='1' output.write(','.join(word)) Can anyone offer any suggestions or help? Thanks so much.

    Read the article

  • Supersede users need to press enter after inputting a string in python 3.0

    - by Cimex
    I've been attempting to create a simple Rock, Paper, Scissors game in python 3.0 -- very standard task for anybody learning programming. But, as I finish up to a point, I think,"wow, that'd be awesome", or,"it'd be cool to do this!" So anyways, I keep building upon the project... I've developed a menu, a single player game vs the computer, and just finished the multiplayer game. But, I've realized, that the multiplayer game isn't very effective. It just dosen't work like the analog version of the game. Currently, it'll ask for player1's input, then player2's input, compare them, and spit out the result and the current score. What I'd rather have happen is that the program asks for both players input at the same time and both players input their choice at the same time. I understand that I can easily do that by just grabbing the index of the first and second answer and compare the 2 inputs -- easy. But what I'd rather have happen is that after both players enter their one character answers at the same time (r for rock, p for paper, or s for scissors), then the program will auto enter the input. Not needing someone to press enter. The input would be dictated by the fact that 2 characters have been entered. I guess my question is: Is there any way to dictate what can be used as an input for 'enter'?

    Read the article

  • Learning Python else syntax error

    - by user1441016
    Hi I am learning python by doing the practice problems for Open course at MIT 6.00 Intro to Computer Science. I am Trying to do practice problem 1 part 2 create a recursive function to count the instance of key in target. My code so far... from string import * def countSubStringMatchRecursive (target, key,x,s): if (find(target,key)==find(target,key,s)) and (find(target,key)==find(target,key,(find(target,key)))):#if first and last return (1) elif (find(target,key)==find(target,key,s))and (find(target,key)!=find(target,key,(find(target,key)))):#if first but not last x=1 s= find(target,key) return (countSubStringMatchRecursive(target,key,s,x) elif (find(target,key,s))==-1 and (find(target,key)!=find(target,key,s)):#if last but not first return (x+1) elif:(find(target,key,s))!=-1 and (find(target,key)!=find(target,key,s)):#if not last and not first x=x+1 s= find(target,key,s) return (countSubStringMatchRecursive(target,key,s,x) I getting a syntax error at line 8. I would just like to know what I did wrong there. Dont worry about the other mistakes I should be able to get those sorted out. I just Stuck on this. Thanks.

    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

  • Intel turbo boost - in reality

    - by gisek
    I have an Intel i7-3630QM processor in my laptop. Its speed is supposed to be from 2.4 to 3.4 GHz in turbo boost mode. In reality, will it ever run all cores on full speed (3.4GHz mentioned above) at the same time? I heard somewhere that this additional 1GHz is shared between all cores in laptops. If the boost is 1GHz per core it's pretty impressive (over 40% speed up). What does it really look like? How long can a processor run in turbo mode?

    Read the article

  • How could there still not be a mysqldb module for Python 3? [closed]

    - by itsadok
    This SO question is now more than two years old. MySQL is an incredibly popular database engine, Python is an incredibly popular programming language, and Python 3 has been officially released two years ago, and was available even before that. What's more, the whole mysqldb module is just a layer translating Python's db-api to MySQL's API. It's not that big of a library. I must be missing something here. How come almost* nobody in the entire open source community has spent the (I'm guessing) two weeks it takes to port this lib? Is Python 3 that unpopular? Is the combination of python and mysql not as common as I assume? Or maybe it's just a lot harder to port mysqldb than I assume? Anyone know the inside story on this? * Now I see that this guy has done it, which takes some of the wind out of my question, but it still seems to little and too late to make sense. EDIT: OK, I'm aware that the stock answers for these kind of questions cover this one as well. Patches welcome, scratch your itch, we don't work for you and we don't have the time, etc. I actually took a shot at porting this about a year ago, but it was my first time doing anything with Python C extensions, and I failed. My point in writing this was not a plea for somebody to write it, but genuine curiosity: it seems that some much more complicated libraries have been ported to python 3 already, and in the poll for which libraries should be ported, mysqldb is not even nominated! That suggests that maybe (2) is the right answer. UPDATE: I found that there are several new libraries that provide mysql support under Python 3, I just wasn't googling hard enough. That explains everything.

    Read the article

  • Does python import all the listed libraries? - Python

    - by RadiantHex
    Hi folks, I'm just wondering, I often have really long python files and imports tend to stack quite quickly. PEP8 says that the imports should always be written at the beginning of the file. Do all the imported libraries get imported when calling a function coded in the file? Or do only the necessary libraries get called? Does it make sense to worry about this? Is there no reason to import libraries within the functions or classes that need them?

    Read the article

  • Replacing words in string

    - by abkai
    Okay, so I have the following little function: def swap(inp): inp = inp.split() out = "" for item in inp: ind = inp.index(item) item = item.replace("i am", "you are") item = item.replace("you are", "I am") item = item.replace("i'm", "you're") item = item.replace("you're", "I'm") item = item.replace("my", "your") item = item.replace("your", "my") item = item.replace("you", "I") item = item.replace("my", "your") item = item.replace("i", "you") inp[ind] = item for item in inp: ind = inp.index(item) item = item + " " inp[ind] = item return out.join(inp) Which, while it's not particularly efficient gets the job done for shorter sentences. Basically, all it does is swaps pronoun etc. perspectives. This is fine when I throw a string like "I love you" at it, it returns "you love me" but when I throw something like: you love your version of my couch because I love you, and you're a couch-lover. I get: I love your versyouon of your couch because I love I, and I'm a couch-lover. I'm confused as to why this is happening. I explicitly split the string into a list to avoid this. Why would it be able to detect it as being a part of a list item, rather than just an exact match? Also, slightly deviating to avoid having to post another question so similar; if a solution to this breaks this function, what will happen to commas, full stops, other punctuation? It made some very surprising mistakes. My expected output is: I love my version of your couch because you love I, and I'm a couch-lover. The reason I formatted it like this, is because I eventually hope to be able to replace the item.replace(x, y) variables with words in a database.

    Read the article

  • It says i have an indented block when i dont?

    - by user3728373
    def cave(): global key global response print(''' You find yourself standing infront of a cave. You venture into the cave to find a large door blocking your path. (insert key, turn around''') response = input("Enter a command: ") while response != 'insert key' or response != 'turn around': if response =='insert key' or response == 'turn around': break print('Choose one of the options: ") response = input() if response == 'insert key': if key == 1: win() else: print('''You don't have a key. Get One!!''') elif response == 'turn around' : home()

    Read the article

  • Python — Time complexity of built-in functions versus manually-built functions in finite fields

    - by stackuser
    Generally, I'm wondering about the advantages versus disadvantages of using the built-in arithmetic functions versus rolling your own in Python. Specifically, I'm taking in GF(2) finite field polynomials in string format, converting to base 2 values, performing arithmetic, then output back into polynomials as string format. So a small example of this is in multiplication: Rolling my own: def multiply(a,b): bitsa = reversed("{0:b}".format(a)) g = [(b<<i)*int(bit) for i,bit in enumerate(bitsa)] return reduce(lambda x,y: x+y,g) Versus the built-in: def multiply(a,b): # a,b are GF(2) polynomials in binary form .... return a*b #returns product of 2 polynomials in gf2 Currently, operations like multiplicative inverse (with for example 20 bit exponents) take a long time to run in my program as it's using all of Python's built-in mathematical operations like // floor division and % modulus, etc. as opposed to making my own division, remainder, etc. I'm wondering how much of a gain in efficiency and performance I can get by building these manually (as shown above). I realize the gains are dependent on how well the manual versions are built, that's not the question. I'd like to find out 'basically' how much advantage there is over the built-in's. So for instance, if multiplication (as in the example above) is well-suited for base 10 (decimal) arithmetic but has to jump through more hoops to change bases to binary and then even more hoops in operating (so it's lower efficiency), that's what I'm wondering. Like, I'm wondering if it's possible to bring the time down significantly by building them myself in ways that maybe some professionals here have already come across.

    Read the article

  • Newbie, deciding Python or Erlang

    - by Joe
    Hi Guys, I'm a Administrator (unix, Linux and some windows apps such as Exchange) by experience and have never worked on any programming language besides C# and scripting on Bash and lately on powershell. I'm starting out as a service provider and using multiple network/server monitoring tools based on open source (nagios, opennms etc) in order to monitor them. At this moment, being inspired by a design that I came up with, to do more than what is available with the open source at this time, I would like to start programming and test some of these ideas. The requirement is that a server software that captures a stream of data and store them in a database(CouchDB or MongoDB preferably) and the client side (agent installed on a server) would be sending this stream of data on a schedule of every 10 minutes or so. For these two core ideas, I have been reading about Python and Erlang besides ruby. I do plan to use either Amazon or Rackspace where the server platform would run. This gives me the scalability needed when we have more customers with many servers. For that reason alone, I thought Erlang was a better fit(I could be totally wrong, new to this game) and I understand that Erlang has limited support in some ways compared to Ruby or Python. But also I'm totally new to the programming realm of things and any advise would be appreciated grately. Jo

    Read the article

  • Where can I find out the following info on python (coming from Ruby)

    - by Michael Durrant
    I'm coming from Ruby and Ruby on Rails to Python. Where can I find or find resources about: The command prompt, what is python's version of 'irb' django, what is a good resource for installing, using, etc. pythoncasts... is there anything like railscats, i.e. good video tutorials web sites with the api info about what version have what and which to use. info and recommendations on editors, plugins and IDE's common gotchas for newbies and good things to know at the outset scaling issues, common reasons what is the equivalent of 'gems', i.e. components I can plug in what are popular plugins for django authentication and forms similar to devise and simple_form testing, what's available, anything similar to rspec? database adapters - any preferences? framework info - is django MVC like rails? OO'yness. Is everything an object that gets send messages? Different paradign? syntax - anything like jslint for checking for well-formed code?

    Read the article

  • python: os.system does not execute shell comand

    - by capoluca
    I need to execute shell command in python program (I have ubuntu). More specifically I want to create graph using graphviz in python script. My code is os.system("dot -Tpng graph.dot -o graph.png") It does not work, but if I just type dot -Tpng graph.dot -o graph.png in command line then everything is fine. Do you know what the problem? Thank you! Edit: Does not work means that nothing happens, there are no errors. Output from dot -v -Tpng graph.dot -o graph.png: dot - graphviz version 2.26.3 (20100126.1600) Activated plugin library: libgvplugin_pango.so.6 Using textlayout: textlayout:cairo Activated plugin library: libgvplugin_dot_layout.so.6 Using layout: dot:dot_layout Using render: cairo:cairo Using device: png:cairo:cairo The plugin configuration file: /usr/lib/graphviz/config6 was successfully loaded. render : cairo dot fig gd map ps svg tk vml vrml xdot layout : circo dot fdp neato nop nop1 nop2 osage patchwork sfdp twopi textlayout : textlayout device : canon cmap cmapx cmapx_np dot eps fig gd gd2 gif gv imap imap_np ismap jpe jpeg jpg pdf plain plain-ext png ps ps2 svg svgz tk vml vmlz vrml wbmp x11 xdot xlib loadimage : (lib) eps gd gd2 gif jpe jpeg jpg png ps svg

    Read the article

  • Ruby or Python?

    - by Bobby Tables
    Hi all, This question is extremely subjective and open-ended. It might even sound like something I should just research for myself and make my own decision. But I'd like to put it out there and get some thoughts from others. Long story short - I burned out with the rat race and am on a self-funded sabbatical this year. Much of it is to take a break from the corporate grind and travel around, but I also want to play around with new technologies and do some self-learning projects, to stay up to speed on programming, and well - I just love tinkering with programming, when there's no pressure! Here's the thing: I am a lifetime C/C++/Java programmer. I'm a bit of a squiggly bracket snob since I've been working with this family of languages for my entire programming career. So I'd like to learn a language which isn't so closely syntactically related to this group. What I'm basically looking for is a language which is relatively general purpose, fun to learn, has some new concepts that are different from C++/Java, and has a good community. A secondary consideration is that it has good web development frameworks. A tertiary consideration is that it's not totally academic (read: there are real world jobs out there using it). I've narrowed it down to Ruby or Python. My impression of Ruby is that it is extremely web oriented - that the only real application of it is as a server side scripting language for doing web stuff (mainly Ruby on Rails). For Python I'm not so sure. TL;DR and to put it as succinctly as possible: which of these would be better for a C++/Java guy to learn to get some new perspectives on programming? And which is more open and general purpose and applicable to a wider set of applications? I'm leaning towards Ruby at the moment, but I worry to an extent that it looks like it's used as nothing but a server side web language.

    Read the article

  • How to distribute python GTK applications?

    - by Nik
    This is in correlation with the previous question I asked here. My aim is to create and package an application for easy installation in Ubuntu and other debian distributions. I understand that the best way to do this is by creating .deb file with which users can easily install my application on their system. However, I would also like to make sure my application is available in multiple languages. This is why I raised the question before which you can read here. In the answers that were provided, I was asked to use disutils for my packaging. I am however missing the bigger picture here. Why is there a need to include a setup.py file when I distribute my application in .deb format? My purpose is to ensure that users do not need to perform python setup.py to install my application but rather just click on the .deb file. I already know how to create a deb file from the excellent tutorial available here. It clearly shows how to edit rules, changelog and everything required to create a clean deb file. You can look at my application source code and folder structure at Github if it helps you better understand my situation. Please note I have glanced through the official python documentation found here. But I am hoping that I would get an answer which would help even a lame man understand since my knowledge is pretty poor in this regard.

    Read the article

  • Strategies for managUse of types in Python

    - by dave
    I'm a long time programmer in C# but have been coding in Python for the past year. One of the big hurdles for me was the lack of type definitions for variables and parameters. Whereas I totally get the idea of duck typing, I do find it frustrating that I can't tell the type of a variable just by looking at it. This is an issue when you look at someone else's code where they've used ambiguous names for method parameters (see edit below). In a few cases, I've added asserts to ensure parameters comply with an expected type but this goes against the whole duck typing thing. On some methods, I'll document the expected type of parameters (eg: list of user objects), but even this seems to go against the idea of just using an object and let the runtime deal with exceptions. What strategies do you use to avoid typing problems in Python? Edit: Example of the parameter naming issues: If our code base we have a task object (ORM object) and a task_obj object (higher level object that embeds a task). Needless to say, many methods accept a parameter named 'task'. The method might expect a task or a task_obj or some other construct such as a dictionary of task properties - it is not clear. It is them up to be to look at how that parameter is used in order to work out what the method expects.

    Read the article

  • Strategies for managing use of types in Python

    - by dave
    I'm a long time programmer in C# but have been coding in Python for the past year. One of the big hurdles for me was the lack of type definitions for variables and parameters. Whereas I totally get the idea of duck typing, I do find it frustrating that I can't tell the type of a variable just by looking at it. This is an issue when you look at someone else's code where they've used ambiguous names for method parameters (see edit below). In a few cases, I've added asserts to ensure parameters comply with an expected type but this goes against the whole duck typing thing. On some methods, I'll document the expected type of parameters (eg: list of user objects), but even this seems to go against the idea of just using an object and let the runtime deal with exceptions. What strategies do you use to avoid typing problems in Python? Edit: Example of the parameter naming issues: If our code base we have a task object (ORM object) and a task_obj object (higher level object that embeds a task). Needless to say, many methods accept a parameter named 'task'. The method might expect a task or a task_obj or some other construct such as a dictionary of task properties - it is not clear. It is them up to be to look at how that parameter is used in order to work out what the method expects.

    Read the article

  • Re: Help with Boost Grammar

    - by Decmac04
    I have redesigned and extended the grammar I asked about earlier as shown below: // BIFAnalyser.cpp : Defines the entry point for the console application. // // /*============================================================================= Copyright (c) Temitope Jos Onunkun 2010 http://www.dcs.kcl.ac.uk/pg/onun/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ //////////////////////////////////////////////////////////////////////////// // // // B Machine parser using the Boost "Grammar" and "Semantic Actions". // // // //////////////////////////////////////////////////////////////////////////// include include include include include include //////////////////////////////////////////////////////////////////////////// using namespace std; using namespace boost::spirit; //////////////////////////////////////////////////////////////////////////// // // Semantic Actions // //////////////////////////////////////////////////////////////////////////// // // namespace { //semantic action function on individual lexeme void do_noint(char const* start, char const* end) { string str(start, end); if (str != "NAT1") cout << "PUSH(" << str << ')' << endl; } //semantic action function on addition of lexemes void do_add(char const*, char const*) { cout << "ADD" << endl; // for(vector::iterator vi = strVect.begin(); vi < strVect.end(); ++vi) // cout << *vi << " "; } //semantic action function on subtraction of lexemes void do_subt(char const*, char const*) { cout << "SUBTRACT" << endl; } //semantic action function on multiplication of lexemes void do_mult(char const*, char const*) { cout << "\nMULTIPLY" << endl; } //semantic action function on division of lexemes void do_div(char const*, char const*) { cout << "\nDIVIDE" << endl; } // // vector flowTable; //semantic action function on simple substitution void do_sSubst(char const* start, char const* end) { string str(start, end); //use boost tokenizer to break down tokens typedef boost::tokenizer Tokenizer; boost::char_separator sep(" -+/*:=()",0,boost::drop_empty_tokens); // char separator definition Tokenizer tok(str, sep); Tokenizer::iterator tok_iter = tok.begin(); pair dependency; //create a pair object for dependencies //create a vector object to store all tokens vector dx; // int counter = 0; // tracks token position for(tok.begin(); tok_iter != tok.end(); ++tok_iter) //save all tokens in vector { dx.push_back(*tok_iter ); } counter = dx.size(); // vector d_hat; //stores set of dependency pairs string dep; //pairs variables as string object // dependency.first = *tok.begin(); vector FV; for(int unsigned i=1; i < dx.size(); i++) { // if(!atoi(dx.at(i).c_str()) && (dx.at(i) !=" ")) { dependency.second = dx.at(i); dep = dependency.first + "|-" + dependency.second + " "; d_hat.push_back(dep); vector<string> row; row.push_back(dependency.first); //push x_hat into first column of each row for(unsigned int j=0; j<2; j++) { row.push_back(dependency.second);//push an element (column) into the row } flowTable.push_back(row); //Add the row to the main vector } } //displays internal representation of information flow table cout << "\n****************\nDependency Table\n****************\n"; cout << "X_Hat\tDx\tG_Hat\n"; cout << "-----------------------------\n"; for(unsigned int i=0; i < flowTable.size(); i++) { for(unsigned int j=0; j<2; j++) { cout << flowTable[i][j] << "\t "; } if (*tok.begin() != "WHILE" ) //if there are no global flows, cout << "\t{}"; //display empty set cout << "\n"; } cout << "***************\n\n"; for(int unsigned j=0; j < FV.size(); j++) { if(FV.at(j) != dependency.second) dep = dependency.first + "|-" + dependency.second + " "; d_hat.push_back(dep); } cout << "PUSH(" << str << ')' << endl; cout << "\n*******\nDependency pairs\n*******\n"; for(int unsigned i=0; i < d_hat.size(); i++) cout << d_hat.at(i) << "\n...\n"; cout << "\nSIMPLE SUBSTITUTION\n\n"; } //semantic action function on multiple substitution void do_mSubst(char const* start, char const* end) { string str(start, end); cout << "PUSH(" << str << ')' << endl; //cout << "\nMULTIPLE SUBSTITUTION\n\n"; } //semantic action function on unbounded choice substitution void do_mChoice(char const* start, char const* end) { string str(start, end); cout << "PUSH(" << str << ')' << endl; cout << "\nUNBOUNDED CHOICE SUBSTITUTION\n\n"; } void do_logicExpr(char const* start, char const* end) { string str(start, end); //use boost tokenizer to break down tokens typedef boost::tokenizer Tokenizer; boost::char_separator sep(" -+/*=:()<",0,boost::drop_empty_tokens); // char separator definition Tokenizer tok(str, sep); Tokenizer::iterator tok_iter = tok.begin(); //pair dependency; //create a pair object for dependencies //create a vector object to store all tokens vector dx; for(tok.begin(); tok_iter != tok.end(); ++tok_iter) //save all tokens in vector { dx.push_back(*tok_iter ); } for(unsigned int i=0; i cout << "PUSH(" << str << ')' << endl; cout << "\nPREDICATE\n\n"; } void do_predicate(char const* start, char const* end) { string str(start, end); cout << "PUSH(" << str << ')' << endl; cout << "\nMULTIPLE PREDICATE\n\n"; } void do_ifSelectPre(char const* start, char const* end) { string str(start, end); //if cout << "PUSH(" << str << ')' << endl; cout << "\nPROTECTED SUBSTITUTION\n\n"; } //semantic action function on machine substitution void do_machSubst(char const* start, char const* end) { string str(start, end); cout << "PUSH(" << str << ')' << endl; cout << "\nMACHINE SUBSTITUTION\n\n"; } } //////////////////////////////////////////////////////////////////////////// // // Machine Substitution Grammar // //////////////////////////////////////////////////////////////////////////// // Simple substitution grammar parser with integer values removed struct Substitution : public grammar { template struct definition { definition(Substitution const& ) { machine_subst = ( (simple_subst) | (multi_subst) | (if_select_pre_subst) | (unbounded_choice) )[&do_machSubst] ; unbounded_choice = str_p("ANY") ide_list str_p("WHERE") predicate str_p("THEN") machine_subst str_p("END") ; if_select_pre_subst = ( ( str_p("IF") predicate str_p("THEN") machine_subst *( str_p("ELSIF") predicate machine_subst ) !( str_p("ELSE") machine_subst) str_p("END") ) | ( str_p("SELECT") predicate str_p("THEN") machine_subst *( str_p("WHEN") predicate machine_subst ) !( str_p("ELSE") machine_subst) str_p("END")) | ( str_p("PRE") predicate str_p("THEN") machine_subst str_p("END") ) )[&do_ifSelectPre] ; multi_subst = ( (machine_subst) *( ( str_p("||") (machine_subst) ) | ( str_p("[]") (machine_subst) ) ) ) [&do_mSubst] ; simple_subst = (identifier str_p(":=") arith_expr) [&do_sSubst] ; expression = predicate | arith_expr ; predicate = ( (logic_expr) *( ( ch_p('&') (logic_expr) ) | ( str_p("OR") (logic_expr) ) ) )[&do_predicate] ; logic_expr = ( identifier (str_p("<") arith_expr) | (str_p("<") arith_expr) | (str_p("/:") arith_expr) | (str_p("<:") arith_expr) | (str_p("/<:") arith_expr) | (str_p("<<:") arith_expr) | (str_p("/<<:") arith_expr) | (str_p("<=") arith_expr) | (str_p("=") arith_expr) | (str_p("=") arith_expr) | (str_p("=") arith_expr) ) [&do_logicExpr] ; arith_expr = term *( ('+' term)[&do_add] | ('-' term)[&do_subt] ) ; term = factor ( ('' factor)[&do_mult] | ('/' factor)[&do_div] ) ; factor = lexeme_d[( identifier | +digit_p)[&do_noint]] | '(' expression ')' | ('+' factor) ; ide_list = identifier *( ch_p(',') identifier ) ; identifier = alpha_p +( alnum_p | ch_p('_') ) ; } rule machine_subst, unbounded_choice, if_select_pre_subst, multi_subst, simple_subst, expression, predicate, logic_expr, arith_expr, term, factor, ide_list, identifier; rule<ScannerT> const& start() const { return predicate; //return multi_subst; //return machine_subst; } }; }; //////////////////////////////////////////////////////////////////////////// // // Main program // //////////////////////////////////////////////////////////////////////////// int main() { cout << "*********************************\n\n"; cout << "\t\t...Machine Parser...\n\n"; cout << "*********************************\n\n"; // cout << "Type an expression...or [q or Q] to quit\n\n"; string str; int machineCount = 0; char strFilename[256]; //file name store as a string object do { cout << "Please enter a filename...or [q or Q] to quit:\n\n "; //prompt for file name to be input //char strFilename[256]; //file name store as a string object cin strFilename; if(*strFilename == 'q' || *strFilename == 'Q') //termination condition return 0; ifstream inFile(strFilename); // opens file object for reading //output file for truncated machine (operations only) if (inFile.fail()) cerr << "\nUnable to open file for reading.\n" << endl; inFile.unsetf(std::ios::skipws); Substitution elementary_subst; // Simple substitution parser object string next; while (inFile str) { getline(inFile, next); str += next; if (str.empty() || str[0] == 'q' || str[0] == 'Q') break; parse_info< info = parse(str.c_str(), elementary_subst !end_p, space_p); if (info.full) { cout << "\n-------------------------\n"; cout << "Parsing succeeded\n"; cout << "\n-------------------------\n"; } else { cout << "\n-------------------------\n"; cout << "Parsing failed\n"; cout << "stopped at: " << info.stop << "\"\n"; cout << "\n-------------------------\n"; } } } while ( (*strFilename != 'q' || *strFilename !='Q')); return 0; } However, I am experiencing the following unexpected behaviours on testing: The text files I used are: f1.txt, ... containing ...: debt:=(LoanRequest+outstandingLoan1)*20 . f2.txt, ... containing ...: debt:=(LoanRequest+outstandingLoan1)*20 || newDebt := loanammount-paidammount || price := purchasePrice + overhead + bb . f3.txt, ... containing ...: yy < (xx+7+ww) . f4.txt, ... containing ...: yy < (xx+7+ww) & yy : NAT . When I use multi_subst as start rule both files (f1 and f2) are parsed correctly; When I use machine_subst as start rule file f1 parse correctly, while file f2 fails, producing the error: “Parsing failed stopped at: || newDebt := loanammount-paidammount || price := purchasePrice + overhead + bb” When I use predicate as start symbol, file f3 parse correctly, but file f4 yields the error: “ “Parsing failed stopped at: & yy : NAT” Can anyone help with the grammar, please? It appears there are problems with the grammar that I have so far been unable to spot.

    Read the article

  • matplotlib and python multithread file processing

    - by Napseis
    I have a large number of files to process. I have written a script that get, sort and plot the datas I want. So far, so good. I have tested it and it gives the desired result. Then I wanted to do this using multithreading. I have looked into the doc and examples on the internet, and using one thread in my program works fine. But when I use more, at some point I get random matplotlib error, and I suspect some conflict there, even though I use a function with names for the plots, and iI can't see where the problem could be. Here is the whole script should you need more comment, i'll add them. Thank you. #!/usr/bin/python import matplotlib matplotlib.use('GTKAgg') import numpy as np from scipy.interpolate import griddata import matplotlib.pyplot as plt import matplotlib.colors as mcl from matplotlib import rc #for latex import time as tm import sys import threading import Queue #queue in 3.2 and Queue in 2.7 ! import pdb #the debugger rc('text', usetex=True)#for latex map=0 #initialize the map index. It will be use to index the array like this: array[map,[x,y]] time=np.zeros(1) #an array to store the time middle_h=np.zeros((0,3)) #x phi c #for the middle of the box current_file=open("single_void_cyl_periodic_phi_c_middle_h_out",'r') for line in current_file: if line.startswith('# === time'): map+=1 np.append(time,[float(line.strip('# === time '))]) elif line.startswith('#'): pass else: v=np.fromstring(line,dtype=float,sep=' ') middle_h=np.vstack( (middle_h,v[[1,3,4]]) ) current_file.close() middle_h=middle_h.reshape((map,-1,3)) #3d array: map, x, phi,c ##### def load_and_plot(): #will load a map file, and plot it along with the corresponding profile loaded before while not exit_flag: print("fecthing work ...") #try: if not tasks_queue.empty(): map_index=tasks_queue.get() print("----> working on map: %s" %map_index) x,y,zp=np.loadtxt("single_void_cyl_growth_periodic_post_map_"+str(map_index),unpack=True, usecols=[1, 2,3]) for i,el in enumerate(zp): if el<0.: zp[i]=0. xv=np.unique(x) yv=np.unique(y) X,Y= np.meshgrid(xv,yv) Z = griddata((x, y), zp, (X, Y),method='nearest') figure=plt.figure(num=map_index,figsize=(14, 8)) ax1=plt.subplot2grid((2,2),(0,0)) ax1.plot(middle_h[map_index,:,0],middle_h[map_index,:,1],'*b') ax1.grid(True) ax1.axis([-15, 15, 0, 1]) ax1.set_title('Profiles') ax1.set_ylabel(r'$\phi$') ax1.set_xlabel('x') ax2=plt.subplot2grid((2,2),(1,0)) ax2.plot(middle_h[map_index,:,0],middle_h[map_index,:,2],'*r') ax2.grid(True) ax2.axis([-15, 15, 0, 1]) ax2.set_ylabel('c') ax2.set_xlabel('x') ax3=plt.subplot2grid((2,2),(0,1),rowspan=2,aspect='equal') sub_contour=ax3.contourf(X,Y,Z,np.linspace(0,1,11),vmin=0.) figure.colorbar(sub_contour,ax=ax3) figure.savefig('single_void_cyl_'+str(map_index)+'.png') plt.close(map_index) tasks_queue.task_done() else: print("nothing left to do, other threads finishing,sleeping 2 seconds...") tm.sleep(2) # except: # print("failed this time: %s" %map_index+". Sleeping 2 seconds") # tm.sleep(2) ##### exit_flag=0 nb_threads=2 tasks_queue=Queue.Queue() threads_list=[] jobs=list(range(map)) #each job is composed of a map print("inserting jobs in the queue...") for job in jobs: tasks_queue.put(job) print("done") #launch the threads for i in range(nb_threads): working_bee=threading.Thread(target=load_and_plot) working_bee.daemon=True print("starting thread "+str(i)+' ...') threads_list.append(working_bee) working_bee.start() #wait for all tasks to be treated tasks_queue.join() #flip the flag, so the threads know it's time to stop exit_flag=1 for t in threads_list: print("waiting for threads %s to stop..."%t) t.join() print("all threads stopped")

    Read the article

  • Python and mechanize login script

    - by Perun
    Hi fellow programmers! I am trying to write a script to login into my universities "food balance" page using python and the mechanize module... This is the page I am trying to log into: http://www.wcu.edu/11407.asp The website has the following form to login: <FORM method=post action=https://itapp.wcu.edu/BanAuthRedirector/Default.aspx><INPUT value=https://cf.wcu.edu/busafrs/catcard/idsearch.cfm type=hidden name=wcuirs_uri> <P><B>WCU ID Number<BR></B><INPUT maxLength=12 size=12 type=password name=id> </P> <P><B>PIN<BR></B><INPUT maxLength=20 type=password name=PIN> </P> <P></P> <P><INPUT value="Request Access" type=submit name=submit> </P></FORM> From this we know that I need to fill in the following fields: 1. name=id 2. name=PIN With the action: action=https://itapp.wcu.edu/BanAuthRedirector/Default.aspx This is the script I have written thus far: #!/usr/bin/python2 -W ignore import mechanize, cookielib from time import sleep url = 'http://www.wcu.edu/11407.asp' myId = '11111111111' myPin = '22222222222' # Browser #br = mechanize.Browser() #br = mechanize.Browser(factory=mechanize.DefaultFactory(i_want_broken_xhtml_support=True)) br = mechanize.Browser(factory=mechanize.RobustFactory()) # Use this because of bad html tags in the html... # Cookie Jar cj = cookielib.LWPCookieJar() br.set_cookiejar(cj) # Browser options br.set_handle_equiv(True) br.set_handle_gzip(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) # Follows refresh 0 but not hangs on refresh > 0 br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) # User-Agent (fake agent to google-chrome linux x86_64) br.addheaders = [('User-agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11'), ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'), ('Accept-Encoding', 'gzip,deflate,sdch'), ('Accept-Language', 'en-US,en;q=0.8'), ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.3')] # The site we will navigate into br.open(url) # Go though all the forms (for debugging only) for f in br.forms(): print f # Select the first (index two) form br.select_form(nr=2) # User credentials br.form['id'] = myId br.form['PIN'] = myPin br.form.action = 'https://itapp.wcu.edu/BanAuthRedirector/Default.aspx' # Login br.submit() # Wait 10 seconds sleep(10) # Save to a file f = file('mycatpage.html', 'w') f.write(br.response().read()) f.close() Now the problem... For some odd reason the page I get back (in mycatpage.html) is the login page and not the expected page that displays my "cat cash balance" and "number of block meals" left... Does anyone have any idea why? Keep in mind that everything is correct with the header files and while the id and pass are not really 111111111 and 222222222, the correct values do work with the website (using a browser...) Thanks in advance EDIT Another script I tried: from urllib import urlopen, urlencode import urllib2 import httplib url = 'https://itapp.wcu.edu/BanAuthRedirector/Default.aspx' myId = 'xxxxxxxx' myPin = 'xxxxxxxx' data = { 'id':myId, 'PIN':myPin, 'submit':'Request Access', 'wcuirs_uri':'https://cf.wcu.edu/busafrs/catcard/idsearch.cfm' } opener = urllib2.build_opener() opener.addheaders = [('User-agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11'), ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'), ('Accept-Encoding', 'gzip,deflate,sdch'), ('Accept-Language', 'en-US,en;q=0.8'), ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.3')] request = urllib2.Request(url, urlencode(data)) open("mycatpage.html", 'w').write(opener.open(request)) This has the same behavior...

    Read the article

  • Python 2.7 list of lists manipulation functionality

    - by user3688163
    I am trying to perform several operations on the myList list of lists below and am having some trouble figuring it out. I am very new to Python. myList = [ ['Issue Id','1.Completeness for OTC','Break',3275,33,33725102303,296384802,20140107], ['Issue Id','2.Validity check1 for OTC','Break',3308,0,34021487105,0,20140107], ['Issue Id','3.Validity check2 for OTC','Break',3308,0,34021487105,0,20140107], ['Issue Id','4.Completeness for RST','Break',73376,1,8.24931E+11,44690130,20140107], ['Issue Id','5.Validity check1 for RST','Break',73377,0,8.24976E+11,0,20140107], ['Liquidity','1. OTC - Null','Break',7821 0,2.28291E+11,0,20140110], ['Liquidity','2. OTC - Unmapped','Break',7778,43,2.27712E+11,579021732.8,20140110], ['Liquidity','3. RST - Null','Break',335120,0,1.01425E+12,0,20140110], ['Liquidity','4. RST - Unmapped','Break',334608,512,1.01351E+12,735465433.1,20140110], ['Liquidity','5. RST - Valid','Break',335120,0,1.01425E+12,0,20140110], ['Issue Id','1.Completeness for OTC','Break',3292,33,32397924450,306203929,20140110], ['Issue Id','2.Validity check1 for OTC','Break',3325,0,32704128379,0,20140110], ['Issue Id','3.Validity check2 for OTC','Break',3325,0,32704128379,0,20140110], ['Issue Id','4.Completeness for RST','Break',73594,3,8.5352E+11,69614602,20140110], ['Issue Id','5.Validity check1 for RST','Break',73597,0,8.5359E+11,0,20140110], ['Unlinked Silver ID','DQ','Break',3201318,176,20000000,54974.33386,20140101], ['Missing GCI','DQ','Break',3201336,158,68000000,49351.9588,20140101], ['Missing Book','DQ Break',3192720,8774,3001000000,2740595.484,20140101], ['Matured Trades','DQ','Break',3201006,488,1371000000,152428.8348,20140101], ['Illiquid Trades','1.Completeness Check for range','Break',43122,47,88597695671,54399061.43,20140107], ['Illiquid Trades','2.Completeness Check for non','Break',39033,0,79133622401,0,20140107] ] I am trying to get the result below but do not know how to do so: newList = [ ['Issue Id','1.Completeness for OTC:2.Validity check1 for OTC:3.Validity check2 for OTC','Break',3275,33,33725102303,296384802,20140107], ['Issue Id','4.Completeness for RST:5.Validity check1 for RST','Break',73376,1,8.24931E+11,44690130,20140107], ['Liquidity','1. OTC - Null','Break:2. OTC - Unmapped','Break',7821 0,2.28291E+11,0,20140110], ['Liquidity','3. RST - Null:4. RST - Unmapped:5. RST - Valid','Break',335120,0,1.01425E+12,0,20140110], ['Issue Id','1.Completeness for OTC:2.Validity check1 for OTC:3.Validity check2 for OTC','Break',3292,33,32397924450,306203929,20140110], ['Issue Id','4.Completeness for RST:5. RST - Valid','Break',73594,3,8.5352E+11,69614602,20140110], ['Unlinked Silver ID','DQ','Break',3201318,176,20000000,54974.33386,20140101], ['Missing GCI','DQ','Break',3201336,158,68000000,49351.9588,20140101], ['Missing Book','DQ Break',3192720,8774,3001000000,2740595.484,20140101], ['Matured Trades','DQ','Break',3201006,488,1371000000,152428.8348,20140101], ['Illiquid Trades','1.Completeness Check for range','Break',43122,47,88597695671,54399061.43,20140107], ['Illiquid Trades','2.Completeness Check for non','Break',39033,0,79133622401,0,20140107] ] Rules to create newList. Create a new list in the newList list of lists if the values in the lists meet the following conditions: multiple lists that match on `myList[i][0]` and `myList[i][7]` but with have (1) sums of `myList[i][3]` and `myList[i][4]` and (2) sums of `myList[i][5]` and `myList[i][6]` that are different from each other are just listed as is in newList if multiple lists match on both `myList[i][0]` (this is the type) and `myList[i][7]` (this is the date) are the same then create a new list for each set of lists with mathcing `myList[i][0]` and `myList[i][7]` that have (1) sums of `myList[i][3]` and `myList[i][4]` and (2) sums of `myList[i][5]` and `myList[i][6]` that are different from the other lists with mathcing `myList[i][0]` and `myList[i][7]`. I also am trying to concatenate `myList[i][1]` separated by a ':' for all those lists with matching `myList[i][0]` and `myList[i][7]` and with sums of `myList[i][3]` + `myList[i][4]` and `myList[i][5]` + `myList[i][6]` that match. So essentially for this case only those lists in `myList` with sums of `myList[i][3]` + `myList[i][4]` and `myList[i][5]` + `myList[i][6]` are different from the other lists are then listed in newList. The above newList illustrates these results I am trying to achieve. If anyone has any ideas how to do this they would be greatly appreciated. Thank you!

    Read the article

< Previous Page | 17 18 19 20 21 22 23 24 25 26 27 28  | Next Page >