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
65,390,129
I create a virtual environment; let's say test\_venv, and I activate it. All successful. HOWEVER, the path of the Python Interpreter doesn't not change. I have illustrated the situation below. For clarification, the python path SHOULD BE `~/Desktop/test_venv/bin/python`. ``` >>> python3 -m venv Desktop/test_venv >>...
2020/12/21
[ "https://Stackoverflow.com/questions/65390129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14392583/" ]
#### *Please make sure to read Note #2.* --- **This is what you should do if you don't want to create a new virtual environment**: In `venv/bin` folder there are 3 files that store your venv path explicitly and if the path is wrong they take the normal python path so you should change the path there to your new path...
Check the value of VIRTUAL\_ENV in /venv/bin/activate . If you renamed your project directory or moved it, then the value may still be the old value. PyCharm doesn't update your venv files if you used PyCharm to rename the project. You can delete the venv and recreate a new one if the path is wrong, or try the answer t...
55,378,150
I have a r Script with the code: ``` args = commandArgs(trailingOnly=TRUE) myData <- read.csv(file=args[0]) ``` I want to run this using a GUI and deliver a choosen csv file with this python code ``` from tkinter import filedialog from tkinter import * import subprocess window = Tk() window.geometry('500x200') win...
2019/03/27
[ "https://Stackoverflow.com/questions/55378150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2377949/" ]
With Java 8 streams: ``` List<Accout> accounts = accounts.values().stream() .filter(account -> account.getBalance() > threshold) .collect(Collectors.toList()) ``` With `foreach`: ``` List<Account> accountsWithMinimum = new ArrayList<>(); for (Account acccount : accounts.values() ) { if (account....
From information you provided best solution seems to be change data from HashMap to [LinkedHashMap](https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html), that keep ordering. If you take a close took to javadoc, you can find following part useful: > > his implementation spares its clients from the ...
55,378,150
I have a r Script with the code: ``` args = commandArgs(trailingOnly=TRUE) myData <- read.csv(file=args[0]) ``` I want to run this using a GUI and deliver a choosen csv file with this python code ``` from tkinter import filedialog from tkinter import * import subprocess window = Tk() window.geometry('500x200') win...
2019/03/27
[ "https://Stackoverflow.com/questions/55378150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2377949/" ]
With Java 8 streams: ``` List<Accout> accounts = accounts.values().stream() .filter(account -> account.getBalance() > threshold) .collect(Collectors.toList()) ``` With `foreach`: ``` List<Account> accountsWithMinimum = new ArrayList<>(); for (Account acccount : accounts.values() ) { if (account....
The example you found predates the use of generics in Java. Any Map is these days actually a Map<K,V>, where K is the type (= the class) of the keys in the mapping, and V is the type (once again the java class) of the value objects the key values are mapped to. So the Map in your example (looking at what types the obje...
761,824
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
2009/04/17
[ "https://Stackoverflow.com/questions/761824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43056/" ]
The [Markdown](https://pypi.org/project/Markdown/) and [BeautifulSoup](https://pypi.org/project/beautifulsoup4/) (now called *beautifulsoup4*) modules will help do what you describe. Once you have converted the markdown to HTML, you can use a HTML parser to strip out the plain text. Your code might look something lik...
Commented and removed it because I finally think I see the rub here: It may be easier to convert your markdown text to HTML and remove HTML from the text. I'm not aware of anything to remove markdown from text effectively but there are many HTML to plain text solutions.
761,824
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
2009/04/17
[ "https://Stackoverflow.com/questions/761824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43056/" ]
The [Markdown](https://pypi.org/project/Markdown/) and [BeautifulSoup](https://pypi.org/project/beautifulsoup4/) (now called *beautifulsoup4*) modules will help do what you describe. Once you have converted the markdown to HTML, you can use a HTML parser to strip out the plain text. Your code might look something lik...
Despite the fact that this is a very old question, I'd like to suggest a solution I came up with recently. This one neither uses BeautifulSoup nor has an overhead of converting to html and back. The **markdown** module core class Markdown has a property **output\_formats** which is not configurable but otherwise patch...
761,824
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
2009/04/17
[ "https://Stackoverflow.com/questions/761824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43056/" ]
The [Markdown](https://pypi.org/project/Markdown/) and [BeautifulSoup](https://pypi.org/project/beautifulsoup4/) (now called *beautifulsoup4*) modules will help do what you describe. Once you have converted the markdown to HTML, you can use a HTML parser to strip out the plain text. Your code might look something lik...
This is similar to Jason's answer, but handles comments correctly. ```py import markdown # pip install markdown from bs4 import BeautifulSoup # pip install beautifulsoup4 def md_to_text(md): html = markdown.markdown(md) soup = BeautifulSoup(html, features='html.parser') return soup.get_text() def example...
761,824
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
2009/04/17
[ "https://Stackoverflow.com/questions/761824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43056/" ]
The [Markdown](https://pypi.org/project/Markdown/) and [BeautifulSoup](https://pypi.org/project/beautifulsoup4/) (now called *beautifulsoup4*) modules will help do what you describe. Once you have converted the markdown to HTML, you can use a HTML parser to strip out the plain text. Your code might look something lik...
I came here while searching for a way to perform s.c. [GitLab Releases](https://docs.gitlab.com/ee/user/project/releases/) via [API call](https://docs.gitlab.com/ee/api/releases/). I hope this matches the use case of the original questioner. I decoded markdown to plain text (including whitespaces in the form of `\n` e...
761,824
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
2009/04/17
[ "https://Stackoverflow.com/questions/761824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43056/" ]
Despite the fact that this is a very old question, I'd like to suggest a solution I came up with recently. This one neither uses BeautifulSoup nor has an overhead of converting to html and back. The **markdown** module core class Markdown has a property **output\_formats** which is not configurable but otherwise patch...
Commented and removed it because I finally think I see the rub here: It may be easier to convert your markdown text to HTML and remove HTML from the text. I'm not aware of anything to remove markdown from text effectively but there are many HTML to plain text solutions.
761,824
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
2009/04/17
[ "https://Stackoverflow.com/questions/761824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43056/" ]
This is similar to Jason's answer, but handles comments correctly. ```py import markdown # pip install markdown from bs4 import BeautifulSoup # pip install beautifulsoup4 def md_to_text(md): html = markdown.markdown(md) soup = BeautifulSoup(html, features='html.parser') return soup.get_text() def example...
Commented and removed it because I finally think I see the rub here: It may be easier to convert your markdown text to HTML and remove HTML from the text. I'm not aware of anything to remove markdown from text effectively but there are many HTML to plain text solutions.
761,824
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
2009/04/17
[ "https://Stackoverflow.com/questions/761824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43056/" ]
Commented and removed it because I finally think I see the rub here: It may be easier to convert your markdown text to HTML and remove HTML from the text. I'm not aware of anything to remove markdown from text effectively but there are many HTML to plain text solutions.
I came here while searching for a way to perform s.c. [GitLab Releases](https://docs.gitlab.com/ee/user/project/releases/) via [API call](https://docs.gitlab.com/ee/api/releases/). I hope this matches the use case of the original questioner. I decoded markdown to plain text (including whitespaces in the form of `\n` e...
761,824
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
2009/04/17
[ "https://Stackoverflow.com/questions/761824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43056/" ]
Despite the fact that this is a very old question, I'd like to suggest a solution I came up with recently. This one neither uses BeautifulSoup nor has an overhead of converting to html and back. The **markdown** module core class Markdown has a property **output\_formats** which is not configurable but otherwise patch...
This is similar to Jason's answer, but handles comments correctly. ```py import markdown # pip install markdown from bs4 import BeautifulSoup # pip install beautifulsoup4 def md_to_text(md): html = markdown.markdown(md) soup = BeautifulSoup(html, features='html.parser') return soup.get_text() def example...
761,824
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
2009/04/17
[ "https://Stackoverflow.com/questions/761824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43056/" ]
Despite the fact that this is a very old question, I'd like to suggest a solution I came up with recently. This one neither uses BeautifulSoup nor has an overhead of converting to html and back. The **markdown** module core class Markdown has a property **output\_formats** which is not configurable but otherwise patch...
I came here while searching for a way to perform s.c. [GitLab Releases](https://docs.gitlab.com/ee/user/project/releases/) via [API call](https://docs.gitlab.com/ee/api/releases/). I hope this matches the use case of the original questioner. I decoded markdown to plain text (including whitespaces in the form of `\n` e...
761,824
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
2009/04/17
[ "https://Stackoverflow.com/questions/761824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43056/" ]
This is similar to Jason's answer, but handles comments correctly. ```py import markdown # pip install markdown from bs4 import BeautifulSoup # pip install beautifulsoup4 def md_to_text(md): html = markdown.markdown(md) soup = BeautifulSoup(html, features='html.parser') return soup.get_text() def example...
I came here while searching for a way to perform s.c. [GitLab Releases](https://docs.gitlab.com/ee/user/project/releases/) via [API call](https://docs.gitlab.com/ee/api/releases/). I hope this matches the use case of the original questioner. I decoded markdown to plain text (including whitespaces in the form of `\n` e...
53,264,593
I have been trying this code to get a random seed, but it always fails. ``` import string import random import time import sys from random import seed possibleCharacters = string.ascii_lowercase + string.digits + string.ascii_uppercase + ' .,!?;:' target = input("Enter text: ") attemptThis = ''.join(random.choice...
2018/11/12
[ "https://Stackoverflow.com/questions/53264593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9199123/" ]
The `random.seed()` function always returns `None` but `time.sleep()` needs a number (the number of seconds to sleep). try `random.randint()` instead to generate a random integer: ``` import random time.sleep(random.randint(1, 50)) ```
Use also `random.randint(a, b)` function - to generate random integer number. `seed` function just initializes random numbers generator.
53,264,593
I have been trying this code to get a random seed, but it always fails. ``` import string import random import time import sys from random import seed possibleCharacters = string.ascii_lowercase + string.digits + string.ascii_uppercase + ' .,!?;:' target = input("Enter text: ") attemptThis = ''.join(random.choice...
2018/11/12
[ "https://Stackoverflow.com/questions/53264593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9199123/" ]
The `random.seed()` function always returns `None` but `time.sleep()` needs a number (the number of seconds to sleep). try `random.randint()` instead to generate a random integer: ``` import random time.sleep(random.randint(1, 50)) ```
The type of seed is None and the time.sleep() expects an integer. To send a random integer as a parameter for sleep you can try: ``` time.sleep(random.randint(1, 60)) ``` You need to import randim libraby for this.
50,073,779
I am aware that [re.search(pattns,text)][1] in python method takes a regular expression pattern and a string and searches for that pattern within the string. If the search is successful, search() returns a match object or None otherwise. My problem however is, am trying to implement this using OOP (class) i want to re...
2018/04/28
[ "https://Stackoverflow.com/questions/50073779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4209906/" ]
The output of `re.search` returns a match object. It tells you whether the regex matches the string. You should identify the group to retrieve string from the match like so: ``` if result: return result.group(0) ``` Replace `return result` in your code with above code snippet. If you are not sure how [`group...
First, there is a subtle *bug* in your code: ``` def __bool__(self): for pattern in self.patterns: result = re.search(pattern,self.text) return result ``` As you return the result of the searched pattern at the end of the first iteration, others patterns are simply ignored. You probaly want someth...
44,262,833
I am facing some error while using classes in python 2.7 My class definition is: ``` class Timer(object): def __init__(self): self.msg = "" def start(self,msg): self.msg = msg self.start = time.time() def stop(self): t = time.time() - self.start return self.msg,...
2017/05/30
[ "https://Stackoverflow.com/questions/44262833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2450212/" ]
When you write `self.start = time.time()`, you replace the function `start()` with a variable named `start`, which has a float value. The next time you write `timer.start()`, start is a float, and you are trying to call it as a function. Just replace the name `self.start` with something else.
I think the problem is that you are using the same name for a method and for an attribute. I would refactor it like this: ``` class Timer(object): def __init__(self): self.msg = "" self.start_time = None #I prefer to declare it but you can avoid this def start(self,msg): self.msg = m...
44,262,833
I am facing some error while using classes in python 2.7 My class definition is: ``` class Timer(object): def __init__(self): self.msg = "" def start(self,msg): self.msg = msg self.start = time.time() def stop(self): t = time.time() - self.start return self.msg,...
2017/05/30
[ "https://Stackoverflow.com/questions/44262833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2450212/" ]
When you write `self.start = time.time()`, you replace the function `start()` with a variable named `start`, which has a float value. The next time you write `timer.start()`, start is a float, and you are trying to call it as a function. Just replace the name `self.start` with something else.
I think now I understood your question and error, the following correct your issue: ``` import time class Timer(object): def __init__(self): self.msg = "" def start(self,msg): self.msg = msg self.start = time.time() # Here, your method name is the same has the variable name ``` If you rename...
44,262,833
I am facing some error while using classes in python 2.7 My class definition is: ``` class Timer(object): def __init__(self): self.msg = "" def start(self,msg): self.msg = msg self.start = time.time() def stop(self): t = time.time() - self.start return self.msg,...
2017/05/30
[ "https://Stackoverflow.com/questions/44262833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2450212/" ]
I think the problem is that you are using the same name for a method and for an attribute. I would refactor it like this: ``` class Timer(object): def __init__(self): self.msg = "" self.start_time = None #I prefer to declare it but you can avoid this def start(self,msg): self.msg = m...
I think now I understood your question and error, the following correct your issue: ``` import time class Timer(object): def __init__(self): self.msg = "" def start(self,msg): self.msg = msg self.start = time.time() # Here, your method name is the same has the variable name ``` If you rename...
52,743,872
I have been creating a game where an image moves according to player input with Keydown and Keyup methods. I want to add boundaries so that the user cannot move the image/character out of the display (I dont want a game over kind of thing if boundary is hit, just that the image/character wont be able to move past that ...
2018/10/10
[ "https://Stackoverflow.com/questions/52743872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10366920/" ]
**Root cause:** Your result is an array but your test is verifying an object. Thus, the postman will throw the exception since it could not compare. **Solution:** Use exactly value of an item in the list with if else command to compare. ``` var arr = pm.response.json(); console.log(arr.length) for (var i = 0; i < a...
You could also just do this: ``` pm.test('Check the response body properties', () => { _.each(pm.response.json(), (item) => { pm.expect(item.Verified).to.be.true pm.expect(item.VerifiedDate).to.be.a('string').and.match(/^\d{4}-\d{2}-\d{2}$/) }) }) ``` The check will do a few things for you, i...
61,924,960
I am querying (via sqlalchemy) *my\_table* with a conditional on a column and then retrieve distinct values in another column. Quite simply ``` selection_1 = session.query(func.distinct(my_table.col2)).\ filter(my_table.col1 == value1) ``` I need to do this repeatedly to get distinct values from different column...
2020/05/21
[ "https://Stackoverflow.com/questions/61924960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13583344/" ]
You don't really need a special class for this. Your existing code ``` selection_2 = session.query(func.distinct(my_table.col3)).\ filter(my_table.col1 == value1).\ filter(my_table.col2 == value2) ``` works because `filter` is returning a *new* query based on the original query, but with an additional filter...
For your `add_filter()` function to work as intended, you need your `set_distinct_col()` function to return a reference to itself (*an instance of `QueryProcessor`*). [`session.query()`](https://docs.sqlalchemy.org/en/13/orm/session_api.html#sqlalchemy.orm.session.Session.query) returns a `Query` object which doesn'...
30,909,627
I am tried to create a slice in django template and get an attribute. How can i do in django template something like this: python code: ``` somelist[1].name ``` please help
2015/06/18
[ "https://Stackoverflow.com/questions/30909627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3520178/" ]
If you are accessing a single element of a list, you don't need the `slice` filter, just use the dot notation. ``` {{ somelist.1.name }} ``` See [the docs](https://docs.djangoproject.com/en/1.8/ref/templates/language/#variables) for more info.
You can use the built-in tag [`slice`](https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#slice) with a combination of [`with`](https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#with): ``` {% with somelist|slice:"1" as item %} {{ item.name }} {% endwith %} ```
49,913,084
All, I am trying to build a Docker image to run my python 2 App within an embedded system which has OS yocto. Since the embedded system has limited flash, I want to have a small Docker image. However, after I install all the python and other packages, I get an image with 730M, which is too big for me. I don't know how...
2018/04/19
[ "https://Stackoverflow.com/questions/49913084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227199/" ]
**Q:** How to reduce the size of my docker image? **A:** There are a few ways you can do this. The most prominent thing I can immediately spot from your Dockerfile is that you are installing packages using individual `RUN` command. While this can make your code look a bit cleaner but each `RUN` statement is an overhe...
You can use docker history command to see which layer is causing more disk space addition. ``` docker@default:~Example>> docker history {image-name}:{image-tag} docker@default:~$ docker history mysql IMAGE CREATED CREATED BY SIZE COMMENT 519...
54,419,118
I am trying to extract table from a PPT using `python-pptx`, however, the I am not sure how do I that using `shape.table`. ``` from pptx import Presentation prs = Presentation(path_to_presentation) # text_runs will be populated with a list of strings, # one for each text run in presentation text_runs = [] for slide in...
2019/01/29
[ "https://Stackoverflow.com/questions/54419118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1479974/" ]
This appears to work for me. ``` prs = Presentation((path_to_presentation)) # text_runs will be populated with a list of strings, # one for each text run in presentation text_runs = [] for slide in prs.slides: for shape in slide.shapes: if not shape.has_table: continue tbl = shape....
To read the values present inside ppt | This code worked for me ``` slide = Deck.slides[1] table = slide.shapes[1].table for r in range(0,len(table.rows)): for c in range(2,len(table.columns)): cell_value = (table.cell(r,c)).text_frame.text print(cell_value) ```
68,173,157
i have a List a ``` a = [["v1_0001.jpg","v1_00015.jpg","v1_0002.jpg"],["v2_0001.jpg","v2_0002.jpg","v2_00015.jpg"]] ``` i want to concatenate these list of list in one list and sort list by alphanumeric While i am try to sort concatenation list ``` ['v1_0001.jpg', 'v1_00015.jpg', 'v1_0002.jpg','v2_0001.jpg' 'v2_00...
2021/06/29
[ "https://Stackoverflow.com/questions/68173157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use `chain` from `itertools`, as so - ``` from itertools import chain a = [[0, 15, 30, 45, 75, 105],[0, 15, 30, 45, 75, 105]] b = list(chain(*a)) print(b) # [0, 15, 30, 45, 75, 105,0, 15, 30, 45, 75, 105] ```
Here is one way. You can do it with recursion ``` solution : ``` ``` import itertools a = [[0, 15, 30, 45, 75, 105],[0, 15, 30, 45, 75, 105]] print(list(itertools.chain.from_iterable(a))) ```
68,173,157
i have a List a ``` a = [["v1_0001.jpg","v1_00015.jpg","v1_0002.jpg"],["v2_0001.jpg","v2_0002.jpg","v2_00015.jpg"]] ``` i want to concatenate these list of list in one list and sort list by alphanumeric While i am try to sort concatenation list ``` ['v1_0001.jpg', 'v1_00015.jpg', 'v1_0002.jpg','v2_0001.jpg' 'v2_00...
2021/06/29
[ "https://Stackoverflow.com/questions/68173157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use `chain` from `itertools`, as so - ``` from itertools import chain a = [[0, 15, 30, 45, 75, 105],[0, 15, 30, 45, 75, 105]] b = list(chain(*a)) print(b) # [0, 15, 30, 45, 75, 105,0, 15, 30, 45, 75, 105] ```
Maybe this is not the best to use in big lists but for understanding the logic might be good: ``` >>> a = [[0, 15, 30, 45, 75, 105],[0, 15, 30, 45, 75, 105]] >>> b = [] # Creates an empty list >>> for list_inside_a in a: # For every list in a ... b+= list_inside_a # Concatenates n-th list with b ... >>> b [0, 1...
37,090,675
I am working with canbus in python (Pcan basic api) and would like to make it easier to use. Via the bus a lot of devices/modules are connected. They are all allowed to send data, if a collison would happen the lowest ID will win. The data Is organized in frames with ID, SubID, hexvalues To illustrate the problem ...
2016/05/07
[ "https://Stackoverflow.com/questions/37090675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Using the [python-can](https://bitbucket.org/hardbyte/python-can/) library will get you the networking thread - giving you a buffered queue of incoming messages. The library supports the PCAN interface among others. Then you would create a middle-ware layer that converts and routes these `can.Message` types into pyqt ...
``` class MySimpleCanBus: def parse_message(self,raw_message): return MyMessageClass._create(*struct.unpack(FRAME_FORMAT,msg)) def recieve_message(self,filter_data): #code to recieve and parse a message(filtered by id) raw = canbus.recv(FRAME_SIZE) return self.parse_m...
37,090,675
I am working with canbus in python (Pcan basic api) and would like to make it easier to use. Via the bus a lot of devices/modules are connected. They are all allowed to send data, if a collison would happen the lowest ID will win. The data Is organized in frames with ID, SubID, hexvalues To illustrate the problem ...
2016/05/07
[ "https://Stackoverflow.com/questions/37090675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Agree with @Hardbyte on the use of [python-can](https://pypi.python.org/pypi/python-can/). It's excellent. As far as messaging between app layers, I've had a lot of luck with [Zero MQ](http://zeromq.org/bindings:python) -- you can set up your modules as event based, from the canbus message event all the way through to...
``` class MySimpleCanBus: def parse_message(self,raw_message): return MyMessageClass._create(*struct.unpack(FRAME_FORMAT,msg)) def recieve_message(self,filter_data): #code to recieve and parse a message(filtered by id) raw = canbus.recv(FRAME_SIZE) return self.parse_m...
37,090,675
I am working with canbus in python (Pcan basic api) and would like to make it easier to use. Via the bus a lot of devices/modules are connected. They are all allowed to send data, if a collison would happen the lowest ID will win. The data Is organized in frames with ID, SubID, hexvalues To illustrate the problem ...
2016/05/07
[ "https://Stackoverflow.com/questions/37090675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Using the [python-can](https://bitbucket.org/hardbyte/python-can/) library will get you the networking thread - giving you a buffered queue of incoming messages. The library supports the PCAN interface among others. Then you would create a middle-ware layer that converts and routes these `can.Message` types into pyqt ...
Agree with @Hardbyte on the use of [python-can](https://pypi.python.org/pypi/python-can/). It's excellent. As far as messaging between app layers, I've had a lot of luck with [Zero MQ](http://zeromq.org/bindings:python) -- you can set up your modules as event based, from the canbus message event all the way through to...
41,033,115
I downloaded and installed datasheder using the below steps: ``` git clone https://github.com/bokeh/datashader.git cd datashader conda install -c bokeh --file requirements.txt python setup.py install ``` After that, I have run the code using terminal like `python data.py, but no graph is displayed; nothin is b...
2016/12/08
[ "https://Stackoverflow.com/questions/41033115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7113481/" ]
I haven't tried your code, but there is nothing in there that would actually display the image. Each shade() call creates an image in memory, but then nothing is done with it here. If you were in a Jupyter notebook environment and the shade() call were the last item in the cell, it would display automatically, but the ...
I was able to produce the plot one of the tf.shade in your code this way. ``` from datashader.utils import export_image img = tf.shade(canvas.points(df,'x','y',agg=reductions.count())) export_image(img=img, filename='test1', fmt=".png", export_path=".") ``` This is the plot in test1.png[![Points_plot](https://i.sta...
31,662,355
I am creating a simple GUI production calculator in python. I am using Tkinter and have a main frame with 10 tabs in it. I have created all the entries and functions do do the calculations we need and it all works. My problem is that i want these entries and labels on each tab line10 - line19. I could manually recreate...
2015/07/27
[ "https://Stackoverflow.com/questions/31662355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5111347/" ]
This can't be intentional, because it can't work. As you've seen, you can't create a table twice. You should delete one of the migrations, possibly merging from the one you delete into the other one. The only differences are the taggings\_count field and the indexes. There isn't enough to go on here to say whether you...
Get use to it. This error will happen often in the future. Usually, it happens when your migration failed in the middle, and for example your table was created, but later creation of indexes failed. Then when you are trying to rerun the migration the table already exists, and migration fails. There are several ways to...
31,662,355
I am creating a simple GUI production calculator in python. I am using Tkinter and have a main frame with 10 tabs in it. I have created all the entries and functions do do the calculations we need and it all works. My problem is that i want these entries and labels on each tab line10 - line19. I could manually recreate...
2015/07/27
[ "https://Stackoverflow.com/questions/31662355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5111347/" ]
This can't be intentional, because it can't work. As you've seen, you can't create a table twice. You should delete one of the migrations, possibly merging from the one you delete into the other one. The only differences are the taggings\_count field and the indexes. There isn't enough to go on here to say whether you...
ActsAsTaggable\* will sometimes install a duplicate migration (or near duplicate) when upgrading the gem. Is the db/schema.rb checked in to the repo? If so, the unchanged version (once you start migrating, it gets changed) will have the "right" settings and help you figure out which one to remove.
51,591,025
I have used Django 1.11.14, python 2.7 and win 7 to build a website which could let registered user to login. however, when I log in, some page display login link again when it should be logout link. main page ```html <!DOCTYPE html> <html lang="en"> <head> {% block title %}<title>xxxxx</title>{% endblock %} ...
2018/07/30
[ "https://Stackoverflow.com/questions/51591025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9669628/" ]
Instead of `render_to_response` you should use [`render`](https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#render) function. This make request available in template. ``` def get(self, request): form = xx[![enter image description here][1]][1]Form() FW_list = FW.objects.all().order_by('approve_time'...
You have missed the point of using class based views here. You should rarely, if ever, be defining `get` (or `post`). In this case you should only define `get_context_data` to add your FW\_list, and let the view handle creating the form and rendering the template. ``` def get_context_data(self, **kwargs): kwargs['...
9,072,175
fellow earthians. I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself. The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish. Then, that if you want to put something to the left of something else ...
2012/01/30
[ "https://Stackoverflow.com/questions/9072175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77804/" ]
It seems most others have not quite understood the gist of your post. I'll break it down for you: CSS positiong is complex because it was designed by many different groups of people over a long period of time, with various versions, and legacy compatibility issues. The first attempts were to keep things simple. Just...
Have you checked out this great book? <http://shop.oreilly.com/product/9781565926226.do> just kidding. I don't think you need an entire resource devoted to this one question. It's rather simple once it clicks. Think of CSS positioning as a way to position items either relatively to themsevels (wherever they fall o...
9,072,175
fellow earthians. I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself. The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish. Then, that if you want to put something to the left of something else ...
2012/01/30
[ "https://Stackoverflow.com/questions/9072175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77804/" ]
There's more to the positioning that just the position property. You need to understand how floats work as well. <http://coding.smashingmagazine.com/2009/10/19/the-mystery-of-css-float-property/> <http://coding.smashingmagazine.com/2007/05/01/css-float-theory-things-you-should-know/> These two articles should get y...
Have you checked out this great book? <http://shop.oreilly.com/product/9781565926226.do> just kidding. I don't think you need an entire resource devoted to this one question. It's rather simple once it clicks. Think of CSS positioning as a way to position items either relatively to themsevels (wherever they fall o...
9,072,175
fellow earthians. I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself. The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish. Then, that if you want to put something to the left of something else ...
2012/01/30
[ "https://Stackoverflow.com/questions/9072175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77804/" ]
It seems most others have not quite understood the gist of your post. I'll break it down for you: CSS positiong is complex because it was designed by many different groups of people over a long period of time, with various versions, and legacy compatibility issues. The first attempts were to keep things simple. Just...
These two courses from code academy should explain CSS positioning well: [First](http://www.codecademy.com/courses/50358c84b87e8f0002022429), [Second](http://www.codecademy.com/courses/advanced-css-positioning).
9,072,175
fellow earthians. I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself. The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish. Then, that if you want to put something to the left of something else ...
2012/01/30
[ "https://Stackoverflow.com/questions/9072175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77804/" ]
Positioning is easy to understand: `relative` positioning -- Render the page exactly as your normally would. Once done, anything with `relative` positioning gets moved, *relative to where it initially was*. Nothing else is affected. `absolute` positioning -- Removes the item from the page flow. Other things render as...
this link is mainly about z-index but IMO it does a pretty good job of explaining how things are positioned on a page <http://coding.smashingmagazine.com/2009/09/15/the-z-index-css-property-a-comprehensive-look/> This link is more focused on positioning but it is important to understand the z axis in order to unders...
9,072,175
fellow earthians. I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself. The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish. Then, that if you want to put something to the left of something else ...
2012/01/30
[ "https://Stackoverflow.com/questions/9072175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77804/" ]
Positioning is easy to understand: `relative` positioning -- Render the page exactly as your normally would. Once done, anything with `relative` positioning gets moved, *relative to where it initially was*. Nothing else is affected. `absolute` positioning -- Removes the item from the page flow. Other things render as...
These two courses from code academy should explain CSS positioning well: [First](http://www.codecademy.com/courses/50358c84b87e8f0002022429), [Second](http://www.codecademy.com/courses/advanced-css-positioning).
9,072,175
fellow earthians. I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself. The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish. Then, that if you want to put something to the left of something else ...
2012/01/30
[ "https://Stackoverflow.com/questions/9072175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77804/" ]
Positioning is easy to understand: `relative` positioning -- Render the page exactly as your normally would. Once done, anything with `relative` positioning gets moved, *relative to where it initially was*. Nothing else is affected. `absolute` positioning -- Removes the item from the page flow. Other things render as...
Have you checked out this great book? <http://shop.oreilly.com/product/9781565926226.do> just kidding. I don't think you need an entire resource devoted to this one question. It's rather simple once it clicks. Think of CSS positioning as a way to position items either relatively to themsevels (wherever they fall o...
9,072,175
fellow earthians. I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself. The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish. Then, that if you want to put something to the left of something else ...
2012/01/30
[ "https://Stackoverflow.com/questions/9072175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77804/" ]
Positioning is easy to understand: `relative` positioning -- Render the page exactly as your normally would. Once done, anything with `relative` positioning gets moved, *relative to where it initially was*. Nothing else is affected. `absolute` positioning -- Removes the item from the page flow. Other things render as...
There's more to the positioning that just the position property. You need to understand how floats work as well. <http://coding.smashingmagazine.com/2009/10/19/the-mystery-of-css-float-property/> <http://coding.smashingmagazine.com/2007/05/01/css-float-theory-things-you-should-know/> These two articles should get y...
9,072,175
fellow earthians. I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself. The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish. Then, that if you want to put something to the left of something else ...
2012/01/30
[ "https://Stackoverflow.com/questions/9072175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77804/" ]
There's more to the positioning that just the position property. You need to understand how floats work as well. <http://coding.smashingmagazine.com/2009/10/19/the-mystery-of-css-float-property/> <http://coding.smashingmagazine.com/2007/05/01/css-float-theory-things-you-should-know/> These two articles should get y...
this link is mainly about z-index but IMO it does a pretty good job of explaining how things are positioned on a page <http://coding.smashingmagazine.com/2009/09/15/the-z-index-css-property-a-comprehensive-look/> This link is more focused on positioning but it is important to understand the z axis in order to unders...
9,072,175
fellow earthians. I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself. The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish. Then, that if you want to put something to the left of something else ...
2012/01/30
[ "https://Stackoverflow.com/questions/9072175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77804/" ]
It seems most others have not quite understood the gist of your post. I'll break it down for you: CSS positiong is complex because it was designed by many different groups of people over a long period of time, with various versions, and legacy compatibility issues. The first attempts were to keep things simple. Just...
this link is mainly about z-index but IMO it does a pretty good job of explaining how things are positioned on a page <http://coding.smashingmagazine.com/2009/09/15/the-z-index-css-property-a-comprehensive-look/> This link is more focused on positioning but it is important to understand the z axis in order to unders...
9,072,175
fellow earthians. I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself. The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish. Then, that if you want to put something to the left of something else ...
2012/01/30
[ "https://Stackoverflow.com/questions/9072175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77804/" ]
It seems most others have not quite understood the gist of your post. I'll break it down for you: CSS positiong is complex because it was designed by many different groups of people over a long period of time, with various versions, and legacy compatibility issues. The first attempts were to keep things simple. Just...
Positioning is easy to understand: `relative` positioning -- Render the page exactly as your normally would. Once done, anything with `relative` positioning gets moved, *relative to where it initially was*. Nothing else is affected. `absolute` positioning -- Removes the item from the page flow. Other things render as...
25,237,039
I have some pickle files of deep learning models built on gpu. I'm trying to use them in production. But when i try to unpickle them on the server, i'm getting the following error. > > Traceback (most recent call last): > > File "score.py", line 30, in > > model = (cPickle.load(file)) > > File "/usr/loc...
2014/08/11
[ "https://Stackoverflow.com/questions/25237039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1505986/" ]
There is a script in pylearn2 which may do what you need: `pylearn2/scripts/gpu_pkl_to_cpu_pkl.py`
This works for me. Note: this doesn't work unless the following environment variable is set: `export THEANO_FLAGS='device=cpu'` ``` import os from pylearn2.utils import serial import pylearn2.config.yaml_parse as yaml_parse if __name__=="__main__": _, in_path, out_path = sys.argv os.environ['THEANO_FLAGS']="device=c...
25,237,039
I have some pickle files of deep learning models built on gpu. I'm trying to use them in production. But when i try to unpickle them on the server, i'm getting the following error. > > Traceback (most recent call last): > > File "score.py", line 30, in > > model = (cPickle.load(file)) > > File "/usr/loc...
2014/08/11
[ "https://Stackoverflow.com/questions/25237039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1505986/" ]
There is a script in pylearn2 which may do what you need: `pylearn2/scripts/gpu_pkl_to_cpu_pkl.py`
I solved this problem by just saving the parameters W & b, but not the whole model. You can save the parameters use this:<http://deeplearning.net/software/theano/tutorial/loading_and_saving.html?highlight=saving%20load#robust-serialization> This can save the CudaNdarray to numpy array. Then you need to read the params ...
25,237,039
I have some pickle files of deep learning models built on gpu. I'm trying to use them in production. But when i try to unpickle them on the server, i'm getting the following error. > > Traceback (most recent call last): > > File "score.py", line 30, in > > model = (cPickle.load(file)) > > File "/usr/loc...
2014/08/11
[ "https://Stackoverflow.com/questions/25237039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1505986/" ]
The related Theano code is [here](https://github.com/Theano/Theano/blob/master/theano/sandbox/cuda/type.py). From there, it looks like there is an option `config.experimental.unpickle_gpu_on_cpu` which you could set and which would make `CudaNdarray_unpickler` return the underlying raw Numpy array.
This works for me. Note: this doesn't work unless the following environment variable is set: `export THEANO_FLAGS='device=cpu'` ``` import os from pylearn2.utils import serial import pylearn2.config.yaml_parse as yaml_parse if __name__=="__main__": _, in_path, out_path = sys.argv os.environ['THEANO_FLAGS']="device=c...
25,237,039
I have some pickle files of deep learning models built on gpu. I'm trying to use them in production. But when i try to unpickle them on the server, i'm getting the following error. > > Traceback (most recent call last): > > File "score.py", line 30, in > > model = (cPickle.load(file)) > > File "/usr/loc...
2014/08/11
[ "https://Stackoverflow.com/questions/25237039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1505986/" ]
The related Theano code is [here](https://github.com/Theano/Theano/blob/master/theano/sandbox/cuda/type.py). From there, it looks like there is an option `config.experimental.unpickle_gpu_on_cpu` which you could set and which would make `CudaNdarray_unpickler` return the underlying raw Numpy array.
I solved this problem by just saving the parameters W & b, but not the whole model. You can save the parameters use this:<http://deeplearning.net/software/theano/tutorial/loading_and_saving.html?highlight=saving%20load#robust-serialization> This can save the CudaNdarray to numpy array. Then you need to read the params ...
25,237,039
I have some pickle files of deep learning models built on gpu. I'm trying to use them in production. But when i try to unpickle them on the server, i'm getting the following error. > > Traceback (most recent call last): > > File "score.py", line 30, in > > model = (cPickle.load(file)) > > File "/usr/loc...
2014/08/11
[ "https://Stackoverflow.com/questions/25237039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1505986/" ]
This works for me. Note: this doesn't work unless the following environment variable is set: `export THEANO_FLAGS='device=cpu'` ``` import os from pylearn2.utils import serial import pylearn2.config.yaml_parse as yaml_parse if __name__=="__main__": _, in_path, out_path = sys.argv os.environ['THEANO_FLAGS']="device=c...
I solved this problem by just saving the parameters W & b, but not the whole model. You can save the parameters use this:<http://deeplearning.net/software/theano/tutorial/loading_and_saving.html?highlight=saving%20load#robust-serialization> This can save the CudaNdarray to numpy array. Then you need to read the params ...
33,157,597
I am trying to install rasterio into my python environment and am getting the following errors. I can do ``` conda install rasterio ``` No error comes up on the install but I come up with the following error when I try to import ``` from rasterio._base import eval_window, window_shape, window_index Im...
2015/10/15
[ "https://Stackoverflow.com/questions/33157597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4812453/" ]
I would suggest trying the ioos anaconda recipe (<https://anaconda.org/ioos/rasterio>). `conda install -c https://conda.anaconda.org/ioos rasterio`. I have run into the same DLL issue you are seeing when trying to install more recent versions of rasterio using the standard anaconda version.
I had the same issue. A reinstall solved it. ``` conda install -f rasterio ```
33,157,597
I am trying to install rasterio into my python environment and am getting the following errors. I can do ``` conda install rasterio ``` No error comes up on the install but I come up with the following error when I try to import ``` from rasterio._base import eval_window, window_shape, window_index Im...
2015/10/15
[ "https://Stackoverflow.com/questions/33157597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4812453/" ]
I would suggest trying the ioos anaconda recipe (<https://anaconda.org/ioos/rasterio>). `conda install -c https://conda.anaconda.org/ioos rasterio`. I have run into the same DLL issue you are seeing when trying to install more recent versions of rasterio using the standard anaconda version.
If you're still having the issue. you can create a new conda enviroment using: ``` conda create -n envname ``` After that install using: `conda install -c conda-forge/label/dev rasterio`
33,157,597
I am trying to install rasterio into my python environment and am getting the following errors. I can do ``` conda install rasterio ``` No error comes up on the install but I come up with the following error when I try to import ``` from rasterio._base import eval_window, window_shape, window_index Im...
2015/10/15
[ "https://Stackoverflow.com/questions/33157597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4812453/" ]
I had the same issue. A reinstall solved it. ``` conda install -f rasterio ```
If you're still having the issue. you can create a new conda enviroment using: ``` conda create -n envname ``` After that install using: `conda install -c conda-forge/label/dev rasterio`
1,575,971
I'm making a stupid little game that saves your score in a highscores.txt file. My problem is sorting the lines. Here's what I have so far. Maybe an alphanumeric sorter for python would help? Thanks. ``` import os.path import string def main(): #Check if the file exists file_exists = os.path.exists("highs...
2009/10/16
[ "https://Stackoverflow.com/questions/1575971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/190983/" ]
after `words = f.readlines()`, try something like: ``` headers = words.pop(0) def myway(aline): i = 0 while aline[i].isdigit(): i += 1 score = int(aline[:i]) return score words.sort(key=myway, reverse=True) words.insert(0, headers) ``` The key (;-) idea is to make a function that returns the "sorting ...
Doing a simple string sort on your ``` new_score = str(score) + ".........." + name ``` items isn't going to work since, for example str(1000) < str(500). In other words, 1000 will come before 500 in an alphanumeric sort. Alex's answer is good in that it demonstrates the use of a sort key function, but here is ano...
1,575,971
I'm making a stupid little game that saves your score in a highscores.txt file. My problem is sorting the lines. Here's what I have so far. Maybe an alphanumeric sorter for python would help? Thanks. ``` import os.path import string def main(): #Check if the file exists file_exists = os.path.exists("highs...
2009/10/16
[ "https://Stackoverflow.com/questions/1575971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/190983/" ]
after `words = f.readlines()`, try something like: ``` headers = words.pop(0) def myway(aline): i = 0 while aline[i].isdigit(): i += 1 score = int(aline[:i]) return score words.sort(key=myway, reverse=True) words.insert(0, headers) ``` The key (;-) idea is to make a function that returns the "sorting ...
I guess something went wrong when you pasted from Alex's answer, so here is your code with a sort in there ``` import os.path def main(): #Check if the file exists file_exists = os.path.exists("highscores.txt") score = 500 name = "Nicholas" #If the file doesn't exist, create one with the high s...
1,575,971
I'm making a stupid little game that saves your score in a highscores.txt file. My problem is sorting the lines. Here's what I have so far. Maybe an alphanumeric sorter for python would help? Thanks. ``` import os.path import string def main(): #Check if the file exists file_exists = os.path.exists("highs...
2009/10/16
[ "https://Stackoverflow.com/questions/1575971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/190983/" ]
after `words = f.readlines()`, try something like: ``` headers = words.pop(0) def myway(aline): i = 0 while aline[i].isdigit(): i += 1 score = int(aline[:i]) return score words.sort(key=myway, reverse=True) words.insert(0, headers) ``` The key (;-) idea is to make a function that returns the "sorting ...
I'd like to encourage you to store your high scores in a more robust format. In particular I suggest JSON. ``` import simplejson as json # Python 2.x # import json # Python 3.x d = {} d["version"] = 1 d["highscores"] = [[100, "Steve"], [200, "Ken"], [400, "Denise"]] s = json.dumps(d) print s # prints: # {"version":...
1,575,971
I'm making a stupid little game that saves your score in a highscores.txt file. My problem is sorting the lines. Here's what I have so far. Maybe an alphanumeric sorter for python would help? Thanks. ``` import os.path import string def main(): #Check if the file exists file_exists = os.path.exists("highs...
2009/10/16
[ "https://Stackoverflow.com/questions/1575971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/190983/" ]
after `words = f.readlines()`, try something like: ``` headers = words.pop(0) def myway(aline): i = 0 while aline[i].isdigit(): i += 1 score = int(aline[:i]) return score words.sort(key=myway, reverse=True) words.insert(0, headers) ``` The key (;-) idea is to make a function that returns the "sorting ...
What you want is probably what's generally known as a "Natural Sort". Searching for "natural sort python" gives many results, but there's some good discussion on [ASPN](http://code.activestate.com/recipes/285264/).
1,575,971
I'm making a stupid little game that saves your score in a highscores.txt file. My problem is sorting the lines. Here's what I have so far. Maybe an alphanumeric sorter for python would help? Thanks. ``` import os.path import string def main(): #Check if the file exists file_exists = os.path.exists("highs...
2009/10/16
[ "https://Stackoverflow.com/questions/1575971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/190983/" ]
I'd like to encourage you to store your high scores in a more robust format. In particular I suggest JSON. ``` import simplejson as json # Python 2.x # import json # Python 3.x d = {} d["version"] = 1 d["highscores"] = [[100, "Steve"], [200, "Ken"], [400, "Denise"]] s = json.dumps(d) print s # prints: # {"version":...
Doing a simple string sort on your ``` new_score = str(score) + ".........." + name ``` items isn't going to work since, for example str(1000) < str(500). In other words, 1000 will come before 500 in an alphanumeric sort. Alex's answer is good in that it demonstrates the use of a sort key function, but here is ano...
1,575,971
I'm making a stupid little game that saves your score in a highscores.txt file. My problem is sorting the lines. Here's what I have so far. Maybe an alphanumeric sorter for python would help? Thanks. ``` import os.path import string def main(): #Check if the file exists file_exists = os.path.exists("highs...
2009/10/16
[ "https://Stackoverflow.com/questions/1575971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/190983/" ]
I'd like to encourage you to store your high scores in a more robust format. In particular I suggest JSON. ``` import simplejson as json # Python 2.x # import json # Python 3.x d = {} d["version"] = 1 d["highscores"] = [[100, "Steve"], [200, "Ken"], [400, "Denise"]] s = json.dumps(d) print s # prints: # {"version":...
I guess something went wrong when you pasted from Alex's answer, so here is your code with a sort in there ``` import os.path def main(): #Check if the file exists file_exists = os.path.exists("highscores.txt") score = 500 name = "Nicholas" #If the file doesn't exist, create one with the high s...
1,575,971
I'm making a stupid little game that saves your score in a highscores.txt file. My problem is sorting the lines. Here's what I have so far. Maybe an alphanumeric sorter for python would help? Thanks. ``` import os.path import string def main(): #Check if the file exists file_exists = os.path.exists("highs...
2009/10/16
[ "https://Stackoverflow.com/questions/1575971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/190983/" ]
I'd like to encourage you to store your high scores in a more robust format. In particular I suggest JSON. ``` import simplejson as json # Python 2.x # import json # Python 3.x d = {} d["version"] = 1 d["highscores"] = [[100, "Steve"], [200, "Ken"], [400, "Denise"]] s = json.dumps(d) print s # prints: # {"version":...
What you want is probably what's generally known as a "Natural Sort". Searching for "natural sort python" gives many results, but there's some good discussion on [ASPN](http://code.activestate.com/recipes/285264/).
26,645,502
The code is self-explained... ``` $ python3 Python 3.4.0 (default, Apr 11 2014, 13:05:18) [GCC 4.8.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import urllib.request as req >>> url = 'http://bangladeshbrands.com/342560550782-44083.html' >>> res = req.urlopen(url) >>> html = r...
2014/10/30
[ "https://Stackoverflow.com/questions/26645502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/907044/" ]
You need to give the dataset name and table name I am going to give you code which is work on my Machine Correctly ``` Dim ds As New DataSet Dim dt As New DataTable Dim RpDs1 As New Microsoft.Reporting.WinForms.ReportDataSource Dim SQL As String = "select * from mfcount" Dim da As New OleDbDataAdapte...
thanks basuraj kumbhar for your help to solve this problem. Here is the working codes for MyCql connection Report in vb.net ``` Dim ds As New DataSet Dim dt As New DataTable Dim RpDs1 As New Microsoft.Reporting.WinForms.ReportDataSource Dim SQL As String = "select * from tb_course" Dim da As New MySqlD...
38,703,423
I have been scouring the internet looking for the answer to this. Please not my python coding skills are not all that great. I am trying to create a command line script that will take the input from the command line like this: ``` $python GetHostID.py serverName.com ``` the last part is what I am wanting to pass ...
2016/08/01
[ "https://Stackoverflow.com/questions/38703423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6664141/" ]
The command line arguments are available as the list `sys.argv`, whose first element is the path to the program. There are a number of libraries you can use (argparse, optparse, etc.) to analyse the command line, but for your simple application you could do something like this: ``` import sys import sys, os import opt...
os.getenv('remoteserver') does not use the variable remoteserver as an argument. Instead it uses a string 'remoteserver'. Also, are you trying to take input as a command line argument? Or are you trying to take it as user input? Your problem description and implementation differ here. The easiest way would be to run y...
38,703,423
I have been scouring the internet looking for the answer to this. Please not my python coding skills are not all that great. I am trying to create a command line script that will take the input from the command line like this: ``` $python GetHostID.py serverName.com ``` the last part is what I am wanting to pass ...
2016/08/01
[ "https://Stackoverflow.com/questions/38703423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6664141/" ]
The command line arguments are available as the list `sys.argv`, whose first element is the path to the program. There are a number of libraries you can use (argparse, optparse, etc.) to analyse the command line, but for your simple application you could do something like this: ``` import sys import sys, os import opt...
you can use [sys.argv](https://docs.python.org/3/library/sys.html#sys.argv) for ``` $python GetHostID.py serverName.com ``` `sys.argv` would be ``` ['GetHostID.py', 'serverName.com'] ``` but for being friendly to the user have a look at the [argparse Tutorial](https://docs.python.org/3/howto/argparse.html)
38,703,423
I have been scouring the internet looking for the answer to this. Please not my python coding skills are not all that great. I am trying to create a command line script that will take the input from the command line like this: ``` $python GetHostID.py serverName.com ``` the last part is what I am wanting to pass ...
2016/08/01
[ "https://Stackoverflow.com/questions/38703423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6664141/" ]
The command line arguments are available as the list `sys.argv`, whose first element is the path to the program. There are a number of libraries you can use (argparse, optparse, etc.) to analyse the command line, but for your simple application you could do something like this: ``` import sys import sys, os import opt...
In Python 2, `input` reads text *and evaluates it as a Python expression in the current context*. This is almost never what you want; you want `raw_input` instead. However, in Python 3, `input` does what `raw_input` did in version 2, and `raw_input` is not available. So, if you need your code to work in *both* Python ...
38,897,842
I have an app running on AWS and I need to save every "event" in a file. An "event" happens, for instance, when a user logs in to the app. When that happens I need to save this information on a file (presumably I would need to save a time stamp and the session id) I expect to have a lot of events (of the order of a mi...
2016/08/11
[ "https://Stackoverflow.com/questions/38897842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/863713/" ]
The `.*` in the lookaheads checks for the letter presence not only in the adjacent word, but later in the string. Use `[a-zA-Z]*`: ``` echo "hello 123 worLD" | grep -oP "\\b(?=[A-Za-z]*[a-z])(?=[A-Za-z]*[A-Z])[a-zA-Z]+" ``` See the [demo online](https://ideone.com/aGaXTA) I also added a word boundary `\b` at the st...
**Answer:** ``` echo "hello 123 worLD" | grep -oP "\b(?=[A-Z]+[a-z]|[a-z]+[A-Z])[a-zA-Z]*" ``` Demo: <https://ideone.com/HjLH5o> **Explanation:** First check if word starts with one or more uppercase letters followed by one lowercase letters or vice versa followed by any number of lowercase and uppercase letters ...
3,124,229
I'm trying to take a screenshot of the entire screen with C and GTK. I don't want to make a call to an external application for speed reasons. I've found Python code for this ([Take a screenshot via a python script. [Linux]](https://stackoverflow.com/questions/69645/take-a-screenshot-via-a-python-script-linux/782768#78...
2010/06/26
[ "https://Stackoverflow.com/questions/3124229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/287750/" ]
After looking at the GNOME-Screenshot code and a Python example, I came up with this: ``` GdkPixbuf * get_screenshot(){ GdkPixbuf *screenshot; GdkWindow *root_window; gint x_orig, y_orig; gint width, height; root_window = gdk_get_default_root_window (); gdk_drawable_get_size (root_window, &wid...
9 years passed and as mentioned above API is removed. As far as I understand, currently the bare minimum to do this at Linux is: ``` GdkWindow * root; GdkPixbuf * screenshot; gint x, y, width, height; root = gdk_get_default_root_window (); gdk_window_get_geometry (root, &x, &y, &width, &height); screenshot = gdk_pix...
6,457,102
I'm trying to load ~2GB of text files (approx 35K files) in my python script. I'm getting a memory error around a third of the way through on page.read(). I' ``` for f in files: page = open(f) pageContent = page.read().replace('\n', '') page.close() cFile_list.append(pageContent) ``` I've never deal...
2011/06/23
[ "https://Stackoverflow.com/questions/6457102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/812575/" ]
You are trying to load too much into memory at once. This can be because of the process size limit (especially on a 32 bit OS), or because you don't have enough RAM. A 64 bit OS (and 64 bit Python) would be able to do this ok given enough RAM, but maybe you can simply change the way your program is working so not ever...
Consider using generators, if possible in your case: ``` file_list = [] for file_ in files: file_list.append(line.replace('\n', '') for line in open(file_)) ``` file\_list now is a list of iterators which is more memory-efficient than reading the whole contents of each file into a string. As soon es you need the...
6,457,102
I'm trying to load ~2GB of text files (approx 35K files) in my python script. I'm getting a memory error around a third of the way through on page.read(). I' ``` for f in files: page = open(f) pageContent = page.read().replace('\n', '') page.close() cFile_list.append(pageContent) ``` I've never deal...
2011/06/23
[ "https://Stackoverflow.com/questions/6457102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/812575/" ]
You are trying to load too much into memory at once. This can be because of the process size limit (especially on a 32 bit OS), or because you don't have enough RAM. A 64 bit OS (and 64 bit Python) would be able to do this ok given enough RAM, but maybe you can simply change the way your program is working so not ever...
This is not effective way to read whole file in memory. Right way - get used to indexes. Firstly you need to complete dictionary with start position of each line (key is line number, and value – cumulated length of previous lines). ``` t = open(file,’r’) dict_pos = {} kolvo = 0 length = 0 for each in t: dict_po...
6,457,102
I'm trying to load ~2GB of text files (approx 35K files) in my python script. I'm getting a memory error around a third of the way through on page.read(). I' ``` for f in files: page = open(f) pageContent = page.read().replace('\n', '') page.close() cFile_list.append(pageContent) ``` I've never deal...
2011/06/23
[ "https://Stackoverflow.com/questions/6457102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/812575/" ]
Consider using generators, if possible in your case: ``` file_list = [] for file_ in files: file_list.append(line.replace('\n', '') for line in open(file_)) ``` file\_list now is a list of iterators which is more memory-efficient than reading the whole contents of each file into a string. As soon es you need the...
This is not effective way to read whole file in memory. Right way - get used to indexes. Firstly you need to complete dictionary with start position of each line (key is line number, and value – cumulated length of previous lines). ``` t = open(file,’r’) dict_pos = {} kolvo = 0 length = 0 for each in t: dict_po...
70,623,704
The following code: ``` from typing import Union def process(actions: Union[list[str], list[int]]) -> None: for pos, action in enumerate(actions): act(action) def act(action: Union[str, int]) -> None: print(action) ``` generates a mypy error: `Argument 1 to "act" has incompatible type "object"; ex...
2022/01/07
[ "https://Stackoverflow.com/questions/70623704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3139441/" ]
`enumerate.__next__` needs more context than is available to have a return type more specific than `Tuple[int, Any]`, so I believe `mypy` itself would need to be modified to make the inference that `enumerate(actions)` produces `Tuple[int,Union[str,int]]` values. Until that happens, you can explicitly cast the value o...
I don't know how it's affecting the types. I do know that using len() can work the same way. It is slower but if it solves the problem it might be worth it. Sorry that it's not much help
70,623,704
The following code: ``` from typing import Union def process(actions: Union[list[str], list[int]]) -> None: for pos, action in enumerate(actions): act(action) def act(action: Union[str, int]) -> None: print(action) ``` generates a mypy error: `Argument 1 to "act" has incompatible type "object"; ex...
2022/01/07
[ "https://Stackoverflow.com/questions/70623704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3139441/" ]
`enumerate.__next__` needs more context than is available to have a return type more specific than `Tuple[int, Any]`, so I believe `mypy` itself would need to be modified to make the inference that `enumerate(actions)` produces `Tuple[int,Union[str,int]]` values. Until that happens, you can explicitly cast the value o...
Seems like mypy isn't able to infer the type and generalizes to object. Might be worth opening an issue at their side. As a workaround you could annotate 'action'. This would remove the error. Does it work if you import the (legacy) `List` from `typing`?
53,715,925
Greetings for the past week (or more) I've been struggling with a problem. **Scenario:** I am developing an app which will allow an expert to create a recipe using a provided image of something to be used as a base. The recipe consists of areas of interests. The program's purpose is to allow non experts to use it, pr...
2018/12/11
[ "https://Stackoverflow.com/questions/53715925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4789509/" ]
Your `DirectView` class must inherit from a `View` class in Django in order to use [`as_view`](https://docs.djangoproject.com/en/2.1/ref/class-based-views/base/#django.views.generic.base.View.as_view). ``` from django.views.generic import View class DirectView(mixins.CreateModelMixin, View): ``` If you're using the...
If we are looking into the [source code of **`mixins.CreateModelMixin`**](https://github.com/encode/django-rest-framework/blob/master/rest_framework/mixins.py#L14), we could see it's inherited from [**`object`**](https://stackoverflow.com/questions/4015417/python-class-inherits-object) (***builtin type***) and hence it...
69,108,130
I am trying to build a voice assistant. I am facing a problem with the playsound library. Please view my code snippet. ``` def respond(output): """ function to respond to user questions """ num=0 print(output) num += 1 response=gTTS(text=output, lang='en') file = str(num)+".mp3" res...
2021/09/08
[ "https://Stackoverflow.com/questions/69108130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16863358/" ]
Query * lookup with it self, join only with the type that the id=3 has. * empty join results => different type so they are filtered out [Test code here](https://mongoplayground.net/p/KnKpOBZYJy7) ```js db.collection.aggregate([ { "$lookup": { "from": "collection", "let": { "type": "$type" ...
You're basically mixing two separate queries: 1. Get an item by ID - returns a **single** item 2. Get a list of items, that have the same type as the type of the first item - returns a **list of items** Because of the difference of the queries, there's no super straightforward way to do so. Surely you can use [$aggre...
18,600,200
in python here is my multiprocessing setup. I subclassed the Process method and gave it a queue and some other fields for pickling/data purposes. This strategy works about 95% of the time, the other 5% for an unknown reason the queue just hangs and it never finishes (it's common that 3 of the 4 cores finish their job...
2013/09/03
[ "https://Stackoverflow.com/questions/18600200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1660802/" ]
Do a `time.sleep(0.001)` at the beginning of your `run()` method.
From my experience ``` time.sleep(0.001) ``` Is by far not long enough. I had a similar problem. It seems to happen if you call `get()` or `put()` on a queue "too early". I guess it somehow fails to initialize quick enough. Not entirely sure, but I'm speculating that it might have something to do with the ways a qu...
46,373,433
I am working in python, trying to be able to put in a data set (eg. (1, 6, 8) that returns a string (eg. 'NO+ F- NO+'). I think that maybe array is not the correct object. I want to be able to plug in large data sets (eg. (1, 1, 6, 1, ..., 8, 8, 6, 1) to return a string. ``` def protein(array): ligand = '' for...
2017/09/22
[ "https://Stackoverflow.com/questions/46373433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8658260/" ]
You probably want `def protein(*array):` This allows you to give in any number of arguments. You also must use `for i in array:` instead of `for i in range(array):`
If you call it like `protein(1, 6, 8)` you are **not** passing it a tuple: you pass it **three parameters**. Since you defined `protein` with *one* parameter: `array`, that errors. You can use arbitrary parameters, by using `*args`. But nevertheless this function is still not very elegant nor is it efficient: it will ...
46,373,433
I am working in python, trying to be able to put in a data set (eg. (1, 6, 8) that returns a string (eg. 'NO+ F- NO+'). I think that maybe array is not the correct object. I want to be able to plug in large data sets (eg. (1, 1, 6, 1, ..., 8, 8, 6, 1) to return a string. ``` def protein(array): ligand = '' for...
2017/09/22
[ "https://Stackoverflow.com/questions/46373433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8658260/" ]
You probably want `def protein(*array):` This allows you to give in any number of arguments. You also must use `for i in array:` instead of `for i in range(array):`
You don't give a list to the protein function. You need to do something like: ``` num_list = [1, 6, 8] protein(num_list) ``` Or directly: ``` protein([1, 6, 8]) ``` Also, you need to fix the for loop after that. At last: ``` def protein(array): ligand = '' for i in array: if i == 1: l...
46,373,433
I am working in python, trying to be able to put in a data set (eg. (1, 6, 8) that returns a string (eg. 'NO+ F- NO+'). I think that maybe array is not the correct object. I want to be able to plug in large data sets (eg. (1, 1, 6, 1, ..., 8, 8, 6, 1) to return a string. ``` def protein(array): ligand = '' for...
2017/09/22
[ "https://Stackoverflow.com/questions/46373433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8658260/" ]
You probably want `def protein(*array):` This allows you to give in any number of arguments. You also must use `for i in array:` instead of `for i in range(array):`
1) replace 'range(array)' by 'array' 2) put list or tuple in argument when calling the function and not multiple numbers. ``` In [2]: def protein(array): ligand = '' for i in array: if i == 1: ligand = ligand + 'NO+' if i == 6: ligand = ligand + 'F-' if i == 8: ligand = ligan...
46,373,433
I am working in python, trying to be able to put in a data set (eg. (1, 6, 8) that returns a string (eg. 'NO+ F- NO+'). I think that maybe array is not the correct object. I want to be able to plug in large data sets (eg. (1, 1, 6, 1, ..., 8, 8, 6, 1) to return a string. ``` def protein(array): ligand = '' for...
2017/09/22
[ "https://Stackoverflow.com/questions/46373433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8658260/" ]
First, you need `*args` as the argument, to accept an arbitrary number of arguments as in your example. Once you do that, you simply iterate over `args`. The rest of your code is OK, if not entirely idiomatic. ``` def protein(*args): ligand = '' for i in args: if i == 1: ligand = ligand + ...
If you call it like `protein(1, 6, 8)` you are **not** passing it a tuple: you pass it **three parameters**. Since you defined `protein` with *one* parameter: `array`, that errors. You can use arbitrary parameters, by using `*args`. But nevertheless this function is still not very elegant nor is it efficient: it will ...
46,373,433
I am working in python, trying to be able to put in a data set (eg. (1, 6, 8) that returns a string (eg. 'NO+ F- NO+'). I think that maybe array is not the correct object. I want to be able to plug in large data sets (eg. (1, 1, 6, 1, ..., 8, 8, 6, 1) to return a string. ``` def protein(array): ligand = '' for...
2017/09/22
[ "https://Stackoverflow.com/questions/46373433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8658260/" ]
First, you need `*args` as the argument, to accept an arbitrary number of arguments as in your example. Once you do that, you simply iterate over `args`. The rest of your code is OK, if not entirely idiomatic. ``` def protein(*args): ligand = '' for i in args: if i == 1: ligand = ligand + ...
You don't give a list to the protein function. You need to do something like: ``` num_list = [1, 6, 8] protein(num_list) ``` Or directly: ``` protein([1, 6, 8]) ``` Also, you need to fix the for loop after that. At last: ``` def protein(array): ligand = '' for i in array: if i == 1: l...
46,373,433
I am working in python, trying to be able to put in a data set (eg. (1, 6, 8) that returns a string (eg. 'NO+ F- NO+'). I think that maybe array is not the correct object. I want to be able to plug in large data sets (eg. (1, 1, 6, 1, ..., 8, 8, 6, 1) to return a string. ``` def protein(array): ligand = '' for...
2017/09/22
[ "https://Stackoverflow.com/questions/46373433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8658260/" ]
First, you need `*args` as the argument, to accept an arbitrary number of arguments as in your example. Once you do that, you simply iterate over `args`. The rest of your code is OK, if not entirely idiomatic. ``` def protein(*args): ligand = '' for i in args: if i == 1: ligand = ligand + ...
1) replace 'range(array)' by 'array' 2) put list or tuple in argument when calling the function and not multiple numbers. ``` In [2]: def protein(array): ligand = '' for i in array: if i == 1: ligand = ligand + 'NO+' if i == 6: ligand = ligand + 'F-' if i == 8: ligand = ligan...
55,253,980
How to debug the code written in python in container using azure dev spaces for kubernetes ?
2019/03/20
[ "https://Stackoverflow.com/questions/55253980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8267052/" ]
Debugging should be similar just like we have it in Dot net core.In dot net , we used to debug something like this **Setting and using breakpoints for debugging** If Visual Studio 2017 is still connected to your dev space, click the stop button. Open Controllers/HomeController.cs and click somewhere on line 20 to put...
Currently debugging in Azure Dev Spaces only lists Node.js, .NET Core, and Java as officially supported. The documentation for how to debug these 3 types of environments was written pretty recently (Quickstarts published on 7/7/2019). I am assuming that a guide for Python should be on the way shortly, but I have been u...
73,565,617
I'm making an age calculator and when calculating the months, I need numbers, not strings such as "January" etc. how do I make it that when the user's selecting their birth month, they see month strings ("Jan", "Feb"), and backend I return the month's number? thought this could be done with if statements, but it's sim...
2022/09/01
[ "https://Stackoverflow.com/questions/73565617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19517516/" ]
You can use list comprehension for that : ``` myList = ['BUD', 'CDG', 'DEL', 'DOH', 'DSM,ORD', 'EWR,HND', 'EWR,HND,ICN', 'EWR,HND,JFK', 'EWR,HND,JFK,LGA', 'EWR,HND,JFK,LGA', 'EWY,LHR', 'EWY,LHR,SFO,DSM', 'EWY,LHR,SFO,DSM,ORD,BGI', 'EWY,LHR,SFO,DSM,ORD,BGI,LGA'] result = [el.split(',') for el in myList...
``` myList = ['BUD', 'CDG', 'DEL', 'DOH', 'DSM,ORD', 'EWR,HND', 'EWR,HND,ICN', 'EWR,HND,JFK', 'EWR,HND,JFK,LGA', 'EWR,HND,JFK,LGA', 'EWY,LHR', 'EWY,LHR,SFO,DSM', 'EWY,LHR,SFO,DSM,ORD,BGI', 'EWY,LHR,SFO,DSM,ORD,BGI,LGA'] nested_list = [[element] for element in myList] ``` output : ``` [['BUD'], ['CD...
73,565,617
I'm making an age calculator and when calculating the months, I need numbers, not strings such as "January" etc. how do I make it that when the user's selecting their birth month, they see month strings ("Jan", "Feb"), and backend I return the month's number? thought this could be done with if statements, but it's sim...
2022/09/01
[ "https://Stackoverflow.com/questions/73565617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19517516/" ]
You can use list comprehension for that : ``` myList = ['BUD', 'CDG', 'DEL', 'DOH', 'DSM,ORD', 'EWR,HND', 'EWR,HND,ICN', 'EWR,HND,JFK', 'EWR,HND,JFK,LGA', 'EWR,HND,JFK,LGA', 'EWY,LHR', 'EWY,LHR,SFO,DSM', 'EWY,LHR,SFO,DSM,ORD,BGI', 'EWY,LHR,SFO,DSM,ORD,BGI,LGA'] result = [el.split(',') for el in myList...
This group each element in order they appear. `new_list = [data_list[i:i+1] for i in range(0, len(data_list), 1)]` you can change integar value like if you want to group in form of 5 elements, replace 1 with 5. .
73,565,617
I'm making an age calculator and when calculating the months, I need numbers, not strings such as "January" etc. how do I make it that when the user's selecting their birth month, they see month strings ("Jan", "Feb"), and backend I return the month's number? thought this could be done with if statements, but it's sim...
2022/09/01
[ "https://Stackoverflow.com/questions/73565617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19517516/" ]
You can use list comprehension for that : ``` myList = ['BUD', 'CDG', 'DEL', 'DOH', 'DSM,ORD', 'EWR,HND', 'EWR,HND,ICN', 'EWR,HND,JFK', 'EWR,HND,JFK,LGA', 'EWR,HND,JFK,LGA', 'EWY,LHR', 'EWY,LHR,SFO,DSM', 'EWY,LHR,SFO,DSM,ORD,BGI', 'EWY,LHR,SFO,DSM,ORD,BGI,LGA'] result = [el.split(',') for el in myList...
``` li = ['BUD', 'CDG', 'DEL', 'DOH', 'DSM,ORD', 'EWR,HND', 'EWR,HND,ICN', 'EWR,HND,JFK', 'EWR,HND,JFK,LGA', 'EWR,HND,JFK,LGA', 'EWY,LHR', 'EWY,LHR,SFO,DSM', 'EWY,LHR,SFO,DSM,ORD,BGI', 'EWY,LHR,SFO,DSM,ORD,BGI,LGA', 'EWY,LHR,SFO,SAN', 'HND,ICN', 'ICN', 'ICN,JFK', 'ICN,JFK,LGA', 'ICN,JFK,LGA', 'LGA', 'LGA', 'LHR,SFO', '...
73,565,617
I'm making an age calculator and when calculating the months, I need numbers, not strings such as "January" etc. how do I make it that when the user's selecting their birth month, they see month strings ("Jan", "Feb"), and backend I return the month's number? thought this could be done with if statements, but it's sim...
2022/09/01
[ "https://Stackoverflow.com/questions/73565617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19517516/" ]
This group each element in order they appear. `new_list = [data_list[i:i+1] for i in range(0, len(data_list), 1)]` you can change integar value like if you want to group in form of 5 elements, replace 1 with 5. .
``` myList = ['BUD', 'CDG', 'DEL', 'DOH', 'DSM,ORD', 'EWR,HND', 'EWR,HND,ICN', 'EWR,HND,JFK', 'EWR,HND,JFK,LGA', 'EWR,HND,JFK,LGA', 'EWY,LHR', 'EWY,LHR,SFO,DSM', 'EWY,LHR,SFO,DSM,ORD,BGI', 'EWY,LHR,SFO,DSM,ORD,BGI,LGA'] nested_list = [[element] for element in myList] ``` output : ``` [['BUD'], ['CD...
73,565,617
I'm making an age calculator and when calculating the months, I need numbers, not strings such as "January" etc. how do I make it that when the user's selecting their birth month, they see month strings ("Jan", "Feb"), and backend I return the month's number? thought this could be done with if statements, but it's sim...
2022/09/01
[ "https://Stackoverflow.com/questions/73565617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19517516/" ]
``` li = ['BUD', 'CDG', 'DEL', 'DOH', 'DSM,ORD', 'EWR,HND', 'EWR,HND,ICN', 'EWR,HND,JFK', 'EWR,HND,JFK,LGA', 'EWR,HND,JFK,LGA', 'EWY,LHR', 'EWY,LHR,SFO,DSM', 'EWY,LHR,SFO,DSM,ORD,BGI', 'EWY,LHR,SFO,DSM,ORD,BGI,LGA', 'EWY,LHR,SFO,SAN', 'HND,ICN', 'ICN', 'ICN,JFK', 'ICN,JFK,LGA', 'ICN,JFK,LGA', 'LGA', 'LGA', 'LHR,SFO', '...
``` myList = ['BUD', 'CDG', 'DEL', 'DOH', 'DSM,ORD', 'EWR,HND', 'EWR,HND,ICN', 'EWR,HND,JFK', 'EWR,HND,JFK,LGA', 'EWR,HND,JFK,LGA', 'EWY,LHR', 'EWY,LHR,SFO,DSM', 'EWY,LHR,SFO,DSM,ORD,BGI', 'EWY,LHR,SFO,DSM,ORD,BGI,LGA'] nested_list = [[element] for element in myList] ``` output : ``` [['BUD'], ['CD...
17,256,602
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this ``` app.add_url_rule('/', view_func=Main.as_view('main'), methods=["GET"]) app.add_url_rule('/<page>/', view_func=Main.as_view('main'), methods=["G...
2013/06/23
[ "https://Stackoverflow.com/questions/17256602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2016434/" ]
This same issue happened to me when I had more than one API function in the module and tried to wrap each function with 2 decorators: 1. @app.route() 2. My custom @exception\_handler decorator I got this same exception because I tried to wrap more than one function with those two decorators: ``` @app.route("/path1"...
In case you are using flask on python notebook, you need to restart kernel everytime you make changes in code
17,256,602
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this ``` app.add_url_rule('/', view_func=Main.as_view('main'), methods=["GET"]) app.add_url_rule('/<page>/', view_func=Main.as_view('main'), methods=["G...
2013/06/23
[ "https://Stackoverflow.com/questions/17256602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2016434/" ]
If you think you have unique endpoint names and still this error is given then probably you are facing [issue](https://github.com/pallets/flask/issues/796). Same was the case with me. This issue is with flask 0.10 in case you have same version then do following to get rid of this: ``` sudo pip uninstall flask sudo pi...
This is issue for me was from an (breaking) update to **flask-jwt-extended (version 4.x.x and up)** used in a basic api I wrote a year ago and am now incorporating into a project. @jwt\_required to @jwt\_required()
17,256,602
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this ``` app.add_url_rule('/', view_func=Main.as_view('main'), methods=["GET"]) app.add_url_rule('/<page>/', view_func=Main.as_view('main'), methods=["G...
2013/06/23
[ "https://Stackoverflow.com/questions/17256602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2016434/" ]
I would just like to add to this a more 'template' type solution. ``` def func_name(f): def wrap(*args, **kwargs): if condition: pass else: whatever you want return f(*args, **kwargs) wrap.__name__ = f.__name__ return wrap ``` would just like to add a reall...
Your view names need to be unique even if they are pointing to the same view method, or you can add from functools import wraps and use @wraps <https://docs.python.org/2/library/functools.html>
17,256,602
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this ``` app.add_url_rule('/', view_func=Main.as_view('main'), methods=["GET"]) app.add_url_rule('/<page>/', view_func=Main.as_view('main'), methods=["G...
2013/06/23
[ "https://Stackoverflow.com/questions/17256602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2016434/" ]
Adding `@wraps(f)` above the wrapper function solved my issue. ``` def list_ownership(f): @wraps(f) def decorator(*args,**kwargs): return f(args,kwargs) return decorator ```
I'm working on a similar problem and I managed to get rid of it by returning the wrapper funcion, which wasn't being done before: ``` def decorator_func(func_to_decorate): def wrapper_func(): return func_to_decorate return wrapper_func # I wasn't returning wrapper func! ```
17,256,602
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this ``` app.add_url_rule('/', view_func=Main.as_view('main'), methods=["GET"]) app.add_url_rule('/<page>/', view_func=Main.as_view('main'), methods=["G...
2013/06/23
[ "https://Stackoverflow.com/questions/17256602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2016434/" ]
For users that use @app.route it is better to use the key-argument `endpoint` rather then chaning the value of `__name__` like [Roei Bahumi](https://stackoverflow.com/a/42254713/5019818) stated. Taking his example will be: ``` @app.route("/path1", endpoint='func1') @exception_handler def func1(): pass @app.route(...
I'm working on a similar problem and I managed to get rid of it by returning the wrapper funcion, which wasn't being done before: ``` def decorator_func(func_to_decorate): def wrapper_func(): return func_to_decorate return wrapper_func # I wasn't returning wrapper func! ```
17,256,602
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this ``` app.add_url_rule('/', view_func=Main.as_view('main'), methods=["GET"]) app.add_url_rule('/<page>/', view_func=Main.as_view('main'), methods=["G...
2013/06/23
[ "https://Stackoverflow.com/questions/17256602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2016434/" ]
For users that use @app.route it is better to use the key-argument `endpoint` rather then chaning the value of `__name__` like [Roei Bahumi](https://stackoverflow.com/a/42254713/5019818) stated. Taking his example will be: ``` @app.route("/path1", endpoint='func1') @exception_handler def func1(): pass @app.route(...
Flask requires you to associate a single 'view function' with an 'endpoint'. You are calling `Main.as_view('main')` twice which creates two different functions (exactly the same functionality but different in memory signature). Short story, you should simply do ``` main_view_func = Main.as_view('main') app.add_url_ru...
17,256,602
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this ``` app.add_url_rule('/', view_func=Main.as_view('main'), methods=["GET"]) app.add_url_rule('/<page>/', view_func=Main.as_view('main'), methods=["G...
2013/06/23
[ "https://Stackoverflow.com/questions/17256602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2016434/" ]
For users that use @app.route it is better to use the key-argument `endpoint` rather then chaning the value of `__name__` like [Roei Bahumi](https://stackoverflow.com/a/42254713/5019818) stated. Taking his example will be: ``` @app.route("/path1", endpoint='func1') @exception_handler def func1(): pass @app.route(...
This can happen also when you have identical function names on different routes.
17,256,602
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this ``` app.add_url_rule('/', view_func=Main.as_view('main'), methods=["GET"]) app.add_url_rule('/<page>/', view_func=Main.as_view('main'), methods=["G...
2013/06/23
[ "https://Stackoverflow.com/questions/17256602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2016434/" ]
This same issue happened to me when I had more than one API function in the module and tried to wrap each function with 2 decorators: 1. @app.route() 2. My custom @exception\_handler decorator I got this same exception because I tried to wrap more than one function with those two decorators: ``` @app.route("/path1"...
There is a fix for Flask issue #570 introduced recenty (flask 0.10) that causes this exception to be raised. See <https://github.com/mitsuhiko/flask/issues/796> So if you go to flask/app.py and comment out the 4 lines 948..951, this may help until the issue is resovled fully in a new version. The diff of that change...
17,256,602
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this ``` app.add_url_rule('/', view_func=Main.as_view('main'), methods=["GET"]) app.add_url_rule('/<page>/', view_func=Main.as_view('main'), methods=["G...
2013/06/23
[ "https://Stackoverflow.com/questions/17256602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2016434/" ]
This can happen also when you have identical function names on different routes.
There is a fix for Flask issue #570 introduced recenty (flask 0.10) that causes this exception to be raised. See <https://github.com/mitsuhiko/flask/issues/796> So if you go to flask/app.py and comment out the 4 lines 948..951, this may help until the issue is resovled fully in a new version. The diff of that change...
17,256,602
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this ``` app.add_url_rule('/', view_func=Main.as_view('main'), methods=["GET"]) app.add_url_rule('/<page>/', view_func=Main.as_view('main'), methods=["G...
2013/06/23
[ "https://Stackoverflow.com/questions/17256602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2016434/" ]
Flask requires you to associate a single 'view function' with an 'endpoint'. You are calling `Main.as_view('main')` twice which creates two different functions (exactly the same functionality but different in memory signature). Short story, you should simply do ``` main_view_func = Main.as_view('main') app.add_url_ru...
If you think you have unique endpoint names and still this error is given then probably you are facing [issue](https://github.com/pallets/flask/issues/796). Same was the case with me. This issue is with flask 0.10 in case you have same version then do following to get rid of this: ``` sudo pip uninstall flask sudo pi...
28,418,677
i just began playing with python 3 and got a little stuck. I have this code: ``` person = ['George', 'Andrew', 'Ryan', 'Jack', 'Daniel'] for item in person: opinion = input("What do you think about "+person[0]+"? ") print(person[0]+" is a "+opinion+"") ``` And i do not know how to make it ask about e...
2015/02/09
[ "https://Stackoverflow.com/questions/28418677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3025008/" ]
You are assigning `item` to each value in `person`, use that variable. ``` for item in person: opinion = input("What do you think about "+item+"? ") print(item+" is a "+opinion+"") ``` When you called `person[0]`, you were setting it to the first value in `person` **every time**, which is not what yo...
What about ``` for item in person opinion = input("What do you think about "+item+"? ") print(item+" is a "+opinion+"") ``` And even better, if you want to make it more verbose: ``` # List with "s" to make it plural persons = ['George', 'Andrew', 'Ryan', 'Jack', 'Daniel'] # List item without the "s" for pe...
28,418,677
i just began playing with python 3 and got a little stuck. I have this code: ``` person = ['George', 'Andrew', 'Ryan', 'Jack', 'Daniel'] for item in person: opinion = input("What do you think about "+person[0]+"? ") print(person[0]+" is a "+opinion+"") ``` And i do not know how to make it ask about e...
2015/02/09
[ "https://Stackoverflow.com/questions/28418677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3025008/" ]
Notice that when you are running your `for` loop, `item` will be whichever person you have in question. Thus, replace `person[0]` with `item` and you will ask about each person as required, like so: ``` for item in person: opinion = input("What do you think about "+item+"? ") print(item+" is a "+opinio...
What about ``` for item in person opinion = input("What do you think about "+item+"? ") print(item+" is a "+opinion+"") ``` And even better, if you want to make it more verbose: ``` # List with "s" to make it plural persons = ['George', 'Andrew', 'Ryan', 'Jack', 'Daniel'] # List item without the "s" for pe...
28,418,677
i just began playing with python 3 and got a little stuck. I have this code: ``` person = ['George', 'Andrew', 'Ryan', 'Jack', 'Daniel'] for item in person: opinion = input("What do you think about "+person[0]+"? ") print(person[0]+" is a "+opinion+"") ``` And i do not know how to make it ask about e...
2015/02/09
[ "https://Stackoverflow.com/questions/28418677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3025008/" ]
Notice that when you are running your `for` loop, `item` will be whichever person you have in question. Thus, replace `person[0]` with `item` and you will ask about each person as required, like so: ``` for item in person: opinion = input("What do you think about "+item+"? ") print(item+" is a "+opinio...
You are assigning `item` to each value in `person`, use that variable. ``` for item in person: opinion = input("What do you think about "+item+"? ") print(item+" is a "+opinion+"") ``` When you called `person[0]`, you were setting it to the first value in `person` **every time**, which is not what yo...
45,654,850
I would like to do a stuff like this in c++ : ``` for (int i = 0, i < 3; ++i) { const auto& author = {"pierre", "paul", "jean"}[i]; const auto& age = {12, 45, 43}[i]; const auto& object = {o1, o2, o3}[i]; print({"even", "without", "identifier"}[i]); ... } ``` Does everyone know how to do this kind of ...
2017/08/12
[ "https://Stackoverflow.com/questions/45654850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443456/" ]
Looks like you should have used a vector of your custom class with `author`, `age`, `object` and `whatever` attributes, put it in a vector and do range for-loop over it - that would be idiomatic in C++: ``` struct foo { std::string author; int age; object_t object; whatever_t whatever; }; std::vector<...
Creating an object like `{"pierre", "paul", "jean"}` results in a initializer list. Initializer list does not have any [] operator [Why doesn't `std::initializer\_list` provide a subscript operator?](https://stackoverflow.com/questions/17787394/why-doesnt-stdinitializer-list-provide-a-subscript-operator). So you should...
22,703,333
I'm working in python, trying to write a code that makes the Fibonacci sequence and return the results as a list. How would I go about doing so? I was able to write a code to return the set of values not as a list, but I'm unsure how I would go about writing a code to return a list. (Here's the code I have to return ...
2014/03/28
[ "https://Stackoverflow.com/questions/22703333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3471046/" ]
The `string` class is in the namespace `std`. You can remove the scoping for `std::`. You'd do best to include it inside the main function, so names don't colide if you use a library that uses the name string or `cout`, or such. ``` #include <iostream> #include <string> int main() { using namespace std; string a...
`string` is in `std` namespace, it's only valid to use `std::string` rather than `string` (the same for `std::cin`, `std::vector` etc). However, in practice, some compilers may let a program using `string` etc without `std::` prefix compile, which makes some programmers think it's OK to omit `std::`, but it's not in st...
841,096
I've recently hit a wall in a project I'm working on which uses PyQt. I have a QTreeView hooked up to a QAbstractItemModel which typically has thousands of nodes in it. So far, it works alright, but I realized today that selecting a lot of nodes is very slow. After some digging, it turns out that QAbstractItemModel.par...
2009/05/08
[ "https://Stackoverflow.com/questions/841096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/103667/" ]
Try calling `setUniformRowHeights(true)` for your tree view: <https://doc.qt.io/qt-4.8/qtreeview.html#uniformRowHeights-prop> Also, there's a C++ tool called modeltest from qt labs. I'm not sure if there is something for python though: <https://wiki.qt.io/Model_Test>
I converted your very nice example code to PyQt5 and ran under Qt5.2 and can confirm that the numbers are still similar, i.e. inexplicably huge numbers of calls. Here for example is the top part of the report for start, cmd-A to select all, scroll one page, quit: ``` ncalls tottime percall cumtime percall filen...