qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 29 22k | response_k stringlengths 26 13.4k | __index_level_0__ int64 0 17.8k |
|---|---|---|---|---|---|---|
32,043,990 | I'm trying to get the `SPF records` of a `domains` and the domains are read from a file.When i am trying to get the spf contents and write it to a file and the code gives me the results of last domain got from input file.
```
Example `Input_Domains.txt`
blah.com
box.com
marketo.com
```
The output,I get is only for... | 2015/08/17 | [
"https://Stackoverflow.com/questions/32043990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5093018/"
] | It is because you are rewriting `full_spf` all the time so only last value is stored
```
with open('Input_Domains.txt','r') as f:
for line in f:
full_spf=getspf(line.strip())
```
**Modification:**
```
with open('Input_Domains.txt','r') as f:
full_spf=""
for line in f:
full_spf+=getspf(li... | Try using [a generator expression](https://wiki.python.org/moin/Generators) inside your `with` block, instead of a regular `for` loop:
```
full_spf = '\n'.join(getspf(line.strip()) for line in f)
```
This will grab all the lines at once, do your custom `getspf` operations to them, and then join them with newlines be... | 12,974 |
25,927,804 | Hey guys For my school project I need to web scrape slideshare.net for page views using python. However, it wont let me scrape the page views of the user name (which the professor specifically told us to scrape) for example if I go to slideshare.net/Username on the bottom there will be a page view counter when i go int... | 2014/09/19 | [
"https://Stackoverflow.com/questions/25927804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4057203/"
] | You have a space at the start of your regex string, so it will only match if there's (at least) one space before the `<span`...
So instead of
`regex = ' <span class="noWrap">(.+?)</span>'`
try
`regex = '<span class="noWrap">(.+?)</span>'`
or even better
`regex = r'<span class="noWrap">\s*(.+?)\s*</span>'`
Raw s... | Although this in not an technically an answer you will need to change your regular expression. I suggest you look at the python regex chapters.
What I will tell you is that your line
```
regex = ' <span class="noWrap">(.+?)</span>'
```
will not match what you are after based on the output of the webpage since there... | 12,975 |
7,621,897 | I was wondering how to implement a global logger that could be used everywhere with your own settings:
I currently have a custom logger class:
```
class customLogger(logging.Logger):
...
```
The class is in a separate file with some formatters and other stuff.
The logger works perfectly on its own.
I import thi... | 2011/10/01 | [
"https://Stackoverflow.com/questions/7621897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815382/"
] | Create an instance of `customLogger` in your log module and use it as a singleton - just use the imported instance, rather than the class. | You can just pass it a string with a common sub-string before the first period. The parts of the string separated by the period (".") can be used for different classes / modules / files / etc. Like so (specifically the `logger = logging.getLogger(loggerName)` part):
```
def getLogger(name, logdir=LOGDIR_DEFAULT, level... | 12,976 |
69,410,508 | I wanted to save all the text which I enter in the listbox. "my\_list" is the listbox over here.
But when I save my file, I get the output in the form of a tuple, as shown below:
```
("Some","Random","Values")
```
Below is the python code. I have added comments to it.
The add\_items function adds data into the entry... | 2021/10/01 | [
"https://Stackoverflow.com/questions/69410508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16781901/"
] | The main part is that `listbox.get(first, last)` returns a tuple so you could use `.join` string method to create a string where each item in the tuple is separated by the given string:
```py
'\n'.join(listbox.get('0', 'end'))
```
Complete example:
```py
from tkinter import Tk, Entry, Listbox, Button
def add_item(... | This is a very simple task.
Where you are saving the file, write this code:
```
newlist = []
for item in mylist.get(0, END):
newlist.append(item)
f = open(file, 'w')
for line in newlist:
f.write(line+'\n')
f.close()
```
To know more about file saving in tkinter or to make it much easier, you can check my txtopp rep... | 12,986 |
60,838,550 | I've written a script in python using selenium to log in to a website and then go on to the target page in order to upload a pdf file. The script can log in successfully but throws `element not interactable` error when it comes to upload the pdf file. This is the [landing\_page](https://jobs.allianz.com/sap/bc/bsp/sap/... | 2020/03/24 | [
"https://Stackoverflow.com/questions/60838550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10568531/"
] | Please refer below solution to avoid your exception,
```
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as Wait
f... | Try this script , it upload document on both pages
```
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
landing_page = 'https://jobs.allianz.com/sap/bc/bsp/sap/zhcmx_erc_u... | 12,987 |
16,505,752 | I collected some tweets through twitter api. Then I counted the words using `split(' ')` in python. However, some words appear like this:
```
correct!
correct.
,correct
blah"
...
```
So how can I format the tweets without punctuation? Or maybe I should try another way to `split` tweets? Thanks. | 2013/05/12 | [
"https://Stackoverflow.com/questions/16505752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/975222/"
] | You can do the split on multiple characters using `re.split`...
```
from string import punctuation
import re
puncrx = re.compile(r'[{}\s]'.format(re.escape(punctuation)))
print filter(None, puncrx.split(your_tweet))
```
Or, just find words that contain certain contiguous characters:
```
print re.findall(re.findall... | Try removing the punctuation from the string before doing the split.
```
import string
s = "Some nice sentence. This has punctuation!"
out = s.translate(string.maketrans("",""), string.punctuation)
```
Then do the `split` on `out`. | 12,988 |
56,399,448 | I have the following code which sums up values of each key. I am trying to use the list in the reducer since my actual use case is to sample values of each key. I get the error I show below? How do I achieve with a list(or tuple). I always get my data in the form of tensors and need to use tensorflow to achieve the red... | 2019/05/31 | [
"https://Stackoverflow.com/questions/56399448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7418127/"
] | What you can do to mock your store is
```
import { store } from './reduxStore';
import sampleFunction from './sampleFunction.js';
jest.mock('./reduxStore')
const mockState = {
foo: { isGood: true }
}
// in this point store.getState is going to be mocked
store.getState = () => mockState
test('sampleFunction retur... | ```
import { store } from './reduxStore';
import sampleFunction from './sampleFunction.js';
beforeAll(() => {
jest.mock('./reduxStore')
const mockState = {
foo: { isGood: true }
}
// making getState as mock function and returning mock value
store.getState = jest.fn().mockReturnValue(mockState)
});
afterAll(() ... | 12,990 |
36,620,656 | I am trying to learn how to write a script `control.py`, that runs another script `test.py` in a loop for a certain number of times, in each run, reads its output and halts it if some predefined output is printed (e.g. the text 'stop now'), and the loop continues its iteration (once `test.py` has finished, either on it... | 2016/04/14 | [
"https://Stackoverflow.com/questions/36620656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can use subprocess module or also the os.popen
```
os.popen(command[, mode[, bufsize]])
```
Open a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'.
With subprocess I would suggest
```
subpro... | You can use the "subprocess" library for that.
```
import subprocess
command = ["python", "test.py", "someargument"]
for i in range(n):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
output = p.stdout.readline()
if output == '' and p.poll() is not ... | 12,991 |
13,238,357 | I face a problem when using Scrapy + Mongodb with Tor. I get the following error when I try to have a mongodb pipeline in Scrapy.
```
2012-11-05 13:41:14-0500 [scrapy] DEBUG: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
|S-chain|-<>-127.0.0... | 2012/11/05 | [
"https://Stackoverflow.com/questions/13238357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139909/"
] | ```
pymongo.errors.AutoReconnect: could not connect to localhost:27017: [Errno 111] Connection refused
```
It seems you cannot connect to the localhost on port 27017. Is this the correct port and correct host? Make sure about that, also make sure mongodb server is running on the background otherwise you will never co... | It might be that it's trying to redirect your MongoDB connection (localhost:27017) to TOR. If you want to exclude localhost connections from proxychains, you can add the following line to your */etc/proxychains.conf*:
```
localnet 127.0.0.1 000 255.255.255.255
``` | 12,995 |
48,734,784 | so im working on this code for school and i dont know much about python. Can someone tell me why my loop keeps outputting invalid score when the input is part of the valid scores. So if i enter 1, it will say invalid score but it should be valid because i set the variable valid\_scores= [0,1,2,3,4,5,6,7,8,9,10].
This c... | 2018/02/11 | [
"https://Stackoverflow.com/questions/48734784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9346720/"
] | The error means that the 3rd line is not well-formed: you need a (*blank space*) between `android:id` value and `android:title` key.
This is the correct XML:
```
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/Profile" android:title=... | Go to code in the toolbar and click on reformat code. | 12,998 |
19,855,110 | I am learning how to use Selenium in `python` and I try to modify a `css` style on <http://www.google.com>.
For example, the `<span class="gbts"> ....</span>` on that page.
I would like to modify the `gbts` class.
```
browser.execute_script("q = document.getElementById('gbts');" + "q.style.border = '1px solid red';"... | 2013/11/08 | [
"https://Stackoverflow.com/questions/19855110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1073181/"
] | You are asking how to get an element by it's CSS class using JavaScript. Nothing to do with Selenium *really*.
Regardless, you have a few options. You can first grab the element using Selenium (so here, yes, Selenium is relevant):
```
element = driver.find_element_by_class_name("gbts")
```
With a reference to this ... | Another pure JavaScript option which you may find gives you more flexibility is to use `document.querySelector()`.
Not only will it automatically select the first item from the results set for you, but additionally say you have multiple elements with that class name, but you know that there is only one element with th... | 12,999 |
61,035,989 | i am trying to run this simple flask app and I keep getting this error in the terminal when trying to run the flask app
`FLASK_APP=app.py flask run`
i keep getting this error :
`sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) fe_sendauth: no password supplied`
here is my app:
```
from flask import Flask... | 2020/04/04 | [
"https://Stackoverflow.com/questions/61035989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10600856/"
] | Other than just setting a password, you can log in without a password by:
1. Enable trust authentication, eg `echo "local all all trust" | sudo tee -a /etc/postgresql/10/main/pg_hba.conf`
2. Create a role with login access with the same username as your local username, eg if `whoami` returns `myname`, then `sudo -u po... | so apparently you need a password to connect to database from SQLAlchemy, I was able to work around this by simply creating a password or adding new user with password.
let me know if there is a different work around/solution | 13,000 |
61,469,948 | I am a beginner in the field of Data Science and I am working with Data Preprocessing in python. However, I am working with the Fingers Dataset so I want to move the pictures so every pic fits in its own directory to be able to use **ImageDataGenerator** and **flowfromdirectory** to import the pictures and apply rescal... | 2020/04/27 | [
"https://Stackoverflow.com/questions/61469948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11381138/"
] | Firstly instead of doing a for each and push promises you can map them and do a Promise all. You need no push. Your function can return directly your promise all call. The caller can await it or use then...
Something like this (I didn't test it)
```js
// serverlist declaration
function getList(serverlist) {
const oper... | For more consistency and for resolving this question i/we(other people which can help you) need *all* code this all variables definition (because for now i can't find where is the `promises` variable is defined). Thanks | 13,001 |
73,805,667 | i am a beginner with python. I need to calculate a binairy number. I used a for loop for this because I need to print those same numbers with the len(). Can someone tell me what i am doing wrong?
```
for binairy in ["101011101"]:
binairy = binairy ** 2
print(binairy)
print(len(binairy))
```
>
> TypeErro... | 2022/09/21 | [
"https://Stackoverflow.com/questions/73805667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14861522/"
] | you used a list but you could use a string directly
```
def binary_to_decimal(binary):
decimal = 0
for digit in binary:
decimal = decimal*2 + int(digit)
return decimal
print(binary_to_decimal("1010"))
``` | ["101011101"] is a list with a single string. "101011101" is a list of characters. Look at this:
```py
for let_me_find_out in ["101011101"]:
print(let_me_find_out)
for let_me_find_out in "101011101":
print(let_me_find_out)
```
With this knowledge, you can now start your binary conversion:
```py
for binairy... | 13,002 |
51,793,379 | In my file, I have a large number of images in **jpg** format and they are named **[fruit type].[index].jpg**.
Instead of manually making three new sub folders to copy and paste the images into each sub folder, is there some python code that can parse through the name of the images and choose where to redirect the i... | 2018/08/10 | [
"https://Stackoverflow.com/questions/51793379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8238011/"
] | Here’s the code to do just that, if you need help merging this into your codebase let me know:
```
import os, os.path, shutil
folder_path = "test"
images = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]
for image in images:
folder_name = image.split('.')[0]
new_path = ... | If they are all formatted similarly to the three fruit example you gave, you can simply do a string.split(".")[0] on each filename you encounter:
```
import os
for image in images:
fruit = image.split(".")[0]
if not os.path.isdir(fruit):
os.mkdir(fruit)
os.rename(os.path.join(fruit, image))
``` | 13,005 |
71,480,638 | Atttempted to implement jit decorator to increase the speed of execution of my code. Not getting proper results. It is throughing all sorts of errors.. Key error, type errors, etc..
The actual code without numba is working without any issues.
```
# The Code without numba is:
df = pd.DataFrame()
df['Serial'] = [865,866... | 2022/03/15 | [
"https://Stackoverflow.com/questions/71480638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15922454/"
] | You can only use `df['A'].values[:]` if the column `A` exists in the dataframe. Otherwise you need to create a new one, possibly with `df['A'] = ...`.
Moreover, the trick with `astype(object)` applies for string but not for numbers. Indeed, string-based dataframe columns do apparently not use Numpy string-based array ... | This Code is giving list to list convertion typeerror.
```
from numba import njit
df = pd.DataFrame()
df['Serial'] = [865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,880]
df['Value'] = [586,586.45,585.95,585.85,585.45,585.5,586,585.7,585.7,585.5,585.5,585.45,585.3,584,584,585]
df['Ref'] = [586.35,586.1,586... | 13,007 |
48,757,747 | Let's consider a file called `test1.py` and containing the following code:
```
def init_foo():
global foo
foo=10
```
Let's consider another file called `test2.py` and containing the following:
```
import test1
test1.init_foo()
print(foo)
```
Provided that `test1` is on the pythonpath (and gets imported ... | 2018/02/13 | [
"https://Stackoverflow.com/questions/48757747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4961888/"
] | For this you need to use [`selModel`](https://docs.sencha.com/extjs/5.1.4/api/Ext.grid.Panel.html#cfg-selModel) config for [`grid`](https://docs.sencha.com/extjs/5.1.4/api/Ext.grid.Panel.html) using [`CheckboxModel`](https://docs.sencha.com/extjs/5.1.4/api/Ext.selection.CheckboxModel.html).
* A **selModel** Ext.select... | I achieved by adding keyup,keydown listeners. Please find the fiddle where i updated the code.
<https://fiddle.sencha.com/#view/editor&fiddle/2d98> | 13,008 |
56,314,194 | I want to get random item from a list, also I don't want some items to be consider while `random.choice()`. Below is my data structure
```
x=[
{ 'id': 1, 'version':0.1, 'ready': True }
{ 'id': 6, 'version':0.2, 'ready': True }
{ 'id': 4, 'version':0.1, 'ready': False }
{ 'id': 35, 'version':0.1, 'ready': Fals... | 2019/05/26 | [
"https://Stackoverflow.com/questions/56314194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2200798/"
] | Have a look at Dotplant2 which uses Yii2 and currency conversion tables in the backend. Specifically these files.
1. components/payment/[PaypalPayment.php](https://github.com/DevGroup-ru/dotplant2/blob/master/application/components/payment/PayPalPayment.php) and 2. their [CurrencyHelper.php](https://github.com/DevGro... | I got this from PayPal support:
>
> Unfortunately domestic transaction is not possible to receive in USD and similarly international transaction should be in USD. There is no way to have single currency for both the transactions. Thanks and regards,
>
>
> | 13,009 |
4,214,031 | I have a PHP website and I would like to execute a very long Python script in background (300 MB memory and 100 seconds). The process communication is done via database: when the Python script finishes its job, it updates a field in database and then the website renders some graphics, based on the results of the Python... | 2010/11/18 | [
"https://Stackoverflow.com/questions/4214031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2203413/"
] | First off [set\_time\_limit(0);](http://php.net/set_time_limit) will make your script run for ever so timeout shouldn't be an issue. Second any \*exec call in PHP does NOT use the PATH by default (might depend on configuration), so your script will exit without giving any info on the problem, and it quite often ends up... | I found that the issue when I tried this was the simple fact that I did not compile the source on the server I was running it on. By compiling on your local machine and then uploading to your server, it will be corrupted in some way. shell\_exec() should work by compiling the source you are trying to run on the same se... | 13,010 |
11,533,939 | If I have more than one class in a python script, how do I call a function from the first class in the second class?
Here is an Example:
```
Class class1():
def function1():
blah blah blah
Class class2():
*How do I call function1 to here from class1*
``` | 2012/07/18 | [
"https://Stackoverflow.com/questions/11533939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1481620/"
] | Functions in classes are also known as methods, and they are invoked on objects. The way to call a method in class1 from class2 is to have an instance of class1:
```
class Class2(object):
def __init__(self):
self.c1 = Class1()
self.c1.function1()
``` | The cleanest way is probably through inheritance:
```
class Base(object):
def function1(self):
# blah blah blah
class Class1(Base):
def a_method(self):
self.function1() # works
class Class2(Base):
def some_method(self):
self.function1() # works
c1 = Class1()
c1.function1() # w... | 13,020 |
27,296,373 | I'm importing data with XLRD. The overall project involves pulling data from existing Excel files, but there are merged cells. Essentially, an operator is accounting for time on one of 3 shifts. As such, for each date on the grid they're working with, there are 3 columns (one for each shift). I want to change the UI as... | 2014/12/04 | [
"https://Stackoverflow.com/questions/27296373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2711535/"
] | I dont think this is a good application for a comprehension, and an explicit loop would be better:
```
lst = [41665.0, '', '', 41666.0, '', '', 41667.0, '', '', 41668.0, '', '', 41669.0, '', '', 41670.0, '', >>> lst = [41665.0, '', '', 41666.0, '', '', 41667.0, '', '', 41668.0, '', '', 41669.0, '', '', 41670.0, '', ''... | Another solution,
```
>>> l = [41665.0, '', '', 41666.0, '', '', 41667.0, '', '', 41668.0, '', '', 41669.0, '', '', 41670.0, '', '', 41671.0, '', '']
>>> lst = [ item for item in l if item is not '']
>>> [ v for item in zip(lst,lst,lst) for v in item ]
[41665.0, 41665.0, 41665.0, 41666.0, 41666.0, 41666.0, 41667.0, 41... | 13,021 |
38,971,465 | I want to use the stack method to get reverse string in this revers question.
"Write a function revstring(mystr) that uses a stack to reverse the characters in a string."
This is my code.
```
from pythonds.basic.stack import Stack
def revstring(mystr):
myStack = Stack() //this is how i have myStack
... | 2016/08/16 | [
"https://Stackoverflow.com/questions/38971465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6712244/"
] | Here's 3 solutions to the same problem, just pick one:
**1ST SOLUTION**
Fixing your solution, you almost got it, you just need to indent properly
your blocks like this:
```
from pythonds.basic.stack import Stack
def revstring(mystr):
myStack = Stack() # this is how i have myStack
for ch in mystr: # loopin... | * the `while` should not be in the `for`
* the `return` should be outside, not in the `while`
**code:**
```
from pythonds.basic.stack import Stack
def revstring(mystr):
myStack = Stack() # this is how i have myStack
for ch in mystr: # looping through characters in my string
myStack.push(... | 13,022 |
69,897,646 | I'm using seaborn.displot to display a distribution of scores for a group of participants.
Is it possible to have the y axis show an actual percentage (example below)?
This is required by the audience for the data.
Currently it is done in excel but It would be more useful in python.
```py
import seaborn as sns
data... | 2021/11/09 | [
"https://Stackoverflow.com/questions/69897646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2015461/"
] | As mentioned by @JohanC, the y axis for a KDE is a [density](https://en.wikipedia.org/wiki/Probability_density_function), not a proportion, so it does not make sense to convert it to a percentage.
You'd have two options. One would be to plot a KDE curve over a histogram with histogram counts expressed as percentages:
... | * [`seaborn.displot`](https://seaborn.pydata.org/generated/seaborn.displot.html) is a figure-level plot providing access to several approaches for visualizing the univariate or bivariate distribution of data ([histplot](https://seaborn.pydata.org/generated/seaborn.histplot.html), [kdeplot](https://seaborn.pydata.org/ge... | 13,023 |
73,098,560 | Try to use pytorch, when I do
import torch
```
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-2-eb42ca6e4af3> in <module>
----> 1 import torch
C:\Big_Data_app\Anaconda3\lib\site-packages\torch\__in... | 2022/07/24 | [
"https://Stackoverflow.com/questions/73098560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14733291/"
] | I solved the problem.
Just reinstall your Anaconda.
**!!Warning!!: you will lose your lib.**
Referring solution:
[Problem with Torch 1.11](https://discuss.pytorch.org/t/problem-with-torch-1-11/146885) | The version may not be exactly as same as yours, but maybe [this question](https://stackoverflow.com/questions/63187161/error-while-import-pytorch-module-the-specified-module-could-not-be-found) asked on 2020-09-04 helps. | 13,024 |
56,303,279 | when i run this code:
```
#!/usr/bin/env python
import scapy.all as scapy
from scapy_http import http
def sniff(interface):
scapy.sniff(iface=interface, store=False, prn=process_sniffed_packet)
def process_sniffed_packet(packet):
if packet.haslayer(http.HTTPRequest):
print(packet)
sniff("eth0")
``... | 2019/05/25 | [
"https://Stackoverflow.com/questions/56303279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11533009/"
] | You can fix this problem by using `python2` instead of `python3`. If you don't want to change your python version then you'd need to make some changes to `scapy-http`'s library codes. From your traceback I can see that file is located at: `/usr/local/lib/python3.7/dist-packages/scapy_http/http.py`. Now open that file w... | You're using `scapy_http` in addition to `scapy`.
`scapy_http` hasn't been update in a while, and has poor compatibility with Python 3+
Feel free to have a look at <https://github.com/secdev/scapy/pull/1925> : it's not merged in Scapy yet (should be sometimes soon I guess) but it's an updated & improved port of `scapy... | 13,027 |
65,977,278 | I have a image:
It has some time in it.
But I need to convert it to this using python:
this:
[](https://i.stack.imgur.com/j3iIp.png)
to this
[](https://i.stack.imgur.com/d61GK.png)
... | 2021/01/31 | [
"https://Stackoverflow.com/questions/65977278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13994535/"
] | Try this out.
```py
sampleList = [
'CustomerA', 'Yes', 'No', 'No',
'CustomerB', 'No', 'No', 'No',
'CustomerC', 'Yes', 'Yes', 'No'
]
preferredOutput = [
tuple(sampleList[n : n + 4])
for n in range(0, len(sampleList), 4)
]
print(preferredOutput)
# OUTPUT (IN PRETTY FORM)
#
# [
# ('CustomerA'... | You can use list comprehension `output=[tuple(sampleList[4*i:4*i+4]) for i in range(3)]` | 13,028 |
49,220,569 | a=[('<https://www.google.co.in/search?q=kite+zerodha&oq=kite%2Cz&aqs=chrome.1.69i57j0l5.4766j0j7&sourceid=chrome&ie=UTF-8>', 1), ('<https://kite.zerodha.com/>', 1), ('<https://kite.trade/connect/login?api_key=xyz>', 1)]
how to get value of api\_key which is xyz from above mentioned `a`.
please help me to write code in... | 2018/03/11 | [
"https://Stackoverflow.com/questions/49220569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9337404/"
] | Just looping over all elements and parsing url to get the api\_key, have a look into below code:
```
from urlparse import urlparse, parse_qs
a=[('https://www.google.co.in/search?q=kite+zerodha&oq=kite%2Cz&aqs=chrome.1.69i57j0l5.4766j0j7&sourceid=chrome&ie=UTF-8', 1), ('https://kite.zerodha.com/', 1), ('https://kite.t... | This will work too. Hope this helps.
>
> * Find all items that has the keyword 'api\_key' (in url[0]),
> * Split it into columns, delimited by '=' (split by '=')
> * The last entry ([-1]) will be the answer (xyz).
>
>
>
```
a=[('https://www.google.co.in/search?q=kite+zerodha&oq=kite%2Cz&aqs=chrome.1.69i57j0l5.476... | 13,029 |
55,905,144 | Here is an image showing Python scope activity (version 3.6 and target x64):
Python Scope
[](https://i.stack.imgur.com/QqZbP.png)
The main problem is the relation between both invoke python methods, the first one is used to start the class object, and the second one to access ... | 2019/04/29 | [
"https://Stackoverflow.com/questions/55905144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11425716/"
] | I believe that this activity was designed with simple scripts in mind, not with entire classes. [Here's](https://forum.uipath.com/t/python-script-with-class-and-object/111110/3) an article on their Community Forum where user Sergiu.Wittenberger goes into more details.
Let's start with the Load Python Script activity:
... | I would like to add to what the above user said that you have to make sure that the imports you use are in the global site-packages, and not in a venv as Studio doesn't have access to that.
Moreoever, always add this:
```
import os
import sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
```
to the ... | 13,030 |
59,317,919 | Training an image classifier using `.fit_generator()` or `.fit()` and passing a dictionary to `class_weight=` as an argument.
I never got errors in TF1.x but in 2.1 I get the following output when starting training:
```none
WARNING:tensorflow:sample_weight modes were coerced from
...
to
['...']
```
What d... | 2019/12/13 | [
"https://Stackoverflow.com/questions/59317919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1838257/"
] | This seems like a bogus message. I get the same warning message after upgrading to TensorFlow 2.1, but I do not use any class weights or sample weights at all. I do use a generator that returns a tuple like this:
```
return inputs, targets
```
And now I just changed it to the following to make the warning go away:
... | I have taken your Gist and installed Tensorflow 2.0, instead of TFA and it worked without any such Warning.
Here is the [Gist](https://colab.sandbox.google.com/gist/rmothukuru/e9d65d1119d90c1ec0d435249f3f5d01/untitled2.ipynb) of the complete code. Code for installing the Tensorflow is shown below:
```
!pip install t... | 13,031 |
21,083,760 | I have two files that are tab delimited.I need to compare file 1 column 3 to file 2 column 1 .If there is a match I need to write column 2 of file 2 next to the matching line in file 1.here is a sample of my file:
file 1:
```
a rao rocky1 beta
b rao buzzy2 beta
c Rachel rocky2 alpha
```
file 2:
```
rocky1 highli... | 2014/01/13 | [
"https://Stackoverflow.com/questions/21083760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2464553/"
] | ```
import sys
# Usage: python SCRIPT.py FILE1 FILE2 > OUTPUT
file1, file2 = sys.argv[1:3]
# Store info from the smaller file in a dict.
d = {}
with open(file2) as fh:
for line in fh:
k, v = line.split()
d[k] = v
# Process the bigger file line-by-line, printing to standard output.
with open(f... | ```
with open('outfile.txt', 'w') as outfile:
with open('file1.txt', 'r') as f1:
with open('file2.txt', 'r') as f2:
for f1line in f1:
for f2line in f2:
## remove new line character at end of each line
f1line = f1line.rs... | 13,037 |
56,504,180 | I have set up a Raspberry Pi connected to an LED strip which is controllable from my phone via a Node server I have running on the RasPi. It triggers a simple python script that sets a colour.
I'm looking to expand the functionality such that I have a python script continuously running and I can send colours to it tha... | 2019/06/08 | [
"https://Stackoverflow.com/questions/56504180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1635908/"
] | Just delete keys that must be exclude for invalid user:
```
myReportsHeader = () => {
const { valid_user } = this.props;
const { tableHeaders } = this.props.tableHeaders
const { labels: tableLabels } = tableHeaders
if (!valid_user) {
delete tableLabels['tb4']
}
return tableLabels
}
```
[Delete operat... | You can first construct an object with default values. Then add additional property if the condition is true and finally return it e.g:
```
const obj = {
tb1: tableLabels.tb1,
tb2: tableLabels.tb2,
tb3: tableLabels.tb3,
tb5: tableLabels.tb5,
tb6: tableLabels.tb6,
tb7: tableLabels.tb7,
tb8: ... | 13,041 |
67,899,519 | I have a json file with size in 500 MB with structure like
```
{"user": "abc@xyz.com","contact":[{"name":"Jack "John","number":"+1 23456789"},{"name":"Jack Jill","number":"+1 232324789"}]}
```
Issue is when i parse this string with pandas read\_json, I get error
`Unexpected character found when decoding object valu... | 2021/06/09 | [
"https://Stackoverflow.com/questions/67899519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9025131/"
] | In general here is no robust way to fix this, nor to ignore any part of the row nor even to ignore the whole row because if a quoted string can contain quotes and can also contain `:`s and `,`s then a messed up string can look exactly like a valid set of fields.
Having said that, if we target only the "name" field and... | You can try removing that extra " using regex `("[\s\w]*)(")([\s\w]*")`.
The regex try to match any string with spaces/alphabets followed by a quote and then followed again by spaces/alphabets and removing that additional quote.
This will work for the given problem but for more complex patterns, you may have to tweak... | 13,045 |
50,848,226 | Currently I am trying to run Stardew Valley from python by doing this:
```
import subprocess
subprocess.call(['cmd', 'D:\SteamR\steamapps\common\Stardew Valley\Stardew Valley.exe'])
```
However, this fails and only opens a CMD window. I have a basic understanding of how to launch programs from python, but I do not u... | 2018/06/14 | [
"https://Stackoverflow.com/questions/50848226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4848801/"
] | Can you try using the steam commandline using the appid of the game:
```
subprocess.call(r"C:\Program Files (x86)\Steam\Steam.exe -applaunch 413150")
```
you can find the app id in the "web document tab" from the desktop shortcut properties
(which can be generated by right click and select create desktop shortcut... | You don't have to use `cmd`, you can start the `.exe` directly.
Additionally you should be aware that `\` is used to escape characters in Python strings, but should not be interpreted specially in Windows paths. Better use raw strings prefixed with `r` for Windows paths, which disable such escapes:
```
import subproc... | 13,046 |
11,108,461 | I'm having a strange problem while trying to install the Python library `zenlib`, using its `setup.py` file. When I run the `setup.py` file, I get an import error, saying
>
> ImportError: No module named Cython.Distutils`
>
>
>
but I do have such a module, and I can import it on the python command line without a... | 2012/06/19 | [
"https://Stackoverflow.com/questions/11108461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1467306/"
] | Install Cython:
```
pip install cython
``` | In the CLI-python, import sys and look what's inside sys.path
Then try to use `export PYTHONPATH=whatyougot` | 13,049 |
38,557,849 | A peak finding program in a 1-D python list which returns a peak with its index if for an index 'x' in the list 'arr' if (arr[x] > arr[x+1] and arr[x] > arr[x-1]).
Special case
Case 1 : In case of the first element. Only compare it to the second element. If arr[x] > arr[x+1], peak found.
Case 2 : Last element. Compare ... | 2016/07/24 | [
"https://Stackoverflow.com/questions/38557849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4254959/"
] | for example, let us create a middleware function that will handle CORS using:
*[github.com/buaazp/fasthttprouter](https://github.com/buaazp/fasthttprouter)* and *[github.com/valyala/fasthttp](https://github.com/valyala/fasthttp)*
```
var (
corsAllowHeaders = "authorization"
corsAllowMethods = "HEAD,GE... | Example of auth middleware for fasthttp & fasthttprouter (new versions)
```
type Middleware func(h fasthttp.RequestHandler) fasthttp.RequestHandler
type AuthFunc func(ctx *fasthttp.RequestCtx) bool
func NewAuthMiddleware(authFunc AuthFunc) Middleware {
return func(h fasthttp.RequestHandler) fasthttp.RequestHandler... | 13,059 |
12,902,178 | >
> **Possible Duplicate:**
>
> [Compare two different files line by line and write the difference in third file - Python](https://stackoverflow.com/questions/7757626/compare-two-different-files-line-by-line-and-write-the-difference-in-third-file)
>
>
>
The logic in my head works something like this...
for lin... | 2012/10/15 | [
"https://Stackoverflow.com/questions/12902178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1747993/"
] | assuming I understand what you want to do .... use set intersection :)
```
for line in newlines:
if set(line.split()) & set(xlines): #set intersection
print "overlap between xlines and current line"
break
else:
fileresult.write(item)
``` | I presume this is what you want to do:
```
outfile = file("outfile.txt", "w")
lines_to_check_for = [ line for line in file("list.txt", "r") ]
for line in file("testing.txt", "r"):
if not line in lines_to_check_for:
outfile.write(line)
```
This will read all the lines in `list.txt` into an array, and then... | 13,060 |
11,452,887 | Based on this example of a line from a file
```
1:alpha:beta
```
I'm trying to get python to read the file in and then line by line print whats after the 2nd `':'`
```
import fileinput
#input file
x = fileinput.input('ids.txt')
strip_char = ":"
for line in x:
strip_char.join(line.split(strip_char)[2:])
```
... | 2012/07/12 | [
"https://Stackoverflow.com/questions/11452887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | For the data format given this will work:
```
with open('data.txt') as inf:
for line in inf:
line = line.strip()
line = line.split(':')
print ':'.join(line[2:])
```
For `'1:alpha:beta'` the output would be `'beta'`
For `'1:alpha:beta:gamma'` the output would be `'beta:gamma'` (Thanks fo... | Values returned by functions aren't automatically sent to stdout in non-interactive mode, you have to explicitly print them.
So, for Python 2, use `print line.split(strip_char, 2)[2]`. If you ever use Python 3, it'll be `print(line.split(strip_char, 2)[2])`.
(Props to Jon Clements, I forgot you could limit how many t... | 13,062 |
48,753,297 | I am trying to evaluate istio and trying to deploy the bookinfo example app provided with the istio installation. While doing that, I am facing the following issue.
```
Environment: Non production
1. Server Node - red hat enterprise linux 7 64 bit VM [3.10.0-693.11.6.el7.x86_64]
Server in customer secure vpn with n... | 2018/02/12 | [
"https://Stackoverflow.com/questions/48753297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3675410/"
] | For your example string, you could remove the `^` like:
[`(?<=FN=).+?(?=&.+?$)`](https://regex101.com/r/33BiQU/1)
`^` means assert the position at start of the string.
For this example, you could also write this as:
[`(?<=FN=)[^&]+`](https://regex101.com/r/uIORIF/1)
**Explanation**
* `(?<=` Positive lookbehind th... | Instead of a regex, you could use the "proper" way of parsing the URI and the query string:
```
Imports System.Web
Module Module1
Sub Main()
Dim u = New Uri("https://portal-gamma.myColgate.com/sites/ENG/Pages/r.aspx?RT=Modify Support&Element=Business Direct&SE=Chain Supply&FN=Freight Forwarder Standard O... | 13,067 |
63,461,566 | Currently using selenium in python and was trying to for loop after locating element by "img" tags in whole webpage. I am trying to save all the urls and img names to my 2 arrays.
```
imgurl = []
imgname = []
allimgtags = browser.find_element_by_tag_name("img")
for a in len(allimgtags):
imgurl.append(wholeimgtags... | 2020/08/18 | [
"https://Stackoverflow.com/questions/63461566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14082479/"
] | You can refer the below sample code:
```
class SampleAdapter(private var list: List<String>,
private val viewmodel: SampleViewModel,
private val lifecycleOwner: LifecycleOwner) : RecyclerView.Adapter<SampleAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewT... | If i understand correctly from [this page](https://medium.com/@stephen.brewer/an-adventure-with-recyclerview-databinding-livedata-and-room-beaae4fc8116) it is not best to pass the `lifeCycleOwner` to a `RecyclerView.Adapter` binding item, since:
>
> When a ViewHolder has been
> detached, meaning it is not currently v... | 13,068 |
32,177,869 | I have several pods, for example a python web app and a redis(shared by other apps), so I need to place redis in a separate pod. But they are all use the same subnet from docker(172.17.0.0/16) or even the same ip address. how can app pods talk with redis pod?
Maybe what I want ask is what's the best way to setup multi... | 2015/08/24 | [
"https://Stackoverflow.com/questions/32177869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853876/"
] | How did you set up Kubernetes? I'm not aware of any installation scripts that put pod IPs into a 172 subnet.
But in general, assuming Kubernetes has been set up properly (ideally using one of the provided scripts), using a [service object](https://github.com/kubernetes/kubernetes/blob/release-1.0/docs/user-guide/servi... | I realize maybe the question was a bit vague:
if what you want is for your app to talk to the redis service, then set a service for redis (with a name of 'redis' for example) and then the redis service will be accessible simply by calling it by its hostname 'redis'
check the guestbook example that sets up a Redis mas... | 13,077 |
69,602,778 | I have installed the library in Base conda environment (the only one I have):
```
(base) C:\Users\44444>conda install graphviz
Collecting package metadata (current_repodata.json): done
Solving environment: done
# All requested packages already installed.
```
Set the path in System -> Environment Variables : to both... | 2021/10/17 | [
"https://Stackoverflow.com/questions/69602778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16339433/"
] | You have only installed the `graphiz` software, not the python interface to it. For that you will need [this package](https://anaconda.org/conda-forge/python-graphviz) which you can install with
```
conda install -c conda-forge python-graphviz
``` | Don't add conda's folders to the system PATH manually. What you need to do to work with Anaconda is activating the environment via
```
conda activate
```
This will add all the following folders temporarily to the PATH:
```
C:\Users\44444\anaconda3
C:\Users\44444\anaconda3\Library\mingw-w64\bin
C:\Users\44444\anacon... | 13,082 |
52,089,002 | I was trying to install a plugin for tmux called powerline. I was installing some thing on brew like PyPy and python.
Now when I try to open a vim file I get:
```
dyld: Library not loaded: /usr/local/opt/python/Frameworks/Python.framework/Versions/3.6/Python
Referenced from: /usr/local/bin/vim
Reason: image not foun... | 2018/08/30 | [
"https://Stackoverflow.com/questions/52089002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9470570/"
] | `=AVERAGE.WEIGHTED(FILTER(A:A,ISNUMBER(A:A)),FILTER(B:B,ISNUMBER(A:A)))`
`=SUM(FILTER(A:A*B:B / sum(FILTER(B:B,ISNUMBER(A:A))),ISNUMBER(A:A)))`
`=SUM(FILTER(A:A*B:B / (sum(B:B) - SUMIF(A:A,"><", B:B)),ISNUMBER(A:A)))`
case both columns contain strings, add 1 more condition for each formula:
`=AVERAGE.WEIGHTED(FILTE... | So let us suppose our numbers (we hope) sit in A2:A4 and the weights are in B2:B4. In C2, place
```
=if(and(ISNUMBER(A2),isnumber(B2)),A2,"")
```
and drag that down to C4 to keep only actual numbers for which we have weights.
Similarly in D2 (and drag to D4), use
```
=if(and(ISNUMBER(A2),isnumber(B2)),B2,"")
```... | 13,083 |
18,560,993 | This may be a well-known question stored in some FAQ but i can't google the solution. I'm trying to write a scalar function of scalar argument but allowing for ndarray argument. The function should check its argument for domain correctness because domain violation may cause an exception. This example demonstrates what ... | 2013/09/01 | [
"https://Stackoverflow.com/questions/18560993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1038377/"
] | This will work fine in NumPy >= 1.9 (not released as of writing this). On previous versions you can work around by an extra `np.asarray` call:
```
x[np.asarray(x > 0)] = 0
``` | Could you call `f([1.0])` instead?
Otherwise you can do:
```
x = np.asarray(x)
if x.ndim == 0:
x = x[..., None]
``` | 13,084 |
32,395,635 | I'm very new to odoo and python and was wondering if I could get some help getting my module to load. I've been following the odoo 8 documentation very closely and can't get anything to appear in the local modules part. (Yes, I have clicked refresh/update module list).
I have also made sure that I put the correct path... | 2015/09/04 | [
"https://Stackoverflow.com/questions/32395635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5300262/"
] | I think you might have missed to include the addon directory which includes the custom module.
It can be accomplished via two methods.
1. You can add to, the addons\_path directive in openerp-server.conf, (separate paths with a comma)
```
eg: addons_path = /opt/openerp/server/openerp/addons,custom_path_here
```
2.... | You need to restart your service (odoo-service). | 13,085 |
58,506,732 | **Objective**: to extract the first email from an email thread
**Description**: Based on manual inspection of the emails, I realized that the next email in the email thread always starts with a set of From, Sent, To and Subject
**Test Input**:
```
Hello World from: the other side of the first email
from: this
sen... | 2019/10/22 | [
"https://Stackoverflow.com/questions/58506732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4457330/"
] | To only get the first match, you could use a capturing group and match exactly what should follow.
```
^(.*)\r?\n\s*\r?\nfrom:.*\r?\nsent:.*\r?\nto:.*\r?\nsubject:
```
* `^` Start of string
* `(.*)` Match any char except a newline 0+ times
* `\r?\n\s*` Match a newline followed by 0+ times a whitespace char using `\s... | Maybe I am misunderstanding, but why don't you just do this:
```
re.compile(r"^.*from:\s(\w+@\w+\.\w+)")
```
This will find the first string in "email-form" (group 1) after the first "from: " at beginning of the string. | 13,086 |
34,998,210 | How do I pip install pattern packages in python 3.5?
While in CMD:
```
pip install pattern
syntaxerror: missing parentheses in call to 'print'
```
Shows error:
```
messageCommand "python setup.py egg_info" failed with error
code 1 in temp\pip-build-3uegov4d\pattern
```
`seaborn` and `tweepy` were all suc... | 2016/01/25 | [
"https://Stackoverflow.com/questions/34998210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5818150/"
] | The short answer at the moment is - you can't. They haven't quite finished the port to python3 yet.
There is alleged compatibility in the development branch but the recommended manual setup didn't work for me (in virtualenv) - it fails in a different way.
<https://github.com/clips/pattern/tree/development>
The portin... | Additionally, I was facing :
```
"BadZipFile: File is not a zip file" error while importing from pattern.
```
This is because `sentiwordnet` which is out of date in nltk. So comment it in :
```
C:\Anaconda3\Lib\site-packages\Pattern-2.6-py3.5.egg\pattern\text\en\wordnet\_init.py
```
Make sure the necessary corpo... | 13,089 |
8,891,099 | I seem to have stumbled across a quirk in Django custom model fields. I have the following custom modelfield:
```
class PriceField(models.DecimalField):
__metaclass__ = models.SubfieldBase
def to_python(self, value):
try:
return Price(super(PriceField, self).to_python(value))
excep... | 2012/01/17 | [
"https://Stackoverflow.com/questions/8891099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/836049/"
] | Answered my own question: This apparently is a Django bug. values\_list does not deserialize the database data.
It's being tracked here: <https://code.djangoproject.com/ticket/9619> and is pending a design decision. | Just to note that this was resolved in Django 1.8 with the addition of the `from_db_value` method on custom fields.
See <https://docs.djangoproject.com/en/1.8/howto/custom-model-fields/#converting-values-to-python-objects> | 13,099 |
10,354,000 | I using python 2.7 and openCV 2.3.1 (win 7).
I trying open video file:
```
stream = cv.VideoCapture("test1.avi")
if stream.isOpened() == False:
print "Cannot open input video!"
exit()
```
But I have warning:
```
warning: Error opening file (../../modules/highgui/src/cap_ffmpeg_impl_v2.hpp:394)
```
If use video ca... | 2012/04/27 | [
"https://Stackoverflow.com/questions/10354000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1361499/"
] | Try using `cv.CaptureFromFile()` instead.
Copy this code if you must: [Watch Video in Python with OpenCV](http://web.michaelchughes.com/how-to/watch-video-in-python-with-opencv). | you can use the new interface of OpenCV (cv2), the object oriented one, which is binded from c++.
I find it easier and more readable.
note: if your open a picture with this, the fps doesn't mean anything, so the picture stays still.
```
import cv2
import sys
try:
vidFile = cv2.VideoCapture(sys.argv[1])
except:
... | 13,100 |
43,044,060 | There is this similar [question](https://stackoverflow.com/questions/22214086/python-a-program-to-find-the-length-of-the-longest-run-in-a-given-list), but not quite what I am asking.
Let's say I have a list of ones and zeroes:
```
# i.e. [1, 0, 0, 0, 1, 1, 1, 1, 0, 1]
sample = np.random.randint(0, 2, (10,)).tolist()
... | 2017/03/27 | [
"https://Stackoverflow.com/questions/43044060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3120489/"
] | You can first create tuples of indices and values with `enumerate(..)`. Next you `groupby` but on the second element of the tuple, and finally you map them back on the second index. Like:
```
**map(lambda x:x[0][0],** # obtain the index of the first element
sorted([list(l) for _,l in itertools.groupby(**enumerate(... | You can use a `groupby` the `sorted` function with generator function to do this efficiently.
```
from itertools import groupby
from operator import itemgetter
data = [1, 0, 0, 0, 1, 1, 1, 1, 0, 1]
def gen(items):
for _, elements in groupby(enumerate(items)):
indexes, values = zip(*elements)
yiel... | 13,103 |
60,182,910 | In my droplet is running several PHP websites, recently I tried to deploy a Django website that I build. But it's doesn't work properly.
I will explain the step that I did.
1, Pointed a Domain name to my droplet.
2, Added Domain name using Plesk Add Domain Option.
3, Uploaded the Django files to httpdocs by Plesk ... | 2020/02/12 | [
"https://Stackoverflow.com/questions/60182910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9892045/"
] | [Django Runserver is not a production one](https://vsupalov.com/django-runserver-in-production/), it should be used only for development. That's why you need to explicitly type in the port and it sometimes go down because of code reload or other triggers.
Check [Gunicorn](https://gunicorn.org/) for example, as a prod... | I suggest following this [guide](https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04). Covers initial setup of django with gunicorn and nginx which is essential for deployment, you don't have to add the port to access the site. It doesn't cover how to a... | 13,104 |
3,631,510 | how to do a zoom in/out with wxpython? what are the very basics for this purpose? I googled this, but could not find much, thanks!! | 2010/09/02 | [
"https://Stackoverflow.com/questions/3631510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/427183/"
] | JavaScript is single threaded. So this wouldn't apply to JavaScript.
However, it is possible to spawn multiple threads through a very **limited** [Worker](http://www.w3.org/TR/workers/#dedicated-workers-and-the-worker-interface) interface introduced in HTML5 and is already available on some browsers. From an [MDC arti... | For most things in JavaScript there's one thread, so there's no method for this, since it'd invariable by "1" where you could access such information. There are more threads in the background for events and queuing (handled by the browser), but as far as your code's concerned, there's a main thread.
Java != JavaScript... | 13,105 |
3,664,124 | I posted this basic question before, but didn't get an answer I could work with.
I've been writing applications on my Mac, and have been physically making them into .app bundles
(i.e., making the directories and plist files by hand). But when I open a file in the application by right clicking on the file in finder and... | 2010/09/08 | [
"https://Stackoverflow.com/questions/3664124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428582/"
] | The file is passed by the Apple Event, see [this Apple document](http://developer.apple.com/mac/library/documentation/cocoa/conceptual/ScriptableCocoaApplications/SApps_handle_AEs/SAppsHandleAEs.html#//apple_ref/doc/uid/20001239-BBCBCIJE). You need to receive that from inside your Python script. If it's a PyObjC script... | Are we referring to the file where per-user binding of file types/extensions are set to point to certain applications?
```
~/Library/Preferences/com.apple.LaunchServices.plist
```
The framework is [launchservices](http://developer.apple.com/library/mac/#documentation/Carbon/Conceptual/LaunchServicesConcepts/LSCIntr... | 13,110 |
52,079,637 | I have been trying to scroll the output of a script run via Ipython in a separate window/session created by tmux (off notebook, meaning that I am not using Ipython notebook as usual: I am just using Ipython). I see that, while the program is loading the output, I can’t scroll the window to see what has been published b... | 2018/08/29 | [
"https://Stackoverflow.com/questions/52079637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10285919/"
] | I finally found the answer to my problem right here <https://superuser.com/questions/209437/how-do-i-scroll-in-tmux> , it did not depend on Ipython but on tmux as I was suspecting. To scroll on tmux press ctrl+b and then [, so that you can enter the copy mode, and then use arrows or page up/down to scroll through the w... | Use threads for data processing, visualization, and gui interaction that is how you can avoid freez. | 13,117 |
38,079,862 | Sometimes this code works just fine and runs through, but other times it throws the int object not callable error. I am not real sure as to why it is doing so.
```
for ship in ships:
vert_or_horz = randint(0,100) % 2
for size in range(ship.size):
if size == 0:
ship.location.append((random_r... | 2016/06/28 | [
"https://Stackoverflow.com/questions/38079862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2759574/"
] | You might be able to directly call [TransferHandler#exportAsDrag(...)](http://docs.oracle.com/javase/8/docs/api/javax/swing/TransferHandler.html#exportAsDrag-javax.swing.JComponent-java.awt.event.InputEvent-int-) method in `MouseMotionListener#mouseDragged(...)`:
```
import java.awt.*;
import java.awt.event.*;
import ... | >
> Selection mode should only be possible via click and should be extendable via shift + click, not via dragging
>
>
>
You may be able to alter the behavior by overriding JTable's `processMouseEvent` method with some additional logic. When a button down event occurs - and shift is not down - alter the selection o... | 13,118 |
49,280,016 | I'm trying to create a dataset from a CSV file with 784-bit long rows. Here's my code:
```
import tensorflow as tf
f = open("test.csv", "r")
csvreader = csv.reader(f)
gen = (row for row in csvreader)
ds = tf.data.Dataset()
ds.from_generator(gen, [tf.uint8]*28**2)
```
I get the following error:
```
----------------... | 2018/03/14 | [
"https://Stackoverflow.com/questions/49280016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128156/"
] | The `generator` argument (perhaps confusingly) should not actually be a generator, but a callable returning an iterable (for example, a generator function). Probably the easiest option here is to use a `lambda`. Also, a couple of errors: 1) [`tf.data.Dataset.from_generator`](https://www.tensorflow.org/api_docs/python/t... | [From the docs](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_generator), which you linked:
>
> The `generator` argument must be a callable object that returns an
> object that support the `iter()` protocol (e.g. a generator function)
>
>
>
This means you should be able to do something like thi... | 13,119 |
49,244,935 | I am trying to execute a Python program as a background process inside a container with `kubectl` as below (`kubectl` issued on local machine):
`kubectl exec -it <container_id> -- bash -c "cd some-dir && (python xxx.py --arg1 abc &)"`
When I log in to the container and check `ps -ef` I do not see this process running... | 2018/03/12 | [
"https://Stackoverflow.com/questions/49244935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1650281/"
] | The [nohup](https://en.wikipedia.org/wiki/Nohup#Overcoming_hanging) Wikipedia page can help; you need to redirect all three IO streams (stdout, stdin and stderr) - an example with `yes`:
```
kubectl exec pod -- bash -c "yes > /dev/null 2> /dev/null &"
```
`nohup` is not required in the above case because I did not ... | Actually, the best way to make this kind of things is adding an entry point to your container and run execute the commands there.
Like:
`entrypoint.sh`:
```
#!/bin/bash
set -e
cd some-dir && (python xxx.py --arg1 abc &)
./somethingelse.sh
exec "$@"
```
You wouldn't need to go manually inside every single contain... | 13,121 |
21,255,168 | I am trying to understand why does the recursive function returns 1003 instead of 1005.
```
l = [1,2,3]
def sum(l):
x, *y = l
return x + sum(y) if y else 1000
sum(l)
```
According to [pythontutor](http://pythontutor.com/visualize.html) the last value of `y` list is 5 and that would make return value `1000 +... | 2014/01/21 | [
"https://Stackoverflow.com/questions/21255168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1984680/"
] | >
> According to pythontutor the last value of y list is 5 and that would make return value `1000 + sum([2,3])` 1005, am I correct?
>
>
>
No, the last value of `y` is `[]`. It's never anything but a list, and besides, there are no `5`s for it to ever be. On top of that, the recursive return value is always on the ... | Recursion step by step
1) `x = 1` `y = [2,3]`
2) `x = 2` `y = [3]`
3) `x = 3` `y = []`
Note that step 3) returns `1000` since `not y`. This is because your return statement is equivalent to
```
(x + sum(y)) if y else 1000
```
Thus we have
3) `1000`
2) `1000 + 2`
1) `1002 + 1`
The result is `1003`.
So perha... | 13,122 |
72,173,762 | I am trying to speed up my code by splitting the job among several python processes. In the single-threaded version of the code, I am looping through a code that accumulates the result in several matrices of different dimensions. Since there's no data sharing between each iteration, I can divide the task among several ... | 2022/05/09 | [
"https://Stackoverflow.com/questions/72173762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11342618/"
] | Sort a Range
------------
```vb
Sub SortData()
'Dim wb As Workbook: Set wb = ThisWorkbook
'Dim ws As Worksheet: Set ws = wb.Worksheets("Sheet1")
Dim ws As Worksheet: Set ws = ActiveSheet
With ws.Range("A1").CurrentRegion
.Sort _
Key1:=.Columns(1), Order1:=xlAscending, _
... | You aren't quite using the `With` statement correctly. Try it like this:
```
Sub Sort()
With ActiveSheet.Sort
Cells.Select
.SortFields.Clear
.SortFields.Add2 key:=Range("A2:A35" _
), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SortFields.Add2 ... | 13,127 |
20,213,981 | I have following list of items (key-value pairs):
```
items = [('A', 1), ('B', 1), ('B', 2), ('C', 3)]
```
What I want to get:
```
{
'A' : 1,
'B' : [1,2]
'C' : 3
}
```
My naive solution:
```
res = {}
for (k,v) in items:
if k in res:
res[k].append(v)
else:
res[k] = [v]
```
I'm ... | 2013/11/26 | [
"https://Stackoverflow.com/questions/20213981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940208/"
] | Use could use defaultdict here.
```
from collections import defaultdict
res = defaultdict(list)
for (k,v) in items:
res[k].append(v)
# Use as dict(res)
```
**EDIT:**
This is using groupby, but please note, **the above is far cleaner and neater to the eyes**:
```
>>> data = [('A', 1), ('B', 1), ('B', 2), ('C',... | This is very easy to do with `defaultdict`, which can be imported from `collections`.
```
>>> from collections import defaultdict
>>> items = [('A', 1), ('B', 1), ('B', 2), ('C', 3)]
>>> d = defaultdict(list)
>>> for k, v in items:
d[k].append(v)
>>> d
defaultdict(<class 'list'>, {'A': [1], 'C': [3], 'B': [1, 2]})... | 13,128 |
12,924,287 | I have a text file like this:-
```
V1xx AB1
V2xx AC34
V3xx AB1
```
Can we add `;` at each end of line through python script?
```
V1xx AB1;
V2xx AC34;
V3xx AB1;
``` | 2012/10/16 | [
"https://Stackoverflow.com/questions/12924287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1750896/"
] | Here's what you can try. I have `overwritten the same file` though.
You can `try creating a new one`(I leave it to you) - You'll need to modify your `with` statement a little : -
```
lines = ""
with open('D:\File.txt') as file:
for line in file:
lines += line.strip() + ";\n"
file = open('D:\File.txt', ... | ```
#Open the original file, and create a blank file in write mode
File = open("D:\myfilepath\myfile.txt")
FileCopy = open("D:\myfilepath\myfile_Copy.txt","w")
#For each line in the file, remove the end line character,
#insert a semicolon, and then add a new end line character.
#copy these lines into the blank fil... | 13,137 |
34,839,184 | Which approach is the best when we want to deploy two websites on the same aws EC2 instance?
* two separate Docker container each consists a django project
* one Docker container consists of two separate django project
if the two of them are basic django-cms projects and we know they wont expand in future (nor python... | 2016/01/17 | [
"https://Stackoverflow.com/questions/34839184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4566737/"
] | I am sure the answer is "It depends" but I believe the whole reason for using Docker is to isolate your environment, and gain flexibility.
So what happens if one project uses a bunch of python packages, and the other uses a bunch of other packages. Worse, what if any of them conflict with each other. Forget about a ca... | What is easier to maintain for you?
* Handling software updates?
* Redeploying sources?
* Reconfiguring each app?
I like separation and therefore I would define two separate Docker container but then your in need of a load balancer in front because both containers will need a separate port. The load balancer itself w... | 13,140 |
67,404,079 | I want to read a file and return word and space in the file with python.
and i don't want to pass caractere to caractere.
I already used :
```
def openfile(name_file) :
with open(name_file) as f :
l = re.split(' ',re.sub('\n',' ',f.read()))
sentence = []
for i in l :
sentence.append(i)
... | 2021/05/05 | [
"https://Stackoverflow.com/questions/67404079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15844030/"
] | This is not the best solution for this, but you can do something like this:
```
import re
def openfile(name_file):
with open(name_file) as f:
original_list = []
lines = f.readlines()
for line in lines:
li = line.split(' ')
for item in li:
if item !=... | Add a parameter on the end of print
```py
def openfile(name_file) :
with open(name_file) as f :
l = re.split(' ',re.sub('\n',' ',f.read()))
for i in l :
print('i :', i, '\ni : ')
``` | 13,143 |
54,879,916 | I've the following string in python, example:
```
"Peter North / John West"
```
Note that there are two spaces before and after the forward slash.
What should I do such that I can clean it to become
```
"Peter North_John West"
```
I tried using regex but I am not exactly sure how.
Should I use re.sub or pand... | 2019/02/26 | [
"https://Stackoverflow.com/questions/54879916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11117700/"
] | You can use
```
a = "Peter North / John West"
import re
a = re.sub(' +/ +','_',a)
```
Any number of spaces with slash followed by any number of slashes can be replaced by this pattern. | In case of varying number of white spaces before and after `/`:
```
import re
re.sub("\s+/\s+", "_", "Peter North / John West")
# Peter North_John West
``` | 13,146 |
10,184,476 | I'm making a Django page that has a sidebar with some info that is loaded from external websites(e.g. bus arrival times).
I'm new to web development and I recognize this as a bottleneck. As it is, the page hangs for a fraction of a second as it loads the data from the other sites. It doesn't display anything until it ... | 2012/04/17 | [
"https://Stackoverflow.com/questions/10184476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1337686/"
] | You probably don't need up-to-the-second information, so have [another process](http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/) load the data into a cache, and have your website read it from the local cache. | The easiest but not most beautiful way to integrate something like this would be with iframes. Just make iframes for the secondary stuff, and they will load themselves in due time. No javascript required. | 13,147 |
48,282,074 | I'm trying to learn python for data science application and signed up for a course. I am doing the exercises and got stuck even though my answer is the same as the one in the answer key.
I'm basically trying to add two new items to a dictionary with the following piece of code:
```
# Create a new key-value pair for '... | 2018/01/16 | [
"https://Stackoverflow.com/questions/48282074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9224360/"
] | I had a list in there with the sets I think that was what was throwing the error I just converted the list to a set and joined them with .union. Thank you @Adelin, @Bilkokuya, @ Piinthesky, and @Kurast for you're quick responses and input! | for union of sets you can use `|`
```
location_dict['Camden'] | location_dict['Southwark']
``` | 13,148 |
358,471 | I am writing a program that requires the use of XMODEM to transfer data from a sensor device. I'd like to avoid having to write my own XMODEM code, so I was wondering if anyone knew if there was a python XMODEM module available anywhere? | 2008/12/11 | [
"https://Stackoverflow.com/questions/358471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | There is XMODEM module on PyPi. It handles both sending and receiving of data with XModem. Below is sample of its usage:
```
import serial
try:
from cStringIO import StringIO
except:
from StringIO import StringIO
from xmodem import XMODEM, NAK
from time import sleep
def readUntil(char = None):
def serialP... | I think you’re stuck with rolling your own.
You might be able to use [sz](http://linux.about.com/library/cmd/blcmdl1_sz.htm), which implements X/Y/ZMODEM. You could call out to the binary, or port the necessary code to Python. | 13,149 |
12,243,129 | For a research project I am trying to boot as many VM's as possible, using python libvirt bindings, in KVM under Ubuntu server 12.04. All the VM's are set to idle after boot, and to use a minimum amount of memory. At the most I was able to boot 1000 VM's on a single host, at which point the kernel (Linux 3x) became unr... | 2012/09/03 | [
"https://Stackoverflow.com/questions/12243129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1642856/"
] | You are booting all the VMs using qemu-kvm right, and after 100s of VM you feel it's becoming successively slow. So when you feels it stop using kvm, just boot using qemu, I expect you see the same slowliness. My guess is that after those many VMs, KVM (hardware support) exhausts. Because KVM is nothing but software la... | The following virtual hardware limits for guests have been tested. We ensure host and VMs install and work successfully, even when reaching the limits and there are no major performance regressions (CPU, memory, disk, network) since the last release (SUSE Linux Enterprise Server 11 SP1).
Max. Guest RAM Size --- 512 GB... | 13,159 |
13,965,823 | I'm trying to get NLTK and wordnet working on Heroku. I've already done
```
heroku run python
nltk.download()
wordnet
pip install -r requirements.txt
```
But I get this error:
```
Resource 'corpora/wordnet' not found. Please use the NLTK
Downloader to obtain the resource: >>> nltk.download()
Searched in:
... | 2012/12/20 | [
"https://Stackoverflow.com/questions/13965823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1881006/"
] | I know this is an old question, but since the "right" answer has changed thanks to Heroku offering support for `nltk`, I thought it might be worthwhile to answer.
Heroku now supports `nltk`. If you need to download something for `nltk` (wordnet in this example, or perhaps stopwords or a corpora), you can do so by simp... | I was also facing the issue when i tried to use this code lemmatizer.lemmatize('goes'), its actually because of packages they have not downloaded.
so try to download them using following code, may be it can solve many problems regarding to these,
nltk.download('wordnet')
nltk.download('omw-1.4')
Thank You.. | 13,160 |
64,734,118 | I'm trying to make a discord bot, and when I try to load a .env with load\_dotenv() it doesn't work because it says
```
Traceback (most recent call last):
File "/home/fanjin/Documents/Python Projects/Discord Bot/bot.py", line 15, in <module>
client.run(TOKEN)
File "/home/fanjin/.local/lib/python3.8/site-packag... | 2020/11/08 | [
"https://Stackoverflow.com/questions/64734118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9509783/"
] | I had same error trying to load my environment configuration on ubuntu 20.04 and python-dotenv 0.15.0. I was able to rectify this using python interpreter which will log out any error encountered while trying to load your environments. Whenever your environment variable is loaded successfully, load\_dotenv() returns `T... | So this took me a while. My load\_dotenv() was returning True.
I had commas after some records which is not correct.
Once I removed the commas the variables were working. | 13,170 |
63,756,673 | I'm facing weird issue in my Jupyter-notebook.
In my first cell:
```
import sys
!{sys.executable} -m pip install numpy
!{sys.executable} -m pip install Pillow
```
In the second cell:
```
import numpy as np
from PIL import Image
```
But it says : **ModuleNotFoundError: No module named 'numpy'**
[![ModuleNotFound... | 2020/09/05 | [
"https://Stackoverflow.com/questions/63756673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10305444/"
] | Thanks to @suuuehgi.
When Jupyter Notebook isn't opened as root:
```
import sys
!{sys.executable} -m pip install --user numpy
``` | I've had occasional weird install issues with Jupyter Notebooks as well when I'm running a particular virtual environment. Generally, installing with pip directly in the notebook in this form:
`!pip install numpy`
fixes it. Let me know how it goes. | 13,173 |
36,481,891 | Is there a way to call Excel add-ins from python? In my company there are several excel add-ins that are available, they usually provide direct access to some database and make additional calculations.
What is the best way to call those functions directly from python?
To clarify, I'm NOT interested in accessing pytho... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36481891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5181181/"
] | There are at least 3 possible ways to call an Excel add-in, call the COM add-in directly or through automation.
Microsoft provide online documentation for it's Excel interop (<https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel>). Whilst it's for .NET, it highlights the main limitations. You ca... | This [link](https://docs.continuum.io/anaconda/excel) list some of the available packages to work with Excel and Excel files. You might find the answer to your question there.
As a summary, here are the name of some of the listed packages:
>
> 1. openpyxl - Read/Write Excel 2007 xlsx/xlsm files
> 2. xlrd - Extract d... | 13,180 |
74,111,833 | I want to add a new field to a PostgreSQL database.
It's a not null and unique CharField, like
```
dyn = models.CharField(max_length=31, null=False, unique=True)
```
The database already has relevant records, so it's not an option to
* delete the database
* reset the migrations
* wipe the data
* set a default stat... | 2022/10/18 | [
"https://Stackoverflow.com/questions/74111833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5675325/"
] | I ended up using [one of the methods](https://stackoverflow.com/a/56398787/5675325) shown by Oleg
```
def dynamic_default_value():
"""
This function will be called when a default value is needed.
It'll return a 31 length string with a-z, 0-9.
"""
alphabet = string.ascii_lowercase + string.digits
... | you can reset the migrations or edit it or create new one like:
```
python manage.py makemigrations name_you_want
```
after that:
```
python manage.py migrate same_name
```
edit:
example for funcation:
```
def generate_default_data():
return datetime.now()
class MyModel(models.Model):
field = models.Da... | 13,181 |
70,133,541 | I have a list of 4 binary numbers and i want to check if they are divisible by 5, and if it's the case, i print them.
I've tried something but i'm stuck with an error, showing you the error and the code i made.
```
---------------------------------------------------------------------------
TypeError ... | 2021/11/27 | [
"https://Stackoverflow.com/questions/70133541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17522853/"
] | EDIT: Originally answered [here](https://discussions.apple.com/thread/253425286?answerId=256408798022#256408798022).
If you are using any package manager (e.g. homebrew), then you need the command line tools.
Here is my current SDK for macOS Monterey 12.0.1:
[ can just be re-installed. | 13,182 |
62,562,064 | One Population Proportion
Research Question: In previous years 52% of parents believed that electronics and social media was the cause of their teenager’s lack of sleep. Do more parents today believe that their teenager’s lack of sleep is caused due to electronics and social media?
Population: Parents with a teenager... | 2020/06/24 | [
"https://Stackoverflow.com/questions/62562064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13807934/"
] | You approximate the binomial distribution with the normal since n\*p > 30 and the zscore for a [proportion test](https://online.stat.psu.edu/statprogram/reviews/statistical-concepts/proportions) is:
[](https://i.stack.imgur.com/Iue0em.png)
So the ca... | The question is formulated as a binomial problem: 1018 people take a yes/no decision with constant probability. In your case 570 out of 1018 people hold that belief and that probability is to be compared to 52 %
I do not know about Python, but I con confirm your teachers result in R:
```
> binom.test(570, 1018, p = .... | 13,183 |
18,487,171 | I am having a direcotry structure as :
```
D:\testfolder\folder_to_tar:
|---folder1
|--- file1.txt
|---folder2
|--- file2.txt
|---file3.txt
```
I want to create a tarball using Python at the same directory level. However, I a... | 2013/08/28 | [
"https://Stackoverflow.com/questions/18487171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1514773/"
] | Try replacing the tarout.add line with:
```
tarout.add(tarname,arcname=os.path.basename(tarname))
```
Note: you also need to `import os` | Have you tried adding `\` at the end of `tarname`? | 13,184 |
21,820,104 | I am attempting to use the Python [requests](http://requests.readthedocs.org/en/latest/) library to login to a website called surfline.com, then `get` a webpage once logged in (presumably within a persisting [session](http://docs.python-requests.org:8000/en/latest/user/advanced/)).
The login form that surfline.com use... | 2014/02/17 | [
"https://Stackoverflow.com/questions/21820104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1337422/"
] | Consider using WPF's built in validation techniques. See this MSDN documentation on the [`ValidationRule`](http://msdn.microsoft.com/en-us/library/system.windows.controls.validationrule%28v=vs.110%29.aspx) class, and this [how-to](http://msdn.microsoft.com/en-us/library/ms753962%28v=vs.110%29.aspx). | Based on your clarification, you want to limit user input to be a number with decimal points.
You also mentioned you are creating the TextBox programmatically.
Use the TextBox.PreviewTextInput event to determine the type of characters and validate the string inside the TextBox, and then use e.Handled to cancel the use... | 13,185 |
66,200,173 | I have the following question, why is `myf(x)` giving less accurate results than `myf2(x)`. Here is my python code:
```
from math import e, log
def Q1():
n = 15
for i in range(1, n):
#print(myf(10**(-i)))
#print(myf2(10**(-i)))
return
def myf(x):
return ((e**x - 1)/x)
def myf2(x):
... | 2021/02/14 | [
"https://Stackoverflow.com/questions/66200173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14858513/"
] | Let's start with the difference between `x` and `log(exp(x))`, because the rest of the computation is the same.
```py
>>> for i in range(10):
... x = 10**-i
... y = exp(x)
... print(x, log(y))
...
1 1.0
0.1 0.10000000000000007
0.01 0.009999999999999893
0.001 0.001000000000000043
0.0001 0.00010000000000004... | >
> Why is this result more accurate than another result by equivalent functions
>
>
>
Bad luck. Neither function is reliable pass about `(17-n)/2` digits.
Difference in results relies on common implementations of `exp` and `log`, yet not language specified.
---
For a given `x` as a negative `n` power of 10, th... | 13,187 |
5,591,557 | I have some python code that does a certain task. I need to call this code from C# without converting the python file as an .exe, since the whole application is built on C#.
How can I do this? | 2011/04/08 | [
"https://Stackoverflow.com/questions/5591557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/692856/"
] | If your python code can be executed via [IronPython](http://www.ironpython.net/) then this is definitely the way to go - it offers the best interop and means that you will be able to use .Net objects in your scripts.
There are many ways to invoke IronPython scripts from C# ranging from compiling the script up as an e... | Have a look at [IronPython](http://www.ironpython.net/).
Based on your answer and comments, I believe that the best thing you can do is to embed IronPython in your application. As always, there is a relevant SO [question](https://stackoverflow.com/questions/208393/how-to-embed-ironpython-in-a-net-application) about th... | 13,188 |
52,943,850 | Example I have this two csv, how can overwrite the value of column `type` in a.csv or replace if it matched both the string in column `fruit` in a.csv and b.csv
```
a.csv
fruit,name,type
apple,anna,A
banana,lisa,A
orange,red,A
pine,tin,A
b.csv
fruit,type
banana,B
apple,B
```
**How to output this:** OR how to over... | 2018/10/23 | [
"https://Stackoverflow.com/questions/52943850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | As per your input you have given
```
import pandas as pd
df1=pd.read_csv("a.csv")
df2=pd.read_csv("b.csv")
df = pd.merge(df1, df2, on='fruit', how='outer')
df['type_x'] = df['type_y'].combine_first(df['type_x'])
del df["type_y"]
df = df[pd.notnull(df['name'])]
```
input df1
```
fruit name type
0 apple ... | Use [`map`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html) by `Series` created by [`set_index`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html) and then rewrite missing unmatched values by original column values by [`fillna`](http://pandas.pydata.org... | 13,191 |
56,923,131 | I have a string converted to an MD5 hash using a python script with the following command:
```py
admininfo['password'] = hashlib.md5(admininfo['password'].encode("utf-8")).hexdigest()
```
This value is now stored in an online database.
Now I'm creating a C++ script to do a login on this database. During the login, ... | 2019/07/07 | [
"https://Stackoverflow.com/questions/56923131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10006055/"
] | ```
(unsigned char*)&string
```
You're hashing the pointer itself (and unspecified data after it), not the string that it points to.
And it changes on every execution (maybe).
You meant just `(unsigned char*)string`. | Make it `MD5((unsigned char*)string, ...)`; drop the ampersand. You are not passing the character data to `MD5` - you are passing the value of the `string` pointer itself (namely, the address of the first character of the password), plus whatever garbage happens to be on the stack after it. | 13,194 |
65,544,809 | I'm trying to create several class instances of graphs and initialize each one with an empty set, so that I can add in-neighbors/out-neighbors to each instance:
```
class Graphs:
def __init__(self, name, in_neighbors=None, out_neighbors=None):
self.name = name
if in_neighbors is None:
... | 2021/01/02 | [
"https://Stackoverflow.com/questions/65544809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14735451/"
] | ```
Dog dog1 = new Dog(1, "Dog1", "Cheese");
Dog dog2 = new Dog(1, "Dog1", "Meat");
Dog dog3 = new Dog(2, "Dog2", "Fish");
Dog dog4 = new Dog(2, "Dog2", "Milk");
List<Dog> dogList = List.of(dog1, dog2, dog3, dog4);
//insert dog objects into dog list
//Creating HashMap that will have id as the key and dog objects as ... | Hi Tosh and welcome to Stackoverflow.
The problem is in your if statement when you check for IDs of your two objects.
```
for (Dog dog : dogList) {
if(dog.getId() == dog.getId()){
crMap.put(cr.getIndividualId(), clientReceivables.);
}
}
```
Here you check IDs of the same object named "dog" and you will alw... | 13,195 |
68,319,575 | I see that the example python code from Intel offers a way to change the resolution as below:
```
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
# Start streaming
pipeline.start(config)
```
<https://github.com/IntelRealSense/librealsense/blob/master/wrappers/python/examples/opencv_viewer_example.... | 2021/07/09 | [
"https://Stackoverflow.com/questions/68319575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1231714/"
] | You were close, but you need to set the revised object to a new variable. Also, you probably want to aggregate arrays since there are multiple 'completed'. This first creates the base object and then populates it using `reduce()` for both actions
```
let keys=todos.reduce((b,a) => ({...b, [a.status]:[]}),{}),
rev... | ```
function getByValue(arr, value) {
var result = arr.filter(function(o){return o.status == value;} );
return result? result[0] : null; // or undefined
}
todo_obj = getByValue(arr, 'todo')
deleted_obj = getByValue(arr, 'deleted')
completed_obj = getByValue(arr, 'completed')
``` | 13,197 |
34,708,302 | I've got a list of dictionaries in a JSON file that looks like this:
```
[{"url": "http://www.URL1.com", "date": "2001-01-01"},
{"url": "http://www.URL2.com", "date": "2001-01-02"}, ...]
```
but I'm struggling to import it into a pandas data frame — this should be pretty easy, but I'm blanking on it. Anyone able t... | 2016/01/10 | [
"https://Stackoverflow.com/questions/34708302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4309943/"
] | You can use [`from_dict`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_dict.html):
```
import pandas as pd
lis = [{"url": "http://www.URL1.com", "date": "2001-01-01"},
{"url": "http://www.URL2.com", "date": "2001-01-02"}]
print pd.DataFrame.from_dict(lis)
date ... | While `from_dict` will work here, the prescribed way would be to use [`pd.read_json`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html) with `orient='records'`. This parses an input that is
>
> list-like `[{column -> value}, ... , {column -> value}]`
>
>
>
Example: say this is the text... | 13,207 |
43,259,717 | I am trying to use a progress bar in a python script that I have since I have a for loop that takes quite a bit of time to process. I have looked at other explanations on here already but I am still confused. Here is what my for loop looks like in my script:
```
for member in members:
url = "http://api.wiki123.com... | 2017/04/06 | [
"https://Stackoverflow.com/questions/43259717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7681184/"
] | To show the progress bar:
```
from tqdm import tqdm
for x in tqdm(my_list):
# do something with x
#### In case using with enumerate:
for i, x in enumerate( tqdm(my_list) ):
# do something with i and x
```
[](https://i.stack.imgur.com/H9sUC... | Or you can use this (can be used for any situation):
```
for i in tqdm (range (1), desc="Loading..."):
for member in members:
url = "http://api.wiki123.com/v1.11/member?id="+str(member)
header = {"Authorization": authorization_code}
api_response = requests.get(url, headers=header)
memb... | 13,208 |
72,216,546 | Used the standard python installation file (3.9.12) for windows.
The installation file have a built in option for pip installation:
[](https://i.stack.imgur.com/CEH51.png)
The resulting python is without pip.
Then I try to install pip directly by usin... | 2022/05/12 | [
"https://Stackoverflow.com/questions/72216546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8812406/"
] | One should add `min-h-0` to `<main>`.. I swear I tried everything. | Add `overflow-y-scroll h-3/5` to the div containing the paragraphs.
Please find below the solution code and watch result in full screen.
```html
<script src="https://cdn.tailwindcss.com" ></script>
<div class="flex h-full flex-col">
<mark class="bg-red-900 p-2 font-semibold text-white"> Warning message </mark>
<m... | 13,218 |
55,436,896 | I have a table of IDs and dates of quarterly data and i would like to reindex this to daily (weekdays).
Example table:
[](https://i.stack.imgur.com/bLvFf.png)
I'm trying to figure out a pythonic or pandas way to reindex to a higher frequency date ra... | 2019/03/31 | [
"https://Stackoverflow.com/questions/55436896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5615327/"
] | Yes you can do with `merge`
```
new_idx_frame=new_idx.to_frame()
new_idx_frame.columns=['date', 'id', 'type']
Yourdf=df.reset_index().merge(new_idx_frame,how='right',sort =True).groupby('id').ffill()# here I am using toy data
Out[408]:
id date type value
0 1 1 1 NaN
1 1 1 2 ... | Wen-Ben's answer is almost there - thank you for that. The only thing missing is grouping by ['id', 'type'] when doing the forward fill.
Further, when creating the new multindex in my use case should have unique values:
```
new_idx = pd.MultiIndex.from_product([dates, df.index.get_level_values(1).unique(), df.index.g... | 13,219 |
66,491,254 | I have created python desktop software. Now I want to market that as a product. But my problem is, anyone can decompile my exe file and they will get the actual code.
So is there any way to encrypt my code and convert it to exe before deployment. I have tried different ways.
But nothing is working. Is there any way to... | 2021/03/05 | [
"https://Stackoverflow.com/questions/66491254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14155439/"
] | This [link](https://wiki.python.org/moin/Asking%20for%20Help/How%20do%20you%20protect%20Python%20source%20code%3F) has most of the info you need.
But since links are discouraged here:
There is py2exe, which compiles your code into an .exe file, but afaik it's not difficult to reverse-engineer the code from the exe fil... | You can install pyinstaller per `pip install pyinstaller` (make sure to also add it to your environment variables) and then open shell in the folder where your file is (shift+right-click somewhere where no file is and "open PowerShell here") and the do "pyinstaller --onefile YOUR\_FILE".
If there will be created a dis... | 13,220 |
4,331,348 | If I have a python module that has a bunch of functions, say like this:
```
#funcs.py
def foo() :
print "foo!"
def bar() :
print "bar!"
```
And I have another module that is designed to parse a list of functions from a string and run those functions:
```
#parser.py
from funcs import *
def execute(command)... | 2010/12/02 | [
"https://Stackoverflow.com/questions/4331348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67829/"
] | `import module_name` does something fundamentally different from what `from module_name import *` does.
The former creates a global named `module_name`, which is of type `module` and which contains the module's names, accessed as attributes. The latter creates a global for each of those names within `module_name`, but... | * Print the globals after you import parser to see what it did
* `parser` is it built-in module also. Usually the built-in parser should load not yours.
I would change the name so you do not have problems.
* Your importing funcs but parser imports \* from funcs?
I would think carefully about what order you are importi... | 13,221 |
73,066,303 | I have python 3.10, selenium 4.3.0 and i would like to click on the following element:
```
<a href="#" onclick="fireLoginOrRegisterModalRequest('sign_in');ga('send', 'event', 'main_navigation', 'login', '1st_level');"> Mein Konto </a>
```
Unfortunately,
`driver.find_element(By.CSS_SELECTOR,"a[onclick^='fireLoginOrRe... | 2022/07/21 | [
"https://Stackoverflow.com/questions/73066303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19163184/"
] | It turns out that despite opening up to all IP-addresses, the networkpolicy does not allow egress to the DNS pod, which is in another namespace.
```
# Identifying DNS pod
kubectl get pods -A | grep dns
# Identifying DNS pod label
kubectl describe pods -n kube-system coredns-64cfd66f7-rzgwk
```
Next I add the dns la... | The reason is, `curl` attempts to form a 2-way TCP connection with the HTTP server at `www.google.com`. This means, *both* egress and ingress traffic need to be allowed on your policy. Currently, only out-bound traffic is allowed. Maybe, you'll be able to see this in more detail if you ran curl in verbose mode:
```
ku... | 13,223 |
61,243,561 | I wrote some classes which were a shopping cart, Customer, Order, and some functions for discounts for the orders. this is the final lines of my code.
```
anu = Customer('anu', 4500) # 1
user_cart = [Lineitem('apple', 7, 7), Lineitem('orange', 5, 6)] # 2
order1 = Order(anu, user_cart) # 2
print(type(joe)) # 4
prin... | 2020/04/16 | [
"https://Stackoverflow.com/questions/61243561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12857878/"
] | You can do this by awaiting the listen even, wrapping it in a promise, and calling the promise resolve as the callback to the server listen
```js
const app = express();
let server;
await new Promise(resolve => server = app.listen(0, "127.0.0.1", resolve));
this.global.server = server;
```
You could also put ... | Extending [Robert Mennell](https://stackoverflow.com/users/5377773) answer:
>
> You could also put a custom callback that will just call the promise resolver as the third argument to the `app.listen()` and it should run that code then call resolve if you need some sort of diagnostics.
>
>
>
```js
let server;
cons... | 13,224 |
57,122,160 | I am setting up a django rest api and need to integrate social login feature.I followed the following link
[Simple Facebook social Login using Django Rest Framework.](https://medium.com/@katherinekimetto/simple-facebook-social-login-using-django-rest-framework-e2ac10266be1)
After setting up all , when a migrate (7 th ... | 2019/07/20 | [
"https://Stackoverflow.com/questions/57122160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5113584/"
] | Firefox uses different flags. I am not sure exactly what your aim is but I am assuming you are trying to avoid some website detecting that you are using selenium.
There are different methods to avoid websites detecting the use of Selenium.
1) The value of navigator.webdriver is set to true by default when using Selen... | you may try:
```
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver import Firefox
profile = FirefoxProfile()
profile.set_preference('devtools.jsonview.enabled', False)
profile.update_preferences()
desired = DesiredCapabilit... | 13,225 |
3,633,288 | I'll to explain this right:
I'm in an environment where I can't use python built-in functions (like 'sorted', 'set'), can't declare methods, can't make conditions (if), and can't make loops, except for:
* can call methods (but just one each time, and saving returns on another variable
foo python:item.sort(); #foo ... | 2010/09/03 | [
"https://Stackoverflow.com/questions/3633288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/334872/"
] | It's hard to answer, not knowing exactly what's allowed and what's not. But how about this O(N^2) solution?
```
[x for x in correct_order if x in messed_order] + [x for x in messed_order if x not in correct_order]
``` | Does the exact order of the 55/66/44 items matter, or do they just need to be listed at the end? If the order doesn't matter you could do this:
```
[i for i in correct_order if i in messed_order] +
list(set(messed_order) - set(correct_order))
``` | 13,226 |
41,954,262 | I am running through a very large data set with a json object for each row. And after passing through almost 1 billion rows I am suddenly getting an error with my transaction.
I am using Python 3.x and psycopg2 to perform my transactions.
The json object I am trying to write is as follows:
```
{"message": "ConfigMan... | 2017/01/31 | [
"https://Stackoverflow.com/questions/41954262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2302843/"
] | you're trying to write a `tuple` to your file.
While it would work for `print` since `print` knows how to print several arguments, `write` is more strict.
Just format your `var` properly.
```
var = "\n{}\n".format(test)
``` | I assume you want to concatinate the string, so use `+` instead of `,`
```
import pandas as pd
import os
#path = '/test'
#os.chdir(path)
def writeScores(test):
with open('output.txt', 'w') as f:
var = "\n" + test + "\n"
f.write(var)
writeScores("asd")
``` | 13,233 |
38,589,830 | I have following:
1. ```
python manage.py crontab show # this command give following
Currently active jobs in crontab:
12151a7f59f3f0be816fa30b31e7cc4d -> ('*/1 * * * *', 'media_api_server.cron.cronSendEmail')
```
2. My app is in virtual environment (env) active
3. In my media\_api\_server/cron.py I have follo... | 2016/07/26 | [
"https://Stackoverflow.com/questions/38589830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5287027/"
] | Your code actually works. You may be think that `print("Hello")` should appear in stdout? So it doesn't work that way, because cron doesn't use `stdour` and `stderr` for it's output. To see actual results you should point path to some log file in `CRONJOBS` list: just put `'>> /path/to/log/file.log'` as last argument, ... | Try to change the crontab with a first line like:
```
SHELL=/bin/bash
```
Create the new line at crontab with:
```
./manage.py crontab add
```
And change the line created by crontab library with the command:
>
> crontab -e
>
>
>
```
*/1 * * * * source /home/app/env/bin/activate && /home/app/manage.py cronta... | 13,238 |
55,476,131 | I'm trying to implement fastai pretrain language model and it requires torch to work. After run the code, I got some problem about the import torch.\_C
I run it on my linux, python 3.7.1, via pip: torch 1.0.1.post2, cuda V7.5.17. I'm getting this error:
```
Traceback (most recent call last):
File "pretrain_lm.py",... | 2019/04/02 | [
"https://Stackoverflow.com/questions/55476131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6332850/"
] | My problem is solved. I'm uninstalling my torch twice
```
pip uninstall torch
pip uninstall torch
```
and then re-installing it back:
```
pip install torch==1.0.1.post2
``` | Try to use `pytorch` 1.4.0. For which, upgrade the `pytorch` library using the following command,
```
pip install -U torch==1.5
```
If you are working on Colab then use the following command,
```
!pip install -U torch==1.5
```
Still facing challenges on the library then install `detectron2` library also.
```
!pi... | 13,243 |
60,693,395 | I created a small app in Django and runserver and admin works fine.
I wrote some tests which can call with `python manage.py test` and the tests pass.
Now I would like to call one particular test via PyCharm.
This fails like this:
```
/home/guettli/x/venv/bin/python
/snap/pycharm-community/179/plugins/python-ce... | 2020/03/15 | [
"https://Stackoverflow.com/questions/60693395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/633961/"
] | You can add DJANGO\_SETTINGS\_MODULE as an environmental variable:
In the menu: Run -> Edit Configurations -> Templates -> Python Tests -> Unittests
[](https://i.stack.imgur.com/XKKTG.png)
And delete old "Unittests for tests...." entries. | You can specify the settings in your test command
Assuming your in the xyz directory, and the structure is
```
/xyz
- manage.py
- xyz/
- settings.py
```
The following command should work
```
python manage.py test --settings=xyz.settings
``` | 13,245 |
34,116,682 | I am trying to save an image with python that is Base64 encoded. Here the string is to large to post but here is the image
[](https://i.stack.imgur.com/JYHLV.jpg)
And when received by python the last 2 characters are `==` although the string is not f... | 2015/12/06 | [
"https://Stackoverflow.com/questions/34116682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3630528/"
] | There is no need to add `data:image/png;base64,` before, I tried using the code below, it works fine.
```
import base64
data = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADBQTFRFA6b1q Ci5/f2lt/9yu3 Y8v2cMpb1/DSJbz5i9R2NLwfLrWbw m T8I8////////SvMAbAAAABB0Uk5T//////... | If you append **data:image/png;base64,** to data, then you get error. If You have this, you must replace it.
```
new_data = initial_data.replace('data:image/png;base64,', '')
``` | 13,251 |
56,838,851 | I am getting an error when execute robot scripts through CMD (windows)
>
> 'robot' is not recognized as an internal or external command, operable
> program or batch file"
>
>
>
My team installed Python in C:\Python27 folder and I installed ROBOT framework and all required libraries with the following command
`... | 2019/07/01 | [
"https://Stackoverflow.com/questions/56838851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9717530/"
] | I've installed robotframework using this command "sudo pip3 install robotframework" in jenkins server. and now my jenkins pipeline script can now run my robot scripts | I'm not very comfort with Windows environment, so let me give my two cents:
1) Try to set the PATH or PYTHONPATH to the location where your robot file is
2) Try to run robot from python script. I saw that you tried it above, but take a look at the RF User Guide and see if you are doing something wrong:
<https://robo... | 13,252 |
56,646,940 | I load a saved h5 model and want to save the model as pb.
The model is saved during training with the `tf.keras.callbacks.ModelCheckpoint` callback function.
TF version: 2.0.0a
**edit**: same issue also with 2.0.0-beta1
My steps to save a pb:
1. I first set `K.set_learning_phase(0)`
2. then I load the model wit... | 2019/06/18 | [
"https://Stackoverflow.com/questions/56646940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6510273/"
] | I do save the model to `pb` from `h5` model:
```py
import logging
import tensorflow as tf
from tensorflow.compat.v1 import graph_util
from tensorflow.python.keras import backend as K
from tensorflow import keras
# necessary !!!
tf.compat.v1.disable_eager_execution()
h5_path = '/path/to/model.h5'
model = keras.models... | I'm wondering the same thing, as I'm trying to use get\_session() and set\_session() to free up GPU memory. These functions seem to be missing and [aren't in the TF2.0 Keras documentation](http://faroit.com/keras-docs/2.0.0/backend/). I imagine it has something to do with Tensorflow's switch to eager execution, as dire... | 13,261 |
62,655,911 | I'm looking at using Pandas UDF's in PySpark (v3). For a number of reasons, I understand iterating and UDF's in general are bad and I understand that the simple examples I show here can be done PySpark using SQL functions - all of that is besides the point!
I've been following this guide: <https://databricks.com/blog/... | 2020/06/30 | [
"https://Stackoverflow.com/questions/62655911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1802510/"
] | I figured this out. So simple after you write it down and publish the problem to the world.
All that needs to happen is to return an array and then convert to a Pandas Series:
```
@pandas_udf('long')
def test4(x: pd.Series, y: pd.Series) -> pd.Series:
return pd.Series([a if a > b else b for a, b in zip(x, y)])
d... | I've spent the last two days looking for this answer, thank you simon\_dmorias!
I needed a slightly modified example here. I'm breaking out the single pandas\_udf into multiple components for easier management. Here is an example of what I'm using for others to reference:
```
xdf = pd.DataFrame(([1, 2, 3,'Fixed'], [4... | 13,263 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.