content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Changing the indexing order of BitArray in Python
I am using a BitArray in my python script, and I was wondering if there is a way to change the indexes order of the BitArray that I create. Right now the indexes are from 0 to N-1 where N is the number of bits. Is there away to change the indexes to go from N-1 to... | Changing the indexing order of BitArray in Python | I am using a BitArray in my python script, and I was wondering if there is a way to change the indexes order of the BitArray that I create. Right now the indexes are from 0 to N-1 where N is the number of bits. Is there away to change the indexes to go from N-1 to O?
dataBits = BitArray('0b10100000')
print(dataBits[0]... | [
"Yes. What you're looking for is the module variable lsb0:\nbitstring.lsb0 = True\ndataBits = bitstring.BitArray('0b10100000')\nprint(dataBits[0])\n\nPrints out False.\n"
] | [
0
] | [] | [] | [
"bitstring",
"python"
] | stackoverflow_0058862579_bitstring_python.txt |
Q:
Involutive (up to precision) operations "dataframe to csv" and "csv to dataframe"
I have a numerically really intensive vectorized python function def f(x,y) in two variables that I evaluate (with frompyfunc and broadcasting) on a np.array X = [x0, ...., xN-1] of x's and a np.array Y = [y0, ...., yM-1] of y's with... | Involutive (up to precision) operations "dataframe to csv" and "csv to dataframe" | I have a numerically really intensive vectorized python function def f(x,y) in two variables that I evaluate (with frompyfunc and broadcasting) on a np.array X = [x0, ...., xN-1] of x's and a np.array Y = [y0, ...., yM-1] of y's with N,M between 5 and 10 thousands. This returns as result a 2D np.array Z of shape (N,M)... | [
"It should be difference, because in csv all data are saved like strings, so if use index_col=0 here is correctly create FloatIndex, but columns names are strings, also data in columns should be parsed differently (e.g. if mixed strings and numeric):\nf = 'file.csv'\ndf.to_csv(f)\n\ndf = pd.read_csv(f, index_col=0)... | [
1
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074612027_dataframe_numpy_pandas_python.txt |
Q:
Best way to find a folder in the test directory for pytest
I have a folder structure as below for my pytest files
tests/my_test1.py
tests/input/data.txt
tests/bench/bench.csv
The test my_test1.py would have to read the file tests/input/data.txt. The challenge is to find the location of the file.
The tests can be ... | Best way to find a folder in the test directory for pytest | I have a folder structure as below for my pytest files
tests/my_test1.py
tests/input/data.txt
tests/bench/bench.csv
The test my_test1.py would have to read the file tests/input/data.txt. The challenge is to find the location of the file.
The tests can be invoked in Mutiple ways as mentioned here https://docs.pytest.or... | [
"You could create a fixture in the root of the tests folder (tests/conftest.py) to help you read any file relative to the tests folder:\nfrom pathlib import Path\nimport pytest\n\n@pytest.fixture()\ndef get_file():\n def _(file_path: str):\n return (Path(__file__).parent / file_path).read_text()\n\n re... | [
1
] | [] | [] | [
"pytest",
"python"
] | stackoverflow_0074611616_pytest_python.txt |
Q:
Run 2 aplications simultaneously with python and save csv files
I am trying to write a single python app that extracts data from an ICU monitor via ETH and grabs data from a HTTP endpoint and save the data input as csv files. They should be opend at the exact same time so that the data timestamp is the same.
The p... | Run 2 aplications simultaneously with python and save csv files | I am trying to write a single python app that extracts data from an ICU monitor via ETH and grabs data from a HTTP endpoint and save the data input as csv files. They should be opend at the exact same time so that the data timestamp is the same.
The program that reads the ICU data is called VitalSignsCapture.
VitalSign... | [
"I guess you could multiple processes.\none main which define the future time stamp at which both action will be performed, and which passes this timestamp via a queue to the second.\nThen at the given time stamp both process execute their own tasks~\nseems like it's better to edit than to add another answer so I e... | [
0
] | [] | [] | [
"csv",
"python",
"windows_11"
] | stackoverflow_0074611815_csv_python_windows_11.txt |
Q:
How to group a list of paths by their parent?
I have a list of paths and I want them to dynamically separate into lists they should belong to based on the folder name they come from. First two come from "tent1" folder and I want them together in one list and so on. I don't want to hardcode the names of those folde... | How to group a list of paths by their parent? | I have a list of paths and I want them to dynamically separate into lists they should belong to based on the folder name they come from. First two come from "tent1" folder and I want them together in one list and so on. I don't want to hardcode the names of those folders and then append paths to them. For example:
path... | [
"If your input is sorted by path (i.e. the same paths are sequential), you can use itertools.groupby:\nfrom itertools import groupby\nfrom os.path import dirname\n\nout = [list(g) for _,g in groupby(paths, dirname)]\n\nIf the paths are not sorted, you can use a dictionary as intermediate:\nout = {}\nfor p in paths:... | [
6
] | [] | [] | [
"path",
"python"
] | stackoverflow_0074612068_path_python.txt |
Q:
Mocking os.environ with python unittests
I am trying to test a class that handles for me the working directory based on a given parameter. To do so, we are using a class variable to map them.
When a specific value is passed, the path is retrieved from the environment variables (See baz in the example below). This ... | Mocking os.environ with python unittests | I am trying to test a class that handles for me the working directory based on a given parameter. To do so, we are using a class variable to map them.
When a specific value is passed, the path is retrieved from the environment variables (See baz in the example below). This is the specific case that I'm trying to test.
... | [
"So the problem is that you added map as a static variable.\nYour patch works correctly as you can see here:\npatch actually works\nThe problem is that when it runs it's already too late because the map variable was already calculated (before the patch).\nIf you want you can move it to the init function and it will... | [
5,
0
] | [] | [] | [
"environment_variables",
"python",
"python_unittest",
"unit_testing"
] | stackoverflow_0074611329_environment_variables_python_python_unittest_unit_testing.txt |
Q:
Python Dataframe editing
I wanna replace ( [ with ([.
Essentially get rid of the space between the brackets.
But df.replace() does not work.
Even if the code executes
the output remains the same.
Code
cdf=cdf.replace('( [','([')
cdf is a dataframe with 3 columns.
There is non error, its just that the replacing is... | Python Dataframe editing | I wanna replace ( [ with ([.
Essentially get rid of the space between the brackets.
But df.replace() does not work.
Even if the code executes
the output remains the same.
Code
cdf=cdf.replace('( [','([')
cdf is a dataframe with 3 columns.
There is non error, its just that the replacing is not happening.
| [
"If I understood you question right, then the df.applymap(mapping) function is what you are searching for. It applies the mapping (for example a lambda) to all cells of you data frame. Here is an example:\nimport pandas as pd\n\ndata = {\"c1\": [\"Test\", \"Test[ (Test)]\"],\n \"c2\": [\"Test\", \"Test[ (Tes... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074611366_dataframe_pandas_python.txt |
Q:
Replace text after string in python
I'm trying to replace string in a very big json File (30MB) so i try to automate this.
Here is an example of what I have
"local_notifications": [
{
"is_enabled": false,
"notification_type": "basic",
"notification_title": "localised_strings.show_name_debug_l... | Replace text after string in python | I'm trying to replace string in a very big json File (30MB) so i try to automate this.
Here is an example of what I have
"local_notifications": [
{
"is_enabled": false,
"notification_type": "basic",
"notification_title": "localised_strings.show_name_debug_lobbies",
"notification_body": "loca... | [
"Did you try to convert your Json into a dictionary?\nfor instance using these resources:\nhttps://www.geeksforgeeks.org/convert-json-to-dictionary-in-python/\nYou convert to a dictionary, you edit the contents of the key you want, then save it back to Json if you need\n"
] | [
1
] | [] | [] | [
"json",
"python",
"replace"
] | stackoverflow_0074611804_json_python_replace.txt |
Q:
ValueError: setting an array element with a sequence in SVM for simple arrays
I am trying to use SVM on my dataset but I am getting the error TypeError: only size-1 arrays can be converted to Python scalars. My inputs are:
y = df['emotion'].values.tolist()
X = df['flatten_embeddings']
Where y us just target like ... | ValueError: setting an array element with a sequence in SVM for simple arrays | I am trying to use SVM on my dataset but I am getting the error TypeError: only size-1 arrays can be converted to Python scalars. My inputs are:
y = df['emotion'].values.tolist()
X = df['flatten_embeddings']
Where y us just target like Sad, Angry, Neutral ... and X is
0 [1.702582, 1.277809, 1.7816906, -5.0634155,... | [
"The hint at the end was really the issue. The error in actual was ValueError: setting an array element with a sequence. I used a function to pad all the rows with 0 with were less in size than row with max length.\n# Find length of max row\nmax = max(map(len, X_arr))\n\n# Pad the rows with 0\nX_arr_same = np.array... | [
0
] | [] | [] | [
"arrays",
"machine_learning",
"numpy",
"pandas",
"python"
] | stackoverflow_0074611951_arrays_machine_learning_numpy_pandas_python.txt |
Q:
How are small sets stored in memory?
If we look at the resize behavior for sets under 50k elements:
>>> import sys
>>> s = set()
>>> seen = {}
>>> for i in range(50_000):
... size = sys.getsizeof(s)
... if size not in seen:
... seen[size] = len(s)
... print(f"{size=} {len(s)=}")
... s.a... | How are small sets stored in memory? | If we look at the resize behavior for sets under 50k elements:
>>> import sys
>>> s = set()
>>> seen = {}
>>> for i in range(50_000):
... size = sys.getsizeof(s)
... if size not in seen:
... seen[size] = len(s)
... print(f"{size=} {len(s)=}")
... s.add(i)
...
size=216 len(s)=0
size=728 len(... | [
"We are going to inspect how small sets uses 216 bytes.\nFirst of all a set object in python is represented by following C structure.\ntypedef struct {\n PyObject_HEAD\n\n Py_ssize_t fill; /* Number active and dummy entries*/\n Py_ssize_t used; /* Number active entries */\n\n /* Th... | [
7
] | [] | [] | [
"cpython",
"memory",
"python",
"python_internals",
"set"
] | stackoverflow_0074606984_cpython_memory_python_python_internals_set.txt |
Q:
how to split raw data into excel/ csv and identitfy rows that are not properly formed (python)?
I have raw data.
I want to split this into csv/excel.
after that if the data in the rows are not correctly stored( for e.g. if 0 is there entered instead of 121324) I want python to identify those rows.
I mean while spl... | how to split raw data into excel/ csv and identitfy rows that are not properly formed (python)? | I have raw data.
I want to split this into csv/excel.
after that if the data in the rows are not correctly stored( for e.g. if 0 is there entered instead of 121324) I want python to identify those rows.
I mean while splitting raw data into csv through python code, some rows might form incorrectly( please understand).
H... | [
"@mozway is right you better give an example input and expected result.\nAnyway if you're dealing with a variable number of columns in the input please refer to Handling Variable Number of Columns with Pandas - Python\nBest\n"
] | [
0
] | [] | [] | [
"database",
"dataframe",
"python",
"raw_data"
] | stackoverflow_0074611968_database_dataframe_python_raw_data.txt |
Q:
Unexpected round behaviour of Numpy float32
I am trying to understand how numpy handles the float32 datatype.
The following code produces 0.25815687
print(np.float32(0.2581568658351898).astype(str)) # 0.25815687
But an online float converter https://www.h-schmidt.net/FloatConverter/IEEE754.html gives 0.2581568658... | Unexpected round behaviour of Numpy float32 | I am trying to understand how numpy handles the float32 datatype.
The following code produces 0.25815687
print(np.float32(0.2581568658351898).astype(str)) # 0.25815687
But an online float converter https://www.h-schmidt.net/FloatConverter/IEEE754.html gives 0.2581568658351898193359375, Is Numpy doing something special... | [
"\nIs Numpy doing something special when printing the single-precision float or there is something I missed?\n\n0.2581568658351898 is not exactly encodable as a 32-bit float.\nThe closest is 0.2581568658351898193359375 or 0x1.085a46p-2\nWhen 0.2581568658351898193359375 is printed with reduced precision, the result ... | [
1,
0
] | [] | [] | [
"floating_point",
"ieee_754",
"numpy",
"python"
] | stackoverflow_0074610105_floating_point_ieee_754_numpy_python.txt |
Q:
get public key from private key with python OpenSSL
Well, I generate a private key with pyOpenSSL as follows:
from OpenSSL import crypto
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 2048)
print crypto.dump_privatekey(crypto.FILETYPE_PEM, k)
How do I get the public key string from it? I've still not found wha... | get public key from private key with python OpenSSL | Well, I generate a private key with pyOpenSSL as follows:
from OpenSSL import crypto
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 2048)
print crypto.dump_privatekey(crypto.FILETYPE_PEM, k)
How do I get the public key string from it? I've still not found what method of this library does it. Thanks
| [
"If\ncert = crypto.dump_certificate(crypto.FILETYPE_PEM, k)\n\ndoesn't do what you want, then it doesn't look like pyOpenSSL supports public key dumping. There is an unmerged branch here that adds that functionality but I can't claim that it does what is purports.\n",
"Updated:\nNow it has the method to get publi... | [
3,
1
] | [] | [] | [
"openssl",
"pyopenssl",
"python"
] | stackoverflow_0014939033_openssl_pyopenssl_python.txt |
Q:
python decrement at special case in for-loop
I need to decrement in a python for-loop at a special case (or just don't increment).
In C-like languages, this can be easily accomplished by decrementing the index, or if you have an iterator-like structure you could just "decrement" the iterator. But I have no clue ho... | python decrement at special case in for-loop | I need to decrement in a python for-loop at a special case (or just don't increment).
In C-like languages, this can be easily accomplished by decrementing the index, or if you have an iterator-like structure you could just "decrement" the iterator. But I have no clue how to achieve this in python.
One solution would be... | [
"You can make an iteration loop by yourself. You could easily add a loop index independent from next calls, so that you could even use a skip condition that uses the current index.\nskip_iteration = True\nit = iter(range(10))\niterating = True\nvalue = next(it)\nwhile iterating:\n try:\n print(value, end=... | [
0
] | [
"If the condition in the if statement is somehow related to the iterator i itself then the loop might not end but if the condition is not depended on i then there shall not be any problem\nyou can also try skipping that particular iteration by using continue.\n"
] | [
-1
] | [
"loops",
"python"
] | stackoverflow_0068680782_loops_python.txt |
Q:
Converting a nested JSON into a flatten one and then to pandas dataframe using pd.json_normalize()
I am trying to convert the below JSON as a dataframe. The below JSON is in a string.
json_str='{"TileName": "Master",
"Report Details":
[
{
"r1name": "Primary",
"r1link": "link1",
... | Converting a nested JSON into a flatten one and then to pandas dataframe using pd.json_normalize() | I am trying to convert the below JSON as a dataframe. The below JSON is in a string.
json_str='{"TileName": "Master",
"Report Details":
[
{
"r1name": "Primary",
"r1link": "link1",
"report Accessible": ["operations", "Sales"]
},
{
"r2name": "Secondry",
... | [
"You have wrong record_path, which should be ['Report Details', 'report Accessible'].\njs_obj = json.loads(json_str.replace('r2', 'r1')) # keep columns consistent\ndf = pd.json_normalize(js_obj, ['Report Details', 'report Accessible'], \n ['TileName', ['Report Details', 'r1name'], ['Report De... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074611154_pandas_python.txt |
Q:
How to find how many iframe present in source code -Python Selenium
There is a span dropdown and inside there are 3 more dropdowns. I need to first select "home" and then "task tracking" and the option in that drop down.
I have seen the iframe present in the source code and I am not able to find and put the soluti... | How to find how many iframe present in source code -Python Selenium | There is a span dropdown and inside there are 3 more dropdowns. I need to first select "home" and then "task tracking" and the option in that drop down.
I have seen the iframe present in the source code and I am not able to find and put the solution in my python code.
example HTML
Both find_element_by_css_selector and ... | [
"Selenium in Python has By.TAG_NAME attribute.\nBy.tagName is Selenium Java syntax.\n",
"it's self.driver.find_element(By.TAG_NAME,\"iframe\")\n"
] | [
0,
0
] | [] | [] | [
"automation",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074611428_automation_python_selenium_web_scraping.txt |
Q:
Adding to 2d dict not working as expected (python)
Im creating a function that returns a 2d dictionary, however, when adding the second part of the inner dict, it overwrites the first part and they both become the same value.
It will become more clear by reading the following:
# variables from other part of my cod... | Adding to 2d dict not working as expected (python) | Im creating a function that returns a 2d dictionary, however, when adding the second part of the inner dict, it overwrites the first part and they both become the same value.
It will become more clear by reading the following:
# variables from other part of my code
int_col = [1,3]
data = [['CJ', '20', 'Male', '20000']... | [
"The problem is that you use the same col_stats twice.\nIt becomes clear if you have a bit of tracing :\n+ print(f\"comparing {row[col]=!r} > {max_int}\")\n if row[col] > max_int:\n max_int = row[col]\n+ print(f\"{max_int=!r}\")\n\n+ ... | [
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074604396_dictionary_python.txt |
Q:
Regex selecting numbers
I am trying to capture the numbers in the text below with regex. But it seems to fail on the last text, which only has one digit inside a parenthesis. I can't figure out why since my knowledge with Regex is limited.
Any suggestions?
Regex
[\s(](\d[\d,\.\s]+)
Text
This banana costs 0,5 usd ... | Regex selecting numbers | I am trying to capture the numbers in the text below with regex. But it seems to fail on the last text, which only has one digit inside a parenthesis. I can't figure out why since my knowledge with Regex is limited.
Any suggestions?
Regex
[\s(](\d[\d,\.\s]+)
Text
This banana costs 0,5 usd from previous (50)
The toothb... | [
"Your pattern matches at least 2 characters, being a digit and 1 or more times one of \\d , . \\s\nYou can match either a space or ( and then capture a single digit followed by optionally repeating the chars in the character class.\n[\\s(](\\d[\\d,.\\s]*)\n\nSee a regex demo.\nIf you don't want trailing spaces, dot... | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074606947_python_regex.txt |
Q:
Inserting tuple into postegresql with python - Select statment
Hello I am trying to insert to a pgadmin table using python, I used execute and it worked, but for my second aprt i need to use a fucntion, I got everything working except the inserts with select, it tells my syntax error, or forgot comma, literally ev... | Inserting tuple into postegresql with python - Select statment | Hello I am trying to insert to a pgadmin table using python, I used execute and it worked, but for my second aprt i need to use a fucntion, I got everything working except the inserts with select, it tells my syntax error, or forgot comma, literally everything. Im new, so help would be apprecitated .
def insrtDirector(... | [
"You need to properly use subqueries (google it!). Try something like this, it might work (and please fix your variable names, qwertyu is not good, should be descriptive like unique_id, uname, dname, first_name, etc.)\ndef insrtDirector(q,w,e,r,t,y,u):\n # Assume w and e are always subqueries with one result\n ... | [
0
] | [] | [] | [
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0074608480_postgresql_psycopg2_python.txt |
Q:
Can we get random row value from a specific Key inside a dictionary
I fetched records from a .CSV file into a Pandas dataframe, Then I want to fetch a random record/row in it without using index inside a specific key like French or English. Even a specific row like French word and its English meaning and display t... | Can we get random row value from a specific Key inside a dictionary | I fetched records from a .CSV file into a Pandas dataframe, Then I want to fetch a random record/row in it without using index inside a specific key like French or English. Even a specific row like French word and its English meaning and display the pulled out random record at a specific key/row.
# this is the .CSV fi... | [
"The solution I figured out\n# read data from a dataframe into a dictionary\nwords_data_dict = {row.French: row.English for (index, row) in data.iterrows()}\nprint(words_data_dict)\n\n# convert the dictionary to a list\nlist_of_entry = list(words_data_dict.items())\nprint(list_of_entry)\n\n# generate a random row f... | [
0
] | [] | [] | [
"dictionary",
"dictionary_comprehension",
"nested",
"python"
] | stackoverflow_0074610164_dictionary_dictionary_comprehension_nested_python.txt |
Q:
How to use VSCode with the existing docker container
I've made an Python+Django+git docker container.
Now, I would like to 'Attach to a running container..' with VSCode to develop, i.e. run and debug, a Python app inside.
Is it good idea? Or it is better only setting up VSCode to run app inside the container?
I do... | How to use VSCode with the existing docker container | I've made an Python+Django+git docker container.
Now, I would like to 'Attach to a running container..' with VSCode to develop, i.e. run and debug, a Python app inside.
Is it good idea? Or it is better only setting up VSCode to run app inside the container?
I don't want VSCode make a docker container by itself.
Thanks.... | [
"I use such an environment to develop python app inside a container.\nimage_create.sh # script to create image to use it local and on the server\n\nimage_dockerfile # dockerfile with script how to create an image\n\ncontainer_create.sh # create named container from image\n\ncontainer_restart.sh # restart existing ... | [
1,
0,
0
] | [] | [] | [
"docker",
"python",
"visual_studio_code"
] | stackoverflow_0074572709_docker_python_visual_studio_code.txt |
Q:
Numpy-MKL for OS X
I love being able to use Christoph Gohlke's numpy-MKL version of NumPy linked to Intel's Math Kernel Library on Windows. However, I have been unable to find a similar version for OS X, preferably NumPy 1.7 linked for Python 3.3 on Mountain Lion. Does anyone know where this might be obtained?
EDI... | Numpy-MKL for OS X | I love being able to use Christoph Gohlke's numpy-MKL version of NumPy linked to Intel's Math Kernel Library on Windows. However, I have been unable to find a similar version for OS X, preferably NumPy 1.7 linked for Python 3.3 on Mountain Lion. Does anyone know where this might be obtained?
EDIT:
So after a bit of hun... | [
"Intel has release their MKL under a community license, which is free, with limited technical support. Currently MKL under the Community License is available for Linux and Windows, and it is expected they will provide a version for Mac OS X soon.\nhttps://software.intel.com/en-us/comment/1839012\nIn one of their r... | [
4,
3,
1
] | [] | [] | [
"intel_mkl",
"macos",
"numpy",
"python",
"python_3.3"
] | stackoverflow_0015665385_intel_mkl_macos_numpy_python_python_3.3.txt |
Q:
Graphql and Stake.com, POST body missing, invalid Content-Type, or JSON object has no keys
Please, help. I'm use scrapingant for bypass cloudflare.
The task to develop a real-time data parser, stuck at the request stage... :(
`
headers = {
"accept": "*/*",
"accept-encoding": "gzip, deflate, br",
"accep... | Graphql and Stake.com, POST body missing, invalid Content-Type, or JSON object has no keys | Please, help. I'm use scrapingant for bypass cloudflare.
The task to develop a real-time data parser, stuck at the request stage... :(
`
headers = {
"accept": "*/*",
"accept-encoding": "gzip, deflate, br",
"accept-language": "ru-RU,ru;q=0.9,en-GB;q=0.8,en;q=0.7,en-US;q=0.6",
"cf-device-type": "",
"c... | [
"CAUTION: NEVER publish any API key\nI was able to run your code without error.\nimport requests\nfrom urllib.parse import urlencode\n...\noperationName = \"highrollerSportBets\"\nvariables = {\"limit\":10}\n\nurl = 'https://stake.com/_api/graphql'\nsa_key = 'xxxx'\nsa_api = 'https://api.scrapingant.com/v2/general'... | [
0,
0
] | [] | [] | [
"graphql",
"python",
"python_3.x"
] | stackoverflow_0074367143_graphql_python_python_3.x.txt |
Q:
Sets intersection with returning every match
everyone!
I'm looking for most elegant way to find intersection of two sets, but I need to get a every match of keys
The examples of what I mean:
s1 = {1, 1, 2, 3}
s2 = {4, 5, 1, 1}
s1.intersection(s2)
Output is:
{1}
What output I need:
{1, 1}
Thank you everyone for ... | Sets intersection with returning every match | everyone!
I'm looking for most elegant way to find intersection of two sets, but I need to get a every match of keys
The examples of what I mean:
s1 = {1, 1, 2, 3}
s2 = {4, 5, 1, 1}
s1.intersection(s2)
Output is:
{1}
What output I need:
{1, 1}
Thank you everyone for help and sorry for my english
| [
"If you want a set-like thing for which items can appear with multiplicity greater than 1, then you could use a multiset. These can be represented by Counter objects. There is no built-in intersection method for those, but you could write a function which computes it by taking the min of two counts:\nfrom collectio... | [
2
] | [] | [] | [
"intersection",
"python",
"set"
] | stackoverflow_0074611882_intersection_python_set.txt |
Q:
Taking n elements at a time from 1d list and add them to 2d list
I have a list making up data, and I'd like to take 4 elements at a time from this list and put them in a 2d list where each 4-element increment is a new row of said list.
My first attempts involve input to 1d list:
list.append(input("Enter data type ... | Taking n elements at a time from 1d list and add them to 2d list | I have a list making up data, and I'd like to take 4 elements at a time from this list and put them in a 2d list where each 4-element increment is a new row of said list.
My first attempts involve input to 1d list:
list.append(input("Enter data type 1:")) list.append(input("Enter data type 2:")) etc.
and then I've trie... | [
"I think this post is probably what you need. With np.reshape() you can just have your list filled with all the values you need and do the reshaping after in a single step.\n"
] | [
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074612332_list_python.txt |
Q:
How to append json in Python List
I want to create a JSON Python List shown as below using without repeated codes(Python functions).
Expected Output:
Steps=[
{
'Name': 'Download Config File',
'ActionOnFailure': 'CONTINUE',
'HadoopJarStep': {
'Jar'... | How to append json in Python List | I want to create a JSON Python List shown as below using without repeated codes(Python functions).
Expected Output:
Steps=[
{
'Name': 'Download Config File',
'ActionOnFailure': 'CONTINUE',
'HadoopJarStep': {
'Jar': 'command-runner.jar',
... | [
"There is an issue with the indentation here:\nfor date in ['20210801','20210807','20210814']:\n addingstep = addSteps(date)\n steps.append(addingstep)\n steps =json.dumps(steps)\n\nFix:\nfor date in ['20210801','20210807','20210814']:\n addingstep = addSteps(date)\n steps.append(addingstep)\n\nsteps... | [
2
] | [] | [] | [
"amazon_emr",
"aws_lambda",
"list",
"python",
"python_3.x"
] | stackoverflow_0074612350_amazon_emr_aws_lambda_list_python_python_3.x.txt |
Q:
Get all permutations of bool array
I need all permutations of a bool array, the following code is inefficient, but does what I want:
from itertools import permutations
import numpy as np
n1=2
n2=3
a = np.array([True]*n1+[False]*n2)
perms = set(permutations(a))
However it is inefficient and fails for long arrays... | Get all permutations of bool array | I need all permutations of a bool array, the following code is inefficient, but does what I want:
from itertools import permutations
import numpy as np
n1=2
n2=3
a = np.array([True]*n1+[False]*n2)
perms = set(permutations(a))
However it is inefficient and fails for long arrays. Is there a more efficent implementatio... | [
"What about sampling the combinations of indices of the True values:\nfrom itertools import combinations\nimport numpy as np\n\na = np.arange(n1+n2)\n\nout = [np.isin(a, x).tolist() for x in combinations(range(n1+n2), r=n1)]\n\nOutput:\n[[True, True, False, False, False],\n [True, False, True, False, False],\n [Tru... | [
3
] | [] | [] | [
"numpy",
"python",
"python_itertools"
] | stackoverflow_0074612253_numpy_python_python_itertools.txt |
Q:
Pass a 2d numpy array to c using ctypes
What is the correct way to pass a numpy 2d - array to a c function using ctypes ?
My current approach so far (leads to a segfault):
C code :
void test(double **in_array, int N) {
int i, j;
for(i = 0; i<N; i++) {
for(j = 0; j<N; j++) {
printf("%e ... | Pass a 2d numpy array to c using ctypes | What is the correct way to pass a numpy 2d - array to a c function using ctypes ?
My current approach so far (leads to a segfault):
C code :
void test(double **in_array, int N) {
int i, j;
for(i = 0; i<N; i++) {
for(j = 0; j<N; j++) {
printf("%e \t", in_array[i][j]);
}
print... | [
"This is probably a late answer, but I finally got it working. All credit goes to Sturla Molden at this link.\nThe key is, note that double** is an array of type np.uintp. Therefore, we have\nxpp = (x.ctypes.data + np.arange(x.shape[0]) * x.strides[0]).astype(np.uintp)\ndoublepp = np.ctypeslib.ndpointer(dtype=np.ui... | [
28,
2,
0,
0
] | [] | [] | [
"c",
"ctypes",
"numpy",
"python"
] | stackoverflow_0022425921_c_ctypes_numpy_python.txt |
Q:
How to convert string hex into bytes format?
The string is like "e52c886a88b6f421a9324ea175dc281478f03003499de6162ca72ddacf4b09e0", when I run the code, the output is not my expectation, like this.
hexstr = "e52c886a88b6f421a9324ea175dc281478f03003499de6162ca72ddacf4b09e0"
hexstr = bytes.fromhex(hexstr)
print(hexs... | How to convert string hex into bytes format? | The string is like "e52c886a88b6f421a9324ea175dc281478f03003499de6162ca72ddacf4b09e0", when I run the code, the output is not my expectation, like this.
hexstr = "e52c886a88b6f421a9324ea175dc281478f03003499de6162ca72ddacf4b09e0"
hexstr = bytes.fromhex(hexstr)
print(hexstr)
The output is
b'\xe5,\x88j\x88\xb6\xf4!\xa92N... | [
"Your code is correct.\nPython tries to be helpful by displaying bytes that map to an ASCII character as that character. For example, \\x2c maps to ,.\n>>> b',' == b'\\x2c'\nTrue\n\n"
] | [
0
] | [] | [] | [
"byte",
"hex",
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0074612406_byte_hex_python_python_2.7_python_3.x.txt |
Q:
How to fix "ResourceExhaustedError: OOM when allocating tensor"
I wanna make a model with multiple inputs. So, I try to build a model like this.
# define two sets of inputs
inputA = Input(shape=(32,64,1))
inputB = Input(shape=(32,1024))
# CNN
x = layers.Conv2D(32, kernel_size = (3, 3), activation = 'relu')(input... | How to fix "ResourceExhaustedError: OOM when allocating tensor" | I wanna make a model with multiple inputs. So, I try to build a model like this.
# define two sets of inputs
inputA = Input(shape=(32,64,1))
inputB = Input(shape=(32,1024))
# CNN
x = layers.Conv2D(32, kernel_size = (3, 3), activation = 'relu')(inputA)
x = layers.Conv2D(32, (3,3), activation='relu')(x)
x = layers.MaxP... | [
"OOM stands for \"out of memory\". Your GPU is running out of memory, so it can't allocate memory for this tensor. There are a few things you can do:\n\nDecrease the number of filters in your Dense, Conv2D layers\nUse a smaller batch_size (or increase steps_per_epoch and validation_steps)\nUse grayscale images (you... | [
56,
2,
0,
0
] | [] | [] | [
"deep_learning",
"keras",
"machine_learning",
"python",
"tensorflow"
] | stackoverflow_0059394947_deep_learning_keras_machine_learning_python_tensorflow.txt |
Q:
networkx directed graph can't add weight in the middle of the edges from pandas df
My dataframe columns are A,B,Weight. Around 50 rows
Here is my code
G = nx.from_pandas_edgelist(df, source='A',
target='B',
create_using=nx.DiGraph())
weight = nx.get_e... | networkx directed graph can't add weight in the middle of the edges from pandas df | My dataframe columns are A,B,Weight. Around 50 rows
Here is my code
G = nx.from_pandas_edgelist(df, source='A',
target='B',
create_using=nx.DiGraph())
weight = nx.get_edge_attributes(G, 'Weight')
pos = nx.circular_layout(G, scale=1)
nx.draw(G, pos, with_la... | [
"There are two errors that prevented this. First, you need to assign the edge attributes to the graph when defining it. Second, you need to use nx.draw_networkx_edge_labels() and not nx.draw_networkx_labels(). The latter is for node labels, not edge labels.\nimport pandas as pd\nimport networkx as nx\n\ndf = pd.... | [
1
] | [] | [] | [
"networkx",
"pandas",
"python"
] | stackoverflow_0074610256_networkx_pandas_python.txt |
Q:
Running part of python program with/without sudo
I am trying to control some LEDs on my Raspberry Pi Zero 2w with rpi_ws281x using some audio from pyaudio as input. One of them needs sudo, the other only works without sudo...
I tried to import rpi_ws281x in a script without sudo. That crashes because the 'permissi... | Running part of python program with/without sudo | I am trying to control some LEDs on my Raspberry Pi Zero 2w with rpi_ws281x using some audio from pyaudio as input. One of them needs sudo, the other only works without sudo...
I tried to import rpi_ws281x in a script without sudo. That crashes because the 'permission to open \dev\mem is denied'. So the program has to ... | [
"Okay, so I solved the issue after a non-zero amount of googling and messing up my pulseaudio installation enough times to warrant a reinstall more often than I would like to admit.\nrpi_ws281x requires the PWM pin (GPIO 18 on the Pi Zero 2w) for which it needs sudo privileges. So the solution is to run pulseaudio ... | [
0
] | [] | [] | [
"pulseaudio",
"pyaudio",
"python",
"raspberry_pi",
"sudo"
] | stackoverflow_0074591584_pulseaudio_pyaudio_python_raspberry_pi_sudo.txt |
Q:
Python, ctypes, multi-Dimensional Array
I have structure in Python code and in C code. I fill these fields
("bones_pos_vect",((c_float*4)*30)),
("bones_rot_quat",((c_float*4)*30))
in python code with the right values, but when I request them in C code, I get only 0.0 from all array cells. Why do I lose the values... | Python, ctypes, multi-Dimensional Array | I have structure in Python code and in C code. I fill these fields
("bones_pos_vect",((c_float*4)*30)),
("bones_rot_quat",((c_float*4)*30))
in python code with the right values, but when I request them in C code, I get only 0.0 from all array cells. Why do I lose the values? All other fields of my structures work fine... | [
"Here's an example of how you can use a multidimensional array with Python and ctypes. \nI wrote the following C code, and used gcc in MinGW to compile this to slib.dll:\n#include <stdio.h>\n\ntypedef struct TestStruct {\n int a;\n float array[30][4];\n} TestStruct;\n\nextern void print_struct(TestStru... | [
16,
0
] | [] | [] | [
"ctypes",
"multidimensional_array",
"python",
"python_3.x",
"structure"
] | stackoverflow_0011384015_ctypes_multidimensional_array_python_python_3.x_structure.txt |
Q:
Press key to game window with Python
I try to pass keyboard event to game window but it doesn't work. For another program such as Notepad++ it is works.
from pynput.keyboard import Controller
keyboard = Controller()
keyboard.press('a')
keyboard.release('a')
The same a problem I have with mouse events. I tried us... | Press key to game window with Python | I try to pass keyboard event to game window but it doesn't work. For another program such as Notepad++ it is works.
from pynput.keyboard import Controller
keyboard = Controller()
keyboard.press('a')
keyboard.release('a')
The same a problem I have with mouse events. I tried use "Mouse and Keyboard Recorder" program an... | [
"It's my answer:\nWin32API Mouse vs Real Mouse Click\nBut I don't know how to write a custom driver :)\n"
] | [
0
] | [] | [] | [
"events",
"keyboard",
"python"
] | stackoverflow_0074603939_events_keyboard_python.txt |
Q:
Matplotlib x-axis and secondary y-axis customization questions
Data - we import historical yields of the ten and thirty year Treasury and calculate the spread (difference) between the two (this block of code is good; feel free so skip):
#Import statements
import yfinance as yf
import pandas as pd
import matplotli... | Matplotlib x-axis and secondary y-axis customization questions | Data - we import historical yields of the ten and thirty year Treasury and calculate the spread (difference) between the two (this block of code is good; feel free so skip):
#Import statements
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
#Constants
sta... | [
"Let's create some data:\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport numpy as np\n\ndays = np.array([\"2022-01-01\", \"2022-07-01\", \"2023-02-15\", \"2023-11-15\", \"2024-03-03\"],\n dtype = \"datetime64\")\nval = np.array([20, 20, -10, -10, 10])\n\nFor the date in t... | [
0
] | [] | [] | [
"matplotlib",
"pandas",
"python",
"yticks"
] | stackoverflow_0074608599_matplotlib_pandas_python_yticks.txt |
Q:
Multi-table inheritance and two many to many via through model not working in admin inline
I'm trying to create navigation menu from the django admin as per user's requirement.
The Model look like this:
class MenuItem(models.Model):
title = models.CharField(max_length=200, help_text='Title of the item')
cr... | Multi-table inheritance and two many to many via through model not working in admin inline | I'm trying to create navigation menu from the django admin as per user's requirement.
The Model look like this:
class MenuItem(models.Model):
title = models.CharField(max_length=200, help_text='Title of the item')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_no... | [
"Everything just worked once I switched to MySQL. It was not working on Sqlite. I don't know why it doesn't work with sqlite maybe it is a bug. But changing the database solved my problem.\n"
] | [
0
] | [] | [] | [
"django",
"django_4.1",
"django_modeladmin",
"django_models",
"python"
] | stackoverflow_0074610252_django_django_4.1_django_modeladmin_django_models_python.txt |
Q:
sys.exit() GCP Cloud Function
Have written GCP Cloud Function in Python 3.7. While executing, sys.exit() I'm getting 'A server error occurred ...'. I need to exit out of the function and have written following code.
import sys
if str(strEnabled) == 'True':
printOperation = "Operation: Enabling of user"
... | sys.exit() GCP Cloud Function | Have written GCP Cloud Function in Python 3.7. While executing, sys.exit() I'm getting 'A server error occurred ...'. I need to exit out of the function and have written following code.
import sys
if str(strEnabled) == 'True':
printOperation = "Operation: Enabling of user"
else:
sys.exit() #Exit From... | [
"Use return instead of sys.exit\nCopied from bigbounty's comment\n",
"If you are calling a function from another function and needs to directly exit from the inner function without return you can use abort.\nabort will directly return the response and exit the program from the place you are calling it.\nimport sy... | [
3,
0
] | [] | [] | [
"google_cloud_functions",
"google_cloud_platform",
"python"
] | stackoverflow_0063090501_google_cloud_functions_google_cloud_platform_python.txt |
Q:
Get the column names for 2nd largest value for each row in a Pandas dataframe
Say I have such Pandas dataframe
df = pd.DataFrame({
'a': [4, 5, 3, 1, 2],
'b': [20, 10, 40, 50, 30],
'c': [25, 20, 5, 15, 10]
})
so df looks like:
print(df)
a b c
0 4 20 25
1 5 10 20
2 3 40 5
3 1 50 15
4... | Get the column names for 2nd largest value for each row in a Pandas dataframe | Say I have such Pandas dataframe
df = pd.DataFrame({
'a': [4, 5, 3, 1, 2],
'b': [20, 10, 40, 50, 30],
'c': [25, 20, 5, 15, 10]
})
so df looks like:
print(df)
a b c
0 4 20 25
1 5 10 20
2 3 40 5
3 1 50 15
4 2 30 10
And I want to get the column name of the 2nd largest value in each row... | [
"Use numpy.argsort for positions of second largest values:\ndf['new'] = df['new'] = df.columns.to_numpy()[np.argsort(df.to_numpy())[:, -2]]\nprint(df)\n a b c new\n0 4 20 25 b\n1 5 10 20 b\n2 3 40 5 c\n3 1 50 15 c\n4 2 30 10 c\n\nYour solution should working, but is slow:\ndef second... | [
4,
2
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074612525_dataframe_numpy_pandas_python.txt |
Q:
maximum word split
Given a string s and a dictionary of valid words d, determine the largest number of valid words the string
can be split up into.
I tried solving this problem with the code below but it is not giving me the answer I am looking for.
def word_split_dp(s):
n = len(s)
ans = [0]*n
# base c... | maximum word split | Given a string s and a dictionary of valid words d, determine the largest number of valid words the string
can be split up into.
I tried solving this problem with the code below but it is not giving me the answer I am looking for.
def word_split_dp(s):
n = len(s)
ans = [0]*n
# base case
ans[0] = 0
f... | [
"There are a few issues in your attempt. Starting from the top:\n\nAssuming that ans[i] represents the maximum number of partitions of the substring s[0:i] into valid words, you'll need to make this list one entry longer, so that there is an ans[n], which will eventually contain the answer, i.e. the maximum number ... | [
0
] | [] | [] | [
"algorithm",
"python",
"word_break"
] | stackoverflow_0074606098_algorithm_python_word_break.txt |
Q:
Problem with matplotlib events (plot does not appear)
In the documentation about event handling, we have an interesting example (the "Picking excercise")
I am interested in something similar but instead of a new window appearing every time a point is picked in the first window (as it is now) I would like to change... | Problem with matplotlib events (plot does not appear) | In the documentation about event handling, we have an interesting example (the "Picking excercise")
I am interested in something similar but instead of a new window appearing every time a point is picked in the first window (as it is now) I would like to change the plot of the same second window.
So I did
"""
Compute t... | [
"I have made small test on your code, changing the last line of your onpick function to figR.canvas.draw() solve the issue for me, the function should look like:\ndef onpick(event):\n if event.artist != line:\n return\n n = len(event.ind)\n if not n:\n return\n print(\"Index \",event.ind)\... | [
1
] | [] | [] | [
"events",
"matplotlib",
"python"
] | stackoverflow_0074609730_events_matplotlib_python.txt |
Q:
How to nest a "for i in range()" loop in another loop that takes data from a dictionary?
The following code runs 599 instances of bootstrapping using data stored in the dictionary data_rois. data_rois is a dictionary that includes many keys and each key is associated with an array of numeric values. This part of t... | How to nest a "for i in range()" loop in another loop that takes data from a dictionary? | The following code runs 599 instances of bootstrapping using data stored in the dictionary data_rois. data_rois is a dictionary that includes many keys and each key is associated with an array of numeric values. This part of the code works fine when it is coded as below:
boot_i = []
for i in range(599):
boot = np.r... | [
"It is partially unclear what you are trying to do since you didn't provide a minimal reproducible example. I've filled in as best I can and I think this should still help you solve your problem. You may need to adjust the type of aggregation to fit your needs.\nYour for loop is of course executing as many times as... | [
2,
1
] | [] | [] | [
"dictionary",
"for_loop",
"python"
] | stackoverflow_0074611900_dictionary_for_loop_python.txt |
Q:
Azure function returns 503 after 30 seconds
I created an Azure function in python to insert data into SQL server. The process was taking around a minute when I was locally testing it. But when I deployed the code, I ended up receiving 403 error as shown below.
After debugging, I realized the data was successfully ... | Azure function returns 503 after 30 seconds | I created an Azure function in python to insert data into SQL server. The process was taking around a minute when I was locally testing it. But when I deployed the code, I ended up receiving 403 error as shown below.
After debugging, I realized the data was successfully persisted in the database(the whole 1 min process... | [
"In Azure Functions, HTTP Error 503 Service Unavailable can be caused due to few reasons like:\n\nThe backend server returned 503 due to a memory leak/issue in the code.\nPlatform issue due to the backend server not running/ allocated\nFunction host is down/restarting.\n\n\nHave a look into the \"Diagnose and Solve... | [
0,
0
] | [] | [] | [
"azure",
"azure_functions",
"python",
"serverless"
] | stackoverflow_0071658591_azure_azure_functions_python_serverless.txt |
Q:
How do I delete a file from a folder in Python?
I do know about os.remove() I am working on - When an excel file is created into a folder then the script runs and it will add the excel file data into the particular columns of the table of database. What I want is the file should be deleted from that folder just af... | How do I delete a file from a folder in Python? | I do know about os.remove() I am working on - When an excel file is created into a folder then the script runs and it will add the excel file data into the particular columns of the table of database. What I want is the file should be deleted from that folder just after running the script so that when a new excel file ... | [
"You could use os.listdir() to list all files of a given folder.\nThen you could either delete all files or delete files based on their file name or file type/suffix.\nE. g.:\nimport os\nfrom pathlib import Path\n\nfiles = os.listdir(\"your/path\")\nfor file in files:\n os.remove(file) # delete all files\n\n ... | [
1
] | [] | [] | [
"delete_file",
"python"
] | stackoverflow_0074612487_delete_file_python.txt |
Q:
Azure function python: blob.set method store empty file in blob container through output binding
An azure function is triggered via blob trigger event.
Trigger gives a csv file as myblob to the function from
new-container.
The function also gets base.csv as base from base-container.
Both CSV files are read via pa... | Azure function python: blob.set method store empty file in blob container through output binding | An azure function is triggered via blob trigger event.
Trigger gives a csv file as myblob to the function from
new-container.
The function also gets base.csv as base from base-container.
Both CSV files are read via pandas library.
Some processing is done to create df_final.
df_final is converted to string representati... | [
"After reproducing from my end, this was working fine. I believe that the there is no value that is getting returned from process_data. Make sure there is no null value that is getting returned from process_data. Below is a sample code that I used in process_data which gave me expected results.\ndef process_data(df... | [
0
] | [] | [] | [
"azure",
"azure_blob_storage",
"azure_functions",
"csv",
"python"
] | stackoverflow_0074600764_azure_azure_blob_storage_azure_functions_csv_python.txt |
Q:
Why does Python Pandas read the string of an excel file as datetime
I have the following questions.
I have Excel files as follows:
When i read the file using
df = pd.read_excel(file,dtype=str).
the first row turned to 2003-02-14 00:00:00 while the rest are displayed as it is.
How do i prevent pd.read_excel() from... | Why does Python Pandas read the string of an excel file as datetime | I have the following questions.
I have Excel files as follows:
When i read the file using
df = pd.read_excel(file,dtype=str).
the first row turned to 2003-02-14 00:00:00 while the rest are displayed as it is.
How do i prevent pd.read_excel() from converting its value into datetime or something else?
Thanks!
| [
"As @ddejohn correctly said it in the comments, the behavior you face is actually coming from Excel, automatically converting the data to date. Thus pandas will have to deal with that data AS date, and treat it later to get the correct format back as you expect, as like you say you cannot modify the input Excel fil... | [
0
] | [] | [] | [
"excel",
"pandas",
"python"
] | stackoverflow_0074609395_excel_pandas_python.txt |
Q:
Get sort string array by column value in a pandas DataFrame
Be the following python pandas DataFrame.
| date | days | country |
| ------------- | ---------- | --------- |
| 2022-02-01 | 1 | Spain |
| 2022-02-02 | 2 | Spain |
| 2022-02-01 | 3 | Italy ... | Get sort string array by column value in a pandas DataFrame | Be the following python pandas DataFrame.
| date | days | country |
| ------------- | ---------- | --------- |
| 2022-02-01 | 1 | Spain |
| 2022-02-02 | 2 | Spain |
| 2022-02-01 | 3 | Italy |
| 2022-02-03 | 2 | France |
| 2022-02-03 | 1 ... | [
"Firat aggreagte sum, then sorting values and convert to DataFrame:\ndf1 = (df.groupby('country')['days']\n .sum()\n .sort_values(ascending=False)\n .reset_index(name='count_days'))\nprint (df1)\n country count_days\n0 Spain 8\n1 Italy 4\n2 UK ... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074612716_dataframe_pandas_python.txt |
Q:
Scrape all elements inside a li tag
I'm trying to scrape some information from the a Kaggle page. All the elements I'm looking for are in <ul role="list" class="km-list km-list--three-line">. And each element decomposes within the <li role="listitem" class="sc-jfmDQi hfJycS">. I'm trying to scrape all these elemen... | Scrape all elements inside a li tag | I'm trying to scrape some information from the a Kaggle page. All the elements I'm looking for are in <ul role="list" class="km-list km-list--three-line">. And each element decomposes within the <li role="listitem" class="sc-jfmDQi hfJycS">. I'm trying to scrape all these elements from this page. Here is an HTML exampl... | [
"The page loads data dynamically using an API, so you don't see that data when u try to get it. U need to figure out which query provides the information and what data is required to get it. I made a small example where we get the necessary tokens and information via api. Next change page varible to get new ids.\ni... | [
3
] | [] | [] | [
"beautifulsoup",
"python",
"python_3.x",
"web_scraping"
] | stackoverflow_0074611861_beautifulsoup_python_python_3.x_web_scraping.txt |
Q:
Printing not happening in python pika microservice consumer inside a docker-compose service
I am trying to receive messages from my pika producer. I am following along with this tutorial: https://www.youtube.com/watch?v=0iB5IPoTDts.
I can see that when I manually run docker-compose exec backend bash and then run p... | Printing not happening in python pika microservice consumer inside a docker-compose service | I am trying to receive messages from my pika producer. I am following along with this tutorial: https://www.youtube.com/watch?v=0iB5IPoTDts.
I can see that when I manually run docker-compose exec backend bash and then run python consumer.py, I can receive messages and they are being logged to stdout through the print()... | [
"You need to actually start consuming messages. As it is right now you have a function called callback that never gets called (and is never referenced in your code).\nchannel.basic_consume(queue='main', on_message_callback=callback)\nchannel.start_consuming()\n\nAdd these lines at the end of your code. This will as... | [
0,
0
] | [] | [] | [
"cloudamqp",
"docker",
"docker_compose",
"pika",
"python"
] | stackoverflow_0065444445_cloudamqp_docker_docker_compose_pika_python.txt |
Q:
Send different number of arguments to a function in a Pythonic way
I'm trying to make a small function which calls another function from a library I import, I have 8 similar use cases but I don't want the code to be long and repeating.
each time I send the exact same function and with the same arguments but with d... | Send different number of arguments to a function in a Pythonic way | I'm trying to make a small function which calls another function from a library I import, I have 8 similar use cases but I don't want the code to be long and repeating.
each time I send the exact same function and with the same arguments but with different number of them.
Let me show an example of what I mean:
This is ... | [
"You can create a function that accepts any amount of arguments using the unpack operater *.\nHere is an example of a function that takes any amount of arguments:\n\ndef my_awesome_function(*args):\n # do awesome job!\n print(args)\n\n # depending on len of args do something...\n\n\nOr if you always have a on... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074612684_python.txt |
Q:
batch_distance.cpp:274: error: (-215:Assertion failed)
` I have the following code :
import cv2
import os
from os import listdir
import numpy as np
from PIL import Image
from tabulate import tabulate
import itertools
#sift
sift = cv2.SIFT_create()
#feature matching
bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=Tr... | batch_distance.cpp:274: error: (-215:Assertion failed) | ` I have the following code :
import cv2
import os
from os import listdir
import numpy as np
from PIL import Image
from tabulate import tabulate
import itertools
#sift
sift = cv2.SIFT_create()
#feature matching
bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)
# get the path/directory
folder_dir = "./runs/myDetect... | [
"Please try the same code with steps in below\n\nFirst :\n\nall_descriptors.append(descriptors)\n\n\nthen :\n\na=np.array(a).astype('float32')\n\n"
] | [
0
] | [] | [] | [
"feature_extraction",
"opencv",
"python",
"sift"
] | stackoverflow_0074612128_feature_extraction_opencv_python_sift.txt |
Q:
Extract all matches unless string contains
I am using the re package's re.findall to extract terms from strings. How can I make a regex to say capture these matches unless you see this substring (in this case the substring "fake"). I attempted this via a anchored look-ahead solution.
Current Output:
import re
f... | Extract all matches unless string contains | I am using the re package's re.findall to extract terms from strings. How can I make a regex to say capture these matches unless you see this substring (in this case the substring "fake"). I attempted this via a anchored look-ahead solution.
Current Output:
import re
for x in ['a man dogs', "fake: too many dogs", 'h... | [
"Since re does not support unknown length lookbehind patterns, the plain regex solution is not possible. However, the PyPi regex library supports such lookbehind patterns.\nAfter installing PyPi regex, you can use\n(?<!fake.*)(man[a-z]?\\b|dog)(?!.*fake)\n\nSee the regex demo.\nDetails:\n\n(?<!fake.*) - a negative ... | [
1,
1
] | [] | [] | [
"python",
"python_3.x",
"python_re",
"regex"
] | stackoverflow_0074607870_python_python_3.x_python_re_regex.txt |
Q:
Python ibm_db equivalent of db2look
SO I am using ibm_db library for fetch necessary information. Now I want to get the full table creation script along with index and all. I can see there is one db2look command to generate the same
db2look -d some_db -z xxxx -t xxxx -e -i xxxx-w xxxx -o script.sql
Is there an eq... | Python ibm_db equivalent of db2look | SO I am using ibm_db library for fetch necessary information. Now I want to get the full table creation script along with index and all. I can see there is one db2look command to generate the same
db2look -d some_db -z xxxx -t xxxx -e -i xxxx-w xxxx -o script.sql
Is there an equivalent thing in ibm_db?
| [
"No, there is not an exact equivalent in the python ibm_db for the db2look tool.\nAlternative approaches exist.\nNothing (except suitable authorities/permissions) prevents you from running a stored procedure that exececutes (i.e. shells out to) db2look on the database-server and return its output to the python scri... | [
1
] | [] | [] | [
"db2",
"python"
] | stackoverflow_0074612459_db2_python.txt |
Q:
CSS static file is not loading in Django
I am learning Django and i tried to implement a blog app . i am getting an error while using the static files inside project.i know, There are lot of questions with the same title. But i tried every way, still its not rendering the css file on the browser.
Folder structure... | CSS static file is not loading in Django | I am learning Django and i tried to implement a blog app . i am getting an error while using the static files inside project.i know, There are lot of questions with the same title. But i tried every way, still its not rendering the css file on the browser.
Folder structure:
firstBlog is the project name.
blog is the a... | [
"I'll try to help, but I'm not an expert!\nThe reason why http://127.0.0.1:8000/blog/static_files/blog/main.css is working is because you are accessing the main.css file directly. I would assume that your <link rel=\"stylesheet\" type=\"text/css\" href=\"{% static 'blog/main.css' % }\"> is not pointing to the corre... | [
2,
2,
0,
0
] | [] | [] | [
"css",
"django",
"django_staticfiles",
"python",
"python_3.x"
] | stackoverflow_0059688135_css_django_django_staticfiles_python_python_3.x.txt |
Q:
Change color of figures with PyOpenGL
I have to do a basic program in Python using the library Opengl...when somebody press the key 'r', the figure change to red, when somebody pressed key 'g' change green and when somebody pressed 'b' change blue. I don't know why the color doesn't change, but i know the program ... | Change color of figures with PyOpenGL | I have to do a basic program in Python using the library Opengl...when somebody press the key 'r', the figure change to red, when somebody pressed key 'g' change green and when somebody pressed 'b' change blue. I don't know why the color doesn't change, but i know the program know when a key is pressed, this is my code... | [
"I suspect that because the 2nd line in dibujarCirculo resets glColor3f to (0,0,0), you keep losing the change you made in keyPressed. Have you tried initializing glColor3f somewhere other than dibujarCirculo ?\n",
"You can do something like this where you store the current shape color globally and update that wh... | [
0,
0
] | [] | [] | [
"opengl",
"pyopengl",
"python",
"python_2.7"
] | stackoverflow_0028523120_opengl_pyopengl_python_python_2.7.txt |
Q:
How does one show x10(superscript number) instead of 1e(number) for axes in matplotlib?
The only way I know how to use scientific notation for the end of the axes in matplotlib is with
plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
but this will use 1e instead of x10. In the example code below it sho... | How does one show x10(superscript number) instead of 1e(number) for axes in matplotlib? | The only way I know how to use scientific notation for the end of the axes in matplotlib is with
plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
but this will use 1e instead of x10. In the example code below it shows 1e6, but I want x10 to the power of 6, x10superscript6 (x10^6 with the 6 small and no ^). ... | [
"The offset is formatted differently depending on the useMathText argument. If True it will show the offset in a latex-like (MathText) format as x 10^6 instead of 1e6\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.figure()\nx = np.linspace(0,1000)\ny = x**2\nplt.plot(x,y)\nplt.ticklabel_format(style='sci... | [
4,
0
] | [] | [] | [
"matplotlib",
"python",
"python_3.x"
] | stackoverflow_0054354823_matplotlib_python_python_3.x.txt |
Q:
python GPU memory exploding?
I'm having a hard time understanding why the memory of my GPU explodes whenever I run the following function to extract the CLIP embedding of images or captions:
def get_features(item):
"""
Function returning the clip embedding of an image or a caption, to be used to compute th... | python GPU memory exploding? | I'm having a hard time understanding why the memory of my GPU explodes whenever I run the following function to extract the CLIP embedding of images or captions:
def get_features(item):
"""
Function returning the clip embedding of an image or a caption, to be used to compute the similarity.
----
Argumen... | [] | [] | [
"I don't see why your GPU RAM is exploding. Perhaps it helps if you debug your code following here:\nhttps://discuss.pytorch.org/t/how-to-debug-causes-of-gpu-memory-leaks/6741/13\nimport torch\nimport gc\nfor obj in gc.get_objects():\n try:\n if torch.is_tensor(obj) or (hasattr(obj, 'data') and torch.is_t... | [
-1
] | [
"clip",
"gpu",
"memory",
"python"
] | stackoverflow_0074612575_clip_gpu_memory_python.txt |
Q:
How to pull value from a column when several columns match in two data frames?
I am trying to write a script which will search a database similar to that in Table 1 based on a product/region/year specification outlined in table 2. The plan is to search for a match in Table 1 to a specification outlined in Table 2 ... | How to pull value from a column when several columns match in two data frames? | I am trying to write a script which will search a database similar to that in Table 1 based on a product/region/year specification outlined in table 2. The plan is to search for a match in Table 1 to a specification outlined in Table 2 and then pull the observation value, as seen in Table 2 - with results.
I need this ... | [
"You can perform a merge operation and provide a list of columns that you want from Table_1.\nimport pandas as pd\n\nTable_1 = pd.DataFrame({\n \"Product_L1\":[\"Portland cement\", \"Portland cement\", \"Portland cement\", \"Portland cement\", \"Portland cement\", \"Portland cement\", \"Portland cement\"],\n ... | [
1
] | [] | [] | [
"match",
"python",
"where_clause"
] | stackoverflow_0074612422_match_python_where_clause.txt |
Q:
Original system and bakeoff meaning in NLP
So I am doing this homework in the one of standford courses and I managed to solve all the questions but I am trying to understand the last and correct me if I am wrong.
One it says build original system: That is building the model
The other one is bake off: That is compa... | Original system and bakeoff meaning in NLP | So I am doing this homework in the one of standford courses and I managed to solve all the questions but I am trying to understand the last and correct me if I am wrong.
One it says build original system: That is building the model
The other one is bake off: That is comparing different models to each other to see the b... | [
"Backoff means you go back to a n-1 gram level to calculate the probabilities when you encounter a word with prob=0. So in our case you will use a 3-gram model to calculate the probability of \"sunny\" in the context \"is a very\".\nThe most used scheme is called \"stupid backoff\" and whenever you go back 1 level ... | [
2
] | [] | [] | [
"nlp",
"python"
] | stackoverflow_0074612797_nlp_python.txt |
Q:
How can I use matplotlib.pyplot in a docker container?
I have a certain setting of Python in an docker image named deep. I used to run python code
docker run --rm -it -v "$PWD":/app -w /app deep python some-code.py
For information, -v and -w options are to link a local file in the current path to the container.
H... | How can I use matplotlib.pyplot in a docker container? | I have a certain setting of Python in an docker image named deep. I used to run python code
docker run --rm -it -v "$PWD":/app -w /app deep python some-code.py
For information, -v and -w options are to link a local file in the current path to the container.
However, I can't use matplotlib.pyplot. Let's say test.py is ... | [
"Interestingly, I found quite nice and thorough solutions in ROS community. http://wiki.ros.org/docker/Tutorials/GUI\nFor my problem, my final choice is the second way in the tutorial:\ndocker run --rm -it \\\n --user=$(id -u) \\\n --env=\"DISPLAY\" \\\n --workdir=/app \\\n --volume=\"$PWD\":/app \\\n --v... | [
25,
3,
3,
0,
0
] | [] | [] | [
"docker",
"matplotlib",
"python"
] | stackoverflow_0046018102_docker_matplotlib_python.txt |
Q:
Get pandas column where two column values are equal
I want to subset a DataFrame by two columns in different dataframes if the values in the columns are the same. Here is an example of df1 and df2:
df1
A
0 apple
1 pear
2 orange
3 apple
df2
B
0 apple
1 orange
2 orange
3 pear
I wou... | Get pandas column where two column values are equal | I want to subset a DataFrame by two columns in different dataframes if the values in the columns are the same. Here is an example of df1 and df2:
df1
A
0 apple
1 pear
2 orange
3 apple
df2
B
0 apple
1 orange
2 orange
3 pear
I would like the output to be a subsetted df1 based upon the d... | [
"If need compare index values with both columns create Multiindex and use Index.isin:\ndf = df1[df1.set_index('A', append=True).index.isin(df2.set_index('B', append=True).index)]\nprint (df)\n A\n0 apple\n2 orange\n\n"
] | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074612960_pandas_python.txt |
Q:
Flask Form Action is not referring to the variable
I have a form and am passing the variable as below using Jinja template
<form action = "/user_data/{{period}}" method="POST">
It is not redirecting required page /user_data/Oct-2022
But while just using {{period}} for testing in html page, variable is returning t... | Flask Form Action is not referring to the variable | I have a form and am passing the variable as below using Jinja template
<form action = "/user_data/{{period}}" method="POST">
It is not redirecting required page /user_data/Oct-2022
But while just using {{period}} for testing in html page, variable is returning the result as Oct-2022. Not sure why the same variable is... | [
"First we imported the Flask class. An instance of this class will be our WSGI application.\nNext we create an instance of this class. The first argument is the name of the application’s module or package. If you are using a single module (as in this example), you should use name because depending on if it’s starte... | [
0
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074612765_flask_python.txt |
Q:
Convert a String representation of a Dictionary to a dictionary
How can I convert the str representation of a dict, such as the following string, into a dict?
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
I prefer not to use eval. What else can I use?
The main reason for this, is one of my coworkers classes he wrote... | Convert a String representation of a Dictionary to a dictionary | How can I convert the str representation of a dict, such as the following string, into a dict?
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
I prefer not to use eval. What else can I use?
The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the mood to go and modi... | [
"You can use the built-in ast.literal_eval:\n>>> import ast\n>>> ast.literal_eval(\"{'muffin' : 'lolz', 'foo' : 'kitty'}\")\n{'muffin': 'lolz', 'foo': 'kitty'}\n\nThis is safer than using eval. As its own docs say:\n\n>>> help(ast.literal_eval)\nHelp on function literal_eval in module ast:\n\nliteral_eval(node_or_... | [
1594,
368,
225,
52,
31,
25,
20,
11,
7,
6,
0
] | [] | [] | [
"dictionary",
"python",
"string"
] | stackoverflow_0000988228_dictionary_python_string.txt |
Q:
Where does pip3 install package binaries?
It see that depending on system and configuration, packages are installed in different places.
Example:
Machine 1:
pip3 install fb-idb
pip3 show fb-idb
> ...
> /opt/homebrew/lib/python3.9/site-packages
Machine 2:
pip3 install fb-idb
pip3 show fb-idb
> ...
> /us/local/li... | Where does pip3 install package binaries? | It see that depending on system and configuration, packages are installed in different places.
Example:
Machine 1:
pip3 install fb-idb
pip3 show fb-idb
> ...
> /opt/homebrew/lib/python3.9/site-packages
Machine 2:
pip3 install fb-idb
pip3 show fb-idb
> ...
> /us/local/lib/python3.10/site-packages
Now the problem I h... | [
"pip3 show --files fb-idb shows where pip has installed all the files of the package. Run\npip3 show --files fb-idb | grep -F /bin/\n\nto extract the directory where pip installed scripts and entry points (On Windows it's \\Scripts\\). The directories are related to the header Location: so either do grep -F Locatio... | [
1
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0074597855_pip_python.txt |
Q:
Fails using multiprocessing in decorators (Can't pickle : it's not the same object as __main__.test_func)
I want to use decorator with multiprocessing to stop function test_func by timout.
When I don't use decorator (commited just_func()), process with test_func killed successfully. But when I do the same in decor... | Fails using multiprocessing in decorators (Can't pickle : it's not the same object as __main__.test_func) | I want to use decorator with multiprocessing to stop function test_func by timout.
When I don't use decorator (commited just_func()), process with test_func killed successfully. But when I do the same in decorator function_to_process I've got the error message:
_pickle.PicklingError: Can't pickle <function test_func at... | [
"I've found the solution here Windows: using decorator with multiprocessing\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074562015_python.txt |
Q:
Generate Header file for C code using python script
I am trying to generate a header file for C code using pyhton script.
I want to read some variables from csv file, the problem that i cant use libraries in the c code so i am not able to read the csv file from the c code.
I need to develop python script able to c... | Generate Header file for C code using python script | I am trying to generate a header file for C code using pyhton script.
I want to read some variables from csv file, the problem that i cant use libraries in the c code so i am not able to read the csv file from the c code.
I need to develop python script able to create a kind of simple input list to this C code.
Any sug... | [
"\nI want to read some variables from csv file, the problem that i cant use libraries in the c code so i am not able to read the csv file from the c code.\n\nAnd you don't need to. Simply this is how the file gets generated:\n[CSV File] -> Python -> [.h file]\n\nSo, you actually need to parse and convert the file i... | [
1
] | [] | [] | [
"c",
"python"
] | stackoverflow_0074612751_c_python.txt |
Q:
What is the most efficient way to extract and process files from the link?
I am able to browse all the links I need, but these links are redirecting me to the websites which have another links with pdf files, I have to open and process these pdfs. But I do not know what is the most efficient way to do it
import re... | What is the most efficient way to extract and process files from the link? | I am able to browse all the links I need, but these links are redirecting me to the websites which have another links with pdf files, I have to open and process these pdfs. But I do not know what is the most efficient way to do it
import requests
from bs4 import BeautifulSoup
import re
url = 'https://oeil.secure.euro... | [
"For all links that you crawl from the main url, you need to do exactly the same as before (request, bs4, extract hrefs).\n\nThen check if href of link ends with \".pdf\"\nIf href is a relative path of the pdf file, use urllib to extract the domain from the website url and concatenate the domain and the pdf file na... | [
1,
0
] | [] | [] | [
"beautifulsoup",
"parsing",
"pdf",
"python",
"web_scraping"
] | stackoverflow_0074612624_beautifulsoup_parsing_pdf_python_web_scraping.txt |
Q:
How to get first n characters from another column that doesn't contain specific characters
I have this dataframe
ID
product name
1BJM10
1BJM10_RS2022_PK
L_RS2022_PK
2PKL10_RS2022_PK
3BDG10_RS2022_PK
1BJM10
1BJM10_RS2022_PK
My desired output is like this
ID
product name
1BJM10
1BJM10_RS2022_PK
-
L_RS2022_... | How to get first n characters from another column that doesn't contain specific characters | I have this dataframe
ID
product name
1BJM10
1BJM10_RS2022_PK
L_RS2022_PK
2PKL10_RS2022_PK
3BDG10_RS2022_PK
1BJM10
1BJM10_RS2022_PK
My desired output is like this
ID
product name
1BJM10
1BJM10_RS2022_PK
-
L_RS2022_PK
2PKL10
2PKL10_RS2022_PK
3BDG10
3BDG10_RS2022_PK
1BJM10
1BJM10_RS... | [
"Chain both conditions by & for bitwise AND with helper Series:\ns = df['product name'].str[:6]\ndf.loc[df['ID'].isna() & ~s.str.contains(\"_\"), 'ID'] = s\nprint (df)\n ID product name\n0 1BJM10 1BJM10_RS2022_PK\n1 NaN L_RS2022_PK\n2 2PKL10 2PKL10_RS2022_PK\n3 3BDG10 3BDG10_RS2022_PK\n4 ... | [
2,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074612969_pandas_python.txt |
Q:
Displaying country in choropleth map - UnicodeDecodeError: 'charmap' codec can't decode byte 0x88
I'm trying to display unemployment of Czech Republic's counties in choropleth map.
I have json coordinates and unemployment data saved in csv file. But Im getting this error:
UnicodeDecodeError: 'charmap' codec can't... | Displaying country in choropleth map - UnicodeDecodeError: 'charmap' codec can't decode byte 0x88 | I'm trying to display unemployment of Czech Republic's counties in choropleth map.
I have json coordinates and unemployment data saved in csv file. But Im getting this error:
UnicodeDecodeError: 'charmap' codec can't decode byte 0x88 in position
211750: character maps to undefined.
Which is weird because when I run t... | [] | [] | [
"It's because your json file is UTF-8. Add the UTF-8 enconding to your Choropleth class parameters:\nchoropleth = folium.Choropleth(\ngeo_data=state_geo,\nname='choropleth',\ndata=state_data,\ncolumns=['Name', 'Un'],\nkey_on='feature.id',\nfill_color='YlGn',\nfill_opacity=0.7,\nline_opacity=0.2,\nlegend_name='Unemp... | [
-1
] | [
"choropleth",
"csv",
"folium",
"pandas",
"python"
] | stackoverflow_0062570459_choropleth_csv_folium_pandas_python.txt |
Q:
how to remove some entries from json file using python?
How to remove some entries from a JSON file using python?
I have a JSON file that looks like this:
json_data = [
{
"authType": "ldap",
"password": "",
"permissions": [
{
"collections": [
... | how to remove some entries from json file using python? | How to remove some entries from a JSON file using python?
I have a JSON file that looks like this:
json_data = [
{
"authType": "ldap",
"password": "",
"permissions": [
{
"collections": [
"aks9099",
"aks9098",
... | [
"You can analyse recursively you input data and remove all forbidden values:\ndef filter_data(data, forbidden_values):\n if isinstance(data, str):\n return data\n if isinstance(data, dict):\n return {\n key: filter_data(value, forbidden_values) for key, value in data.items()\n ... | [
0
] | [] | [] | [
"json",
"python",
"python_3.x"
] | stackoverflow_0074611405_json_python_python_3.x.txt |
Q:
Error converting Detectron2 torchscript model to CoreML using coremltools
I have a Detectron2 model that is trained to identify specific items on a backend server. I would like to make this model available on iOS devices and convert it to a CoreML model using coremltools v6.1. I used the export_model.py script p... | Error converting Detectron2 torchscript model to CoreML using coremltools | I have a Detectron2 model that is trained to identify specific items on a backend server. I would like to make this model available on iOS devices and convert it to a CoreML model using coremltools v6.1. I used the export_model.py script provided by Facebook to create a torchscript model, but when I try to convert th... | [
"From the error message it looks like you are using a torch script model:\n\nSupport for converting Torch Script Models is experimental. If\npossible you should use a traced model for conversion.\n\nif possible try to use a traced model e.g.:\ndummy_input = torch.randn(batch, channels, width, height)\ntraceable_mod... | [
0
] | [] | [] | [
"coreml",
"coremltools",
"detectron",
"python",
"torchscript"
] | stackoverflow_0074607629_coreml_coremltools_detectron_python_torchscript.txt |
Q:
Django 'model' object is not iterable when response
I have 2 model. And the two models are connected to the ManyToManyField.
models.py
class PostModel(models.Model):
id = models.AutoField(primary_key=True, null=False)
title = models.TextField()
comments = models.ManyToManyField('CommentModel')
class Co... | Django 'model' object is not iterable when response | I have 2 model. And the two models are connected to the ManyToManyField.
models.py
class PostModel(models.Model):
id = models.AutoField(primary_key=True, null=False)
title = models.TextField()
comments = models.ManyToManyField('CommentModel')
class CommentModel(models.Model):
id = models.AutoField(prima... | [
"Referring from this thread, you should remove many=True in PostModel_serializer.\nAlso it should be comment_list not comments_list.\n@api_view(['GET'])\ndef getPost(request, pk):\n post = PostModel.objects.filter(id=pk).first()\n comment_list = CommentModel.objects.filter(post_id=post.id)\n for i in comme... | [
1,
0
] | [] | [] | [
"django",
"django_queryset",
"django_rest_framework",
"django_serializer",
"python"
] | stackoverflow_0074612530_django_django_queryset_django_rest_framework_django_serializer_python.txt |
Q:
Change color of every 2-nd element on x axis and every 3-rd element on y-axis to black
I don't know what's wrong and why nothing worked for me. The picture is 500x500.
I tried using arrays and loops but It didn't work out. My code
from PIL import Image
picture_resized = picture.resize( (500,500) )
im = np.array(... | Change color of every 2-nd element on x axis and every 3-rd element on y-axis to black | I don't know what's wrong and why nothing worked for me. The picture is 500x500.
I tried using arrays and loops but It didn't work out. My code
from PIL import Image
picture_resized = picture.resize( (500,500) )
im = np.array(Image.open('Lenna.png').convert('RGB'))
Image.fromarray(im).save('result.png')
im[0::2,0::... | [
"You're close! This should do what you want:\nimport numpy as np\nfrom PIL import Image\n\n# Load image and make into Numpy array\nim = np.array(Image.open('artistic-swirl.jpg'))\n\n# Make every second element on x-axis black\nim[:, 0::2] = [0,0,0]\n\n# Make every third element on y-axis black\nim[::3, :] = [0,0,0]... | [
0
] | [] | [] | [
"image_processing",
"jupyter",
"jupyter_notebook",
"python"
] | stackoverflow_0074608032_image_processing_jupyter_jupyter_notebook_python.txt |
Q:
Machine learning options to detect errors in a large number of sql tables?
I'm new to ML and want to build a system that can detect errors or anomalies in input data that I receive from customers. The data is structured in sql tables with various column names. The value types for each column varies but the most co... | Machine learning options to detect errors in a large number of sql tables? | I'm new to ML and want to build a system that can detect errors or anomalies in input data that I receive from customers. The data is structured in sql tables with various column names. The value types for each column varies but the most common are numbers, strings and dates.
Some of the values in these tables will be ... | [
"\nNull values or empty strings: an ML algorithm will probably not accept such an input\nTruncated strings in numbers: ?\nString formatted numbers: numbers are always formatted as strings\nWeird date formats: an ML system will require huge samples before it learns rules that you can implement in two minutes\nBad or... | [
2
] | [] | [] | [
"algorithm",
"anomaly_detection",
"machine_learning",
"python"
] | stackoverflow_0074612829_algorithm_anomaly_detection_machine_learning_python.txt |
Q:
python boto3 for AWS - S3 Bucket Sync optimization
currently I am trying to compare two S3 buckets with the target to delete files.
problem defintion:
-BucketA
-BucketB
The script is looking for files (same key name) in BucketB which are not available in BucketA.
That files which are only available in BucketB have... | python boto3 for AWS - S3 Bucket Sync optimization | currently I am trying to compare two S3 buckets with the target to delete files.
problem defintion:
-BucketA
-BucketB
The script is looking for files (same key name) in BucketB which are not available in BucketA.
That files which are only available in BucketB have to be deleted.
The buckets contain about 3-4 Million fi... | [
"The ListBucket() API call only returns 1000 objects at a time, so listing buckets with 100,000+ objects is very slow and best avoided. You have 3-4 million objects, so definitely avoid listing them!\nInstead, use Amazon S3 Inventory, which can provide a daily or weekly CSV file listing all objects in a bucket. Act... | [
0
] | [] | [] | [
"amazon_web_services",
"boto3",
"paginator",
"python"
] | stackoverflow_0074611433_amazon_web_services_boto3_paginator_python.txt |
Q:
Extract output tensor from any layer of onnx model
I want to extract the output of different layers of an onnx model (e.g., squeezenet.onnx, etc.) during image inference. I am trying to use the code in [How to extract output tensor from any layer of models][1]:
# add all intermediate outputs to onnx net
or... | Extract output tensor from any layer of onnx model | I want to extract the output of different layers of an onnx model (e.g., squeezenet.onnx, etc.) during image inference. I am trying to use the code in [How to extract output tensor from any layer of models][1]:
# add all intermediate outputs to onnx net
ort_session = ort.InferenceSession('<you path>/model.onnx'... | [
"Unfortunately that is not possible. However you could re-export the original model from PyTorch to onnx, and add the output of the desired layer to the return statement of the forward method of your model. (you might have to feed it through a couple of methods up to the first forward method in your model)\n"
] | [
0
] | [] | [] | [
"conv_neural_network",
"image_processing",
"onnx",
"python",
"tensorflow"
] | stackoverflow_0074600082_conv_neural_network_image_processing_onnx_python_tensorflow.txt |
Q:
Resample hourly to daily and group by min, max and mean values
I have a hourly dataframe, df, and i need to create a new dataframe with the min, mean and max values from each day. Here's what i tried to do:
df = pd.DataFrame(np.random.rand(72, 1),
columns=["Random"],
index=p... | Resample hourly to daily and group by min, max and mean values | I have a hourly dataframe, df, and i need to create a new dataframe with the min, mean and max values from each day. Here's what i tried to do:
df = pd.DataFrame(np.random.rand(72, 1),
columns=["Random"],
index=pd.date_range(start="20220101000000", end="20220103230000", freq='H')... | [
"Use Resample.agg with list of functions, then reshape by DataFrame.stack and remove second level of MultiIndex by Series.droplevel:\ns = df.resample('D')['Random'].agg(['min','mean','max']).stack().droplevel(1)\nprint (s)\n2022-01-01 0.162976\n2022-01-01 0.574074\n2022-01-01 0.980742\n2022-01-02 0.0122... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074613251_pandas_python.txt |
Q:
Python issue with fitting a custom function containing double integrals
I want to fit some data using a custom function which contains a double integral. a,b, and c are pre-defined parameters, and alpha and beta are two angles on which the function must be integrated.
import numpy as np
from scipy import integrate... | Python issue with fitting a custom function containing double integrals | I want to fit some data using a custom function which contains a double integral. a,b, and c are pre-defined parameters, and alpha and beta are two angles on which the function must be integrated.
import numpy as np
from scipy import integrate
x=np.linspace(0,100,100)
a=100
b=5
c=1
def custom_function(x,a,b,c):
f = ... | [
"Are you sure you are not trying to multiply sinc functions, sin(x*u)/(x*u)? Currently you are multiplying terms like u * sin(x*u) / x because there are not parenthesis in the denominator.\nYou should be able to fit your function for small a,b,c. But having a = 100, you should have a much higher resolution, I would... | [
0
] | [] | [] | [
"custom_function",
"integral",
"numpy",
"python"
] | stackoverflow_0074612970_custom_function_integral_numpy_python.txt |
Q:
Apply a function row by row using other dataframes' rows as list inputs in python
I'm trying to apply a function row-by-row which takes 5 inputs, 3 of which are lists. I want these lists to come from each row of 3 correspondings dataframes.
I've tried using 'apply' and 'lambda' as follows:
sol['tf_dd']=sol.apply(l... | Apply a function row by row using other dataframes' rows as list inputs in python | I'm trying to apply a function row-by-row which takes 5 inputs, 3 of which are lists. I want these lists to come from each row of 3 correspondings dataframes.
I've tried using 'apply' and 'lambda' as follows:
sol['tf_dd']=sol.apply(lambda tsol, rfsol, rbsol:
taurho_difdif(xy=xy,
... | [
"Try to use \"name\" field in Series Type to get index value, and then get the same index for the other DataFrame\nimport pandas as pd\nimport numpy as np\n\n\ndef postional_sum(inot, df1, df2, df3):\n \"\"\"\n Get input index and gather the same position for the other DataFrame collection\n \"\"\"\n\n... | [
2,
0,
0
] | [] | [] | [
"apply",
"function",
"lambda",
"pandas",
"python"
] | stackoverflow_0074612434_apply_function_lambda_pandas_python.txt |
Q:
gaierror, NewConnectionError, MaxRetryError, ConnectionError with URL in requests
I am trying to check the response of the URL same as the domain record from the WHOIS database.
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
The code:
def abnormal_url(url):
resp... | gaierror, NewConnectionError, MaxRetryError, ConnectionError with URL in requests | I am trying to check the response of the URL same as the domain record from the WHOIS database.
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
The code:
def abnormal_url(url):
response = requests.get(url,verify=False)
domainname = urlparse(url).netloc
domain ... | [
"The connection could not be established because the site can't be reached.\nJust execute the get request inside your try/except and it will work.\ndef abnormal_url(url):\n domainname = urlparse(url).netloc\n domain = whois.whois(domainname)\n try:\n response = requests.get(url,verify=False)\n ... | [
1
] | [] | [] | [
"dataframe",
"jupyter_notebook",
"python",
"python_requests"
] | stackoverflow_0074613109_dataframe_jupyter_notebook_python_python_requests.txt |
Q:
Django logging custom attributes in formatter
How can Django use logging to log using custom attributes in the formatter? I'm thinking of logging the logged in username for example.
In the settings.py script, the LOGGING variable is defined:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
... | Django logging custom attributes in formatter | How can Django use logging to log using custom attributes in the formatter? I'm thinking of logging the logged in username for example.
In the settings.py script, the LOGGING variable is defined:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
... | [
"You can use a filter to add your custom attribute. For example :\ndef add_my_custom_attribute(record):\n record.myAttribute = 'myValue'\n record.username = record.request.user.username \n return True\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n ...\n... | [
33,
3,
2,
0
] | [] | [] | [
"django",
"logging",
"python"
] | stackoverflow_0044424040_django_logging_python.txt |
Q:
How to make a code faster to calculate the linear distances from the point Python?
Here is the code:
Outputs = []
for X2, Y2 in X:
Color_Gradient = 0
Lowest = 0
for X1, Y1, grad in zip(Velocity_Momentum[:, 0], Velocity_Momentum[:, 1], Color):
XD = X2 - X1
YD = Y2 - Y1
Distance ... | How to make a code faster to calculate the linear distances from the point Python? | Here is the code:
Outputs = []
for X2, Y2 in X:
Color_Gradient = 0
Lowest = 0
for X1, Y1, grad in zip(Velocity_Momentum[:, 0], Velocity_Momentum[:, 1], Color):
XD = X2 - X1
YD = Y2 - Y1
Distance = math.sqrt((XD * XD) + (YD * YD))
if Lowest == 0 or Lowest > Distance:
... | [
"It looks like you are using numpy arrays. With numpy, it is faster to use vectorized operations on whole arrays at the same time, compared to loops. It also usually gives cleaner code.\nAs I understand it, you want to extract the color corresponding to the smallest (euclidean) distance to a specific point.\nOutput... | [
3
] | [] | [] | [
"performance",
"process",
"python",
"python_3.x"
] | stackoverflow_0074612910_performance_process_python_python_3.x.txt |
Q:
How to optimize N+1 SQL queries when serializing a post with mptt comments?
I have the following serializer for a detailed post:
class ArticleDetailSerializer(serializers.ModelSerializer):
author = ArticleAuthorSerializer(read_only=True)
comments = CommentSerializer(many=True, read_only=True)
class Me... | How to optimize N+1 SQL queries when serializing a post with mptt comments? | I have the following serializer for a detailed post:
class ArticleDetailSerializer(serializers.ModelSerializer):
author = ArticleAuthorSerializer(read_only=True)
comments = CommentSerializer(many=True, read_only=True)
class Meta:
model = Article
fields = '__all__'
Comment Serializer:
class... | [
"This kind of solution worked for me.\nclass ArticleDetailSerializer(serializers.ModelSerializer):\n author = ArticleAuthorSerializer(read_only=True)\n comments = serializers.SerializerMethodField()\n\n class Meta:\n model = Article\n fields = '__all__'\n\n def get_comments(self, obj):\n ... | [
0
] | [] | [] | [
"django",
"django_mptt",
"django_rest_framework",
"python"
] | stackoverflow_0074612577_django_django_mptt_django_rest_framework_python.txt |
Q:
How to solve "type object 'datetime.datetime' has no attribute 'timedelta'" when creating a new date?
I'm using Django and Python 3.7. I'm trying to calculate a new datetime by adding a number of seconds to an existing datetime. From this -- What is the standard way to add N seconds to datetime.time in Python?, ... | How to solve "type object 'datetime.datetime' has no attribute 'timedelta'" when creating a new date? | I'm using Django and Python 3.7. I'm trying to calculate a new datetime by adding a number of seconds to an existing datetime. From this -- What is the standard way to add N seconds to datetime.time in Python?, I thought i could do
new_date = article.created_on + datetime.timedelta(0, elapsed_time_in_seconds)
where ... | [
"You've imported the wrong thing; you've done from datetime import datetime so that datetime now refers to the class, not the containing module.\nEither do:\nimport datetime\n...article.created_on + datetime.timedelta(...)\n\nor\nfrom datetime import datetime, timedelta\n...article.created_on + timedelta(...)\n\n"
... | [
8
] | [
"You should use the correct import:\nfrom datetime import timedelta\n\nnew_date = article.created_on + timedelta(0, elapsed_time_in_seconds)\n\n",
"I got the same issue, i solved it by replacing\nfrom datetime import datetime as my_datetime\nwith\nimport datetime as my_datetime\n"
] | [
-1,
-1
] | [
"datetime",
"django",
"python",
"python_3.x"
] | stackoverflow_0055340547_datetime_django_python_python_3.x.txt |
Q:
Not able to create table from CSV in Databricks
I am trying to create a table from a CSV file stored in Azure Storage Account. I am using the below code. I am using Azure Databricks. Notebook is in Python.
%sql
drop table if exists customer;
create table customer
using csv
options ( path "/mnt/datalake/data/Custo... | Not able to create table from CSV in Databricks | I am trying to create a table from a CSV file stored in Azure Storage Account. I am using the below code. I am using Azure Databricks. Notebook is in Python.
%sql
drop table if exists customer;
create table customer
using csv
options ( path "/mnt/datalake/data/Customer.csv", header "True", mode "FAILFAST", inferSchema... | [
"I have reproduced above and got the below results.\nThis my csv file in data container.\n\nThis is my mounting:\n\nI have mounted this and when I tried to create table from CSV file, I got same error.\n\nThe above error arises when we don't give correct path in the csv file. In file path after /mnt give mount poin... | [
0
] | [] | [] | [
"azure",
"azure_databricks",
"databricks",
"python",
"sql"
] | stackoverflow_0074605049_azure_azure_databricks_databricks_python_sql.txt |
Q:
How to return serialized JSON from Flask-SQLAlchemy relationship query?
i'm using Flask-SQLAlchemy and i have the following models with one to many relationship,
class User(db.Model):
# Table name
__tablename__ = "users"
# Primary key
user_id = db.Column(db.Integer, primary_key=True)
# Field... | How to return serialized JSON from Flask-SQLAlchemy relationship query? | i'm using Flask-SQLAlchemy and i have the following models with one to many relationship,
class User(db.Model):
# Table name
__tablename__ = "users"
# Primary key
user_id = db.Column(db.Integer, primary_key=True)
# Fields (A-Z)
email = db.Column(db.String(50), nullable=False, unique=True)
... | [
"As you said, you can simply write a second serializer method. So you keep the other one for your /uploads API call.\n# User serializer\ndef serialize_user(self):\n if self.uploads:\n uploads = [upload.serialize_upload_bis() for upload in self.uploads]\n return {\n \"email\": self.email,\n ... | [
0,
0
] | [] | [] | [
"flask_sqlalchemy",
"json",
"python",
"sqlalchemy"
] | stackoverflow_0049372413_flask_sqlalchemy_json_python_sqlalchemy.txt |
Q:
What is the behavior of `.close()` on a generator that has just started?
What is the behavior of .close() on a generator that has just started?
def gen():
while True:
yield 1
g = gen()
g.send(1)
throws TypeError: can't send non-None value to a just-started generator
def gen():
while True:
try:
... | What is the behavior of `.close()` on a generator that has just started? | What is the behavior of .close() on a generator that has just started?
def gen():
while True:
yield 1
g = gen()
g.send(1)
throws TypeError: can't send non-None value to a just-started generator
def gen():
while True:
try:
yield 1
except GeneratorExit:
print("exit")
... | [
"Quoting from the docs (shortened):\n\nRaises a GeneratorExit at the point where the generator function was\npaused.\n\n\nclose() does nothing if the generator has already exited\n\nWhen it was not started, it couldn't be paused or exited. The case it was not started (with an initial next or send) is not mentioned.... | [
1
] | [] | [] | [
"generator",
"python"
] | stackoverflow_0074611602_generator_python.txt |
Q:
Ordering by time block - Pandas and Altair
I have data that I am visualizing that is categorized by time block. The column looks something like this:
time column
I ultimately want to get to a point where I can order my data by this time block on the x axis of my chart, while plotting the corresponding value on the... | Ordering by time block - Pandas and Altair | I have data that I am visualizing that is categorized by time block. The column looks something like this:
time column
I ultimately want to get to a point where I can order my data by this time block on the x axis of my chart, while plotting the corresponding value on the y. Something like this:
example chart
The issue... | [
"My suggestion is not the perfect one, I didn't find the way to use your time blocks as axis labels. But it could be a starting point)\nSo here is my suggestion:\n\ncreate a separate column with start of your time blocks using split function and transforming this column to a datetime type\n\ndata['start_block']=dat... | [
0
] | [] | [] | [
"altair",
"datetime",
"pandas",
"python",
"x_axis"
] | stackoverflow_0074606014_altair_datetime_pandas_python_x_axis.txt |
Q:
Get only positive answers in a subtraction question python
I'm making a math game, i want my subtraction answers to only have positive integers, how do i do that? I don't want questions like 6-10 but questions like 10-6.
this is the code i tried to make, but it doesn't work. Any help and suggestions would be appre... | Get only positive answers in a subtraction question python | I'm making a math game, i want my subtraction answers to only have positive integers, how do i do that? I don't want questions like 6-10 but questions like 10-6.
this is the code i tried to make, but it doesn't work. Any help and suggestions would be appreciated, thanks.
import random
x=random.randint(1,10)
y=random.r... | [
"You can use built-in max and min functions:\ndef q():\n greater, smaller = max(x, y), min(x, y)\n que = int(input(\"what is {}-{}?\".format(greater, smaller)))\n ...\n\n",
"You can use:\ndef q(x, y):\n if y > x:\n return q(y, x)\n return int(input(\"what is {}-{}?\".format(x,y)))\n\n",
"Y... | [
2,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0062554315_python.txt |
Q:
Kubernetes deploy, how to solve : psycopg2.OperationalError: SCRAM authentication requires libpq version 10 or above?
I deployed a pod and service of a Flask API in Kubernetes.
When I run the Nifi processor InvoqueHTTP that calls the API, I have the error :
File "/opt/app-root/lib64/python3.8/site-packages/psycopg... | Kubernetes deploy, how to solve : psycopg2.OperationalError: SCRAM authentication requires libpq version 10 or above? | I deployed a pod and service of a Flask API in Kubernetes.
When I run the Nifi processor InvoqueHTTP that calls the API, I have the error :
File "/opt/app-root/lib64/python3.8/site-packages/psycopg2/__init__.py"
psycopg2.OperationalError: SCRAM authentication requires libpq version 10 or above
The API connects to PGA... | [
"For psycopg2.OperationalError: SCRAM authentication requires libpq version 10 or above follow the below work arounds:\nSolution :1\nDownload libpq.dll from https://www.exefiles.com/en/dll/libpq-dll/ then replace old libpq.dll at php directory with the latest downloaded\nSolution :2\nChange authentication to md5, ... | [
0
] | [] | [] | [
"kubernetes",
"psycopg2",
"python"
] | stackoverflow_0074612583_kubernetes_psycopg2_python.txt |
Q:
How to do with Pydantic regex validation?
I'm trying to write a validator with usage of Pydantic for following strings (examples):
1.1.0, 3.5.6, 1.1.2, etc..
I'm failing with following syntax:
install_component_version: constr(regex=r"^[0-9]+.[0-9]+.[0-9]$")
install_component_version: constr(regex=r"^([0-9])+.([0-... | How to do with Pydantic regex validation? | I'm trying to write a validator with usage of Pydantic for following strings (examples):
1.1.0, 3.5.6, 1.1.2, etc..
I'm failing with following syntax:
install_component_version: constr(regex=r"^[0-9]+.[0-9]+.[0-9]$")
install_component_version: constr(regex=r"^([0-9])+.([0-9])+.([0-9])$")
install_component_version: cons... | [
"The error you are facing is due to type annotation.\nAs per https://github.com/pydantic/pydantic/issues/156 this is not yet fixed, you can try using pydantic.Field and then pass the regex argument there like so\ninstall_component_version: str = Field(regex=r\"^[0-9]+.[0-9]+.[0-9]$\")\nThis way you get the regex va... | [
1
] | [] | [] | [
"pydantic",
"python"
] | stackoverflow_0074607041_pydantic_python.txt |
Q:
Jupyter - Split Classes in multiple Cells
I wonder if there is a possibility to split jupyter classes into different cells? Lets say:
#first cell:
class foo(object):
def __init__(self, var):
self.var = var
#second cell
def print_var(self):
print(self.var)
For more complex classes its real... | Jupyter - Split Classes in multiple Cells | I wonder if there is a possibility to split jupyter classes into different cells? Lets say:
#first cell:
class foo(object):
def __init__(self, var):
self.var = var
#second cell
def print_var(self):
print(self.var)
For more complex classes its really annoying to write them into one cell.
I wo... | [
"Two solutions were provided to this problem on Github issue \"Define a Python class across multiple cells #1243\" which can be found here: https://github.com/jupyter/notebook/issues/1243\nOne solution is using a magic function from a package developed for this specific case called jdc - or Jupyter dynamic classes.... | [
23,
8,
3,
1,
0,
0
] | [] | [] | [
"jupyter_notebook",
"python"
] | stackoverflow_0045161393_jupyter_notebook_python.txt |
Q:
Add reserved tokens to `tft.vocabulary`
I would like to append words to the vocabulary created by tft.vocabulary that are not a part of the training samples (i.e. <mask> and <pad> tokens).
I see in the docs that the tft.vocabulary function can take an argument key_fn which the docs says:
Supply key_fn if you woul... | Add reserved tokens to `tft.vocabulary` | I would like to append words to the vocabulary created by tft.vocabulary that are not a part of the training samples (i.e. <mask> and <pad> tokens).
I see in the docs that the tft.vocabulary function can take an argument key_fn which the docs says:
Supply key_fn if you would like to generate a vocabulary with coverage... | [
"What is it that you're trying to achieve?\nI don't think that key_fn is related as it only affects the ordering of the vocabulary (and top k when provided)\nCould you compute the vocabulary after appending the added information?\ntft.vocabulary(tf.strings.join([words, <mask>, <pad>]), ...)\nThis would result in th... | [
0
] | [] | [] | [
"mlops",
"python",
"tensorflow",
"tensorflow_transform",
"tfx"
] | stackoverflow_0071771353_mlops_python_tensorflow_tensorflow_transform_tfx.txt |
Q:
Parsing XML with python ElementTree: ParseError: mismatched tag
I have several XML files I have to parse through with python ElemetTree (they are legacy from another developer).
I've corrected those files a bit and parsed a good chunk so far but at some moment I got this parsing error, and I can't get around it. T... | Parsing XML with python ElementTree: ParseError: mismatched tag | I have several XML files I have to parse through with python ElemetTree (they are legacy from another developer).
I've corrected those files a bit and parsed a good chunk so far but at some moment I got this parsing error, and I can't get around it. Tried parsing the original file (i was working with a copy ofcourse), ... | [
"Take a look at line ParseError: mismatched tag: line 449, column 3.\nline 449 is the line number in your source XML file.\nFind this line and look what is wrong with the content.\nProbably this line contains some tag (e.g. closing) which has no\nopening conterpart.\nAn alternative: Visit any XML validation site an... | [
5,
0
] | [
"I find that sometimes you get this error at a line number a lot later than the actual error. It only notices something wrong when you close a tag that you didn't correctly open. Look earlier in the file.\nFor example I had a similar problem where the error message claimed\n\nxml.etree.ElementTree.ParseError: misma... | [
-1
] | [
"elementtree",
"parsing",
"python",
"xml",
"xml_parsing"
] | stackoverflow_0059909308_elementtree_parsing_python_xml_xml_parsing.txt |
Q:
Check if all key-value pairs are present in dictionary (pytest)
I am trying to write a test to check if all key-value pairs from the expected result are present in the actual result
import pytest
def common_pairs(dict1, dict2):
return {key: dict1[key] for key in dict1 if key in dict2 and dict1[key] == dict2[k... | Check if all key-value pairs are present in dictionary (pytest) | I am trying to write a test to check if all key-value pairs from the expected result are present in the actual result
import pytest
def common_pairs(dict1, dict2):
return {key: dict1[key] for key in dict1 if key in dict2 and dict1[key] == dict2[key]}
@pytest.mark.parametrize(
"input_data,expected", [({"a": ... | [
"I mean the most natural way to do this imo would be\nfor key,val in dict1.items():\n assert val == dict2[key]\n\n"
] | [
1
] | [] | [] | [
"pytest",
"python"
] | stackoverflow_0074613664_pytest_python.txt |
Q:
Find the highest value locations within an interval and for a specific index?
Given this pandas dataframe with three columns, 'room_id', 'temperature' and 'State'. How do I get a forth column 'Max' indicating wehn the value is a maximum for each interval where State is True and for each room ?
117 1.489000 Tr... | Find the highest value locations within an interval and for a specific index? | Given this pandas dataframe with three columns, 'room_id', 'temperature' and 'State'. How do I get a forth column 'Max' indicating wehn the value is a maximum for each interval where State is True and for each room ?
117 1.489000 True
8.9 False
2.5 False
4.370000 False
... | [
"You can use groupby.idxmax to get the index of the max per custom group:\n# get the indices of the max value per group\nidx = (df[df['State']].groupby(['room_id', (~df['State']).cumsum()])\n ['temperature'].idxmax()\n )\n\n# assign the new value\ndf.loc[idx, 'max_temp'] = 'max'\n\nIf you want the tempe... | [
0
] | [] | [] | [
"group_by",
"intervals",
"max",
"pandas",
"python"
] | stackoverflow_0074613397_group_by_intervals_max_pandas_python.txt |
Q:
Dataframe name with get_df_name(df) reset
I changed by mistake the name of the dataframe (no idea how, I was trying several things), and now I get the wrong name when calling get_df_name(df)
tables=[df1,df2,df3,df4,df5]
def get_df_name(df):
name = [x for x in globals() if globals()[x] is df][0]
return name... | Dataframe name with get_df_name(df) reset | I changed by mistake the name of the dataframe (no idea how, I was trying several things), and now I get the wrong name when calling get_df_name(df)
tables=[df1,df2,df3,df4,df5]
def get_df_name(df):
name = [x for x in globals() if globals()[x] is df][0]
return name
for i in tables:
print(get_df_name(i),list... | [] | [] | [
"Solved it after posting. Changed the variable in the for loop from i to smth else, it reset the whole thing. If anyone has an explanation, can write it for other people.\n"
] | [
-1
] | [
"dataframe",
"python"
] | stackoverflow_0074613860_dataframe_python.txt |
Q:
Pandas: AttributeError: 'module' object has no attribute '__version__'
When I try to import pandas into Python I get this error:
>>> import pandas
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/robertdefilippi/miniconda2/lib/python2.7/site-packages/pandas/__init__.py", line... | Pandas: AttributeError: 'module' object has no attribute '__version__' | When I try to import pandas into Python I get this error:
>>> import pandas
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/robertdefilippi/miniconda2/lib/python2.7/site-packages/pandas/__init__.py", line 44, in <module>
from pandas.core.api import *
File "/Users/robertdefi... | [
"Remove (or rename) the file matplotlib.py from your current working directory. It shadows the real library with the same name.\n",
"I have a simple solution,delete your __init__.pyc and __init__.py files in your project dictionary. because i encounter the problem too,I have been solve it perfectly use this metho... | [
12,
0,
0
] | [] | [] | [
"import",
"pandas",
"python"
] | stackoverflow_0034564249_import_pandas_python.txt |
Q:
merge chronological elements
I have a set of items that consists of the start and stop dates, as the following:
ID
started
stop
1
2019-01-14
2018-02-05
2
2019-01-14
2019-03-06
3
2019-03-07
2019-03-20->
4
Some-Date
NULL
5
2020-09-08
2020-09-14
6
2020-09-15
2020-10-14
7
->2019-03-21
2019-03-30
I would like ... | merge chronological elements | I have a set of items that consists of the start and stop dates, as the following:
ID
started
stop
1
2019-01-14
2018-02-05
2
2019-01-14
2019-03-06
3
2019-03-07
2019-03-20->
4
Some-Date
NULL
5
2020-09-08
2020-09-14
6
2020-09-15
2020-10-14
7
->2019-03-21
2019-03-30
I would like to merge those item... | [
"Do you have to use the Records-class? If not, pandas offers a very clean implementation of what you are looking for:\nimport datetime\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame([[datetime.date(2017, 8, 14), datetime.date(2018, 3, 5)],\n [datetime.date(2019, 1, 14), datetime.da... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074612181_python.txt |
Q:
do not run lemmatize of nltk package
Hello I Have a code for lemmatization a string in python . code is below
from nltk.stem.wordnet import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
print("better :", lemmatizer.lemmatize("better", pos ="a"))
but when it compile and run some errors occure
errors is :
Trac... | do not run lemmatize of nltk package | Hello I Have a code for lemmatization a string in python . code is below
from nltk.stem.wordnet import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
print("better :", lemmatizer.lemmatize("better", pos ="a"))
but when it compile and run some errors occure
errors is :
Traceback (most recent call last):
File "C:\... | [
"In addition to\nimport nltk\nnltk.download(\"wordnet\")\n\nI also had to run this:\nimport nltk\nnltk.download('omw-1.4')\n\nCan you share the contents of your nltk_data directory (usually it is either C:\\Users\\yourusername\\nltk_data\\ or C:\\Users\\yourusername\\AppData\\Roaming\\nltk_data)? Also which version... | [
0
] | [] | [] | [
"lemmatization",
"nltk",
"python"
] | stackoverflow_0074613719_lemmatization_nltk_python.txt |
Q:
How to get foreign key values with getattr from models
I have a model Project and i am getting the attributes of that with the following instr
attr = getattr(project, 'id', None)
project is the instance, id is the field and None is the default return type.
My question is: what if I want to get the Foreign Key key... | How to get foreign key values with getattr from models | I have a model Project and i am getting the attributes of that with the following instr
attr = getattr(project, 'id', None)
project is the instance, id is the field and None is the default return type.
My question is: what if I want to get the Foreign Key keys with this?
Get customer name
project.customer.name
How to... | [
"You can do something like follows:\ndef get_repr(value): \n if callable(value):\n return '%s' % value()\n return value\n\ndef get_field(instance, field):\n field_path = field.split('.')\n attr = instance\n for elem in field_path:\n try:\n attr = getattr(attr, elem)\n ... | [
19,
0
] | [] | [] | [
"callable",
"getattr",
"model",
"python",
"relational_database"
] | stackoverflow_0020235807_callable_getattr_model_python_relational_database.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.