Unnamed: 0 int64 0 1.91M | id int64 337 73.8M | title stringlengths 10 150 | question stringlengths 21 64.2k | answer stringlengths 19 59.4k | tags stringlengths 5 112 | score int64 -10 17.3k |
|---|---|---|---|---|---|---|
8,100 | 48,908,353 | Adding a column to dictReader without modifying the CSV file | <p>I have a CSV file that has 3 columns. Let's say: <code>a</code>, <code>b</code>, <code>c</code>. I'm using <code>csv.dictReader</code> to read it and add another column that has just the name of the file on each row. </p>
<p>This is my function:</p>
<pre><code>def addFilename(self):
with open(self.datafile, "r... | <p>You do not have to iterate on the level of column names. You can treat all of the existing column values returned by <code>for ... in reader</code> as a tuple. Then:</p>
<pre><code> def addFilename2(self):
with open(self.datafile, "r") as f:
reader = csv.DictReader(f, delimiter='|')
for column... | python|csv | 1 |
8,101 | 72,445,800 | How to Clear Dynamically Generated Page Cached on the Server | <p>I'm generating a html page that is basically a list of photos saved in a single folder. I trigger the generation of the pictures.html template each time a new photo is added to the folder.</p>
<p>My problem is the old template page seems to be used from the cached even when I open a new browser on a different devic... | <p>Turned out I was barking up the wrong tree :)
I changed my approach and removed all the changeable file information from the pictures.html template.
I then added code to app.py that reads the file information and saves it to a list. I then pass the list to the pictures.html template and in the html, iterated throug... | python|apache | 0 |
8,102 | 50,967,231 | Pandas - Select Rows by 'type' (Not dtype) | <p>I have a DataFrame....</p>
<pre><code> _id doc_count doc_media_url image_tagging
0 327bcc224b8c7049 1.0 URL1 {'success': True, 'tags': [], 'custom_tags': []}
1 e466c4966666c69e 1.0 URL2 {'success': True, 'tags': [{'tag': 'Cartoon', ...
2 b4303830389cf8f9 1.0 URL3 {'success': T... | <p>try this:</p>
<pre><code>df = df[df.image_tagging.map(type)==dict]
</code></pre>
<p>Demo:</p>
<pre><code>In [146]: df = pd.DataFrame({
...: 'A': [{'1':1, 'a':2}, [1,2,3], {'2':2}],
...: })
In [147]: df
Out[147]:
A
0 {'1': 1, 'a': 2}
1 [1, 2, 3]
2 {'2': 2}
In [14... | python|pandas | 8 |
8,103 | 57,842,985 | Python logging to write all level logs to file | <pre><code>import logging
def set_logging():
logging.basicConfig(
format='%(asctime)s %(levelname)s %(message)s',
level=logging.INFO,
datefmt='%m/%d/%Y %I:%M:%S %p'
)
logger = logging.getLogger('simple_example')
fl = logging.FileHandler("myapp.log")
fl.setLevel(logging.I... | <p>If you just add <code>logger.propagate = False</code> this line in <code>set_logging</code> function. It will write all levels of log into the file and will not be shown on the console.</p>
<pre class="lang-py prettyprint-override"><code>def set_logging():
logging.basicConfig(
format='%(asctime)s %(leve... | python|logging | 1 |
8,104 | 56,425,375 | pure-python callback function was called with parameter b'', lossing the actual data in cython function | <p>I try to call a callback function in cython cdef block, I can printf the actual data during cython function call, but when my callback function was called or I call a print(buffer) in cython cdef block, I got the (paramter/result) with b'',I try other demo, It's all works fine.</p>
<p>windows 10, python3.7, cython ... | <p>Calling either <code>print(o)</code> or <code>self.func(o)</code> involves converting <code>o</code> to a Python object, in this case a <code>bytes</code> object. This conversion assumes that the <code>char*</code> is a c string (i.e. is null terminated) since Cython has no other way to determine the length. However... | python-3.x|callback|byte|cython | 1 |
8,105 | 56,999,272 | How to remove first closed paren and last open in a sentence using regex? | <p>I need to get rid of false parens. This is example sentence:</p>
<pre><code>s = "trees 1) whatever ( goor brc ) the content ( and bad now."
</code></pre>
<p>I need to remove only first <code>)</code> and last <code>(</code> from it.</p>
<p>My code doesn't work because I use illegal syntax. However, I some languag... | <p>I'm guessing that this expression,</p>
<pre><code>(\([^)]+\))|([()]+)
</code></pre>
<p>might work to some extent, not sure though.</p>
<h3>Test with <code>re.sub</code></h3>
<pre><code>import re
regex = r"(\([^)]+\))|([()]+)"
test_str = "trees 1) whatever ( goor brc ) the content ( and bad now. tree... | regex|python-3.x | 1 |
8,106 | 25,832,125 | A way to share modules between python 3.4 installation standard and anaconda py34 one | <p>I'd like to use either python 3.4 installation standard and Anaconda with python 3.4 in the same Computer. But when I make a standard installation of a new module or python installation (for example pip install Django) all is right in anaconda environment but it doesn't work in the python 3.4 standard environment. M... | <p>I have found a solution or better I learn a thing I did not know. For installing a module in the python 3.4 installation I should use per specif pip3.4.exe file which is in the directory scripts in the python 3.4 installation and not the "general" pip.exe file which install all the modules in the python 3.4 anaconda... | python|module|anaconda | 0 |
8,107 | 46,285,590 | pandas adding data from index table to dataframe | <p>I have a pandas <code>dataframe</code> <code>monthlyTempDiff</code> with contents as:</p>
<pre><code>monthlyAdder.ix[1:3]
City1 City2 City3
monthID
1 0.01 0.1 0.02
2 0.04 0.2 0.03
8 0.17 0.3 0.05
</code></pre>
<p>Colum... | <p>Let's try <code>set_index</code> and <code>add</code>:</p>
<pre><code>fwdTempTable.set_index('monthID', append=True).add(monthlyAdder, fill_value=0).reset_index('monthID')
</code></pre>
<p>Output:</p>
<pre><code> monthID City1 City2 City3 City4
DateTime
2017-1-0... | python|pandas|dataframe | 2 |
8,108 | 30,778,367 | how to setup filter in template | <p>I want to setup filter in templates </p>
<p>I have filtered objects that I wanted, and now how can I setup the template?</p>
<p>So I can filter objects through dropdown?</p>
<p>What I'have done so far</p>
<pre><code>@login_required
def list_jobs(request):
assigned_jobs = Job.objects.filter(assign_to=request.... | <p>Example Something like this: </p>
<pre><code><select id="id">
{% for i in assigned_jobs %}
<option value="{{ i.id }}">{{ i.name }}</option>
{% endfor %}
</select>
</code></pre> | python|django | 3 |
8,109 | 29,211,055 | Scrapy returns unicode - how to convert to a string? | <p>When I make a request to a url using scrapy shell, I get back something like this:</p>
<pre><code>In [6]: sel.xpath("//div[@class='my_class']").extract()
[u'<div class="my_class"><ul><li class="parent">\n<a href="/category/tractors-ride-on-mowers/">\n\u0422\u0420\u0410\u041a\u0422\u041e\u04... | <p>once you print it (or write it into a file) it will be readable</p>
<pre><code>>>> u = u'<div class="my_class"><ul><li class="parent">\n<a href="/category/tractors-ride-on-mowers/">\n\u0422\u0420\u0410\u041a\u0422\u041e\u0420\u042b \u0438 \u0420\u0410\u0419\u0414\u0415\u0420\u042b&l... | python|web-scraping|scrapy | 5 |
8,110 | 47,861,084 | how to store numpy arrays as tfrecord? | <p>I am trying to create a dataset in tfrecord format from numpy arrays. I am trying to store 2d and 3d coordinates.</p>
<p>2d coordinates are numpy array of shape (2,10) of type float64
3d coordinates are numpy array of shape (3,10) of type float64</p>
<p>this is my code:</p>
<pre><code>def _floats_feature(value):
... | <p>The function <code>_floats_feature</code> described in the <a href="https://www.tensorflow.org/tutorials/load_data/tfrecord" rel="noreferrer">Tensorflow-Guide</a> expects a scalar (either float32 or float64) as input.</p>
<pre><code>def _float_feature(value):
"""Returns a float_list from a float / double."""
re... | python|numpy|tensorflow|tfrecord | 30 |
8,111 | 32,970,854 | Django 1.6 format datetime in views | <p>I've a booking form in my template that sends an email when it's submitted. In my database the datetime field is shown like: <code>Oct. 6, 2015, 3:58 p.m.</code> But when I get the email the datetime field is shown like: <code>2015-10-06 15:58:50.954102</code> How do i format it such that in the email it's shown exa... | <p>You can format datestrings using <a href="https://docs.python.org/2/library/datetime.html#datetime.date.strftime" rel="nofollow"><code>strftime</code></a></p>
<pre><code>>>> from datetime import date
>>> dt = date(2015, 10, 6, 15, 58, 50)
>>> dt.strftime("%b. %-d %Y %-I:%M %p")
'Oct. 6 20... | python|django|datetime | 3 |
8,112 | 51,385,733 | How to change formatting of colorbar in combination with shrink | <p>I am creating a colorbar for my figure like this:</p>
<pre><code>def fmt(x, pos):
a='{:10.1f}'.format(x)
return a
fig.colorbar(CS, ax=ax,shrink=0.35,label=r'Electric Field/(V/$\mathrm{\AA}$)',format=ticker.FuncFormatter(fmt))
</code></pre>
<p>Creating the colorbar without the format command works just fin... | <p>You are shifting the labels away from the colorbar yourself. So if you don't want that don't do it.</p>
<p>I.e. Using <code>'{:10.1f}'.format(1)</code> you tell the formatter to use 10 places before the decimal separator. You may leave out the 10 to get it to only use as many places as it needs,</p>
<pre><code>'{:... | python|matplotlib | 0 |
8,113 | 69,869,350 | ATBS Regex Search Project-How to solve local scope error? | <p>this is my first time asking a question on StackOverflow. I've been working through the book ATBS with Python and I have a question about the Chapter 8 project "Regex Search". It asks you to create a program that opens all ".txt" files in a folder and searches for any line that matches a user-sup... | <p>I think you should try Result_text as a global variable instead of local variable.</p> | python-3.x | 0 |
8,114 | 69,773,459 | 'dict of list of dict' to dataframe | <p>I have a dict of list of dict</p>
<pre><code>{
'Col1Name': [{'date': '2020', 'value': '1111'},
{'date': '2019', 'value': '2222'},
{'date': '2018', 'value': '3333'}],
'Col2Name': [{'date': '2020', 'value': '777'},
{'date': '2018', 'value': '999'}]
}
</code></pre>
<p>How can I im... | <p>Here is a way using <code>pandas.concat</code> and a small comprehension:</p>
<pre><code>import pandas as pd
pd.concat({c: pd.DataFrame(l).set_index('date').T
for c,l in d.items()}).droplevel(1)
</code></pre>
<p>Output:</p>
<pre><code>date 2020 2019 2018
Col1Name 1111 2222 3333
Col2Name 777 ... | python|pandas | 1 |
8,115 | 73,087,585 | python lambda : maximum recursion depth exceeded in comparison | <p>I wrote the following code in Python:</p>
<pre><code>func = lambda x : x * 2
func = lambda x : func(x)
func(6)
</code></pre>
<p>When I ran the code above, I got</p>
<blockquote>
<p>RecursionError: maximum recursion depth exceeded in comparison</p>
</blockquote>
<p>I think the reason maybe : when it runs, it looks li... | <p>When you write <code>func = lambda x : func(x)</code>, you are redefining <code>func</code> to be that lambda, which just calls itself repeatedly until it bottoms out at the recursion limit. Consider a <code>def</code> version of the same:</p>
<pre class="lang-py prettyprint-override"><code>def i_call_myself_forever... | python|lambda-calculus | 3 |
8,116 | 55,671,260 | Python WebScraping using Soap + Request | <p>I'm trying to get the information of a link using soap in Python. I'm able to get the whole Array with the information, but I don't know how to manipulate the information the way I want. </p>
<p>For example: I want to show online Name(Nome) and Status.</p>
<hr>
<p>I've tried to get only the div, but it return "no... | <p>In this particular case, you don't need <code>BeautifulSoup</code> at all. You can directly get the <code>source.contents</code>, decode it and use <em><a href="https://docs.python.org/3.7/library/ast.html#ast.literal_eval" rel="nofollow noreferrer">ast.literal_eval</a></em> to get a list.</p>
<pre><code>import req... | python|beautifulsoup | 0 |
8,117 | 55,673,961 | Coloring bar chart by category of the values | <p>I need to color my bar plot by the values' category. Is that possible using Matplotlib?</p>
<p>Example:
Normally I use two list to create a bar chart:
values = [5, 2, 1, 7, 8, 12]
xticks = [John, Nina, Darren, Peter, Joe, Kendra]</p>
<p>Is it possible to add an extra category list, and color those bars based on th... | <p>If you want, you could structure your data as a dictionary, then it could be solved like this, where each entry as a property "gender" which is also the lookup key in the dictionar <code>color_map</code> : </p>
<pre><code>import matplotlib.pyplot as plt
fig,ax=plt.subplots(1,1)
data={
0:{"name":"John", "val... | python-3.x|matplotlib | 1 |
8,118 | 55,789,010 | NameError when calling a class method | <p>trying to understand classes and methods in Python 3.7. I keep running the code below, but keep getting this NameError, associated with the points variable I established in the initialize method of the Stats class. I believe the error is the result of some problem recognizing local/global variables, but can't put my... | <p>You need <code>self.</code> before referencing instance variables:</p>
<pre><code>class Stats:
def __init__(self, points, rebounds, assists, steals):
self.points = points
self.rebounds = rebounds
self.assists = assists
self.steals = steals
def tripDub(self):
if self.... | python|class|methods|attributes|nameerror | 4 |
8,119 | 63,994,088 | How to write pymongo query to get all the data based on date time Python | <p>I have more than 100 documents in <code>mongodb</code> which has below data:</p>
<pre><code>{
"Length": 2.9,
"Number": 33,
"Stop Time": "2020-09-20T11:05:58",
"Start Time": "2020-09-20T11:05:53"
}
</code></pre>
<p>I want a query to get all t... | <p>your date <code>2020-09-20T11:00:00</code> is of type string. You have to convert it to a datetime.</p>
<pre><code>datetime.datetime.strptime("2020-09-20T11:00:00", '%Y-%m-%dT%H:%M:%S')
</code></pre> | python|pymongo | 0 |
8,120 | 10,775,767 | storing for loop iteration data | <p>I am playing with cgi (uploading file form),</p>
<p>and I am receiving the files as storage object and I sotred it in (input) variable.</p>
<p>this is the simple iteration.</p>
<pre><code>for file in input:
filepath = ....
filename, fileext = os.path.splitext(filepath)
file_real_name = ....
file_size = ..... | <p>You want to use a data structure to hold your data. Depending on the complexity, you may want to simply use a list of dictionaries:</p>
<pre><code>files = []
for file in input:
files.append({
"path": get_path(file),
"name": get_name(file),
"size": get_size(file),
...
})
</cod... | python|storage|iteration | 1 |
8,121 | 5,321,219 | Query on Table View - Model/View programming | <p>I'm practicing some examples on model-view programming and have a query why the colors are not correctly represented.</p>
<p>The code is as follows:</p>
<p>I have created a Table View </p>
<pre><code>table_view = QTableView()
table_view.show()
table_view.setModel(model)
test_data = data(4,5)
model = paletteTable... | <p>I test your code and there is no problem but the colors is nearly the same on my display. I think you may meet the same problem, which seems all the color is red without any clear difference. I suggest to use another way to generate the color data ( return by "data" function ).<br>
I give my whole test code, you can... | python|pyqt|pyqt4|tableview | 1 |
8,122 | 62,863,272 | Pandas dataframe - duplicates in data but dups don't reside in same columns | <p>I have a df where there are duplicate rows in aggregate but in this form:</p>
<pre><code>timestamp animal_1 animal_2
2020-06-28 14:28:57 dog fox
2020-06-28 14:28:57 fox dog
2020-06-29 18:28:57 dog fox
2020-06-29 18:28:57 fox dog
2020-06-30 17:35:57 dog fox
2020-06-30 17:35:57 fox dog... | <p>First we need sort the column animals , the <code>drop_duplicates</code></p>
<pre><code>df[['animal_1', 'animal_2']]=np.sort(df[['animal_1', 'animal_2']].values, axis=1)
df=df.drop_duplicates()
</code></pre> | python|pandas|dataframe | 1 |
8,123 | 61,804,130 | How to make visualization sketches? What program or package in R or Pyhon is there? | <p>Some years ago this destiny plots were posted. Now i need to create similar sketches,
does anyone know how these were created? and what technology would be the best to make something similar? </p>
<p><img src="https://i.stack.imgur.com/XjCwm.jpg" alt="enter image description here"></p>
<p>This graph was originall... | <p>You can use <a href="https://ggplot2.tidyverse.org/reference/facet_grid.html" rel="nofollow noreferrer">ggplot facets</a> </p>
<pre><code>library("tidyverse")
data = iris %>% gather(key, value, -Species)
data %>%
ggplot(aes(x = value, color = Species)) +
geom_density() +
facet_wrap(key ~ .)
</code... | python|r|ggplot2|themes | 0 |
8,124 | 67,283,059 | searching and splitting a list | <p>I am trying to search through a list of hex values and split them out into separate lists when I see a '55'. The list of hex values looks like this</p>
<pre><code>['55', '00', '09', '07', '01', '56', 'd2', '40', '00', 'f0', '05', '91',
'73', '06', '00', '00', 'ff', 'ff', 'ff', 'ff', '44', '00', 'fd', '55',
'00', '... | <p>A cleaner way of solving the problem can be this</p>
<pre class="lang-py prettyprint-override"><code>def splitList(a):
combined = "|".join(a)
splitString = combined.split("55")
response = [f'55{splitPart.replace("|", "")}' for splitPart in splitString[1:]]
retu... | python|list|formatting | 1 |
8,125 | 60,509,013 | Weighted average of dataframes with mask on NaN's | <p>I have found some answers about averaging dataframes, but none that includes the treatment of weights. I have figured a way to get to the result I want (see title) but I wonder if there is a more direct way of achieving the same goal.</p>
<p>EDIT: I need to average more than just two dataframes, however the example... | <p>To make it a tidy one-line, I cheated a little with the imports, but here is the best I could do:</p>
<pre><code>import pandas as pd
import numpy as np
from numpy.ma import average as avg
from numpy.ma import masked_array as ma
df1 = pd.DataFrame([[np.nan, 2, np.nan, 0],
[3, 4, np.nan, 1],
... | python|pandas|numpy|dataframe | 1 |
8,126 | 60,390,153 | Is there a numpy/scipy function to calculate outbound penalty? | <p>In my minimization problem, all bounded minimize methods, such as 'L-BFGS-B', 'TNC' do not converge, but 'Nelder-Mead' converged very good. So I prefer to use 'Nelder-Mead', with modified minimize function, like this:</p>
<pre><code>def outbound_penalty(x, bounds):
o1 = (bounds[:, 0]-x).max()
o2 = (x-bounds... | <p>You can use broadcasting to perform the outbound elementwise function call in one go, and of course use <code>np.max()</code> instead of comparing <code>y</code> to <code>mx</code> in a for loop:</p>
<pre><code>import numpy as np
def outbound_penalty(x, bs):
o1 = (bs[:, 0] - x).max()
o2 = (x - bs[:, 1]).m... | python|numpy|scipy|minimize|scipy-optimize | 1 |
8,127 | 11,182,062 | Utf8 encoding with MySQLdb on non-utf symbols | <p>I am receiving an xml feed which has values such as:</p>
<pre><code><Theme>Valentine&#39;s Day</Theme>
<Copyright>&#169; Ventures. All Rights Reserved.</Copyright>
</code></pre>
<p>I need to parse the value and store it in a mysql database. What would be the best way to cleanse the ... | <p>If you parse the XML with a real xml parser, you'll get Unicode strings as text. You can then encode them with UTF-8:</p>
<pre><code>title = text.encode('utf8')
</code></pre>
<p>and title will be writable into your database, though many details are still unclear because we don't know how you're writing to your da... | python|mysql|unicode|encoding|utf-8 | 2 |
8,128 | 11,275,133 | What kind of authorization I should use for my facebook application | <p>I am building a social reader Facebook application using Django where I am using Google Data API (Blogger API). But I am unable to deal with the authorization step to use the Google API (currently using ClientLogin under development).</p>
<p>I tried to read the OAuth documentation but couldn't figure out how to pro... | <p>Django has some packages like <code>django-facebook</code> or <code>django-social-auth</code> which manage the authentication part of facebook login for you. You could either use these in your project, or look at the code there as a good starting point to learn about FB OAuth implementation.</p> | python|django|oauth|google-api|gdata-api | 1 |
8,129 | 11,089,420 | sqlalchemy change with executemany from version 0.5 to 0.7 | <p>I'm attempting to collect up a list of dictionaries, and do a bulk insert into a mysql db with sqlalchemy.</p>
<p>According to <a href="http://docs.sqlalchemy.org/en/rel_0_5/sqlexpression.html#executing-multiple-statements" rel="nofollow">these docs for version 0.5</a>, you do this with an <code>executemany</code> ... | <p>I think you're misreading the 0.5 link, the example you're pointing to still uses "execute()". SQLAlchemy has never exposed an explicit executemany() method. executemany() is specifically a function of the <em>underlying DBAPI</em>, which SQLAlchemy will make use of if the given parameter set is detected as a lis... | python|mysql|sqlalchemy|bulkinsert | 2 |
8,130 | 11,234,815 | python url mapping syntax | <p>I am writing a python program for google appengine using jinja2 as my template engine. I would like to have a single handler for a multitude of posts and some of them having pretty different URLs but all having the same base.</p>
<p>Is is possible for me to have a URL handler like this:</p>
<pre><code>app = webap... | <p>If you don't need (as parameters for the handler) the parts of the path that are after the /post/{param1} you can simple write <code>app = webapp2.WSGIApplication([('/post/(.*)/.*', PostPage)</code> and the handler will except everything in the form of /post/{id}/.*</p> | python|google-app-engine|jinja2|url-mapping | 3 |
8,131 | 11,028,325 | parsing XML file in python | <p>I have a XML file such as:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<result>
<data>
<_0>stream1</_0>
<_1>file</_1>
<_2>livestream1</_2>
</data>
</result>
</code></pre>
<p>I used</p>
<pre><code>xmlTag = dom.getElementsBy... | <p>I would suggest to use ElementTree. It's faster than the usual DOM implementations and I think its more elegant as well.</p>
<pre><code>from xml.etree import ElementTree
#assuming xml_string is your XML above
xml_etree = ElementTree.fromstring(xml_string)
data = xml_etree.find('data')
for elem in data:
print e... | python|xml-parsing | 2 |
8,132 | 70,687,620 | De-aggregate data in Pandas | <p>I'm trying to figure out how to work with pre-aggregated data in pandas/matplotlib.
I'm extracting my data from Kibana/ElasticSearch, so it's not raw data it's already been aggregated into buckets.</p>
<p>Some example data looks like this (actual data has many more categories and buckets that go up to 40).</p>
<pre>... | <p>You could group by Category and then calculate the statistics for each:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
for cat, df_cat in df.groupby('Category'):
print(f'\nCategory: {cat}')
print(np.repeat(df_cat['Bucket'], df_cat['Count'] / 10).describe())
</code... | python|pandas|numpy|matplotlib | 0 |
8,133 | 63,468,140 | how to remove space and special character from a list in python | <p><em>i have a list like</em>:</p>
<pre><code>
['BOOL_CONST_GROUP | |\n',
'BOOL_GROUP | ... | <p>You can use like this,</p>
<pre><code>a = ['BOOL_CONST_GROUP
| |\n',
'BOOL_GROUP
| ... | python|python-3.x | 1 |
8,134 | 63,734,822 | Search, and copy paste a text to corresponding file using pandas python | <p>Assuming I have a source file containing product price from local shops.</p>
<pre><code>$ less SourceFile.txt # see this file using less function in terminal.
Store Price Dollars
>shop1 >price1 $5
>shop2 >price2 $3
</code></pre>
<p>And, there are some marketing data called <code>sub files</code> for eac... | <p>An efficient way is create a dictionary from sourcefile. In dictionary <code>Id</code> columns is the key and rest of the columns are values.</p>
<pre><code>from pathlib import Path
with open('source_file.txt') as fp:
next(fp)
res = dict(line.strip().split(' ', 1) for line in fp)
for file in Path('files').... | python|python-3.x | 1 |
8,135 | 63,702,221 | Is there a way to serialize multiple objects in Django? | <p>In a Django Project I would like to implement a simple chat-box.</p>
<p><strong>Version</strong></p>
<p>Django version 3.0.8</p>
<p><strong>Models.py</strong></p>
<pre><code>class DirectMessageClass(models.Model):
sender = models.ForeignKey(User, on_delete=models.CASCADE,
related_name=... | <p>Use <em><strong>list up-packing</strong></em> technique</p>
<pre><code>def loadbox(request):
# rest of your code
return JsonResponse(
<b>[
*[message.serialize() for message in messages],
*[reply.serialize() for reply in replies]
]</b>,
safe=False
)</code></... | python|json|django | 2 |
8,136 | 55,643,265 | Class method does not run when called upon in Kivy | <p>I am new to kivy.
I have created a login page with 2 text fields. I am now trying to pass the variables to the next page, which will use a ssh client for python to connect to a server. However, when I run the program, it seems that the method I am calling in my second screen does not even run, as none of the debuggi... | <p>The <code>yield ssh</code> is preventing the <code>Connect.routine()</code> from executing. Try comment it off.</p> | python-3.x|kivy|kivy-language | 0 |
8,137 | 55,788,478 | Insert while loop values to tkinter magic window | <p>I have a code to create a "magic window" in python.
It should shows title, time and news.
I took news with function <code>newz</code> to loop (it should show the news on-by-on in Tkinter window)
I tried to insert it into tkinter <code>label</code> but it doesn't work(it just doesn't appear, but when I insert plain ... | <p>I don't know what you want to display but you have to use </p>
<pre><code> source.config(text="some text")
root.after(1000, newz)
</code></pre>
<p>inside function <code>newz</code></p>
<p>Something like this</p>
<pre><code>#--- newz - start ---
def newz():
url = 'https://news.google.com/rss?hl=ja&... | python|python-3.x|tkinter | 0 |
8,138 | 56,451,585 | JSONtoCSV with python (nested json) | <p>Trying to convert a nested json to csv</p>
<p>json data</p>
<pre><code>{"LOG_28MAY":[{"pk":"22","venue_name":"manchester","venue_code":"03839",
"fields":{"codename":"L01","name":"Can add log entry","content_type":"8","DAILY_LIST":["LOG_ID:12309","HOST_ID:1293123"]}},{"pk":"23","venue_name":"Birmingham","fields":{"... | <pre><code>import json
import csv
def get_leaves(item, key=None):
if isinstance(item, dict):
leaves = {}
for i in item.keys():
leaves.update(get_leaves(item[i], i))
return leaves
elif isinstance(item, list):
leaves = {}
for i in item:
leaves.updat... | python|json|csv | 1 |
8,139 | 56,773,378 | Finding time range of imputed time interval in Python | <p>I want to make a function that will take <code>start_time</code> and <code>end_time</code> and that will find the time interval where those times fit.
Time range must be at every 5 minutes, but imputed time interval can be any other time. </p>
<p>I have these intervals (I made them with a function below):</p>
<pre... | <p>try this:</p>
<pre class="lang-py prettyprint-override"><code>import datetime
import time
# creating time intervals at every 5 minutes
def create_intervals():
start_time = "00:00:00"
end_time = "0:59:59"
start = datetime.datetime.strptime(start_time, '%H:%M:%S')
end = datetime.datetime.strptime(e... | python | 2 |
8,140 | 61,026,839 | Unable to understand the syntax for iloc for reversing all rows vs reversing all columns | <p>I'm unable to bring my head around the syntax used for reversing all rows vs reversing all columns in Pandas.</p>
<pre><code>1. Reversing all rows : df.iloc[::-1]
2. Reversing all columns : df.iloc[:,::-1]
</code></pre>
<p>On a related note, what would be the way to reverse both rows and columns?</p> | <blockquote>
<p>On a related note, what would be the way to reverse both rows and columns?</p>
</blockquote>
<pre><code>df.iloc[::-1, ::-1]
</code></pre>
<p>I think for explain slicing is best check how working it in <a href="https://stackoverflow.com/questions/509211/understanding-slice-notation">lists</a>, here i... | python|pandas|dataframe | 2 |
8,141 | 66,029,274 | Draw specific letters and numbers in python | <p>I made a function to generate a combination of letters and random numbers in python:</p>
<pre><code>from random import choice, random, sample
def generateKeyId(self):
keyId = sample(ascii_uppercase,4)+sample(digits,4)+sample(ascii_uppercase,1)
return ''.join(keyId)
</code></pre>
<p>this is one of the exits ... | <p>You can do the following:</p>
<pre><code>from random import randint, choice
from string import ascii_uppercase
letters = ascii_uppercase[:10] # A-J
def generateKeyId():
return str(randint(1, 200)) + choice(letters)
>>> generateKeyId()
'33D'
>>> generateKeyId()
'115D'
>>> generateK... | python|random | 1 |
8,142 | 68,063,002 | should django modal have a separate view? | <p>I am working on an application that has a page with a table that is a list of users. Each user has a button which pops up a modal that does something. I am trying to create the modal that will get the user information when the button in clicked, additionally, I need in that modal some logic based on the user informa... | <p>You can try the following steps to solve the issue.</p>
<ol>
<li>Create a separate view for the modal on a separate url.</li>
<li>Take the modal data out of this html file and place it in another html file. The empty modal in the original html should look something like this.</li>
</ol>
<pre><code><div id="S... | python|django|django-views|django-templates|bootstrap-modal | 2 |
8,143 | 68,069,661 | Python 3, list of objects? New to python | <p>New to python and self-taught so I'm probably going about this horribly wrong but I'm trying to find the best way to list out objects while also placing them in a list. I was advised to find a way to do this by a friend to avoid double entry of creating my object then typing my object's name in. I'm open to any crit... | <p>The problem is you are naming your variables while appending them. If you are never going to access them by their name just do it like so:</p>
<pre><code>Starters = []
Starters.append(Digi("Botamon",0,1,1,1,1,[""]))
Starters.append(Digi("Poyomon",0,1,1,1,1,[""]))
Starters.appe... | python-3.x | 1 |
8,144 | 68,083,524 | y.append(sum(x)) modifies x array by adding sum of x array to x array and i don't know why | <p>So bascially I want to have one array(result) to which I add sum of the second array (array) but
when I try to add to result sum of array it adds to array what should be added to result</p>
<pre><code>def some_function(signature, n):
array = result = signature
count = 1
while count <= n:
... | <p><code>array = result = signature</code> doesn't copy anything. All three variables point to <em>one and the same list</em> because assignment doesn't copy.</p>
<p>Because they point the the same list, <code>result.append(sum(array))</code> is exactly the same as <code>array.append(sum(array))</code>, or <code>result... | python|arrays|sum|append|python-3.9 | -1 |
8,145 | 68,334,012 | Multiplication of Data Array Python | <p><strong>Hello guys</strong></p>
<p>I want to ask, for example, we have data:
data = [12,3,4,5,12,5,64,31,42]. After that, I want to multiply the data: times = [0,1,0,0,0,0,0]</p>
<p>What I want to ask is, there are 9 values multiplied by 7 values, so how do the scores continue? if it continues: [0,1,0,0,0,0,0,0,1]... | <p>You can use <code>cycle</code> from <code>itertools</code> if you want the values to be repeated, and do the multiplication using list comprehension:</p>
<pre class="lang-py prettyprint-override"><code>>>> from itertools import cycle
>>> [i*j for i,j in zip(data, cycle(times))]
#output: [0, 3, 0, ... | python|numpy | 0 |
8,146 | 68,317,913 | Python pandas: add index column based on existing columns, with duplicates sharing the same index | <p>I would like to add an index column based on existing columns. Duplicates would share the same index. For example,</p>
<p><a href="https://i.stack.imgur.com/BdOH5.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>If the values for the two columns ['old_index','year'] are the same, then the new i... | <pre><code>
df['new_id'] = df.groupby(df.columns.tolist(), sort=False).ngroup() + 1
df
index year id new_id
0 1 2000 5 1
1 2 1996 3 2
2 2 1996 3 2
3 4 1994 2 3
4 4 1999 4 4
5 4 1999 4 4
6 12 1989 1 5
7 12 1989 1 5
8 12 1985 0 6
9 12... | python|pandas|dataframe|data-science | 1 |
8,147 | 73,127,928 | Speed up Fuzzy Wuzzy by cutting number of comparisons | <p>I am currently using Fuzzy Wuzzy string similarity comparison and have code that is working, but am trying to cut down the run time since it takes long. Currently, the code I am using takes each username and compares it to every other username, and then goes to the next and does it again. I am trying to think of a w... | <p>I don't entirely understand the code above (what's process.extract? - I assume it is a function that compares the first argument to each element in the second argument), but I think you want something like this:</p>
<pre><code>mat1 = []
list1 = df4['usernames'].tolist()
for i, username in enumerate(list1):
... | python|optimization|fuzzywuzzy | 0 |
8,148 | 62,183,463 | Add a key with multiple values to nested JSON | <p>I have a JSON-variable like this:</p>
<pre><code>json_file = {
"Line 1": [
{"HFGR62"},
{"K6RTFV"},
{"86G37F"}
],
"Line 2": [
{"FG3RH5"},
{"45H4H4"},
{"H4HTH5"}
]
}
</code></pre>
<p>And a string that looks like this:</p>
<pre><code>string = "{Line 3} Bla bla bla <F3465> <G46... | <p><code>set()</code> isn't valid JSON type, use simple string instead:</p>
<pre><code>string = "{Line 3} Bla bla bla <F3465> <G46H6> bla bla bla <4H6HH> bla <4TH56> bla bla <G4H65>"
current_key = ''
for k, v in re.findall(r'{(.*?)}|<(.*?)>', string):
if k:
json_file[k]... | python|json|python-3.x|regex | 1 |
8,149 | 59,036,061 | How to fix TypeError while plotting using pyqtgraph | <p>I have a code to plot live data on a polar graph. I send two arrays to a function (real and imaginary values) where I update the data of the polar graph to make it live. It works but I constantly get this error message:</p>
<p><a href="https://i.stack.imgur.com/pc6jM.png" rel="nofollow noreferrer"><img src="https:/... | <p>I realised that if you update it really fast it gives this error. Slowing it down solved the problem</p> | python-3.x|pyqt5|pyqtgraph | 0 |
8,150 | 73,218,399 | df.rename does not alter df column names, but df.columns and df.set_axis do (Pandas) | <p>I have a pandas dataframe that I want to rename the columns on</p>
<p>When I run:</p>
<pre><code>df.rename(columns={0:"C", 1:"D"}, inplace=True)
</code></pre>
<p>No change happens, it's still the original column names.
But if I do:</p>
<pre><code>df.columns = ["C", "D"]
</code... | <p>If you don't want to rename by using the old name, you could <code>zip</code> the current columns and pass in the number of items you want.</p>
<p>If you're using Python 3.7+ then order should be <a href="https://stackoverflow.com/questions/15372949/preserve-ordering-when-consolidating-two-lists-into-a-dict">preserv... | python|pandas|dataframe | 2 |
8,151 | 31,457,937 | Is there a way to retrieve indices of particular values using Pycuda? | <p>I have a 3D numpy array of size 1000x1000x1000. I am looking for the indices of the values 1 in the entire array. The np.nonzero(array) is very slow for larger dataset as mine. I was wondering if there is a way to do it via pycuda. Or is there some other more efficient method. </p> | <p>I have not used PyCuda before, but since I found a <a href="http://wiki.tiker.net/PyCuda/Examples/ThrustInterop" rel="nofollow">good example on how to use thrust in PyCuda</a>, I came up with the following solution.</p>
<p>Internally, it uses <code>thrust::counting_iterator</code> and <code>thrust::copy_if</code> t... | python|numpy|cuda|pycuda | 1 |
8,152 | 15,906,443 | Write unique keys from 'list of dictionaries' to csv as headers & also write relevant values under each header using Python | <p>I have a list of dictionaries;</p>
<pre><code>information = [{'Edu':'School','Age':'40','Height':'5.11','DOB':'08091972','Name':'Jack'},
{'Edu':'College','Age':'30','Height':'4.11','DOB':'05041982','Name':'Alex','Pro':'Teacher'},
{'Name':'Elizabeth','Nickname':'Lizzy','DOB':'01012005'}]
</code></pre>
<p>I would ... | <p>You are almost there:</p>
<pre><code>...
dw.writeheader()
dw.writerows(information)
</code></pre> | python | 2 |
8,153 | 59,615,092 | Create category column based on data from another column | <p>I have a python dataframe df as:</p>
<pre><code> Pkg DateType
Date
2020-01-07 2.39 2020-01-07
2020-01-08 4.20 2020-01-09
2020-01-19 7.49 2020-02-01
2020-01-20 7.49 2020-03-01
</code></pre>
<p>I want the following:</p>
<pre><code> Pkg DateType DTCat
Date ... | <p>Just <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer">map</a> it:</p>
<pre><code>df['DTCat'] = df['DateType'].map({'2020-01-07': 'NDay', '2020-01-01': 'BM', '2020-02-01': 'NM', '2020-03-01': 'NP1M'})
</code></pre> | pandas|python-3.5 | 1 |
8,154 | 59,876,245 | visual studio issue syntax error with combining string to number | <p>currently having some issues with visual code that dont make sense.
tried printing out the following sentence in python:</p>
<pre><code> count = 0
message = f"We have {count} even numbers."
print(message)
</code></pre>
<p>With the following error:</p>
<pre><code>message = f"We have {count} even numbers."
... | <p>It's probably because you're using a version that is under 3.6, if so, use <code>%s</code> string formatting:</p>
<pre><code>count = 0
message = "We have %s even numbers." % count
print(message)
</code></pre>
<p>Or use <code>str.format</code>:</p>
<pre><code>count = 0
message = "We have {} even numbers.".format(c... | python|visual-studio | 0 |
8,155 | 49,243,360 | Angular python-shell fails on first line | <p><strong>Set Up</strong></p>
<p>I am having an odd problem.
I have a website and I am hoping to run a python script when someone presses a button. </p>
<p>So, I have followed this tutorial: <a href="https://www.npmjs.com/package/python-shell" rel="nofollow noreferrer">https://www.npmjs.com/package/python-shell</a><... | <p>require() does not exist in the browser/client-side JavaScript. You need <a href="http://requirejs.org/docs/1.0/docs/optimization.html#download" rel="nofollow noreferrer">require.js</a> to use require() in the browser. You must also add this to package.json:</p>
<pre><code>"require.js": "version"
</code></pre>
<p>... | python|angular|npm | 1 |
8,156 | 49,336,100 | List of list if statement for Python | <p>I have a list that looks like: </p>
<pre><code>[['a', 'b', 'null', 'c'], ['d', 'e', '5', 'f'], ['g' ,'h', 'null' ,'I'] ]
</code></pre>
<p>I want to uppercase all strings, but when I try:</p>
<pre><code>x = 0
for row in range(1, sheet.nrows):
listx.append(sheet.cell(row, x))
[x.upper() for x in x in listx]... | <p>This list comprehension does it, and retains your list of lists structure:</p>
<pre><code>listx = [['a', 'b', 'null', 'c'], ['d', 'e', '5', 'f'], ['g' ,'h', 'null' ,'I'] ]
[[x.upper() for x in sublist] for sublist in listx]
</code></pre>
<p>returns:</p>
<pre><code>[['A', 'B', 'NULL', 'C'], ['D', 'E', '5', 'F'], ... | python|list | 3 |
8,157 | 49,180,936 | How to one hot encode with pandas on a new dataset? | <p>I have a training data set that has categorical features on which I use <code>pd.get_dummies</code> to one hot encode. This produces a data set with n features. I then train a classification model on this data set with n features. If I now get some new data with the same categorical features and again perform one ho... | <p>For example , </p>
<p>You have tradf with column ['A_1','A_2']</p>
<p>With your new df you have column['A'] but only have one category 1 , you can do </p>
<pre><code>pd.get_dummies(df).reindex(columns=tradf.columns,fill_value=0)
</code></pre> | python|pandas | 2 |
8,158 | 25,195,011 | How come I can just "Import Image"? | <p>In python, I can type <code>import Image</code> to import the Python Imaging Library (PIL). I can just type that instead of <code>from PIL import Image</code>, like everyone else seems to do. How come I can do this? Is there any difference between <code>from PIL import Image</code> and <code>import Image</code>?</p>... | <p>Looks like when you "import Image" directly, what is really going on inside that Image module is: "from PIL.Image import *", which copies all of the names from the PIL.Image module into the Image module. </p>
<p>Take a look at the source:</p>
<pre><code>In [1]: import Image
In [2]: Image??
Type: module
Str... | python|python-imaging-library | 2 |
8,159 | 2,393,544 | Classname same as file/module name leads to inheritance issue | <p>My code worked fine when it was all in one file. Now, I'm splitting up classes into different modules. The modules have been given the same name as the classes. Perhaps this is a problem, because <code>MainPage</code> is failing when it is loaded. Does it think that I'm trying to inherit from a module? Can module/cl... | <p>Yes, module names share the same namespace as everything else, and, yes, Python thinks you are trying to inherit from a module.</p>
<p>Change:</p>
<pre><code>class MainPage(BaseHandler):
</code></pre>
<p>to:</p>
<pre><code>class MainPage(BaseHandler.BaseHandler):
</code></pre>
<p>and you should be good to go. ... | python|class|import|module | 18 |
8,160 | 67,677,345 | keras custom metrics for multi-label classification without all() | <p>I'm using sigmoid and binary_crossentropy for multi-label classification. A very similar question asked <a href="https://stackoverflow.com/questions/53037451/keras-custom-metrics-for-multi-label-classfication">here</a>. And the following custom metric was suggested:</p>
<pre><code>from keras import backend as K
def... | <p>Unless I'm mistaken the default binary_crossentropy metric/loss already does what you need. Taking your example</p>
<pre><code>import tensorflow as tf
from tensorflow import keras
y_true = tf.constant([[1, 0, 0, 1, 1]], dtype=tf.int32)
y_pred = tf.constant([[0.6, 0, 0, 1, 1]], dtype=tf.float32)
m = keras.metrics.b... | tensorflow|machine-learning|keras|deep-learning|multilabel-classification | 0 |
8,161 | 67,685,910 | How to split the background/facecolor in parts? | <p>I wanna have something similar to the following figures
<a href="https://i.stack.imgur.com/6mGrQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6mGrQ.png" alt="enter image description here" /></a></p>
<p>How to archive such split?
I tried to set the face color but i cannt there only set a margin ... | <p>To split the x-range into 4 equal parts, the <a href="https://matplotlib.org/stable/tutorials/advanced/transforms_tutorial.html" rel="nofollow noreferrer"><code>axes transform</code></a> can be used. As <code>axvspan</code> doesn't seem to take the transform into account, explicit rectangles can be created:</p>
<pr... | python|pandas|matplotlib | 1 |
8,162 | 66,898,509 | I am new to programming and I have faced a dilemma | <p>I have begun programming and I have faced a dilemma that do I need to learn everything about a particular language or do i need to learn the main concepts</p> | <p>It's impossible to learn literally everything about a programming language. Using python for example, there are so many packages, and new ones packages are being developed every week, nobody knows them all. It's more important to know the main concept. If you're using python for data science, for example, you'll nee... | python | 0 |
8,163 | 42,974,286 | Python: how to get hidden html contents from a HTML page | <p>i'm trying to make a program that can reissue the books i've taken from the library using robobrowser so,for that i was supposed to </p>
<p>1) login to my ID<br>
2) tick on the checkboxes of the respective books<br>
3) click on submit </p>
<p>after i did the login and printed the response of the page, it did ind... | <p>this question can be solved by adding script URL from the network tab by inspecting the element i.e.</p>
<p>1) Go to the network tab in inspect element tool.<br>
2) get the <code>url</code> of <code>js</code> or <code>css</code> which have <code>ok</code> responses and use the <code>browser.session.get(url_of_js_or... | javascript|jquery|html|python-3.x|robobrowser | 0 |
8,164 | 66,622,649 | AttributeError: module 'cv2' has no attribute 'VideoCapture' | <p>I had some problems with Opencv in Python.</p>
<p>This attribute problem also happens with <code>imread</code></p>
<p>I tried to uninstall and reinstall with contrib-Opencv,but it did not work.</p>
<p>About 2 months ago, my opencv file still worked well, but I don't know why it doesn't work now.</p>
<p>In the next r... | <p>One of the issue I noticed is that you used <strong>cv11</strong> as the main.py name.</p>
<p>It is very easy for PyCharm to get confused if you have a file saved as cv2.py. Please check if you have any other similar files with the name cv2.</p>
<p>Else, try to do this:</p>
<ol>
<li>remove OpenCV</li>
<li>reinstall ... | python|opencv | 3 |
8,165 | 72,139,845 | how to click button and download a file using robot frame work or selenium, it not contains link | <p><a href="https://www.nasdaq.com/market-activity/stocks/screener" rel="nofollow noreferrer">https://www.nasdaq.com/market-activity/stocks/screener</a> - i need to download csv file from this site,</p>
<p><strong>If solution in selenium or robot frame work both are fine. It is good to guide me with a reference code.</... | <p>This should work:</p>
<pre><code>driver.get("https://www.nasdaq.com/market-activity/stocks/screener")
try:
# Trying to click on 'Accept Cookies' if the footer banner appears
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='onetrust-accept-btn-handler']"))).c... | python|selenium|flask|robotframework | 1 |
8,166 | 72,372,265 | MyPy fails dataclass argument with optional list of objects type | <p>I'm having trouble getting MyPy to pass my script which contains a <code>dataclass</code> <code>Bar</code> with an optional argument <code>foos</code> that holds a list of <code>Foo</code> objects and defaults to an empty list.</p>
<p>Stranger still, adding a method <code>Bar.sum_foos()</code> which iterates through... | <p>Well, the code in your question is almost fine as-is. <code>Optional[X]</code> is equivalent to <code>X | None</code> - why do you make your list optional? This field is never None, factory means that <code>foos</code> attribute will be an empty list, if not passed to the constructor. Thus declaring as <code>list[Fo... | python|mypy|python-typing|python-dataclasses | 1 |
8,167 | 50,420,637 | speed up finite difference model | <p>I have a complex finite difference model which is written in python using the same general structure as the below example code. It has two for loops one for each iteration and then within each iteration a loop for each position along the x array. Currently the code takes two long to run (probably due to the for loop... | <p>For starters, this little change to the structure improves efficiency by roughly 15%. I would not be surprised if this code can be further optimized but that will most likely be algorithmic inside the function, i.e. some way to simplify the array element operation. Using a generator may likely help, too. </p>
<pr... | python|numpy|numerical-methods | 3 |
8,168 | 50,405,946 | pip doesn't upgrade in windows | <p>Even though there were some similar question but none of proposed solution applied to my case. Simply, after <code>tensorflow</code> installationattempting to install packages this message </p>
<pre><code>"You are using pip version 9.0.1, however version 10.0.1 is available. You
should consider upgrading via... | <p>I think it manybe PIP command before installing <code>TensorFlow</code> can be normal use, only after installation problems, probably because the new version of Python compatible with TensorFlow might be a little less, so update PIP and conda command, can fix. by command <code>conda install pip</code></p> | python|tensorflow|pip|python-3.6|miniconda | 2 |
8,169 | 50,604,298 | Numerical calculation of curvature | <p>I would like to calculate local curvature i.e at each point. I have a set of data points that a equally spaced in x. Below is the code for generating curvature.</p>
<pre><code>data=np.loadtxt('newsorted.txt') #data with uniform spacing
x=data[:,0]
y=data[:,1]
dx = np.gradient(data[:,0]) # first derivatives
dy = np... | <p>I've been playing a bit with your values and i've found that they aren't smooth enough to compute curvature. In fact, even the first derivative is flawed.
Here is why : <a href="https://i.stack.imgur.com/i7Yyq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i7Yyq.png" alt="Few plots of given data ... | python|numpy|derivative | 3 |
8,170 | 35,301,417 | copy all files and directory of the folder tar it and then send it destination for untar in python | <p>I need to copy all files and directory of folder with same permission after tarring it, send it to the target host (via sftp) then untar it to the same location.</p>
<p>I am new to python and just curious to do it via python script.</p> | <p>Have a look at the python standard modules! Tar and zip files are easy with python.
<a href="https://docs.python.org/2/library/tarfile.html" rel="nofollow">https://docs.python.org/2/library/tarfile.html</a></p> | python | 2 |
8,171 | 26,765,268 | anova_lm() python: on which model type does it work? | <p>I am new to Python and trying to transition to a unique platform, Python, from Matlab+R platforms.</p>
<p>I need to do a regression of my data. </p>
<p>After reading what is available online - unfortunately not as numerous as for R just yet - I realized that I need to play with the following options:</p>
<pre><co... | <p>I figured why it wasn't working on all models.</p>
<p><code>anova_lm()</code> wants the <code>fit()</code> attribute:</p>
<pre><code>table = sm.stats.anova_lm(modX.fit())
print table
</code></pre>
<p>however, it works only with mod2 and mod3, therefore it would not work with GLM models.</p>
<p>Here some info I f... | python|r|glm|anova | 0 |
8,172 | 26,664,102 | Why can I not create a wheel in python? | <p>Here are the commands I am running:</p>
<pre><code>$ python setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'
$ pip --version
pip 1.5.6 fr... | <p>Install the <a href="https://pypi.python.org/pypi/wheel"><code>wheel</code> package</a> first:</p>
<pre><code>pip install wheel
</code></pre>
<p>The documentation isn't overly clear on this, but <em>"the wheel project provides a bdist_wheel command for setuptools"</em> actually means <em>"the wheel <strong>package... | python|pip|setuptools|python-wheel | 309 |
8,173 | 56,867,142 | Why is Django ORM explain() function not giving expected output? | <p>I'm trying to understand how the <code>.explain()</code> function works in <strong>Django ORM</strong>.</p>
<p>The official documentation <a href="https://docs.djangoproject.com/en/2.1/ref/models/querysets/#explain" rel="nofollow noreferrer">here</a> says this.</p>
<pre><code>print(Blog.objects.filter(title='My Bl... | <p>If you're using MySQL, you can get the more readable result (i.e. including column headers for the <code>EXPLAIN</code> output) with some extra work: get the raw SQL for the query, then prefix that with <code>EXPLAIN</code> in a MySQL session.</p>
<p>E.g.</p>
<pre><code>>>> from django.contrib.admin.models ... | python|django|python-3.x|django-models|django-orm | 0 |
8,174 | 44,877,098 | How to extract feature vectors in a fine-tuned network in keras | <p>I am trying to extract feature vectors from an added Dense layer after fine tuning the Inception v3 CNN on keras with new data. Basically, I load the network structure and its weights, add two dense layers (my data is for a two class problem) and update weights from only some part of the network as the code below sh... | <p>I solved my own problem with this. Hope it fits well to you too.</p>
<p>First, the K.function to extract the features is this</p>
<pre><code>_convout1_f = K.function([model.layers[0].input, K.learning_phase()],[model.layers[312].output])
</code></pre>
<p>where 312 is the 312th layer I want to extract features</p>... | python|tensorflow|deep-learning|keras | 1 |
8,175 | 45,199,346 | Peculiar issue adding series to pandas dataframe | <p>I am facing a peculiar issue. I have 2 dataframes, x with 180k rows, y with 700 rows. I am creating another series z by looking up a column from x into y and getting a third column as series. But when I add this series to x, the values change completely. Given below are the two count distributions. Any idea why this... | <p>Check the len of z series. May be you have repeated keys in y or not have corresponding keys, so z may have not same size as x['colnew'].</p> | python|pandas | 0 |
8,176 | 61,239,393 | How to get return of InLineKeyboardButton with python-telegram-bot | <p>I am working with <code>python-telegram-bot</code> building a menu system.</p>
<p>I created a Django project, as shown below, using <strong>Webhook</strong> to connect to Telegram.</p>
<p>I have the button menu built, according to the codes below, but I'm not sure how to interact with the contact when he clicks th... | <p>Process the <code>json_telegram</code> you will get your own <code>callback_data</code>, which you sent, which will comeback like a boomerang</p>
<p>That is the basic principle for Bot programming</p>
<p>Documentation <a href="https://python-telegram-bot.readthedocs.io/en/latest/telegram.inlinekeyboardbutton.html... | python|django|telegram | 1 |
8,177 | 61,439,907 | why does escape character \b shows an unknown character? | <p>i have a simple line of code</p>
<pre><code> print("Hello \bWorld!")
</code></pre>
<p>and the output instead of <strong><em>HelloWorld!</em></strong> is</p>
<p><a href="https://i.stack.imgur.com/9pyLs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9pyLs.png" alt="enter image description here"... | <p>Your <em>console output</em> is incapeable of displaying the <code>'\b'</code>. This has nothing to do with python. </p>
<p>It works in Visual Studio: You can verify it by setting a breakpoint in your debugger and inspect the value (most IDEs have UTF-8 support) - the windows console f.e. has not.</p>
<p>Debugging... | python|python-3.x|utf-8|python-3.5|unicode-escapes | 1 |
8,178 | 58,041,109 | python loop over a list ( show the total 30 days with weekdays) | <pre><code>list = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
</code></pre>
<p>I want to show the total 30 days with weekdays, can somebody tell me how to do that in for or while loop ? Thanks</p>
<p>the output I want is :</p>
<pre><code>day 0 : Sun
day 1 : Mon
day 2 : Tue
day 3 : Wed
day 4 : Thu
day 5 : Fri
d... | <p>Your problem is that you are trying to print <code>weekdays[7]</code> when <code>weekdays</code> only has seven elements (i.e. <code>weekdays[0]</code> to <code>weekdays[6]</code>).</p>
<p>There are many ways to solve this problem, but in this case, the simplest is the best.</p>
<p>In your loop, use <code>weekdays... | python | 0 |
8,179 | 56,297,728 | Returning a list or tuple of arrays from pybind11 wrapping eigen | <p>I have a c++ function using eigen, which is wrapped using pybind11 so that I can call it from python. A simple version of the intended function returns an <code>Eigen::MatrixXd</code> type, which pybind successfully converts to a 2D numpy array. </p>
<p>I would like this function to be able to return either a list ... | <p>I have used Eigen before but I am not an expert, so others might be able to improve this solution.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <pybind11/pybind11.h>
#include <pybind11/eigen.h>
#include <pybind11/stl.h>
#include <Eigen/Dense>
std::vector<Eigen::MatrixXd&... | python|numpy|eigen|pybind11 | 4 |
8,180 | 56,096,670 | why i am getting field error in python django when ia going to develop project | <p>I am developing a blog project using python django framework where I am getting </p>
<blockquote>
<p>FieldError at /2019/05/10/india-movie-information-rulz/ Cannot resolve
keyword 'publish_year' into field. Choices are: author, author_id,
body, created, id, publish, slug, status,</p>
</blockquote> | <p>When We are filtering by sql functions, named <a href="https://docs.djangoproject.com/en/2.1/ref/models/querysets/#field-lookups" rel="nofollow noreferrer">field lookups</a> (In this example "year") we use two underscores.
So we do like <code>.filter(publish__year=sth)</code> and not <code>.filter(publish_year=sth)<... | python | 0 |
8,181 | 69,310,500 | Django redirect to detail page after authentication | <p>here is my code</p>
<pre><code>class UserProfileView(DetailView):
template_name = 'main/userprofile.html'
context_object_name = 'userprofile'
model = ProfilePersonal
# def dispatch(self, request, *args, **kwargs):
# if request.user.is_authenticated:
# pass
# else:
... | <p>I've solve it with</p>
<pre><code>return redirect(f'/accounts/login next=userprofile/{self.get_object().id}')
</code></pre> | python|django | 0 |
8,182 | 69,536,248 | Converting binary into categorical | <p>I have a dataframe in the form of</p>
<pre><code> black orange yellow green
1 0 1 0 1
2 0 0 0 1
3 1 0 0 0
</code></pre>
<p>I would like to create another column that would tell which colours are present, so the final output SHOULD b... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dot.html" rel="nofollow noreferrer"><code>DataFrame.dot</code></a> with the columns names and then remove last <code>5</code> values:</p>
<pre><code>df['colours'] = df.astype(bool).dot(df.columns.astype(str) + ' and ').str[:-5]
... | python|pandas | 3 |
8,183 | 55,421,386 | Tensorflow/Keras, How to convert tf.feature_column into input tensors? | <p>I have the following code to average embeddings for list of item-ids.
(Embedding is trained on review_meta_id_input, and used as look up for pirors_input and for getting average embedding)</p>
<pre><code> review_meta_id_input = tf.keras.layers.Input(shape=(1,), dtype='int32', name='review_meta_id')
priors_input = ... | <p>The behavior you desire could be achieved through following steps.</p>
<p>This works in TF 2.0.0-beta1, but may being changed or even simplified in further reseases.</p>
<p>Please check out issue in TensorFlow github repository <a href="https://github.com/tensorflow/tensorflow/issues/27416#issuecomment-502218673" ... | tensorflow|keras | 1 |
8,184 | 57,395,490 | Unable to iterate through all the alarms on cloudwatch using boto3 paginate | <p>I am trying to list all the alarms in AWS Cloudwatch. Currently I have around 200. However, when I try to list them I get maximum 100. I try paginating, but unable to go to next page or use next token. </p>
<p>Below is the code snippet</p>
<pre><code>response = client.describe_alarms(StateValue='OK', MaxRecords = ... | <p>When you call the <code>paginator.paginate()</code> method, you are passing <code>'MaxItems': 100</code>. That is going to limit the total number of items returned by your paginator to 100, regardless of how many <em>total</em> items there are. If you get rid of that argument, you'll get a paginator that will pagina... | python|amazon-web-services|boto3|amazon-cloudwatch | 1 |
8,185 | 57,561,851 | replace string with re in a file | <p>I want to quickly cancel out some unimportant strings in my file using the python module re.</p>
<p>I've tried it with other modules too, various loops and functions, but all I can get is to find the strings, not replace them with re.sub.</p>
<pre class="lang-py prettyprint-override"><code>import re
chat = open("... | <p><code>re.sub()</code> doesn't automatically replace data in a file - you need to write it to the file as well. <a href="https://stackoverflow.com/a/18935646/7431860">This answer</a> provides a great example; I've modified it slightly to match your code. Note that you're also missing a close-paren on your <code>chat ... | python|regex | 0 |
8,186 | 42,222,358 | pyqtgraph real time updating graph not showing | <p>I have tried the following code, that works in a single script file, I can see a chart being updated real time,</p>
<pre><code>from PyQt4 import QtGui, QtCore
import numpy as np
import pyqtgraph as pg
from pyqtgraph.ptime import time
app = QtGui.QApplication([])
pw = pg.plot()
timer = pg.QtCore.QTimer()
def upd... | <p>You only have to pass the parent to the timer. Change </p>
<pre><code>timer = pg.QtCore.QTimer()
</code></pre>
<p>to</p>
<pre><code>timer = pg.QtCore.QTimer(self)
</code></pre> | python|pyqt|pyqt4|pyqtgraph | 2 |
8,187 | 58,277,642 | Pytorch tracing - How do you trace a saved weight? | <p>I am trying to trace a saved weight I have so that I can load it with Catalyst. I checked the documentation on PyTorch, but I only found tracing on functions.</p> | <p>You can trace <code>torch.nn.Module</code> instances.</p>
<p>If you are not using data dependent flow control simply use <code>torch.jit.trace</code>, for example:</p>
<pre><code>torch.jit.trace(module, example_input)
</code></pre>
<p>If it does, use <code>torch.jit.script</code>:</p>
<pre><code>torch.jit.script... | python|machine-learning|pytorch | 0 |
8,188 | 45,461,954 | Use of label in sqlalchemy , database, ORM | <pre><code>q = session.query(
label('id1', func.least(Communication.initiator_id, Communication.receiver_id)),
label('id2', func.greatest(Communication.initiator_id, Communication.receiver_id)),
label('orga_id1', func.greatest(0, 1)),
label('orga_id2', func.greatest(0, 1)),
label('nb', func.count(Co... | <p>You cannot reference the output columns of the parent query in a subquery, though you could reference the parent's source tables:</p>
<pre><code>select 1 as one, (select one) as two;
</code></pre>
<p>will not work, but</p>
<pre><code>select 1 as one, (select s.i) as two from generate_series(2, 2) s(i);
</code></p... | python|database|python-3.x|postgresql|sqlalchemy | 4 |
8,189 | 45,685,429 | Errors in using fromtimestamp function in python | <p>I am trying to use fromtimestamp function in python to convert datetime data into seconds. But, the error happens in certain points.
one example is </p>
<p>1478422800 and 1478422740 in seconds date.</p>
<p>although 1478422800 is bigger than 1478422740 by 60 seconds,
1478422800 is converted to (2016, 11, 6, 1, 0), ... | <p>This is almost certainly some sort of correction related to <a href="https://www.timeanddate.com/time/change/usa/new-york?year=2016" rel="nofollow noreferrer">daylight saving time</a>, which occurred on November 6, 2016 in the U.S causing all clocks to go back 1 hour when the time reached 2 am. It is most likely app... | python-2.7|datetime | 0 |
8,190 | 28,727,631 | How to do zero down time schema migrations for large tables | <p>I'm looking for a solution that is compatible with django + mysql/postgres to do online migrations. The best solution I've seen is <a href="https://github.com/soundcloud/lhm" rel="nofollow">Large Hadron Migrator</a>, but LHM is a rails application and I would need to keep the ORMs in sync by hand, the second best to... | <p>If that's on option: <strong>Migrate your application to MySQL 5.6</strong> - migrations are way less painless since MySQL 5.6 supports online DDL just like PostgreSQL and it will release you from many headaches migrating big tables.</p>
<p>Here's a list of what is possible: <a href="http://dev.mysql.com/doc/refman... | python|mysql|django|migration|rds | 0 |
8,191 | 14,597,122 | Parsing large NTriples File Python | <p>I am trying to parse a rather large NTriples file using the code from <a href="https://stackoverflow.com/questions/3868888/parse-large-rdf-in-python">Parse large RDF in Python</a></p>
<p>I installed raptor and the redland-bindings for python.</p>
<pre><code>import RDF
parser=RDF.Parser(name="ntriples") #as name fo... | <p>It's slow because you are reading into an in-memory store (RDF.Model() default) which has no indexing. So it gets slower and slower. The parsing of N-Triples does stream from the file, it never sucks it all into memory.</p>
<p>See the <a href="http://librdf.org/docs/api/redland-storage-modules.html" rel="nofollow... | python|rdf|n-triples|redland | 2 |
8,192 | 25,859,733 | Why does this Python code work as it does? Please explain | <p>In the CS101 course at Udacity, the trainer demonstrates procedures in Python by writing the following code to print out the bigger number of the two parameters <em>n1</em> & <em>n2</em></p>
<pre><code>def bigger(n1,n2):
if n1 > n2:
return n1
return n2
</code></pre>
<p>So, for example, he does... | <p>It is not true that <code>return n2</code> will always execute. If n1 is greater than n2, the first <code>return n1</code> will execute. That returns from the function, and nothing else in the function is executed. A function can only return once.</p> | python|function|procedures | 4 |
8,193 | 44,817,583 | Issue with saving classifier as a pickle file in Python | <p>I tried saving my Multinomial Naive Bayes classifier as a <code>.pkl</code> file but encountered an error.</p>
<p>I tried </p>
<pre><code>import pickle
with open(r'C:\Users\User\Desktop\clf.pkl','rb') as f:
pickle.dump(mnb,f)
#mnb is the MultinomialNB classifier
</code></pre>
<p>I am getting the error as </... | <p>If you are trying to save it, then open it in <code>'wb'</code> write mode instead of <code>'rb'</code> read mode as following:</p>
<pre><code>with open(r'C:\Users\User\Desktop\clf.pkl','wb') as f:
pickle.dump(mnb,f)
</code></pre>
<blockquote>
<p>In write mode, it will automatically create a file if not pres... | python|python-3.x | 2 |
8,194 | 61,772,469 | return the position of the first occurrence of a value that can occur multiple times in the sorted list of values using Binary Search | <p>for example if list= [2,3,3,4,5,7,7,9,10],</p>
<p>i want to return index 1.</p>
<p><strong>In this case,there is no target parameter unlike the usual way we do binary search</strong></p>
<p>[<strong>Updated</strong>]</p>
<p>[This is the code that I have for now.It should return 1 since the first occurence of a m... | <p>Perform your binary search as usual; but when you arrive at the item you searched for, keep searching to the left.</p>
<p>I.e.:</p>
<ul>
<li>Set <code>min</code> to the first index, <code>max</code> to the last (plus one).</li>
<li>Look at the one in the middle (<code>(min+max)/2</code>).</li>
<li>If the value the... | python | 0 |
8,195 | 23,662,280 | How to log the contents of a ConfigParser? | <p>How can I print the contents of a Python 2.7 <code>ConfigParser</code> to <code>logging</code>? </p>
<p>The only solution I can find is to write to a temporary file and read that file back in. Another idea I had was to get a fake "file handle" from the logging utility and pass that to the ConfigParser write method,... | <p>As this is the top Google search result and I was hoping to find a solution to print the values of the <code>ConfigParser</code> instance to stdout, here's a one-liner to help all future readers:</p>
<pre class="lang-py prettyprint-override"><code>print({section: dict(config[section]) for section in config.sections(... | python|python-2.7|logging | 39 |
8,196 | 24,259,968 | If function for annotating from pandas | <p>I'm scatter plotting values from pandas dataframe. I would like to annotate points only if the value is greater than 100. I have no idea how to go about it.</p>
<p>Here's the code I'm working with (it's terrible but I'm very new to this):</p>
<pre><code>female_data = r'/home/jg/Desktop/hurricanedata_f.csv'
female_... | <p>You can loop over all your data points and check if each is greater than 100. Then give those points an annotation. </p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import string
# Fake data
x = np.arange(10)
y = 10*np.random.rand(10) + 95
names = string.lowercase[:10] # first 10 lowercase letter... | python|matplotlib|pandas | 0 |
8,197 | 20,605,354 | create mask of non-nan matrix intersections | <p>I have two (or more) numpy arrays, in which I need to perform a calulcation on <em>each</em> cell where all matching cell positions have non-null values.</p>
<pre><code>import numpy
arr_a = numpy.zeros(shape=(5,6))
arr_a.fill(numpy.nan)
arr_b = numpy.zeros(shape=(5,6))
arr_b.fill(numpy.nan)
arr_a[1,1] = 12.9
arr_... | <p>To test for Not Not-A-Number (not NAN):</p>
<pre><code>from numpy import isnan
result = ~isnan(arr_a) * ~isnan(arr_b)
</code></pre>
<p>Alternatively, if you want to rule out both NANs and infinities, then run:</p>
<pre><code>from numpy import isfinite
isfinite(arr_a) * isfinite(arr_b)
</code></pre>
<p>On your te... | python|numpy | 5 |
8,198 | 72,117,875 | Guess the number in 5 chance using if else in python | <p>I'm working on a simple assignment, where I need to guess the number in five tries without utilizing a while loop. I've written the following code, however, I'm not sure how to continue the loop in this code; any suggestions would be greatly appreciated.</p>
<pre><code>number=9
guess_taken=0
if guess_taken < 5:
... | <p>You can use a recursive function until your condition is met.</p>
<pre><code>number=9
guess_taken=0
def guess(guess_taken):
if guess_taken < 5:
number_input = int(input('please guess: '))
if number_input==number:
print('correct guess: '+ str(number_input))
elif number_inpu... | python | 1 |
8,199 | 29,778,153 | Serve file to browser from python (flask) webservice | <p>I have a python webservice that is suppose to receive a GET request from the browser, writes some data into a csv file and serves it back to the browser.</p>
<p>I am struggling with this last step. How can I serve the file back to the browser? Is there a way to do it without creating or keeping the csv file on the ... | <p>Instead of writing the file to disk, you can just return it like this:</p>
<pre><code>from flask import make_response
outdata = ""
for data in alldata:
outdata += ",".join(data) + "\n"
response = make_response(outdata)
response.headers["Content-Disposition"] = "attachment; filename=data.csv"
return response... | python|web-services|io|flask | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.