qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
listlengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
|---|---|---|---|---|---|
14,303,300
|
>
> **Possible Duplicate:**
>
> [Python \_\_str\_\_ and lists](https://stackoverflow.com/questions/727761/python-str-and-lists)
>
>
>
What is the cause when python prints the address of an object instead of the object itself?
for example the output for a print instruction is this:
```
[< ro.domain.entities.Person object at 0x01E6BA10>, < ro.domain.entities.Person object at 0x01E6B9F0>, < ro.domain.entities.Person object at 0x01E6B7B0>]
```
My code looks like this:
```
class PersonRepository:
"""
Stores and manages person information.
"""
def __init__(self):
"""
Initializes the list of persons.
"""
self.__list=[]
def __str__(self):
"""
Returns the string format of the persons list.
"""
s=""
for i in range(0, len(self.__list)):
s=s+str(self.__list[i])+"/n"
return s
def add(self, p):
"""
data: p - person.
Adds a new person, raises ValueError if there is already a person with the given id.
pos: list contains new person.
"""
for q in self.__list:
if q.get_personID()==p.get_personID():
raise ValueError("Person already exists.")
self.__list.append(p)
def get_all(self):
"""
Returns the list containing all persons.
"""
l=str(self.__list)
return l
```
I have a Person class as well, with a get\_personID() function. After I have added some elements and try to print them using get\_all(), it returns the above line, instead of the persons I have added.
|
2013/01/13
|
[
"https://Stackoverflow.com/questions/14303300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1796659/"
] |
You are looking at the `repr()` representation of a custom class, which by default include the `id()` (== memory address in CPython).
This is the default used when printing a list, any contents are included using the representation:
```
>>> class CustomObject(object):
... def __str__(self):
... return "I am a custom object"
...
>>> custom = CustomObject()
>>> print(custom)
I am a custom object
>>> print(repr(custom))
<__main__.CustomObject object at 0x10552ff10>
>>> print([custom])
[<__main__.CustomObject object at 0x10552ff10>]
```
|
Python calls for every list item the **repr**() output of each list item.
See [Python \_\_str\_\_ and lists](https://stackoverflow.com/questions/727761/python-str-and-lists)
|
3,306,518
|
I needed to have a directly executable python script, so i started the file with `#!/usr/bin/env python`. However, I also need unbuffered output, so i tried `#!/usr/bin/env python -u`, but that fails with `python -u: no such file or directory`.
I found out that `#/usr/bin/python -u` works, but I need it to get the `python` in `PATH` to support virtual `env` environments.
What are my options?
|
2010/07/22
|
[
"https://Stackoverflow.com/questions/3306518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381048/"
] |
Here is a script alternative to `/usr/bin/env`, that permits passing of arguments on the hash-bang line, based on `/bin/bash` and with the restriction that spaces are disallowed in the executable path. I call it "envns" (env No Spaces):
```
#!/bin/bash
ARGS=( $1 ) # separate $1 into multiple space-delimited arguments.
shift # consume $1
PROG=`which ${ARGS[0]}`
unset ARGS[0] # discard executable name
ARGS+=( "$@" ) # remainder of arguments preserved "as-is".
exec $PROG "${ARGS[@]}"
```
Assuming this script is located at /usr/local/bin/envns, here's your shebang line:
```
#!/usr/local/bin/envns python -u
```
Tested on Ubuntu 13.10 and cygwin x64.
|
Building off of Larry Cai's answer, `env` allows you to set a variable directly in the command line. That means that `-u` can be replaced by the equivalent `PYTHONUNBUFFERED` setting before `python`:
```
#!/usr/bin/env PYTHONUNBUFFERED="YESSSSS" python
```
Works on RHEL 6.5. I am pretty sure that feature of `env` is just about universal.
|
3,306,518
|
I needed to have a directly executable python script, so i started the file with `#!/usr/bin/env python`. However, I also need unbuffered output, so i tried `#!/usr/bin/env python -u`, but that fails with `python -u: no such file or directory`.
I found out that `#/usr/bin/python -u` works, but I need it to get the `python` in `PATH` to support virtual `env` environments.
What are my options?
|
2010/07/22
|
[
"https://Stackoverflow.com/questions/3306518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381048/"
] |
Building off of Larry Cai's answer, `env` allows you to set a variable directly in the command line. That means that `-u` can be replaced by the equivalent `PYTHONUNBUFFERED` setting before `python`:
```
#!/usr/bin/env PYTHONUNBUFFERED="YESSSSS" python
```
Works on RHEL 6.5. I am pretty sure that feature of `env` is just about universal.
|
I recently wrote a patch for the GNU Coreutils version of `env` to address this issue:
<http://lists.gnu.org/archive/html/coreutils/2017-05/msg00018.html>
If you have this, you can do:
```
#!/usr/bin/env :lang:--foo:bar
```
`env` will split `:lang:foo:--bar` into the fields `lang`, `foo` and `--bar`. It will search `PATH` for the interpreter `lang`, and then invoke it with arguments `--foo`, `bar`, plus the path to the script and that script's arguments.
There is also a feature to pass the name of the script in the middle of the options. Suppose you want to run `lang -f <thecriptname> other-arg`, followed by the remaining arguments. With this patched `env`, it is done like this:
```
#!/usr/bin/env :lang:-f:{}:other-arg
```
The leftmost field which is equivalent to `{}` is replaced with the first argument that follows, which, under hash bang invocation, is the script name. That argument is then removed.
Here, `other-arg` could be something processed by `lang` or perhaps something processed by the script.
To understand better, see the numerous `echo` test cases in the patch.
I chose the `:` character because it is an existing separator used in `PATH` on POSIX systems. Since `env` does `PATH` searching, it's vanishingly unlikely to be used for a program whose name contains a colon. The `{}` marker comes from the `find` utility, which uses it to denote the insertion of a path into the `-exec` command line.
|
3,306,518
|
I needed to have a directly executable python script, so i started the file with `#!/usr/bin/env python`. However, I also need unbuffered output, so i tried `#!/usr/bin/env python -u`, but that fails with `python -u: no such file or directory`.
I found out that `#/usr/bin/python -u` works, but I need it to get the `python` in `PATH` to support virtual `env` environments.
What are my options?
|
2010/07/22
|
[
"https://Stackoverflow.com/questions/3306518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381048/"
] |
Passing arguments to the shebang line is not standard and in as you have experimented do not work in combination with env in Linux. The solution with bash is to use the builtin command "set" to set the required options. I think you can do the same to set unbuffered output of stdin with a python command.
my2c
|
Building off of Larry Cai's answer, `env` allows you to set a variable directly in the command line. That means that `-u` can be replaced by the equivalent `PYTHONUNBUFFERED` setting before `python`:
```
#!/usr/bin/env PYTHONUNBUFFERED="YESSSSS" python
```
Works on RHEL 6.5. I am pretty sure that feature of `env` is just about universal.
|
3,306,518
|
I needed to have a directly executable python script, so i started the file with `#!/usr/bin/env python`. However, I also need unbuffered output, so i tried `#!/usr/bin/env python -u`, but that fails with `python -u: no such file or directory`.
I found out that `#/usr/bin/python -u` works, but I need it to get the `python` in `PATH` to support virtual `env` environments.
What are my options?
|
2010/07/22
|
[
"https://Stackoverflow.com/questions/3306518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381048/"
] |
In some environment, env doesn't split arguments.
So your env is looking for `python -u` in your path.
We can use sh to work around.
Replace your shebang with the following code lines and everything will be fine.
```
#!/bin/sh
''''exec python -u -- "$0" ${1+"$@"} # '''
# vi: syntax=python
```
p.s. we need not worry about the path to sh, right?
|
Building off of Larry Cai's answer, `env` allows you to set a variable directly in the command line. That means that `-u` can be replaced by the equivalent `PYTHONUNBUFFERED` setting before `python`:
```
#!/usr/bin/env PYTHONUNBUFFERED="YESSSSS" python
```
Works on RHEL 6.5. I am pretty sure that feature of `env` is just about universal.
|
3,306,518
|
I needed to have a directly executable python script, so i started the file with `#!/usr/bin/env python`. However, I also need unbuffered output, so i tried `#!/usr/bin/env python -u`, but that fails with `python -u: no such file or directory`.
I found out that `#/usr/bin/python -u` works, but I need it to get the `python` in `PATH` to support virtual `env` environments.
What are my options?
|
2010/07/22
|
[
"https://Stackoverflow.com/questions/3306518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381048/"
] |
Here is a script alternative to `/usr/bin/env`, that permits passing of arguments on the hash-bang line, based on `/bin/bash` and with the restriction that spaces are disallowed in the executable path. I call it "envns" (env No Spaces):
```
#!/bin/bash
ARGS=( $1 ) # separate $1 into multiple space-delimited arguments.
shift # consume $1
PROG=`which ${ARGS[0]}`
unset ARGS[0] # discard executable name
ARGS+=( "$@" ) # remainder of arguments preserved "as-is".
exec $PROG "${ARGS[@]}"
```
Assuming this script is located at /usr/local/bin/envns, here's your shebang line:
```
#!/usr/local/bin/envns python -u
```
Tested on Ubuntu 13.10 and cygwin x64.
|
This is a kludge and requires bash, but it works:
```
#!/bin/bash
python -u <(cat <<"EOF"
# Your script here
print "Hello world"
EOF
)
```
|
3,306,518
|
I needed to have a directly executable python script, so i started the file with `#!/usr/bin/env python`. However, I also need unbuffered output, so i tried `#!/usr/bin/env python -u`, but that fails with `python -u: no such file or directory`.
I found out that `#/usr/bin/python -u` works, but I need it to get the `python` in `PATH` to support virtual `env` environments.
What are my options?
|
2010/07/22
|
[
"https://Stackoverflow.com/questions/3306518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381048/"
] |
This might be a little bit outdated but env(1) manual tells one can use '-S' for that case
```
#!/usr/bin/env -S python -u
```
It seems to work pretty good on FreeBSD.
|
Here is a script alternative to `/usr/bin/env`, that permits passing of arguments on the hash-bang line, based on `/bin/bash` and with the restriction that spaces are disallowed in the executable path. I call it "envns" (env No Spaces):
```
#!/bin/bash
ARGS=( $1 ) # separate $1 into multiple space-delimited arguments.
shift # consume $1
PROG=`which ${ARGS[0]}`
unset ARGS[0] # discard executable name
ARGS+=( "$@" ) # remainder of arguments preserved "as-is".
exec $PROG "${ARGS[@]}"
```
Assuming this script is located at /usr/local/bin/envns, here's your shebang line:
```
#!/usr/local/bin/envns python -u
```
Tested on Ubuntu 13.10 and cygwin x64.
|
3,306,518
|
I needed to have a directly executable python script, so i started the file with `#!/usr/bin/env python`. However, I also need unbuffered output, so i tried `#!/usr/bin/env python -u`, but that fails with `python -u: no such file or directory`.
I found out that `#/usr/bin/python -u` works, but I need it to get the `python` in `PATH` to support virtual `env` environments.
What are my options?
|
2010/07/22
|
[
"https://Stackoverflow.com/questions/3306518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381048/"
] |
Passing arguments to the shebang line is not standard and in as you have experimented do not work in combination with env in Linux. The solution with bash is to use the builtin command "set" to set the required options. I think you can do the same to set unbuffered output of stdin with a python command.
my2c
|
Here is a script alternative to `/usr/bin/env`, that permits passing of arguments on the hash-bang line, based on `/bin/bash` and with the restriction that spaces are disallowed in the executable path. I call it "envns" (env No Spaces):
```
#!/bin/bash
ARGS=( $1 ) # separate $1 into multiple space-delimited arguments.
shift # consume $1
PROG=`which ${ARGS[0]}`
unset ARGS[0] # discard executable name
ARGS+=( "$@" ) # remainder of arguments preserved "as-is".
exec $PROG "${ARGS[@]}"
```
Assuming this script is located at /usr/local/bin/envns, here's your shebang line:
```
#!/usr/local/bin/envns python -u
```
Tested on Ubuntu 13.10 and cygwin x64.
|
3,306,518
|
I needed to have a directly executable python script, so i started the file with `#!/usr/bin/env python`. However, I also need unbuffered output, so i tried `#!/usr/bin/env python -u`, but that fails with `python -u: no such file or directory`.
I found out that `#/usr/bin/python -u` works, but I need it to get the `python` in `PATH` to support virtual `env` environments.
What are my options?
|
2010/07/22
|
[
"https://Stackoverflow.com/questions/3306518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381048/"
] |
This might be a little bit outdated but env(1) manual tells one can use '-S' for that case
```
#!/usr/bin/env -S python -u
```
It seems to work pretty good on FreeBSD.
|
I recently wrote a patch for the GNU Coreutils version of `env` to address this issue:
<http://lists.gnu.org/archive/html/coreutils/2017-05/msg00018.html>
If you have this, you can do:
```
#!/usr/bin/env :lang:--foo:bar
```
`env` will split `:lang:foo:--bar` into the fields `lang`, `foo` and `--bar`. It will search `PATH` for the interpreter `lang`, and then invoke it with arguments `--foo`, `bar`, plus the path to the script and that script's arguments.
There is also a feature to pass the name of the script in the middle of the options. Suppose you want to run `lang -f <thecriptname> other-arg`, followed by the remaining arguments. With this patched `env`, it is done like this:
```
#!/usr/bin/env :lang:-f:{}:other-arg
```
The leftmost field which is equivalent to `{}` is replaced with the first argument that follows, which, under hash bang invocation, is the script name. That argument is then removed.
Here, `other-arg` could be something processed by `lang` or perhaps something processed by the script.
To understand better, see the numerous `echo` test cases in the patch.
I chose the `:` character because it is an existing separator used in `PATH` on POSIX systems. Since `env` does `PATH` searching, it's vanishingly unlikely to be used for a program whose name contains a colon. The `{}` marker comes from the `find` utility, which uses it to denote the insertion of a path into the `-exec` command line.
|
3,306,518
|
I needed to have a directly executable python script, so i started the file with `#!/usr/bin/env python`. However, I also need unbuffered output, so i tried `#!/usr/bin/env python -u`, but that fails with `python -u: no such file or directory`.
I found out that `#/usr/bin/python -u` works, but I need it to get the `python` in `PATH` to support virtual `env` environments.
What are my options?
|
2010/07/22
|
[
"https://Stackoverflow.com/questions/3306518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381048/"
] |
In some environment, env doesn't split arguments.
So your env is looking for `python -u` in your path.
We can use sh to work around.
Replace your shebang with the following code lines and everything will be fine.
```
#!/bin/sh
''''exec python -u -- "$0" ${1+"$@"} # '''
# vi: syntax=python
```
p.s. we need not worry about the path to sh, right?
|
When you use shebang on Linux, the entire rest of the line after the interpreter name is interpreted as a single argument. The `python -u` gets passed to `env` as if you'd typed: `/usr/bin/env 'python -u'`. The `/usr/bin/env` searches for a binary called `python -u`, which there isn't one.
|
3,306,518
|
I needed to have a directly executable python script, so i started the file with `#!/usr/bin/env python`. However, I also need unbuffered output, so i tried `#!/usr/bin/env python -u`, but that fails with `python -u: no such file or directory`.
I found out that `#/usr/bin/python -u` works, but I need it to get the `python` in `PATH` to support virtual `env` environments.
What are my options?
|
2010/07/22
|
[
"https://Stackoverflow.com/questions/3306518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381048/"
] |
When you use shebang on Linux, the entire rest of the line after the interpreter name is interpreted as a single argument. The `python -u` gets passed to `env` as if you'd typed: `/usr/bin/env 'python -u'`. The `/usr/bin/env` searches for a binary called `python -u`, which there isn't one.
|
Building off of Larry Cai's answer, `env` allows you to set a variable directly in the command line. That means that `-u` can be replaced by the equivalent `PYTHONUNBUFFERED` setting before `python`:
```
#!/usr/bin/env PYTHONUNBUFFERED="YESSSSS" python
```
Works on RHEL 6.5. I am pretty sure that feature of `env` is just about universal.
|
41,020,233
|
How to get user-defined class attributes from class instance? I tried this:
```
class A:
FOO = 'foo'
BAR = 'bar'
a = A()
print(a.__dict__) # {}
print(vars(a)) # {}
```
I use python 3.5.
Is there a way to get them?
I know that `dir(a)` returns a list with names of attributes, but I need only used defined, and as a dict name to value.
|
2016/12/07
|
[
"https://Stackoverflow.com/questions/41020233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7262895/"
] |
You've defined those variables within the class namespace which haven't propagated into instances. You can use the `__class__` attribute of the instance to access the class object, and then use the `__dict__` method to get the namespace's contents:
```
>>> {k: v for k, v in a.__class__.__dict__.items() if not k.startswith('__')}
{'BAR': 'bar', 'FOO': 'foo'}
```
|
Try this:
```
In [5]: [x for x in dir(a) if not x.startswith('__')]
Out[5]: ['BAR', 'FOO']
```
|
58,499,136
|
I have a python script which I want to execute when someone clicks on a button in an HTML/PHP web page in the browser. How can this be achieved and what is the best way of doing it?
|
2019/10/22
|
[
"https://Stackoverflow.com/questions/58499136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8110933/"
] |
You need to use flask server for this requirement as browser can not access local file.
By using flask, You need to write Ajax call in `.js`.
Sample Ajax call.
```
$(document).ready(function () {
$('#<ButtonID>').click(function (event) {
$.ajax({
url: '/<Flask URL>',
type: 'POST',
success: function (data) {
<DATA OBJECT>
},
});
event.preventDefault();
});
});
```
Sample Flask function
```
@app.route('/<Flask URL>',methods=['POST'])
def result():
try:
<DO>
except:
logger.error()
raise
return jsonify({'data':<Python variable>})
```
You might need to import necessary modules.
|
With `exec`,
```
$command = "python script_path";
exec($command,$output,$return_var);
if ($return_var) {
$error = error_get_last();
var_dump($error)
}
```
|
62,857,693
|
How do I install spacy on ARM processor? I get an error
```
ERROR: Command errored out with exit status 1:
command: /root/miniforge3/bin/python3.7 /root/miniforge3/lib/python3.7/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-ahxo0t0p/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel 'cython>=0.25' 'cymem>=2.0.2,<2.1.0' 'preshed>=3.0.2,<3.1.0' 'murmurhash>=0.28.0,<1.1.0' thinc==7.4.1
```
Full error log:
<https://gist.github.com/shantanuo/1fb62b83a54713e517307c9cad9624f5>
|
2020/07/12
|
[
"https://Stackoverflow.com/questions/62857693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139150/"
] |
>
> You cannot use "hot reload" features with flutter app because the process of deployment/running never finishes
>
>
>
Actually, you can! Just connect to the device with `adb connect <IP>` instead of going through the socket. See my full blog post here:
<https://dnmc.in/2021/01/25/setting-up-flutter-natively-with-wsl2-vs-code-hot-reload/>
|
If you are like me you had a lot of issues getting adb to work. You need to make sure that windows host and the linux image both have the same version of adb. Following this guide <https://www.androidexplained.com/install-adb-fastboot/#update> helped me update adb on windows.
|
66,524,661
|
Here I check the installed version of pip
`py -m pip --version`
```
pip 21.0.1 from C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\pip (python 3.9)
```
Now I try to run a pip command
`pip install pip --target $HOME\\.pyenv`
```
pip: The term 'pip' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
```
|
2021/03/08
|
[
"https://Stackoverflow.com/questions/66524661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/865220/"
] |
Add the scripts folder to PATH
`C:\Users\hp\AppData\Local\Programs\Python\Python39\Scripts`
or
`C:\Python39\Scripts`
(depending on how you have installed python locate and add python/scripts folder)
|
Just use on the terminal:
```
py -m pip install
```
followed by the library you want to install. It tends to work.
|
19,494,511
|
```
Error: Error: if n == 0 or n>4:
UnboundLocalError: local variable 'n' referenced before assignment.
```
Tried isdigit method, but seems not working. what is the issue ?
```
#!usr/bin/python
import sys
class Person:
def __init__(self, firstname=None, lastname=None, age=None, gender=None):
self.fname = firstname
self.lname = lastname
self.age = age
self.gender = gender
def display(self):
found = False
n1 = raw_input("Enter for Search Criteria\n1.FirstName == 2.LastName == 3.Age == 4.Gender : " )
print "Not a valid input"
if n1.isdigit():
n = int(n1)
else:
print "Enter Integer only"
if n == 0 or n>4:
print "Enter valid search "
if n == 1:
StringSearch = raw_input("Enter FirstName :")
for records in list_of_records:
if StringSearch in records.fname:
found = True
print records.fname, records.lname, records.age, records.gender
if not found:
print "No matched record"
if n == 2:
StringSearch = raw_input("Enter LastName :")
for records in list_of_records:
if StringSearch in records.lname:
found = True
print records.fname, records.lname, records.age, records.gender
if not found:
print "No matched record"
if n == 3:
StringSearch = raw_input("Enter Age :")
for records in list_of_records:
if StringSearch in records.age:
if not found:
print "No matched record"
if n == 4:
StringSearch = raw_input("Enter Gender(M/F) :")
for records in list_of_records:
if StringSearch in records.gender:
found = True
print records.fname, records.lname, records.age, records.gender
if not found:
print "No matched record"
f= open("abc","r")
list_of_records = [Person(*line.split()) for line in f]
#for record in list_of_records:
for per in list_of_records:
per.display()
```
PLease help me out in how to handle this issue ?
|
2013/10/21
|
[
"https://Stackoverflow.com/questions/19494511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2897545/"
] |
Okay, you are doing a few things wrong.
First of all, `raw_input` will always give you a string.
So you need to convert it into an integer anyway. But also, you are using the variable `n` in parts of your code that it might not exist at yet.
You need to change this part:
```
print "Not a valid input"
if n1.isdigit():
n = int(n1)
else:
print "Enter Integer only"
```
To this:
```
try:
n = int(n1)
except:
print "Enter Integer only"
raise
```
Unless you want to keep asking until valid input is received, then make a function:
```
def get_user_int(prompt="Enter an integer: "):
while True:
try:
return int(raw_input(prompt)))
except:
print 'Try again'
```
And call it like this:
```
n = get_user_int("Enter choice for Search Criteria\n - 1.FirstName\n - 2.LastName\n - 3.Age\n - 4.Gender\n> ")
```
|
Your're testing for n == something condition before setting the value of n. Simply initialize it to zero or whatever else default value.
```
def display(self):
found = False
n = 0
```
|
19,494,511
|
```
Error: Error: if n == 0 or n>4:
UnboundLocalError: local variable 'n' referenced before assignment.
```
Tried isdigit method, but seems not working. what is the issue ?
```
#!usr/bin/python
import sys
class Person:
def __init__(self, firstname=None, lastname=None, age=None, gender=None):
self.fname = firstname
self.lname = lastname
self.age = age
self.gender = gender
def display(self):
found = False
n1 = raw_input("Enter for Search Criteria\n1.FirstName == 2.LastName == 3.Age == 4.Gender : " )
print "Not a valid input"
if n1.isdigit():
n = int(n1)
else:
print "Enter Integer only"
if n == 0 or n>4:
print "Enter valid search "
if n == 1:
StringSearch = raw_input("Enter FirstName :")
for records in list_of_records:
if StringSearch in records.fname:
found = True
print records.fname, records.lname, records.age, records.gender
if not found:
print "No matched record"
if n == 2:
StringSearch = raw_input("Enter LastName :")
for records in list_of_records:
if StringSearch in records.lname:
found = True
print records.fname, records.lname, records.age, records.gender
if not found:
print "No matched record"
if n == 3:
StringSearch = raw_input("Enter Age :")
for records in list_of_records:
if StringSearch in records.age:
if not found:
print "No matched record"
if n == 4:
StringSearch = raw_input("Enter Gender(M/F) :")
for records in list_of_records:
if StringSearch in records.gender:
found = True
print records.fname, records.lname, records.age, records.gender
if not found:
print "No matched record"
f= open("abc","r")
list_of_records = [Person(*line.split()) for line in f]
#for record in list_of_records:
for per in list_of_records:
per.display()
```
PLease help me out in how to handle this issue ?
|
2013/10/21
|
[
"https://Stackoverflow.com/questions/19494511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2897545/"
] |
```
n = 0
if n1.isdigit():
n = int(n1)
else:
"""If the execution comes here (not n1.isdigit())
the variable `n` will remain undefined.
Therefore you should define it in this block or before if,
say initially setting it to zero.
"""
print "Enter Integer only"
```
<http://codepad.org/5PNWnDrN>
Another approach:
```
try:
n = int(n1)
except ValueError, TypeError:
n = 0
```
<http://codepad.org/JEdXO9dz>
|
Your're testing for n == something condition before setting the value of n. Simply initialize it to zero or whatever else default value.
```
def display(self):
found = False
n = 0
```
|
19,494,511
|
```
Error: Error: if n == 0 or n>4:
UnboundLocalError: local variable 'n' referenced before assignment.
```
Tried isdigit method, but seems not working. what is the issue ?
```
#!usr/bin/python
import sys
class Person:
def __init__(self, firstname=None, lastname=None, age=None, gender=None):
self.fname = firstname
self.lname = lastname
self.age = age
self.gender = gender
def display(self):
found = False
n1 = raw_input("Enter for Search Criteria\n1.FirstName == 2.LastName == 3.Age == 4.Gender : " )
print "Not a valid input"
if n1.isdigit():
n = int(n1)
else:
print "Enter Integer only"
if n == 0 or n>4:
print "Enter valid search "
if n == 1:
StringSearch = raw_input("Enter FirstName :")
for records in list_of_records:
if StringSearch in records.fname:
found = True
print records.fname, records.lname, records.age, records.gender
if not found:
print "No matched record"
if n == 2:
StringSearch = raw_input("Enter LastName :")
for records in list_of_records:
if StringSearch in records.lname:
found = True
print records.fname, records.lname, records.age, records.gender
if not found:
print "No matched record"
if n == 3:
StringSearch = raw_input("Enter Age :")
for records in list_of_records:
if StringSearch in records.age:
if not found:
print "No matched record"
if n == 4:
StringSearch = raw_input("Enter Gender(M/F) :")
for records in list_of_records:
if StringSearch in records.gender:
found = True
print records.fname, records.lname, records.age, records.gender
if not found:
print "No matched record"
f= open("abc","r")
list_of_records = [Person(*line.split()) for line in f]
#for record in list_of_records:
for per in list_of_records:
per.display()
```
PLease help me out in how to handle this issue ?
|
2013/10/21
|
[
"https://Stackoverflow.com/questions/19494511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2897545/"
] |
Okay, you are doing a few things wrong.
First of all, `raw_input` will always give you a string.
So you need to convert it into an integer anyway. But also, you are using the variable `n` in parts of your code that it might not exist at yet.
You need to change this part:
```
print "Not a valid input"
if n1.isdigit():
n = int(n1)
else:
print "Enter Integer only"
```
To this:
```
try:
n = int(n1)
except:
print "Enter Integer only"
raise
```
Unless you want to keep asking until valid input is received, then make a function:
```
def get_user_int(prompt="Enter an integer: "):
while True:
try:
return int(raw_input(prompt)))
except:
print 'Try again'
```
And call it like this:
```
n = get_user_int("Enter choice for Search Criteria\n - 1.FirstName\n - 2.LastName\n - 3.Age\n - 4.Gender\n> ")
```
|
```
n = 0
if n1.isdigit():
n = int(n1)
else:
"""If the execution comes here (not n1.isdigit())
the variable `n` will remain undefined.
Therefore you should define it in this block or before if,
say initially setting it to zero.
"""
print "Enter Integer only"
```
<http://codepad.org/5PNWnDrN>
Another approach:
```
try:
n = int(n1)
except ValueError, TypeError:
n = 0
```
<http://codepad.org/JEdXO9dz>
|
41,061,824
|
I have a problem with installing csv package in pycharm (running under python 3.5.2)
When I try to install it I get an error saying
Executed command:
`pip install --user csv`
Error occurred:
Non-zero exit code (1)
Could not find a version that satisfies the requirement csv (from versions: )
No matching distribution found for csv
I updated the pip package to version 9.0.1 but still nothing.
When I run the following code:
```
import csv
f = open('fl.csv')
csv_f = csv.reader(f)
f.close()
```
I get this error:
csv\_f = csv.reader(f)
AttributeError: module 'csv' has no attribute 'reader'
I thought it was because I could not install the "csv package"
also I tried running:
```
import csv
print(dir(csv))
```
and the print result is:
['**doc**', '**loader**', '**name**', '**package**', '**path**', '**spec**']
A lot of methods including csv.reader are missing
This is pretty much all the useful information up until comment #29
|
2016/12/09
|
[
"https://Stackoverflow.com/questions/41061824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4005127/"
] |
You can't `pip install csv` because the csv module is included in the Python installation.
You can directly use :
```
import csv
```
in your program
Thanks
|
The problem is that you have another file in your directory called `csv.py`. And in this file you do not have a `reader` function.
Change its name to `my_csv.py`
|
41,061,824
|
I have a problem with installing csv package in pycharm (running under python 3.5.2)
When I try to install it I get an error saying
Executed command:
`pip install --user csv`
Error occurred:
Non-zero exit code (1)
Could not find a version that satisfies the requirement csv (from versions: )
No matching distribution found for csv
I updated the pip package to version 9.0.1 but still nothing.
When I run the following code:
```
import csv
f = open('fl.csv')
csv_f = csv.reader(f)
f.close()
```
I get this error:
csv\_f = csv.reader(f)
AttributeError: module 'csv' has no attribute 'reader'
I thought it was because I could not install the "csv package"
also I tried running:
```
import csv
print(dir(csv))
```
and the print result is:
['**doc**', '**loader**', '**name**', '**package**', '**path**', '**spec**']
A lot of methods including csv.reader are missing
This is pretty much all the useful information up until comment #29
|
2016/12/09
|
[
"https://Stackoverflow.com/questions/41061824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4005127/"
] |
You can't `pip install csv` because the csv module is included in the Python installation.
You can directly use :
```
import csv
```
in your program
Thanks
|
1. 'csv' is an in-built package. So you dont have to install it again in Pycharm.
2. When you try to import csv, make sure that you dont have **any file**(*created by you*) named as 'csv.py' in your project folder(or Python Path Variable folders) because of this you are not actually importing 'csv' package.
|
41,061,824
|
I have a problem with installing csv package in pycharm (running under python 3.5.2)
When I try to install it I get an error saying
Executed command:
`pip install --user csv`
Error occurred:
Non-zero exit code (1)
Could not find a version that satisfies the requirement csv (from versions: )
No matching distribution found for csv
I updated the pip package to version 9.0.1 but still nothing.
When I run the following code:
```
import csv
f = open('fl.csv')
csv_f = csv.reader(f)
f.close()
```
I get this error:
csv\_f = csv.reader(f)
AttributeError: module 'csv' has no attribute 'reader'
I thought it was because I could not install the "csv package"
also I tried running:
```
import csv
print(dir(csv))
```
and the print result is:
['**doc**', '**loader**', '**name**', '**package**', '**path**', '**spec**']
A lot of methods including csv.reader are missing
This is pretty much all the useful information up until comment #29
|
2016/12/09
|
[
"https://Stackoverflow.com/questions/41061824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4005127/"
] |
You can't `pip install csv` because the csv module is included in the Python installation.
You can directly use :
```
import csv
```
in your program
Thanks
|
for python 3, you should run this command:
```
pip install python-csv
```
|
41,061,824
|
I have a problem with installing csv package in pycharm (running under python 3.5.2)
When I try to install it I get an error saying
Executed command:
`pip install --user csv`
Error occurred:
Non-zero exit code (1)
Could not find a version that satisfies the requirement csv (from versions: )
No matching distribution found for csv
I updated the pip package to version 9.0.1 but still nothing.
When I run the following code:
```
import csv
f = open('fl.csv')
csv_f = csv.reader(f)
f.close()
```
I get this error:
csv\_f = csv.reader(f)
AttributeError: module 'csv' has no attribute 'reader'
I thought it was because I could not install the "csv package"
also I tried running:
```
import csv
print(dir(csv))
```
and the print result is:
['**doc**', '**loader**', '**name**', '**package**', '**path**', '**spec**']
A lot of methods including csv.reader are missing
This is pretty much all the useful information up until comment #29
|
2016/12/09
|
[
"https://Stackoverflow.com/questions/41061824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4005127/"
] |
You can't `pip install csv` because the csv module is included in the Python installation.
You can directly use :
```
import csv
```
in your program
Thanks
|
You should go to Terminal in PyCharm and type:
```
pip3 install python-csv
```
|
41,061,824
|
I have a problem with installing csv package in pycharm (running under python 3.5.2)
When I try to install it I get an error saying
Executed command:
`pip install --user csv`
Error occurred:
Non-zero exit code (1)
Could not find a version that satisfies the requirement csv (from versions: )
No matching distribution found for csv
I updated the pip package to version 9.0.1 but still nothing.
When I run the following code:
```
import csv
f = open('fl.csv')
csv_f = csv.reader(f)
f.close()
```
I get this error:
csv\_f = csv.reader(f)
AttributeError: module 'csv' has no attribute 'reader'
I thought it was because I could not install the "csv package"
also I tried running:
```
import csv
print(dir(csv))
```
and the print result is:
['**doc**', '**loader**', '**name**', '**package**', '**path**', '**spec**']
A lot of methods including csv.reader are missing
This is pretty much all the useful information up until comment #29
|
2016/12/09
|
[
"https://Stackoverflow.com/questions/41061824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4005127/"
] |
The problem is that you have another file in your directory called `csv.py`. And in this file you do not have a `reader` function.
Change its name to `my_csv.py`
|
You should go to Terminal in PyCharm and type:
```
pip3 install python-csv
```
|
41,061,824
|
I have a problem with installing csv package in pycharm (running under python 3.5.2)
When I try to install it I get an error saying
Executed command:
`pip install --user csv`
Error occurred:
Non-zero exit code (1)
Could not find a version that satisfies the requirement csv (from versions: )
No matching distribution found for csv
I updated the pip package to version 9.0.1 but still nothing.
When I run the following code:
```
import csv
f = open('fl.csv')
csv_f = csv.reader(f)
f.close()
```
I get this error:
csv\_f = csv.reader(f)
AttributeError: module 'csv' has no attribute 'reader'
I thought it was because I could not install the "csv package"
also I tried running:
```
import csv
print(dir(csv))
```
and the print result is:
['**doc**', '**loader**', '**name**', '**package**', '**path**', '**spec**']
A lot of methods including csv.reader are missing
This is pretty much all the useful information up until comment #29
|
2016/12/09
|
[
"https://Stackoverflow.com/questions/41061824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4005127/"
] |
1. 'csv' is an in-built package. So you dont have to install it again in Pycharm.
2. When you try to import csv, make sure that you dont have **any file**(*created by you*) named as 'csv.py' in your project folder(or Python Path Variable folders) because of this you are not actually importing 'csv' package.
|
You should go to Terminal in PyCharm and type:
```
pip3 install python-csv
```
|
41,061,824
|
I have a problem with installing csv package in pycharm (running under python 3.5.2)
When I try to install it I get an error saying
Executed command:
`pip install --user csv`
Error occurred:
Non-zero exit code (1)
Could not find a version that satisfies the requirement csv (from versions: )
No matching distribution found for csv
I updated the pip package to version 9.0.1 but still nothing.
When I run the following code:
```
import csv
f = open('fl.csv')
csv_f = csv.reader(f)
f.close()
```
I get this error:
csv\_f = csv.reader(f)
AttributeError: module 'csv' has no attribute 'reader'
I thought it was because I could not install the "csv package"
also I tried running:
```
import csv
print(dir(csv))
```
and the print result is:
['**doc**', '**loader**', '**name**', '**package**', '**path**', '**spec**']
A lot of methods including csv.reader are missing
This is pretty much all the useful information up until comment #29
|
2016/12/09
|
[
"https://Stackoverflow.com/questions/41061824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4005127/"
] |
for python 3, you should run this command:
```
pip install python-csv
```
|
You should go to Terminal in PyCharm and type:
```
pip3 install python-csv
```
|
47,900,257
|
I have the Python Extensions for Windows installed. Within the PythonWin IDE I can get autocomplete on Automation objects (specifically, objects created with `win32com.client.Dispatch`):
[](https://i.stack.imgur.com/uxxkh.png)
How can I get the same autocomplete in VS Code?
I am using the [Microsoft Python extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python).
The Python Windows Extensions has a tool called COM Makepy, which apparently generates Python representations of Automation objects, but I can't figure out how to use it.
**Update**
Apparently, the Microsoft Python extension uses [Jedi](https://github.com/davidhalter/jedi) for autocompletion.
I've filed an [issue](https://github.com/Microsoft/vscode-python/issues/487) on the extension project on Github.
Note that in general I have Intellisense in Python; it's only the Intellisense on Automation objects that I am missing.
|
2017/12/20
|
[
"https://Stackoverflow.com/questions/47900257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/111794/"
] |
I don't think that the example you show with `PythonWin` is easily reproducible in VS Code. The quick start guide of `win32com` itself (cited below) says, its only possible with a COM browser or the documentation of the product (Word in this case). The latter one is unlikely, so `PythonWin` is probably using a COM browser to find the properties. And because `PythonWin` and `win32com` come in the same package, its not that unlikely that `PythonWin` has a COM browser built in.
>
> **How do I know which methods and properties are available?**
>
>
> Good question. This is hard! You need to use the documentation with the
> products, or possibly a COM browser. Note however that COM browsers
> typically rely on these objects registering themselves in certain
> ways, and many objects to not do this. You are just expected to know.
>
>
>
If you wanted the same functionality from the [VS Code plugin](https://marketplace.visualstudio.com/items?itemName=ms-python.python) a COM browser would have to be implemented into [Jedi](https://github.com/davidhalter/jedi) (IntelliSense of the VS Code plugin).
**Edit:** I found [this](https://wingware.com/pipermail/wingide-users/2016-August/011203.html) suggestion, on how a auto-complete, that can find these hidden attributes, could be done:
>
> These wrappers do various things that make static analysis difficult,
> unless we were to special case them. The general solution for such
> cases is to run to a breakpoint and work in the live runtime state.
> The auto-completer should then include the complete list of symbols
> because it inspects the runtime.
>
>
>
The conversation is from an mailing list of the python IDE [wingwide](https://wingware.com). [Here](https://wingware.com/doc/edit/auto-completion) you can see, that they implemented the above mentioned approach:
[](https://i.stack.imgur.com/dE6M7.png)
|
I think your problem is related to defining `Python interpreter`.
Choose proper Python interpreter by executing `python interpreter` command in `VS Code` command palette by pressing **`f1`** or **`ctrl+shift+p`** key.
|
47,900,257
|
I have the Python Extensions for Windows installed. Within the PythonWin IDE I can get autocomplete on Automation objects (specifically, objects created with `win32com.client.Dispatch`):
[](https://i.stack.imgur.com/uxxkh.png)
How can I get the same autocomplete in VS Code?
I am using the [Microsoft Python extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python).
The Python Windows Extensions has a tool called COM Makepy, which apparently generates Python representations of Automation objects, but I can't figure out how to use it.
**Update**
Apparently, the Microsoft Python extension uses [Jedi](https://github.com/davidhalter/jedi) for autocompletion.
I've filed an [issue](https://github.com/Microsoft/vscode-python/issues/487) on the extension project on Github.
Note that in general I have Intellisense in Python; it's only the Intellisense on Automation objects that I am missing.
|
2017/12/20
|
[
"https://Stackoverflow.com/questions/47900257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/111794/"
] |
*Review*
I have confirmed your problem in VSCode, although it may be possible IntelliSense works fine. Note Ctrl+Space invokes suggestions for a *pre-defined* variable:
[](https://i.stack.imgur.com/B9Zq2.png)
However, there does not appear to be public attributes available for `win32com.client` by default. This may be why IntelliSense does not appear to work.
*Test*
Having [installed `win32com`](https://stackoverflow.com/questions/23864234/importerror-no-module-named-win32com-client) for Python 3.6, I have confirmed the following code in Jupyter notebook, IPython console and the native Python REPL:
```
import win32com.client
app = win32com.client.Dispatch("Word.Application")
len(dir(app))
# 55
[x for x in dir(app) if not x.startswith("_")]
# []
```
This issue of hidden attributes is [not a new](https://wingware.com/pipermail/wingide-users/2016-August/011202.html). Please confirm this test in another environment/IDE. It may be your environment or particular version of PythonWin pre-loads certain variables in the global namespace.
Verify the following:
* The [Python extension](https://code.visualstudio.com/docs) is installed
* A [Python interpreter is selected](https://code.visualstudio.com/docs/python/python-tutorial#_select-a-python-interpreter)
* A [Python file is selected](https://code.visualstudio.com/docs/python/python-tutorial#_create-a-python-hello-world-source-code-file); this starts up the Python server
*References*
* [Post by the extension's creator](https://donjayamanne.github.io/pythonVSCodeDocs/docs/troubleshooting_intellisense/) for troubleshooting autocompletion issues.
* [Thread on how autocompletion works via PyScriptor](https://groups.google.com/forum/#!msg/pyscripter/TadjX_PO4fo/EXAcsqHZNS0J)
|
I think your problem is related to defining `Python interpreter`.
Choose proper Python interpreter by executing `python interpreter` command in `VS Code` command palette by pressing **`f1`** or **`ctrl+shift+p`** key.
|
12,756,885
|
I've looked at all the other questions like this and they all seem to be a slight variation of this one in which I can't extract an answer for my problem.
```
>>> import numpy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named numpy
```
So I installed it with homebrew into the site-packages directory. At this point in time, importing numpy worked. But then when I had trouble downloading matplotlib, I downloaded the original python 2.7 as opposed to the one that comes on Mac. Now I can't import the module unless I' in the numpy directory, and when I try to build matplotlib it can't find numpy (which is a dependency). Any ideas on what could be wrong?
|
2012/10/06
|
[
"https://Stackoverflow.com/questions/12756885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1217616/"
] |
Third-party add-ons ("distributions") to Python, like `numpy`, are installed to a particular instance of Python. On OS X 10.8 (Mountain Lion), the Apple-supplied Python 2.7 comes with a version of `numpy` pre-installed. You can access that python with:
```
/usr/bin/python2.7
```
I'm not sure what you mean by "downloaded the original python2.7", but if you installed another version of python, you would need to install another version of `numpy` using it.
|
If Your Numpy not install during python 2.7 installation so you can download numpy and install easly from this link [install link](http://www.iram.fr/IRAMFR/GILDAS/doc/html/gildas-python-html/node38.html)
|
29,786,474
|
I execute `launchctl start com.xxx.xxx.plist`
I can find `AutoMakeLog.err` and the content :
```
Traceback (most recent call last):
File "/Users/xxxx/Downloads/Kevin/auto.py", line 67, in <module>
output = open(file_name, 'w')
IOError: [Errno 13] Permission denied: '2015-04-22-09:15:40.log'
```
plist content :
```
<array>
<string>/Users/xxxx/Downloads/Kevin/auto.sh</string>
</array>
<key>StartCalendarInterval</key>
<dict>
<key>Minute</key>
<integer>30</integer>
<key>Hour</key>
<integer>08</integer>
</dict>
<key>StandardOutPath</key>
<string>/Users/xxxx/Downloads/Kevin/AutoMakeLog.log</string>
<key>StandardErrorPath</key>
<string>/Users/xxx/Downloads/Kevin/AutoMakeLog.err</string>
```
auto.sh
```
#!/bin/sh
/usr/bin/python /Users/xxxx/Downloads/Kevin/auto.py
```
auto.py
```
file_name = time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time()))
file_name += '.log'
output = open(file_name, 'w')
output.writelines(response.text)
output.close()
```
auto.sh and auto.py have chomd 777
PS: I direct execution auto.sh there is nothing error.
|
2015/04/22
|
[
"https://Stackoverflow.com/questions/29786474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1327056/"
] |
`int[]` is an `integer array` type.
`int` is an `integer` type.
You can't convert an array to a number.
|
You have multiple problems in the code. declare int as integer, initialise Questions and You have to convert String to integer before assigning it to question.
```
int i = 0;
int [] question = new int [100];
question[i++] = Integer.parseInt(line[0]);
```
|
29,786,474
|
I execute `launchctl start com.xxx.xxx.plist`
I can find `AutoMakeLog.err` and the content :
```
Traceback (most recent call last):
File "/Users/xxxx/Downloads/Kevin/auto.py", line 67, in <module>
output = open(file_name, 'w')
IOError: [Errno 13] Permission denied: '2015-04-22-09:15:40.log'
```
plist content :
```
<array>
<string>/Users/xxxx/Downloads/Kevin/auto.sh</string>
</array>
<key>StartCalendarInterval</key>
<dict>
<key>Minute</key>
<integer>30</integer>
<key>Hour</key>
<integer>08</integer>
</dict>
<key>StandardOutPath</key>
<string>/Users/xxxx/Downloads/Kevin/AutoMakeLog.log</string>
<key>StandardErrorPath</key>
<string>/Users/xxx/Downloads/Kevin/AutoMakeLog.err</string>
```
auto.sh
```
#!/bin/sh
/usr/bin/python /Users/xxxx/Downloads/Kevin/auto.py
```
auto.py
```
file_name = time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time()))
file_name += '.log'
output = open(file_name, 'w')
output.writelines(response.text)
output.close()
```
auto.sh and auto.py have chomd 777
PS: I direct execution auto.sh there is nothing error.
|
2015/04/22
|
[
"https://Stackoverflow.com/questions/29786474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1327056/"
] |
You have declared variable `i` as an `int` array and using it to track index of `question[]`. Indices in arrays are represented by 0,1,2,3... which are of type regular `int` and not `int[]`. So you're getting the error `int[] cannot be converted to int`
**Solution:**
Change `int[] i = new int[0];` to `int i = 0;`
And also you have more problems in your code. You're not incrementing index value of `question[]`. So you're always copying the result from `line[]` array into 1st element of `question[]` which makes all the other elements in your array useless. Instead of using `String array`, use `StringBuilder` to save the value.
|
You have multiple problems in the code. declare int as integer, initialise Questions and You have to convert String to integer before assigning it to question.
```
int i = 0;
int [] question = new int [100];
question[i++] = Integer.parseInt(line[0]);
```
|
49,776,619
|
I'm learning flask web microframework and after initialization of my database I run `flask db init` I run `flask db migrate`, to migrate my models classes to the database and i got an error. I work on Windows 10, the database is MySQL, and extensions install are `flask-migrate`, `flask-sqlalchemy`, `flask-login`.
```
(env) λ flask db migrate
Traceback (most recent call last):
File "c:\python36\Lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\python36\Lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\aka\Dev\dream-team\env\Scripts\flask.exe\__main__.py", line 9, in <module>
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 513, in main
cli.main(args=args, prog_name=name)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 380, in main
return AppGroup.main(self, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 697, in main
rv = self.invoke(ctx)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 257, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\cli.py", line 90, in migrate
rev_id, x_arg)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\__init__.py", line 197, in migrate
version_path=version_path, rev_id=rev_id)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\command.py", line 176, in revision
script_directory.run_env()
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\script\base.py", line 427, in run_env
util.load_python_file(self.dir, 'env.py')
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\pyfiles.py", line 81, in load_python_file
module = load_module_py(module_id, path)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\compat.py", line 83, in load_module_py
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "migrations\env.py", line 87, in <module>
run_migrations_online()
File "migrations\env.py", line 70, in run_migrations_online
poolclass=pool.NullPool)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 465, in engine_from_config
return create_engine(url, **options)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 424, in create_engine
return strategy.create(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\strategies.py", line 50, in create
u = url.make_url(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 211, in make_url
return _parse_rfc1738_args(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 270, in _parse_rfc1738_args
"Could not parse rfc1738 URL from string '%s'" % name)
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'mysql/dt_admin:dt2016@localhost/dreamteam_db'
```
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49776619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8559808/"
] |
i'd forget the port number to enter the port, this is the URL connection string:
```
`SQLALCHEMY_DATABASE_URI = 'mysql://dt_admin:dt2016@localhost:3308/dreamteam_db'
```
it work now, thanks
|
For me I got this error once I was trying to fix this issue
```
raise TypeError("option values must be strings")
TypeError: option values must be strings
```
so I tried to stringify the url like so
```py
config.set_main_option(
"sqlalchemy.url", f'{os.environ.get("DATABASE_URL")}')
```
After that I got new error because `os.environ.get()` does not return the Environment Value in windows without exporting the value, here is the error I got
```
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'None'
```
So I should either export the value than get it with `os.environ.get()` or use a config file and get it like so:
```py
config.set_main_option(
"sqlalchemy.url", settings.database_url.replace("postgres://", "postgresql+asyncpg://", 1))
```
>
> A detail about how to get env vars using config file you can find it on this answer [os.environ.get() does not return the Environment Value in windows?](https://stackoverflow.com/questions/42978739/os-environ-get-does-not-return-the-environment-value-in-windows/72916628#72916628)
>
>
>
|
49,776,619
|
I'm learning flask web microframework and after initialization of my database I run `flask db init` I run `flask db migrate`, to migrate my models classes to the database and i got an error. I work on Windows 10, the database is MySQL, and extensions install are `flask-migrate`, `flask-sqlalchemy`, `flask-login`.
```
(env) λ flask db migrate
Traceback (most recent call last):
File "c:\python36\Lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\python36\Lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\aka\Dev\dream-team\env\Scripts\flask.exe\__main__.py", line 9, in <module>
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 513, in main
cli.main(args=args, prog_name=name)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 380, in main
return AppGroup.main(self, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 697, in main
rv = self.invoke(ctx)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 257, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\cli.py", line 90, in migrate
rev_id, x_arg)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\__init__.py", line 197, in migrate
version_path=version_path, rev_id=rev_id)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\command.py", line 176, in revision
script_directory.run_env()
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\script\base.py", line 427, in run_env
util.load_python_file(self.dir, 'env.py')
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\pyfiles.py", line 81, in load_python_file
module = load_module_py(module_id, path)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\compat.py", line 83, in load_module_py
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "migrations\env.py", line 87, in <module>
run_migrations_online()
File "migrations\env.py", line 70, in run_migrations_online
poolclass=pool.NullPool)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 465, in engine_from_config
return create_engine(url, **options)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 424, in create_engine
return strategy.create(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\strategies.py", line 50, in create
u = url.make_url(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 211, in make_url
return _parse_rfc1738_args(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 270, in _parse_rfc1738_args
"Could not parse rfc1738 URL from string '%s'" % name)
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'mysql/dt_admin:dt2016@localhost/dreamteam_db'
```
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49776619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8559808/"
] |
You are not using a valid URL in the connection string.
Review the documentation on how the MySQL connection URLs need to be structured: <http://docs.sqlalchemy.org/en/latest/dialects/mysql.html>.
Depending on the MySQL driver that you use the connection URL is different. For example, if you use pymysql, your URL should be:
```
mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
```
|
make sure that there is no space or newline in the **URI** string
|
49,776,619
|
I'm learning flask web microframework and after initialization of my database I run `flask db init` I run `flask db migrate`, to migrate my models classes to the database and i got an error. I work on Windows 10, the database is MySQL, and extensions install are `flask-migrate`, `flask-sqlalchemy`, `flask-login`.
```
(env) λ flask db migrate
Traceback (most recent call last):
File "c:\python36\Lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\python36\Lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\aka\Dev\dream-team\env\Scripts\flask.exe\__main__.py", line 9, in <module>
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 513, in main
cli.main(args=args, prog_name=name)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 380, in main
return AppGroup.main(self, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 697, in main
rv = self.invoke(ctx)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 257, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\cli.py", line 90, in migrate
rev_id, x_arg)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\__init__.py", line 197, in migrate
version_path=version_path, rev_id=rev_id)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\command.py", line 176, in revision
script_directory.run_env()
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\script\base.py", line 427, in run_env
util.load_python_file(self.dir, 'env.py')
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\pyfiles.py", line 81, in load_python_file
module = load_module_py(module_id, path)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\compat.py", line 83, in load_module_py
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "migrations\env.py", line 87, in <module>
run_migrations_online()
File "migrations\env.py", line 70, in run_migrations_online
poolclass=pool.NullPool)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 465, in engine_from_config
return create_engine(url, **options)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 424, in create_engine
return strategy.create(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\strategies.py", line 50, in create
u = url.make_url(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 211, in make_url
return _parse_rfc1738_args(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 270, in _parse_rfc1738_args
"Could not parse rfc1738 URL from string '%s'" % name)
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'mysql/dt_admin:dt2016@localhost/dreamteam_db'
```
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49776619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8559808/"
] |
URL in the connection string is not valid.
you can check the documentation on how the MySQL connection URLs need to be structured here : <http://docs.sqlalchemy.org/en/latest/dialects/mysql.html>.
Example syntax for postgresql with psycopg2 driver it look like this :-
```
sql_alchemy_conn = postgresql+psycopg2://ubuntu@localhost:5432/airflow
```
|
For me I got this error once I was trying to fix this issue
```
raise TypeError("option values must be strings")
TypeError: option values must be strings
```
so I tried to stringify the url like so
```py
config.set_main_option(
"sqlalchemy.url", f'{os.environ.get("DATABASE_URL")}')
```
After that I got new error because `os.environ.get()` does not return the Environment Value in windows without exporting the value, here is the error I got
```
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'None'
```
So I should either export the value than get it with `os.environ.get()` or use a config file and get it like so:
```py
config.set_main_option(
"sqlalchemy.url", settings.database_url.replace("postgres://", "postgresql+asyncpg://", 1))
```
>
> A detail about how to get env vars using config file you can find it on this answer [os.environ.get() does not return the Environment Value in windows?](https://stackoverflow.com/questions/42978739/os-environ-get-does-not-return-the-environment-value-in-windows/72916628#72916628)
>
>
>
|
49,776,619
|
I'm learning flask web microframework and after initialization of my database I run `flask db init` I run `flask db migrate`, to migrate my models classes to the database and i got an error. I work on Windows 10, the database is MySQL, and extensions install are `flask-migrate`, `flask-sqlalchemy`, `flask-login`.
```
(env) λ flask db migrate
Traceback (most recent call last):
File "c:\python36\Lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\python36\Lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\aka\Dev\dream-team\env\Scripts\flask.exe\__main__.py", line 9, in <module>
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 513, in main
cli.main(args=args, prog_name=name)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 380, in main
return AppGroup.main(self, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 697, in main
rv = self.invoke(ctx)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 257, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\cli.py", line 90, in migrate
rev_id, x_arg)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\__init__.py", line 197, in migrate
version_path=version_path, rev_id=rev_id)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\command.py", line 176, in revision
script_directory.run_env()
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\script\base.py", line 427, in run_env
util.load_python_file(self.dir, 'env.py')
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\pyfiles.py", line 81, in load_python_file
module = load_module_py(module_id, path)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\compat.py", line 83, in load_module_py
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "migrations\env.py", line 87, in <module>
run_migrations_online()
File "migrations\env.py", line 70, in run_migrations_online
poolclass=pool.NullPool)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 465, in engine_from_config
return create_engine(url, **options)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 424, in create_engine
return strategy.create(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\strategies.py", line 50, in create
u = url.make_url(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 211, in make_url
return _parse_rfc1738_args(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 270, in _parse_rfc1738_args
"Could not parse rfc1738 URL from string '%s'" % name)
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'mysql/dt_admin:dt2016@localhost/dreamteam_db'
```
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49776619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8559808/"
] |
You are not using a valid URL in the connection string.
Review the documentation on how the MySQL connection URLs need to be structured: <http://docs.sqlalchemy.org/en/latest/dialects/mysql.html>.
Depending on the MySQL driver that you use the connection URL is different. For example, if you use pymysql, your URL should be:
```
mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
```
|
For me I got this error once I was trying to fix this issue
```
raise TypeError("option values must be strings")
TypeError: option values must be strings
```
so I tried to stringify the url like so
```py
config.set_main_option(
"sqlalchemy.url", f'{os.environ.get("DATABASE_URL")}')
```
After that I got new error because `os.environ.get()` does not return the Environment Value in windows without exporting the value, here is the error I got
```
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'None'
```
So I should either export the value than get it with `os.environ.get()` or use a config file and get it like so:
```py
config.set_main_option(
"sqlalchemy.url", settings.database_url.replace("postgres://", "postgresql+asyncpg://", 1))
```
>
> A detail about how to get env vars using config file you can find it on this answer [os.environ.get() does not return the Environment Value in windows?](https://stackoverflow.com/questions/42978739/os-environ-get-does-not-return-the-environment-value-in-windows/72916628#72916628)
>
>
>
|
49,776,619
|
I'm learning flask web microframework and after initialization of my database I run `flask db init` I run `flask db migrate`, to migrate my models classes to the database and i got an error. I work on Windows 10, the database is MySQL, and extensions install are `flask-migrate`, `flask-sqlalchemy`, `flask-login`.
```
(env) λ flask db migrate
Traceback (most recent call last):
File "c:\python36\Lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\python36\Lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\aka\Dev\dream-team\env\Scripts\flask.exe\__main__.py", line 9, in <module>
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 513, in main
cli.main(args=args, prog_name=name)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 380, in main
return AppGroup.main(self, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 697, in main
rv = self.invoke(ctx)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 257, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\cli.py", line 90, in migrate
rev_id, x_arg)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\__init__.py", line 197, in migrate
version_path=version_path, rev_id=rev_id)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\command.py", line 176, in revision
script_directory.run_env()
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\script\base.py", line 427, in run_env
util.load_python_file(self.dir, 'env.py')
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\pyfiles.py", line 81, in load_python_file
module = load_module_py(module_id, path)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\compat.py", line 83, in load_module_py
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "migrations\env.py", line 87, in <module>
run_migrations_online()
File "migrations\env.py", line 70, in run_migrations_online
poolclass=pool.NullPool)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 465, in engine_from_config
return create_engine(url, **options)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 424, in create_engine
return strategy.create(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\strategies.py", line 50, in create
u = url.make_url(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 211, in make_url
return _parse_rfc1738_args(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 270, in _parse_rfc1738_args
"Could not parse rfc1738 URL from string '%s'" % name)
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'mysql/dt_admin:dt2016@localhost/dreamteam_db'
```
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49776619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8559808/"
] |
make sure that there is no space or newline in the **URI** string
|
For me I got this error once I was trying to fix this issue
```
raise TypeError("option values must be strings")
TypeError: option values must be strings
```
so I tried to stringify the url like so
```py
config.set_main_option(
"sqlalchemy.url", f'{os.environ.get("DATABASE_URL")}')
```
After that I got new error because `os.environ.get()` does not return the Environment Value in windows without exporting the value, here is the error I got
```
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'None'
```
So I should either export the value than get it with `os.environ.get()` or use a config file and get it like so:
```py
config.set_main_option(
"sqlalchemy.url", settings.database_url.replace("postgres://", "postgresql+asyncpg://", 1))
```
>
> A detail about how to get env vars using config file you can find it on this answer [os.environ.get() does not return the Environment Value in windows?](https://stackoverflow.com/questions/42978739/os-environ-get-does-not-return-the-environment-value-in-windows/72916628#72916628)
>
>
>
|
49,776,619
|
I'm learning flask web microframework and after initialization of my database I run `flask db init` I run `flask db migrate`, to migrate my models classes to the database and i got an error. I work on Windows 10, the database is MySQL, and extensions install are `flask-migrate`, `flask-sqlalchemy`, `flask-login`.
```
(env) λ flask db migrate
Traceback (most recent call last):
File "c:\python36\Lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\python36\Lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\aka\Dev\dream-team\env\Scripts\flask.exe\__main__.py", line 9, in <module>
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 513, in main
cli.main(args=args, prog_name=name)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 380, in main
return AppGroup.main(self, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 697, in main
rv = self.invoke(ctx)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 257, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\cli.py", line 90, in migrate
rev_id, x_arg)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\__init__.py", line 197, in migrate
version_path=version_path, rev_id=rev_id)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\command.py", line 176, in revision
script_directory.run_env()
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\script\base.py", line 427, in run_env
util.load_python_file(self.dir, 'env.py')
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\pyfiles.py", line 81, in load_python_file
module = load_module_py(module_id, path)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\compat.py", line 83, in load_module_py
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "migrations\env.py", line 87, in <module>
run_migrations_online()
File "migrations\env.py", line 70, in run_migrations_online
poolclass=pool.NullPool)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 465, in engine_from_config
return create_engine(url, **options)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 424, in create_engine
return strategy.create(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\strategies.py", line 50, in create
u = url.make_url(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 211, in make_url
return _parse_rfc1738_args(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 270, in _parse_rfc1738_args
"Could not parse rfc1738 URL from string '%s'" % name)
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'mysql/dt_admin:dt2016@localhost/dreamteam_db'
```
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49776619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8559808/"
] |
You are not using a valid URL in the connection string.
Review the documentation on how the MySQL connection URLs need to be structured: <http://docs.sqlalchemy.org/en/latest/dialects/mysql.html>.
Depending on the MySQL driver that you use the connection URL is different. For example, if you use pymysql, your URL should be:
```
mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
```
|
URL in the connection string is not valid.
you can check the documentation on how the MySQL connection URLs need to be structured here : <http://docs.sqlalchemy.org/en/latest/dialects/mysql.html>.
Example syntax for postgresql with psycopg2 driver it look like this :-
```
sql_alchemy_conn = postgresql+psycopg2://ubuntu@localhost:5432/airflow
```
|
49,776,619
|
I'm learning flask web microframework and after initialization of my database I run `flask db init` I run `flask db migrate`, to migrate my models classes to the database and i got an error. I work on Windows 10, the database is MySQL, and extensions install are `flask-migrate`, `flask-sqlalchemy`, `flask-login`.
```
(env) λ flask db migrate
Traceback (most recent call last):
File "c:\python36\Lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\python36\Lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\aka\Dev\dream-team\env\Scripts\flask.exe\__main__.py", line 9, in <module>
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 513, in main
cli.main(args=args, prog_name=name)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 380, in main
return AppGroup.main(self, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 697, in main
rv = self.invoke(ctx)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 257, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\cli.py", line 90, in migrate
rev_id, x_arg)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\__init__.py", line 197, in migrate
version_path=version_path, rev_id=rev_id)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\command.py", line 176, in revision
script_directory.run_env()
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\script\base.py", line 427, in run_env
util.load_python_file(self.dir, 'env.py')
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\pyfiles.py", line 81, in load_python_file
module = load_module_py(module_id, path)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\compat.py", line 83, in load_module_py
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "migrations\env.py", line 87, in <module>
run_migrations_online()
File "migrations\env.py", line 70, in run_migrations_online
poolclass=pool.NullPool)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 465, in engine_from_config
return create_engine(url, **options)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 424, in create_engine
return strategy.create(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\strategies.py", line 50, in create
u = url.make_url(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 211, in make_url
return _parse_rfc1738_args(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 270, in _parse_rfc1738_args
"Could not parse rfc1738 URL from string '%s'" % name)
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'mysql/dt_admin:dt2016@localhost/dreamteam_db'
```
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49776619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8559808/"
] |
i'd forget the port number to enter the port, this is the URL connection string:
```
`SQLALCHEMY_DATABASE_URI = 'mysql://dt_admin:dt2016@localhost:3308/dreamteam_db'
```
it work now, thanks
|
just had to remove the quotes
I was using like that:
```
sql_alchemy_conn = 'postgresql://user:password@host:port/db'
```
And this worked:
```
sql_alchemy_conn = postgresql://user:password@host:port/db
```
|
49,776,619
|
I'm learning flask web microframework and after initialization of my database I run `flask db init` I run `flask db migrate`, to migrate my models classes to the database and i got an error. I work on Windows 10, the database is MySQL, and extensions install are `flask-migrate`, `flask-sqlalchemy`, `flask-login`.
```
(env) λ flask db migrate
Traceback (most recent call last):
File "c:\python36\Lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\python36\Lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\aka\Dev\dream-team\env\Scripts\flask.exe\__main__.py", line 9, in <module>
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 513, in main
cli.main(args=args, prog_name=name)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 380, in main
return AppGroup.main(self, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 697, in main
rv = self.invoke(ctx)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 257, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\cli.py", line 90, in migrate
rev_id, x_arg)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\__init__.py", line 197, in migrate
version_path=version_path, rev_id=rev_id)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\command.py", line 176, in revision
script_directory.run_env()
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\script\base.py", line 427, in run_env
util.load_python_file(self.dir, 'env.py')
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\pyfiles.py", line 81, in load_python_file
module = load_module_py(module_id, path)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\compat.py", line 83, in load_module_py
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "migrations\env.py", line 87, in <module>
run_migrations_online()
File "migrations\env.py", line 70, in run_migrations_online
poolclass=pool.NullPool)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 465, in engine_from_config
return create_engine(url, **options)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 424, in create_engine
return strategy.create(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\strategies.py", line 50, in create
u = url.make_url(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 211, in make_url
return _parse_rfc1738_args(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 270, in _parse_rfc1738_args
"Could not parse rfc1738 URL from string '%s'" % name)
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'mysql/dt_admin:dt2016@localhost/dreamteam_db'
```
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49776619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8559808/"
] |
You are not using a valid URL in the connection string.
Review the documentation on how the MySQL connection URLs need to be structured: <http://docs.sqlalchemy.org/en/latest/dialects/mysql.html>.
Depending on the MySQL driver that you use the connection URL is different. For example, if you use pymysql, your URL should be:
```
mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
```
|
just had to remove the quotes
I was using like that:
```
sql_alchemy_conn = 'postgresql://user:password@host:port/db'
```
And this worked:
```
sql_alchemy_conn = postgresql://user:password@host:port/db
```
|
49,776,619
|
I'm learning flask web microframework and after initialization of my database I run `flask db init` I run `flask db migrate`, to migrate my models classes to the database and i got an error. I work on Windows 10, the database is MySQL, and extensions install are `flask-migrate`, `flask-sqlalchemy`, `flask-login`.
```
(env) λ flask db migrate
Traceback (most recent call last):
File "c:\python36\Lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\python36\Lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\aka\Dev\dream-team\env\Scripts\flask.exe\__main__.py", line 9, in <module>
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 513, in main
cli.main(args=args, prog_name=name)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 380, in main
return AppGroup.main(self, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 697, in main
rv = self.invoke(ctx)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 257, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\cli.py", line 90, in migrate
rev_id, x_arg)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\__init__.py", line 197, in migrate
version_path=version_path, rev_id=rev_id)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\command.py", line 176, in revision
script_directory.run_env()
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\script\base.py", line 427, in run_env
util.load_python_file(self.dir, 'env.py')
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\pyfiles.py", line 81, in load_python_file
module = load_module_py(module_id, path)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\compat.py", line 83, in load_module_py
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "migrations\env.py", line 87, in <module>
run_migrations_online()
File "migrations\env.py", line 70, in run_migrations_online
poolclass=pool.NullPool)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 465, in engine_from_config
return create_engine(url, **options)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 424, in create_engine
return strategy.create(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\strategies.py", line 50, in create
u = url.make_url(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 211, in make_url
return _parse_rfc1738_args(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 270, in _parse_rfc1738_args
"Could not parse rfc1738 URL from string '%s'" % name)
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'mysql/dt_admin:dt2016@localhost/dreamteam_db'
```
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49776619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8559808/"
] |
i'd forget the port number to enter the port, this is the URL connection string:
```
`SQLALCHEMY_DATABASE_URI = 'mysql://dt_admin:dt2016@localhost:3308/dreamteam_db'
```
it work now, thanks
|
URL in the connection string is not valid.
you can check the documentation on how the MySQL connection URLs need to be structured here : <http://docs.sqlalchemy.org/en/latest/dialects/mysql.html>.
Example syntax for postgresql with psycopg2 driver it look like this :-
```
sql_alchemy_conn = postgresql+psycopg2://ubuntu@localhost:5432/airflow
```
|
49,776,619
|
I'm learning flask web microframework and after initialization of my database I run `flask db init` I run `flask db migrate`, to migrate my models classes to the database and i got an error. I work on Windows 10, the database is MySQL, and extensions install are `flask-migrate`, `flask-sqlalchemy`, `flask-login`.
```
(env) λ flask db migrate
Traceback (most recent call last):
File "c:\python36\Lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\python36\Lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\aka\Dev\dream-team\env\Scripts\flask.exe\__main__.py", line 9, in <module>
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 513, in main
cli.main(args=args, prog_name=name)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 380, in main
return AppGroup.main(self, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 697, in main
rv = self.invoke(ctx)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask\cli.py", line 257, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\cli.py", line 90, in migrate
rev_id, x_arg)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\flask_migrate\__init__.py", line 197, in migrate
version_path=version_path, rev_id=rev_id)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\command.py", line 176, in revision
script_directory.run_env()
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\script\base.py", line 427, in run_env
util.load_python_file(self.dir, 'env.py')
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\pyfiles.py", line 81, in load_python_file
module = load_module_py(module_id, path)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\alembic\util\compat.py", line 83, in load_module_py
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "migrations\env.py", line 87, in <module>
run_migrations_online()
File "migrations\env.py", line 70, in run_migrations_online
poolclass=pool.NullPool)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 465, in engine_from_config
return create_engine(url, **options)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\__init__.py", line 424, in create_engine
return strategy.create(*args, **kwargs)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\strategies.py", line 50, in create
u = url.make_url(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 211, in make_url
return _parse_rfc1738_args(name_or_url)
File "c:\users\aka\dev\dream-team\env\lib\site-packages\sqlalchemy\engine\url.py", line 270, in _parse_rfc1738_args
"Could not parse rfc1738 URL from string '%s'" % name)
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'mysql/dt_admin:dt2016@localhost/dreamteam_db'
```
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49776619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8559808/"
] |
i'd forget the port number to enter the port, this is the URL connection string:
```
`SQLALCHEMY_DATABASE_URI = 'mysql://dt_admin:dt2016@localhost:3308/dreamteam_db'
```
it work now, thanks
|
make sure that there is no space or newline in the **URI** string
|
50,126,064
|
I've been learning about about C++ in college and one thing that interests me is the ability to create a shared header file so that all the cpp files can access the objects within. I was wondering if there is some way to do the same thing in python with variables and constants? I only know how to import and use the functions or classes in other py files.
|
2018/05/02
|
[
"https://Stackoverflow.com/questions/50126064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7944978/"
] |
First, if you've ever used `sys.argv` or `os.sep`, you've already used another module's variables and constants.
Because the way you share variables and constants is exactly the same way you share functions and classes.
In fact, functions, classes, variables, constants—they're all just module-global variables as far as Python is concerned. They may have values of different types, but they're the same kind of variable.
So, let's say you write this module:
```
# spam.py
cheese = ['Gouda', 'Edam']
def breakfast():
print(cheese[-1])
```
If you `import spam`, you can use `cheese`, exactly the same way you use `eggs`:
```
import spam
# call a function
spam.eggs()
# access a variable
print(spam.cheese)
# mutate a variable's value
spam.cheese.append('Leyden')
spam.eggs() # now it prints Leyden instead of Edam
# even rebind a variable
spam.cheese = (1, 2, 3, 4)
spam.eggs() # now it prints 4
# even rebind a function
spam.eggs = lambda: print('monkeypatched')
spam.eggs()
```
---
C++ header files are really just a poor man's modules. Not every language is as flexible as Python, but almost every language from Ruby to Rust has some kind of real module system; only C++ (and C) requires you to fake it by having code that gets included into a bunch of different files at compile time.
|
If you are just looking to make function definitions, then this post may answer your question:
[Python: How to import other Python files](https://stackoverflow.com/questions/2349991/python-how-to-import-other-python-files)
Then you can define a function as per here:
<https://www.tutorialspoint.com/python/python_functions.htm>
Or if you are looking to make a class:
<https://docs.python.org/3/tutorial/classes.html>
You can look at example 3.9.5 in the previous link in order to understand how to create a shared variable among different object instances.
|
5,971,635
|
My python script which calls many python functions and shell scripts. I want to set a environment variable in Python (main calling function) and all the daughter processes including the shell scripts to see the environmental variable set.
I need to set some environmental variables like this:
```
DEBUSSY 1
FSDB 1
```
`1` is a number, not a string. Additionally, how can I read the value stored in an environment variable? (Like `DEBUSSY`/`FSDB` in another python child script.)
|
2011/05/11
|
[
"https://Stackoverflow.com/questions/5971635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/749632/"
] |
Try using the `os` module.
```
import os
os.environ['DEBUSSY'] = '1'
os.environ['FSDB'] = '1'
# Open child processes via os.system(), popen() or fork() and execv()
someVariable = int(os.environ['DEBUSSY'])
```
See the [Python docs](http://docs.python.org/library/os.html#os.environ) on `os.environ`. Also, for spawning child processes, see Python's [subprocess docs](http://docs.python.org/library/subprocess.html#module-subprocess).
|
Use `os.environ[str(DEBUSSY)]` for both reading and writing (<http://docs.python.org/library/os.html#os.environ>).
As for reading, you have to parse the number from the string yourself of course.
|
5,971,635
|
My python script which calls many python functions and shell scripts. I want to set a environment variable in Python (main calling function) and all the daughter processes including the shell scripts to see the environmental variable set.
I need to set some environmental variables like this:
```
DEBUSSY 1
FSDB 1
```
`1` is a number, not a string. Additionally, how can I read the value stored in an environment variable? (Like `DEBUSSY`/`FSDB` in another python child script.)
|
2011/05/11
|
[
"https://Stackoverflow.com/questions/5971635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/749632/"
] |
Try using the `os` module.
```
import os
os.environ['DEBUSSY'] = '1'
os.environ['FSDB'] = '1'
# Open child processes via os.system(), popen() or fork() and execv()
someVariable = int(os.environ['DEBUSSY'])
```
See the [Python docs](http://docs.python.org/library/os.html#os.environ) on `os.environ`. Also, for spawning child processes, see Python's [subprocess docs](http://docs.python.org/library/subprocess.html#module-subprocess).
|
First things first :) reading books is an *excellent* approach to problem solving; it's the difference between band-aid fixes and long-term investments in solving problems. Never miss an opportunity to learn. :D
You might *choose* to interpret the `1` as a number, but environment variables don't care. They just pass around strings:
```
The argument envp is an array of character pointers to null-
terminated strings. These strings shall constitute the
environment for the new process image. The envp array is
terminated by a null pointer.
```
(From `environ(3posix)`.)
You access environment variables in python using the [`os.environ` dictionary-like object](http://docs.python.org/library/os.html):
```
>>> import os
>>> os.environ["HOME"]
'/home/sarnold'
>>> os.environ["PATH"]
'/home/sarnold/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'
>>> os.environ["PATH"] = os.environ["PATH"] + ":/silly/"
>>> os.environ["PATH"]
'/home/sarnold/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/silly/'
```
|
5,971,635
|
My python script which calls many python functions and shell scripts. I want to set a environment variable in Python (main calling function) and all the daughter processes including the shell scripts to see the environmental variable set.
I need to set some environmental variables like this:
```
DEBUSSY 1
FSDB 1
```
`1` is a number, not a string. Additionally, how can I read the value stored in an environment variable? (Like `DEBUSSY`/`FSDB` in another python child script.)
|
2011/05/11
|
[
"https://Stackoverflow.com/questions/5971635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/749632/"
] |
Try using the `os` module.
```
import os
os.environ['DEBUSSY'] = '1'
os.environ['FSDB'] = '1'
# Open child processes via os.system(), popen() or fork() and execv()
someVariable = int(os.environ['DEBUSSY'])
```
See the [Python docs](http://docs.python.org/library/os.html#os.environ) on `os.environ`. Also, for spawning child processes, see Python's [subprocess docs](http://docs.python.org/library/subprocess.html#module-subprocess).
|
If you want to pass global variables into new scripts, you can create a python file that is only meant for holding global variables (e.g. globals.py). When you import this file at the top of the child script, it should have access to all of those variables.
If you are writing to these variables, then that is a different story. That involves concurrency and locking the variables, which I'm not going to get into unless you want.
|
5,971,635
|
My python script which calls many python functions and shell scripts. I want to set a environment variable in Python (main calling function) and all the daughter processes including the shell scripts to see the environmental variable set.
I need to set some environmental variables like this:
```
DEBUSSY 1
FSDB 1
```
`1` is a number, not a string. Additionally, how can I read the value stored in an environment variable? (Like `DEBUSSY`/`FSDB` in another python child script.)
|
2011/05/11
|
[
"https://Stackoverflow.com/questions/5971635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/749632/"
] |
First things first :) reading books is an *excellent* approach to problem solving; it's the difference between band-aid fixes and long-term investments in solving problems. Never miss an opportunity to learn. :D
You might *choose* to interpret the `1` as a number, but environment variables don't care. They just pass around strings:
```
The argument envp is an array of character pointers to null-
terminated strings. These strings shall constitute the
environment for the new process image. The envp array is
terminated by a null pointer.
```
(From `environ(3posix)`.)
You access environment variables in python using the [`os.environ` dictionary-like object](http://docs.python.org/library/os.html):
```
>>> import os
>>> os.environ["HOME"]
'/home/sarnold'
>>> os.environ["PATH"]
'/home/sarnold/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'
>>> os.environ["PATH"] = os.environ["PATH"] + ":/silly/"
>>> os.environ["PATH"]
'/home/sarnold/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/silly/'
```
|
Use `os.environ[str(DEBUSSY)]` for both reading and writing (<http://docs.python.org/library/os.html#os.environ>).
As for reading, you have to parse the number from the string yourself of course.
|
5,971,635
|
My python script which calls many python functions and shell scripts. I want to set a environment variable in Python (main calling function) and all the daughter processes including the shell scripts to see the environmental variable set.
I need to set some environmental variables like this:
```
DEBUSSY 1
FSDB 1
```
`1` is a number, not a string. Additionally, how can I read the value stored in an environment variable? (Like `DEBUSSY`/`FSDB` in another python child script.)
|
2011/05/11
|
[
"https://Stackoverflow.com/questions/5971635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/749632/"
] |
If you want to pass global variables into new scripts, you can create a python file that is only meant for holding global variables (e.g. globals.py). When you import this file at the top of the child script, it should have access to all of those variables.
If you are writing to these variables, then that is a different story. That involves concurrency and locking the variables, which I'm not going to get into unless you want.
|
Use `os.environ[str(DEBUSSY)]` for both reading and writing (<http://docs.python.org/library/os.html#os.environ>).
As for reading, you have to parse the number from the string yourself of course.
|
5,971,635
|
My python script which calls many python functions and shell scripts. I want to set a environment variable in Python (main calling function) and all the daughter processes including the shell scripts to see the environmental variable set.
I need to set some environmental variables like this:
```
DEBUSSY 1
FSDB 1
```
`1` is a number, not a string. Additionally, how can I read the value stored in an environment variable? (Like `DEBUSSY`/`FSDB` in another python child script.)
|
2011/05/11
|
[
"https://Stackoverflow.com/questions/5971635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/749632/"
] |
First things first :) reading books is an *excellent* approach to problem solving; it's the difference between band-aid fixes and long-term investments in solving problems. Never miss an opportunity to learn. :D
You might *choose* to interpret the `1` as a number, but environment variables don't care. They just pass around strings:
```
The argument envp is an array of character pointers to null-
terminated strings. These strings shall constitute the
environment for the new process image. The envp array is
terminated by a null pointer.
```
(From `environ(3posix)`.)
You access environment variables in python using the [`os.environ` dictionary-like object](http://docs.python.org/library/os.html):
```
>>> import os
>>> os.environ["HOME"]
'/home/sarnold'
>>> os.environ["PATH"]
'/home/sarnold/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'
>>> os.environ["PATH"] = os.environ["PATH"] + ":/silly/"
>>> os.environ["PATH"]
'/home/sarnold/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/silly/'
```
|
If you want to pass global variables into new scripts, you can create a python file that is only meant for holding global variables (e.g. globals.py). When you import this file at the top of the child script, it should have access to all of those variables.
If you are writing to these variables, then that is a different story. That involves concurrency and locking the variables, which I'm not going to get into unless you want.
|
3,148,352
|
Need Help Creating GAE Datastore Loader Class for uploading data using appcfg.py?
Any other way to simplified this process?
is there any detailed example better than [here](http://code.google.com/appengine/docs/python/tools/uploadingdata.html)
When try using bulkloader.yaml:
```
Uploading data records.
[INFO ] Logging to bulkloader-log-20100701.041515
[INFO ] Throttling transfers:
[INFO ] Bandwidth: 250000 bytes/second
[INFO ] HTTP connections: 8/second
[INFO ] Entities inserted/fetched/modified: 20/second
[INFO ] Batch Size: 10
[INFO ] Opening database: bulkloader-progress-20100701.041515.sql3
[INFO ] Connecting to livelihoodproducer.appspot.com/remote_api
[INFO ] Starting import; maximum 10 entities per post
[ERROR ] [Thread-1] WorkerThread:
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/adaptive_thread_pool.py", line 150, in WorkOnItems
status, instruction = item.PerformWork(self.__thread_pool)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/bulkloader.py", line 693, in PerformWork
transfer_time = self._TransferItem(thread_pool)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/bulkloader.py", line 848, in _TransferItem
self.content = self.request_manager.EncodeContent(self.rows)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/bulkloader.py", line 1269, in EncodeContent
entity = loader.create_entity(values, key_name=key, parent=parent)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/bulkload/bulkloader_config.py", line 385, in create_entity
return self.dict_to_entity(input_dict, self.bulkload_state)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/bulkload/bulkloader_config.py", line 133, in dict_to_entity
self.__run_import_transforms(input_dict, instance, bulkload_state_copy)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/bulkload/bulkloader_config.py", line 233, in __run_import_transforms
value = self.__dict_to_prop(transform, input_dict, bulkload_state)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/bulkload/bulkloader_config.py", line 188, in __dict_to_prop
value = transform.import_transform(value)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/bulkload/bulkloader_parser.py", line 93, in __call__
return self.method(*args, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/bulkload/transform.py", line 143, in generate_foreign_key_lambda
return datastore.Key.from_path(kind, value)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/datastore_types.py", line 387, in from_path
'received %r (a %s).' % (i + 2, id_or_name, typename(id_or_name)))
BadArgumentError: Expected an integer id or string name as argument 2; received None (a NoneType).
[INFO ] [Thread-3] Backing off due to errors: 1.0 seconds
[INFO ] Unexpected thread death: Thread-1
[INFO ] An error occurred. Shutting down...
[ERROR ] Error in Thread-1: Expected an integer id or string name as argument 2; received None (a NoneType).
[INFO ] 30 entites total, 0 previously transferred
[INFO ] 0 entities (733 bytes) transferred in 2.8 seconds
[INFO ] Some entities not successfully transferred
```
In the process, i've downloadeded csv data manually inserted on appspot.com. While i try to upload my own csv data, the column order should made exactly like csv downloaded from appspot.com? how about blank value?
|
2010/06/30
|
[
"https://Stackoverflow.com/questions/3148352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/288541/"
] |
I've created config.yaml with bulkloader config, and also written simple helper function to process None-references. I don't know why it's not done in original helper.
The helper (file `helpers.py` is very simple, just place it to the same directory where you placed `config.yaml`):
```
from google.appengine.api import datastore
def create_foreign_key(kind, key_is_id=False):
def generate_foreign_key_lambda(value):
if value is None:
return None
if key_is_id:
value = int(value)
return datastore.Key.from_path(kind, value)
return generate_foreign_key_lambda
```
And this is cut from my `config.yaml`:
```
python_preamble:
- import: helpers # this will import our helper
[other imports]
...
- kind: ArticleComment
connector: simplexml
connector_options:
xpath_to_nodes: "/blog/Comments/Comment"
style: element_centric
property_map:
- property: __key__
external_name: key
export_transform: transform.key_id_or_name_as_string
- property: parent_comment
external_name: parent-comment
export_transform: transform.key_id_or_name_as_string
import_transform: helpers.create_foreign_key('ArticleComment')
# ^^^^^^^ here it is
# use this instead of transform.create_foreign_key
```
|
It looks like you have reference properties with None values, such values are handled incorrectly by bulkloader's helpers.
|
68,490,787
|
Any time I make a change in the view, and HTML, or CSS, I have to stop and re-run
```
python manage.py runserver
```
for my changes to be dispayed. This is very annoying because it wastes a lot of my time trying to find the terminal and run it again. Is there a workaround for this?
|
2021/07/22
|
[
"https://Stackoverflow.com/questions/68490787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14296523/"
] |
`python manage.py runserver` should normally perform hot reload on your Django application, except you've updated the config in the settings.py file. Check if `DEBUG = True` in settings.py
|
My advice is to use Vscode for Django developing because it gives you autosave feature so you don't have to stop and rerun the server the only thing you have to do is reload the web page. I hope it might be helpful
|
11,590,082
|
I am using python and sqlite3 to handle a website. I need all timezones to be in localtime, and I need daylight savings to be accounted for. The ideal method to do this would be to use sqlite to set a global datetime('now') to be +10 hours.
If I can work out how to change sqlite's 'now' with a command, then I was going to use a cronjob to adjust it (I would happily go with an easier method if anyone has one, but cronjob isn't too hard)
|
2012/07/21
|
[
"https://Stackoverflow.com/questions/11590082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1503619/"
] |
I'm not 100% on what you're asking, but to keep this simple I would say store your dates in UTC, and present them as local time if need be:
```
sqlite> select datetime('now', 'utc');
2012-07-21 09:58:21
sqlite> select datetime('now', 'localtime');
2012-07-21 13:58:33
```
See SQLite's [date and time functions documentation](http://www.sqlite.org/lang_datefunc.html).
|
you can try this code, I am in Taiwan , so I add 8 hours:
`DateTime('now','+8 hours')`
|
9,597,122
|
I have established a basic hadoop master slave cluster setup and able to run mapreduce programs (including python) on the cluster.
Now I am trying to run a python code which accesses a C binary and so I am using the subprocess module. I am able to use the hadoop streaming for a normal python code but when I include the subprocess module to access a binary, the job is getting failed.
As you can see in the below logs, the hello executable is recognised to be used for the packaging, but still not able to run the code.
.
.
packageJobJar: [**/tmp/hello/hello**, /app/hadoop/tmp/hadoop-unjar5030080067721998885/] [] /tmp/streamjob7446402517274720868.jar tmpDir=null
```
JarBuilder.addNamedStream hello
.
.
12/03/07 22:31:32 INFO mapred.FileInputFormat: Total input paths to process : 1
12/03/07 22:31:32 INFO streaming.StreamJob: getLocalDirs(): [/app/hadoop/tmp/mapred/local]
12/03/07 22:31:32 INFO streaming.StreamJob: Running job: job_201203062329_0057
12/03/07 22:31:32 INFO streaming.StreamJob: To kill this job, run:
12/03/07 22:31:32 INFO streaming.StreamJob: /usr/local/hadoop/bin/../bin/hadoop job -Dmapred.job.tracker=master:54311 -kill job_201203062329_0057
12/03/07 22:31:32 INFO streaming.StreamJob: Tracking URL: http://master:50030/jobdetails.jsp?jobid=job_201203062329_0057
12/03/07 22:31:33 INFO streaming.StreamJob: map 0% reduce 0%
12/03/07 22:32:05 INFO streaming.StreamJob: map 100% reduce 100%
12/03/07 22:32:05 INFO streaming.StreamJob: To kill this job, run:
12/03/07 22:32:05 INFO streaming.StreamJob: /usr/local/hadoop/bin/../bin/hadoop job -Dmapred.job.tracker=master:54311 -kill job_201203062329_0057
12/03/07 22:32:05 INFO streaming.StreamJob: Tracking URL: http://master:50030/jobdetails.jsp?jobid=job_201203062329_0057
12/03/07 22:32:05 ERROR streaming.StreamJob: Job not Successful!
12/03/07 22:32:05 INFO streaming.StreamJob: killJob...
Streaming Job Failed!
```
Command I am trying is :
```
hadoop jar contrib/streaming/hadoop-*streaming*.jar -mapper /home/hduser/MARS.py -reducer /home/hduser/MARS_red.py -input /user/hduser/mars_inputt -output /user/hduser/mars-output -file /tmp/hello/hello -verbose
```
where hello is the C executable. It is a simple helloworld program which I am using to check the basic functioning.
My Python code is :
```
#!/usr/bin/env python
import subprocess
subprocess.call(["./hello"])
```
Any help with how to get the executable run with Python in hadoop streaming or help with debugging this will get me forward in this.
Thanks,
Ganesh
|
2012/03/07
|
[
"https://Stackoverflow.com/questions/9597122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1253987/"
] |
Used simple id and hash token like Amazon for now...
|
Your site can absolutely be an OAuth server (to clients) and an OAuth consumer (of other APIs) at the same time, the same way that a hairdresser can also be the customer of another hairdresser.
|
72,720,385
|
I created a model like this.
```
class BloodDiscard(models.Model):
timestamp = models.DateTimeField(auto_now_add=True, blank=True)
created_by = models.ForeignKey(Registration, on_delete=models.SET_NULL, null=True)
blood_group = models.ForeignKey(BloodGroupMaster, on_delete=models.SET_NULL, null=True)
blood_cells = models.ForeignKey(BloodCellsMaster, on_delete=models.SET_NULL, null=True)
quantity = models.FloatField()
```
But now I need to apply inheritance to my model, like this. [(models.Model) ---> (BaseModel)]
```
class BloodDiscard(BaseModel):
timestamp = models.DateTimeField(auto_now_add=True, blank=True)
created_by = models.ForeignKey(Registration, on_delete=models.SET_NULL, null=True)
blood_group = models.ForeignKey(BloodGroupMaster, on_delete=models.SET_NULL, null=True)
blood_cells = models.ForeignKey(BloodCellsMaster, on_delete=models.SET_NULL, null=True)
quantity = models.FloatField()
```
BaseModel is another model I created before but forgot to inherit it in my current model.
```
class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
status_master = models.ForeignKey(StatusMaster,on_delete=models.SET_NULL,default=3,null=True, blank=True)
```
I applied "python manage.py makemigrations" after changing (models.Model) ---> (BaseModel) and got this...
```
(venv) G:\office\medicover\medicover_bloodbank_django>python manage.py makemigrations
You are trying to add the field 'created_at' with 'auto_now_add=True' to blooddiscard without a default; the database needs something to populate existing rows.
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
You can accept the default 'timezone.now' by pressing 'Enter' or you can provide another value.
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
[default: timezone.now] >>>
Migrations for 'Form':
Form\migrations\0018_auto_20220622_2322.py
- Add field created_at to blooddiscard
- Add field status_master to blooddiscard
- Add field updated_at to blooddiscard
```
But after that when I am applying "python manage.py migrate". I am getting this error.
```
(venv) G:\office\medicover\medicover_bloodbank_django>python manage.py migrate
Operations to perform:
Apply all migrations: Form, Master, User, admin, auth, contenttypes, sessions
Running migrations:
Applying Form.0018_auto_20220622_2322...Traceback (most recent call last):
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.ForeignKeyViolation: insert or update on table "Form_blooddiscard" violates foreign key constraint "Form_blooddiscard_status_master_id_ffe293fa_fk_Master_st"
DETAIL: Key (status_master_id)=(3) is not present in table "Master_statusmaster".
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle
post_migrate_state = executor.migrate(
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration
state = migration.apply(state, schema_editor)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\migrations\migration.py", line 126, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards
schema_editor.add_field(
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\base\schema.py", line 522, in add_field
self.execute(sql, params)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\base\schema.py", line 145, in execute
cursor.execute(sql, params)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: insert or update on table "Form_blooddiscard" violates foreign key constraint "Form_blooddiscard_status_master_id_ffe293fa_fk_Master_st"
DETAIL: Key (status_master_id)=(3) is not present in table "Master_statusmaster".
```
And when doing "python manage.py runserver" getting this...
```
(venv) G:\office\medicover\medicover_bloodbank_django>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): Form.
Run 'python manage.py migrate' to apply them.
June 22, 2022 - 23:23:51
Django version 3.2.5, using settings 'App.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
```
**NOTE:-**
In StatusMaster table there's only two rows having id's 1 and 2.
|
2022/06/22
|
[
"https://Stackoverflow.com/questions/72720385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15809668/"
] |
You can use the `matplotlib`'s `Dateformatter`. Updated code and plot below. I did notice that the `Date` column you posted had dates on 2nd and 17th. I changed those to show everything on the 2nd. Otherwise, there would be too many entries. Hope this helps...
```
df = pd.DataFrame({"Date":["2015-02-02 10:19:00","2015-02-02 12:22:00","2015-02-02 14:57:00","2015-02-02 16:58:59"],"Occurrence":[1,0,1,1]})
df["Date"] = pd.to_datetime(df["Date"])
import seaborn as sns
sns.set_theme(style="darkgrid")
ax = sns.lineplot(x="Date", y="Occurrence", data=df)
import matplotlib.dates as mdates
ax.xaxis.set_major_locator(mdates.HourLocator(interval=2))
# set formatter
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
```
**Output Plot**
[](https://i.stack.imgur.com/FAQm4.png)
|
You would want to convert your ['Date'] column to only include time information, im not sure if you want the data to be ordered by date or not but that should just show time information on the X-axis:
```
df['Date'].dt.time
```
|
5,043,188
|
i have a trouble with run django project on production server with Apache and mod\_wsgi. This Error happened when i'm start apache and go to site first time or go from other:
>
> ImportError at /
>
> Exception Value: cannot import name MyName
>
> Exception Location /var/www/projectname/appname/somemodule.py
>
>
>
When i'm reload page the error disappears and site work fine. Another point is that this error happened selectively and sometime not appear.
In project i'm use imports without project name prefix (i mean 'from accounts.models import Account' instead 'from projectname.accounts.models import Account').
On development (manage.py runserver) server all work fine without any troubles.
I have used many variations of my apache and wsgi script configurations but problem is not solved.
Here my current projectname.wsgi:
```
#!/usr/bin/env python
import os, sys, re
sys.path.append('/var/www/projectname')
sys.path.append('/var/www')
os.environ['PYTHON_EGG_CACHE'] = '/var/www/projectname/.python-egg'
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
```
Here is some parts from apache config:
```
<VirtualHost ip:80>
ServerAdmin admin@server.com
DocumentRoot /var/www
ServerName www.projectname.com
WSGIScriptAlias / "/var/www/projectname/projectname.wsgi"
WSGIDaemonProcess projectname threads=5 maximum-requests=5000
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
....
```
Also i'm use a separate Virtual Host for SSL.
I hope somebody help me.
Thanks!
|
2011/02/18
|
[
"https://Stackoverflow.com/questions/5043188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337077/"
] |
```
php -i | more
```
should work on both Linux and Unix. On Linux, though, `more` is simply an alias for the equivalent `less`
|
On Linux you could do from the shell
```
php -r "phpinfo();" | less
```
|
33,124,269
|
I have been following a Caffe example [here](http://nbviewer.ipython.org/github/BVLC/caffe/blob/master/examples/00-classification.ipynb) to plot the Convolution kernels from my ConvNet. I have attached an image below of my kernels, however it looks nothing like the kernels in the example. I have followed the example exactly, anyone know what the issue may be?
My net is trained on a set of simulated images (with two classes) and the performance of the net is pretty good, around 80% test accuracy.
[](https://i.stack.imgur.com/iwWNU.png)
```
layer {
name: "input"
type: "Data"
top: "data"
top: "label"
include {
phase: TRAIN
}
transform_param {
mean_file: "/tmp/stage5/mean/mean.binaryproto"
}
data_param {
source: "/tmp/stage5/train/train-lmdb"
batch_size: 100
backend: LMDB
}
}
layer {
name: "input"
type: "Data"
top: "data"
top: "label"
include {
phase: TEST
}
transform_param {
mean_file: "/tmp/stage5/mean/mean.binaryproto"
}
data_param {
source: "/tmp/stage5/validation/validation-lmdb"
batch_size: 10
backend: LMDB
}
}
layer {
name: "conv1"
type: "Convolution"
bottom: "data"
top: "conv1"
param {
lr_mult: 1.0
}
param {
lr_mult: 2.0
}
convolution_param {
num_output: 40
kernel_size: 5
stride: 1
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "pool1"
type: "Pooling"
bottom: "conv1"
top: "pool1"
pooling_param {
pool: MAX
kernel_size: 3
stride: 2
}
}
layer {
name: "ip1"
type: "InnerProduct"
bottom: "pool1"
top: "ip1"
param {
lr_mult: 1.0
}
param {
lr_mult: 2.0
}
inner_product_param {
num_output: 500
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "ip2"
type: "InnerProduct"
bottom: "ip1"
top: "ip2"
param {
lr_mult: 1.0
}
param {
lr_mult: 2.0
}
inner_product_param {
num_output: 2
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "loss"
type: "SoftmaxWithLoss"
bottom: "ip2"
bottom: "label"
top: "loss"
}
```
|
2015/10/14
|
[
"https://Stackoverflow.com/questions/33124269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5321075/"
] |
Twilio developer evangelist here.
You absolutely can do app to app calls using the iOS SDK. Let me explain.
Your Twilio Client capability token is created with a TwiML Application, which supplies the URL that Twilio will hit when a call is created to find out what to do with it. Normally, you would pass a phone number as a parameter to your `TCDevice`'s `connect` which would be handed to your app URL when the call connects. This would then be used to produce TwiML to direct the call onto that number, like this:
```
<Response>
<Dial>
<Number>{{ to_number }}</Number>
</Dial>
</Response>
```
To make this work for client to client calls, you can pass another client ID to the URL and on your server, instead of `<Dial>`ing to a `<Number>` you would `<Dial>` to a `<Client>`. Like so:
```
<Response>
<Dial>
<Client>{{ client_id }}</Client>
</Dial>
</Response>
```
You can discover which clients are available by listening for [presence events](https://www.twilio.com/docs/client/ios/TCPresenceEvent) with your `TCDevice` object. You will also have to [handle incoming calls within applications](https://www.twilio.com/docs/quickstart/php/ios-client/incoming-connections).
I recommend following the [Twilio Client iOS Quickstart guide](https://www.twilio.com/docs/quickstart/php/ios-client) all the way through, which will guide you through most of these points, including passing parameters to your application URL and generating the right TwiML to accomplish this (though it doesn't cover presence events).
Let me know if this helps at all.
|
Not sure it is possible with Twilio. We have used twilio for the same purpose u mentioned (Call to phone numbers) and was working fine. I think the main purpose of twilio is that. Anyways i'm not sure about it.
May be [VoIP](https://en.wikipedia.org/wiki/Voice_over_IP) will suit for your functionality. **PortSIP** is a good SDK for voice and video communications between apps.
You can download the **iOS SDK** from here <https://www.portsip.com/downloads-center/>
It is payable like Twilio only if you want to use it for business.
For more refer [here](http://www.portsip.com/)
Thanks.
|
33,124,269
|
I have been following a Caffe example [here](http://nbviewer.ipython.org/github/BVLC/caffe/blob/master/examples/00-classification.ipynb) to plot the Convolution kernels from my ConvNet. I have attached an image below of my kernels, however it looks nothing like the kernels in the example. I have followed the example exactly, anyone know what the issue may be?
My net is trained on a set of simulated images (with two classes) and the performance of the net is pretty good, around 80% test accuracy.
[](https://i.stack.imgur.com/iwWNU.png)
```
layer {
name: "input"
type: "Data"
top: "data"
top: "label"
include {
phase: TRAIN
}
transform_param {
mean_file: "/tmp/stage5/mean/mean.binaryproto"
}
data_param {
source: "/tmp/stage5/train/train-lmdb"
batch_size: 100
backend: LMDB
}
}
layer {
name: "input"
type: "Data"
top: "data"
top: "label"
include {
phase: TEST
}
transform_param {
mean_file: "/tmp/stage5/mean/mean.binaryproto"
}
data_param {
source: "/tmp/stage5/validation/validation-lmdb"
batch_size: 10
backend: LMDB
}
}
layer {
name: "conv1"
type: "Convolution"
bottom: "data"
top: "conv1"
param {
lr_mult: 1.0
}
param {
lr_mult: 2.0
}
convolution_param {
num_output: 40
kernel_size: 5
stride: 1
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "pool1"
type: "Pooling"
bottom: "conv1"
top: "pool1"
pooling_param {
pool: MAX
kernel_size: 3
stride: 2
}
}
layer {
name: "ip1"
type: "InnerProduct"
bottom: "pool1"
top: "ip1"
param {
lr_mult: 1.0
}
param {
lr_mult: 2.0
}
inner_product_param {
num_output: 500
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "ip2"
type: "InnerProduct"
bottom: "ip1"
top: "ip2"
param {
lr_mult: 1.0
}
param {
lr_mult: 2.0
}
inner_product_param {
num_output: 2
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "loss"
type: "SoftmaxWithLoss"
bottom: "ip2"
bottom: "label"
top: "loss"
}
```
|
2015/10/14
|
[
"https://Stackoverflow.com/questions/33124269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5321075/"
] |
Twilio developer evangelist here.
You absolutely can do app to app calls using the iOS SDK. Let me explain.
Your Twilio Client capability token is created with a TwiML Application, which supplies the URL that Twilio will hit when a call is created to find out what to do with it. Normally, you would pass a phone number as a parameter to your `TCDevice`'s `connect` which would be handed to your app URL when the call connects. This would then be used to produce TwiML to direct the call onto that number, like this:
```
<Response>
<Dial>
<Number>{{ to_number }}</Number>
</Dial>
</Response>
```
To make this work for client to client calls, you can pass another client ID to the URL and on your server, instead of `<Dial>`ing to a `<Number>` you would `<Dial>` to a `<Client>`. Like so:
```
<Response>
<Dial>
<Client>{{ client_id }}</Client>
</Dial>
</Response>
```
You can discover which clients are available by listening for [presence events](https://www.twilio.com/docs/client/ios/TCPresenceEvent) with your `TCDevice` object. You will also have to [handle incoming calls within applications](https://www.twilio.com/docs/quickstart/php/ios-client/incoming-connections).
I recommend following the [Twilio Client iOS Quickstart guide](https://www.twilio.com/docs/quickstart/php/ios-client) all the way through, which will guide you through most of these points, including passing parameters to your application URL and generating the right TwiML to accomplish this (though it doesn't cover presence events).
Let me know if this helps at all.
|
Twilio support sip now. you must have some setting with your twilio account.
As I know ,you can follow [here](https://www.twilio.com/docs/voice/api/sending-sip) to set your twilio sip server and implement sip client on your ios client.
|
49,135,963
|
I am new to python and currently work on data analysis.
I am trying to open multiple folders in a loop and read all files in folders.
Ex. working directory contains 10 folders needed to open and each folder contains 10 files.
My code for open each folder with .txt file;
```
file_open = glob.glob("home/....../folder1/*.txt")
```
I want to open folder 1 and read all files, then go to folder 2 and read all files... until folder 10 and read all files.
Can anyone help me how to write loop to open folder, included library needed to be used?
I have my background in R, for example, in R I could write loop to open folders and files use code below.
```
folder_open <- dir("......./main/")
for (n in 1 to length of (folder_open)){
file_open <-dir(paste0("......./main/",folder_open[n]))
for (k in 1 to length of (file_open){
file_open<-readLines(paste0("...../main/",folder_open[n],"/",file_open[k]))
//Finally I can read all folders and files.
}
}
```
|
2018/03/06
|
[
"https://Stackoverflow.com/questions/49135963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9452236/"
] |
This recursive method will scan all directories within a given directory and then print the names of the `txt` files. I kindly invite you to take it forward.
```
import os
def scan_folder(parent):
# iterate over all the files in directory 'parent'
for file_name in os.listdir(parent):
if file_name.endswith(".txt"):
# if it's a txt file, print its name (or do whatever you want)
print(file_name)
else:
current_path = "".join((parent, "/", file_name))
if os.path.isdir(current_path):
# if we're checking a sub-directory, recursively call this method
scan_folder(current_path)
scan_folder("/example/path") # Insert parent direcotry's path
```
|
This code will look for all directories inside a directory, printing out the names of all files found there:
```
#--------*---------*---------*---------*---------*---------*---------*---------*
# Desc: print filenames one level down from starting folder
#--------*---------*---------*---------*---------*---------*---------*---------*
import os, fnmatch, sys
def find_dirs(directory, pattern):
for item in os.listdir(directory):
if os.path.isdir(os.path.join(directory, item)):
if fnmatch.fnmatch(item, pattern):
filename = os.path.join(directory, item)
yield filename
def find_files(directory, pattern):
for item in os.listdir(directory):
if os.path.isfile(os.path.join(directory, item)):
if fnmatch.fnmatch(item, pattern):
filename = os.path.join(directory, item)
yield filename
#--------*---------*---------*---------*---------*---------*---------*---------#
while True:# M A I N L I N E #
#--------*---------*---------*---------*---------*---------*---------*---------#
# # Set directory
os.chdir("C:\\Users\\Mike\\\Desktop")
for filedir in find_dirs('.', '*'):
print ('Got directory:', filedir)
for filename in find_files(filedir, '*'):
print (filename)
sys.exit() # END PROGRAM
```
|
49,135,963
|
I am new to python and currently work on data analysis.
I am trying to open multiple folders in a loop and read all files in folders.
Ex. working directory contains 10 folders needed to open and each folder contains 10 files.
My code for open each folder with .txt file;
```
file_open = glob.glob("home/....../folder1/*.txt")
```
I want to open folder 1 and read all files, then go to folder 2 and read all files... until folder 10 and read all files.
Can anyone help me how to write loop to open folder, included library needed to be used?
I have my background in R, for example, in R I could write loop to open folders and files use code below.
```
folder_open <- dir("......./main/")
for (n in 1 to length of (folder_open)){
file_open <-dir(paste0("......./main/",folder_open[n]))
for (k in 1 to length of (file_open){
file_open<-readLines(paste0("...../main/",folder_open[n],"/",file_open[k]))
//Finally I can read all folders and files.
}
}
```
|
2018/03/06
|
[
"https://Stackoverflow.com/questions/49135963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9452236/"
] |
This recursive method will scan all directories within a given directory and then print the names of the `txt` files. I kindly invite you to take it forward.
```
import os
def scan_folder(parent):
# iterate over all the files in directory 'parent'
for file_name in os.listdir(parent):
if file_name.endswith(".txt"):
# if it's a txt file, print its name (or do whatever you want)
print(file_name)
else:
current_path = "".join((parent, "/", file_name))
if os.path.isdir(current_path):
# if we're checking a sub-directory, recursively call this method
scan_folder(current_path)
scan_folder("/example/path") # Insert parent direcotry's path
```
|
I think nice way to do that would be to use os.walk. That will generate tree and you can then iterate through that tree.
```
import os
directory = './'
for d in os.walk(directory):
print(d)
```
|
49,135,963
|
I am new to python and currently work on data analysis.
I am trying to open multiple folders in a loop and read all files in folders.
Ex. working directory contains 10 folders needed to open and each folder contains 10 files.
My code for open each folder with .txt file;
```
file_open = glob.glob("home/....../folder1/*.txt")
```
I want to open folder 1 and read all files, then go to folder 2 and read all files... until folder 10 and read all files.
Can anyone help me how to write loop to open folder, included library needed to be used?
I have my background in R, for example, in R I could write loop to open folders and files use code below.
```
folder_open <- dir("......./main/")
for (n in 1 to length of (folder_open)){
file_open <-dir(paste0("......./main/",folder_open[n]))
for (k in 1 to length of (file_open){
file_open<-readLines(paste0("...../main/",folder_open[n],"/",file_open[k]))
//Finally I can read all folders and files.
}
}
```
|
2018/03/06
|
[
"https://Stackoverflow.com/questions/49135963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9452236/"
] |
Your `glob()` pattern is almost correct. Try one of these:
```
file_open = glob.glob("home/....../*/*.txt")
file_open = glob.glob("home/....../folder*/*.txt")
```
The first one will examine all of the text files in any first-level subdirectory of `home/......`, whatever that is. The second will limit itself to subdirectories named like "folder1", "folder2", etc.
I don't speak R, but this might translate your code:
```
for filename in glob.glob("......../main/*/*.txt"):
with open(filename) as file_handle:
for line in file_handle:
# perform data on each line of text
```
|
[pathlib](https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob) is a good choose
```
from pathlib import Path
# or use: glob('**/*.txt')
for txt_path in [_ for _ in Path('demo/test_dir').rglob('*.txt') if _.is_file()]:
print(txt_path.absolute())
```
|
49,135,963
|
I am new to python and currently work on data analysis.
I am trying to open multiple folders in a loop and read all files in folders.
Ex. working directory contains 10 folders needed to open and each folder contains 10 files.
My code for open each folder with .txt file;
```
file_open = glob.glob("home/....../folder1/*.txt")
```
I want to open folder 1 and read all files, then go to folder 2 and read all files... until folder 10 and read all files.
Can anyone help me how to write loop to open folder, included library needed to be used?
I have my background in R, for example, in R I could write loop to open folders and files use code below.
```
folder_open <- dir("......./main/")
for (n in 1 to length of (folder_open)){
file_open <-dir(paste0("......./main/",folder_open[n]))
for (k in 1 to length of (file_open){
file_open<-readLines(paste0("...../main/",folder_open[n],"/",file_open[k]))
//Finally I can read all folders and files.
}
}
```
|
2018/03/06
|
[
"https://Stackoverflow.com/questions/49135963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9452236/"
] |
This recursive method will scan all directories within a given directory and then print the names of the `txt` files. I kindly invite you to take it forward.
```
import os
def scan_folder(parent):
# iterate over all the files in directory 'parent'
for file_name in os.listdir(parent):
if file_name.endswith(".txt"):
# if it's a txt file, print its name (or do whatever you want)
print(file_name)
else:
current_path = "".join((parent, "/", file_name))
if os.path.isdir(current_path):
# if we're checking a sub-directory, recursively call this method
scan_folder(current_path)
scan_folder("/example/path") # Insert parent direcotry's path
```
|
Given the following folder/file tree:
```
C:.
├───folder1
│ file1.txt
│ file2.txt
│ file3.csv
│
└───folder2
file4.txt
file5.txt
file6.csv
```
The following code will recursively locate all `.txt` files in the tree:
```
import os
import fnmatch
for path,dirs,files in os.walk('.'):
for file in files:
if fnmatch.fnmatch(file,'*.txt'):
fullname = os.path.join(path,file)
print(fullname)
```
Output:
```
.\folder1\file1.txt
.\folder1\file2.txt
.\folder2\file4.txt
.\folder2\file5.txt
```
|
49,135,963
|
I am new to python and currently work on data analysis.
I am trying to open multiple folders in a loop and read all files in folders.
Ex. working directory contains 10 folders needed to open and each folder contains 10 files.
My code for open each folder with .txt file;
```
file_open = glob.glob("home/....../folder1/*.txt")
```
I want to open folder 1 and read all files, then go to folder 2 and read all files... until folder 10 and read all files.
Can anyone help me how to write loop to open folder, included library needed to be used?
I have my background in R, for example, in R I could write loop to open folders and files use code below.
```
folder_open <- dir("......./main/")
for (n in 1 to length of (folder_open)){
file_open <-dir(paste0("......./main/",folder_open[n]))
for (k in 1 to length of (file_open){
file_open<-readLines(paste0("...../main/",folder_open[n],"/",file_open[k]))
//Finally I can read all folders and files.
}
}
```
|
2018/03/06
|
[
"https://Stackoverflow.com/questions/49135963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9452236/"
] |
Given the following folder/file tree:
```
C:.
├───folder1
│ file1.txt
│ file2.txt
│ file3.csv
│
└───folder2
file4.txt
file5.txt
file6.csv
```
The following code will recursively locate all `.txt` files in the tree:
```
import os
import fnmatch
for path,dirs,files in os.walk('.'):
for file in files:
if fnmatch.fnmatch(file,'*.txt'):
fullname = os.path.join(path,file)
print(fullname)
```
Output:
```
.\folder1\file1.txt
.\folder1\file2.txt
.\folder2\file4.txt
.\folder2\file5.txt
```
|
This code will look for all directories inside a directory, printing out the names of all files found there:
```
#--------*---------*---------*---------*---------*---------*---------*---------*
# Desc: print filenames one level down from starting folder
#--------*---------*---------*---------*---------*---------*---------*---------*
import os, fnmatch, sys
def find_dirs(directory, pattern):
for item in os.listdir(directory):
if os.path.isdir(os.path.join(directory, item)):
if fnmatch.fnmatch(item, pattern):
filename = os.path.join(directory, item)
yield filename
def find_files(directory, pattern):
for item in os.listdir(directory):
if os.path.isfile(os.path.join(directory, item)):
if fnmatch.fnmatch(item, pattern):
filename = os.path.join(directory, item)
yield filename
#--------*---------*---------*---------*---------*---------*---------*---------#
while True:# M A I N L I N E #
#--------*---------*---------*---------*---------*---------*---------*---------#
# # Set directory
os.chdir("C:\\Users\\Mike\\\Desktop")
for filedir in find_dirs('.', '*'):
print ('Got directory:', filedir)
for filename in find_files(filedir, '*'):
print (filename)
sys.exit() # END PROGRAM
```
|
49,135,963
|
I am new to python and currently work on data analysis.
I am trying to open multiple folders in a loop and read all files in folders.
Ex. working directory contains 10 folders needed to open and each folder contains 10 files.
My code for open each folder with .txt file;
```
file_open = glob.glob("home/....../folder1/*.txt")
```
I want to open folder 1 and read all files, then go to folder 2 and read all files... until folder 10 and read all files.
Can anyone help me how to write loop to open folder, included library needed to be used?
I have my background in R, for example, in R I could write loop to open folders and files use code below.
```
folder_open <- dir("......./main/")
for (n in 1 to length of (folder_open)){
file_open <-dir(paste0("......./main/",folder_open[n]))
for (k in 1 to length of (file_open){
file_open<-readLines(paste0("...../main/",folder_open[n],"/",file_open[k]))
//Finally I can read all folders and files.
}
}
```
|
2018/03/06
|
[
"https://Stackoverflow.com/questions/49135963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9452236/"
] |
This recursive method will scan all directories within a given directory and then print the names of the `txt` files. I kindly invite you to take it forward.
```
import os
def scan_folder(parent):
# iterate over all the files in directory 'parent'
for file_name in os.listdir(parent):
if file_name.endswith(".txt"):
# if it's a txt file, print its name (or do whatever you want)
print(file_name)
else:
current_path = "".join((parent, "/", file_name))
if os.path.isdir(current_path):
# if we're checking a sub-directory, recursively call this method
scan_folder(current_path)
scan_folder("/example/path") # Insert parent direcotry's path
```
|
Your `glob()` pattern is almost correct. Try one of these:
```
file_open = glob.glob("home/....../*/*.txt")
file_open = glob.glob("home/....../folder*/*.txt")
```
The first one will examine all of the text files in any first-level subdirectory of `home/......`, whatever that is. The second will limit itself to subdirectories named like "folder1", "folder2", etc.
I don't speak R, but this might translate your code:
```
for filename in glob.glob("......../main/*/*.txt"):
with open(filename) as file_handle:
for line in file_handle:
# perform data on each line of text
```
|
49,135,963
|
I am new to python and currently work on data analysis.
I am trying to open multiple folders in a loop and read all files in folders.
Ex. working directory contains 10 folders needed to open and each folder contains 10 files.
My code for open each folder with .txt file;
```
file_open = glob.glob("home/....../folder1/*.txt")
```
I want to open folder 1 and read all files, then go to folder 2 and read all files... until folder 10 and read all files.
Can anyone help me how to write loop to open folder, included library needed to be used?
I have my background in R, for example, in R I could write loop to open folders and files use code below.
```
folder_open <- dir("......./main/")
for (n in 1 to length of (folder_open)){
file_open <-dir(paste0("......./main/",folder_open[n]))
for (k in 1 to length of (file_open){
file_open<-readLines(paste0("...../main/",folder_open[n],"/",file_open[k]))
//Finally I can read all folders and files.
}
}
```
|
2018/03/06
|
[
"https://Stackoverflow.com/questions/49135963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9452236/"
] |
Your `glob()` pattern is almost correct. Try one of these:
```
file_open = glob.glob("home/....../*/*.txt")
file_open = glob.glob("home/....../folder*/*.txt")
```
The first one will examine all of the text files in any first-level subdirectory of `home/......`, whatever that is. The second will limit itself to subdirectories named like "folder1", "folder2", etc.
I don't speak R, but this might translate your code:
```
for filename in glob.glob("......../main/*/*.txt"):
with open(filename) as file_handle:
for line in file_handle:
# perform data on each line of text
```
|
I think nice way to do that would be to use os.walk. That will generate tree and you can then iterate through that tree.
```
import os
directory = './'
for d in os.walk(directory):
print(d)
```
|
49,135,963
|
I am new to python and currently work on data analysis.
I am trying to open multiple folders in a loop and read all files in folders.
Ex. working directory contains 10 folders needed to open and each folder contains 10 files.
My code for open each folder with .txt file;
```
file_open = glob.glob("home/....../folder1/*.txt")
```
I want to open folder 1 and read all files, then go to folder 2 and read all files... until folder 10 and read all files.
Can anyone help me how to write loop to open folder, included library needed to be used?
I have my background in R, for example, in R I could write loop to open folders and files use code below.
```
folder_open <- dir("......./main/")
for (n in 1 to length of (folder_open)){
file_open <-dir(paste0("......./main/",folder_open[n]))
for (k in 1 to length of (file_open){
file_open<-readLines(paste0("...../main/",folder_open[n],"/",file_open[k]))
//Finally I can read all folders and files.
}
}
```
|
2018/03/06
|
[
"https://Stackoverflow.com/questions/49135963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9452236/"
] |
This recursive method will scan all directories within a given directory and then print the names of the `txt` files. I kindly invite you to take it forward.
```
import os
def scan_folder(parent):
# iterate over all the files in directory 'parent'
for file_name in os.listdir(parent):
if file_name.endswith(".txt"):
# if it's a txt file, print its name (or do whatever you want)
print(file_name)
else:
current_path = "".join((parent, "/", file_name))
if os.path.isdir(current_path):
# if we're checking a sub-directory, recursively call this method
scan_folder(current_path)
scan_folder("/example/path") # Insert parent direcotry's path
```
|
[pathlib](https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob) is a good choose
```
from pathlib import Path
# or use: glob('**/*.txt')
for txt_path in [_ for _ in Path('demo/test_dir').rglob('*.txt') if _.is_file()]:
print(txt_path.absolute())
```
|
49,135,963
|
I am new to python and currently work on data analysis.
I am trying to open multiple folders in a loop and read all files in folders.
Ex. working directory contains 10 folders needed to open and each folder contains 10 files.
My code for open each folder with .txt file;
```
file_open = glob.glob("home/....../folder1/*.txt")
```
I want to open folder 1 and read all files, then go to folder 2 and read all files... until folder 10 and read all files.
Can anyone help me how to write loop to open folder, included library needed to be used?
I have my background in R, for example, in R I could write loop to open folders and files use code below.
```
folder_open <- dir("......./main/")
for (n in 1 to length of (folder_open)){
file_open <-dir(paste0("......./main/",folder_open[n]))
for (k in 1 to length of (file_open){
file_open<-readLines(paste0("...../main/",folder_open[n],"/",file_open[k]))
//Finally I can read all folders and files.
}
}
```
|
2018/03/06
|
[
"https://Stackoverflow.com/questions/49135963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9452236/"
] |
Your `glob()` pattern is almost correct. Try one of these:
```
file_open = glob.glob("home/....../*/*.txt")
file_open = glob.glob("home/....../folder*/*.txt")
```
The first one will examine all of the text files in any first-level subdirectory of `home/......`, whatever that is. The second will limit itself to subdirectories named like "folder1", "folder2", etc.
I don't speak R, but this might translate your code:
```
for filename in glob.glob("......../main/*/*.txt"):
with open(filename) as file_handle:
for line in file_handle:
# perform data on each line of text
```
|
This code will look for all directories inside a directory, printing out the names of all files found there:
```
#--------*---------*---------*---------*---------*---------*---------*---------*
# Desc: print filenames one level down from starting folder
#--------*---------*---------*---------*---------*---------*---------*---------*
import os, fnmatch, sys
def find_dirs(directory, pattern):
for item in os.listdir(directory):
if os.path.isdir(os.path.join(directory, item)):
if fnmatch.fnmatch(item, pattern):
filename = os.path.join(directory, item)
yield filename
def find_files(directory, pattern):
for item in os.listdir(directory):
if os.path.isfile(os.path.join(directory, item)):
if fnmatch.fnmatch(item, pattern):
filename = os.path.join(directory, item)
yield filename
#--------*---------*---------*---------*---------*---------*---------*---------#
while True:# M A I N L I N E #
#--------*---------*---------*---------*---------*---------*---------*---------#
# # Set directory
os.chdir("C:\\Users\\Mike\\\Desktop")
for filedir in find_dirs('.', '*'):
print ('Got directory:', filedir)
for filename in find_files(filedir, '*'):
print (filename)
sys.exit() # END PROGRAM
```
|
49,135,963
|
I am new to python and currently work on data analysis.
I am trying to open multiple folders in a loop and read all files in folders.
Ex. working directory contains 10 folders needed to open and each folder contains 10 files.
My code for open each folder with .txt file;
```
file_open = glob.glob("home/....../folder1/*.txt")
```
I want to open folder 1 and read all files, then go to folder 2 and read all files... until folder 10 and read all files.
Can anyone help me how to write loop to open folder, included library needed to be used?
I have my background in R, for example, in R I could write loop to open folders and files use code below.
```
folder_open <- dir("......./main/")
for (n in 1 to length of (folder_open)){
file_open <-dir(paste0("......./main/",folder_open[n]))
for (k in 1 to length of (file_open){
file_open<-readLines(paste0("...../main/",folder_open[n],"/",file_open[k]))
//Finally I can read all folders and files.
}
}
```
|
2018/03/06
|
[
"https://Stackoverflow.com/questions/49135963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9452236/"
] |
Given the following folder/file tree:
```
C:.
├───folder1
│ file1.txt
│ file2.txt
│ file3.csv
│
└───folder2
file4.txt
file5.txt
file6.csv
```
The following code will recursively locate all `.txt` files in the tree:
```
import os
import fnmatch
for path,dirs,files in os.walk('.'):
for file in files:
if fnmatch.fnmatch(file,'*.txt'):
fullname = os.path.join(path,file)
print(fullname)
```
Output:
```
.\folder1\file1.txt
.\folder1\file2.txt
.\folder2\file4.txt
.\folder2\file5.txt
```
|
I think nice way to do that would be to use os.walk. That will generate tree and you can then iterate through that tree.
```
import os
directory = './'
for d in os.walk(directory):
print(d)
```
|
6,131,629
|
I'm trying to create a module that initializes a serial port connection using python:
```
import serial
class myserial:
def __init__(self, port, baudrate)
self = serial.Serial(port, baudrate)
```
When I run this in Python I get an AttributeError message stating that self does not have an attribute open. Does anyone have any idea what's wrong with this code above? Any help would be greatly appreciated.
thanks
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6131629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Those are the basic pieces of information. Anything beyond that could be viewed as SpyWare-like and privacy advocates will [justifiably] frown upon it.
The best way to obtain more information from your users is to ask them, make the fields optional, and inform your user of exactly what you will be using the information for. Will you be mailing them a newsletter?
If you plan to eMail them, then you MUST use the "confirmed opt-in" approach -- get their consent (by having them respond to an eMail, keyed with a special-secret-unique number, confirming that they are granting permission for you to send them that newsletter or whatever notifications you plan to send to them) first.
As long as you're up-front about how you plan to use the information, and give the users options to decide how you can use it (these options should all be "you do NOT have permission" by default), you're likely to get more users who are willing to trust you and provide you with better quality information. For those who don't wish to reveal any personal information about themselves, don't waste your time trying to get it because many of them take steps to prevent that and hide anyway (and that is their right).
|
For what end?
Remember that client IP is close to meaningless now. All users coming from the same proxy or same NAT point would have the same client IP. Years go, all of AOL traffic came from just a few proxies, though now actual AOL users may be outnumbered by the proxies :).
If you want to uniquely identify a user, its easy to create a cookie in apache (mod\_usertrack) or whatever framework you use. If the person blocks cookies, please respect that and don't try tricks to track them anyway. Or take the lesson of Google, make it so useful, people will choose the utility over cookie worries.
Remember that Javascript runs on the client. Your document.write() will show the info on their webpage, not do anything for your server. You'd want to use Javascript to put this info in a cookie, or store with a form submission if you have any forms.
|
6,131,629
|
I'm trying to create a module that initializes a serial port connection using python:
```
import serial
class myserial:
def __init__(self, port, baudrate)
self = serial.Serial(port, baudrate)
```
When I run this in Python I get an AttributeError message stating that self does not have an attribute open. Does anyone have any idea what's wrong with this code above? Any help would be greatly appreciated.
thanks
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6131629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
The list that is available to PHP is found [here](http://www.php.net/manual/en/reserved.variables.server.php).
If you need more details than that, you might want to consider using [Browserhawk](http://www.cyscape.com/).
|
```
phpinfo(32);
```
Prints a table with the whole extractable information. You can simply copy and paste the variables directly into your php code.
e.g:
```
_SERVER["GEOIP_COUNTRY_CODE"] AT
```
would be in php code:
```
echo $_SERVER["GEOIP_COUNTRY_CODE"];
```
|
6,131,629
|
I'm trying to create a module that initializes a serial port connection using python:
```
import serial
class myserial:
def __init__(self, port, baudrate)
self = serial.Serial(port, baudrate)
```
When I run this in Python I get an AttributeError message stating that self does not have an attribute open. Does anyone have any idea what's wrong with this code above? Any help would be greatly appreciated.
thanks
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6131629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Get all the information of client's machine with this small PHP:
```
<?php
foreach($_SERVER as $key => $value){
echo '$_SERVER["'.$key.'"] = '.$value."<br />";
}
?>
```
|
For what end?
Remember that client IP is close to meaningless now. All users coming from the same proxy or same NAT point would have the same client IP. Years go, all of AOL traffic came from just a few proxies, though now actual AOL users may be outnumbered by the proxies :).
If you want to uniquely identify a user, its easy to create a cookie in apache (mod\_usertrack) or whatever framework you use. If the person blocks cookies, please respect that and don't try tricks to track them anyway. Or take the lesson of Google, make it so useful, people will choose the utility over cookie worries.
Remember that Javascript runs on the client. Your document.write() will show the info on their webpage, not do anything for your server. You'd want to use Javascript to put this info in a cookie, or store with a form submission if you have any forms.
|
6,131,629
|
I'm trying to create a module that initializes a serial port connection using python:
```
import serial
class myserial:
def __init__(self, port, baudrate)
self = serial.Serial(port, baudrate)
```
When I run this in Python I get an AttributeError message stating that self does not have an attribute open. Does anyone have any idea what's wrong with this code above? Any help would be greatly appreciated.
thanks
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6131629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
The list that is available to PHP is found [here](http://www.php.net/manual/en/reserved.variables.server.php).
If you need more details than that, you might want to consider using [Browserhawk](http://www.cyscape.com/).
|
For what end?
Remember that client IP is close to meaningless now. All users coming from the same proxy or same NAT point would have the same client IP. Years go, all of AOL traffic came from just a few proxies, though now actual AOL users may be outnumbered by the proxies :).
If you want to uniquely identify a user, its easy to create a cookie in apache (mod\_usertrack) or whatever framework you use. If the person blocks cookies, please respect that and don't try tricks to track them anyway. Or take the lesson of Google, make it so useful, people will choose the utility over cookie worries.
Remember that Javascript runs on the client. Your document.write() will show the info on their webpage, not do anything for your server. You'd want to use Javascript to put this info in a cookie, or store with a form submission if you have any forms.
|
6,131,629
|
I'm trying to create a module that initializes a serial port connection using python:
```
import serial
class myserial:
def __init__(self, port, baudrate)
self = serial.Serial(port, baudrate)
```
When I run this in Python I get an AttributeError message stating that self does not have an attribute open. Does anyone have any idea what's wrong with this code above? Any help would be greatly appreciated.
thanks
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6131629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Those are the basic pieces of information. Anything beyond that could be viewed as SpyWare-like and privacy advocates will [justifiably] frown upon it.
The best way to obtain more information from your users is to ask them, make the fields optional, and inform your user of exactly what you will be using the information for. Will you be mailing them a newsletter?
If you plan to eMail them, then you MUST use the "confirmed opt-in" approach -- get their consent (by having them respond to an eMail, keyed with a special-secret-unique number, confirming that they are granting permission for you to send them that newsletter or whatever notifications you plan to send to them) first.
As long as you're up-front about how you plan to use the information, and give the users options to decide how you can use it (these options should all be "you do NOT have permission" by default), you're likely to get more users who are willing to trust you and provide you with better quality information. For those who don't wish to reveal any personal information about themselves, don't waste your time trying to get it because many of them take steps to prevent that and hide anyway (and that is their right).
|
get all the outputs of $\_SERVER variables:
```
<?php
$test_HTTP_proxy_headers = array('GATEWAY_INTERFACE','SERVER_ADDR','SERVER_NAME','SERVER_SOFTWARE','SERVER_PROTOCOL','REQUEST_METHOD','REQUEST_TIME','REQUEST_TIME_FLOAT','QUERY_STRING','DOCUMENT_ROOT','HTTP_ACCEPT','HTTP_ACCEPT_CHARSET','HTTP_ACCEPT_ENCODING','HTTP_ACCEPT_LANGUAGE','HTTP_CONNECTION','HTTP_HOST','HTTP_REFERER','HTTP_USER_AGENT','HTTPS','REMOTE_ADDR','REMOTE_HOST','REMOTE_PORT','REMOTE_USER','REDIRECT_REMOTE_USER','SCRIPT_FILENAME','SERVER_ADMIN','SERVER_PORT','SERVER_SIGNATURE','PATH_TRANSLATED','SCRIPT_NAME','REQYEST_URI','PHP_AUTH_DIGEST','PHP_AUTH_USER','PHP_AUTH_PW','AUTH_TYPE','PATH_INFO','ORIG_PATH_INFO','GEOIP_COUNTRY_CODE');
foreach($test_HTTP_proxy_headers as $header){
echo $header . ": " . $_SERVER[$header] . "<br/>";
}
?>
```
|
6,131,629
|
I'm trying to create a module that initializes a serial port connection using python:
```
import serial
class myserial:
def __init__(self, port, baudrate)
self = serial.Serial(port, baudrate)
```
When I run this in Python I get an AttributeError message stating that self does not have an attribute open. Does anyone have any idea what's wrong with this code above? Any help would be greatly appreciated.
thanks
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6131629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Get all the information of client's machine with this small PHP:
```
<?php
foreach($_SERVER as $key => $value){
echo '$_SERVER["'.$key.'"] = '.$value."<br />";
}
?>
```
|
get all the outputs of $\_SERVER variables:
```
<?php
$test_HTTP_proxy_headers = array('GATEWAY_INTERFACE','SERVER_ADDR','SERVER_NAME','SERVER_SOFTWARE','SERVER_PROTOCOL','REQUEST_METHOD','REQUEST_TIME','REQUEST_TIME_FLOAT','QUERY_STRING','DOCUMENT_ROOT','HTTP_ACCEPT','HTTP_ACCEPT_CHARSET','HTTP_ACCEPT_ENCODING','HTTP_ACCEPT_LANGUAGE','HTTP_CONNECTION','HTTP_HOST','HTTP_REFERER','HTTP_USER_AGENT','HTTPS','REMOTE_ADDR','REMOTE_HOST','REMOTE_PORT','REMOTE_USER','REDIRECT_REMOTE_USER','SCRIPT_FILENAME','SERVER_ADMIN','SERVER_PORT','SERVER_SIGNATURE','PATH_TRANSLATED','SCRIPT_NAME','REQYEST_URI','PHP_AUTH_DIGEST','PHP_AUTH_USER','PHP_AUTH_PW','AUTH_TYPE','PATH_INFO','ORIG_PATH_INFO','GEOIP_COUNTRY_CODE');
foreach($test_HTTP_proxy_headers as $header){
echo $header . ": " . $_SERVER[$header] . "<br/>";
}
?>
```
|
6,131,629
|
I'm trying to create a module that initializes a serial port connection using python:
```
import serial
class myserial:
def __init__(self, port, baudrate)
self = serial.Serial(port, baudrate)
```
When I run this in Python I get an AttributeError message stating that self does not have an attribute open. Does anyone have any idea what's wrong with this code above? Any help would be greatly appreciated.
thanks
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6131629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
For what end?
Remember that client IP is close to meaningless now. All users coming from the same proxy or same NAT point would have the same client IP. Years go, all of AOL traffic came from just a few proxies, though now actual AOL users may be outnumbered by the proxies :).
If you want to uniquely identify a user, its easy to create a cookie in apache (mod\_usertrack) or whatever framework you use. If the person blocks cookies, please respect that and don't try tricks to track them anyway. Or take the lesson of Google, make it so useful, people will choose the utility over cookie worries.
Remember that Javascript runs on the client. Your document.write() will show the info on their webpage, not do anything for your server. You'd want to use Javascript to put this info in a cookie, or store with a form submission if you have any forms.
|
get all the outputs of $\_SERVER variables:
```
<?php
$test_HTTP_proxy_headers = array('GATEWAY_INTERFACE','SERVER_ADDR','SERVER_NAME','SERVER_SOFTWARE','SERVER_PROTOCOL','REQUEST_METHOD','REQUEST_TIME','REQUEST_TIME_FLOAT','QUERY_STRING','DOCUMENT_ROOT','HTTP_ACCEPT','HTTP_ACCEPT_CHARSET','HTTP_ACCEPT_ENCODING','HTTP_ACCEPT_LANGUAGE','HTTP_CONNECTION','HTTP_HOST','HTTP_REFERER','HTTP_USER_AGENT','HTTPS','REMOTE_ADDR','REMOTE_HOST','REMOTE_PORT','REMOTE_USER','REDIRECT_REMOTE_USER','SCRIPT_FILENAME','SERVER_ADMIN','SERVER_PORT','SERVER_SIGNATURE','PATH_TRANSLATED','SCRIPT_NAME','REQYEST_URI','PHP_AUTH_DIGEST','PHP_AUTH_USER','PHP_AUTH_PW','AUTH_TYPE','PATH_INFO','ORIG_PATH_INFO','GEOIP_COUNTRY_CODE');
foreach($test_HTTP_proxy_headers as $header){
echo $header . ": " . $_SERVER[$header] . "<br/>";
}
?>
```
|
6,131,629
|
I'm trying to create a module that initializes a serial port connection using python:
```
import serial
class myserial:
def __init__(self, port, baudrate)
self = serial.Serial(port, baudrate)
```
When I run this in Python I get an AttributeError message stating that self does not have an attribute open. Does anyone have any idea what's wrong with this code above? Any help would be greatly appreciated.
thanks
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6131629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Those are the basic pieces of information. Anything beyond that could be viewed as SpyWare-like and privacy advocates will [justifiably] frown upon it.
The best way to obtain more information from your users is to ask them, make the fields optional, and inform your user of exactly what you will be using the information for. Will you be mailing them a newsletter?
If you plan to eMail them, then you MUST use the "confirmed opt-in" approach -- get their consent (by having them respond to an eMail, keyed with a special-secret-unique number, confirming that they are granting permission for you to send them that newsletter or whatever notifications you plan to send to them) first.
As long as you're up-front about how you plan to use the information, and give the users options to decide how you can use it (these options should all be "you do NOT have permission" by default), you're likely to get more users who are willing to trust you and provide you with better quality information. For those who don't wish to reveal any personal information about themselves, don't waste your time trying to get it because many of them take steps to prevent that and hide anyway (and that is their right).
|
The list that is available to PHP is found [here](http://www.php.net/manual/en/reserved.variables.server.php).
If you need more details than that, you might want to consider using [Browserhawk](http://www.cyscape.com/).
|
6,131,629
|
I'm trying to create a module that initializes a serial port connection using python:
```
import serial
class myserial:
def __init__(self, port, baudrate)
self = serial.Serial(port, baudrate)
```
When I run this in Python I get an AttributeError message stating that self does not have an attribute open. Does anyone have any idea what's wrong with this code above? Any help would be greatly appreciated.
thanks
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6131629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Those are the basic pieces of information. Anything beyond that could be viewed as SpyWare-like and privacy advocates will [justifiably] frown upon it.
The best way to obtain more information from your users is to ask them, make the fields optional, and inform your user of exactly what you will be using the information for. Will you be mailing them a newsletter?
If you plan to eMail them, then you MUST use the "confirmed opt-in" approach -- get their consent (by having them respond to an eMail, keyed with a special-secret-unique number, confirming that they are granting permission for you to send them that newsletter or whatever notifications you plan to send to them) first.
As long as you're up-front about how you plan to use the information, and give the users options to decide how you can use it (these options should all be "you do NOT have permission" by default), you're likely to get more users who are willing to trust you and provide you with better quality information. For those who don't wish to reveal any personal information about themselves, don't waste your time trying to get it because many of them take steps to prevent that and hide anyway (and that is their right).
|
```
phpinfo(32);
```
Prints a table with the whole extractable information. You can simply copy and paste the variables directly into your php code.
e.g:
```
_SERVER["GEOIP_COUNTRY_CODE"] AT
```
would be in php code:
```
echo $_SERVER["GEOIP_COUNTRY_CODE"];
```
|
6,131,629
|
I'm trying to create a module that initializes a serial port connection using python:
```
import serial
class myserial:
def __init__(self, port, baudrate)
self = serial.Serial(port, baudrate)
```
When I run this in Python I get an AttributeError message stating that self does not have an attribute open. Does anyone have any idea what's wrong with this code above? Any help would be greatly appreciated.
thanks
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6131629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Get all the information of client's machine with this small PHP:
```
<?php
foreach($_SERVER as $key => $value){
echo '$_SERVER["'.$key.'"] = '.$value."<br />";
}
?>
```
|
```
phpinfo(32);
```
Prints a table with the whole extractable information. You can simply copy and paste the variables directly into your php code.
e.g:
```
_SERVER["GEOIP_COUNTRY_CODE"] AT
```
would be in php code:
```
echo $_SERVER["GEOIP_COUNTRY_CODE"];
```
|
24,751,181
|
I have a text file named headerValue.txt which contains the following data:-
```
Name Age
sam 22
Bob 21
```
I am trying to write a python script that would add a new header called 'Eligibility'.
It would read the lines from the text file and check if the age is more than 18, then it will print 'True' underneath 'Eligibility' header and also add one more header named 'Adult' and print a 'yes' underneath and 'no' if the age is less than 18.
Since in the text file the age of both is more than 18. The output will something be like:-
```
Name Age Eligibility Adult
sam 22 True yes
Bob 21 True yes
```
code snippet:-
```
fo =open("headerValue.txt", "r")
data = fo.readlines()
for line in data:
if "Age" in line:
if int(Age) > 18:
Eligibility = "True"
Adult = "yes"
```
I am kinda stuck here since I am new to python. Any help how to update the text file and add headers with its values?Thanks
|
2014/07/15
|
[
"https://Stackoverflow.com/questions/24751181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3559954/"
] |
```
fo =open("headerValue.txt", "r")
data = [l.split() for l in fo.readlines()]
headers = data[0]
headers.extend(('Eligibility', 'Adult'))
ageind = headers.index('Age')
for line in data[1:]:
if int(line[ageind]) > 18:
line.extend(('True', 'yes'))
else:
line.extend(('False', 'no'))
```
The `if` in your code would only be true for the first line (not the one you're interested in). I replaced it with checking for the index of age. Also, usually variable names are not capitalized.
Also, regarding `data = [l.split() for l in fo.readlines()]` - it looks like your file is space separated. If it's tab/comma separated you can split accordingly, but I suggest using [csv](https://docs.python.org/2/library/csv.html).
|
This module is suited for you : <https://docs.python.org/2/library/fileinput.html?highlight=fileinput#fileinput>
For a infile edition you can use:
```
#!/usr/bin/python
import fileinput
cont = 0
for line in fileinput.input("./path/to/file", inplace=True):
if not cont:
name = "Name"
age = "Age"
Eligibility= "Eligibility"
Adult = "Adult"
else:
name ,age = line.split()
if int(age) > 18:
Eligibility = "True"
Adult = "yes"
print "{0}\t{1}\t{2}\t{3}".format(name, age, Eligibility, Adult)
cont += 1
```
This , will **update** your **original** file.
|
24,751,181
|
I have a text file named headerValue.txt which contains the following data:-
```
Name Age
sam 22
Bob 21
```
I am trying to write a python script that would add a new header called 'Eligibility'.
It would read the lines from the text file and check if the age is more than 18, then it will print 'True' underneath 'Eligibility' header and also add one more header named 'Adult' and print a 'yes' underneath and 'no' if the age is less than 18.
Since in the text file the age of both is more than 18. The output will something be like:-
```
Name Age Eligibility Adult
sam 22 True yes
Bob 21 True yes
```
code snippet:-
```
fo =open("headerValue.txt", "r")
data = fo.readlines()
for line in data:
if "Age" in line:
if int(Age) > 18:
Eligibility = "True"
Adult = "yes"
```
I am kinda stuck here since I am new to python. Any help how to update the text file and add headers with its values?Thanks
|
2014/07/15
|
[
"https://Stackoverflow.com/questions/24751181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3559954/"
] |
You're trying to check if the string `"Age"` exists in a line. It only exists on the first line. Then you try to convert a variable `Age` to an integer and see if it's larger than 18. I can't see that you've defined `Age` anywhere so I can't tell if this code runs.
It seems like you have a tab-delimited or a space-delimited file. It looks like a CSV-file so you might as well treat it as such. It's easier, because python provides a builtin [`csv`](https://docs.python.org/2/library/csv.html) module. In that module there's the [`csv.DictReader`](https://docs.python.org/2/library/csv.html#csv.DictReader) and [`csv.DictWriter`](https://docs.python.org/2/library/csv.html#csv.DictWriter) objects which allow you to modify each line in the csv-file as a dictionary. In the below file, the `csv.DictWriter` gets default header names and the `restval`-parameter defines the default parameter for the fields. This simplifies the code as you can see below:
```
>>> with open("test.csv", "r") as inf, open("out.csv", "w") as outf:
... in_reader = csv.DictReader(inf, delimiter=" ")
... out_writer = csv.DictWriter(outf, delimiter=" ", fieldnames=['Name', 'Age', 'Eligibility', 'Adult'], restval=False)
... out_writer.writeheader()
... for line in in_reader:
... if int(line['Age']) > 18:
... line['Eligibility'] = True
... line['Adult'] = True
... out_writer.writerow(line)
```
Input file is `test.csv`:
```
msvalkon@lunkwill~$: cat test.csv
Name Age
sam 22
Bob 21
foo 5
```
Output in `out.csv`:
```
msvalkon@lunkwill~$: cat out.csv
Name Age Eligibility Adult
sam 22 True True
Bob 21 True True
foo 5 False False
```
|
This module is suited for you : <https://docs.python.org/2/library/fileinput.html?highlight=fileinput#fileinput>
For a infile edition you can use:
```
#!/usr/bin/python
import fileinput
cont = 0
for line in fileinput.input("./path/to/file", inplace=True):
if not cont:
name = "Name"
age = "Age"
Eligibility= "Eligibility"
Adult = "Adult"
else:
name ,age = line.split()
if int(age) > 18:
Eligibility = "True"
Adult = "yes"
print "{0}\t{1}\t{2}\t{3}".format(name, age, Eligibility, Adult)
cont += 1
```
This , will **update** your **original** file.
|
24,751,181
|
I have a text file named headerValue.txt which contains the following data:-
```
Name Age
sam 22
Bob 21
```
I am trying to write a python script that would add a new header called 'Eligibility'.
It would read the lines from the text file and check if the age is more than 18, then it will print 'True' underneath 'Eligibility' header and also add one more header named 'Adult' and print a 'yes' underneath and 'no' if the age is less than 18.
Since in the text file the age of both is more than 18. The output will something be like:-
```
Name Age Eligibility Adult
sam 22 True yes
Bob 21 True yes
```
code snippet:-
```
fo =open("headerValue.txt", "r")
data = fo.readlines()
for line in data:
if "Age" in line:
if int(Age) > 18:
Eligibility = "True"
Adult = "yes"
```
I am kinda stuck here since I am new to python. Any help how to update the text file and add headers with its values?Thanks
|
2014/07/15
|
[
"https://Stackoverflow.com/questions/24751181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3559954/"
] |
```
fo =open("headerValue.txt", "r")
data = [l.split() for l in fo.readlines()]
headers = data[0]
headers.extend(('Eligibility', 'Adult'))
ageind = headers.index('Age')
for line in data[1:]:
if int(line[ageind]) > 18:
line.extend(('True', 'yes'))
else:
line.extend(('False', 'no'))
```
The `if` in your code would only be true for the first line (not the one you're interested in). I replaced it with checking for the index of age. Also, usually variable names are not capitalized.
Also, regarding `data = [l.split() for l in fo.readlines()]` - it looks like your file is space separated. If it's tab/comma separated you can split accordingly, but I suggest using [csv](https://docs.python.org/2/library/csv.html).
|
You're trying to check if the string `"Age"` exists in a line. It only exists on the first line. Then you try to convert a variable `Age` to an integer and see if it's larger than 18. I can't see that you've defined `Age` anywhere so I can't tell if this code runs.
It seems like you have a tab-delimited or a space-delimited file. It looks like a CSV-file so you might as well treat it as such. It's easier, because python provides a builtin [`csv`](https://docs.python.org/2/library/csv.html) module. In that module there's the [`csv.DictReader`](https://docs.python.org/2/library/csv.html#csv.DictReader) and [`csv.DictWriter`](https://docs.python.org/2/library/csv.html#csv.DictWriter) objects which allow you to modify each line in the csv-file as a dictionary. In the below file, the `csv.DictWriter` gets default header names and the `restval`-parameter defines the default parameter for the fields. This simplifies the code as you can see below:
```
>>> with open("test.csv", "r") as inf, open("out.csv", "w") as outf:
... in_reader = csv.DictReader(inf, delimiter=" ")
... out_writer = csv.DictWriter(outf, delimiter=" ", fieldnames=['Name', 'Age', 'Eligibility', 'Adult'], restval=False)
... out_writer.writeheader()
... for line in in_reader:
... if int(line['Age']) > 18:
... line['Eligibility'] = True
... line['Adult'] = True
... out_writer.writerow(line)
```
Input file is `test.csv`:
```
msvalkon@lunkwill~$: cat test.csv
Name Age
sam 22
Bob 21
foo 5
```
Output in `out.csv`:
```
msvalkon@lunkwill~$: cat out.csv
Name Age Eligibility Adult
sam 22 True True
Bob 21 True True
foo 5 False False
```
|
67,665,789
|
Hi I am a Newbie to programming. So I spent 4 days trying to learn python. I evented some new swear words too.
I was particularly interested in trying as an exercise some web-scraping to learn something new and get some exposure to see how it all works.
This is what I came up with. See code at end. It works (to a degree)
But what's missing?
1. This website has pagination on it. In this case 11 pages worth. How would you go about adding to this script and getting python to go look at those other pages too and carry out the same scrape. Ie scrape page one , scrape page 2, 3 ... 11 and post the results to a csv?
<https://www.organicwine.com.au/vegan/?pgnum=1>
<https://www.organicwine.com.au/vegan/?pgnum=2>
<https://www.organicwine.com.au/vegan/?pgnum=3>
<https://www.organicwine.com.au/vegan/?pgnum=4>
<https://www.organicwine.com.au/vegan/?pgnum=5>
<https://www.organicwine.com.au/vegan/?pgnum=6>
<https://www.organicwine.com.au/vegan/?pgnum=7>
8, 9,10, and 11
2. On these pages the images are actually a thumbnail images something like 251px by 251px.
How would you go about adding to this script to say. And whilst you are at it follow the links to the detailed product page and capture the image link from there where the images are 1600px by 1600px and post those links to CSV
<https://www.organicwine.com.au/mercer-wines-preservative-free-shiraz-2020>
3. When we have identified those links lets also download those larger images to a folder
4. CSV writer. Also I don't understand line 58
for i in range(23)
how would i know how many products there were without counting them (i.e. there is 24 products on page one)
So this is what I want to learn how to do. Not asking for much (he says sarcastically) I could pay someone on up-work to do it but where's the fun in that? and that does not teach me how to 'fish'.
Where is a good place to learn python? A master class on web-scraping. It seems to be trial and error and blog posts and where ever you can pick up bits of information to piece it all together.
Maybe I need a mentor.
I wish there had been someone I could have reached out to, to tell me what beautifulSoup was all about. worked it out by trial and error and mostly guessing. No understanding of it but it just works.
Anyway, any help in pulling this all together to produce a decent script would be greatly appreciated.
Hopefully there is someone out there who would not mind helping me.
Apologies to organicwine for using their website as a learning tool. I do not wish to cause any harm or be a nuisance to the site
Thank you in advance
John
code:
```
import requests
import csv
from bs4 import BeautifulSoup
URL = "https://www.organicwine.com.au/vegan/?pgnum=1"
response = requests.get(URL)
website_html = response.text
soup = BeautifulSoup(website_html, "html.parser")
product_title = soup.find_all('div', class_="caption")
# print(product_title)
winename = []
for wine in product_title:
winetext = wine.a.text
winename.append(winetext)
print(f'''Wine Name: {winetext}''')
# print(f'''\nWine Name: {winename}\n''')
product_price = soup.find_all('div', class_='wrap-thumb-mob')
# print(product_price.text)
price =[]
for wine in product_price:
wineprice = wine.span.text
price.append(wineprice)
print(f'''Wine Price: {wineprice}''')
# print(f'''\nWine Price: {price}\n''')
image =[]
product_image_link = (soup.find_all('div', class_='thumbnail-image'))
# print(product_image_link)
for imagelink in product_image_link:
wineimagelink = imagelink.a['href']
image.append(wineimagelink)
# image.append(imagelink)
print(f'''Wine Image Lin: {wineimagelink}''')
# print(f'''\nWine Image: {image}\n''')
#
#
# """ writing data to CSV """
# open OrganicWine2.csv file in "write" mode
# newline stops a blank line appearing in csv
with open('OrganicWine2.csv', 'w',newline='') as file:
# create a "writer" object
writer = csv.writer(file, delimiter=',')
# use "writer" obj to write
# you should give a "list"
writer.writerow(["Wine Name", "Wine Price", "Wine Image Link"])
for i in range(23):
writer.writerow([
winename[i],
price[i],
image[i],
])
```
|
2021/05/24
|
[
"https://Stackoverflow.com/questions/67665789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16011875/"
] |
In this case, to do pagination, instead of `for i in range(1, 100)` which is a hardcoded way of paging, it's better to use a `while` loop to dynamically paginate all possible pages.
"While" is an infinite loop and it will be executed until the transition to the next page is possible, in this case it will check for the presence of the button for the next page, for which the CSS selector ".fa-chevron-right" is responsible:
```py
if soup.select_one(".fa-chevron-right"):
params["pgnum"] += 1 # go to the next page
else:
break
```
To extract the full size image an additional request is required, CSS selector ".main-image a" is responsible for full-size images:
```py
full_image_html = requests.get(link, headers=headers, timeout=30)
image_soup = BeautifulSoup(full_image_html.text, "lxml")
try:
original_image = f'https://www.organicwine.com.au{image_soup.select_one(".main-image a")["href"]}'
except:
original_image = None
```
An additional step to avoid being blocked is to [rotate user-agents](https://serpapi.com/blog/how-to-reduce-chance-of-being-blocked-while-web/#rotate-user-agents). Ideally, it would be better to use residential proxies with random user-agent.
[`pandas`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html) can be used to extract data in CSV format:
```py
pd.DataFrame(data=data).to_csv("<csv_file_name>.csv", index=False)
```
For a quick and easy search for CSS selectors, you can use the [SelectorGadget](https://selectorgadget.com/) Chrome extension (*not always work perfectly if the website is rendered via JavaScript*).
Check code with pagination and saving information to CSV in [online IDE](https://replit.com/@denisskopa/scrape-organicwine-with-pagination-bs4#main.py).
```py
from bs4 import BeautifulSoup
import requests, json, lxml
import pandas as pd
# https://requests.readthedocs.io/en/latest/user/quickstart/#custom-headers
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36",
}
params = {
'pgnum': 1 # number page by default
}
data = []
while True:
page = requests.get(
"https://www.organicwine.com.au/vegan/?",
params=params,
headers=headers,
timeout=30,
)
soup = BeautifulSoup(page.text, "lxml")
print(f"Extracting page: {params['pgnum']}")
for products in soup.select(".price-btn-conts"):
try:
title = products.select_one(".new-h3").text
except:
title = None
try:
price = products.select_one(".price").text.strip()
except:
price = None
try:
snippet = products.select_one(".price-btn-conts p a").text
except:
snippet = None
try:
link = products.select_one(".new-h3 a")["href"]
except:
link = None
# additional request is needed to extract full size image
full_image_html = requests.get(link, headers=headers, timeout=30)
image_soup = BeautifulSoup(full_image_html.text, "lxml")
try:
original_image = f'https://www.organicwine.com.au{image_soup.select_one(".main-image a")["href"]}'
except:
original_image = None
data.append(
{
"title": title,
"price": price,
"snippet": snippet,
"link": link,
"original_image": original_image
}
)
if soup.select_one(".fa-chevron-right"):
params["pgnum"] += 1
else:
break
# save to CSV (install, import pandas as pd)
pd.DataFrame(data=data).to_csv("<csv_file_name>.csv", index=False)
print(json.dumps(data, indent=2, ensure_ascii=False))
```
Example output:
```json
[
{
"title": "Yangarra McLaren Vale GSM 2016",
"price": "$29.78 in a straight 12\nor $34.99 each",
"snippet": "The Yangarra GSM is a careful blending of Grenache, Shiraz and Mourvèdre in which the composition varies from year to year, conveying the traditional estate blends of the southern Rhône. The backbone of the wine comes fr...",
"link": "https://www.organicwine.com.au/yangarra-mclaren-vale-gsm-2016",
"original_image": "https://www.organicwine.com.au/assets/full/YG_GSM_16.png?20211110083637"
},
{
"title": "Yangarra Old Vine Grenache 2020",
"price": "$37.64 in a straight 12\nor $41.99 each",
"snippet": "Produced from the fruit of dry grown bush vines planted high up in the Estate's elevated vineyards in deep sandy soils. These venerated vines date from 1946 and produce a wine that is complex, perfumed and elegant with a...",
"link": "https://www.organicwine.com.au/yangarra-old-vine-grenache-2020",
"original_image": "https://www.organicwine.com.au/assets/full/YG_GRE_20.jpg?20210710165951"
},
#...
]
```
|
Create the URL by putting the page number in it, then put the rest of your code into a `for` loop and you can use `len(winenames)` to count how many results you have. You should do the writing outside the `for` loop. Here's your code with those changes:
```py
import requests
import csv
from bs4 import BeautifulSoup
num_pages = 11
result = []
for pgnum in range(num_pages):
url = f"https://www.organicwine.com.au/vegan/?pgnum={pgnum+1}"
response = requests.get(url)
website_html = response.text
soup = BeautifulSoup(website_html, "html.parser")
product_title = soup.find_all("div", class_="caption")
winename = []
for wine in product_title:
winetext = wine.a.text
winename.append(winetext)
product_price = soup.find_all("div", class_="wrap-thumb-mob")
price = []
for wine in product_price:
wineprice = wine.span.text
price.append(wineprice)
image = []
product_image_link = soup.find_all("div", class_="thumbnail-image")
for imagelink in product_image_link:
winelink = imagelink.a["href"]
response = requests.get(winelink)
wine_page_soup = BeautifulSoup(response.text, "html.parser")
main_image = wine_page_soup.find("a", class_="fancybox")
image.append(main_image['href'])
for i in range(len(winename)):
result.append([winename[i], price[i], image[i]])
with open("/tmp/OrganicWine2.csv", "w", newline="") as file:
writer = csv.writer(file, delimiter=",")
writer.writerow(["Wine Name", "Wine Price", "Wine Image Link"])
writer.writerows(results)
```
And here's how I would rewrite your code to accomplish this task. It's more pythonic (you should basically never write `range(len(something))`, there's always a cleaner way) and it doesn't require knowing how many pages of results there are:
```py
import csv
import itertools
import time
import requests
from bs4 import BeautifulSoup
data = []
# Try opening 100 pages at most, in case the scraping code is broken
# which can happen because websites change.
for pgnum in range(1, 100):
url = f"https://www.organicwine.com.au/vegan/?pgnum={pgnum}"
response = requests.get(url)
website_html = response.text
soup = BeautifulSoup(website_html, "html.parser")
search_results = soup.find_all("div", class_="thumbnail")
for search_result in search_results:
name = search_result.find("div", class_="caption").a.text
price = search_result.find("p", class_="price").span.text
# link to the product's page
link = search_result.find("div", class_="thumbnail-image").a["href"]
# get the full resolution product image
response = requests.get(link)
time.sleep(1) # rate limit
wine_page_soup = BeautifulSoup(response.text, "html.parser")
main_image = wine_page_soup.find("a", class_="fancybox")
image_url = main_image["href"]
# or you can just "guess" it from the thumbnail's URL
# thumbnail = search_result.find("div", class_="thumbnail-image").a.img['src']
# image_url = thumbnail.replace('/thumbL/', '/full/')
data.append([name, price, link, image_url])
# if there's no "next page" button or no search results on the current page,
# stop scraping
if not soup.find("i", class_="fa-chevron-right") or not search_results:
break
# rate limit
time.sleep(1)
with open("/tmp/OrganicWine3.csv", "w", newline="") as file:
writer = csv.writer(file, delimiter=",")
writer.writerow(["Wine Name", "Wine Price", "Wine Link", "Wine Image Link"])
writer.writerows(data)
```
|
70,883,363
|
I am working on a python project that depends on some other files. It all works fine while testing. However, I want the program to run on start up. The working directory for programs that run on start up seems to be `C:Windows\system32`. When installing a program, it usually asks where to install it and no matter where you put it, if it runs on start up, it knows where its files are located. How do they achieve that? Also, how to achieve the same thing in python?
|
2022/01/27
|
[
"https://Stackoverflow.com/questions/70883363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12209262/"
] |
>
> But now the project grade file seems different.
>
>
>
Yes, starting with the new [Bumblebee](https://android-developers.googleblog.com/2022/01/android-studio-bumblebee-202111-stable.html) update of Android Studio, the build.gradle (Project) file is changed. In order to be able to use Google Services, you have to add to your build.gradle (Project) file the following lines:
```
plugins {
id 'com.android.application' version '7.1.0' apply false
id 'com.android.library' version '7.1.0' apply false
id 'com.google.gms.google-services' version '4.3.0' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
```
And inside your build.gradle (Module) file, the following plugin IDs:
```
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
```
In this way, your Firebase services will finally work.
P.S. Not 100% sure if the [Firebase Assistant](https://firebase.google.com/docs/android/setup) is updated with these new Android Studio changes.
**Edit 2022-14-07**:
Here is a repo that uses this new structure:
* <https://github.com/alexmamo/FirestoreCleanArchitectureApp>
**Edit:**
There is nothing changed regarding the way you add dependencies in the build.gradle (Module) file. If for example, you want to add Firestore and Glide, please use:
```
dependencies {
//Regular dependecies
implementation platform("com.google.firebase:firebase-bom:29.0.4")
implementation "com.google.firebase:firebase-firestore"
implementation "com.github.bumptech.glide:glide:4.12.0"
}
```
**Edit2:**
With the new updates, you don't need to worry about adding any lines under the repositories { }. That was a requirement in the previous versions.
|
I've had the same problem just add in the gradle.build project
>
> id 'com.google.gms.google-services' version '4.3.0' apply false
>
>
>
and then add in gradle.build module
>
> dependencies {
> //Regular dependecies
> implementation platform("com.google.firebase:firebase-bom:30.4.0")
> implementation "com.google.firebase:firebase-firestore"
>
>
>
}
|
70,883,363
|
I am working on a python project that depends on some other files. It all works fine while testing. However, I want the program to run on start up. The working directory for programs that run on start up seems to be `C:Windows\system32`. When installing a program, it usually asks where to install it and no matter where you put it, if it runs on start up, it knows where its files are located. How do they achieve that? Also, how to achieve the same thing in python?
|
2022/01/27
|
[
"https://Stackoverflow.com/questions/70883363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12209262/"
] |
>
> But now the project grade file seems different.
>
>
>
Yes, starting with the new [Bumblebee](https://android-developers.googleblog.com/2022/01/android-studio-bumblebee-202111-stable.html) update of Android Studio, the build.gradle (Project) file is changed. In order to be able to use Google Services, you have to add to your build.gradle (Project) file the following lines:
```
plugins {
id 'com.android.application' version '7.1.0' apply false
id 'com.android.library' version '7.1.0' apply false
id 'com.google.gms.google-services' version '4.3.0' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
```
And inside your build.gradle (Module) file, the following plugin IDs:
```
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
```
In this way, your Firebase services will finally work.
P.S. Not 100% sure if the [Firebase Assistant](https://firebase.google.com/docs/android/setup) is updated with these new Android Studio changes.
**Edit 2022-14-07**:
Here is a repo that uses this new structure:
* <https://github.com/alexmamo/FirestoreCleanArchitectureApp>
**Edit:**
There is nothing changed regarding the way you add dependencies in the build.gradle (Module) file. If for example, you want to add Firestore and Glide, please use:
```
dependencies {
//Regular dependecies
implementation platform("com.google.firebase:firebase-bom:29.0.4")
implementation "com.google.firebase:firebase-firestore"
implementation "com.github.bumptech.glide:glide:4.12.0"
}
```
**Edit2:**
With the new updates, you don't need to worry about adding any lines under the repositories { }. That was a requirement in the previous versions.
|
You will find your classpath from <https://console.firebase.google.com/>
**You will find something like this in the firebase**(if you already got your **classpath** then you can ignore this section)
```
buildscript {
repositories {
// Make sure that you have the following two repositories
google() // Google's Maven repository
mavenCentral() // Maven Central repository
}
dependencies {
...
// Add the dependency for the Google services Gradle plugin
classpath 'com.google.gms:google-services:4.3.13'
}
}
allprojects {
...
repositories {
// Make sure that you have the following two repositories
google() // Google's Maven repository
mavenCentral() // Maven Central repository
}
}
```
***just copy the classpath***
**1)In build.gradle(project)**
**before plugins make these changes-->**
```
buildscript {
dependencies {
classpath 'com.google.gms:google-services:4.3.13'
}
}
plugins {
id 'com.android.application' version '7.2.2' apply false
id 'com.android.library' version '7.2.2' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
```
**2)In build.gradle(module) add these lines in pulgins and dependencies section**
```
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
dependencies {
implementation platform('com.google.firebase:firebase-bom:30.2.0')
implementation 'com.google.firebase:firebase-analytics'
}
```
|
51,039,271
|
<https://github.com/ITCoders/Human-detection-and-Tracking/blob/master/main.py>
This is the code I obtained for the human detection. I'm using anaconda navigator(jupyter notebook). How can I use argument parser in this? How can I give the video path *-v* ? Can anyone please say me a solution for this? As the running of the program is done by clicking on the run button or by giving *shift+Enter*. I need to do human detection. I'm a beginner to python and opencv. So please do help.
|
2018/06/26
|
[
"https://Stackoverflow.com/questions/51039271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9993397/"
] |
What you are asking seems similar to: [Passing command line arguments to argv in jupyter/ipython notebook](https://stackoverflow.com/questions/37534440/passing-command-line-arguments-to-argv-in-jupyter-ipython-notebook)
There are two different methods mentioned in the post that were helpful. That said, I would suggest using command line tools and a Python IDE for writing scripts to run machine learning models. IPython may be helpful for visualization, fast debugging or running pre-trained models on commonly available datasets.
|
I tried out the answers listed on "[Passing command line arguments to argv in jupyter/ipython notebook](https://stackoverflow.com/questions/37534440/passing-command-line-arguments-to-argv-in-jupyter-ipython-notebook)", and came up with a different solution.
My original code was
```
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="path to input image")
ap.add_argument("-y", "--yolo", required=True, help="base path to YOLO directory")
ap.add_argument("-c", "--confidence", type=float, default=0.5, help="minimum probability to filter weak detections")
ap.add_argument("-t", "--threshold", type=float, default=0.3, help="threshold when applying non-maxima suppression")
args = vars(ap.parse_args())
```
The most common solution was to create a dummy class, which I wrote as:
```
Class Args():
image='photo.jpg'
yolo='yolo-coco'
confidence=0.5
threshold=0.3
args=Args()
```
but futher code snippets were producing an error.
So I printed `args` after `vars(ap.parse_args())` and found that it was a dictionary.
So just create a dictionary for the original args:
```
args={"image": 'photo.jpg', "yolo": 'yolo-coco', "confidence": 0.5,"threshold": 0.3}
```
|
51,039,271
|
<https://github.com/ITCoders/Human-detection-and-Tracking/blob/master/main.py>
This is the code I obtained for the human detection. I'm using anaconda navigator(jupyter notebook). How can I use argument parser in this? How can I give the video path *-v* ? Can anyone please say me a solution for this? As the running of the program is done by clicking on the run button or by giving *shift+Enter*. I need to do human detection. I'm a beginner to python and opencv. So please do help.
|
2018/06/26
|
[
"https://Stackoverflow.com/questions/51039271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9993397/"
] |
**All for me to do was pass an empty string to parser.parse\_args()**
`parser.parse_args() > parser.parse_args("")`
**And that was all for me.**
|
I tried out the answers listed on "[Passing command line arguments to argv in jupyter/ipython notebook](https://stackoverflow.com/questions/37534440/passing-command-line-arguments-to-argv-in-jupyter-ipython-notebook)", and came up with a different solution.
My original code was
```
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="path to input image")
ap.add_argument("-y", "--yolo", required=True, help="base path to YOLO directory")
ap.add_argument("-c", "--confidence", type=float, default=0.5, help="minimum probability to filter weak detections")
ap.add_argument("-t", "--threshold", type=float, default=0.3, help="threshold when applying non-maxima suppression")
args = vars(ap.parse_args())
```
The most common solution was to create a dummy class, which I wrote as:
```
Class Args():
image='photo.jpg'
yolo='yolo-coco'
confidence=0.5
threshold=0.3
args=Args()
```
but futher code snippets were producing an error.
So I printed `args` after `vars(ap.parse_args())` and found that it was a dictionary.
So just create a dictionary for the original args:
```
args={"image": 'photo.jpg', "yolo": 'yolo-coco', "confidence": 0.5,"threshold": 0.3}
```
|
72,879,863
|
yolov5 is detecting perfect while I run detect.py but unfortunately with deepsort track.py is not tracking even not detecting with tracker. how to set parameter my tracker ?
---
yolov5:
```
>> python detect.py --source video.mp4 --weights best.pt
```
yolov5+deepsort:
```
>> python track.py --yolo-weights best.pt --source video.mp4 --strong-sort-weights osnet_x0_25_msmt17.pt --show-vid --imgsz 640 --hide-labels
```
---
```
import argparse
from email.headerregistry import ContentDispositionHeader
import os
from pkg_resources import fixup_namespace_packages
# limit the number of cpus used by high performance libraries
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["OPENBLAS_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["VECLIB_MAXIMUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
import sys
import numpy as np
from pathlib import Path
import torch
import torch.backends.cudnn as cudnn
FILE = Path(__file__).resolve()
ROOT = FILE.parents[0] # yolov5 strongsort root directory
WEIGHTS = ROOT / 'weights'
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add ROOT to PATH
if str(ROOT / 'yolov5') not in sys.path:
sys.path.append(str(ROOT / 'yolov5')) # add yolov5 ROOT to PATH
if str(ROOT / 'strong_sort') not in sys.path:
sys.path.append(str(ROOT / 'strong_sort')) # add strong_sort ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
import logging
from yolov5.models.common import DetectMultiBackend
from yolov5.utils.dataloaders import VID_FORMATS, LoadImages, LoadStreams
from yolov5.utils.general import (LOGGER, check_img_size, non_max_suppression, scale_coords, check_requirements, cv2,
check_imshow, xyxy2xywh, increment_path, strip_optimizer, colorstr, print_args, check_file)
from yolov5.utils.torch_utils import select_device, time_sync
from yolov5.utils.plots import Annotator, colors, save_one_box
from strong_sort.utils.parser import get_config
from strong_sort.strong_sort import StrongSORT
# remove duplicated stream handler to avoid duplicated logging
logging.getLogger().removeHandler(logging.getLogger().handlers[0])
list_ball_cord = list()
@torch.no_grad()
def run(
source='0',
yolo_weights=WEIGHTS / 'yolov5m.pt', # model.pt path(s),
strong_sort_weights=WEIGHTS / 'osnet_x0_25_msmt17.pt', # model.pt path,
config_strongsort=ROOT / 'strong_sort/configs/strong_sort.yaml',
imgsz=(640, 640), # inference size (height, width)
conf_thres=0.25, # confidence threshold
iou_thres=0.45, # NMS IOU threshold
max_det=1000, # maximum detections per image
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
show_vid=False, # show results
save_txt=False, # save results to *.txt
save_conf=False, # save confidences in --save-txt labels
save_crop=False, # save cropped prediction boxes
save_vid=False, # save confidences in --save-txt labels
nosave=False, # do not save images/videos
classes=None, # filter by class: --class 0, or --class 0 2 3
agnostic_nms=False, # class-agnostic NMS
augment=False, # augmented inference
visualize=False, # visualize features
update=False, # update all models
project=ROOT / 'runs/track', # save results to project/name
name='exp', # save results to project/name
exist_ok=False, # existing project/name ok, do not increment
line_thickness=3, # bounding box thickness (pixels)
hide_labels=False, # hide labels
hide_conf=False, # hide confidences
hide_class=False, # hide IDs
half=False, # use FP16 half-precision inference
dnn=False, # use OpenCV DNN for ONNX inference
):
source = str(source)
save_img = not nosave and not source.endswith('.txt') # save inference images
is_file = Path(source).suffix[1:] in (VID_FORMATS)
is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
if is_url and is_file:
source = check_file(source) # download
# Directories
if not isinstance(yolo_weights, list): # single yolo model
exp_name = str(yolo_weights).rsplit('/', 1)[-1].split('.')[0]
elif type(yolo_weights) is list and len(yolo_weights) == 1: # single models after --yolo_weights
exp_name = yolo_weights[0].split(".")[0]
else: # multiple models after --yolo_weights
exp_name = 'ensemble'
exp_name = name if name is not None else exp_name + "_" + str(strong_sort_weights).split('/')[-1].split('.')[0]
save_dir = increment_path(Path(project) / exp_name, exist_ok=exist_ok) # increment run
(save_dir / 'tracks' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
# Load model
device = select_device(device)
model = DetectMultiBackend(yolo_weights, device=device, dnn=dnn, data=None, fp16=half)
stride, names, pt = model.stride, model.names, model.pt
imgsz = check_img_size(imgsz, s=stride) # check image size
# Dataloader
if webcam:
show_vid = check_imshow()
cudnn.benchmark = True # set True to speed up constant image size inference
dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
nr_sources = len(dataset)
else:
dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
nr_sources = 1
vid_path, vid_writer, txt_path = [None] * nr_sources, [None] * nr_sources, [None] * nr_sources
# initialize StrongSORT
cfg = get_config()
cfg.merge_from_file(opt.config_strongsort)
# Create as many strong sort instances as there are video sources
strongsort_list = []
for i in range(nr_sources):
strongsort_list.append(
StrongSORT(
strong_sort_weights,
device,
max_dist=cfg.STRONGSORT.MAX_DIST,
max_iou_distance=cfg.STRONGSORT.MAX_IOU_DISTANCE,
max_age=cfg.STRONGSORT.MAX_AGE,
n_init=cfg.STRONGSORT.N_INIT,
nn_budget=cfg.STRONGSORT.NN_BUDGET,
mc_lambda=cfg.STRONGSORT.MC_LAMBDA,
ema_alpha=cfg.STRONGSORT.EMA_ALPHA,
)
)
outputs = [None] * nr_sources
# Run tracking
model.warmup(imgsz=(1 if pt else nr_sources, 3, *imgsz)) # warmup
dt, seen = [0.0, 0.0, 0.0, 0.0], 0
curr_frames, prev_frames = [None] * nr_sources, [None] * nr_sources
for frame_idx, (path, im, im0s, vid_cap, s) in enumerate(dataset):
t1 = time_sync()
im = torch.from_numpy(im).to(device)
im = im.half() if half else im.float() # uint8 to fp16/32
im /= 255.0 # 0 - 255 to 0.0 - 1.0
if len(im.shape) == 3:
im = im[None] # expand for batch dim
t2 = time_sync()
dt[0] += t2 - t1
# Inference
visualize = increment_path(save_dir / Path(path[0]).stem, mkdir=True) if opt.visualize else False
pred = model(im, augment=opt.augment, visualize=visualize)
t3 = time_sync()
dt[1] += t3 - t2
# Apply NMS
pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, opt.classes, opt.agnostic_nms, max_det=opt.max_det)
dt[2] += time_sync() - t3
# Process detections
for i, det in enumerate(pred): # detections per image
seen += 1
if webcam: # nr_sources >= 1
p, im0, _ = path[i], im0s[i].copy(), dataset.count
p = Path(p) # to Path
s += f'{i}: '
txt_file_name = p.name
save_path = str(save_dir / p.name) # im.jpg, vid.mp4, ...
else:
p, im0, _ = path, im0s.copy(), getattr(dataset, 'frame', 0)
p = Path(p) # to Path
# video
### =============================================================================================
### ROI Rectangle ( I will use cv2.selectROI later )
# left_roi = [(381,331), (647,336), (647,497), (334,492)]
# right_roi = [(648,335), (914,338), (958,498), (646,495)]
# table_roi = [(381,331), (914,338), (958,498), (334,492)]
# table_roi = [(0,0), (1280,0), (1280,720), (0,720)]
table_roi = [(381,331), (1280,0), (1280,720), (0,720)]
cv2.polylines(im0, [np.array(table_roi, np.int32)],True, (0,0,255),2 )
# cv2.polylines(im0, [np.array(right_roi, np.int32)],True, (0,0,255),2 )
### =============================================================================================
if source.endswith(VID_FORMATS):
txt_file_name = p.stem
save_path = str(save_dir / p.name) # im.jpg, vid.mp4, ...
# folder with imgs
else:
txt_file_name = p.parent.name # get folder name containing current img
save_path = str(save_dir / p.parent.name) # im.jpg, vid.mp4, ...
curr_frames[i] = im0
txt_path = str(save_dir / 'tracks' / txt_file_name) # im.txt
s += '%gx%g ' % im.shape[2:] # print string
imc = im0.copy() if save_crop else im0 # for save_crop
annotator = Annotator(im0, line_width=2, pil=not ascii)
if cfg.STRONGSORT.ECC: # camera motion compensation
strongsort_list[i].tracker.camera_update(prev_frames[i], curr_frames[i])
if det is not None and len(det):
# Rescale boxes from img_size to im0 size
det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
# Print results
for c in det[:, -1].unique():
n = (det[:, -1] == c).sum() # detections per class
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
xywhs = xyxy2xywh(det[:, 0:4])
confs = det[:, 4]
clss = det[:, 5]
# pass detections to strongsort
t4 = time_sync()
outputs[i] = strongsort_list[i].update(xywhs.cpu(), confs.cpu(), clss.cpu(), im0)
t5 = time_sync()
dt[3] += t5 - t4
# draw boxes for visualization
if len(outputs[i]) > 0:
for j, (output, conf) in enumerate(zip(outputs[i], confs)):
### ========================================================================================================================================================
### Results ROI
### ========================================================================================================================================================
# if output[5] == 0.0:
# bboxes = output[0:4]
# id = output[4]
# cls = output[5]
# center = int((((output[0]) + (output[2]))/2) , (((output[1]) + (output[3]))/2))
# print("center",center)
"""
- create rectangle left/right
- display ball cordinates
- intersect ball & rectangle left/right
"""
## ball cord..
if output[5] == 0.0:
# print("bbox----------", output[0:4])
print("class----------", output[5])
# print("id -------------", output[4])
print("=============================================")
# display ball rectangle
## cv2.rectangle(im0,(int(output[0]),int(output[1])),(int(output[2]),int(output[3])),(0,255,0),2 )
ball_box = output[0:4]
list_ball_cord.append(ball_box)
bbox_left = output[0]
bbox_top = output[1]
bbox_w = output[2] - output[0]
bbox_h = output[3] - output[1]
# print("bbox_left--------", bbox_left)
# print("bbox_top--------", bbox_top)
# print("bbox_w--------", bbox_w)
# print("bbox_h--------", bbox_h)
## ball center point
ball_cx = int(bbox_left + bbox_w /2)
ball_cy = int(bbox_top + bbox_h /2)
# cv2.circle(im0, (ball_cx,ball_cy),5, (0,0,255),-1)
# # ball detect only on table >> return three output +1-inside the table -1-outside the table 0-on the boundry
ball_on_table_res = cv2.pointPolygonTest(np.array(table_roi,np.int32), (int(ball_cx),int(ball_cy)), False)
if ball_on_table_res >= 0:
cv2.circle(im0, (ball_cx,ball_cy),20, (0,0,0),-1)
### ========================================================================================================================================================
bboxes = output[0:4]
id = output[4]
cls = output[5]
# print("bboxes--------", bboxes)
# print("cls-----------", cls)
if save_txt:
# to MOT format
bbox_left = output[0]
bbox_top = output[1]
bbox_w = output[2] - output[0]
bbox_h = output[3] - output[1]
# Write MOT compliant results to file
with open(txt_path + '.txt', 'a') as f:
f.write(('%g ' * 10 + '\n') % (frame_idx + 1, id, bbox_left, # MOT format
bbox_top, bbox_w, bbox_h, -1, -1, -1, i))
if save_vid or save_crop or show_vid: # Add bbox to image
c = int(cls) # integer class
id = int(id) # integer id
label = None if hide_labels else (f'{id} {names[c]}' if hide_conf else \
(f'{id} {conf:.2f}' if hide_class else f'{id} {names[c]} {conf:.2f}'))
annotator.box_label(bboxes, label, color=colors(c, True))
#####################print("label---------", label)
if save_crop:
txt_file_name = txt_file_name if (isinstance(path, list) and len(path) > 1) else ''
save_one_box(bboxes, imc, file=save_dir / 'crops' / txt_file_name / names[c] / f'{id}' / f'{p.stem}.jpg', BGR=True)
fps_StrongSORT = 1 / (t5-t4)
fps_yolo = 1/ (t3-t2)
LOGGER.info(f'{s}Done. YOLO:({t3 - t2:.3f}s), StrongSORT:({t5 - t4:.3f}s), ')
print("fps_StrongSORT-----", fps_StrongSORT)
print("fps_yolo-----", fps_yolo)
else:
strongsort_list[i].increment_ages()
LOGGER.info('No detections')
# Stream results
im0 = annotator.result()
if show_vid:
# im0 = cv2.resize(im0, (640,640))
cv2.imshow(str(p), im0)
cv2.waitKey(1) # 1 millisecond
# Save results (image with detections)
if save_vid:
if vid_path[i] != save_path: # new video
vid_path[i] = save_path
if isinstance(vid_writer[i], cv2.VideoWriter):
vid_writer[i].release() # release previous video writer
if vid_cap: # video
fps = vid_cap.get(cv2.CAP_PROP_FPS)
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
else: # stream
fps, w, h = 30, im0.shape[1], im0.shape[0]
save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
vid_writer[i].write(im0)
prev_frames[i] = curr_frames[i]
print("fffffffffffffffffffffffffffffffff----------------------------------------",list_ball_cord)
# Print results
t = tuple(x / seen * 1E3 for x in dt) # speeds per image
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS, %.1fms strong sort update per image at shape {(1, 3, *imgsz)}' % t)
if save_txt or save_vid:
s = f"\n{len(list(save_dir.glob('tracks/*.txt')))} tracks saved to {save_dir / 'tracks'}" if save_txt else ''
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
if update:
strip_optimizer(yolo_weights) # update model (to fix SourceChangeWarning)
def parse_opt():
parser = argparse.ArgumentParser()
parser.add_argument('--yolo-weights', nargs='+', type=str, default='v5best_bp.pt', help='model.pt path(s)')
parser.add_argument('--strong-sort-weights', type=str, default=WEIGHTS / 'osnet_x0_25_msmt17.pt')
parser.add_argument('--config-strongsort', type=str, default='strong_sort/configs/strong_sort.yaml')
parser.add_argument('--source', type=str, default='0', help='file/dir/URL/glob, 0 for webcam')
parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
parser.add_argument('--conf-thres', type=float, default=0.5, help='confidence threshold')
parser.add_argument('--iou-thres', type=float, default=0.5, help='NMS IoU threshold')
parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
parser.add_argument('--show-vid', action='store_true', help='display tracking video results')
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
parser.add_argument('--save-vid', action='store_true', help='save video tracking results')
parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
# class 0 is person, 1 is bycicle, 2 is car... 79 is oven
parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
parser.add_argument('--augment', action='store_true', help='augmented inference')
parser.add_argument('--visualize', action='store_true', help='visualize features')
parser.add_argument('--update', action='store_true', help='update all models')
parser.add_argument('--project', default=ROOT / 'runs/track', help='save results to project/name')
parser.add_argument('--name', default='exp', help='save results to project/name')
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
parser.add_argument('--hide-class', default=False, action='store_true', help='hide IDs')
parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
opt = parser.parse_args()
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
print_args(vars(opt))
return opt
def main(opt):
check_requirements(requirements=ROOT / 'requirements.txt', exclude=('tensorboard', 'thop'))
run(**vars(opt))
if __name__ == "__main__":
opt = parse_opt()
main(opt)
```
[enter image description here](https://i.stack.imgur.com/QuUHW.jpg)
|
2022/07/06
|
[
"https://Stackoverflow.com/questions/72879863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14141667/"
] |
DISCLAIMER: I am the creator of <https://github.com/mikel-brostrom/Yolov5_StrongSORT_OSNet>
First of all:
Does Yolov5+StrongSORT+OSNet run correctly without you custom modifications?
Secondly:
Have you checked that you are loading the same weights for Yolov5 and Yolov5+StrongSORT+OSNet?
Moreover:
Why all the custom modifications? If you only want to track class 0. Then you can run the following command:
```
python track.py --source 0 --yolo-weights best.pt --classes 0
```
|
I am also using the same model and was facing the same issue.
Try annotating more image and increase the image size to 1024. Also make sure to use the best weights of yolov5 in yolov5+deepsort.
|
66,877,531
|
I have the following arguments which are to be parsed using argparse
* input\_dir (string: Mandatory)
* output\_dir (string: Mandatory)
* file\_path (string: Mandatory)
* supported\_file\_extensions (comma separated string - Optional)
* ignore\_tests (boolean - Optional)
If either comma separated string and a string are provided for `supported_file_extensions` and `ignore_tests` respectively, then I want the value to be set to the argument variable. My set up is as follows
```
import sys
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'input_dir', type=str,
help='Fully qualified directory for the input directory')
parser.add_argument(
'file_path', type=str,
help='Fully qualified path name for file')
parser.add_argument(
'output', type=str, help='Fully qualified output directory path')
parser.add_argument(
'-supported_file_extensions',nargs='?', type=str, default=None,
help='optional comma separated file extensions'
) # Should default to False
parser.add_argument(
'-ignore_tests', nargs='?', type=bool, default=True
) # Should default to True if the argument is passed
(arguments, _) = parser.parse_known_args(sys.argv[1:])
print(arguments)
```
When I pass the following command
```
python cloc.py -input_dir /myproject -file_path /myproject/.github/CODEOWNERS -output output.json --supported_file_extensions java,kt --ignore_tests False
```
I want the value of the arguments.--supported\_file\_extensions to be equal to `java,kt` and `ignore_tests` to equal to `False` but I get the following values
```
Namespace(file_path='/myproject/.github/CODEOWNERS', ignore_tests=True, input_dir='/myproject', output='output.json', supported_file_extensions=None)
```
If I don't pass `--ignored_tests` in my command line argument, then I want the file to default to `False`. Similarly, when I pass `--ignored_tests`, then I want the argument to be set to `True`.
If I pass `--supported_file_extensions java,kt`, then I want the argument to be set to `java,kt` as a string, and not a list.
I have tried going through but I have not had any success.
1. [Python argparse: default value or specified value](https://stackoverflow.com/questions/15301147/python-argparse-default-value-or-specified-value)
2. [python argparse default value for optional argument](https://stackoverflow.com/questions/29847450/python-argparse-default-value-for-optional-argument)
3. [Creating command lines with python (argparse)](https://stackoverflow.com/questions/61216374/creating-command-lines-with-python-argparse)
**UPDATE**
I updated the last two arguments as follows:
```
parser.add_argument(
'-supported_file_extensions', type=str,
help='optional comma separated file extensions'
)
parser.add_argument(
'-ignore_tests', action='store_true',
help='optional flag to ignore '
)
(arguments, _) = parser.parse_known_args(sys.argv[1:])
print(arguments)
```
When I run the command as
```
python cloc.py -input_dir /myproject -file_path /myproject/.github/CODEOWNERS -output output.json --supported_file_extensions java,kt
```
The output is as follows
```
Namespace(file_path='/myproject/.github/CODEOWNERS', ignore_tests=False, input_dir='/myproject', output='output.json', supported_file_extensions=None)
```
While the value of `ignore_tests` is correct, (defaulted to false), the value of `supported_file_extensions` is `None`, which is not correct since I had passed `java,kt` as command line arguments.
When I pass
```
python cloc.py -input_dir /myproject -file_path /myproject/.github/CODEOWNERS -output output.json --supported_file_extensions java,kt --ignore_tests
```
I get the following output
```
Namespace(file_path='/myproject/.github/CODEOWNERS', ignore_tests=False, input_dir='/myproject', output='output.json', supported_file_extensions=None)
```
|
2021/03/30
|
[
"https://Stackoverflow.com/questions/66877531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7717431/"
] |
The column `type` is ambiguous because it appears in both `t1` and in your JSON\_TABLE result. You should qualify the column.
```
mysql> select distinct t.type from t1,
json_table(type, '$[*]' columns (type varchar(50) PATH '$')) as t
order by t.type;
+-------+
| type |
+-------+
| type1 |
| type2 |
| type4 |
+-------+
```
|
I am able to resolve it by writing a `CROSS JOIN`
```
SELECT distinct j.type FROM t1
CROSS JOIN
JSON_TABLE(t1.type, " $ [*]"
COLUMNS ( type VARCHAR(20) PATH '$' )
) j
```
|
8,456,516
|
How can I go about "selecting" on multiple [`queue.Queue`](http://docs.python.org/py3k/library/queue.html)'s simultaneously?
Golang has the [desired feature](http://golang.org/doc/go_spec.html#Select_statements) with its channels:
```
select {
case i1 = <-c1:
print("received ", i1, " from c1\n")
case c2 <- i2:
print("sent ", i2, " to c2\n")
case i3, ok := (<-c3): // same as: i3, ok := <-c3
if ok {
print("received ", i3, " from c3\n")
} else {
print("c3 is closed\n")
}
default:
print("no communication\n")
}
```
Wherein the first channel to unblock executes the corresponding block. How would I achieve this in Python?
Update0
-------
Per [the link](http://www.1024cores.net/home/lock-free-algorithms/queues) given in [tux21b's answer](https://stackoverflow.com/a/8539910/149482), the desired queue type has the following properties:
* Multi-producer/multi-consumer queues (MPMC)
* provides per-producer FIFO/LIFO
* When a queue is empty/full consumers/producers get blocked
Furthermore channels can be blocking, producers will block until a consumer retrieves the item. I'm not sure that Python's Queue can do this.
|
2011/12/10
|
[
"https://Stackoverflow.com/questions/8456516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/149482/"
] |
There are many different implementations of producer-consumer queues, like [queue.Queue](http://docs.python.org/py3k/library/queue.html) available. They normally differ in a lot of properties like listed on this [excellent article](http://www.1024cores.net/home/lock-free-algorithms/queues) by Dmitry Vyukov. As you can see, there are more than 10k different combinations possible. The algorithms used for such queues also differ widely depending on the requirements. It's not possible to just extend an existing queue algorithm to guarantee additional properties, since that normally requires different internal data structures and different algorithms.
Go's channels offer a relatively high number of guaranteed properties, so those channels might be suitable for a lot of programs. One of the hardest requirements there is the support for reading / blocking on multiple channels at once (select statement) and to choose a channel fairly if more than one branch in a select statement is able to proceed, so that no messages will be left behind. Python's [queue.Queue](http://docs.python.org/py3k/library/queue.html) doesn't offer this features, so it's simply not possible to archive the same behavior with it.
So, if you want to continue using [queue.Queue](http://docs.python.org/py3k/library/queue.html) you need to find workarounds for that problem. The workarounds have however their own list of drawbacks and are harder to maintain. Looking for another producer-consumer queue which offers the features you need might be a better idea! Anyway, here are two possible workarounds:
**Polling**
```
while True:
try:
i1 = c1.get_nowait()
print "received %s from c1" % i1
except queue.Empty:
pass
try:
i2 = c2.get_nowait()
print "received %s from c2" % i2
except queue.Empty:
pass
time.sleep(0.1)
```
This might use a lot of CPU cycles while polling the channels and might be slow when there are a lot of messages. Using time.sleep() with an exponential back-off time (instead of the constant 0.1 secs shown here) might improve this version drastically.
**A single notify-queue**
```
queue_id = notify.get()
if queue_id == 1:
i1 = c1.get()
print "received %s from c1" % i1
elif queue_id == 2:
i2 = c2.get()
print "received %s from c2" % i2
```
With this setup, you must send something to the notify queue after sending to c1 or c2. This might work for you, as long as only one such notify-queue is enough for you (i.e. you do not have multiple "selects", each blocking on a different subset of your channels).
Alternatively you can also consider using Go. Go's goroutines and concurrency support is much more powerful than Python's limited threading capabilities anyway.
|
If you use `queue.PriorityQueue` you can get a similar behaviour using the channel objects as priorities:
```
import threading, logging
import random, string, time
from queue import PriorityQueue, Empty
from contextlib import contextmanager
logging.basicConfig(level=logging.NOTSET,
format="%(threadName)s - %(message)s")
class ChannelManager(object):
next_priority = 0
def __init__(self):
self.queue = PriorityQueue()
self.channels = []
def put(self, channel, item, *args, **kwargs):
self.queue.put((channel, item), *args, **kwargs)
def get(self, *args, **kwargs):
return self.queue.get(*args, **kwargs)
@contextmanager
def select(self, ordering=None, default=False):
if default:
try:
channel, item = self.get(block=False)
except Empty:
channel = 'default'
item = None
else:
channel, item = self.get()
yield channel, item
def new_channel(self, name):
channel = Channel(name, self.next_priority, self)
self.channels.append(channel)
self.next_priority += 1
return channel
class Channel(object):
def __init__(self, name, priority, manager):
self.name = name
self.priority = priority
self.manager = manager
def __str__(self):
return self.name
def __lt__(self, other):
return self.priority < other.priority
def put(self, item):
self.manager.put(self, item)
if __name__ == '__main__':
num_channels = 3
num_producers = 4
num_items_per_producer = 2
num_consumers = 3
num_items_per_consumer = 3
manager = ChannelManager()
channels = [manager.new_channel('Channel#{0}'.format(i))
for i in range(num_channels)]
def producer_target():
for i in range(num_items_per_producer):
time.sleep(random.random())
channel = random.choice(channels)
message = random.choice(string.ascii_letters)
logging.info('Putting {0} in {1}'.format(message, channel))
channel.put(message)
producers = [threading.Thread(target=producer_target,
name='Producer#{0}'.format(i))
for i in range(num_producers)]
for producer in producers:
producer.start()
for producer in producers:
producer.join()
logging.info('Producers finished')
def consumer_target():
for i in range(num_items_per_consumer):
time.sleep(random.random())
with manager.select(default=True) as (channel, item):
if channel:
logging.info('Received {0} from {1}'.format(item, channel))
else:
logging.info('No data received')
consumers = [threading.Thread(target=consumer_target,
name='Consumer#{0}'.format(i))
for i in range(num_consumers)]
for consumer in consumers:
consumer.start()
for consumer in consumers:
consumer.join()
logging.info('Consumers finished')
```
Example output:
```
Producer#0 - Putting x in Channel#2
Producer#2 - Putting l in Channel#0
Producer#2 - Putting A in Channel#2
Producer#3 - Putting c in Channel#0
Producer#3 - Putting z in Channel#1
Producer#1 - Putting I in Channel#1
Producer#1 - Putting L in Channel#1
Producer#0 - Putting g in Channel#1
MainThread - Producers finished
Consumer#1 - Received c from Channel#0
Consumer#2 - Received l from Channel#0
Consumer#0 - Received I from Channel#1
Consumer#0 - Received L from Channel#1
Consumer#2 - Received g from Channel#1
Consumer#1 - Received z from Channel#1
Consumer#0 - Received A from Channel#2
Consumer#1 - Received x from Channel#2
Consumer#2 - Received None from default
MainThread - Consumers finished
```
In this example, `ChannelManager` is just a wrapper around `queue.PriorityQueue` that implements the `select` method as a `contextmanager` to make it look similar to the `select` statement in Go.
A few things to note:
* Ordering
+ In the Go example, the order in which the channels are written inside the `select` statement determines which channel's code will be executed if there's data available for more than one channel.
+ In the python example the order is determined by the priority assigned to each channel. However, the priority can be dinamically assigned to each channel (as seen in the example), so changing the ordering would be possible with a more complex `select` method that takes care of assigning new priorities based on an argument to the method. Also, the old ordering could be reestablished once the context manager is finished.
* Blocking
+ In the Go example, the `select` statement is blocking if a `default` case exists.
+ In the python example, a boolean argument has to be passed to the `select` method to make it clear when blocking/non-blocking is desired. In the non-blocking case, the channel returned by the context mananager is just the string `'default'` so it's easy in the code inside to detect this in the code inside the `with` statement.
* Threading: Object in the `queue` module are already ready for multi-producer, multiconsumer-scenarios as already seen in the example.
|
8,456,516
|
How can I go about "selecting" on multiple [`queue.Queue`](http://docs.python.org/py3k/library/queue.html)'s simultaneously?
Golang has the [desired feature](http://golang.org/doc/go_spec.html#Select_statements) with its channels:
```
select {
case i1 = <-c1:
print("received ", i1, " from c1\n")
case c2 <- i2:
print("sent ", i2, " to c2\n")
case i3, ok := (<-c3): // same as: i3, ok := <-c3
if ok {
print("received ", i3, " from c3\n")
} else {
print("c3 is closed\n")
}
default:
print("no communication\n")
}
```
Wherein the first channel to unblock executes the corresponding block. How would I achieve this in Python?
Update0
-------
Per [the link](http://www.1024cores.net/home/lock-free-algorithms/queues) given in [tux21b's answer](https://stackoverflow.com/a/8539910/149482), the desired queue type has the following properties:
* Multi-producer/multi-consumer queues (MPMC)
* provides per-producer FIFO/LIFO
* When a queue is empty/full consumers/producers get blocked
Furthermore channels can be blocking, producers will block until a consumer retrieves the item. I'm not sure that Python's Queue can do this.
|
2011/12/10
|
[
"https://Stackoverflow.com/questions/8456516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/149482/"
] |
If you use `queue.PriorityQueue` you can get a similar behaviour using the channel objects as priorities:
```
import threading, logging
import random, string, time
from queue import PriorityQueue, Empty
from contextlib import contextmanager
logging.basicConfig(level=logging.NOTSET,
format="%(threadName)s - %(message)s")
class ChannelManager(object):
next_priority = 0
def __init__(self):
self.queue = PriorityQueue()
self.channels = []
def put(self, channel, item, *args, **kwargs):
self.queue.put((channel, item), *args, **kwargs)
def get(self, *args, **kwargs):
return self.queue.get(*args, **kwargs)
@contextmanager
def select(self, ordering=None, default=False):
if default:
try:
channel, item = self.get(block=False)
except Empty:
channel = 'default'
item = None
else:
channel, item = self.get()
yield channel, item
def new_channel(self, name):
channel = Channel(name, self.next_priority, self)
self.channels.append(channel)
self.next_priority += 1
return channel
class Channel(object):
def __init__(self, name, priority, manager):
self.name = name
self.priority = priority
self.manager = manager
def __str__(self):
return self.name
def __lt__(self, other):
return self.priority < other.priority
def put(self, item):
self.manager.put(self, item)
if __name__ == '__main__':
num_channels = 3
num_producers = 4
num_items_per_producer = 2
num_consumers = 3
num_items_per_consumer = 3
manager = ChannelManager()
channels = [manager.new_channel('Channel#{0}'.format(i))
for i in range(num_channels)]
def producer_target():
for i in range(num_items_per_producer):
time.sleep(random.random())
channel = random.choice(channels)
message = random.choice(string.ascii_letters)
logging.info('Putting {0} in {1}'.format(message, channel))
channel.put(message)
producers = [threading.Thread(target=producer_target,
name='Producer#{0}'.format(i))
for i in range(num_producers)]
for producer in producers:
producer.start()
for producer in producers:
producer.join()
logging.info('Producers finished')
def consumer_target():
for i in range(num_items_per_consumer):
time.sleep(random.random())
with manager.select(default=True) as (channel, item):
if channel:
logging.info('Received {0} from {1}'.format(item, channel))
else:
logging.info('No data received')
consumers = [threading.Thread(target=consumer_target,
name='Consumer#{0}'.format(i))
for i in range(num_consumers)]
for consumer in consumers:
consumer.start()
for consumer in consumers:
consumer.join()
logging.info('Consumers finished')
```
Example output:
```
Producer#0 - Putting x in Channel#2
Producer#2 - Putting l in Channel#0
Producer#2 - Putting A in Channel#2
Producer#3 - Putting c in Channel#0
Producer#3 - Putting z in Channel#1
Producer#1 - Putting I in Channel#1
Producer#1 - Putting L in Channel#1
Producer#0 - Putting g in Channel#1
MainThread - Producers finished
Consumer#1 - Received c from Channel#0
Consumer#2 - Received l from Channel#0
Consumer#0 - Received I from Channel#1
Consumer#0 - Received L from Channel#1
Consumer#2 - Received g from Channel#1
Consumer#1 - Received z from Channel#1
Consumer#0 - Received A from Channel#2
Consumer#1 - Received x from Channel#2
Consumer#2 - Received None from default
MainThread - Consumers finished
```
In this example, `ChannelManager` is just a wrapper around `queue.PriorityQueue` that implements the `select` method as a `contextmanager` to make it look similar to the `select` statement in Go.
A few things to note:
* Ordering
+ In the Go example, the order in which the channels are written inside the `select` statement determines which channel's code will be executed if there's data available for more than one channel.
+ In the python example the order is determined by the priority assigned to each channel. However, the priority can be dinamically assigned to each channel (as seen in the example), so changing the ordering would be possible with a more complex `select` method that takes care of assigning new priorities based on an argument to the method. Also, the old ordering could be reestablished once the context manager is finished.
* Blocking
+ In the Go example, the `select` statement is blocking if a `default` case exists.
+ In the python example, a boolean argument has to be passed to the `select` method to make it clear when blocking/non-blocking is desired. In the non-blocking case, the channel returned by the context mananager is just the string `'default'` so it's easy in the code inside to detect this in the code inside the `with` statement.
* Threading: Object in the `queue` module are already ready for multi-producer, multiconsumer-scenarios as already seen in the example.
|
```
from queue import Queue
# these imports needed for example code
from threading import Thread
from time import sleep
from random import randint
class MultiQueue(Queue):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.queues = []
def addQueue(self, queue):
queue.put = self._put_notify(queue, queue.put)
queue.put_nowait = self._put_notify(queue, queue.put_nowait)
self.queues.append(queue)
def _put_notify(self, queue, old_put):
def wrapper(*args, **kwargs):
result = old_put(*args, **kwargs)
self.put(queue)
return result
return wrapper
if __name__ == '__main__':
# an example of MultiQueue usage
q1 = Queue()
q1.name = 'q1'
q2 = Queue()
q2.name = 'q2'
q3 = Queue()
q3.name = 'q3'
mq = MultiQueue()
mq.addQueue(q1)
mq.addQueue(q2)
mq.addQueue(q3)
queues = [q1, q2, q3]
for i in range(9):
def message(i=i):
print("thread-%d starting..." % i)
sleep(randint(1, 9))
q = queues[i%3]
q.put('thread-%d ending...' % i)
Thread(target=message).start()
print('awaiting results...')
for _ in range(9):
result = mq.get()
print(result.name)
print(result.get())
```
Rather than try to use the `.get()` method of several queues, the idea here is to have the queues notify the `MultiQueue` when they have data ready -- sort of a `select` in reverse. This is achieved by having `MultiQueue` wrap the various `Queue`'s `put()` and `put_nowait()` methods so that when something is added to those queues, that queue is then `put()` into the the `MultiQueue`, and a corresponding `MultiQueue.get()` will retrieve the `Queue` that has data ready.
This `MultiQueue` is based on the FIFO Queue, but you could also use the LIFO or Priority queues as the base depending on your needs.
|
8,456,516
|
How can I go about "selecting" on multiple [`queue.Queue`](http://docs.python.org/py3k/library/queue.html)'s simultaneously?
Golang has the [desired feature](http://golang.org/doc/go_spec.html#Select_statements) with its channels:
```
select {
case i1 = <-c1:
print("received ", i1, " from c1\n")
case c2 <- i2:
print("sent ", i2, " to c2\n")
case i3, ok := (<-c3): // same as: i3, ok := <-c3
if ok {
print("received ", i3, " from c3\n")
} else {
print("c3 is closed\n")
}
default:
print("no communication\n")
}
```
Wherein the first channel to unblock executes the corresponding block. How would I achieve this in Python?
Update0
-------
Per [the link](http://www.1024cores.net/home/lock-free-algorithms/queues) given in [tux21b's answer](https://stackoverflow.com/a/8539910/149482), the desired queue type has the following properties:
* Multi-producer/multi-consumer queues (MPMC)
* provides per-producer FIFO/LIFO
* When a queue is empty/full consumers/producers get blocked
Furthermore channels can be blocking, producers will block until a consumer retrieves the item. I'm not sure that Python's Queue can do this.
|
2011/12/10
|
[
"https://Stackoverflow.com/questions/8456516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/149482/"
] |
There are many different implementations of producer-consumer queues, like [queue.Queue](http://docs.python.org/py3k/library/queue.html) available. They normally differ in a lot of properties like listed on this [excellent article](http://www.1024cores.net/home/lock-free-algorithms/queues) by Dmitry Vyukov. As you can see, there are more than 10k different combinations possible. The algorithms used for such queues also differ widely depending on the requirements. It's not possible to just extend an existing queue algorithm to guarantee additional properties, since that normally requires different internal data structures and different algorithms.
Go's channels offer a relatively high number of guaranteed properties, so those channels might be suitable for a lot of programs. One of the hardest requirements there is the support for reading / blocking on multiple channels at once (select statement) and to choose a channel fairly if more than one branch in a select statement is able to proceed, so that no messages will be left behind. Python's [queue.Queue](http://docs.python.org/py3k/library/queue.html) doesn't offer this features, so it's simply not possible to archive the same behavior with it.
So, if you want to continue using [queue.Queue](http://docs.python.org/py3k/library/queue.html) you need to find workarounds for that problem. The workarounds have however their own list of drawbacks and are harder to maintain. Looking for another producer-consumer queue which offers the features you need might be a better idea! Anyway, here are two possible workarounds:
**Polling**
```
while True:
try:
i1 = c1.get_nowait()
print "received %s from c1" % i1
except queue.Empty:
pass
try:
i2 = c2.get_nowait()
print "received %s from c2" % i2
except queue.Empty:
pass
time.sleep(0.1)
```
This might use a lot of CPU cycles while polling the channels and might be slow when there are a lot of messages. Using time.sleep() with an exponential back-off time (instead of the constant 0.1 secs shown here) might improve this version drastically.
**A single notify-queue**
```
queue_id = notify.get()
if queue_id == 1:
i1 = c1.get()
print "received %s from c1" % i1
elif queue_id == 2:
i2 = c2.get()
print "received %s from c2" % i2
```
With this setup, you must send something to the notify queue after sending to c1 or c2. This might work for you, as long as only one such notify-queue is enough for you (i.e. you do not have multiple "selects", each blocking on a different subset of your channels).
Alternatively you can also consider using Go. Go's goroutines and concurrency support is much more powerful than Python's limited threading capabilities anyway.
|
```
from queue import Queue
# these imports needed for example code
from threading import Thread
from time import sleep
from random import randint
class MultiQueue(Queue):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.queues = []
def addQueue(self, queue):
queue.put = self._put_notify(queue, queue.put)
queue.put_nowait = self._put_notify(queue, queue.put_nowait)
self.queues.append(queue)
def _put_notify(self, queue, old_put):
def wrapper(*args, **kwargs):
result = old_put(*args, **kwargs)
self.put(queue)
return result
return wrapper
if __name__ == '__main__':
# an example of MultiQueue usage
q1 = Queue()
q1.name = 'q1'
q2 = Queue()
q2.name = 'q2'
q3 = Queue()
q3.name = 'q3'
mq = MultiQueue()
mq.addQueue(q1)
mq.addQueue(q2)
mq.addQueue(q3)
queues = [q1, q2, q3]
for i in range(9):
def message(i=i):
print("thread-%d starting..." % i)
sleep(randint(1, 9))
q = queues[i%3]
q.put('thread-%d ending...' % i)
Thread(target=message).start()
print('awaiting results...')
for _ in range(9):
result = mq.get()
print(result.name)
print(result.get())
```
Rather than try to use the `.get()` method of several queues, the idea here is to have the queues notify the `MultiQueue` when they have data ready -- sort of a `select` in reverse. This is achieved by having `MultiQueue` wrap the various `Queue`'s `put()` and `put_nowait()` methods so that when something is added to those queues, that queue is then `put()` into the the `MultiQueue`, and a corresponding `MultiQueue.get()` will retrieve the `Queue` that has data ready.
This `MultiQueue` is based on the FIFO Queue, but you could also use the LIFO or Priority queues as the base depending on your needs.
|
8,456,516
|
How can I go about "selecting" on multiple [`queue.Queue`](http://docs.python.org/py3k/library/queue.html)'s simultaneously?
Golang has the [desired feature](http://golang.org/doc/go_spec.html#Select_statements) with its channels:
```
select {
case i1 = <-c1:
print("received ", i1, " from c1\n")
case c2 <- i2:
print("sent ", i2, " to c2\n")
case i3, ok := (<-c3): // same as: i3, ok := <-c3
if ok {
print("received ", i3, " from c3\n")
} else {
print("c3 is closed\n")
}
default:
print("no communication\n")
}
```
Wherein the first channel to unblock executes the corresponding block. How would I achieve this in Python?
Update0
-------
Per [the link](http://www.1024cores.net/home/lock-free-algorithms/queues) given in [tux21b's answer](https://stackoverflow.com/a/8539910/149482), the desired queue type has the following properties:
* Multi-producer/multi-consumer queues (MPMC)
* provides per-producer FIFO/LIFO
* When a queue is empty/full consumers/producers get blocked
Furthermore channels can be blocking, producers will block until a consumer retrieves the item. I'm not sure that Python's Queue can do this.
|
2011/12/10
|
[
"https://Stackoverflow.com/questions/8456516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/149482/"
] |
There are many different implementations of producer-consumer queues, like [queue.Queue](http://docs.python.org/py3k/library/queue.html) available. They normally differ in a lot of properties like listed on this [excellent article](http://www.1024cores.net/home/lock-free-algorithms/queues) by Dmitry Vyukov. As you can see, there are more than 10k different combinations possible. The algorithms used for such queues also differ widely depending on the requirements. It's not possible to just extend an existing queue algorithm to guarantee additional properties, since that normally requires different internal data structures and different algorithms.
Go's channels offer a relatively high number of guaranteed properties, so those channels might be suitable for a lot of programs. One of the hardest requirements there is the support for reading / blocking on multiple channels at once (select statement) and to choose a channel fairly if more than one branch in a select statement is able to proceed, so that no messages will be left behind. Python's [queue.Queue](http://docs.python.org/py3k/library/queue.html) doesn't offer this features, so it's simply not possible to archive the same behavior with it.
So, if you want to continue using [queue.Queue](http://docs.python.org/py3k/library/queue.html) you need to find workarounds for that problem. The workarounds have however their own list of drawbacks and are harder to maintain. Looking for another producer-consumer queue which offers the features you need might be a better idea! Anyway, here are two possible workarounds:
**Polling**
```
while True:
try:
i1 = c1.get_nowait()
print "received %s from c1" % i1
except queue.Empty:
pass
try:
i2 = c2.get_nowait()
print "received %s from c2" % i2
except queue.Empty:
pass
time.sleep(0.1)
```
This might use a lot of CPU cycles while polling the channels and might be slow when there are a lot of messages. Using time.sleep() with an exponential back-off time (instead of the constant 0.1 secs shown here) might improve this version drastically.
**A single notify-queue**
```
queue_id = notify.get()
if queue_id == 1:
i1 = c1.get()
print "received %s from c1" % i1
elif queue_id == 2:
i2 = c2.get()
print "received %s from c2" % i2
```
With this setup, you must send something to the notify queue after sending to c1 or c2. This might work for you, as long as only one such notify-queue is enough for you (i.e. you do not have multiple "selects", each blocking on a different subset of your channels).
Alternatively you can also consider using Go. Go's goroutines and concurrency support is much more powerful than Python's limited threading capabilities anyway.
|
The [pychan](https://github.com/stuglaser/pychan) project duplicates Go channels in Python, including multiplexing. It implements the same algorithm as Go, so it meets all of your desired properties:
* Multiple producers and consumers can communicate through a Chan. When both a producer and consumer are ready, the pair of them will block
* Producers and consumers are serviced in the order they arrived (FIFO)
* An empty (full) queue will block consumers (producers).
Here's what your example would look like:
```
c1 = Chan(); c2 = Chan(); c3 = Chan()
try:
chan, value = chanselect([c1, c3], [(c2, i2)])
if chan == c1:
print("Received %r from c1" % value)
elif chan == c2:
print("Sent %r to c2" % i2)
else: # c3
print("Received %r from c3" % value)
except ChanClosed as ex:
if ex.which == c3:
print("c3 is closed")
else:
raise
```
(Full disclosure: I wrote this library)
|
8,456,516
|
How can I go about "selecting" on multiple [`queue.Queue`](http://docs.python.org/py3k/library/queue.html)'s simultaneously?
Golang has the [desired feature](http://golang.org/doc/go_spec.html#Select_statements) with its channels:
```
select {
case i1 = <-c1:
print("received ", i1, " from c1\n")
case c2 <- i2:
print("sent ", i2, " to c2\n")
case i3, ok := (<-c3): // same as: i3, ok := <-c3
if ok {
print("received ", i3, " from c3\n")
} else {
print("c3 is closed\n")
}
default:
print("no communication\n")
}
```
Wherein the first channel to unblock executes the corresponding block. How would I achieve this in Python?
Update0
-------
Per [the link](http://www.1024cores.net/home/lock-free-algorithms/queues) given in [tux21b's answer](https://stackoverflow.com/a/8539910/149482), the desired queue type has the following properties:
* Multi-producer/multi-consumer queues (MPMC)
* provides per-producer FIFO/LIFO
* When a queue is empty/full consumers/producers get blocked
Furthermore channels can be blocking, producers will block until a consumer retrieves the item. I'm not sure that Python's Queue can do this.
|
2011/12/10
|
[
"https://Stackoverflow.com/questions/8456516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/149482/"
] |
The [pychan](https://github.com/stuglaser/pychan) project duplicates Go channels in Python, including multiplexing. It implements the same algorithm as Go, so it meets all of your desired properties:
* Multiple producers and consumers can communicate through a Chan. When both a producer and consumer are ready, the pair of them will block
* Producers and consumers are serviced in the order they arrived (FIFO)
* An empty (full) queue will block consumers (producers).
Here's what your example would look like:
```
c1 = Chan(); c2 = Chan(); c3 = Chan()
try:
chan, value = chanselect([c1, c3], [(c2, i2)])
if chan == c1:
print("Received %r from c1" % value)
elif chan == c2:
print("Sent %r to c2" % i2)
else: # c3
print("Received %r from c3" % value)
except ChanClosed as ex:
if ex.which == c3:
print("c3 is closed")
else:
raise
```
(Full disclosure: I wrote this library)
|
```
from queue import Queue
# these imports needed for example code
from threading import Thread
from time import sleep
from random import randint
class MultiQueue(Queue):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.queues = []
def addQueue(self, queue):
queue.put = self._put_notify(queue, queue.put)
queue.put_nowait = self._put_notify(queue, queue.put_nowait)
self.queues.append(queue)
def _put_notify(self, queue, old_put):
def wrapper(*args, **kwargs):
result = old_put(*args, **kwargs)
self.put(queue)
return result
return wrapper
if __name__ == '__main__':
# an example of MultiQueue usage
q1 = Queue()
q1.name = 'q1'
q2 = Queue()
q2.name = 'q2'
q3 = Queue()
q3.name = 'q3'
mq = MultiQueue()
mq.addQueue(q1)
mq.addQueue(q2)
mq.addQueue(q3)
queues = [q1, q2, q3]
for i in range(9):
def message(i=i):
print("thread-%d starting..." % i)
sleep(randint(1, 9))
q = queues[i%3]
q.put('thread-%d ending...' % i)
Thread(target=message).start()
print('awaiting results...')
for _ in range(9):
result = mq.get()
print(result.name)
print(result.get())
```
Rather than try to use the `.get()` method of several queues, the idea here is to have the queues notify the `MultiQueue` when they have data ready -- sort of a `select` in reverse. This is achieved by having `MultiQueue` wrap the various `Queue`'s `put()` and `put_nowait()` methods so that when something is added to those queues, that queue is then `put()` into the the `MultiQueue`, and a corresponding `MultiQueue.get()` will retrieve the `Queue` that has data ready.
This `MultiQueue` is based on the FIFO Queue, but you could also use the LIFO or Priority queues as the base depending on your needs.
|
38,272,965
|
It seems win32api should be able to do this given the answer [here](http://VBComponents.Remove) and [.
I would like to remove all modules from an excel workbook (.xls) using python
|
2016/07/08
|
[
"https://Stackoverflow.com/questions/38272965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/360826/"
] |
Consider using the [VBComponents collection](https://msdn.microsoft.com/en-us/library/aa443983(v=vs.60).aspx) available in the COM interface accessible with Python's `win23com.client` module. However, inside the particular workbook you need to first grant [programmatic access to the VBA object library](https://stackoverflow.com/questions/25638344/programmatic-access-to-visual-basic-project-is-not-trusted-excel).
Also, you will need to conditionally set the type as this procedure cannot delete object modules including Sheets (`Type = 100`) and Workbooks (`Type = 100`). Only Standard Modules (`Type = 1`), Class Modules (`Type = 2`), UserForms (`Type= 3`), and other inserted components can be removed. Of course you can iterate through defined list of modules to remove. `Try/Except` statement is used to effectively close out the Excel.Application process whether script fails or not.
```
import win32com.client
# OPEN EXCEL APP AND WORKBOOK
xlApp = win32com.client.Dispatch("Excel.Application")
xlwb = xlApp.Workbooks.Open("C:\\Path\\To\\Workbook.xlsm")
# ITERATE THROUGH EACH VB COMPONENT (CLASS MODULE, STANDARD MODULE, USER FORMS)
try:
for i in xlwb.VBProject.VBComponents:
xlmodule = xlwb.VBProject.VBComponents(i.Name)
if xlmodule.Type in [1, 2, 3]:
xlwb.VBProject.VBComponents.Remove(xlmodule)
except Exception as e:
print(e)
finally:
# CLOSE AND SAVE AND UNINITIALIZE APP
xlwb.Close(True)
xlApp.Quit
xlApp = None
```
|
Actually simply reading in the file with [`xlrd`](https://pypi.python.org/pypi/xlrd), copying with [`xlutils`](https://pypi.python.org/pypi/xlutils), and spitting it out with [`xlwt`](https://pypi.python.org/pypi/xlwt) will remove the VBA (and other stuff):
```
import xlrd, xlwt
from xlutils.copy import copy as xl_copy
rb = xlrd.open_workbook('/path/to/fin.xls')
wb = xl_copy(rb)
wb.save('/path/to/fou.xls')
```
|
8,923,764
|
```
#!/bin/python
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
import time
import commands
import sys
import string
import random
device = MonkeyRunner.waitForConnection(10)
device.press('KEYCODE_BACK', MonkeyDevice.DOWN_AND_UP)
time.sleep(1)
device.press('KEYCODE_BACK', MonkeyDevice.DOWN_AND_UP)
package = 'com.pak.pak1'
activity = 'com.pak.pak1.Activity123'
runComponent = package + '/' + activity
device.startActivity(component=runComponent)
time.sleep(1)
device.touch( 20, 90, MonkeyDevice.DOWN_AND_UP )
time.sleep(2)
device.touch( 20, 90, MonkeyDevice.DOWN_AND_UP )
#time.sleep(10)
device.touch( 450, 95, MonkeyDevice.DOWN_AND_UP )
```
if I run the script like this it works just fine
But if I put some delay (time.sleep(10)) then ti gives this error
```
120119 10:31:24.823:S [main] [com.android.monkeyrunner.adb.AdbMonkeyDevice] Error getting the manager to quit
120119 10:31:24.823:S [main] [com.android.monkeyrunner.adb.AdbMonkeyDevice]java.net.SocketException: Broken pipe
120119 10:31:24.823:S [main] [com.android.monkeyrunner.adb.AdbMonkeyDevice] at java.net.SocketOutputStream.socketWrite0(Native Method)
120119 10:31:24.823:S [main] [com.android.monkeyrunner.adb.AdbMonkeyDevice] at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
120119 10:31:24.823:S [main] [com.android.monkeyrunner.adb.AdbMonkeyDevice] at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
120119 10:31:24.823:S [main] [com.android.monkeyrunner.adb.AdbMonkeyDevice] at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:202)
120119 10:31:24.823:S [main] [com.android.monkeyrunner.adb.AdbMonkeyDevice] at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:272)
120119 10:31:24.823:S [main] [com.android.monkeyrunner.adb.AdbMonkeyDevice] at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:276)
120119 10:31:24.823:S [main] [com.android.monkeyrunner.adb.AdbMonkeyDevice] at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:122)
120119 10:31:24.823:S [main] [com.android.monkeyrunner.adb.AdbMonkeyDevice] at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:212)
120119 10:31:24.823:S [main] [com.android.monkeyrunner.adb.AdbMonkeyDevice] at java.io.BufferedWriter.flush(BufferedWriter.java:236)
120119 10:31:24.823:S [main] [com.android.monkeyrunner.adb.AdbMonkeyDevice] at com.android.monkeyrunner.MonkeyManager.sendMonkeyEventAndGetResponse(MonkeyManager.java:167)
120119 10:31:24.823:S [main] [com.android.monkeyrunner.adb.AdbMonkeyDevice] at com.android.monkeyrunner.MonkeyManager.quit(MonkeyManager.java:288)
120119 10:31:24.823:S [main] [com.android.monkeyrunner.adb.AdbMonkeyDevice] at com.android.monkeyrunner.adb.AdbMonkeyDevice.dispose(AdbMonkeyDevice.java:79)
120119 10:31:24.823:S [main] [com.android.monkeyrunner.adb.AdbMonkeyDevice] at com.android.monkeyrunner.adb.AdbBackend.shutdown(AdbBackend.java:120)
120119 10:31:24.823:S [main] [com.android.monkeyrunner.adb.AdbMonkeyDevice] at com.android.monkeyrunner.MonkeyRunnerStarter.run(MonkeyRunnerStarter.java:95)
120119 10:31:24.823:S [main] [com.android.monkeyrunner.adb.AdbMonkeyDevice] at com.android.monkeyrunner.MonkeyRunnerStarter.main(MonkeyRunnerStarter.java:203)
```
|
2012/01/19
|
[
"https://Stackoverflow.com/questions/8923764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/706780/"
] |
Not all namespaces have corresponding DLL file names used in the Add Reference dialog. System.Windows is one of these.
For example, `System.Windows.Clipboard` is resident in the PresentationCore.dll, but `System.Windows.SizeConverter` is in WindowsBase.dll. It all depends on the actual types you need to access.
|
System.Windows is the WPF base classes - you cant add that assembly to an ASP.NET site. You will need to change your application type to use it.
|
55,930,785
|
I am trying to understand NumPy `np.fromfunction()`.
following piece of code is extracted from this [post](https://stackoverflow.com/a/55929789/11074017).
```
dist = np.array([ 1, -1])
f = lambda x: np.linalg.norm(x, 1)
f(dist)
```
the output
```
2.0
```
is as expected.
when I put them together to use np.linalg.norm() inside np.fromfunction()
```
ds = np.array([[1, 2, 1],
[1, 1, 0],
[0, 1, 1]])
np.fromfunction(f, ds.shape)
```
error shows up.
```
> TypeError Traceback (most recent call
last) <ipython-input-6-f5d65a6d95c4> in <module>()
2 [1, 1, 0],
3 [0, 1, 1]])
----> 4 np.fromfunction(f, ds.shape)
~/anaconda3/envs/tf11/lib/python3.6/site-packages/numpy/core/numeric.py
in fromfunction(function, shape, **kwargs)
2026 dtype = kwargs.pop('dtype', float)
2027 args = indices(shape, dtype=dtype)
-> 2028 return function(*args, **kwargs)
2029
2030
TypeError: <lambda>() takes 1 positional argument but 2 were given
```
is it possible to put a lambda function(may be another lambda function) inside np.fromfunction() to do this job(get a distance array)?
|
2019/05/01
|
[
"https://Stackoverflow.com/questions/55930785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Look at the error:
```
In [171]: np.fromfunction(f, ds.shape)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-171-1a3ed1ade41a> in <module>
----> 1 np.fromfunction(f, ds.shape)
/usr/local/lib/python3.6/dist-packages/numpy/core/numeric.py in fromfunction(function, shape, **kwargs)
2026 dtype = kwargs.pop('dtype', float)
2027 args = indices(shape, dtype=dtype)
-> 2028 return function(*args, **kwargs)
2029
2030
TypeError: <lambda>() takes 1 positional argument but 2 were given
```
`fromfunction` is a small Python function; there's no compiled magic.
Based on the shape you give, it generates `indices`.
```
In [172]: np.indices(ds.shape)
Out[172]:
array([[[0, 0, 0],
[1, 1, 1],
[2, 2, 2]],
[[0, 1, 2],
[0, 1, 2],
[0, 1, 2]]])
```
That's a (2,3,3) array. The 2 from the 2 element shape, and the (3,3) from the shape itself. This is similar to what `np.meshgrid` and `np.mgrid` produce. Just indexing arrays.
It then passes that array to your function, with `*args` unpacking.
```
function(*args, **kwargs)
In [174]: f(Out[172][0], Out[172][1])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-174-40469f1ab449> in <module>
----> 1 f(Out[172][0], Out[172][1])
TypeError: <lambda>() takes 1 positional argument but 2 were given
```
That's all it does - generate a n-d grid, and pass it as n arguments to your function.
===
Note also that you passed `ds.shape` to `fromfunction`, but not `ds` itself. You could just as well written `np.fromfunction(f,(3,3))`.
What do you want your `lambda` to do with `ds`? Clearly `fromfunction` isn't doing it for you.
===
With this `f`, the only that `fromfunction` can do is give it a `arange`:
```
In [176]: np.fromfunction(f, (10,))
Out[176]: 45.0
In [177]: f(np.arange(10))
Out[177]: 45.0
```
===
In the linked SO the lambda takes 2 arguments, `lambda x,y`:
```
np.fromfunction(lambda x,y: np.abs(target[0]-x) + np.abs(target[1]-y), ds.shape)
```
In that SO, both the question and answer, the `ds` array is just the source of the shape, Target is (0,1), the largest element of `ds`.
Effectively, the `fromfunction` in the linked answer is just doing:
```
In [180]: f1 = lambda x,y: np.abs(0-x) + np.abs(1-y)
In [181]: f1(Out[172][0], Out[172][1])
Out[181]:
array([[1, 0, 1],
[2, 1, 2],
[3, 2, 3]])
In [182]: np.abs(0-Out[172][0]) + np.abs(1-Out[172][1])
Out[182]:
array([[1, 0, 1],
[2, 1, 2],
[3, 2, 3]])
In [183]: np.abs(np.array([0,1])[:,None,None]-Out[172]).sum(axis=0)
Out[183]:
array([[1, 0, 1],
[2, 1, 2],
[3, 2, 3]])
In [184]: np.abs(0-np.arange(3))[:,None] + np.abs(1-np.arange(3))
Out[184]:
array([[1, 0, 1],
[2, 1, 2],
[3, 2, 3]])
```
|
As you are using a 2 dimensional array, your function needs to take 2 inputs.
The docs of `np.fromfunction()` <https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfunction.html> say "Construct an array by executing a function over each coordinate."
So it will pass the coordinates of each element of the array ((0,0), then (0,1) ... etc) to construct an array. Is this really what you are trying to do?
You could change the lambda to something like this, but it really depends on what you are trying to do!
```
f = lambda x, y: np.linalg.norm([x,y],1)
```
|
31,965,153
|
I'm actually trying to program a sort of "rolegame", and actually I'm stuck in the process of creating the new Character files. I'm actually trying to make it so, if I call a character file, the system checks if it exists and, if not, it will create it. This is the code, just trying if it will create an empty file called `(charactername).char`:
```
import os
def call_char(name):
file = "%s.char" %name
if os.path.exists(file):
print ("file loaded")
open_char(file)
else:
print ("creating new character")
new_char(file)
"""creates a new character file"""
def new_char(file):
print ("Character %s."%file)
file(file, "w")
call_char("Volgrand")
```
However, I get this error while executing `call_char("Volgrand")`
```
File "E:\python\Juego foral\test.py", line 51, in new_char
file(file, "w")
TypeError: 'str' object is not callable"
```
I though that calling the variable `file` (a string) should work to create the new file.
|
2015/08/12
|
[
"https://Stackoverflow.com/questions/31965153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5219236/"
] |
This is a cordova bug - <https://issues.apache.org/jira/browse/CB-5398>.
You can change your path like this.
```
function uploadPhoto(imageURI) {
//alert(imageURI); return false;
//alert(imageURI);
if (imageURI.substring(0,21)=="content://com.android") {
photo_split=imageURI.split("%3A");
imageURI="content://media/external/images/media/"+photo_split[1];
}
var options = new FileUploadOptions();
options.fileKey="file";
//options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1)+'.png';
options.mimeType="image/jpeg";
var params = {};
params.value1 = "test";
params.value2 = "param";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.params = params;
options.chunkedMode = true; //this is important to send both data and files
//alert(options.fileName);
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("file_upload.php"), win, fail, options);
}
```
And send image request to file\_upload.php. Add some condition like this.
```
$file=$_FILES['file']['name'];
$new_file=explode('.', $file);
$img_file=end($new_file);
if($img_file=='png' || $img_file=='jpeg' || $img_file=='jpg')
{
$file_name=$new_file[0];
} else {
$file_name=$_FILES['file']['name'];
$_FILES['file']['name']=$_FILES['file']['name'].'.jpg';
}
move_uploaded_file($_FILES["file"]["tmp_name"], 'your_location'.$file_name);
```
|
You can specify `encodingType: Camera.EncodingType.JPEG` and render image in your success callback like this- `$('#yourElement).attr('src', "data:image/jpeg;base64," + ImageData);`
```
navigator.camera.getPicture(onSuccess, onFail, {
quality: 100,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 500,
targetHeight: 500,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false,
correctOrientation: true
});
function onSuccess(imageData) {
console.log("Image URI success");
ImageData = imageData;
$('#yourElement).attr('src', "data:image/jpeg;base64," + ImageData);
}
```
|
69,334,001
|
When i am using "optimizer = keras.optimizers.Adam(learning\_rate)" i am getting this error
"AttributeError: module 'keras.optimizers' has no attribute 'Adam". I am using python3.8 keras 2.6 and backend tensorflow 1.13.2 for running the program. Please help to resolve !
|
2021/09/26
|
[
"https://Stackoverflow.com/questions/69334001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17007363/"
] |
Use `tf.keras.optimizers.Adam(learning_rate)` instead of `keras.optimizers.Adam(learning_rate)`
|
I think you are using Keras directly. Instead of giving as from keras.distribute import —> give as from tensorflow.keras.distribute import
Hope this would help you.. It is working for me.
|
69,334,001
|
When i am using "optimizer = keras.optimizers.Adam(learning\_rate)" i am getting this error
"AttributeError: module 'keras.optimizers' has no attribute 'Adam". I am using python3.8 keras 2.6 and backend tensorflow 1.13.2 for running the program. Please help to resolve !
|
2021/09/26
|
[
"https://Stackoverflow.com/questions/69334001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17007363/"
] |
As per the [documentation](https://keras.io/api/optimizers/) , try to import `keras` into your code like this,
```
>>> from tensorflow import keras
```
This has helped me as well.
|
I think you are using Keras directly. Instead of giving as from keras.distribute import —> give as from tensorflow.keras.distribute import
Hope this would help you.. It is working for me.
|
69,334,001
|
When i am using "optimizer = keras.optimizers.Adam(learning\_rate)" i am getting this error
"AttributeError: module 'keras.optimizers' has no attribute 'Adam". I am using python3.8 keras 2.6 and backend tensorflow 1.13.2 for running the program. Please help to resolve !
|
2021/09/26
|
[
"https://Stackoverflow.com/questions/69334001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17007363/"
] |
Make sure you've imported tensorflow:
```
import tensorflow as tf
```
Then use
```
tf.optimizers.Adam(learning_rate)
```
|
I think you are using Keras directly. Instead of giving as from keras.distribute import —> give as from tensorflow.keras.distribute import
Hope this would help you.. It is working for me.
|
69,334,001
|
When i am using "optimizer = keras.optimizers.Adam(learning\_rate)" i am getting this error
"AttributeError: module 'keras.optimizers' has no attribute 'Adam". I am using python3.8 keras 2.6 and backend tensorflow 1.13.2 for running the program. Please help to resolve !
|
2021/09/26
|
[
"https://Stackoverflow.com/questions/69334001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17007363/"
] |
There are ways to solve your problem as you are using keras 2.6 and tensorflow too:
* use (from keras.optimizer\_v2.adam import Adam as Adam) but go through the function documentation once to specify your learning rate and beta values
* you can also use (Adam = keras.optimizers.Adam).
* (import tensorflow as tf) then (Adam = tf.keras.optimizers.Adam)
Use the form that is useful for the environment you set
|
I think you are using Keras directly. Instead of giving as from keras.distribute import —> give as from tensorflow.keras.distribute import
Hope this would help you.. It is working for me.
|
69,334,001
|
When i am using "optimizer = keras.optimizers.Adam(learning\_rate)" i am getting this error
"AttributeError: module 'keras.optimizers' has no attribute 'Adam". I am using python3.8 keras 2.6 and backend tensorflow 1.13.2 for running the program. Please help to resolve !
|
2021/09/26
|
[
"https://Stackoverflow.com/questions/69334001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17007363/"
] |
Use `tf.keras.optimizers.Adam(learning_rate)` instead of `keras.optimizers.Adam(learning_rate)`
|
As per the [documentation](https://keras.io/api/optimizers/) , try to import `keras` into your code like this,
```
>>> from tensorflow import keras
```
This has helped me as well.
|
69,334,001
|
When i am using "optimizer = keras.optimizers.Adam(learning\_rate)" i am getting this error
"AttributeError: module 'keras.optimizers' has no attribute 'Adam". I am using python3.8 keras 2.6 and backend tensorflow 1.13.2 for running the program. Please help to resolve !
|
2021/09/26
|
[
"https://Stackoverflow.com/questions/69334001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17007363/"
] |
Use `tf.keras.optimizers.Adam(learning_rate)` instead of `keras.optimizers.Adam(learning_rate)`
|
Make sure you've imported tensorflow:
```
import tensorflow as tf
```
Then use
```
tf.optimizers.Adam(learning_rate)
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.