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:
How to sum the rows by using the name of multiindex in pandas?
I am doing the exercise from
https://github.com/guipsamora/pandas_exercises/blob/master/03_Grouping/Occupation/Exercise.ipynb
I tried to use the code below to solve question 5:
Step 5. Discover the Male ratio per occupation and sort it from the most to... | How to sum the rows by using the name of multiindex in pandas? | I am doing the exercise from
https://github.com/guipsamora/pandas_exercises/blob/master/03_Grouping/Occupation/Exercise.ipynb
I tried to use the code below to solve question 5:
Step 5. Discover the Male ratio per occupation and sort it from the most to the least
users.groupby("occupation").gender.value_counts().loc[occ... | [
"You could try the following:\nmale_ratios = (\n users\n .groupby(\"occupation\")[\"gender\"].value_counts()\n .unstack()\n .assign(male_ratio=lambda df: df[\"M\"] / df.sum(axis=1))\n .sort_values(\"male_ratio\", ascending=False)\n)\n\nWith .unstack you're pulling the gender part of the multiindex in... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074215885_dataframe_pandas_python.txt |
Q:
Serving static files after deployment with django 2.2
I deployed my site at the level of my host, but the imgaes are not displayed.
I did python manage.py collectstatic and it copied the files to my STATIC_ROOT
myprojet/settings.py
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static')
]
STATIC_URL = '/static/'
S... | Serving static files after deployment with django 2.2 | I deployed my site at the level of my host, but the imgaes are not displayed.
I did python manage.py collectstatic and it copied the files to my STATIC_ROOT
myprojet/settings.py
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static')
]
STATIC_URL = '/static/'
STATIC_ROOT='/home/www/mySite.com/static/'
index.html
{% ex... | [
"You need to configure your web server to serve the static files from the STATIC_ROOT directory. Django does not handle static files by itself in production, it only does so in development with the runserver command. Depending on your web server, you need to add some rules to tell it where to find the static files ... | [
3
] | [] | [] | [
"django",
"django_settings",
"python"
] | stackoverflow_0074224712_django_django_settings_python.txt |
Q:
python getattr and setattr with self.__dict__
I have been reading about overriding getattr and setattr and I can't figure out if I need the overriding assignments if I use self.__dict__ = self in the constructor.
Once I make an instance of the class
a = OPT(foo='bar')
a.foo and a['foo'] work with and without the... | python getattr and setattr with self.__dict__ | I have been reading about overriding getattr and setattr and I can't figure out if I need the overriding assignments if I use self.__dict__ = self in the constructor.
Once I make an instance of the class
a = OPT(foo='bar')
a.foo and a['foo'] work with and without the __getattr__ and __setattr__ declaration.
Can some... | [
"You override getattr and setattr when you want to do something extra when the class user gets or sets an attribute. For example:\n1) you might avoid raising an exception when user manipulates an invalid attribute, so you just return None for an unknown attribute.\n2) attribute manipulations are actually forwarded/... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0022161876_python.txt |
Q:
Pandas convert mongodb bson.tz_util.FixedOffset to standard date
I am trying to calculate offset from epoch seconds with a Pandas dataframe created from data from a mongodb document.
An example of the data layout and operation is as per below (this codes works OK)
data = {'ds': ['2018-01-13 18:47:05.069722+00:00',... | Pandas convert mongodb bson.tz_util.FixedOffset to standard date | I am trying to calculate offset from epoch seconds with a Pandas dataframe created from data from a mongodb document.
An example of the data layout and operation is as per below (this codes works OK)
data = {'ds': ['2018-01-13 18:47:05.069722+00:00', '2018-01-14 18:47:05.119994+00:00', '2018-01-15 18:47:05.178768+00:00... | [
"This worked for me.\nimport pandas as pd\n\n# have to convert the series to date index\ndsIndex = pd.Index(df['ds'])\n\n# strip off the TZ info (assume it was <bson.tz_util.FixedOffset objec...)\ndsIndex = dsIndex.tz_localize(tz=None)\n\n# Reassign it to UTC\ndsUTC = dsIndex.tz_localize(tz='UTC')\n\n",
"import p... | [
1,
0
] | [] | [] | [
"mongodb",
"pandas",
"python"
] | stackoverflow_0048615563_mongodb_pandas_python.txt |
Q:
Plotly python: How to get 3d plots in subplots to show completely
This refers to plotly on Python: How to can I get three 3d plots in subplots to show completely, without getting cut off?
Minimal code:
import pandas as pd
import plotly.io as pio
pio.renderers.default='browser'
from plotly.subplots ... | Plotly python: How to get 3d plots in subplots to show completely | This refers to plotly on Python: How to can I get three 3d plots in subplots to show completely, without getting cut off?
Minimal code:
import pandas as pd
import plotly.io as pio
pio.renderers.default='browser'
from plotly.subplots import make_subplots
import plotly.graph_objects as go
# d... | [
"As @Hamzah pointed out, one solution is to update the camera controls. Here is my solution:\nimport pandas as pd\nimport plotly.io as pio\npio.renderers.default='browser'\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objects as go\n\n\nd = {'Temp1': [25, 25, 25, 210, 210, 210], \n 'Dopant': ... | [
1
] | [] | [] | [
"plotly",
"plotly_python",
"python"
] | stackoverflow_0074163444_plotly_plotly_python_python.txt |
Q:
How to add a new value by accessing another object if it exists
I am thinking about this question.
How could I add a new value to this object without getting an error?
data = {
'attributes': processed_data['attributes'],
'categories': processed_data['categories'],
'filters': processed_data['filters'],
'min... | How to add a new value by accessing another object if it exists | I am thinking about this question.
How could I add a new value to this object without getting an error?
data = {
'attributes': processed_data['attributes'],
'categories': processed_data['categories'],
'filters': processed_data['filters'],
'min_price': processed_data['min_price'],
'max_price': processed_data['... | [
"If statement:\nif 'new_value' in process_data:\n data['new_value'] = process_data['new_value']\n\nTernary operator:\ndata['new_value'] = process_data['new_value'] if 'test' in process_data else -1\n\n.get() Function (best):\n# second argument is the default if it doesn't exist\ndata['new_value'] = process_data.... | [
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074224599_python.txt |
Q:
'PythonModelContext' object returned from mlflow.pyfunc.load_model - how to retrieve original model that was saved
I am creating a custom myflow.pyfunc object that I would like to save to MLFlow and retrieve later. I don't understand the relationship between the object that is saved with mlflow.pyfunc.save_model()... | 'PythonModelContext' object returned from mlflow.pyfunc.load_model - how to retrieve original model that was saved | I am creating a custom myflow.pyfunc object that I would like to save to MLFlow and retrieve later. I don't understand the relationship between the object that is saved with mlflow.pyfunc.save_model(), and the one that is retrieved with mlflow.pyfunc.load_model().
The loaded model is a 'PythonModelContext' object rathe... | [
"If you take a close look at the signature of the abstract method predict() in the mlflow.pyfunc.PythonModel class that you are extending, you will see that has 3 parameters:\ndef predict(self, context, model_input):\n\nSo, if you change your simple class to have the extra parameter context, your example should wor... | [
2
] | [] | [] | [
"mlflow",
"python"
] | stackoverflow_0074224196_mlflow_python.txt |
Q:
How can I handle eval() exec() multiline as first in first out
I have code from this Question: Why is Python's eval() rejecting this multiline string, and how can I fix it?
def multiline_eval(expr, context={}):
"Evaluate several lines of input, returning the result of the last line"
tree = ast.parse(expr)
... | How can I handle eval() exec() multiline as first in first out | I have code from this Question: Why is Python's eval() rejecting this multiline string, and how can I fix it?
def multiline_eval(expr, context={}):
"Evaluate several lines of input, returning the result of the last line"
tree = ast.parse(expr)
eval_exprs = []
exec_exprs = []
for module in tree.body:... | [
"The code you've posted sorts the ast tree body in 2 buckets, the ast.Exprs and the rest, and then processes them bucket-wise. So, you have to remove the \"bucketing\". You could try something like the following:\nimport ast\n\ndef multiline_eval(expr, ctx={}):\n results = []\n for node in ast.parse(expr).bod... | [
0
] | [] | [] | [
"exec",
"python",
"val"
] | stackoverflow_0074218830_exec_python_val.txt |
Q:
Accessing dict keys like an attribute?
I find it more convenient to access dict keys as obj.foo instead of obj['foo'], so I wrote this snippet:
class AttributeDict(dict):
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
However, I assume... | Accessing dict keys like an attribute? | I find it more convenient to access dict keys as obj.foo instead of obj['foo'], so I wrote this snippet:
class AttributeDict(dict):
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
However, I assume that there must be some reason that Python ... | [
"Update - 2020\nSince this question was asked almost ten years ago, quite a bit has changed in Python itself since then.\nWhile the approach in my original answer is still valid for some cases, (e.g. legacy projects stuck to older versions of Python and cases where you really need to handle dictionaries with very d... | [
388,
128,
93,
88,
29,
23,
21,
18,
12,
10,
8,
8,
7,
5,
4,
4,
4,
4,
4,
4,
3,
3,
2,
2,
2,
1,
1,
1,
1,
0,
0
] | [] | [] | [
"attributes",
"dictionary",
"python",
"syntax"
] | stackoverflow_0004984647_attributes_dictionary_python_syntax.txt |
Q:
Using grouper to plot subset of dataframe
I am using plotly express to plot a figure.
I have a dataframe that has a datetime value as the index that looks like:
index account A B NH alloc
2021-10-13 16:00:50 sysadmin 1 2 4.0025 True
2021-10-13 21:28:43 sysadmin ... | Using grouper to plot subset of dataframe | I am using plotly express to plot a figure.
I have a dataframe that has a datetime value as the index that looks like:
index account A B NH alloc
2021-10-13 16:00:50 sysadmin 1 2 4.0025 True
2021-10-13 21:28:43 sysadmin 1 3 0.0197 True
2021-10-14 08:11:2... | [
"Figured it out. Create the figure with px.bar, then add the second trace with fig.add_bar:\nfig = px.bar(x=df[df[\"alloc\"]==False].groupby([pd.Grouper(freq=\"6H\")]).sum()['NH'].index,\n y=df[df[\"alloc\"]==False].groupby([pd.Grouper(freq=\"6H\")]).sum()['NH'], \n labels={ \"x\": \... | [
0
] | [] | [] | [
"pandas",
"plot",
"plotly",
"python"
] | stackoverflow_0074224688_pandas_plot_plotly_python.txt |
Q:
Python: inconsistence in the way you define the function __setattr__?
Consider this code:
class Foo1(dict):
def __getattr__(self, key): return self[key]
def __setattr__(self, key, value): self[key] = value
class Foo2(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
o1 = Foo1()... | Python: inconsistence in the way you define the function __setattr__? | Consider this code:
class Foo1(dict):
def __getattr__(self, key): return self[key]
def __setattr__(self, key, value): self[key] = value
class Foo2(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
o1 = Foo1()
o1.x = 42
print(o1, o1.x)
o2 = Foo2()
o2.x = 42
print(o2, o2.x)
I would ... | [
"I suspect it has to do with a lookup optimization. From the source code:\n /* speed hack: we could use lookup_maybe, but that would resolve the\n method fully for each attribute lookup for classes with\n __getattr__, even when the attribute is present. So we use\n _PyType_Lookup and create the me... | [
7,
3,
1,
0
] | [] | [] | [
"getattr",
"python",
"setattr"
] | stackoverflow_0006305267_getattr_python_setattr.txt |
Q:
how to parse highly nested json column in my dataframe
I have a dataframe that has a column named 'blocks'. in the 'blocks' column the data looks like this
[
{
"block_id":"5zI",
"elements":[
{
"elements":[
{
"type":"user",
"user... | how to parse highly nested json column in my dataframe | I have a dataframe that has a column named 'blocks'. in the 'blocks' column the data looks like this
[
{
"block_id":"5zI",
"elements":[
{
"elements":[
{
"type":"user",
"user_id":"U03MXVDRV7W"
},
{
... | [
"You can make types from each piece. For example,\nstruct Elements: Codable {\n var type: String\n var user_id: String\n}\n\nThen incorporate them into the larger type you are using to decode.\nstruct ElementsBlock: Codable {\n var elements: Elements\n}\n\nstruct Block: Codable {\n var blockID: String\n var elem... | [
0
] | [] | [] | [
"dictionary",
"json",
"list",
"python",
"slack"
] | stackoverflow_0074224905_dictionary_json_list_python_slack.txt |
Q:
Identify which country won the most gold, in each olympic games
When I write the below codes in pandas
gold.groupby(['Games','country'])['Medal'].value_counts()
I get the below result, how to extract the top medal winner for each Games,The result should be all the games,country with most medal,medal tally
Games ... | Identify which country won the most gold, in each olympic games | When I write the below codes in pandas
gold.groupby(['Games','country'])['Medal'].value_counts()
I get the below result, how to extract the top medal winner for each Games,The result should be all the games,country with most medal,medal tally
Games country Medal
1896 Summer Australia Gold 2
... | [
"The data Your data only included Chinese gold medal winners so I added a row:\n ID Name Sex Age Height Weight Team NOC \\\n0 17294 Cai Yalin M 23.0 174.0 60.0 China CHN \n1 17299 Cai Yun M 32.0 181.0 68.0 China-1 CHN \n2 17995 Cao Lei ... | [
3,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0070785293_pandas_python.txt |
Q:
How to access the keys or values of Python GDB Value
I have a struct in GDB and want to run a script which examines this struct. In Python GDB you can easily access the struct via
(gdb) python mystruct = gdb.parse_and_eval("mystruct")
Now I got this variable called mystruct which is a GDB.Value object. And I can ... | How to access the keys or values of Python GDB Value | I have a struct in GDB and want to run a script which examines this struct. In Python GDB you can easily access the struct via
(gdb) python mystruct = gdb.parse_and_eval("mystruct")
Now I got this variable called mystruct which is a GDB.Value object. And I can access all the members of the struct by simply using this ... | [
"From GDB documentation:\nYou can get the type of mystruct like so:\ntp = mystruct.type\n\nand iterate over the fields via tp.fields()\nNo evil workarounds required ;-)\nUpdate:\nGDB 7.4 has just been released. From the announcement:\n\nType objects for struct and union types now allow access to\n the fields using... | [
7,
1,
0
] | [] | [] | [
"gdb",
"linux",
"python"
] | stackoverflow_0008912338_gdb_linux_python.txt |
Q:
When is `__dict__` re-initialized?
I subclass dict so that the attributes are identical to the keys:
class DictWithAttr(dict):
def __init__(self, *args, **kwargs):
self.__dict__ = self
super(DictWithAttr, self).__init__(*args, **kwargs)
print(id(self), id(self.__dict__))
def copy(s... | When is `__dict__` re-initialized? | I subclass dict so that the attributes are identical to the keys:
class DictWithAttr(dict):
def __init__(self, *args, **kwargs):
self.__dict__ = self
super(DictWithAttr, self).__init__(*args, **kwargs)
print(id(self), id(self.__dict__))
def copy(self):
return DictWithAttr(self._... | [
"There's no reinitialization. Your problem is that self.__dict__ = self hits your __setattr__ override. It's not actually changing the dict used for attribute lookups. It's setting an entry for the '__dict__' key on self and leaving the attribute dict untouched.\nIf you wanted to keep your (pointless) __setattr__ o... | [
3,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0056233721_dictionary_python.txt |
Q:
Detect bounced emails in Python smtplib
I'm trying to catch all emails that bounced when sending them via smtplib in Python. I looked at this similar post which suggested adding an exception catcher, but I noticed that my sendmail function doesn't throw any exceptions even for fake email addresses.
Here is my send... | Detect bounced emails in Python smtplib | I'm trying to catch all emails that bounced when sending them via smtplib in Python. I looked at this similar post which suggested adding an exception catcher, but I noticed that my sendmail function doesn't throw any exceptions even for fake email addresses.
Here is my send_email function which uses smtplib.
def send... | [
"import poplib\nfrom email import parser\n\n#breaks with if this is left out for some reason (MAXLINE is set too low by default.)\npoplib._MAXLINE=20480\n\npop_conn = poplib.POP3_SSL('your pop server',port)\npop_conn.user(username)\npop_conn.pass_(password)\n#Get messages from server:\nmessages = [pop_conn.retr(i) ... | [
2,
0
] | [] | [] | [
"email",
"mime",
"python",
"smtp",
"smtplib"
] | stackoverflow_0040369645_email_mime_python_smtp_smtplib.txt |
Q:
How to get value of ManyToMany field rather than their ids?
I have three models, as shown below:
class TagsModel(models.Model):
title = models.CharField(max_length=200)
def __str__(self):
return self.title
class ImagesModel(models.Model):
title = models.CharField(max_length=500, default='ima... | How to get value of ManyToMany field rather than their ids? | I have three models, as shown below:
class TagsModel(models.Model):
title = models.CharField(max_length=200)
def __str__(self):
return self.title
class ImagesModel(models.Model):
title = models.CharField(max_length=500, default='image')
image_cdn = models.TextField(null=True, blank=True)
... | [
"Solution\nclass ProductSerializer(serializers.ModelSerializer):\n cate = serializers.SerializerMethodField('get_cate')\n\n def get_cate(self,obj):\n return [cate.name for cate in obj.cate.all()]\n \n class Meta:\n model = ProductModel \n fields = \"__all__\"\n\nResponse output\... | [
2,
0
] | [] | [] | [
"django",
"django_models",
"django_rest_framework",
"python"
] | stackoverflow_0074134986_django_django_models_django_rest_framework_python.txt |
Q:
How to run multiple functions at the same time?
I'm trying to run 2 functions at the same time.
def func1():
print('Working')
def func2():
print('Working')
func1()
func2()
Does anyone know how to do this?
A:
Do this:
from threading import Thread
def func1():
print('Working')
def func2():
pri... | How to run multiple functions at the same time? | I'm trying to run 2 functions at the same time.
def func1():
print('Working')
def func2():
print('Working')
func1()
func2()
Does anyone know how to do this?
| [
"Do this:\nfrom threading import Thread\n\ndef func1():\n print('Working')\n\ndef func2():\n print(\"Working\")\n\nif __name__ == '__main__':\n Thread(target = func1).start()\n Thread(target = func2).start()\n\n",
"The answer about threading is good, but you need to be a bit more specific about what y... | [
118,
15,
11,
4,
2,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"concurrency",
"multithreading",
"parallel_processing",
"python",
"python_3.x"
] | stackoverflow_0002957116_concurrency_multithreading_parallel_processing_python_python_3.x.txt |
Q:
In a panda dataframe how can I use boolean indexing on an index (in a multi-index dataframe)?
I have a data frame with four named indices, time, lev, lon, and lat, like this (this is just the head, it's a huge dataframe):
O N
time lev lat lon ... | In a panda dataframe how can I use boolean indexing on an index (in a multi-index dataframe)? | I have a data frame with four named indices, time, lev, lon, and lat, like this (this is just the head, it's a huge dataframe):
O N
time lev lat lon
2021-01-01 4.055141e-10 -90.0 0.0 0.954735 0.046307
... | [
"You can use Index.get_level_values:\ndf = df[df.index.get_level_values('lev') > 1]\n\nOr with query (provided there is no column with the same name):\ndf = df.query('lev > 1')\n\nExample with a different condition to get a non-empty output:\ndf[df.index.get_level_values('lon') > 17]\n\noutput:\n ... | [
1
] | [] | [] | [
"boolean",
"dataframe",
"indexing",
"pandas",
"python"
] | stackoverflow_0074224857_boolean_dataframe_indexing_pandas_python.txt |
Q:
Cannot swap values in for loop in python in the first iteration
I am trying to find the minimum swaps to sort an array without duplicates in python.I have the following code and i am using the greedy approach where i sort the array and compare and swap accordingly
def minimumSwaps(arr):
totalswapcount=0
so... | Cannot swap values in for loop in python in the first iteration | I am trying to find the minimum swaps to sort an array without duplicates in python.I have the following code and i am using the greedy approach where i sort the array and compare and swap accordingly
def minimumSwaps(arr):
totalswapcount=0
sortedarr=sorted(arr)
for x in range(0,len(arr)-1):
if (arr... | [
"When you assign to\narr[x],arr[arr.index(sortedarr[x])]=\n\nit calculates the subscript arr.index(sortedarr[x]) after it has already assigned to arr[x]. Get the index outside the spread assignment, so it will use the new index of the element if the element has been moved into a lower index.\n if (arr[x]!=so... | [
1
] | [] | [] | [
"algorithm",
"arrays",
"python"
] | stackoverflow_0074225034_algorithm_arrays_python.txt |
Q:
Saving and logging mlflow custom model
I am trying to use mlflow in Azure databricks for a custom ML model I have created. I am however new to mlflow so to get an idea of how to save and log the model I have created a small example from the mlflow documentation that I am trying to make work.
import pandas as pd
im... | Saving and logging mlflow custom model | I am trying to use mlflow in Azure databricks for a custom ML model I have created. I am however new to mlflow so to get an idea of how to save and log the model I have created a small example from the mlflow documentation that I am trying to make work.
import pandas as pd
import mlflow
# Define the model class
class ... | [
"The mlflow.pyfunc.log_model function's artifact_path parameter, is defined as :\n:param artifact_path: The run-relative artifact path to which to log the Python model.\n\nThat means, it is just a name that should identify the model in the context of that run and hence cannot be an absolute path like what you passe... | [
0
] | [] | [] | [
"azure_databricks",
"databricks",
"mlflow",
"python"
] | stackoverflow_0074224896_azure_databricks_databricks_mlflow_python.txt |
Q:
How to fetch related entries in Django through reverse foreign key
Django newbie here!
I am coming from .NET background I am frustrated as to how to do the following simple thing:
My simplified models are as follows
class Circle(BaseClass):
name = models.CharField("Name", max_length=2048, blank=False, null=Fal... | How to fetch related entries in Django through reverse foreign key | Django newbie here!
I am coming from .NET background I am frustrated as to how to do the following simple thing:
My simplified models are as follows
class Circle(BaseClass):
name = models.CharField("Name", max_length=2048, blank=False, null=False)
active = models.BooleanField(default=False)
...
class Circl... | [
".prefetch_related will use a second query to reduce the bandwidth, otherwise it will repeat data for the same Circle and CircleParticipants multiple times. Your CircleParticipant however acts as a junction table, so you can use:\nCircle.objects.filter(id=43).prefetch_related(\n Prefetch('circleparticipant_set',... | [
1,
0
] | [] | [] | [
"django",
"python",
"sql"
] | stackoverflow_0074224541_django_python_sql.txt |
Q:
Trying to Understand a python code to build up a Sudoku Solver
def init_valid(self):
# Fill out dictionary V such that V[(r,c)], where (r,c) are the coordinates of a cell, contains the set of integers that can be
# written in cell (r,c) without breaking any of the rules
# If a number has already been ... | Trying to Understand a python code to build up a Sudoku Solver | def init_valid(self):
# Fill out dictionary V such that V[(r,c)], where (r,c) are the coordinates of a cell, contains the set of integers that can be
# written in cell (r,c) without breaking any of the rules
# If a number has already been written in cell (r,c), then V[(r,c)] should contain the empty set
... | [
"Your code is a super compact version of the following:\nself.V = {}\nfor i in range(9):\n for j in range(9):\n \n my_set = set()\n for value in self.N(i, j):\n my_set.add(self.S[value[0]][value[1]]) \n \n self.V[(i, j)] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} - my_set\n... | [
1
] | [] | [] | [
"dictionary",
"python",
"sudoku"
] | stackoverflow_0074224929_dictionary_python_sudoku.txt |
Q:
pip install saying no .egg-info directory found
I updated pip yesterday, and since then I can not install anything using pip. I get the error:
ERROR: No .egg-info directory found in C:\Users\(my username)\AppData\Local\Temp\pip-pip-egg-info-7kf6p_vq
I have tried uninstall python, and reinstalling it, and downgrad... | pip install saying no .egg-info directory found | I updated pip yesterday, and since then I can not install anything using pip. I get the error:
ERROR: No .egg-info directory found in C:\Users\(my username)\AppData\Local\Temp\pip-pip-egg-info-7kf6p_vq
I have tried uninstall python, and reinstalling it, and downgrading pip to the version that i thought I had last.
Run... | [
"I downgraded to pip version 22.2.4 and the error went away. I tried downgrading before this post before, but it seems the other version I had downgraded to didnt work. 22.2.4 stopped the error\n"
] | [
0
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0074150554_pip_python.txt |
Q:
How can I iterate through two lists and compare the values of each in Python?
Suppose I have the following lists:
x = [0.5, 0.9, 0.1, 0.3, 0.6]
y = [0.4, 0.3, 0.6, 0.1, 0.9]
I want to write a function that iterates through the list and compares each value in order.
def compare_numbers(prob,thresh):
output = []
... | How can I iterate through two lists and compare the values of each in Python? | Suppose I have the following lists:
x = [0.5, 0.9, 0.1, 0.3, 0.6]
y = [0.4, 0.3, 0.6, 0.1, 0.9]
I want to write a function that iterates through the list and compares each value in order.
def compare_numbers(prob,thresh):
output = []
for x, y in zip(prob, thresh):
if x >= y:
output.append(1)
else:
out... | [
"Psychic debugging:\n\nYour first function is passed a float for either prob or thresh, but the code assumes both inputs are list (really, any iterable) of numbers.\n\nYour second function has the opposite problem, it assumes thresh is a single scalar value (e.g. float), but you passed it as a list.\n\n\nSeems like... | [
2,
1,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074224411_list_python.txt |
Q:
How to get every second element/character from a string in python?
I've this string: mystr = 'one two three four five six'
and I want to get every second element from a string. So the output I want is: 'two four six'
Because eventually I want the output to be as: 'one owt three ruof five xis' i.e; I want to revers... | How to get every second element/character from a string in python? | I've this string: mystr = 'one two three four five six'
and I want to get every second element from a string. So the output I want is: 'two four six'
Because eventually I want the output to be as: 'one owt three ruof five xis' i.e; I want to reverse every second element from the string and that's why I'm fetching every... | [
"For a concise and efficient solution you can use a list-builder notation to create an array where the word is reversed (w[::-1]) at even indices and forwards at odd indices (w). enumerate(some_list) allows you to iterate over the indices and values simultaneously. In this case, we used mystr.split() to split it at... | [
0
] | [] | [] | [
"character",
"python",
"string"
] | stackoverflow_0074225082_character_python_string.txt |
Q:
Pytorch model summary - forward func has more than one argument. One argument is an integer
I am using torch summary. I want to pass more than one argument when printing the model summary, one of which is just an integer. However, I get an error. I follow this question recommendation but it is not working.
My netw... | Pytorch model summary - forward func has more than one argument. One argument is an integer | I am using torch summary. I want to pass more than one argument when printing the model summary, one of which is just an integer. However, I get an error. I follow this question recommendation but it is not working.
My network looks like
import torch
from torch import nn
from torchsummary import summary
class SimpleN... | [
"Changing from (3, 64, 64),(1) to (3, 64, 64),(1,) helped because all the elements of list should be Tuple type.\nHowever when it tries to run forward it cannot perform multiplication of tuple by tuple (because it is not possible in any python code).\nYou can change from Tuple to torch.Tensor\nsummary(model,[torch.... | [
0
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0074224954_python_pytorch.txt |
Q:
How to match non-equivalent categories in two datasets for record linkage?
I am trying to find record matches between two sets of data using supervised machine learning for the classification of potential matches.
I have two sets of data each with their own categories which are non mutually exclusive and not equi... | How to match non-equivalent categories in two datasets for record linkage? | I am trying to find record matches between two sets of data using supervised machine learning for the classification of potential matches.
I have two sets of data each with their own categories which are non mutually exclusive and not equivalent. e.g
Set A
Name
Species
Cuteness
Alice
Cat
Very
Bob
Snake
No
... | [
"How to match non-equivalent categories in two datasets for record linkage using Python?\nRecord linkage is the process of identifying and linking records that refer to the same entity across different data sources. One of the challenges of record linkage is to deal with non-equivalent categories, which are categor... | [
2
] | [] | [] | [
"matching",
"python",
"record_linkage"
] | stackoverflow_0074214557_matching_python_record_linkage.txt |
Q:
How to attach debugger to a python subproccess?
I need to debug a child process spawned by multiprocessing.Process(). The pdb degugger seems to be unaware of forking and unable to attach to already running processes.
Are there any smarter python debuggers which can be attached to a subprocess?
A:
I've been searc... | How to attach debugger to a python subproccess? | I need to debug a child process spawned by multiprocessing.Process(). The pdb degugger seems to be unaware of forking and unable to attach to already running processes.
Are there any smarter python debuggers which can be attached to a subprocess?
| [
"I've been searching for a simple to solution for this problem and came up with this:\nimport sys\nimport pdb\n\nclass ForkedPdb(pdb.Pdb):\n \"\"\"A Pdb subclass that may be used\n from a forked multiprocessing child\n\n \"\"\"\n def interaction(self, *args, **kwargs):\n _stdin = sys.stdin\n ... | [
97,
14,
11,
3,
3,
0,
0,
0,
0
] | [
"If you are on a supported platform, try DTrace. Most of the BSD / Solaris / OS X family support DTrace.\nHere is an intro by the author. You can use Dtrace to debug just about anything. \nHere is a SO post on learning DTrace.\n"
] | [
-1
] | [
"debugging",
"multiprocessing",
"python",
"subprocess"
] | stackoverflow_0004716533_debugging_multiprocessing_python_subprocess.txt |
Q:
python for-loop to remove duplication in list
hi everyone this is my code to remove repeated items in a list of numbers:
numbers=[5,2,2,2,2,2,34,5,46,78,65,34,78,34,3,2,47,5,8,76]
for item in numbers:
if numbers.count(item)>1:
numbers.remove(item)
print(numbers)
and the result is this:
[2... | python for-loop to remove duplication in list | hi everyone this is my code to remove repeated items in a list of numbers:
numbers=[5,2,2,2,2,2,34,5,46,78,65,34,78,34,3,2,47,5,8,76]
for item in numbers:
if numbers.count(item)>1:
numbers.remove(item)
print(numbers)
and the result is this:
[2, 2, 46, 65, 78, 34, 3, 2, 47, 5, 8, 76]
still has... | [
"Don't remove items from a list while you're iterating it! That's very dangerous and can return weird results, as you can see. Instead, you can use this approach:\nc = set()\nunique_numbers = []\nfor n in numbers:\n if n not in c:\n unique_numbers.append(n)\n c.add(n)\n\nHere is the result:\n>>> un... | [
0
] | [] | [] | [
"for_loop",
"list",
"python"
] | stackoverflow_0074225326_for_loop_list_python.txt |
Q:
How to combine the same return value in different methods?
I have three different methods. But the return statement of the three methods is almost identicall.
So I have this three methods:
def filter_verdi_total_number_fruit(self):
regex = r"(\d*(?:\.\d+)*)\s*\W+(?:" + '|'.join(re.escape(word)
... | How to combine the same return value in different methods? | I have three different methods. But the return statement of the three methods is almost identicall.
So I have this three methods:
def filter_verdi_total_number_fruit(self):
regex = r"(\d*(?:\.\d+)*)\s*\W+(?:" + '|'.join(re.escape(word)
for word in self.extr... | [
"For simpler shorter methods, I would have them return the regex rather than the matches. Add methods to join the list and to find the matches.\n def fruit_list(self, format_=re.escape):\n \"\"\" Return a string with all the fruit words, \n escaped or formatted for use in a regex \"\"\"\n ... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074224823_python.txt |
Q:
what is the correct way to use Python typing when creating numpy/pandas objects?
I've been using numpy/pandas for years but have only recently started type checking all my code with mypy.
The following example shows code that works as intended but doesn't pass mypy. What is the correct way to add type annotation t... | what is the correct way to use Python typing when creating numpy/pandas objects? | I've been using numpy/pandas for years but have only recently started type checking all my code with mypy.
The following example shows code that works as intended but doesn't pass mypy. What is the correct way to add type annotation to this example ?
import pandas as pd
import numpy as np
def get_repeats(date: pd.Tim... | [
"Looking at the docs, technically speaking np.repeat requires an arraylike first parameter, and a timestamp isn't one.\nHowever, a timestamp in a list is. In other words,\ndef get_repeats(date: pd.Timestamp) -> np.ndarray:\n return np.repeat([date], 3)\n\nmakes mypy happy:\n$ mypy zup.py\nSuccess: no issues foun... | [
0
] | [] | [] | [
"mypy",
"numpy",
"pandas",
"python",
"typing"
] | stackoverflow_0074225029_mypy_numpy_pandas_python_typing.txt |
Q:
Is there a way of solving this without iterating?
I came up with a solution but it does not perform well enough to pass with very large inputs. Any way of maybe doing it without iterating?
Challange:
Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequenc... | Is there a way of solving this without iterating? | I came up with a solution but it does not perform well enough to pass with very large inputs. Any way of maybe doing it without iterating?
Challange:
Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.
... | [
"You will have to iterate the sequence no matter what. However, your code is performing slowly because, for each iteration, you are:\n\nCopying the sequence\nYou're copying it again into a set\nYou're comparing it to the shortened array\nYou're sorting the shortened array\n\nThe key to this challenge is realizing y... | [
0,
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0074225221_python_sorting.txt |
Q:
random.choice() keeps returning error. I can't see the problem :(
My code is as follows:
import random
players = []
def player_list(new_player):
for x in range (5):
players.append(new_player)
return players
for x in range (5):
new_player = input("Please enter your player name: ")
winner=(ra... | random.choice() keeps returning error. I can't see the problem :( | My code is as follows:
import random
players = []
def player_list(new_player):
for x in range (5):
players.append(new_player)
return players
for x in range (5):
new_player = input("Please enter your player name: ")
winner=(random.choice(players))
print("You are the winner," , winner)
It keeps r... | [
"import random\n\nplayers = []\n\nfor x in range(5):\n new_player = input(\"Please enter your player name: \")\n players.append(new_player)\n\nwinner = random.choice(players)\nprint(\"You are the winner,\", winner)\n\n",
"It seems that you do not call the function, hence the list remains empty.\n",
"list ... | [
3,
3,
1
] | [] | [] | [
"python",
"random"
] | stackoverflow_0074225490_python_random.txt |
Q:
Python multiprocess debugging
I'm trying to debug a simple python application but no luck so far.
import multiprocessing
def worker(num):
for a in range(0, 10):
print a
if __name__ == '__main__':
for i in range(5):
p = multiprocessing.Process(target=worker, args=(i,))
p.start()
I... | Python multiprocess debugging | I'm trying to debug a simple python application but no luck so far.
import multiprocessing
def worker(num):
for a in range(0, 10):
print a
if __name__ == '__main__':
for i in range(5):
p = multiprocessing.Process(target=worker, args=(i,))
p.start()
I want to set a breakpoint inside th... | [
"I found it very useful to replace multiprocessing.Process() with threading.Thread() when I'm going to set breakpoints. Both classes have similar arguments so in most cases they are interchangeable.\nUsually my scripts use Process() until I specify command line argument --debug which effectively replaces those call... | [
7,
3,
2,
2,
1,
0
] | [
"WingIDE Pro provides this functionality right out-of-the-box. \nNo additional code (e.g., use of the traceback module) is needed. You just run your program, and the Wing debugger will not only print stdout from subprocesses, but it will break on errors in a subprocess and instantly create and an interactive shell ... | [
-1
] | [
"debugging",
"multiprocessing",
"pycharm",
"python",
"winpdb"
] | stackoverflow_0011106000_debugging_multiprocessing_pycharm_python_winpdb.txt |
Q:
Plotting H5PY/HDF5 Data
Afternoon!
I'm trying to plot the following HDF5 data:
https://www.gw-openscience.org/eventapi/html/GWTC-1-confident/GW150914/v3/H-H1_GWOSC_4KHZ_R1-1126259447-32.hdf5
This returns the time (in seconds) and the strain (which has no units), with plot being the strain as a function of time.
Ho... | Plotting H5PY/HDF5 Data | Afternoon!
I'm trying to plot the following HDF5 data:
https://www.gw-openscience.org/eventapi/html/GWTC-1-confident/GW150914/v3/H-H1_GWOSC_4KHZ_R1-1126259447-32.hdf5
This returns the time (in seconds) and the strain (which has no units), with plot being the strain as a function of time.
However, the code so far doesn'... | [
"You need to define the 't' and 'strain' variables by calling your loadLIGOdata() function. From what you posted, Hanford also needs to be defined as a file path. The following should work after changing the file path to where Hanford is located on your computer.\nimport matplotlib.pyplot as plt\nimport numpy as np... | [
0
] | [] | [] | [
"h5py",
"hdf5",
"python"
] | stackoverflow_0074225069_h5py_hdf5_python.txt |
Q:
How to replicate a table from R to python using Matplotlib or Plotly
I am trying to replicate a table, which is currently produced in R, in python implementing plotnine library. I am using facet.grid with two variables (CBRegion and CBIndustry).
I have found a similar problem, however, it is also done in R. I app... | How to replicate a table from R to python using Matplotlib or Plotly | I am trying to replicate a table, which is currently produced in R, in python implementing plotnine library. I am using facet.grid with two variables (CBRegion and CBIndustry).
I have found a similar problem, however, it is also done in R. I applied similar codes as in that link and produced the following table:
I tr... | [
"The other issues with colours, overlapping labels, wrapping text etc can be fixed, but unfortunately space = 'free' is not currently supported in plotnine. See documentation here. Unfortunately that's kind of a deal-breaker for your table, sadly. You will need to do in R's ggplot.\n"
] | [
0
] | [] | [] | [
"matplotlib",
"plotly",
"plotnine",
"python",
"r"
] | stackoverflow_0074174436_matplotlib_plotly_plotnine_python_r.txt |
Q:
increase the value of x by 1
x=1
if display == old_display:
x=x+1
print(x)
print(stages[7-x])
I need the value of x to increase by 1 when the condition display == old display is true
I tried to set the condition with if statement and when it is true i need x to decrease by 1. This is a p... | increase the value of x by 1 | x=1
if display == old_display:
x=x+1
print(x)
print(stages[7-x])
I need the value of x to increase by 1 when the condition display == old display is true
I tried to set the condition with if statement and when it is true i need x to decrease by 1. This is a part of hang man game and this part... | [
"if display == old_display:\n x -=1\n\nthis snippet decreases x by 1 every time display == old_display\n"
] | [
0
] | [] | [] | [
"for_loop",
"if_statement",
"increment",
"python",
"while_loop"
] | stackoverflow_0074225484_for_loop_if_statement_increment_python_while_loop.txt |
Q:
Celery / Flask update_state not changing state
My flask config looks like this
CELERY_BROKER_URL = "redis://127.0.0.1:6379/0"
CELERY_RESULT_BACKEND = "redis://127.0.0.1:6379/0"
CELERY_CACHE_BACKEND = "redis://127.0.0.1:6379/0"
BROKER_URL = "redis://127.0.0.1:6379/0"
RESULT_BACKEND = "redis://127.0.... | Celery / Flask update_state not changing state | My flask config looks like this
CELERY_BROKER_URL = "redis://127.0.0.1:6379/0"
CELERY_RESULT_BACKEND = "redis://127.0.0.1:6379/0"
CELERY_CACHE_BACKEND = "redis://127.0.0.1:6379/0"
BROKER_URL = "redis://127.0.0.1:6379/0"
RESULT_BACKEND = "redis://127.0.0.1:6379/0"
CACHE_BACKEND = "redis://127.0.0.1:6... | [
"I've realised I missed out the kwarg state from the update_state call. Which must have been throwing an error or having unintended side effects.\nself.update_state(state=\"Running\", meta={\"test\":1, \"val\": oi})\nThis has fixed it.\n"
] | [
0
] | [] | [] | [
"celery",
"python"
] | stackoverflow_0074225220_celery_python.txt |
Q:
Set ticks with logarithmic scale and keep scientific notation
I am trying to set specific tick marks on a logarithmic scale:
I found one solution at this link and I will copy and paste the code below:
import matplotlib
from matplotlib import pyplot as plt
fig1, ax1 = plt.subplots()
ax1.plot([10, 100, 1000], [1,2,3... | Set ticks with logarithmic scale and keep scientific notation | I am trying to set specific tick marks on a logarithmic scale:
I found one solution at this link and I will copy and paste the code below:
import matplotlib
from matplotlib import pyplot as plt
fig1, ax1 = plt.subplots()
ax1.plot([10, 100, 1000], [1,2,3])
ax1.set_xscale('log')
ax1.set_xticks([20, 200, 500])
ax1.get_xax... | [
"It is a bit rough, but I would do it like this using the math package:\nimport matplotlib\nfrom matplotlib import pyplot as plt\nfrom math import log10, floor\n\nfig1, ax1 = plt.subplots()\nax1.plot([10, 100, 1000], [1,2,3])\nax1.set_xscale('log')\nyticks = [2e1, 2e2, 5e2]\nylab=[]\nfor c,x in enumerate(yticks):\n... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074225409_matplotlib_python.txt |
Q:
run two views at the same time
So as the title says, im trying to run two views at the same time. Or at least, that is what i think i have to do. I have system that lets user like the model and if model like count is bigger than 3, the view should be redirected to a view that sends email message to client. I dont ... | run two views at the same time | So as the title says, im trying to run two views at the same time. Or at least, that is what i think i have to do. I have system that lets user like the model and if model like count is bigger than 3, the view should be redirected to a view that sends email message to client. I dont want to put email message code in th... | [
"There's no way to run two views at the same time. And this isn't what you want to do anyway, since the \"likes_email\" function doesn't return a response to the user, which is part of the contract of a view.\nThe pattern for running time-consuming operations is to farm them out to a separate process, usually with ... | [
3,
0
] | [] | [] | [
"django",
"python",
"view"
] | stackoverflow_0043852088_django_python_view.txt |
Q:
Python group by row and topic and create new columns with binary value
I have a large csv where each row is a separate school course, each of which is tagged with one or more topics, like so:
school name
department
course name
topics
A
A1
X
1; 2
A
A1
Y
1; 3
B
B1
Z
1; 2; 4
C
C1
XX
1; 5
I need to calculate the... | Python group by row and topic and create new columns with binary value | I have a large csv where each row is a separate school course, each of which is tagged with one or more topics, like so:
school name
department
course name
topics
A
A1
X
1; 2
A
A1
Y
1; 3
B
B1
Z
1; 2; 4
C
C1
XX
1; 5
I need to calculate the presence of each topic for each course. Each topic needs to be ... | [
"You can try this:\ndf.set_index(['school name', 'department', 'course name'])['topics'].str.get_dummies(';')\\\n .add_prefix('topics ')\\\n .reset_index()\n\nOutput:\n school name department course name topics 2 topics 3 topics 4 topics 5 topics 1\n0 A A1 X 1 ... | [
2,
0,
0,
0
] | [] | [] | [
"group_by",
"loops",
"nested_loops",
"pandas",
"python"
] | stackoverflow_0074225523_group_by_loops_nested_loops_pandas_python.txt |
Q:
Command works on Command Prompt but it does not work when called with subprocess.run() or os.system() in python
Python 3.10.6
Windows 10
I have a python function that executes a DXL script using subsystem.run() or os.system() (whichever works best I guess). The problem is that when I run a custom command using pyt... | Command works on Command Prompt but it does not work when called with subprocess.run() or os.system() in python | Python 3.10.6
Windows 10
I have a python function that executes a DXL script using subsystem.run() or os.system() (whichever works best I guess). The problem is that when I run a custom command using python it does not work, but when I paste the same command in the command prompt, it works. I should also clarify that c... | [
"When calling subprocess.run with a command list and shell=True, python will expand the command list to a string, adding more quoting along the way. The details are OS dependent (on Windows, you always have to expand the list to a command) but you can see the result via the subprocess.list2cmdline() function.\nYour... | [
0
] | [] | [] | [
"ibm_doors",
"python",
"python_3.x"
] | stackoverflow_0074224110_ibm_doors_python_python_3.x.txt |
Q:
regex match behaviour, why is it returning the rest of the string
Year_month_day=re.match("(\d{4})-(\d{2})-(\d{2})",time_string)
if (Year_month_day):
Year_month_day=Year_month_day.string.split('-')
temp_df.loc[i-1,'day']=Year_month_day[1]
Why for the above code is time_string='2022-10-26 12:59:06 PM' bein... | regex match behaviour, why is it returning the rest of the string | Year_month_day=re.match("(\d{4})-(\d{2})-(\d{2})",time_string)
if (Year_month_day):
Year_month_day=Year_month_day.string.split('-')
temp_df.loc[i-1,'day']=Year_month_day[1]
Why for the above code is time_string='2022-10-26 12:59:06 PM' being returned as the array
['2022','10','26 12:59:06 PM'] and not [['2022'... | [
"Because you are splitting the .string attribute, which contains the original input string. You want to split .group(0) which contains the actual match.\nBetter yet, since you already collected the matches in groups, use them.\nif Year_month_day:\n temp_df.loc[i-1,'day'] = Year_month_day.group(2)\n\n(Your code w... | [
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074225463_python_regex.txt |
Q:
Is it possible to create an external shared link under the group's name?
I would like to know, If it is possible to create an external shared link under the group's name using Dropbox API in python. Currently, I'm generating links under my account
user = 'dbmid:CODE'
dbx = dropbox.DropboxTeam(ACCESS TOKEN)
downloa... | Is it possible to create an external shared link under the group's name? | I would like to know, If it is possible to create an external shared link under the group's name using Dropbox API in python. Currently, I'm generating links under my account
user = 'dbmid:CODE'
dbx = dropbox.DropboxTeam(ACCESS TOKEN)
download_url = dbx.as_user(user).sharing_create_shared_link_with_settings(dropbox_pat... | [
"No, the Dropbox API doesn't offer a way to create a shared link associated with a group instead of an account, but I'll pass this along as a feature request. I can't promise if or when that might be implemented though.\n"
] | [
1
] | [] | [] | [
"dropbox",
"dropbox_api",
"python"
] | stackoverflow_0074218437_dropbox_dropbox_api_python.txt |
Q:
How do I make this character counter be insensitive to case?
I wrote this little code to count occurrences of words in a text:
string=input("Paste text here: ")
word=input("Type word to count: ")
string.count(word)
x=string.count(word)
print (x)
The problem is that it is case sensitive. How can I make it be case ... | How do I make this character counter be insensitive to case? | I wrote this little code to count occurrences of words in a text:
string=input("Paste text here: ")
word=input("Type word to count: ")
string.count(word)
x=string.count(word)
print (x)
The problem is that it is case sensitive. How can I make it be case insensitive?
| [
"Convert both the text and the word you're searching for to uppercase.\nstring.upper().count(word.upper())\n\nSince strings are immutable, it won't permanently change the text or the word.\n",
"Use .lower() or .upper() to convert your inputs to all uppercase or lowercase\nstring=input(\"Paste text here: \").lower... | [
22,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0029242428_python.txt |
Q:
Extract and plot pystan3 prediction
I have been tasked to convert an R-stan script into python pystan3 for a research project. The collegue who wrote the R code left time ago and won't help much so I was left on my own devices.
Here is the stan-model code, my python implementation of the stan calls and some demo-d... | Extract and plot pystan3 prediction | I have been tasked to convert an R-stan script into python pystan3 for a research project. The collegue who wrote the R code left time ago and won't help much so I was left on my own devices.
Here is the stan-model code, my python implementation of the stan calls and some demo-data. I can run the model but I don't know... | [
"First, you can omit the text between ''' if it is not something that you want to see. It is a multi-line comment.\nThis is a coding example where the python variable names, are not really helpful so it's not easy to understand what the values represent.\nTo explain the dependent, independent and predicted variable... | [
0
] | [] | [] | [
"pystan",
"python"
] | stackoverflow_0074225340_pystan_python.txt |
Q:
Merge multiple column values into one column in python pandas
I have a pandas data frame like this:
Column1 Column2 Column3 Column4 Column5
0 a 1 2 3 4
1 a 3 4 5
2 b 6 7 8
3 c 7 7
What I want to do n... | Merge multiple column values into one column in python pandas | I have a pandas data frame like this:
Column1 Column2 Column3 Column4 Column5
0 a 1 2 3 4
1 a 3 4 5
2 b 6 7 8
3 c 7 7
What I want to do now is getting a new dataframe containing Column1 and a new columnA.... | [
"You can call apply pass axis=1 to apply row-wise, then convert the dtype to str and join:\nIn [153]:\ndf['ColumnA'] = df[df.columns[1:]].apply(\n lambda x: ','.join(x.dropna().astype(str)),\n axis=1\n)\ndf\n\nOut[153]:\n Column1 Column2 Column3 Column4 Column5 ColumnA\n0 a 1 2 ... | [
142,
21,
10,
3
] | [] | [] | [
"dataframe",
"list",
"pandas",
"python",
"row"
] | stackoverflow_0033098383_dataframe_list_pandas_python_row.txt |
Q:
TypeError when plotting multiple scatter graphs?
I am having an issue when trying to plot scatter graphs. I am using Tiingo Api to get stock data and have plotted 4 separate histograms for my data with no issue (code below)
import datetime
import pandas_datareader as pdr
import pandas as pd`
api_key='thisisasecr... | TypeError when plotting multiple scatter graphs? | I am having an issue when trying to plot scatter graphs. I am using Tiingo Api to get stock data and have plotted 4 separate histograms for my data with no issue (code below)
import datetime
import pandas_datareader as pdr
import pandas as pd`
api_key='thisisasecret'
tickers = ['TSLA', 'ADDYY', 'UPS', 'PFE']
start="2... | [
"I can't replicate your pdf.tiingo... line so I can't be absolutely certain, but I suspect your dates are not actually datetimes.\nTry something like:\ndatelist = [pd.to_datetime(d) for d in all_data.date]\nall_data['date'] = datelist\n\nSee if that fixes it. If not, please report back.\n"
] | [
0
] | [] | [] | [
"pandas",
"python",
"scatter_plot",
"typeerror"
] | stackoverflow_0074225379_pandas_python_scatter_plot_typeerror.txt |
Q:
Python correspondent for MATLAB matrix operation
I have a vector of indices (let's call it peo), a sparse matrix P and a matrix W. In MATLAB I can do an operation of this kind:
P(peo, peo) = W(peo, peo)
Is there a way to do the same in Python maintaining the same computational and time complexity?
A:
Choosing l... | Python correspondent for MATLAB matrix operation | I have a vector of indices (let's call it peo), a sparse matrix P and a matrix W. In MATLAB I can do an operation of this kind:
P(peo, peo) = W(peo, peo)
Is there a way to do the same in Python maintaining the same computational and time complexity?
| [
"Choosing library\nThere is a very similar way of expressing that in python if you use dense matrices. Using a sparse matrix is a little more complex. In general, if your code is not slowed by dense matrices too much and memory is not a problem I would stick to dense matrices with numpy since it is very convenient.... | [
2
] | [] | [] | [
"matlab",
"matrix",
"python",
"sparse_matrix"
] | stackoverflow_0074211663_matlab_matrix_python_sparse_matrix.txt |
Q:
2d array printing values
So i am making a 2d array for a library system task. This is what my array looks like
books = [[0, "From Lukov with Love", True],[1, "172 hours on the moon",True],[2, "Archer's Voice",False],[3, "Floored",True],[4, "The Mermaid of Black Conch"],[5, "Kite Runner",True],[6, "The Brilliant Wo... | 2d array printing values | So i am making a 2d array for a library system task. This is what my array looks like
books = [[0, "From Lukov with Love", True],[1, "172 hours on the moon",True],[2, "Archer's Voice",False],[3, "Floored",True],[4, "The Mermaid of Black Conch"],[5, "Kite Runner",True],[6, "The Brilliant World of Tom Gates", False], [7,... | [
"You have a bug. You expect each object in books[][] to be in format:\n[index, title, bool], however when you add a new book you do:\nbooks.append(newBook) where newBook is only a title of the book.\nNext time you will iterate over the list and try to access books[i][1] you will get a runtime error.\nMaintaining th... | [
1
] | [] | [] | [
"arrays",
"multidimensional_array",
"python"
] | stackoverflow_0074225689_arrays_multidimensional_array_python.txt |
Q:
How to get quotas of AWS via boto3?
I'm working on boto3 - SDK python for AWS.
I am starting with simple service quota for ec2 but always ending up with the below error,
import boto3
quota_client = boto3.client('service-quotas')
response = quota_client.get_service_quota(
ServiceCode='ec2'
)
Error:
botocore.excep... | How to get quotas of AWS via boto3? | I'm working on boto3 - SDK python for AWS.
I am starting with simple service quota for ec2 but always ending up with the below error,
import boto3
quota_client = boto3.client('service-quotas')
response = quota_client.get_service_quota(
ServiceCode='ec2'
)
Error:
botocore.exceptions.UnknownServiceError: Unknown servic... | [
"I could reproduce the problem with my current boto3-1.9.174 botocore-1.12.174 installation.\nI then did:\npip install boto3 --upgrade\n\nIt moved me to version boto3-1.9.208 botocore-1.12.208 and it works fine.\nI try to use Python virtual environments to isolate libraries for easy updating.\n",
"Actually, get_s... | [
1,
0
] | [] | [] | [
"amazon_web_services",
"boto3",
"python",
"python_3.x"
] | stackoverflow_0057493848_amazon_web_services_boto3_python_python_3.x.txt |
Q:
web scraping of webpage on chartink.com
Please help me to scrape this link.
link - https://chartink.com/screener/time-pass-48
I am trying to web scrape but it is not showing the table which I want. please help me the same.
I have tried this code, but it is not giving me the desired result.
import requests
from bs4... | web scraping of webpage on chartink.com | Please help me to scrape this link.
link - https://chartink.com/screener/time-pass-48
I am trying to web scrape but it is not showing the table which I want. please help me the same.
I have tried this code, but it is not giving me the desired result.
import requests
from bs4 import BeautifulSoup
URL = 'https://chartin... | [
"Data indeed comes from a POST request. You don't need to allow JavaScript to run. You simply need to pick up one cookie (ci_session - which can be done using Session object to hold cookies from initial landing page request to pass on with subsequent POST), and one token (X-CSRF-TOKEN - which can be pulled from a m... | [
5,
1,
0,
0
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"web",
"web_scraping"
] | stackoverflow_0068188760_beautifulsoup_html_python_web_web_scraping.txt |
Q:
Download a file to a google driver folder using selenium in heroku
Can i use the url to a google drive folder as a download_path in selenium
for instance like this .Heroku error says file not found
mudopy.download_path(r"https://drive.google.com/drive/folders/1IPNuefeIXXCKm8Xxm3u1ekltxTF3dCT0")
A:
According to ... | Download a file to a google driver folder using selenium in heroku | Can i use the url to a google drive folder as a download_path in selenium
for instance like this .Heroku error says file not found
mudopy.download_path(r"https://drive.google.com/drive/folders/1IPNuefeIXXCKm8Xxm3u1ekltxTF3dCT0")
| [
"According to the code of mudopy module, it saves the downloaded file into a local directory. So you can later upload that file to a google drive. Not sure if heroku allows to store something locally.\nMoreover, the function mudopy.download_path does not download anything yet, but only creates a local file that sto... | [
0
] | [] | [] | [
"bots",
"google_drive_api",
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074224379_bots_google_drive_api_python_selenium_selenium_webdriver.txt |
Q:
JavaScript crypto.randomBytes(8) to Python Code
I am working with Python in an API. The API is coded using Javascript, and I do not know how would be the equivalent code of this line in Python:
crypto.randomBytes(8).join("")
I found out this link https://docs.python.org/3/library/uuid.html, but I do not know what... | JavaScript crypto.randomBytes(8) to Python Code | I am working with Python in an API. The API is coded using Javascript, and I do not know how would be the equivalent code of this line in Python:
crypto.randomBytes(8).join("")
I found out this link https://docs.python.org/3/library/uuid.html, but I do not know what to do to get exactly the same result.
Thank you for ... | [
"Try:\nfrom random import randint\nbytes([randint(0, 255) for _ in range(8)])\n\nEDIT: If you need secure random bytes:\nfrom secrets import token_bytes\ntoken_bytes(8)\n\ndocs\n"
] | [
0
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0073665311_javascript_python.txt |
Q:
Polars add/substract utc offset from datetime object
I wanted to add/subtract the UTC offset (usually in hours) to/from the datetime object in polars but I don't seem to see a way to do this. the UTC offset can be dynamic given there's Day Light Saving period comes into play in a calendar year. (e.g., EST/EDT maps... | Polars add/substract utc offset from datetime object | I wanted to add/subtract the UTC offset (usually in hours) to/from the datetime object in polars but I don't seem to see a way to do this. the UTC offset can be dynamic given there's Day Light Saving period comes into play in a calendar year. (e.g., EST/EDT maps to 5/4 hours of UTC offset respectively).
from datetime i... | [
"It seems you're looking for with_time_zone;\nfrom datetime import date\nimport polars as pl\n\ndf = pl.DataFrame(\n pl.date_range(\n low=date(2022, 1, 3),\n high=date(2022, 9, 30),\n interval=\"5m\",\n time_unit=\"ns\",\n time_zone=\"UTC\",\n ).alias(\"timestamp\")\n)\n\nus... | [
1,
0
] | [] | [] | [
"datetime",
"pandas",
"python",
"python_polars",
"timezone_offset"
] | stackoverflow_0074165901_datetime_pandas_python_python_polars_timezone_offset.txt |
Q:
How to increment and decrement with a string Python?
Hope you all are doing well in these times.
here's my code:
def ab(n):
first = 0
last = -1
endprod = n[first] + n[last]
endprod2 = n[first+1] + n[last-1]
endprod3 = n[first+2] + n[last-2]
endprod4 = n[first+3] + n[last-3]
endprod5... | How to increment and decrement with a string Python? | Hope you all are doing well in these times.
here's my code:
def ab(n):
first = 0
last = -1
endprod = n[first] + n[last]
endprod2 = n[first+1] + n[last-1]
endprod3 = n[first+2] + n[last-2]
endprod4 = n[first+3] + n[last-3]
endprod5 = n[first+4] + n[last-4]
endprod100 = endp... | [
"Try this:\ndef ab(n):\n result = ''\n for j in range(len(n) // 2):\n result += n[-j-1] + n[j]\n if len(n) % 2 == 1:\n result += n[len(n) // 2]\n return result\n\nYou also need the part\nif len(n) % 2 == 1:\n result += n[len(n) // 2]\n\nbecause your input string might have an odd number... | [
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074225466_python.txt |
Q:
Python scatter plot and matplotlib
I have a scatter plot in python onto which i want to draw a trendline. From the various examples i have found around the internet to learn how to draw the trendline my code is the following:
import matplotlib.pyplot as plt
import numpy as np
x=np.array([9.80,13.20,13.46,14.09,13... | Python scatter plot and matplotlib | I have a scatter plot in python onto which i want to draw a trendline. From the various examples i have found around the internet to learn how to draw the trendline my code is the following:
import matplotlib.pyplot as plt
import numpy as np
x=np.array([9.80,13.20,13.46,14.09,13.96,10.77,8.79,8.61,8.83,11.08,10.13,12.... | [
"I think it is because x values are not sorted. Look at this code:\nimport matplotlib.pyplot as plt \nimport numpy as np\n\nx=np.array([9.80,13.20,13.46,14.09,13.96,10.77,8.79,8.61,8.83,11.08,10.13,12.40,9.90,10.96,12.75,11.79,11.79,12.38,12.78,\n 13.08,12.83,12.57,12.96,12.90,12.91,13.67,12.83,12.50,12.... | [
2,
1,
0
] | [] | [] | [
"matplotlib",
"python",
"scatter_plot",
"trendline"
] | stackoverflow_0045132334_matplotlib_python_scatter_plot_trendline.txt |
Q:
Hosting flask app on subdomain (with WordPress hosted on main domain)
I hope you can help with the following as Iβve been struggling to make it work for many days now.
To give you a little background, I used to host a flask app on my website domain.xyz. It is hosted on namecheap and runs via the CPanel Python App.... | Hosting flask app on subdomain (with WordPress hosted on main domain) | I hope you can help with the following as Iβve been struggling to make it work for many days now.
To give you a little background, I used to host a flask app on my website domain.xyz. It is hosted on namecheap and runs via the CPanel Python App.
I then decided to also have a WordPress on the same site, so I had to move... | [
"Not entirely sure if this is your issue but flask may be failing to find your flask program so in the directory with the program in (as well as any virtual environment used is activated) run:\nexport FLASK_APP=<Your Python Program Name>\n\nYou can test if it found your program by running\nflask run --host=0.0.0.0\... | [
1,
1,
0
] | [] | [] | [
"flask",
"namecheap",
"python",
"subdomain"
] | stackoverflow_0066471365_flask_namecheap_python_subdomain.txt |
Q:
How to color a dataframe row based on a column value when converting to HTML?
I am trying to color a row based on a minimum value in a column.
My mystyle.css is
.mystyle {
font-size: 11pt;
font-family: Arial;
border-collapse: collapse;
border: 1px solid rgb(7, 7, 7);
}
.mystyle td, th {
pad... | How to color a dataframe row based on a column value when converting to HTML? | I am trying to color a row based on a minimum value in a column.
My mystyle.css is
.mystyle {
font-size: 11pt;
font-family: Arial;
border-collapse: collapse;
border: 1px solid rgb(7, 7, 7);
}
.mystyle td, th {
padding: 5px;
}
and I am generating a random dataframe,
import pandas as pd
import nu... | [
"This line stands out to me:\nif df[colname].min():\n\nYou should probably check that this is equal to something, right? Otherwise it just reads as something like \"if 6:\" which is never true.\nUpdate: You want to color the whole row if the value in that column matches the max of the column, so the .apply(function... | [
1
] | [] | [] | [
"css",
"dataframe",
"html",
"pandas",
"python"
] | stackoverflow_0074225237_css_dataframe_html_pandas_python.txt |
Q:
split a string of numbers into a list python
I have a string that contains a random amounts of numbers, these numbers can be like 1, 2, 3 and so, but they can even be 100, 20, 25... so if I'm searching for 14, I will find a 14 in 144, if the string contains it. I Have to split them into a list of integers. Here's ... | split a string of numbers into a list python | I have a string that contains a random amounts of numbers, these numbers can be like 1, 2, 3 and so, but they can even be 100, 20, 25... so if I'm searching for 14, I will find a 14 in 144, if the string contains it. I Have to split them into a list of integers. Here's what I tried:
def to_list(string):
result_list... | [
"You can use regex for that\nimport re\na = \"1001010050101\"\na = list(map(int, re.findall(r\"[1-9]+0*\", a)))\nprint(a)\n\n\n"
] | [
5
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0074225995_list_python_string.txt |
Q:
Most efficient way to split up a dataframe into smaller dataframes
I am writing a python program that will parse a large dataframe (tens of thousands of lines) into smaller dataframes based on a column value, and it needs to be fairly efficient, because the user can change the ways they break up the dataframe, and... | Most efficient way to split up a dataframe into smaller dataframes | I am writing a python program that will parse a large dataframe (tens of thousands of lines) into smaller dataframes based on a column value, and it needs to be fairly efficient, because the user can change the ways they break up the dataframe, and I would like the output to update dynamically.
Example input:
id
Co... | [
"here is one way to do it\n# create lists to hold name and the trimmed data from df\ndflist=[]\ndflist2=[]\nfor k,v in df.groupby(['id']):\n var='id'+str(k)\n\n# append dataframe name in a list\n dflist.append(var)\n\n# create a DF with a variable name\n globals()[var] = v\n\n# append dataframe in a list... | [
1,
0,
0
] | [] | [] | [
"pandas",
"performance",
"python"
] | stackoverflow_0074225949_pandas_performance_python.txt |
Q:
Validating given input and printing every prime number =< given input. (Python)
So I have read tons of solutions to this type of questions, but they all seem to be way too complicated, or I can't find any useful solutions in them.
I have written the first part where I have to ask for an input and validate it to be... | Validating given input and printing every prime number =< given input. (Python) | So I have read tons of solutions to this type of questions, but they all seem to be way too complicated, or I can't find any useful solutions in them.
I have written the first part where I have to ask for an input and validate it to be an integer, but I can't figure out how to write the code for the second part. Effici... | [
"Write an isPrime(n) function that returns true if n is prime, false otherwise. Then test all the numbers from 2 up to the entered integer to see if they are prime.\nWe will help you to improve your code, but you have to write it first.\n",
"It is better to edit multi-line code into your question, rather than pos... | [
0,
0
] | [] | [] | [
"input",
"primes",
"python",
"validation"
] | stackoverflow_0074222209_input_primes_python_validation.txt |
Q:
Can I add images from an AWS S3 bucket to Wagtail/Django database, without downloading and re-uploading each file?
I have a pre-existing AWS S3 bucket that I want to use for Wagtail Images. I want to populate the gallery with the images held in the S3 bucket, so that they're accessible to image fields on page mode... | Can I add images from an AWS S3 bucket to Wagtail/Django database, without downloading and re-uploading each file? | I have a pre-existing AWS S3 bucket that I want to use for Wagtail Images. I want to populate the gallery with the images held in the S3 bucket, so that they're accessible to image fields on page models and also to RichText embedded imagery.
The issue is that there are 1500 images, so I think I want to avoid having the... | [
"I wasn't able to stop Wagtail from downloading the files, as it needs to ascertain image dimensions, but I was able to stop it from uploading duplicate original imagery. With the below solution, the original S3 file keys are used by Wagtail.\n(Of course, renditions are still created and added to the S3 bucket as p... | [
1
] | [] | [] | [
"amazon_s3",
"django",
"image",
"python",
"wagtail"
] | stackoverflow_0074222524_amazon_s3_django_image_python_wagtail.txt |
Q:
Multiple PIDs for Jupyter notebook
When Jupyter notebook starts in my centos 7, It is spawning multiple processes with different process ids (147 unique PIDs). Inspite of shutting down all my notebooks, I see every of those PIDs are running .
pgrep 'jupyter' | wc -l
147
When I start any new notebook, count of pro... | Multiple PIDs for Jupyter notebook | When Jupyter notebook starts in my centos 7, It is spawning multiple processes with different process ids (147 unique PIDs). Inspite of shutting down all my notebooks, I see every of those PIDs are running .
pgrep 'jupyter' | wc -l
147
When I start any new notebook, count of processes are not increasing. It is the sam... | [
"One process corresponds to one instance of the kernel. Therefore, each running notebook on your jupyter lab server is a process. And hence, the several PIDs.\n"
] | [
0
] | [] | [] | [
"jupyter",
"jupyter_notebook",
"python"
] | stackoverflow_0049470802_jupyter_jupyter_notebook_python.txt |
Q:
What is the equivalence of tf.contrib.seq2seq.prepare_attention in TensorFlow 2
I've recently working on some code written in tensorflow 1.0.1 and i want to make it available on tenorflow 2.
I am not very familiar with seq2seq.
Thank you very much.
(attention_keys,
attention_values,
attention_score_fn,
attention_c... | What is the equivalence of tf.contrib.seq2seq.prepare_attention in TensorFlow 2 | I've recently working on some code written in tensorflow 1.0.1 and i want to make it available on tenorflow 2.
I am not very familiar with seq2seq.
Thank you very much.
(attention_keys,
attention_values,
attention_score_fn,
attention_construct_fn) = tf.contrib.seq2seq.prepare_attention(
attention_states=attention_s... | [
"As per this Github Comment, tf.contrib.seq2seq.prepare_attention() is renamed as tf.contrib.seq2seq.DynamicAttentionWrapper.\nAs per this Github Tensorflow Commit, DynamicAttentionWrapper has been renamed to AttentionWrapper.\nSo, in 1.15, the Function equivalent to tf.contrib.seq2seq.prepare_attention() is tf.con... | [
0,
0
] | [] | [] | [
"python",
"seq2seq",
"tensorflow",
"tensorflow2.0"
] | stackoverflow_0062856917_python_seq2seq_tensorflow_tensorflow2.0.txt |
Q:
Tensorflow v2 alternative of sequence_loss_by_example
I am exploring the following tensorflow example: https://github.com/googledatalab/notebooks/blob/master/samples/TensorFlow/LSTM%20Punctuation%20Model%20With%20TensorFlow.ipynb which apparently is written in tf v1, so I upgraded with the v2 upgrade script and th... | Tensorflow v2 alternative of sequence_loss_by_example | I am exploring the following tensorflow example: https://github.com/googledatalab/notebooks/blob/master/samples/TensorFlow/LSTM%20Punctuation%20Model%20With%20TensorFlow.ipynb which apparently is written in tf v1, so I upgraded with the v2 upgrade script and there were three main inconsistencies:
ERROR: Using member tf... | [
"First install tensorflow addons using:\npip install tensorflow-addons\n\nThen import it in your program:\nimport tensorflow_addons as tfa\n\nAnd use:\ntfa.seq2seq.sequence_loss\n\n"
] | [
0
] | [] | [] | [
"deep_learning",
"machine_learning",
"python",
"tensorflow",
"tensorflow2.0"
] | stackoverflow_0064522160_deep_learning_machine_learning_python_tensorflow_tensorflow2.0.txt |
Q:
How to unpack a variable in a lambda function?
Given an input tuple, the goal is to produce a dictionary with some pre-defined keys, e.g. in this case, we have an add_header lambda and use the unpacking inside when calling the function.
>>> z = (2,1)
>>> add_header = lambda x, y: {"EVEN": x, "ODD": y}
>>> add_head... | How to unpack a variable in a lambda function? | Given an input tuple, the goal is to produce a dictionary with some pre-defined keys, e.g. in this case, we have an add_header lambda and use the unpacking inside when calling the function.
>>> z = (2,1)
>>> add_header = lambda x, y: {"EVEN": x, "ODD": y}
>>> add_header(*z)
{'EVEN': 2, 'ODD': 1}
My question is, is the... | [
"You can try using dict() with zip():\nz = (2, 1)\nadd_header = lambda tpl: dict(zip((\"EVEN\", \"ODD\"), tpl))\n\nprint(add_header(z))\n\nPrints:\n{'EVEN': 2, 'ODD': 1}\n\n",
"Don't use a named lambda in the first place. Use the def instead.\nP.S. I think there's an argument to be made that lambdas are weak on p... | [
2,
1
] | [] | [] | [
"dictionary",
"iterable_unpacking",
"lambda",
"python"
] | stackoverflow_0074226092_dictionary_iterable_unpacking_lambda_python.txt |
Q:
How can I connect to a locally hosted site within a docker container?
I'm trying to connect to a docker container's locally hosted address. I'm using Django to serve a website within the container, and I want to connect to it on my local machine.
How can I access this site from my local machine?
I've tried to ins... | How can I connect to a locally hosted site within a docker container? | I'm trying to connect to a docker container's locally hosted address. I'm using Django to serve a website within the container, and I want to connect to it on my local machine.
How can I access this site from my local machine?
I've tried to inspect the container and found that the local IP address is 172.28.0.4. Even ... | [
"If you can connect to the docker instance through ssh, try:\nssh user@172.28.0.4 -L 8000:172.28.0.4:8000\nThen navigate to your project and do py manage.py runserver 0.0.0.0:8000\nThen on your local machine go to your browser and you should be able to access your app @ http://127.0.0.1:8000\n"
] | [
1
] | [] | [] | [
"django",
"docker",
"docker_compose",
"python"
] | stackoverflow_0074225802_django_docker_docker_compose_python.txt |
Q:
How to use signal protocol to encrypt/decrypt?
I was reverse engineering WhatsApp web. I created a custom client in python to connect to WhatsApp with websocket, generate a QR code, and save the login credentials to a file. When I tried to use it, I realized that WhatsApp's end to end encryption is real. I used th... | How to use signal protocol to encrypt/decrypt? | I was reverse engineering WhatsApp web. I created a custom client in python to connect to WhatsApp with websocket, generate a QR code, and save the login credentials to a file. When I tried to use it, I realized that WhatsApp's end to end encryption is real. I used this python module to generate 2 signal protocol keys:... | [
"I got an open source project that does exactly that, but now unfortunately whatsapp forced an updated, that changed a lot, and no longer supports that.\nHere is the project: WhatsApp Web reverse engineered\nEDIT:\nSo I was wrong with signal protocol, because whatsapp used curve25519.\nWhen recived _login (source) ... | [
1
] | [] | [] | [
"cryptography",
"python",
"signal_protocol"
] | stackoverflow_0069737393_cryptography_python_signal_protocol.txt |
Q:
How to interchange x and y axis when plotting using xarray?
I am plotting some data from the cdasws.datarepresentation. I have plotted the plots using matlabplotlib but i cannot figure out how to flip the axes and i couldnt find it in the documentation.
here is the code
%pip install xarray
%pip install cdflib
%pip... | How to interchange x and y axis when plotting using xarray? | I am plotting some data from the cdasws.datarepresentation. I have plotted the plots using matlabplotlib but i cannot figure out how to flip the axes and i couldnt find it in the documentation.
here is the code
%pip install xarray
%pip install cdflib
%pip install cdasws
from cdasws import CdasWs
from cdasws.datarepres... | [
"when you plot a 2-dimensional array, the default plotting handler is xr.DataArray.plot.pcolormesh, so arguments will be handled by that function. To see the full set of available plotting methods and the default handler for 1, 2, and 3 dimensions, see xr.DataArray.plot and the Plotting section of the user guide.\n... | [
0
] | [] | [] | [
"python",
"python_xarray"
] | stackoverflow_0074219963_python_python_xarray.txt |
Q:
Is there I can repeat this for a section of rows?
I'm trying to print the rs_id, p_dot and corresponding header for each row after 7 where a cell is occupied on the CSV file.
import csv
with open("CYP2C9.csv",'r') as infile:
reader = csv.reader(infile, delimiter=",")
header= next(reader)
for row in rea... | Is there I can repeat this for a section of rows? | I'm trying to print the rs_id, p_dot and corresponding header for each row after 7 where a cell is occupied on the CSV file.
import csv
with open("CYP2C9.csv",'r') as infile:
reader = csv.reader(infile, delimiter=",")
header= next(reader)
for row in reader:
rs_id = row[4]
snp = row[7]
... | [
"row[7] is a single element of your list, and will be a string. You can compare this to a string (\"\") because it is already a string.\nrow[start:end] is a slice of rows, which is a list. You can't compare a list to a string, because those are two different things. Instead, you want to compare each element of your... | [
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074226117_csv_python.txt |
Q:
How to fetch data from database with django
Im trying to fetch data from django database.
I want to display all the data as divs with different titles, images and description.
views.py
from .models import Links
def all_links(request):
links= Links.objects.all()
return render(request, 'links.html',
{'link... | How to fetch data from database with django | Im trying to fetch data from django database.
I want to display all the data as divs with different titles, images and description.
views.py
from .models import Links
def all_links(request):
links= Links.objects.all()
return render(request, 'links.html',
{'links' : links})
models.py
class Links(models.Model)... | [
"You're referencing a variable named link_list in your template, but the name of the variable you are passing into the view is links. Change it to this:\n{% for link in links %}\n\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074226263_django_python.txt |
Q:
mypy does not detect errors when wrongly using a function imported from an external package
I've run a simple experiment where I've created a very simple python package containing the following files:
In the folder my_package:
# example.py
def foo(number: int, text: str) -> None:
print(number)
print(text)
... | mypy does not detect errors when wrongly using a function imported from an external package | I've run a simple experiment where I've created a very simple python package containing the following files:
In the folder my_package:
# example.py
def foo(number: int, text: str) -> None:
print(number)
print(text)
An empty __init__.py
In the root folder, a setup.py file:
from setuptools import setup
setup(
... | [
"According to PEP-561 (a python standard that regulates use of typing data for packages), there are two general ways to declare types for package.\nThe first (applicable in your case) is py.typed marker. It is an empty file named py.typed, placed in package root (the same place where the topmost __init__.py resides... | [
1
] | [] | [] | [
"mypy",
"python",
"python_3.x"
] | stackoverflow_0074193458_mypy_python_python_3.x.txt |
Q:
kafka consumer to ruby on rails
I am currently working with a rails server which is supposed to run python script, which are kafka consumer/producer.
The server must to run the script then receive the processed data from consumer, and render them to the site.
I am able to run a script but can not fund a solution f... | kafka consumer to ruby on rails | I am currently working with a rails server which is supposed to run python script, which are kafka consumer/producer.
The server must to run the script then receive the processed data from consumer, and render them to the site.
I am able to run a script but can not fund a solution for the consumer to be connected. As t... | [
"Not sure why you are trying to run python scripts from a running Rails server. It sounds like a very bad idea to me. You can run Kafka consumers/producers from Ruby and Ruby on Rails directly. I suggest you investigate Karafka. We've been using it successfully at work.\n"
] | [
0
] | [] | [] | [
"apache_kafka",
"mq",
"python",
"ruby_on_rails"
] | stackoverflow_0074153287_apache_kafka_mq_python_ruby_on_rails.txt |
Q:
How to keep system alive in case of inactivity?
Is there any way in Python to keep it system active all the time?
A:
Best way For Windows without Python
copy the below code and save the file as .ps1 extension
After saving file, Right click on it and select Run With PowerShell
Clear-Host
Echo "toggling scroll loc... | How to keep system alive in case of inactivity? | Is there any way in Python to keep it system active all the time?
| [
"Best way For Windows without Python\ncopy the below code and save the file as .ps1 extension\nAfter saving file, Right click on it and select Run With PowerShell\nClear-Host\nEcho \"toggling scroll lock\"\n$WShell = New-Object -com \"Wscript.Shell\"\nwhile ($true) {\n$WShell.sendkeys(\"{SCROLLLOCK}\")\nStart-Sleep... | [
6,
2,
0,
0,
0,
0
] | [
"//Create Windows Form project in Visual Studio using C#\n//Make sure this form is in focus while the project is running\n\n using System;\n using System.Windows.Forms;\n \n namespace MsTeamsAvailable\n {\n public partial class Form1 : Form\n {\n public Form1()\n {... | [
-1,
-2
] | [
"microsoft_teams",
"python"
] | stackoverflow_0071029364_microsoft_teams_python.txt |
Q:
Fastest way to write a dataframe with millions of lines into csv
I have a dataframe with ~7 million lines and 18 columns.
What is the fastest library that consumes less time?
Right now I am writing the dataframe using:
df.to_csv('file.csv', header=True, index=False)
And it is taking me ~3 hours.
The file has ~800... | Fastest way to write a dataframe with millions of lines into csv | I have a dataframe with ~7 million lines and 18 columns.
What is the fastest library that consumes less time?
Right now I am writing the dataframe using:
df.to_csv('file.csv', header=True, index=False)
And it is taking me ~3 hours.
The file has ~800 MB.
Is there a faster method/library to speed up the writing process?... | [
"Try using https://pypi.org/project/pyarrow/\nI've found it to be 86% faster for reading and 30% faster for writing CSV files as compared to pandas!\n"
] | [
0
] | [] | [] | [
"csv",
"dataframe",
"python"
] | stackoverflow_0062881472_csv_dataframe_python.txt |
Q:
jinja2 : how to match string to json field
I'm having a problem in a jinja template. If I have an object 'jsonobj' like so:
{
"type": "test",
"people": [{"name": "bill", "age": 43}]
}
in my template I'm trying to do an if like
{% if 'test' is jsonobj.type %}
<!-- some html here -->
{% else %}
<!--... | jinja2 : how to match string to json field | I'm having a problem in a jinja template. If I have an object 'jsonobj' like so:
{
"type": "test",
"people": [{"name": "bill", "age": 43}]
}
in my template I'm trying to do an if like
{% if 'test' is jsonobj.type %}
<!-- some html here -->
{% else %}
<!-- some other html here -->
{% endif %}
but I g... | [
"May be you forget endif tag at end?\n {% if 'test' is jsonobj.type %}\n ...\n {% else %}\n ...\n {% endif %}\n\n",
"{% endif %} it seems you forgot to turn off the if blog\n",
"I was able to resolve this issue by making sure the whitespace/indenting was even. That seemed to resolve the issue\n"
... | [
0,
0,
0
] | [] | [] | [
"jinja2",
"json",
"python",
"templates"
] | stackoverflow_0074209666_jinja2_json_python_templates.txt |
Q:
Intersection between 2d image point and 3d mesh
Given: Mesh, Source Camera - I have intrinsic and extrinsic parameters, Image coordinate 2d
Output: 3D point, which is the intersection of a ray from camera center, through the 2d point on the image plane and the mesh. (I'm trying to find the 3d point on the mesh)
Th... | Intersection between 2d image point and 3d mesh | Given: Mesh, Source Camera - I have intrinsic and extrinsic parameters, Image coordinate 2d
Output: 3D point, which is the intersection of a ray from camera center, through the 2d point on the image plane and the mesh. (I'm trying to find the 3d point on the mesh)
This is the process:
From Multiple View Geometry in Co... | [
"As Grillteller pointed out in the comment, this is a ray intersection problem with the 3d mesh. As far as I know, humanity does not yet know a quick way to determine the intersection for an arbitrary mesh. In your problem context, you should Ray Tracing, which is also pointed out by Grillteller, however this has s... | [
4,
4,
0
] | [] | [] | [
"geometry",
"mesh",
"open3d",
"opencv",
"python"
] | stackoverflow_0066968822_geometry_mesh_open3d_opencv_python.txt |
Q:
How to display two lists at the same time
I have two lists
x = ['34', '22', '45']
y = ['red', 'blue', 'grean']
I need to output these two lists together
34, red
22, blue
45, grean
i tried to get it all through for in
for a, b in x, y:
print(a, b)
but i get an error
too many values to unpack (expected 2)
A... | How to display two lists at the same time | I have two lists
x = ['34', '22', '45']
y = ['red', 'blue', 'grean']
I need to output these two lists together
34, red
22, blue
45, grean
i tried to get it all through for in
for a, b in x, y:
print(a, b)
but i get an error
too many values to unpack (expected 2)
| [
"x = ['34', '22', '45']\ny = ['red', 'blue', 'grean']\n\nfor a, b in zip(x, y):\n print(f\"{a}, {b}\")\n\nOutput:\n34, red\n22, blue\n45, grean\n\n",
"Try this:\nx = ['34', '22', '45']\ny = ['red', 'blue', 'green'] // you made a typo in 'green' so i fixed it\nfor i, x in enumerate(x):\n print(f\"{x}, {y[i]}... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074226354_python.txt |
Q:
How can I iterate over specific index in pandas?
So I have a list of index close_index I want to iterate over these specific index and update the column values.
hhinc8,owncar,longitude,latitude,category
5,1,-82.99194508,40.04649963,LRLC
6,2,-82.99584706,40.03738548,LRHC
5,1,-82.99697268,40.02674247,LRLC
6,2,-82.99... | How can I iterate over specific index in pandas? | So I have a list of index close_index I want to iterate over these specific index and update the column values.
hhinc8,owncar,longitude,latitude,category
5,1,-82.99194508,40.04649963,LRLC
6,2,-82.99584706,40.03738548,LRHC
5,1,-82.99697268,40.02674247,LRLC
6,2,-82.99160441,40.03612997,LRHC
1,2,-82.994716,40.04691778,ERH... | [
"here is one way to do it\n# create a dictionary to map owncar to the category value\nd={1: 'LRLC', 2: 'LRHC'}\n\n\nclose_index =[1,3,4]\n\ndf['category'] = df.loc[close_index]['owncar'].map(d)\ndf\n\n\nor simply\nhhinc8 owncar longitude latitude category\n0 5 1 -82.991945 40.046500 LRLC\n1 6 2 ... | [
1,
0
] | [] | [] | [
"loops",
"pandas",
"python"
] | stackoverflow_0074226359_loops_pandas_python.txt |
Q:
Methods to shorten ifs in python using OOP or other patterns
I asked several people how I could shorten the ifs in python, but I did not find a clear answer
For example I have the following code below
if 'attributes' not in data:
data['attributes']: list = []
# filter columns with attributes
attribute... | Methods to shorten ifs in python using OOP or other patterns | I asked several people how I could shorten the ifs in python, but I did not find a clear answer
For example I have the following code below
if 'attributes' not in data:
data['attributes']: list = []
# filter columns with attributes
attributes: group.filter = group.filter(like='attribute')
# we take a ... | [
"words = {'attributes': 'attribute', \n 'categories': 'category', \n 'filters': 'filters', \n 'disliked_products': 'dislike product'}\n\nfor word, singular_word in words.items():\n if word in data:\n continue\n\n data[word]: list = []\n\n # filter columns with categories\n ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074226249_python.txt |
Q:
Snowflake connector python package not recognized
Trying to import snowflake.connector:
import snowflake.connector
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Cell In [1], line 1
----> 1 import snowflake.co... | Snowflake connector python package not recognized | Trying to import snowflake.connector:
import snowflake.connector
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Cell In [1], line 1
----> 1 import snowflake.connector
ModuleNotFoundError: No module named 'snowflak... | [
"The answer as pointed out by @Sergiu was that I had a package called snowflake also installed. Solution:\npip3 uninstall snowflake\n\n"
] | [
2
] | [] | [] | [
"jupyter_notebook",
"pip",
"python",
"snowflake_cloud_data_platform"
] | stackoverflow_0074223900_jupyter_notebook_pip_python_snowflake_cloud_data_platform.txt |
Q:
adding rows with Nan values to Pandas DataFrame
I want to insert rows with Nan values after each row
index
values
0
44
1
50
2
51
3
66
4
23
DataFrame should look like this
index
values
0
44
1
Nan
2
50
3
Nan
4
51
5
Nan
6
66
7
Nan
8
23
A:
Use concat with DataFrame filled by NaNs and same indices an... | adding rows with Nan values to Pandas DataFrame | I want to insert rows with Nan values after each row
index
values
0
44
1
50
2
51
3
66
4
23
DataFrame should look like this
index
values
0
44
1
Nan
2
50
3
Nan
4
51
5
Nan
6
66
7
Nan
8
23
| [
"Use concat with DataFrame filled by NaNs and same indices and then use DataFrame.sort_index:\ndf = (pd.concat([df, pd.DataFrame(index=df.index)])\n .sort_index(kind='stable', ignore_index=True))\nprint (df)\n values\n0 44.0\n1 NaN\n2 50.0\n3 NaN\n4 51.0\n5 NaN\n6 66.0\n7 NaN\n8... | [
1,
0,
0
] | [] | [] | [
"dataframe",
"nan",
"pandas",
"python",
"rows"
] | stackoverflow_0071170892_dataframe_nan_pandas_python_rows.txt |
Q:
How to Login with a Custom User Model Table in Django 4.1.1?
I'm making an educational website in Django 4.1.1, and i need students to be able to register and login, so i created a Custom User Model Table in my models.py file.
from django.db import models
from django.contrib.auth.models import AbstractUser
from dj... | How to Login with a Custom User Model Table in Django 4.1.1? | I'm making an educational website in Django 4.1.1, and i need students to be able to register and login, so i created a Custom User Model Table in my models.py file.
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import UserManager
class Custom(UserMa... | [
"The Problem was that i was miss-spelling the request.method == 'Post' , it should be request.method == 'POST' , the second problem was that i was naming my login view login, and that's unacceptable, because that name is already taken by django.contrib.auth.login, so i changed the view name , and the problem was so... | [
0
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0074225956_django_django_forms_django_models_python.txt |
Q:
Limiting floats to two decimal points
I want a to be rounded to 13.95. I tried using round, but I get:
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
For the analogous issue with the standard library Decimal class, see How can I format a decimal to always show 2 decimal places?.
A:
You are running ... | Limiting floats to two decimal points | I want a to be rounded to 13.95. I tried using round, but I get:
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
For the analogous issue with the standard library Decimal class, see How can I format a decimal to always show 2 decimal places?.
| [
"You are running into the old problem with floating point numbers that not all numbers can be represented exactly. The command line is just showing you the full floating point form from memory.\nWith floating point representation, your rounded version is the same number. Since computers are binary, they store float... | [
2159,
759,
400,
275,
172,
100,
99,
71,
71,
65,
57,
56,
43,
31,
30,
28,
24,
16,
13,
10,
8,
7,
7,
7,
7,
6,
4,
4,
3,
3,
0,
0
] | [
"Just use this function and pass bytes as an input to it:\ndef getSize(bytes):\n kb = round(bytes/1024, 4)\n mb = round(kb/1024, 4)\n gb = round(mb/1024, 4)\n if(gb > 1):\n return str(gb) + \" GB\"\n elif(mb > 1):\n return str(mb) + \" MB\"\n else:\n return str(kb) + \" KB\"\n... | [
-1,
-17
] | [
"floating_point",
"precision",
"python",
"rounding"
] | stackoverflow_0000455612_floating_point_precision_python_rounding.txt |
Q:
python string convert to datetime doesn't work
I'm trying to convert a string, I got from my program, to datetime.dateime but it doesn't seem to work because I have the wrong format? The thing is, I have the right format...
Here is some code:
from datetime import datetime
Timer = "27.10.2022 β’ 08:24:03"
Timer = Ti... | python string convert to datetime doesn't work | I'm trying to convert a string, I got from my program, to datetime.dateime but it doesn't seem to work because I have the wrong format? The thing is, I have the right format...
Here is some code:
from datetime import datetime
Timer = "27.10.2022 β’ 08:24:03"
Timer = Timer.replace(".", "/")
Timer = Timer.replace("β’", "",... | [
"It does work, you have to use %Y instead of %y\n%Y works with years like 2022, 2023\n%y works with years like 22, 23\n"
] | [
3
] | [] | [] | [
"datetime",
"python",
"python_datetime",
"replace",
"type_conversion"
] | stackoverflow_0074226484_datetime_python_python_datetime_replace_type_conversion.txt |
Q:
(Discord.py) Is there any way to check that sent attachment is image?
Im making a image-editing bot and i cant figure out how to check if sent attachment is image.
So im wondering if theres any way to check it, thanks for answer.
I tried:
if = ctx.message.attachments[0].image == True:
# do stuff
But sadly got ... | (Discord.py) Is there any way to check that sent attachment is image? | Im making a image-editing bot and i cant figure out how to check if sent attachment is image.
So im wondering if theres any way to check it, thanks for answer.
I tried:
if = ctx.message.attachments[0].image == True:
# do stuff
But sadly got error (i was expecting it!!!!)
| [
"The discord.Attachment class has a content_type attribute that contains the MIME-type of the attachment. For example, if the user uploads a .png file, the value of this will be \"image/png\". Checking if it starts with \"image/\" is probably good enough for your use-case, unless you only want to allow very specifi... | [
1
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074226299_discord_discord.py_python.txt |
Q:
Compare two nested lists in Python
I have two lists:
list_a = [["the", "ball", "is", "red", "and", "the", "car", "is", "red"],
["the", "boy", "is", "tall", "and", "the", "man", "is", "tall"]]
list_b = [["the", 0], ["ball", 0], ["is", 0], ["red", 0], ["and", 0], ["car", 0]],
["The", 0], ["boy", ... | Compare two nested lists in Python | I have two lists:
list_a = [["the", "ball", "is", "red", "and", "the", "car", "is", "red"],
["the", "boy", "is", "tall", "and", "the", "man", "is", "tall"]]
list_b = [["the", 0], ["ball", 0], ["is", 0], ["red", 0], ["and", 0], ["car", 0]],
["The", 0], ["boy", 0], ["is", 0], ["and", 0], ["man", 0], [... | [
"You can use enumerate and find the index of each row in list_b and base row_index, Use collections.Counter for list_a and update value in each sublist of each row in list_b.\nfrom collections import Counter\n\nfor row, lst_b in enumerate(list_b):\n cnt_list_a = Counter(list_a[row])\n for lst in lst_b:\n ... | [
3
] | [] | [] | [
"compare",
"list",
"python"
] | stackoverflow_0074226472_compare_list_python.txt |
Q:
Python count elements in dictionary comprehension when count is above a threshold
I want to populate a dictionary with the counts of various items in a list, but only when the count exceeds a certain number. (This is in Python 2.7)
For example:
x = [2,3,4,2,3,5,6] if I only want numbers that appear twice or more, ... | Python count elements in dictionary comprehension when count is above a threshold | I want to populate a dictionary with the counts of various items in a list, but only when the count exceeds a certain number. (This is in Python 2.7)
For example:
x = [2,3,4,2,3,5,6] if I only want numbers that appear twice or more, I would want only
d = {2: 2, 3: 2} as an output.
I wanted to do this with a dictionary ... | [
"Use Counter to count each items in x, the use a dictionary comprehension to pull those values where the count is greater than or equal to your threshold (e.g. 2).\nfrom collections import Counter\n\nx = [2, 3, 4, 2, 3, 5, 6]\nthreshold = 2\nc = Counter(x)\nd = {k: v for k, v in c.iteritems() if v >= threshold}\n>>... | [
4,
2,
0,
0,
0
] | [] | [] | [
"dictionary_comprehension",
"python",
"python_2.7"
] | stackoverflow_0045855034_dictionary_comprehension_python_python_2.7.txt |
Q:
How can I iterate through two Pandas columns?
Consider:
In [35]: test = pd.DataFrame({'a':range(4),'b':range(4,8)})
In [36]: test
Out[36]:
a b
0 0 4
1 1 5
2 2 6
3 3 7
In [37]: for i in test['a']:
....: print i
....:
0
1
2
3
In [38]: for i,j in test:
....: print i,j
....:
--------------... | How can I iterate through two Pandas columns? | Consider:
In [35]: test = pd.DataFrame({'a':range(4),'b':range(4,8)})
In [36]: test
Out[36]:
a b
0 0 4
1 1 5
2 2 6
3 3 7
In [37]: for i in test['a']:
....: print i
....:
0
1
2
3
In [38]: for i,j in test:
....: print i,j
....:
------------------------------------------------------------
Trac... | [
"Use the DataFrame.itertuples() method:\nfor a, b in test.itertuples(index=False):\n print a, b\n\n",
"You can use zip (this is native in PythonΒ 3 and can be imported from itertools as izip in PythonΒ 2.7):\nPython 3\nfor a,b in zip(test.a, test.b):\n print(a,b)\n\nPython 2\nfor a,b in izip(test.a, test.b):\... | [
51,
33,
10,
8,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0015125343_pandas_python.txt |
Q:
python regex parse using re.sub() with multiple posibilities
I am trying to parse the numeral content embedded in a string. The string has three possible forms:
'avenue\d+', where \d+ is a number with one or more digits
or
'road\d+'
or
'lane\d+'
I tried:
re.sub(r'(?:avenue(\d+)|road(\d+)|lane(\d*))',r'\1','road1... | python regex parse using re.sub() with multiple posibilities | I am trying to parse the numeral content embedded in a string. The string has three possible forms:
'avenue\d+', where \d+ is a number with one or more digits
or
'road\d+'
or
'lane\d+'
I tried:
re.sub(r'(?:avenue(\d+)|road(\d+)|lane(\d*))',r'\1','road12')
This code works well for the first line below, but incorrectl... | [
"The capturing group that participated in the match was different. In the first case, it was Group 1, in the second case, it was Group 2.\nAlso, note that the non-capturing group is superfluous, remove it.\nTo fix the immediate issue, you can use r'\\1\\2\\3' as replacement:\nre.sub(r'avenue(\\d+)|road(\\d+)|lane(... | [
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074226650_python_regex.txt |
Q:
How to add multiple print functions into one string
I have multiple function that instead of returning they print a certain string I canβt put the whole function but thatβs what they end up doing I want to take all of these function and make them into a single string.
Hereβs an example of what one function would p... | How to add multiple print functions into one string | I have multiple function that instead of returning they print a certain string I canβt put the whole function but thatβs what they end up doing I want to take all of these function and make them into a single string.
Hereβs an example of what one function would print and what I tried
def print_names(lst):
... | [
"ok you should do it like this\ndef print_names(lst):\n return lst[0]\ndef print_id(lst):\n return lst[3]\n\nlst = [name, not_name, not_name,id] \nid_and_name = print_names(lst) + print_id(lst)\n\nafter that you will be able to print the \"id_and_name\" together\n",
"If you tried to return the Values, it wo... | [
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074226553_python.txt |
Q:
For loop runs and perform task on only the first element of the the iterable but not the rest and returns the result of only the action on 1st element
The last for loop of the code seems to only run for the first element of the list and not the rest of the element
a = int(input())
setA = set(map(int, input().split... | For loop runs and perform task on only the first element of the the iterable but not the rest and returns the result of only the action on 1st element | The last for loop of the code seems to only run for the first element of the list and not the rest of the element
a = int(input())
setA = set(map(int, input().split()))
n = int(input())
com = [input() for alnum in range(n*2)]
nestcom = []
cmd = []
for i in com:
if com.index(i)%2 == 0:
nestcom.append([i, com... | [
"here is your last loop:\nfor u in cmd:\n eval('setA.'+cmd[0][0][0]+'('+str(cmd[0][1])+')')\n\nYou are using cmd in what you are doing within the loop, not u. That is, you aren't using each element in cmd, you are just using cmd a number of times.\nYou likely want to use u in the loop itself (like eval('setA.'+u... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074225887_python.txt |
Q:
Weighted sparse categorical cross entropy
I am dealing with a semantic segmentation problem where the two classes in which I am interested (in addition to background) are quiet unbalanced in the image pixels. I am actually using sparse categorical cross entropy as a loss, due to the way in which training masks are... | Weighted sparse categorical cross entropy | I am dealing with a semantic segmentation problem where the two classes in which I am interested (in addition to background) are quiet unbalanced in the image pixels. I am actually using sparse categorical cross entropy as a loss, due to the way in which training masks are encoded. Is there any version of it which take... | [
"As far as I know you can use class weights in model.fit for any loss function. I have used it with categorical_cross_entropy and it works. It just weights the loss with the class weight so I see no reason it should not work with sparse_categorical_cross_entropy.\n",
"I think this is the solution to weigh sparse_... | [
1,
1,
0
] | [] | [] | [
"cross_entropy",
"image_segmentation",
"keras",
"python",
"tensorflow"
] | stackoverflow_0065188739_cross_entropy_image_segmentation_keras_python_tensorflow.txt |
Q:
How can I get with_loader_criteria to apply to multiple models in a query?
I'm using SQLAlchemy's with_loader_criteria along with the do_orm_execute hook to update queries to add additional WHERE statements before they're executed. This is to replace the old process of using the before_compile hook, which has been... | How can I get with_loader_criteria to apply to multiple models in a query? | I'm using SQLAlchemy's with_loader_criteria along with the do_orm_execute hook to update queries to add additional WHERE statements before they're executed. This is to replace the old process of using the before_compile hook, which has been deprecated in SQLAlchemy 1.4.
My hook handler looks like this
@event.listens_fo... | [
"I ended up using this, which is more or less what I had when I was using before_compile. I couldn't get with_loader_criteria to work for multiple models.\n@event.listens_for(Session, \"do_orm_execute\")\ndef receive_do_orm_execute(execute_state):\n if execute_state.is_select and not execute_state.is_column_load... | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0074197458_python_sqlalchemy.txt |
Q:
Jupyter Notebook Restart and Run All Cells Automatically
My code connects with a database and sometimes the database disconnects on me. As result the script ends. I would like to be able to add a line of code that would allow me to restart and run all the cells in Jupyter notebook.
Input:
if condition ==True:
#... | Jupyter Notebook Restart and Run All Cells Automatically | My code connects with a database and sometimes the database disconnects on me. As result the script ends. I would like to be able to add a line of code that would allow me to restart and run all the cells in Jupyter notebook.
Input:
if condition ==True:
#Kernel restart and run all jupyter cells
I understand there i... | [
"Would a keyboard shortcut suffice?\nFor JupyterLab users and those using the document-centric notebook experience in the future, see How to save a lot of time by have a short cut to Restart Kernel and Run All Cells?.\n\nFor those still using the classic notebook (version 6 and earlier) interface to run Jupyter not... | [
0
] | [] | [] | [
"jupyter_notebook",
"python"
] | stackoverflow_0074215823_jupyter_notebook_python.txt |
Q:
Trying to find the first value in each line and print same values together
I am trying to collapse everything together through subclasses and parentclass and print the textfile properly.
I have assigned values for each subclass when printing, how do I tell python to find it and combine every line with the same val... | Trying to find the first value in each line and print same values together | I am trying to collapse everything together through subclasses and parentclass and print the textfile properly.
I have assigned values for each subclass when printing, how do I tell python to find it and combine every line with the same value (like my output)
I have tried putting i_car & d_car inside the for loop but i... | [
"Try something like this:\nclass Car:\n def __init__(self, brand: str, model: str, year: str, price: str, type: str):\n self.brand = brand\n self.model = model\n self.year = year\n self.price = price\n self.type = type\n\n def print_info(self) -> None:\n raise NotImpl... | [
0
] | [] | [] | [
"inheritance",
"python",
"superclass"
] | stackoverflow_0074194902_inheritance_python_superclass.txt |
Q:
python -m pip install pygame==2.0.0 error
EDIT: I'm on MSYS2, that might be an important detail.
I'm trying to install the Pygame module.
I tried both the command in the title and pip3 install pygame==2.0.0
It gives me the exact same error
Downloading pygame-2.0.0.tar.gz (5.5 MB)
ββββββββββββββββββββββββββββ... | python -m pip install pygame==2.0.0 error | EDIT: I'm on MSYS2, that might be an important detail.
I'm trying to install the Pygame module.
I tried both the command in the title and pip3 install pygame==2.0.0
It gives me the exact same error
Downloading pygame-2.0.0.tar.gz (5.5 MB)
ββββββββββββββββββββββββββββββββββββββββ 5.5/5.5 MB 5.7 MB/s eta 0:00:00
... | [
"It looks like you don't have pkg-config installed:\n\n/bin/sh: line 1: pkg-config: command not found\n\n"
] | [
0
] | [] | [] | [
"pip",
"pygame",
"python"
] | stackoverflow_0074225688_pip_pygame_python.txt |
Q:
Upload folders from local system to FTP using Python script
I have to automatically upload folders to an FTP using a Python script. I am able to upload a single file, but not folders with subfolders and files in them. I did a lot of search, but failed. Could some one help me out here? Thanks in advance.
#! /usr/bi... | Upload folders from local system to FTP using Python script | I have to automatically upload folders to an FTP using a Python script. I am able to upload a single file, but not folders with subfolders and files in them. I did a lot of search, but failed. Could some one help me out here? Thanks in advance.
#! /usr/bin/python
import ftplib
s = ftplib.FTP('serverip','usrname','pass... | [
"I recently came into this problem and figured out a recursive function to solve it.\nimport ftplib\nimport os\n\nserver = 'localhost'\nusername = 'generic_user'\npassword = 'password'\nmyFTP = ftplib.FTP(server, username, password)\nmyPath = r'c:\\temp'\ndef uploadThis(path):\n files = os.listdir(path)\n os.... | [
25,
9,
5,
4,
3,
2,
0
] | [] | [] | [
"ftp",
"ftplib",
"python"
] | stackoverflow_0005663787_ftp_ftplib_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.