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
5,200
72,866,707
How to get Json Data Inside cloudWatch's Log Event Using boto3
<p>I am <em>AWS CloudWatch</em>. I have these log events inside a log group. I can get the name, creation date etc of these log events but I wanted to get the json information inside every log events.</p> <p><a href="https://i.stack.imgur.com/v9Z7W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v9Z7...
<p>You could do something like this which will iterate through the log groups and streams and add them to a nested dictionary. Regarding your question, if your logs are output in json format already then they will appear in the list associated with the log stream name.</p> <p>The appropriate boto3 function was <a href=...
python-3.x|boto3|amazon-cloudwatch
1
5,201
62,168,741
Multiplying 2 columns in excel using .write_formula (xlsxwriter) in python
<p><a href="https://i.stack.imgur.com/eoHcc.png" rel="nofollow noreferrer">I want to multiply columns "D" and "E" and write the answer in column "F"</a></p>
<p>Check out the <a href="https://xlsxwriter.readthedocs.io/worksheet.html#write_formula" rel="nofollow noreferrer">documentation</a>.</p> <p>This should be as easy as <code>worksheet.write_formula('F3', '=D3*E3')</code>. If you want to do it for your whole sheet, just write a loop like</p> <pre><code>for row in rang...
python|excel|xlsxwriter
1
5,202
62,393,635
Is there a limit to the number of objects I can detect in TFLite?
<p>From Tensorflow's <a href="https://www.tensorflow.org/lite/models/object_detection/overview" rel="nofollow noreferrer">website</a>, I found that the model they provided had a maximum number of 10 objects per image. Could I make a model that could detect more objects in an image (like 16 for example)? or is it a soft...
<p>Usually there's a limit to how many objects "survive" the non-max suppression stage. You can set this limit higher.</p> <p>Often there is an upper limit to how many objects can be detected in total, but it depends on the size of the search grid and how many detectors there are per grid cell. For something like SSD ...
tensorflow-lite
0
5,203
62,222,194
Simplify numpy expression
<p>How can I simplify this:</p> <pre><code>import numpy as np ex = np.arange(27).reshape(3, 3, 3) def get_plane(axe, index): return ex.swapaxes(axe, 0)[index] # is there a better way ? </code></pre> <p>I cannot find a numpy function to get a plane in a higher dimensional array, is there one? </p> <h2>EDIT</h...
<p>Inspired by <a href="https://stackoverflow.com/a/24399139/4238408">this answer</a>, you can do something like this:</p> <pre><code>def get_plane(axe, index): slices = [slice(None)]*len(ex.shape) slices[axe]=index return ex[tuple(slices)] get_plane(1,1) </code></pre> <p>output:</p> <pre><code>array([[...
python-3.x|numpy|multidimensional-array
2
5,204
58,860,696
How speed up xbrl file parsing in python lxml?
<p>I am trying to parse xbrl file (1.35Gb) via <a href="http://arelle.org/" rel="nofollow noreferrer">arelle</a>. During debug I spot that execution holds on line <a href="https://github.com/Arelle/Arelle/blob/4211c6222626309e4167888059c4f97e8b579b1c/arelle/ModelDocument.py#L157" rel="nofollow noreferrer">ModelDocument...
<p>Maybe my answer will be more relevant, in the long term, to developers of XBRL processors, but I would encourage taking a look at what makes an instance streaming-friendly, notably, the following candidate recommendation by XBRL international:</p> <p><a href="https://specifications.xbrl.org/work-product-index-strea...
python|lxml|xbrl|arelle
0
5,205
58,951,869
FileNotFoundError when calling pip in Python subprocess
<p>I need to run some commands that call pip from a python script. Pip is installed on my machine (running Ubuntu). Simply entering 'pip' in a terminal outputs help for the pip command.</p> <p>However, trying to call pip from a python script raises an error. Calling other commands (such as 'ls') from a script works as...
<p>I have not tried this on Ubuntu yet but had similar experiences on Windows.</p> <p>Does the following work?</p> <pre><code>subprocess.Popen(["python"]) </code></pre> <p>If so, you can try</p> <pre><code>subprocess.Popen(["python", "m", "pip", "list"]) # or my case on windows subprocess.Popen(["C:\Python27\ArcGI...
python|shell|subprocess|popen
0
5,206
73,281,749
Using filter(lambda, list) in python to clean data
<p>I'm web-scraping a website as a project. I am currently clearing the data. I have a list containing some information/sentences, but some are empty and I wanted to delete them.</p> <p>My thought was to create a lambda function that identifies null and non-null values ​​to return False or True. Then I would put this f...
<p>check <code>x == &quot;&quot;</code></p> <pre class="lang-py prettyprint-override"><code>f = lambda x: x is not None and x != &quot;&quot; </code></pre>
python|list|filter
0
5,207
73,517,266
how to create by code an Excel workbook with several sheets using pandas.to_excel?
<p>with an SQL query, I get a number of customers, then a number of suppliers for each customer. The objective is to create an Excel workbook per customer and in this workbook, at the rate of one sheet per supplier, copy the details of the supplier's invoices. The code below allows you to create Excel workbooks and one...
<p>after several modifications of the code, the problem is solved. &quot;</p> <pre class="lang-py prettyprint-override"><code>Clients = list(generator_df['Client'].unique()) for i in range(0, len(Clients)): if len(Clients[i]) != 0: writer = pd.ExcelWriter( path+'&quot;'+Clients[i]+&quot;.xlsx&qu...
pandas|dataframe|export-to-excel
-1
5,208
31,658,239
Scikit ROC auc raises ValueError: Only one class present in y_true. ROC AUC score is not defined in that case
<p>Trying to create a ROC curve. </p> <pre><code>model = RandomForestClassifier(500, n_jobs = -1); model.fit(X_train, y_train) y_pred = model.predict(X_test) probas = model.predict_proba(X_test)[:, 1] precision = metrics.precision_score(y_test, y_pred) # returns 0.72 recall = metrics.recall_score(y_test.values, y...
<p>Ended up answering my own question: </p> <p>Had imported y_test as a pandas DataFrame instead of a Series (had saved it using to_csv and imported elsewhere with from_csv). </p> <p>This confused scikit on the ROC curves, but it seems quite happy with that everywhere else. </p> <p>I'll leave this here in the (unlik...
pandas|scikit-learn|random-forest|roc|auc
4
5,209
31,375,216
How to trade on steam with python
<p>i am currently working on a project that involves TF2,python,and steam trading. I would like to know how i can send a steam trade offer from python. I do not need source code or anything, just point me in the right direction. I have searched for ~20 mins on google and cant find anything quite like what i want, they ...
<p>I looked hard and couldn't find a Python library unfortunately, but I did find this Node.js library that does what you want and looks robust at first glance:</p> <blockquote> <p><strong>Steam trading for Node.js</strong><br> Allows you to automate Steam trading in Node.js.<br> <a href="https://github.com/seis...
python|bots|steam
1
5,210
31,596,979
Multiplication between 2 lists
<p>i have 2 lists</p> <pre><code>a=[[2,3,5],[3,6,2],[1,3,2]] b=[4,2,1] </code></pre> <p>i want the output to be:</p> <pre><code>c=[[8,12,20],[6,12,4],[1,3,2]] </code></pre> <p>At present i am using the following code but its problem is that the computation time is very high as the number of values in my list are ve...
<p>You can use numpy :</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a=np.array([[2,3,5],[3,6,2],[1,3,2]]) &gt;&gt;&gt; b=np.array([4,2,1]) &gt;&gt;&gt; a*np.vstack(b) array([[ 8, 12, 20], [ 6, 12, 4], [ 1, 3, 2]]) </code></pre> <p>Or as @csunday95 suggested as a more optimized way you...
python|python-3.x|matrix-multiplication
4
5,211
31,373,531
Parsing through a text file with accentuated characters [Python]
<p>I'm trying to iterate through, and count the occurence of words in a text file in French (containing accentuated characters). The following code pick all the words, but doesn't consider accentuated characters:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import re wordcount={} f = open("verbatim...
<p>Count/totalize/aggregate words of four or more characters without using a regular expression:</p> <pre><code>import collections d = collections.counter() with open('file') as f for line in f: line = line.strip() line = line.split() words = (word for word in line if len(word) &gt;= 4) ...
python|regex|parsing
1
5,212
59,513,258
Why is the following .sh script saying .py command not found when the script is in PATH?
<p>I am trying to run the Example Workflow in <a href="https://rki_bioinformatics.gitlab.io/ditasic/" rel="nofollow noreferrer">https://rki_bioinformatics.gitlab.io/ditasic/</a>, in which example.sh is the major bash script that will take the example data and output some data matrices. </p> <p>In the example.sh script...
<p>Change <code>ditasic_matrix.py</code> line in your script to be <code>./ditasic_matrix.py</code> because of current path not being included in executable search.</p> <p>If it still doesn't execute, maybe the file does not have executable bit set.</p> <p>Open a terminal/console in that folder and issue</p> <pre><c...
python|bash|macos|bioinformatics
2
5,213
49,061,522
Django Form not rendering on HTML
<p>I'm a beginner in developing with django, I've been having a problem with a form I've made, I've been searching for similar problems but none of them could solve my problem.</p> <p>No field of the form render in the HTML but the button renders fine</p> <p>my form:</p> <pre><code>from django import forms from .mod...
<p>Problem solved!!</p> <pre><code>from django import forms from .models import Aluno class NovoAluno(forms.Form): model = Aluno nome = forms.CharField(min_length=15, max_length=100) direccion = forms.CharField(min_length=10, max_length=250) ciudad = forms.CharField(min_length=3, max_length=50) p...
django|python-3.x|django-forms|django-views
1
5,214
70,896,549
AttributeError: 'ArabertPreprocessor' object has no attribute 'farasa_segmenter'
<p>I had this error while using AraBERT,</p> <pre><code>from arabert.preprocess import ArabertPreprocessor model_name = &quot;bert-base-arabertv2&quot; arabert_prep = ArabertPreprocessor(model_name=model_name, keep_emojis=False) text = &quot;ولن نبالغ إذا قلنا إن هاتف أو كمبيوتر المكتب في زمننا هذا ضروري&quot; araber...
<p>It might be that <code>farasapy</code> is required as per the <a href="https://github.com/aub-mind/arabert#preprocessing" rel="nofollow noreferrer">docs</a>, so try to install first.</p> <blockquote> <p>It is recommended to apply our preprocessing function before training/testing on any dataset. Install farasapy to ...
python|nlp|google-colaboratory|arabic
0
5,215
59,944,697
Setting Verbosity to Verbose in psycopg2
<p>How do I set the setting value VERBOSE in psycopg2 </p> <p>This is the equivalent command in postgreSQL</p> <pre><code>\set VERBOSITY verbose </code></pre>
<p>According to the postgres <a href="https://www.postgresql.org/docs/9.4/app-psql.html#APP-PSQL-VARIABLES" rel="nofollow noreferrer">psql documentation</a> <code>VERBOSITY</code> is used to</p> <blockquote> <p>control the verbosity of error reports.</p> </blockquote> <p>Given that the name similarity and the fact ...
python-3.x|postgresql|psycopg2
1
5,216
2,629,889
Django SMTP and secure password authentication
<p>I have an SMTP server that requires secure password authentication (e.g. Outlook requires to check SPA). Is there a way to deal with it with Django SMTPConnection? Or maybe ideas about any python solution to deal SPA?</p> <p>Honestly, I couldn't find enough about SPA, to understand what is it exactly:</p> <ul> <li...
<p>After googling for it I found the same question asked on Google Groups: <a href="http://groups.google.com/group/django-users/browse_thread/thread/fc7f77e2f796e6a4/90ae093cbb2863b8?pli=1" rel="nofollow">http://groups.google.com/group/django-users/browse_thread/thread/fc7f77e2f796e6a4/90ae093cbb2863b8?pli=1</a></p> <...
python|django|smtp|ntlm
0
5,217
2,822,052
How to add OSX menu bar icon with wxPython
<p>I would like to add an icon to the OSX menu bar at the top of the screen using wxPython. I have tried wx.TaskBarIcon, which adds a System Tray icon in Windows, but this doesn't work - it changes the Dock icon for the app instead. Does anyone know how to do this?</p>
<p>It seems that with wxPython2.9-osx-cocoa-py2.7 you can in fact put up a menubar icon. It looks like you can also call <code>PopupMenu()</code> on <code>TaskBarIcon</code> to attach a menu, which you should be able to use to create a full blown OSX menu bar application. </p> <pre><code>import wx class TaskBarFrame(...
python|macos|wxpython|taskbar|menubar
3
5,218
6,011,235
Run a program from python, and have it continue to run after the script is killed
<p>I've tried running things like this:</p> <pre><code>subprocess.Popen(['nohup', 'my_command'], stdout=open('/dev/null', 'w'), stderr=open('logfile.log', 'a')) </code></pre> <p>This works if the parent script exits gracefully, but if I kill the script (Ctrl-C), all my child processe...
<p>The child process receives the same <code>SIGINT</code> as your parent process because it's in the same process group. You can put the child in its own process group by calling <code>os.setpgrp()</code> in the child process. <code>Popen</code>'s <code>preexec_fn</code> argument is useful here:</p> <pre><code>subpro...
python|subprocess|nohup
64
5,219
67,758,498
Update or create does not update and only creates
<pre><code>@require_http_methods([&quot;POST&quot;]) @login_required def edit_question(request): req = json.loads(request.body) question_no = req[&quot;question_no&quot;] guided_answers=req[&quot;guided_answer&quot;] for guided_answer in guided_answers: obj, created= models.ModelAnswer.objects....
<p>i dont know why exactly you ran into this problem but you have a problem in code..you are filtering ModelAnswer by question_id but you are giving it a queryset. this code(Questions.objects.get(pk=question_no)) returns a queryset object or None if DoesNotExist and you are passing it to question_id.. you can change qu...
python|django|django-views|backend
0
5,220
67,029,993
PyQt, Creating a popup in the window
<p>I am trying to create a GUI using PyQt5 and I want to add a popup similar to the one shown below(example taken from Discord because that's the first thing I could think of). How would I go about creating a popup inside of a window that I already have. I don't want to create a whole new window using something like a ...
<p>Creating an &quot;embedded&quot; widget is actually easy: the only thing you need to do is to set its <em>parent</em> as the window (or widget) when you create it. Reparenting can also be done after a widget is created (but a call to <code>show()</code> or <code>setVisible(True)</code> is <em>always</em> required).<...
python|qt|pyqt|pyqt5
2
5,221
67,087,580
Loading the nth line of a txt file in python without loading the whole file
<p>I have a large txt file that is split into lines. I want to load the nth line of this file for use in a for loop in my code. I can't however load the whole array then slice it because of the RAM (the whole file is like 500GB!). Any help would be much appreciated.</p>
<p>You can use a for-loop to iterate over the lines.</p> <pre class="lang-py prettyprint-override"><code>with open(&quot;file.txt&quot;) as f: for line in f: print(line) </code></pre> <p>When iterating over the file, you only have the current line in memory.</p>
python|memory|ram|txt
0
5,222
42,737,276
__eq__ method returns True for both == and > operators
<p>I have declared a class <code>Triangle</code> in Python which takes base and height as <code>__init__</code> arguments and has a method <code>area</code> that computes and returns the area of the triangle. The <code>__eq__</code> method of the <code>Triangle</code> class compares the area of the triangles and return...
<p>Although I can't find a source on this, it seems as if Python 2 uses the <code>id</code> to compare two objects if you don't define the respective magic methods yourself.</p> <p>Observe:</p> <pre><code>&gt;&gt;&gt; t1 = Triangle(3, 4) &gt;&gt;&gt; t3 = Triangle(2, 6) &gt;&gt;&gt; t1 &gt; t3 False &gt;&gt;&gt; t1 &...
python|comparison
3
5,223
72,295,073
Error while multi threading API queries in Python
<p>I'm performing queries in a server with Open Source Routing Machine (OSRM) deployed. I send a set of coordinates and obtain a n x n matrix of network distances over a streets network.</p> <p>In order to improve the speed of the computations, I want to use &quot;ThreadPoolExecutor&quot; to parallelize queries.</p> <p...
<p>I was guided in the right direction by someone outside Stack Overflow.</p> <p>The trick was to point the workers of the pool to a request Session. The function to send the queries was re-worked as follows:</p> <pre><code>def osrm_query(url_input, session): 'Send request' response = session.get(url_input) ...
python|parallel-processing|request|osrm
1
5,224
65,628,306
In tensorflow why for a same dropout value of 0.8 when run with adam optimiser with 50epochs give different accuracy each time i run it?
<p>I am building ANN as below:-</p> <pre><code>model=Sequential() model.add(Flatten(input_shape=(25,))) model.add(Dense(25,activation='relu')) model.add(Dropout(0.8)) model.add(Dense(16,activation='relu')) model.add(Dropout(0.8)) model.add(Dense(5,activation='relu')) model.add(Dense(1,activation='sigmoid')) model.comp...
<p>Great questions. Answers:</p> <ol> <li><p>I think your theory is right; it's the dropout. That's the only layer with an element of randomness each run, so it's likely the culprit. Try removing that layer, leaving everything else fixed, and run multiple times. Check if the accuracy is the same.</p> </li> <li><p>Cross...
python|tensorflow|keras|neural-network
0
5,225
3,250,327
Python twisted asynchronous write using deferred
<p>With regard to the Python Twisted framework, can someone explain to me how to write asynchronously a very large data string to a consumer, say the protocol.transport object?</p> <p>I think what I am missing is a <code>write(data_chunk)</code> function that returns a <code>Deferred</code>. This is what I would like...
<p>As Jean-Paul says, you should use <a href="http://twistedmatrix.com/documents/10.1.0/core/howto/producers.html" rel="noreferrer">IProducer and IConsumer</a>, but you should also note that the lack of <code>deferredWrite</code> is a somewhat intentional omission.</p> <p>For one thing, creating a <code>Deferred</code...
python|asynchronous|twisted
8
5,226
35,029,083
.gt operator in Pandas DataFrame
<p>I have a master_reference object that corresponds to a file in a Pandas data frame with four columns of metrics. </p> <pre><code>d = {'one' : pd.Series([1000., 1001., 2000., 3000.], index=['A', 'B', 'C', 'D']), 'two' : pd.Series([1000., 1001., 2000., 3000.], index=['A', 'B', 'C', 'D']), 'three' : pd.Series...
<p>You are confusing yourself by the way you are chaining the operations there. The result of applying a boolean operation like <code>lt</code> is a series containing True or False at every position: True if the value satisfies the condition, false otherwise. Since True in Python is the same as the number one, in som...
python|python-2.7|pandas
4
5,227
35,105,664
Find PID of a daemon?
<p>Hey guys I am using elasticsearch and I ran it as a daemon...unfortunately now I don't know how to terminate it. whenever i go to 9200 i always get this: </p> <p>{ "status" : 200, "name" : "Patsy Walker", "cluster_name" : "elasticsearch", "version" : { "number" : "1.7.4", "build_hash" : "0d3159b9fc8...
<p>To find the PID, try this:</p> <pre><code>ps -ef | grep elasticsearch | xargs | awk '{print $2}' </code></pre> <p>To kill it:</p> <pre><code>sudo kill -9 PID </code></pre> <p>I have little experience with Mac. This link may help in finding a proper way to stop a daemon: <a href="http://elasticsearch-users.115913...
python|django|elasticsearch|pid
2
5,228
26,721,157
xpath syntax for ignoring whitespace and newlines
<p>I'm trying to use xpath on <a href="http://www.meetup.com/ny-tech/members/" rel="nofollow">this page</a> to capture the text "past few days" from:</p> <pre><code>&lt;li class="last"&gt; Last visited &lt;span&gt; past few days &lt;/span&gt; &lt;/li&gt; </code></pre> <p>I've tried several variants of the xpath ex...
<p>That page has a default namespace (<code>xmlns="http://www.w3.org/1999/xhtml"</code>). You'll either have to register that namespace and use a prefix in your xpath or use <code>local-name()</code> (and <code>namespace-uri()</code> if there is a possibility of elements from different namespaces having the same local ...
xpath|web-scraping|scrapy|python-requests
0
5,229
45,133,742
django.db.utils.ProgrammingError: cannot cast type text[] to jsonb
<p>I was trying to include JSONField in my model:</p> <pre><code>from django.contrib.postgres.fields import JSONField class Trigger(models.Model): solutions = JSONField(blank=True, null=True) </code></pre> <p>However, when I try to migrate the database, it gives the following error: </p> <pre><code>django.db.uti...
<p>You can update the migration file from </p> <pre><code>operations = [ migrations.AlterField( model_name='foo', name='bar', field=django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=dict), ), ] </code></pre> <p>to</p> <pre><code>operations = [ migrations.RemoveFie...
python|django|postgresql|django-models|django-jsonfield
18
5,230
45,098,390
Python: Generate List name from file
<p>Hi there I want to add a file to python with a few diffrent list in it like</p> <pre><code> File.txt: ListA=1,2,3,4 ListB=2,3,4 </code></pre> <p>I want to save the list in my script with the same name like in the File.txt. For example: ListA=[1,2,3,4] ListB=[2,3,4] After that I want to copy one list to a new li...
<p>You need to split the text by <code>=</code> sign which will seprate the list name with list contents then split the content by <code>,</code> </p> <pre><code>f=open('text.txt','r') a,b=f.read().split('=') print (a,list(b.split(',')) </code></pre>
python|list
1
5,231
61,302,874
Buttons created in loops returning wrong values
<p>I want to create a simple calculator with buttons from 1 to 9. I want to do that in two loops to be able to place them in a 3x3 square. But all buttons are returning the same value (9), and I can't figure out why. Anyone can help me with that? There is a code:</p> <pre><code>from tkinter import * root = Tk() e = ...
<p>This line is almost correct: </p> <pre><code>button = Button(root, text=k, padx=25, pady=25, command=lambda: button_click(k)) </code></pre> <p>try:</p> <pre><code>button = Button(root, text=k, padx=25, pady=25, command=lambda k=k: button_click(k)) </code></pre>
python|tkinter
1
5,232
61,593,561
Tkinter - Problem after add background in my project
<p><strong>Hi Guys I have Problem after add background in my project, I don't see anything but after resize I see background: I don't want to use ttk in my object.</strong></p> <p><strong>This is my code:</strong></p> <pre><code>from tkinter import (Button, Label, Frame) class HomeFrame(Frame): # Inherit Frame cla...
<pre><code>from tkinter import (Button, Label, Frame) class HomeFrame(Frame): # Inherit Frame class """Application main interface""" def __init__(self, parent=None): Frame.__init__(self, parent) self.root = parent # Define internal variable root self.root.configure(background='green') ...
python|python-3.x|tkinter|tkinter-canvas|tkinter-entry
0
5,233
57,927,673
How to make a script think it's running using a termnal?
<p>I am using a python script(x.py) that required to be run using terminal, but I have a large list that need to be iterate so I did a script that can call the x.py but I could not save the output due to sys.stdout.isatty(), how can I make python script think it runs using <code>atty</code> device?</p>
<p>I've used 'unbuffer' which is part of the 'expect' package. Search for unbuffer in this page: <a href="https://wiki.archlinux.org/index.php/Color_output_in_console" rel="nofollow noreferrer">https://wiki.archlinux.org/index.php/Color_output_in_console</a></p>
python|windows|stdout|tty|sys
0
5,234
56,307,382
Reading and printing values from tcx files in Python
<p>I am writing Python code to read a TCX file that downloads from my Polar Heart Rate monitor. I have tried using the xml.dom library and what I am getting appears to be some sort of class or memory location.</p> <p>The data I am looking at has heart rates (and other information) for each second in an exercise file.<...
<p>In order to get the text of the XML element you need to use the 'text' property of the element. </p> <p>(You can have a look at this code <a href="https://github.com/vkurup/python-tcxparser" rel="nofollow noreferrer">https://github.com/vkurup/python-tcxparser</a>)</p> <pre><code>while i &lt;= 10: print(trackP...
python|xml|dom
0
5,235
57,538,784
Why does my comprehension list do not work?
<p>Hello here is my code in Python :</p> <pre><code>test = [test[i-1]+3 if i &gt; 0 else 4 for i in range(0, 10)] </code></pre> <p>My problem is that I want to use a comprehension list for this :</p> <pre><code>test[0] = 4 test[i] = test[i-1]+3 if i &gt; 0 </code></pre> <p>I want to use a comprehension list to do t...
<p>You don't need any kind of recursion for this. The final list you want is</p> <pre><code>[4, 7, 10, 13, ...] # 4 + 0, 4 + 3, 4 + 6, 4 + 9, ... </code></pre> <p>which you can define simply as</p> <pre><code>test = [4 + 3*i for i in range(10)] </code></pre>
python|python-3.x
4
5,236
53,968,214
Feature extraction NLP
<p>I'm working on a reviews dataset. The problem is to fetch the important(number of times the same feature reviewed) positive and negative features of that specific product from the reviews.</p> <p>Ex: <code>some xyz car</code></p> <p><strong>positive:</strong> Great mileage, good looking, spacious etc</p> <p><stro...
<p>Some write-ups of the "Word Mover's Distance" calculation, for identifying similar sentences/phrases, use reviews as their dataset and seem to extract common themes and representative phrases well. </p> <p>See for example:</p> <p>"Navigating themes in restaurant reviews with Word Mover’s Distance" <a href="http://...
python|machine-learning|nlp|doc2vec
2
5,237
53,855,850
Issue "Remote end closed connection without response" when create multiple sessions
<p>Here is my situation:</p> <p>When I use a for loop to login some REST-Web site for about 100 ~500 times, if I use requests.post method to lanch my request, requests freamwork is aways issuing the titled Bug. code as follow:</p> <pre><code># coding: UTF-8 """ @Author: ITACHY @CreateTime:2018/12/19 17:26 """ im...
<p>If you have encountered this problem, please check if there is a NGINX proxy before the real website, if there is one, try to make a direct connection to the website, cause plenty cases of current issue are "proxy" caused; </p>
python|python-3.x|python-requests
0
5,238
58,275,534
NameError: name 'K' is not defined
<p>I'm following the guide to Transformers and the colab project <a href="https://colab.research.google.com/drive/1XBP0Zh8K4g_n0A2p1UlGFf3dij0EX_Kt" rel="nofollow noreferrer">https://colab.research.google.com/drive/1XBP0Zh8K4g_n0A2p1UlGFf3dij0EX_Kt</a></p> <p>but when I run the cell with the line <code>multi_head = bu...
<p>If you look at where <code>K</code> is being used you will see:</p> <p><code>K.expand_dims K.cumsum K.batch_dot</code></p> <p>These are Keras backend functions. The code is missing a <code>from keras import backend as K</code>, which I think is a standard abbreviation. </p>
python|tensorflow2.0
6
5,239
58,258,937
Python: TypeError: float() argument must be a string or a number, not 'function'
<p>I am working on Jupyter Web and below is my code.</p> <pre><code>def get_hist(img, bins): histogram = np.zeros(bins) for pixel in im: histogram[pixel] += 1 return get_hist hist = get_hist(flat, 256) plt.plot(hist) </code></pre> <p>And I am keep getting this problem.</p> <pre><code>TypeErro...
<p>You wrote a function that returns it's own function object. That won't provide much functionality or usability. You likely need to return <code>histogram</code>, which is what it seems your function intends to do.</p>
python
0
5,240
45,562,683
Tensorflow serving using the client
<p>I successfully created a server that receives a TF <code>saved_model</code>, but now I want to send it queries and get predictions. However, I'm having a hard time of understanding how the client works and how to implement it. All I found online is the <a href="https://www.tensorflow.org/serving/serving_basic" rel="...
<p>I really thank google to make tensorflow serving open source, it is so helpful for people like me to put prediction models into production. But I have to admit tensorflow serving did poorly in documentation, or, they assume people who use it should already have pretty good knowledge in tensorflow. I stuck for a long...
tensorflow|tensorflow-serving
3
5,241
45,497,156
TKinter button avoid double click
<p>I have a script that enables a Power supply after the user click "ONLY ONE TIME" the "START TEST" button, right after, I disable the button to avoid the "double click, however, I have noticed that "some how" if user perform a "double click" my application launch a second operation. </p> <pre><code>def starttest(): ...
<p>Each time you call <code>starttest()</code> function by pressing the inherent button, a new button widget is created: that is why it looks like you are able to click indefinitely on the <em>falsely</em> "same" button.</p> <p>You should create that button somewhere else in your program:</p> <pre><code>... power_sup...
python-3.x|tkinter
1
5,242
28,664,383
MongoDB not allowing using '.' in key
<p>I'm trying to save a dictionary containing a special character '.' in key portion to the MongoDB. The error is presented below, which clearly states that the key must not contain a special character '.'.</p> <pre><code>&gt;&gt;&gt; import pymongo &gt;&gt;&gt; client = pymongo.MongoClient('localhost') &gt;&gt;&gt; d...
<p>You can set <code>check_keys</code> to False according to the <a href="https://github.com/mongodb/mongo-python-driver/blob/master/pymongo/collection.py">source</a>:</p> <pre><code> test.insert(d,check_keys=False) def insert(self, doc_or_docs, manipulate=True, safe=None, check_keys=True, continue_on_er...
python|mongodb
29
5,243
68,779,348
get days from long timestamp csv file python
<p>I have a csv file with a long timestamp column (years):</p> <pre><code>1990-05-12 14:01 . . 1999-01-10 10:00 </code></pre> <p>where the time is in hh:mm format. I'm trying to extract each day worth of data into a new csv file. Here's my code:</p> <pre><code>import datetime import pandas as pd df = pd.read_csv(&quo...
<p>You are converting to datetime two times which is not needed</p> <p>Something like that should work</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.read_csv('data.csv') df['month_data'] = pd.to_datetime(df['timestamp'], format='%Y-%m-%d %H:%M') df['month_data'] = df['month_data'].dt...
python|pandas|dataframe|csv
1
5,244
41,499,618
How to match unordered things in pyPEG?
<p>I have the following file:</p> <pre><code>orange apple orange apple apple lime banana </code></pre> <p>Each type of fruit has a class to match it:</p> <pre><code>class Banana: grammar = .... class Apple: ... </code></pre> <p>I have to match each fruit unordered, I cannot tell upfront what will be the o...
<p>Use a <a href="https://fdik.org/pyPEG/grammar_elements.html#lists" rel="nofollow noreferrer">list</a>:</p> <blockquote> <p>A <code>list</code> instance which is not derived from <code>pypeg2.Concat</code> represents different options. They're tested in their sequence. The first option which parses is chosen, the ...
python|peg|pypeg
2
5,245
54,131,111
Exception has occurred: TypeError:only size-1 arrays can be converted to Python scalars
<p>That's my first post here. I'm doing a project in Python about Football Scores statistics and prediction. I got the ideas from <a href="https://github.com/dashee87/blogScripts/blob/master/Jupyter/2017-06-04-predicting-football-results-with-statistical-modelling.ipynb" rel="nofollow noreferrer">this project</a> and I...
<p>The problem is that your arrays for the bar plot are 2d arrays and you have to flatten them. This can be easily done using <code>.flatten()</code> which converts the 2d arrays in your code into 1-d arrays. If you look at <code>chel_home.values</code>, it looks like</p> <pre><code>array([[0.33333333], [0.2222...
python|pandas|matplotlib
1
5,246
25,783,266
django - {% blocktrans %} {{rendered_variable}} {% endblocktrans %}
<p>django trans is not working for me in this case: </p> <pre><code>{% blocktrans %} {{sign}} {% endblocktrans %} </code></pre> <p>the <code>{{sign}}</code> are coming from views.py and are Sunsigns like: </p> <pre><code>'Capricorn' 'Aquarius' 'Pisces' 'Aries' 'Taurus' 'Gemini' 'Cancer' 'Leo' 'Virgo' 'Libra' ...
<p><code>blocktrans</code> is for translating the text around a variable, but it won't translate the variable itself.</p> <p><a href="https://stackoverflow.com/questions/1813516/django-blocktrans-and-i18n-in-templates">This answer</a> can be helpful for you. More info in <a href="https://docs.djangoproject.com/en/dev/...
python|django
1
5,247
44,439,683
Canonical way to free string passed back from a c function in cffi?
<pre><code>ffi = FFI() C = ffi.dlopen("mycffi.so") ffi.cdef(""" char* foo(T *t); void free_string(char *s); """) def get_foo(x): cdata = C.foo(x) s = ffi.string(cdata) ret = s[:] C.free_string(cdata) return ret </code></pre> <p>If I pass a <code>char *</code> from c function to python, python sh...
<p>It turns out I don't need to copy <code>s</code>, <code>s</code> is already a copy of <code>cdata</code></p> <pre><code>def get_foo(x): cdata = C.foo(x) s = ffi.string(cdata) C.free_string(cdata) return s </code></pre>
python|cffi
3
5,248
44,528,474
How to get specific table from Word Doc using win32 COM?
<p>I am attempting to go through a word document and find a few specific tables among many tables. I know how to iterate through all tables using either the docx library or win32, found <a href="https://stackoverflow.com/questions/10366596/how-to-read-contents-of-an-table-in-ms-word-file-using-python">here</a>. However...
<p>I think the collection you're looking for is <code>doc.Paragraphs</code>.</p> <p><code>doc.ListParagraphs</code> only returns paragraphs that have list formatting, like bullets or numbers.</p> <p>There are other challenges involved, but that's the first mystery solved I believe :)</p>
python|ms-word|win32com|python-docx
0
5,249
24,113,001
Applying setStyle to QLabel in PySide/PyQt
<p>In PySide, I am trying to change the overall style of a simple GUI window (a QLabel object), as outlined at the PySide documentation:</p> <p><a href="http://srinikom.github.io/pyside-docs/PySide/QtGui/QStyle.html#detailed-description" rel="nofollow noreferrer">http://srinikom.github.io/pyside-docs/PySide/QtGui/QSty...
<p>The most helpful resource I found, which answered my question, was this wonderful gallery of widgets:</p> <p><a href="http://qt-project.org/doc/qt-4.8/gallery.html" rel="nofollow">Widget Gallery</a></p> <p>It shows the look of pretty much every type of widget under the different styles.</p> <p>It turns out my "pr...
python|qt|user-interface|pyqt|pyside
1
5,250
20,713,981
Python - AttributeError: 'tuple' object has no attribute 'read'
<p>I am working on a simple python client and server that can write code to a file as its sent. So far I have been stuck on this error: AttributeError: 'tuple' object has no attribute 'read'</p> <p>Here is the client's code:</p> <pre><code># CCSP Client # (C) Chris Dorman - 2013 - GPLv2 import socket import sys # S...
<p>You should read <a href="http://docs.python.org/2/library/socket.html#socket.socket.accept" rel="nofollow">some doc</a>. <code>accept()</code> returns a tuple not a file-like object.</p>
python
2
5,251
20,482,770
How can I convert my pygame game to an .exe
<p>I know py2exe isn't compatible with Python 3.3(which I use) I tried using cx_freeze it worked but I need to have my files with my .exe also. I have a folder that has images that I use for my game and without them the game doesn't work. Anybody know how I can convert my 3.3 pygame with a folder to an .exe? P.S I'm on...
<p>If you want to include other "data files" along with your code in the <code>.exe</code>, use a setup script to list all the files needed. These two links should help you: <a href="http://cx-freeze.readthedocs.org/en/latest/faq.html#using-data-files" rel="nofollow">FAQs- Using Data Files</a> and <a href="http://cx-fr...
python|pygame|py2exe|cx-freeze
1
5,252
20,799,403
Improving performance of Cronbach Alpha code python numpy
<p>I made some code for calculating Cronbach Alpha that works. But I am not too good using lambda functions. Is there a way to reduce the code and improve efficiency by using lambda instead of the svar() function and getting rid of some of the for loops by using numpy arrays? </p> <pre><code>import numpy as np def s...
<pre><code>def CronbachAlpha(itemscores): itemscores = numpy.asarray(itemscores) itemvars = itemscores.var(axis=1, ddof=1) tscores = itemscores.sum(axis=0) nitems = len(itemscores) return nitems / (nitems-1.) * (1 - itemvars.sum() / tscores.var(ddof=1)) </code></pre> <p>NumPy has a variance functi...
python|performance|numpy
10
5,253
20,521,873
Faster way to count number of string occurrences in a numpy array python
<p>I have a numpy array of tuples:</p> <pre><code>trainY = np.array([('php', 'image-processing', 'file-upload', 'upload', 'mime-types'), ('firefox',), ('r', 'matlab', 'machine-learning'), ('c#', 'url', 'encoding'), ('php', 'api', 'file-get-contents'), ('proxy', ...
<p>I think using <a href="http://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow">Counters</a> may be a good option in this case.</p> <pre><code>from collections import Counter c = Counter([i for j in trainY for i in j]) print c['php'] # Returns 2 print c.most_common(5) # Print the 5 mo...
python|arrays|string|performance|numpy
6
5,254
46,223,793
Python SQLite insert data from variables
<p>I am trying to add the contents of variables into a SQLite DB but I am getting an error of </p> <pre><code>sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type. </code></pre> <p>My code is:-</p> <pre><code>import requests import json import eventlet import os import sqlite3 #Get the curr...
<p>@roganjosh's comment fixed it! I needed to incude the DB transactions in the for loop as below:</p> <pre><code>import requests import json import eventlet import os import sqlite3 #Get the currect vuln_sets response = requests.get('https://vulners.com/api/v3/search/stats/') vuln_set = json.loads(response.text) vul...
python|json|sqlite
0
5,255
49,761,161
Python win32 client saving %20 instead of spaces
<p>I have an issue saving the pdf files. The code works to convert excel files to pdf, but it is saving all of my files with %20 instead of spaces. So "Fort Worth" would save as "Fort%20Worth".</p> <p>Here is the code below. Thanks.</p> <pre><code>import xlwings as xw import win32com.client curyq = "2017Q4" msa_lis...
<p>I had the same issue when running a similar code on a Windows machine. The path was using forward slashes. Using double backslashes solved the problem.</p> <p>To make it non OS specific I used the os and pathlib modules to format the path correctly:</p> <pre><code>path_to_pdf = os.fspath(Path(path_to_pdf)) </code></...
python|excel
1
5,256
21,355,394
?how to check if the user is logged in in python
<p>I am making a python script that executes when you log in. I would like to execute it when the user logs in locally. It says welcome and bla bla bla, but it also reads the number of unread emails and reads the first three subjects aloud. Is there any way that I can execute it when the user logs in?</p>
<p>You're asking a compound question.</p> <p>Your first question is really <code>How can I open a program/run a script when a user logs in?</code></p> <p>The answer is that it depends on which version of OS X you're using.</p> <p>This used to be done via a "login hook" pre 10.5. Now, the most straight forward way to...
python|macos|automator
0
5,257
70,281,086
How to add calculated fields in pandas pivot table
<p>Suppose I have a pivot like this:</p> <pre><code>import pandas as pd d = {'Col_A': [1,2,3,3,3,4,9,9,10,11], 'Col_B': ['A','K','E','E','H','A','J','A','L','A'], 'Value1':[648,654,234,873,248,45,67,94,180,120], 'Value2':[180,120,35,654,789,34,567,21,235,83], 'Value3':[567,21,235,83,248,45,67,94,1...
<p>Apply these transformations before the pivot:</p> <pre class="lang-py prettyprint-override"><code>df = df.groupby(['Col_A', 'Col_B']).sum() df = df.eval('V23 = Value2 / Value3')[['Value1', 'V23']] </code></pre> <p>Then apply the pivot and clean-up:</p> <pre class="lang-py prettyprint-override"><code>df.reset_index()...
python|pandas|pivot|pivot-table|calculated-field
1
5,258
70,162,838
How to sort an column in Python?
<p>I'm trying to open the demo.csv to convert it to an xlsx to sort column x, header name is called Birthplace, but I can't wrap my head around why the column doesn't want to sort.</p> <p>Its does everything fine but doesn't sort the column.</p> <pre><code>import os import time from pathlib import Path from selenium i...
<p>I think I understand the confusion. Pandas will read the CSV file but it will not automatically save the results. You will have to save the file explicitly using something like <code>df.to_excel</code> or <code>df.to_csv</code>.</p> <p>As OP wrote in their question, one can sort the dataframe using <code>.sort_value...
python|pandas
1
5,259
53,582,144
Wagtail admin - playing with urls
<p>I created in wagtail a model called Regbox in model.py and also RegboxModelAdmin in wagtail_hooks.py. Wagtail admin includes item Regbox in wagtail side bar menu. Then I programmatically created a new collection, a new group with permissions add, edit, delete Regbox and this group is assigned to new user after regis...
<p>Permissions in Django (and Wagtail by extension) are handled on a per model basis, not per instance. Therefore, giving edit permissions on the <code>Regbox</code> to a user will allow him/her to edit every instances of that model. There are a few exceptions in Wagtail (like the Page model).</p> <p>Anyway, you shoul...
python|django|wagtail
2
5,260
54,883,814
Using group by in regression to define x and y values in python
<p>Is it possible to group the data (for defining x and y variables) for running regression directly in regPlot (or any other seaborn feature)? I am unable to find an inbuilt feature of that sort.</p> <p>For example, in a column, I have a categorical variable "C", then I am trying to fit a regression line (with x and ...
<p>You need to group by your data with <code>pandas</code> first and then plot it with <code>seaborn</code>. Since you didn't provide your dataframe, I will use a seaborn sample dataset to demonstrate.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import seaborn as sns # load dataframe df = s...
python|python-3.x|seaborn
1
5,261
73,583,901
Predict with tensorflow lite input_data from CountVectorizer: ValueError: Cannot set tensor: Got value of type STRING but expected type FLOAT32
<p>I saved a Keras CNN with TFLiteConverter and also the CountVectorizer (scikit-learn) that was used during training of the same model using pickle.</p> <p>When I load both and try to predict the result of a new example I occur following error:</p> <p><code>ValueError: Cannot set tensor: Got value of type STRING but e...
<p>Finally, I got it running...</p> <p>I just had to make the <code>input_data</code> an array:</p> <pre><code>input_data = loaded_vectorizer.transform([html]).astype('float32') input_data = input_data.toarray() </code></pre>
python|tensorflow|scikit-learn|tensorflow2.0|tensorflow-lite
0
5,262
73,542,145
How to convert a pandas dataframe multicolumn to one single column
<p>I am trying to convert a pandas dataframe with different columns per year, to a pandas dataframe with one column with the value and other column with the year:</p> <p><strong>input</strong></p> <pre><code>column name: a, b, c, d column 2015: 1, 2, 3, 4 column 2016: 5, 6, 7, 8 </code></pre> <p><strong>Desired output<...
<p><a href="https://pandas.pydata.org/docs/reference/api/pandas.melt.html" rel="nofollow noreferrer"><code>pandas.melt</code></a> would do the job.</p> <pre><code>print(df) ### name 2015 2016 0 a 1 5 1 b 2 6 2 c 3 7 3 d 4 8 </code></pre> <pre><code>print(pd.melt(df, value...
python|pandas|dataframe
0
5,263
21,410,757
How I plot the linear regression
<p>I am trying to plot a graph with the calculated linear regression, but I get the error "ValueError: x and y must have same first dimension". This is a multivariate (2 variables) linear regression with 3 samples (x1,x2,x3).</p> <p>1 - First, I am calculating the linear regression correctly?</p> <p>2 - I know that t...
<p>The problem here is that you're creating a list <code>A</code> where you want an array instead. <code>m*A</code> is not doing what you expect.</p> <p>This:</p> <pre><code>A = np.array([x1, x2, x3]) </code></pre> <p>will get rid of the error.</p> <p>NB: multiplying a <strong>list</strong> <em>A</em> and an <stron...
python|matplotlib|math|regression|linear-regression
1
5,264
31,102,686
Django Inclusion Tag doesn't post to database
<p>I'm trying to build a form to save Names and Email Adresses to my database. However, it doesn't save... I've used an Inclusion Tag because I want to use the same form in different templates. This is my models.py:</p> <pre><code>class Contact(models.Model): FRAU = 'FR' HERR= 'HR' GENDER_CHOICES = ( ...
<p><code>Post</code> is a method of server request which is handled by views. </p> <p>Inclusion tag is rendered along with the page (that is during server response). Thus page context can not get <code>request.POST</code> - of cause, if you don't send POST deliberately as a context variable to the page (but it won't b...
python|django|inclusion
0
5,265
40,325,218
python bluetooth - check connection status
<p>I am using the bluetooth module for python <code>import bluetooth</code> which I believe is the PyBluez package. I am able to connect, send, and receive just fine from the bluetooth.BluetoothSocket class but my application is completely blind when it comes to the status of the connection.</p> <p>I want my applicat...
<p>If your SO is linux, you could use the <a href="http://linuxcommand.org/man_pages/hcitool1.html" rel="nofollow noreferrer">hcitool</a>, which will tell you the status of your bluetooth devices. </p> <p>Please find below a small Python snippet that can accomplish your need. You will need to know your bluetooth devic...
python|bluetooth|pybluez
4
5,266
28,931,274
Separating numbers from symbols in lists; python
<p>I got an assignment, but I'm stuck, I need to analyze a list and separate the numbers from the symbols and create 2 different lists, adding numbers to one list and symbols to the other. Right now I have this list:</p> <pre><code>[1, '+', '(', 2, '+', 3, ')'] </code></pre> <p>what I need is to have the other 2 list...
<p>Numbers are integers, symbols are simply strings:</p> <pre><code>numbers = [i for i in the_list if isinstance(i, int)] symbols = [i for i in the_list if isinstance(i, str)] </code></pre>
python|list
3
5,267
29,196,060
Have slug populate from title or create random - Django Form
<p>I would like the slug to be generated automatically from the title the user imports, or have random integers generated if the title is blank. The way I currently have it, the slug is supposed to be populated from the form title, but I get an error saying the form doesn't have a title field.</p> <p>So, I need to: </...
<p>This line is your problem:</p> <pre><code>new_slug = Photo.objects.get(slug=form.title) </code></pre> <p>You're setting the value of <code>new_slug</code> to a retrieved object, not a string. That isn't going to slugify. You probably just want this:</p> <pre><code>new_slug = form.title </code></pre> <p>But if yo...
python|django|django-models|django-forms|django-views
0
5,268
29,241,984
Solve for the positions of all six roots PYTHON
<p>I'm using Newton's method, so I want to find the positions of all six roots of the sixth-order polynomial, basically the points where the function is zero.</p> <p>I found the rough values on my graph with this code below but want to output those positions of all six roots. I'm thinking of using x as an array to inp...
<p>The traditional way is to use deflation to factor out the already found roots. If you want to avoid manipulations of the coefficient array, then you have to divide the roots out. </p> <p>Having found z[1],...,z[k] as root approximations, form </p> <pre><code>g(x)=(x-z[1])*(x-z[2])*...*(x-z[k]) </code></pre> <p>an...
python-2.7|numerical-methods|polynomial-math|newtons-method
1
5,269
29,128,059
Numpy: how to copy a matrix to a column of n-D array?
<p>I read an image and convert it to a grayscale one:</p> <pre><code>gs=cv2.imread('bgr.png',cv2.IMREAD_GRAYSCALE) </code></pre> <p>From <code>gs</code>, I want to create an empty picture which has a third dimension:</p> <pre><code>empty_image=numpy.zeros((gs.shape[0],gs.shape[1],3),dtype=numpy.uint8) </code></pre> ...
<p>From what I understand, you want to copy your greyscale image into the first channel of your 3-channel image. You can do that as follows:</p> <pre><code>empty_image[:, :, 0] = gs </code></pre> <p><code>empty_image[:, :, 0]</code> uses an index of zero in the third dimension (to select the first element), and selec...
python|numpy
0
5,270
8,813,539
How do I compare dates from Twitter data stored in MongoDB via PyMongo?
<p>Are the dates stored in the 'created_at' fields marshaled to Python datetime objects via PyMongo, or do I have to manually replace the text strings with Python Date objects? i.e. </p> <p><a href="https://stackoverflow.com/questions/2900674/how-do-i-convert-a-property-in-mongodb-from-text-to-date-type">How do I conv...
<p>you can parse Twitter's created_at timestamps to Python datetimes like so:</p> <pre><code>import datetime, pymongo created_at = 'Mon Jun 8 10:51:32 +0000 2009' # Get this string from the Twitter API dt = datetime.strptime(created_at, '%a %b %d %H:%M:%S +0000 %Y') </code></pre> <p>and insert them into your Mongo co...
python|mongodb|twitter|pymongo
17
5,271
8,621,527
Python 2.7.2 and Google App Engine SDK 1.6.1 on Win 7 Home Premium not working
<p>I have installed Python 2.7.2 (Win7 32-bit) and Google App Engine SDK 1.6.1 for Win7 on a 64-bit system running Win7 Home Premium. Default folder locations for both Python and GAE. When I try to run the <em>helloworld</em> project as described in the Google Python Getting Started doc, the Launcher's "browse" butto...
<p>The Google docs for setting up GAE with Python 2.7 have some issues. If you are trying to launch the basic "hello world" app through the GUI App Engine interface, after following the instructions, you are probably seeing red text and all the buttons are grayed out?</p> <p>If so, it is because there are errors withi...
python|windows|google-app-engine
3
5,272
52,416,558
Unable to add string when printing
<p>I can't seem to figure out how to fix my error. </p> <p>Pretty new to Python so if you can be as specific as possible, it helps.</p> <pre><code>print ('HStartX: ') + str(HSX) print ('LStartX: ') + str(LSX) print ('HStartY: ') + str(HSY) print ('LStartY: ') + str(LSY) print ('HendX: ') + str(HEX) print ('LendX: ') ...
<p>You should concatenate a string with another string, not with the returning value of <code>print</code> (which is always <code>None</code>):</p> <pre><code>print ('HStartX: ' + str(HSX)) </code></pre>
python
1
5,273
52,428,537
how to search for a specific from and to keyword in a file and print the sentence in python
<p>I am trying to get a file as an input and search for a special character. I am giving from and to keys as input. if the to keyword is in the next line i should print till the to keyword is found.</p> <pre><code>for line in contents: if line.startswith("*CHI: ") : line = line.strip("*") tokenize = li...
<p>If you can read the file and convert it into a string. We can use </p> <pre><code>string = "123123STRINGabcabc" def find_between( string, first, last ): try: start = string.index( first ) + len( first ) end = string.index( last, start ) return string[start:end] except ValueError: ...
python|regex|file|search
1
5,274
52,136,460
Power over integer in python 3
<p>Trying to compute a power of a long integer in Python 3.6.5, and I am getting 0. Is it the expected behavior? Then it contradicts the official docs.</p> <pre><code>In [16]: i Out[16]: 16777216 In [17]: i**2 Out[17]: 0 In [18]: float(i)**2 Out[18]: 281474976710656.0 </code></pre>
<p>This can happen only if <code>i</code> is not an <code>int</code>. It is possible to find the type of <code>i</code> by running:</p> <pre><code>print(type(i)) </code></pre> <p><hr> In Python, it is possible to define a class that looks like an int, and defines its own <code>__pow__()</code> methods. So without fur...
python
0
5,275
51,906,063
Distribution mean and standard deviation using scipy.stats
<p>I was trying to get the mean and standard deviation for log-normal distribution, where mu=0.4104857306 and sigma=3.4070874277012617, and I am expecting mean=500 and std=600. I am unsure what I have done wrong. Here are the code:</p> <pre><code>import scipy.stats as stats import numpy as np a = 3.4070874277012617 b ...
<p>The <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.lognorm.html" rel="nofollow noreferrer"><code>scipy.stats.lognorm</code></a> lognormal distribution is parameterised in a slightly unusual way, in order to be consistent with the other continuous distributions. The first argument is the sh...
python|numpy|scipy
3
5,276
51,606,048
Python Open CV overlay image on contour of a big image
<p>I have a big image of shape where i'm looking to overlap an image on a shape based on the contour </p> <p>I have this image <a href="https://i.stack.imgur.com/wbV38.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wbV38.png" alt="enter image description here"></a></p> <p>I have this contur where ...
<p>I have a working solution. Hope it is what you were looking for.</p> <p><strong>Code:</strong></p> <pre><code>import cv2 import numpy as np image = cv2.imread('C:/Users/524316/Desktop/shapes.png', 1) monkey = cv2.imread('C:/Users/524316/Desktop/monkey.png', 1) image2 = image.copy() image3 = image.copy() gray = ...
python|opencv
2
5,277
18,882,227
Organizing PDFs in pyPDF
<p>I have a question regarding Python and pyPdf. </p> <p>What I am attempting to do, is create a PDF(obviously) and then have it ordered in a certain way. So that every time I run my script, it sorts it in a certain way for me, regardless of when the files were created. </p> <p>If I have 7 files in my target folder, ...
<p>os.listdir returns a list of filenames in arbitrary order, so you'll have to order its elements as you desire before you process them. The sort method of the list class will let you do so. Assuming your suffixes 'a', 'b', ... are the order you want, sorting by the date part of the filename and then the suffix will g...
python|pdf
0
5,278
56,199,061
Dynamic multidimensional list in Python
<p>I want to create function which can insert a given value to a given index into a given array. It's quite simple with two-dimensional arrays:</p> <pre><code>def insertInto(index, array, value): are index in array? no: iterate over range (len(array) -&gt; index): insert None in...
<p>A way to simplify the problem would be to use recursive functions. That way variables stay in the scope and shouldn't erase each other.</p> <p>I did use <code>(index, *tail)</code> instead of a tuple based index for simplicity</p> <pre><code>def ensure_array_index(array, index): while len(array) &lt;= index: ...
python|arrays|multidimensional-array
1
5,279
67,348,207
How to sort decimals by Odd/Even (Python)
<p>I have this code:</p> <pre><code>def mrdot2(v): for x in v: if x % 2 == 0: print(&quot;Even&quot;) elif x % 2 == 1: print(&quot;Odd&quot;) mrdot2([2,4,6,23,68,5,3,2.4,29,4877.5423,8139,48.3,89.5,10.3,-7,-8]) </code></pre> <p>And everything works as usual (prints &quot;Even&quot; with even numb...
<p>If I understand correctly, you can determine if a number is even, odd or neither and print. Decimal numbers (decimal part different to 0) are not even or odd. Note that for example 5.0 = 5 in this special case. Maybe the following code can help you.</p> <pre><code>def function(myList): for number in myList: ...
python
1
5,280
36,360,167
When using python os.rmdir, get PermissionError: [WinError 5] Access is denied
<p>I'm building a file-transfer script, and the source cleanup function makes use of <code>os.rmdir('C:\\Users\\Grav\\Desktop\\TestDir0\\Om')</code>. This is the error I get:</p> <pre><code>PermissionError: [WinError 5] Access is denied: 'C:\\Users\\Grav\\Desktop\\TestDir0\\Om' </code></pre> <p>I checked the permissi...
<p>I had a same issue, could do it via <code>shutil</code> module.</p> <pre><code>import shutil shutil.rmtree('/path/to/your/dir/') </code></pre>
python|python-2.7|file-permissions
12
5,281
13,488,746
Memory Error When Parsing Large File - Python
<p>There have been questions asked about memory errors in Python, but I want to ask one more specific to my situation. I am new to programming and Python.</p> <p>When parsing a large text file (~8GB), the line</p> <pre><code>mylist = [line.strip('\n').split('|') for line in f] </code></pre> <p>resulted in "MemoryErr...
<p>The memory error is coming because you're trying to store your whole file in a list(which is in memory). So, try to work on each line instead of storing it:</p> <pre><code>for line in f: data = line.strip('\n').split('|') #do something here with data </code></pre>
python|list|memory
5
5,282
13,533,156
Get string source of Python xml ElementTree
<p>How would you get the source of an <code>ElementTree</code> as a string in Python?</p>
<pre><code>import xml.etree.ElementTree as ET tree = ET.parse(source) root = tree.getroot() ET.tostring(root) </code></pre> <p>Note that there may be formatting differences between the content of <code>source</code> and <code>ET.tostring(doc)</code>.</p>
python|xml|elementtree
9
5,283
21,982,136
(How) can I set session data from inside a django test?
<p>I'm relying on some session data for my django tests. I was wondering if i could still do that or if i need to rethink my logic.</p> <p>Anyway, i'm trying to set the session data like this:</p> <pre><code>self.client.session['last_page_id'] = unicode(self.t1_p5.id) response = self.client.post(final_page_path, fin...
<p>I don't know which version of Django you use but in some old docs it is written:</p> <blockquote> <p>To modify the session and then save it, it must be stored in a variable first (because a new SessionStore is created every time this property is accessed):</p> </blockquote> <p>Example:</p> <pre><code>def test_s...
python|django|session
1
5,284
22,095,527
Iterator inside for-loop: why is this not working?
<p>I have this piece of code, it's not working and I have no idea why.</p> <p>My data structure:</p> <ul> <li>"genes" is a dictionary with as key it's ID, as value multiple instances of the object Gene.</li> <li>the Gene object contains a similar dictionary with instances of the object "Transcript".</li> </ul> <p>Fi...
<p>Your code</p> <pre><code>ptrans = next(t for t in g.transcripts.values() if t.ID == parent) </code></pre> <p>almost certainly isn't doing what you think. I suspect that there are no items in <code>g.transcript.values()</code> that have the parent as their ID, since calling <code>next()</code> on an empty generator...
python|loops|for-loop|iterator
2
5,285
57,929,615
Python Dataframe how to create a new column values based on a condition
<p>My dataframe is given below</p> <p>df = </p> <pre><code>index element data1 data2 data3 0 M1 10 20 30 1 M1 40 50 60 2 M2 70 80 90 3 M2 100 120 130 4 M3 140 150 160 5 M3...
<h1>Solution</h1> <pre class="lang-py prettyprint-override"><code># Make element lists e1 = np.arange(1,26,3) e2 = e1 + 1 e3 = e1 + 2 element_list1 = [f'M{x}' for x in e1.tolist()] element_list2 = [f'M{x}' for x in e2.tolist()] element_list3 = [f'M{x}' for x in e3.tolist()] element_lists = [element_list1, element_lis...
python|pandas|dataframe
1
5,286
54,384,341
Replace alpha numeric in text using regex/replace in python
<p>I want to remove alphanumeric characters in a text. For ex I have text as given below:</p> <pre><code>text= I want to remove alphanumeric jhanb562nkk from the text. Remove alphanumeric from all the texts. uhufshfn76429 is very hard to figure out. </code></pre> <p><strong>Expected result</strong></p> <pre><code>re...
<p>You can use the following regex:<br> <code>[A-Za-z]+[\d]+[\w]*|[\d]+[A-Za-z]+[\w]*</code></p> <p>The function call would be:<br> <code>re.sub(rgx_str, '', text)</code></p> <p>Do note that this would leave a extra space wherever the alphanumeric text was cleared. A simple way to remove this is to run another regex ...
python|regex|replace
2
5,287
71,235,741
Unable to install pandas or other packages in linux virtual environment
<p>I am unable to install module pandas in my linux vm. I tried all ways to install it, but it says it has version 1.1.5 requirement already satistied. But when I try running the code, it says, no module found. The latest version of python in it is 2.7.3, but I want to install 3.8 or 3.7, but I'm unable to. Where am I ...
<p>Did you try installing python3 from your package manager? You can install python 3.9 from apt using the below command</p> <p><code>apt install python3 pip -y</code></p> <p>You can also install the below package to use python in the terminal instead of python3 every time</p> <p><code>apt install python-is-python3 -y<...
python|pandas
0
5,288
39,260,247
Faster RCNN:libcudart.so.7.0: cannot open shared object file: No such file or directory
<p>I get the following error when I run the demo from <a href="https://github.com/rbgirshick/py-faster-rcnn/tree/master" rel="nofollow">https://github.com/rbgirshick/py-faster-rcnn/tree/master</a> and all the other steps before demo has been done successfully:</p> <pre><code>mona@pascal:~/computer_vision/py-faster-rcn...
<p>While not a neat solution, I ended up changing the paths to use CUDA 7.0. For whatever reason, seems Faster RCNN currently is not compatible with CUDA 7.5 on Ubuntu 14.04. On Ubuntu 15.10 I had it work with CUDA7.5 with the same exact settings!!!!</p>
python|cuda|shared-libraries|caffe|cudnn
1
5,289
39,183,970
regex - swap two phrases around
<p>Python 3. Each line is constructed of a piece of text, then a pipe symbol, then a second piece of text. I want to swap the two pieces of text around and remove the pipe. This is the code so far:</p> <pre><code>p = re.compile('^(.*) \| (.*)$', re.IGNORECASE) mytext = p.sub(r'\2\1', mytext) </code></pre> <p>Yet for ...
<p>This should help you. (View demo on <a href="https://regex101.com/r/hW2kR9/2" rel="nofollow">regex101</a>)</p> <pre><code>(\S+)\s*\|\s*(.+) </code></pre> <p>Sub with:</p> <pre><code> \2\1 </code></pre>
python|regex|python-3.x
1
5,290
37,260,935
Resizing an image in Python using PIL
<p>I'm trying to resize an image in Python, and did the following:</p> <pre><code>from PIL import Image img = Image.open('1.jpg') img.resize((300,200)) img.save('image','jpeg') </code></pre> <p>In the result, the image remains the same size. Why is that? What could I be missing?</p> <p>Thanks.</p>
<p>Resize returns a new object, and you didn't assign it to anything. Use this instead:</p> <pre><code>img = img.resize((300,200)) </code></pre>
python|image
4
5,291
34,031,727
Python + TKinter + OMXPlayer window on top
<p>I own a raspberry pi 2 and i start learning Python. I would like to do something very basic : the window of my Python program on top of omxplayer window like a notification system.</p> <p>I have been able to make an "always on top" window with TKinter but when i launch omxplayer my window is no more on top. </p> <...
<p>My solution is to used Hello_font from the hello_pi examples on the raspberry pi.</p>
python|omxplayer
0
5,292
66,272,233
Linear Loss and Accuracy CNN graph
<p>I recently ran my CNN under various batch sizes and noticed that the smaller the batch sizes(32, 64), the higher the accuracy but the graphs looked like this:</p> <p><a href="https://i.stack.imgur.com/p8DUB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p8DUB.png" alt="Loss graph" /></a></p> <p><...
<p>Ideally (according to classic gradient descent method) you should use one batch (the whole of your dataset). But it is too slow and your dataset might not fit into memory. So we use approximation of gradient (Stochastic gradient descent method) - by splitting dataset by batches (see here - <a href="https://en.wikipe...
python|tensorflow|keras|conv-neural-network
0
5,293
72,691,781
Try Catch Exception in Python (Similar to Java)
<p>I'm pretty new to Python overall, but I know Java pretty well. I am trying to use the exceptions in Python, but I'm not quite sure how they work.</p> <p>In Java I would do this:</p> <pre class="lang-java prettyprint-override"><code>try { //Code inside } catch (Exception e) { continue; } </code></pre> <p>How ...
<p>While your own solution is correct Python, it is not quite the equivalent of the given Java code. Python's bare <code>except</code> catches all throwables (which extend from <code>BaseException</code> in Python), not just all exceptions. This includes things like <code>KeyboardInterrupt</code> (called by Ctrl+C) and...
python|exception|try-catch
2
5,294
72,741,712
Regex match word not immediately preceded by another word but possibly preceded by that word before
<p>I need to match all strings that contain one word of a list, but only if that word is not <strong>immediately</strong> preceded by another specific word. I have this regex:</p> <p><code>.*(?&lt;!forbidden)\b(word1|word2|word3)\b.*</code></p> <p>that is still matching a sentence like <code>hello forbidden word1</code...
<p>This one seems to work well :</p> <pre><code>^.*\b(?!(?:forbidden|word[1-3])\b)\w+ (word[1-3]).*$ </code></pre> <p><code>\b(?!(?:forbidden|word[1-3])\b)\w+</code> checks for multiple following words that are not <code>forbidden</code> or <code>word[1-3]</code>.</p> <p>So it matches <code>hi forbidden hello word1 tes...
python|regex
1
5,295
72,516,561
Delete every fourth line in a .txt file in Python
<p>I have a .txt file in which I have multiple lines of code which looks like this:-</p> <pre><code>[03-Jun-22 06:32 AM] flylineman#0052 9fSQR7M1aS95wtmDpsRTvzKJzbP49dngMVn58rG2Usxo [03-Jun-22 06:32 AM] Doughnut#6155 AM3k8ggVkRgZrYfRCnon14wy2qtbso5HYRiynwvM5eFS [03-Jun-22 06:33 AM] Antares#4605 7apq5QKC3bmVbkWRd5ke...
<p>What about deleting every line that starts with &quot;[&quot;?</p> <pre class="lang-py prettyprint-override"><code>with open(&quot;test.txt&quot;, &quot;r&quot;) as f: lines = f.readlines() with open(&quot;test.txt&quot;, &quot;w&quot;) as f: for line in lines: if not &quot;[&quot; in line and line....
python|cmd|txt
3
5,296
39,857,757
Fetch HTML From URL in Python
<p>I am trying to read the <code>HTML</code> contents of a <code>URL</code> with <code>Python</code>. To fetch the <code>HTML</code> contents of a <code>URL</code>, would I use the module <code>wget</code>, <code>urllib</code> or a different module entirely? </p> <p>After Answers: I will use the <code>urllib</code> m...
<p>Here is a sample to get you started with <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a>:</p> <pre><code>import requests resp = requests.get('http://httpbin.org/get') if resp.ok: print (resp.text) else: print ("Boo! {}".format(resp.status_code)) print (resp...
python|html|url
3
5,297
38,848,537
Sortin apache log with Python
<p>For example I have this simple apache log:</p> <pre><code>192.168.1.1 GET /index.php 192.168.1.1 GET /pilt.png 192.168.1.1 GET /index.php 192.168.1.5 GET /index.php 192.168.1.5 GET /pilt.png 192.168.1.7 GET /index.php 192.168.1.7 GET /index.php 192.168.1.7 GET /index.php 192.168.1.7 GET /kaust/index.php 192.168.1.7...
<p>This is how it will be done : </p> <pre><code>x = open('PATH_TO_FILE').read() from itertools import groupby from operator import itemgetter x = x.split('\n') for i in range(len(x)): x[i] = x[i].split(' ') j = 0 for elt, items in groupby(x, itemgetter(0)): j += 1 k = 0 print elt, items for i i...
python|apache|python-2.7
0
5,298
38,835,352
Joining Array In Python
<p>Hi I want to join multiple arrays in python, using numpy to form multidimensional arrays, it's inside of a for loop, this is a pseudocode</p> <pre><code>import numpy as np h = np.zeros(4) for x in range(3): x1 = some array of length of 4 returned from a previous function (3,5,6,7) h = np.concatenate((h,x1), a...
<p>You need to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html" rel="nofollow">vstack</a>. It allows you to stack arrays. You take a sequence of arrays and stack them vertically to make a single array</p> <pre><code> import numpy as np h = np.zeros(4) for x in range(3): x1 =...
python|arrays|numpy
1
5,299
40,454,897
Simple algorithm to move from one tile to another using only a chess knight's moves
<p>I have a problem shown below that wants to find the quickest way to get between any two points by using only the moves of a knight in chess. My first thought was to us the <code>A*</code> algorithm or <code>Dijkstra's</code> algorithm however, <strong>I don't know how to make sure only the moves of a knight are used...
<p>Approach the problem in the following way:</p> <p><strong>Step 1</strong>: Construct a graph where each square of the chess board is a vertex.</p> <p><strong>Step 2</strong>: Place an edge between vertices exactly when there is a single knight-move from one square to another.</p> <p><strong>Step 3</strong>: Apply...
python|algorithm|path-finding
2