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 |
|---|---|---|---|---|---|---|
65,869,272 | I've created a TensorFlow model that uses RaggedTensors. Model works fine and when calling `model.predict` and I get the expected results.
```
input = tf.ragged.constant([[[-0.9984272718429565, -0.9422321319580078, -0.27657580375671387, -3.185823678970337, -0.6360141634941101, -1.6579184532165527, -1.9000954627990723,... | 2021/01/24 | [
"https://Stackoverflow.com/questions/65869272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1115237/"
] | <https://www.tensorflow.org/tfx/serving/api_rest#predict_api>
I think that you need to use a columnar format as recommended in the REST API instead of the row format because the dimensions of your 0th input do not match.
This means that instead of instances you will have to use inputs.
Since you also have multiple inp... | Others may benefit from this, as it took me a while to stitch together:
1. Training a toy LSTM model on ragged tensors.
2. Loading it into TensorFlow Serving.
3. Making a prediction request with a serielized ragged tensor.
If anyone knows how to rename "args\_0" and "args\_0\_1", please add.
Relevant Git Issue: <http... | 4,001 |
69,929,986 | I tried many ways but neither worked. I have to convert string like `assdggg` to `a2sd3g` in python. If letters are next to each other we leave only one letter and before it we write how mamy of them were next to eachother. Any idea how can it be done? | 2021/11/11 | [
"https://Stackoverflow.com/questions/69929986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14868201/"
] | I'd suggest `itertools.groupby` then format as you need
```
from itertools import groupby
# groupby("assdggg")
# {'a': ['a'], 's': ['s', 's'], 'd': ['d'], 'g': ['g', 'g', 'g']}
result = ""
for k, v in groupby("assdggg"):
count = len(list(v))
result += (str(count) if count > 1 else "") + k
print(result) # a... | Try using `.groupby()`:
```
from itertools import groupby
txt = "assdggg"
print(''.join(str(l) + k if (l := len(list(g))) != 1 else k for k, g in groupby(txt)))
```
output :
```
a2sd3g
``` | 4,002 |
16,704,588 | I would like to keep firefox as my system default browser on my Mac, but launch IPython Notebook in Chrome[1].
[This answer](https://stackoverflow.com/a/15748692/1730674) led me to my `ipython_notebook_config.py` file but I can't get an instance of Chrome running. After `c = get_config()` and `import webbrowser`, I've... | 2013/05/23 | [
"https://Stackoverflow.com/questions/16704588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1730674/"
] | This might not be the right things to do , but
```
$ open -a Google\ Chrome http://localhost:8888
$ open -a Firefox http://localhost:8888
```
Works from me (only on mac) to open any url in one of the 2 browser.
Use the `--no-browser` option and make an bash function that does that.
Or even have a bookmark in Chrome... | For future reference, this works looks the most elegant way to edit `jupyter_notebook_config.py` for me on macOS:
```
c.NotebookApp.browser = u'open -a "Google Chrome" %s'
```
>
> You can obviously replace `"Google Chrome"` with any other browser.
>
>
>
Full procedure:
1. `jupyter notebook --generate-config`
2... | 4,005 |
7,022,148 | In the below python the message RSU is not supported on single node machine\*\* is not getting printed. can anyone help please??
```
#! /usr/bin/env python
import sys
class SWMException(Exception):
def __init__(self, arg):
print "inside exception"
Exception.__init__(self, arg)
class RSUNotSuppor... | 2011/08/11 | [
"https://Stackoverflow.com/questions/7022148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889384/"
] | It is not printed, because you're even not trying to print it :) Here:
```
try:
isPrepActionNeeded()
except RSUNotSupported as e:
print str(e)
sys.exit(1)
``` | Because you handle the exception with your try/except clause. | 4,015 |
68,435,024 | My code:
```py
import pyttsx3
#sapi5 is default windows voice api
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
print(voices[1].id)
engine.setProperty('voice', voices[0].id)
def speak(audio):
pass
```
On running the code instead of getting that voice ID printed I am getting this error:
... | 2021/07/19 | [
"https://Stackoverflow.com/questions/68435024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15030983/"
] | No, they don't conflict with Windows 11! For me they still are running efficiently! Try to uninstall Python and pip including all modules as well and then download them.
If that doesn't work you, you could try switching to older versions of Python that support these quiet efficiently or you can download these librarie... | Ok, I have tried the code and works fine for me now as per me there is no problem in your code and its probably the windows 11 or the installation has a defect / glitch cause windows 11 is not yet the smoothest and it may be causing your code to not run properly
i would also like to ask you to see if the permissions a... | 4,017 |
16,627,533 | I'm very new to python. How can I convert a unit in python? I mean not using a conversion function to do this. Just as a built-in syntax in python, like the complex numbers works.
E.g., when I typed 1mm in python command line, and expect the result is 0.001
```
>>> 1mm
0.001
#Just like the built-in complex numbers or ... | 2013/05/18 | [
"https://Stackoverflow.com/questions/16627533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2397416/"
] | how bout
```
mm = 0.001
1*mm
```
not sure if that is what you are asking for ... if you have ever messed with report lab they do simillar stuff. (although they use it to convert pixels to actual border sizes and what not)
eg:
```
inch = DPI*some_thing
margin = 2*inch
``` | If you are doing scientific work with physical units, it is a good idea to use a units library (not built-in) like [quantities](http://pythonhosted.org/quantities/user/tutorial.html) which also supports scientific packages like numpy. For example:
```
>>> from quantities import meter
>>> q = 1 * meter
>>> q.units = 'f... | 4,018 |
43,897,628 | I updated to pandas 0.20.1 recently and I tried to use the new feature of to\_json(orient='table')
```
import pandas as pd
pd.__version__
# '0.20.1'
a = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
a.to_json('a.json', orient='table')
```
But how can I read this JSON file to DataFrame?
I tried `pd.read_json('a.json', o... | 2017/05/10 | [
"https://Stackoverflow.com/questions/43897628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4956987/"
] | Apparently the new method outputs some metadata with the dataset into json such as the pandas version. Hence, consider using the built-in `json` module to read in this nested object to extract the value at *data* key:
```
import json
...
with open('a.json', 'r') as f:
json_obj = json.loads(f.read())
df = pd... | Here is a function I have developed from Parfait answer:
```
def table_to_df(table):
df = pd.DataFrame(table['data'],
columns=[t['name'] for t in table['schema']['fields']])
for t in table['schema']['fields']:
if t['type'] == "datetime":
df[t['name']] = pd.to_datetime(... | 4,020 |
66,129,496 | I am using Featuretools library to try to generate custom features involving customer transactions. I tested the function and it returns the answer so I am not sure why I am getting this error.
I tried using the following link:
<https://featuretools.alteryx.com/en/stable/getting_started/primitives.html>
Thank you!
`... | 2021/02/10 | [
"https://Stackoverflow.com/questions/66129496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15179950/"
] | Default CSS should be overridden by your CSS. SO your need to use `!important` in your CSS. Here is the css :
```
<style>
.toasting {
color: yellow !important;
background-color: pink !important;
}
</style>
```
Working [demo](https://codesandbox.io/s/vue-toasted-example-forked-hd4n3?file=/App.vue) | If someone is facing the same issue, the solution above works but keep in mind it's only **without** style scoping! | 4,021 |
15,777,992 | First, note that I understand that `==` is used for comparing two expressions, while `=` is used for assigning a value to a variable. However, python is such a clean language with minimal syntax requirements, that this seems like an easy operator to axe. Also I am not trying to start a debate or discussion, but rather ... | 2013/04/03 | [
"https://Stackoverflow.com/questions/15777992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2218093/"
] | One very simple reason is that python allows boolean expressions:
```
a = b == c
```
and also multiple assignment:
```
a = b = c
```
In the first case, `a` gets assigned a boolean value\* (`True` or `False`) depending on whether `b` and `c` are equal. In the second case, `a` and `b` end up referencing the same ob... | The two operators can overlap. For instance, consider
```
a = b = c
```
which sets `a` and `b` both to `c`, and
```
a = b == c
```
which sets `a` to either `True` or `False` based on whether `b` and `c` are equal.
---
More generally, Python attempts to avoid syntax that is even possibly ambiguous to allow the p... | 4,022 |
72,089,771 | I have a working python package that's a CLI tool and I wanted to convert it into a single `.exe` file to upload it to other package managers so I used Pyinstaller. After building the `.exe` file with this command:
```
pyinstaller -c --log-level=DEBUG main.py 2> build.txt --onefile --exclude-module=pytest --add-data "... | 2022/05/02 | [
"https://Stackoverflow.com/questions/72089771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15747757/"
] | It means that the parameter is optional and has a dynamic default value. Usually, optional parameters have default values that are static, like this:
```
foo (string $bar = null): bool
```
Or this:
```
foo (string $bar = 0): bool
```
But in some cases, the default value changes depending on environment. These are... | The `$description` argument is optional, but its default value is not a constant. The manual explains:
>
> From PHP 7, if no description is provided, a default description equal to the source code for the invocation of `assert()` is provided.
>
>
>
This can't be easily expressed in the syntax summary, so they use... | 4,023 |
41,982,238 | Is there a way to add a header row to a CSV without loading the CSV into memory in python? I have an 18GB CSV I want to add a header to, and all the methods I've seen require loading the CSV into memory, which is obviously unfeasible. | 2017/02/01 | [
"https://Stackoverflow.com/questions/41982238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6637269/"
] | You will need to rewrite the whole file. Simplest is not to use python
```
echo 'col1, col2, col2,... ' > out.csv
cat in.csv >> out.csv
```
Python based solutions will work at much higher levels and will be a lot slower. 18GB is a lot of data after all. Better to work with operating system functionality, which will ... | Here is a comparison of the three suggested solutions for a ~200 MB CSV file with 10^6 rows and 10 columns (n=50).
The ratio stays approximately the same for larger and smaller files (10 MB to 8 GB).
>
> cp:shutil:csv\_reader 1:10:55
>
>
>
i.e. using the builtin `cp` function is approximately 55 times faster than... | 4,026 |
54,195,111 | I have a JSON data set that looks like this:
```
{"sequence":109428985,"bids":[["0.1243","53",5],["0.12429","24",2],["0.12428","6",1],["0.12427","6",2],["0.12426","6",1],["0.12425","6",1],["0.12424","6",1],["0.12423","6",1],["0.12422","6",1],["0.12421","6",1],["0.124206","6496",2],["0.124205","36032",1],["0.124201","... | 2019/01/15 | [
"https://Stackoverflow.com/questions/54195111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10915583/"
] | What I've done: I've recalculated the `viewBox` of your svg element, then I calculated the center of your svg. I've added a blue circle with the center in the center of the svg element.
To get the size of your svg I deleted first the transform and used the `getBBox()` method. I've used the properties of the bounding bo... | Just to expand on enxanetas answer to orient the arrow correctly, here is the code, with all transforms reduced and your viewbox/sizes intact (plus I tidied up the circles):
```html
<?xml version="1.0" encoding="utf-8"?>
<svg version="1.0" width="160pt" height="157pt" viewBox="0 0 160 157" preserveAspectRatio="xMidYM... | 4,028 |
57,823,327 | I'm new to python and I'm trying to make user registration that is extend from user creation model, I created profile model with the fields I want and saved the profile object with signal when user is saved, the profile is created successfully and linked with the user but profile data is not saved (in this example: job... | 2019/09/06 | [
"https://Stackoverflow.com/questions/57823327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2930966/"
] | Remove the second `@receiver(post_save, sender=User)`, it's useless (it's always done in the #1 profile).
When you do `user = form.save()`, the signal is raised, creating an *empty* `profile`.
So, just after `user = form.save()`, get the profile that has been created through the signal, like:
```
profile = Profile.o... | You need to also import signals in app to let django know about your implementation.
You can implement it in following manner:
```
from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'users'
def ready(self):
import users.signals
``` | 4,030 |
38,134,900 | I'm following the `rangeslider` example on the Plotly website: <https://plot.ly/python/range-slider/>
Is there a way to automatically (or even manually) rescale the y axis as the x range changes? For example, if the date range in the example above is set between Nov 2008 - April 2009, how can we automatically rescale ... | 2016/06/30 | [
"https://Stackoverflow.com/questions/38134900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4830338/"
] | There is no need to use triple pointer `***`. Passing two-dimensional array will work as is. Here is the code:
```
#include <stdio.h>
#include <stdlib.h>
// create zero initialized matrix
int** callocMatrix(int rmax, int colmax) {
int **mat = calloc(rmax, sizeof(int*));
for(int i = 0; i < rmax; i++) mat[i] = ... | Should be:
```
scanf("%d", &(*mat)[i][j]);
```
You're passing a pointer to you matrix object, so you need to dereference it (with `*`) just as you do with `printf`. `scanf` then needs the address of the element to write into, so you need the `&` | 4,031 |
34,989,032 | ```
#code like this
import dns
import dns.resolver
import dns.name
import dns.message
import dns.query
request = dns.message.make_query("google.com",dns.rdatatype.NS)
response = dns.query.udp(request,"216.239.32.10")
print response.authority
```
but it's null
=============
and then when use " nslookup google.com 21... | 2016/01/25 | [
"https://Stackoverflow.com/questions/34989032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5836175/"
] | Are you sure?
```
c:\srv>nslookup google.com 216.239.32.10
Server: ns1.google.com
Address: 216.239.32.10
Name: google.com
Addresses: 2a00:1450:400f:805::200e
178.74.30.16
178.74.30.49
178.74.30.37
178.74.30.24
178.74.30.26
178.74.30.59
178.74... | I also encountered the same problem.
It turned out to be that some DNS resolvers do not reply with authority or additional sections (Check the packets using Wireshark).
Change the IP address to `127.0.1.1` in your python code and make sure that you have configured your DNS resolver is not pointing to your original res... | 4,032 |
57,438,262 | I have a python function that reads random snippets from a large file and does some processing on it. I want the processing to happen in multiple processes and so make use of multiprocessing. I open the file (in binary mode) in the parent process and pass the file descriptor to each child process then use a multiproces... | 2019/08/09 | [
"https://Stackoverflow.com/questions/57438262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/601004/"
] | This seems to be caused by buffering: using `open(args.file, 'rb', buffering=0)` I can't reproduce anymore.
<https://docs.python.org/3/library/functions.html#open>
>
> buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off [...] When no buffering argument is given, the defa... | I've checked, only using multiprocessing.Lock (without buffering = 0), still met the `bad data`. with both `multiprocessing.Lock` and `buffering=0`, all things goes well | 4,033 |
11,836,748 | I am using
```
httplib.HTTPConnection ("http://ipaddr:port")
conn.request("GET", "", params, headers)
```
I am able to do PUT/GET using ipaddr:port using my firefox client!!.
But I am seeing this error on execution of the script:
```
File "post_python.py", line 5, in <module>
conn.request("GET", "", params... | 2012/08/06 | [
"https://Stackoverflow.com/questions/11836748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1524625/"
] | Try this instead (without "http://" before the IP address):
```
conn = httplib.HTTPConnection("x.x.x.x", port)
conn.request("GET", "", params, headers)
``` | You might have a proxy in between that the browser already knows about. If you're under linux try setting `http_proxy` environment variable. | 4,034 |
54,496,251 | I'm trying to create a PDF file using Python and FPDF. I've read the project's page about unicode and I've tryed to follow their instructions, but everytime I run my program, I receave the error:
>
> File "eventsmanager.py", line 8 SyntaxError: Non-ASCII character
> '\xc3' in file eventsmanager.py on line 8, but no ... | 2019/02/02 | [
"https://Stackoverflow.com/questions/54496251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10735382/"
] | You need to declare that the file encoding is UTF8 as Python 2 defaults to Latin-1. UTF8 became default in Python 3. The linked PEP contain the required line that you have to add at the beginning of the file:
```
# coding: utf8
```
This must be the first line after the `#!` line
EMACS and VIM formats are also suppo... | If you are using Python 3.x you have to use:
```
pdf.output(dest='S').encode('latin-1','ignore')
```
or
```
text=text.encode('latin-1', 'ignore').decode('latin-1')
```
in order to get the output. | 4,037 |
52,641,587 | I made a class in python and when I tried to call it into another python file (after importing it) it doesn't recognizes it as a class but as an object and then it tells me that my class is not callable
here is my class:
```
class Cell:
def __init__(self,value=9,isVissible=False):
self.value=value
... | 2018/10/04 | [
"https://Stackoverflow.com/questions/52641587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10455256/"
] | The `Cell` has been used for both your imported module and your class. According to the error, python has mapped it to the module name. So, when you are writing `Cell()`, it tries to use the module name as a function, instead of calling the class constructor.
If the class `Cell` is inside the `Cell` module, use `Cell.... | Your import statement is wrong, you're importing a module called Cell instead of your Cell class. You should use lower case for your filenames and import it like so:
```
from cell import Cell
test = Cell()
``` | 4,038 |
26,979,711 | I am limited to python2.5, and I thought that threading.Thread was asynchronous. I run: python t.py and the script does not return to the shell until 3 seconds have gone by, which means its blocking. Why is it blocking?
My Code:
```
#!/usr/bin/python
import threading,time
def doit():
time.sleep(3)
print "DONE"
... | 2014/11/17 | [
"https://Stackoverflow.com/questions/26979711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420259/"
] | By default, threads in Python are non-daemonic. A Python application [will not exit](https://docs.python.org/2.7/library/threading.html#thread-objects) until the all non-daemon threads have completed, so in your case it won't exit until `doit` has finished. If you want to script to exit immediately upon reaching the en... | Threading in Python is "kind-of" asynchronous. What does this mean?
* Only one thread can be running Python code at one time
* threads that are Python code and CPU intensive will not benefit
Your issue seems to be that you think a Python thread should keep running after Python itself quits -- that's not how it works.... | 4,039 |
45,248,279 | I tried to run a script using turtle module on pythonanywere.com, however, got stuck at an error that cannot find the module named "**tkinter**" and I need to install python3-tk package. I followed this tutorial [installing new modules on pythonanywhere](https://help.pythonanywhere.com/pages/InstallingNewModules/) in a... | 2017/07/21 | [
"https://Stackoverflow.com/questions/45248279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5186966/"
] | You can't use the tkinter module from a server such as pythonanywhere. It needs to have a connection to a display and not just a browser window.
<https://www.pythonanywhere.com/forums/topic/360/> | Just learnt the lesson of finding answer by asking question in different way. My purpose is to use turtle module on pythonanywere, which is not possible as explained in the answer above. However, I just found out that pythonanywhere has an affiliate website that is free and supports turtle ([www.trinker.io](http://www.... | 4,040 |
49,631,966 | I want to access a list which is field from different python function. Please refer below code for more details
```
abc = []
name = "apple,orange"
def foo(name):
abc = name.split(',')
print abc
foo(name)
print abc
print name
```
The output is as below.
>
> ['apple', 'orange']
>
>
> []
>
>
> apple,orang... | 2018/04/03 | [
"https://Stackoverflow.com/questions/49631966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5993900/"
] | ```
abc = []
name = "apple,orange"
def foo(name):
global abc # do this
abc = name.split(',')
print abc
foo(name)
print abc
print name
``` | abc from function is not the same as abc from first line, because abc in def foo is a local variable, if you want to refer to abc declared above you have to use global abc. | 4,041 |
22,796,547 | I have an issue where I am trying to log some additional attributes (the user ID and connecting host IP) on a Python CGI script. This is running under python 2.6.8 on a RHEL 5 system. I am following the documentation for extending the attributes in the basic logging dictionary as follows:
```
from __future__ import pr... | 2014/04/01 | [
"https://Stackoverflow.com/questions/22796547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1980968/"
] | I figured out what was happening here:
I am also importing Google's oauth2client.client module which is using the logging module as well. Since the oauth2cleint.client module is considered a "child" of my page, logging was being passed up to my logging object and since the Google module is not including the extra logg... | Faced a similar problem. I guess the error occurs when there are loggers used which do not have filters added (to add the extra attributes on instantiating the loggers) but still passing the records to the formatters using formats corresponding to these attributes.
[Link to documentation example using filters](https:/... | 4,043 |
50,760,826 | I have the date in the following format:
```
data = """*Date:* May 31, 2018 at 1:49:05 PM EDT"""
```
I need to extract the date and month in 2 different variables:
```
date = 31
month = "May"
```
How can i do that using regex in python 3??. I tried using the below regex to get the date and month:
```
month , dat... | 2018/06/08 | [
"https://Stackoverflow.com/questions/50760826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422965/"
] | **Update**: [@Markonius' answer](https://stackoverflow.com/a/54548429/288201) is the proper way to do it.
Here is a script that does this based on experimenting with an LFS repository. I didn't look at the LFS protocol in details, so there might be quirks unaccounted for, but it worked for my simple case.
[git-lfs-ca... | When last I was working with LFS, there were conversations on the project page about better integration - such as by writing diff and/or merge tools that could be plugged in via `.gitattributes`. These didn't seem to be considered high priority, since the main intended use case of LFS is to protect large *binary* files... | 4,045 |
45,225,741 | I'm learning how to use the python `xarray` package, however, I'm having troubles with multi-dimensional data. Specifically, how to add and use additional coordinates?
Here's an example.
```
import xarray as xr
import pandas as pd
import numpy as np
site_id = ['brw','sum','mlo']
dss = []
for site in site_id:
df... | 2017/07/20 | [
"https://Stackoverflow.com/questions/45225741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4603445/"
] | Thanks for the easy-to-reproduce example!
You can only use `.sel(x=y)` with `=`, because of the limitations of python. An example using `.isel` with latitude (`sel` is harder because it's a float type):
```
In [7]: ds.isel(latitude=0)
Out[7]:
<xarray.Dataset>
Dimensions: (index: 20, longitude: 3, site: 3)
Coordina... | Another solution for selecting data through "sel" method would be using the "slice" object of Python.
So, in order to select data from a Xarray object whose latitude is greater than a given value (i.e. 50 degrees north), one could write the following:
```
ds.sel(dict(latitude=slice(50,None)))
```
I hope it helps... | 4,048 |
62,113,084 | I googled it and tried lots of solutions, but this problem still happened.
This is my yum.conf:
```
[root@localhost etc]# cat yum.conf
[main]
gpgcheck=1
installonly_limit=3
clean_requirements_on_remove=True
best=True
```
I tried to re-install epel-release:
```
[root@localhost ~]# dnf update
Last metadata expirati... | 2020/05/31 | [
"https://Stackoverflow.com/questions/62113084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13651016/"
] | You can find the below information useful to install the Nginx web server. But, Nginx is not available in CentOS 8 default repository. So, follow the below steps. And please let me know if it works for you or not.
**Step 1: Installation of EPEL repository**
You have to install the `EPEL` (Extra Package for Enterprise... | I hope it helps you.
I am trying to install Nginx using Yum.
Instructions for installing Nginx can be found in the Download section of the NGINX official website.
```
sudo vi /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/OS/OSRELEASE/$basearch/
gpgcheck=0
enabled=1
```
In t... | 4,049 |
57,927,442 | On the following linke: <https://classicdb.ch/?quest=788>
here at `//*[@id="main-contents"]/div[1]/table[1]/tbody/tr/td`
it contains a text
>
> Mottled Boar slain (10)
>
>
>
```
//*[@id="main-contents"]/div[1]/table[1]/tbody/tr/td/a
```
contains only:
>
> Mottled Boar
>
>
>
And I only need the second p... | 2019/09/13 | [
"https://Stackoverflow.com/questions/57927442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6854832/"
] | Try this xpath.
```
//table[@class='iconlist']//tr//td[contains(.,'slain')]//a[contains(.,'Mottled Boar')]
```
**Edit**
```
//table[@class='iconlist']//tr//td//a
```
Use **javaScript** executor. where `firstChild` will return the `Mottled Boar` and
`lastChild` will return `slain (10)`
```
driver.get("https://cl... | You xpath is correct. you can try this approach to get the text directly from that node. you will need lxml import.
```
from lxml import html
tree = html.fromstring(driver.page_source)
myText = tree.xpath("//*[@id='main-contents']/div[1]/table[1]/tbody/tr/td/a/following-sibling::text()")
print(str(myText).replace('\... | 4,050 |
48,583,455 | I'm using the Python C API to call a method. At present I am using [`PyObject_CallMethodObjArgs`](https://docs.python.org/3/c-api/object.html#c.PyObject_CallMethodObjArgs) to do this. This is a variadic function:
```
PyObject* PyObject_CallMethodObjArgs(PyObject *o, PyObject *name, ..., NULL)
```
This is absolutely ... | 2018/02/02 | [
"https://Stackoverflow.com/questions/48583455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/505088/"
] | I am not sure if I am completey wrong, but AFAICT it should be possible to
* create a tuple with the required number of arguments
* pass this tuple to <https://docs.python.org/3/c-api/object.html#c.PyObject_CallObject> or <https://docs.python.org/3/c-api/object.html#c.PyObject_Call> (this decision depending on the nee... | A possible way might be to use [libffi](https://sourceware.org/libffi/), perhaps thru the [ctypes](https://docs.python.org/3/library/ctypes.html) Python library. It knows your [ABI](https://en.wikipedia.org/wiki/Application_binary_interface) and [calling conventions](https://en.wikipedia.org/wiki/Calling_convention) (s... | 4,051 |
42,794,384 | [python update](https://i.stack.imgur.com/gyHJ2.png)
I have Python 3.5 installed on my (LinuxMint) computer by:
```
sudo apt-get install python3.5
```
However, when I run python -V, it shows that Python 2.7 is being used.
How do I tell the system to use the updated version of Python? | 2017/03/14 | [
"https://Stackoverflow.com/questions/42794384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You have python2.7 installed and you already have a link to the `python2.7` executable so that when you simply run `python`, it actually runs `python2.7`. When you install python3.5, that link still exists.
You should either run `python3` (or `python3.5`) or you should replace the link with a new link like so (assumin... | More dynamically,
```
ln -sf $(which python3) $(which python)
```
which forces the creation of symbolic link from python3 to python. | 4,052 |
50,619,846 | I'm trying to create a series of subplots:
```
count=0
fig1, axes1 = plt.subplots(nrows=2, ncols=1, figsize=(10,80))
for x in b:
"""code gets data here as a dataframe"""
axes1[count]=q1.plot()
count=count+1
```
However this creates two plots rather than 2 subplots in one figure. I am using python 3.5 in Pyc... | 2018/05/31 | [
"https://Stackoverflow.com/questions/50619846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9874771/"
] | `DataReceived` event returns on another/secondary thread, which means you will have to marshal back to the UI thread to update your `TextBox`
[SerialPort.DataReceived Event](https://msdn.microsoft.com/fi-fi/library/system.io.ports.serialport.datareceived(v=vs.110).aspx)
>
> The DataReceived event is raised on a sec... | I got now the problem that when i send my command using **SerialPort.Write(string cmd)**, I can't read back the answer... | 4,053 |
57,551,049 | I am new to web scraping. I am trying to extract data using python from <https://www.clinicaltrialsregister.eu> using keywords "acute myeloid leukemia", "chronic myeloid leukemia", "acute lymphoblastic leukemia" to extract following information-EudraCT Number, Trial Status, Full title of the trial, Name of Sponsor, Cou... | 2019/08/19 | [
"https://Stackoverflow.com/questions/57551049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11266219/"
] | As i said, you can achieve this by concatenating the required part of url to every result.
Try this code:
```
import requests
from bs4 import BeautifulSoup
page = requests.get('https://www.clinicaltrialsregister.eu/ctr-search/search?query=acute+myeloid+leukemia&page=1')
soup = BeautifulSoup(page.text, 'html.parser')... | This script will traverse all pages of the search results and try to find relevant information.
It's necessary to add full url, not just `https://www.clinicaltrialsregister.eu`.
```
import requests
from bs4 import BeautifulSoup
base_url = 'https://www.clinicaltrialsregister.eu/ctr-search/search?query=acute+myeloid+l... | 4,054 |
11,300,737 | I cant import rdflib in python. error detailed:
```
Python 2.7.3 (default, Jun 27 2012, 23:48:21)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import rdflib
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/sit... | 2012/07/02 | [
"https://Stackoverflow.com/questions/11300737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1497041/"
] | If you actually install rdflib via `pip`, then its dependencies will come along with it (isodate included):
```
pip install -U rdflib
```
or
```
easy_install -U rdflib
```
Chances are you might have installed it directly from source, meaning you would have to take care of the deps yourself.
Information on instal... | It seems there is a dependency to [isodate](http://pypi.python.org/pypi/isodate/), so try installing that via your favorite PyPI-Installer (*pip* oder \*easy\_install\*). | 4,055 |
5,646,322 | I've written a python cgi script to generate random numbers and add them together
than ask the user to give the answer.
But even user answer was correct, it gives him wrong. The answer will not be correct.
The problem is in the flow :
```
#!/usr/bin/python2.7
import cgi,sys,random
sys.stderr = sys.stdout
input_fie... | 2011/04/13 | [
"https://Stackoverflow.com/questions/5646322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
javascript:
var all_product_ids = #{raw existing_ids.to_json};
var products_json = #{raw @filter.data.to_json};
``` | I had a similar problem with this. Using the code that others have provided didn't work for me because slim was html escaping my variable. I ended up using [Gon](https://github.com/gazay/gon-sinatra). This one is for Sinatra, but they have a gem for Rails as well. Hope it helps others having similar problems. | 4,056 |
58,917,280 | I am trying to base64 encode using a custom character set in python3. Most of the examples I have seen in SO are related to Python 2, so I had to make some minor adjustments to the code. The issue that I am facing is that I am replacing the character `/` with `_`, but it is still printing with `/`. My code is: This is ... | 2019/11/18 | [
"https://Stackoverflow.com/questions/58917280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7402287/"
] | If the only characters you want to switch are `+` and `\`, you can use [base64.urlsafe\_b64encode](https://docs.python.org/2/library/base64.html#base64.urlsafe_b64encode) to replace with `-` and `_` respectively.
```
>>> base64.urlsafe_b64encode(data.encode())
b'c29tZSByYW5kb20_IGRhdGE='
```
Alternatively, you can r... | Shouldn't this work:
```
import base64
data = 'some random? data'
custom = b"-_"
rslt = base64.b64encode(data)
print(rslt)
rslt = base64.b64encode(data, altchars=custom)
print(rslt)
```
I get following output:
```
c29tZSByYW5kb20/IGRhdGE=
c29tZSByYW5kb20_IGRhdGE=
```
or if you insist, that custom contains:
`... | 4,066 |
65,335,763 | Good day I am using FastAPI and I want to render the database contents on index.html - however I get the following error:
```
INFO: 127.0.0.1:55139 - "GET /?skip=0&limit=100 HTTP/1.1" 500 Internal Server Error
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/Users/barnaby/.local/... | 2020/12/17 | [
"https://Stackoverflow.com/questions/65335763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372626/"
] | BMC does not use OS services. BMC is completely OS independent and it may monitor and control hardware even when no OS is running or installed. BMC power line is independent on the host power and BMC is powered even when the host is powered off. It is ensured by power source design. BMC can control the host power suppl... | A general design is:
BMC connects to a CPLD, which controls the power sequence. When power off is needed, BMC will trigger the CPLD so that it is the same as if someone pushes the front panel power button. | 4,067 |
59,087,639 | I have the following code:
```
for i in range (0,20,1):
df = pd.read_excel(url, sheet_name=i,sep='\s*,\s*')
print('sample:',i+1)
df1 = df.loc[0:50] #initial push
ma=df1['Latest: Potential (V)'].values.tolist()
max_force_initial_push=max(ma)
```
And when I run it, I get the... | 2019/11/28 | [
"https://Stackoverflow.com/questions/59087639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12007010/"
] | This happens because the Promise object holds its state internally .
So when you call `.then` on a Promise object it will either :
* Await for resolution, and then fire the callback
* If the promise is already resolved, the callback will execute immediately | >
> So does it mean that the compiler does sth to assist here? for example, the compiler merge the then clause right after the promise1 statement just like example 1?
>
>
>
No, there is much less magic happening than you think. `new Promise` returns a promise object. A promise object has a `.then` method. You use ... | 4,068 |
69,614,180 | Hi I have a set of data which I extracted from an api and I am trying to split the data in the set down into separate sets since currently they are all nested in the larger set.
My current set:
```
api = {
"9/30/2018": {
"Capital Expenditure": "-13313000",
"End Cash Position": "25913000",
"Financing C... | 2021/10/18 | [
"https://Stackoverflow.com/questions/69614180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13970042/"
] | Given this structure:
```
api = {
"9/30/2018": {
"Capital Expenditure": "-13313000",
"End Cash Position": "25913000",
},
"9/30/2019": {
....
```
to get a list of key,values for the first entry can run:
```
for key,value in api["9/30/2018"]:
l = [key, value]
print(f" {key}, {value}")
# prin... | Your dictionary keys are string so use quotes when you access them like
```
s_19_30_2018 = api["9/30/2018"]
```
also I don't see any key such as "19\_30\_2018" in your dictionary. | 4,069 |
66,670,681 | I am working on a desktop application that I made by using the python language and some open-source library. When I convert that .py file to a .exe file using Pyinstaller it runs on window 10 but shows an error on window 7. Is there any way to make one .exe for all window versions 7/8/10?
* List item | 2021/03/17 | [
"https://Stackoverflow.com/questions/66670681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10975941/"
] | You do not need to "import" the functions, you would need just to create a `class` that keeps all your needed functions, and import that class.
I am supposing you use an IDE, you could go to your IDE and create a simple `class`.
e.g:
```java
public class Utils
{
public static int doSmth(/* Your parameters here */... | You can add at the beginning:
import
like-
```java
import utils;
```
Assuming it is in the same package as the current class
Else it should be:
```java
import <package name>.<class name>
``` | 4,074 |
19,162,812 | I have a python data structure like this
```
dl= [{'plat': 'unix', 'val':['', '', '1ju', '', '', '202', '', '']},
{'plat': 'Ios', 'val':['', '', '', '', 'Ty', '', 'Jk', '']},
{'plat': 'NT', 'val':['', '', 1, '', '' , '202', '', '']},
{'plat': 'centOs', 'val':['', '', ''... | 2013/10/03 | [
"https://Stackoverflow.com/questions/19162812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2843234/"
] | ```
dl= [{'plat': 'unix', 'val':['', '', '1ju', '', '', '202', '', '']},
{'plat': 'Ios', 'val':['', '', '', '', 'Ty', '', 'Jk', '']},
{'plat': 'NT', 'val':['', '', 1, '', '' , '202', '', '']},
{'plat': 'centOs', 'val':['', '', '', '', '', '202', '', '']},
{'plat': 'ubu... | ```
from itertools import izip
from operator import itemgetter
# create an iterator over columns
columns = izip(*(d['val'] for d in dl))
# make function keeps non-empty columns
keepfunc = itemgetter(*(i for i, c in enumerate(columns) if any(c)))
# apply function to each list
for d in dl:
d['val'] = list(keepfunc... | 4,076 |
40,701,398 | I am trying to figure out how to take the following for loop that splits an array based on the index of the lowest value in the row and use vectorization. I've looked at this [link](https://www.safaribooksonline.com/library/view/python-for-data/9781449323592/ch04.html) and have been trying to use the numpy.where functi... | 2016/11/20 | [
"https://Stackoverflow.com/questions/40701398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5025845/"
] | First, use `argsort` to see where the lowest value in each row is:
```
>>> a.argsort(axis=1)
array([[0, 1, 2],
[0, 1, 2],
[0, 1, 2],
[1, 0, 2],
[1, 0, 2],
[1, 0, 2],
[2, 1, 0],
[2, 1, 0],
[2, 1, 0]])
```
Note that wherever a row has `0`, that is the smallest c... | This is not the best solution since it relies on simple python loops and is not very efficient when you start dealing with large data sets but it should get you started.
The point is to create an array of "buckets" which store the data based on the depth of the lengthiest element. Then enumerate each element in `val... | 4,081 |
66,776,644 | My freelance client is giving FTP access to the shared hosting, I am new to web development and can't figure out how to deploy the flask app to cgi-bin folder, please help me understand how this works?
```
.htaccess file
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f # Don't interfere with static files
RewriteR... | 2021/03/24 | [
"https://Stackoverflow.com/questions/66776644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13993581/"
] | First create a python script which will contain:
```py
import sys
import subprocess
# implement pip as a subprocess:
subprocess.check_call([sys.executable, '-m', 'pip', 'install',
'flask'])
```
And then follow the instructions given by **Hostgator**.
Please mark it as an answer if it is helpful!
[![Rajdeep, a Ful... | Sorry but the Flask hosting can't be done within Shared-Hosting.
You need **DigitalOcean** or **Heroku** or **PythonAnywhere**(easiest) Hosting to deploy a **Flask**/**Django** Website. | 4,083 |
48,044,680 | I have a problem with python that is I want to generate a multidict like the one below, using a for loop. Numbers are generated randomly and if the two elements are the same, the value if 0.
```
arcs, capacity = multidict({
(0, 0): 0,
(0, 1): 80,
(0, 2): 11,
(1, 0): 15,
(1, 1): 0,
(1, 2): 120
(2, 0... | 2017/12/31 | [
"https://Stackoverflow.com/questions/48044680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Unit tests call functions that they test. You want to know if a function F called by a unit test can eventually invoke malloc (or new or ...). Seems like what you really want to do is build a call graph for your entire system, and then ask for the critical functions F whether F can reach malloc etc. in the call graph. ... | If you're using libraries which invoke malloc, then you might want to take a look at the [Joint Strike Fighter C++ Coding Standards](http://www.stroustrup.com/JSF-AV-rules.pdf). It's a coding style aimed towards mission critical software. One suggestion would be to write your own allocator(s). Another suggestion is to ... | 4,084 |
7,076,254 | I have a program which deals with nested data structures where the underlying type usually ends up being a decimal. e.g.
```
x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.999990111111]],...}
```
Is there a simple pythonic way to print such a variable but rounding all floats to (say) 3dp and not assuming a par... | 2011/08/16 | [
"https://Stackoverflow.com/questions/7076254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/768552/"
] | This will recursively descend dicts, tuples, lists, etc. formatting numbers and leaving other stuff alone.
```
import collections
import numbers
def pformat(thing, formatfunc):
if isinstance(thing, dict):
return type(thing)((key, pformat(value, formatfunc)) for key, value in thing.iteritems())
if isins... | ```
>>> b = []
>>> x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.999990111111]]}
>>> for i in x.get('a'):
if type(i) == type([]):
for y in i:
print("%0.3f"%(float(y)))
else:
print("%0.3f"%(float(i)))
1.056
2.346
1.111
10.000
```
The proble... | 4,087 |
49,883,687 | How to close a file if it is already open?
```
import xlwings as xw
wb = xw.Book(folderpath + 'Metrics - auto.xlsx')
```
Using try:except: but need a way to close the file so it can be opened, or find the file and work with it?
I get this error if it's already open:
```
wb = xw.Book(folderpath + 'Metrics - auto.... | 2018/04/17 | [
"https://Stackoverflow.com/questions/49883687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3664733/"
] | You can check the workbook collection with
```
import xlwings as xw
xw.books
```
and check if your fullname is already open using something like:
```
if myworkbook in [i.fullname for i in xw.books]:
...
``` | I have no experience with the xlwings package, but looking at the [source code](https://github.com/ZoomerAnalytics/xlwings/blob/master/xlwings/main.py) for `Book.__init__`, it looks like it automatically looks for any instances of the work book that are already open. If there is only one, then it returns it. If there i... | 4,090 |
35,692,537 | I want to scan some websites and would like to get all the java script files names and content.I tried python requests with BeautifulSoup but wasn't able to get the scripts details and contents.am I missing something ?
I have been trying lot of methods to find but I felt like stumbling in the dark.
This is the code I ... | 2016/02/29 | [
"https://Stackoverflow.com/questions/35692537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5478079/"
] | You can get all the linked JavaScript code use the below code:
```
l = [i.get('src') for i in soup.find_all('script') if i.get('src')]
```
* `soup.find_all('script')` returns a list of all the `<script>` tags in the page.
* A [*list comprehension*](https://stackoverflow.com/questions/34835951/) is used here to loop... | You can use a select with `script[src]` which will only find script tags with a src, you don't need to call .get multiple times:
```
import requests
from bs4 import BeautifulSoup
r = requests.get("http://www.marunadanmalayali.com/")
soup = BeautifulSoup(r.content)
src = [sc["src"] for sc in soup.select("script[src]"... | 4,091 |
71,443,087 | i'm struggling to debug my python code with regex in PyCharm.
The idea:
I want to find any case of 'here we are',
which can go with or without 'attention',
and the word 'attention' can be separated by whitespace, dot, comma, exclamation mark.
I expect this expression should do the job
```
r'(attention.{0,2})?here we... | 2022/03/11 | [
"https://Stackoverflow.com/questions/71443087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15769721/"
] | I would assume that you're using class components, so the solution I would provide is for that.
First step is to import ConnectedProps:
```
import { connect, ConnectedProps } from 'react-redux'
```
Next step is to define the objects that your state/reducer, so in a file that we can name `TsConnector.ts`, add someth... | Have you tried `useDispatch` and `useSelector` in ts file to get redux state
```
import {
useSelector as useReduxSelector,
TypedUseSelectorHook,
} from 'react-redux'
export const useSelector: TypedUseSelectorHook<RootState> = useReduxSelector
``` | 4,092 |
3,878,195 | The Python [logging module](http://docs.python.org/library/logging.html) is cumbersome to use. Is there a more elegant alternative? Integration with desktop notifications would be a plus. | 2010/10/07 | [
"https://Stackoverflow.com/questions/3878195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105066/"
] | You can look into [Twiggy](https://github.com/wearpants/twiggy), it's an early stage attempt to build a more pythonic alternative to the logging module. | ```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import logging.handlers
from logging.config import dictConfig
logger = logging.getLogger(__name__)
DEFAULT_LOGGING = {
'version': 1,
'disable_existing_loggers': False,
}
def configure_logging(logfile_path):
"""
Initialize logging defaul... | 4,093 |
64,913,140 | As per the [documentation](https://docs.python.org/3/reference/datamodel.html#object.__bool__), every class has a default `__bool__` that returns `true`.
Is there a way to "remove" this default behaviour so that it raises an error when used as bool (for instance in a expression like `if obj`?
And especially, is there... | 2020/11/19 | [
"https://Stackoverflow.com/questions/64913140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4444546/"
] | you can use Array map function on **option.selectedOption** too
just like:
```
{restaurant.map((option, marker) => (
<p key={marker.id}>
{option.selectedOption.map((optn, index) => (
<strong key={index}>
{optn.label + ', '}
... | You should do that instead:
```
{restaurant.map((option, marker) => (
<p key={marker.id}>
<strong>
{option.selectedOption.reduce(labels, label, index => labels += `${index > 0 ? ', ' : ''}${label}`, '')}
</strong>
</p>
))}
```
The array function `reduce()` allow you to (as the na... | 4,099 |
13,455,143 | Having a class
```
class A(object):
z = 0
def Func1(self):
return self.z
def Func2(self):
return A.z
```
Both methods (`Func1` and `Func2`) give the same result and are only included in this artificial example to illustrate the two possible methods of how to address `z`.
The result of ... | 2012/11/19 | [
"https://Stackoverflow.com/questions/13455143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572616/"
] | I would say that the proper way to get access to the variable is simply:
```
a_instance.z #instance variable 'z'
A.z #class variable 'z'
```
No need for `Func1` and `Func2` here.
---
As a side note, if you *must* write `Func2`, it seems like a `classmethod` might be appropriate:
```
@classmethod
def Fu... | I would usually use `self.z`, because in case there are subclasses with different values for `z` it will choose the "right" one. The only reason not to do that is if you know you will always want the `A` version notwithstanding.
Accessing via self or via a classmethod (see mgilson's answer) also facilitates the creati... | 4,100 |
64,996,663 | I was testing this function on some sample text file to make sure it is working as expected.
```
#include <stdio.h>
#include <time.h>
#define BUF 100
int main(){
FILE *fp = fopen("my_huge_file.txt","r");
char str[BUF];
int count=0;
while( (fgets(str, BUF, fp)) != NULL ){
... | 2020/11/25 | [
"https://Stackoverflow.com/questions/64996663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12549160/"
] | This issue is because your pipeline agent does not have Java 11 pre-installed in it.
You have two options to solve this issue.
**Option 1:** Change the pipeline agent to an agent which does have Java 11 pre-installed.
If you are using Microsoft-hosted pipeline agents, you can use this link to check which all agents ... | Perhaps the JDK running in your pipeline is, say, version 8. In that case, the Java compiler that is executed doesn't understand what version 11 means. Perhaps your local environment is using Java 11 where this problem would therefore not happen. | 4,103 |
58,167,766 | I am referring to the documentation of the [`re.findall`](https://docs.python.org/3/library/re.html#re.findall) function:
What is the meaning of *"Empty matches are included in the result."*? | 2019/09/30 | [
"https://Stackoverflow.com/questions/58167766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1779091/"
] | It just means when the match is “” or an empty string, that it is included in the list of results. | If a subject is an empty string then fullmatch() evaluates to True for any regex that can find a ... The overall regex match is not included in the tuple, unless you place the entire ... appear in the regular expression, as raw strings do not offer a means to escape it. | 4,106 |
62,684,468 | I'm working on an automated web scraper for a Restaurant website, but I'm having an issue. The said website uses Cloudflare's anti-bot security, which I would like to bypass, not the Under-Attack-Mode but a captcha test that only triggers when it detects a non-American IP or a bot. I'm trying to bypass it as Cloudflare... | 2020/07/01 | [
"https://Stackoverflow.com/questions/62684468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7032457/"
] | This really piqued my interests. The `requests` solution that I was able to get working.
Solution
--------
Finally narrow down the problem. When you use requests it uses urllib3 connection pool. There seems to be some inconsistency between a regular urllib3 connection and a connection pool. A working solution:
```py... | After some debugging, and thanks to the answers of @TuanGeek, we've found out the issue with the requests library seems to come from a DNS issue on requests' part when dealing with cloudflare, a simple fix to this issue is connecting directly to the host IP as such:
```
import requests
from collections import OrderedD... | 4,111 |
52,608,420 | I am using a language I made with a similar syntax to python, and I wanted to use python syntax highlighting for my language as well.
The only problem is that my language uses curly brackets rather then : and indents.
So some times when I type return for example it highlights the return in red.
Is there any way I ca... | 2018/10/02 | [
"https://Stackoverflow.com/questions/52608420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6516763/"
] | I'm surprised that someone is still using jQuery Mobile but I think I have most of the code you need.
Several years ago I wrote an article covering a complex jQuery Mobile authorization tutorial: <https://www.gajotres.net/complex-jquery-mobile-authorization-example/>
The main idea is to post your authorization inform... | I'm not sure what your php file looks like as you have not provided the code...
But here is a mockup example of the front-end js and html.
Place js in between head tags.
```
<script type="text/javascript">
$(document).ready(function () {
$("#insert").click(function () {
var email = $("#email... | 4,112 |
58,100,383 | I have been experimenting to create a docker image with python3.6 based on amazonlinux.
So far, I have not been very successful. I use
```
docker run -it amazonlinux
```
to start an interactive docker terminal. Inside the terminal, I run "yum install python36" and see the following error message. Note that I copied... | 2019/09/25 | [
"https://Stackoverflow.com/questions/58100383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1947254/"
] | You can check this [Dockerfile](https://github.com/RealSalmon/docker-amazonlinux-python/blob/master/Dockerfile) based on amazon Linux and having python version is `PYTHON_VERSION=3.6.4`.
Or you can work with your existing one like
```
ARG PYTHON_VERSION=3.6.4
ARG BOTO3_VERSION=1.6.3
ARG BOTOCORE_VERSION=1.9.3
ARG APP... | I too had similiar issue for docker.
yum install docker
Loaded plugins: ovl, priorities
amzn2-core | 3.7 kB 00:00:00
No package docker available.
Error: Nothing to do
instead yum I used amazon-linux-extras, it worked
amazon-linux-extras install docker
================================== | 4,113 |
53,296,469 | below is the python code
```
def load_scan(path):
print(path)
slices = [dicom.read_file(path + '/' + s) for s in os.listdir(path)]
slices.sort(key = lambda x: int(x.InstanceNumber))
try:
slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2])
except:
slice_thickness = np... | 2018/11/14 | [
"https://Stackoverflow.com/questions/53296469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207817/"
] | Find where filereader.py is. You can see the directory from the traceback itself.
Replace `raise StopIteration` with `return` and you are set to go.
Your filereader.py directory will look like this : `/usr/local/lib/python3.7/site-packages/dicom/filereader.py` | I believe dicom is no longer supported, Use [pydicom](https://pypi.org/project/pydicom/) instead of dicom. | 4,115 |
24,255,734 | I have a list of dicts that can be anywhere from 0 to 100 elements long. I want to look through the first three elements only, and I don't want to throw an error if there are less than three elements in the list. How do I do this cleanly in python?
psuedocode:
```
for element in my_list (max of 3):
do_stuff(eleme... | 2014/06/17 | [
"https://Stackoverflow.com/questions/24255734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672601/"
] | You could use `itertools.islice`:
```
for element in itertools.islice(my_list, 0, 3):
do_stuff(element)
```
Of course, if it actually *is* a list, then you could just use a regular slice:
```
for element in my_list[:3]:
do_stuff(element)
```
Regular slices on normal sequences are "forgiving" in that if yo... | ```
for element in my_list[:3]:
do_stuff(element)
``` | 4,116 |
69,979,902 | I am doing this assignment for a python course but I am nowhere near the solution.
Let's say if I enter x = 4, this is what I am supposed to get:
```
"pyramid(0) =>" [ ]
"pyramid(1) =>" [ [1] ]
"pyramid(2) =>" [ [1], [1, 1] ]
"pyramid(3) =>" [ [1], [1, 1], [1, 1, 1] ]
```
I believe t... | 2021/11/15 | [
"https://Stackoverflow.com/questions/69979902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15572613/"
] | You can do:
```
def pyramid(n):
result = []
for i in range(n):
result.append([1] * (i+1))
return result
>>> pyramid(0)
[]
>>> pyramid(1)
[[1]]
>>> pyramid(2)
[[1], [1, 1]]
``` | I tried to come up with words to guide you to this solution, but it just wasn't possible. You need a 'for' loop to count to 4, and you need `[1]*i` to create a list with a certain number of 1s.
```
x = 4
list1 = []
print("pyramid(0) =>", list1)
for i in range(x):
list1.append( [1] * i )
print("pyramid(%d) =>" ... | 4,121 |
44,311,287 | I am new to Robot Framework - I have tried to call this code to robot framework, but to no avail. I just need some help in order to run my python script in robot framework and return PASS and FAIL within that application. Any help on this would be greatly appreciated.
```
# -*- coding: utf-8 -*-
import paramiko
import... | 2017/06/01 | [
"https://Stackoverflow.com/questions/44311287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8055089/"
] | If this were my project, I would convert the code to a function and then create a keyword library that includes that function.
For example, you could create a file named CustomLibrary.py with a function defined like this:
```
def verify_model(model):
prompt = "#"
datetime = datetime.now()
ssh_pre = param... | To call Python code from Robot Framework, you need to use the same syntax as a Robot Framework Library, but once you do, it's very simple. Here's an example, in a file called CustomLibrary.py located in the same folder as the test:
```
from robot.libraries.BuiltIn import BuiltIn
# Do any other imports you want here.
... | 4,123 |
46,418,397 | This may appear like a very trivial question but I have just started learning python classes and objects. I have a code like below.
```
class Point(object):
def __init__(self,x,y):
self.x = float(x)
self.y = float(y)
def __str__(self):
return '('+str(self.x)+','+str(self.y)+... | 2017/09/26 | [
"https://Stackoverflow.com/questions/46418397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8629294/"
] | I would use Repeat to add one element and implement the interpolation as a new lambda layer. I don't think there's an existing layer for this in keras. | Surprisingly there is no existing layer/function in keras that does such an interpolation of a tensor (as pointed out by xtof54). So, I implemented it using a lambda layer, and it worked fine.
```
def resize_like(input_tensor, ref_tensor): # resizes input tensor wrt. ref_tensor
H, W = ref_tensor.get_shape(... | 4,126 |
66,742,855 | I am working in selenium with python.
I used the code that worked, one hour ago, but now it returns me that
```
no such element: Unable to lacate element:...
```
The same code worked maximum one hour ago.
Where is the problem? I checked the source code, but it still the same
Here is my code:
```
import selenium
f... | 2021/03/22 | [
"https://Stackoverflow.com/questions/66742855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15446325/"
] | You could also use a capture group without a global flag to match for only a single match, and match all lines that do not start with 10 hyphens using a negative lookahead.
```
^(?:(?!----------).*\n)+(?=----------$)
```
[regex demo](https://regex101.com/r/h0BlCk/1)
Or you can match as least as possible lines, unti... | You may try matching on the following pattern, with DOT ALL mode enabled:
```regex
^.*?(?=----------|$)
```
[Demo
----](https://regex101.com/r/mvZxBD/1)
This will match all content up to, but including, the first set of dashes. Note that for inputs not having any dash separators, it would return all content.
If yo... | 4,127 |
64,812,794 | The following code appears when I am running a cell on Google Colab:
```
NameError Traceback (most recent call last)
<ipython-input-36-5f325bc0550d in <module>()
4
5 TAGGER_PATH = "crf_nlu.tagger" # path to the tagger- it will save/access the model from here
----> 6 ct = ... | 2020/11/12 | [
"https://Stackoverflow.com/questions/64812794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14597269/"
] | I just sorted it out. For the google colab, I had to add the following line:
>
> pip install sklearn-pycrfsuite
>
>
> | Use:
>
> pip install python-crfsuite
>
>
>
Scikit-crfsuite provides API similar to scikit-learn library. | 4,128 |
21,492,214 | I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python". | 2014/01/31 | [
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] | You can execute your file by using this:
```
python /Users/luca/Documents/python/gameover.py
```
You can also run the file by moving to the path of the file you want to run and typing:
```
python gameover.py
``` | Let's say your script is called `my_script.py` and you have put it in your Downloads folder.
There are many ways of installing Python, but [Homebrew](https://brew.sh/) is the easiest.
0. Open [Terminal.app](https://en.wikipedia.org/wiki/Terminal_(macOS)) (press ⌘+Space and type "Terminal" and press the [Enter key](ht... | 4,129 |
42,165,925 | I have .txt file that has 6 lines on it.
```
Line 1 name
Line 2 eamil address
line 4 phone number
line 5 sensor name
line 6 link .
```
I want to read those 6 lines in python and forward an email to the email address listed in the second line. I have a script that does this . But I don't know how to do this from... | 2017/02/10 | [
"https://Stackoverflow.com/questions/42165925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7449247/"
] | ```
with open("filename", "r") as f:
for l in f:
// do your processing, maybe keep track of how many lines you see since you need to do something different on each line
``` | Have a look at this question: [How do I read a text file into a string variable in Python](https://stackoverflow.com/q/8369219/2519977)
It shows you how to read a file line per line into an array.
So you can do:
```
with open('data.txt', 'r') as myfile:
data=myfile.read().replace('\n', '')
```
`data[1]` woul... | 4,139 |
65,912,670 | I have .csv file with only 2 columns. ("left" and "right")
The file size is less than 200 MB
I use the following code on **dev server** and it works as expected:
```
import pandas as pd
df = pd.read_csv('en_bigram.csv')
st = df[df["right"] == "some_text"]["left"]
st[st.str.startswith("My")].to_list()
```
"pandas" mo... | 2021/01/27 | [
"https://Stackoverflow.com/questions/65912670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139150/"
] | I ran the following experiments on my machine (Intel 9th Gen i7) with a test data file of ~535 MB:
### Pandas version
```py
# import measurement dependencies
import time
import psutil
p = psutil.Process()
start = time.process_time()
import pandas as pd
df = pd.read_csv('test.csv')
st = df[df["right"] == "some_text... | >
> Is there any overhead (like memory/ cpu) in using pandas in production? Can the 4 lines pandas code written using python's built in modules like csv in 4 or 5 lines?
>
>
>
I'm going to say go with pandas. Once you start slicing and dicing large datasets, numpy arrays are much more efficient than python lists. | 4,141 |
67,172,207 | I've seen a couple of questions similar to this but none in python. Basically, I want to check if certain words are in a list. Though the words I want to compare might have a ',' which I want to ignore. I have tried this, though it does not ignore the ','.
```py
x = ['hello','there,','person']
y = ['there','person']
s... | 2021/04/20 | [
"https://Stackoverflow.com/questions/67172207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14222251/"
] | Check out this code use `any function` along with `map` to map containing conditon.
```
x = ['hello','there,','person']
y = ['there','person'] # or take this for more intuation ['there','person','bro']
similar = [words for words in y if any(map(lambda i: i.count(words), x))]
print(similar)
```
**OUTPUT:**
```
['the... | Just compare the strings without any comma:
```py
similar = [words for words in x if words.replace(',', '') in y ]
```
**Output**:
```py
>>similar
['there,', 'person']
``` | 4,142 |
24,807,434 | I've run into a problem with having imports in `__init__.py` and using `import as` with absolute imports in modules of the package.
My project has a subpackage and in its `__init__.py` I "lift" one of the classes from a module to the subpackage level with `from import as` statement. The module imports other modules fr... | 2014/07/17 | [
"https://Stackoverflow.com/questions/24807434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3227133/"
] | You incorrectly assume that one cannot have an alias with `from ... import`, as `from ... import ... as` has been there since Python 2.0. The `import ... as` is the obscure syntax that not many know about, but which you use by accident in your code.
[PEP 0221](http://legacy.python.org/dev/peps/pep-0221/) claims that t... | Your project structure regarding the way you call modules, must be like this:
```
pkg/
├── __init__.py
├── subpkg
│ ├── __init__.py
│ ├── one.py
│ └── two.py
tst.py
```
Define your **two.py** like this:
```
class TWO:
def functionTwo(self):
print("2")
```
Define your **one.py** like this :
```
... | 4,145 |
73,404,980 | I need to include a directory containing a python script and binaries that need to be executed by the script based on the parsed arguments in the JavaFX application.
The project is modular and built using Maven (although the modular part is not such an important piece of information).
When built using the maven run c... | 2022/08/18 | [
"https://Stackoverflow.com/questions/73404980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19794251/"
] | Problems
========
The `src/main/resources` directory only exists in your project sources. It does not exist in the build output, and it definitely does not exist in your deployment location. In other words, using:
```java
var pyPath = Paths.get("src/main/resources/script/main.py").toAbsolutePath().toString();
```
W... | I managed to create the artifacts using the [Java Packager](https://github.com/fvarrui/JavaPackager) plugin for Maven which made the deployment a much easier task. | 4,148 |
19,795,357 | I need to run some python files over and over with different settings and different file names.
Here is an example of a task I need to do. This is for Linux, but I need to do the same thing in Windows. Is there a way to use python to be the caller and run other python scripts which are already set to work on STD I/O? ... | 2013/11/05 | [
"https://Stackoverflow.com/questions/19795357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1018733/"
] | Don't think you can work around using `require`, but you can specifically check for `MODULE_NOT_FOUND` errors:
```
function moduleExists(mod) {
try {
require(mod);
} catch(e) {
if (e.code === 'MODULE_NOT_FOUND')
return false;
throw e;
};
return true;
}
``` | I'm showing with the "swig" module. There might be better ways, but this works for me.
```
var swig;
try {
swig = require('swig');
} catch (err) {
console.log(" [FAIL]\t Cannot load swig.\n\t Have you tried installing it? npm install swig");
}
if (swig != undefined) {
console.log(" [ OK ]\t Module: swig"... | 4,149 |
55,602,574 | I am attempting to programmatically put data into a locally running DynamoDB Container by triggering a Python lambda expression.
I'm trying to follow the template provided here: <https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Python.03.html>
I am using the amazon/dynamodb-local you ca... | 2019/04/09 | [
"https://Stackoverflow.com/questions/55602574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4740463/"
] | As per [the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Parameters) suggests, the `monthIndex` would start at 0, rather than 1. So you need to manually subtract 1.
```
data.forEach((item) => {
item.date.pop()
item.date[1]--
item.date = new Date(...item.dat... | The month is represented by a value from 0 to 11, 4 is the fifth month, it corresponds to May, you just need to decrease it by 1. | 4,152 |
60,654,425 | I am making a lot of plots and saving them to a file, it all works, but during the compilation I get the following message:
```
RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much... | 2020/03/12 | [
"https://Stackoverflow.com/questions/60654425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11085398/"
] | Replace `fig.close()` with `plt.close(fig)`, [`close`](https://matplotlib.org/2.1.0/api/_as_gen/matplotlib.pyplot.close.html) is a function defined directly in the module. | Try this, matplotlib.pyplot.close(fig) , for more information refer this website
<https://matplotlib.org/2.1.0/api/_as_gen/matplotlib.pyplot.close.html> | 4,153 |
14,082,909 | I'm creating a simple script for blender and i need a little help with get some data from file i've created before via python.
That file got structure like below:
```
name first morph
values -1.0000 1.0000
data 35 0.026703 0.115768 -0.068769
data 36 -0.049349 0.015188 -0.029470
data 37 -0.042880 -0.045805 -0.039931
d... | 2012/12/29 | [
"https://Stackoverflow.com/questions/14082909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1936580/"
] | ```
names = []
values = []
data = []
with open('yourfile') as lines:
for line in lines:
first, rest = line.split(' ', 1)
if first == 'name':
names.append(rest)
elif first == 'values':
floats = map(float, rest.split())
values.append(tuple(floats))
... | Here is a simple python "for line in" solution... you can just call `processed.py`...
```
fp = open("data1.txt", "r")
data = fp.readlines()
fp1 = open("processed.py", "w")
fp1.write("names = []\nvalues=[]\ndata=[]\n")
for line in data:
s = ""
if "name" in line:
s = "names.append('" + line[5:].strip(... | 4,154 |
33,936,017 | I learn how to remove items from a list while iterating from [here](https://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python) by:
```
somelist = [x for x in somelist if determine(x)]
```
Further, how do I remove a specific index from a list while iterating? For instance,
```
li... | 2015/11/26 | [
"https://Stackoverflow.com/questions/33936017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3067748/"
] | Basically your attempt is not supported according to any documentation. In general you should not modify a container while iterating unless the documentation explicitly says that you can. It doesn't help if it "seems to work" since you then just exploiting some behavior in the version of the implementation you're using... | You can produce the same thing using list comprehension:
```
somelist = [i for idx, i in enumerate(lists) if i[0] != lists[idx][0]]
``` | 4,155 |
13,033,820 | I have a question about while loops in python.
I want to make a program that performs a while loop in a certain time.I want to add the extra feature that while the program us running,a certain variable can be changed by pressing a random key.
```
from time import sleep
import time
i=0
a=0
while i<10:
... | 2012/10/23 | [
"https://Stackoverflow.com/questions/13033820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1714419/"
] | This might be happening because you render the *header*, *menu* and *body* inside a `<table>`. At least the *body* seems to be missing the row and cell tags (`<tr><td>...</td></tr>`). Therefore there are no rows and cells in your table which can lead to all sorts of rendering problems.
It would probably help if you di... | This looks to be nothing to do with the MVC side of what you are doing - that looks perfectly fine.
The issue will be with your HTML. I would suggest having a look at the site using one of the browser developer tools (e.g. in Chrome or IE open your site and press F12) - you can use the features of these to examine ho... | 4,156 |
59,407,592 | Below code has a call to a method called **lago**.
```
#!/usr/bin/env python
#
# Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
#
import sys
class InstallTest():
"""Ru Ovirt System Tests"""
def run_command_checking_exit_code(command):
""" Runs a command"""
print("Com... | 2019/12/19 | [
"https://Stackoverflow.com/questions/59407592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12342391/"
] | Try this :
```js
var value1="4111111111111111"
var pattern = new RegExp('^4[0-9]{12}(?:[0-9]{3})?$}');
var result=pattern.test(value1);
console.log(result);
```
This will return either `True` or `False` | If you pattern is somthimg like that: `4111111111111111` or `4111111111111111`
then use this code:
```
const str="^4[0-9]{12}([0-9]{3})?$";
'4111111111111'.match(str)
'4111111111111111'.match(str)
``` | 4,157 |
56,750,400 | Is there any library implementation for the `label2idx()` function in python?
I wish to extract superpixels from the label representation to the format exactly returned by the `label2idx()` function.
label2idx function: <https://in.mathworks.com/help/images/ref/label2idx.html> | 2019/06/25 | [
"https://Stackoverflow.com/questions/56750400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9215748/"
] | Given an array of labels `label_arr` containing all labels from `1` to `max(label_arr)`, you can do:
```
def label2idx(label_arr):
return [
np.where(label_arr.ravel() == i)[0]
for i in range(1, np.max(label_arr) + 1)]
```
---
If you want to relax the requirement of all labels being contained you... | MATLAB's [`label2idx`](https://www.mathworks.com/help/images/ref/label2idx.html) outputs the flattened indices (column-major ordered) given the labeled image.
We can use `scikit-image's` built-in [`regionprops`](https://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.regionprops) to get those indice... | 4,158 |
37,662,732 | I'm looking for an XPATH to extract 'sets' as separate sequences. It has to be interpreted by python `lxml` (which is a wrapper around `libxml2`).
For example, given the following:
```
<root>
<sub1>
<sub2>
<Container>
<item>1 - My laptop has exploded again</item>
... | 2016/06/06 | [
"https://Stackoverflow.com/questions/37662732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/204634/"
] | 1. Evaluate this XPath expression:
`count(/*/*/*)`
This finds the number of `<sub2>` elements (equivalent and more readable, but longer, is:
```
count(/*/sub1/sub2))
```
2. For each `$n` in 1 to `count(/*/*/*)` evaluate the following XPath expression:
`/*/*/*[$n]/*/item/text()`
Again, this is equivalent to the l... | ```
from lxml import etree
doc=etree.parse("data.xml");
v = doc.findall('sub1/sub2/Container')
finalResult = list()
for vv in v:
sequence = list()
for item in vv.findall('item'):
sequence.append(item.text)
finalResult.append(sequence)
print finalResult
```
And this is the result:
```
[['1 - My l... | 4,159 |
64,457,733 | I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefine... | 2020/10/21 | [
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] | To save `json` data in django the [TextIOWrapper](https://docs.python.org/3/library/io.html#io.TextIOWrapper) is used:
>
> The default encoding is now `locale.getpreferredencoding(False)` (...)
>
>
>
In documentation of `locale.getpreferredencoding` fuction we can [read](https://docs.python.org/3/library/locale.h... | Here is the solution from djangoproject.com
You go to Settings there's a "Use Unicode UTF-8 for worldwide language support", box in "Language" - "Administrative Language Settings" - "Change system locale" - "Region Settings".
If we apply that, and reboot, then we get a sensible, modern, default encoding from Python.... | 4,160 |
56,460,723 | I am working with Django and currently try to move my local dev. to Docker. I managed to run my web server. However, what I didn't to yet was `npm install`. That's where I got stuck and I couldn't find documentation or good examples. Anyone who has done that before?
**Dockerfile**:
```
# Pull base image
FROM python:3... | 2019/06/05 | [
"https://Stackoverflow.com/questions/56460723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10419791/"
] | It is simple, you should just follow this instruction:
```
npm install
//or
yarn install
```
This will install all node\_modules, when it is not found in the current directory, it will search for the **node\_modules** on directory up.
Hope this answers your question. | In the Dockerfile just add:
RUN npm install
This will look if there is a package.json in the current directory and if it does, it will install all dependencies. | 4,170 |
12,091,009 | I'm trying to get this [nodetime](http://nodetime.com/docs) running, but seems there's some prblems I can't figur out. I did exactly as the guide say, So i supposed to get following:
>
> After your start your application, a link of the form https://nodetime.com/[session\_id] will be printed to the console, where the ... | 2012/08/23 | [
"https://Stackoverflow.com/questions/12091009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1326868/"
] | No. You cannot embed an Apps Script web app in an external site. You can only do it on a Google Site. | Yes it is possible I have installed google comments and google follower on my tumblr blog. | 4,171 |
44,093,441 | In C++, how are the local class variables declared? I'm new to C++ but have some python experience. I'm wondering if C++ classes have a way of identifying their local variables, for example, in python your class' local variables are marked with a self. so they would be like:
```
self.variable_name
```
Does C++ have ... | 2017/05/21 | [
"https://Stackoverflow.com/questions/44093441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8034222/"
] | That's pretty close! Within the class, however, one would mention the class variables simply using their own name, therefore as `variable` as opposed to `class.variable`.
(Also, note that your functions need to have a semicolon following them, and by convention these functions tend to be defined under the class itsel... | When you read Effective C++ (written by Scott Meyers), member variables are init when ctor initializer. After ctor, all assignment is assignment, not init. You can write ctor like this.
```
Circle(double value, bool isTrueFalse, <More Variables>) : class.variable(value), class.othervariable(isTrueFalse), ..<More Varia... | 4,172 |
63,147,540 | This is my first time using Python and I'm tasked with the following: print a list of cities from this JSON: <http://jsonplaceholder.typicode.com/users>
I'm trying to print out a list that should read:
Gwenborough
Wisokyburgh
McKenziehaven
South Elvis
etc.
This is the code I have so far:
```
import json
import reque... | 2020/07/29 | [
"https://Stackoverflow.com/questions/63147540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13488080/"
] | As `users` is a list, it should be:
```
print(users[0]['address']['city'])
```
This is how you can access nested properties in JSON response.
You can also loop over the users and print their city in the same format.
```
for user in users:
print(user['address']['city'])
``` | You can get city name with user['address']['city']
and use loop to get all city names
like this
```
for user in users:
print(user['address']['city'])
```
output :
```
Gwenborough
Wisokyburgh
McKenziehaven
South Elvis
Roscoeview
South Christy
Howemouth
Aliyaview
Bartholomebury
Lebsackbury
[Program finished]
``... | 4,173 |
7,196,148 | I know there is not much on stackoverflow on dojango, but I thought I'd ask anyway.
Dojango describes RegexField as follows:
```
class RegexField(DojoFieldMixin, fields.RegexField):
widget = widgets.ValidationTextInput
js_regex = None # we additionally have to define a custom javascript regexp, because the py... | 2011/08/25 | [
"https://Stackoverflow.com/questions/7196148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/563247/"
] | After three days of beavering away I fould that you need to send `regex` and `js_regex`, though `regex` is not used:
```
post_code = RegexField(
regex='',
required = True,
widget=ValidationTextInput(
attrs={
'invalid': 'Post Code in incorrect format',
'regExp': '[A-Z]{1,2}\d... | The error is related to `super().__init__` call. If `fields.RegexField` is standard Django `RegexField`, then it requires `regex` keyword argument, as documented. Since you don't pass it, you get `TypeError`. If it's supposed to be the same as `js_regex`, then pass it along in the super call.
```
def __init__(self, js... | 4,175 |
46,327,700 | I have this `list` in `python` which can have `n` elements. Now what I am trying to do is show `4` elements from this `list` at a time with an added option 'next' to show next set of 4 elements. So if my list is something like this:
```
['room 11','room 22','room 33','room 44','room 55','room 65','room 77']
```
then... | 2017/09/20 | [
"https://Stackoverflow.com/questions/46327700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2966197/"
] | This will help you
```
room_list_num = 0
room_list_slot = 0
def room_try():
room_list = ['room 11','room 22','room 33','room 44','room 55','room 66','room 77','room 88','room 99','room 110','room 111','room 112']
inner_list_str = ["%d. Room number: %s" % ((i%4)+1, x)
for i, x in enumerat... | You can do something like this:
```
def room_try():
room_list_num = 0
room_list_slot = 0
room_list = ['room 11', 'room 22', 'room 33', 'room 44', 'room 55', 'room 66', 'room 77', 'room 88', 'room 99', 'room 110', 'room 111', 'room 112']
inner_list_str = ["%d. Room number: %s" % (i, x)
... | 4,176 |
53,823,349 | I have a set of values that I'd like to plot the gaussian kernel density estimation of, however there are two problems that I'm having:
1. I only have the values of bars not the values themselves
2. I am plotting onto a categorical axis
Here's the plot I've generated so far:
[ instead, but then it wouldn't be a KDE distribution.
Not all hope is l... | I have stated my reservations to applying a KDE to OP's categorical data in my comments above. Basically, as the phylogenetic distance between species does not obey the triangle inequality, there cannot be a valid kernel that could be used for kernel density estimation. However, there are other density estimation metho... | 4,177 |
57,094,939 | I am wrote a serializer for the User model in Django with DRF:
the model:
```py
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import BaseUserManager
from django.db import models
from django.utils.translation import ugettext
class BaseModel(models.Model):
# all models sho... | 2019/07/18 | [
"https://Stackoverflow.com/questions/57094939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1907902/"
] | I hope this will solve the issue,
```
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['email', 'username', 'password']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
**return models.User.objects.c... | You can create your own user manager by overriding `BaseUserManager` and use `set_password()` method there. There is a full example in django's [documentation](https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#a-full-example). So your `models.py` will be:
```py
# models.py
from django.db import models
fr... | 4,179 |
33,493,861 | I wrote script which create animation (movie) from fits files. One file has size 2.8 MB and the no. of files is 9000.
Here is code
```
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import os
import pyfits
import glob
import re
Writ... | 2015/11/03 | [
"https://Stackoverflow.com/questions/33493861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2952470/"
] | I would recommend you to use `ffmpeg`. With the command `image2pipe` you don't have to load all the images into your RAM but rather one by one (i think) into a pipe.
In addition to that, `ffmpeg` allows you to manipulate the video (framerate, codec, format, etc...).
<https://ffmpeg.org/ffmpeg.html> | You might be better off creating your animation with FuncAnimation instead of ArtistAnimation, as explained in [ArtistAnimation vs FuncAnimation matplotlib animation matplotlib.animation](https://stackoverflow.com/questions/22158395/artistanimation-vs-funcanimation-matplotlib-animation-matplotlib-animation) FuncAnimati... | 4,180 |
50,438,762 | The code below is a basic square drawing using Turtle in python.
Running the code the first time works. But running the code again activates a Turtle window that is non-responsive and subsequently crashes every time.
The error message includes `raise Terminator` and `Terminator`
Restarting kernel in Spyder (Python 3... | 2018/05/20 | [
"https://Stackoverflow.com/questions/50438762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9655448/"
] | I realize this will seem wholly unsatisfactory, but I have found that creating the turtle with:
```
try:
tess = turtle.Turtle()
except:
tess = turtle.Turtle()
```
works (that is, eliminates the "working every other time" piece. I also start with
```
wn = turtle.Screen()
```
and end with
```
from sys i... | The module uses a class variable \_RUNNING which remains true between executions when running in spyder instead of running it as a self contained script. I have requested for the module to be updated.
Meanwhile, work around/working example beyond what DukeEgr93 has proposed
1)
```
import importlib
import turtle
imp... | 4,181 |
50,192,322 | this is my code the I am currently writing for a robot in my university project. This code works, however the loop will constantly print statements every second and I would like it to only print when I change the input condition (break the if condition), so it wouldn't keep on printing. Is there anyway to fix this? Tha... | 2018/05/05 | [
"https://Stackoverflow.com/questions/50192322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9746251/"
] | Keep track of the last category - something like that.
```
previous_category = 0
while True:
#some stuff
if 0.01 < joystick.get_axis(1) <= 0.25:
if previous_category != 1:
print ('moving backward with 25% speed')
previous_category = 1
# performing some actions
elif... | You can accomplish this with a global integer that stores the last value printed. Something like this:
```
_last_count = None
def condprint(count):
global _last_count
if count != _last_count:
print('Waiting for joystick '+str(count))
_last_count = count
``` | 4,182 |
63,043,387 | I have three arrays, such that:
```
Data_Arr = np.array([1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5])
ID_Arr = np.array([1, 2, 3, 4, 5])
Value_Arr = np.array([0.1, 0.6, 0.3, 0.8, 0.2])
```
I want to create a new array which has the dimensions of Data, but where each element is from Values, using the index positi... | 2020/07/22 | [
"https://Stackoverflow.com/questions/63043387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2868191/"
] | Since `ID_Arr` is sorted, we can directly use [`np.searchsorted`](https://numpy.org/doc/stable/reference/generated/numpy.searchsorted.html) and index `Value_Arr` with the result:
```
Value_Arr[np.searchsorted(ID_Arr, Data_Arr)]
array([0.1, 0.1, 0.1, 0.6, 0.6, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.8, 0.8,
0.2, 0.2, 0.... | Looks like you want:
```
out = Value_Arr[ID_Arr[Data_Arr - 1] - 1]
```
Note that the `- 1` are due to the fact that Python/Numpy is `0`-based index. | 4,183 |
33,761,993 | Here's what I'm doing, I'm web crawling for my personal use on a website to copy the text and put the chapters of a book on text format and then transform it with another program to pdf automatically to put it in my cloud. Everything is fine until this happens: special characters are not copying correctly, for example ... | 2015/11/17 | [
"https://Stackoverflow.com/questions/33761993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3431636/"
] | The easiest way to fix this problem that I found is adding `encoding= "utf-8"` in the open function:
```
with open('file.txt','w',encoding='utf-8') as file :
file.write('ñoño')
``` | The only error I can spot is,
```
str(texta).encode("utf-8")
```
In it, you are forcing a conversion to str and encoding it. It should be replaced with,
```
texta.encode("utf-8")
```
**EDIT:**
The error stems in the server not giving the correct encoding for the page. So `requests` assumes a `'ISO-8859-1'`. As n... | 4,186 |
10,080,944 | I have a weird parsing problem with python. I need to parse the following text.
Here I need only the section between(not including) "pre" tag and column of numbers (starting with 205 4 164). I have several pages in this format.
```
<html>
<pre>
A Short Study of Notation Efficiency
CACM August, 1960
Smith Jr., H. ... | 2012/04/09 | [
"https://Stackoverflow.com/questions/10080944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776614/"
] | Here's a regular expression to do that:
```
findData = re.compile('(?<=<pre>).+?(?=[\d\s]*</pre>)', re.S)
# ...
result = findData.search(data).group(0).strip()
```
[Here's a demo.](http://codepad.org/M71yUzqw) | Quazi, this calls out for a regex, specifically `<pre>(.+?)(?:\d+\s+){3}` with the DOTALL flag enabled.
You can find out about how to use regex in Python at <http://docs.python.org/library/re.html> and if you do a lot of this sort of string extraction, you'll be very glad you did. Going over my provided regex piece-by... | 4,188 |
61,511,948 | I am coding a Discord bot in a library for python, discord.py.
I don't need help with that but with scraping some info from the site.
```py
@commands.command(aliases=["rubyuserinfo"])
async def rubyinfo(self, ctx, input):
HEADERS = {
'User-Agent' : 'Magic Browser'
}
url = ... | 2020/04/29 | [
"https://Stackoverflow.com/questions/61511948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11251803/"
] | *How about the following, using .select() method*
```
from bs4 import BeautifulSoup
html = '<p class="margin-none font-color">Hey! My name is KOMKO190 :) </p>'
soup = BeautifulSoup(html, features="lxml")
element = soup.select('p.margin-none')[0]
print(element.text)
```
*Prints out*
>
>
> ```
> Hey! My name is ... | ```
from bs4 import BeautifulSoup as bs
url = 'https://rubyrealms.com/user/username/'
session = requests.Session()
request = session.get(url=url)
if request.status_code == 200:
soup = bs(request.text, 'lxml')
print(soup.find('p', class_='margin-none font-color').text)
else:
print(request.status_code)
```... | 4,193 |
48,136,092 | I installed the python module tabula-py which is apparently based on the Java version of tabula. When I try to run it I get an error saying that the wrong version of Java is installed, but when I check in system perferences on MacOS it says I've got the latest version (Version 8 update 151). On the github page it menti... | 2018/01/07 | [
"https://Stackoverflow.com/questions/48136092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6670570/"
] | This answer on the github issues page fixed the problem. <https://github.com/chezou/tabula-py/issues/54>
```
sudo mv /usr/bin/java /usr/bin/java-1.6
sudo ln -s /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java /usr/bin/java
``` | Probably You installed java in mutiple locations.
Typ in terminal
$ wich java
To check where is this java 6 located. Then maybe You will fiund out how to uninstall it from this location. | 4,196 |
68,992,767 | I'm trying to implement selection sort in python using a list. But the implementation part is correct and is as per my algorithm but it is not resulting in correct output. Adding my code:
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex =... | 2021/08/31 | [
"https://Stackoverflow.com/questions/68992767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12116796/"
] | ```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
... | Your algorithm is almost correct but
`element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]` in this line you made the mistake.
It shouldn't be `compare_index`, it should be `element`. Please check the correct algorithm below
```
my_list = [64, 25, 12, 11, 32]
def selec... | 4,197 |
8,733,807 | >
> **Possible Duplicate:**
>
> [Is there a java equivalent of the python eval function?](https://stackoverflow.com/questions/7143343/is-there-a-java-equivalent-of-the-python-eval-function)
>
>
>
There is a String, something like `String str = "if a[0]=1 & a[1]=2"`. How to use this string in a real IF THEN exp... | 2012/01/04 | [
"https://Stackoverflow.com/questions/8733807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1089623/"
] | Java isn't a scripting language that supports dynamic evaluation (although it does support script execution). I would challenge you to check to see if what you're attempting to do is being done in the right way within Java.
There are two common ways you can approach this, listed below. However they have a significant ... | I don't think you can do what you're asking.
Also your java doesn't seem to make much sense. Something like this would make more sense:
```
for (Integer a : myNumbers) {
if (a.equals(Integer.valueOf(1))){
//...
}
}
```
You can however say:
```
if("hello".equals("world")){
//...
}
```
And you can ... | 4,202 |
70,461,539 | I have created a list of dictionaries of named tuples, keyed with an event type.
```
[{'EVENT_DELETE': DeleteRequestDetails(rid=53421, user='user1', type='EVENT_DELETE', reviewed=1, approved=1, completed=0)},{'EVENT_DELETE': DeleteRequestDetails(rid=13423, user='user2', type='EVENT_DELETE', reviewed=1, approved=1, com... | 2021/12/23 | [
"https://Stackoverflow.com/questions/70461539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3713151/"
] | Also you can trigger a link by JavaScript.
```
<button
onclick="window.location(this.getAttribute('data-link'))"
data-link="/hello">go to hello</button>
``` | One way could be to use an anchor tag instead of the button and make it look like a button.
HTML:
```html
<div class="buttons">
<a class="btn custom-btn position-bottom-right"> Add to cart</a>
</div>
```
CSS:
```css
.custom-btn {
border: medium dashed green;
}
```
Alternatively, you could do:
```
<button cl... | 4,203 |
72,335,222 | EDIT2:
------
A minimal demonstration is:
```
code = """\
a=1
def f1():
print(a)
print(f1.__closure__)
f1()
"""
def foo():
exec(code)
foo()
```
Which gives:
```
None
Traceback (most recent call last):
File "D:/workfiles/test_eval_rec.py", line 221, in <module>
foo()
File "D:/workfiles//test_eval_... | 2022/05/22 | [
"https://Stackoverflow.com/questions/72335222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9758790/"
] | **Using Exec**
You've already covered most of the problems and workarounds with `exec`, but I feel that there is still value in adding a summary.
The key issue is that `exec` only knows about `globals` and `locals`, but not about free variables and the non-local namespace. That is why the [docs](https://docs.python.o... | **Why this phenomena happen:**
Actually [the answer](https://stackoverflow.com/a/2749806/9758790) of the [question 4](https://stackoverflow.com/q/2749655/9758790) listed above can answer this question.
When call `exec()` on one code string, the code string is first compiled. I suppose that during compiling, the provi... | 4,207 |
23,244,245 | I have developed an application which uses udisks version 1 to find and list details of connected USB drives. The details include device (/dev/sdb1...etc), mount point, and free space. However, I found that modern distros has udisks2 installed by default. Here is the little code found on the other SO thread:-
```
#!/u... | 2014/04/23 | [
"https://Stackoverflow.com/questions/23244245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2221360/"
] | After lot of hit and trial, I could get what I wanted. Just posting it so that some one can benefit in the future. Here is the code:-
```
#!/usr/bin/python2.7
# coding: utf-8
import dbus
def get_usb():
devices = []
bus = dbus.SystemBus()
ud_manager_obj = bus.get_object('org.freedesktop.UDisks2', '/org/fre... | **Edit**
Note that the `Block` object does not have `ConnectionBus` or `Removable` properties. You will have to change the code to remove references to `Drive` object properties for the code to work.
**/Edit**
If you want to connect to `Block`, not `Drive`, then instead of
```
drive_info = v.get('org.freedesktop.UD... | 4,209 |
61,448,722 | I have a python function that outputs/prints the following:
```
['CN=*.something1.net', 'CN=*.something2.net', 'CN=*.something4.net', 'CN=something6.net', 'CN=something8.net', 'CN=intranet.something89.net', 'CN=intranet.something111.net, 'OU=PositiveSSL Multi-Domain, CN=something99.net', 'OU=Domain Control Validated, ... | 2020/04/26 | [
"https://Stackoverflow.com/questions/61448722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3704597/"
] | The last single quote is indicating the end of the string, so it seems you just want everything after `CN=`. Assuming that's the case, you can just chop off the first three characters:
```
subdomains = [item[3:] for item in my_list if item.startswith('CN=')]
``` | Here is a more readable code that extracts the subdomains in more clean or better way;
@tzaman code didn't really give me subdomains.
```
myDirtyDomains = ['CN=*.something1.net', 'CN=*.something2.net', 'CN=*.something4.net',\
'CN=something6.net', 'CN=something8.net', 'CN=intranet.something89.net',\
'CN=intranet.somet... | 4,210 |
50,283,776 | I am writing a python script and i want to execute some code only if the python script is being run directly from terminal and not from any another script.
How to do this in Ubuntu without using any extra command line arguments .?
The answer in here **DOESN't WORK**:
[Determine if the program is called from a script ... | 2018/05/11 | [
"https://Stackoverflow.com/questions/50283776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6665568/"
] | You should probably be using command-line arguments instead, but this *is* doable. Simply check if the current process is the process group leader:
```
$ sh -c 'echo shell $$; python3 -c "import os; print(os.getpid.__name__, os.getpid()); print(os.getpgid.__name__, os.getpgid(0)); print(os.getsid.__name__, os.getsid(0... | I recommend using command-line arguments.
**script.sh**
```sh
./testpython.py --from-script
```
**testpython.py**
```
import sys
if "--from-script" in sys.argv:
# From script
else:
# Not from script
``` | 4,212 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.