Questions tagged [python]

229141 questions
0

votes
2

answer
561

Views

How to split a file which is delimited by bullet points

I'm trying to split a large file that has several paragraphs, each one is of variable length and the only delimiter would be the bullet point for the next paragraph... Is there a way to get several different files with each individual paragraph? The final thing is to write each individual paragraph...
Did
0

votes
1

answer
49

Views

Writing a command line app

I am in Ubuntu 16.4. I have just written a program that can be executed using the command(assuming i'm in the correct directory) ./Main.py -h However I want this to be distributable, so that you can use it from the command line like nmap or youtube-dl. My idea was to put an alias is .bashrc. This h...
Peyto
0

votes
1

answer
64

Views

How to get the correct result when I use re.compile(pattern), if the pattern contains some special characters, like, (),? [duplicate]

This question already has an answer here: Escaping regex string in Python 4 answers I am trying to replace a string in a file using python re lib. But I failed on replacing some texts with some special characters, like, (), ?, etc. Can anyone help me look at this issue? I attached my code in here.:...
ping
-3

votes
2

answer
6.8k

Views

Avoiding: syntax error near unexpected token in bash

I have a shell that calls a python script like so... Shell code: #!/bin/sh python PyTest.py print('FE FI FO FUM I'M GOING TO MAKE IT TUMBLE TUM TUM') 5 + 4 print('No semicolons here!') Python code: #This is my test Python script running from bash print('FE FI FO FUM I'M GOING TO MAKE IT TUMBLE TUM T...
Perplexing Pies
9

votes
2

answer
2.6k

Views

Distributing Programs Written in Python [duplicate]

Possible Duplicate: Distributing Python programs I have several source codes for some GUI programs I made in Python. I'd like to distribute them. However, I'd like to make it as easy as possible for the end user to get the program up and running. What are the common way's of going about this proble...
rectangletangle
0

votes
1

answer
315

Views

Not able to send the mdm Payload and Command to device

I am developing mdm for iOS for testing purpose. I have installed the profile on the device and I have got the Device Token, PushMagic and now I want to send the mdm payload {'mdm':'PushMagicValue'} and for this I am using the code from APNSWrapper import * wrapper = APNSNotificationWrapper('Push...
Atul
0

votes
5

answer
47

Views

Convert dict to list of dict for each combinations

I have a dict looks like this : my_dict = { 'a':[1, 2, 3], 'b':[10], 'c':[4, 5], 'd':[11] } And I would like to obtain a list containig all combinations keeping keys and value like this: result = [ {'a':1, 'b':10, 'c':4, 'd':11}, {'a':1, 'b':10, 'c':5, 'd':11}, {'a':2, 'b':10, 'c':4, 'd':11}, {'a':2...
Furlings
-1

votes
2

answer
71

Views

Python TypeError: 'function' object is not subscriptable in nested function when i try to implement switch case

I am trying to code a random decision between 3 machines. Since Python does not have any switch/case function, I resorted to if and elif. Each machine (line1(),line2(),line3()) has its own function as well. However, I have been getting errors. Please advise me on what is going wrong. machine_choic...
PCiah
1

votes
1

answer
831

Views

Creating file and saving in Django model (AttributeError?)

I have a huge string that I want to save as a file in a Django model. In order to do that, I have written the following code: with open('new_file', 'w') as outfile: outfile.write(myString) outfile.close() my_obj = Model_Type(obj_name = name, my_file = outfile) my_obj.save() This raises an error, '_...
Xabi Linazasoro
-2

votes
2

answer
226

Views

Can anybody show me an alternative to [::-1] ? I am trying to print a list in reverse order [duplicate]

This question already has an answer here: How can I reverse a list in Python? 30 answers infile=open('Integers.txt', 'r') ListIntegers=infile.readline().strip('\n').split(';') def avgFirstThreeDigits(mylist): list=[] for i in range(0,len(mylist)): sumFirstThreeDigits=(int(mylist[i][0])+int(mylist[i...
Atakan Ak
1

votes
4

answer
263

Views

super simple python program - substituting whitespaces with newlines? [closed]

I am trying to write a program with python. I want to substitute whitespaces in a txt document with new lines. I have tried writing it myself but my output file gets filled with weird characters. Can you help? :)
Freddy
0

votes
1

answer
1.3k

Views

defining caffe prototxt in python [duplicate]

This question already has an answer here: caffe: model definition: write same layer with different phase using caffe.NetSpec() 5 answers How to add a layer for both the TRAIN and TEST phase with different parameters in one prototxt file using caffe in python? If you look at https://github.com/BVLC/...
Gaurav Gupta
0

votes
2

answer
53

Views

Python: Read the content of a variable [duplicate]

This question already has an answer here: Running Python code contained in a string 4 answers For example I have: x = True and True print x I want to be able to do something like: x = True and True print 'The answer to ', some_function(x), 'is', x Such that the program reads: The answer to True and...
J Bauer
10

votes
1

answer
2.3k

Views

ensuring the Cartesian product of keys appears in a Pandas table

I have a Pandas dataframe that has two key columns, and I want to ensure that the Cartesian product of those keys exist in the table (because I'll have to make a 2D plot containing all combinations). I'm having trouble coming up with a reasonably brief and idiomatic way to do this. For example, I st...
Dan Lenski
-2

votes
2

answer
45

Views

How can I make my multiple if statements work? Or preferably how do I use nested loops in my code

What I want to do, is transform my variable: table = 'female\tIngelin\tAleksandersen\nmale\tJohnny\tDigre\nmale\tOsman\tBremseth\nfemale\tCathrine\tDagestad\nfemale\tTirill\tBakker' Into a kind of scheme like this: Row: 0 Col: 0 Cell value: female Row: 0 Col: 1 Cell value: Ingelin Row: 0 Col: 2 Cel...
pythonstud
0

votes
1

answer
1.4k

Views

How do I create an empty pandas DataFrame with different data types assigned to each column?

This post provides an elegant way to create an empty pandas DataFrame of a specified data type. And if you specify np.nan values when you initialize it, the data type is set to float: df_training_outputs = pd.DataFrame(np.nan, index=index, columns=column_names) But I want to create an empty DataFra...
Bill
0

votes
2

answer
117

Views

python, importing a file with a dynamic name [duplicate]

This question already has an answer here: How to import a module given its name? 11 answers Folks, I would like to import python files, and functions dynamically. The modulenames should be passed to a function like so: def scrape(url, foo): modulename = url['modulename'] import modulename modulena...
Cmag
0

votes
1

answer
93

Views

Find every combination of a list of integers split into exactly two subsets [duplicate]

This question already has an answer here: How to get all possible combinations of a list’s elements? 23 answers Suppose I have a list of integers: myList = [1,2,3,4] How would one return every possible combination of these two subsets with Python. For example, set [1,2,3,4] would produce [1,2], [...
0

votes
3

answer
212

Views

Trouble with Changing Characters in a String Then Returning the String

The code was too long to past here, so it's on PasteBin: http://pastebin.com/UDPFYsLJ What I want to happen is to be able to put in something like '555-GET-FOOD' and get '555-438-3663'. I have the code changing the letters to numbers...just on completely different lines. Here's a small excerpt: Numb...
Chelsea
0

votes
1

answer
61

Views

sparse BLAS solver used in a shared library doesn't work (returns '-1')

I have tried to program a solver-function in C (with Ubuntu in Code::Blocks). I want to call that solver from a Python script, so I have build it as a shared library and called it with 'ctypes' in Python. At first have tried the example from there http://www.netlib.org/blas/blast-forum/chapter3.pdf...
PBassler
1

votes
1

answer
100

Views

Assigning Descriptor attribute outside class

I have a Descriptor for lazy loading from a data store that returns a default value if the data store is not available. The Descriptor works fine except for the case in which I want the default value to be an instance of a supplied class type which is the same class type in which the Descriptor is d...
jeshep
0

votes
1

answer
88

Views

OpenCV : Vehicle axle detection

I tried to detect vehicle axles in an image. Here are the steps that I followed. Read the image and changed to grayscale. Applied median. Applied canny edge detection. Applied Hough circles. For canny the threshold1, threshold2 parameters are varied using track bar and for Hough circles param1, pa...
Rangooski
2

votes
1

answer
63

Views

rewinding multiple lines when iterating with f.next()

Follow up from this question. How can I modify this code to allow for rewinding of multiple lines? class rewindable_iterator(object): not_started = object() def __init__(self, iterator): self._iter = iter(iterator) self._use_save = False self._save = self.not_started def __iter__(self): return sel...
Pierpaolo
-16

votes
1

answer
112

Views

if condition not working in python [closed]

import light import urllib2 true = 1 while(true): try: response = urllib2.urlopen('http://192.168.1.6/light.php') status = response.read() except urllib2.HTTPError, e: print e.code except urllib2.URLError, e: print e.args print status if status=='17': light.lighton(); elif status=='0': light.lightof...
Ishant Matlani
0

votes
2

answer
1.4k

Views

Draw matplotlib plot to PNG in Jupyter when inline matplotlib is enabled

I am drawing a confusion matrix heatmap in Jupyter using code similar to the example here using imshow Matplotlib is set to draw plots inline. This works fine for outputting to the cell in the notebook, but I want to not output to the cell but instead get PNG data (ideally raw, not saved to a file)...
Graham Wheeler
0

votes
1

answer
70

Views

Scope of an argument of a function

I am trying to get the following recursive function to work. It is supposed to find the biggest list of vectors in vspace(n) such that all the vectors are at least distance d from each other. My current issue is that the variable sol does not seem to be behaving locally. For some reason when the cod...
SeanBallentine
-1

votes
3

answer
120

Views

How to convert String into integers in python sickit-learn [duplicate]

This question already has an answer here: Convert all strings in a list to int 2 answers I have a list as above: probs= ['2','3','5','6'] and i want to convert those string to a numeric values like the following result: resultat=[2, 3, 4, 5, 6] I tried some solutions appearing on this link: How t...
Ha KiM's
0

votes
1

answer
27

Views

How can I exclude my count from my grade average?

I'm trying to figure out how to have a count when when I want to display my file, but not have the count get added into my grade average. def main(): choice = 'q' while choice != 'X': print_menu() choice = input('Enter an option (D, C, X): ') if choice == 'D': DisplayScores() elif choice == 'C': Cal...
Brady Alger
0

votes
2

answer
34

Views

Creating cdata of type `REAL (* vertices)[DIM]` in CFFI

I'm trying to build a python interface around some existing C code with CFFI. As usual with C code trimmed for performance, it is fraught with extensive macros and typedefs. ATM I am working on replicating following struct #define DIM 3 typedef double REAL; struct Object_structure { int numpoin...
PeterE
1

votes
1

answer
1.2k

Views

OpenCV: findContours(): how contours are ordered?

When we want to find the contours of a given image according to a certain threshold, we use the function cv2.findContours() which returns among other things, the list of contours (a Pythonic list of arrays representing contours of the picture). Here is how to use of the function: contours, hierarchy...
0

votes
3

answer
235

Views

Python slicing from last to first element?

so i have a tuple in python and i need to slice from the last element to first element but only want the last and first... example: big tuple: (1,2,3,4,5) i want to slice the tuple so i end up with (5,1) some_list[::len(some_list)-1] above code slices from first to last and only includes the first a...
3MIN3M
0

votes
2

answer
114

Views

Python script to genrate XML file from PSQL database table

I am trying to generate XML file from PostgreSQL database table. I was able to generate using below code but it is not formatted and displaying in single line. While getting row from rows it displays complete file in single row. How can i fix this problem? def tableToXML(message): conn = None try: c...
Navi
9

votes
2

answer
8.2k

Views

python opencv - blob detection or circle detection

I am having problems detecting circle areas. I tried it with the HoughCircles function from opencv. However even though the images are pretty similar the parameters for the funtion have to be different in order to detect the cirles. Another approach I tried was to iterate over every pixel and check...
cmplx96
0

votes
1

answer
19

Views

Disappearing Dimensions in Multi-Output Keras Model

When I try to train the autoencoder described below, I receive an error that ' A target array with shape (256, 28, 28, 1) was passed for an output of shape (None, 0, 28, 1) while using as loss `binary_crossentropy. This loss expects targets to have the same shape as the output.' The input and output...
Harrison Rose
0

votes
2

answer
43

Views

Python filtered and date sorted list

How would I have to create a date modified sorted list with Python of all files in /var/log starting with yum.log ls -la /var/log/yum.log* [17-01-04 11:36:41] -rw-------. 1 root root 0 Jan 1 03:...
willemdh
0

votes
1

answer
78

Views

Replacing one layer in a Dense autoencoder with Conv1D

I currently have a fully connected autoencoder in keras which looks like this: model.add(Dense(4096, input_shape=(4096,), activation='relu')) model.add(Dense(512, activation='relu')) model.add(Dense(64, activation='relu')) model.add(Dense(512, activation='relu')) model.add(Dense(4096, activation='re...
VegardKT
0

votes
1

answer
535

Views

Pydev/eclipse : After import from GIT, can not set as pydev project

I am running Eclipse Luna on a windows 64bits system, and installed pydev plugin, using python 2.7.8 as interpreter. I imported a project from GitHub. Once this done, did right-click on the project, then: pydev/Set as pydevproject then once more right-click on the project, then: pydev/Set as source...
Vince
0

votes
2

answer
66

Views

How to map function on all argument values, as a list? but have explicit argument names in the function definition

I want to define a function using explicit argument names ff(a,b,c) in the function definition, but I also want to map a function over all arguments to get a list: ff(a,b,c): return list(map(myfunc,[a,b,c])) However, I don't want to explicitly write parameter names inside function as a,b,c. I want t...
user15964
1

votes
1

answer
51

Views

Extracting a text following a symbol from a string without using regex: Python

def extractdollarsign(text) > extractdollarsign('the day is good $GoodDay') ['GoodDay'] > extractdollarsign('the day is good$GoodDay') [] > extractdollarsign('the day is good $GoodDay $Day') ['GoodDay', 'Day'] list = [] extractedtxt = text[text.find('$')+1:].split()[0] list.append(extractedtxt) ret...
Maxwell
16

votes
1

answer
14.3k

Views

“TypeError”: 'list' object is not callable flask

I am trying to show the list of connected devices in browser using flask. I enabled flask on port 8000: in server.py: @server.route('/devices',methods = ['GET']) def status(): return app.stat() if __name__ == '__main__': app.run() in app.py: def stat(): return(glob.glob('/dev/tty57') + glob.glo...
N45