Dataset Viewer
Auto-converted to Parquet Duplicate
qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
sequencelengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
41,850,558
I have a model called "document-detail-sample" and when you call it with a GET, something like this, **GET** `https://url/document-detail-sample/` then you get every "document-detail-sample". Inside the model is the id. So, if you want every Id, you could just "iterate" on the list and ask for the id. Easy. But... th...
2017/01/25
[ "https://Stackoverflow.com/questions/41850558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4050960/" ]
You could use `@list_route` decorator ``` from rest_framework.decorators import detail_route, list_route from rest_framework.response import Response class DocumentDetailSampleViewSet(viewsets.ModelViewSet): queryset = DocumentDetailSample.objects.all() serializer_class = DocumentDetailSampleSerializer ...
Assuming you don't need pagination, just override the `list` method like so ``` class DocumentDetailSampleViewSet(viewsets.ModelViewSet): queryset = DocumentDetailSample.objects.all() serializer_class = DocumentDetailSampleSerializer def list(self, request): return Response(self.get_queryset().val...
14,585,722
Suppose you have a python function, as so: ``` def foo(spam, eggs, ham): pass ``` You could call it using the positional arguments only (`foo(1, 2, 3)`), but you could also be explicit and say `foo(spam=1, eggs=2, ham=3)`, or mix the two (`foo(1, 2, ham=3)`). Is it possible to get the same kind of functionality...
2013/01/29
[ "https://Stackoverflow.com/questions/14585722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/731881/" ]
You can do something like this: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument('foo',nargs='?',default=argparse.SUPPRESS) parser.add_argument('--foo',dest='foo',default=None) parser.add_argument('bar',nargs='?',default=argparse.SUPPRESS) parser.add_argument('--bar',dest='bar',default=None)...
I believe this is what you are looking for [Argparse defaults](http://docs.python.org/dev/library/argparse.html#default)
14,585,722
Suppose you have a python function, as so: ``` def foo(spam, eggs, ham): pass ``` You could call it using the positional arguments only (`foo(1, 2, 3)`), but you could also be explicit and say `foo(spam=1, eggs=2, ham=3)`, or mix the two (`foo(1, 2, ham=3)`). Is it possible to get the same kind of functionality...
2013/01/29
[ "https://Stackoverflow.com/questions/14585722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/731881/" ]
You can also use this module: [docopt](https://github.com/docopt/docopt)
I believe this is what you are looking for [Argparse defaults](http://docs.python.org/dev/library/argparse.html#default)
14,585,722
Suppose you have a python function, as so: ``` def foo(spam, eggs, ham): pass ``` You could call it using the positional arguments only (`foo(1, 2, 3)`), but you could also be explicit and say `foo(spam=1, eggs=2, ham=3)`, or mix the two (`foo(1, 2, ham=3)`). Is it possible to get the same kind of functionality...
2013/01/29
[ "https://Stackoverflow.com/questions/14585722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/731881/" ]
You can do something like this: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument('foo',nargs='?',default=argparse.SUPPRESS) parser.add_argument('--foo',dest='foo',default=None) parser.add_argument('bar',nargs='?',default=argparse.SUPPRESS) parser.add_argument('--bar',dest='bar',default=None)...
You can also use this module: [docopt](https://github.com/docopt/docopt)
72,950,868
I would like to add a closing parenthesis to strings that have an open parenthesis but are missing a closing parenthesis. For instance, I would like to modify "The dog walked (ABC in the park" to be "The dog walked (ABC) in the park". I found a similar question and solution but it is in Python ([How to add a missing c...
2022/07/12
[ "https://Stackoverflow.com/questions/72950868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19533566/" ]
Try this ``` stringr::str_replace_all(text, '\\([A-Z]+(?!\\))\\b', '\\0\\)') ``` * output ``` "The dog walked (ABC) in the park" ```
Not a one liner, but it does the trick and is (hopefully!) intuitive. ``` library(stringr) add_brackets = function(text) { brackets = str_extract(text, "\\([:alpha:]+") # finds the open bracket and any following letters brackets_new = paste0(brackets, ")") # adds in the closing brackets str_replace(text, ...
72,950,868
I would like to add a closing parenthesis to strings that have an open parenthesis but are missing a closing parenthesis. For instance, I would like to modify "The dog walked (ABC in the park" to be "The dog walked (ABC) in the park". I found a similar question and solution but it is in Python ([How to add a missing c...
2022/07/12
[ "https://Stackoverflow.com/questions/72950868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19533566/" ]
Try this ``` stringr::str_replace_all(text, '\\([A-Z]+(?!\\))\\b', '\\0\\)') ``` * output ``` "The dog walked (ABC) in the park" ```
You might also use gsub, and first use the word boundary and then the negative lookahead. In the replacement use the first capture group followed by `)` ``` text = "The dog walked (ABC in the park" gsub('(\\([A-Z]+)\\b(?!\\))', '\\1\\)', text, perl=T) ``` Output ``` [1] "The dog walked (ABC) in the park" ```
72,950,868
I would like to add a closing parenthesis to strings that have an open parenthesis but are missing a closing parenthesis. For instance, I would like to modify "The dog walked (ABC in the park" to be "The dog walked (ABC) in the park". I found a similar question and solution but it is in Python ([How to add a missing c...
2022/07/12
[ "https://Stackoverflow.com/questions/72950868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19533566/" ]
You might also use gsub, and first use the word boundary and then the negative lookahead. In the replacement use the first capture group followed by `)` ``` text = "The dog walked (ABC in the park" gsub('(\\([A-Z]+)\\b(?!\\))', '\\1\\)', text, perl=T) ``` Output ``` [1] "The dog walked (ABC) in the park" ```
Not a one liner, but it does the trick and is (hopefully!) intuitive. ``` library(stringr) add_brackets = function(text) { brackets = str_extract(text, "\\([:alpha:]+") # finds the open bracket and any following letters brackets_new = paste0(brackets, ")") # adds in the closing brackets str_replace(text, ...
67,609,973
I chose to use Python 3.8.1 Azure ML in Azure Machine learning studio, but when i run the command `!python train.py`, it uses python Anconda 3.6.9, when i downloaded python 3.8 and run the command `!python38 train.py` in the same dir as before, the response was `python3.8: can't open file` . Any idea? Also Python 3 in ...
2021/05/19
[ "https://Stackoverflow.com/questions/67609973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14915505/" ]
You should try adding a new Python 3.8 Kernel. Here and instructions how to add a new Kernel: <https://learn.microsoft.com/en-us/azure/machine-learning/how-to-access-terminal#add-new-kernels>
Yeah I understand your pain point, and I agree that calling bash commands in a notebook cell should execute in the same conda environment as the one associated with the selected kernel of the notebook. I think this is bug, I'll flag it to the notebook feature team, but I encourage you to open a priority support ticket ...
58,483,706
I am new to python and trying my hands on certain problems. I have a situation where I have 2 dataframe which I want to combine to achieve my desired dataframe. I have tried .merge and .join, both of which was not able to get my desired outbcome. let us suppose I have the below scenario: ``` lt = list(['a','b','c','...
2019/10/21
[ "https://Stackoverflow.com/questions/58483706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11378087/" ]
If you don't mind the order of the columns changing, this is just a right join. The only caveat is that those are performed on rows rather than columns, so you need to transpose first: ```py In [44]: df.T.join(df1.T, how='right').T Out[44]: a a a b b b c d 0 10 10 10 11 11 11 12 12 1 15 15 ...
Use [`concat()`](https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html) ```py pd.concat([df, df1], axis=0, join='inner', sort=False) a b c d a b a b 0 10 11 12 12 10 11 10 11 1 15 14 12 10 15 14 15 14 ```
58,483,706
I am new to python and trying my hands on certain problems. I have a situation where I have 2 dataframe which I want to combine to achieve my desired dataframe. I have tried .merge and .join, both of which was not able to get my desired outbcome. let us suppose I have the below scenario: ``` lt = list(['a','b','c','...
2019/10/21
[ "https://Stackoverflow.com/questions/58483706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11378087/" ]
What you can do is to use the columns of `df` and select the corresponding columns in `df1`, like so: ```py lt = list(['a','b','c','d','a','b','a','b']) df = pd.DataFrame(columns = lt) data = [[10,11,12,12], [15,14,12,10]] df1 = pd.DataFrame(data, columns = ['a','b','c','d']) df2 = df1[df.columns] print(df2) ``` ...
Use [`concat()`](https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html) ```py pd.concat([df, df1], axis=0, join='inner', sort=False) a b c d a b a b 0 10 11 12 12 10 11 10 11 1 15 14 12 10 15 14 15 14 ```
14,187,973
Simmilar question (related with Python2: [Python: check if method is static](https://stackoverflow.com/questions/8727059/python-check-if-method-is-static)) Lets concider following class definition: ``` class A: def f(self): return 'this is f' @staticmethod def g(): return 'this is g' ``` In Python 3 ...
2013/01/06
[ "https://Stackoverflow.com/questions/14187973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889902/" ]
``` class A: def f(self): return 'this is f' @staticmethod def g(): return 'this is g' print(type(A.__dict__['g'])) print(type(A.g)) <class 'staticmethod'> <class 'function'> ```
I needed this solution and wrote the following based on the answer from @root ``` def is_method_static(cls, method_name): # http://stackoverflow.com/questions/14187973/python3-check-if-method-is-static for c in cls.mro(): if method_name in c.__dict__: return isinstance(c.__dict__[method_nam...
14,187,973
Simmilar question (related with Python2: [Python: check if method is static](https://stackoverflow.com/questions/8727059/python-check-if-method-is-static)) Lets concider following class definition: ``` class A: def f(self): return 'this is f' @staticmethod def g(): return 'this is g' ``` In Python 3 ...
2013/01/06
[ "https://Stackoverflow.com/questions/14187973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889902/" ]
``` class A: def f(self): return 'this is f' @staticmethod def g(): return 'this is g' print(type(A.__dict__['g'])) print(type(A.g)) <class 'staticmethod'> <class 'function'> ```
For Python 3.2 or newer, use [`inspect.getattr_static()`](https://docs.python.org/3/library/inspect.html#inspect.getattr_static) to retrieve the attribute without invoking the descriptor protocol: > > Retrieve attributes without triggering dynamic lookup via the descriptor protocol, `__getattr__()` or `__getattribute...
14,187,973
Simmilar question (related with Python2: [Python: check if method is static](https://stackoverflow.com/questions/8727059/python-check-if-method-is-static)) Lets concider following class definition: ``` class A: def f(self): return 'this is f' @staticmethod def g(): return 'this is g' ``` In Python 3 ...
2013/01/06
[ "https://Stackoverflow.com/questions/14187973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889902/" ]
For Python 3.2 or newer, use [`inspect.getattr_static()`](https://docs.python.org/3/library/inspect.html#inspect.getattr_static) to retrieve the attribute without invoking the descriptor protocol: > > Retrieve attributes without triggering dynamic lookup via the descriptor protocol, `__getattr__()` or `__getattribute...
I needed this solution and wrote the following based on the answer from @root ``` def is_method_static(cls, method_name): # http://stackoverflow.com/questions/14187973/python3-check-if-method-is-static for c in cls.mro(): if method_name in c.__dict__: return isinstance(c.__dict__[method_nam...
46,132,431
I have written code to generate numbers from 0500000000 to 0500000100: ``` def generator(nums): count = 0 while count < 100: gg=print('05',count, sep='') count += 1 g = generator(10) ``` as I use linux, I thought I may be able to use this command `python pythonfilename.py >> file.txt` Yet,...
2017/09/09
[ "https://Stackoverflow.com/questions/46132431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5548783/" ]
Here I've assumed we're laying out two general images, rather than plots. If your images are actually plots you've created, then you can lay them out as a single image for display using `gridExtra::grid.arrange` for grid graphics or `par(mfrow=c(1,2))` for base graphics and thereby avoid the complications of laying out...
Put them in the same code chunk and do not use align. Let them use html. THis has worked for me. ``` ````{r echo=FALSE, fig.height=3.0, fig.width=3.0} #type your code here ggplot(anscombe, aes(x=x1 , y=y1)) + geom_point() +geom_smooth(method="lm") + ggtitle("Results for x1 and y1 ") ggplot(anscombe, aes(x=...
54,007,542
input is like: ``` text="""Hi Team from the following Server : <table border="0" cellpadding="0" cellspacing="0" style="width:203pt"> <tbody> <tr> <td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td> </tr> </tbody> </table> <p>&nbsp;</p> <p>Please archive the followin...
2019/01/02
[ "https://Stackoverflow.com/questions/54007542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9901523/" ]
Use `BeautifulSoup` to parse HTML **Ex:** ``` from bs4 import BeautifulSoup text="""<p>Hi Team from the following Server :</p> <table border="0" cellpadding="0" cellspacing="0" style="width:203pt"> <tbody> <tr> <td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td> </tr> ...
You can use `HTMLParser` as demonstrated below: ``` from HTMLParser import HTMLParser s = \ """ <html> <p>Hi Team from the following Server :</p> <table border="0" cellpadding="0" cellspacing="0" style="width:203pt"> <tbody> <tr> <td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td...
54,007,542
input is like: ``` text="""Hi Team from the following Server : <table border="0" cellpadding="0" cellspacing="0" style="width:203pt"> <tbody> <tr> <td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td> </tr> </tbody> </table> <p>&nbsp;</p> <p>Please archive the followin...
2019/01/02
[ "https://Stackoverflow.com/questions/54007542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9901523/" ]
Use `BeautifulSoup` to parse HTML **Ex:** ``` from bs4 import BeautifulSoup text="""<p>Hi Team from the following Server :</p> <table border="0" cellpadding="0" cellspacing="0" style="width:203pt"> <tbody> <tr> <td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td> </tr> ...
If you do not want to use external library, you can use `re` module to remove tables: ``` output = re.sub('<table.+?</table>','',text,flags=re.DOTALL) ``` printing output give: ``` Hi Team from the following Server : <p>&nbsp;</p> <p>Please archive the following Project Areas :</p> ``` (and 2 empty lines which...
54,007,542
input is like: ``` text="""Hi Team from the following Server : <table border="0" cellpadding="0" cellspacing="0" style="width:203pt"> <tbody> <tr> <td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td> </tr> </tbody> </table> <p>&nbsp;</p> <p>Please archive the followin...
2019/01/02
[ "https://Stackoverflow.com/questions/54007542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9901523/" ]
If you do not want to use external library, you can use `re` module to remove tables: ``` output = re.sub('<table.+?</table>','',text,flags=re.DOTALL) ``` printing output give: ``` Hi Team from the following Server : <p>&nbsp;</p> <p>Please archive the following Project Areas :</p> ``` (and 2 empty lines which...
You can use `HTMLParser` as demonstrated below: ``` from HTMLParser import HTMLParser s = \ """ <html> <p>Hi Team from the following Server :</p> <table border="0" cellpadding="0" cellspacing="0" style="width:203pt"> <tbody> <tr> <td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td...
38,776,104
I would like to redirect the standard error and standard output of a Python script to the same output file. From the terminal I could use ``` $ python myfile.py &> out.txt ``` to do the same task that I want, but I need to do it from the Python script itself. I looked into the questions [Redirect subprocess stder...
2016/08/04
[ "https://Stackoverflow.com/questions/38776104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1461999/" ]
This works ``` sys.stdout = open('out.log', 'w') sys.stderr = sys.stdout ```
A SyntaxError in a Python file like the above is raised before your program even begins to run: Python files are compiled just like in any other compiled language - if the parser or compiler can't find sense in your Python file, no executable bytecode is generated, therefore the program does not run. The correct way t...
57,843,695
I haven't changed my system configuration, But I'm spotting this error for the first time today. I've reported it here: <https://github.com/jupyter/notebook/issues/4871> ``` > jupyter notebook [I 10:44:20.102 NotebookApp] JupyterLab extension loaded from /usr/local/anaconda3/lib/python3.7/site-packages/jupyterlab [I ...
2019/09/08
[ "https://Stackoverflow.com/questions/57843695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/435129/" ]
I fixed this by updating both jupyter on pip and pip3 (just to be safe) and this fixed the problem using both > > `pip install --upgrade jupyter` > > > and > > `pip3 install --upgrade jupyter --no-cache-dir` > > > I believe you can do this in the terminal as well as in conda's terminal (since conda envs al...
As per [Where does Jupyter install site-packages on macOS?](https://stackoverflow.com/questions/57843888/where-does-jupyter-install-site-packages-on-macos), I locate where on my system `jupyter` is searching for this missing file: ``` > find / -path '*/static/components' 2>/dev/null /usr/local/anaconda3/pkgs/notebook...
44,175,800
Simple question: given a string ``` string = "Word1 Word2 Word3 ... WordN" ``` is there a pythonic way to do this? ``` firstWord = string.split(" ")[0] otherWords = string.split(" ")[1:] ``` Like an unpacking or something? Thank you
2017/05/25
[ "https://Stackoverflow.com/questions/44175800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2131783/" ]
Since Python 3 and [PEP 3132](https://www.python.org/dev/peps/pep-3132/), you can use extended unpacking. This way, you can unpack arbitrary string containing any number of words. The first will be stored into the variable `first`, and the others will belong to the list (possibly empty) `others`. ``` first, *others =...
From [Extended Iterable Unpacking](https://www.python.org/dev/peps/pep-3132/). Many algorithms require splitting a sequence in a "first, rest" pair, if you're using Python2.x, you need to try this: ``` seq = string.split() first, rest = seq[0], seq[1:] ``` and it is replaced by the cleaner and probably more efficie...
28,717,067
I am trying to place a condition after the for loop. It will print the word available if the retrieved rows is not equal to zero, however if I would be entering a value which is not stored in my database, it will return a message. My problem here is that, if I'd be inputting value that isn't stored on my database, it w...
2015/02/25
[ "https://Stackoverflow.com/questions/28717067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4529171/" ]
Quite apart from the 0/NULL confusion, your logic is wrong. If there are no matching rows, you won't get a 0 as the value of a row; in fact you won't get any rows at all, and you will never even get into the for loop. A much better way to do this would be simply run a COUNT query, get the single result with `fetchone(...
In python you should check for `None` not `NULL`. In your code you can just check for object, if it is not None then control should go inside `if` otherwise `else` will be executed ``` for row in rows: if row: print('Available') else: print('No available copies of the said book in the library')...
28,717,067
I am trying to place a condition after the for loop. It will print the word available if the retrieved rows is not equal to zero, however if I would be entering a value which is not stored in my database, it will return a message. My problem here is that, if I'd be inputting value that isn't stored on my database, it w...
2015/02/25
[ "https://Stackoverflow.com/questions/28717067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4529171/" ]
Quite apart from the 0/NULL confusion, your logic is wrong. If there are no matching rows, you won't get a 0 as the value of a row; in fact you won't get any rows at all, and you will never even get into the for loop. A much better way to do this would be simply run a COUNT query, get the single result with `fetchone(...
First of all NULL in python is called None. Next: according to documentation: "The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no more rows are available, it returns an empty list. " enpty list is not None ``` >>> row = [] >>> row is None False ``` So you need to...
65,995,857
I'm quite new to coding and I'm working on a math problem in python. To solve it, I would like to extract the first 7 numbers from a string of one hundred 50-digit number (take first 7 numbers, skip 43 numbers, and then take the first 7 again). The numbers aren't separated in any way (just one long string). Then I want...
2021/02/01
[ "https://Stackoverflow.com/questions/65995857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15117090/" ]
Python allows you to iterate over a range with custom step sizes. So that should be allow you to do something like: ```py your_list = [] for idx in range(0, len(string), 50): # Indexes 0, 50, 100, so on first_seven_digits = string[idx:idx+7] # Say, "1234567" str_to_int = int(first_seven_digits) # Converts to t...
first of all your number string is 4999 characters long so you'll have to add one. secondly if you want to use numpy you could make a 100 by 50 array by reshaping the original 5000 long array. like this ``` arr = np.array(list(number)).reshape(100, 50) ``` than you can slice the arr in a way that the first 7 element...
21,307,128
Since I have to mock a static method, I am using **Power Mock** to test my application. My application uses \**Camel 2.1*\*2. I define routes in *XML* that is read by *camel-spring* context. There were no issues when `Junit` alone was used for testing. While using power mock, I get the error listed at the end of the po...
2014/01/23
[ "https://Stackoverflow.com/questions/21307128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2345966/" ]
This error message usually means that your specified truststore can not be read. What I would check: * Is the path correct? (I'm sure you checked this...) * Has the user who started the JVM enough access privileges to read the trustore? * When do you set the system properties? Are they already set when the webservice ...
``` Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty ``` > > * In my case, I have 2 duplicate Java installations (OpenJDK and > JDK-17). > * I installed JDK-17 after configuring environment variable for OpenJDK and...
49,059,660
I am looking for a simple way to constantly monitor a log file, and send me an email notification every time thhis log file has changed (new lines have been added to it). The system runs on a Raspberry Pi 2 (OS Raspbian /Debian Stretch) and the log monitors a GPIO python script running as daemon. I need something ver...
2018/03/01
[ "https://Stackoverflow.com/questions/49059660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9431262/" ]
You asked for simple: ``` #!/bin/bash cur_line_count="$(wc -l myfile.txt)" while true do new_line_count="$(wc -l myfile.txt)" if [ "$cur_line_count" != "$new_line_count" ] then python ./sendmail.py fi cur_line_count="$new_line_count" sleep 5 done ```
I've done this a bunch of different ways. If you run a cron job every minute that counts the number of lines (wc -l) compares that to a stored count (e.g. in /tmp/myfilecounter) and sends the emails when the numbers are different. If you have inotify, there are more direct ways to get "woken up" when the file changes,...
56,794,886
guys! So I recently started learning about python classes and objects. For instance, I have a following list of strings: ``` alist = ["Four", "Three", "Five", "One", "Two"] ``` Which is comparable to a class of Numbers I have: ``` class Numbers(object): One=1 Two=2 Three=3 Four=4 Five=5 ``` How co...
2019/06/27
[ "https://Stackoverflow.com/questions/56794886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10713538/" ]
If you are set on using the class, one way would be to use [`__getattribute__()`](https://docs.python.org/3/reference/datamodel.html#object.__getattribute__) ``` print([Numbers().__getattribute__(a) for a in alist]) #[4, 3, 5, 1, 2] ``` But a much better (and more pythonic IMO) way would be to use a `dict`: ``` Num...
**EDIT:** I suppose that the words and numbers are just a trivial example, a dictionary is the right way to do it if that's not the case as written in the comments. Your assumptions are correct - either create an empty list and populate it using for loop, or use list comprehension with a for loop to create a new list ...
56,794,886
guys! So I recently started learning about python classes and objects. For instance, I have a following list of strings: ``` alist = ["Four", "Three", "Five", "One", "Two"] ``` Which is comparable to a class of Numbers I have: ``` class Numbers(object): One=1 Two=2 Three=3 Four=4 Five=5 ``` How co...
2019/06/27
[ "https://Stackoverflow.com/questions/56794886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10713538/" ]
Most objects (and hence classes) in python have the `__dict__` field, which is a mapping from attribute names to their values. You can access this field using the built-in [`vars`](https://docs.python.org/3/library/functions.html#vars), so ``` values = [vars(Numbers)[a] for a in alist] ``` will give you what you wan...
**EDIT:** I suppose that the words and numbers are just a trivial example, a dictionary is the right way to do it if that's not the case as written in the comments. Your assumptions are correct - either create an empty list and populate it using for loop, or use list comprehension with a for loop to create a new list ...
56,794,886
guys! So I recently started learning about python classes and objects. For instance, I have a following list of strings: ``` alist = ["Four", "Three", "Five", "One", "Two"] ``` Which is comparable to a class of Numbers I have: ``` class Numbers(object): One=1 Two=2 Three=3 Four=4 Five=5 ``` How co...
2019/06/27
[ "https://Stackoverflow.com/questions/56794886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10713538/" ]
While I totally agree that using a `dict` for `Numbers` would be easier and straight forward, but showing you the `Enum` way as your class involves magic numbers and sort of a valid use case for using enums. A similar implementation using `Enum` would be: ``` from enum import Enum class Numbers(Enum): One = 1 ...
**EDIT:** I suppose that the words and numbers are just a trivial example, a dictionary is the right way to do it if that's not the case as written in the comments. Your assumptions are correct - either create an empty list and populate it using for loop, or use list comprehension with a for loop to create a new list ...
36,108,377
I want to count the number of times a word is being repeated in the review string I am reading the csv file and storing it in a python dataframe using the below line ``` reviews = pd.read_csv("amazon_baby.csv") ``` The code in the below lines work when I apply it to a single review. ``` print reviews["review"][1]...
2016/03/19
[ "https://Stackoverflow.com/questions/36108377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2861976/" ]
You're trying to split the entire review column of the data frame (which is the Series mentioned in the error message). What you want to do is apply a function to each row of the data frame, which you can do by calling [apply](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html) on the dat...
Well, the problem is with: ``` reviews["review"] ``` The above is a Series. In your first snippet, you are doing this: ``` reviews["review"][1].split("disappointed") ``` That is, you are putting an index for the review. You could try looping over all rows of the column and perform your desired action. For example...
36,108,377
I want to count the number of times a word is being repeated in the review string I am reading the csv file and storing it in a python dataframe using the below line ``` reviews = pd.read_csv("amazon_baby.csv") ``` The code in the below lines work when I apply it to a single review. ``` print reviews["review"][1]...
2016/03/19
[ "https://Stackoverflow.com/questions/36108377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2861976/" ]
You're trying to split the entire review column of the data frame (which is the Series mentioned in the error message). What you want to do is apply a function to each row of the data frame, which you can do by calling [apply](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html) on the dat...
You can use `.str` to use string methods on series of strings: ``` reviews["review"].str.split("disappointed") ```
36,108,377
I want to count the number of times a word is being repeated in the review string I am reading the csv file and storing it in a python dataframe using the below line ``` reviews = pd.read_csv("amazon_baby.csv") ``` The code in the below lines work when I apply it to a single review. ``` print reviews["review"][1]...
2016/03/19
[ "https://Stackoverflow.com/questions/36108377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2861976/" ]
You're trying to split the entire review column of the data frame (which is the Series mentioned in the error message). What you want to do is apply a function to each row of the data frame, which you can do by calling [apply](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html) on the dat...
pandas 0.20.3 has **pandas.Series.str.split()** which acts on every string of the series and does the split. So you can simply split and then count the number of splits made ``` len(reviews['review'].str.split('disappointed')) - 1 ``` [pandas.Series.str.split](https://pandas.pydata.org/pandas-docs/stable/generated/p...
36,108,377
I want to count the number of times a word is being repeated in the review string I am reading the csv file and storing it in a python dataframe using the below line ``` reviews = pd.read_csv("amazon_baby.csv") ``` The code in the below lines work when I apply it to a single review. ``` print reviews["review"][1]...
2016/03/19
[ "https://Stackoverflow.com/questions/36108377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2861976/" ]
pandas 0.20.3 has **pandas.Series.str.split()** which acts on every string of the series and does the split. So you can simply split and then count the number of splits made ``` len(reviews['review'].str.split('disappointed')) - 1 ``` [pandas.Series.str.split](https://pandas.pydata.org/pandas-docs/stable/generated/p...
Well, the problem is with: ``` reviews["review"] ``` The above is a Series. In your first snippet, you are doing this: ``` reviews["review"][1].split("disappointed") ``` That is, you are putting an index for the review. You could try looping over all rows of the column and perform your desired action. For example...
36,108,377
I want to count the number of times a word is being repeated in the review string I am reading the csv file and storing it in a python dataframe using the below line ``` reviews = pd.read_csv("amazon_baby.csv") ``` The code in the below lines work when I apply it to a single review. ``` print reviews["review"][1]...
2016/03/19
[ "https://Stackoverflow.com/questions/36108377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2861976/" ]
pandas 0.20.3 has **pandas.Series.str.split()** which acts on every string of the series and does the split. So you can simply split and then count the number of splits made ``` len(reviews['review'].str.split('disappointed')) - 1 ``` [pandas.Series.str.split](https://pandas.pydata.org/pandas-docs/stable/generated/p...
You can use `.str` to use string methods on series of strings: ``` reviews["review"].str.split("disappointed") ```
72,329,252
Let's say we have following list. This list contains response times of a REST server in a traffic run. [1, 2, 3, 3, 4, 5, 6, 7, 9, 1] I need following output Percentage of the requests served within a certain time (ms) 50% 3 60% 4 70% 5 80% 6 90% 7 100% 9 How can we get it done in python? This is apache bench...
2022/05/21
[ "https://Stackoverflow.com/questions/72329252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4137009/" ]
You can try something like this: ``` responseTimes = [1, 2, 3, 3, 4, 5, 6, 7, 9, 1] for time in range(3,10): percentage = len([x for x in responseTimes if x <= time])/(len(responseTimes)) print(f'{percentage*100}%') ``` > > *"So basically lets say at 50%, we need to find point in list below which 50% of the...
You basically need to compute the cumulative ratio of the sorted response times. ```py from collections import Counter values = [1, 2, 3, 3, 4, 5, 6, 7, 9, 1] frequency = Counter(values) # {1: 2, 2: 1, 3: 2, ...} total = 0 n = len(values) for time in sorted(frequency): total += frequency[time] print(time, f'...
50,239,640
In python have three one dimensional arrays of different shapes (like the ones given below) ``` a0 = np.array([5,6,7,8,9]) a1 = np.array([1,2,3,4]) a2 = np.array([11,12]) ``` I am assuming that the array `a0` corresponds to an index `i=0`, `a1` corresponds to index `i=1` and `a2` corresponds to `i=2`. With these ass...
2018/05/08
[ "https://Stackoverflow.com/questions/50239640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3761166/" ]
You can use `numpy` stack functions to speed up: ``` aa = [a0, a1, a2] np.hstack(tuple(np.vstack((np.full(ai.shape, i), ai)) for i, ai in enumerate(aa))).T ```
One way to do this would be a simple list comprehension: ``` result = np.array([[i, arr_v] for i, arr in enumerate([a0, a1, a2]) for arr_v in arr]) >>> result array([[ 0, 5], [ 0, 6], [ 0, 7], [ 0, 8], [ 0, 9], [ 1, 1], [ 1, 2], [ 1...
50,239,640
In python have three one dimensional arrays of different shapes (like the ones given below) ``` a0 = np.array([5,6,7,8,9]) a1 = np.array([1,2,3,4]) a2 = np.array([11,12]) ``` I am assuming that the array `a0` corresponds to an index `i=0`, `a1` corresponds to index `i=1` and `a2` corresponds to `i=2`. With these ass...
2018/05/08
[ "https://Stackoverflow.com/questions/50239640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3761166/" ]
You can use `numpy` stack functions to speed up: ``` aa = [a0, a1, a2] np.hstack(tuple(np.vstack((np.full(ai.shape, i), ai)) for i, ai in enumerate(aa))).T ```
Here's an almost vectorized approach - ``` L = [a0,a1,a2] # list of all arrays lens = [len(i) for i in L] # only looping part* out = np.dstack(( np.repeat(np.arange(len(L)), lens), np.concatenate(L))) ``` \*The looping part is simply to get the lengths of the arrays, which should have negligible impact on the total ...
45,939,564
I am accessing a python file via python. The google sheets looks like the following: [![enter image description here](https://i.stack.imgur.com/eIW7v.png)](https://i.stack.imgur.com/eIW7v.png) But when I access it via: ``` self.probe=[] self.scope = ['https://spreadsheets.google.com/feeds'] self.creds = S...
2017/08/29
[ "https://Stackoverflow.com/questions/45939564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3554329/" ]
I'm not familiar with gspread, which appears to be a third-party client for the Google Sheets API, but it looks like you should be using [`get_all_values`](https://github.com/burnash/gspread#getting-all-values-from-a-worksheet-as-a-list-of-lists) rather than `get_all_records`. That will give you a list of lists, rather...
Python dictionaries are unordered. There is the [OrderedDict](https://docs.python.org/3.6/library/collections.html#collections.OrderedDict) in collections, but hard to say more about what the best course of action should be without more insight into why you need this dictionary ordered...
55,508,830
In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error: ``` raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2). ...
2019/04/04
[ "https://Stackoverflow.com/questions/55508830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6154769/" ]
I've just been through this. I had to install a separate newer version of SQLite, from <https://www.sqlite.org/download.html> That is in /usr/local/bin. Then I had to recompile Python, telling it to look there: ``` sudo LD_RUN_PATH=/usr/local/lib ./configure --enable-optimizations sudo LD_RUN_PATH=/usr/local/lib mak...
In addition to the above mentioned answers, just in case if you experience this behaviour on Travis CI, add `dist: xenial` directive to fix it.
55,508,830
In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error: ``` raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2). ...
2019/04/04
[ "https://Stackoverflow.com/questions/55508830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6154769/" ]
I've just been through this. I had to install a separate newer version of SQLite, from <https://www.sqlite.org/download.html> That is in /usr/local/bin. Then I had to recompile Python, telling it to look there: ``` sudo LD_RUN_PATH=/usr/local/lib ./configure --enable-optimizations sudo LD_RUN_PATH=/usr/local/lib mak...
I have applied the following fix and it worked for my CentOS 7.x server. Edit `/usr/lib64/python3.6/site-packages/django/db/backends/sqlite3/base.py` file as per the below example: ``` def check_sqlite_version(): # if Database.sqlite_version_info < (3, 8, 3): # 2018-07-07, edit if Database.sqlite_version_info < (3, ...
55,508,830
In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error: ``` raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2). ...
2019/04/04
[ "https://Stackoverflow.com/questions/55508830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6154769/" ]
If you don't want to recompile Python and you're using a virtualenv you can do this to set it up without affecting the system as a whole (I've done this with Ubuntu 16/18): 1. Download SQLite tarball from <https://www.sqlite.org/download.html> 2. Extract the contents and cd into the folder. 3. Run the following comman...
I've just been through this. I had to install a separate newer version of SQLite, from <https://www.sqlite.org/download.html> That is in /usr/local/bin. Then I had to recompile Python, telling it to look there: ``` sudo LD_RUN_PATH=/usr/local/lib ./configure --enable-optimizations sudo LD_RUN_PATH=/usr/local/lib mak...
55,508,830
In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error: ``` raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2). ...
2019/04/04
[ "https://Stackoverflow.com/questions/55508830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6154769/" ]
If you don't want to recompile Python and you're using a virtualenv you can do this to set it up without affecting the system as a whole (I've done this with Ubuntu 16/18): 1. Download SQLite tarball from <https://www.sqlite.org/download.html> 2. Extract the contents and cd into the folder. 3. Run the following comman...
In addition to the above mentioned answers, just in case if you experience this behaviour on Travis CI, add `dist: xenial` directive to fix it.
55,508,830
In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error: ``` raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2). ...
2019/04/04
[ "https://Stackoverflow.com/questions/55508830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6154769/" ]
This error comes because your virtual environment could not connect to newly updated sqlite3 database. For that you have to update your sqlite3 database version manually and then give path of it to your virtual environment. Kindly follow below steps: 1. Download latest sqlite3 from official site. (<https://www.sqlite....
In addition to the above mentioned answers, just in case if you experience this behaviour on Travis CI, add `dist: xenial` directive to fix it.
55,508,830
In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error: ``` raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2). ...
2019/04/04
[ "https://Stackoverflow.com/questions/55508830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6154769/" ]
If you don't want to recompile Python and you're using a virtualenv you can do this to set it up without affecting the system as a whole (I've done this with Ubuntu 16/18): 1. Download SQLite tarball from <https://www.sqlite.org/download.html> 2. Extract the contents and cd into the folder. 3. Run the following comman...
I have applied the following fix and it worked for my CentOS 7.x server. Edit `/usr/lib64/python3.6/site-packages/django/db/backends/sqlite3/base.py` file as per the below example: ``` def check_sqlite_version(): # if Database.sqlite_version_info < (3, 8, 3): # 2018-07-07, edit if Database.sqlite_version_info < (3, ...
55,508,830
In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error: ``` raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2). ...
2019/04/04
[ "https://Stackoverflow.com/questions/55508830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6154769/" ]
This error comes because your virtual environment could not connect to newly updated sqlite3 database. For that you have to update your sqlite3 database version manually and then give path of it to your virtual environment. Kindly follow below steps: 1. Download latest sqlite3 from official site. (<https://www.sqlite....
I have applied the following fix and it worked for my CentOS 7.x server. Edit `/usr/lib64/python3.6/site-packages/django/db/backends/sqlite3/base.py` file as per the below example: ``` def check_sqlite_version(): # if Database.sqlite_version_info < (3, 8, 3): # 2018-07-07, edit if Database.sqlite_version_info < (3, ...
55,508,830
In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error: ``` raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2). ...
2019/04/04
[ "https://Stackoverflow.com/questions/55508830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6154769/" ]
If you don't want to recompile Python and you're using a virtualenv you can do this to set it up without affecting the system as a whole (I've done this with Ubuntu 16/18): 1. Download SQLite tarball from <https://www.sqlite.org/download.html> 2. Extract the contents and cd into the folder. 3. Run the following comman...
This error comes because your virtual environment could not connect to newly updated sqlite3 database. For that you have to update your sqlite3 database version manually and then give path of it to your virtual environment. Kindly follow below steps: 1. Download latest sqlite3 from official site. (<https://www.sqlite....
46,143,091
I'm pretty new to python so it's a basic question. I have data that I imported from a csv file. Each row reflects a person and his data. Two attributes are Sex and Pclass. I want to add a new column (predictions) that is fully depended on those two in one line. If both attributes' values are 1 it should assign 1 to th...
2017/09/10
[ "https://Stackoverflow.com/questions/46143091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5252187/" ]
You could try adding a composite index ``` create index test on screenshot (DateTaken, id) ```
Try running this query: ``` SELECT COUNT(*) as total FROM screenshot WHERE DateTaken BETWEEN '2000-05-01' AND '2000-06-10'; ``` The reference to `ID` in the `SELECT` could be affecting the use of the index.
46,143,091
I'm pretty new to python so it's a basic question. I have data that I imported from a csv file. Each row reflects a person and his data. Two attributes are Sex and Pclass. I want to add a new column (predictions) that is fully depended on those two in one line. If both attributes' values are 1 it should assign 1 to th...
2017/09/10
[ "https://Stackoverflow.com/questions/46143091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5252187/" ]
There is no problem. Your index is fine. To explain... The `5730138` in `EXPLAIN` is an *estimate*. It can be larger or smaller than the actual value, sometimes by a large amount. Do not be bothered by it. You have 2.8M of screenshots in that date range, correct? Well, it could take 15 seconds to scan the index to co...
Try running this query: ``` SELECT COUNT(*) as total FROM screenshot WHERE DateTaken BETWEEN '2000-05-01' AND '2000-06-10'; ``` The reference to `ID` in the `SELECT` could be affecting the use of the index.
71,568,396
We are using a beam multi-language pipeline using python and java(ref <https://beam.apache.org/documentation/sdks/python-multi-language-pipelines/>). We are creating a cross-language pipeline using java. We have some external jar files that required a java library path. Code gets compiled properly and is able to create...
2022/03/22
[ "https://Stackoverflow.com/questions/71568396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9648514/" ]
A Worksheet Change Event: Monitor Change in Column's Data --------------------------------------------------------- * I personally would go with JvdV's suggestion in the comments. * On each manual change of a cell, e.g. in column `A`, it will check the formula `=SUM(A2:ALastRow)` in cell `A1` and if it is not correct ...
Use a nested function as below: =SUM(OFFSET(A2,,,COUNTA(A2:A26)))
49,005,651
This question is motivated by my another question: [How to await in cdef?](https://stackoverflow.com/questions/48989065/how-to-await-in-cdef) There are tons of articles and blog posts on the web about `asyncio`, but they are all very superficial. I couldn't find any information about how `asyncio` is actually implemen...
2018/02/27
[ "https://Stackoverflow.com/questions/49005651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5691066/" ]
It all boils down to the two main challenges that asyncio is addressing: * How to perform multiple I/O in a single thread? * How to implement cooperative multitasking? The answer to the first point has been around for a long while and is called a [select loop](https://en.wikipedia.org/wiki/Asynchronous_I/O#Select(/po...
If you picture an airport control tower, with many planes waiting to land on the same runway. The control tower can be seen as the event loop and runway as the thread. Each plane is a separate function waiting to execute. In reality only one plane can land on the runway at a time. What asyncio basically does it allows ...
49,005,651
This question is motivated by my another question: [How to await in cdef?](https://stackoverflow.com/questions/48989065/how-to-await-in-cdef) There are tons of articles and blog posts on the web about `asyncio`, but they are all very superficial. I couldn't find any information about how `asyncio` is actually implemen...
2018/02/27
[ "https://Stackoverflow.com/questions/49005651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5691066/" ]
It all boils down to the two main challenges that asyncio is addressing: * How to perform multiple I/O in a single thread? * How to implement cooperative multitasking? The answer to the first point has been around for a long while and is called a [select loop](https://en.wikipedia.org/wiki/Asynchronous_I/O#Select(/po...
It allows you to write single-threaded asynchronous code and implement concurrency in Python. Basically, `asyncio` provides an event loop for asynchronous programming. For example, if we need to make requests without blocking the main thread, we can use the `asyncio` library. The asyncio module allows for the implemen...
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
8