qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
33,617,221
I am trying to speed up some heavy simulations by using python's multiprocessing module on a machine with 24 cores that runs Suse Linux. From reading through the documentation, I understand that this only makes sense if the individual calculations take much longer than the overhead for creating the pool etc. What con...
2015/11/09
[ "https://Stackoverflow.com/questions/33617221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5543796/" ]
Cores are shared resource like anything else on computer. OS will usually balance load. Meaning it will spread threads on as many cores as possible.`*` Guiding metric will be core load. So if there are less thread counts then core count some cores will sit idle. (Thread architecture prevent splitting onto multiple co...
The answer to this question kind of makes the question redundant. It turns out that the machine has only 12 physical cores that accept two threads each. The output of `multiprocessing.cpu_count()` is 24. However `lscpu` yields that there are only two sockets with six cores each. This explains why above ten processe...
65,157,911
I"m struggling on how to count the letter, number, and special character in a string. I'm a beginner and exploring python. Thank you in advance guys! ``` string=input("Enter string: Abc123--- ") count1=0 count2=0 count3=0 count4=0 for i in string: if(i.isletter()): count1=count1+1 count2=c...
2020/12/05
[ "https://Stackoverflow.com/questions/65157911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8055559/" ]
* You should import your classes directly: ``` from Item import Item # Assuming the file name is Item.py from Inventory import Inventory # Assuming the file name is Inventory.py ``` and then you can do: ``` item1 = Item(0,"Hat", 14, 10.00) ``` * Then you use `Item` inside the `Inventory` class, but you...
This error statement TypeError: 'module' object is not callable is raised as you are being confused about the Class name and Module name. The problem is in the import line . You are importing a module, not a class. This happend because the module name and class name have the same name. If you have a class MyClass in a ...
2,693,820
How might one extract all images from a pdf document, at native resolution and format? (Meaning extract tiff as tiff, jpeg as jpeg, etc. and without resampling). Layout is unimportant, I don't care were the source image is located on the page. I'm using python 2.7 but can use 3.x if required.
2010/04/22
[ "https://Stackoverflow.com/questions/2693820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14420/" ]
Often in a PDF, the image is simply stored as-is. For example, a PDF with a jpg inserted will have a range of bytes somewhere in the middle that when extracted is a valid jpg file. You can use this to very simply extract byte ranges from the PDF. I wrote about this some time ago, with sample code: [Extracting JPGs from...
I added all of those together in PyPDFTK [here](https://github.com/ronanpaixao/PyPDFTK/blob/master/pdf_images.py). My own contribution is handling of `/Indexed` files as such: ``` for obj in xObject: if xObject[obj]['/Subtype'] == '/Image': size = (xObject[obj]['/Width'], xObject[obj]['/Height']) ...
2,693,820
How might one extract all images from a pdf document, at native resolution and format? (Meaning extract tiff as tiff, jpeg as jpeg, etc. and without resampling). Layout is unimportant, I don't care were the source image is located on the page. I'm using python 2.7 but can use 3.x if required.
2010/04/22
[ "https://Stackoverflow.com/questions/2693820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14420/" ]
Libpoppler comes with a tool called "pdfimages" that does exactly this. (On ubuntu systems it's in the poppler-utils package) <http://poppler.freedesktop.org/> <http://en.wikipedia.org/wiki/Pdfimages> Windows binaries: <http://blog.alivate.com.au/poppler-windows/>
Here is my version from 2019 that recursively gets all images from PDF and reads them with PIL. Compatible with Python 2/3. I also found that sometimes image in PDF may be compressed by zlib, so my code supports decompression. ``` #!/usr/bin/env python3 try: from StringIO import StringIO except ImportError: fr...
2,693,820
How might one extract all images from a pdf document, at native resolution and format? (Meaning extract tiff as tiff, jpeg as jpeg, etc. and without resampling). Layout is unimportant, I don't care were the source image is located on the page. I'm using python 2.7 but can use 3.x if required.
2010/04/22
[ "https://Stackoverflow.com/questions/2693820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14420/" ]
You can use the module PyMuPDF. This outputs all images as .png files, but worked out of the box and is fast. ``` import fitz doc = fitz.open("file.pdf") for i in range(len(doc)): for img in doc.getPageImageList(i): xref = img[0] pix = fitz.Pixmap(doc, xref) if pix.n < 5: # this is GR...
I did this for my own program, and found that the best library to use was PyMuPDF. It lets you find out the "xref" numbers of each image on each page, and use them to extract the raw image data from the PDF. ``` import fitz from PIL import Image import io filePath = "path/to/file.pdf" #opens doc using PyMuPDF doc = f...
2,693,820
How might one extract all images from a pdf document, at native resolution and format? (Meaning extract tiff as tiff, jpeg as jpeg, etc. and without resampling). Layout is unimportant, I don't care were the source image is located on the page. I'm using python 2.7 but can use 3.x if required.
2010/04/22
[ "https://Stackoverflow.com/questions/2693820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14420/" ]
Libpoppler comes with a tool called "pdfimages" that does exactly this. (On ubuntu systems it's in the poppler-utils package) <http://poppler.freedesktop.org/> <http://en.wikipedia.org/wiki/Pdfimages> Windows binaries: <http://blog.alivate.com.au/poppler-windows/>
I installed [ImageMagick](http://www.imagemagick.org) on my server and then run commandline-calls through `Popen`: ``` #!/usr/bin/python import sys import os import subprocess import settings IMAGE_PATH = os.path.join(settings.MEDIA_ROOT , 'pdf_input' ) def extract_images(pdf): output = 'temp.png' ...
2,693,820
How might one extract all images from a pdf document, at native resolution and format? (Meaning extract tiff as tiff, jpeg as jpeg, etc. and without resampling). Layout is unimportant, I don't care were the source image is located on the page. I'm using python 2.7 but can use 3.x if required.
2010/04/22
[ "https://Stackoverflow.com/questions/2693820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14420/" ]
I prefer minecart as it is extremely easy to use. The below snippet show how to extract images from a pdf: ``` #pip install minecart import minecart pdffile = open('Invoices.pdf', 'rb') doc = minecart.Document(pdffile) page = doc.get_page(0) # getting a single page #iterating through all pages for page in doc.iter_...
After some searching I found the following script which works really well with my PDF's. It does only tackle JPG, but it worked perfectly with my unprotected files. Also is does not require any outside libraries. Not to take any credit, the script originates from Ned Batchelder, and not me. Python3 code: extract jpg's...
2,693,820
How might one extract all images from a pdf document, at native resolution and format? (Meaning extract tiff as tiff, jpeg as jpeg, etc. and without resampling). Layout is unimportant, I don't care were the source image is located on the page. I'm using python 2.7 but can use 3.x if required.
2010/04/22
[ "https://Stackoverflow.com/questions/2693820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14420/" ]
Much easier solution: Use the poppler-utils package. To install it use homebrew (homebrew is MacOS specific, but you can find the poppler-utils package for Widows or Linux here: <https://poppler.freedesktop.org/>). First line of code below installs poppler-utils using homebrew. After installation the second line (run ...
After some searching I found the following script which works really well with my PDF's. It does only tackle JPG, but it worked perfectly with my unprotected files. Also is does not require any outside libraries. Not to take any credit, the script originates from Ned Batchelder, and not me. Python3 code: extract jpg's...
2,693,820
How might one extract all images from a pdf document, at native resolution and format? (Meaning extract tiff as tiff, jpeg as jpeg, etc. and without resampling). Layout is unimportant, I don't care were the source image is located on the page. I'm using python 2.7 but can use 3.x if required.
2010/04/22
[ "https://Stackoverflow.com/questions/2693820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14420/" ]
Here is my version from 2019 that recursively gets all images from PDF and reads them with PIL. Compatible with Python 2/3. I also found that sometimes image in PDF may be compressed by zlib, so my code supports decompression. ``` #!/usr/bin/env python3 try: from StringIO import StringIO except ImportError: fr...
You could use `pdfimages` command in Ubuntu as well. Install poppler lib using the below commands. ``` sudo apt install poppler-utils sudo apt-get install python-poppler pdfimages file.pdf image ``` List of files created are, (for eg.,. there are two images in pdf) ``` image-000.png image-001.png ``` It works ...
2,693,820
How might one extract all images from a pdf document, at native resolution and format? (Meaning extract tiff as tiff, jpeg as jpeg, etc. and without resampling). Layout is unimportant, I don't care were the source image is located on the page. I'm using python 2.7 but can use 3.x if required.
2010/04/22
[ "https://Stackoverflow.com/questions/2693820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14420/" ]
I prefer minecart as it is extremely easy to use. The below snippet show how to extract images from a pdf: ``` #pip install minecart import minecart pdffile = open('Invoices.pdf', 'rb') doc = minecart.Document(pdffile) page = doc.get_page(0) # getting a single page #iterating through all pages for page in doc.iter_...
As of February 2019, the solution given by @sylvain (at least on my setup) does not work without a small modification: `xObject[obj]['/Filter']` is not a value, but a list, thus in order to make the script work, I had to modify the format checking as follows: ``` import PyPDF2, traceback from PIL import Image input1...
2,693,820
How might one extract all images from a pdf document, at native resolution and format? (Meaning extract tiff as tiff, jpeg as jpeg, etc. and without resampling). Layout is unimportant, I don't care were the source image is located on the page. I'm using python 2.7 but can use 3.x if required.
2010/04/22
[ "https://Stackoverflow.com/questions/2693820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14420/" ]
Here is my version from 2019 that recursively gets all images from PDF and reads them with PIL. Compatible with Python 2/3. I also found that sometimes image in PDF may be compressed by zlib, so my code supports decompression. ``` #!/usr/bin/env python3 try: from StringIO import StringIO except ImportError: fr...
I rewrite solutions as single python class. It should be easy to work with. If you notice new "/Filter" or "/ColorSpace" then just add it to internal dictionaries. <https://github.com/survtur/extract_images_from_pdf> Requirements: * Python3.6+ * PyPDF2 * PIL
2,693,820
How might one extract all images from a pdf document, at native resolution and format? (Meaning extract tiff as tiff, jpeg as jpeg, etc. and without resampling). Layout is unimportant, I don't care were the source image is located on the page. I'm using python 2.7 but can use 3.x if required.
2010/04/22
[ "https://Stackoverflow.com/questions/2693820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14420/" ]
After reading the posts using **pyPDF2**. The error while using @sylvain's code `NotImplementedError: unsupported filter /DCTDecode` must come from the method `.getData()`: It is solved when using `._data` instead, by @Alex Paramonov. So far I have only met "DCTDecode" cases, but I am sharing the adapted code that i...
**Try below code. it will extract all image from pdf.** ``` import sys import PyPDF2 from PIL import Image pdf=sys.argv[1] print(pdf) input1 = PyPDF2.PdfFileReader(open(pdf, "rb")) for x in range(0,input1.numPages): xObject=input1.getPage(x) xObject = xObject['/Resources'][...
94,334
What is the best python framework to create distributed applications? For example to build a P2P app.
2008/09/18
[ "https://Stackoverflow.com/questions/94334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You could checkout [pyprocessing](http://pyprocessing.berlios.de/) which will be included in the standard library as of 2.6. It allows you to run tasks on multiple processes using an API similar to threading.
You could download the source of BitTorrent for starters and see how they did it. <http://download.bittorrent.com/dl/>
94,334
What is the best python framework to create distributed applications? For example to build a P2P app.
2008/09/18
[ "https://Stackoverflow.com/questions/94334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I think you mean "Networked Apps"? Distributed means an app that can split its workload among multiple worker clients over the network. You probably want. [Twisted](http://twistedmatrix.com/trac/)
You could download the source of BitTorrent for starters and see how they did it. <http://download.bittorrent.com/dl/>
94,334
What is the best python framework to create distributed applications? For example to build a P2P app.
2008/09/18
[ "https://Stackoverflow.com/questions/94334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You probably want [Twisted](http://twistedmatrix.com/trac/). There is a P2P framework for Twisted called "[Vertex](http://divmod.org/trac/wiki/DivmodVertex)". While not actively maintained, it does allow you to tunnel through NATs and make connections directly between users in a very abstract way; if there were more in...
You could download the source of BitTorrent for starters and see how they did it. <http://download.bittorrent.com/dl/>
94,334
What is the best python framework to create distributed applications? For example to build a P2P app.
2008/09/18
[ "https://Stackoverflow.com/questions/94334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You could checkout [pyprocessing](http://pyprocessing.berlios.de/) which will be included in the standard library as of 2.6. It allows you to run tasks on multiple processes using an API similar to threading.
If it's something where you're going to need tons of threads and need better concurrent performance, check out [Stackless Python](http://www.stackless.com/). Otherwise you could just use the [SOAP](http://en.wikipedia.org/wiki/SOAP) or [XML-RPC](http://www.xmlrpc.com/) protocols. In response to Ben's post, if you don't...
94,334
What is the best python framework to create distributed applications? For example to build a P2P app.
2008/09/18
[ "https://Stackoverflow.com/questions/94334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I think you mean "Networked Apps"? Distributed means an app that can split its workload among multiple worker clients over the network. You probably want. [Twisted](http://twistedmatrix.com/trac/)
If it's something where you're going to need tons of threads and need better concurrent performance, check out [Stackless Python](http://www.stackless.com/). Otherwise you could just use the [SOAP](http://en.wikipedia.org/wiki/SOAP) or [XML-RPC](http://www.xmlrpc.com/) protocols. In response to Ben's post, if you don't...
94,334
What is the best python framework to create distributed applications? For example to build a P2P app.
2008/09/18
[ "https://Stackoverflow.com/questions/94334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You probably want [Twisted](http://twistedmatrix.com/trac/). There is a P2P framework for Twisted called "[Vertex](http://divmod.org/trac/wiki/DivmodVertex)". While not actively maintained, it does allow you to tunnel through NATs and make connections directly between users in a very abstract way; if there were more in...
If it's something where you're going to need tons of threads and need better concurrent performance, check out [Stackless Python](http://www.stackless.com/). Otherwise you could just use the [SOAP](http://en.wikipedia.org/wiki/SOAP) or [XML-RPC](http://www.xmlrpc.com/) protocols. In response to Ben's post, if you don't...
94,334
What is the best python framework to create distributed applications? For example to build a P2P app.
2008/09/18
[ "https://Stackoverflow.com/questions/94334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You could checkout [pyprocessing](http://pyprocessing.berlios.de/) which will be included in the standard library as of 2.6. It allows you to run tasks on multiple processes using an API similar to threading.
You probably want [Twisted](http://twistedmatrix.com/trac/). There is a P2P framework for Twisted called "[Vertex](http://divmod.org/trac/wiki/DivmodVertex)". While not actively maintained, it does allow you to tunnel through NATs and make connections directly between users in a very abstract way; if there were more in...
94,334
What is the best python framework to create distributed applications? For example to build a P2P app.
2008/09/18
[ "https://Stackoverflow.com/questions/94334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I think you mean "Networked Apps"? Distributed means an app that can split its workload among multiple worker clients over the network. You probably want. [Twisted](http://twistedmatrix.com/trac/)
You probably want [Twisted](http://twistedmatrix.com/trac/). There is a P2P framework for Twisted called "[Vertex](http://divmod.org/trac/wiki/DivmodVertex)". While not actively maintained, it does allow you to tunnel through NATs and make connections directly between users in a very abstract way; if there were more in...
51,817,237
I am working on a Flask project and I am using marshmallow to validate user input. Below is a code snippet: ``` def create_user(): in_data = request.get_json() data, errors = Userschema.load(in_data) if errors: return (errors), 400 fname = data.get('fname') lname = data.get('lname') ema...
2018/08/13
[ "https://Stackoverflow.com/questions/51817237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10217900/" ]
I recommend you check your dependency versions. Per the [Marshmallow API reference](http://marshmallow.readthedocs.io/en/latest/api_reference.html#schema), schema.load returns: > > Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if ...
according to the documentation in its most recent version (3.17.1) the way of handling with validation errors is as follows: ``` from marshmallow import ValidationError try: result = UserSchema().load({"name": "John", "email": "foo"}) except ValidationError as err: print(err.messages) # => {"email": ['"foo" ...
48,072,131
I am not sure what would be an appropriate heading for this question and this can be a repeated question as well. So please guide accordingly. I am new to python programming. I have this simple code to generate Fibonacci series. ``` 1: def fibo(n): 2: a = 0 3: b = 1 4: for x in range(n): 5: print (a, ...
2018/01/03
[ "https://Stackoverflow.com/questions/48072131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1755089/" ]
``` a = b b = a + b ``` is actually: ``` a = b b = b + b ``` what you want is: ``` a = b b = old_value_of_a + b ``` When you do `a, b = b, a + b` it really is doing: ``` tmp_a = b tmp_b = a + b a = tmp_a b = tmp_b ``` which is what you want
In line 7, you've already assigned the value in `b` to `a`, so in line 8, new value for `b` is actually double the old b's value. While in line 6, the values on the right side of `=` will be using the old values, that's why you could get Fibo series.
48,072,131
I am not sure what would be an appropriate heading for this question and this can be a repeated question as well. So please guide accordingly. I am new to python programming. I have this simple code to generate Fibonacci series. ``` 1: def fibo(n): 2: a = 0 3: b = 1 4: for x in range(n): 5: print (a, ...
2018/01/03
[ "https://Stackoverflow.com/questions/48072131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1755089/" ]
In line 7, you've already assigned the value in `b` to `a`, so in line 8, new value for `b` is actually double the old b's value. While in line 6, the values on the right side of `=` will be using the old values, that's why you could get Fibo series.
Thought make it simple so anyone can understand it if you use this kind of syntax ``` a = 10 b = 20 a = b b = a+b print (a) print (b) ``` after initially assigning a = 10 it will be assigning a = 20 since python is dynamically typed language it will change the value of variable a from 10 to 20 so the result will...
48,072,131
I am not sure what would be an appropriate heading for this question and this can be a repeated question as well. So please guide accordingly. I am new to python programming. I have this simple code to generate Fibonacci series. ``` 1: def fibo(n): 2: a = 0 3: b = 1 4: for x in range(n): 5: print (a, ...
2018/01/03
[ "https://Stackoverflow.com/questions/48072131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1755089/" ]
In line 7, you've already assigned the value in `b` to `a`, so in line 8, new value for `b` is actually double the old b's value. While in line 6, the values on the right side of `=` will be using the old values, that's why you could get Fibo series.
I think the `#` line is pythonic solution. But if you got confused,you can you use a variable which is temporary. you can assign the value `temp` before, then you can change the values
48,072,131
I am not sure what would be an appropriate heading for this question and this can be a repeated question as well. So please guide accordingly. I am new to python programming. I have this simple code to generate Fibonacci series. ``` 1: def fibo(n): 2: a = 0 3: b = 1 4: for x in range(n): 5: print (a, ...
2018/01/03
[ "https://Stackoverflow.com/questions/48072131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1755089/" ]
``` a = b b = a + b ``` is actually: ``` a = b b = b + b ``` what you want is: ``` a = b b = old_value_of_a + b ``` When you do `a, b = b, a + b` it really is doing: ``` tmp_a = b tmp_b = a + b a = tmp_a b = tmp_b ``` which is what you want
[Assignment Statements](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements) assigns reference of source variable to target variable. Let walk through an example to understand more ``` >>> a = 5 >>> b = 6 >>> a = b ``` In this example `b` is source variable and `a` is the target variable. Now...
48,072,131
I am not sure what would be an appropriate heading for this question and this can be a repeated question as well. So please guide accordingly. I am new to python programming. I have this simple code to generate Fibonacci series. ``` 1: def fibo(n): 2: a = 0 3: b = 1 4: for x in range(n): 5: print (a, ...
2018/01/03
[ "https://Stackoverflow.com/questions/48072131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1755089/" ]
``` a = b b = a + b ``` is actually: ``` a = b b = b + b ``` what you want is: ``` a = b b = old_value_of_a + b ``` When you do `a, b = b, a + b` it really is doing: ``` tmp_a = b tmp_b = a + b a = tmp_a b = tmp_b ``` which is what you want
Thought make it simple so anyone can understand it if you use this kind of syntax ``` a = 10 b = 20 a = b b = a+b print (a) print (b) ``` after initially assigning a = 10 it will be assigning a = 20 since python is dynamically typed language it will change the value of variable a from 10 to 20 so the result will...
48,072,131
I am not sure what would be an appropriate heading for this question and this can be a repeated question as well. So please guide accordingly. I am new to python programming. I have this simple code to generate Fibonacci series. ``` 1: def fibo(n): 2: a = 0 3: b = 1 4: for x in range(n): 5: print (a, ...
2018/01/03
[ "https://Stackoverflow.com/questions/48072131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1755089/" ]
``` a = b b = a + b ``` is actually: ``` a = b b = b + b ``` what you want is: ``` a = b b = old_value_of_a + b ``` When you do `a, b = b, a + b` it really is doing: ``` tmp_a = b tmp_b = a + b a = tmp_a b = tmp_b ``` which is what you want
I think the `#` line is pythonic solution. But if you got confused,you can you use a variable which is temporary. you can assign the value `temp` before, then you can change the values
48,072,131
I am not sure what would be an appropriate heading for this question and this can be a repeated question as well. So please guide accordingly. I am new to python programming. I have this simple code to generate Fibonacci series. ``` 1: def fibo(n): 2: a = 0 3: b = 1 4: for x in range(n): 5: print (a, ...
2018/01/03
[ "https://Stackoverflow.com/questions/48072131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1755089/" ]
[Assignment Statements](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements) assigns reference of source variable to target variable. Let walk through an example to understand more ``` >>> a = 5 >>> b = 6 >>> a = b ``` In this example `b` is source variable and `a` is the target variable. Now...
Thought make it simple so anyone can understand it if you use this kind of syntax ``` a = 10 b = 20 a = b b = a+b print (a) print (b) ``` after initially assigning a = 10 it will be assigning a = 20 since python is dynamically typed language it will change the value of variable a from 10 to 20 so the result will...
48,072,131
I am not sure what would be an appropriate heading for this question and this can be a repeated question as well. So please guide accordingly. I am new to python programming. I have this simple code to generate Fibonacci series. ``` 1: def fibo(n): 2: a = 0 3: b = 1 4: for x in range(n): 5: print (a, ...
2018/01/03
[ "https://Stackoverflow.com/questions/48072131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1755089/" ]
[Assignment Statements](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements) assigns reference of source variable to target variable. Let walk through an example to understand more ``` >>> a = 5 >>> b = 6 >>> a = b ``` In this example `b` is source variable and `a` is the target variable. Now...
I think the `#` line is pythonic solution. But if you got confused,you can you use a variable which is temporary. you can assign the value `temp` before, then you can change the values
43,566,044
Python does a lot with magic methods and most of these are part of some protocol. I am familiar with the "iterator protocol" and the "number protocol" but recently stumbled over the term ["sequence protocol"](https://docs.python.org/c-api/sequence.html#sequence-protocol). But even after some research I'm not exactly su...
2017/04/23
[ "https://Stackoverflow.com/questions/43566044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5393381/" ]
It's not really consistent. Here's [`PySequence_Check`](https://github.com/python/cpython/blob/3.6/Objects/abstract.c#L1460): ``` int PySequence_Check(PyObject *s) { if (PyDict_Check(s)) return 0; return s != NULL && s->ob_type->tp_as_sequence && s->ob_type->tp_as_sequence->sq_item != NULL; } ...
For a type to be in accordance with the sequence protocol, these 4 conditions must be met: * Retrieve elements by index `item = seq[index]` * Find items by value `index = seq.index(item)` * Count items `num = seq.count(item)` * Produce a reversed sequence `r = reversed(seq)`
26,199,376
I am trying to use level db in my python project. I zeroed in on python binding PlyVel <http://plyvel.readthedocs.org/en/latest/installation.html>, which seems to be better maintained and documented python binding. However installation fails for plyvel > > plyvel/\_plyvel.cpp:359:10: fatal error: 'leveldb/db.h' fil...
2014/10/05
[ "https://Stackoverflow.com/questions/26199376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089768/" ]
In OS X, it seems like `/usr/local/include`, where the leveldb headers (db.h) live, is not visible to gcc. You need to install the Apple command line tools: ``` xcode-select --install ``` plyvel will compile after that. [Link to GH issue](https://github.com/wbolster/plyvel/issues/34). Seems to be an OS X problem.
I'm not familiar with leveldb but most direct binary installations require you to run `./configure` then `make` then `make install` before the binary is actually installed. You should try that. Also, according to this github page you should be able to install it with `gem`: <https://github.com/DAddYE/leveldb>
26,199,376
I am trying to use level db in my python project. I zeroed in on python binding PlyVel <http://plyvel.readthedocs.org/en/latest/installation.html>, which seems to be better maintained and documented python binding. However installation fails for plyvel > > plyvel/\_plyvel.cpp:359:10: fatal error: 'leveldb/db.h' fil...
2014/10/05
[ "https://Stackoverflow.com/questions/26199376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089768/" ]
The easiest way to install leveldb on Mac OS X would be to use [homebrew](http://brew.sh/). [With homebrew](https://brewinstall.org/Install-leveldb-on-Mac-with-Brew/) you only need to run: ``` brew install leveldb ```
I'm not familiar with leveldb but most direct binary installations require you to run `./configure` then `make` then `make install` before the binary is actually installed. You should try that. Also, according to this github page you should be able to install it with `gem`: <https://github.com/DAddYE/leveldb>
26,199,376
I am trying to use level db in my python project. I zeroed in on python binding PlyVel <http://plyvel.readthedocs.org/en/latest/installation.html>, which seems to be better maintained and documented python binding. However installation fails for plyvel > > plyvel/\_plyvel.cpp:359:10: fatal error: 'leveldb/db.h' fil...
2014/10/05
[ "https://Stackoverflow.com/questions/26199376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089768/" ]
As mentioned by jAlpedrinha The easiest way to install leveldb on Mac OS X would be to use homebrew. With homebrew you only need to run: ``` brew install leveldb ``` You also need to have gcc or clang installed. If there is a problem installing python bindings as mentioned here, <https://github.com/wbolster/plyvel...
I'm not familiar with leveldb but most direct binary installations require you to run `./configure` then `make` then `make install` before the binary is actually installed. You should try that. Also, according to this github page you should be able to install it with `gem`: <https://github.com/DAddYE/leveldb>
26,199,376
I am trying to use level db in my python project. I zeroed in on python binding PlyVel <http://plyvel.readthedocs.org/en/latest/installation.html>, which seems to be better maintained and documented python binding. However installation fails for plyvel > > plyvel/\_plyvel.cpp:359:10: fatal error: 'leveldb/db.h' fil...
2014/10/05
[ "https://Stackoverflow.com/questions/26199376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089768/" ]
If you are a MacPorts user, you can `sudo port install leveldb` to install the shared libraries. Depending on how you've installed pip/python, you may also need to tell pip where to find the necessary files. Per <https://stackoverflow.com/a/22942120/5568265> you will want to do something like this: ``` pip install --...
I'm not familiar with leveldb but most direct binary installations require you to run `./configure` then `make` then `make install` before the binary is actually installed. You should try that. Also, according to this github page you should be able to install it with `gem`: <https://github.com/DAddYE/leveldb>
26,199,376
I am trying to use level db in my python project. I zeroed in on python binding PlyVel <http://plyvel.readthedocs.org/en/latest/installation.html>, which seems to be better maintained and documented python binding. However installation fails for plyvel > > plyvel/\_plyvel.cpp:359:10: fatal error: 'leveldb/db.h' fil...
2014/10/05
[ "https://Stackoverflow.com/questions/26199376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089768/" ]
The easiest way to install leveldb on Mac OS X would be to use [homebrew](http://brew.sh/). [With homebrew](https://brewinstall.org/Install-leveldb-on-Mac-with-Brew/) you only need to run: ``` brew install leveldb ```
In OS X, it seems like `/usr/local/include`, where the leveldb headers (db.h) live, is not visible to gcc. You need to install the Apple command line tools: ``` xcode-select --install ``` plyvel will compile after that. [Link to GH issue](https://github.com/wbolster/plyvel/issues/34). Seems to be an OS X problem.
26,199,376
I am trying to use level db in my python project. I zeroed in on python binding PlyVel <http://plyvel.readthedocs.org/en/latest/installation.html>, which seems to be better maintained and documented python binding. However installation fails for plyvel > > plyvel/\_plyvel.cpp:359:10: fatal error: 'leveldb/db.h' fil...
2014/10/05
[ "https://Stackoverflow.com/questions/26199376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089768/" ]
In OS X, it seems like `/usr/local/include`, where the leveldb headers (db.h) live, is not visible to gcc. You need to install the Apple command line tools: ``` xcode-select --install ``` plyvel will compile after that. [Link to GH issue](https://github.com/wbolster/plyvel/issues/34). Seems to be an OS X problem.
As mentioned by jAlpedrinha The easiest way to install leveldb on Mac OS X would be to use homebrew. With homebrew you only need to run: ``` brew install leveldb ``` You also need to have gcc or clang installed. If there is a problem installing python bindings as mentioned here, <https://github.com/wbolster/plyvel...
26,199,376
I am trying to use level db in my python project. I zeroed in on python binding PlyVel <http://plyvel.readthedocs.org/en/latest/installation.html>, which seems to be better maintained and documented python binding. However installation fails for plyvel > > plyvel/\_plyvel.cpp:359:10: fatal error: 'leveldb/db.h' fil...
2014/10/05
[ "https://Stackoverflow.com/questions/26199376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089768/" ]
The easiest way to install leveldb on Mac OS X would be to use [homebrew](http://brew.sh/). [With homebrew](https://brewinstall.org/Install-leveldb-on-Mac-with-Brew/) you only need to run: ``` brew install leveldb ```
As mentioned by jAlpedrinha The easiest way to install leveldb on Mac OS X would be to use homebrew. With homebrew you only need to run: ``` brew install leveldb ``` You also need to have gcc or clang installed. If there is a problem installing python bindings as mentioned here, <https://github.com/wbolster/plyvel...
26,199,376
I am trying to use level db in my python project. I zeroed in on python binding PlyVel <http://plyvel.readthedocs.org/en/latest/installation.html>, which seems to be better maintained and documented python binding. However installation fails for plyvel > > plyvel/\_plyvel.cpp:359:10: fatal error: 'leveldb/db.h' fil...
2014/10/05
[ "https://Stackoverflow.com/questions/26199376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089768/" ]
The easiest way to install leveldb on Mac OS X would be to use [homebrew](http://brew.sh/). [With homebrew](https://brewinstall.org/Install-leveldb-on-Mac-with-Brew/) you only need to run: ``` brew install leveldb ```
If you are a MacPorts user, you can `sudo port install leveldb` to install the shared libraries. Depending on how you've installed pip/python, you may also need to tell pip where to find the necessary files. Per <https://stackoverflow.com/a/22942120/5568265> you will want to do something like this: ``` pip install --...
26,199,376
I am trying to use level db in my python project. I zeroed in on python binding PlyVel <http://plyvel.readthedocs.org/en/latest/installation.html>, which seems to be better maintained and documented python binding. However installation fails for plyvel > > plyvel/\_plyvel.cpp:359:10: fatal error: 'leveldb/db.h' fil...
2014/10/05
[ "https://Stackoverflow.com/questions/26199376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089768/" ]
If you are a MacPorts user, you can `sudo port install leveldb` to install the shared libraries. Depending on how you've installed pip/python, you may also need to tell pip where to find the necessary files. Per <https://stackoverflow.com/a/22942120/5568265> you will want to do something like this: ``` pip install --...
As mentioned by jAlpedrinha The easiest way to install leveldb on Mac OS X would be to use homebrew. With homebrew you only need to run: ``` brew install leveldb ``` You also need to have gcc or clang installed. If there is a problem installing python bindings as mentioned here, <https://github.com/wbolster/plyvel...
47,944,927
I am trying to make a GET request to a shopify store, packershoes as follow: ``` endpoint = "http://www.packershoes.com" print session.get(endpoint, headers=headers) ``` When I run a get request to the site I get the following error: ``` File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 467, in ge...
2017/12/22
[ "https://Stackoverflow.com/questions/47944927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8528309/" ]
This looks like more of an SSL problem than a Python problem. You haven't shown us your code, so I'm making some guesses here, but it looks as if the site to which you are connecting is presenting an SSL certificate that doesn't match the hostname you're using. The resolution here is typically: * See if there is an al...
Requests verifies SSL certificates for HTTPS requests, just like a web browser. By default, SSL verification is enabled, and Requests will throw a `SSLError` if it's unable to verify the certificate, you have set verify to False: ``` session.get("http://www.packershoes.com", headers=headers, verify=False) ```
22,042,673
I've setup a code in python to search for tweets using the oauth2 and urllib2 libraries only. (I'm not using any particular twitter library) I'm able to search for tweets based on keywords. However, I'm getting zero number of tweets when I search for this particular keyword - "Jurgen%20Mayer-Hermann". (this is challen...
2014/02/26
[ "https://Stackoverflow.com/questions/22042673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2935885/" ]
Change `$(document).load(` to [`$(document).ready(`](http://learn.jquery.com/using-jquery-core/document-ready/) ``` $(document).ready(function() { var vague = $('.zero').Vague({ intensity: 3, forceSVGUrl: false }); vague.blur(); }); ``` or use ``` $(window).load(function(){ ``` or...
Try to use: ``` $(window).load(function() { ``` or: ``` $(document).ready(function() { ``` instead of: ``` $(document).load(function() { ```
22,042,673
I've setup a code in python to search for tweets using the oauth2 and urllib2 libraries only. (I'm not using any particular twitter library) I'm able to search for tweets based on keywords. However, I'm getting zero number of tweets when I search for this particular keyword - "Jurgen%20Mayer-Hermann". (this is challen...
2014/02/26
[ "https://Stackoverflow.com/questions/22042673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2935885/" ]
Change `$(document).load(` to [`$(document).ready(`](http://learn.jquery.com/using-jquery-core/document-ready/) ``` $(document).ready(function() { var vague = $('.zero').Vague({ intensity: 3, forceSVGUrl: false }); vague.blur(); }); ``` or use ``` $(window).load(function(){ ``` or...
Make sure the permissions on the Vague.js are set to 755. Assuming a LAMP stack of course.
22,042,673
I've setup a code in python to search for tweets using the oauth2 and urllib2 libraries only. (I'm not using any particular twitter library) I'm able to search for tweets based on keywords. However, I'm getting zero number of tweets when I search for this particular keyword - "Jurgen%20Mayer-Hermann". (this is challen...
2014/02/26
[ "https://Stackoverflow.com/questions/22042673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2935885/" ]
Try to use: ``` $(window).load(function() { ``` or: ``` $(document).ready(function() { ``` instead of: ``` $(document).load(function() { ```
Make sure the permissions on the Vague.js are set to 755. Assuming a LAMP stack of course.
56,112,849
I have a Div containing 4 images of the same size, placed in a row. I want them to occupy all the space avaible in the div by staying in the same row, with the first image in the far left and the fourth image in the far right, they also have to be equally spaced. I can accomplish this by modifying the padding of each i...
2019/05/13
[ "https://Stackoverflow.com/questions/56112849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11426745/" ]
You can use flexbox. Read more about it here: <https://css-tricks.com/snippets/css/a-guide-to-flexbox/> ```css #my-container { display: flex; justify-content: space-between; } ``` ```html <div id="my-container"> <img src="https://placekitten.com/50/50" /> <img src="https://placekitten.com/50/50" /> <i...
if bootstrap is available and you can change the html then you can wrap each image in a div and use bootstrap's grid system ([here is a demo](https://codepen.io/carnnia/pen/ZNprZa)). ```css #container{ width: 100%; border: 1px solid red; } .row{ text-align: center; } ``` ```html <div class="container" i...
8,051,506
am I going about this in the correct way? Ive never done anything like this before, so im not 100% sure on what I am doing. The code so far gets html and css files and that works fine, but images wont load, and will I have to create a new "if" for every different file type? or am I doing this a silly way...here is what...
2011/11/08
[ "https://Stackoverflow.com/questions/8051506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/787367/" ]
You are on the right track with it, though your ifs are very redundant. I suggest you refactor the code to check for type using a loop and a dict: ``` mime = {"html":"text/html", "css":"text/css", "png":"image/png"} if RequestedFileType in mime.keys(): self.send_response(200) self.send_header('Content-type', m...
As to a panoply of `if` statements, the usual approach is to have a file that handles the mapping between extensions and mime types (look here: [List of ALL MimeTypes on the Planet, mapped to File Extensions?](https://stackoverflow.com/questions/1735659/list-of-all-mimetypes-on-the-planet-mapped-to-file-extensions)). R...
74,061,083
My python GUI has been working fine from VSCode for months now, but today (with no changes in the code that I can find) it has been throwing me an error in the form of: Exception has occurred: ModuleNotFoundError No module named '\_tkinter' This error occurs for any import that is not commented out. The GUI works as ...
2022/10/13
[ "https://Stackoverflow.com/questions/74061083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20234707/" ]
Press Ctrl+Shift+P and type "select interpreter", press Enter and select the python interpreter path that you want to use by default in current project. If currently selected one does not have some libraries installed, you may see error from Pylance.
The cause of this problem may be that there are multiple python versions on your machine, and the interpreter environment you are currently using is not the same environment where you installed the third-party library. **Solution:** 1. Use the following code to get the current interpreter path ``` import sys print(s...
35,127,452
Could someone please help me create a field in my model that generates a unique 8 character alphanumeric string (i.e. A#######) ID every time a user makes a form submission? My **models.py** form is currently as follows: ``` from django.db import models from django.contrib.auth.models import User class Transfer(...
2016/02/01
[ "https://Stackoverflow.com/questions/35127452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2798841/" ]
Something like this: ``` ''.join(random.choice(string.ascii_uppercase) for _ in range(8)) ```
In order for the ID to be truly unique you have to keep track of previously generated unique IDs, This can be simply done with a simple sqlite DB. In order to generate a simple unique id use the following line: ``` import random import string u_id = ''.join(random.choice(string.ascii_letters + string.digits) for _ in...
35,127,452
Could someone please help me create a field in my model that generates a unique 8 character alphanumeric string (i.e. A#######) ID every time a user makes a form submission? My **models.py** form is currently as follows: ``` from django.db import models from django.contrib.auth.models import User class Transfer(...
2016/02/01
[ "https://Stackoverflow.com/questions/35127452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2798841/" ]
Something like this: ``` ''.join(random.choice(string.ascii_uppercase) for _ in range(8)) ```
I suggest to make a token generator class like this: ``` import string, random class RandomTokenGenerator(object): def __init__(self, chars=None, random_generator=None): self.chars = chars or string.ascii_uppercase + string.ascii_lowercase + string.digits self.random_generator = random_generator or...
35,127,452
Could someone please help me create a field in my model that generates a unique 8 character alphanumeric string (i.e. A#######) ID every time a user makes a form submission? My **models.py** form is currently as follows: ``` from django.db import models from django.contrib.auth.models import User class Transfer(...
2016/02/01
[ "https://Stackoverflow.com/questions/35127452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2798841/" ]
Something like this: ``` ''.join(random.choice(string.ascii_uppercase) for _ in range(8)) ```
You could use the DB id and convert that to a sting using someting like this: ``` def int_to_key(num): if num == 0: return "" return "{0}{1}".format( int_to_key(num // 52), '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'[num % 52] ) ``` If you can adjust the cod...
13,529,852
I have a python GUI and i want to run a shell command which you cannot do using windows cmd i have installed cygwin and i was wondering how i would go about running cygwin instead of the windows cmd. I am wanting to use subprocess and get the results of the .sh file but my code ``` subprocess.check_output("./listChai...
2012/11/23
[ "https://Stackoverflow.com/questions/13529852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1810400/" ]
Execute a cygwin shell (e.g. `bash`) and have it run your script, instead of running your script directly: ``` subprocess.check_output("C:/cygwin/bin/bash.exe ./listChains.sh < 2p31protein.pdb") ``` Alternatively, associate the `.sh` filetype extension to open with `bash.exe`.
Using python sub-process to run a cygwin executable requires that the ./bin directory with `cygwin1.dll` be on the Windows path. `cygwin1.dll` exposes cygwin executables to Windows, allowing them to run in Windows command line and be called by Python sub-process.
74,581,136
I would like to do the same in python pandas as shown on the picture. [pandas image](https://i.stack.imgur.com/ZsHLT.png) This is sum function where the first cell is fixed and the formula calculates "**continuous sum**". I tried to create pandas data frame however I did not manage to do this exactly.
2022/11/26
[ "https://Stackoverflow.com/questions/74581136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557036/" ]
The phrasing, and the unqualified template, aren't super-helpful in figuring out the difference, but: `transform()` does "re-boxing" into an optional, but `and_then()` does not, expecting the function to returned a boxed value on its own. So, * `transform()` is for when you want to use a function like `T2 foo(T1 x)`. ...
`and_then` is monadic `bind` aka `flatmap` aka `>>=` and `transform` is functorial `map`. One can express `map` in terms of `bind` generically, but not the other way around, because a functor is not necessarily a monad. Of course the particular monad of `std::optional` can be opened at any time, so both functions are ...
74,581,136
I would like to do the same in python pandas as shown on the picture. [pandas image](https://i.stack.imgur.com/ZsHLT.png) This is sum function where the first cell is fixed and the formula calculates "**continuous sum**". I tried to create pandas data frame however I did not manage to do this exactly.
2022/11/26
[ "https://Stackoverflow.com/questions/74581136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557036/" ]
The phrasing, and the unqualified template, aren't super-helpful in figuring out the difference, but: `transform()` does "re-boxing" into an optional, but `and_then()` does not, expecting the function to returned a boxed value on its own. So, * `transform()` is for when you want to use a function like `T2 foo(T1 x)`. ...
`and_then` only takes functions of type `T -> std::optional<U>` (whereas `transform` is free to take functions returning any type). If you just `transform` with such a function you will get a `std::optional<std::optional<U>>`. `and_then` just then flattens the `std::optional<std::optional<U>>` into an `std::optional<...
74,581,136
I would like to do the same in python pandas as shown on the picture. [pandas image](https://i.stack.imgur.com/ZsHLT.png) This is sum function where the first cell is fixed and the formula calculates "**continuous sum**". I tried to create pandas data frame however I did not manage to do this exactly.
2022/11/26
[ "https://Stackoverflow.com/questions/74581136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557036/" ]
`and_then` is monadic `bind` aka `flatmap` aka `>>=` and `transform` is functorial `map`. One can express `map` in terms of `bind` generically, but not the other way around, because a functor is not necessarily a monad. Of course the particular monad of `std::optional` can be opened at any time, so both functions are ...
`and_then` only takes functions of type `T -> std::optional<U>` (whereas `transform` is free to take functions returning any type). If you just `transform` with such a function you will get a `std::optional<std::optional<U>>`. `and_then` just then flattens the `std::optional<std::optional<U>>` into an `std::optional<...
60,155,460
I was planning to automate the manual steps to run the ssh commands using python. I developed the code that automatically executes the below command and log me in VM. The SSH command works fine whenever i run the code in spyder and conda prompt. The command works whenever I open the cmd and try the command directly whe...
2020/02/10
[ "https://Stackoverflow.com/questions/60155460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12873907/" ]
Just resolved the issue here. I updated to the last version of all libs ``` "@react-navigation/bottom-tabs": "^5.0.1", "@react-navigation/core": "^5.1.0", "@react-navigation/material-top-tabs": "^5.0.1", "@react-navigation/native": "^5.0.1", "@react-navigation/stack": "^5.0.1", ``` and then i deleted my package-loc...
Make sure you have installed latest versions of `@react-navigation/native` and `@react-navigation/bottom-tabs`: ```js npm install @react-navigation/native @react-navigation/bottom-tabs ``` Then clear the cache: ```sh npm react-native start --reset-cache ``` Or if using Expo: ```js expo start -c ```
54,337,433
I have a list of tuples and need to delete tuples if its 1st item is matching with 1st item of other tuples in the list. 3rd item may or may not be the same, so I cannot use set (I have seen this question - [Grab unique tuples in python list, irrespective of order](https://stackoverflow.com/questions/35975441/grab-uniq...
2019/01/23
[ "https://Stackoverflow.com/questions/54337433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2565385/" ]
The usual way is keying a dict off whatever you want to dedupe by, for example: ``` >>> a = [(0, 13, 'order1'), (14, 27, 'order2'), (14, 27, 'order2.1'), (0, 13, 'order1'), (28, 41, 'order3')] >>> print(*{tup[:2]: tup for tup in a}.values()) (0, 13, 'order1') (14, 27, 'order2.1') (28, 41, 'order3') ``` This is *O(...
You can get the first element of each group in a grouped, sorted list: ``` from itertools import groupby from operator import itemgetter a = [(0, 13, 'order1'), (14, 27, 'order2'), (14, 27, 'order2.1'), (0, 13, 'order1'), (28, 41, 'order3')] result = [list(g)[0] for k, g in groupby(sorted(a), key=itemgetter(0))] pri...
54,337,433
I have a list of tuples and need to delete tuples if its 1st item is matching with 1st item of other tuples in the list. 3rd item may or may not be the same, so I cannot use set (I have seen this question - [Grab unique tuples in python list, irrespective of order](https://stackoverflow.com/questions/35975441/grab-uniq...
2019/01/23
[ "https://Stackoverflow.com/questions/54337433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2565385/" ]
You should avoid modifying your list in place while iterating over it. Instead, you can use the popular [`itertools` `unique_everseen` recipe](https://docs.python.org/3/library/itertools.html#itertools-recipes), also available in 3rd party [`more_itertools`](https://more-itertools.readthedocs.io/en/stable/api.html#more...
You can get the first element of each group in a grouped, sorted list: ``` from itertools import groupby from operator import itemgetter a = [(0, 13, 'order1'), (14, 27, 'order2'), (14, 27, 'order2.1'), (0, 13, 'order1'), (28, 41, 'order3')] result = [list(g)[0] for k, g in groupby(sorted(a), key=itemgetter(0))] pri...
54,337,433
I have a list of tuples and need to delete tuples if its 1st item is matching with 1st item of other tuples in the list. 3rd item may or may not be the same, so I cannot use set (I have seen this question - [Grab unique tuples in python list, irrespective of order](https://stackoverflow.com/questions/35975441/grab-uniq...
2019/01/23
[ "https://Stackoverflow.com/questions/54337433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2565385/" ]
The usual way is keying a dict off whatever you want to dedupe by, for example: ``` >>> a = [(0, 13, 'order1'), (14, 27, 'order2'), (14, 27, 'order2.1'), (0, 13, 'order1'), (28, 41, 'order3')] >>> print(*{tup[:2]: tup for tup in a}.values()) (0, 13, 'order1') (14, 27, 'order2.1') (28, 41, 'order3') ``` This is *O(...
You should avoid modifying your list in place while iterating over it. Instead, you can use the popular [`itertools` `unique_everseen` recipe](https://docs.python.org/3/library/itertools.html#itertools-recipes), also available in 3rd party [`more_itertools`](https://more-itertools.readthedocs.io/en/stable/api.html#more...
54,028,502
I have this kind of list of dictionary in python ``` [ { "compania": "Fiat", "modelo": "2014", "precio": "1000" }, { "compania": "Renault", "modelo": "2014", "precio": "2000" }, { "compania": "Volkwagen", "modelo": "2014", "precio": "3000" }, { "compani...
2019/01/03
[ "https://Stackoverflow.com/questions/54028502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10864244/" ]
We can use dict comprehension ``` {a.get('compania'): {k: v for k, v in a.items() if k != 'compania'} for a in c} {'Fiat': {'modelo': '2014', 'precio': '1000'}, 'Renault': {'modelo': '2014', 'precio': '2000'}, 'Volkwagen': {'modelo': '2014', 'precio': '3000'}, 'Chevrolet': {'modelo': '2014', 'precio': '1000'}, 'P...
``` result = {} for d in l: # Store the value of the key 'compania' before popping it from the small dictionary d compania = d['compania'] d.pop('compania') # Construct new dictionary with key of the compania and value of the small dictionary without the compania key/value pair result[compania] = d ...
54,028,502
I have this kind of list of dictionary in python ``` [ { "compania": "Fiat", "modelo": "2014", "precio": "1000" }, { "compania": "Renault", "modelo": "2014", "precio": "2000" }, { "compania": "Volkwagen", "modelo": "2014", "precio": "3000" }, { "compani...
2019/01/03
[ "https://Stackoverflow.com/questions/54028502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10864244/" ]
We can use dict comprehension ``` {a.get('compania'): {k: v for k, v in a.items() if k != 'compania'} for a in c} {'Fiat': {'modelo': '2014', 'precio': '1000'}, 'Renault': {'modelo': '2014', 'precio': '2000'}, 'Volkwagen': {'modelo': '2014', 'precio': '3000'}, 'Chevrolet': {'modelo': '2014', 'precio': '1000'}, 'P...
with a mapper function to return a new customized list of dicts ``` a=[ { "compania": "Fiat", "modelo": "2014", "precio": "1000" }, { "compania": "Renault", "modelo": "2014", "precio": "2000" }, { "compania": "Volkwagen", "modelo": "2014", "precio": "3000" },...
54,028,502
I have this kind of list of dictionary in python ``` [ { "compania": "Fiat", "modelo": "2014", "precio": "1000" }, { "compania": "Renault", "modelo": "2014", "precio": "2000" }, { "compania": "Volkwagen", "modelo": "2014", "precio": "3000" }, { "compani...
2019/01/03
[ "https://Stackoverflow.com/questions/54028502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10864244/" ]
You can create a dictionary by iterating over the elements of your original list. Assuming your list is called `car_list`: ``` d = { x["compania"]: {"modelo": x["modelo"], "precio": x["precio"] } for x in car_list } ```
Assuming your list is called `l`, you could accomplish this using simple iteration and building a new dictionary `d`: ``` d = {} for sub in l: d[sub.pop('compania')] = sub ``` This produces in the dictionary `d`: ``` {'Chevrolet': {'modelo': '2014', 'precio': '1000'}, 'Fiat': {'modelo': '2014', 'precio': '1000'...
54,028,502
I have this kind of list of dictionary in python ``` [ { "compania": "Fiat", "modelo": "2014", "precio": "1000" }, { "compania": "Renault", "modelo": "2014", "precio": "2000" }, { "compania": "Volkwagen", "modelo": "2014", "precio": "3000" }, { "compani...
2019/01/03
[ "https://Stackoverflow.com/questions/54028502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10864244/" ]
You can create a dictionary by iterating over the elements of your original list. Assuming your list is called `car_list`: ``` d = { x["compania"]: {"modelo": x["modelo"], "precio": x["precio"] } for x in car_list } ```
I would share simple solution: ``` >>> {d.pop("compania"):d for d in dd} ```
54,028,502
I have this kind of list of dictionary in python ``` [ { "compania": "Fiat", "modelo": "2014", "precio": "1000" }, { "compania": "Renault", "modelo": "2014", "precio": "2000" }, { "compania": "Volkwagen", "modelo": "2014", "precio": "3000" }, { "compani...
2019/01/03
[ "https://Stackoverflow.com/questions/54028502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10864244/" ]
Assuming your list is called `l`, you could accomplish this using simple iteration and building a new dictionary `d`: ``` d = {} for sub in l: d[sub.pop('compania')] = sub ``` This produces in the dictionary `d`: ``` {'Chevrolet': {'modelo': '2014', 'precio': '1000'}, 'Fiat': {'modelo': '2014', 'precio': '1000'...
I would share simple solution: ``` >>> {d.pop("compania"):d for d in dd} ```
54,028,502
I have this kind of list of dictionary in python ``` [ { "compania": "Fiat", "modelo": "2014", "precio": "1000" }, { "compania": "Renault", "modelo": "2014", "precio": "2000" }, { "compania": "Volkwagen", "modelo": "2014", "precio": "3000" }, { "compani...
2019/01/03
[ "https://Stackoverflow.com/questions/54028502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10864244/" ]
You can create a dictionary by iterating over the elements of your original list. Assuming your list is called `car_list`: ``` d = { x["compania"]: {"modelo": x["modelo"], "precio": x["precio"] } for x in car_list } ```
with a mapper function to return a new customized list of dicts ``` a=[ { "compania": "Fiat", "modelo": "2014", "precio": "1000" }, { "compania": "Renault", "modelo": "2014", "precio": "2000" }, { "compania": "Volkwagen", "modelo": "2014", "precio": "3000" },...
54,028,502
I have this kind of list of dictionary in python ``` [ { "compania": "Fiat", "modelo": "2014", "precio": "1000" }, { "compania": "Renault", "modelo": "2014", "precio": "2000" }, { "compania": "Volkwagen", "modelo": "2014", "precio": "3000" }, { "compani...
2019/01/03
[ "https://Stackoverflow.com/questions/54028502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10864244/" ]
We can use dict comprehension ``` {a.get('compania'): {k: v for k, v in a.items() if k != 'compania'} for a in c} {'Fiat': {'modelo': '2014', 'precio': '1000'}, 'Renault': {'modelo': '2014', 'precio': '2000'}, 'Volkwagen': {'modelo': '2014', 'precio': '3000'}, 'Chevrolet': {'modelo': '2014', 'precio': '1000'}, 'P...
I would share simple solution: ``` >>> {d.pop("compania"):d for d in dd} ```
54,028,502
I have this kind of list of dictionary in python ``` [ { "compania": "Fiat", "modelo": "2014", "precio": "1000" }, { "compania": "Renault", "modelo": "2014", "precio": "2000" }, { "compania": "Volkwagen", "modelo": "2014", "precio": "3000" }, { "compani...
2019/01/03
[ "https://Stackoverflow.com/questions/54028502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10864244/" ]
Assuming your list is called `l`, you could accomplish this using simple iteration and building a new dictionary `d`: ``` d = {} for sub in l: d[sub.pop('compania')] = sub ``` This produces in the dictionary `d`: ``` {'Chevrolet': {'modelo': '2014', 'precio': '1000'}, 'Fiat': {'modelo': '2014', 'precio': '1000'...
with a mapper function to return a new customized list of dicts ``` a=[ { "compania": "Fiat", "modelo": "2014", "precio": "1000" }, { "compania": "Renault", "modelo": "2014", "precio": "2000" }, { "compania": "Volkwagen", "modelo": "2014", "precio": "3000" },...
54,028,502
I have this kind of list of dictionary in python ``` [ { "compania": "Fiat", "modelo": "2014", "precio": "1000" }, { "compania": "Renault", "modelo": "2014", "precio": "2000" }, { "compania": "Volkwagen", "modelo": "2014", "precio": "3000" }, { "compani...
2019/01/03
[ "https://Stackoverflow.com/questions/54028502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10864244/" ]
You can create a dictionary by iterating over the elements of your original list. Assuming your list is called `car_list`: ``` d = { x["compania"]: {"modelo": x["modelo"], "precio": x["precio"] } for x in car_list } ```
You can simply use dictionary [update](https://docs.python.org/3/library/stdtypes.html#dict.update) which can then produce a new dictionary of your preference. ``` from pprint import PrettyPrinter as pp d={} for i in l: # 'l' represents your list of dictionary d.update({i['compania']:{"modelo":i['modelo'],"preci...
54,028,502
I have this kind of list of dictionary in python ``` [ { "compania": "Fiat", "modelo": "2014", "precio": "1000" }, { "compania": "Renault", "modelo": "2014", "precio": "2000" }, { "compania": "Volkwagen", "modelo": "2014", "precio": "3000" }, { "compani...
2019/01/03
[ "https://Stackoverflow.com/questions/54028502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10864244/" ]
Assuming your list is called `l`, you could accomplish this using simple iteration and building a new dictionary `d`: ``` d = {} for sub in l: d[sub.pop('compania')] = sub ``` This produces in the dictionary `d`: ``` {'Chevrolet': {'modelo': '2014', 'precio': '1000'}, 'Fiat': {'modelo': '2014', 'precio': '1000'...
You can simply use dictionary [update](https://docs.python.org/3/library/stdtypes.html#dict.update) which can then produce a new dictionary of your preference. ``` from pprint import PrettyPrinter as pp d={} for i in l: # 'l' represents your list of dictionary d.update({i['compania']:{"modelo":i['modelo'],"preci...
55,655,666
Hello i m new at django. I installed all moduoles from anaconda. Then created a web application with ``` django-admin startproject ``` My project crated successfully. No problem Then i tried to run that project at localhost to see is everything okay or not. And i run that code in command line ``` python manage.py ...
2019/04/12
[ "https://Stackoverflow.com/questions/55655666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4511476/" ]
I had this problem. I solved it by running it in the Anaconda shell. 1. Open **Anaconda Shell/terminal** by pressing your Windows key and searching Anaconda 2. Go to the directory you have your django project in 3. `python manage.py runserver`
It sounds like you need to install SQLite: <https://www.sqlite.org/download.html> Or you could change the database settings in your settings file to use some other database.
55,655,666
Hello i m new at django. I installed all moduoles from anaconda. Then created a web application with ``` django-admin startproject ``` My project crated successfully. No problem Then i tried to run that project at localhost to see is everything okay or not. And i run that code in command line ``` python manage.py ...
2019/04/12
[ "https://Stackoverflow.com/questions/55655666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4511476/" ]
I had this problem. I solved it by running it in the Anaconda shell. 1. Open **Anaconda Shell/terminal** by pressing your Windows key and searching Anaconda 2. Go to the directory you have your django project in 3. `python manage.py runserver`
Remove anaconda Download and install from python.org in c:\python37. Here it will be easy to set variables Setup python variables Don't forget to select pip while installing python. Path:c:\python37,c:\python32\Scripts If you want to install django on a virtual environment install virtualevmwrapper-win Voila! It ...
55,655,666
Hello i m new at django. I installed all moduoles from anaconda. Then created a web application with ``` django-admin startproject ``` My project crated successfully. No problem Then i tried to run that project at localhost to see is everything okay or not. And i run that code in command line ``` python manage.py ...
2019/04/12
[ "https://Stackoverflow.com/questions/55655666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4511476/" ]
I had this problem. I solved it by running it in the Anaconda shell. 1. Open **Anaconda Shell/terminal** by pressing your Windows key and searching Anaconda 2. Go to the directory you have your django project in 3. `python manage.py runserver`
if you want to use anaconda then follow below steps > > conda create --name MyDjangoEnv(virtual environment) Django > > > press y to install. before press y please make sure correct version of software are selected > > > activate myDjangoEnv > > > conda info --envs > > > conda install django > > > conda ins...
55,655,666
Hello i m new at django. I installed all moduoles from anaconda. Then created a web application with ``` django-admin startproject ``` My project crated successfully. No problem Then i tried to run that project at localhost to see is everything okay or not. And i run that code in command line ``` python manage.py ...
2019/04/12
[ "https://Stackoverflow.com/questions/55655666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4511476/" ]
I had this problem. I solved it by running it in the Anaconda shell. 1. Open **Anaconda Shell/terminal** by pressing your Windows key and searching Anaconda 2. Go to the directory you have your django project in 3. `python manage.py runserver`
I found a solution in this site: <http://felipegalvao.com.br/blog/2017/01/03/como-criar-ambientes-e-instalar-o-django-com-distribuicao-anaconda/> Basically, you need to activate an environment in your anaconda prompt. Step 1: `conda info --envs` Step 2 : `conda create --name env_name python=3` Step 3: `pip install...
55,655,666
Hello i m new at django. I installed all moduoles from anaconda. Then created a web application with ``` django-admin startproject ``` My project crated successfully. No problem Then i tried to run that project at localhost to see is everything okay or not. And i run that code in command line ``` python manage.py ...
2019/04/12
[ "https://Stackoverflow.com/questions/55655666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4511476/" ]
I had this problem. I solved it by running it in the Anaconda shell. 1. Open **Anaconda Shell/terminal** by pressing your Windows key and searching Anaconda 2. Go to the directory you have your django project in 3. `python manage.py runserver`
I was facing the same problem, it simply means that dll module is not installed in that path while creating a project don't go with first option i.e venv(virtual environment) this will not let modules to import in your project.., go with the second option for interpreter and select your respective python.exe. > > > ...
55,779,936
I used pip to install keras and tensorflow, yet when I import subpackages from keras, my shell fails a check for PyBfloat16\_Type.tp\_base. I tried uninstalling and reinstalling tensorflow, but I don't know for certain what is causing this error. ``` from keras.models import Sequential from keras.layers import Dense ...
2019/04/21
[ "https://Stackoverflow.com/questions/55779936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11262404/" ]
You may try to downgrade python to 3.6 (I know some people have troubles with tensorflow and keras using python 3.7). One simple way is to download anaconda, create a new environment with python 3.6, then install tensorflow and keras. `conda create -n myenv python=3.6` `conda activate myenv` `pip3 install tensorflow...
You have a few options to try: First, try to uninstall and re-install the TensorFlow and see whether the problem is resolved or not (replace `tensorflow` with `tensorflow-gpu` in the following commands if you have installed the GPU version): ``` pip uninstall tensorflow pip install --no-cache-dir tensorflow ``` I...
28,023,697
I want to setup cronjobs on various servers at the same time for Data Mining. I was also already following the steps in [Ansible and crontabs](https://stackoverflow.com/questions/21787755/ansible-and-crontabs) but so far nothing worked. Whatever i do, i get the Error Message: ``` ERROR: cron is not a legal parameter ...
2015/01/19
[ "https://Stackoverflow.com/questions/28023697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4469762/" ]
I've got (something very much like) this in a ./roles/cron/tasks/main.yml file: ``` - name: Creates weekly backup cronjob cron: minute="20" hour="5" weekday="sun" name="Backup mysql tables (weekly schedule)" cron_file="mysqlbackup-WeeklyBackups" user="root" job="/usr/local/bin/mysqlba...
If you're setting it up to run on the Crontab of the user: ``` - name: Install Batchjobs on crontab cron: name: "Manage Disk Space" minute: "30" hour: "02" weekday: "0-6" job: "home/export/manageDiskSpace.sh > home/export/manageDiskSpace.sh.log 2>&1" #user: "admin" disabled: "no" become...
28,023,697
I want to setup cronjobs on various servers at the same time for Data Mining. I was also already following the steps in [Ansible and crontabs](https://stackoverflow.com/questions/21787755/ansible-and-crontabs) but so far nothing worked. Whatever i do, i get the Error Message: ``` ERROR: cron is not a legal parameter ...
2015/01/19
[ "https://Stackoverflow.com/questions/28023697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4469762/" ]
I've got (something very much like) this in a ./roles/cron/tasks/main.yml file: ``` - name: Creates weekly backup cronjob cron: minute="20" hour="5" weekday="sun" name="Backup mysql tables (weekly schedule)" cron_file="mysqlbackup-WeeklyBackups" user="root" job="/usr/local/bin/mysqlba...
``` --- - hosts: servers tasks: - name: "Cronjob Entry" cron: name: "### recording mixing/compressing/ftping scripts" minute: 0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57 hour: "*" day: "*" month: "*" weekday: "*" job: /usr/share/astguiclient/AST_CRON_audio...
28,023,697
I want to setup cronjobs on various servers at the same time for Data Mining. I was also already following the steps in [Ansible and crontabs](https://stackoverflow.com/questions/21787755/ansible-and-crontabs) but so far nothing worked. Whatever i do, i get the Error Message: ``` ERROR: cron is not a legal parameter ...
2015/01/19
[ "https://Stackoverflow.com/questions/28023697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4469762/" ]
``` --- - hosts: servers tasks: - name: "Cronjob Entry" cron: name: "### recording mixing/compressing/ftping scripts" minute: 0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57 hour: "*" day: "*" month: "*" weekday: "*" job: /usr/share/astguiclient/AST_CRON_audio...
If you're setting it up to run on the Crontab of the user: ``` - name: Install Batchjobs on crontab cron: name: "Manage Disk Space" minute: "30" hour: "02" weekday: "0-6" job: "home/export/manageDiskSpace.sh > home/export/manageDiskSpace.sh.log 2>&1" #user: "admin" disabled: "no" become...
61,262,487
Having an issue with Django Allauth. When I log out of one user, and log back in with another, I get this issue, both locally and in production. I'm using the latest version of Allauth, Django 3.0.5, and Python 3.7.4. It seems like this is an Allauth issue, but I haven't seen it reported online anywhere else. So just...
2020/04/17
[ "https://Stackoverflow.com/questions/61262487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636064/" ]
You need to have the segue from LiveController, not from Navigation Controller
This could be a few things so try these fixes: 1. Clean and build your project. Then, run again. 2. Quit Xcode, open up project and run. 3. In the `Attribute Inspector`, remove `openWelcomePage` and leave it blank. Hope that either of these suggestions help.
8,651,095
How do you control how the order in which PyYaml outputs key/value pairs when serializing a Python dictionary? I'm using Yaml as a simple serialization format in a Python script. My Yaml serialized objects represent a sort of "document", so for maximum user-friendliness, I'd like my object's "name" field to appear fir...
2011/12/28
[ "https://Stackoverflow.com/questions/8651095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247542/" ]
Took me a few hours of digging through PyYAML docs and tickets, but I eventually discovered [this comment](https://web.archive.org/web/20170308231702/http://pyyaml.org/ticket/29) that lays out some proof-of-concept code for serializing an OrderedDict as a normal YAML map (but maintaining the order). e.g. applied to my...
The last time I checked, Python's dictionaries weren't ordered. If you really want them to be, I strongly recommend using a list of key/value pairs. ``` [ ('key', 'value'), ('key2', 'value2') ] ``` Alternatively, define a list with the keys and put them in the right order. ``` keys = ['key1', 'name', 'price...
8,651,095
How do you control how the order in which PyYaml outputs key/value pairs when serializing a Python dictionary? I'm using Yaml as a simple serialization format in a Python script. My Yaml serialized objects represent a sort of "document", so for maximum user-friendliness, I'd like my object's "name" field to appear fir...
2011/12/28
[ "https://Stackoverflow.com/questions/8651095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247542/" ]
I think the problem is when you dump the data. I looked into the code of PyYaml and there is a optional argument called `sort_keys`, setting that value to `False` seems to do the trick.
The last time I checked, Python's dictionaries weren't ordered. If you really want them to be, I strongly recommend using a list of key/value pairs. ``` [ ('key', 'value'), ('key2', 'value2') ] ``` Alternatively, define a list with the keys and put them in the right order. ``` keys = ['key1', 'name', 'price...
8,651,095
How do you control how the order in which PyYaml outputs key/value pairs when serializing a Python dictionary? I'm using Yaml as a simple serialization format in a Python script. My Yaml serialized objects represent a sort of "document", so for maximum user-friendliness, I'd like my object's "name" field to appear fir...
2011/12/28
[ "https://Stackoverflow.com/questions/8651095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247542/" ]
**New Solution** (as of **2020** and PyYAML 5.1) You can dump a dictionary in its current order by simply using ``` yaml.dump(data, default_flow_style=False, sort_keys=False) ```
The last time I checked, Python's dictionaries weren't ordered. If you really want them to be, I strongly recommend using a list of key/value pairs. ``` [ ('key', 'value'), ('key2', 'value2') ] ``` Alternatively, define a list with the keys and put them in the right order. ``` keys = ['key1', 'name', 'price...
8,651,095
How do you control how the order in which PyYaml outputs key/value pairs when serializing a Python dictionary? I'm using Yaml as a simple serialization format in a Python script. My Yaml serialized objects represent a sort of "document", so for maximum user-friendliness, I'd like my object's "name" field to appear fir...
2011/12/28
[ "https://Stackoverflow.com/questions/8651095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247542/" ]
Took me a few hours of digging through PyYAML docs and tickets, but I eventually discovered [this comment](https://web.archive.org/web/20170308231702/http://pyyaml.org/ticket/29) that lays out some proof-of-concept code for serializing an OrderedDict as a normal YAML map (but maintaining the order). e.g. applied to my...
I think the problem is when you dump the data. I looked into the code of PyYaml and there is a optional argument called `sort_keys`, setting that value to `False` seems to do the trick.
8,651,095
How do you control how the order in which PyYaml outputs key/value pairs when serializing a Python dictionary? I'm using Yaml as a simple serialization format in a Python script. My Yaml serialized objects represent a sort of "document", so for maximum user-friendliness, I'd like my object's "name" field to appear fir...
2011/12/28
[ "https://Stackoverflow.com/questions/8651095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247542/" ]
Took me a few hours of digging through PyYAML docs and tickets, but I eventually discovered [this comment](https://web.archive.org/web/20170308231702/http://pyyaml.org/ticket/29) that lays out some proof-of-concept code for serializing an OrderedDict as a normal YAML map (but maintaining the order). e.g. applied to my...
**New Solution** (as of **2020** and PyYAML 5.1) You can dump a dictionary in its current order by simply using ``` yaml.dump(data, default_flow_style=False, sort_keys=False) ```
52,528,911
In the [docs](https://docs.aws.amazon.com/neptune/latest/userguide/access-graph-gremlin-differences.html) under **Updating a Vertex Property**, it is mentioned that one can *"update a property value without adding an additional value to the set of values"* by doing `g.V('exampleid01').property(single, 'age', 25)` ...
2018/09/27
[ "https://Stackoverflow.com/questions/52528911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4007615/" ]
You need to be sure to import `single` which is seen [here in the code](https://github.com/apache/tinkerpop/blob/d1a3fa147d1f009ae57274827c9b59426dfc6e58/gremlin-python/src/main/jython/gremlin_python/process/traversal.py#L127) and can be imported with: ``` from gremlin_python.process.traversal import Cardinality ``` ...
``` from gremlin_python.process.traversal import Cardinality g.V().hasLabel('placeholder-vertex').property(Cardinality.single,'maker','unknown').next() ``` This should also work.
52,528,911
In the [docs](https://docs.aws.amazon.com/neptune/latest/userguide/access-graph-gremlin-differences.html) under **Updating a Vertex Property**, it is mentioned that one can *"update a property value without adding an additional value to the set of values"* by doing `g.V('exampleid01').property(single, 'age', 25)` ...
2018/09/27
[ "https://Stackoverflow.com/questions/52528911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4007615/" ]
You need to be sure to import `single` which is seen [here in the code](https://github.com/apache/tinkerpop/blob/d1a3fa147d1f009ae57274827c9b59426dfc6e58/gremlin-python/src/main/jython/gremlin_python/process/traversal.py#L127) and can be imported with: ``` from gremlin_python.process.traversal import Cardinality ``` ...
Import `statics` from `gremlin_python` ``` from gremlin_python import statics statics.load_statics(globals()) update_prop_overwrite = g.V().hasLabel('placeholder-vertex').property(single,'maker','unknown').next() ```
52,528,911
In the [docs](https://docs.aws.amazon.com/neptune/latest/userguide/access-graph-gremlin-differences.html) under **Updating a Vertex Property**, it is mentioned that one can *"update a property value without adding an additional value to the set of values"* by doing `g.V('exampleid01').property(single, 'age', 25)` ...
2018/09/27
[ "https://Stackoverflow.com/questions/52528911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4007615/" ]
``` from gremlin_python.process.traversal import Cardinality g.V().hasLabel('placeholder-vertex').property(Cardinality.single,'maker','unknown').next() ``` This should also work.
Import `statics` from `gremlin_python` ``` from gremlin_python import statics statics.load_statics(globals()) update_prop_overwrite = g.V().hasLabel('placeholder-vertex').property(single,'maker','unknown').next() ```
15,713,427
I want to remove rows from several data frames so that they are all length n. When I tried to use a -for- loop, the changes would not persist through the rest of the script. ``` n = 50 groups = [df1, df2, df3] for dataset in groups: dataset = dataset[:n] ``` Redefining names individually (e.g., df1 = df1[:n] ),...
2013/03/30
[ "https://Stackoverflow.com/questions/15713427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1560238/" ]
This is a slight python mis-understanding, rather than to do with pandas specific one. :) You're re-assigning the variable used in the iteration and not changing it in the list: ``` In [1]: L = [1, 2, 3] In [2]: for i in L: i = i + 1 In [3]: L Out[3]: [1, 2, 3] ``` You want to actually change the list...
Your code creates (and discards) a new variable `dataset` in the for-loop. Try this: ``` n = 50 groups = [df1, df2, df3] for dataset in groups: dataset[:] = dataset[:n] ```
15,713,427
I want to remove rows from several data frames so that they are all length n. When I tried to use a -for- loop, the changes would not persist through the rest of the script. ``` n = 50 groups = [df1, df2, df3] for dataset in groups: dataset = dataset[:n] ``` Redefining names individually (e.g., df1 = df1[:n] ),...
2013/03/30
[ "https://Stackoverflow.com/questions/15713427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1560238/" ]
This is a slight python mis-understanding, rather than to do with pandas specific one. :) You're re-assigning the variable used in the iteration and not changing it in the list: ``` In [1]: L = [1, 2, 3] In [2]: for i in L: i = i + 1 In [3]: L Out[3]: [1, 2, 3] ``` You want to actually change the list...
``` n = 50 groups = [df1, df2, df3] groups = [df.head(n) for df in groups] ``` --- In Python, you can think of variable names as pointing to objects. The statement ``` groups = [df1, df2, df3] ``` makes the variable name, `groups`, point to a list object, which contains 3 other objects. The `for-loop`: ``` for ...
15,713,427
I want to remove rows from several data frames so that they are all length n. When I tried to use a -for- loop, the changes would not persist through the rest of the script. ``` n = 50 groups = [df1, df2, df3] for dataset in groups: dataset = dataset[:n] ``` Redefining names individually (e.g., df1 = df1[:n] ),...
2013/03/30
[ "https://Stackoverflow.com/questions/15713427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1560238/" ]
``` n = 50 groups = [df1, df2, df3] groups = [df.head(n) for df in groups] ``` --- In Python, you can think of variable names as pointing to objects. The statement ``` groups = [df1, df2, df3] ``` makes the variable name, `groups`, point to a list object, which contains 3 other objects. The `for-loop`: ``` for ...
Your code creates (and discards) a new variable `dataset` in the for-loop. Try this: ``` n = 50 groups = [df1, df2, df3] for dataset in groups: dataset[:] = dataset[:n] ```
52,465,856
``` def frame_processing(frame): out_frame = np.zeros((frame.shape[0],frame.shape[1],4),dtype = np.uint8) b,g,r = cv2.split(frame) alpha = np.zeros_like(b , dtype=np.uint8) print(out_frame.shape) print(b.shape);print(g.shape);print(r.shape);print(alpha.shape) for i in range(frame.shape[0]): for j in range(frame.sha...
2018/09/23
[ "https://Stackoverflow.com/questions/52465856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9811461/" ]
Use `cv2.inRange` to find the mask, then merge them with `np.dstack`: ``` #!/use/bin/python3 # 2018/09/24 11:51:31 (CST) import cv2 import numpy as np #frame = ... mask = cv2.inRange(frame, (225,225,225), (255,255,255)) #dst = np.dstack((frame, 255-mask)) dst = np.dstack((frame, mask)) cv2.imwrite("dst.png", dst) ...
Its a simple typo. You are changing the variable "b" in the for loop and it conflicts with variable of blue channel. Change `b = (225,225,225)` to `threshold = (225, 255, 255)` and `zip(a,b)` to `zip(a, threshold)` should fix the problem. By the way, you can use this to create your alpha channel: ``` alpha = np.ze...
60,823,720
I have a really long ordered dict that looks similar to this: ``` OrderedDict([('JIRAUSER16100', {'name': 'john.smith', 'fullname': 'John Smith', 'email': '[email protected]', 'active': True}), ('JIRAUSER16300', {'name': 'susan.jones', 'fullname': 'Susan Jones', 'email': '[email protected]', 'active': True}...
2020/03/24
[ "https://Stackoverflow.com/questions/60823720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11483315/" ]
Two ways you could potentially improve on this. You say your `OrderedDict` is really long, so I'd recommend the first option, since quickly become faster than the second as the size of your data grows. 1) **use [Pandas](https://pandas.pydata.org/)**: ``` In [1]: from collections import OrderedDict In [2]: import pan...
If you are looking for a specific match you will have to iterate through your structure until you find it so you don't have to go through the entire dictionary. Something like: ``` In [19]: d = OrderedDict([('JIRAUSER16100', {'name': 'john.smith', 'fullname': 'John Smith', 'email': '[email protected]', ...:...
58,983,828
I am using docplex in google collab with python For the following LP, the some of the decision variables are predetermined, and the LP needs to be solved for that. It's a sequencing problem and the sequence is a set of given values. The other decision variables will be optimized based on this. ``` #Define the decisi...
2019/11/21
[ "https://Stackoverflow.com/questions/58983828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3916398/" ]
`join()` doesn't do anything to the child thread -- all it does is block until the child thread has exited. It only has an effect on the calling thread (i.e. by blocking its progress). The child thread can keep running for as long as it wants (although typically you'd prefer it to exit quickly, so that the thread calli...
> > And to my surprise, joining these alive threads does not remove them from list of threads that top is giving. Is this expected behaviour? > > > That suggests the thread(s) are still running. Calling `join()` on a thread doesn't have any impact on that running thread; simply the calling thread waits for the cal...
54,440,762
I'm busy configuring a TensorFlow Serving client that asks a TensorFlow Serving server to produce predictions on a given input image, for a given model. If the model being requested has not yet been served, it is downloaded from a remote URL to a folder where the server's models are located. (The client does this). At...
2019/01/30
[ "https://Stackoverflow.com/questions/54440762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/141789/" ]
So it took me ages of trawling through pull requests to finally find a code example for this. For the next person who has the same question as me, here is an example of how to do this. (You'll need the `tensorflow_serving package` for this; `pip install tensorflow-serving-api`). Based on this pull request (which at th...
**Add a model** to TF Serving server and to the existing config file `conf_filepath`: Use arguments `name`, `base_path`, `model_platform` for the new model. Keeps the original models intact. Notice a small difference from @Karl 's answer - using `MergeFrom` instead of `CopyFrom` > > pip install tensorflow-serving-ap...
54,440,762
I'm busy configuring a TensorFlow Serving client that asks a TensorFlow Serving server to produce predictions on a given input image, for a given model. If the model being requested has not yet been served, it is downloaded from a remote URL to a folder where the server's models are located. (The client does this). At...
2019/01/30
[ "https://Stackoverflow.com/questions/54440762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/141789/" ]
So it took me ages of trawling through pull requests to finally find a code example for this. For the next person who has the same question as me, here is an example of how to do this. (You'll need the `tensorflow_serving package` for this; `pip install tensorflow-serving-api`). Based on this pull request (which at th...
If you're using the method described in [this answer](https://stackoverflow.com/a/65519903/10999642), please note that you're actually launching multiple tensorflow model server instances instead of a single model server, effectively making the servers compete for resources instead of working together to optimize tail ...
54,440,762
I'm busy configuring a TensorFlow Serving client that asks a TensorFlow Serving server to produce predictions on a given input image, for a given model. If the model being requested has not yet been served, it is downloaded from a remote URL to a folder where the server's models are located. (The client does this). At...
2019/01/30
[ "https://Stackoverflow.com/questions/54440762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/141789/" ]
So it took me ages of trawling through pull requests to finally find a code example for this. For the next person who has the same question as me, here is an example of how to do this. (You'll need the `tensorflow_serving package` for this; `pip install tensorflow-serving-api`). Based on this pull request (which at th...
While the solutions mentioned here works fine, there is one more method that you can use to hot-reload your models. You can use `--model_config_file_poll_wait_seconds` As mentioned here in the [documentation](https://www.tensorflow.org/tfx/serving/serving_config#reloading_model_server_configuration) - > > By setting...
54,440,762
I'm busy configuring a TensorFlow Serving client that asks a TensorFlow Serving server to produce predictions on a given input image, for a given model. If the model being requested has not yet been served, it is downloaded from a remote URL to a folder where the server's models are located. (The client does this). At...
2019/01/30
[ "https://Stackoverflow.com/questions/54440762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/141789/" ]
**Add a model** to TF Serving server and to the existing config file `conf_filepath`: Use arguments `name`, `base_path`, `model_platform` for the new model. Keeps the original models intact. Notice a small difference from @Karl 's answer - using `MergeFrom` instead of `CopyFrom` > > pip install tensorflow-serving-ap...
If you're using the method described in [this answer](https://stackoverflow.com/a/65519903/10999642), please note that you're actually launching multiple tensorflow model server instances instead of a single model server, effectively making the servers compete for resources instead of working together to optimize tail ...
54,440,762
I'm busy configuring a TensorFlow Serving client that asks a TensorFlow Serving server to produce predictions on a given input image, for a given model. If the model being requested has not yet been served, it is downloaded from a remote URL to a folder where the server's models are located. (The client does this). At...
2019/01/30
[ "https://Stackoverflow.com/questions/54440762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/141789/" ]
**Add a model** to TF Serving server and to the existing config file `conf_filepath`: Use arguments `name`, `base_path`, `model_platform` for the new model. Keeps the original models intact. Notice a small difference from @Karl 's answer - using `MergeFrom` instead of `CopyFrom` > > pip install tensorflow-serving-ap...
While the solutions mentioned here works fine, there is one more method that you can use to hot-reload your models. You can use `--model_config_file_poll_wait_seconds` As mentioned here in the [documentation](https://www.tensorflow.org/tfx/serving/serving_config#reloading_model_server_configuration) - > > By setting...
54,440,762
I'm busy configuring a TensorFlow Serving client that asks a TensorFlow Serving server to produce predictions on a given input image, for a given model. If the model being requested has not yet been served, it is downloaded from a remote URL to a folder where the server's models are located. (The client does this). At...
2019/01/30
[ "https://Stackoverflow.com/questions/54440762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/141789/" ]
While the solutions mentioned here works fine, there is one more method that you can use to hot-reload your models. You can use `--model_config_file_poll_wait_seconds` As mentioned here in the [documentation](https://www.tensorflow.org/tfx/serving/serving_config#reloading_model_server_configuration) - > > By setting...
If you're using the method described in [this answer](https://stackoverflow.com/a/65519903/10999642), please note that you're actually launching multiple tensorflow model server instances instead of a single model server, effectively making the servers compete for resources instead of working together to optimize tail ...
10,496,815
I have written a job server that runs 1 or more jobs concurrently (or simultaneously depending on the number of CPUs on the system). A lot of the jobs created connect to a SQL Server database, perform a query, fetch the results and write the results to a CSV file. For these types of jobs I use `pyodbc` and Microsoft SQ...
2012/05/08
[ "https://Stackoverflow.com/questions/10496815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1328695/" ]
I had a very similar problem and in my case the solution was to upgrade the ODBC driver on the machine I was trying to make the connection from. I'm afraid I don't know much about why that fixed the problem. I suspect something was changed or upgraded on the database server I was trying to connect to. This answer migh...
I also encounter this problem recently. My config includes unixODBC-2.3.0 plus MS ODBC Driver 1.0 for Linux. After some experiments, we speculate that the problem may arise due to database upgrade (to SQLServer 2008 SP1 in our case), thus triggering some bugs in the MS ODBC driver. The problem also occurs in this threa...
10,496,815
I have written a job server that runs 1 or more jobs concurrently (or simultaneously depending on the number of CPUs on the system). A lot of the jobs created connect to a SQL Server database, perform a query, fetch the results and write the results to a CSV file. For these types of jobs I use `pyodbc` and Microsoft SQ...
2012/05/08
[ "https://Stackoverflow.com/questions/10496815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1328695/" ]
I cannot detail the specifics of the underlying mechanics behind this problem. I can however say that the problem was being caused by using the Queue class in python's multiprocessing module. Whether I was implementing this Queue correctly remains unanswered but it appears the queue was not terminating the sub process ...
I also encounter this problem recently. My config includes unixODBC-2.3.0 plus MS ODBC Driver 1.0 for Linux. After some experiments, we speculate that the problem may arise due to database upgrade (to SQLServer 2008 SP1 in our case), thus triggering some bugs in the MS ODBC driver. The problem also occurs in this threa...
57,465,747
I do the following operations: 1. Convert string datetime in pandas dataframe to python datetime via `apply(strptime)` 2. Convert `datetime` to posix timestamp via `.timestamp()` method 3. If I revert posix back to `datetime` with `.fromtimestamp()` I obtain different datetime It differs by 3 hours which is my timezo...
2019/08/12
[ "https://Stackoverflow.com/questions/57465747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5331908/" ]
First, I suggest using the `np.timedelta64` dtype when working with `pandas`. In this case it makes the reciprocity simple. ``` pd.to_datetime('2018-03-03 14:30:00').value #1520087400000000000 pd.to_datetime(pd.to_datetime('2018-03-03 14:30:00').value) #Timestamp('2018-03-03 14:30:00') ``` The issue with the other ...
An answer with the [`to_datetime`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html) function: ```py df = pd.DataFrame(['2018-03-03 14:30:00'], columns=['c']) df['c'] = pd.to_datetime(df['c'].values, dayfirst=False).tz_localize('Your/Timezone') ``` When working with date, you should...