question_id
int64
59.5M
79.7M
creation_date
stringdate
2020-01-01 00:00:00
2025-07-15 00:00:00
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
60,421,630
2020-2-26
https://stackoverflow.com/questions/60421630/pytorch-tensor-save-produces-huge-files-for-small-tensors-from-mnist
I'm working with MNIST dataset from Kaggle challange and have troubles preprocessing with data. Furthermore, I don't know what are the best practices and was wondering if you could advise me on that. Disclaimer: I can't just use torchvision.datasets.mnist because I need to use Kaggle's data for training and submission....
As explained in this discussion, torch.save() saves the whole tensor, not just the slice. You need to explicitly copy the data using clone(). Don't worry, at runtime the data is only allocated once unless you explicitly create copies. As a general advice: If the data easily fits into your memory, just load it at once. ...
9
18
60,421,663
2020-2-26
https://stackoverflow.com/questions/60421663/is-python-3-semantically-versioned-and-forwards-compatible
I'm looking at some software that is wanting to bring in Python 3.6 for use in an environment where 3.5 is the standard. Reading up on Python's documentation I can't find anything about whether: 3.5 is representative of a semantic version number 3.6 would represent a forwards compatible upgrade (ie: code written for a...
The short answer is "No", the long answer is "They strive for something close to it". As a rule, micro versions match semantic versioning rules; they're not supposed to break anything or add features, just fix bugs. This isn't always the case (e.g. 3.5.1 broke vars() on a namedtuple, because it caused a bug that was wo...
14
16
60,418,497
2020-2-26
https://stackoverflow.com/questions/60418497/how-do-i-use-kwargs-in-python-3-class-init-function
I am writing a class in Python 3 that I want to be able to take various keyword arguments from the user and to store these values for later use in class methods. An example code would be something like this: class MathematicalModel: def __init__(self, var1, var2, var3, **kwargs): self.var1 = var1 self.var2 = var2 self....
General kwargs ideas When you load variables with self.var = value, it adds it to an internal dictionary that can be accessed with self.__dict__. class Foo1: def __init__(self, **kwargs): self.a = kwargs['a'] self.b = kwargs['b'] foo1 = Foo1(a=1, b=2) print(foo1.a) # 1 print(foo1.b) # 2 print(foo1.__dict__) # {'a': 1, ...
20
53
60,410,178
2020-2-26
https://stackoverflow.com/questions/60410178/how-to-invoke-python-function-as-a-callback-inside-c-thread-using-pybind11
I designed a C++ system that invokes user defined callbacks from procedure running in a separate thread. Simplified system.hpp looks like this: #pragma once #include <atomic> #include <chrono> #include <functional> #include <thread> class System { public: using Callback = std::function<void(int)>; System(): t_(), cb_()...
Thanks to this discussion and many other resources (1, 2, 3) I figured out that guarding the functions that start and join the C++ thread with gil_scoped_release seems to solve the problem: PYBIND11_MODULE(mysystembinding, m) { py::class_<System>(m, "System") .def(py::init<>()) .def("start", &System::start, py::call_gu...
9
7
60,410,625
2020-2-26
https://stackoverflow.com/questions/60410625/get-django-allowed-hosts-env-variable-formated-right-in-settings-py
I'm facing the following issue. My .env files contains a line like: export SERVERNAMES="localhost domain1 domain2 domain3" <- exactly this kind of format But the variable called SERVERNAMES is used multiple times at multiple locations of my deployment so i can't declare this as compatible list of strings that settings...
Simply split your SERVERNAMES variable using space as separator instead of comma ALLOWED_HOSTS = os.environ.get('SERVERNAMES').split(' ')
12
21
60,345,503
2020-2-21
https://stackoverflow.com/questions/60345503/pandas-parsererror-error-tokenizing-data-c-error-eof-inside-string
I have data that is over 400,000 lines long. When running this code: f=pd.read_csv(filename,error_bad_lines=False) I get the following error: pandas.errors.ParserError: Error tokenizing data. C error: EOF inside string starting at row 454751 My data by the end of the file looks like this: BTC 9948 8718 1.57E+12 ASK B...
Changing the Parser engine from C to Python should solve your problem. Use the following line to read your csv: f = pd.read_csv(filename, error_bad_lines=False, engine="python") From the read_csv documentation: engine : {‘c’, ‘python’}, optional Parser engine to use. The C engine is faster while the python engine is ...
16
28
60,312,374
2020-2-20
https://stackoverflow.com/questions/60312374/what-are-all-these-deprecated-loop-parameters-in-asyncio
A lot of the functions in asyncio have deprecated loop parameters, scheduled to be removed in Python 3.10. Examples include as_completed(), sleep(), and wait(). I'm looking for some historical context on these parameters and their removal. What problems did loop solve? Why would one have used it in the first place? Wh...
What problems did loop solve? Why would one have used it in the first place? Prior to Python 3.6, asyncio.get_event_loop() was not guaranteed to return the event loop currently running when called from an asyncio coroutine or callback. It would return whatever event loop was previously set using set_event_loop(some_l...
40
49
60,330,837
2020-2-21
https://stackoverflow.com/questions/60330837/jupyter-server-not-started-no-kernel-in-vs-code
i am trying to use jupyter notebooks from vs code and installed jupyter notebook extension and i am using (base)conda environment for execution. while this happened Error: Jupyter cannot be started. Error attempting to locate jupyter: at A.startServer (c:\Users\DELL\.vscode\extensions\ms-python.python-2020.2.63990\out\...
I had exactly the same problem when I installed Visual Studio Code and tried to run some Python code from a jupyter notebook on my fresh Ubuntu 18.04. How I solved it: Make sure you have installed the Jupyter Extension in VS Code. (for those who don't read the SO question :)) Press Command+Shift+P to open a new comma...
54
81
60,370,869
2020-2-24
https://stackoverflow.com/questions/60370869/print-underscore-separated-integer
Since python3.6, you can use underscore to separate digits of an integer. For example x = 1_000_000 print(x) #1000000 This feature was added to easily read numbers with many digits and I found it very useful. But when you print the number you always get a number not separated with digits. Is there a way to print the n...
Try using this: >>> x = 1_000_000 >>> print(f"{x:_}") 1_000_000 Here are details Another way would be to use format explicitly: >>> x = 1_000_000 >>> print(format(x, '_d')) 1_000_000
11
33
60,345,426
2020-2-21
https://stackoverflow.com/questions/60345426/json-to-protobuf-in-python
Hey I know there is a solution for this in Java, I'm curious to know if anyone knows of a Python 3 solution for converting a JSON object or file into protobuf format. I would accept either or as converting to an object is trivial. Searching the stackoverflow site, I only found examples of protobuf->json, but not the ot...
The library you're looking for is google.protobuf.json_format. You can install it with the directions in the README here. The library is compatible with Python >= 2.7. Example usage: Given a protobuf message like this: message Thing { string first = 1; bool second = 2; int32 third = 3; } You can go from Python dict or...
26
52
60,368,298
2020-2-24
https://stackoverflow.com/questions/60368298/could-not-load-dynamic-library-libnvinfer-so-6
I am trying to normally import the TensorFlow python package, but I get the following error: Here is the text from the above terminal image: 2020-02-23 19:01:06.163940: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libnvinfer.so.6'; dlerror: libnvinfer.so.6: cannot ope...
This is a warning, not an error. You can still use TensorFlow. The shared libraries libnvinfer and libnvinfer_plugin are optional and required only if you are using nvidia's TensorRT capabilities. To suppress this and all other warnings, set the environment variable TF_CPP_MIN_LOG_LEVEL="2".
51
53
60,300,644
2020-2-19
https://stackoverflow.com/questions/60300644/python-image-processing-on-captcha-how-to-remove-noise
I am so new on Image Processing and what I'm trying to do is clearing the noise from captchas; For captchas, I have different types of them: For the first one what I did is : Firstly, I converted every pixel that is not black to the black. Then, I found a pattern that is a noise from the image and deleted it. For...
Here is my solution, Firstly I got the background pattern(Edited on paint by hand). From: After that, I created a blank image to fill it with differences between the pattern and image. img = Image.open("x.png").convert("RGBA") pattern = Image.open("y.png").convert("RGBA") pixels = img.load() pixelsPattern = pattern.l...
8
2
60,303,795
2020-2-19
https://stackoverflow.com/questions/60303795/why-i-can-sometimes-use-functions-from-nested-modules-without-importing-the-whol
I was wondering what's the difference between these two cases? Is the inner structure of the modules somehow different? So why this one works: >>> import numpy >>> numpy.random.RandomState <class 'numpy.random.mtrand.RandomState'> But this one doesn't work until I import the nested module also: >>> import tkinter >>> ...
This kind of import behavior can be achieved by importing the deep class in the respective __init__.py files. Here's a quick demonstration of a project structure that works pretty much exactly like the real numpy and tkinter packages did: . ├── main.py ├── numpy │ ├── __init__.py │ └── random │ ├── __init__.py │ └── mt...
8
4
60,347,349
2020-2-21
https://stackoverflow.com/questions/60347349/attributeerror-tensor-object-has-no-attribute-numpy-in-tensorflow-2-1
I am trying to convert the shape property of a Tensor in Tensorflow 2.1 and I get this error: AttributeError: 'Tensor' object has no attribute 'numpy' I already checked that the output of tf.executing eagerly() is True, A bit of context: I load a tf.data.Dataset from a TFRecords, then I apply a map. The maping functio...
The problem in your code is that you cannot use .numpy() inside functions that are mapped onto tf.data.Datasets, because .numpy() is Python code not pure TensorFlow code. When you use a function like my_dataset.map(my_function), you can only use tf.* functions inside your my_function function. This is not a bug of Tens...
14
30
60,369,047
2020-2-24
https://stackoverflow.com/questions/60369047/pytest-using-parametized-fixture-vs-pytest-mark-parametrize
I'm writing some unit tests using Pytest and came across two ways to parameterize test inputs. One is using parametereized fixtures and the other is using the pytest.mark.parametrize method. The two examples I have are: # method 1 def tokens(): yield from ["+", "*", "?"] @pytest.mark.parametrize("token", tokens()) def ...
As pk786 mentions in his comment, you should use a fixture "...if you have something to set up and teardown for the test or using (the) same dataset for multiple tests then use fixture". For example, you may want to load several datasets that you test against in different test functions. Using a fixture allows you to o...
12
14
60,384,288
2020-2-24
https://stackoverflow.com/questions/60384288/pyinstaller-modulenotfounderror
I have built a python script using tensorflow and I am now trying to convert it to an .exe file, but have ran into a problem. After using pyinstaller and running the program from the command prompt I get the following error: File "site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 25, in <module> ModuleN...
EDIT: The latest versions of PyInstaller (4.0+) now include support for tensorflow out of the box. Create a directory structure like this: - main.py # Your code goes here - don't bother actually naming you file this - hooks - hook-tensorflow.py Copy the following into hook-tensorflow.py: from PyInstaller.utils.hooks i...
7
20
60,292,750
2020-2-19
https://stackoverflow.com/questions/60292750/plotly-how-to-plot-a-bar-line-chart-combined-with-a-bar-chart-as-subplots
I am trying to plot two different charts in python through plotly. I have two plots, one plot consists of merged graph ( line and bar chart) like the following, , and another one is bar chart as follows, I wanted to display one single chart with these two combined charts and display the same. I have tried this in plo...
The key here is to assign your traces to the subplot through row and col in fig.add_trace(). And you don't have to use from plotly.offline import iplot for the latest plotly updates. Plot: Code: # imports from plotly.subplots import make_subplots import plotly.graph_objects as go import pandas as pd import numpy as np...
11
7
60,309,060
2020-2-19
https://stackoverflow.com/questions/60309060/cannot-load-library-libcairo
I have problem when trying to run a website in Django: OSError: no library called "libcairo-2" was found cannot load library 'libcairo.so.2': /lib/x86_64-linux-gnu/libfontconfig.so.1: undefined symbol: FT_Done_MM_Var cannot load library 'libcairo.so': /lib/x86_64-linux-gnu/libfontconfig.so.1: undefined symbol: FT_Done_...
For Ubuntu 20 and Debian based distro, try: sudo apt-get install libpangocairo-1.0-0
13
18
60,381,208
2020-2-24
https://stackoverflow.com/questions/60381208/ignoring-django-migrations-in-pyproject-toml-file-for-black-formatter
I just got Black and Pre-Commit set up for my Django repository. I used the default config for Black from the tutorial I followed and it's been working great, but I am having trouble excluding my migrations files from it. Here is the default configuration I've been using: pyproject.toml [tool.black] line-length = 79 in...
Add the migration exclusion to your .pre-commit-config.yaml file - id: black exclude: ^.*\b(migrations)\b.*$
22
18
60,382,793
2020-2-24
https://stackoverflow.com/questions/60382793/what-are-the-inputs-to-the-transformer-encoder-and-decoder-in-bert
I was reading the BERT paper and was not clear regarding the inputs to the transformer encoder and decoder. For learning masked language model (Cloze task), the paper says that 15% of the tokens are masked and the network is trained to predict the masked tokens. Since this is the case, what are the inputs to the trans...
Ah, but you see, BERT does not include a Transformer decoder. It is only the encoder part, with a classifier added on top. For masked word prediction, the classifier acts as a decoder of sorts, trying to reconstruct the true identities of the masked words. Classifying Non-masked is not included in the classification ta...
7
6
60,298,514
2020-2-19
https://stackoverflow.com/questions/60298514/how-to-reinstall-python2-from-homebrew
I have been having issues with openssl and python@2 with brew, which have explained here (unresolved). The documented workaround to reinstall Python and openssl was not working, so I decided I would uninstall and reinstall Python. The problem is, when you try to install Python 2 with brew, you receive this message: bre...
It seems that the homebrew staff really makes it as hard as possible to use Python 2.7 on macOS as they can. The linked brew extract link is really not helpful, you need to look for answers here about how to make your own tap from extracted sources. The linked commit: 028f11f9e is wrong, as it contains the already del...
206
183
60,371,624
2020-2-24
https://stackoverflow.com/questions/60371624/drawing-a-3d-box-in-a-3d-scatterplot-using-plotly
I was trying to plot a 3d box in a 3d scatterplot. Basically, this was the result of an optimization problem (background is here). The box is the largest empty box possible given all the points. In the plotly docs I noticed an example of a 3d cube built using 3dmesh. I copied this: import plotly.graph_objects as go x=[...
For me using the argument flatshading = True did the job. Code fig = go.Figure(data=[ go.Scatter3d(x=x, y=y, z=z, mode='markers', marker=dict(size=2) ), go.Mesh3d( # 8 vertices of a cube x=[0.608, 0.608, 0.998, 0.998, 0.608, 0.608, 0.998, 0.998], y=[0.091, 0.963, 0.963, 0.091, 0.091, 0.963, 0.963, 0.091], z=[0.140, 0.1...
8
11
60,296,197
2020-2-19
https://stackoverflow.com/questions/60296197/flask-orjson-instead-of-json-module-for-decoding
I'm using flask and have a lot of requests. The json module, which is used by flask, is quite slow. I automatically can use simplejson, but thats a bit slower, not faster. According to the documentation I can define a decoder (flask.json_decoder), but orjson doesn't have this class. I only have the function loads and d...
a very basic implementation could look like this: class ORJSONDecoder: def __init__(self, **kwargs): # eventually take into consideration when deserializing self.options = kwargs def decode(self, obj): return orjson.loads(obj) class ORJSONEncoder: def __init__(self, **kwargs): # eventually take into consideration when ...
10
8
60,358,228
2020-2-23
https://stackoverflow.com/questions/60358228/how-to-set-title-on-seaborn-jointplot
The JointPlot documentation does not show the title : can it be set? http://seaborn.pydata.org/generated/seaborn.jointplot.html?highlight=reg
this worked for me p = sns.jointplot(x = 'x_', y = 'y_', data = df, kind="kde") p.fig.suptitle("Your title here") p.ax_joint.collections[0].set_alpha(0) p.fig.tight_layout() p.fig.subplots_adjust(top=0.95) # Reduce plot to make room
17
38
60,294,463
2020-2-19
https://stackoverflow.com/questions/60294463/attributeerror-dataframe-object-has-no-attribute-set-value
I'm using flask and getting error at set_values. I'm reading the input from html and passing it to the code @app.route('/home', methods=['POST']) def first(): source = request.files['first'] destination = request.files['second'] df = pd.read_csv(source) df1 = pd.read_csv(destination) val1 = int(request.form['val1']) v...
Check your pandas version. df.set_value() is deprecated since pandas version 0.21.0 Instead use df.at import pandas as pd df = pd.DataFrame({"A":[1, 5, 3, 4, 2], "B":[3, 2, 4, 3, 4], "C":[2, 2, 7, 3, 4], "D":[4, 3, 6, 12, 7]}) df.at[2,'B']=100 A B C D 0 1 3 2 4 1 5 2 2 3 2 3 100 7 6 3 4 3 3 12 4 2 4 4 7
16
48
60,310,647
2020-2-19
https://stackoverflow.com/questions/60310647/is-tensorflow-data-dataset-the-same-as-datasetv1adapter
When I use: training_ds = tf.data.Dataset.from_generator(SomeTrainingDirectoryIterator, (tf.float32, tf.float32)) I expect for it to return a Tensorflow Dataset, but instead, training_ds is a DatasetV1Adapter object. Are they essentially the same thing? If not could I convert the DatasetV1Adapter to a Tf.Data.Dataset ...
If you're using Tensorflow 2.0 (or below) from_generator will give you DatasetV1Adapter. For the Tensorflow version greater than 2.0 from_generator will give you FlatMapDataset. The error you are facing is not related to the type of dataset from_generator returns, but with the way you are printing the dataset. batch.it...
10
6
60,358,216
2020-2-23
https://stackoverflow.com/questions/60358216/python-requests-post-request-dropping-authorization-header
I'm trying to make an API POST request using the Python requests library. I am passing through an Authorization header but when I try debugging, I can see that the header is being dropped. I have no idea what's going on. Here's my code: access_token = get_access_token() bearer_token = base64.b64encode(bytes("'Bearer {}...
TLDR The url you are requesting redirects POST requests to a different host, so the requests library drops the Authoriztion header in fear of leaking your credentials. To fix that you can override the responsible method in requests' Session class. Details In requests 2.4.3, the only place where reqeuests removes the Au...
12
23
60,323,366
2020-2-20
https://stackoverflow.com/questions/60323366/valueerror-numpy-ufunc-size-changed-may-indicate-binary-incompatibility-expec
In jupyter notebook I am running through this error. I am using py I just installed pytorch, previously it was working fine. import pyodbc import pandas as pd import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') When I run the above cell I got the following error: ------------------------...
Which version of numpy do you have installed? I got the same error with 1.18.5, downgrading to 1.16.0 or 1.16.1 solved the issue. Also check which numpy version is required by pytorch, and any other library requiring numpy, I found pipdeptree quite useful for that.
17
8
60,394,664
2020-2-25
https://stackoverflow.com/questions/60394664/cant-debug-django-unit-tests-within-visual-studio-code
I want to be able to run and debug unit tests for a Django project from within Visual Studio Code. I am an experienced developer, but fairly new to both Django and Visual Studio Code. The crux of the problem is that either the tests are undiscoverable within Visual Studio Code, or if they are discoverable, I get a Con...
You need to load the django configuration previous to run any test, for that reason the code in __init__.py file. If pytest is an option for you, you have to install pytest and pytest-django pip install pytest pytest-django create a pytest configuration (ex: pytest.ini) at the same level of manage.py file with the fo...
16
6
60,305,098
2020-2-19
https://stackoverflow.com/questions/60305098/modulenotfounderror-no-module-named-sklearn-preprocessing-data
My question is similar to this. I also use pickle to save & load model. I meet the below error during pickle.load( ) from sklearn.preprocessing import StandardScaler # SAVE scaler = StandardScaler().fit(X_train) X_trainScale = scaler.transform(X_train) pickle.dump(scaler, open('scaler.scl','wb')) # ================= # ...
I had exactly the same error message with StandardScaler using Anaconda. Fixed it by running: conda update --all I think the issue was caused by running the pickle dump for creating the scaler file on a machine with a newer version of scikit-learn, and then trying to run pickle load on machine with an older version o...
14
5
60,330,730
2020-2-21
https://stackoverflow.com/questions/60330730/typing-interfaces
What is the correct way to type an "interface" in python 3? In the following sample: class One(object): def foo(self) -> int: return 42 class Two(object): def foo(self) -> int: return 142 def factory(a: str): if a == "one": return One() return Two() what would be the correct way to type the return value of the factory...
You could use a typing.Union but, it sounds like you really want structural typing not nominal. Python supports this using typing.Protocol, which is a supported part of the python type-hinting system, so mypy will understand it, for example: import typing class Fooable(typing.Protocol): def foo(self) -> int: ... class ...
11
14
60,377,747
2020-2-24
https://stackoverflow.com/questions/60377747/return-predictions-wav2vec-fairseq
I'm trying to use wav2vec to train my own Automatic Speech Recognition System: https://github.com/pytorch/fairseq/tree/master/examples/wav2vec import torch from fairseq.models.wav2vec import Wav2VecModel cp = torch.load('/path/to/wav2vec.pt') model = Wav2VecModel.build_model(cp['args'], task=None) model.load_state_dict...
After trying various things I was able to figure this out and trained a wav2vec model from scratch. Some background: wav2vec uses semi-supervised learning to learn vector representations for preprocessed sound frames. This is similar to what word2vec does to learn word embeddings a text corpus. In the case of wav2vec i...
8
20
60,367,378
2020-2-23
https://stackoverflow.com/questions/60367378/finding-neighbourhoods-cliques-in-street-data-a-graph
I am looking for a way to automatically define neighbourhoods in cities as polygons on a graph. My definition of a neighbourhood has two parts: A block: An area inclosed between a number of streets, where the number of streets (edges) and intersections (nodes) is a minimum of three (a triangle). A neighbourhood: For...
Finding city blocks using the graph is surprisingly non-trivial. Basically, this amounts to finding the smallest set of smallest rings (SSSR), which is an NP-complete problem. A review of this problem (and related problems) can be found here. On SO, there is one description of an algorithm to solve it here. As far as I...
12
6
60,338,062
2020-2-21
https://stackoverflow.com/questions/60338062/why-does-assigning-with-versus-iloc-yield-different-results-in-pandas
I am so confused with different indexing methods using iloc in pandas. Let say I am trying to convert a 1-d Dataframe to a 2-d Dataframe. First I have the following 1-d Dataframe a_array = [1,2,3,4,5,6,7,8] a_df = pd.DataFrame(a_array).T And I am going to convert that into a 2-d Dataframe with the size of 2x4. I star...
There is a very, very big difference between series.iloc[:] and series[:], when assigning back. (i)loc always checks to make sure whatever you're assigning from matches the index of the assignee. Meanwhile, the [:] syntax assigns to the underlying NumPy array, bypassing index alignment. s = pd.Series(index=[0, 1, 2, 3]...
13
4
60,395,570
2020-2-25
https://stackoverflow.com/questions/60395570/invalidargumentexception-message-invalid-argument-using-must-be-a-string
im very new to python, trying to create reusable code. when i try to call the class Login and function login_user in test_main.py by passing all the arguments that were used under Login class, im getting an error as InvalidArgumentException: Message: invalid argument: 'using' must be a string. test_main.py file which r...
I fixed it myself by removing the extra pair of parenthesis from the line loginButton = self.driver.find_element((By.XPATH, Locators_test.loginlink_xpath)) Right way is loginButton = self.driver.find_element(By.XPATH, Locators_test.loginlink_xpath) ps: this applies to all the lines.
13
24
60,359,268
2020-2-23
https://stackoverflow.com/questions/60359268/how-to-output-the-second-layer-of-a-network
My model is trained on digit images (MNIST dataset). I am trying to print the output of the second layer of my network - an array of 128 numbers. After reading a lot of examples - for instance this, and this, or this. I did not manage to do this on my own network. Neither of the solutions work of my own algorithm. Link...
Looks like you are mixing old keras (before tensorflow 2.0: import keras) and new keras (from tensorflow import keras). Try not to use old keras alongside tensorflow>=2.0 (and not to refer to the old documentation as in your first link), as it is easily confused with the new one (although nothing strictly illogical): ...
9
3
60,363,908
2020-2-23
https://stackoverflow.com/questions/60363908/spark-why-does-python-significantly-outperform-scala-in-my-use-case
To compare performance of Spark when using Python and Scala I created the same job in both languages and compared the runtime. I expected both jobs to take roughly the same amount of time, but Python job took only 27min, while Scala job took 37min (almost 40% longer!). I implemented the same job in Java as well and it ...
Your basic assumption, that Scala or Java should be faster for this specific task, is just incorrect. You can easily verify it with minimal local applications. Scala one: import scala.io.Source import java.time.{Duration, Instant} object App { def main(args: Array[String]) { val Array(filename, string) = args val start...
17
14
60,403,545
2020-2-25
https://stackoverflow.com/questions/60403545/flake8-not-giving-errors-warnings-on-missing-docstring-or-code-not-following-pep
I am trying to run Flake8 for my python code however I'm noticing it's not giving me any of the PyDocStyle errors on a simple class with missing docstrings or warning about my class name cars which should be Cars according to PEP8 style guide Example code file (cars.py) class cars: def __init__(self, some_value): self....
So what I found out was that by default Flake8 wraps pycodestyle: 2.5.0 by default which from the documentation says: Among other things, these features are currently not in the scope of the pycodestyle library: naming conventions: this kind of feature is supported through plugins. Install flake8 and the pep8-naming ...
11
11
60,383,266
2020-2-24
https://stackoverflow.com/questions/60383266/python-reuse-functions-in-dash-callbacks
I'm trying to make an app in the Python Dash framework which lets a user select a name from a list and use that name to populate two other input fields. There are six places where a user can select a name from (the same) list, and so a total of 12 callbacks that need to be performed. My question is, how can I use a sin...
You could do something like this: def update_health(monster): if monster != '': relevant = [m for m in monster_data if m['name'] == monster] return relevant[0]['health'] else: return 11 @app.callback( Output('rp-mon1-health', 'value'), [Input('rp-mon1-name', 'value')] ) def monster_1_callback(*args, **kwargs): return u...
9
9
60,340,107
2020-2-21
https://stackoverflow.com/questions/60340107/pandas-dataframe-bin-on-multiple-columns-get-statistics-on-another-column
Problem I have a target variable x and some additional variables A and B. I want to calculate averages (and other statistics) of x when certain conditions for A and B are met. A real world example would be to calculate the average air temperature (x) from a long series of measurements when solar radiation (A) and wind ...
Approach #1 : Pandas + NumPy (some to none) We will try to keep it to pandas/NumPy so that we could leverage dataframe methods or array methods and ufuncs, while vectorizing it at their level. This makes it easier to extend the functionalities when complex problems are to be solved or statistics are to be generated, as...
14
12
60,390,709
2020-2-25
https://stackoverflow.com/questions/60390709/working-with-mixed-datetime-formats-in-pandas
I read a file into a pandas dataframe with dates that vary in their format: either the American: YYYY-MM-DD or the European: DD.MM.YYYY They come as a string. I would like to format them all as a date object so pandas.Series.dt can work with them and ideally have them in the second format (DD.MM.YYYY). pandas.Series....
Use to_datetime with both formats separately, so get missing values if format not match, so for new column use Series.fillna: df = pd.DataFrame({'date': ['2000-01-12', '2015-01-23', '20.12.2015', '31.12.2009']}) print (df) date 0 2000-01-12 1 2015-01-23 2 20.12.2015 3 31.12.2009 date1 = pd.to_datetime(df['date'], error...
9
13
60,388,502
2020-2-25
https://stackoverflow.com/questions/60388502/how-can-i-replace-the-first-occurrence-of-a-character-in-every-word
How can I replace the first occurrence of a character in every word? Say I have this string: hello @jon i am @@here or @@@there and want some@thing in '@here" # ^ ^^ ^^^ ^ ^ And I want to remove the first @ on every word, so that I end up having a final string like this: hello jon i am @here or @@there and want someth...
I would do a regex replacement on the following pattern: @(@*) And then just replace with the first capture group, which is all continous @ symbols, minus one. This should capture every @ occurring at the start of each word, be that word at the beginning, middle, or end of the string. inp = "hello @jon i am @@here or ...
45
50
60,382,598
2020-2-24
https://stackoverflow.com/questions/60382598/django-aws-elastic-beanstalk-error-improperlyconfigured-error-loading-mysqldb-m
I know this error have come to many people and I have tried different solutions and none of them worked. I am using aws eb cli. I am using following command eb deploy to deploy my application to server. Following are the configuration for my Django. under .ebextensions directory, I have following 2 files: 1: 01_package...
Try running sudo yum install mysql-devel gcc python-devel Then pip install mysqlclient
7
2
60,378,705
2020-2-24
https://stackoverflow.com/questions/60378705/python-vs-julia-autocorrelation
I am trying to do autocorrelation using Julia and compare it to Python's result. How come they give different results? Julia code using StatsBase t = range(0, stop=10, length=10) test_data = sin.(exp.(t.^2)) acf = StatsBase.autocor(test_data) gives 10-element Array{Float64,1}: 1.0 0.13254954979179642 -0.20302834193214...
This is because your test_data is different: Python: array([ 0.84147098, -0.29102733, 0.96323736, 0.75441021, -0.37291918, 0.85600145, 0.89676529, -0.34006519, -0.75811102, -0.99910501]) Julia: [0.8414709848078965, -0.2910273263243299, 0.963237364649543, 0.7544102058854344, -0.3729191776326039, 0.8560014512776061, 0.9...
20
27
60,368,956
2020-2-24
https://stackoverflow.com/questions/60368956/attributeerrorbytes-object-has-no-attribute-encode
Trying to import a code from python2 to python 3 and this problem happens <ipython-input-53-e9f33b00348a> in aesEncrypt(text, secKey) 43 def aesEncrypt(text, secKey): 44 pad = 16 - len(text) % 16 ---> 45 text = text.encode("utf-8") + (pad * chr(pad)).encode("utf-8") 46 encryptor = AES.new(secKey, 2, '0102030405060708'...
If you don't know if a stringlike object is a Python 2 string (bytes) or Python 3 string (unicode). You could have a generic converter. Python3 shell: >>> def to_bytes(s): ... if type(s) is bytes: ... return s ... elif type(s) is str or (sys.version_info[0] < 3 and type(s) is unicode): ... return codecs.encode(s, 'utf-...
20
8
60,367,476
2020-2-23
https://stackoverflow.com/questions/60367476/context-manager-that-handles-exceptions
I am trying to wrap my head around how to write a context manager that deals with writing some logs while handling any exceptions. The problem I am trying to solve is to make code like this: try: # code that can raise exception here except Exception as e: print('failed', e) print('all good') This is a repeated pattern...
The way the @contextmanager decorator works, you should write yield once within your context manager function, so that the with block will be executed while the yield statement pauses your function's execution. That means if the with block throws an exception, you can catch it by wrapping yield in a try/except block: f...
10
19
60,365,473
2020-2-23
https://stackoverflow.com/questions/60365473/by-how-much-can-i-approx-reduce-disk-volume-by-using-dvc
I want to classify ~1m+ documents and have a Version Control System for in- and Output of the corresponding model. The data changes over time: sample size increases over time new Features might appear anonymization procedure might Change over time So basically "everything" might change: amount of observations, Featu...
Let me try to summarize how does DVC store data and I hope you'll be able to figure our from this how much space will be saved/consumed in your specific scenario. DVC is storing and deduplicating data on the individual file level. So, what does it usually mean from a practical perspective. I will use dvc add as an exam...
9
14
60,352,850
2020-2-22
https://stackoverflow.com/questions/60352850/wave-error-unknown-format-3-arises-when-trying-to-convert-a-wav-file-into-text
I need to record an audio from the microphone and convert it into text. I have tried this conversion process using several audio clips that I downloaded from the web and it works fine. But when I try to convert the audio clip I recorded from the microphone it gives the following error. Traceback (most recent call last)...
You wrote the file in float format: soxi output.wav Input File : 'output.wav' Channels : 2 Sample Rate : 44100 Precision : 25-bit Duration : 00:00:03.00 = 132300 samples = 225 CDDA sectors File Size : 1.06M Bit Rate : 2.82M Sample Encoding: 32-bit Floating Point PCM and wave module can't read it. To store int16 format...
9
9
60,351,135
2020-2-22
https://stackoverflow.com/questions/60351135/hours-and-minutes-as-labels-in-altair-plot-spanning-more-than-one-day
I'm trying to create in Altair a Vega-Lite specification of a plot of a time series whose time range spans a few days. Since in my case, it will be clear which day is which, I want to reduce noise in my axis labels by letting labels be of the form '%H:%M', even if this causes labels to be non-distinct. Here's some exam...
To expand on @fuglede's answer, there are two distinct concepts at play with dates and times in Altair. Time formats let you specify how times are displayed on an axis; they look like this: chart.encode( x=alt.X('time:T', axis=alt.Axis(format='%H:%M')) ) Altair uses format codes from d3-time-format. Time units let you...
8
6
60,351,804
2020-2-22
https://stackoverflow.com/questions/60351804/no-validation-on-field-choices-django-postgres
I created a Student model with field choices. However, when I save it, it doesn't validate whether the choice is in the choices I specified in the model field. Why doesn't it prevent me from saving a new object with a choice I didn't specify in my model? Here is the model: class Student(models.Model): year_in_school =...
You might want to read more about choices here. The relevant part copied below: If choices are given, they’re enforced by model validation Choices are not enforced at the database level. You need to perform model validation (by calling full_clean()) in order to check it. full_clean() will not be called automatically ...
13
13
60,341,728
2020-2-21
https://stackoverflow.com/questions/60341728/is-there-a-way-to-call-azure-devops-via-python-using-requests
So, from what I see from most sources, they say if youre trying to make a python program call azure devops api calls, it uses a python import statement such as : from azure.devops.connection import Connection from msrest.authentication import BasicAuthentication ... Is there any way to use requests or other built in i...
Surely, it is supported to use requests to call Azure DevOps REST API Firstly, you need to create a personal access token (PAT) Then you can use the PAT to create the basic auth header, and make the request: import requests import base64 pat = 'tcd******************************tnq' authorization = str(base64.b64encode(...
7
21
60,333,494
2020-2-21
https://stackoverflow.com/questions/60333494/this-paymentmethod-was-previously-used-without-being-attached-to-a-customer-or-w
Having a weird issue here. Following the docs, I am attaching the PaymentMethod to an existing customer, but it's not working. Roughly, I: create a customer create a payment intent with the customer create a card element with the payment intent customer enters card info confirm payment succeeded and sent intent back t...
It looks like there is an issue with the Stripe documentation. On https://stripe.com/docs/payments/save-after-payment#web-collect-card-details they have: setup_future_usage: 'off_session' But on https://stripe.com/docs/payments/save-and-reuse#web-collect-card-details they are missing this critical line. But in your ...
20
26
60,345,906
2020-2-21
https://stackoverflow.com/questions/60345906/alternative-segmentation-techniques-other-than-watershed-for-soil-particles-in-i
I am searching for an alternative way for segmenting the grains in the following image of soil grains other than watershed segmentation in python as it may mislead the right detection for the grains furthermore , I am working on the edge detection image ( using HED algorithm ) as attached .. I hope to find a better way...
You could try using Connected Components with Stats already implemented as cv2.connectedComponentsWithStats to perform component labeling. Using your binary image as input, here's the false-color image: The centroid of each object can be found in centroid parameter and other information such as area can be found in th...
9
8
60,342,896
2020-2-21
https://stackoverflow.com/questions/60342896/how-to-use-type-hinting-with-dictionaries-and-google-protobuf-enum
I am trying to use protobuf enum as a type for values in a dictionary but it does not work for some reason. My enum definition in proto is: enum Device { UNSPECIFIED = 0; ON = 1; OFF = 2; } After successful compilation and importing, the following code results in error. from devices_pb2 import Device def foo(device: D...
Adding the following solved the problem: from __future__ import annotations For more details, please check here.
11
11
60,330,655
2020-2-21
https://stackoverflow.com/questions/60330655/bizarre-ordering-of-sets-in-python
When I convert a Python 3.8.0 list to a set, the resulting set ordering* is highly structured in a non-trivial way. How is this structure being extracted from the pseudo-random list? As part of an experiment I am running, I am generating a random set. I was surprised to see that plotting the set suddenly showed unexpe...
Basically, this is because of two things: A set in Python is implemented using a hashtable, The hash of an integer is the integer itself. Therefore, the index that an integer appears in the underlying array will be determined by the integer's value, modulo the length of the underlying array. So, integers will tend to...
17
18
60,324,614
2020-2-20
https://stackoverflow.com/questions/60324614/suppress-output-on-library-import-in-python
I have a library that I need to import on my code. However, whenever it is imported it outputs several lines of data to the console. How can I suppress the output? Thanks
import os import sys # silence command-line output temporarily sys.stdout, sys.stderr = os.devnull, os.devnull # import the desired library import library # unsilence command-line output sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__
7
11
60,323,392
2020-2-20
https://stackoverflow.com/questions/60323392/why-1-0-01-99-in-python
I imagine this is a classic floating point precision question, but I am trying to wrap my head around this result, running 1//0.01 in Python 3.7.5 yields 99. I imagine it is an expected result, but is there any way to decide when it is safer to use int(1/f) rather than 1//f ?
If this were division with real numbers, 1//0.01 would be exactly 100. Since they are floating-point approximations, though, 0.01 is slightly larger than 1/100, meaning the quotient is slightly smaller than 100. It's this 99.something value that is then floored to 99.
33
25
60,321,389
2020-2-20
https://stackoverflow.com/questions/60321389/sklearn-importerror-cannot-import-name-plot-roc-curve
I am trying to plot a Receiver Operating Characteristics (ROC) curve with cross validation, following the example provided in sklearn's documentation. However, the following import gives an ImportError, in both python2 and python3. from sklearn.metrics import plot_roc_curve Error: Traceback (most recent call last): Fi...
Plotting API was introduced in the version 0.22. As mentioned here, Scikit-learn 0.20 was the last version to support Python 2.7 and Python 3.4. Scikit-learn now requires Python 3.5 or newer.
12
5
60,319,271
2020-2-20
https://stackoverflow.com/questions/60319271/jupyterlab-how-to-clear-output-of-current-cell-using-a-keyboard-shortcut
This question has been asked and answered for Jupyter Notebooks here. There is one suggestion regarding JupyterLab there as well on how to hide cell output, but not to clear it. This is easy enough using the menu under Edit > Clear Outputs. But how do you do it using a keyboard shortcut? Many other commands under Edit ...
The answer: You'll have to assign a custom shortcut key under Settings > Advanced Settings Editor by inserting the following under User Preferences: {// List of Keyboard Shortcuts "shortcuts": [ { "command": "notebook:clear-cell-output", "keys": [ "F10" ], "selector": ".jp-Notebook.jp-mod-editMode" }, ] } I went for F...
10
12
60,309,604
2020-2-19
https://stackoverflow.com/questions/60309604/aws-cognito-for-django3-drf-authentication
I'm trying to set up an AWS Cognito backend I have a React frontend already working with it, now I need my DRF API to authenticate using the Cognito as backend. I have found a few Python packages for that, none of them seem to be actively maintained django-warrant doesn't work with Django3 and is pretty much dead Djang...
Basically, there are 2 steps to achieve your goal. Get IdToken and AccessToken from Cognito by Boto3 library. Apply the IdToken in this Pattern Authorization Bearer IdToken to call API via curl. Unlike rest_framework_jwt , django_cognito_jwt only deals with JWT token at header. django_cognito_jwt does not cover step ...
7
5
60,306,156
2020-2-19
https://stackoverflow.com/questions/60306156/simplehttpserver-not-found-python3
I'm trying to write a simple server in python. So after watching tutorial, I'm trying to import a few modules. from http.server import HTTPServer from http.server import SimpleHTTPServer As the doc says, it has been moved, that's why i'm doing so. But it gives me this error : from http.server import SimpleHTTPServer I...
The SimpleHTTPServer module was moved to be the module http.server. So the command is: python3 -m http.server Also, the new SimpleHTTPRequestHandler object is BaseHTTPRequestHandler.
16
30
60,303,682
2020-2-19
https://stackoverflow.com/questions/60303682/why-is-pip-installing-an-incompatible-package-version
I am using pip 20.0.2 on Ubuntu, and installing a bunch of requirements from a requirements file. For some reason, pip is deciding to install idna==2.9(link), even though that is not a compatible version with one of my directly listed dependencies. So I used python -m pipdeptree -r within the virtualenv that I'm instal...
Pip does not have a dependency resolver. If you tell it to install package foo without any qualifications, you’re getting the newest version of foo, even if it conflicts with other packages you’ve already installed. Other solutions like poetry exist which do have the logic to keep everything compatible. If you need thi...
12
10
60,299,967
2020-2-19
https://stackoverflow.com/questions/60299967/how-to-get-allocated-gpu-spec-in-google-colab
I'm using Google Colab for deep learning and I'm aware that they randomly allocate GPU's to users. I'd like to be able to see which GPU I've been allocated in any given session. Is there a way to do this in Google Colab notebooks? Note that I am using Tensorflow if that helps.
Since you can run bash command in colab, just run !nvidia-smi:
51
62
60,294,634
2020-2-19
https://stackoverflow.com/questions/60294634/select-first-row-when-there-are-multiple-rows-with-repeated-values-in-a-column
I want to select the first row when there are multiple rows with repeated values in a column. For example: import pandas as pd df = pd.DataFrame({'col1':['one', 'one', 'one', 'one', 'one', 'one', 'one', 'one'], 'col2':['ID=ABCD1234', 'ID=ABCD1234', 'ID=ABCD1234', 'ID=ABCD5678', 'ID=ABCD5678', 'ID=ABCD5678', 'ID=ABCD910...
You can use: df.drop_duplicates(subset = ['col2'], keep = 'first', inplace = True)
8
13
60,254,571
2020-2-17
https://stackoverflow.com/questions/60254571/no-module-named-socks
import requests, socket, socks ModuleNotFoundError: No module named 'socks' I have tried pip install socks, and followed instructions of other stackoverflow posts but none of them worked. I'm working on pycharm right now and I have also installed socks and socket on there, in fact, it does show I have installed it. A...
I think you mean to install PySocks, so do pip install PySocks. pypi docs for PySocks pip install socks installs something different. pypi docs for socks
14
31
60,193,899
2020-2-12
https://stackoverflow.com/questions/60193899/venv-not-respecting-copies-argument
I am ssh’d into a development environment (vagrant Ubuntu box) and my project directory is mapped to another filesystem (via vbox) so symlinks are not supported. I am attempting to create a new venv, but the --copies flag isn’t being respected. $sudo python -m venv --copies venv Error: [Errno 71] Protocol error: 'lib' ...
Per @chepner's comment above, it looks like the --copies argument is ignored on non-Windows systems (no mention of this in the documentation). I was able to workaround the issue by creating the venv in a local directory, manually copying the symlinked lib64 to a real directory, moving the venv to my project folder and ...
7
5
60,224,850
2020-2-14
https://stackoverflow.com/questions/60224850/send-mail-python-asyncio
I'm trying to learn asyncio. If I run this program normally without the asyncio library than it takes less time while it takes more time in this way so is this the right way to send mail using asyncio or there is any other way? import smtplib import ssl import time import asyncio async def send_mail(receiver_email): tr...
You are not really doing sending your emails correctly using asyncio. You should be using the aiosmtplib for making asynchronous SMTP calls such as connect, starttls, login, etc. See the following example, which I have stripped down from a more complicated program that handled attachments. This code sends two emails as...
7
18
60,247,157
2020-2-16
https://stackoverflow.com/questions/60247157/how-can-i-get-stub-files-for-matplotlib-numpy-scipy-pandas-etc
I know that the stub files for built-in Python library for type checking and static analysis come with mypy or PyCharm installation. How can I get stub files for matplotlib, numpy, scipy, pandas, etc.?
Type stubs are sometimes packaged directly with the library. Otherwise there can be some external libraries to provide them. Numpy Starting with numpy 1.20 type stubs will be included in numpy. See this changelog and this PR adding them Before that they could added with the library https://github.com/numpy/numpy-stubs ...
58
24
60,229,375
2020-2-14
https://stackoverflow.com/questions/60229375/solution-for-specificationerror-nested-renamer-is-not-supported-while-agg-alo
def stack_plot(data, xtick, col2='project_is_approved', col3='total'): ind = np.arange(data.shape[0]) plt.figure(figsize=(20,5)) p1 = plt.bar(ind, data[col3].values) p2 = plt.bar(ind, data[col2].values) plt.ylabel('Projects') plt.title('Number of projects aproved vs rejected') plt.xticks(ind, list(data[xtick].values)) ...
In this specific case you can change temp['total'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'total':'count'})).reset_index()['total'] temp['Avg'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'Avg':'mean'})).reset_index()['Avg'] to the new syntax temp['total'] = pd.DataFrame(project_data.groupby(col...
61
78
60,251,799
2020-2-16
https://stackoverflow.com/questions/60251799/how-to-start-a-new-django-project-using-poetry
How to start a new Django project using poetry? With virtualenv it is simple: virtualenv -p python3 env_name --no-site-packages source env_name/bin/activate pip install django django-admin.py startproject demo pip freeze > requirements.txt What will be equivalent to this using Poetry?
Create a new project folder and step in: $ mkdir djangodemo $ cd djangodemo Create a basic pyproject.toml with django as dependency: $ poetry init --no-interaction --dependency django Create venv with all dependencies needed: $ poetry install Init your demo-project: For Django versions after 4: $ poetry run django-a...
15
30
60,212,658
2020-2-13
https://stackoverflow.com/questions/60212658/issues-with-pyenv-virtualenv-python-and-pip-not-changed-when-activating-deact
I installed pyenv-virtualenv using Linuxbrew (Homebrew 2.2.5) on my Ubuntu 16.04 VPS. The pyenv version is: 1.2.16. Now when I do a test like this: pyenv install 3.8.1 pyenv virtualenv 3.8.1 test cd /.pyenv/versions/3.8.1/envs/test pyenv local 3.8.1 Then entering / leaving the /.pyenv/versions/3.8.1/envs/test doesn't ...
It turns out that in order to automatically activate / deactivate a venv when entering / leaving a directory the .python-version file in there must contain the venv name and not the Python version associated with that venv So executing: pyenv local 3.8.1 creates a .python-version file which only includes the Python ver...
11
13
60,199,316
2020-2-13
https://stackoverflow.com/questions/60199316/how-to-save-a-list-of-numpy-arrays-into-a-single-file-and-load-file-back-to-orig
I am currently trying to save a list of numpy arrays into a single file, an example of such a list can be of the form below import numpy as np np_list = [] for i in range(10): if i % 2 == 0: np_list.append(np.random.randn(64)) else: np_list.append(np.random.randn(32, 64)) I can combine all of them using into a single ...
I would go with np.save and np.load because it's platform-independent, faster than savetxt and works with lists of arrays, for example: import numpy as np a = [ np.arange(100), np.arange(200) ] np.save('a.npy', np.array(a, dtype=object), allow_pickle=True) b = np.load('a.npy', allow_pickle=True) This is the documentat...
12
20
60,285,826
2020-2-18
https://stackoverflow.com/questions/60285826/transaction-atomic-needed-for-bulk-create
I'm using the bulk_create method from Django to create many entries at once. To ensure that the changes are only committed if there is no exception I'm thinking about adding transaction.atomic() to the code blocks but I'm not sure if I need to add it. From my understanding I only need to add it in Scenario 2 because in...
No, you don't have to for either scenario. According to the Django source code, using transaction atomic would be redundant for bulk_create as that method already uses atomic transactions.
11
17
60,247,155
2020-2-16
https://stackoverflow.com/questions/60247155/how-to-bypass-the-message-your-connection-is-not-private-on-non-secure-page-us
I'm trying to interact with the page "Your connection is not private". The solution of using options.add_argument('--ignore-certificate-errors') is not helpful for two reasons: I'm using an already open window. Even if I was using a "selenium opened window" the script runs non stop, and the issue I'm trying to solve i...
For chrome: from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument('--ignore-ssl-errors=yes') options.add_argument('--ignore-certificate-errors') driver = webdriver.Chrome(options=options) If not work then this: from selenium import webdriver from selenium.webdriver import DesiredCapab...
21
50
60,219,622
2020-2-14
https://stackoverflow.com/questions/60219622/python-convert-dcm-to-png-images-are-too-bright
I have to convert some files which come by default as .dcm to .png, I've found some code samples to achieve that around here but the end results are too bright. Could anybody have a look at this, please? def convert_to_png(file): ds = pydicom.dcmread(file) shape = ds.pixel_array.shape # Convert to float to avoid overf...
Some DICOM datasets require window center/width rescaling of the original pixel intensities (via the (0028,1050) Window Center and (0028,1051) Window Width elements in the VOI LUT Module) in order to reproduce the way they were "viewed". pydicom has a function apply_voi_lut() for applying this windowing: from pydicom i...
10
17
60,240,747
2020-2-15
https://stackoverflow.com/questions/60240747/multivariate-multiple-regression-using-python-libraries
Is there any library to perform a Multivariate Multiple Regression (a Multiple Regression with multiple dependent variables) in Python? Greetings and thanks in advance
You can try the modules in sklearn, the response variable can be 2 or more dimensional, and i think it works for OLS (linear regression), lasso, ridge.. The models in statsmodels can only do 1 response (just checked). Example dataset: import pandas as pd from sklearn.datasets import load_iris iris = load_iris() df = pd...
7
5
60,279,160
2020-2-18
https://stackoverflow.com/questions/60279160/compare-two-dataframes-pyspark
I'm trying to compare two data frames with have same number of columns i.e. 4 columns with id as key column in both data frames df1 = spark.read.csv("/path/to/data1.csv") df2 = spark.read.csv("/path/to/data2.csv") Now I want to append new column to DF2 i.e. column_names which is the list of the columns with different ...
Assuming that we can use id to join these two datasets I don't think that there is a need for UDF. This could be solved just by using inner join, array and array_remove functions among others. First let's create the two datasets: df1 = spark.createDataFrame([ [1, "ABC", 5000, "US"], [2, "DEF", 4000, "UK"], [3, "GHI", 3...
11
20
60,286,623
2020-2-18
https://stackoverflow.com/questions/60286623/python-loses-connection-to-mysql-database-after-about-a-day
I am developing a web-based application using Python, Flask, MySQL, and uWSGI. However, I am not using SQL Alchemy or any other ORM. I am working with a preexisting database from an old PHP application that wouldn't play well with an ORM anyway, so I'm just using mysql-connector and writing queries by hand. The applica...
I have it working now. Using pooled connections seemed to fix the issue for me. mysql.connector.connect( host='10.0.0.25', user='xxxxxxx', passwd='xxxxxxx', database='xxxxxxx', pool_name='batman', pool_size = 3 ) def connection(): """Get a connection and a cursor from the pool""" db = mysql.connector.connect(pool_name ...
10
6
60,236,745
2020-2-15
https://stackoverflow.com/questions/60236745/is-it-true-that-in-multiprocessing-each-process-gets-its-own-gil-in-cpython-h
Are there any caveats to it? I have a few questions related to it. How costly is it to create more GILs? Is it any different from creating a separate python runtime? Once a new GIL is created, will it create everything (objects, variables, stack, heap) from scratch as required in that process or a copy of everything in...
Looking back at this question after 6 months, I feel I can clarify the doubts of my younger self. I hope this would be helpful to people who stumble upon it. Yes, It is true that in multiprocessing module, each process has a separate GIL and there are no caveats to it. But the understanding of the runtime and GIL is fl...
10
12
60,257,377
2020-2-17
https://stackoverflow.com/questions/60257377/encountering-warn-procfsmetricsgetter-exception-when-trying-to-compute-pagesi
I installed Spark and when trying to run it, I am getting the error: WARN ProcfsMetricsGetter: Exception when trying to compute pagesize, as a result reporting of ProcessTree metrics is stopped Can someone help me with that?
The same problem occured with me because python path was not added to system environment. I added this in environment and now it works perfectly. Adding PYTHONPATH environment variable with value as: %SPARK_HOME%\python;%SPARK_HOME%\python\lib\py4j-<version>-src.zip;%PYTHONPATH% helped resolve this issue. Just check w...
25
11
60,197,392
2020-2-12
https://stackoverflow.com/questions/60197392/high-performance-replacement-for-multiprocessing-queue
My distributed application consists of many producers that push tasks into several FIFO queues, and multiple consumers for every one of these queues. All these components live on a single node, so no networking involved. This pattern is perfectly supported by Python's built-in multiprocessing.Queue, however when I am s...
After trying a few available implementations and frameworks, I still could not find anything that would be suitable for my task. Either too slow or too heavy. To solve the issue my colleagues and I developed this: https://github.com/alex-petrenko/faster-fifo faster-fifo is a drop-in replacement for Python's multiproces...
8
10
60,239,051
2020-2-15
https://stackoverflow.com/questions/60239051/pytorch-runtimeerror-expected-object-of-scalar-type-double-but-got-scalar-type
I am trying to implement a custom dataset for my neural network. But got this error when running the forward function. The code is as follows. import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader import numpy as np class ParamData(Dataset): def __init__(sel...
Now that I have more experience with pytorch, I think I can explain the error message. It seems that the line RuntimeError: Expected object of scalar type Double but got scalar type Float for argument #2 'mat2' in call to _th_mm is actually refering to the weights of the linear layer when the matrix multiplication is ...
21
10
60,186,698
2020-2-12
https://stackoverflow.com/questions/60186698/create-a-numba-typed-list-without-looping-over-a-python-list
I want to use a numba.typed.List (going to call it List) to pass into my function which is wrapped in njit. However this List should be created from an existing python list. When I look at the documentation it seems the way you create a List is to initialize it and then append elements to it. However this requires you ...
I am working on numba 0.49.1 where you can pass the list by the construction. py_list = [2,3,5] number_list = numba.typed.List(py_list)
10
13
60,239,099
2020-2-15
https://stackoverflow.com/questions/60239099/csv-file-with-arabic-characters-is-displayed-as-symbols-in-excel
I am using python to extract Arabic tweets from twitter and save it as a CSV file, but when I open the saved file in excel the Arabic language displays as symbols. However, inside python, notepad, or word, it looks good. May I know where is the problem?
This is a problem I face frequently with Microsoft Excel when opening CSV files that contain Arabic characters. Try the following workaround that I tested on latest versions of Microsoft Excel on both Windows and MacOS: Open Excel on a blank workbook Within the Data tab, click on From Text button (if not activated, ma...
24
54
60,244,570
2020-2-16
https://stackoverflow.com/questions/60244570/how-to-bypass-python-function-definition-with-decorator
I would like to know if its possible to control Python function definition based on global settings (e.g. OS). Example: @linux def my_callback(*args, **kwargs): print("Doing something @ Linux") return @windows def my_callback(*args, **kwargs): print("Doing something @ Windows") return Then, if someone is using Linux, ...
If the goal is to have the same sort of effect in your code that #ifdef WINDOWS / #endif has.. here's a way to do it (I'm on a mac btw). Simple Case, No Chaining >>> def _ifdef_decorator_impl(plat, func, frame): ... if platform.system() == plat: ... return func ... elif func.__name__ in frame.f_locals: ... return fram...
70
61
60,240,694
2020-2-15
https://stackoverflow.com/questions/60240694/suppress-scientific-notation-in-sklearn-metrics-plot-confusion-matrix
I was trying to plot a confusion matrix nicely, so I followed scikit-learn's newer version 0.22's in built plot confusion matrix function. However, one value of my confusion matrix value is 153, but it appears as 1.5e+02 in the confusion matrix plot: Following the scikit-learn's documentation, I spotted this parameter...
Just remove ".format" and the {} brackets from your call parameter declaration: disp = plot_confusion_matrix(logreg, X_test, y_test, display_labels=class_names, cmap=plt.cm.Greens, normalize=normalize, values_format = '.5f') In addition, you can use '.5g' to avoid decimal 0's Taken from source
15
15
60,199,213
2020-2-13
https://stackoverflow.com/questions/60199213/pandas-read-csv-error-due-to-pandas-io-common-not-importing-is-url-in-1-0-x
I'm trying to read in a regular csv file into pandas through pd.read_csv(). I have done this on my local desktop many times before but I am using a virtual machine now and am getting this error : ImportError: cannot import name 'is_url' from 'pandas.io.common' (/opt/conda/lib/python3.7/site-packages/pandas/io/common.py...
conda update --force-reinstall pandas this worked for me.
10
7
60,288,953
2020-2-18
https://stackoverflow.com/questions/60288953/how-to-change-the-crs-of-a-raster-with-rasterio
I am trying to change the CRS of a raster tif file. When I assign new CRS using the following code: with rio.open(solar_path, mode='r+') as raster: raster.crs = rio.crs.CRS({'init': 'epsg:27700'}) show((raster, 1)) print(raster.crs) The print function returns 'EPSG:27700', however after plotting the image the CRS clea...
Unlike Geopandas, rasterio requires manual re-projection when changing the crs. def reproject_raster(in_path, out_path): """ """ # reproject raster to project crs with rio.open(in_path) as src: src_crs = src.crs transform, width, height = calculate_default_transform(src_crs, crs, src.width, src.height, *src.bounds) kwa...
9
10
60,212,552
2020-2-13
https://stackoverflow.com/questions/60212552/pytest-deprecation-junit-family-default-value-will-change-to-xunit2
I'm getting deprecation warning from my pipelines at circleci. Message. /home/circleci/evobench/env/lib/python3.7/site-packages/_pytest/junitxml.py:436: PytestDeprecationWarning: The 'junit_family' default value will change to 'xunit2' in pytest 6.0. Command - run: name: Tests command: | . env/bin/activate mkdir test-...
Run your command in this ways. with xunit2 python -m pytest -o junit_family=xunit2 --junitxml=test-reports/junit.xml with xunit1 python -m pytest -o junit_family=xunit1 --junitxml=test-reports/junit.xml or python -m pytest -o junit_family=legacy --junitxml=test-reports/junit.xml This here describes the change in detai...
13
14
60,289,405
2020-2-18
https://stackoverflow.com/questions/60289405/a-good-way-to-make-classes-for-more-complex-playing-card-types-than-those-found
I am extremely new to object-oriented programming, and am trying to begin learning in python by making a simple card game (as seems to be traditional!). I have done the following example which works fine, and teaches me about making multiple instances of the PlayingCard() class to create an instance of the Deck() class...
When you are approaching a problem with OOP, you usually want to model behavior and properties in a reusable way, i.e., you should think of abstractions and organize your class hierarchy based on that. I would write something like the following: class Card: def __init__(self, money_value=0): self.money_value = money_va...
9
3
60,226,033
2020-2-14
https://stackoverflow.com/questions/60226033/no-module-named-cython-with-pip-installation-of-tar-gz
I use Poetry to build tar.gz and whl files for my example package (https://github.com/iamishalkin/cyrtd) and then try to install package inside pipenv environment. tar.gz installation fails and this is a piece of logs: $ poetry build ... $ pip install dist/cyrtd-0.1.0.tar.gz Processing c:\work2\cyrtd\dist\cyrtd-0.1.0.t...
Adding cython in build-system section in pyproject.toml helped me pyproject.toml: ... [build-system] requires = ["poetry>=0.12", "cython"] ...
14
2
60,238,873
2020-2-15
https://stackoverflow.com/questions/60238873/python-jupyter-notebook-shap-force-plot-how-to-change-the-background-color-or-t
Is there any way that I can change the shap plot background color or text color in the dark theme? I need either the white background or white text. The plot is an object of IPython.core.display.HTML. It is generated by shap.force_plot(explainer.expected_value[1], shap_values[1][0,:], X_test.iloc[0,:],link="logit") T...
After adding the argument of matplotlib=True, the problem is solved. shap.force_plot(explainer.expected_value[1], shap_values[1][0,:], X_test.iloc[0,:],link="logit", matplotlib=True) It seems the plot is created with matplotlib on a html file. To plot properly, firstly I used style.use('seaborn-dark') in the dark mode...
7
7
60,267,911
2020-2-17
https://stackoverflow.com/questions/60267911/keras-inconsistent-prediction-time
I tried to get an estimate of the prediction time of my keras model and realised something strange. Apart from being fairly fast normally, every once in a while the model needs quite long to come up with a prediction. And not only that, those times also increase the longer the model runs. I added a minimal working exam...
TF2 generally exhibits poor and bug-like memory management in several instances I've encountered - brief description here and here. With prediction in particular, the most performant feeding method is via model(x) directly - see here, and its linked discussions. In a nutshell: model(x) acts via its its __call__ method ...
19
10
60,275,455
2020-2-18
https://stackoverflow.com/questions/60275455/using-yolo-or-other-image-recognition-techniques-to-identify-all-alphanumeric-te
I have multiple images diagram, all of which contains labels as alphanumeric characters instead of just the text label itself. I want my YOLO model to identify all the numbers & alphanumeric characters present in it. How can I train my YOLO model to do the same. The dataset can be found here. https://drive.google.com/o...
A possible approach is to use the EAST (Efficient and Accurate Scene Text) deep learning text detector based on Zhou et al.’s 2017 paper, EAST: An Efficient and Accurate Scene Text Detector. The model was originally trained for detecting text in natural scene images but it may be possible to apply it on diagram images....
13
8
60,270,233
2020-2-17
https://stackoverflow.com/questions/60270233/trying-to-create-dynamic-subdags-from-parent-dag-based-on-array-of-filenames
I am trying to move s3 files from a "non-deleting" bucket (meaning I can't delete the files) to GCS using airflow. I cannot be guaranteed that new files will be there everyday, but I must check for new files everyday. my problem is the dynamic creation of subdags. If there ARE files, I need subdags. If there are NOT fi...
Below is the recommended way to create a dynamic DAG or sub-DAG in airflow, though there are other ways also, but I guess this would be largely applicable to your problem. First, create a file (yaml/csv) which includes the list of all s3 files and locations, in your case you have written a function to store them in lis...
12
4
60,229,970
2020-2-14
https://stackoverflow.com/questions/60229970/aws-cli-errorrootcode-for-hash-md5-was-not-found
When trying to run the AWS CLI, I am getting this error: aws ERROR:root:code for hash md5 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name)...
Ran into a similar issue with brew install python2 error when trying to use pip. It's probably because python@2 was deleted from homebrew/core in commit 028f11f9e: python@2: delete (https://github.com/Homebrew/homebrew-core/issues/49796) EOL 1 January 2020. See this post here https://github.com/Homebrew/homebrew-co...
23
56
60,225,185
2020-2-14
https://stackoverflow.com/questions/60225185/how-to-throw-http-error-code-with-aws-lambda-using-lambda-proxy
I created an AWS Lambda function using Python 3.8 with a Lambda Proxy API Gateway trigger: It is indeed possible to return custom HTTP error codes: def lambda_handler(event, context): return { 'statusCode': 400, 'body': json.dumps('This is a bad request!') } However, some online examples (e.g. 1, 2) simply raise an E...
DurandA - I believe you are absolutely correct: the simplified Lambda Proxy Integration approach relies on you catching your exceptions and returning the standardized format: def lambda_handler(event, context): return { 'statusCode': 400, 'body': json.dumps('This is a bad request!') } The simplified Lambda Proxy Integ...
18
34
60,278,766
2020-2-18
https://stackoverflow.com/questions/60278766/best-way-to-insert-python-numpy-array-into-postgresql-database
Our team uses software that is heavily reliant on dumping NumPy data into files, which slows our code quite a lot. If we could store our NumPy arrays directly in PostgreSQL we would get a major performance boost. Other performant methods of storing NumPy arrays in any database or searchable database-like structure are ...
Not sure if this is what you are after, but assuming you have read/write access to an existing postgres DB: import numpy as np import psycopg2 as psy import pickle db_connect_kwargs = { 'dbname': '<YOUR_DBNAME>', 'user': '<YOUR_USRNAME>', 'password': '<YOUR_PWD>', 'host': '<HOST>', 'port': '<PORT>' } connection = psy.c...
13
14
60,215,436
2020-2-13
https://stackoverflow.com/questions/60215436/how-to-correctly-set-specific-module-to-debug-in-vs-code
I was following the instruction by VS code's website but it seemed that nothing that I tried worked. I created a new configuration as required but whenever I put the path it refuses to work in VS code although the path VS code complains about in the integrated terminal window works fine when I call it manually. The err...
You are using module instead of program in launch.json. When using module you must pass only the module\sub-module name, not the entire path. Visual Studio will then load the specified module and execute it's __main__.py file. This would be the correct input, assuming automl is a module and experiments is a submodule: ...
13
6
60,279,762
2020-2-18
https://stackoverflow.com/questions/60279762/migrating-flask-web-application-currently-using-uwsgi-web-server-to-asgi-web-ser
I currently have a flask web application using uWSGI web server that implements the WSGI standard and need to migrate this app to uvicorn web server that implements the ASGI standard. If I choose to use uvicorn web server from the many available options say, Hypercorn, Daphne, then which web microframework(instead of f...
So here I would like to add something that I have concluded so far, FastAPI learned from Flask (and several of its plug-ins) several things, including its simplicity. For example, the way you declare routes is very similar. That makes it easy to migrate from Flask to FastAPI (which I see a lot of people doing). Flask...
10
12