qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
58,475,837
I am trying to learn the functional programming way of doing things in python. I am trying to serialize a list of strings in python using the following code ``` S = ["geeks", "are", "awesome"] reduce(lambda x, y: (str(len(x)) + '~' + x) + (str(len(y)) + '~' + y), S) ``` I am expecting: ``` 5~geeks3~are7~awesome `...
2019/10/20
[ "https://Stackoverflow.com/questions/58475837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6101835/" ]
You need to add the `initializer` parameter - an empty string to the `reduce()` function. It will be the first argument passed to the `lambda` function before the values from the list. ``` from functools import reduce S = ["geeks", "are", "awesome"] reduce(lambda x, y: x + f'{len(y)}~{y}', S, '') # 5~geeks3~are7~awe...
* here is the solution for `pyton3.7+` using `fstring`. ```py >>> S = ["geeks", "are", "awesome"] >>> ''.join(f'{len(s)}~{s}' for s in S) '5~geeks3~are7~awesome' ```
70,765,867
I have been trying to use github actions to deploy a docker image to AWS ECR, but there is a step that is consistently failing. Here is the portion that is failing: ``` - name: Pulling ECR for updates and instantiating new updated containers. uses: appleboy/ssh-action@master with: host: ${{s...
2022/01/19
[ "https://Stackoverflow.com/questions/70765867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17970861/" ]
Welcome to StackOverflow and the joys of programming and the cloud! It seems that the AWS CLI is failing to configure the access key id and secret on the pipeline. In order to solve this and make it easier to manage in the long run, I would recommend using the pre-built actions from AWS to ease your pipeline's setup p...
Actually, I just had to install AWS CLI on my EC2 instance, but thank you so much for the help!
55,966,757
When (and why) was the Python `__new__()` function introduced? There are three steps in creating an instance of a class, e.g. `MyClass()`: * `MyClass.__call__()` is called. This method must be defined in the metaclass of `MyClass`. * `MyClass.__new__()` is called (by `__call__`). Defined on `MyClass` itself. This cre...
2019/05/03
[ "https://Stackoverflow.com/questions/55966757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2097/" ]
The blog post [**`The Inside Story on New-Style Classes`**](http://python-history.blogspot.com/2010/06/inside-story-on-new-style-classes.html) (from the aptly named **`http://python-history.blogspot.com`**) written by [**`Guido van Rossum`**](https://en.wikipedia.org/wiki/Guido_van_Rossum) (Python's BDFL) provides som...
I will not explain the history of `__new__` here because I have only used Python since 2005, so after it was introduced into the language. But here is the rationale behind it. The *normal* configuration method for a new object is the `__init__` method of its class. The object has already been created (usually via an i...
40,007,305
I am using kivy to create a small Gui for my python program. This Gui is not always visible. So I start it with these settings: ``` Config.set('graphics', 'borderless', True) Config.set('graphics', 'resizable', False) Config.set('graphics', 'window_state', 'hidden') ``` However: Somewhere in my program I want to mak...
2016/10/12
[ "https://Stackoverflow.com/questions/40007305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2129897/" ]
It seems that if you are using the SDL provider you have a **hide & show** functions on the Window object from the kivy.core.window docs: ``` hide() Added in 1.9.0 Hides the window. This method should be used on desktop platforms only. Note This feature requires the SDL2 window provider and is currently only support...
I'm not familiar with Kivy, but it looks like you just need to set it to visible. `window_state`: string , one of 'visible', 'hidden', 'maximized' \ or 'minimized' from: <https://kivy.org/docs/_modules/kivy/config.html> Looking at this github post: <https://github.com/kivy/kivy/issues/3637> The method they're usin...
9,724,872
I have a python (django) web application. It uses an external web service (Facebook Graph). All the code for making external (http) calls is wrapped in one extra function (called `facebook_api`), which takes some arguments and returns a parsed dict (it does some logging, checks for errors etc.) Around this function, I ...
2012/03/15
[ "https://Stackoverflow.com/questions/9724872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161922/" ]
I think you are looking for [Mock's side\_effect](http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.side_effect) . For example ``` def my_facebook_api(input): if input=='A': return 'X' elif input=='B': return 'D' facebook_api = Mock(side_effect=my_facebook_api) ```
I have been using mockito-python (<http://code.google.com/p/mockito-python/>) with a good success. It allows you to specify behaviour of mocks with simple syntax (straight from their documentation): ``` >>> dummy = mock() >>> when(dummy).reply("hi").thenReturn("hello") >>> when(dummy).reply("bye").thenReturn("good-bye...
9,724,872
I have a python (django) web application. It uses an external web service (Facebook Graph). All the code for making external (http) calls is wrapped in one extra function (called `facebook_api`), which takes some arguments and returns a parsed dict (it does some logging, checks for errors etc.) Around this function, I ...
2012/03/15
[ "https://Stackoverflow.com/questions/9724872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161922/" ]
I think you are looking for [Mock's side\_effect](http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.side_effect) . For example ``` def my_facebook_api(input): if input=='A': return 'X' elif input=='B': return 'D' facebook_api = Mock(side_effect=my_facebook_api) ```
This is an example with [mock](http://www.voidspace.org.uk/python/mock/): ``` >>> import mock >>> patcher = mock.patch('django.core.urlresolvers.reverse') >>> reverse_mock = patcher.start() >>> reverse_mock.return_value = "/foo/" >>> from django.core.urlresolvers import reverse >>> reverse('someview') '/foo/' >>> patc...
11,021,853
The IPython documentation pages suggest that opening several different sessions of IPython notebook is the only way to interact with saved notebooks in different directories or subdirectories, but this is not explicitly confirmed anywhere. I am facing a situation where I might need to interact with hundreds of differe...
2012/06/13
[ "https://Stackoverflow.com/questions/11021853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567620/" ]
> > The IPython documentation pages suggest that opening several different sessions of IPython notebook is the only way to interact with saved notebooks in different directories or subdirectories, but this is not explicitly confirmed anywhere. > > > Yes, this is a current (*temporary*) limitation of the Notebook s...
The interface and architecture design issues for multiple directory support (and more generally for "project" support) for iPython notebook are important to get right. A design is described in [IPEP 16: Notebook multi directory dashboard and URL mapping](https://github.com/ipython/ipython/wiki/IPEP-16%3A-Notebook-mult...
13,586,153
**Objectives:** Implement a program (java or python) to retrieve data from videos that I published on my Youtube channel. This program will be launched daily (1:00 AM). **Solutions:** To retrieve data Youtube, including the number of views per day, YouTube Analytics API is in my opinion the best solution. I use the ...
2012/11/27
[ "https://Stackoverflow.com/questions/13586153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1856335/" ]
You can't use a service account when making a YouTube Analytics API request. You need to use an account that is either the owner of the YouTube channel or a content owner associated with the channel, and I don't believe a service account can be either of those things. Please go through the OAuth 2 flow once while signe...
Yes you can authenticate for any of Youtubes APIs using a Service Account. The service account and the account you want to work with, have to be in the same CMS. (note for Youtube-Partner-Channels you will also need to set their content-owner-ID, when calling the API). How it works for me: I generate an access\_token...
53,259,674
it 's possible to put a variable into the path in python/linux for example : ``` >>>counter = 0; >>>image = ClImage(file_obj=open('/home/user/image'counter'.jpeg', 'rb')) ``` I have syntax error when i do that.
2018/11/12
[ "https://Stackoverflow.com/questions/53259674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9100401/" ]
You could use an [f-string](https://www.python.org/dev/peps/pep-0498/) if you’re working in python 3.6+ This is the most efficient method. ``` counter = 0 filepath = f"/home/user/image{counter}.jpeg" image = ClImage(file_obj=open(filepath, 'rb')) ``` Otherwise the second best would be using the [.format()](https://...
You can use Python's [.format()](https://realpython.com/python-string-formatting/) method: ``` counter = 0 filepath = '/home/user/image{0}.jpeg'.format(counter) image = ClImage(file_obj=open(filepath, 'rb')) ```
53,259,674
it 's possible to put a variable into the path in python/linux for example : ``` >>>counter = 0; >>>image = ClImage(file_obj=open('/home/user/image'counter'.jpeg', 'rb')) ``` I have syntax error when i do that.
2018/11/12
[ "https://Stackoverflow.com/questions/53259674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9100401/" ]
You could use an [f-string](https://www.python.org/dev/peps/pep-0498/) if you’re working in python 3.6+ This is the most efficient method. ``` counter = 0 filepath = f"/home/user/image{counter}.jpeg" image = ClImage(file_obj=open(filepath, 'rb')) ``` Otherwise the second best would be using the [.format()](https://...
You need [string concatenation](https://www.pythonforbeginners.com/concatenation/string-concatenation-and-formatting-in-python). ``` >>>counter = 0; >>>image = ClImage(file_obj=open('/home/user/image' + str(counter) + '.jpeg', 'rb')) ```
36,551,531
**My Flume configuration** ``` source_agent.sources = tail source_agent.sources.tail.type = exec source_agent.sources.tail.command = python loggen.py source_agent.sources.tail.batchSize = 1 source_agent.sources.tail.channels = memoryChannel #memory-channel source_agent.channels = memoryChannel source_agent.channels...
2016/04/11
[ "https://Stackoverflow.com/questions/36551531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3536400/" ]
You can use --jars option if you are running the job using spark-submit For Ex: ``` spark-submit --jars ....../lib/spark-streaming_2.10-1.2.1‌​.2.2.6.0-2800.jar ``` or add this to your SBT configuration ``` libraryDependencies += "org.apache.spark" %% "spark-streaming-flume" % "2.1.0" ``` <https://spark.apache.o...
Add this to your build to get rid of this error: ``` <!-- https://mvnrepository.com/artifact/org.apache.spark/spark-streaming-flume_2.10 --> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-streaming-flume_2.10</artifactId> <version>2.0.0</version> ...
27,218,638
I need to replace `\` into `\\` with python from pattern matching. For example, `$$\a\b\c$$` should be matched replaced with `$$\\a\\b\\c$$`. I couldn't use the regular expression to find a match. ``` >>> import re >>> p = re.compile("\$\$([^$]+)\$\$") >>> a = "$$\a\b\c$$" >>> m = p.search(a) >>> m.group(1) '\x07\x...
2014/11/30
[ "https://Stackoverflow.com/questions/27218638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
The reason you're having trouble is because the string you're inputting is `$$\a\b\c$$`, which python translates to `'$$\x07\x08\\c$$'`, and the only back slash in the string is actually in the segment '\c' the best way to deal with this would be to input a as such ``` a=r'$$\a\b\c$$' ``` This will tell python to co...
Split the string with single backslashes, then join the resulting list with double backslashes. ``` s = r'$$\a\b\c$$' t = r'\\'.join(s.split('\\')) print('%s -> %s' % (s, t)) ```
67,687,962
I am trying to build a Word2vec model but when I try to reshape the vector for tokens, I am getting this error. Any idea ? ``` wordvec_arrays = np.zeros((len(tokenized_tweet), 100)) for i in range(len(tokenized_tweet)): wordvec_arrays[i,:] = word_vector(tokenized_tweet[i], 100) wordvec_df = pd.DataFrame(wordvec_a...
2021/05/25
[ "https://Stackoverflow.com/questions/67687962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8020986/" ]
As of Gensim 4.0 & higher, the `Word2Vec` model doesn't support subscripted-indexed access (the `['...']') to individual words. (Previous versions would display a deprecation warning,` Method will be removed in 4.0.0, use self.wv.**getitem**() instead`, for such uses.) So, when you want to access a specific word, do i...
use the following method: ``` model.wv.get_item() ```
67,687,962
I am trying to build a Word2vec model but when I try to reshape the vector for tokens, I am getting this error. Any idea ? ``` wordvec_arrays = np.zeros((len(tokenized_tweet), 100)) for i in range(len(tokenized_tweet)): wordvec_arrays[i,:] = word_vector(tokenized_tweet[i], 100) wordvec_df = pd.DataFrame(wordvec_a...
2021/05/25
[ "https://Stackoverflow.com/questions/67687962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8020986/" ]
As of Gensim 4.0 & higher, the `Word2Vec` model doesn't support subscripted-indexed access (the `['...']') to individual words. (Previous versions would display a deprecation warning,` Method will be removed in 4.0.0, use self.wv.**getitem**() instead`, for such uses.) So, when you want to access a specific word, do i...
**Since Gensim > 4.0** I tried to store words with: ``` vocab = w2v_model.wv.key_to_index.keys() ``` and then iterate, but the method has been changed: ``` for word in vocab: w2v_model.wv.get_index(word) ... ``` And finally I created the words vectors matrix without issues..
67,687,962
I am trying to build a Word2vec model but when I try to reshape the vector for tokens, I am getting this error. Any idea ? ``` wordvec_arrays = np.zeros((len(tokenized_tweet), 100)) for i in range(len(tokenized_tweet)): wordvec_arrays[i,:] = word_vector(tokenized_tweet[i], 100) wordvec_df = pd.DataFrame(wordvec_a...
2021/05/25
[ "https://Stackoverflow.com/questions/67687962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8020986/" ]
**Since Gensim > 4.0** I tried to store words with: ``` vocab = w2v_model.wv.key_to_index.keys() ``` and then iterate, but the method has been changed: ``` for word in vocab: w2v_model.wv.get_index(word) ... ``` And finally I created the words vectors matrix without issues..
use the following method: ``` model.wv.get_item() ```
58,945,475
I'm somewhat new to python: I'm trying to write a text file into a different format. Given a file of format: ``` [header] rho = 1.1742817531 mu = 1.71997e-05 q = 411385.1046712013 ... ``` I want: ``` [header] 1.1742817531, 1.71997e-05, 411385.1046712013, ... ``` and be able to write successive lines below...
2019/11/20
[ "https://Stackoverflow.com/questions/58945475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12400757/" ]
Cache the images on the filesystem when you first download them. When you load an image, check the cache, and download the images only if they're not yet cached. If they are, load them from the filesystem instead.
Try using glide or Picasso to load images in different list views. Glide internally caches images using their url as a key to retrieve cache. That way when your images are loaded once in any of your list view, they can be cached for future use in other list views. However, you will still need to create new instances of...
57,464,098
I am currently doing some exercises with Kernel Density Estimation and I am trying to run this piece of code: ```py from sklearn.datasets import load_digits from sklearn.model_selection import GridSearchCV digits = load_digits() bandwidths = 10 ** np.linspace(0, 2, 100) grid = GridSearchCV(KDEClassifier(), {'bandwid...
2019/08/12
[ "https://Stackoverflow.com/questions/57464098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11491321/" ]
It's simple, I also face the same problem, Just replace this line- ``` scores = [val.mean_test_score for val in grid.cv_results_] ``` with ``` scores = grid.cv_results_.get('mean_test_score').tolist() ``` Because, 'mean\_test\_score' is depricated and grid.cv\_results\_ is in dict format.
The [documentation](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html) of the object `GridSearchCV` specifies that the attribute `cv_results_` is a dictionary, therefore, iterating over a python dictionary returns the strings of the keys as you can se [here](https://realpython....
20,386,727
Currently I have data in the following format ``` A A -> B -> C -> D -> Z A -> B -> O A -> X ``` This is stored in a list [line1,line2, and so forth] Now I want to print this in the following manner ``` A |- X |- B |- O |- C |- D |- Z ``` I'm new to python so. I was thinking of find...
2013/12/04
[ "https://Stackoverflow.com/questions/20386727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2838679/" ]
1. You don't modify method parameters, you make copies of them. 2. You don't null-check/empty-check inside the loop, you do it first thing in the method. 3. The standard in a `for loop` is `i < size`, not `size > i`... meh ``` /** * Splits the string str into individual characters: Small becomes S m a l l */ public...
Ask yourself a question, where is **s** coming from? ``` char space = s.charAt(); ??? s ??? ``` A second question, character at? ``` public static String split(String str){ for(int i = 0; i < str.length(); i++) { if (str.length() > 0) { char space = str.charAt(i) } } return s...
20,386,727
Currently I have data in the following format ``` A A -> B -> C -> D -> Z A -> B -> O A -> X ``` This is stored in a list [line1,line2, and so forth] Now I want to print this in the following manner ``` A |- X |- B |- O |- C |- D |- Z ``` I'm new to python so. I was thinking of find...
2013/12/04
[ "https://Stackoverflow.com/questions/20386727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2838679/" ]
My solution uses `concat` to build the `str2`, and `trim` to remove last white space. ``` public static String split(String str) { String str2 = ""; for(int i=0; i<str.length(); i++) { str2 = str2.concat(str.charAt(i)+" "); } return str2.trim(); } ```
Ask yourself a question, where is **s** coming from? ``` char space = s.charAt(); ??? s ??? ``` A second question, character at? ``` public static String split(String str){ for(int i = 0; i < str.length(); i++) { if (str.length() > 0) { char space = str.charAt(i) } } return s...
20,386,727
Currently I have data in the following format ``` A A -> B -> C -> D -> Z A -> B -> O A -> X ``` This is stored in a list [line1,line2, and so forth] Now I want to print this in the following manner ``` A |- X |- B |- O |- C |- D |- Z ``` I'm new to python so. I was thinking of find...
2013/12/04
[ "https://Stackoverflow.com/questions/20386727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2838679/" ]
1. You don't modify method parameters, you make copies of them. 2. You don't null-check/empty-check inside the loop, you do it first thing in the method. 3. The standard in a `for loop` is `i < size`, not `size > i`... meh ``` /** * Splits the string str into individual characters: Small becomes S m a l l */ public...
@Babanfaraj, this a answer from a newbie like you!! The code is very easy. The corrected program is- ``` class fopl { public static void main(String str) { int n=str.length(); for (int i = 0;i<n; i++) { if (n>=0) { String space = str.charAt(i)+" "; Sys...
20,386,727
Currently I have data in the following format ``` A A -> B -> C -> D -> Z A -> B -> O A -> X ``` This is stored in a list [line1,line2, and so forth] Now I want to print this in the following manner ``` A |- X |- B |- O |- C |- D |- Z ``` I'm new to python so. I was thinking of find...
2013/12/04
[ "https://Stackoverflow.com/questions/20386727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2838679/" ]
My solution uses `concat` to build the `str2`, and `trim` to remove last white space. ``` public static String split(String str) { String str2 = ""; for(int i=0; i<str.length(); i++) { str2 = str2.concat(str.charAt(i)+" "); } return str2.trim(); } ```
@Babanfaraj, this a answer from a newbie like you!! The code is very easy. The corrected program is- ``` class fopl { public static void main(String str) { int n=str.length(); for (int i = 0;i<n; i++) { if (n>=0) { String space = str.charAt(i)+" "; Sys...
54,174,950
**Context** I am trying to run my Django application and Postgres database in a docker development environment using docker-compose (it's my first time using Docker). I want to use my application with a custom role and database both named `teddycrepineau` (as opposed to using the default postgres user and db). **G...
2019/01/14
[ "https://Stackoverflow.com/questions/54174950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5022051/" ]
This happens because your pgsql db was launched without any envs. The pgsql docker image only uses the envs the first time you created the container, after that it won't recreate DB and users. The solution is to remove the pgsql volume so next time you `docker-compose up` you will have a fresh db with envs read. Simpl...
Change your env order like this. ``` POSTGRES_DB=teddycrepineau POSTGRES_USER=teddycrepineau POSTGRES_PASSWORD= ``` I find it at [this issue](https://github.com/docker-library/postgres/issues/41#issuecomment-382925263). I hope it works.
54,174,950
**Context** I am trying to run my Django application and Postgres database in a docker development environment using docker-compose (it's my first time using Docker). I want to use my application with a custom role and database both named `teddycrepineau` (as opposed to using the default postgres user and db). **G...
2019/01/14
[ "https://Stackoverflow.com/questions/54174950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5022051/" ]
Change your env order like this. ``` POSTGRES_DB=teddycrepineau POSTGRES_USER=teddycrepineau POSTGRES_PASSWORD= ``` I find it at [this issue](https://github.com/docker-library/postgres/issues/41#issuecomment-382925263). I hope it works.
when you run the ``` sudo docker-compose exec web python manage.py migrate ``` yes of course you will receive ***"django.db.utils.OperationalError: FATAL: role "user" does not exist*** first you need to put ``` sudo docker-compose down -v sudo docker system prune ``` check container, they should be deleted ``...
54,174,950
**Context** I am trying to run my Django application and Postgres database in a docker development environment using docker-compose (it's my first time using Docker). I want to use my application with a custom role and database both named `teddycrepineau` (as opposed to using the default postgres user and db). **G...
2019/01/14
[ "https://Stackoverflow.com/questions/54174950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5022051/" ]
Change your env order like this. ``` POSTGRES_DB=teddycrepineau POSTGRES_USER=teddycrepineau POSTGRES_PASSWORD= ``` I find it at [this issue](https://github.com/docker-library/postgres/issues/41#issuecomment-382925263). I hope it works.
I encountered the issue due to a mismatch between the `$POSTGRES_DB` and `$POSTGRES_USER` variables. By default, psql will attempt to set the database to the same name as the user logging in, so when there is a mismatch between the variables it fails with an error along the lines of psql: > > FATAL: database "root" d...
54,174,950
**Context** I am trying to run my Django application and Postgres database in a docker development environment using docker-compose (it's my first time using Docker). I want to use my application with a custom role and database both named `teddycrepineau` (as opposed to using the default postgres user and db). **G...
2019/01/14
[ "https://Stackoverflow.com/questions/54174950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5022051/" ]
This happens because your pgsql db was launched without any envs. The pgsql docker image only uses the envs the first time you created the container, after that it won't recreate DB and users. The solution is to remove the pgsql volume so next time you `docker-compose up` you will have a fresh db with envs read. Simpl...
when you run the ``` sudo docker-compose exec web python manage.py migrate ``` yes of course you will receive ***"django.db.utils.OperationalError: FATAL: role "user" does not exist*** first you need to put ``` sudo docker-compose down -v sudo docker system prune ``` check container, they should be deleted ``...
54,174,950
**Context** I am trying to run my Django application and Postgres database in a docker development environment using docker-compose (it's my first time using Docker). I want to use my application with a custom role and database both named `teddycrepineau` (as opposed to using the default postgres user and db). **G...
2019/01/14
[ "https://Stackoverflow.com/questions/54174950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5022051/" ]
This happens because your pgsql db was launched without any envs. The pgsql docker image only uses the envs the first time you created the container, after that it won't recreate DB and users. The solution is to remove the pgsql volume so next time you `docker-compose up` you will have a fresh db with envs read. Simpl...
I encountered the issue due to a mismatch between the `$POSTGRES_DB` and `$POSTGRES_USER` variables. By default, psql will attempt to set the database to the same name as the user logging in, so when there is a mismatch between the variables it fails with an error along the lines of psql: > > FATAL: database "root" d...
47,031,382
I am using PyTorch with python3. I tried the following while in ipdb mode: ``` regions = np.zeros([107,4], dtype='uint8') torch.from_numpy(regions) ``` This prints the tensor. However when trying: ``` regions = np.zeros([107,107,4], dtype='uint8') torch.from_numpy(regions) ``` I get the following error: ``` ***...
2017/10/31
[ "https://Stackoverflow.com/questions/47031382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683130/" ]
``` Pleas make sure our AWS S3 configuration : <CORSConfiguration> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>Authorization</AllowedHeader> </CORSRule> </CO...
One of your uploads is failing. You will need to catch the error from s3Client.uploadPart() and retry. I recommend the following improvements on the simple code below. 1) Add an increasing timeout for each retry. 2) Process the type of error to determine if a retry will make sense. For some errors you should just re...
47,031,382
I am using PyTorch with python3. I tried the following while in ipdb mode: ``` regions = np.zeros([107,4], dtype='uint8') torch.from_numpy(regions) ``` This prints the tensor. However when trying: ``` regions = np.zeros([107,107,4], dtype='uint8') torch.from_numpy(regions) ``` I get the following error: ``` ***...
2017/10/31
[ "https://Stackoverflow.com/questions/47031382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683130/" ]
``` Pleas make sure our AWS S3 configuration : <CORSConfiguration> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>Authorization</AllowedHeader> </CORSRule> </CO...
I was able to resolve this issue by using **GeneratePresignedUrlRequest** feature of AWS. But now I am getting a new error.**413 request entity too large nginx**. I have googled for the solution where I found that I need to make changes in nginx.conf file of server. Now the question arises that since I am going to have...
47,031,382
I am using PyTorch with python3. I tried the following while in ipdb mode: ``` regions = np.zeros([107,4], dtype='uint8') torch.from_numpy(regions) ``` This prints the tensor. However when trying: ``` regions = np.zeros([107,107,4], dtype='uint8') torch.from_numpy(regions) ``` I get the following error: ``` ***...
2017/10/31
[ "https://Stackoverflow.com/questions/47031382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683130/" ]
One of your uploads is failing. You will need to catch the error from s3Client.uploadPart() and retry. I recommend the following improvements on the simple code below. 1) Add an increasing timeout for each retry. 2) Process the type of error to determine if a retry will make sense. For some errors you should just re...
I was able to resolve this issue by using **GeneratePresignedUrlRequest** feature of AWS. But now I am getting a new error.**413 request entity too large nginx**. I have googled for the solution where I found that I need to make changes in nginx.conf file of server. Now the question arises that since I am going to have...
55,210,888
I faced with problem when I installed python-pptx with conda on cleaned environment: conda install -c conda-forge python-pptx. After install was successfully finished I tried to import pptx module and got following error: > > > ``` > >>> import pptx > Traceback (most recent call last): > File "<stdin>", line 1, i...
2019/03/17
[ "https://Stackoverflow.com/questions/55210888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9869122/" ]
If you are allowed to use built-in functions, you could do this: ``` idx = s[::-1].find(c[::-1]) return len(s) - (idx + len(c)) if idx >= 0 else -1 ```
Your problem is this line: ``` last_position = next_position + len(c) ``` This is skipping potential matches. As it is, your code considers only the first, third, and fifth positions for matches. As you say, the right answer comes from checking the fourth position (index == 3). But you're skipping that because you m...
55,210,888
I faced with problem when I installed python-pptx with conda on cleaned environment: conda install -c conda-forge python-pptx. After install was successfully finished I tried to import pptx module and got following error: > > > ``` > >>> import pptx > Traceback (most recent call last): > File "<stdin>", line 1, i...
2019/03/17
[ "https://Stackoverflow.com/questions/55210888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9869122/" ]
If you are allowed to use built-in functions, you could do this: ``` idx = s[::-1].find(c[::-1]) return len(s) - (idx + len(c)) if idx >= 0 else -1 ```
It's because you're increasing next\_position with length of found substring thus missing last match. ``` def find_last(s, c): last_position = 0 result = -1 while True: next_position = s.find(c, last_position) if next_position == -1: break result = next_position ...
49,105,693
I have the following code: ``` import csv import requests from bs4 import BeautifulSoup import datetime with open("D:/python/sursa_alimentare.csv", "w+") as f: writer = csv.writer(f) writer.writerow(["Descriere", "Pret"])` ``` Because I run this quite often, I want to save the csv file with a na...
2018/03/05
[ "https://Stackoverflow.com/questions/49105693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8947024/" ]
you have to use `.strftime` ``` filename = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M.csv") with open(filename, "w+") as f: writer = csv.writer(f) writer.writerow(["Descriere", "Pret"])` ``` here is some details <https://www.tutorialspoint.com/python/time_strftime.htm>
I guess this might help you add datetime to your filename, ``` import csv import requests from bs4 import BeautifulSoup import datetime file_name = 'sursa_alimentare-'+str(datetime.datetime.now())+'.csv' with open(file_name, "w+") as f: writer = csv.writer(f) writer.writerow(["Descriere", "Pret"]) ``...
49,105,693
I have the following code: ``` import csv import requests from bs4 import BeautifulSoup import datetime with open("D:/python/sursa_alimentare.csv", "w+") as f: writer = csv.writer(f) writer.writerow(["Descriere", "Pret"])` ``` Because I run this quite often, I want to save the csv file with a na...
2018/03/05
[ "https://Stackoverflow.com/questions/49105693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8947024/" ]
Avoid using `datetime.now()` directly, as this will create `:` in the filename, which would fail if used on a Windows file system. Instead use [`strftime()`](https://docs.python.org/3.6/library/datetime.html?highlight=strptime#strftime-and-strptime-behavior) to add the required formatting: ``` from datetime import dat...
I guess this might help you add datetime to your filename, ``` import csv import requests from bs4 import BeautifulSoup import datetime file_name = 'sursa_alimentare-'+str(datetime.datetime.now())+'.csv' with open(file_name, "w+") as f: writer = csv.writer(f) writer.writerow(["Descriere", "Pret"]) ``...
21,265,633
I need to read a huge (larger than memory) unquoted TSV file. Fields may contain the string "\n". However, python tries to be clever and split that string in two. So for example a row containing: ``` cat dog fish\nchips 4.50 ``` gets split into two lines: ``` ['cat', 'dog', 'fish'] ['chips', 4.5] ``` Wha...
2014/01/21
[ "https://Stackoverflow.com/questions/21265633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2400966/" ]
This already works correctly; for a file with a literal `\` followed by a literal `n` character (two bytes), will **never** be seen by Python as a newline. What you have, then, is a single `\n` character, an actual newline. The *rest* of your file is separated by the `\r\n` Windows conventional line separator. Use [`...
If your problem is .readline() and splitting on \t, try using the csv builtin: ``` import csv with open(path, 'r') as file: reader = csv.Reader(file, delimiter='\t') # Or DictReader - I like DictReader. reader.next() ``` It handles these things for us.
20,998,832
I've ran the brown-clustering algorithm from <https://github.com/percyliang/brown-cluster> and also a python implementation <https://github.com/mheilman/tan-clustering>. And they both give some sort of binary and another integer for each unique token. For example: ``` 0 the 6 10 chased 3 11...
2014/01/08
[ "https://Stackoverflow.com/questions/20998832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
If I understand correctly, the algorithm gives you a tree and you need to truncate it at some level to get clusters. In case of those bit strings, you should just take first `L` characters. For example, cutting at the second character gives you two clusters ``` 10 chased 11 dog 11 ...
My guess is: According to Figure 2 in [Brown et al 1992](http://acl.ldc.upenn.edu/J/J92/J92-4003.pdf), the clustering is hierarchical and to get from the root to each word "leaf" you have to make an up/down decision. If up is 0 and down is 1, you can represent each word as a bit string. From <https://github.com/mhei...
20,998,832
I've ran the brown-clustering algorithm from <https://github.com/percyliang/brown-cluster> and also a python implementation <https://github.com/mheilman/tan-clustering>. And they both give some sort of binary and another integer for each unique token. For example: ``` 0 the 6 10 chased 3 11...
2014/01/08
[ "https://Stackoverflow.com/questions/20998832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
The integers are counts of how many times the word is seen in the document. (I have tested this in the python implementation.) From the comments at the top of the python implementation: > > Instead of using a window (e.g., as in Brown et al., sec. 4), this > code computed PMI using the probability that two randomly...
My guess is: According to Figure 2 in [Brown et al 1992](http://acl.ldc.upenn.edu/J/J92/J92-4003.pdf), the clustering is hierarchical and to get from the root to each word "leaf" you have to make an up/down decision. If up is 0 and down is 1, you can represent each word as a bit string. From <https://github.com/mhei...
20,998,832
I've ran the brown-clustering algorithm from <https://github.com/percyliang/brown-cluster> and also a python implementation <https://github.com/mheilman/tan-clustering>. And they both give some sort of binary and another integer for each unique token. For example: ``` 0 the 6 10 chased 3 11...
2014/01/08
[ "https://Stackoverflow.com/questions/20998832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
In Percy Liang's implementation (<https://github.com/percyliang/brown-cluster>), the `-C` parameter allows you to specify the number of word clusters. The output contains all the words in the corpus, together with a bit-string annotating the cluster and the word frequency in the following format: `<bit string> <word> <...
My guess is: According to Figure 2 in [Brown et al 1992](http://acl.ldc.upenn.edu/J/J92/J92-4003.pdf), the clustering is hierarchical and to get from the root to each word "leaf" you have to make an up/down decision. If up is 0 and down is 1, you can represent each word as a bit string. From <https://github.com/mhei...
20,998,832
I've ran the brown-clustering algorithm from <https://github.com/percyliang/brown-cluster> and also a python implementation <https://github.com/mheilman/tan-clustering>. And they both give some sort of binary and another integer for each unique token. For example: ``` 0 the 6 10 chased 3 11...
2014/01/08
[ "https://Stackoverflow.com/questions/20998832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
Change your running : ./wcluster --text input.txt --c 3 --c number this number means the number of cluster, and the default is 50. You can't distinguish the different cluster of words because the default input has only three sentences. Change 50 clusters to 3 clusters and you can tell the difference. I enter three...
My guess is: According to Figure 2 in [Brown et al 1992](http://acl.ldc.upenn.edu/J/J92/J92-4003.pdf), the clustering is hierarchical and to get from the root to each word "leaf" you have to make an up/down decision. If up is 0 and down is 1, you can represent each word as a bit string. From <https://github.com/mhei...
20,998,832
I've ran the brown-clustering algorithm from <https://github.com/percyliang/brown-cluster> and also a python implementation <https://github.com/mheilman/tan-clustering>. And they both give some sort of binary and another integer for each unique token. For example: ``` 0 the 6 10 chased 3 11...
2014/01/08
[ "https://Stackoverflow.com/questions/20998832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
If I understand correctly, the algorithm gives you a tree and you need to truncate it at some level to get clusters. In case of those bit strings, you should just take first `L` characters. For example, cutting at the second character gives you two clusters ``` 10 chased 11 dog 11 ...
The integers are counts of how many times the word is seen in the document. (I have tested this in the python implementation.) From the comments at the top of the python implementation: > > Instead of using a window (e.g., as in Brown et al., sec. 4), this > code computed PMI using the probability that two randomly...
20,998,832
I've ran the brown-clustering algorithm from <https://github.com/percyliang/brown-cluster> and also a python implementation <https://github.com/mheilman/tan-clustering>. And they both give some sort of binary and another integer for each unique token. For example: ``` 0 the 6 10 chased 3 11...
2014/01/08
[ "https://Stackoverflow.com/questions/20998832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
If I understand correctly, the algorithm gives you a tree and you need to truncate it at some level to get clusters. In case of those bit strings, you should just take first `L` characters. For example, cutting at the second character gives you two clusters ``` 10 chased 11 dog 11 ...
In Percy Liang's implementation (<https://github.com/percyliang/brown-cluster>), the `-C` parameter allows you to specify the number of word clusters. The output contains all the words in the corpus, together with a bit-string annotating the cluster and the word frequency in the following format: `<bit string> <word> <...
20,998,832
I've ran the brown-clustering algorithm from <https://github.com/percyliang/brown-cluster> and also a python implementation <https://github.com/mheilman/tan-clustering>. And they both give some sort of binary and another integer for each unique token. For example: ``` 0 the 6 10 chased 3 11...
2014/01/08
[ "https://Stackoverflow.com/questions/20998832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
If I understand correctly, the algorithm gives you a tree and you need to truncate it at some level to get clusters. In case of those bit strings, you should just take first `L` characters. For example, cutting at the second character gives you two clusters ``` 10 chased 11 dog 11 ...
Change your running : ./wcluster --text input.txt --c 3 --c number this number means the number of cluster, and the default is 50. You can't distinguish the different cluster of words because the default input has only three sentences. Change 50 clusters to 3 clusters and you can tell the difference. I enter three...
20,998,832
I've ran the brown-clustering algorithm from <https://github.com/percyliang/brown-cluster> and also a python implementation <https://github.com/mheilman/tan-clustering>. And they both give some sort of binary and another integer for each unique token. For example: ``` 0 the 6 10 chased 3 11...
2014/01/08
[ "https://Stackoverflow.com/questions/20998832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
In Percy Liang's implementation (<https://github.com/percyliang/brown-cluster>), the `-C` parameter allows you to specify the number of word clusters. The output contains all the words in the corpus, together with a bit-string annotating the cluster and the word frequency in the following format: `<bit string> <word> <...
The integers are counts of how many times the word is seen in the document. (I have tested this in the python implementation.) From the comments at the top of the python implementation: > > Instead of using a window (e.g., as in Brown et al., sec. 4), this > code computed PMI using the probability that two randomly...
20,998,832
I've ran the brown-clustering algorithm from <https://github.com/percyliang/brown-cluster> and also a python implementation <https://github.com/mheilman/tan-clustering>. And they both give some sort of binary and another integer for each unique token. For example: ``` 0 the 6 10 chased 3 11...
2014/01/08
[ "https://Stackoverflow.com/questions/20998832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
Change your running : ./wcluster --text input.txt --c 3 --c number this number means the number of cluster, and the default is 50. You can't distinguish the different cluster of words because the default input has only three sentences. Change 50 clusters to 3 clusters and you can tell the difference. I enter three...
The integers are counts of how many times the word is seen in the document. (I have tested this in the python implementation.) From the comments at the top of the python implementation: > > Instead of using a window (e.g., as in Brown et al., sec. 4), this > code computed PMI using the probability that two randomly...
43,303,575
I am trying to install Cassandra on windows 10 localhost. I am getting error as `Can't detect Python version!` I am trying this way Downloaded and extracted Cassandra in `C:\wamp64\apache-cassandra-3.10` Set `Set-ExecutionPolicy Unrestricted` in Windows powershell From Windows CMD ``` cd C:\wamp64\apache-cassandra...
2017/04/09
[ "https://Stackoverflow.com/questions/43303575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have installed latest version of Apache Cassandra 3.11.9 for Windows, My python env variable is already set for python3 (Python 3.8), as I actively use python 3.8. I was continuously getting error, then I installed python2 inside 'Apache Cassandra 3.11.9\bin'. I need not to reset my env variable to python2. The more...
I think you are following wrong python installation procedures. **please uninstall all the python instances using programs and features section in control panel. then install python obtained from [python.org](https://www.python.org/). ensure add to path option is checked on the time of installation. verify python insta...
43,303,575
I am trying to install Cassandra on windows 10 localhost. I am getting error as `Can't detect Python version!` I am trying this way Downloaded and extracted Cassandra in `C:\wamp64\apache-cassandra-3.10` Set `Set-ExecutionPolicy Unrestricted` in Windows powershell From Windows CMD ``` cd C:\wamp64\apache-cassandra...
2017/04/09
[ "https://Stackoverflow.com/questions/43303575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have installed latest version of Apache Cassandra 3.11.9 for Windows, My python env variable is already set for python3 (Python 3.8), as I actively use python 3.8. I was continuously getting error, then I installed python2 inside 'Apache Cassandra 3.11.9\bin'. I need not to reset my env variable to python2. The more...
I had this issue as I was running Python3 and Python2 on Windows. It seems like the problem was with missing PATH to Python2. To check, run in cmd: ``` python --version ``` If you get nothing, it means that the PATH is not added. Note: To add path when installing Python2 you need to scroll down to Customize Pyt...
67,281,038
I have wrote a code for face recognition in python. My code works perfectly in `.py` file (without any errors or warning), but after making a `.exe` file out of it, through `pyinstaller` it won't work at all. I have searched through, for the same and tried the following methods, but it still won't work. first method i ...
2021/04/27
[ "https://Stackoverflow.com/questions/67281038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14332805/" ]
First of all, make sure your function app can be compiled. Second, the format of your publish url is no problem. So maybe this problem is not from the Visual Studio side. please make sure the function app is not stop or restarting, the scm site is not under the protection of NETWorking and you have login the right Mi...
In my case opening azure functions app in my browser helped. Until that it was giving error when I try to publish it in Visual Studio.
45,457,324
I have set up a spark cluster and all the nodes have access to network shared storage where they can access a file to read. I am running this in a python jupyter notebook. It was working a few days ago, and now it stopped working but I'm not sure why, or what I have changed. I have tried restarting the nodes and maste...
2017/08/02
[ "https://Stackoverflow.com/questions/45457324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8236204/" ]
From the error it looks like it is checking the file on your local system. Just make sure that you have file present on specified Path. Also try below suggestions. 1. try with file URI : file:///nas/file123.csv 2. Upload the file on HDFS and try to read the file from HDFS URI like hdfs:///... Hope this helps. Regard...
If you are loading the data from local directory, remember to make sure file exists in all of your worker nodes.
62,246,786
I would like to run my scrapy sprider from python script. I can call my spider with the following code, ``` subprocess.check_output(['scrapy crawl mySpider']) ``` Untill all is well. But before that, I instantiate the class of my spider by initializing the start\_urls, then the call to scrapy crawl doesn't work sin...
2020/06/07
[ "https://Stackoverflow.com/questions/62246786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13700256/" ]
``` stock = {'meat':100,'fish':100,'bread':100, 'milk':100,'chips':100} total = 0 for v in stock.values(): total += v ```
``` >>> from statistics import mean >>> stock={'meat':100,'fish':100,'bread':100, 'milk':100,'chips':100} >>> print(f"Total stock level : {mean(stock.values())*len(stock)}") Total stock level : 500 ```
62,246,786
I would like to run my scrapy sprider from python script. I can call my spider with the following code, ``` subprocess.check_output(['scrapy crawl mySpider']) ``` Untill all is well. But before that, I instantiate the class of my spider by initializing the start\_urls, then the call to scrapy crawl doesn't work sin...
2020/06/07
[ "https://Stackoverflow.com/questions/62246786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13700256/" ]
Your current code using `sum()` is the best way to do this, and I would recommend keeping things as-is. However, just for illustrative purposes, here's a for-loop method that does the same thing. ```py stock = {'meat': 100, 'fish': 100, 'bread': 100, 'milk': 100, 'chips': 100} totalstock = 0 for item, value in stock....
``` >>> from statistics import mean >>> stock={'meat':100,'fish':100,'bread':100, 'milk':100,'chips':100} >>> print(f"Total stock level : {mean(stock.values())*len(stock)}") Total stock level : 500 ```
62,246,786
I would like to run my scrapy sprider from python script. I can call my spider with the following code, ``` subprocess.check_output(['scrapy crawl mySpider']) ``` Untill all is well. But before that, I instantiate the class of my spider by initializing the start\_urls, then the call to scrapy crawl doesn't work sin...
2020/06/07
[ "https://Stackoverflow.com/questions/62246786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13700256/" ]
``` stock = {'meat':100,'fish':100,'bread':100, 'milk':100,'chips':100} total = 0 for v in stock.values(): total += v ```
Your can iterate threw a dictonary in python very easily. ``` for key in dict: print(key) ``` So in your case you should do the following: ``` totalstock = 0 for key in stock: totalstock += stock[key] print(totalstock) ```
62,246,786
I would like to run my scrapy sprider from python script. I can call my spider with the following code, ``` subprocess.check_output(['scrapy crawl mySpider']) ``` Untill all is well. But before that, I instantiate the class of my spider by initializing the start\_urls, then the call to scrapy crawl doesn't work sin...
2020/06/07
[ "https://Stackoverflow.com/questions/62246786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13700256/" ]
Your current code using `sum()` is the best way to do this, and I would recommend keeping things as-is. However, just for illustrative purposes, here's a for-loop method that does the same thing. ```py stock = {'meat': 100, 'fish': 100, 'bread': 100, 'milk': 100, 'chips': 100} totalstock = 0 for item, value in stock....
Your can iterate threw a dictonary in python very easily. ``` for key in dict: print(key) ``` So in your case you should do the following: ``` totalstock = 0 for key in stock: totalstock += stock[key] print(totalstock) ```
56,128,397
I pulled the official mongo image from the Docker website and started a mongo container named `dataiomongo`. I now want to connect to the mongodb inside the container using pymongo. This is the python script I wrote: ``` from pprint import pprint from pymongo import MongoClient client = MongoClient('localhost', p...
2019/05/14
[ "https://Stackoverflow.com/questions/56128397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5684940/" ]
run mongo ========= First you need to run mongo ``` $ docker run --rm --name my-mongo -it -p 27017:27017 mongo:latest ``` as a daemon =========== ``` $ docker run --name my-mongo -d mongo:latest ``` connect to the previous container.. with another container =======================================================...
Make sure you bind the 27017 container port to host port via -p 27017:27017 flag.
56,128,397
I pulled the official mongo image from the Docker website and started a mongo container named `dataiomongo`. I now want to connect to the mongodb inside the container using pymongo. This is the python script I wrote: ``` from pprint import pprint from pymongo import MongoClient client = MongoClient('localhost', p...
2019/05/14
[ "https://Stackoverflow.com/questions/56128397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5684940/" ]
I think you miss `-p 27017:27017` flag. `docker run -p 27017:27017 --name mymongo -d mongo` .
Make sure you bind the 27017 container port to host port via -p 27017:27017 flag.
56,128,397
I pulled the official mongo image from the Docker website and started a mongo container named `dataiomongo`. I now want to connect to the mongodb inside the container using pymongo. This is the python script I wrote: ``` from pprint import pprint from pymongo import MongoClient client = MongoClient('localhost', p...
2019/05/14
[ "https://Stackoverflow.com/questions/56128397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5684940/" ]
run mongo ========= First you need to run mongo ``` $ docker run --rm --name my-mongo -it -p 27017:27017 mongo:latest ``` as a daemon =========== ``` $ docker run --name my-mongo -d mongo:latest ``` connect to the previous container.. with another container =======================================================...
I think you miss `-p 27017:27017` flag. `docker run -p 27017:27017 --name mymongo -d mongo` .
56,803,812
I want to include a cron task in a MariaDB container, based on the latest image `mariadb`, but I'm stuck with this. I tried many things without success because I can't launch both MariaDB and Cron. Here is my actual dockerfile: ``` FROM mariadb:10.3 # DB settings ENV MYSQL_DATABASE=beurre \ MYSQL_ROOT_PASSWORD=...
2019/06/28
[ "https://Stackoverflow.com/questions/56803812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9678258/" ]
Elaborating on @k0pernikus's comment, I would recommend to use a separate container that runs cron. The cronjobs in that container can then work with your mysql database. Here's how I would approach it: 1. Create a Cron Docker Container ================================= You can set up a cron container fairly simply....
I recommend the [solution provided by fjc](https://stackoverflow.com/a/56804227/457268). Treat this as nice-to-know to understand why your approach is not working. --- Docker has `RUN` commands that are only being executed during build. Not on container startup. It also has a `CMD` (or ENTRYPOINT) for executing spec...
62,827,871
I'm looking for a compiler to compile '.py' file to a single '.exe' file. I've try already **auto-py-to-exe** but I'm not happy with it. I've tried **PyInstaller**, but one of its dependencies (PyCrypto, which I need) is not working/ maintained anymore and fails to install. <https://pyinstaller.readthedocs.io/en/stab...
2020/07/10
[ "https://Stackoverflow.com/questions/62827871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11943028/" ]
I had a similar issue to this, needing to run Python code on machines where Python could not be downloaded. I used py2exe, and it worked quite well. (<https://www.py2exe.org/>)
You could try these **steps to convert .py to .exe in Python 3.8** 1. Install [Python 3.8](https://www.python.org/downloads/). 2. Install cx\_Freeze, (open your command prompt and type `pip install cx_Freeze`. 3. Install idna, (open your command prompt and type `pip install idna`. 4. Write a `.py` a program named `myf...
64,764,650
Say that there are two iterators: ``` def genA(): while True: yield 1 def genB(): while True: yield 2 gA = genA() gB = genB() ``` According to [this SO answer](https://stackoverflow.com/a/8770796/3259896) they can be ***evenly*** interleaved using the [`itertools` recipes](https://docs.pyth...
2020/11/10
[ "https://Stackoverflow.com/questions/64764650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3259896/" ]
If you're okay with a deterministic approach (as I understand from your self-answer), you can add an argument which is the percentage of the first iterator and then just calculate each iterator's "part". For example, if you want `.75` from the first iterator - this translates to: *for every **three** elements from `ite...
``` def genA(): while True: yield 1 def genB(): while True: yield 2 gA = genA() gB = genB() import random def xyz(itt1, itt2): while True: if random.random() < .25: yield next(itt1) else: yield next(itt2) newGen = xyz(gA, gB) next(newGen) ``` T...
19,965,453
Im making a multipart POST using the python package requests. Im using xlrd to change some values in an Excel file save it then send that up in a multipart POST. This working fine when I run it locally on my mac but when I put the code on a remote machine and make the same request the body content type is blank where a...
2013/11/13
[ "https://Stackoverflow.com/questions/19965453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946337/" ]
The `files` parameter accepts a dictionary of keys to tuples, with the following form: ``` files = {'name': (<filename>, <file object>, <content type>, <per-part headers>)} ``` In your specific case, you could write this: ``` files = {'file': ('filename.xls', open('filename.xls'), 'application/vnd.ms-excel', {})} ...
I believe you can use the headers parameter, e.g ``` requests.post(url, data=my_data, headers={"Content-type": "application/vnd.ms-excel"}) ```
29,686,328
Edit: Rather than vote me down can you provide an url on where you would recommend a newbie learn Python? Be part of the solution versus problem. I'm trying to compile a basic program (for a class) that when specific if/elif/else conditions are met a specific roman numeral shows though I'm a bit confused on why I'm ge...
2015/04/16
[ "https://Stackoverflow.com/questions/29686328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4259649/" ]
``` else(number==3): print("The number is X") ``` Is incorret. You should use only ``` else : print("The number is X") ```
Just use `else:` instead of `else(number==3)`. `else:` doesn't take a condition. Also, you don't need to put parentheses around the conditions in Python.
29,686,328
Edit: Rather than vote me down can you provide an url on where you would recommend a newbie learn Python? Be part of the solution versus problem. I'm trying to compile a basic program (for a class) that when specific if/elif/else conditions are met a specific roman numeral shows though I'm a bit confused on why I'm ge...
2015/04/16
[ "https://Stackoverflow.com/questions/29686328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4259649/" ]
``` else(number==3): print("The number is X") ``` Is incorret. You should use only ``` else : print("The number is X") ```
this line: ``` number = input(int("Please enter a number within the range of 1-10")) ``` is now giving you problems. You need get the input, then convert to an int: ``` number = int(input("Please enter a number within the range of 1-10")) ``` This code will still throw an error if the user enters anything that it...
29,686,328
Edit: Rather than vote me down can you provide an url on where you would recommend a newbie learn Python? Be part of the solution versus problem. I'm trying to compile a basic program (for a class) that when specific if/elif/else conditions are met a specific roman numeral shows though I'm a bit confused on why I'm ge...
2015/04/16
[ "https://Stackoverflow.com/questions/29686328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4259649/" ]
this line: ``` number = input(int("Please enter a number within the range of 1-10")) ``` is now giving you problems. You need get the input, then convert to an int: ``` number = int(input("Please enter a number within the range of 1-10")) ``` This code will still throw an error if the user enters anything that it...
Just use `else:` instead of `else(number==3)`. `else:` doesn't take a condition. Also, you don't need to put parentheses around the conditions in Python.
67,017,354
**My problem**: starting a threaded function and, **asynchronously**, act upon the returned value I know how to: * start a threaded function with `threading`. The problem: no simple way to get the result back * [get the return value](https://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-threa...
2021/04/09
[ "https://Stackoverflow.com/questions/67017354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/903011/" ]
You can use [`concurrent.futures.add_done_callback`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future.add_done_callback) as shown below. The callback must be a callable taking a single argument, the `Future` instance — and it must get the result from that as shown. The example also ad...
You can use [add\_done\_callback](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future.add_done_callback) of `concurrent.futures` library, so you can modify your example like this: ```py def the_callback(something): print(f"the thread returned {something.result()}") with concurrent....
6,969,222
Every time I run my code in Python IDLE development environment, I get a Visual C++ runtime error/unhandled exception in pythonw.exe. ``` Figure 1: pythonw.exe - Application Error The exception unknown software exception (0x40000015) occurred in the application at location 0x1e0e1379. ``` I am using networkx and ...
2011/08/06
[ "https://Stackoverflow.com/questions/6969222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264970/" ]
The easiest fix for this is to open IDLE from the start menu and then opening your code files from there.
The solution to this problem was indeed to quit using IDLE. I got the Python stuff for Eclipse; I'd recommend that setup.
45,530,741
I'm trying to run my code with a multiprocessing function but mongo keep returning > > "MongoClient opened before fork. Create MongoClient with > connect=False, or create client after forking." > > > I really doesn't understand how i can adapt my code to this. Basically the structure is: ``` db = MongoClient()...
2017/08/06
[ "https://Stackoverflow.com/questions/45530741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3476027/" ]
db.authenticate will have to connect to mongo server and it will try to make a connection. So, even though connect=False is being used, db.authenticate will require a connection to be open. Why don't you create the mongo client instance after fork? That's look like the easiest solution.
Since `db.authenticate` must open the MongoClient and connect to the server, it creates connections which won't work in the forked subprocess. Hence, the error message. Try this instead: ``` db = MongoClient('mongodb://user:password@localhost', connect=False).database ``` Also, delete the Lock `l`. Acquiring a lock ...
45,530,741
I'm trying to run my code with a multiprocessing function but mongo keep returning > > "MongoClient opened before fork. Create MongoClient with > connect=False, or create client after forking." > > > I really doesn't understand how i can adapt my code to this. Basically the structure is: ``` db = MongoClient()...
2017/08/06
[ "https://Stackoverflow.com/questions/45530741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3476027/" ]
db.authenticate will have to connect to mongo server and it will try to make a connection. So, even though connect=False is being used, db.authenticate will require a connection to be open. Why don't you create the mongo client instance after fork? That's look like the easiest solution.
Here is how I did it for my problem: ``` import pathos.pools as pp import time import db_access class MultiprocessingTest(object): def __init__(self): pass def test_mp(self): data = [[form,'form_number','client_id'] for form in range(5000)] pool = pp.ProcessPool(4) pool.map(...
21,687,643
I am working on a large scale project that involves giving a python script a first name and getting back a result as to what kind of gender it belongs to. My current program is written in Java and using Jython to interact with a Python script called "sex machine." It works great in most cases and I've tested it with sm...
2014/02/10
[ "https://Stackoverflow.com/questions/21687643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1461393/" ]
I don't know if it helps but this is what I did and it works for me. ``` public static void main(String[] args){ PythonInterpreter pI = new PythonInterpreter(); pI.exec("x = 3"); PyObject result = pI.get("x"); System.out.println(result); } ```
Not sure if you sorted this out, but have an extra apostrophe on ``` d.get_gender('Christinewazonek'') ``` Just like in Java, everything you open you need to close, and in this case you opened a string containing `)\n")` which was not closed. Depending on the interpreter you are using, this can be flagged easily. ...
34,132,484
i have a large string like ``` res = ["FAV_VENUE_CITY_NAME == 'Mumbai' & EVENT_GENRE == 'KIDS' & count_EVENT_GENRE >= 1", "FAV_VENUE_CITY_NAME == 'Mumbai' & EVENT_GENRE == 'FANTASY' & count_EVENT_GENRE >= 1", "FAV_VENUE_CITY_NAME =='Mumbai' & EVENT_GENRE == 'FESTIVAL' & count_EVENT_GENRE >= 1", "FAV_VENUE_CITY_NAME =...
2015/12/07
[ "https://Stackoverflow.com/questions/34132484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5533254/" ]
The latest d.ts file now has the component method. Update yours with `tsd update -o`
We had a kinda similar issue earlier today and it was to do with using Angular 1.5. Beta 1 which doesn't contain the component function. To fix it we had to upgrade to Angular 1.5 Beta 2 which does contain the component functon.
70,921,901
I have been trying to fetch the metadata from a KDB+ Database using python, basically, I installed a library called **`qpython`** and using this library we connect and query the KDB+ Database. I want to store the metadata for all the appropriate cols for a table/view in KDB+ Database using python. I am unable to separ...
2022/01/31
[ "https://Stackoverflow.com/questions/70921901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12553730/" ]
The metadata that you have returned from kdb is correct but is being displayed in python as a kdb dictionary format which I agree is not very useful. If you pass the pandas=True flag into your qconnection call then qPython will parse kdb datastructures, such as a table into pandas data structures or sensible python ty...
In the meantime, I have checked quite a bit of KBD documentation and found that the metadata provides the following as the output. You can see that here [kdb metadata](https://code.kx.com/q4m3/8_Tables/) `c | t f a` c-columns t-symbol f-foreign key association a-attributes associated with the column We can access th...
62,503,638
I have a data frame as shown below. which is a sales data of two health care product starting from December 2016 to November 2018. ``` product price sale_date discount A 50 2016-12-01 5 A 50 2017-01-03 4 B 200 2016-12-24 10 A ...
2020/06/21
[ "https://Stackoverflow.com/questions/62503638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8901845/" ]
The problem with the first query is that it returns no rows if there is 1 row (or less) in the table. It looks like they consider that an empty resultset is not the correct answer in this case. Instead, they always want one row as a result that contains a `null` value (which indicates the absence of the Nth salary in ...
This query: ``` SELECT DISTINCT Salary AS SecondHighestSalary -- (DISTINCT is really not needed) FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1 ``` in case the table has only 1 row, does not return `null`. It returns nothing (no rows). But when it is placed inside another query as a derived column: ``` S...
35,700,781
I have a small Python app that produces a form, the user enters some strings in and it collects them as an array and adds (or tries to) that array as a value of a key in Google's Memcache. This is the script: ``` import webapp2 from google.appengine.api import memcache MAIN_PAGE_HTML = """\ <html> <body> <form...
2016/02/29
[ "https://Stackoverflow.com/questions/35700781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3136727/" ]
Given that you work with system logs and their format is known and stable, my approach would be something like: * identify a set of keywords (either common, or one per log) * for each log, iterate line by line * once keywords match, add the relevant information from each line in e.g. a dictionary You could use shell ...
If you want ot use tool then you can use ELK(Elastic,Logstash and kibana). if no then you have to read first log file then apply regex according to your requirment.
35,700,781
I have a small Python app that produces a form, the user enters some strings in and it collects them as an array and adds (or tries to) that array as a value of a key in Google's Memcache. This is the script: ``` import webapp2 from google.appengine.api import memcache MAIN_PAGE_HTML = """\ <html> <body> <form...
2016/02/29
[ "https://Stackoverflow.com/questions/35700781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3136727/" ]
Given that you work with system logs and their format is known and stable, my approach would be something like: * identify a set of keywords (either common, or one per log) * for each log, iterate line by line * once keywords match, add the relevant information from each line in e.g. a dictionary You could use shell ...
In case you might be interested in extracting some data and save it to a `.txt` file, the following sample code might be helpful: ``` import re import sys import os.path expDate = '2018-11-27' expTime = '11-21-09' infile = r"/home/xenial/Datasets/CIVIT/Nov_27/rover/NMND17420010S_"+expDate+"_"+expTime+".LOG" keep_ph...
36,913,153
When I do this calculation `2*(5+5/(3+3))*3` I get 30 in Python (2.7). But what it seems is that `2*(5+5/(3+3))*3`is equal to `35`. Can someone tell me why python gives me the answer of 30 instead of 35? I've tested with JavaScript, Lua and Mac Calculator and they show me 35. Why does Python calculate wrong? <http://...
2016/04/28
[ "https://Stackoverflow.com/questions/36913153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4841229/" ]
This happens because of the piece `5/(3 + 3)` which evalautes to 0. You need to use either of them as float.
Always assume it's an issue with something you're doing rather than with an entire coding language! It works fine for me in Python shell. 35 is the expected answer and 35 is what we get! Most likely something on your end or a mis-type / you've miss-commented something out. This is from copy pasting your code above. e...
52,958,847
I am trying to calculate a DTW distance matrix which will look into 150,000 time series each having between 13 to 24 observations - that is the produced distance matrix will be a list of the size of approximately (150,000 x 150,000)/2= 11,250,000,000. I am running this over a big data cluster of the size of 200GB but ...
2018/10/23
[ "https://Stackoverflow.com/questions/52958847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6235045/" ]
Thanks to @KacperMadej for this solution on [github](https://github.com/highcharts/highcharts-angular/issues/89). To load a theme simply add the following somewhere in the project: ```js import * as Highcharts from 'highcharts'; require('highcharts/themes/dark-blue')(Highcharts); ```
The theme factory is now the default export of `highcharts/themes/<theme-name>` so this will work: ``` import * as Highcharts from 'highcharts'; import theme from 'highcharts/themes/dark-unica'; theme(Highcharts); ```
52,958,847
I am trying to calculate a DTW distance matrix which will look into 150,000 time series each having between 13 to 24 observations - that is the produced distance matrix will be a list of the size of approximately (150,000 x 150,000)/2= 11,250,000,000. I am running this over a big data cluster of the size of 200GB but ...
2018/10/23
[ "https://Stackoverflow.com/questions/52958847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6235045/" ]
Thanks to @KacperMadej for this solution on [github](https://github.com/highcharts/highcharts-angular/issues/89). To load a theme simply add the following somewhere in the project: ```js import * as Highcharts from 'highcharts'; require('highcharts/themes/dark-blue')(Highcharts); ```
I found another way to do this. The versions I am using are ``` "angular-highcharts": "^12.0.0", "highcharts": "^9.3.0", ``` In your module imports you have ``` import {ChartModule, HIGHCHARTS_MODULES} from "angular-highcharts"; import theme from 'highcharts/themes/dark-blue'; ``` And in the providers section you...
52,958,847
I am trying to calculate a DTW distance matrix which will look into 150,000 time series each having between 13 to 24 observations - that is the produced distance matrix will be a list of the size of approximately (150,000 x 150,000)/2= 11,250,000,000. I am running this over a big data cluster of the size of 200GB but ...
2018/10/23
[ "https://Stackoverflow.com/questions/52958847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6235045/" ]
The theme factory is now the default export of `highcharts/themes/<theme-name>` so this will work: ``` import * as Highcharts from 'highcharts'; import theme from 'highcharts/themes/dark-unica'; theme(Highcharts); ```
I found another way to do this. The versions I am using are ``` "angular-highcharts": "^12.0.0", "highcharts": "^9.3.0", ``` In your module imports you have ``` import {ChartModule, HIGHCHARTS_MODULES} from "angular-highcharts"; import theme from 'highcharts/themes/dark-blue'; ``` And in the providers section you...
32,492,183
When I run `python manage.py runserver`, everything starts out fine, but then I get a `SystemCheckError` stating that Pillow is not installed; however, Pillow is definitely installed on this machine. This is the error I receive: > > Performing system checks... > > > Unhandled exception in thread started by Traceba...
2015/09/10
[ "https://Stackoverflow.com/questions/32492183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4501444/" ]
This should do the trick: `/(?| (")((?:\\"|[^"])+)\1 | (')((?:\\'|[^'])+)\1 )/xg` [Demo](https://regex101.com/r/cG3qR3/2) --------------------------------------- BTW: [regex101.com](https://regex101.com/r/rX4rL7/1) is a great resource to use (which is where I got the regex above) Update ------ The first one I post...
Maybe I read your question incorrectly but this is working for me `/\".+\"/gm` <https://regex101.com/r/wF0yN4/1>
32,492,183
When I run `python manage.py runserver`, everything starts out fine, but then I get a `SystemCheckError` stating that Pillow is not installed; however, Pillow is definitely installed on this machine. This is the error I receive: > > Performing system checks... > > > Unhandled exception in thread started by Traceba...
2015/09/10
[ "https://Stackoverflow.com/questions/32492183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4501444/" ]
Simplest way would be to do: ``` /"[^"]*?"/g ``` This will return an array with `"hi"`, `"abc\nddk"` and `"gh"` and you can do something like `piece.replace(/"/g, "")` on individual pieces to get rid of the `"`. If you don't like that then rather than do a `match` you can do a [search and don't replace](http://ejohn...
This should do the trick: `/(?| (")((?:\\"|[^"])+)\1 | (')((?:\\'|[^'])+)\1 )/xg` [Demo](https://regex101.com/r/cG3qR3/2) --------------------------------------- BTW: [regex101.com](https://regex101.com/r/rX4rL7/1) is a great resource to use (which is where I got the regex above) Update ------ The first one I post...
32,492,183
When I run `python manage.py runserver`, everything starts out fine, but then I get a `SystemCheckError` stating that Pillow is not installed; however, Pillow is definitely installed on this machine. This is the error I receive: > > Performing system checks... > > > Unhandled exception in thread started by Traceba...
2015/09/10
[ "https://Stackoverflow.com/questions/32492183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4501444/" ]
Simplest way would be to do: ``` /"[^"]*?"/g ``` This will return an array with `"hi"`, `"abc\nddk"` and `"gh"` and you can do something like `piece.replace(/"/g, "")` on individual pieces to get rid of the `"`. If you don't like that then rather than do a `match` you can do a [search and don't replace](http://ejohn...
Maybe I read your question incorrectly but this is working for me `/\".+\"/gm` <https://regex101.com/r/wF0yN4/1>
18,802,563
**Background**: My Python program handles relatively large quantities of data, which can be generated in-program, or imported. The data is then processed, and during one of these processes, the data is deliberately copied and then manipulated, cleaned for duplicates and then returned to the program for further use. T...
2013/09/14
[ "https://Stackoverflow.com/questions/18802563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1644700/" ]
You really want to use NumPy if you're handling large quantities of data. Here's how I would do it : Import NumPy : ``` import numpy as np ``` Generate 8000 high-precision floats (128-bits will be enough for your purposes, but note that I'm converting the 64-bits output of `random` to 128 just to fake it. Use your ...
Why don't you create a dict that maps the 14dp values to the corresponding full 16dp values: ``` d = collections.defaultdict(list) for x in l: d[round(x, 14)].append(x) ``` Now if you just want "unique" (by your definition) values, you can do ``` unique = [v[0] for v in d.values()] ```
67,541,366
I have a set of filter objects, which inherit the properties of a `Filter` base class ``` class Filter(): def __init__(self): self.filterList = [] def __add__(self,f): self.filterList += f.filterList def match(self, entry): for f in self.filterList: if not f(entry): ...
2021/05/14
[ "https://Stackoverflow.com/questions/67541366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4177926/" ]
I would go for something like this: ```py class Filter: def __init__(self, filter: Callable[[Any], bool]): self.filter = filter def __add__(self, added: Filter): return OrFilter(self, added) def __mul__(self, mult: Filter): return AndFilter(self, mult) def __invert__(self): return Filter(lam...
Thanks, @njzk2 for the solution. In my code I used `|` and `&`. To be backwards compatible I also kept the `.match()` instead of using `__call__()` and also added the `__add__` again. ``` class Filter: def __init__(self, filter: Callable[[Any], bool]): self.filter = filter def __or__(self, ored: Filte...
48,490,272
I'm trying to launch Safari with Selenium in python with all my sessions logged in (e.g. gmail) so I don't have to login manually. The easy solution would be to launch safari with the default user profile, but I can't find documentation on how to do this. ``` from selenium import webdriver driver = webdriver.Safari()...
2018/01/28
[ "https://Stackoverflow.com/questions/48490272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2827060/" ]
In the "[Creating Builds](https://dojotoolkit.org/documentation/tutorials/1.10/build/)" tutorial, it says: > > You might be asking yourself "if we build everything we need into a > layer, why do we worry about the rest of the modules?" If you were to > only keep the layer files and not have the rest of the modules ...
I don't know if this is a useful but I have a situation where I am creating a layer which loads from a completely different location to the core dojo app. This means that I actually don't need the `dojo`, `dijit` and `dojox` to be in my build. I was having the issue of all files being bundled in to my location whethe...
57,978,333
While training a job on a SageMaker instance using H2o AutoML a message "This H2OFrame is empty" has come up after running the code, what should I do to fix the problem? ``` /opt/ml/input/config/hyperparameters.json All Parameters: {'nfolds': '5', 'training': "{'classification': 'true', 'target': 'y'}", 'max_runtime_s...
2019/09/17
[ "https://Stackoverflow.com/questions/57978333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8836963/" ]
thanks @Marcel Mendes Reis for following up on your solution in the comments. I will repost here for others to easily find: *I realized the issue was due to the max\_runtime. When I trained the model with more time I didn't have the problem.*
Doing some tests I realized that the problem was because of the max\_runtime, I believe I didn't allow the model to train enough.
72,122,475
I have a custom field in employee module in Odoo to display the age. That field is calculated from birtday field ``` for record in self: today = datetime.date.today() record['x_studio_age_2'] = today.year - record['birthday'].year - ((today.month, today.day) < (record['birthday'].month, record['birthday'].day...
2022/05/05
[ "https://Stackoverflow.com/questions/72122475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7259851/" ]
I think you should do someting like that. `False` means value is not set. ```py today = datetime.date.today() for record in self: if record['birthday']: record['x_studio_age_2'] = today.year - record['birthday'].year - ((today.month, today.day) < (record['birthday'].month, record['birthday'].day)) else...
you have to check the birthday first , because if it's not set it will return false value as boolean
64,583,022
I imported a csv file with the variable “HEIGHT” which has 10 values. ``` HEIGHT 62 58 72 63 66 62 63 62 62 67 ``` I want to use numpy and numpy only to count the number of times the value ‘62’ does not occur. The answer should be 6. ``` import numpy import csv with open(‘measurements.csv’),’r’) as f: rows=f.readli...
2020/10/28
[ "https://Stackoverflow.com/questions/64583022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14458035/" ]
Using numpy you can do: ``` data = np.array([62, 58, 72, 63, 66, 62, 63, 62, 62, 67]) (data != 62).sum() ``` That is, `data != 62` will make a numpy Boolean array, and `sum` will add these up, with `True` as `1`, giving the total count.
If you want to use *numpy and numpy only*, Load the file using numpy: ``` dataset = np.loadtxt('measurements.csv', delimiter=',') ``` Seems like the height variable is in the 3rd column (index *2*). When you use `loadtxt`, you'll get a 2D array that looks like a table. You need the column with index 2, and you can ...
2,896,179
Can anyone help me out in fitting a gamma distribution in python? Well, I've got some data : X and Y coordinates, and I want to find the gamma parameters that fit this distribution... In the [Scipy doc](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gamma.html#scipy.stats.gamma), it turns out that a fi...
2010/05/24
[ "https://Stackoverflow.com/questions/2896179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348838/" ]
Generate some gamma data: ``` import scipy.stats as stats alpha = 5 loc = 100.5 beta = 22 data = stats.gamma.rvs(alpha, loc=loc, scale=beta, size=10000) print(data) # [ 202.36035683 297.23906376 249.53831795 ..., 271.85204096 180.75026301 # 364.60240242] ``` Here we fit the data to the gamma distributi...
If you want a long example including a discussion about estimating or fixing the support of the distribution, then you can find it in <https://github.com/scipy/scipy/issues/1359> and the linked mailing list message. Preliminary support to fix parameters, such as location, during fit has been added to the trunk versio...
2,896,179
Can anyone help me out in fitting a gamma distribution in python? Well, I've got some data : X and Y coordinates, and I want to find the gamma parameters that fit this distribution... In the [Scipy doc](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gamma.html#scipy.stats.gamma), it turns out that a fi...
2010/05/24
[ "https://Stackoverflow.com/questions/2896179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348838/" ]
Generate some gamma data: ``` import scipy.stats as stats alpha = 5 loc = 100.5 beta = 22 data = stats.gamma.rvs(alpha, loc=loc, scale=beta, size=10000) print(data) # [ 202.36035683 297.23906376 249.53831795 ..., 271.85204096 180.75026301 # 364.60240242] ``` Here we fit the data to the gamma distributi...
I was unsatisfied with the ss.gamma.rvs-function as it can generate negative numbers, something the gamma-distribution is supposed not to have. So I fitted the sample through expected value = mean(data) and variance = var(data) (see wikipedia for details) and wrote a function that can yield random samples of a gamma di...
2,896,179
Can anyone help me out in fitting a gamma distribution in python? Well, I've got some data : X and Y coordinates, and I want to find the gamma parameters that fit this distribution... In the [Scipy doc](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gamma.html#scipy.stats.gamma), it turns out that a fi...
2010/05/24
[ "https://Stackoverflow.com/questions/2896179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348838/" ]
Generate some gamma data: ``` import scipy.stats as stats alpha = 5 loc = 100.5 beta = 22 data = stats.gamma.rvs(alpha, loc=loc, scale=beta, size=10000) print(data) # [ 202.36035683 297.23906376 249.53831795 ..., 271.85204096 180.75026301 # 364.60240242] ``` Here we fit the data to the gamma distributi...
1): the "data" variable could be in the format of a python list or tuple, or a numpy.ndarray, which could be obtained by using: ``` data=numpy.array(data) ``` where the 2nd data in the above line should be a list or a tuple, containing your data. 2: the "parameter" variable is a first guess you could optionally pro...
2,896,179
Can anyone help me out in fitting a gamma distribution in python? Well, I've got some data : X and Y coordinates, and I want to find the gamma parameters that fit this distribution... In the [Scipy doc](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gamma.html#scipy.stats.gamma), it turns out that a fi...
2010/05/24
[ "https://Stackoverflow.com/questions/2896179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348838/" ]
Generate some gamma data: ``` import scipy.stats as stats alpha = 5 loc = 100.5 beta = 22 data = stats.gamma.rvs(alpha, loc=loc, scale=beta, size=10000) print(data) # [ 202.36035683 297.23906376 249.53831795 ..., 271.85204096 180.75026301 # 364.60240242] ``` Here we fit the data to the gamma distributi...
[OpenTURNS](http://www.openturns.org/) has a simple way to do this with the `GammaFactory` class. First, let's generate a sample: ``` import openturns as ot gammaDistribution = ot.Gamma() sample = gammaDistribution.getSample(100) ``` Then fit a Gamma to it: ``` distribution = ot.GammaFactory().build(sample) ``` ...
2,896,179
Can anyone help me out in fitting a gamma distribution in python? Well, I've got some data : X and Y coordinates, and I want to find the gamma parameters that fit this distribution... In the [Scipy doc](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gamma.html#scipy.stats.gamma), it turns out that a fi...
2010/05/24
[ "https://Stackoverflow.com/questions/2896179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348838/" ]
I was unsatisfied with the ss.gamma.rvs-function as it can generate negative numbers, something the gamma-distribution is supposed not to have. So I fitted the sample through expected value = mean(data) and variance = var(data) (see wikipedia for details) and wrote a function that can yield random samples of a gamma di...
If you want a long example including a discussion about estimating or fixing the support of the distribution, then you can find it in <https://github.com/scipy/scipy/issues/1359> and the linked mailing list message. Preliminary support to fix parameters, such as location, during fit has been added to the trunk versio...
2,896,179
Can anyone help me out in fitting a gamma distribution in python? Well, I've got some data : X and Y coordinates, and I want to find the gamma parameters that fit this distribution... In the [Scipy doc](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gamma.html#scipy.stats.gamma), it turns out that a fi...
2010/05/24
[ "https://Stackoverflow.com/questions/2896179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348838/" ]
If you want a long example including a discussion about estimating or fixing the support of the distribution, then you can find it in <https://github.com/scipy/scipy/issues/1359> and the linked mailing list message. Preliminary support to fix parameters, such as location, during fit has been added to the trunk versio...
1): the "data" variable could be in the format of a python list or tuple, or a numpy.ndarray, which could be obtained by using: ``` data=numpy.array(data) ``` where the 2nd data in the above line should be a list or a tuple, containing your data. 2: the "parameter" variable is a first guess you could optionally pro...
2,896,179
Can anyone help me out in fitting a gamma distribution in python? Well, I've got some data : X and Y coordinates, and I want to find the gamma parameters that fit this distribution... In the [Scipy doc](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gamma.html#scipy.stats.gamma), it turns out that a fi...
2010/05/24
[ "https://Stackoverflow.com/questions/2896179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348838/" ]
If you want a long example including a discussion about estimating or fixing the support of the distribution, then you can find it in <https://github.com/scipy/scipy/issues/1359> and the linked mailing list message. Preliminary support to fix parameters, such as location, during fit has been added to the trunk versio...
[OpenTURNS](http://www.openturns.org/) has a simple way to do this with the `GammaFactory` class. First, let's generate a sample: ``` import openturns as ot gammaDistribution = ot.Gamma() sample = gammaDistribution.getSample(100) ``` Then fit a Gamma to it: ``` distribution = ot.GammaFactory().build(sample) ``` ...
2,896,179
Can anyone help me out in fitting a gamma distribution in python? Well, I've got some data : X and Y coordinates, and I want to find the gamma parameters that fit this distribution... In the [Scipy doc](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gamma.html#scipy.stats.gamma), it turns out that a fi...
2010/05/24
[ "https://Stackoverflow.com/questions/2896179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348838/" ]
I was unsatisfied with the ss.gamma.rvs-function as it can generate negative numbers, something the gamma-distribution is supposed not to have. So I fitted the sample through expected value = mean(data) and variance = var(data) (see wikipedia for details) and wrote a function that can yield random samples of a gamma di...
1): the "data" variable could be in the format of a python list or tuple, or a numpy.ndarray, which could be obtained by using: ``` data=numpy.array(data) ``` where the 2nd data in the above line should be a list or a tuple, containing your data. 2: the "parameter" variable is a first guess you could optionally pro...
2,896,179
Can anyone help me out in fitting a gamma distribution in python? Well, I've got some data : X and Y coordinates, and I want to find the gamma parameters that fit this distribution... In the [Scipy doc](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gamma.html#scipy.stats.gamma), it turns out that a fi...
2010/05/24
[ "https://Stackoverflow.com/questions/2896179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348838/" ]
I was unsatisfied with the ss.gamma.rvs-function as it can generate negative numbers, something the gamma-distribution is supposed not to have. So I fitted the sample through expected value = mean(data) and variance = var(data) (see wikipedia for details) and wrote a function that can yield random samples of a gamma di...
[OpenTURNS](http://www.openturns.org/) has a simple way to do this with the `GammaFactory` class. First, let's generate a sample: ``` import openturns as ot gammaDistribution = ot.Gamma() sample = gammaDistribution.getSample(100) ``` Then fit a Gamma to it: ``` distribution = ot.GammaFactory().build(sample) ``` ...
2,896,179
Can anyone help me out in fitting a gamma distribution in python? Well, I've got some data : X and Y coordinates, and I want to find the gamma parameters that fit this distribution... In the [Scipy doc](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gamma.html#scipy.stats.gamma), it turns out that a fi...
2010/05/24
[ "https://Stackoverflow.com/questions/2896179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348838/" ]
[OpenTURNS](http://www.openturns.org/) has a simple way to do this with the `GammaFactory` class. First, let's generate a sample: ``` import openturns as ot gammaDistribution = ot.Gamma() sample = gammaDistribution.getSample(100) ``` Then fit a Gamma to it: ``` distribution = ot.GammaFactory().build(sample) ``` ...
1): the "data" variable could be in the format of a python list or tuple, or a numpy.ndarray, which could be obtained by using: ``` data=numpy.array(data) ``` where the 2nd data in the above line should be a list or a tuple, containing your data. 2: the "parameter" variable is a first guess you could optionally pro...
59,273,273
I am attempting to open a serial connection to a usb device using PySerial, and with the following code I am getting the following error: ``` import serial ser = serial.Serial('/dev/tty.usbserial-EN270425') ``` ``` File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/serial/serialpos...
2019/12/10
[ "https://Stackoverflow.com/questions/59273273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11313162/" ]
This is an interesting problem, for which I believe there is no standard function yet. This is not a huge problem because the hash itself contains an identifier telling us which hash algorithm was used. The important thing to note here is that `PASSWORD_DEFAULT` is a **constant**. Constants do not change. To figure o...
***Edit*** As of PHP 7.4.3 you can continue using `PASSWORD_DEFAULT === PASSWORD_BCRYPT` *<https://3v4l.org/nN4Qi>* --- You don't actually have to use `password_hash` twice. A better and faster way is to provide an already hashed value with `Bcrypt` and check it against `PASSWORD_DEFAULT` with [password\_needs\_re...
48,238,171
I'm getting string data into my python code.Some time data is coming with an extra "and" or " or for example ``` Tom and Mark and ``` in this case I need to remove the last "and" & final outcome will look like ``` Tom and Mark ``` But when data will come like this ``` Harry and John ``` Then I will consider t...
2018/01/13
[ "https://Stackoverflow.com/questions/48238171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9184713/" ]
``` [2, 4] [4, -3, -4, 4] ``` Sorted: `[2, 4] [-4, -3, 4, 4]` ``` qs are negative, p is positive: 2 + 4 + 2 + 3 = sum(4, 3) + 2*2 qs are larger than p: 4 - 2 + 4 - 2 = sum(4, 4) - 2*2 qs are negative, p is positive: 4 + 4 + 4 + 3 = sum(4, 3) + 2*4 qs are equal to p: 4 - 4 + 4 - 4 = 0 qs are smaller than p (not i...
It may or may not be more efficient to add or subtract the (unmodified) difference depending on sign instead of ("unconditionally") "adding `abs()`". I'd expect a contemporary compiler, even JIT, to detect the equivalence, though. ``` ! Sum of Absolute Differences between every pair of elements of two arrays; INTEG...
12,797,274
I've just installed Python 2.7 on windows along with IPython. I'm used to running IPython from within Emacs on Linux, e.g. ``` M-x shell ``` Then type '`ipython`' at the prompt. This works fine under Linux, but under Windows it hangs after printing the IPython banner text, i.e. it looks like it's working, but then...
2012/10/09
[ "https://Stackoverflow.com/questions/12797274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1041868/" ]
In Windows it won't work as easily, and it's very annoying. First, make sure you have installed pyreadline. Next, I have got it working with a bat file that is in my system path containing: ``` [ipython.bat] @python.exe -i C:\devel\Python\2.7-bin\Scripts\ipython.py --pylab %* ``` Next get python-mode.el and delete...
I wish I had seen this post a while ago. My experiences with running python, ipython from within Emacs are the following: I tried a number of options (Using python(x,y)-2.7.3.0 on Windows 7) Using ipython.el: It still works, provided that you change ipython-command. I do not recommend this, since you loose some func...
12,797,274
I've just installed Python 2.7 on windows along with IPython. I'm used to running IPython from within Emacs on Linux, e.g. ``` M-x shell ``` Then type '`ipython`' at the prompt. This works fine under Linux, but under Windows it hangs after printing the IPython banner text, i.e. it looks like it's working, but then...
2012/10/09
[ "https://Stackoverflow.com/questions/12797274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1041868/" ]
In Windows it won't work as easily, and it's very annoying. First, make sure you have installed pyreadline. Next, I have got it working with a bat file that is in my system path containing: ``` [ipython.bat] @python.exe -i C:\devel\Python\2.7-bin\Scripts\ipython.py --pylab %* ``` Next get python-mode.el and delete...
Using `python -i` or `ipython -i` instead of `python` or `ipython` worked for me (it gets me the prompt in Emacs, instead of hanging indefinitely). From python --help : > > -i : inspect interactively after running script; forces a prompt even > if stdin does not appear to be a terminal; also PYTHONINSPECT=x > > >...
44,123,641
I am using the python libraries from the Assistant SDK for speech recognition via gRPC. I have the speech recognized and returned as a string calling the method `resp.result.spoken_request_text` from `\googlesamples\assistant\__main__.py` and I have the answer as an audio stream from the assistant API with the method `...
2017/05/22
[ "https://Stackoverflow.com/questions/44123641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3415195/" ]
Currently (Assistant SDK Developer Preview 1), there is no direct way to do this. You can probably feed the audio stream into a Speech-to-Text system, but that really starts getting silly. Speaking to the engineers on this subject while at Google I/O, they indicated that there are some technical complications on their...
Update: for > > google.assistant.embedded.v1alpha2 > > > the assistant SDK includes the field `supplemental_display_text` > > which is meant to extract the assistant response as text which aids > the user's understanding > > > or to be displayed on screens. Still making the text available to the develope...
36,911,421
If a class contains two constructors that take in different types of arguments as shown here: ``` public class Planet { public double xxPos; //its current x position public double yyPos; //its current y position public double xxVel; //its current veolicity in the x direction public double yyVel; //its curr...
2016/04/28
[ "https://Stackoverflow.com/questions/36911421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5249753/" ]
> > 1) How does another class with a main that calls this class determine > which constructor to use? > > > Compiler follows same process as overloaded method for static binding by checking unique method signature. To know about method signature [see this](https://docs.oracle.com/javase/tutorial/java/javaOO/metho...
### 1) How does another class with a main that calls this class determine which constructor to use? Classes don't determine anything, the programmer do, and he does it by placing the appropriate parameters. For example, if you have 2 constructors `public Test (int i)`and `public Test()`, when you call `new Test(5)` it...