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
9,000
62,345,912
tensorflow Optimizer: Attempting to use uninitialized value fc.bias/Momentum
<p>Here is the thing.</p> <p>I build a trained network and save .meta and .data in ckpt. The optimizer is MomentumOptimizer:</p> <p><code>tf.train.MomentumOptimizer(learning_rate=lr, momentum=0.9, name='Momentum')</code>, which is also saved in .meta.</p> <p>But I forget to save paramters to do with Momentum, So wh...
<p><code>momentum=0.9</code>is saved when saving the model, so don't worry about it. Or you can make <code>momentum</code> a placeholder so you can load whatever you want when resotring models.</p>
python|tensorflow|optimization|deep-learning|momentum
0
9,001
62,182,599
Get lastest values periodically in column
<p>Here is an example of my <em>pandas</em> based data:</p> <pre><code>print(df) country cases date 2020-01-22 Austria 0 2020-01-23 Austria 0 2020-01-24 Austria 0 .... 2020-05-31 Austria 0 2020-06-01 Austria 1 2020-06-02 Austria 0...
<p>if you want them as a dataframe, you can do <code>groupby</code> and <code>tail</code> like:</p> <pre><code>df.sort_values(['country','date']).groupby('country').tail(3) country cases date 2020-05-31 Austria 0 2020-06-01 Austria 1 2020-06-02...
python|pandas
3
9,002
65,729,276
When creating lists, it seems that forms like [[False] * 3] * 3 only copies the references?
<p>I create a list using the below codes.</p> <pre class="lang-py prettyprint-override"><code>a = [[False] * 3] * 3 </code></pre> <p>which creates a 3x3 matrix with all elements of <code>False</code> value.</p> <p>And when I changed <code>a[0][0]</code> to be <code>True</code> using <code>a[0][0] = True</code>, the res...
<ul> <li><code>[False] * 3</code> gives us a list of 3 references of the same <code>False</code>, but since boolean is immutable, each one of those is independent.</li> <li><code>[[False] * 3] * 3</code> gives us a list of 3 references of the same <code>[False] * 3</code>, and since list is mutable, those 3 lists are a...
python|list
1
9,003
57,796,041
Hourly time series forecast
<p>I'm taking a course on <a href="https://www.udemy.com/python-for-time-series-data-analysis/learn/lecture/13773072#overview" rel="nofollow noreferrer">Udemy</a> to learn a little bit of Time Series prediction and I'm trying to run this piece of code, with hourly data from one year:</p> <pre><code>from statsmodels.ts...
<p>You are creating a correct index on a dataframe called <em>ts_data</em>, but you are fitting your model on a different dataframe called <em>train</em>.</p> <p>Try looking at the index of the <em>train</em> dataframe and see if it is in the right format.</p>
python|pandas|time-series|statsmodels
0
9,004
56,042,158
snakemake: correct syntax for accessing dictionary values
<p>Here's an example of what I am trying to do:</p> <pre><code>mydictionary={ 'apple': 'crunchy fruit', 'banana': 'mushy and yellow' } rule all: input: expand('{key}.txt', key=mydictionary.keys()) rule test: output: temp('{f}.txt') shell: """ echo {mydictionary[wildcards.f]} &gt; ...
<p>I'm pretty sure the bracket markup can only replace variables with string representations of their values, but does not support any code evaluation within the brackets. That is, <code>{mydictionary[wildcards.f]}</code> will try to look up a variable literally named <code>"mydictionary[wildcards.f]"</code>. Likewise...
python|snakemake
5
9,005
54,159,139
declare a value is not there after x amount of tries
<p>I am trying to create a script where it checks a text file and checks if values 'names' contains names or not after x amount of tries.</p> <p>For now I have managed to create a script that opens the text file which contains a json format. I have also added a counter that checks if the names is empty after x amount ...
<pre><code>import json import time count = 0 last_names = [] while True: with open('./test.txt', 'r') as f: new_product_values = json.load(f) if not new_product_values['names']: count += 1 time.sleep(1) elif new_product_values['names']!=last_names: print("NEW NAMES!") ...
python|json|for-loop
1
9,006
54,552,113
Calling a function from HTML
<p>HTML:</p> <pre><code>&lt;button type="button" class="btn btn-primary"&gt;Notifications &lt;span class="badge badge-light"&gt;&lt;/span&gt; &lt;/button&gt; </code></pre> <p>python:</p> <pre><code>def notif(): not_num = False if count &gt; 0: return count else return not_num def co...
<p>You probably need to use built-in <code>if</code> template tag.</p> <p>Something like:</p> <pre><code>{% if notifications %} &lt;button type="button" class="btn btn-primary"&gt;Notifications ({{ notifications|length }}) &lt;span class="badge badge-light"&gt;&lt;/span&gt; &lt;/button&gt; {% else %} ...
html|django|python-3.x
3
9,007
47,958,892
How to calculate the presence time of student during a class session with image processing
<p>I am trying to calculate the total presence time of students using face recognition. Such that at the end of class i can get two things: 1, total time a student was present. 2, from which time to which time he was present, and same for when he was not present(i.e. 9:00-9:20(Present), 9:20-9:22(not present), 9:22-9:4...
<p>You could store each observation in a row instead of a column. Such a table looks like this:</p> <pre><code> classId | studentId | observationTime | present ---------------------------------------------------- 1 1 9:00 p 1 1 9:02 p 1 ...
python|database|image-processing|logic
0
9,008
64,271,351
Iterating through big data with pandas, large and small dataframes
<p>This is my first post here and it’s based upon an issue I’ve created and tried to solve at work. I’ll try to precisely summarize my issue as I’m having trouble wrapping my head around a preferred solution. #3 is a real stumper for me. <img src="https://i.stack.imgur.com/vpLdQ.png" alt="Error" /></p> <ol> <li><p>Grab...
<p>I think the <code>groupby</code> function will work:</p> <pre><code>df.groupby('session_id')['duration'].sum() </code></pre> <p>More info here: <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html...
python|pandas|dataframe
2
9,009
55,746,528
Create several columns with default values in Salesforce
<p>I have a dataframe that looks like 1000 rows, 10 columns</p> <p>I want to add 20 columns with only one single value in each column (what I call a default value)</p> <p>Therefore, my final df would be 1000 rows, with 30 columns</p> <p>I know that I can do it 30 times by doing:</p> <pre><code>df['column 11'] = 'de...
<p>One way to do so:</p> <pre><code>df_len = len(df) new_df = pd.DataFrame({col: [val] * df_len for col,val in your_dict.items()}) df = pd.concat((df,new_df), axis=1) </code></pre>
python|pandas|dataframe
2
9,010
73,343,529
Django google kubernetes client not running exe inside the job
<p>I have a docker image that I want to run inside my django code. Inside that image there is an executable that I have written using c++ that writes it's output to google cloud storage. Normally when I run the django code like this:</p> <pre><code>container = client.V1Container(name=container_name, command=[&quot;//us...
<p>Apparently for anyone having a similar issue, we fixed it by adding the command we want to run at the end of the <code>Dockerfile</code> instead of passing it as a parameter inside django's container call like this:</p> <pre><code>cmd[&quot;entrypoint.sh&quot;] </code></pre> <p>entrypoint.sh:</p> <pre><code>xvfb-run...
python|django|kubernetes|google-cloud-platform|google-cloud-storage
5
9,011
73,204,176
How to move only specific blocks of XML to a new XML file?
<p>I'm trying to filter an XML such that only specific blocks of XML would be needed I have the original XML like this</p> <pre><code>&lt;PROJECT&gt; &lt;TASK&gt; &lt;INSTALL_METHOD installer=&quot;TYPE 1&quot; /&gt; &lt;FILE&gt; &lt;INSTALL_OPTIONS option=&quot;signature&quot;/&gt; &lt;INSTALL_...
<p>For each <code>TASK</code>, check the value of the <code>installer</code> attribute on the <code>INSTALL_METHOD</code> child element. Remove the <code>TASK</code>s for which the value is not &quot;TYPE 1&quot; or &quot;TYPE 3&quot;.</p> <pre class="lang-py prettyprint-override"><code>import xml.etree.ElementTree as...
python|xml|xml-parsing|elementtree
0
9,012
73,390,287
How to get input for functions with tkinter?
<p>How can I pass the input I receive with Tkinter to the getLink function? I want it to send the input to the function when I press the button.</p> <pre class="lang-py prettyprint-override"><code>import tkinter as tk import requests pencere=tk.Tk() pencere.title(&quot;İnstagram Share App&quot;) pencere.geometry(&quot...
<p>You are calling the function and only returning the value ! Which you shouldn't in the below line <code>b1=tk.Button(text=&quot;Link&quot;,bg=&quot;black&quot;,fg=&quot;white&quot;,font=&quot;Arial 20 bold&quot;,command=buton_link()) </code></p> <p>Instead you should just write the name of function in command argume...
python|tkinter
0
9,013
50,107,749
Keep prompting user for correct directory to file, store input in variable
<p>This is the beginning of my code that takes a dataset and plots it using matplotlib. However, I want to create a while loop that prompts the user to provide the correct path or directory to the file (e.g. /Users/Hello/Desktop/file.txt). </p> <p>While the user does not inputs a correct path, the loop should keep pro...
<p>Write a function. Your code has multiple problems, but I guess you want something like this. </p> <pre><code>def prompt_for_filepath(): """ Prompt the user for the right path to the file. If the file is not there, ask again. If the path is correct, return it. """ while True: ...
python
1
9,014
66,600,444
Select points with constant distance along a list, python
<p>I am new with geospatial python libraries and distance calculations and I would like to avoid for loops that could be very costly.</p> <p>I have the lists of the latitude and longitude and I need to create another a list of the points at fixed dist=5 sequentially along the trajectory.</p> <pre><code>list_x = [] list...
<p>SOLVED</p> <p>Explained in &quot;Splitting at a specified distance&quot; in the link <a href="https://stackoverflow.com/questions/62990029/how-to-get-equally-spaced-points-on-a-line-in-shapely">How to get equally spaced points on a line in Shapely</a></p> <p>In this post how <a href="https://stackoverflow.com/questi...
python|pandas|numpy|geospatial|geopandas
0
9,015
64,148,371
Discord Bot can only see itself and no other users in guild
<p>I have recently been following <a href="https://realpython.com/how-to-make-a-discord-bot-python/" rel="noreferrer">this tutorial</a> to get myself started with Discord's API. Unfortunately, when I got the part about printing all the users in the guild I hit a wall.</p> <p>When I try to print all users' names <strong...
<ol> <li><p>Enable the <strong>server members intent</strong> near the bottom of the <strong>Bot</strong> tab of your <a href="https://discord.com/developers/applications" rel="nofollow noreferrer"><strong>Discord Developer Portal</strong></a>:</p> <p><a href="https://i.stack.imgur.com/Znf8s.png" rel="nofollow noreferr...
python|python-3.x|pycharm|discord|discord.py
17
9,016
52,909,589
How do you fix the Nameerror for this function?
<pre><code>def make_greeting(name, greeting = "Hello"): return (greeting + " " + name + "!") # get name and greeting, send to make_greeting print(make_greeting(get_name(), get_greeting())) def get_name(): name_entry = input("enter a name: ") return name_entry def get_greeting(): greeting_entry = inp...
<p>move print line at the bottom:</p> <pre><code>def make_greeting(name, greeting = "Hello"): return (greeting + " " + name + "!") def get_name(): name_entry = input("enter a name: ") return name_entry def get_greeting(): greeting_entry = input("enter a greeting: ") return greeting_entry # get n...
python
0
9,017
53,084,688
Python complex operation with dataframe
<p>I have the following dataframe:</p> <pre><code>&gt; df = pd.DataFrame({'A':[1,1,1,1,0],'B':[1,0,1,1,0],'C':[1,1,1,0,0],'D':[1,1,0,0,0],'E':[1,0,0,0,0]}) &gt; print(df) A B C D E 0 1 1 1 1 1 1 1 0 1 1 0 2 1 1 1 0 0 3 1 1 0 0 0 4 0 0 0 0 0 </code></pre> <p>I want to produce a new data...
<p>You can define a simple function to find the first index where 0 occurs, and return an array with 1's filled to that position. Also need to account for rows with no zeros and send back all 1's. </p> <pre><code>def findOnes(x): res = np.zeros(len(x)) fstZero = np.where(x==0)[0] if len(fstZero) == 0: ...
python|python-3.x|python-2.7
1
9,018
65,063,685
Fancy indexing in tensorflow
<p>I have implemented a 3D CNN with a custom loss function <code>(Ax' - y)^2</code> where x' is a flattened and cropped vector of the 3D output from the CNN, y is the ground truth and A is a linear operator that takes an x and outputs a y. So I need a way to flatten the 3D output and crop it using fancy indexing before...
<p>Try this code:</p> <pre><code>import tensorflow as tf y_pred = tf.random.uniform((10, 145, 59, 82)) indices = tf.random.uniform((396929,), 0, 145*59*82, dtype=tf.int32) voxels = tf.reshape(y_pred, (-1, 145 * 59 * 82)) # to flatten and reshape using Fortran-like index order voxels = tf.gather(voxels, indices, axis=...
python|tensorflow|matrix-indexing
0
9,019
65,445,923
Calling function using label Tkinter python
<p>Working on a unit converter using Tkinter python, I want to change all other units according to the input unit but can't able to call that function which later configures other labels of units.</p> <pre><code>mainEntry = Entry(width=15,font=&quot;arial 15 bold&quot;) mainEntry.grid(row=0,column=0) </code></pre> <p>T...
<p>Set a variable to <code>Entry</code> widget and use the <code>trace</code> method to detect any changes in the text and update labels accordingly.</p> <p>Here is an example:</p> <pre class="lang-py prettyprint-override"><code>from tkinter import * def change_lbl(*args): lbl['text']=var.get() root = Tk() var = ...
python|tkinter
0
9,020
65,286,707
FireFox geckodriver Not callable in selenium
<p>Hello i try to use FireFox geckodriver in python by Selenium Exactly like this :</p> <pre><code>driver = webdriver.firefox() siteAddress='https://stackoverflow.com' driver.get(siteAddress) </code></pre> <p>But i get this error:</p> <pre><code>'module' object is not callable </code></pre> <p>Also my WebDriver is near...
<p><code>webdriver.firefox</code> is <em>module</em> while you need to use <code>webdriver.Firefox</code> <em>class instance</em></p> <p>Try to replace</p> <pre><code>driver = webdriver.firefox() </code></pre> <p>with</p> <pre><code>driver = webdriver.Firefox() </code></pre>
python|python-3.x|selenium|web-scraping|geckodriver
2
9,021
65,165,141
Train test split for ensuring all categories are included in train set
<p>Let's say there are some 20 categorical columns in the data, each having a different set of unique categorical values. Now a train test split has to done, and one needs to ensure that all unique categories are included in the train set. How can it be done? I have not tried yet, but should all these columns be includ...
<p>Yes. That's correct.</p> <p>For demonstration, I'm using <a href="https://www.kaggle.com/dansbecker/melbourne-housing-snapshot/home" rel="nofollow noreferrer">Melbourne Housing Dataset</a>.</p> <pre><code>import pandas as pd from sklearn.model_selection import train_test_split Meta = pd.read_csv('melb_data.csv') Me...
python|categorical-data|train-test-split
1
9,022
72,003,898
In python, how to reshape a dataframe so that some datetime columns become rows
<p>In a pandas dataframe, I want to transpose and agrupate datetime columns into rows.</p> <p>Like this (there are about 12 date columns):</p> <pre><code> Category Type 11/2021 12/2021 0 A 1 0.0 20 1 A 2 NaN 13 2 B 1 5.0 7 3 B 2 20.0 4 </...
<p>You could do:</p> <pre><code>(df.melt(['Category', 'Type'], var_name = 'Date'). pivot(['Date', 'Category'],'Type').reset_index()) Date Category value Type 1 2 0 11/2021 A 0.0 NaN 1 11/2021 B 5.0 20.0 2 12/2021 A 20.0 13.0 3 12...
python|pandas|time-series|pivot-table
0
9,023
68,726,867
Maximum path sum with prime number check in python
<p>There is a task similar to project euler 18, but this time you can only walk over non prime numbers. Task is:</p> <p>You will have a triangle input below and you need to find the maximum sum of the numbers according to given rules below;</p> <pre><code> 1 8 4 2 6 9 8 5 9 3 </code></pre> <p>1-You will...
<p>I actually tried to solve it with multiple ways, but all other methods that I tried are way way way slower than this one. I'm pretty sure this is not the best method, but it works anyway. To call the function you need <code>solvearray(num)</code> and the num must always have the same format as the one you gave as an...
python|dynamic|primes
0
9,024
71,450,155
Accept or reject cookies with Selenium
<p>I am trying to login to my Garmin connect account. I can enter the website by cannot get rid of the window to accept or reject cookies. Would you have a solution for this ? Here is my code: Thanks a lot!</p> <pre><code>from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver...
<p>You can try to close the popup window, get the xpath of the close button and if it's regular and appears always at loading of page you can close it.</p>
python|selenium-webdriver|cookies
0
9,025
71,605,777
How to convert multiple sheets in an excel workbook to csv files in python
<p>I have a excel workbook that contains 8 sheets with different alphabetical names. i want to create csv files for each of these sheets and store it in a folder in python. Currently i am able to do this for a single sheet from the workbook but i am struggling to make a workflow on how to convert multiple sheets and st...
<p>If you want to get all of the sheets, you can pass <code>sheet_name=None</code> to the <code>read_excel()</code> call. This will then return a dictionary containing each sheet name as a key, with the value being the dataframe. With this you can iterate over each and create separate CSV files.</p> <p>The following ex...
python|excel|pandas|csv
2
9,026
71,743,628
cant connect make request from fastapi container to kafka container
<p>I have two containers one is kafka container open port 9092:9092 and another is Fastapi container. If I don't dockerize Fastapi, I can make rest api request to fastapi to kafka. It sends message to kafka via fastapi. But when I dockerize fastapi can't connect fastapi container to kafka container. I cant run fastapi ...
<blockquote> <p>cant run fastapi docker file with -p 8000:8000 -p 9092:9092 it says 9092 is already used.</p> </blockquote> <p>Remove it then. Unclear why you need port 9092 on your API, anyway ; it's not the Kafka service.</p> <p>Without seeing your complete Kafka client code, it's hard to say what your other problems...
python|docker|apache-kafka
0
9,027
10,261,551
TypeError: must be dict, not str
<p>Hey guys I was trying to use the argument variable in Python however am unable to execute the program at the terminal.</p> <p><strong>Program:</strong></p> <pre><code>from sys import argv script,first,second,third = argv print "The script is called:", script print "Your first variable is:", first print "Your sec...
<p><a href="http://docs.python.org/library/functions.html#execfile" rel="nofollow"><code>execfile()</code></a> doesn't take command arguments. Try using <a href="http://docs.python.org/library/subprocess.html" rel="nofollow"><code>subprocess</code></a> instead.</p>
python
4
9,028
62,762,801
Spyder 4.0.1(python 3.7) cannot import class Ui_MainWindow from Qt designer autogenerated module
<p>I am still very new to python and trying to write a small program that contains a Main Window and a couple of pop-up dialog boxes. The older version of spyder (3.x.x, python 3.6.x) seems to work well with the code, but after I switched to the newest version of spyder 4.0.1(python 3.7) by installing the newest anacon...
<p>Found an answer right after this was posted. It turned out there is a python file named exactly the same in the C:\Users/myusername. After deleting that file, python is again searching the current folder as a higher priority.</p>
python|anaconda|pyqt5|spyder
0
9,029
62,841,564
What value I need to give for kwargs here?
<p>I'm converting my code: <br> <code>start_new_thread(clientthread, (conn, addr))</code> from python 2<br> Using code from internet:</p> <pre><code>threading.Thread(target=some_callable_function, args=(tuple, of, args), kwargs={'dict': 'of', 'keyword': 'args'}, ).start() </code></pre> <p>Can you help ...
<p>It's an optional argument and in your case you should leave it blank. It's for <a href="https://book.pythontips.com/en/latest/args_and_kwargs.html#usage-of-kwargs" rel="nofollow noreferrer">named arguments</a> which you don't have.</p>
python|python-3.x|multithreading|python-2.7
2
9,030
67,392,024
(Python) name 'curr' is not defined
<pre><code>@socketio.on('disconnect') def disconnect_details(): for room_num in room_users_counter: curr = 0 expected_num = room_users_counter[room_num] emit(f&quot;{room_num}$attendance&quot;, broadcast=True, include_self=False) @socketio.on(&quot;here&quot;) def here(_room_...
<p>You want <code>nonlocal</code>, not <code>global</code> since <code>curr</code> is a local variable (local to <code>disconnect_details</code>), not a global one.</p> <pre><code>def here(_room_num): nonlocal curr if _room_num == room_num: curr += 1 </code></pre>
python|flask|error-handling
0
9,031
60,566,838
how to convert rgb value to a integer number based on a map in python
<p>I have a large RGB image, I want to convert each RGB value to an index_id based on a map. I am doing that as following but it is very slow. is there a faster way to do it?</p> <pre><code>NewDic = OrderedDict([ ((0,0,0), 0), ((20,20,20), 1), ((100,20,3),2) ]) ann = Image.open(im...
<p>Do you need a specific mapping otherwise you could try a direct mapping.</p> <pre><code>ann = Image.open(img_rgb) ann = np.asarray(ann) # define newann as: newoann = ann[:, :, 0] + ann[:, :, 1] * 256 + ann[:, :, 2] * 256**2 # Then do the mapping </code></pre> <p>This will lead to a unique index for every RGB Value...
python|image-processing|matrix|computer-vision
0
9,032
63,735,989
What does this warning message mean, tensorflow:Efficient allreduce is not supported for 4 IndexedSlices?
<p>I am using tensorflow V2.3 and the server has 2 GPUs. With MirroredStrategy, I get the following warning message:</p> <blockquote> <p>tensorflow:Efficient allreduce is not supported for 4 IndexedSlices</p> </blockquote> <p>How does it impact my computing? What do I have to do to improve the situation? I use 'nvtop' ...
<p>Currently, MirroredStrategy.reduce will do a concatenation of IndexedSlices on one device, and broadcast the result back to all GPUs. This is not efficient, hence the warning. This is a known limitation and the current suggestion is to use MultiWorkerMirroredStrategy, which has a slightly better implementation for h...
tensorflow|gpu|tensorflow2.0
2
9,033
18,176,050
Programatically determine if a user is calling code from the notebook
<p>I'm writing some software that creates matplotlib plots of simulation data. Since these plotting routines are often running in a headless environment, I've chosen to use the matplotlib object oriented interface explicitly assign canvases to figures only just before they are saved. This means I cannot use pylab or p...
<p>Answerd many time : No you cant.</p> <p><a href="https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-is-executed-in-the-ipython-notebook">How can I check if code is executed in the IPython notebook?</a></p> <p>Same kernel can be connected to notebook, qtconsole and terminal at the same time, even ...
matplotlib|ipython
1
9,034
17,814,913
How to remove lines from a large file
<p>I have a large file with each line of the form</p> <p><code>a b c</code></p> <p>I would like to remove all such lines where there does not exist another line either like</p> <p><code>b d e</code> </p> <p>or <code>d a e</code></p> <p>with <code>abs(c - e) &lt; 10</code>.</p> <p><code>a</code>, <code>b</code>, <...
<p>I don't know if this can be done in linear time. It is straightforward to do it in O(n·log n) time if there are n triplets in the input. Here is a sketch of a method, in a not-necessarily-preferred form of implementation:</p> <ol> <li><p>Make an array of markers M, initially all clear. </p></li> <li><p>Create an ...
python|algorithm
3
9,035
69,259,702
Efficient element wise comparison between a pandas frame and a list
<p>Suppose that I have 2 objects:</p> <ul> <li><code>A</code> is a list of names</li> <li><code>B</code> is a pandas frame with 3 columns: 'name','friend1','friend2', which list a person's name and the names of their 2 best friends</li> </ul> <p>For my application, I would like to know: for each person in <code>A</code...
<p>You can try this:</p> <pre><code>import numpy as np import pandas as pd A = np.array(['Bob', 'Becky', 'Mark', 'Joe', 'Zeke']) B = pd.DataFrame([['Joe', 'Mark', 'Bob'], ['Becky', 'Joe', 'Bob'], ['Mark', 'Tom', 'Trisha']], columns=['name', 'friend1', 'friend2']) # resulting shape is (len(A), len(B.friend1)) friend1...
python-3.x|pandas|performance|vectorization
1
9,036
68,882,602
How to add random state in numpy array
<p>I am creating a random noise using <code>np.random.normal()</code>. I wanted to add random state in it. I tried this:</p> <pre><code>R = np.random.RandomState(1989) mu, sigma = 0, 0.1 noise = R.normal(mu, sigma, [2, 2]) </code></pre> <p>I also tried setting random state using <code>random</code> package:</p> <pre>...
<p>I think you might be confused of how the RandomState works:</p> <pre><code>import numpy as np R = np.random.RandomState(1989) mu, sigma = 0, 0.1 noise = R.normal(mu, sigma, [2, 2]) </code></pre> <p>Out:</p> <pre><code>array([[-0.02637181, 0.00853202], [ 0.0430007 , 0.08950686]]) </code></pre> <p>Ok, what ...
python|numpy|random
0
9,037
72,590,784
get string from mongodb to python as raw string solved but new problem with parse_latex
<p>i am getting following as string from MongoDB query:</p> <pre><code>1000*\frac{1-{(\frac{1}{1+0.1025})^{10}}}{0.09806}' </code></pre> <p>like to take it to equate to expression</p> <pre><code>expression = '1000*\frac{1-{(\frac{1}{1+0.1025})^{10}}}{0.09806}' </code></pre> <p>then convert to sympy expression with</p> ...
<p>Raw string can be created by prefixing a string literal with <code>r&quot;&quot;</code>. In your case:</p> <pre><code>from sympy.parsing.latex import parse_latex r_string = r&quot;1000*\frac{1-{(\frac{1}{1+0.1025})^{10}}}{0.09806}&quot; expression = parse_latex(r_string) expression </code></pre> <p>EDIT to accommoda...
python|mongodb|parsing|sympy|rawstring
0
9,038
72,645,289
When I connect to vps I get an error: Connection refused
<p>I wrote in vps- console two files, that work great (test message comes from the client and is displayed by the server script). Server.py:</p> <pre><code>import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) sock.bind(('localhost', 8884)) ...
<p>your server code:</p> <pre class="lang-py prettyprint-override"><code>sock.bind(('localhost', 8884)) </code></pre> <p>means that the server is only listening for incoming connections on loopback device.</p> <p>Change that localhost to <code>0.0.0.0</code> and then the server listens on all available network devices...
python|sockets
2
9,039
72,589,428
How do I write a DAG to pass sql file?
<p>I am new to Airflow. I have a requirement to write a DAG in which I need to pass the sql file. The sql file consists of lot of queries and it uses Big Query tables. It should be scheduled to run once a day around 3 AM PST. Which operators do I need to use for this DAG? Also In the DML there is a variable called even...
<p>As Airflow uses UTC timezone, so I have converted PST to UTC and it's 11 am UST. Wrote a DAG and scheduled it at 11 am</p> <pre><code>import datetime import os import logging from airflow import DAG from airflow.providers.google.cloud.operators.bigquery import BigQueryInsertJobOperator from composer_plugins import g...
python|google-cloud-platform|airflow|airflow-scheduler|directed-acyclic-graphs
0
9,040
68,151,872
Apply a function to rows within a DataFrame
<p>Assume I have the following df:</p> <pre><code>df = pd.DataFrame({'A': [120,108.6], 'B': [109, 147]}) </code></pre> <p>Assume I have the following function:</p> <pre><code>def cpt_p(A, B): n = np.arange(1, B+1) p = [A] * B # Creates a repeating value of A of length B i.e. [A, A, A, ...] return p * n </co...
<p>You can <strong>use lambda function within <code>.apply()</code></strong> and access the column values by syntax like <code>x['A']</code> for column <code>A</code> values, etc. For each function parameter, just put the corresponding <code>x['A']</code>, <code>x['B']</code> at the correct position of the function ca...
python|arrays|pandas|list|numpy
0
9,041
68,414,600
how to sort numbers in an array ignoring text in Python?
<p>soo I have a problem. I would like to sort a list, with an other list inside (which contains numbers and text) by numbers but if there are 2 same numbers then sort should not sort by text, in other words, let the sort skip text.</p> <p>My code:</p> <pre><code>nums = [[4,'w'],[4,'a'],[2,'a']] print(sorted(nums)) </c...
<p>You have a list of lists, not a multidimensional array. But this will do what you have asked.<br /> x[0] will sort by first index of each list.</p> <pre class="lang-py prettyprint-override"><code>nums = [[4,'w'],[4,'a'],[2,'a']] foo = sorted(nums, key=lambda x: x[0]) print(foo) [[2, 'a'], [4, 'w'], [4, 'a']] </cod...
python|arrays|python-3.x|sorting
3
9,042
59,061,352
Networkx get multiple depths
<p>I have a csv file that include multiple Directed Acrylic Graphs. I am trying to use the networkx to get the depth of each graph. but I don't know if it's the problem that I import all the graph as one. How can I import multiple DAG and calculate the longest path for each connected graph?</p> <p>my csv file has two ...
<p>You can compute the connected components in <code>g</code> first, and then iterate over the components, induce a subgraph on its constituent nodes, and compute your path lengths for each subgraph. </p> <pre><code>longest_depths = [] for component in nx.connected_components(g): subgraph = nx.subgraph(g, componen...
python-3.x|networkx
1
9,043
59,202,936
Reading csv column in python returns error
<p>I have a problem concerning a certain csv column. When trying to read this column as following:</p> <pre><code>import pandas as pd data = pd.read_csv('master.csv') print(data['gdp_for_year ($)']) </code></pre> <p>It gives the following error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\wor...
<p>Well, <code>"gdp_for_year ($)"</code> is not a valid column name</p>
python|python-3.x|pandas|csv
1
9,044
63,196,544
Web Scraping using Requests - Python
<p>I am trying to get data using the Resquest library, but I’m doing something wrong. My explanation, manual search:</p> <p>URL - <a href="https://www9.sabesp.com.br/agenciavirtual/pages/template/siteexterno.iface?idFuncao=18" rel="nofollow noreferrer">https://www9.sabesp.com.br/agenciavirtual/pages/template/siteextern...
<p>When you go to the site using the browser, a session is created and stored in a cookie on your machine. When you make the POST request, the cookies are sent with the request. You receive an <code>session-expired</code> error because you're not sending any session data with your request.</p> <p>Try this code. It requ...
python|web-scraping|python-requests|python-requests-html
0
9,045
62,364,203
How to covert array of shape n, to n,m
<p>I'm trying convert numpy array of shape <code>(80000,)</code> to <code>(80000,55)</code> I'm having the data like below <code>[[1212,121,121],[12,122,111]]</code> After convert this list of list I'm getting the shape of <code>(2,)</code> but I wanna have shape like <code>(2,3)</code> how to do it. </p>
<pre><code>In [68]: np.array([[1212,121,121],[12,122,111]] ) Out[68]: array([[1212, 121, 121], [ 12, 122, 111]]) In [69]: _.shape Out[69]: (2, 3) </...
python|python-3.x|pandas|numpy
5
9,046
62,371,102
Numpy Array Index Error: IndexError: boolean index did not match indexed array along dimension 0; dimension is 16
<p>the following code throws an error:</p> <pre><code>Traceback (most recent call last): File "training.py", line 19, in &lt;module&gt; preds = model.predict(x_test, test_df) File "D:\brand\models\lstm_detection_model\lstm_brand_detection.py", line 46, in predict output = [' '.join(np.array(token_df[i])[np...
<p>Yes, in the past boolean index arrays could be longer than the object they are indexing; now they must match. That's logical, right. The former behavior let buggy code run.</p> <p>This line creates a list of lists; even if <code>ind</code> was 2d array, the new lists could differ in length:</p> <pre><code>ind = ...
python|python-3.x|numpy|numpy-ndarray
1
9,047
35,516,013
How to find the index of all letters in a user inputted string
<p>This is the assignment: Write a program that gets a single word from the user. For each letter in the word, print the index of that letter in the string 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' (e.g., 'A' would print 0, 'z' would print 51). Print all the indices on one line, separated by spaces.</p> <...
<p>You're calling <code>index</code> the wrong way. You need to swap the arguments:</p> <pre><code>answer = alphabet.index(ind) </code></pre>
python
1
9,048
58,917,280
How can I base64 encode using a custom letter set?
<p>I am trying to base64 encode using a custom character set in python3. Most of the examples I have seen in SO are related to Python 2, so I had to make some minor adjustments to the code. The issue that I am facing is that I am replacing the character <code>/</code> with <code>_</code>, but it is still printing with ...
<p>If the only characters you want to switch are <code>+</code> and <code>\</code>, you can use <a href="https://docs.python.org/2/library/base64.html#base64.urlsafe_b64encode" rel="nofollow noreferrer">base64.urlsafe_b64encode</a> to replace with <code>-</code> and <code>_</code> respectively.</p> <pre><code>&gt;&gt;...
python|python-3.x|string|encoding|base64
4
9,049
15,712,761
Proper input/output for python code in a pig udf?
<p>I have this short python script:</p> <pre><code>import langid import sys for pig_tuple in sys.stdin: cols = pig_tuple.split() if len(cols) &lt; 2: sys.exit(0) try: id = int(cols[0]) text = " ".join(cols[1:]) except: sys.exit(0) (lang,prob) = langid.classify(te...
<p>The <code>AS (pid:chararray,planguage:chararray)</code> tells pig to expect an output that is a tuple of strings but you return tab delimited strings. You should return print out the results as </p> <pre><code>print "(%s,%s)" %(id,lang) </code></pre> <p><a href="http://pig.apache.org/docs/r0.11.0/udf.html#python-...
python|hadoop|apache-pig
0
9,050
15,670,957
Sort the values in a histogram in python and plot them
<p>So say I have the following:</p> <p>[1,5,1,1,6,3,3,4,5,5,5,2,5]</p> <p>Counts: 1-3 2-1 3-2 4-1 5-5 6-1</p> <p>Now, I wanted to print a plot like a histogram that is sorted on the x axis, as in:</p> <p>not : 1 2 3 4 5 6</p> <p>But sorted by the total number: 2 4 6 3 1 5.</p> <p>Please help me out! Thanks...</p>...
<p>Use <code>collections.Counter</code>, sort the items with <code>sorted</code>, passing in a custom key function:</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; values = [1,5,1,1,6,3,3,4,5,5,5,2,5] &gt;&gt;&gt; counts = Counter(values) &gt;&gt;&gt; for k, count in reversed(counts.most_commo...
python|sorting|matplotlib|histogram
2
9,051
59,877,819
python double loop for matrix modification
<p>I have to perform a double iteration in data with a shape like <code>[a,b,c]</code>. This is the code I wrote but the result I obtain is not in the format type I need. in the loop dati is the input data. In my case <code>a = 512</code> (reduced using mroi_i, mroi_f)</p> <pre><code>frame_corr=[] dati_corr=[] for i ...
<p>I found the solution using this form of loop</p> <pre><code>frame_corr=np.zeros((a,b)) # First i define empty matrix dati_corr=np.zeros((a,b,c)) for i in range(0,c): for j in range(0,b): f = dati[mroi_i:mroi_f,:,i] s = f[:,j] s_corr = (s-d_mean)/(w_mean-d_mean) frame_corr[:,j]=s_...
python|loops
0
9,052
49,214,989
Access file in external hard drive using python on mac
<p>I have a Python file in <code>/Users/homedir/...</code> and I want it to access a <code>csv</code> file on an external hard drive.</p> <p>Does anyone know how to do this? I only need reading permission.</p>
<p>External drives can be found under <strong>/Volumes</strong> on macOS. If you provide the full path and have read access you should be able to read in your csv.</p>
python|macos|io
8
9,053
60,284,789
Is Python 3 continue loop statement a problem in compute methods in Odoo 13?
<p>I am migrating a module to version 13.0, which uses <code>continue</code> in a loop inside a compute method, and an error was driving me crazy for a while.</p> <p>I simplified the code to the minimum until I had this kind of nosense:</p> <pre><code>@api.depends('move_lines', 'move_lines.price_subtotal') def _compu...
<p>It is required to set value for each record set. If we use continue and don't set value for that specific recordset, will get issue as you mentioned.</p> <p>Try with following code:</p> <pre><code>@api.depends('move_lines', 'move_lines.price_subtotal') def _compute_subtotal(self): for picking in self: ...
python|python-3.x|odoo|odoo-13
3
9,054
60,311,162
pairing one picture to multiple pictures in folder
<p>I have some pictures in the folder I want to pair so I can add them to my slide with iterative fashion. I want to pair pictures ending with <code>mp</code> ones to <code>bp</code> ones. One caveat is that there are multiple pictures ending with <code>bp</code> and <code>bp</code> so that adding logical check would b...
<p>You can check all combinations and pick the ones that match:</p> <pre><code>from itertools import combinations from pathlib import Path files = Path(folder).glob('*.png') list_of_pairs = [(a, b) for a, b in combinations(files, 2) if (a.name.startswith(b.name[0]) and (('mp' in a.name and 'bp' in b.n...
python|pandas|for-loop|if-statement|python-pptx
1
9,055
3,183,707
Stripping off the seconds in datetime python
<p>now() gives me </p> <pre><code>datetime.datetime(2010, 7, 6, 5, 27, 23, 662390) </code></pre> <p>How do I get just <code>datetime.datetime(2010, 7, 6, 5, 27, 0, 0)</code> (the datetime object) where everything after minutes is zero?</p>
<pre><code>dtwithoutseconds = dt.replace(second=0, microsecond=0) </code></pre> <p><a href="http://docs.python.org/library/datetime.html#datetime.datetime.replace" rel="noreferrer">http://docs.python.org/library/datetime.html#datetime.datetime.replace</a></p>
python
147
9,056
67,918,535
Detecting if an event happens multiple times in a short timespan
<p>This might be a bit hard to explain, but I hope I can explain it in a sufficient and understandable way.</p> <p>I want to create a system to detect if a large amount of users suddenly joins our server, but i'm not sure how this would be setup.</p> <p>Should I store every single new user in Redis and a timestamp, and...
<p>when a user connects a server (depending upon what kind of server you have) say if you have a linux server every user connection to your server has a entry in (/var/log/&lt;file.log&gt;) location you can write a simple python program to monitor this file and put regex to count the user &quot;successful login&quot;. ...
python
0
9,057
67,968,948
Problem querying AWS Athena from Lambda introducing a variable
<p>I need help on a little problem that I have with my AWS Lambda function. This function queries my AWS Athena database. The code looks like this :</p> <pre><code>import json import boto3 import time def lambda_handler(event, context): client = boto3.client('athena') QueryResponse = client.start_query_exec...
<p>As said in comment, the solution was to use :</p> <pre><code>MyString = 'my string to replace in query' QueryString = f&quot;SELECT * FROM {MyString};&quot; </code></pre>
python|sql|amazon-web-services|aws-lambda
1
9,058
30,658,964
What does it mean when you assign int to a variable in Python?
<p>i.e. <code>x = int</code></p> <p>I understand that this will make <code>x</code> an integer if it is not already one, but I'd like to understand the process behind this. In particular, I'd like to know what <code>int</code> is (as opposed to <code>int()</code>). I know that <code>int()</code> is a function, but I'm...
<p>Imagine you had a function called <code>func</code></p> <pre><code>def func(): print("hello from func") return 7 </code></pre> <p>If you then assigned <code>func</code> to <code>x</code> you are assigning the function <em>itself</em> to <code>x</code> <strong>not</strong> the result of the call</p> <pre><...
python|variables|int|type-conversion
7
9,059
66,845,303
Deploying a Plotly/Dash app to AWS using Serverless Framework
<p>I am trying to deploy a Plotly Dash app as an AWS Lambda using Serverless framework. The app works as expected locally and I can start it using <code>serverless wsgi serve</code> command. <code>serverless deploy</code> reports success. However when invoked, lambda fails with the following error:</p> <pre><code>Trace...
<p>The reason for <code>ModuleNotFoundError: No module named '_brotli'</code> is improper dependencies packaging. It is fixed by packaging the app via the use of Docker and the docker-lambda image. <code>slim: true</code> and <code>strip: false</code> minimise the package size while preserving binaries wich is required...
python|amazon-web-services|aws-lambda|serverless-framework|plotly-dash
5
9,060
67,165,074
Using multiple functions with pandas transform
<p>I have a dataset that looks like this:</p> <pre><code> entity_id transaction_date transaction_month net_flow inflow outflow 0 51 2018-07-02 2018-07-01 10161.06 20161.06 10000.00 1 51 2018-07-03 2018-07-01 5823.73 5867.37 43.64 2 51 2018-07-05...
<p>I don't think it is possible with <code>transform</code>. You have two workarounds (at least). Either <code>merge</code> the result of <code>groupby.agg</code> on the original dataframe:</p> <pre><code>tmp_ = ( raw_transactions .groupby(['entity_id','transaction_month'])[['inflow','outflow']] .agg([ ...
python|pandas
2
9,061
66,819,489
how to print something in the terminal for limited rime
<p>I want to print random number in the terminal for just a few second</p> <pre><code>number = 10 print(number) </code></pre> <p>but I can't delete it after its display in terminal. is there any way to hide number after it show in terminal?</p>
<p>You can go back to the beginning of the line with <code>\r</code> and <code>flush=True</code>, then overwrite the content of the line.</p> <pre><code>import time print(&quot;secret message&quot;, end=&quot;\r&quot;, flush=True) time.sleep(3) print(&quot; &quot; * 20) </code></pre> <p>For more complex behaviour, incl...
python
1
9,062
67,098,742
Write & Apply Python Function with Grouped Pandas Data
<p>I have data that is grouped by a column 'plant_name' and I need to write &amp; apply a function to test for a trend on one of the columns, i.e., named &quot;10%&quot; or '90%' for example.</p> <p>My data looks like this -</p> <pre><code> plant_name year count mean std min 10% 50% 90% max 0 AR...
<p>For a given <code>column</code>, you can run the test in a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer"><strong><code>GroupBy.apply()</code></strong></a> and return the <code>result</code> as a <code>Series</code> indexed by <co...
pandas|function|group-by|pandas-groupby
1
9,063
63,811,770
Creating a list from series of pandas
<p><a href="https://i.stack.imgur.com/Qtdi6.png" rel="nofollow noreferrer">Click here for the image</a>I m trying to create a list from 3 different series which will be of the shape &quot;({A} {B} {C})&quot; where A denotes the 1st element from series 1, B is for 1st element from series 2, C is for 1st element from ser...
<p>Use <code>pandas.DataFrame.itertuples</code> with <code>str.format</code>:</p> <pre><code># Sample data print(df) col1 col2 col3 0 1 2 7 1 21 11 45 2 32 25 32 3 45 76 49 fmt = &quot;({} {} {})&quot; [fmt.format(*tup) for tup in df[[&quot;col1&quot;, &quot;col2&quot;, &qu...
python-3.x|openfoam
0
9,064
42,818,361
How to make two plots side-by-side
<p>I found the following example on matplotlib:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x1 = np.linspace(0.0, 5.0) x2 = np.linspace(0.0, 2.0) y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) y2 = np.cos(2 * np.pi * x2) plt.subplot(2, 1, 1) plt.plot(x1, y1, 'ko-') plt.title('A tale of 2 subplots'...
<p>Change your subplot settings to:</p> <pre><code>plt.subplot(1, 2, 1) ... plt.subplot(1, 2, 2) </code></pre> <p>The parameters for <code>subplot</code> are: number of rows, number of columns, and which subplot you're currently on. So <code>1, 2, 1</code> means "a 1-row, 2-column figure: go to the first subplot." ...
python|matplotlib|subplot
197
9,065
50,951,572
How do I sum values from one column dependent on items in other columns?
<p>I have the following dataframe:</p> <pre><code> Course Orders Ingredient 1 Ingredient 2 Ingredient 3 starter 3 Fish Bread Mayonnaise starter 1 Olives Bread starter 5 Hummus Pita main 1 Pizza main 6 Beef Potato...
<p>I don't believe there's really slick way to this with groupby or other such pandas methods, though I'm happy to be proven wrong. In any case, the following is not especially pretty, but it will give you what you're after.</p> <pre><code>import pandas as pd from collections import defaultdict # The data you provide...
python|pandas
0
9,066
3,905,548
Adding database module
<p>I am new to django</p> <p>I would like to start a project but when i run it i get this error</p> <pre><code>Error loading MySQLdb module </code></pre> <p>How do i add the MYSQL module or any other module for that matter</p>
<p>Install it on your system, using either a native installer or package, via <code>pip</code> or <code>easy_install</code>, or by running <code>setup.py</code> in the tarball.</p>
python|mysql|django
2
9,067
35,248,015
Going to a specific position in a file
<p>I am fairly new to python. I have been doing a project that i have been struggling on recently and I'd be glad if i can receive some help. </p> <p>I am conducting a programme in which will take an input from a user and see if the input is seen in the file. The input is a name tag, e.g. the user will have to type in...
<p>First of all, you don't need to open and read the file three times - once will suffice.</p> <p>The data appears to be in CSV format so you can use the <a href="https://docs.python.org/3/library/csv.html" rel="nofollow"><code>csv</code></a> module to help parse the file.</p> <pre><code>import csv nametag = input("...
python|file|search
2
9,068
26,831,291
Understanding Flow of Multiple Bash Outputs
<p>I'm having trouble understanding the flow of this command: </p> <pre><code>$ cat epron-jpron.data | ./em.py epron-jpron.viterbi &gt;epron-jpron.probs 2&gt;epron-jpron.logs </code></pre> <p>I understand that <code>epron-jpron.data</code> is <code>stdin</code> for <code>em.py</code>, but how does <code>em.py</cod...
<ol> <li><code>cat</code> reads file epron-jpron.data.</li> <li><code>cat</code>'s stdout is redirected (by <code>|</code>) to <code>./em.py</code>'s stdin.</li> <li>Stdout of <code>./em.py</code> is redirected (by <code>&gt;</code>) to file epron-jpron.probs.</li> <li>Stderr of <code>./em.py</code> is redirected (by <...
python|bash|unix|io-redirection
3
9,069
26,910,319
Python AES text encryption script
<p>I am working on a python script which encrypts text using 128-AES algorithm but i have a problem: </p> <p>Picture shows my script processes. This works fine the thing is in the decryption when i give wrong key output decimals goes out of range of ASCII, so program can't show any text at the output.<br> I expected ...
<p>That's normal, because AES (and most modern cryptosystems) is dealing with encrypting the actual byte values, not the ASCII values. With an incorrect key, the data won't be decrypted correctly, resulting in ranges outside of the normal ASCII values.</p> <p>If you're looking for something that encrypts/decrypts ASCI...
python|ascii
1
9,070
65,037,222
groupby with multiple conditions
<pre><code>df fruit year sale important 0 apple 2010 1 apple 2011 2 apple 2012 3 apple 2013 4 apple 2014 True Yes 5 apple 2015 True 6 apple 2017 True 7 apple 2018 True 7 apple 2019 8 apple 2020 True Yes 9 banana 2010 ... </code></pre> <p>How could I generate the &quot;importa...
<p>Please try if this works for your case. Assuming that df is sorted by fruit and year.</p> <pre><code>for i in df['fruit'].unique(): df1 = df[(df['sale'] == 'True') &amp; (df['sale'].shift() != 'True') &amp; (df['fruit'] == i)] df1 = df1[(df1['year'].diff() &gt;=3) | (df1['year'].diff().fillna(0) == 0)] d...
python|python-3.x|pandas|dataframe|pandas-groupby
1
9,071
61,547,176
Is there a way to clear the undo/redo stack for the Text widget in Tkinter?
<p>I'm building a specialized text editor using Tkinter Text widgets. Some of the files that will be edited are fairly large (300K-500K lines). Some of the functions in the editor affect the whole file (e.g., tagging certain lines based on content, etc.). I'm using autoseparators to handle these situations where an und...
<p>The <code>edit_reset</code> method clears the undo stack. </p>
python|tkinter|text|widget
3
9,072
61,495,449
Hex to plain ASCII? Python 2.7.13
<p>Im trying to turn this: %73%6c%61%70%72%69%73%65%40%6c%69%65%6e%6d%75%6c%74%69%6d%65%64%69%61%2e%63%6f%6d</p> <p>into this: slaprise@lienmultimedia.com</p> <p>and my brain is exploding.. Any help would be appreciated. </p> <p>Thank you</p>
<p>Python 2.7.17 (should work for Python 2.7.13)</p> <pre><code>import urllib2 url = urllib2.unquote("%73%6c%61%70%72%69%73%65%40%6c%69%65%6e%6d%75%6c%74%69%6d%65%64%69%61%2e%63%6f%6d") print(url) # slaprise@lienmultimedia.com </code></pre>
python|hex
2
9,073
69,665,569
How Can I Play A Video Using Python?
<p>I wanna create a simple program that help me to open any video i want, just by writing the name of the video; Is there any libraries i can use.</p>
<p>the most common way to work with images and videos in python is using opencv, a powerfull library that allows you to read imgs, videos and show them. If you only want to reproduce a video you can use a code like this:</p> <pre><code>import cv2 videoName = yourVideoPathAndName #'DJI_0209.MP4' #create a videoCaptur...
python|video
0
9,074
55,458,891
Airflow error with pandas: AttributeError: 'Pendulum' object has no attribute 'nanosecond'
<p>I have a pandas.DataFrame <code>df</code> with <code>df.index</code> which yeilds something like this:</p> <pre><code>DatetimeIndex(['2014-10-06 00:55:11.357899904', '2014-10-06 00:56:39.046799898', '2014-10-06 00:56:39.057499886', '2014-10-06 00:56:40.684299946', ...
<p>After some searching, I found the source of the problem and a solution.</p> <p><strong>the problem</strong></p> <p>The issue is caused by the two macros passed down from Airflow:</p> <ul> <li><p><code>start_date</code>, which is the <code>execution_date</code> macro</p></li> <li><p><code>end_date</code>, which is...
python|pandas|airflow|pendulum
3
9,075
55,381,861
'method' object is not sub scriptable in python
<p>I am implementing Minimum Remaining Values of CSP in python.And I got some errors.</p> <p>I run with python3 and also with python2 interpreter .</p> <pre><code>def select_unassigned_variable(assignments, csp): variables = [var for var in csp.nodes() if var not in assignments.keys()] if...
<p>change to something like</p> <pre><code>key=(lambda var: (len(csp.nodes()[var]['domain'])))) </code></pre>
python|constraint-programming
1
9,076
55,418,764
How to count a value in a specific row of an array with Python
<p>So basically I have an array, that consists of 14 rows and 426 Columns, every row represents one property of a dog and every column represents one dog, now I want to know how many dogs are ill, this property is represented by the 14. row. 0 = Healthy and 1 = ill, so how do I count the specific row? </p> <p>I tried ...
<p>You can simply sum the values of the 14.row and you get the number (count) of ill dogs:</p> <pre><code>count = A[13,:].sum() # number of ill dogs -- 13 because the index starts with 0 </code></pre>
python|arrays|numpy|artificial-intelligence
1
9,077
42,297,923
Least Squares Fit on Cubic Bezier Curve
<p>I would like fit a cubic bezier curve on a set of 500 random points.</p> <p>Here's the code I have for the bezier curve:</p> <pre><code>import numpy as np from scipy.misc import comb def bernstein_poly(i, n, t): """ The Bernstein polynomial of n, i as a function of t """ return comb(n, i) * ( t*...
<p>Use the function curve_fit in scipy, <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html</a></p> <pre><code>import numpy as np from scipy.optimize import curve_fit de...
python|linear-regression|curve-fitting|bezier|least-squares
1
9,078
58,249,951
Classification using word embeddings
<p>I'm trying to do Classification using word embeddings, but I face typeError problem.</p> <pre><code> # glove word embeddings import numpy as np embeddings_index = {} with open('glove.6B/glove.6B.50d.txt', 'r') as f: for line in f: values = line.split() word = values[0] coefs = np.asarr...
<p>The problem is that, <a href="https://docs.python.org/3/library/stdtypes.html#dict-views" rel="nofollow noreferrer">in Python 3, dict_values is merely a view and not a list</a>.</p> <p>If you want to get the first element lenght, you have to replace</p> <blockquote> <p>dim = len(embeddings.values()[0])</p> </blo...
python|python-3.x|word-embedding
0
9,079
58,544,352
How to create gif from different sized images(.png) in Python
<p>I am using ImageIO to create a .gif file. I have 3 .png images with different sizes as:</p> <pre><code>(width, length, rgb) (2520, 1800, 3) (3840, 1800, 3) (1800, 1800, 3) </code></pre> <p>As its visible that 2nd image is too wide and its going out of the frame. Is it possible to fix the frame size of the .gif so ...
<p>To create gif from images of different sizes, we can use "moviepy.editor" and concatenate the images by passing argument method="compose".</p> <p>method="compose" retains the dimension of each image(frame) and creates a gif file with the frame of maximum height and width.</p> <p>Here is the code:</p> <pre><code>d...
python|gif|python-imageio
1
9,080
65,129,162
Multidimensional non-linear optimization in python
<p>I have several different blocks in my Python-based program, with each block representing a non-linear function <code>f(x, l)</code> with <code>x</code> representing a class containing several different parameters (here labeled as <code>k</code>, <code>l</code> and <code>m</code>). The function is acting on those par...
<p>There are many ways to optimize a function. In your case, I would suggest to recast your problem and optimize independently for each number of functions to use. In other words optimize a first time when using only one function, then 2 and three, etc.</p> <p>For each of these optimization, optimize the order/type of ...
python|nonlinear-optimization
1
9,081
28,538,907
Attribute error for Association Proxy in SQLAlchemy
<p>I try to use the association proxy of the SQLAlchemy toolbox. These are the two concerning models, mapped for a one-to-many relation:</p> <pre><code>class User(object): query = db_session.query_property() def __init__(self, id): self.id = id def __repr__(self): return '{\"id: \"%i}' % (s...
<p>The cause of the problem is the <code>lazy='dynamic'</code> on your relationship, which returns a <code>Query</code> object (so that additional operations like filtering/ordering etc) can be performed. To solve this, just call <code>all()</code>:</p> <pre><code>user = User.query.filter(User.id==id) for context in u...
python|flask|sqlalchemy
1
9,082
68,516,544
How can I reproducibly (py)test the failure mode of code that opens a file if the file is missing?
<p>I would like to write a pytest case for the behavior of a function that opens a file in case that file does not exist.</p> <p>I think the question boils down to a different one, namely &quot;How can I be sure a file path does not exist on the file system?&quot;</p> <pre class="lang-py prettyprint-override"><code>imp...
<p>the easiest way is to use the builtin <code>tmp_path</code> fixture to generate a unique, empty directory:</p> <pre class="lang-py prettyprint-override"><code>def test_does_not_exist(tmp_path): with pytest.raises(FileNotFoundError): file_content(tmp_path.joinpath('dne')) </code></pre> <p><code>tmp_path</...
python|pytest
2
9,083
68,481,660
Django admin, page not found in custom view
<p>I encountered very annoying problem.</p> <p>I have created my own <code>AdminSite</code> like this:</p> <pre><code>from django.contrib import admin from django.template.response import TemplateResponse from django.urls import path class MyAdminSite(admin.AdminSite): def get_urls(self): urls = super().g...
<p>Well. I'm going to answer to my own question, in order to help other people.</p> <p>The solution of this problem was to switch returning url addition like this:</p> <pre><code> return my_urls + urls </code></pre> <p><code>my_urls</code> comes first and the other <code>urls</code>.</p> <p>Why this is happening? Becau...
python|django
4
9,084
41,364,656
How to pass Date Range Picker start and end value to django view.py
<p>I am using a Date Range Picker (<a href="http://www.daterangepicker.com/" rel="nofollow noreferrer">http://www.daterangepicker.com/</a>) and I would like to pass selected start and end date to django view.py so I can generate report between this two dates.</p> <p>This is my html:</p> <pre><code> {% extends "Bas...
<p>In your example, you are using POST METHOD.</p> <p>So you need to link your form to your daterangepicker. You don't do it in your code.</p> <p>You have your form, and after you created a div with your datepicker. You can create a form with two datefield.</p> <pre><code>date_start = forms.DateField(...) date_end ...
jquery|python|django
1
9,085
6,431,033
intersect two lists of words in python
<p>i want to find the intersection of two lists in python. i have something that looks like this:</p> <pre><code>&gt;&gt;&gt; q = ['apple', 'peach', 'pear', 'watermelon', 'strawberry'] &gt;&gt;&gt; w = ['pineapple', 'peach', 'watermelon', 'kiwi'] </code></pre> <p>and i want to find something that looks like this:</p>...
<p>The intersection() method is available for <a href="http://docs.python.org/library/stdtypes.html#set">sets</a>, which can be easily made from lists. </p> <p>ETA: if you want a list out of it... </p> <pre><code>q = ['apple', 'peach', 'pear', 'watermelon', 'strawberry'] w = ['pineapple', 'peach', 'watermelon', 'kiwi...
python|list
11
9,086
57,048,553
Unable To Import Pygame After Pip Install
<p>I installed pygame through pip. I know for a fact it is there, as I have seen the file labeled 'pygame' in the file explorer. However Python does not agree with me that it is certainly there.</p> <p>What makes this odd is that i've installed pygame using pip before on a different user, it worked fine, and i did not...
<p>Check your virtual environment. It seems that you are not using the environment where you have installed pygame. If you are using Anaconda, the environment is specified in parentheses. You can activate your environment using: <code>conda activate &lt;conda environment name here&gt;</code></p> <p>Hope this works!</p...
python|pip|pygame
0
9,087
25,561,578
While running python script as another user (with sudo), input string taken as variable name
<p>I have a simple python script, test.py:</p> <pre><code>x = input("Enter string") print("Entered str: ", x) </code></pre> <p>I want to run the script as another user; lets call him scratch:</p> <pre><code>sudo -u scratch python test.py </code></pre> <p>The program waits for the console input. When I enter "abc", ...
<p><code>input</code> behaves differently in Python 2.x and 3.x. The other account has Python 2.x set as its default, or has a Python 2.x executable first in its <code>PATH</code>. Your usual account, on the other hand, is using a Python 3.x executable. Probably the best way to do this is to use the full path to the Py...
python|command-line|sudo|nameerror
2
9,088
25,649,367
Python changing list element based on value being odd or even
<p>Supposed to change a value of a list based on if the value is odd or even. Error: </p> <pre><code>list assignment index out of range </code></pre> <p>Code:</p> <pre><code>def list_mangler(list_in): for i in list_in: if i % 2 == 0: list_in[i] = i * 2 else: list_in[i] =...
<p>the problem is that <code>for i in list_in</code> yields <em>items</em> in the list, not <em>indices</em>. To get the indices, use <code>enumerate</code>:</p> <pre><code>for i, val in enumerate(list_in): if i % 2 == 0: list_in[i] = val * 2 ... </code></pre> <p>If you wanted to return a <em>new</em...
python|list
4
9,089
25,833,173
A method that run authomatically when instaciate a class with a duplicate variable
<p><code>earth</code> is a class standing for some countries. When I instantiate a country, <code>total_population</code> increases by <code>1</code> person and the population of that country starts at <code>1</code>. We can add\sub <code>1</code> to\from total-poulation and country-population using <code>burn()</code...
<p>Yes, first <code>__init__</code> for the second instance is being called, to create it. Then, because the first instance is no longer referred to by any variable it is being deleted. It is being deleted because after the last variable which was pointing to it is rebound to something else it is impossible to reach it...
python|python-2.7|python-3.x
1
9,090
44,390,255
How to disable keyboard input in curses
<p>I have some long running tasks and would like to disable the keyboard input during the procedure. After the keyboard is disabled, the keyboard inputs will be discarded automatically.</p> <pre><code>disable keyboard running the task enable keyboard </code></pre> <p>Can I do this with python curses?</p>
<p>Well, there's no input until you ask for it, so there's no need to explicitly disable it. But, to flush the input queue before you start taking input again, just call <code>curses.flushinp()</code>.</p>
python-3.x|curses
2
9,091
44,624,648
TensorFlow: “Attempting to use uninitialized value” in variable initialization
<p>Here's my code.</p> <pre><code>import tensorflow as tf a=tf.Variable(tf.constant([0,1,2],dtype=tf.int32)) b=tf.Variable(tf.constant([1,1,1],dtype=tf.int32)) recall=tf.metrics.recall(b,a) init=tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) rec=sess.run(recall) print(rec) </...
<p>You also need to initialise the local variables hidden in the <code>tf.metrics.recall</code>method.</p> <p>For example, this piece of code would work:</p> <pre><code>init_g = tf.global_variables_initializer() init_l = tf.local_variables_initializer() with tf.Session() as sess: sess.run(init_g) sess.run(ini...
tensorflow
45
9,092
20,609,500
In Python, importing twice with class instantiation?
<p>In <code>models.py</code> I have:</p> <pre><code>... db = SQLAlchemy(app) class User(db.Document): ... </code></pre> <p>In my app both <code>serve.py</code> and <code>models.py</code> call:</p> <pre><code>from models import User </code></pre> <p>Is that double import going to instantiate the db twice and poten...
<blockquote> <p>Is that double import going to instantiate the db twice and potentially cause a problem?</p> </blockquote> <p>No it will not. Once a module is imported it remains available regardless of any further imports via the <code>import</code> statement.</p> <p>The module is stored in <code>sys.modules</code...
python
11
9,093
71,857,310
Pandas: percentage of a value relative to the total of the group
<p>I have a dataframe with sales quantity for a list of products. Each product is assigned a design/range name. Within each design, there may be multiple products. How can I perform calculations within only a certain design to find the sales split? I want to find out what percentage of a given range come from a certain...
<p>Edit: You should see <a href="https://stackoverflow.com/a/71857434/12932966">mozway's solution</a>, because mine is basically doing the same thing in more steps ; I didn't know about <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><...
python|pandas|dataframe|pandas-groupby
3
9,094
49,574,187
Convert hex to bytes
<p>I have results of script in text and bytes stored in CSV text file, which looks like:</p> <blockquote> <p>found_value_1;b'UT\x05\x00\x03'</p> <p>found_value_2;b'UT\x05\x00\x04'</p> </blockquote> <p>There is some text and, separated by semicolon, dump of bytes. I was seriously looking, but could not find instructions...
<p>let's say you have your csv file. Read it and evaluate the bytes using <code>ast.literal_eval</code>:</p> <pre><code>import csv,ast.literal_eval with open("input.csv") as f: cr = csv.reader(f,delimiter=";") for row in cr: print(ast.literal_eval(row[1])) </code></pre>
python|hex
1
9,095
20,951,424
Is path broken for anaconda ipython?
<p>I wish to use anaconda distribution of ipython, but typing <code>ipython</code> at the terminal produces an error message: </p> <pre><code>Traceback (most recent call last): File "/usr/local/bin/ipython", line 5, in &lt;module&gt; from pkg_resources import load_entry_point File "/System/Library/Frameworks/P...
<p>Your problem is in your $PATH. If you look at your traceback, it's running /usr/local/bin/ipython - this is the one that is installed by Homebrew, and not by Anaconda. (Anaconda installs everything into /anaconda/bin.)</p> <p>The reason this is getting picked up is because the very last line of your .bash_profile...
python|bash|ipython|anaconda
9
9,096
53,565,087
Concat pandas dataframe combines out of order
<p>I am trying to combine a list of files into one dataframe in order to write it back out to a single csv. Each time I combine the files using pd.concat, everything completely reorders itself (both columns and rows) in the combined output file. My code is:</p> <pre><code>#create list of file paths paths = [] for file...
<p>Datetime Format issue:</p> <p>If you look in the documentation for read_csv you can see that it has the argument "parse_dates". In order to tell pandas that your time column is datetime, you can read in the csv using below <code>pd.read_csv(file,header=0,parse_dates=['time'])</code> </p> <p>Column Order Issue:</p>...
python|pandas|csv|dataframe|concat
0
9,097
45,826,043
How to pickle NotImplementedType
<p>How do you add support for pickling traditionally non-pickablable types in Python?</p> <p>I have a complex object I need to pickle, and it include references to the class <code>NotImplementedType</code>. The class is third-party, so I can't override its <code>__copy__()</code> or <code>__deepcopy__()</code> or <cod...
<p>It's highly unlikely the class in question actually contains <code>NotImplementedType</code>; rather, it probably is pickling <code>NotImplemented</code>, and the reduction function for <code>NotImplemented</code> is trying to pickle it in terms of its type, but <code>NotImplementedType</code> isn't exposed directly...
python|python-2.7|pickle|deep-copy
2
9,098
54,920,650
Can't Reshape Numpy Array, even with multiple methods
<p>I am getting a very strange error:</p> <pre><code>print(np.asarray(X[i%len(y)]).shape) x_train = X[i%len(y)] x_train.shape = (1, x_train.shape[0], x_train.shape[1]) (39, 4096) Traceback (most recent call last): File "scripts/train_new.py", line 172, in &lt;module&gt; model.fit_generator(train_generator(), s...
<p>Use <code>reshape</code> not <code>shape</code>:</p> <pre><code>arr = np.zeros((39, 4096)) dim1, dim2 = arr.shape arr.reshape((1,dim1,dim2)).shape (1, 39, 4096) </code></pre>
python|python-2.7|numpy|numpy-ndarray
1
9,099
33,157,955
How to combine a list of lists with a second list into a single list of lists?
<p>I have two lists of same length:</p> <pre><code>l1 = [['a','b'],['b','c'],[]] l2 = [0,1,3] </code></pre> <p>How do I make a list <code>l3</code> from these two lists such that:</p> <pre><code>l3 = [['a','b',0],['b','c',1],[3]] </code></pre>
<p>Hint: here's the answer</p> <pre><code>l1 = [['a','b'],['b','c'],[]] l2 = [0,1,3] l3 = [l1[i] + [x] for i, x in enumerate(l2)] </code></pre>
python|list|nested-lists
2