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 |
|---|---|---|---|---|---|---|
0 | 20,581,479 | Can python or JS hide video embedded source? | <p>I'm doing a video website right now and I would like to hide the embedded source of the video from being seen by beginner programmer. (I know they are no 100% way to hide the video embeded source).</p>
<p>Any experience programmer knows how python or JS can help to do this? or it can't?</p> | <p>For Javascript, hiding code (almost) cannot be done!</p>
<p>However, if your code is sensetive in any manner, try using obfuscators so that the code will not be readable by human eye.</p>
<p>Here are few obfuscation services:</p>
<ol>
<li><p>Free Javascript Obfuscator: <a href="http://javascriptobfuscator.com/" r... | javascript|jquery|python|video|video-streaming | 3 |
1 | 71,894,592 | How to concatenate database elements to a string | <p>I'm currently trying to take elements from a database to be displayed in a string by iterating through each row and adding it to an empty string.</p>
<pre><code> def PrintOverdueBooks():
printed_message = ""
for row in db_actions.GetAllOverdue():
printed_message += row
... | <p>You can try this:</p>
<pre><code>def PrintOverdueBooks():
printed_message = ''
for row in db_actions.GetAllOverdue():
stup = ''.join(row)
printed_message += stup
print(printed_message)
</code></pre> | python|database|concatenation | 0 |
2 | 36,150,410 | 'DataFrame' object has no attribute 'value_counts' | <p>My dataset is a DataFrame of dimension (840,84). When I write the code:
<code>ds[ds.columns[1]].value_counts()</code><br>
I get a correct output:</p>
<pre><code>Out[82]:
0 847
1 5
Name: o_East, dtype: int64
</code></pre>
<p>But when I write a loop to store values, I get <em>'DataFrame' object has no attrib... | <p>Thanks to @EdChum adviced, I checked :</p>
<pre><code>len(ds_wdire.columns),len(ds_wdire.columns.unique())
Out[100]: (83,84)
</code></pre>
<p>Actually, there was a missing name value in the dict that should have been modified from 'WNW' to 'o_WNW'.:</p>
<pre><code>o_wdire.rename(columns={'ENE': 'o_ENE','ESE': 'o_... | python|python-2.7|pandas|dataframe | 1 |
3 | 46,529,659 | How to find ellipses in text string Python? | <p>Fairly new to Python (And Stack Overflow!) here. I have a data set with subject line data (text strings) that I am working on building a bag of words model with. I'm creating new variables that flags a 0 or 1 for various possible scenarios, but I'm stuck trying to identify where there is an ellipsis ("...") in the ... | <p>Using <code>search()</code> instead of <code>match()</code> would spot an ellipses at any point in the text. If you need <code>0</code> or <code>1</code> to be returned, convert to bool and then int.</p>
<pre><code>import re
for test in ["hello..", "again... this", "is......a test", "...def"]:
print int(bool(... | python|regex | 2 |
4 | 60,791,304 | google.cloud namespace import error in __init__.py | <p>I have read through at least a dozen different stackoverflow questions that all present the same basic problem and have the same basic answer: either the module isn't installed correctly or the OP is doing the import wrong.</p>
<p>In this case, I am trying to do <code>from google.cloud import secretmanager_v1beta1<... | <p>It have to be installed via terminal: <code>pip install google-cloud-secret-manager</code>
Because package name is not secretmanager but google-cloud-secret-manager</p> | python-3.x|google-cloud-platform|python-import|google-secret-manager | 8 |
5 | 49,532,854 | Python - Multiple 'split' Error | <p>I posted here 4-5 days ago, about one problem to sort some numbers from file.
Now, is the same of the other problem but, I want to sort numbers from one file (x) to another file (y). For example: In x i have: (5,6,3,11,7), and I want to sort this numbers to y (3,5,6,7,11). But I have some errors and can't resolve on... | <p>There are too many problems with your code for me to address. Try this:</p>
<pre><code>from sys import argv
with open(argv[1], "r") as infile:
with open("nums_ordenats.txt", "w") as outfile:
for line in infile:
nums = [int(n) for n in line.split(',')]
nums.sort()
out... | python|python-3.x|list|sorting|tuples | 0 |
6 | 62,587,462 | PyQT - QlistWidget with infinite scroll | <p>I have a QlistWidget and I need to implement on this an Infinite Scroll, something like this HTML example:</p>
<p><a href="https://scrollmagic.io/examples/advanced/infinite_scrolling.html" rel="nofollow noreferrer">https://scrollmagic.io/examples/advanced/infinite_scrolling.html</a></p>
<p>Basically, when the user s... | <p>There are likely many ways to achieve this task, but the easiest I found is to watch for changes in the scroll bar, and detect if we're at the bottom before adding more items to the list widget.</p>
<pre><code>import sys, random
from PyQt5.QtWidgets import QApplication, QListWidget
class infinite_scroll_area(QListW... | python|pyqt|pyqt5|qlistwidget | 1 |
7 | 53,736,868 | How to correctly import custom widgets in kivy | <p>I have a widget(W2), made of other widgets (W1). Each has a corresponding .kv file as below. Running main.py, I expect to see a black background with two labels, vertically stacked. Instead, I get both labels on top of each other, so something has gone wrong.</p>
<pre><code>kivy.factory.FactoryException: Unknown cl... | <p>why are you using two different kv files for this?
I would say the proper way would be similar to what i have with my kv file. because you are spliting up things that can be done on a single page and if you need different pages you use the <code>ScreenManager</code> import stuff</p>
<p><strong>main.py</strong>:</p>
... | python-3.x|kivy|kivy-language | 0 |
8 | 53,456,874 | ImportError: cannot import name 'convert_kernel' | <p>When i try to use tensorflow to train model, i get this error message. </p>
<p>File "/Users/ABC/anaconda3/lib/python3.6/site-packages/keras/utils/layer_utils.py", line 7, in
from .conv_utils import convert_kernel</p>
<p>ImportError: cannot import name 'convert_kernel'</p>
<p>i have already install Keras</p> | <p>I got the same issue. The filename of my python code was "tensorflow.py". After I changed the name to "test.py". The issue was resolved.</p>
<p>I guess there is already a "tensorflow.py" in the tensorflow package. If anyone uses the same name, it may lead to the conflict.</p>
<p>If your python code is also called ... | python|tensorflow | 1 |
9 | 53,467,807 | Python function that identifies if the numbers in a list or array are closer to 0 or 1 | <p>I have a <code>numpy</code> array of numbers. Below is an example:</p>
<pre><code>[[-2.10044520e-04 1.72314372e-04 1.77235336e-04 -1.06613465e-04
6.76617611e-07 2.71623057e-03 -3.32789944e-05 1.44899758e-05
5.79249863e-05 4.06502549e-04 -1.35823707e-05 -4.13955189e-04
5.29862793e-05 -1.98286005e-04 -2.22829175... | <p>A straightforward way:</p>
<pre><code>lst=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
closerTo1 = [x >= 0.5 for x in lst]
</code></pre>
<p>Or you can use np:</p>
<pre><code>import numpy as np
lst=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
arr = np.array(lst)
closerTo1 = arr >= 0.5
</code></pre>
<p>Note that <code>&... | python|arrays|list|function|numpy | 22 |
10 | 53,424,798 | Python pandas: map and return Nan | <p>I have two data frame, the first one is:</p>
<pre><code>id code
1 2
2 3
3 3
4 1
</code></pre>
<p>and the second one is:</p>
<pre><code>id code name
1 1 Mary
2 2 Ben
3 3 John
</code></pre>
<p>I would like to map the data frame 1 so that it looks like:</p>
<pre><code>id code name
1 2 ... | <p>Problem is different type of values in column <code>code</code> so necessary converting to integers or strings by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="noreferrer"><code>astype</code></a> for same types in both:</p>
<pre><code>print (df1['code'].dtype)
object... | python|pandas|dataframe | 6 |
11 | 54,843,657 | How to select a specific range of cells in an Excel worksheet with Python library tools | <p>I would like to select a specific range of cells in a workbook worksheet. I am currently able to set a variable to a workbook worksheet with the line below.</p>
<pre><code> import pandas as pd
sheet1 = pd.read_excel('workbookname1.xlsx', sheet_name = ['sheet1'])
</code></pre>
<p>I would like to go one step furth... | <p>You can utilize <code>OpenPyXl</code> module.</p>
<pre><code>from openpyxl import Workbook, load_workbook
wb = load_workbook("workbookname1.xlsx")
ws = wb.active
cell_range = ws['A1':'C2']
</code></pre>
<p>You can also use <code>iter_rows()</code> or <code>iter_columns()</code> methods.</p>
<p>For additional inf... | python|pandas|series | 2 |
12 | 33,204,160 | Listing all class members with Python `inspect` module | <p>What is the "optimal" way to list all class methods of a given class using <code>inspect</code>? It works if I use the <code>inspect.isfunction</code> as predicate in <code>getmembers</code> like so</p>
<pre><code>class MyClass(object):
def __init(self, a=1):
pass
def somemethod(self, b=1):
... | <p>As described in the documentation, <a href="https://docs.python.org/3/library/inspect.html#inspect.ismethod" rel="noreferrer"><code>inspect.ismethod</code></a> will show bound methods. This means you have to create an instance of the class if you want to inspect its methods. Since you are trying to inspect methods o... | python|class|inspect | 10 |
13 | 33,425,495 | Groupby in pandas multiplication | <p>I have a data frame called <code>bf</code>. The commas are mine, it was imported from a csv file.</p>
<pre><code>val,ben
a,123
b,234
c,123
</code></pre>
<p>I have another larger data frame <code>df</code></p>
<pre><code> bla,val, blablab, blablaa
1,a,123,333
2,b,333,222
3,c,12,33
1,a,123,333
... | <p>Probably you want to use a merge to bring in the column <code>ben</code> into your dataframe:</p>
<pre><code>df_merged = pd.merge(df, bf, on='val')
</code></pre>
<p>Then you can calculate your product however you like, for example:</p>
<pre><code>df_prod = df_merged * df_merged.ben
</code></pre> | python|pandas|group-by | 1 |
14 | 13,055,309 | Why doesn't this python function with a dictionary named parameter and a default value apply the default value each time it's called? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument">“Least Astonishment” in Python: The Mutable Default Argument</a> </p>
</blockquote>
<p>The following code illustrates the issue:</p>
<pre><cod... | <p>The default value of <code>named_param</code> is evaluated once, when the function definition is executed. It is the same dictionary each time and its value is retained between calls to the function.</p>
<p>Do not use mutable objects as default values in functions unless you do not mutate them. Instead, use <code>N... | python | 1 |
15 | 12,921,260 | Importing a class to another class in python | <p>I am trying to learn python i tried to import a class in another class but it is not working</p>
<p><code>Application.py</code>:</p>
<pre><code>class Application:
def example(self):
return "i am from Application class"
</code></pre>
<p><code>Main.py</code></p>
<pre><code>class Main:
def main():... | <p>You should instantiate your Main class first. </p>
<pre><code>if __name__ == '__main__':
myMain = Main()
myMain.main()
</code></pre>
<p>But this will give you another error:</p>
<blockquote>
<p>TypeError: main() takes no arguments (1 given)</p>
</blockquote>
<p>There are two ways to fix this. Either ma... | python | 0 |
16 | 21,924,444 | Jinja2 extensions - get the value of variable passed to extension | <p>So I have a Jinja2 extension. Basically follows the parser logic, except that I need to get a value from the parsed args being passed in.</p>
<p>For instance, if I have an extension called loadfile, and pass it a variable:</p>
<p><code>{% loadfile "file.txt" %}</code></p>
<p>when I grab the argument through <code... | <p>This works for me</p>
<pre><code>def parse(self, parser):
lineno = parser.stream.next().lineno
# args will contains filename
args = [parser.parse_expression()]
return nodes.Output([
nodes.MarkSafeIfAutoescape(self.call_method('handle', args))
]).set_lineno(lineno)
def handle(self, fil... | python|jinja2 | 1 |
17 | 24,472,957 | Get relative links from html page | <p>I want to extract only relative urls from html page; somebody has suggest this :</p>
<pre><code>find_re = re.compile(r'\bhref\s*=\s*("[^"]*"|\'[^\']*\'|[^"\'<>=\s]+)', re.IGNORECASE)
</code></pre>
<p>but it return :</p>
<p>1/all absolute and relative urls from the page.</p>
<p>2/the url may be quated by <... | <p>Use <a href="https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags">the tool for the job</a>: an <code>HTML parser</code>, like <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow noreferrer"><code>BeautifulSoup</code></a>.</p>
<p>You can <a hre... | python|html|regex|html-parsing | 4 |
18 | 24,665,403 | replace information in Json string based on a condition | <p>I have a very large json file with several nested keys. From whaat I've read so far, if you do:</p>
<pre><code>x = json.loads(data)
</code></pre>
<p>Python will interpret it as a dictionary (correct me if I'm wrong). The fourth level of nesting in the json file contains several elements named by an ID number and a... | <p>First of all, your JSON is invalid. I assume you want this:</p>
<pre><code>{"level1":
{"level2":
{"level3":
{
"ID1":{"children": [1,2,3,4,5]},
"ID2":{"children": []},
"ID3":{"children": [6,7,8,9,10]}
}
}
}
}
</code></pre>
<p>Now, l... | python|json|python-3.x | 1 |
19 | 38,326,387 | How to get percentiles on groupby column in python? | <p>I have a dataframe as below:</p>
<pre><code>df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
'office_id': list(range(1, 7)) * 2,
'sales': [np.random.randint(100000, 999999) for _ in range(12)]})
</code></pre>
<p>To get percentiles of sales,state wise,I have written below code... | <p>How about this?</p>
<pre><code>quants = np.arange(.1,1,.1)
pd.concat([df.groupby('state')['sales'].quantile(x) for x in quants],axis=1,keys=[str(x) for x in quants])
</code></pre> | python|pandas | 1 |
20 | 38,490,748 | Isolating subquery from its parent | <p>I have a <code>column_property</code> on my model that is a count of the relationships on a secondary model.</p>
<pre><code>membership_total = column_property(
select([func.count(MembershipModel.id)]).where(
MembershipModel.account_id == id).correlate_except(None))
</code></pre>
<p>This works f... | <p>Pass <code>MembershipModel</code> to <code>correlate_except()</code> instead of <code>None</code>, as described <a href="http://docs.sqlalchemy.org/en/latest/orm/mapped_sql_expr.html#using-column-property" rel="nofollow">here</a> in the documentation. Your current method allows omitting everything from the subquery'... | python|sqlalchemy | 2 |
21 | 31,154,238 | Clustering latitude longitude points in Python with fixed number of clusters | <p>kmeans does not work properly for geospatial coordinates - even when changing the distance function to haversine as stated <a href="https://datascience.stackexchange.com/a/848/10436">here</a>.</p>
<p>I had a look at <a href="http://scikit-learn.org/stable/auto_examples/cluster/plot_dbscan.html" rel="nofollow norefe... | <p>Using just lat and longitude leads to problems when your geo data spans a large area. Especially since the distance between longitudes is less near the poles. To account for this it is good practice to first convert lon and lat to cartesian coordinates.</p>
<p>If your geo data spans the united states for example ... | python|gis|geospatial|latitude-longitude|k-means | 4 |
22 | 39,930,022 | How to make exceptions during the iteration of a for loop in python | <p>Sorry in advance for the certainly simple answer to this but I can't seem to figure out how to nest an <code>if ______ in ____:</code> block into an existing <code>for</code> block.</p>
<p>For example, how would I change this block to iterate through each instance of <code>i</code>, omitting odd numbers. </p>
<pre... | <p>This has nothing to do with nesting. You are comparing apples to pears, or in this case, trying to find an <code>int</code> in a list of <code>str</code> objects.</p>
<p>So the <code>if</code> test never matches, because there is no <code>1</code> in the list <code>['1', '3', '5', '7', '9']</code>; there is no <cod... | python|python-3.x|if-statement|for-loop|nested | 4 |
23 | 8,482,007 | Python 2.6.2: writing lines to file hard wrap at 192 characters | <p>I implemented a function to make a wrapper to write to files. This is the code:</p>
<pre><code>def writeStringToFile(thestring, thefile, mode='w'):
"""Write a string to filename `thefile' to the directory specified in `dir_out'."""
with open(os.path.join(dir_out, thefile), mode) as fh:
fh.write("{0... | <p>My own stupidity -- I was writing strings that had the character sequence <code>\n</code> in them, and python was rightly interpreting them as newlines. I need to escape them in my string. I'd take this post down if it hadn't already been responded to.</p> | python | 1 |
24 | 59,013,654 | list of indices in 3D array | <p>I have an array that looks like this:</p>
<pre><code> [[[ -1., 1., -1., 1., -1., 1., 1., 1., 1., -1., 1., 1., 1., 1.]],
[[ 1., 0., 1., 0., 1., 0., 1., 0., 1., 0., 1., 0., 1., 0.]],
[[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]]
</code></pre>
<p>I have a list of... | <p><strong>Solution 1:</strong></p>
<p><strong>The most pythonic way (my way to go).</strong></p>
<pre><code>c = [a[i] for i,j in enumerate(b) if a[i][0][j] == 1]
print(c)
[[[1, 1, 1]], [[1, 0, 1]], [[1, 0, 0]]]
</code></pre>
<hr>
<p><strong>Solution 2:</strong></p>
<pre><code>a = [[[0,1,0]], [[0,0,0]], [[1,1,1]]... | python|numpy|numpy-ndarray | 1 |
25 | 51,953,821 | Close cmd while Tk object remains | <p>So I made a simple calculator in Python 3.7 and made a batch file to get it to run from the CMD. The thing is, after I run the batch file, I get a CMD window and then the Tk window, but the CMD window remains there and shuts my program down if I close it.
Is there a way to hide the CMD window or just omit its appera... | <p>You can use the <code>pythonw</code> executable, or rename your script to something<code>.pyw</code>.</p>
<p><code>.pyw</code> is a special extension for Python files on Windows which are associated with <code>pythonw</code>, the Python interpreter that does not pop up the console window at all.</p> | python|tkinter|cmd|visible | 4 |
26 | 62,205,131 | PyQt app won't run properly unless I open the whole folder | <p>So I'm trying to share my PyQt project. When I download the zip file and extract it, it looks like</p>
<p><a href="https://i.stack.imgur.com/ApGY4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ApGY4.png" alt="enter image description here"></a></p>
<p>If I run <code>app.py</code> from CMD, it w... | <p>Eventually, I ended up changing how I'm using the paths.</p>
<p>I added this</p>
<pre class="lang-py prettyprint-override"><code>dirname = os.path.dirname(__file__)
iconFile = os.path.join(dirname, 'icon/icon.png')
</code></pre>
<p>So now I'm using <code>iconFile</code> as my path. Seems to fix the issue</p> | python | 2 |
27 | 63,529,436 | Cannot connect VPS Server to MS SQL Server | <p>I'm trying to connect to MS SQL database using my VPS server IP, and login info. But I kept getting login failed error</p>
<blockquote>
<p>pyodbc.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'root'. (18456) (SQLDriverConnect); [28000] [Microsoft]... | <p>When you use IP address to connect to your server, you have to set SQL-Server port even it was default. like this:</p>
<pre><code>server = '66.42.92.32,1433'
</code></pre>
<p>for more information look at this Microsoft link:
<a href="https://docs.microsoft.com/en-us/sql/connect/python/pyodbc/step-3-proof-of-concept-... | python|sql-server|ubuntu|vps | -1 |
28 | 36,676,594 | Spark Sql: TypeError("StructType can not accept object in type %s" % type(obj)) | <p>I am currently pulling data from SQL Server using PyODBC and trying to insert into a table in Hive in a Near Real Time (NRT) manner. </p>
<p>I got a single row from source and converted into List[Strings] and creating schema programatically but while creating a DataFrame, Spark is throwing StructType error.</p>
<p... | <p>here is the reason for error message:</p>
<pre><code>>>> rowstr
['1127', '', '8196660', '', '', '0', '', '', 'None' ... ]
#rowstr is a list of str
>>> myrdd = sc.parallelize(rowstr)
#myrdd is a rdd of str
>>> schema = StructType(fields)
#schema is StructType([StringType, StringType, ... | python|apache-spark|apache-spark-sql | 27 |
29 | 36,393,643 | Encoder for a string - Python | <p>I've been playing around with encoding random sets of strings using a dictionary. I've gotten my code to replace the letters I want, but in some cases it will replace a character more than once, when I truly only want it to replace the letter in the string once. This is what I have:</p>
<pre><code>def encode(msg,co... | <p>Python 3's <a href="https://docs.python.org/3.3/library/stdtypes.html?highlight=translate#str.translate" rel="nofollow"><code>str.translate</code></a> function does what you want. Note that the translation dictionary must use Unicode ordinals for keys, so the function uses a dictionary comprehension to convert it t... | python|string|loops|dictionary|encoding | 2 |
30 | 13,593,514 | assigning values in a numpy array | <p>I have a numpy array of zeros. For concreteness, suppose it's 2x3x4:</p>
<pre><code>x = np.zeros((2,3,4))
</code></pre>
<p>and suppose I have a 2x3 array of random integers from 0 to 3 (the index of the 3rd dimension of x).</p>
<pre><code>>>> y = sp.stats.distributions.randint.rvs(0, 4, size=(2,3))
>&... | <p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html" rel="nofollow">numpy.meshgrid</a>() to make arrays of indexes that you can use to index into both your original array and the array of values for the third dimension.</p>
<pre><code>import numpy as np
import scipy as sp
import sci... | python|arrays|numpy|variable-assignment | 1 |
31 | 13,558,653 | How can I create a new folder with Google Drive API in Python? | <p>From <a href="https://developers.google.com/drive/v2/reference/files/insert" rel="noreferrer">this example</a>. Can I use MediafileUpload with creating folder? How can I get the parent_id from?</p>
<p>From <a href="https://developers.google.com/drive/folder" rel="noreferrer">https://developers.google.com/drive/fold... | <p>To create a folder on Drive, try:</p>
<pre><code> def createRemoteFolder(self, folderName, parentID = None):
# Create a folder on Drive, returns the newely created folders ID
body = {
'title': folderName,
'mimeType': "application/vnd.google-apps.folder"
}
if pa... | python|google-drive-api | 22 |
32 | 22,296,150 | Deadlock when creating index | <p>I try to create an index with a Cypher query using py2neo 1.6.2 and neo4j 2.0.1:</p>
<pre><code>graph_db = neo4j.GraphDatabaseService()
query = "CREATE INDEX ON :Label(prop)"
neo4j.CypherQuery(graph_db, query).run()
</code></pre>
<p>The query works fine in the neo4j web interface but throws a deadlock error in py2... | <p>Judging from the deadlock graph in the details section, this looks like a bug in 2.0.1. Are you doing anything else to the database other than running this specific query, or is this just starting up a fresh database and running the code you provided?</p>
<p>In any case, since it works in the Neo4j Browser, I'd sug... | python|neo4j|cypher|py2neo | 1 |
33 | 43,838,895 | Data comes out misaligned when printing list | <p>I have a code that reads an inventory txt file that is suppose to display a menu for the user when it is run. However, when it runs the quantity and pice columns are misaligned:</p>
<pre><code>Select an item ID to purchase or return:
ID Item Quantity Price
244 Large Cake Pan 7.00 19.99
576 Assort... | <p>Using your class <code>Inventory</code>'s getters you can make a list and just join the output.</p>
<pre><code>def printMenu (all_data):
print ()
print ('Select an item ID to purchase or return: ')
print ()
print ('ID\tItem\t\t Quantity\t Price')
for item in all_data:
product_id = item... | python|list | 0 |
34 | 71,384,054 | How to save a dictionary having multiple lists of values for each key in a csv file | <p>I have a dictionary in the format:</p>
<pre><code>cu = {'m':[['a1','a2'],['a3','a4'],['a5','a6']], 'n':[['b1','b2'], ['b3','b4']]}
</code></pre>
<p>#the code I used to save the dictionary in csv file was:</p>
<pre><code>#using numpy to make the csv file
import numpy as np
# using the savetxt
np.savetxt("cu_... | <p>The error is caused by <code>cu</code> being a dictionary type, which is not an array type.</p>
<p>However, simply converting to an array isn't going to work either, since what you want is fairly complicated. One way to perform this data transformation is to append the key to each subarray:</p>
<pre><code>([['m', a1... | python|numpy|csv|dictionary | 0 |
35 | 39,063,571 | Binding command line arguments to the object methods calls in Python | <p>I am working on a command line utility with a few possible arguments. The argument parsing is done with argparse module. In the end, with some additional customization, I get a dictionary with one and only one element:</p>
<pre><code>{'add_account': ['example.com', 'example']}
</code></pre>
<p>Where the key is an ... | <p>You can use <code>getattr</code> to fetch a method object (<code>argparse.py</code> uses this approach several times).</p>
<p>You didn't give us a concrete example, but I'm guessing you have a class like this:</p>
<pre><code>In [387]: class MyClass(object):
...: def add_account(self,*args):
...: ... | python-3.x|argparse | 0 |
36 | 39,258,038 | The most efficient way to iterate over a list of elements. Python 2.7 | <p>I am trying to iterate over a list of elements, however the list can be massive and takes too long to execute. I am using newspaper api. The for loop I constructed is:</p>
<pre><code>for article in list_articles:
</code></pre>
<p>Each article in the list_articles are an object in the format of:</p>
<pre><code><... | <p>The best way is to use built in functions, when possible, such as functions to split strings, join strings, group things, etc...</p>
<p>The there is the list comprehension or <code>map</code> when possible. If you need to construct one list from another by manipulating each element, then this is it.</p>
<p>The th... | python|list|python-2.7|loops|cpython | 2 |
37 | 52,505,943 | SyntaxError: invalid syntax in URLpattern | <p>hi am getting a syntax error</p>
<p>url:</p>
<pre><code>url(r'^reset-password/$',
PasswordResetView.as_view(template_name='accounts/reset_password.html', 'post_reset_redirect': 'accounts:password_reset_done'), name='reset_password'),
</code></pre>
<p>What is the problem?</p>
<p>thanks</p> | <p>The problem is that you mix dictionary syntax with parameter syntax:</p>
<pre><code>url(
r'^reset-password/$',
PasswordResetView.as_view(
template_name='accounts/reset_password.html',
<s><b>'post_reset_redirect': 'accounts:password_reset_done'</b></s>
),
name='reset_password'
)</code... | python|django|syntax | 3 |
38 | 52,831,640 | Converting hex to binary in array | <p>I'm working on Visual Studio about python Project and The user input like that <code>010203</code> and
I use this code for saparating the input:</p>
<pre><code>dynamic_array = [ ]
hexdec = input("Enter the hex number to binary ");
strArray = [hexdec[idx:idx+2] for idx in range(len(hexdec)) if idx%2 == 0]
dynam... | <p>It's a lot easier if you thnk of hex as a integer (number).<br>
There's a lot of tips on how to convert integers to different outcomes, but one useful string representation tool is <code>.format()</code> which can format a integer (and others) to various outputs.</p>
<p>This is a combination of:</p>
<ul>
<li><a hr... | python|python-3.x | 3 |
39 | 52,626,708 | Why is my program shifting s and c by the wrong amount if I enter 5 into my program but not with any other letters or number? | <p>This program is meant to ask you for a sentence and a number then it shifts the letters down the alphabet all by the inputted number and then lets you undo it by shift it by minus what you enter. For some reason when you enter <code>5</code> as your shift the letter s shift to different random letters and does not g... | <p>The problem is that you define a global <code>x</code> variable, and also a local one. The local one shadows the global one and so the result of <code>eval("x")</code> is not anymore what you expected to have. </p>
<p>Solution: use a different variable for the <code>for</code> loop.</p>
<p>There is much that can b... | python|arrays|loops|eval | 0 |
40 | 47,735,224 | Receiving service messages in a group chat using Telegram Bot | <p>I am trying to create a bot in my group to help me track the group users who have invited other users into the group.</p>
<p>I have disabled the privacy mode so the bot can receive all messages in a group chat. However, it seems to be that <code>update.message</code> only gets messages supplied by other users but n... | <p>I suppose you are using <code>python-telegram-bot</code> library.</p>
<p>You can add a handler with a specific filter to listen to service messages:</p>
<pre><code>from telegram.ext import MessageHandler, Filters
def callback_func(bot, update):
# here you receive a list of new members (User Objects) in a sing... | python|python-3.x|telegram-bot|python-telegram-bot | 1 |
41 | 47,930,647 | Pandas division with 2 dfs | <p>I want to divide 2 dfs by matching their names. For example,</p>
<p><code>df1 = pd.DataFrame({'Name':['xy-yz','xa-ab','yz-ijk','zb-ijk'],1:[1,2,3,4],2:[1,2,1,2],3:[2,2,2,2]} )</code></p>
<p><code>df2 = pd.DataFrame({'Name2':['x','y','z','a'],1:[0,1,2,3],2:[1,2,3,4],3:[5,5,5,6]})</code></p>
<p>df1:</p>
<pre><cod... | <p>I do not know why you need it , but this give back what you need </p>
<pre><code>df2=df2.set_index('Name2')
dfNew=df2.reindex(df1.Name1.str.split('-',expand=True)[0])
df1=df1.set_index('Name1')
pd.concat([df1.reset_index(),dfNew.reset_index().rename(columns={0:'Name1'}),pd.DataFrame(df1.values/dfNew.values,columns=... | python|pandas|dataframe|division | 3 |
42 | 34,316,747 | Django logout() returns none | <p>Morning everyone</p>
<p>Im using django logout() to end my sessions just like django docs says :</p>
<p><strong>views.py</strong></p>
<pre><code>class Logout(View):
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse('cost_control_app:login'))
</code></pre>
<p>and i... | <p>I'm curious, why do you have the method named <code>logout_view()</code>? By default, nothing is going to call that method. You need to change the name to match the HTTP verb which will be used to call the page. For instance, if it's going to be a <code>GET</code> request, you would change it to:</p>
<pre><code>def... | python|django|logout | 2 |
43 | 72,769,527 | Def and Return Function in python | <p>I'm having some problems with the def and return function in Python.
On the top of my program I've defined:</p>
<pre><code>from subprogram import subprogram
</code></pre>
<p>then I've defined the def in which I've included the values I wanted to be returned:</p>
<pre><code>def subprogram(ssh, x_off, y_off, data_arra... | <p>The function doesn't return the variable, only the value on it.</p>
<p>If you want to get the returned value on var_colonna_1, you should asign it, as Sayse said, you should do:</p>
<pre><code>var_colonna_1 = subprogram(ssh, x_off, y_off, data_array, i, j)
</code></pre> | python | 1 |
44 | 16,380,528 | Faster alternatives to Popen for CAN bus access? | <p>I'm currently using Popen to send instructions to a utility (<code>canutils</code>... the <code>cansend</code> function in particular) via the command line.</p>
<p>The entire function looks like this.</p>
<pre><code>def _CANSend(self, register, value, readWrite = 'write'):
"""send a CAN frame"""
queue=self... | <p>I suspect that most of that time is due to the overhead of forking every time you run cansend. To get rid of it, you'll want an approach that doesn't have to create a new process for each send.</p>
<p>According to <a href="http://libbits.wordpress.com/2012/05/22/socketcan-support-in-python/" rel="nofollow">this bl... | python|linux|popen|can-bus|socketcan | 4 |
45 | 38,892,509 | how to install wordcloud package in python? | <pre><code>pip install wordcloud
File "<ipython-input-130-12ee30540bab>", line 1
pip install wordcloud
^
SyntaxError: invalid syntax
</code></pre>
<p>This is the problem I am facing while using <code>pip install wordcloud</code>.</p> | <p><code>pip</code> is a tool used for installing python packages. You should not use this command inside the python interactive shell. </p>
<p>Instead, exit out of it and write <code>pip install wordcloud</code> on the main shell.</p> | python|word-cloud | 5 |
46 | 38,810,696 | Python -- sizing frames with weights | <p>In the minimum example code below, you can change the last range(), currently at 3, to 6 and notice that the frames with buttons all get smaller than if you run it with 3. I have configured 6 columns of "lower_frame" to all be weight 1. The expected result is that there are 6 empty columns of the same width no mat... | <p>If you want all of the rows and all of the columns to have the same width/height, you can set the <code>uniform</code> attribute of each row and column. All columns with the same <code>uniform</code> value will be the same width, and all rows with the same <code>uniform</code> value will be the same height.</p>
<p>... | python|python-2.7|user-interface|tkinter|tk | 1 |
47 | 40,621,144 | Can't get stored python integer back in java in habase google cloud | <p>I'm using hbase over google cloud bigtable to store my bigdata. I have 2 programs. first, store data using python into hbase and the second, read those info back from java by connecting to the same endpoint.</p>
<p>so from python interactive shell I can read byte arrays back into an integer (command 15)</p>
<pre><... | <p>I found the problem<br/>
the column stored as long value so I had to first read it as long in java and then convert it to int</p> | java|python|hbase|google-cloud-dataproc | 0 |
48 | 1,504,804 | Using IronPython to learn the .NET framework, is this bad? | <p>Because I'm a Python fan, I'd like to learn the .NET framework using IronPython. Would I be missing out on something? Is this in some way not recommended?</p>
<p>EDIT:
I'm pretty knowledgeable of Java ( so learning/using a new language is not a problem for me ). If needed, will I be able to use everything I learned... | <p>No, sounds like a good way to learn to me. You get to stick with a language and syntax that you are familiar with, and learn about the huge range of classes available in the framework, and how the CLR supports your code.</p>
<p>Once you've got to grips with some of the framework and the CLR services you could alway... | c#|.net|ironpython | 11 |
49 | 32,230,578 | Django: handle migrations for an imported database? | <p>I'm working in Django 1.8 and trying to set up an existing project. I've inherited a database dump, plus a codebase. </p>
<p>I've imported the database dump successfully. </p>
<p>The problem is that if I try to run <code>migrate</code> against the imported database I then get errors about columns already existing,... | <p>I think your migrations problem solved by the previous Answer. Therefore I'm adding a link below...</p>
<p>If you just started django 1.7 and above then</p>
<p>Here I'ld like to add a link <a href="https://markusholtermann.eu/2014/09/django-17-database-migrations-done-right/" rel="nofollow">Django Migration How wo... | python|django|django-migrations|django-database | 1 |
50 | 32,399,565 | convert python integer to its signed binary representation | <p>Given a positive integer such as 171 and a "register" size, e.g. 8.</p>
<p>I want the integer which is represented by the binary representation of 171, i.e. '0b10101011' interpreted as twos complement.</p>
<p>In the present case, the 171 should become -85.
It is negative because given the "register" size 8, the MS... | <p>You don't need binary conversion to achieve that:</p>
<pre><code>>>> size = 8
>>> value = 171
>>> unsigned = value % 2**size
>>> signed = unsigned - 2**size if unsigned >= 2**(size-1) else unsigned
>>> signed
-85
</code></pre> | python|binary|integer|twos-complement | 3 |
51 | 43,992,609 | Unable to uninstall anaconda from Ubuntu 16.04 | <p>I am trying to uninstall Ananconda from my Ubuntu 16.04 LTS machine.</p>
<p>I ran the following commands</p>
<pre><code>conda install anaconda-clean
anaconda-clean
rm -rf ~/anaconda
</code></pre>
<p>Everything is getting exceuted without any error/warning. If fact, when I run <code>anaconda-clean</code> it is saying... | <pre><code>conda install anaconda-clean
anaconda-clean --yes
rm -rf ~/anaconda3
</code></pre>
<p>Replace <em>anaconda3</em> with your version of anaconda</p>
<p>This will uninstall anaconda</p> | python|ubuntu|anaconda|ubuntu-16.04|uninstallation | 4 |
52 | 34,612,214 | if loop repeating first if statement | <p>I'm trying to create a continuous question loop to process all my calculations for my nmea sentences in my project. For some reason only the first <code>if</code> statement is executed. What am I doing wrong? I'm still fairly new to python</p>
<pre><code> if command_type == "$GPGGA" or "GPGGA" or "GGA":
#... | <pre><code>if command_type == "$GPGGA" or "GPGGA" or "GGA":
</code></pre>
<p>As you can see, here you are not trying to check if <em>command_type</em> is valued "$GPGGA" or "GPGGA" or "GGA". But if <em>command_type == "$GPGGA"</em> is true <strong>or</strong> <em>"GPGGA"</em> is true <strong>or</strong> <em>"GGA"</em>... | python|loops|python-3.x|if-statement | 2 |
53 | 789,598 | What is the easiest way to build Python26.zip for embedded distribution? | <p>I am using Python as a plug-in scripting language for an existing C++ application. I am able to embed the python interpreter as stated in the Python documentation. Everything works successfully with the initialization and de-initialization of the interpreter. I am, however, having trouble loading modules because I h... | <p>I would probably use <a href="http://peak.telecommunity.com/DevCenter/setuptools" rel="nofollow noreferrer">setuptools</a> to create an egg (basically a java jar for python). The setup.py would probably look something like this:</p>
<pre><code>from setuptools import setup, find_packages
setup(
name='python26_... | c++|python|distribution|embedded-language | 2 |
54 | 1,053,344 | Modeling a complex relationship in Django | <p>I'm working on a Web service in Django, and I need to model a very specific, complex relationship which I just can't be able to solve.</p>
<p>Imagine three general models, let's call them Site, Category and Item. Each Site contains one or several Categories, but it can relate to them in one of two possible ways: on... | <p>Why not just have both types of category in one model, so you just have 3 models?</p>
<pre><code>Site
Category
Sites = models.ManyToManyField(Site)
IsCommon = models.BooleanField()
Item
Category = models.ForeignKey(Category)
</code></pre>
<p>You say "Internally, those two type of Categories are completel... | python|django|django-models|entity-relationship | 4 |
55 | 815,530 | How to use subversion Ctypes Python Bindings? | <p>Subversion 1.6 introduce something that is called 'Ctypes Python Binding', but it is not documented. Is it any information available what this bindings are and how to use it? For example, i have a fresh windows XP and want to control SVN repository using subversiion 1.6 and this mysterious python bindings. What exac... | <p>You need the Subversion source distribution, Python (>= 2.5), and <a href="http://code.google.com/p/ctypesgen/" rel="nofollow noreferrer">ctypesgen</a>.</p>
<p>Instructions for building the ctypes bindings are <a href="http://svn.apache.org/repos/asf/subversion/trunk/subversion/bindings/ctypes-python/README" rel="n... | python|svn | 1 |
56 | 47,413,755 | Installing Python's Cryptography on Windows | <p>I've created a script on windows to connect to Remote SSH server. I have successfully installed <code>cryptography</code>, <code>pynacl</code> and finally <code>paramiko</code>(Took me an entire day to figure out how to successfully install them on windows).</p>
<p>Now that I run the script, it pops an error saying... | <p>After a lot of googling, I finally stumbled upon <a href="https://github.com/pyca/pynacl/issues/281" rel="nofollow noreferrer">this</a>. As mentioned in the conversation I uninstalled my previous pynacl installation, downloaded the zipped source from <a href="https://github.com/lmctv/pynacl/archive/v1.2.a0.reorder.z... | python|windows|ssh | 0 |
57 | 47,206,902 | OpenCV Python Assertion Failed | <p>I am trying to run opencv-python==3.3.0.10 on a macOS 10.12.6 to read from a file and show the video in a window. I have exactly copied the code from here <a href="http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html" rel="nofollow noreferrer">http://openc... | <p>It's not clear from your question, but it looks like you're specifically running into a situation where the video completes playing without being interrupted. I <em>think</em> the issue is that the VideoCapture object is already closed by the time you get to <code>cap.release()</code>. I'd recommend putting the call... | python|opencv|opencv3.0|opencv-python | 1 |
58 | 57,332,622 | reference to invalid character number: (Python ElementTree parse) | <p>I have xml file which has following content:</p>
<pre><code> <word>vegetation</word>
<word>cover</word>
<word>(&#x2;31%</word>
<word>split_identifier ;</word>
<word>Still</word>
<word>and</word>
</code></pre>
<p>When... | <p>If you want to get rid of those special characters, you can by scrubbing the input XML as a string:</p>
<pre><code>respXML = response.content.decode("utf-16")
scrubbedXML = re.sub('&.+[0-9]+;', '', respXML)
respRoot = ET.fromstring(scrubbedXML)
</code></pre>
<p>If you prefer to keep the special characters yo... | python|elementtree | 1 |
59 | 57,447,687 | Can I save results anyway even when Keyboardinterrupt? | <p>I have a very long code which is taking forever to run. I was wondering if there is a way to save the results even if I use the keyboard to interrupt the code from running? All the examples I found were using except with Keyboardinterrupt, so I don't know if this is the right code to use.</p>
<p>More concretely: I ... | <p>You could use a <code>try</code>-<code>except</code> with <code>KeyboardInterrupt</code>:</p>
<pre><code>def your_function():
removed = [...]
try:
# Code that takes long time
for a, b in itertools.combinations(removed, 2):
...
return removed
except KeyboardInterrupt:... | python|python-3.x|keyboardinterrupt | 2 |
60 | 71,057,396 | How can i replace a value in a specific row and column in a csv file | <p>I need to replace a value in correspondence of an ID in a .csv file:</p>
<pre><code>ChatId,Color
805525230,black
</code></pre>
<p>So if the ID in input is equal to the one in the file my program will replace the Color "black" with the new one. I tried this:</p>
<pre class="lang-py prettyprint-override"><co... | <p>Assuming you loaded the csv on a dataframe, you could you use some of its functions.</p>
<p>For example: <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html</a></p>
<p>Alternatively, ... | python|pandas|csv | 0 |
61 | 11,737,817 | What is the simplest language which support template&context mechanism? | <p>I need to find the easiest way to automatically build ebooks from downloaded articles.</p>
<p>I want to automatically generate TOC, which will be based on HTML template.</p>
<p>I know that python django has template & context mechanism, however django is a little to complicated for people to which I am prepari... | <p>IMHO, if you are familiar with Django:</p>
<ul>
<li>if you want to build a command line application or a abstract library, look at <a href="http://jinja.pocoo.org/docs/" rel="nofollow">Jinja2</a> template engine.</li>
<li>if you are looking for a web framework simpler than Django, look at <a href="http://flask.poco... | python|django|templates|programming-languages|django-context | 3 |
62 | 46,815,043 | python managing tasks in threads when using priority queue | <p>I'm trying to write a program which starts new tasks in new threads.
Data is passed from task threads to a single worker/processing thread via a priority queue (so more important jobs are processes first).
The worker/processing thread gets higher priority data from the queue and limits calls to a REST API </p>
<p>... | <p>In your request queue entry include a response queue. When finished place a response on the response queue.</p>
<p>The requesting thread waits on the response queue.</p>
<p>A callback method could alternately be used.</p> | python|queue | 0 |
63 | 46,730,360 | Wrong datetimes picked up by pandas | <p>Data Scraped</p>
<p><a href="https://i.stack.imgur.com/lULod.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lULod.png" alt="enter image description here"></a></p>
<p>So I've scraped data from a website with a timestamp of when it was scraped. As you can see I have no date between 2017-09-14 13:... | <p>Assuming your timestamps have the same format as the filenames in your screenshot, this should work (after the replacement of <code>"|"</code> by <code>" "</code>):</p>
<pre><code>df['dtScraped'] = pd.to_datetime(df['dtScraped'], format="%Y-%m-%d %H-%M-%S")
</code></pre> | python-3.x|pandas | 0 |
64 | 37,619,363 | Plot wind speed and direction from u, v components | <p>I'm trying to plot the wind speed and direction, but there is an error code that keeps telling me that "sequence too large; cannot be greater than 32." Here is the code that I am using:</p>
<pre><code>N = 500
ws = np.array(u)
wd = np.array(v)
df = pd.DataFrame({'direction': [ws], 'speed': [wd]})
df
direction sp... | <p>To plot wind U, V use <code>barbs</code> and <code>quiver</code>. Look at the code below:</p>
<pre><code>import matplotlib.pylab as plt
import numpy as np
x = np.linspace(-5, 5, 5)
X, Y = np.meshgrid(x, x)
d = np.arctan(Y ** 2. - .25 * Y - X)
U, V = 5 * np.cos(d), np.sin(d)
# barbs plot
ax1 = plt.subplot(1, 2, 1)
... | python|pandas|matplotlib|jupyter-notebook | 1 |
65 | 37,934,099 | Python 2.7.3 urllib2 Error | <p>When I try to run my python script this error happens. How can I solve this problem ?</p>
<pre><code>['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'urllib2']
Traceback (most recent call last):
File "m.py", line 3, in <module>
import requests
File "/usr/local/lib/python2.7/dist-pac... | <p>you need to upgrade <a href="https://pypi.python.org/pypi/requests/" rel="nofollow">requests</a> </p>
<pre><code>pip install --upgrade requests
</code></pre> | python | 2 |
66 | 67,669,925 | "The request's session was deleted before the request completed. The user may have logged out in a concurrent request" | <p>"The request's session was deleted before the request completed. The user may have logged out in a concurrent request" I am facing this error when trying to use 2 request.session().</p>
<p>In my code my using two request.session() to store variables.After one request successfully completed,its going to ano... | <p>Since my dataset has 8000 rows, It was not a good idea to store in session variables. I have written some rest calls and that solved my problem.</p> | python|django | 0 |
67 | 30,036,305 | Shelves an multiple items | <p>I've been trying to make a quote input that puts multiple quotes inside a file (coupled with the authors name). I have tried with pickle, but I could not get more than 2 pickled items inside a file and finally I decided to use shelf.</p>
<p>However, I am having some trouble with shelves as well.</p>
<p>I dont real... | <p>You can do this with pickle. As this <a href="https://stackoverflow.com/questions/12761991/how-to-use-append-with-pickle-in-python">answer</a> describes, you can append a pickled object to a binary file using open with append in binary mode. </p>
<p>To read the multiple pickled objects out of the file, just call <c... | python | 0 |
68 | 57,028,126 | "chalice deploy" call ends up with "Unknown parameter in input: "Layers"" | <p>I create the most basic chalice app </p>
<pre><code>from chalice import Chalice
app = Chalice(app_name='testApp')
@app.route('/')
def index():
return {'hello': 'world'}
</code></pre>
<p>with empty requirements.txt and config that looks like this:</p>
<pre><code>{
"version": "2.0",
"app_name": "testApp"... | <p>After troubleshooting found some issues with my local configurations. What helped was running the chalice in virtualenv (<a href="https://virtualenv.pypa.io/en/latest/" rel="nofollow noreferrer">https://virtualenv.pypa.io/en/latest/</a>)</p> | python|amazon-web-services|deployment|aws-lambda|chalice | 0 |
69 | 65,540,231 | Import and insert word in sequence in Python | <p>I want to <strong>import</strong> and <strong>insert</strong> word in <strong>sequence</strong> and <strong>NOT RANDOMLY</strong>, each registration attempt uses a <strong>single</strong> username and <strong>stop</strong> until the registration is <strong>completed</strong>. Then logout and begin a <strong>new</str... | <p>I am going to assume that you are happy with what the code does, with exception that the names it picks are random. This narrows everything down to one line, and namely the one that picks names randomly:</p>
<pre><code>idx = random.randint(0, len(names) - 1)
</code></pre>
<p>Simple enough, you want "the next wo... | python|import|webforms | 0 |
70 | 65,903,633 | Load a text file paragraph into a string without libraries | <p>sorry if this question may look a bit dumb for some of you but i'm totally a beginner at programming in Python so i'm quite bad and got a still got a lot to learn.
So basically I have this long text file separated by paragraphs, sometimes the newline can be double or triple to make the task more hard for us so i add... | <p>This should do the trick. It is very short and elegant:</p>
<pre><code>with open('dummy text.txt') as file:
data = file.read().replace('\n', '')
print(data)#prints out the file
</code></pre>
<p>The output is:</p>
<pre><code>"random questions about files with a dummy text and strings hey look a new paragraph... | python|string|file|txt | 1 |
71 | 43,439,172 | Python/Kivy Assertion Error | <p>I obtained an Assertion error while attempting to learn BoxLayout in kivy. I cannot figure out what has went wrong.</p>
<pre><code> from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
class BoxLayoutApp(App):
def build(self):
return ... | <p>Try subclassing boxlayout instead:</p>
<pre><code>from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
class MyBoxLayout(BoxLayout):
pass
Builder.load_string('''
<MyBoxLayout>:
BoxLayout:
Button:
tex... | python|kivy | 5 |
72 | 36,966,316 | How to get the dimensions of a tensor (in TensorFlow) at graph construction time? | <p>I am trying an Op that is not behaving as expected.</p>
<pre><code>graph = tf.Graph()
with graph.as_default():
train_dataset = tf.placeholder(tf.int32, shape=[128, 2])
embeddings = tf.Variable(
tf.random_uniform([50000, 64], -1.0, 1.0))
embed = tf.nn.embedding_lookup(embeddings, train_dataset)
embed = t... | <p>I see most people confused about <code>tf.shape(tensor)</code> and <code>tensor.get_shape()</code>
Let's make it clear:</p>
<ol>
<li><code>tf.shape</code></li>
</ol>
<p><code>tf.shape</code> is used for dynamic shape. If your tensor's shape is <strong>changable</strong>, use it.
An example: a input is an image wi... | python|tensorflow|deep-learning|tensor | 62 |
73 | 36,993,569 | /usr/bin/python: No module named pip | <p>I am having a bit of trouble getting everything to work on my Mac running El Capitan. I am running 3.5.1. I am under the impression that Pip is included with an install of the above, however when I try to use it to install sympy using the syntax in terminal: <code>python -m pip install SomePackage</code>, I get the ... | <p>I believe that you can run it by calling <code>pip</code> in the terminal. If you have it already installed.</p>
<p><code>pip install sympy</code></p> | python|python-3.x|pip | 2 |
74 | 36,897,802 | Get params validation on viewsets.ModelViewSet | <p>I am new to django and building a REST API using <code>django-rest-framework</code>.
I have written some code to check whether the user has supplied some parameters or not.But that is very ugly with lot of <code>if conditions</code>, so i want to refactor it.Below is the code that i have written please suggest how t... | <p>You can make <a href="http://www.django-rest-framework.org/api-guide/serializers/#modelserializer" rel="noreferrer">serializers</a>, they have a very easy way to validate your data. As in your case all the fields seem to be required it becomes even easier.</p>
<p>Create a file on you api app like:</p>
<h3>serializer... | python|django|django-views|django-rest-framework | 8 |
75 | 48,687,009 | Python - Error in two-layer neural network | <p>I am trying to implement a 2-layer neural network from scratch. But there is something wrong. After some iterations, my loss becomes <code>nan</code>.</p>
<pre><code>'''
We are implementing a two layer neural network.
'''
import numpy as np
x,y = np.random.rand(64,1000),np.random.randn(64,10)
w1,w2 = np.random.ran... | <p>Its because your loss is becoming too high<br>
try this </p>
<pre><code>loss = np.square(ypred - y).mean()
</code></pre>
<p>and if still doesn't work try reducing the learning rate to something like <code>1e-8</code>.<br>
and observe if the loss is going up or down, if loss is reducing thats good, if the loss is i... | python|neural-network | 0 |
76 | 19,919,498 | How to implement n times nested loops in python? | <p>I want to do nested loops with n times, this n is an variable and can be provided by function or input methods. In order to do this, I have to write lots of if..elif blocks depend on size of n, does anybody have good strategies to handle this task? The codes (for combination of 4 letters problem) I used are as follo... | <p>You can use <a href="http://docs.python.org/2/library/itertools.html#itertools.product" rel="noreferrer">itertools.product</a> with <code>repeat</code> parameter</p>
<pre><code>import itertools
def charCombination(n):
return ["".join(item) for item in itertools.product("ATCG", repeat=n)]
print charCombination... | python | 5 |
77 | 66,959,167 | Timer for variable time delay | <p>I would like a timer (Using Python 3.8 currently) that first checks the system time or Naval Observatory clock, so it can be started at any time and synch with the 00 seconds.</p>
<p>I'm only interested in the number of seconds on the system clock or Naval Observatory. At the top of every minute, i.e when the second... | <p>This will call a function when the seconds are 0:</p>
<pre><code>def time_loop(job):
while True:
if int(time.time()) % 60 == 0:
job()
time.sleep( 1 )
</code></pre> | python|variables|time|timer|delay | 1 |
78 | 48,054,298 | Finding nearest timeindex for many categories | <p>I am trying to obtain the data points nearest to the query timestamp for multiple independent categories like this (<a href="https://gist.github.com/talesa/babe9955b891c8f75611eaf8e4f48974" rel="nofollow noreferrer">example in more detail in the gist</a>):</p>
<pre><code>dt = pd.to_datetime(dt)
df_output = list()
f... | <p>Pandas was made for time-series data so this is it's bread and butter. Try this for performance:</p>
<pre><code>dt = '2017-12-23 01:49:13'
df["timedelta"] = abs(df.index - pd.Timestamp(dt))
df.loc[df.groupby(by="category")["timedelta"].idxmin()].drop("timedelta", axis=1)
</code></pre>
<p>This is creating a new co... | python|pandas|time-series | 1 |
79 | 48,082,038 | Cassandra Pagination CPU Utilization Issue | <p>I had developed a python script for pulling the data but it is using only single cpu core and when I do top cassandra is using more than 200% cpu. Going into Idle state since in between GC coming into picture Unable understand how can I convert the code to utilize multiple cores and parallel processing.</p>
<pre><c... | <p>You wont get blazing performance out of python driver, but you can look at cqlsh's copy functions (<a href="https://github.com/apache/cassandra/blob/trunk/pylib/cqlshlib/copyutil.py#L229" rel="nofollow noreferrer">https://github.com/apache/cassandra/blob/trunk/pylib/cqlshlib/copyutil.py#L229</a>) if you really want ... | python-3.x|cassandra | 1 |
80 | 48,376,460 | finding just full words in a python string | <p>Basically it all comes down to finding just the fullword, not matching also a substring thereof.</p>
<p>I have phrases like: </p>
<p>texto = "hello today is the first day of working week" and what I wanted to do is to split that phrase into words to see if any matched fullwords that I have obtained from a sql quer... | <p>I dont't see why split() should not work. The issue is the <code>.__str__()</code> (which I don't see any need for). It creates one single string in which the keywords are searched - and then it will find substrings as well. </p>
<p>The following is working for me:</p>
<pre><code>texto = "hello today is the first ... | python | 0 |
81 | 73,682,019 | How to solve a Dataset problem in python? | <p>i have a dataset with different programming language in a column titled and i want to get the 10 most used programming language in my dataset python</p>
<p>Dataset: <a href="https://drive.google.com/file/d/1nJLDFSdIbkNxcqY7NBtJZfcgLW1wpsUZ/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/... | <p>On StackOverflow, you should not link to outside sources, but include relevant data in your question. You should also pare down the data - if it is long, make it as short as possible and still illustrate your question.</p>
<p>Finally, on StackOverflow, we don't ask bare questions like "how to do x". You ... | python | 0 |
82 | 17,505,091 | Python/Django - Having trouble giving an object a foreignkey that was just created | <p>I am expanding on the basic django Poll site tutorial, and I have made a view that allows users to add their own polls. Adding a poll works, adding choices does not. Apparently this is because the poll does not "exist" yet, and the p.id cannot be used. However, the p.id works when redirecting the browser at the bott... | <p>Nevermind, I figured it out. The choice doent need an id, rather, it needs the object.
FIxed by changing:</p>
<pre><code>c1 = Choice(poll=p.id, choice_text=request.POST['c1'], votes=0)
</code></pre>
<p>to</p>
<pre><code>c1 = Choice(poll=p, choice_text=request.POST['c1'], votes=0)
</code></pre> | python|django | 1 |
Dataset Details
Dataset Description
TP4 is a comprehensive dataset containing a curated collection of questions and answers from Stack Overflow. Focused on the realms of Python programming, NumPy, Pandas, TensorFlow, and PyTorch, TP4 includes essential attributes such as question ID, title, question body, answer body, associated tags, and score. This dataset is designed to facilitate research, analysis, and exploration of inquiries and solutions within the Python and machine learning communities on Stack Overflow.
Dataset Structure
-Question ID: Unique identifiers for each question, facilitating easy referencing and linkage. -Title: Concise titles summarizing the essence of each question. -Question and Answer Bodies: Rich textual content providing detailed context and solutions. -Tags: Categorization labels such as 'python', 'numpy', 'pandas', 'tensorflow', and 'pytorch' for efficient filtering. -Score: Numerical representation of the community's evaluation of the question or answer.
Dataset Card Authors
SYED HASAN ABBAS
- Downloads last month
- 49