qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 29 22k | response_k stringlengths 26 13.4k | __index_level_0__ int64 0 17.8k |
|---|---|---|---|---|---|---|
28,506,726 | I am new to the `subprocess` module in python.
The documentation provided this example:
```
>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'
```
What I tried is:
```
>>> import subprocess
>>> subprocess.check_output(["cd", "../tests", "ls"])
/usr/bin/cd: line 4: cd: ../tests: No such file o... | 2015/02/13 | [
"https://Stackoverflow.com/questions/28506726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815710/"
] | The relative path to the `tests` directory depends on where the script is being run from. I would suggest calling `subprocess.check_output(["pwd"])` to check where you are.
Also you can't combine two commands in the same call like in your attempt with `["cd", "../tests", "python", "printy.py"]`. You'll need to make tw... | You are missing a argument here I think.
Here a snippet from the only python script I ever wrote:
```
#!/usr/local/bin/python
from subprocess import call
...
call( "rm " + backupFolder + "*.bz2", shell=True )
```
Please note the `shell=True` in the end of that call. | 7,466 |
63,030,306 | I have the below python snippet
```py
@click.argument('file',type=click.Path(exists=True))
```
The above command read from a file in the below format
```sh
python3 code.py file.txt
```
The same file is processed using a function
```py
def get_domains(domain_names_file):
with open(domain_names_file) as f:
... | 2020/07/22 | [
"https://Stackoverflow.com/questions/63030306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8474328/"
] | `click.argument` by default creates arguments that are read from the command line:
```
@click.argument('file')
```
This should create an argument that is read from the command line and made available in the `file` argument.
See the docs & examples [here](https://pocoo-click.readthedocs.io/en/latest/arguments/) | You may use `argparse`:
```
import argparse
# set up the different arguments
parser = argparse.ArgumentParser(description='Some nasty description here.')
parser.add_argument("--domain", help="Domain: www.some-domain.com", required=True)
args = parser.parse_args()
print(args.domain)
```
And you invoke it via
```... | 7,471 |
60,527,883 | I have a dataset of 284 features I am trying to impute using scikit-learn, however I get an error where the number of features changes to 283:
```
imputer = SimpleImputer(missing_values = np.nan, strategy = "mean")
imputer = imputer.fit(data.iloc[:,0:284])
df[:,0:284] = imputer.transform(df[:,0:284])
X = MinMaxScaler(... | 2020/03/04 | [
"https://Stackoverflow.com/questions/60527883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8831033/"
] | This could happen if you have a feature without any values, from <https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html>:
'Columns which only contained missing values at fit are discarded upon transform if strategy is not “constant”'.
You can tell if this is indeed the problem by using a h... | I was dealing with the same situation and i got my solution by adding this transformation before the SimpleImputer mean strategy
```
imputer = SimpleImputer(strategy = 'constant', fill_value = 0)
df_prepared_to_mean_or_anything_else = imputer.fit_transform(previous_df)
```
What does it do? Fills everything missing w... | 7,473 |
69,011,571 | Which function was used for the following plot in R?
At least it looks like a predefined function to me.
Edit: Okay it seems to be Stata according Claudio.
New question:
Is there anything comparable in python/R to get this output?
How to calculate Coef.? What kind of coefficient is this?
[![enter image description h... | 2021/09/01 | [
"https://Stackoverflow.com/questions/69011571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15870842/"
] | You can simply switch over `status` inside the body of your view and assign the correct `String` and `foregroundColor` to your `Text` inside each `case.
```
struct StatusView: View {
let status: Status
var body: some View {
switch status {
case .accepted:
Text("accepted")
... | Here is an updated and refactored answer based on **David** answer, with this way you do not need that `ststusColor` function anymore and you can access the **colorValue** every where in your project instead of last answer that was accessible only inside `StatusView`.
```
struct StatusView: View {
let status: Sta... | 7,474 |
5,373,474 | I'm trying to use argparse to parse the command line arguments for a program I'm working on. Essentially, I need to support multiple positional arguments spread within the optional arguments, but cannot get argparse to work in this situation. In the actual program, I'm using a custom action (I need to store a snapshot ... | 2011/03/21 | [
"https://Stackoverflow.com/questions/5373474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/668807/"
] | You can't interleave the switches (i.e. `-a` and `-b`) with the positional arguments (i.e. fileone, filetwo and filethree) in this way. The switches must appear before or after the positional arguments, not in-between.
Also, in order to have multiple positional arguments, you need to specify the `nargs` parameter to `... | The 'append' action makes more sense with an optional:
```
parser.add_argument('-i', '--input',action='append')
parser.parse_args(['-i','fileone', '-a', '-i','filetwo', '-b', '-i','filethree'])
```
You can interleave optionals with separate positionals ('input1 -a input2 -b input3'), but you cannot interleave option... | 7,475 |
2,604,917 | I'm trying to make a program so that I can run it through the command line with the following format:
```
./myProgram
```
I made it executable and put `#!/usr/bin/env python` in the header, but it's giving me the following error.
```
env: python\r: No such file or directory
```
However, when I run "python myProg... | 2010/04/09 | [
"https://Stackoverflow.com/questions/2604917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305105/"
] | Your line endings are wrong. Use `dos2unix` to fix them. | `dos2unix filename.py` or inside vim issue the command `:set fileformat=unix` and save. | 7,480 |
16,903,416 | I've used:
```
data = DataReader("yhoo", "yahoo", datetime.datetime(2000, 1, 1),
datetime.datetime.today())
```
in pandas (python) to get history data of yahoo, but it cannot show today's price (the market has not yet closed) how can I resolve such problem, thanks in advance. | 2013/06/03 | [
"https://Stackoverflow.com/questions/16903416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/857130/"
] | ```
import pandas
import pandas.io.data
import datetime
import urllib2
import csv
YAHOO_TODAY="http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sd1ohgl1vl1"
def get_quote_today(symbol):
response = urllib2.urlopen(YAHOO_TODAY % symbol)
reader = csv.reader(response, delimiter=",", quotechar='"')
for ro... | The simplest way to extract Indian stock price data into Python is to use the nsepy library.
In case you do not have the nsepy library do the following:
```
pip install nsepy
```
The following code allows you to extract HDFC stock price for 10 years.
```
from nsepy import get_history
from datetime import date
dfc=... | 7,483 |
2,040,616 | When I run my python script I get the following warning
```
DeprecationWarning: the sets module is deprecated
```
How do I fix this? | 2010/01/11 | [
"https://Stackoverflow.com/questions/2040616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247873/"
] | Stop using the `sets` module, or switch to an older version of python where it's not deprecated.
According to [pep-004](http://www.python.org/dev/peps/pep-0004/), `sets` is deprecated as of v2.6, replaced by the built-in [`set` and `frozenset` types](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset... | You don't need to import the `sets` module to use them, they're in the builtin namespace. | 7,493 |
5,118,608 | I'm novice in python and got a problem in which I would appreciate some help.
The problem in short:
1. ask for a string
2. check if all letter in a predefined list
3. if any letter is not in the list then ask for a new string, otherwise go to next step
4. ask for a second string
5. check again whether the second strin... | 2011/02/25 | [
"https://Stackoverflow.com/questions/5118608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/634333/"
] | I suggest you start here: <http://docs.python.org/tutorial/introduction.html#first-steps-towards-programming>
And continue to next chapter: <http://docs.python.org/tutorial/controlflow.html> | You have a couple of options, you could use iteration, or recursion. For this kind of problem I would go with iteration. If you don't know what iteration and recursion are, and how they work in Python then you should use the links Kugel suggested. | 7,502 |
52,345,375 | i'm new with python and wants to do the following:
1. search inside text to check if token exists
2. token cannot be substring inside the text - must be "as is" (string11111 is not string1)
```
file = "string11111 aaaaa string1 bbbbb"
token = "string1"
if token in file:
print "NOT yay!"
```
3. token needs to be... | 2018/09/15 | [
"https://Stackoverflow.com/questions/52345375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1596023/"
] | First tokenize your `file` variable
```
tokens = file.split()
```
Then look for your token
```
if token in tokens:
# do your thing
``` | hoping the below solution meets your need -
```
file = "string11111 aaaaa string1 bbbbb"
token = "string1"
token_matched = [file_token for file_token in file.split()[::-1] if token in file_token and len(token) == len(file_token)]
print('Matched tokens (reverse order) - ', token_matched)
if len(token_matched) > 1:
... | 7,505 |
58,603,894 | I am trying to convert the below mentioned json string to python dictionary. I am using python 3's json package for the same. Here is the code that I am using :
```
a = "[{'id': 35, 'name': 'Comedy'}, {'id': 18, 'name': 'Drama'}, {'id': 10751, 'name': 'Family'}, {'id': 10749, 'name': 'Romance'}]"
b = json.loads(json.d... | 2019/10/29 | [
"https://Stackoverflow.com/questions/58603894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4720757/"
] | The json string that you are trying to convert is not properly formatted. Also, you need to only call json.loads to convert string into `dict` or `list`.
The updated code would look like:
```
import json
a = '[{"id": 35, "name": "Comedy"}, {"id": 18, "name": "Drama"}, {"id": 10751, "name": "Family"}, {"id": 10749, "n... | **JSON Array** is enclosed in `[ ]` while **JSON object** is enclosed in `{ }`
>
> The string in `a` is a *json array* so you can change that into a *list* only.
>
>
>
>
Your *key and value should be enclosed with double quotes*, that's the requirement to use json library of python.
>
> `b = json.loads(a)` w... | 7,507 |
44,780,952 | So I'm writing a Python program that reads lines of serial data, and compares them to a dictionary of line codes to figure out which specific lines are being transmitted. I am attempting to use a Regular Expression in order to filter out the extra garbage line serial read string has on it, but I'm having a bit of an is... | 2017/06/27 | [
"https://Stackoverflow.com/questions/44780952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3711832/"
] | Your problem is threefold:
1) your string contains extra `\r` (Carriage Return character) before `\n` (New Line character); this is common in Windows and in network communication protocols; it is probably best to remove any trailing whitespace from your string:
```
regexString = regexString.rstrip()
```
2) as ment... | There are several ways to get rid of the "\r", but first a little analysis of your code :
1. the special charakter for the end is just '$' not '$\' in python.
2. re.sub will substitute the matched pattern with a string ( '' in your case) wich would substitute the string you want to get with an empty string and you are ... | 7,508 |
25,518,623 | I wonder why the python magic method (**str**) always looking for the return statement rather a print method ?
```
class test:
def __init__(self):
print("constructor called")
def __call__(self):
print("callable")
def __str__(self):
return "string method"
obj=test() ## print const... | 2014/08/27 | [
"https://Stackoverflow.com/questions/25518623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2199012/"
] | This is more to enable the conversion of an object into a `str` - your users don't necessary want all that stuff be printed into the terminal whenever they want to do something like
```
text = str(obj_instance)
```
They want `text` to contain the result, not printed out onto the terminal.
Doing it your way, the cod... | Because `__str__()` is used when you `print` the object, so the user is already calling `print` which needs the String that represent the Object - as a variable to pass back to the user's `print`
In the example you provided above, if `__str__` would print you would get:
```
print(obj)
```
translated into:
```
prin... | 7,510 |
56,063,686 | I've just recently switched to PyTorch after getting frustrated in debugging tf and understand that it is equivalent to coding in numpy almost completely. My question is what are the permitted python aspects we can use in a PyTorch model (to be put completely on GPU) eg. if-else has to be implemented as follows in tens... | 2019/05/09 | [
"https://Stackoverflow.com/questions/56063686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7779411/"
] | The problem is that if it can only contain one of those words, then where it doesn't contain one of the keywords the SEARCH function will return an error. Capture that using IFERROR to set errors (values not found) to 0, and then get the MAX to find the position of the word that was found (if any). If no values are fou... | You can use the normally entered function:
```
=AGGREGATE(14,6,SEARCH({"Success","Unknown","Failed"},Q_DTL_GetAll__3[@MESSAGE]),1)
```
Your `SEARCH` is returning an array of values. In the given case:
`{#VALUE!,42,#VALUE!}`
So you need some way of only returning the non-error value. `AGGREGATE` can do that.
This ... | 7,511 |
28,532,672 | I have N 10-dimensional vectors where each element can have value of 0,1 or 2.
For example, `vector v=(0,1,1,2,0,1,2,0,1,1)` is one of the vectors.
Is there an algorithm (preferably in python) that compresses these vectors into a minimum number of Cartesian products. If not perfect solution, is there a algorithm that a... | 2015/02/15 | [
"https://Stackoverflow.com/questions/28532672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4570066/"
] | Another alternative way is using [.one()](http://api.jquery.com/one/) (the handler is executed at most once per element per event type), something like this,
```
$(".done p").one('click', function() {
$(this).parent().attr("class", "item not-done");
$(this).parent().hide().prependTo('.list').fadeIn('.5s');
});
``... | You just need to unbind the click handler, so the following should work:
```
$(".done p").click(function() {
$(this).parent().attr("class", "item not-done");
$(this).parent().hide().prependTo('.list').fadeIn('.5s');
$(this).unbind('click');
});
``` | 7,512 |
39,191,252 | I'm running Spark 1.5.1 in standalone (client) mode using Pyspark. I'm trying to start a job that seems to be memory heavy (in python that is, so that should not be part of the executor-memory setting). I'm testing on a machine with 96 cores and 128 GB of RAM.
I have a master and worker running, started using the star... | 2016/08/28 | [
"https://Stackoverflow.com/questions/39191252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/696992/"
] | Check or set the value for spark.executor.instances. The default is 2, which may explain why you get 2 executors.
Since your server has 96 cores, and you set defaultcores to 40, you only have room for 2 executors since 2\*40 = 80. The remaining 16 cores are insufficient for another executor and the driver also requir... | >
> I expect there to be 1 executor. However, 2 executors are started
>
>
>
I think the one executor you see, it's actually the driver.
So one master, one slave (2 nodes in totals).
You can add to your script these configuration flags:
```
--conf spark.executor.cores=8 <-- will set it 8, you probably wan... | 7,515 |
27,798,829 | I have installed PySide in my Ubuntu 12.04. When I try to use import PySide in the python console I am getting the following error.
```
import PySide
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named PySide
```
My Python Path is :
```
print sys.path ['', '/usr/lib/p... | 2015/01/06 | [
"https://Stackoverflow.com/questions/27798829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2871542/"
] | To use python 3, just follow the instructions here:
<https://wiki.qt.io/PySide_Binaries_Linux>
which in ubuntu 12.04 means just typing one line in the console:
```
sudo apt-get install python3-pyside
``` | The latest build and install instructions for PySide are here:
<http://pyside.readthedocs.org/en/latest/building/linux.html> | 7,516 |
70,922,066 | I am building a docker image to run a flask app, which is named dp-offsets for context. This flask app uses matplotlib. I have been unable to fully install matlplotlib despite including all of the necessary dependencies (i think). The code seems to be erroring on timestamp **791.9**s due to bdist\_wheel. I'm not sure w... | 2022/01/31 | [
"https://Stackoverflow.com/questions/70922066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18075955/"
] | You have to rearrange the whole thing in your required format. To do that you have to access the data to it's specific position. You did something awkward there in your code at the second array base. you should specify your section somewhere else,maybe the next line. To access it you have to write:
```
obj.name //Fo... | Objects are defined like this: {key1: value1, key2: value2}
Keys are the identifiers of your values. When you are assigning section: 'A', section: 'B', section: 'C', you are using the same key, so the previous values are overwritten and only the last is stored. That's why it logs 'C'.
You can try changing the keys or m... | 7,518 |
70,186,395 | I have uploaded my databricks notebooks to a repo and replace %run sentences with import using the new databrick public available features (Repo integration and python import): <https://databricks.com/blog/2021/10/07/databricks-repos-is-now-generally-available.html>
But its seems its not working
I already activate th... | 2021/12/01 | [
"https://Stackoverflow.com/questions/70186395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1075163/"
] | You can use a hierarchical query and `CONNECT_BY_ROOT`.
Either starting at the root of the hierarchy and working down:
```sql
SELECT id,
CONNECT_BY_ROOT(id) AS root_id
FROM entry
WHERE id IN (6, 3)
START WITH parent_id IS NULL
CONNECT BY PRIOR id = parent_id;
```
Or, from the entry back up to the root:
`... | You can use recursive CTE to walk the graph and find the initial parent. For example:
```
with
n (starting_id, current_id, parent_id, v) as (
select id, id, parent_id, 0 from entry where id in (6, 3)
union all
select n.starting_id, e.id, e.parent_id, n.v - 1
from n
join entry e on e.id = n.parent_id
)
select ... | 7,519 |
18,541,648 | I have a table in a database which contains query statements in the columns. I need to update this. Is there any way I can update this It seems to be giving me an error:
```
UPDATE Items
SET Query = 'SELECT isnull((sum(OrigDocAmt) ),0) amount from AP where Acct in (1234) and Status='O' and Doc in ('CK') {SLLocCode}'
... | 2013/08/30 | [
"https://Stackoverflow.com/questions/18541648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2684009/"
] | You need to use 2 single quotes ('') around each literal value
```
'SELECT isnull((sum(OrigDocAmt) ),0) amount from AP where Acct in (1234) and Status=''O'' and Doc in (''CK'') {SLLocCode}'
``` | You need to escape the single quotes in the query string. In SQL Server, you just double the single quotes:
```
UPDATE Items
SET Query = 'SELECT isnull((sum(OrigDocAmt) ),0) amount from AP where Acct in (1234) and Status=''O'' and Doc in (''CK'') {SLLocCode}'
WHERE ID = '111';
``` | 7,520 |
49,781,303 | I'm trying to write in a microsoft azure jupyter python notebook and I am receiving an error when I try to import the Tweepy module.
Please take a look at the simple code below and let me know your thoughts. Thank you. I'm working on a chromebook if that helps, but I'm not sure it's relevant.
```
import tweepy as tw... | 2018/04/11 | [
"https://Stackoverflow.com/questions/49781303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9631959/"
] | From the [Azure Notebooks docs](https://notebooks.azure.com/help/jupyter-notebooks/package-installation/python):
>
> The simplest way to install packages is to do it from within a Jupyter Python notebook. Inside of the notebook your path will be setup to have both pip and conda on it pointing to the proper version of... | I had the same error when I was trying to use tweepy. You can try using these commands instead:
`from tweepy import OAuthHandler from tweepy import API from tweepy import Cursor` | 7,522 |
46,509,906 | This code is supposed to find the number which is biggest and then it should print out how many is there, but for some reason this commented if statement doesn't work.
```
#!/bin/python3
import sys
def birthdayCakeCandles(n, ar):
j=1
b=0
f=0
maxn=0
for f in range(0,n-1,1):
b=ar[f]
#... | 2017/10/01 | [
"https://Stackoverflow.com/questions/46509906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6659439/"
] | I found the **almost** perfect working answer in [Levi Fuller's blog](https://medium.com/@levifuller/how-to-deploy-an-angular-cli-application-built-on-asp-net-1fa03c0ca365).
You can get it working with a minor change: unlike what Levi states, you really need **only a single** npm task
1. set up the **npm task**
* by ... | There isn’t the build template that you use directly, the template is convenient to use, you need to modify it per to detail requirement.
Refer to these steps:
1. Go to build page of team project (e.g. `https://XXX.visualstudio.com/[teamproject]/_build`)
2. Click +New button to create a build definition with ASP.NET ... | 7,523 |
31,234,170 | So I am a bit new to Java and Eclipse. I am more used to python. Using IDLE in python I am able to run my program from it's file and and then continue to use the variables. For example, if I have all the code written out defining a function, in idle I can just write it there.
```
x = foo()
print x
```
However, in Ja... | 2015/07/05 | [
"https://Stackoverflow.com/questions/31234170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4967646/"
] | Java is a compiled language, python is a scripting language. You could use scala, or jython (or another scripting language) to get the behavior you want. It's also possible to use a [*Scrapbook page*](http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftask-create_scrapbook_page.htm) in e... | Your environment is one that sounds like its a python based environment. in this case you are storing the variables into your IDE's runtime variable pool. thats why you can later go and act on a variable you set up. in eclipse when you run your program you are launching a new instance of java that is disconnected (from... | 7,524 |
399,991 | When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file.
So I have this .py file that reads like:
```
starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
```
Then I execute the file and get the data. Since the program is all on my machin... | 2008/12/30 | [
"https://Stackoverflow.com/questions/399991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46634/"
] | ```
vinko@mithril$ more a.py
def foo(a):
print a
vinko@mithril$ more b.py
import a
import inspect
a.foo(89)
print inspect.getsource(a.foo)
vinko@mithril$ python b.py
89
def foo(a):
print a
``` | Are you asking about this?
```
def writeoptions(directory):
options=""
options+="starting_length=%s%s"%(starting_length,os.linesep)
options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep)
options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep)
options+="def pippo(a,b):%s" % ... | 7,525 |
51,007,893 | I have a homework to draw a spiral(from inside to outside) in python with turtle, but I cant think of a way to do that, beside what I did its need to be like this:
[](https://i.stack.imgur.com/UQCW8.gif)
I tried to do it like that, but its not workin... | 2018/06/24 | [
"https://Stackoverflow.com/questions/51007893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7528938/"
] | As described in this link : [Create Deep Links](https://developer.android.com/training/app-links/deep-linking)
You should add this in your manifest :
```
<activity
android:name="com.example.android.GizmosActivity"
android:label="@string/title_gizmos" >
<intent-filter android:label="@string/filter_view_htt... | Yes it is possible by handling adding state parms in your url and then redirecting to play store from your server side code.
eg - your app generates url which points to some user profile -
<https://www.yourSocialNewtwork.com/profile/sandeshDahake>
Step 1 - Create a deep link in your app with intent filter. This w... | 7,532 |
70,431,040 | I think the title gives the general idea of what I am looking for, but to be more specific I will give an example with code.
So let's say I have a Python class with a few required position variables that also takes an arbitrary number of keyword arguments. The class has many data members, and some of them will be defi... | 2021/12/21 | [
"https://Stackoverflow.com/questions/70431040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16043632/"
] | It would be easier to find the answer if you explained the purpose for the requirement.
From my experience one common task is to distinguish `authorization_code` and `client_credentials` flow use for the same client, but that's easy: the second one does not contain user information (`sub` and `sid` claims).
Also do... | One option is to have different client definitions for the different flows and then use a [ClientClaim](https://docs.duendesoftware.com/identityserver/v5/fundamentals/claims/#client-claims) to indicate what type of client it is:
To set the client claims in the client definition just set it like:
```
ClientClaimsPrefi... | 7,533 |
10,062,967 | Is there an idiomatic way of encoding and decoding a string in Clojure as hexadecimal? Example from Python:
```python
'Clojure'.encode('hex')
# ⇒ '436c6f6a757265'
'436c6f6a757265'.decode('hex')
# ⇒ 'Clojure'
```
To show some effort on my part:
```clj
(defn hexify [s]
(apply str
(map #(format "%02x" (int %)) s... | 2012/04/08 | [
"https://Stackoverflow.com/questions/10062967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165806/"
] | Your implementation(s) don't work for non-ascii characters,
```clj
(defn hexify [s]
(apply str
(map #(format "%02x" (int %)) s)))
(defn unhexify [hex]
(apply str
(map
(fn [[x y]] (char (Integer/parseInt (str x y) 16)))
(partition 2 hex))))
(= "\u2195" (unhexify(hexify "\u2195")))
false ;... | I believe your `unhexify` function is as idiomatic as it can be. However, `hexify` can be written in a simpler way:
```
(defn hexify [s]
(format "%x" (new java.math.BigInteger (.getBytes s))))
``` | 7,534 |
57,318,921 | I'm trying to use xtensor-python example found [here](https://xtensor-python.readthedocs.io/en/latest/).
I have xtensor-python, pybind11, and xtensor installed and also created a CMakeLists.txt.
from /build I ran.
$ cmake ..
$ make
and it builds without errors.
My CMakeLists.txt looks like this.
```
cmake_minimu... | 2019/08/02 | [
"https://Stackoverflow.com/questions/57318921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11395552/"
] | This is actually really simple and done in a few lines
```c#
public GameObject prefab;
public float radius;
public float amount;
// Start is called before the first frame update
private void Start()
{
var angle = 0f;
for (var i = 0; i <= amount; i++)
{
var y = Mathf.Sin(Mathf.Deg2Rad * angle) * ... | Ok, so this is more of a math problem then anything else really. Now assuming that you are not a total beginner with Unity I will not write you code for your solution, but just generaly describe it.
First thing you need to be inputed is radius, this will determine how far away from the center of the circle should your... | 7,538 |
48,825,312 | I am new to python,
I have written test cases for my class ,
I am using
`python -m pytest --cov=azuread_api` to get code coverage.
I am getting coverage on the console as [](https://i.stack.imgur.com/iKRNP.png)
How do I get which lines are missed b... | 2018/02/16 | [
"https://Stackoverflow.com/questions/48825312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3556028/"
] | If you check the [documentation for reporting](https://pytest-cov.readthedocs.io/en/latest/reporting.html) in pytest-cov, you can see how to manipulate the report and generate extra versions.
For example, adding the option `--cov-report term-missing` you'll get the missing lines printed in the terminal.
A more user f... | In addition to the [answer from Ignacio](https://stackoverflow.com/a/48825483/149900), one can also set [`show_missing = true`](https://coverage.readthedocs.io/en/latest/config.html#config-report-show-missing) in `.coveragerc`, as pytest-cov reads that config file as well. | 7,539 |
30,987,825 | I have a list of lists in python. I want to group similar lists together. That is, if first three elements of each list are the same then those three lists should go in one group. For eg
```
[["a", "b", "c", 1, 2],
["d", "f", "g", 8, 9],
["a", "b", "c", 3, 4],
["d","f", "g", 3, 4],
["a", "b", "c", 5, 6]]
```
I w... | 2015/06/22 | [
"https://Stackoverflow.com/questions/30987825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4378672/"
] | You can use [`itertools.groupby`](https://docs.python.org/3.4/library/itertools.html#itertools.groupby) :
```
>>> A=[["a", "b", "c", 1, 2],
... ["d", "f", "g", 8, 9],
... ["a", "b", "c", 3, 4],
... ["d","f", "g", 3, 4],
... ["a", "b", "c", 5, 6]]
>>> from operator import itemgetter
>>> [list(g) for _,g in ... | You don't need to sort, you can group in a dict using a tuple of the first three elements from each list as the key:
```
from collections import OrderedDict
l=[
["a", "b", "c", 1, 2],
["d", "f", "g", 8, 9],
["a", "b", "c", 3, 4],
["d","f", "g", 3, 4],
["a", "b", "c", 5, 6]
]
od = Ordere... | 7,540 |
24,272,228 | I am using ArgParse for giving commandline parameters in Python.
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--quality", type=int,help="enter some quality limit")
args = parser.parse_args()
qual=args.quality
if args.quality:
qual=0
$ python a.py --quality
a.py: error: argument --q... | 2014/06/17 | [
"https://Stackoverflow.com/questions/24272228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2596951/"
] | Use `nargs='?'` to allow `--quality` to be used with 0 or 1 value supplied. Use `const=0` to handle `script.py --quality` without a value supplied. Use `default=0` to handle bare calls to `script.py` (without `--quality` supplied).
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--quality",... | Have a loot at <https://docs.python.org/2/howto/argparse.html#id1>. Simply add the argument `default` to your add\_argument call.
`parser.add_argument("--quality", type=int, default=0, nargs='?', help="enter some quality limit")`
If you want to use `--quality` as a flag you should use `action="store_true"`. This will... | 7,541 |
4,858,733 | Python has this magic [`__call__`](http://docs.python.org/reference/datamodel.html#object.__call__) method that gets called when the object is called like a function. Does C# support something similar?
---
Specifically, I was hoping for a way to use delegates and objects interchangeably. Trying to design an API where... | 2011/02/01 | [
"https://Stackoverflow.com/questions/4858733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/65387/"
] | Sure, if you inherit from [DynamicObject](http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx). I think you're after [TryInvoke](http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.tryinvoke.aspx) which executes on `obj(...)`, but there are several other method you can override to... | I bow to Simon Svensson - who shows a way to do it if you inherit from DynamicObject - for a more strait forward non dynamic point of view:
Sorry but no - but there are types of objects that can be called - delegates for instance.
```
Func<int, int> myDelagate = x=>x*2;
int four = myDelagate(2)
```
There is a... | 7,544 |
21,377,656 | Why is the self.year twice? I am having trouble to find out the logic of the line. Can some one help me with this?
```
return (self.year and self.year == date.year or True)
```
I am going through <http://www.openp2p.com/pub/a/python/2004/12/02/tdd_pyunit.html> and encountered the line ... And of course I have no pro... | 2014/01/27 | [
"https://Stackoverflow.com/questions/21377656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2770850/"
] | Assuming these are parallel arrays (the first entry in `eenhedennamen` uses the first entry in `value`), you can loop through with jQuery's [`$.each`](http://api.jquery.com/jQuery.each), which gives you the index and the entry for each entry, and build the object from the loop.
```
var obj = {};
$.each(eenhedennamen, ... | ```
var eenhedennamen = [ 'unit1', 'unit2', 'unit3' ];
var value = [ 1, 2, 3 ];
var z = new Array();
for ( var i = 0; i < eenhedennamen.length; i++) {
z[eenhedennamen[i]]=value[i];
}
```
The previous answer is better. | 7,546 |
33,106,871 | I have a batch script runs python script continuously in a loop.
```
:start
python log_capture.py > log.txt
goto start
```
I want to print the output of each iteration in a .txt file. I am using following command get output from log\_capture.py to a log.txt file.
```
python log_capture.py >log.txt
```
But in the... | 2015/10/13 | [
"https://Stackoverflow.com/questions/33106871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5138377/"
] | I have used this service in the past and I noticed today that text messages sent were not received. Looking into this a bit further it seems something happened due to folks using this service to spam... and it's not working at present. Not sure what the future holds...
See: [issue listed on textbelt](https://github.com... | 2-563-567-890 doesn't look like a valid US phone number, so I would double-check that. There is also an international endpoint, `/intl`, but it tends to be less reliable. | 7,548 |
20,307,590 | I am trying to make an HTTP POST request using javascript and connecting it to an onclick event.
For example, if someone clicks on a button then make a HTTP POST request to `http://www.example.com/?test=test1&test2=test2`. It just needs to hit the url and can close the connection.
I've messed around in python and go... | 2013/12/01 | [
"https://Stackoverflow.com/questions/20307590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2159019/"
] | You need to use `XMLHttpRequest` (see [MDN](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)).
```
var xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.onload = // something
document.getElementById("your_button's_ID").addEventListener("click",
function() {xhr.send(data)},
false
);
... | If you can include the JQuery library, then I'd suggest you look in to the jQuery .ajax() method (<http://api.jquery.com/jQuery.ajax/>):
```
$.ajax("http://www.example.com/", {
type: 'POST',
data: {
test: 'test1',
test2: 'test2'
}
})
``` | 7,549 |
17,793,742 | I want to profile python code on Widnows 7. I would like to use something a little more user friendly than the raw dump of cProfile. In that search I found the GUI RunSnakeRun, but I cannot find a way to download RunSnakeRun on Windows. Is it possible to use RunSnakeRun on windows or what other tools could I use?
**Ed... | 2013/07/22 | [
"https://Stackoverflow.com/questions/17793742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417902/"
] | The standard solution is to use cProfile (which is in the standard library) and then open the profiles in RunSnakeRun:
<http://www.vrplumber.com/programming/runsnakerun/>
cProfile, however only profiles at the per-functions level. If you want line by line profiling try line profiler:
<https://github.com/rkern/line_pro... | I installed runsnake following these [installation instructions](http://www.vrplumber.com/programming/runsnakerun/).
The step `python runsnake.py profile.pfl` failed because the installation step (`easy_install SquareMap RunSnakeRun`) did not create a file `runsnake.py`.
For me (on Ubuntu), the installation step cre... | 7,550 |
72,452,208 | I'm trying to make a publisher for a Ublox GPS sensor, but I'm getting this ROS error:
>
> ubuntu@fieldrover:~/field-rover-gps/gps/gps\_pkg$ cd
> ~/field-rover-gps/gps/gps\_pkg/ && colcon build && . install/setup.bash
> && ros2 run gps\_pkg gps
>
>
> Starting >>> gps\_pkg Finished <<< gps\_pkg [2.98s]
>
>
> Summa... | 2022/05/31 | [
"https://Stackoverflow.com/questions/72452208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12497264/"
] | As it already has been pointed outed both in the comments and the answer by *@AbhinavMathur*, in order to improve performance you need to implement [*Doubly linked list*](https://en.wikipedia.org/wiki/Doubly_linked_list) data structure.
Note that it's mandatory to create your *own implementation* that will maintain a ... | Using an array, you're setting the "removed" elements as `-1`; repeatedly skipping them in each traversal causes the performance penalty.
Instead of an array, use a [doubly linked list](https://www.geeksforgeeks.org/doubly-linked-list/). Each removal can be easily done in `O(1)` time, and each left/right operation wou... | 7,552 |
52,787,147 | I want to use CTR mode in DES algorithm in python by using PyCryptodome package. My code presented at the end of this post. However I got this error: "TypeError: Impossible to create a safe nonce for short block sizes". It is worth to mention that, this code work well for AES algorithm but it does not work for DES, DES... | 2018/10/12 | [
"https://Stackoverflow.com/questions/52787147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9982452/"
] | The library [defines the nonce](https://www.pycryptodome.org/en/latest/src/cipher/classic.html#ctr-mode)
as that part of the counter block that is not incremented.
Since the block is only 64 bits long, it is hard to securely define how long that nonce should be,
given the danger of wraparound (if you encrypt a lot of ... | ```
bs = DES.block_size
plen = bs - len(plaintext) % bs
padding = [plen] * plen
padding = pack('b' * plen, *padding)
key = get_random_bytes(8)
nonce = Random.get_random_bytes(4)
ctr = Counter.new(32, prefix=nonce)
cipher = DES.new(key, DES.MODE_CTR,counter=ctr)
ciphertext = cipher.encrypt(plaintext+padding)
``` | 7,553 |
52,416,852 | I am trying to use your project named dask-spark proposed by Matthew Rocklin.
When adding the dask-spark into my project, I have a problem: Waiting for workers as shown in the following figure.
Here, I run two worker nodes (dask) as dask-worker tcp://ubuntu8:8786 and tcp://ubuntu9:8786 and run two worker nodes (spar... | 2018/09/20 | [
"https://Stackoverflow.com/questions/52416852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have revised the program in core.py, as:
```
def spark_to_dask(sc, loop=None):
""" Launch a Dask cluster from a Spark Context
"""
cluster = LocalCluster(n_workers=None, loop=loop, threads_per_worker=None)
rdd = sc.parallelize(range(1000))
address = cluster.scheduler.address
```
Following which,... | As noted in the README of the project, dask-spark is not mature. It was a weekend project and I do not recommend its use.
Instead, I recommend launching Dask directly using one of the mechanisms described here: <http://dask.pydata.org/en/latest/setup.html>
If you have to use Mesos then I'm not sure I'll be of much h... | 7,554 |
59,697,566 | My input is a list, say `l`
It can either contain 4 or 5 elements. I want to assign it to 5 variables , say `a`, `b`, `c`, `d` and `e`.
If the list has only 4 elements then the third variable (`c`) should be `None`.
If python had an increment (++) operator I could do something like this.
```
l = [4 or 5 string inp... | 2020/01/11 | [
"https://Stackoverflow.com/questions/59697566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11316253/"
] | You're trying to use a C solution because you're unfamiliar with Python's tools. Using unpacking is much cleaner than trying to emulate `++`:
```
a, b, *c, d, e = l
c = c[0] if c else None
```
The `*c` target receives a list of all elements of `l` that weren't unpacked into the other targets. If this list is nonempt... | I can't see that you really need to be incrementing at all since you have fixed positions for each variable subject to your c condition.
```
l = [4 or 5 string inputs]
a = l[0]
b = l[1]
if len(l) > 4:
c = l[2]
d = l[3]
e = l[4]
else:
c = None
d = l[2]
e = l[3]
``` | 7,555 |
66,593,382 | To run `pytest` within GitHub Actions, I have to pass some `secrets` for Python running environ.
e.g.,
```
- name: Test env vars for python
run: python -c 'import os;print(os.environ)'
env:
TEST_ENV: 'hello world'
TEST_SECRET: ${{ secrets.MY_TOKEN }}
```
However, the output is as follows,
```
... | 2021/03/12 | [
"https://Stackoverflow.com/questions/66593382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/482899/"
] | There are three types of secrets within GitHub Actions.
1. Organization secrets
2. Repository secrets
3. Environment secrets
To access Environment secrets, you have to [referencing an environment](https://docs.github.com/en/actions/reference/environments#referencing-an-environment) in your job. (Thanks to @riQQ)
[![... | You try the things below:
```
- name: Test env vars for python
run: TEST_SECRET=${{ secrets.MY_TOKEN }} python -c 'import os;print(os.environ['TEST_SECRET'])
```
This will pass `${{ secrets.MY_TOKEN }}` directly as an environment variable to the python process and not share with other processes. Then you can u... | 7,560 |
12,763,015 | Sorry if my title is not correct. Below is the explanation of what i'm looking for.
I've coded a small GUI game (let say a snake game) in python, and I want it to be run on Linux machine. I can run this program by just run command "python snake.py" in the terminal.
However, I want to combine all my .py files into one... | 2012/10/06 | [
"https://Stackoverflow.com/questions/12763015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1058861/"
] | You can use [Freeze](http://wiki.python.org/moin/Freeze) for Unix, or [py2exe](http://wiki.python.org/moin/Py2Exe) for Windows.
[cx\_freeze](http://cx-freeze.sourceforge.net/), [PyInstaller](http://www.pyinstaller.org/), [bbfreeze](http://www.jroller.com/alessiopace/entry/python_standalone_executables_with_bbfreeze) ... | If you only want it to run on a Linux machine, using Python eggs is the simplest way.
python snake.egg will try to execute the **main**.py inside the egg.
Python eggs are meant to be packages, and basically is a zip file with metadata files included. | 7,561 |
57,035,263 | I'm trying RSA encrypt text with JSEncrypt(javascript) and decrypt with python crypto (python3.7). Most of the time, it works. But sometimes, python cannot decrypt.
```js
const encrypt = new JSEncrypt()
encrypt.setPublicKey(publicKey)
encrypt.encrypt(data)
```
```py
from base64 import b64decode
from Crypto.Cipher im... | 2019/07/15 | [
"https://Stackoverflow.com/questions/57035263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11784926/"
] | If the ciphertext is Base64-decoded, the reason becomes clearer: The ciphertext doesn't have the length of the modulus (128 byte), but only 127 byte, i.e. it isn't padded to the length of the modulus with leading `0x00` values. This ciphertext is invalid (see [RFC8017](https://www.rfc-editor.org/rfc/rfc8017#section-7.2... | Thanks to Topaco, it solved.
```
from base64 import b64decode, b16decode
from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5
from Crypto.PublicKey import RSA
crypt_text = \
"R247QGAFEeSW1wwXQuNf/cm/K/tnW5xwXLb5MuHW6/Fr8SRklM0n6Rmj07TgFwApeN72j/avXAvpoR70U92ehOJsDnnZguYN4u2bMXHDyTNmAXuJw9xPm59bSGcvgRm1X+V0Zq... | 7,562 |
54,813,438 | I am looking to extract content from [a page](https://app.updateimpact.com/treeof/org.json4s/json4s-native_2.11/3.5.2) that is requires a list node to be selected. I have retrieve the page html using python and Selenium. Passing the page source to BS4 I can parse out the content that I am looking for using
```
ope... | 2019/02/21 | [
"https://Stackoverflow.com/questions/54813438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2033214/"
] | ```
=Unique(A:B)
```
should be enough to return non-duplicate rows
<https://support.google.com/docs/answer/3093198?hl=en>
[](https://i.stack.imgur.com/w77Gm.png)
You can also use Sortn:
```
=sortn(A:B,9E+99,2,1,true,2,true)
``` | ```
=QUERY(QUERY(A1:B,
"select A, B, count(A)
group by A, B", 1),
"select Col1, Col2
where Col1 is not null", 1)
```
[](https://i.stack.imgur.com/oQyB2.png) | 7,563 |
31,695,910 | I'm parsing the US Patent XML files (downloaded from [Google patent dumps](https://www.google.com/googlebooks/uspto-patents-redbook.html)) using Python and Beautifulsoup; parsed data is exported to MYSQL database.
Each year's data contains close to 200-300K patents - which means parsing 200-300K xml files.
The server... | 2015/07/29 | [
"https://Stackoverflow.com/questions/31695910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2404998/"
] | Here is a [tutorial on multi-threading](http://www.tutorialspoint.com/python/python_multithreading.htm), because currently that code will run on 1 thread, 1 core.
Remove all try/except statements and handle the code properly. Exceptions are expensive.
Run a [profiler](http://docs.python.org/2/library/profile.html) to... | So, you're doing two things wrong. First, you're using BeautifulSoup, which is slow, and second, you're using a "find" call, which is also slow.
As a first cut, look at `lxml`'s [ability to pre-compile xpath queries](https://lxml.de/xpathxslt.html) (Look at the heading "The Xpath class). That will give you a **huge** ... | 7,566 |
11,707,151 | allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly.
i have seen questions regarding this particular problem on here before - but i hav... | 2012/07/29 | [
"https://Stackoverflow.com/questions/11707151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1560582/"
] | Check out regular expressions, python's `re` module (http://docs.python.org/library/re.html). For example,
```
import re
first = str(input())
second = str(input())
regex = first[:-1] + '(?=' + first[-1] + ')'
print(len(re.findall(regex, second)))
``` | **Answer**
```
needle=input()
haystack=input()
counter=0
for i in range(0,len(haystack)):
if(haystack[i:len(needle)+i]!=needle):
continue
counter=counter+1
print(counter)
``` | 7,567 |
53,844,589 | I wrote the below python script in sublime text3 on executing it ( ctrl + B ) it is not giving any result.
Step 1:
Code:
```
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.__init__(self)
```
Step 2:
```
ctrl + B
```
Step 3:
Result:
***Repl Closed*** | 2018/12/19 | [
"https://Stackoverflow.com/questions/53844589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9983752/"
] | That's because you're only declaring a class, not instantiating it.
Your variable avenger1 exists within the **init** function, therefore it isn't being called. Indentation matters in python.
Try this:
```
class Avengers(object):
def __init__(self):
print('hello')
if __name__ == "__main__":
avenger1 = Avenger... | You are not instantiating the class. Try something like:
```
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.__init__(self)
avengers = Avengers() # Initiates the class
```
When you instantiate a class like this, it will execute the `__init__` function for that... | 7,577 |
21,369,607 | I am trying to convert the following python extract to C
```
tvip = "192.168.0.3"
myip = "192.168.0.7"
mymac = "00-0c-29-3e-b1-4f"
appstring = "iphone..iapp.samsung"
tvappstring = "iphone.UE55C8000.iapp.samsung"
remotename = "Python Samsung Remote"
ipencoded = base64.b64encode(myip)
macencoded = base64.b64encode(mym... | 2014/01/26 | [
"https://Stackoverflow.com/questions/21369607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126280/"
] | `fragment` lexer rules can only be used by other lexer rules: these will never become a token on their own. Therefor, you cannot use `fragment` rules in parser rules. | The `fragment` is not the root cause.
First, try to reproduce your errors:
------------------------------------
When compiling your Test.g4, it will appear warnings below:
```
warning(156): Test.g4:11:21: invalid escape sequence \"
warning(156): Test.g4:123:59: invalid escape sequence \"
warning(146): Test.g4:11:0: ... | 7,582 |
59,415,503 | I am trying to run the object detection API in tensorflow following this tutorial / accompanying code: <https://gilberttanner.com/blog/creating-your-own-objectdetector>
When I type `python2 generate_tfrecord.py --csv_input=images_train.csv --image_dir=images\train --output_path=train.record` into the terminal, I see a... | 2019/12/19 | [
"https://Stackoverflow.com/questions/59415503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11756066/"
] | What you have here is an async function that performs an async operation, where that operation does *not* use promises. This means that you need to setup a function that manages and returns a promise explicitly. You don't need the `async` keyword here, since you want to explicitly `return` a `Promise` that you create, ... | Basically, you are trying to write an `async` function without having anything in that function to await. You use async/await when there is some asynchronous-ness in the code, while in yours, there isn't.
This is an example that might be useful:
```
const getItemsAsync = async () => {
const res = await DoSomethin... | 7,583 |
63,664,484 | I have to create a function called read\_data that takes a filename as its only parameter. This function must then open the file with the given name and return a dictionary where the keys are the location names in the file and the values are a list of the readings.
The result of the first function works and displays:
... | 2020/08/31 | [
"https://Stackoverflow.com/questions/63664484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14001036/"
] | Given:
```
di={'Monday': [67 , 43], 'Tuesday': [14, 26], 'Wednesday': [68, 44], 'Thursday':[15, 35],'Friday':[70, 31],'Saturday':[34, 39],'Sunday':[22, 18]}
```
You can do:
```
>>> {k:sum(v)/len(v) for k,v in di.items()}
{'Monday': 55.0, 'Tuesday': 20.0, 'Wednesday': 56.0, 'Thursday': 25.0, 'Friday': 50.5, 'Saturda... | You were close but had at least one problem. One was this:
`Friday’:[50.50],’Saturday’;[36.50],’Sunday’: [22, 18]`
Notice ’Saturday’ is followed by a semicolon, not a colon. That's in both examples. Also, notice your text changes color from red to blue. That usually (this case included) means that you switched from s... | 7,584 |
46,078,088 | I want to upload an image on Google Cloud Storage from a python script. This is my code:
```
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery
scopes = ['https://www.googleapis.com/auth/devstorage.full_control']
credentials = ServiceAccountCredentials.from_json_k... | 2017/09/06 | [
"https://Stackoverflow.com/questions/46078088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7219743/"
] | If you want to upload your image from file.
```
import os
from google.cloud import storage
def upload_file_to_gcs(bucket_name, local_path, local_file_name, target_key):
try:
client = storage.Client()
bucket = client.bucket(bucket_name)
full_file_path = os.path.join(local_path, local_file_n... | `MediaIoBaseUpload` expects an [`io.Base`](https://docs.python.org/3/library/io.html#io.IOBase)-like object and raises following error:
```
'numpy.ndarray' object has no attribute 'seek'
```
upon receiving a ndarray object. To solve it I am using `TemporaryFile` and `numpy.ndarray().tofile()`
```
from oauth2clien... | 7,585 |
35,144,550 | My ubuntu is 14.04 LTS.
When I install cryptography, the error is:
```
Installing egg-scripts.
uses namespace packages but the distribution does not require setuptools.
Getting distribution for 'cryptography==0.2.1'.
no previously-included directories found matching 'documentation/_build'
zip_safe flag not set; anal... | 2016/02/02 | [
"https://Stackoverflow.com/questions/35144550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2890633/"
] | The answer is on the docs of `cryptography`'s [installation section](https://cryptography.io/en/latest/installation/#building-cryptography-on-linux) which pretty much reflects Angelos' answer:
Quoting it:
>
> For Debian and **Ubuntu**, the following command will ensure that the
> required dependencies are installed... | I had the same problem when pip installing the cryptography module on Ubuntu 14.04. I solved it by installing libffi-dev:
```
apt-get install -y libffi-dev
```
Then I got the following error:
```
build/temp.linux-x86_64-3.4/_openssl.c:431:25: fatal error: openssl/aes.h: No such file or directory
#include <openssl/... | 7,590 |
70,021,042 | ```
import spacy
nlp = spacy.load('en_core_web_sm')
from spacy.lemmatizer import Lemmatizer
from spacy.lang.en import LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES
lemmatizer = Lemmatizer(LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES)
lemmattizer('chunkles', 'NOUN')
```
Can anyone help me? I'm using Version 3 of python | 2021/11/18 | [
"https://Stackoverflow.com/questions/70021042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17447993/"
] | The official document shows that after spacy 3.0, the lemmatizer has become a standalone pipeline component. Therefore, you should install the spacy whose version is smaller than 3.0. The link is as follow: <https://spacy.io/api/lemmatizer> | try:
doc = nlp('chuckles')
doc[0].lemma\_ | 7,593 |
9,345,250 | I have tried:
```
>>> l = [1,2,3]
>>> x = 1
>>> x in l and lambda: print("Foo")
x in l && print "Horray"
^
SyntaxError: invalid syntax
```
A bit of googling revealed that `print` is a statement in `python2` whereas it's a function in `python3`. But, I have tried the above snipped in `python3` and it... | 2012/02/18 | [
"https://Stackoverflow.com/questions/9345250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1218583/"
] | ```
l = [1, 2, 3]
x = 1
if x in l: print "Foo"
```
I'm not being a smart ass, this is the way to do it in **one line**. Or, if you're using Python3:
```
if x in l: print("Foo")
``` | Getting rid of the shortcomings of print as a statement in Python2.x using `from __future__ import print_function` is the first step. Then the following all work:
```
x in l and (lambda: print("yes"))() # what an overkill!
(x in l or print("no")) and print("yes") # note the order, print returns None
print("yes"... | 7,594 |
61,642,246 | What I want to make is angrybirds game.
There is a requirement
1.Draw a rectangle randomly between 100 and 200 in length and length 10 in length.
2. Receive the user inputting the launch speed and the launch angle.
3. Project shells square from origin (0,0).
4. If the shell is hit, we'll end it, or we'll continue from ... | 2020/05/06 | [
"https://Stackoverflow.com/questions/61642246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13483726/"
] | the local declaration has to be like this way,
```
int (*localArr)[M][N]; //pointer to an MxN array
//int * localArr[m][N];//An MxN array of pointer to int
``` | What do you want to achieve? If you just want to print your 2d array then why don't you use this approach?
```
void print(int localArr[M][N]) {
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
cout << localArr[i][j];
}
}
}
```
If there are some constraints then Nithees... | 7,598 |
35,859,927 | For say in terminal I did `cd Desktop` you should know it moves you to that directory, but how do I do that in python but with use Desktop with `raw_input("")` to pick my command? | 2016/03/08 | [
"https://Stackoverflow.com/questions/35859927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Your code structure is very unconventional and I suspect you're rather new to scheme/racket. Your procedure can be written in a much more idiomatic way.
The first criticism I'd probably make about your code is that it makes the assumption that the lists you're unzipping will only have 2 elements each.
* What about un... | It is combining the lists correctly, but it's not combining the correct lists.
Extracting the local definitions makes them testable in isolation:
```
(define (front a)
(if (null? a)
'()
(cons (car (car a)) (unzip (cdr a)))))
(define (back b)
(if (null? b)
'()
(cons (car (cdr (car b))) (un... | 7,600 |
62,678,802 | I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible?
I am assuming the best bet would be to transform the .py file into a .exe file but... | 2020/07/01 | [
"https://Stackoverflow.com/questions/62678802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12512519/"
] | This usually happens when you're opening someone else's project after unzipping it and your current Android Studio Version is older to the version the project was compiled in.
The way to solve it is
1. Go to Help and about to see your android studio version
2. go to File>Project Structure> and set your Android Gradle... | Check the version of Android Studio, or the IDEA Plugin.
For example, Android Studio **4.0** and Android Plugin 10.**4.0** require a 4.0.x version of the Android tools.
Therefore in build.gradle, change e.g. `com.android.tools.build:gradle:4.2.0-beta2"` to `com.android.tools.build:gradle:4.0.2"`.
**Update:**
This d... | 7,601 |
55,125,763 | I'm trying to find the size, *in points*, of some text using Pillow in python. As I understand it, font sizes in points correspond to real physical inches on a target display or surface, with 72 points per inch. When I use Pillow's `textsize` method, I can find the size in pixels of some text rendered at a given font s... | 2019/03/12 | [
"https://Stackoverflow.com/questions/55125763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10686733/"
] | **TL;DR**
There is no implicit pixel density, because the Pillow documentation is incorrect. When you create the font, you are specifying the `size` in *pixels* even though the Pillow documentation says it's in points. It's actually doing all of these operations in pixels.
**More detail**
The Pillow documentation fo... | Image don't have an "implicit" pixel density, they just have different number of pixels. The size of anything measured in pixels will depend on the display device's DPI or dots-per-inch.
For example on a 100 DPI device, 12 pixels would appear to be 12/100 or 0.12 inches long. To convert inches to points, multiply the... | 7,611 |
39,980,658 | I am starting to work with the [Django REST framework](http://www.django-rest-framework.org/) for a mini-reddit project I already developed.
The problem is that I am stuck in this situation:
A `Minisub` is like a subreddit. It has, among others, a field named `managers` which is `ManyToMany` with `User`.
An `Ad` is ... | 2016/10/11 | [
"https://Stackoverflow.com/questions/39980658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2595458/"
] | You may get it out of the serializer this way:
```
class YourModelSeializer(serializers.HyperlinkedModelSerializer):
class Meta:
model=YourModel
def validate_myfield(self):
instance = getattr(self, 'instance', None)
...
``` | I believe that this is a job for the [permissions](http://www.django-rest-framework.org/api-guide/permissions/#permissions), if you are performing CRUD operations for inserting that into a database then u can have a permission class returns `True` if the user is a manager.
a permissions instance has access to the requ... | 7,612 |
33,722,333 | It is very nice and easy to run Python from the command line. Especially for testing purposes.
The only drawback is that after making a change in the script, I have to restart Python, do all the imports over again, create the objects and enter the parameters.
```
$ python
>>> from foo import bar
>>> from package.fil... | 2015/11/15 | [
"https://Stackoverflow.com/questions/33722333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5039579/"
] | You could consider turning your testing into an actual python script. which can be run like this, and then checking the output
```
$ python my_tests.py
```
However, a much better way would be to write some unit tests which you can run in a similar way. <https://docs.python.org/2/library/unittest.html>. The unittest ... | Use IPython with a [notebook](http://jupyter.org/) instead. Much better for interactive computing. | 7,613 |
32,616,406 | I'm writing a python application that allows users to write their own plugins and extend the core functionality I provide -
```
$ tree project_dir/
.
├── application.py
├── plugins
│ ├── __init__.py
│ ├── example_plugin.py
│ ├── plugin1.py
│ ├── plugin2.py
│ └── plugin3
│ ├── sounds
│ │ └── tes... | 2015/09/16 | [
"https://Stackoverflow.com/questions/32616406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2417277/"
] | You can use the `__import__()` builtin to import the plugins, and then include the `register_plugin()` call in either the plugin file `example_plugin.py` or in `__init__.py` if it's a directory.
For example, let's say this is your project structure:
```
./
application.py
plugins_manager.py
plugins/
__init__.py
... | Strictly speaking I'd say there is no way to run code without it being invoked somehow. To do this, the running program can use
```
import importlib
```
so that once you've found the file you can import it with:
```
mod = importlib.import_module(import_name, pkg_name)
```
and if that file provides a known functio... | 7,616 |
50,716,680 | I have a file with contents like this (I don't wish to change the contents of the file in any way):
```
.
.
lines I don't need.
.
.
abc # I know where it starts and the data can be anything, not just abc
efg # I know where it ends.
.
.
lines I don't need.
.
.
```
I know the line numbers (index) from where ... | 2018/06/06 | [
"https://Stackoverflow.com/questions/50716680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6027453/"
] | I **guess** the compiler error that you see is referring to the fact that you are using `listener` into it's own defining context.
Try this for a change:
In UserManager:
```
func allUsers(completion:@escaping ([User])->Void) -> ListenerRegistration? {
return db.collection("users").addSnapshotListener { querySnap... | I think that *getDocument* instead of *addSnapshotListener* is what you are looking for.
Using this method the listener is automatically detached at the end of the request...
It will be something similar to
```
func allUsers(completion:@escaping ([User])->Void) {
db.collection("users").getDocument { querySnapshot, ... | 7,617 |
47,747,516 | I hope i will get help here. I'm writing program who will read and export to txt 'devices live logging events' every two minutes. Everything works fine until i generate exe file. What is more interesting, program works on my enviroment(geckodriver and python libraries installed), but does not work on computers without ... | 2017/12/11 | [
"https://Stackoverflow.com/questions/47747516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9082203/"
] | The problem is that the `deny from all` denies **everything** including the error documents.
But hey, .htaccess files work in cascade, so you can
1. create a subfolder in your web root (assuming your webroot is `/www` - `/www/errordocs`
2. => in there put your ErrorDocuments like 403.html etc.
3. create another `.hta... | yes I can help a Little bit to solve permission issue , I was encountered by same problem , You just need to give permission +777 to your /app
if you have linux machine , go inside your web folder
```
sudo chmod -R +777 /app
```
and do the same to any other folders you write there
and for 403 error I think yo... | 7,618 |
23,006,023 | I'm trying to install pyOpenSSL using pip, python version is 2.7, OS is linux.
After pyOpenSSL installed, when I tried to import the module in python, I got the following error:
```
Python 2.7.5 (default, Jun 27 2013, 03:17:39)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "l... | 2014/04/11 | [
"https://Stackoverflow.com/questions/23006023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/855643/"
] | This is because low version pyopenssl has not defined SSL\_OP\_NO\_TICKET。
clone the latest pyopenssl from <https://github.com/pyca/pyopenssl.git> and install it, then that'll be fine. no thks. | The fix is described here:
<https://github.com/pyca/pyopenssl/issues/130>
Indeed, you can apply it manually (not really recommended, but easy)
Or download archive from github
The link to the fix: <https://github.com/pyca/pyopenssl/commit/e7a6939a22a4290fff7aafe39dd0db85157d5e05>
And the fix applied to SSL.py
```
-OP... | 7,619 |
32,156,008 | I am using Calendar and recieve list of lists of lists of tuples from it
```
calendar.Calendar.yeardays2calendar(calendar.Calendar(), year, 1))
```
Output is:
```
[[[[(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6)], [(5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)], [(12, 0), (13, 1),...
```
I w... | 2015/08/22 | [
"https://Stackoverflow.com/questions/32156008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4386321/"
] | Python has a function to flatten one nesting level. It goes by the unfortunate name `itertools.chain.from_iterable()`. If you apply it three times, it will flatten three levels:
```
import itertools
flatten1 = itertools.chain.from_iterable
flattened_data = flatten1(flatten1(flatten1(your_data)))
for a, b in flattened_... | Try this:
```
def flatten(x):
if isinstance(x, list):
return [a for i in x for a in flatten(i)]
else:
return [x]
```
This answer is similar to this: <https://stackoverflow.com/a/2158522/1628832> but checking for the specific `list` type instead of an iterable.
For optimization, memory effic... | 7,620 |
56,721,424 | I have two pandas columns, both converted to datetime format, and can't subtract one from the other.
```
df['date_listed'] = pd.to_datetime(df['date_listed'], errors='coerce').dt.floor('d')
df['date_unconditional'] = pd.to_datetime(df['date_unconditional'], errors='coerce').dt.floor('d')
print df['date_listed'][:5]
... | 2019/06/23 | [
"https://Stackoverflow.com/questions/56721424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4718221/"
] | You could use [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) and [spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) operations and then map to recombine.
```js
data = [
['Jenny', 'id100... | Try this:
```
function addingRows() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Sheet1');
var rg=sh.getRange(2, 1, sh.getLastRow()-1,sh.getLastColumn());
var vA=rg.getValues();
var vB=[];
for(var i=0;i<vA.length;i++) {
vt=vA[i].slice(3);
for(var j=0;j<vt.length;j++) {
vB.pu... | 7,623 |
4,192,744 | If I enter Baltic characters in textctrl and click button **test1** I have an error
```
"InicodeEncodeError: 'ascii' codec can't encode characters in position 0-3:
ordinal not in range(128)"
```
Button **test2** works fine.
```
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import wx
class MyFra... | 2010/11/16 | [
"https://Stackoverflow.com/questions/4192744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/509289/"
] | The [documentation](http://www.novell.com/documentation/suse91/suselinux-adminguide/html/ch12s03.html) for SUSE Linux provides a good explanation of why Linux is booted with a RAMDisk:
>
> As soon as the Linux kernel has been
> booted and the root file system (/)
> mounted, programs can be run and
> further kernel... | The reason that most Linux distributions use a ramfs (initramfs) when booting, is because its contents can be included in the kernel file, or provided by the bootloader. They are therefore available immediately at boot, without the kernel having to load them from somewhere.
That allows the kernel to run userspace prog... | 7,624 |
62,026,013 | I have created a python script which do birthday wish to a person automatically when birthdate is arrive. I added this script on window start up but it run every time when i start my pc and do birthday wish to person also. I want to run that script only once a day. What should i do? | 2020/05/26 | [
"https://Stackoverflow.com/questions/62026013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12942284/"
] | Try this at the start of the file:
```
import datetime
actualday = datetime.datetime.today().day # get the actual day
actualmonth = datetime.datetime.today().month # get the actual month
bday = 1 # day of birthday
bmonth = 1 # month of birthday
if actualday == bday and actualmonth == bmonth :
# code
```
... | You can run this program when the system boot [How to start a python file while Windows starts?](https://stackoverflow.com/questions/4438020/how-to-start-a-python-file-while-windows-starts)
And after that, you need check the time of when the system started like:
```
import datetime
dayToday = datetime.datetime.today(... | 7,625 |
50,225,903 | I am trying a POC running a python script in a back-end implemented in PHP. The web server is Apache in a Docker container.
This is the PHP code:
```
$command = escapeshellcmd('/usr/local/test/script.py');
$output = shell_exec($command);
echo $output;
```
When I execute the python script using the ... | 2018/05/08 | [
"https://Stackoverflow.com/questions/50225903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4681701/"
] | To start is is incredibly bad practice to have relative paths in *any* scripting environment. Start by rewriting your code to use a full path such as `/usr/local/test/script.py` and `/tmp/testfile.txt`. My guess is your script is attempting to write to a different spot than you think it is.
When you *know* exactly whe... | I believe the problem is that you are trying to write to an existing file in the `/tmp/` directory. Typically `/tmp/` [will have the sticky permission bit set.](https://unix.stackexchange.com/questions/71622/what-are-correct-permissions-for-tmp-i-unintentionally-set-it-all-public-recu) That means that only the owner of... | 7,626 |
73,523,116 | i was wondering how i can get the product dimensions and weight from an amazon page. this is the page: [https://www.amazon.com/Vic-Firth-American-5B-Drumsticks/dp/B0002F73Z8/ref=psdc\_11966431\_t1\_B0064RNNP2?th=1](https://rads.stackoverflow.com/amzn/click/com/B0002F73Z8)
there is a place where it says
item weight: 3.... | 2022/08/29 | [
"https://Stackoverflow.com/questions/73523116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17215378/"
] | What you need to do is first install selenium in your computer.
Then after setting it up you can go to the page and click on inspect.Then you search what you need to scrap after that copy the XPath .
You can Follow [Selenium with Python](https://selenium-python.readthedocs.io/) Docs or watch any tutorial for more detai... | I would advise you look into requests, Beautiful Soup and Selenium. These are useful libraries/tools for web scraping. Also I believe Amazon specifically blocks a lot of scraping requests so you will need to mimic a regular users browser for it to work. | 7,627 |
35,173,118 | I am using httplib in my python code and have following mentioned.
`import httplib
httplib.HTTPConnection.debuglevel = 2`
I do get all the info I need but httplib library is printing it on console.
I do not know any way by which I can get all those logs in a log file and not on console. | 2016/02/03 | [
"https://Stackoverflow.com/questions/35173118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2606665/"
] | If you take a look at the httplib source (<https://hg.python.org/cpython/file/2.7/Lib/httplib.py>) you'll see the debugging is done via print statements, so you can't use logging configuration to intercept the logs, and because print is a statement, you can't monkeypatch it to do your bidding.
You have a few options:
... | Maybe try this:
```
f = open('output.txt','w')
sys.stdout = f
```
Redirecting stdout to a file. | 7,629 |
40,518,865 | I am trying to figure out how to use a barely documented feature of a poorly documented API. I have distilled the chunk of code that is giving me trouble down to this for simplicity:
```
def build_custom_args(args):
custom_args = {}
for key in args:
custom_args.update(key.get())
print(c... | 2016/11/10 | [
"https://Stackoverflow.com/questions/40518865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2197234/"
] | Well... I found this in the github link you have provided
```
class Email(object):
# code...
def get(self):
```
Matter of fact, a lot of those classes have get methods.
Since Python is duck typed, there isn't really a way to determine what object is correct, but you're just building a dictionary, so sho... | AFAIK the only class with a `get` [method that can take zero arguments](https://docs.python.org/3/library/queue.html?highlight=get#queue.Queue.get) is a `Queue`.
Which in your example is probably a `Queue` of `dict`s | 7,630 |
8,159,414 | I'm trying to debug my [DJango Paypal IPN integration](https://stackoverflow.com/questions/8145907/what-might-cause-the-django-ipn-tool-to-fail-when-posting-to-a-django-based-rece) but I'm struggling. The Django dev server reports a 500 error to the console (but no other details) and the IPN test tool reports a 500 err... | 2011/11/16 | [
"https://Stackoverflow.com/questions/8159414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15369/"
] | given that you are running a pre-alpha version of django, I would recomment asking this question on the django user list <https://groups.google.com/group/django-users> | have a look at [django-sentry](http://readthedocs.org/docs/sentry/en/latest/index.html)
it logs 500 errors (also supports regular logging), making the dynamic "orange 500 pages" browsable after the fact. this is especially useful when you never get the original error page, e.g. when using ajax or remote apis like your... | 7,631 |
48,373,718 | I have a spring boot web application without registration page or allowing users to register. I'm manually creating passwords using another web spring application which ones gives me encoded password on request.
Using the below link to generate the encoded password: <http://www.baeldung.com/spring-security-registration... | 2018/01/22 | [
"https://Stackoverflow.com/questions/48373718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1550594/"
] | I was facing the same problem, but the following worked for me:
```
bcrypt.gensalt(rounds = 10, prefix=b"2a")
```
This seems to be in sync with the bean `BCryptPasswordEncoder` in SpringBoot :) | BCrypt is a module in python which can be installed using `pip install bcrypt`.
The equivalent to BCryptPasswordEncoder() would require importing bcrypt as `import bcrypt` and then executing `bcrypt.hashpw(password, bcrypt.gensalt())` to encrypt a password.
Source: <https://pypi.python.org/pypi/bcrypt/3.1.0> | 7,634 |
34,030,599 | Hoping you can help me figure this one out. I'm slogging through the [Heroku 'Getting Started with Python'](https://devcenter.heroku.com/articles/getting-started-with-python#declare-app-dependencies) page where you install the necessary dependencies to run an app locally. It all works well up until the 2nd to last step... | 2015/12/01 | [
"https://Stackoverflow.com/questions/34030599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5266746/"
] | pg\_config is part of postgresql ( <http://www.postgresql.org/docs/8.1/static/app-pgconfig.html> ).
So you need to install postgresql. | ```
brew install postgresql
```
resolves this issue on macOS | 7,635 |
68,565,656 | I'm using Selenium to automate a report but when I download it the last number changes as if it were a sequence for example: 0001849191, 0001849192 and so on. I can't make it keep following the order because if someone else generates the report it can skip a number and python doesn't understand that it followed the seq... | 2021/07/28 | [
"https://Stackoverflow.com/questions/68565656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16541350/"
] | You can use the glob and os module to get the latest file.First import os, glob modules i.e:
```
import os
import glob
```
Then you define path.My example gives path for any ones Download folder.
```
home = os.path.expanduser('~')
path = os.path.join(home, 'Downloads')
```
"\*" is necessary.
```
path_a = path + ... | First off, `'\'` is an invalid string, because `\` is used for escape sequences. `'\\'` would get you a string with a single backslash in it.
But more than that, it's best not to construct paths this way; you should use [os.path.join](https://docs.python.org/3/library/os.path.html#os.path.join) to create paths out of ... | 7,638 |
16,840,554 | What's a pythonic approach for reading a line from a file but not advancing where you are in the file?
For example, if you have a file of
```
cat1
cat2
cat3
```
and you do `file.readline()` you will get `cat1\n` . The next `file.readline()` will return `cat2\n` .
Is there some functionality like `file.some_functi... | 2013/05/30 | [
"https://Stackoverflow.com/questions/16840554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431282/"
] | As far as I know, there's no builtin functionality for this, but such a function is easy to write, since most Python `file` objects support `seek` and `tell` methods for jumping around within a file. So, the process is very simple:
* Find the current position within the file using `tell`.
* Perform a `read` (or `writ... | You could use wrap the file up with [itertools.tee](http://docs.python.org/2/library/itertools.html#itertools.tee) and get back two iterators, bearing in mind the caveats stated in the documentation
For example
```
from itertools import tee
import contextlib
from StringIO import StringIO
s = '''\
cat1
cat2
cat3
'''
... | 7,639 |
68,877,064 | I'm pretty new in python and I'm having trouble doing this double summation.

I already tried using
```
x = sum(sum((math.pow(j, 2) * (k+1)) for k in range(1, M-1)) for j in range(N))
```
and using 2 for loops but nothing seens to work | 2021/08/21 | [
"https://Stackoverflow.com/questions/68877064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16722883/"
] | The solution is incredibly easy -
Instead of using just the relevant part of the Alchemy key:
40Oo3XScVabXXXX8sePUEp9tb90gXXXX
I used the whole URL:
<https://eth-rinkeby.alchemyapi.io/v2/40Oo3XScVabXXXX8sePUEp9tb90gXXXX> | I had the same experience but when using hardhat not truffle.My internet connection was ok,try switching from Git bash to terminal(CMD).Use a completely new terminal avoid Gitbash and powershell. | 7,646 |
63,247,247 | I downloaded pyttsx3 in command prompt
I have a big error
this the code:
```
import pyttsx3
engine = pyttsx3.init()
engine.say("I will speak this text")
engine.runAndWait()
```
output error:
>
>
> >
> >
> > >
> > >
> >
> >
> >
>
>
>
'''
= RESTART: C:\Users\RAMS\AppData\Local\Programs\Python\Python38\te... | 2020/08/04 | [
"https://Stackoverflow.com/questions/63247247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14047733/"
] | Looks like the Vercel docs are currently outdated (AWS SDK V2 instead of V3). You can pass the credentials object to the AWS service when you instantiate it. Use an environment variable that is not reserved by adding the name of your app to it for example.
*.env.local*
```
YOUR_APP_AWS_ACCESS_KEY_ID=[your key]
YOUR_A... | If I'm not mistaken, you want to make `AWS_ACCESS_KEY_ID` into a runtime variable as well. Currently, it is a build time variable, which won't be accessible in your node application.
```
// replace this
env: {
//..others
AWS_ACCESS_KEY_ID: process.env.AWS_ACCESS_KEY_ID
},
// with this
module.exports = {
... | 7,650 |
31,264,522 | I've made a simple combobox in python using Tkinter, I want to retrieve the value selected by the user. After searching, I think I can do this by binding an event of selection and call a function that will use something like box.get(), but this is not working. When the program starts the method is automatically called ... | 2015/07/07 | [
"https://Stackoverflow.com/questions/31264522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5018299/"
] | I've figured out what's wrong in the code.
First, as James said the brackets should be removed when binding justamethod to the combobox.
Second, regarding the type error, this is because justamethod is an event handler, so it should take two parameters, self and event, like this,
```
def justamethod (self, event)... | ```
from tkinter import ttk
from tkinter import messagebox
from tkinter import Tk
root = Tk()
root.geometry("400x400")
#^ width - heghit window :D
cmb = ttk.Combobox(root, width="10", values=("prova","ciao","come","stai"))
#cmb = Combobox
class TableDropDown(ttk.Combobox):
def __init__(self, parent):
se... | 7,652 |
70,461,032 | How do I get a user keyboard input with python and print the name of that key ?
e.g:
>
> user clicked on "SPACE" and output is "SPACE"
> user clicked on "CTRL" and output is "CTRL".
>
>
>
for better understanding i'm using pygame libary. and i built setting controller for my game. its worked fine but i'm able to... | 2021/12/23 | [
"https://Stackoverflow.com/questions/70461032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17408857/"
] | `pygame` provides a function for getting the name of the key pressed:
[`pygame.key.name`](https://www.pygame.org/docs/ref/key.html#pygame.key.name)
And so you can use it to get the name of the key, there is no need to use a dictionary for this:
```py
import pygame
pygame.init()
screen = pygame.display.set_mode((500... | ```
pip install keyboard
import keyboard #use keyboard module
while True:
if keyboard.is_pressed('SPACE'):
print('You pressed SPACE!')
break
elif keyboard.is_pressed("ENTER"):
print("You pressed ENTER.")
break
``` | 7,653 |
52,295,117 | I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with
```
from mpl_toolkits.basemap import Basemap`
```
And the Traceback as followed:
```
Traceback (most recent call last):
File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in... | 2018/09/12 | [
"https://Stackoverflow.com/questions/52295117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9101918/"
] | Following mewahl's comment I've added to my .bashrc (I use bash):
>
> export PROJ\_LIB=/path/to/your/instalation/of/anaconda/**share/proj/**
>
>
>
and now basemap (and others work). | I faced same problem. I installed anaconda and install conda install -c anaconda basemap.
I used Anaconda built in IDE named "Spyder".
Spyder is better than pycharm. only problem with spyder is lack of intellisense.
I solved problem of Proj4 by setting path.
Other problem kernel restarting when loading of .json larg... | 7,655 |
36,419,442 | I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command.
>
> aws lambda create-function
>
> --region us-west-2
>
> --function-name HelloPython
>
> --zip-file fileb://hello\_python.zip
>
> --role arn:... | 2016/04/05 | [
"https://Stackoverflow.com/questions/36419442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045354/"
] | I got this problem while testing lambda function.
What worked for me was formatting JSON. | For me, the issue was that I had set the wrong default region environment key. | 7,665 |
65,751,105 | I'm using python prometheus client and have troubles pushing metrics to VictoriaMetrics (VM).
There is a function called `push_to_gateway` and I tried to replace prometheus URL with VM: `http://prometheus:9091 -> http://vm:8428/api/v1/write`. But VM responded with 400 status code. | 2021/01/16 | [
"https://Stackoverflow.com/questions/65751105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6689249/"
] | It possible to use `push_to_gateway` method with VictoriaMetrics, check examples at gist <https://gist.github.com/f41gh7/85b2eb895bb63b93ce46ef73448c62d0> | Also, pls take a look at the client I recently created: <https://github.com/gistart/prometheus-push-client>
>
> supports pushes directly to VictoriaMetrics via UDP and HTTP using InfluxDB line protocol
>
>
>
>
> to StatsD or statsd-exporter in StatsD format via UDP
>
>
>
>
> to pushgateway or prom-aggregati... | 7,675 |
21,202,434 | I have to random choose names from a list in python **using random.randint.**
I have done it so far. but i am unable to figure out how to print them without repetition.
some of the name repeat them after 10 to 15 names.
please help me out. **I am not allowed to use any high functions.** I should do it with simple fun... | 2014/01/18 | [
"https://Stackoverflow.com/questions/21202434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3209210/"
] | Assuming, that you can only use **randint** and basic operations (loops, assignments and sublistings) - you can do the "in place shuffling trick" (modern version of Fisher Yates) to achieve such a result
```
copy = names[:]
for i in xrange( user_input-1, 1, -1 ):
swap = random.randint(0, i)
copy[i],copy[swap]... | Generate an array of random numbers of the same length as `names`
```
sortarr = [random.randint(0, 10*len(names)) for i in range(len(names))]
```
and sort your `names` array based on this new array
```
names = [name for sa, name in sorted(zip(sortarr, names))]
```
What it does is assigns some random numbers to t... | 7,677 |
18,942,003 | I have this Python skeleton, where main.py is fine and server.py is fine. But the moment chat() is launched i see the GUI, but the moment `gtk.main()` was executed it does not allow any activity under server.py module nor in chat.py itself.
How can i have the chat.py flexible so that it does not interupt other class a... | 2013/09/22 | [
"https://Stackoverflow.com/questions/18942003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Instead of the default `sent_tokenize`, what you'll need is the realignment feature that is already pre-coded pre-trained in the `punkt` sentence tokenizer.
```
>>> import nltk
>>> st2 = nltk.data.load('tokenizers/punkt/english.pickle')
>>> sent = 'A problem. She said: "I don\'t know about it."'
>>> st2.tokenize(sent,... | The default sentence tokenizer is `PunktSentenceTokenizer` that detects a new sentence each time it founds a period except, for example, the period belongs to an acronym like U.S.A.
In nltk documentation there are examples of how to train a new sentence splitter with different corpus. You can find it [here.](http://nl... | 7,683 |
23,386,290 | I want to use the logging module instead of printing for debug information and documentation.
The goal is to print on the console with DEBUG level and log to a file with INFO level.
I read through a lot of documentation, the cookbook and other tutorials on the logging module but couldn't figure out, how I can use it t... | 2014/04/30 | [
"https://Stackoverflow.com/questions/23386290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2889642/"
] | In your main module, you're configuring the logger of name `'__main__'` (or whatever `__name__` equates to in your case) while in module.py you're using a different logger. You either need to configure loggers per module, or you can configure the root logger (by configuring `logging.getLogger()`) in your main module wh... | The generally recommended logging setup is having at most 1 logger per module.
If your project is [properly packaged](https://packaging.python.org/), `__name__` will have the value of `"mypackage.mymodule"`, except in your main file, where it has the value `"__main__"`
If you want more context about the code that is ... | 7,684 |
65,222,770 | i am new to all this and im trying to make a shoot 'em up game. after i try to run the code, i encounter an error `TypeError: 'int' object is not subscriptable` at:
line 269:
`collision = isCollision(enemyX[i],enemyY[i],knifeX,knifeY)`
line 118:
`distance = math.sqrt((math.pow(enemyX[i] - knifeX,2)) + (math.pow(enemy... | 2020/12/09 | [
"https://Stackoverflow.com/questions/65222770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11592606/"
] | You call `isCollision()` with `enemyX[i]`, but then in `isCollision`, you try to access `enemyX[i]`. So you're trying to do `enemyX[i][i]`. But since `enemyX[i]` is an integer, trying to get a subscript of it, `[i]`, is invalid so that's why you get that error. | You're already sending the specific number with e.g. `enemyX[i]` when you call `isCollision(enemyX[i], ...)`. Once in that function, you can just use the passed argument (which you also happen to call `enemyX` - it's just a different one from the caller's `enemyX`) by itself, e.g. `math.pow(enemyX -...`. I recommend re... | 7,685 |
38,218,609 | I started to learn Scrapy but I stuck up at weird point where I couldn't set default shell to ipython. The operating system of my laptop is Ubuntu 15.10. I also installed ipython and scrapy. They run well without causing any errors.
According to Scrapy's [official tutorial](http://doc.scrapy.org/en/latest/topics/shell... | 2016/07/06 | [
"https://Stackoverflow.com/questions/38218609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5538922/"
] | Another way to configure (or test) the shell used by `scrapy shell` is the [`SCRAPY_PYTHON_SHELL` environment variable](http://doc.scrapy.org/en/latest/topics/shell.html#configuring-the-shell).
So running:
```
paul@paul:~$ SCRAPY_PYTHON_SHELL=ipython scrapy shell
```
would use `ipython` as first choice, whatever se... | If you are inside of the project you can use this:
```
from scrapy.utils.project import get_project_settings
settings = get_project_settings()
settings.get('IMPORT_API_URL')
```
If you are outside of the project, you can use this:
```
from scrapy.settings import Settings
settings = Settings()
settings_module_pa... | 7,687 |
41,780,388 | Please refrain from calling this a duplicate, I am completely new to idea of accessing USB devices via Python.
The other questions and answers were often too high level for me to comprehend.
I have a qr code scanner that is USB plug and play.
I can't find it on the command line for whatever reason and it has me stu... | 2017/01/21 | [
"https://Stackoverflow.com/questions/41780388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4562973/"
] | With this (second) call:
```
name_array = realloc(name_array, sizeof(char *));
```
You are still allocating just one char pointer. So, you can't store two pointers; you need to increase the size:
```
name_array = realloc(name_array, 2 * sizeof *name_array);
```
Now, you'd be fine.
Note that `p = realloc(p, ..);... | The error is better reported by address sanitizer than valgrind. If you compile your code like:
```
gcc test.c -fsanitize=address -g
```
and then run it, it will report heap-buffer-overflow error in line 19 of your code. This is the line where you assign second element of name\_array having allocated memory for only... | 7,688 |
16,223,412 | I have a relatively big project that has many dependencies, and I would like to distribute this project around, but installing these dependencies where a bit of a pain, and takes a very long time (pip install takes quite some time). So I was wondering if it was possible to migrate a whole virtualenv to another machine ... | 2013/04/25 | [
"https://Stackoverflow.com/questions/16223412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1515864/"
] | Export virtualenvironment
*from within the virtual environment:*
```
pip freeze > requirements.txt
```
as example, here is for myproject virtual environment:
[](https://i.stack.imgur.com/EJUEk.png)
once in the new machine & environment, cop... | When you create a new virtualenv it is configured for the computer it is running on. I even think that it is configured for that specific directory it is created in. So I think you should always create a fresh virtualenv when you move you code. What might work is copying the lib/Pythonx.x/site-packages in your virtuale... | 7,689 |
24,209,181 | I have uploaded my first Django Application called **survey** (Its a work in progress) using `mod_wsgi` with `Apache` on an `Ubuntu` VM but I don't know what the URL of it should be. My VM has been made public through a proxyPass at <http://phaedrus.scss.tcd.ie/bias_experiment>.
When working on my application locally ... | 2014/06/13 | [
"https://Stackoverflow.com/questions/24209181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1214163/"
] | The URL should be <http://phaedrus.scss.tcd.ie/bias_experiment/surveythree/>
I think there is one tiny error in the Apache configuration, which might be my fault (sorry): you need a trailing slash, so:
```
WSGIScriptAlias /bias_experiment/ /var/www/bias_experiment/src/bias_experiment/index.wsgi
```
Also note that y... | Try with this changes:
Apache conf:
```
WSGIApplicationGroup %{GLOBAL}
ServerName phaedrus.scss.tcd.ie
WSGIScriptAlias /bias_experiment/ /var/www/bias_experiment/src/bias_experiment/index.wsgi
WSGIDaemonProcess bias_experiment processes=4 threads=25 display-name=%{GROUP}
WSGIProcessGroup bias_experiment
WSGIPassAutho... | 7,691 |
24,618,832 | I wonder if anyone has an elegant solution to being able to pass a python list, a numpy vector (shape(n,)) or a numpy vector (shape(n,1)) to a function. The idea would be to generalize a function such that any of the three would be valid without adding complexity.
Initial thoughts:
```
1) Use a type checking decorato... | 2014/07/07 | [
"https://Stackoverflow.com/questions/24618832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839375/"
] | You can convert the three types to a "canonical" type, which is a 1dim array, using:
```
arr = np.asarray(arr).ravel()
```
Put in a decorator:
```
import numpy as np
import functools
def takes_1dim_array(func):
@functools.wraps(func)
def f(arr, *a, **kw):
arr = np.asarray(arr).ravel()
retur... | I think the simplest thing to do is to start off your function with [`numpy.atleast_2d`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_2d.html). Then, all 3 of your possibilities will be converted to the `x.shape == (n, 1)` case, and you can use that to simplify your function.
For example,
```
def... | 7,694 |
20,714,517 | **Hi,
I ran into an encoding error with Python Django.
In my views.py, I have the following:**
```
from django.shortcuts import render
from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context
# Create your views here.
def hello(request):
name = 'Mike... | 2013/12/21 | [
"https://Stackoverflow.com/questions/20714517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1139783/"
] | Well, here you are:
Put `# -*- coding: utf-8 -*-` at top of file, it define de encoding.
The [docs](http://www.python.org/dev/peps/pep-0263/) says:
>
> Python will default to ASCII as standard encoding if no other
> encoding hints are given.
>
>
>
> ```
> To define a source code encoding, a magic comment must
... | If you read [PEP 263](http://www.python.org/dev/peps/pep-0263/), it clearly says:
>
> To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file…
>
>
>
(The original proposal said that it had to be the first line after the #!, if any, but pres... | 7,695 |
49,510,289 | I have a gigantic excel workbook with a lot of personal data. Each person has a unique numeric identifier, but has multiple rows of information.
I want to filter all the content through that identifier, and then copy the resulting rows to a template excel workbook and save the results. I'm trying to do this with Pyth... | 2018/03/27 | [
"https://Stackoverflow.com/questions/49510289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9553462/"
] | Yes, all of your answers are correct.
`int` will always take up `sizeof(int)` bytes, 8(int) assuming 32-bit `int` it will take 4 bytes, whereas 8(char) will take up one byte.
The way to think about your last question IMO is that data is stored as *bytes*. *char* and *int* are way of interpreting bytes, so in text fil... | When we consider the memory location for an `int` or for a `char` we think as a whole. Integers are commonly stored using a word of memory, which is 4 bytes or 32 bits, so integers from 0 up to 4,294,967,295 (232 - 1) can be stored in an `int` variable. As we need total 32 bits (32/8 = 4) hence we need 4 bytes for an `... | 7,696 |
57,230,353 | I am working on a Python program for displaying photos on the Raspberry Pi (Model B Revision 2.0 with 512MB RAM). It uses Tk for displaying the images.
The program is mostly finished, but I ran into an issue where the program is terminated by the kernel because of low memory. This seems to happen randomly.
I do not un... | 2019/07/27 | [
"https://Stackoverflow.com/questions/57230353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/653770/"
] | I believe there is a memory leak when you open the image files with PIL and don't close them.
To avoid it, you must call `Image.close()`, or better yet consider using the `with` syntax.
```
def readImage(self,imagePath,w,h):
with Image.open(imagePath) as pilImage:
pilImage = self.rotateImage(pilImage... | I run the code on my machine and I noticed similiar spikes.
After some memory adjustments on a virtual machine I had a system without swap (turned of to get the crash "faster") and approximately 250Mb free memory.
While base memory usage was somewhere around 120Mb, the image change was between 190Mb and 200Mb (using i... | 7,701 |
20,578,798 | I'm new to python dictionaries as well as nesting.
Here's what I'm trying to find - I have objects that all have the same attributes: color and height. I need to compare all the attributes and make of list of all the ones that match.
```
matchList = []
dict = {obj1:{'color': (1,0,0), 'height': 10.6},
obj2:{'... | 2013/12/14 | [
"https://Stackoverflow.com/questions/20578798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3101267/"
] | **Update:** Found this great article from [Matt Gaunt](https://plus.google.com/+MattGaunt/posts) (a Google Employee) on adding a Translucent theme to Android apps. It is very thorough and addresses some of the issues many people seem to be having while implementing this style: [Translucent Theme in Android](http://blog... | It looks like all you need to do is add this element to the themes you want a translucent status bar on:
```
<item name="android:windowTranslucentStatus">true</item>
``` | 7,702 |
48,921,068 | I am using `python 3` and `django 1.11` got the following data in a `.sql` file:
How do I use `DecimalField` and `DateField` components to represent the fields correctly.
I was thinking of doing something like this:
e.g `per_diem = models.DecimalField(max_digits=12, decimal_places=2,null=False)`
``
```
CREATE TABLE e... | 2018/02/22 | [
"https://Stackoverflow.com/questions/48921068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8342189/"
] | The first one is from the apache servlet API for status codes from Interface HttpServletResponse found [here](https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServletResponse.html)
>
> SC\_NOT\_FOUND - Status code (404) indicating that the requested
> resource is not available.
>
>
>
Th... | There is no difference, it is same status code for HTTP from different libraries. | 7,710 |
30,578,381 | I am trying to compile opencv on Slackware 4.1. However I encountered the following error each time.
```
In file included from /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:29:0,
from /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:65:
/usr/include/gstreamer-0.10/gst/pbutils/gstd... | 2015/06/01 | [
"https://Stackoverflow.com/questions/30578381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4962063/"
] | It worked for me after I set WITH\_GSTREAMER\_0\_10 to ON | I am using Ubuntu 12.04 but got the same error.
This can be avoided by using the **-D WITH\_GSTREAMER=OFF** parameter.
As advised [here](http://code.opencv.org/issues/3953) and [here](https://stackoverflow.com/questions/23669638/installing-opencv-on-ubuntu-12-04).
Then [here](https://gist.github.com/melvincabatuan/c8a... | 7,711 |
70,819,915 | This is the code:
```
name = input("Enter file: ")
handle = open(name)
counts = dict()
filetext = handle.read()
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1
print(words)
print(counts)
bigcount = None
bigword = None
for word,count in counts.items():... | 2022/01/23 | [
"https://Stackoverflow.com/questions/70819915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18007432/"
] | After you do `handle.read()`, the file is positioned at end-of-file. There's nothing left for the `for line in handle:` to read. You either need to rewind in between (`handle.seek(0)`), or just skip the first read altogether. | You could consider building a list of lines as you iterate over the file handle rather than doing a read/seek. Also, you can work out the most frequently occurring word as you work through the file rather than doing a second pass of your dictionary. Something like this:
```
D = dict()
M = 0
B = None
C = list()
with op... | 7,717 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.