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
|
|---|---|---|---|---|---|
13,391,444
|
I'm trying to use [PySide](http://qt-project.org/wiki/PySideDocumentation) so I did a `brew install pyside pyside-tools`. However, I get the following error:
```
>>> from PySide.QtGui import QApplication
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dlopen(/Library/Python/2.7/site-packages/PySide/QtGui.so, 2): Library not loaded: QtGui.framework/Versions/4/QtGui
Referenced from: /Library/Python/2.7/site-packages/PySide/QtGui.so
Reason: image not found
```
[This](https://stackoverflow.com/questions/6970319/installing-pyside-on-osx-10-6-8) SO question says to install python 27 and then reinstall pyside but I'm using the native python on mac osx 10.8 and it is already 2.7.2.
The [Homebrew](https://github.com/mxcl/homebrew/issues/15450) recipe for PySide seems to indicate that this should have been fixed but I'm still getting the errors. I made sure libpng is installed as well.
Looking at the path, I know that the QtGui.so file is there. Since I'm new to Python, PySide, and Qt, it is hard for me to Google and further troubleshoot.
If anyone knows why and can provide directions, I will be very grateful. It can involve uninstalling a bunch of stuff and reinstalling. Please give detailed instructions. I did uninstall and try to reinstall and got the same result.
Thank you.
|
2012/11/15
|
[
"https://Stackoverflow.com/questions/13391444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384964/"
] |
I was getting the same error, and I'm using Python installed via Homebrew. I found two PySide libraries in /Library/Python/2.7/site-packages/ . Moving them out of the way, and re-building/installing PySide through Homebrew worked.
|
I tried the import you gave - I am using same system environment. It worked fine. try: brew update and re-install.
|
13,391,444
|
I'm trying to use [PySide](http://qt-project.org/wiki/PySideDocumentation) so I did a `brew install pyside pyside-tools`. However, I get the following error:
```
>>> from PySide.QtGui import QApplication
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dlopen(/Library/Python/2.7/site-packages/PySide/QtGui.so, 2): Library not loaded: QtGui.framework/Versions/4/QtGui
Referenced from: /Library/Python/2.7/site-packages/PySide/QtGui.so
Reason: image not found
```
[This](https://stackoverflow.com/questions/6970319/installing-pyside-on-osx-10-6-8) SO question says to install python 27 and then reinstall pyside but I'm using the native python on mac osx 10.8 and it is already 2.7.2.
The [Homebrew](https://github.com/mxcl/homebrew/issues/15450) recipe for PySide seems to indicate that this should have been fixed but I'm still getting the errors. I made sure libpng is installed as well.
Looking at the path, I know that the QtGui.so file is there. Since I'm new to Python, PySide, and Qt, it is hard for me to Google and further troubleshoot.
If anyone knows why and can provide directions, I will be very grateful. It can involve uninstalling a bunch of stuff and reinstalling. Please give detailed instructions. I did uninstall and try to reinstall and got the same result.
Thank you.
|
2012/11/15
|
[
"https://Stackoverflow.com/questions/13391444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384964/"
] |
I was getting the same error, and I'm using Python installed via Homebrew. I found two PySide libraries in /Library/Python/2.7/site-packages/ . Moving them out of the way, and re-building/installing PySide through Homebrew worked.
|
Got the same error when running `ipython qtconsole` which will import PySide to provide a Qt console.
Finally I thought there might be something wrong after PySide's installation. So I run `pyside_postinstall.py -install` manually which should be automatically run after PySide is installed, and this fixed my problem. Hopes working for your too!
|
61,698,002
|
From python in a nutshell,
>
> Where C is a class, the statement `x=C(23)` is equivalent to:
>
>
>
> ```
> x = C.__new__(C, 23)
> if isinstance(x, C): type(x).__init__(x, 23)
>
> ```
>
>
From my understanding `object.__new__` creates a new, uninitialized instance of the class it receives as its first argument.
Why is there need to be a check with the `isinstance()`. Isn't it obvious that `__new__` will return a object of type `C`.
If it is what happens if this test fails?
Since `classes` are `callables`, is the call to `__new__` is done in the class's `__call()__` method
Am I missing something here, please clarify this to me
|
2020/05/09
|
[
"https://Stackoverflow.com/questions/61698002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13432122/"
] |
>
> Isn't it obvious that `__new__` will return a object of type C.
>
>
>
Not at all. The following is valid:
```
>>> class C:
... def __new__(cls):
... return "not a C"
... def __init__(self):
... print("Never called")
...
>>> C()
'not a C'
```
When you override `__new__`, you will *probably* return an instance of `cls`, but you aren't *required* to. This is useful for defining factory classes, which don't create instances of themselves but rather instances of other classes.
Note that you quote is not quite accurate. `x = C(32)` is equivalent, at the first step, to `x = type.__call__(C, 32)`. It is `type.__call__` that calls `C.__new__`, then decides whether to invoke the return value's `__init__` method.
You can think of `type.__call__` as being defined something like
```
def __call__(cls, *args, **kwargs):
obj = cls.__new__(cls, *args, **kwargs)
if isinstance(obj, cls):
obj.__init__(*args, **kwargs)
return obj
```
Applying this to `C`, we see that `obj` is set to the `str` value `'not a C'`, not an instance of `C`, so that `'not a C'.__init__` is not called before returning the string.
|
[isinstance(a, b)](https://docs.python.org/3/library/functions.html#isinstance) is used to check if a is instance of b. Not sure why you checking it after creation. Magical methods can be redefined. Although in normal cases isinstance() is needed to check dynamic data.
|
44,718,204
|
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition.
```
log file name - my_app_20170622.log
log file entries within time - 00:00:01 to 23:59:59
```
On next day I want to create a new log file with next day's date -
```
log file name - my_app_20170623.log
log file entries within time - 00:00:01 to 23:59:59
```
I'm using logging module of python.
I'm using like below -
```
log_level = int(log_level)
logger = logging.getLogger('simple')
logger.setLevel(log_level)
fh = logging.FileHandler(log_file_name)
fh.setLevel(log_level)
formatter = logging.Formatter(log_format)
fh.setFormatter(formatter)
logger.addHandler(fh)
```
Is their any configurations in logging module of python to create a log on daily basis?
|
2017/06/23
|
[
"https://Stackoverflow.com/questions/44718204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6102259/"
] |
You have to create a `TimedRotatingFileHandler`:
```
from logging.handlers import TimedRotatingFileHandler
logname = "my_app.log"
handler = TimedRotatingFileHandler(logname, when="midnight", interval=1)
handler.suffix = "%Y%m%d"
logger.addHandler(handler)
```
This piece of code will create a `my_app.log` but the log will be moved to a new log file named `my_app.log.20170623` when the current day ends at midnight.
I hope this helps.
|
I suggest you take a look at `logging.handlers.TimedRotatingFileHandler`.
I think it's what you're looking for.
|
44,718,204
|
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition.
```
log file name - my_app_20170622.log
log file entries within time - 00:00:01 to 23:59:59
```
On next day I want to create a new log file with next day's date -
```
log file name - my_app_20170623.log
log file entries within time - 00:00:01 to 23:59:59
```
I'm using logging module of python.
I'm using like below -
```
log_level = int(log_level)
logger = logging.getLogger('simple')
logger.setLevel(log_level)
fh = logging.FileHandler(log_file_name)
fh.setLevel(log_level)
formatter = logging.Formatter(log_format)
fh.setFormatter(formatter)
logger.addHandler(fh)
```
Is their any configurations in logging module of python to create a log on daily basis?
|
2017/06/23
|
[
"https://Stackoverflow.com/questions/44718204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6102259/"
] |
Finally, I got the correct answer and I want to share this answer.
Basically, need to create a [TimedRotatingFileHandler](https://docs.python.org/2.4/lib/node349.html) like below -
```
log_format = "%(asctime)s - %(levelname)s - %(message)s"
log_level = 10
handler = TimedRotatingFileHandler("my_app.log", when="midnight", interval=1)
handler.setLevel(log_level)
formatter = logging.Formatter(log_format)
handler.setFormatter(formatter)
# add a suffix which you want
handler.suffix = "%Y%m%d"
#need to change the extMatch variable to match the suffix for it
handler.extMatch = re.compile(r"^\d{8}$")
# finally add handler to logger
logger.addHandler(handler)
```
This above code will generate file like my\_app.log for current day and my\_app.log.20170704 for previous day.
Hope it helps.
|
I suggest you take a look at `logging.handlers.TimedRotatingFileHandler`.
I think it's what you're looking for.
|
44,718,204
|
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition.
```
log file name - my_app_20170622.log
log file entries within time - 00:00:01 to 23:59:59
```
On next day I want to create a new log file with next day's date -
```
log file name - my_app_20170623.log
log file entries within time - 00:00:01 to 23:59:59
```
I'm using logging module of python.
I'm using like below -
```
log_level = int(log_level)
logger = logging.getLogger('simple')
logger.setLevel(log_level)
fh = logging.FileHandler(log_file_name)
fh.setLevel(log_level)
formatter = logging.Formatter(log_format)
fh.setFormatter(formatter)
logger.addHandler(fh)
```
Is their any configurations in logging module of python to create a log on daily basis?
|
2017/06/23
|
[
"https://Stackoverflow.com/questions/44718204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6102259/"
] |
### [RotatingFileHandler](https://docs.python.org/2.4/lib/node348.html)
```py
class RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])
```
Returns a new instance of the `RotatingFileHandler` *class*. The specified file is opened and used as the stream for logging. If mode is not specified, `a` is used. By default, the file grows indefinitely.
A `RotatingFileHandler` allows us to rotate our log statements into a new file every time the current log file reaches a certain size.
In this example we’ll set it up so that when it reaches 500 bytes we’ll rotate into a new file up to a maximum number of 2 backups.
```py
import logging
import logging.handlers as handlers
import time
logger = logging.getLogger('my_app')
logger.setLevel(logging.INFO)
logHandler = handlers.RotatingFileHandler('app.log', maxBytes=500, backupCount=2)
logHandler.setLevel(logging.INFO)
logger.addHandler(logHandler)
def main():
while True:
time.sleep(1)
logger.info("A Sample Log Statement")
main()
```
Upon execution of this you should notice that every time `app.log` exceeds 500 bytes, it is then closed and renamed `app.log.x` where the value of `x` increments till it reaches whatever we have set `backupCount` to.
### [TimedRotatingFileHandler](https://docs.python.org/2.4/lib/node349.html)
```py
class TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
```
Returns a new instance of the `TimedRotatingFileHandler` *class*. The specified file is opened and used as the stream for logging. On rotating it also sets the filename suffix. Rotating happens based on the product of when and interval.
You can use the when to specify the type of *interval*. The list of possible values is, note that they are not case sensitive:
```sh
| Value | Type of interval |
|:--------:|:---------------------:|
| S | Seconds |
| M | Minutes |
| H | Hours |
| D | Days |
| W | Week day (0=Monday) |
| midnight | Roll over at midnight |
```
`TimedRotatingFileHandler` allows us to capture log files by a time slice.
```py
import logging
import logging.handlers as handlers
import time
logger = logging.getLogger('my_app')
logger.setLevel(logging.INFO)
logHandler = handlers.TimedRotatingFileHandler('timed_app.log', when='M', interval=1)
logHandler.setLevel(logging.INFO)
logger.addHandler(logHandler)
def main():
while True:
time.sleep(1)
logger.info("A Sample Log Statement")
main()
```
Running this code will then create new log files every minute indefinitely. We can set the `backupCount` parameter on our `logHandler` instance and it will cap the number of log files we create.
### Use of Appropriate Log Levels
With the `TimedRotatingFileHandler` and the `RotatingFileHandler` it is possible to do the following things such as log all error messages to a rotating file, but all normal log files to a TimedRotatingFileHandler as we hope that we can expect far more of them than error messages.
Two levels of records are split out two different log levels: `INFO` and `ERROR` to two distinct places.
```py
import logging
import logging.handlers as handlers
import time
logger = logging.getLogger('my_app')
logger.setLevel(logging.INFO)
## Here we define our formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logHandler = handlers.TimedRotatingFileHandler('normal.log', when='M', interval=1, backupCount=0)
logHandler.setLevel(logging.INFO)
logHandler.setFormatter(formatter)
errorLogHandler = handlers.RotatingFileHandler('error.log', maxBytes=5000, backupCount=0)
errorLogHandler.setLevel(logging.ERROR)
errorLogHandler.setFormatter(formatter)
logger.addHandler(logHandler)
logger.addHandler(errorLogHandler)
def main():
while True:
time.sleep(1)
logger.info("A Sample Log Statement")
logger.error("An error log statement")
main()
```
You should notice that 3 log files are created when you run this. The `error.log` will contain only logs that are of level `ERROR` or higher. The `normal.log` will contain a combination of all log messages logged out of our application.
*These are just a few things I feel are important when implementing your own logging system.*
|
I suggest you take a look at `logging.handlers.TimedRotatingFileHandler`.
I think it's what you're looking for.
|
44,718,204
|
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition.
```
log file name - my_app_20170622.log
log file entries within time - 00:00:01 to 23:59:59
```
On next day I want to create a new log file with next day's date -
```
log file name - my_app_20170623.log
log file entries within time - 00:00:01 to 23:59:59
```
I'm using logging module of python.
I'm using like below -
```
log_level = int(log_level)
logger = logging.getLogger('simple')
logger.setLevel(log_level)
fh = logging.FileHandler(log_file_name)
fh.setLevel(log_level)
formatter = logging.Formatter(log_format)
fh.setFormatter(formatter)
logger.addHandler(fh)
```
Is their any configurations in logging module of python to create a log on daily basis?
|
2017/06/23
|
[
"https://Stackoverflow.com/questions/44718204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6102259/"
] |
[TimedRotatingFileHandler](https://docs.python.org/3/library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler) can be used for this purpose. Please refer the below code.
```
from logging.config import dictConfig
import logging
dictConfig({
'version': 1,
'formatters': {
'standard': {
'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
}
},
'handlers': {
'myapp_handler': {
'class': 'logging.handlers.TimedRotatingFileHandler',
'filename': './my_app.log',
'when': 'd',
'interval': 1,
'backupCount': 30,
'level': 'DEBUG',
"encoding": "utf8",
'formatter': 'standard'
},
},
'loggers': {
'simple': {
'level': 'DEBUG',
'handlers': ['myapp_handler']
}
},
})
logger = logging.getLogger("simple")
logger.error("This is a test error")
```
In the above example, I have used dictConfig to configure the logger. Please refer the link: <https://docs.python.org/3/library/logging.config.html> to know the other ways of configuration.
Once the day change, the logger module creates a new file by suffixing the current file with the date.
|
I suggest you take a look at `logging.handlers.TimedRotatingFileHandler`.
I think it's what you're looking for.
|
44,718,204
|
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition.
```
log file name - my_app_20170622.log
log file entries within time - 00:00:01 to 23:59:59
```
On next day I want to create a new log file with next day's date -
```
log file name - my_app_20170623.log
log file entries within time - 00:00:01 to 23:59:59
```
I'm using logging module of python.
I'm using like below -
```
log_level = int(log_level)
logger = logging.getLogger('simple')
logger.setLevel(log_level)
fh = logging.FileHandler(log_file_name)
fh.setLevel(log_level)
formatter = logging.Formatter(log_format)
fh.setFormatter(formatter)
logger.addHandler(fh)
```
Is their any configurations in logging module of python to create a log on daily basis?
|
2017/06/23
|
[
"https://Stackoverflow.com/questions/44718204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6102259/"
] |
You have to create a `TimedRotatingFileHandler`:
```
from logging.handlers import TimedRotatingFileHandler
logname = "my_app.log"
handler = TimedRotatingFileHandler(logname, when="midnight", interval=1)
handler.suffix = "%Y%m%d"
logger.addHandler(handler)
```
This piece of code will create a `my_app.log` but the log will be moved to a new log file named `my_app.log.20170623` when the current day ends at midnight.
I hope this helps.
|
Finally, I got the correct answer and I want to share this answer.
Basically, need to create a [TimedRotatingFileHandler](https://docs.python.org/2.4/lib/node349.html) like below -
```
log_format = "%(asctime)s - %(levelname)s - %(message)s"
log_level = 10
handler = TimedRotatingFileHandler("my_app.log", when="midnight", interval=1)
handler.setLevel(log_level)
formatter = logging.Formatter(log_format)
handler.setFormatter(formatter)
# add a suffix which you want
handler.suffix = "%Y%m%d"
#need to change the extMatch variable to match the suffix for it
handler.extMatch = re.compile(r"^\d{8}$")
# finally add handler to logger
logger.addHandler(handler)
```
This above code will generate file like my\_app.log for current day and my\_app.log.20170704 for previous day.
Hope it helps.
|
44,718,204
|
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition.
```
log file name - my_app_20170622.log
log file entries within time - 00:00:01 to 23:59:59
```
On next day I want to create a new log file with next day's date -
```
log file name - my_app_20170623.log
log file entries within time - 00:00:01 to 23:59:59
```
I'm using logging module of python.
I'm using like below -
```
log_level = int(log_level)
logger = logging.getLogger('simple')
logger.setLevel(log_level)
fh = logging.FileHandler(log_file_name)
fh.setLevel(log_level)
formatter = logging.Formatter(log_format)
fh.setFormatter(formatter)
logger.addHandler(fh)
```
Is their any configurations in logging module of python to create a log on daily basis?
|
2017/06/23
|
[
"https://Stackoverflow.com/questions/44718204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6102259/"
] |
You have to create a `TimedRotatingFileHandler`:
```
from logging.handlers import TimedRotatingFileHandler
logname = "my_app.log"
handler = TimedRotatingFileHandler(logname, when="midnight", interval=1)
handler.suffix = "%Y%m%d"
logger.addHandler(handler)
```
This piece of code will create a `my_app.log` but the log will be moved to a new log file named `my_app.log.20170623` when the current day ends at midnight.
I hope this helps.
|
### [RotatingFileHandler](https://docs.python.org/2.4/lib/node348.html)
```py
class RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])
```
Returns a new instance of the `RotatingFileHandler` *class*. The specified file is opened and used as the stream for logging. If mode is not specified, `a` is used. By default, the file grows indefinitely.
A `RotatingFileHandler` allows us to rotate our log statements into a new file every time the current log file reaches a certain size.
In this example we’ll set it up so that when it reaches 500 bytes we’ll rotate into a new file up to a maximum number of 2 backups.
```py
import logging
import logging.handlers as handlers
import time
logger = logging.getLogger('my_app')
logger.setLevel(logging.INFO)
logHandler = handlers.RotatingFileHandler('app.log', maxBytes=500, backupCount=2)
logHandler.setLevel(logging.INFO)
logger.addHandler(logHandler)
def main():
while True:
time.sleep(1)
logger.info("A Sample Log Statement")
main()
```
Upon execution of this you should notice that every time `app.log` exceeds 500 bytes, it is then closed and renamed `app.log.x` where the value of `x` increments till it reaches whatever we have set `backupCount` to.
### [TimedRotatingFileHandler](https://docs.python.org/2.4/lib/node349.html)
```py
class TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
```
Returns a new instance of the `TimedRotatingFileHandler` *class*. The specified file is opened and used as the stream for logging. On rotating it also sets the filename suffix. Rotating happens based on the product of when and interval.
You can use the when to specify the type of *interval*. The list of possible values is, note that they are not case sensitive:
```sh
| Value | Type of interval |
|:--------:|:---------------------:|
| S | Seconds |
| M | Minutes |
| H | Hours |
| D | Days |
| W | Week day (0=Monday) |
| midnight | Roll over at midnight |
```
`TimedRotatingFileHandler` allows us to capture log files by a time slice.
```py
import logging
import logging.handlers as handlers
import time
logger = logging.getLogger('my_app')
logger.setLevel(logging.INFO)
logHandler = handlers.TimedRotatingFileHandler('timed_app.log', when='M', interval=1)
logHandler.setLevel(logging.INFO)
logger.addHandler(logHandler)
def main():
while True:
time.sleep(1)
logger.info("A Sample Log Statement")
main()
```
Running this code will then create new log files every minute indefinitely. We can set the `backupCount` parameter on our `logHandler` instance and it will cap the number of log files we create.
### Use of Appropriate Log Levels
With the `TimedRotatingFileHandler` and the `RotatingFileHandler` it is possible to do the following things such as log all error messages to a rotating file, but all normal log files to a TimedRotatingFileHandler as we hope that we can expect far more of them than error messages.
Two levels of records are split out two different log levels: `INFO` and `ERROR` to two distinct places.
```py
import logging
import logging.handlers as handlers
import time
logger = logging.getLogger('my_app')
logger.setLevel(logging.INFO)
## Here we define our formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logHandler = handlers.TimedRotatingFileHandler('normal.log', when='M', interval=1, backupCount=0)
logHandler.setLevel(logging.INFO)
logHandler.setFormatter(formatter)
errorLogHandler = handlers.RotatingFileHandler('error.log', maxBytes=5000, backupCount=0)
errorLogHandler.setLevel(logging.ERROR)
errorLogHandler.setFormatter(formatter)
logger.addHandler(logHandler)
logger.addHandler(errorLogHandler)
def main():
while True:
time.sleep(1)
logger.info("A Sample Log Statement")
logger.error("An error log statement")
main()
```
You should notice that 3 log files are created when you run this. The `error.log` will contain only logs that are of level `ERROR` or higher. The `normal.log` will contain a combination of all log messages logged out of our application.
*These are just a few things I feel are important when implementing your own logging system.*
|
44,718,204
|
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition.
```
log file name - my_app_20170622.log
log file entries within time - 00:00:01 to 23:59:59
```
On next day I want to create a new log file with next day's date -
```
log file name - my_app_20170623.log
log file entries within time - 00:00:01 to 23:59:59
```
I'm using logging module of python.
I'm using like below -
```
log_level = int(log_level)
logger = logging.getLogger('simple')
logger.setLevel(log_level)
fh = logging.FileHandler(log_file_name)
fh.setLevel(log_level)
formatter = logging.Formatter(log_format)
fh.setFormatter(formatter)
logger.addHandler(fh)
```
Is their any configurations in logging module of python to create a log on daily basis?
|
2017/06/23
|
[
"https://Stackoverflow.com/questions/44718204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6102259/"
] |
You have to create a `TimedRotatingFileHandler`:
```
from logging.handlers import TimedRotatingFileHandler
logname = "my_app.log"
handler = TimedRotatingFileHandler(logname, when="midnight", interval=1)
handler.suffix = "%Y%m%d"
logger.addHandler(handler)
```
This piece of code will create a `my_app.log` but the log will be moved to a new log file named `my_app.log.20170623` when the current day ends at midnight.
I hope this helps.
|
[TimedRotatingFileHandler](https://docs.python.org/3/library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler) can be used for this purpose. Please refer the below code.
```
from logging.config import dictConfig
import logging
dictConfig({
'version': 1,
'formatters': {
'standard': {
'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
}
},
'handlers': {
'myapp_handler': {
'class': 'logging.handlers.TimedRotatingFileHandler',
'filename': './my_app.log',
'when': 'd',
'interval': 1,
'backupCount': 30,
'level': 'DEBUG',
"encoding": "utf8",
'formatter': 'standard'
},
},
'loggers': {
'simple': {
'level': 'DEBUG',
'handlers': ['myapp_handler']
}
},
})
logger = logging.getLogger("simple")
logger.error("This is a test error")
```
In the above example, I have used dictConfig to configure the logger. Please refer the link: <https://docs.python.org/3/library/logging.config.html> to know the other ways of configuration.
Once the day change, the logger module creates a new file by suffixing the current file with the date.
|
44,718,204
|
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition.
```
log file name - my_app_20170622.log
log file entries within time - 00:00:01 to 23:59:59
```
On next day I want to create a new log file with next day's date -
```
log file name - my_app_20170623.log
log file entries within time - 00:00:01 to 23:59:59
```
I'm using logging module of python.
I'm using like below -
```
log_level = int(log_level)
logger = logging.getLogger('simple')
logger.setLevel(log_level)
fh = logging.FileHandler(log_file_name)
fh.setLevel(log_level)
formatter = logging.Formatter(log_format)
fh.setFormatter(formatter)
logger.addHandler(fh)
```
Is their any configurations in logging module of python to create a log on daily basis?
|
2017/06/23
|
[
"https://Stackoverflow.com/questions/44718204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6102259/"
] |
Finally, I got the correct answer and I want to share this answer.
Basically, need to create a [TimedRotatingFileHandler](https://docs.python.org/2.4/lib/node349.html) like below -
```
log_format = "%(asctime)s - %(levelname)s - %(message)s"
log_level = 10
handler = TimedRotatingFileHandler("my_app.log", when="midnight", interval=1)
handler.setLevel(log_level)
formatter = logging.Formatter(log_format)
handler.setFormatter(formatter)
# add a suffix which you want
handler.suffix = "%Y%m%d"
#need to change the extMatch variable to match the suffix for it
handler.extMatch = re.compile(r"^\d{8}$")
# finally add handler to logger
logger.addHandler(handler)
```
This above code will generate file like my\_app.log for current day and my\_app.log.20170704 for previous day.
Hope it helps.
|
[TimedRotatingFileHandler](https://docs.python.org/3/library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler) can be used for this purpose. Please refer the below code.
```
from logging.config import dictConfig
import logging
dictConfig({
'version': 1,
'formatters': {
'standard': {
'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
}
},
'handlers': {
'myapp_handler': {
'class': 'logging.handlers.TimedRotatingFileHandler',
'filename': './my_app.log',
'when': 'd',
'interval': 1,
'backupCount': 30,
'level': 'DEBUG',
"encoding": "utf8",
'formatter': 'standard'
},
},
'loggers': {
'simple': {
'level': 'DEBUG',
'handlers': ['myapp_handler']
}
},
})
logger = logging.getLogger("simple")
logger.error("This is a test error")
```
In the above example, I have used dictConfig to configure the logger. Please refer the link: <https://docs.python.org/3/library/logging.config.html> to know the other ways of configuration.
Once the day change, the logger module creates a new file by suffixing the current file with the date.
|
44,718,204
|
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition.
```
log file name - my_app_20170622.log
log file entries within time - 00:00:01 to 23:59:59
```
On next day I want to create a new log file with next day's date -
```
log file name - my_app_20170623.log
log file entries within time - 00:00:01 to 23:59:59
```
I'm using logging module of python.
I'm using like below -
```
log_level = int(log_level)
logger = logging.getLogger('simple')
logger.setLevel(log_level)
fh = logging.FileHandler(log_file_name)
fh.setLevel(log_level)
formatter = logging.Formatter(log_format)
fh.setFormatter(formatter)
logger.addHandler(fh)
```
Is their any configurations in logging module of python to create a log on daily basis?
|
2017/06/23
|
[
"https://Stackoverflow.com/questions/44718204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6102259/"
] |
### [RotatingFileHandler](https://docs.python.org/2.4/lib/node348.html)
```py
class RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])
```
Returns a new instance of the `RotatingFileHandler` *class*. The specified file is opened and used as the stream for logging. If mode is not specified, `a` is used. By default, the file grows indefinitely.
A `RotatingFileHandler` allows us to rotate our log statements into a new file every time the current log file reaches a certain size.
In this example we’ll set it up so that when it reaches 500 bytes we’ll rotate into a new file up to a maximum number of 2 backups.
```py
import logging
import logging.handlers as handlers
import time
logger = logging.getLogger('my_app')
logger.setLevel(logging.INFO)
logHandler = handlers.RotatingFileHandler('app.log', maxBytes=500, backupCount=2)
logHandler.setLevel(logging.INFO)
logger.addHandler(logHandler)
def main():
while True:
time.sleep(1)
logger.info("A Sample Log Statement")
main()
```
Upon execution of this you should notice that every time `app.log` exceeds 500 bytes, it is then closed and renamed `app.log.x` where the value of `x` increments till it reaches whatever we have set `backupCount` to.
### [TimedRotatingFileHandler](https://docs.python.org/2.4/lib/node349.html)
```py
class TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
```
Returns a new instance of the `TimedRotatingFileHandler` *class*. The specified file is opened and used as the stream for logging. On rotating it also sets the filename suffix. Rotating happens based on the product of when and interval.
You can use the when to specify the type of *interval*. The list of possible values is, note that they are not case sensitive:
```sh
| Value | Type of interval |
|:--------:|:---------------------:|
| S | Seconds |
| M | Minutes |
| H | Hours |
| D | Days |
| W | Week day (0=Monday) |
| midnight | Roll over at midnight |
```
`TimedRotatingFileHandler` allows us to capture log files by a time slice.
```py
import logging
import logging.handlers as handlers
import time
logger = logging.getLogger('my_app')
logger.setLevel(logging.INFO)
logHandler = handlers.TimedRotatingFileHandler('timed_app.log', when='M', interval=1)
logHandler.setLevel(logging.INFO)
logger.addHandler(logHandler)
def main():
while True:
time.sleep(1)
logger.info("A Sample Log Statement")
main()
```
Running this code will then create new log files every minute indefinitely. We can set the `backupCount` parameter on our `logHandler` instance and it will cap the number of log files we create.
### Use of Appropriate Log Levels
With the `TimedRotatingFileHandler` and the `RotatingFileHandler` it is possible to do the following things such as log all error messages to a rotating file, but all normal log files to a TimedRotatingFileHandler as we hope that we can expect far more of them than error messages.
Two levels of records are split out two different log levels: `INFO` and `ERROR` to two distinct places.
```py
import logging
import logging.handlers as handlers
import time
logger = logging.getLogger('my_app')
logger.setLevel(logging.INFO)
## Here we define our formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logHandler = handlers.TimedRotatingFileHandler('normal.log', when='M', interval=1, backupCount=0)
logHandler.setLevel(logging.INFO)
logHandler.setFormatter(formatter)
errorLogHandler = handlers.RotatingFileHandler('error.log', maxBytes=5000, backupCount=0)
errorLogHandler.setLevel(logging.ERROR)
errorLogHandler.setFormatter(formatter)
logger.addHandler(logHandler)
logger.addHandler(errorLogHandler)
def main():
while True:
time.sleep(1)
logger.info("A Sample Log Statement")
logger.error("An error log statement")
main()
```
You should notice that 3 log files are created when you run this. The `error.log` will contain only logs that are of level `ERROR` or higher. The `normal.log` will contain a combination of all log messages logged out of our application.
*These are just a few things I feel are important when implementing your own logging system.*
|
[TimedRotatingFileHandler](https://docs.python.org/3/library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler) can be used for this purpose. Please refer the below code.
```
from logging.config import dictConfig
import logging
dictConfig({
'version': 1,
'formatters': {
'standard': {
'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
}
},
'handlers': {
'myapp_handler': {
'class': 'logging.handlers.TimedRotatingFileHandler',
'filename': './my_app.log',
'when': 'd',
'interval': 1,
'backupCount': 30,
'level': 'DEBUG',
"encoding": "utf8",
'formatter': 'standard'
},
},
'loggers': {
'simple': {
'level': 'DEBUG',
'handlers': ['myapp_handler']
}
},
})
logger = logging.getLogger("simple")
logger.error("This is a test error")
```
In the above example, I have used dictConfig to configure the logger. Please refer the link: <https://docs.python.org/3/library/logging.config.html> to know the other ways of configuration.
Once the day change, the logger module creates a new file by suffixing the current file with the date.
|
60,949,588
|
I have a python script that does some GUI test on a chromium application. Sometimes this application does not load up correctly and for this reason the GUI test will not pass, but a simple restart of this application can fix the problem.
What I currently have is something like this:
```
def test():
...do some settings...
...SystemOperator.restartController()...
...Login(My.PinCode)...
...GoToDeviceUI()...
...undo settings...
...SystemOperator.restartController()...
```
When doing this login, in case the app did not load correctly an exception is thrown and my test is failing.
What I want to do is something like this:
```
def test():
def testBody():
...do some settings...
...SystemOperator.restartController()...
...Login(My.PinCode)...
...GoToDeviceUI()...
...undo settings...
...SystemOperator.restartController()...
try_cnt = 3
for i in range(try_cnt):
try:
testBody()
break
except:
...SystemOperator.restartController()...
```
But without using a for/while loop.
Thank you!
|
2020/03/31
|
[
"https://Stackoverflow.com/questions/60949588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12200507/"
] |
In OpenCV, the given threshold options (e.g. cv.THRESH\_BINARY or cv.THRESH\_BINARY\_INV) are actually constant integer values. You are trying to use strings instead of these integer values. That is the reason why you get the Type Error. If you want to apply all these different thresholds in a loop, one option is to create a different list for these options, like this:
```py
threshold_options = [cv.THRESH_BINARY, cv.THRESH_BINARY_INV, ...]
```
That way, you can then use the values of this list in the loop as follows:
```py
retval, thresh = cv.threshold(img, 127, 255, threshold_options[i])
```
The entire code would be as follows:
```py
titles = [ 'THRESH_BINARY',
'THRESH_BINARY_INV',
'THRESH_MASK',
'THRESH_OTSU',
'THRESH_TOZERO',
'THRESH_TOZERO_INV',
'THRESH_TRIANGLE',
'THRESH_TRUNC']
threshold_options = [ cv.THRESH_BINARY,
cv.THRESH_BINARY_INV,
cv.THRESH_MASK,
cv.THRESH_OTSU,
cv.THRESH_TOZERO,
cv.THRESH_TOZERO_INV,
cv.THRESH_TRIANGLE,
cv.THRESH_TRUNC]
for i in range(len(titles)):
retval, thresh = cv.threshold(img, 127, 255, threshold_options[i])
plt.subplot(2,3,i+1), plt.title(titles[i]), plt.imshow(thresh, 'gray')
plt.show()
```
|
This might be related: [OpenCV Thresholding example](https://docs.opencv.org/master/d7/d4d/tutorial_py_thresholding.html)
First off, there is no need to use `range`, you can simply do `for flag in titles:` and pass `flag`. Have you checked if your image is loaded correctly? Are you sure that your flag is repsonsible for your error?
For future posts, please include a minimal reproducible example.
|
60,949,588
|
I have a python script that does some GUI test on a chromium application. Sometimes this application does not load up correctly and for this reason the GUI test will not pass, but a simple restart of this application can fix the problem.
What I currently have is something like this:
```
def test():
...do some settings...
...SystemOperator.restartController()...
...Login(My.PinCode)...
...GoToDeviceUI()...
...undo settings...
...SystemOperator.restartController()...
```
When doing this login, in case the app did not load correctly an exception is thrown and my test is failing.
What I want to do is something like this:
```
def test():
def testBody():
...do some settings...
...SystemOperator.restartController()...
...Login(My.PinCode)...
...GoToDeviceUI()...
...undo settings...
...SystemOperator.restartController()...
try_cnt = 3
for i in range(try_cnt):
try:
testBody()
break
except:
...SystemOperator.restartController()...
```
But without using a for/while loop.
Thank you!
|
2020/03/31
|
[
"https://Stackoverflow.com/questions/60949588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12200507/"
] |
In OpenCV, the given threshold options (e.g. cv.THRESH\_BINARY or cv.THRESH\_BINARY\_INV) are actually constant integer values. You are trying to use strings instead of these integer values. That is the reason why you get the Type Error. If you want to apply all these different thresholds in a loop, one option is to create a different list for these options, like this:
```py
threshold_options = [cv.THRESH_BINARY, cv.THRESH_BINARY_INV, ...]
```
That way, you can then use the values of this list in the loop as follows:
```py
retval, thresh = cv.threshold(img, 127, 255, threshold_options[i])
```
The entire code would be as follows:
```py
titles = [ 'THRESH_BINARY',
'THRESH_BINARY_INV',
'THRESH_MASK',
'THRESH_OTSU',
'THRESH_TOZERO',
'THRESH_TOZERO_INV',
'THRESH_TRIANGLE',
'THRESH_TRUNC']
threshold_options = [ cv.THRESH_BINARY,
cv.THRESH_BINARY_INV,
cv.THRESH_MASK,
cv.THRESH_OTSU,
cv.THRESH_TOZERO,
cv.THRESH_TOZERO_INV,
cv.THRESH_TRIANGLE,
cv.THRESH_TRUNC]
for i in range(len(titles)):
retval, thresh = cv.threshold(img, 127, 255, threshold_options[i])
plt.subplot(2,3,i+1), plt.title(titles[i]), plt.imshow(thresh, 'gray')
plt.show()
```
|
You code is not working because the type of the flags is `int` and not `string`.
You can print the type: `print(type(cv.THRESH_BINARY))`.
The result is `<class 'int'>`.
You may create a list of `int`s:
```
th_flags = [cv.THRESH_BINARY, cv.THRESH_BINARY_INV, cv.THRESH_TRUNC, cv.THRESH_TOZERO, cv.THRESH_TOZERO_INV]
for th in th_flags:
retval, thresh = cv.threshold(img, 127, 255, th)
cv.imshow('thresh', thresh)
cv.waitKey(1000)
cv.destroyAllWindows()
```
**The code doesn't cover all the possible options**.
Few flags can be combined using summation.
Example:
```
_, thresh = cv.threshold(img, 127, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
```
|
29,959,550
|
I'm trying to fetch forms for floorplans for individual property's. I can check that the object exists in the database, but when I try to create a form with an instance of it I receive this error:
```
Traceback:
File "/Users/balrog911/Desktop/mvp/mvp_1/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
130. % (callback.__module__, view_name))
Exception Type: ValueError at /dashboard-property/253/
Exception Value: The view properties.views.dashboard_single_property didn't return an HttpResponse object. It returned None instead.
```
My models.py:
```
class Property(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name='user')
name = models.CharField(max_length=120, help_text="This is the name that will display on your profile")
image = models.ImageField(upload_to='properties/', null=True, blank=True)
options=(('House', 'House'),('Condo','Condo'),('Apartment','Apartment'))
rental_type = models.CharField(max_length=120, blank=True, null=True, choices=options, default='Apartment')
address = models.CharField(max_length=120)
phone_number = models.CharField(max_length=120, blank=True, null=True)
email = models.EmailField(max_length=120, blank=True, null=True)
website = models.CharField(max_length=250, blank=True, null=True)
description = models.CharField(max_length=500, blank=True, null=True)
lat = models.CharField(max_length=120, blank=True, null=True)
lng = models.CharField(max_length=120, blank=True, null=True)
coordinates =models.CharField(max_length=120, blank=True, null=True)
slug = models.SlugField(unique=True, max_length=501)
active = models.BooleanField(default= True)
date_added = models.DateTimeField(auto_now_add=True)
def save(self):
super(Property, self).save()
max_length = Property._meta.get_field('slug').max_length
slug_name = slugify(self.name)
self.slug = '%s-%d' % (slug_name, self.id)
self.coordinates = geo_lat_lng(self.address)
self.lat = self.coordinates[0]
self.lng = self.coordinates[1]
super(Property, self).save()
def __unicode__(self):
return '%s-%s-%s' % (self.id, self.name, self.address)
def get_absolute_url(self):
return reverse("single_property", kwargs={"slug": self.slug})
def get_dashboard_url(self):
return reverse("dashboard_single_property", kwargs={"id": self.id})
class FloorPlan(models.Model):
property_name = models.ForeignKey(Property, related_name='property_name')
floor_plan_name = models.CharField(max_length=120, blank=True, null=True)
numbers = (('0','0'),('1','1'),('2','2'),('3','3'),('4','4'),('5','5'),('6+','6+'),)
bedrooms = models.CharField(max_length=120, blank=True, null=True, choices=numbers)
bathrooms = models.CharField(max_length=120, blank=True, null=True, choices=numbers)
sqft = models.IntegerField(max_length=120, blank=True, null=True)
min_price = models.IntegerField(max_length=120, blank=True, null=True)
max_price = models.IntegerField(max_length=120, blank=True, null=True)
availability = models.DateField(null=True, blank=True, help_text='Use mm/dd/yyyy format')
image = models.ImageField(upload_to='floor_plans/', null=True, blank=True)
def __unicode__(self):
return '%s' % (self.property_name)
```
My views.py:
```
def dashboard_single_property(request, id):
if request.user.is_authenticated():
user = request.user
try:
single_property = Property.objects.get(id=id)
user_properties = Property.objects.filter(user=user)
if single_property in user_properties:
user_property = Property.objects.get(id=id)
#Beginning of Pet Policy Instances
user_floor_plan = FloorPlan.objects.select_related('Property').filter(property_name=user_property)
if user_floor_plan:
print user_floor_plan
plans = user_floor_plan.count()
plans = plans + 1
FloorPlanFormset = inlineformset_factory(Property, FloorPlan, extra=plans)
formset_floor_plan = FloorPlanFormset(instance=user_floor_plan)
print "formset_floor_plan is True"
else:
floor_plan_form = FloorPlanForm(request.POST or None)
formset_floor_plan = False
print 'formset is %s' % (formset_floor_plan)
#End
#Beginning of Pet Policy Instances
user_pet_policy = PetPolicy.objects.select_related('Property').filter(property_name=user_property)
print user_pet_policy
if user_pet_policy:
print user_pet_policy
#pet_policy_form = PetPolicyForm(request.POST or None, instance=user_pet_policy)
pet_policy_form = PetPolicyForm(request.POST or None)
else:
pet_policy_form = PetPolicyForm(request.POST or None)
#End
basic_form = PropertyForm(request.POST or None, instance=user_property)
context = {
'user_property': user_property,
'basic_form': basic_form,
'floor_plan_form': floor_plan_form,
'formset_floor_plan': formset_floor_plan,
'pet_policy_form': pet_policy_form,
}
template = 'dashboard/dashboard_single_property.html'
return render(request, template, context)
else:
return HttpResponseRedirect(reverse('dashboard'))
except Exception as e:
raise e
#raise Http404
print "whoops"
else:
return HttpResponseRedirect(reverse('dashboard'))
```
**EDIT:** Took Vishen's tip to make sure the error was raised, updated the views and now I'm getting this error. Here's the full traceback:
```
Environment:
Request Method: GET
Request URL: http://localhost:8080/dashboard-property/253/
Django Version: 1.7.4
Python Version: 2.7.5
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.sites',
'django.contrib.sitemaps',
'django.contrib.staticfiles',
'base',
'properties',
'renters',
'allauth',
'allauth.account',
'crispy_forms',
'datetimewidget',
'djrill',
'import_export',
'multiselectfield')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.locale.LocaleMiddleware')
Traceback:
File "/Users/balrog911/Desktop/mvp/mvp_1/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/balrog911/Desktop/mvp/mvp_1_live/src/properties/views.py" in dashboard_single_property
82. raise e
Exception Type: AttributeError at /dashboard-property/253/
Exception Value: 'QuerySet' object has no attribute 'pk'
```
**EDIT:**
Per Vishen's suggestion, removed the try statement to see if the error would be made more clear. It looks like the issues is with line 51:
```
formset_floor_plan = FloorPlanFormset(instance=user_floor_plan)
```
Here's the traceback:
```
Traceback:
File "/Users/balrog911/Desktop/mvp/mvp_1/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/balrog911/Desktop/mvp/mvp_1_live/src/properties/views.py" in dashboard_single_property
51. formset_floor_plan = FloorPlanFormset(instance=user_floor_plan)
File "/Users/balrog911/Desktop/mvp/mvp_1/lib/python2.7/site-packages/django/forms/models.py" in __init__
855. if self.instance.pk is not None:
Exception Type: AttributeError at /dashboard-property/253/
Exception Value: 'QuerySet' object has no attribute 'pk'
```
|
2015/04/30
|
[
"https://Stackoverflow.com/questions/29959550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4847831/"
] |
```
NSString *n = [NSString stringWithFormat:@"%@",@"http://somedomain.com/api/x?q={\"order_by\":[{\"field\":\"t\",\"direction\":\"desc\"}]}"];
NSURL *url = [NSURL URLWithString:[n stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"%@",url);
```
|
The proper way to compose a URL from strings is to use [NSURLComponents](https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLComponents_class/index.html) helper class.
The reason for this seemingly elaborate approach is that each component of a URL (see [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3)) requires slightly different percent encodings or possibly none.
The exact structure of the *query* component is not defined in RFC 3986, though. Usually, its an array of key/value pairs that will be escaped as described at w3.org: [x-www-form-urlencoded-encoding-algorithm](http://www.w3.org/TR/html5/forms.html#application/x-www-form-urlencoded-encoding-algorithm). `NSURLComponents` provides a method to encode the query component as well.
|
58,472,090
|
I am trying to load a pickle object in R, using the following process found online.
First, I create a Python file called: "pickle\_reader.py":
```py
import pandas as pd
def read_pickle_file(file):
pickle_data = pd.read_pickle(file)
return pickle_data
```
Then, I run the following R code:
```
install.packages('reticulate')
require("reticulate")
source_python("pickle_reader.py")
pickle_data <- read_pickle_file("pathname")
```
but I get an error that says:
>
> Error in py\_run\_file\_impl(file, local, convert) :
> ImportError: No module named pandas
>
>
>
N.B. I tried installing pandas again but this doesn't change the issue.
Do you know how should I proceed?
Thank you in advance
|
2019/10/20
|
[
"https://Stackoverflow.com/questions/58472090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11898786/"
] |
If you want to insert a python package into a different environment, which in this case is R, you must search how to install python packages in R. In this case, looking at the [CRAN webpage](https://cran.r-project.org/web/packages/reticulate/vignettes/python_packages.html) you can see that in order to install pandas in the environment of R you need the command *py\_install('pandas')*.
Hope it helps!
|
Make sure that pandas installed. I suggest using conda environment. I read the pickle applying below steps:
* Create conda environment and install necessary packages.
* Then in R, you can set the right python (which is python in your conda env)
```
Sys.setenv(RETICULATE_PYTHON = "~/anaconda3/envs/your_env/bin/python")
library(reticulate)
```
You can check with `py_config()`
* Now you can read your pickle files in R,
```
loadData = function(file_path){
require("reticulate")
source_python("pickle_reader.py")
pd <- import("pandas")
return (pd$read_pickle(file_path))
}
features = loadData(features_path)
```
|
58,472,090
|
I am trying to load a pickle object in R, using the following process found online.
First, I create a Python file called: "pickle\_reader.py":
```py
import pandas as pd
def read_pickle_file(file):
pickle_data = pd.read_pickle(file)
return pickle_data
```
Then, I run the following R code:
```
install.packages('reticulate')
require("reticulate")
source_python("pickle_reader.py")
pickle_data <- read_pickle_file("pathname")
```
but I get an error that says:
>
> Error in py\_run\_file\_impl(file, local, convert) :
> ImportError: No module named pandas
>
>
>
N.B. I tried installing pandas again but this doesn't change the issue.
Do you know how should I proceed?
Thank you in advance
|
2019/10/20
|
[
"https://Stackoverflow.com/questions/58472090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11898786/"
] |
I find this to be a much more straight forward method than making a new `.py` file. In an R code chunk do:
```
library(reticulate)
pd <- import("pandas")
x <- pd$read_pickle("file.pickle")
```
|
If you want to insert a python package into a different environment, which in this case is R, you must search how to install python packages in R. In this case, looking at the [CRAN webpage](https://cran.r-project.org/web/packages/reticulate/vignettes/python_packages.html) you can see that in order to install pandas in the environment of R you need the command *py\_install('pandas')*.
Hope it helps!
|
58,472,090
|
I am trying to load a pickle object in R, using the following process found online.
First, I create a Python file called: "pickle\_reader.py":
```py
import pandas as pd
def read_pickle_file(file):
pickle_data = pd.read_pickle(file)
return pickle_data
```
Then, I run the following R code:
```
install.packages('reticulate')
require("reticulate")
source_python("pickle_reader.py")
pickle_data <- read_pickle_file("pathname")
```
but I get an error that says:
>
> Error in py\_run\_file\_impl(file, local, convert) :
> ImportError: No module named pandas
>
>
>
N.B. I tried installing pandas again but this doesn't change the issue.
Do you know how should I proceed?
Thank you in advance
|
2019/10/20
|
[
"https://Stackoverflow.com/questions/58472090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11898786/"
] |
I find this to be a much more straight forward method than making a new `.py` file. In an R code chunk do:
```
library(reticulate)
pd <- import("pandas")
x <- pd$read_pickle("file.pickle")
```
|
Make sure that pandas installed. I suggest using conda environment. I read the pickle applying below steps:
* Create conda environment and install necessary packages.
* Then in R, you can set the right python (which is python in your conda env)
```
Sys.setenv(RETICULATE_PYTHON = "~/anaconda3/envs/your_env/bin/python")
library(reticulate)
```
You can check with `py_config()`
* Now you can read your pickle files in R,
```
loadData = function(file_path){
require("reticulate")
source_python("pickle_reader.py")
pd <- import("pandas")
return (pd$read_pickle(file_path))
}
features = loadData(features_path)
```
|
19,427,685
|
i have problems with the array indexes in python.
at function readfile it crashes and prints: **"list index out of range"**
```
inputarr = []
def readfile(filename):
lines = readlines(filename)
with open(filename, 'r') as f:
i = 0
j= 0
k = 0
for line in f:
line = line.rstrip("\n")
if not line == '':
inputarr[j][k] = line
k += 1
#print("\tnew entry\tj=%d\tk=%d" % (j, k))
elif line == '':
k = 0
j += 1
#print("new block!\tj=%d\tk=%d" % (j, k))
i += 1
processing(i, lines)
```
|
2013/10/17
|
[
"https://Stackoverflow.com/questions/19427685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2890530/"
] |
I added the javafx runtime separately to the pom as below and it worked:
```
<dependency>
<groupId>javafx</groupId>
<artifactId>jfxrt</artifactId>
<version>${javafx.min.version}</version>
<scope>system</scope>
<systemPath>${java.home}\lib\jfxrt.jar</systemPath>
</dependency>
```
|
From [*What is JavaFX?*](http://docs.oracle.com/javafx/2/overview/jfxpub-overview.htm#A1095238):
>
> JavaFX 2.2 and later releases are fully integrated with the Java SE 7 Runtime Environment (JRE) and the Java Development Kit (JDK).
>
>
>
This means you should be able to just use the `javafx.*` packages without adding any library besides the JDK. It seems that Eclipse and Maven are being stupid in your case. (The JavaFX library and a bunch of others are in `$JDK_HOME/jre/lib/*`, Eclipse only seems to add what's in `$JDK_HOME/lib`. IntelliJ IDEA does the right thing here.)
|
19,427,685
|
i have problems with the array indexes in python.
at function readfile it crashes and prints: **"list index out of range"**
```
inputarr = []
def readfile(filename):
lines = readlines(filename)
with open(filename, 'r') as f:
i = 0
j= 0
k = 0
for line in f:
line = line.rstrip("\n")
if not line == '':
inputarr[j][k] = line
k += 1
#print("\tnew entry\tj=%d\tk=%d" % (j, k))
elif line == '':
k = 0
j += 1
#print("new block!\tj=%d\tk=%d" % (j, k))
i += 1
processing(i, lines)
```
|
2013/10/17
|
[
"https://Stackoverflow.com/questions/19427685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2890530/"
] |
I added the javafx runtime separately to the pom as below and it worked:
```
<dependency>
<groupId>javafx</groupId>
<artifactId>jfxrt</artifactId>
<version>${javafx.min.version}</version>
<scope>system</scope>
<systemPath>${java.home}\lib\jfxrt.jar</systemPath>
</dependency>
```
|
JavaFX in Java7 is not on any classpath - you need to adjust your project classpath or use a tool like e(fx)clipse which manages that for you.
In Java8 it is on the extension classpath!
|
53,961,912
|
Using django and python, I am building a web app that tracks prices. The user is a manufacturer and will want reports. Each of their products has a recommended price. Each product could have more than one seller, and each seller could have more than one product. My question is, where do I store the prices, especially the seller's price? Right now I have my database schema so the product table stores the recommended price and the seller's price, and that means one single product is repeated a lot of times. Is there a better way to do this?
[](https://i.stack.imgur.com/HJPmc.jpg)
Per the recommendations below this is the correct db schema:
[](https://i.stack.imgur.com/xCs6J.jpg)
|
2018/12/28
|
[
"https://Stackoverflow.com/questions/53961912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5096832/"
] |
You're not adequately representing the one-to-many relationship between products and sellers. Your product table has the seller\_id and the seller\_price, but if one product is sold by many sellers, it cannot.
Instead of duplicating product entries so the same product can have multiple sellers, what you need is a table between products and sellers.
```
CREATE TABLE seller_products (
seller_id integer,
product_id integer,
price decimal
);
```
I'll leave the indexes foreign keys etc to you. Seller ID and product ID might be a unique combination ( historical data is best removed from active datasets for performance longevity ) , but of course any given product will be listed once for each seller that sells it and any given seller will be listed once per product it sells ( along with its unique price).
Then you can join the table back to products to get the data you currently store denormalized in the `products` table directly :
```
SELECT *
FROM products
LEFT JOIN seller_products ON ( seller_products.product_id = products.id)
```
|
This is a Data Warehouse question.
I would recommend putting prices on a Fact as measures and having only attributes on the Dimensions.
Dimensions:
* Product
* Seller
* Manufacturer
Fact (Columns):
* List item
* Seller Price
* List item
* MRSP
* Product ID
* Seller ID
* Manufacturer ID
* Timestamp
|
53,961,912
|
Using django and python, I am building a web app that tracks prices. The user is a manufacturer and will want reports. Each of their products has a recommended price. Each product could have more than one seller, and each seller could have more than one product. My question is, where do I store the prices, especially the seller's price? Right now I have my database schema so the product table stores the recommended price and the seller's price, and that means one single product is repeated a lot of times. Is there a better way to do this?
[](https://i.stack.imgur.com/HJPmc.jpg)
Per the recommendations below this is the correct db schema:
[](https://i.stack.imgur.com/xCs6J.jpg)
|
2018/12/28
|
[
"https://Stackoverflow.com/questions/53961912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5096832/"
] |
Since you have a case of many-to-many then your structure would use a link table. You’ll have tables `seller`, `product` and `link_seller_product`. The last table has a link to the `seller` table via id as well as the `product` table via id. This table therefore can also have any information that is dependent on the seller and the product and is not fixed for either. So price-per-product-per-seller goes there.
So add the additional link table with columns `sellerid`, `productid` and `price` and you’ll have only single rows in sellers and products but each seller can have their own price for the product.
|
You're not adequately representing the one-to-many relationship between products and sellers. Your product table has the seller\_id and the seller\_price, but if one product is sold by many sellers, it cannot.
Instead of duplicating product entries so the same product can have multiple sellers, what you need is a table between products and sellers.
```
CREATE TABLE seller_products (
seller_id integer,
product_id integer,
price decimal
);
```
I'll leave the indexes foreign keys etc to you. Seller ID and product ID might be a unique combination ( historical data is best removed from active datasets for performance longevity ) , but of course any given product will be listed once for each seller that sells it and any given seller will be listed once per product it sells ( along with its unique price).
Then you can join the table back to products to get the data you currently store denormalized in the `products` table directly :
```
SELECT *
FROM products
LEFT JOIN seller_products ON ( seller_products.product_id = products.id)
```
|
53,961,912
|
Using django and python, I am building a web app that tracks prices. The user is a manufacturer and will want reports. Each of their products has a recommended price. Each product could have more than one seller, and each seller could have more than one product. My question is, where do I store the prices, especially the seller's price? Right now I have my database schema so the product table stores the recommended price and the seller's price, and that means one single product is repeated a lot of times. Is there a better way to do this?
[](https://i.stack.imgur.com/HJPmc.jpg)
Per the recommendations below this is the correct db schema:
[](https://i.stack.imgur.com/xCs6J.jpg)
|
2018/12/28
|
[
"https://Stackoverflow.com/questions/53961912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5096832/"
] |
Since you have a case of many-to-many then your structure would use a link table. You’ll have tables `seller`, `product` and `link_seller_product`. The last table has a link to the `seller` table via id as well as the `product` table via id. This table therefore can also have any information that is dependent on the seller and the product and is not fixed for either. So price-per-product-per-seller goes there.
So add the additional link table with columns `sellerid`, `productid` and `price` and you’ll have only single rows in sellers and products but each seller can have their own price for the product.
|
This is a Data Warehouse question.
I would recommend putting prices on a Fact as measures and having only attributes on the Dimensions.
Dimensions:
* Product
* Seller
* Manufacturer
Fact (Columns):
* List item
* Seller Price
* List item
* MRSP
* Product ID
* Seller ID
* Manufacturer ID
* Timestamp
|
8,584,377
|
G'Day,
I have a number of Django projects and a number of other Python projects as git repositories. I have pre-commit hook that runs Pylint on my code before allowing me to commit it - this hook doesn't know whether the project is a Django application or a vanilla Python project.
For all my Django projects, I have a structure like:
```
> my_django_project
|-- manage.py
|-- settings.py
|--> apps
|--> my_django_app
|-- models.py
|-- admin.py
```
Now, when I run pylint on this project, it gives me errors like:
```
F: 4,0: Unable to import 'my_django_app.models'
```
for `my_django_app.admin` module for example.
How to do I configure Pylint, so that when it is going over my django projects (not vanilla python projects), it knows that the `my_django_project/apps` should also be in the `sys.path`? Normally, `manage.py` adds it to the `sys.path`.
Thanks!
|
2011/12/21
|
[
"https://Stackoverflow.com/questions/8584377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47825/"
] |
Take a look at init\_hook in pylint configuration file.
```
init-hook=import sys; sys.path.insert(0, 'my_django_project/apps');
```
You will obviously need a configuration file per Django application, and run pylint as, e.g.
```
pylint --rcfile=pylint.conf my_django_project
```
|
Maybe this doesn't fully answer your question, but I suggest to use [django-lint](http://chris-lamb.co.uk/projects/django-lint/), to avoid warnings like:
```
F: 4: Unable to import 'myapp.views'
E: 15: MyClass.my_function: Class 'MyClass' has no 'objects' member
E: 77: MyClass.__unicode__: Instance of 'MyClass' has no 'id' member
```
|
8,584,377
|
G'Day,
I have a number of Django projects and a number of other Python projects as git repositories. I have pre-commit hook that runs Pylint on my code before allowing me to commit it - this hook doesn't know whether the project is a Django application or a vanilla Python project.
For all my Django projects, I have a structure like:
```
> my_django_project
|-- manage.py
|-- settings.py
|--> apps
|--> my_django_app
|-- models.py
|-- admin.py
```
Now, when I run pylint on this project, it gives me errors like:
```
F: 4,0: Unable to import 'my_django_app.models'
```
for `my_django_app.admin` module for example.
How to do I configure Pylint, so that when it is going over my django projects (not vanilla python projects), it knows that the `my_django_project/apps` should also be in the `sys.path`? Normally, `manage.py` adds it to the `sys.path`.
Thanks!
|
2011/12/21
|
[
"https://Stackoverflow.com/questions/8584377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47825/"
] |
Take a look at init\_hook in pylint configuration file.
```
init-hook=import sys; sys.path.insert(0, 'my_django_project/apps');
```
You will obviously need a configuration file per Django application, and run pylint as, e.g.
```
pylint --rcfile=pylint.conf my_django_project
```
|
Adding to Koterpillar's great answer, you can also configure your pre-commit hook to change the current directory to `my_django_project` and run pylint from there.
|
61,986,195
|
I have this python code that predicts the trade calls with the Bollinger band values and the Close Price.
```html
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
lr1 = LogisticRegression()
x = df[['Lower_Band','Upper_Band','MA_14','Close Price']]
y = df['Call']
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3)
lr1.fit(x_train,y_train)
y_pred = lr1.predict(x_test)
print("Accuracy=",accuracy_score(y_test,y_pred,normalize=True))
```
Each time I run this code, different accuracy values are printed. The accuracy values range everything from 0.3 to 0.8. So how do I predict the accuracy of this model? Is there something wrong in my code?
|
2020/05/24
|
[
"https://Stackoverflow.com/questions/61986195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9471113/"
] |
As described by KolaB, you should use the `random_state` parameter of `train_test_split` to make results reproducible. But actually, you mentioned that your results vary between 0.3 and 0.8 in accuracy score. This is a strong indicator that your results depend on a particular random choice for the test set. I would, therefore, suggest to use k-fold cross-validation as a countermeasure.
```
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
lr1 = LogisticRegression()
x = df[['Lower_Band','Upper_Band','MA_14','Close Price']]
y = df['Call']
print(f'Accuracy = {mean(cross_val_score(lr1, x, y, cv=5))}')
```
The example returns an array for 5 train/test iterations so that each sample was used in the test set once. By getting the average of these 5 runs, you get a better estimate of your model's performance.
|
Your problem is most probably in `train_test_split`. You are not initialising the random state that ensures you get reproducible results. Try changing the line with this function to:
```
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3, random_state=1)
```
Also see scikit learn documentation on the [train\_test\_split function](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html)
|
26,450,336
|
I have this python code. And whenever i start the webbserver and go to the website i don't get the message " test ", just internal server error. How come? what am i doing wrong. Whenever i go to the website its a GET request right, so it should go into domain() function and give me the text " test "
```
@app.route("/", methods=['GET', 'POST'])
def hello():
if request.method == 'GET':
domain()
else:
test()
def domain():
return "test"
def test():
data = request.get_json()
with open("text.txt", "w") as text_file:
pickle.dump(data, text_file)
if __name__ == "__main__":
app.run()
```
|
2014/10/19
|
[
"https://Stackoverflow.com/questions/26450336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4153021/"
] |
I am also new to Android Reversing , and I have spent some time searching for simple understanding of Smali code and found this :
note class structure is L;
==========================
```
Lcom/breakapp/dd/mymod/Processor;->l:I
```
original java file name
=======================
```
.source "example.java"
```
these are class instance variables
==================================
```
.field private someString:Ljava/lang/String;
```
This assigns a string value to v0
=================================
```
const-string v0, "get_value_one"
```
*Finals are not actually used directly, because references to them are replaced by the value itself primitive cheat sheet:*
V - void, B - byte, S - short, C - char, I - int
================================================
J - long (uses two registers), F - float, D - double
====================================================
```
.field public final someInt:I # the :I means integer
.field public final someBool:Z # the :Z means boolean
```
Taken From : [Android Cracking](http://androidcracking.blogspot.in/2010/09/examplesmali.html) !
|
You may want to read the dalvik bytecode doc's since they are more detailed then the documentation you can find about smali.
Anyway, I am also in the process of learning smali so, probably, I can't give you the best answer but maybe this will help.
Let's start by looking at what iput does:
>
> iput vx,vy, field\_id
> Puts vx into an instance field. The instance is referenced by vy.
>
>
> source: <http://pallergabor.uw.hu/androidblog/dalvik_opcodes.html> from the dalvik opcodes
>
>
>
The same happens here. You are affecting the v2 register with the v0 register. That being said the change you made was misguided. You changed the 'I' to '10' but that is not a value. The I means integer in this case. Furthermore, this is not even the place where you want to make a change in your code. Let's see:
```
const-string v0, "get_value_one"
```
the reg v0 now has the value of the string "get\_value\_one" (value may not be the best word to describe it since it is a string but I think i get my point across)
```
invoke-virtual {p0, v0}, Lorg/json/JSONObject;->getInt(Ljava/lang/String;)I
move-result v0
```
now you invoked the method getInt(String) on the JSONObject that you receive via parameter. You know this since the {p0, v0} means that you are passing v0 to the method of the object referenced by p0 which you know is a parameter since it follows the p\* rule. (You can read about it here: <https://code.google.com/p/smali/wiki/Registers>).
By now you must be starting to understand that invoking this method won't help if you want to assing a cont value to your variable 'l'.
```
iput v0, v2, Lcom/breakapp/dd/mymod/Processor;->l:I
```
This last instruction takes your v2 register and puts the value of v0 in it. v0, before this line is executed, has the value that comes out of the JSONObject getInt(String) method while v2 references the Object MyProcessor and the "Lcom/breakapp/dd/mymod/Processor;->l" references the variable 'l' contained in that said obj. The ' :I ' let's you know the type of the variable. Since Java is strongly typed there is always an associated type to a variable as I'm sure you know. This has, of course, to be referenced in the bytecode and this is the way it's done.
I hope this gave some information to be able to do the changes you want but I'll try to help out a little more by suggesting that you change the code you showed to something like this:
```
const/4 v0, 0xA
iput v0, v2, Lcom/breakapp/dd/mymod/Processor;->l:I
```
The first line assings a constant (0xA hexa = 10 decimal) to v0 and then passes it as I referenced before.
Good luck with learning smali and I hope it helped at least a little
|
61,442,421
|
I am using the combination of **request** and **beautifulsoup** to develop a web-scraping program in python.
Unfortunately, I got 403 problem (even using **header**).
Here my code:
```
from bs4 import BeautifulSoup
from requests import get
headers_m = ({'User-Agent':
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'})
sapo_m = "https://www.idealista.it/vendita-case/milano-milano/"
response_m = get(sapo_m, headers=headers_m)
```
|
2020/04/26
|
[
"https://Stackoverflow.com/questions/61442421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13378861/"
] |
This is not general python question. The site blocks such straightforward attempts of **scraping**, you need to find a set of headers (specific for this site) that will pass validation.
Regards,
|
Simply use `Chrome` as `User-Agent`.
```
from bs4 import BeautifulSoup
BeautifulSoup(requests.get("https://...", headers={"User-Agent": "Chrome"}).content, 'html.parser')
```
|
66,254,984
|
I have a list of dicts in python which look like these:
```py
[{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} ,
{'day' : 'Monday' , 'workers' : ['Kelly']}]
```
I want to sort them by day of week such that the result is
```py
[{'day' : 'Monday' , 'workers' : ['Kelly']},
{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']}]
```
I can use this answer to sort list of just weekday names: [Sort week day texts](https://stackoverflow.com/questions/13844158/sort-week-day-texts) but is there a way to sort the above dict?
|
2021/02/18
|
[
"https://Stackoverflow.com/questions/66254984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6415973/"
] |
Use a lambda function that extracts the weekday name from the dictionary and then returns the index as in your linked question.
```
weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri"]
list_of_dicts =
[{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} ,
{'day' : 'Monday' , 'workers' : ['Kelly']}]
list_of_dicts.sort(key = lambda d: weekdays.index(d['day']))
```
|
The same basic approach that the example you link to uses will work for your list of dictionaries case. The trick is, you need to extract the day value from the dictionaries within the list to make it work. A `lambda` expression used for the `key` parameter is one way to do that.
Example:
```
day_order = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
data = [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} , {'day' : 'Monday' , 'workers' : ['Kelly']}]
sorted(data, key=lambda d: day_order.index(d["day"]))
```
Output:
```
[{'day': 'Monday', 'workers': ['Kelly']},
{'day': 'Wednesday', 'workers': ['John', 'Smith']}]
```
|
66,254,984
|
I have a list of dicts in python which look like these:
```py
[{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} ,
{'day' : 'Monday' , 'workers' : ['Kelly']}]
```
I want to sort them by day of week such that the result is
```py
[{'day' : 'Monday' , 'workers' : ['Kelly']},
{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']}]
```
I can use this answer to sort list of just weekday names: [Sort week day texts](https://stackoverflow.com/questions/13844158/sort-week-day-texts) but is there a way to sort the above dict?
|
2021/02/18
|
[
"https://Stackoverflow.com/questions/66254984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6415973/"
] |
The same basic approach that the example you link to uses will work for your list of dictionaries case. The trick is, you need to extract the day value from the dictionaries within the list to make it work. A `lambda` expression used for the `key` parameter is one way to do that.
Example:
```
day_order = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
data = [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} , {'day' : 'Monday' , 'workers' : ['Kelly']}]
sorted(data, key=lambda d: day_order.index(d["day"]))
```
Output:
```
[{'day': 'Monday', 'workers': ['Kelly']},
{'day': 'Wednesday', 'workers': ['John', 'Smith']}]
```
|
To sort a dictionary by a key `"key"`, you can do:
```py
sorted(dicts, key=lambda d: d["key"])
```
Merging this with the answer from the [question you linked](https://stackoverflow.com/q/13844158/14160477):
```py
m = ["Monday", "Tuesday", ...]
print(sorted(dicts, key=lambda d: m.index(d["day"])))
```
|
66,254,984
|
I have a list of dicts in python which look like these:
```py
[{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} ,
{'day' : 'Monday' , 'workers' : ['Kelly']}]
```
I want to sort them by day of week such that the result is
```py
[{'day' : 'Monday' , 'workers' : ['Kelly']},
{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']}]
```
I can use this answer to sort list of just weekday names: [Sort week day texts](https://stackoverflow.com/questions/13844158/sort-week-day-texts) but is there a way to sort the above dict?
|
2021/02/18
|
[
"https://Stackoverflow.com/questions/66254984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6415973/"
] |
The same basic approach that the example you link to uses will work for your list of dictionaries case. The trick is, you need to extract the day value from the dictionaries within the list to make it work. A `lambda` expression used for the `key` parameter is one way to do that.
Example:
```
day_order = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
data = [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} , {'day' : 'Monday' , 'workers' : ['Kelly']}]
sorted(data, key=lambda d: day_order.index(d["day"]))
```
Output:
```
[{'day': 'Monday', 'workers': ['Kelly']},
{'day': 'Wednesday', 'workers': ['John', 'Smith']}]
```
|
Here it is:
```
lst = [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} ,
{'day' : 'Monday' , 'workers' : ['Kelly']},
{'day' : 'Friday' , 'workers' : ['Nelly']}]
m = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
result = sorted(lst, key= lambda x: m.index(x['day']))
print(result)
#[{'day': 'Monday', 'workers': ['Kelly']}, {'day': 'Wednesday', 'workers': ['John', 'Smith']}, {'day': 'Friday', 'workers': ['Nelly']}]
```
|
66,254,984
|
I have a list of dicts in python which look like these:
```py
[{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} ,
{'day' : 'Monday' , 'workers' : ['Kelly']}]
```
I want to sort them by day of week such that the result is
```py
[{'day' : 'Monday' , 'workers' : ['Kelly']},
{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']}]
```
I can use this answer to sort list of just weekday names: [Sort week day texts](https://stackoverflow.com/questions/13844158/sort-week-day-texts) but is there a way to sort the above dict?
|
2021/02/18
|
[
"https://Stackoverflow.com/questions/66254984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6415973/"
] |
Use a lambda function that extracts the weekday name from the dictionary and then returns the index as in your linked question.
```
weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri"]
list_of_dicts =
[{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} ,
{'day' : 'Monday' , 'workers' : ['Kelly']}]
list_of_dicts.sort(key = lambda d: weekdays.index(d['day']))
```
|
To sort a dictionary by a key `"key"`, you can do:
```py
sorted(dicts, key=lambda d: d["key"])
```
Merging this with the answer from the [question you linked](https://stackoverflow.com/q/13844158/14160477):
```py
m = ["Monday", "Tuesday", ...]
print(sorted(dicts, key=lambda d: m.index(d["day"])))
```
|
66,254,984
|
I have a list of dicts in python which look like these:
```py
[{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} ,
{'day' : 'Monday' , 'workers' : ['Kelly']}]
```
I want to sort them by day of week such that the result is
```py
[{'day' : 'Monday' , 'workers' : ['Kelly']},
{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']}]
```
I can use this answer to sort list of just weekday names: [Sort week day texts](https://stackoverflow.com/questions/13844158/sort-week-day-texts) but is there a way to sort the above dict?
|
2021/02/18
|
[
"https://Stackoverflow.com/questions/66254984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6415973/"
] |
Use a lambda function that extracts the weekday name from the dictionary and then returns the index as in your linked question.
```
weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri"]
list_of_dicts =
[{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} ,
{'day' : 'Monday' , 'workers' : ['Kelly']}]
list_of_dicts.sort(key = lambda d: weekdays.index(d['day']))
```
|
Here it is:
```
lst = [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} ,
{'day' : 'Monday' , 'workers' : ['Kelly']},
{'day' : 'Friday' , 'workers' : ['Nelly']}]
m = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
result = sorted(lst, key= lambda x: m.index(x['day']))
print(result)
#[{'day': 'Monday', 'workers': ['Kelly']}, {'day': 'Wednesday', 'workers': ['John', 'Smith']}, {'day': 'Friday', 'workers': ['Nelly']}]
```
|
66,254,984
|
I have a list of dicts in python which look like these:
```py
[{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} ,
{'day' : 'Monday' , 'workers' : ['Kelly']}]
```
I want to sort them by day of week such that the result is
```py
[{'day' : 'Monday' , 'workers' : ['Kelly']},
{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']}]
```
I can use this answer to sort list of just weekday names: [Sort week day texts](https://stackoverflow.com/questions/13844158/sort-week-day-texts) but is there a way to sort the above dict?
|
2021/02/18
|
[
"https://Stackoverflow.com/questions/66254984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6415973/"
] |
To sort a dictionary by a key `"key"`, you can do:
```py
sorted(dicts, key=lambda d: d["key"])
```
Merging this with the answer from the [question you linked](https://stackoverflow.com/q/13844158/14160477):
```py
m = ["Monday", "Tuesday", ...]
print(sorted(dicts, key=lambda d: m.index(d["day"])))
```
|
Here it is:
```
lst = [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} ,
{'day' : 'Monday' , 'workers' : ['Kelly']},
{'day' : 'Friday' , 'workers' : ['Nelly']}]
m = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
result = sorted(lst, key= lambda x: m.index(x['day']))
print(result)
#[{'day': 'Monday', 'workers': ['Kelly']}, {'day': 'Wednesday', 'workers': ['John', 'Smith']}, {'day': 'Friday', 'workers': ['Nelly']}]
```
|
12,343,261
|
OK, so I went on <http://wiki.vg/Protocol>, but I don't understand how to send the packets through a socket to a Minecraft server. I would like to know if it is possible, and if it is how, to send Minecraft packets through a Python socket to a Minecraft server, as if the socket was the Minecraft client. I want to see if there is a way to make a minecraft person appear on a server using python and make him walk in a straight line, for a certain amount of time (probably through a python for loop), than log out. Is there a python package that allows you to do this? Thanks!
|
2012/09/09
|
[
"https://Stackoverflow.com/questions/12343261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1983840/"
] |
Well I'd start with [this](https://gist.github.com/1209061) which sends a packet. It's linked to from the same page you mention. Then adjust the packet ID and the data you add to the stream.
|
No, as a Minecraft server is nothing but a host listening to a TCP socket.
You're better off looking for a Python TCP/sockets tutorial in general, or a Minecraft client/bot library.
|
59,416,899
|
We use ndb datastore in our current python 2.7 standard environment. We migrating this application to python 3.7 standard environment with firestore (native mode).
We use pagination on ndb datastore and construct our query using fetch.
```
query_results , next_curs, more_flag = query_structure.fetch_page(10)
```
The next\_curs and more\_flag are very useful to indicate if there is more data to be fetched after the current query (to fetch 10 elements). We use this to flag the front end for "Next Page" / "Previous Page".
We can't find an equivalent of this in Firestore. Can someone help how to achieve this?
|
2019/12/19
|
[
"https://Stackoverflow.com/questions/59416899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3647998/"
] |
There is no direct equivalent in Firestore pagination. What you can do instead is fetch one more document than the N documents that the page requires, then use the presence of the N+1 document to determine if there is "more". You would omit the N+1 document from the displayed page, then start the next page at that N+1 document.
|
I build a custom firestore API not long ago to fetch records with pagination. You can take a look at the [repository](https://github.com/vwt-digital/firestore-api). This is the story of the learning cycle I went through:
My first attempt was to use limit and offset, this seemed to work like a charm, but then I walked into the issue that it ended up being very costly to fetch like 200.000 records. Because when using offset, google charges you also for the reads on **all** the records before that. The Google Firestore [Pricing Page](https://firebase.google.com/docs/firestore/pricing) clearly states this:
>
> There are no additional costs for using cursors, page tokens, and
> limits. In fact, these features can help you save money by reading
> only the documents that you actually need.
>
>
> However, when you send a query that includes an offset, you are
> charged a read for each skipped document. For example, if your query
> uses an offset of 10, and the query returns 1 document, you are
> charged for 11 reads. Because of this additional cost, you should use
> cursors instead of offsets whenever possible.
>
>
>
My second attempt was using a cursor to minimize those reads. I ended up fetching N+1 documents and place the cursor like so:
```
collection = 'my-collection'
cursor = 'we3adoipjcjweoijfec93r04' # N+1th doc id
q = db.collection(collection)
snapshot = db.collection(collection).document(cursor).get()
q = q.start_at(snapshot) # Place cursor at this document
docs = q.stream()
```
Google wrote a whole [page](https://firebase.google.com/docs/firestore/query-data/query-cursors) on pagination in Firestore. Some useful query methods when implementing pagination:
* `limit()` limits the query to a fixed set of documents.
* `start_at()` includes the cursor document.
* `start_after()` starts right after the cursor document.
* `order_by()` ensures all documents are ordered by a specific field.
|
1,668,223
|
I am in the process of coding an app which has to get the metadata (author,version..etc) out of several modules (.py files) and display them. The user selects a script and the script is executed. (New scripts can be added and old ones be taken of from the target folder just like a plugin system).
Firstly I import a script and I take out the metadata, then I go for the next.
But I want to de-import all the other modules except for the one that the user has selected.
How can I implement this?
I tried these
```
1. del module
2. del sys.modules['module']
```
The latter did not work. I tried #python and got the answer that it was not good to de-import modules, but I want to know a clean way of implementing this. Any ideas/suggestions would help.
|
2009/11/03
|
[
"https://Stackoverflow.com/questions/1668223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200816/"
] |
i think [this post](http://mail.python.org/pipermail/tutor/2006-August/048596.html) should help you
edit:
to secure the availability of this information (in case the link dies or something similar) i will include the original message from the [tutor mailing list](http://mail.python.org/mailman/listinfo/tutor) here:
---
On 8/14/06, Dick Moores wrote:
>
> Actually, my question is, after using IDLE to do some importing of
> modules and initializing of variables, how to return it to it's
> initial condition without closing and reopening it.
>
>
> So, for example after I've done
>
>
>
> ```
> >>> import math, psyco
> >>> a = 4**23
>
> ```
>
> How can I wipe those out without closing IDLE?
> (I used to know how, but I've forgotten.)
>
>
>
Hi Dick,
Usually this entails removing from the "module registry and removing
references to it in the code. If you have a *really* well used module (like
one with config parameters imported into every module), then you'll have an
additional step of removing it from every module. Also, if you have use
"from psyco import ...", then you will not be able to free up the module and
the reference to the module easily (is it from that module, or imported from
a third module? see "if paranoid: code below).
The function below deletes a module by name from the Python interpreter, the
"paranoid" parameter is a list of variable names to remove from every other
module (supposedly being deleted with the module). Be VERY careful with the
paranoid param; it could cause problems for your interpreter if your
functions and classes are named the same in different modules. One common
occurrance of this is "error" for exceptions. A lot of libraries have one
"catch-all" exception called "error" in the module. If you also named your
exception "error" and decided to include that in the paranoid list... there
go a lot of other exception objects.
```
def delete_module(modname, paranoid=None):
from sys import modules
try:
thismod = modules[modname]
except KeyError:
raise ValueError(modname)
these_symbols = dir(thismod)
if paranoid:
try:
paranoid[:] # sequence support
except:
raise ValueError('must supply a finite list for paranoid')
else:
these_symbols = paranoid[:]
del modules[modname]
for mod in modules.values():
try:
delattr(mod, modname)
except AttributeError:
pass
if paranoid:
for symbol in these_symbols:
if symbol[:2] == '__': # ignore special symbols
continue
try:
delattr(mod, symbol)
except AttributeError:
pass
```
Then you should be able to use this like:
```
delete_module('psyco')
```
or
```
delete_module('psyco', ['Psycho', 'KillerError'])
# only delete these symbols from every other module
# (for "from psyco import Psycho, KillerError" statements)
```
-Arcege
|
Suggestion: Import your modules dynamically using `__import__`
E.g.
```
module_list = ['os', 'decimal', 'random']
for module in module_list:
x = __import__(module)
print 'name: %s - module_obj: %s' % (x.__name__, x)
```
Will produce:
```
name: os - module_obj: <module 'os' from '/usr/lib64/python2.4/os.pyc'>
name: decimal - module_obj: <module 'decimal' from '/usr/lib64/python2.4/decimal.pyc'>
name: random - module_obj: <module 'random' from '/usr/lib64/python2.4/random.pyc'>
```
Though, this won't really remove it from the modules registry. The next time that it is imported, it won't re-read the package/module file and it won't execute it. To accomplish that, you can simply modify the above code snippet like this:
```
import sys
module_list = ['os', 'decimal', 'random', 'test1']
for module_name in module_list:
x = __import__(module_name)
print 'name: %s - module_obj: %s' % (x.__name__, x)
del x
sys.modules.pop(module_name)
```
|
1,668,223
|
I am in the process of coding an app which has to get the metadata (author,version..etc) out of several modules (.py files) and display them. The user selects a script and the script is executed. (New scripts can be added and old ones be taken of from the target folder just like a plugin system).
Firstly I import a script and I take out the metadata, then I go for the next.
But I want to de-import all the other modules except for the one that the user has selected.
How can I implement this?
I tried these
```
1. del module
2. del sys.modules['module']
```
The latter did not work. I tried #python and got the answer that it was not good to de-import modules, but I want to know a clean way of implementing this. Any ideas/suggestions would help.
|
2009/11/03
|
[
"https://Stackoverflow.com/questions/1668223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200816/"
] |
i think [this post](http://mail.python.org/pipermail/tutor/2006-August/048596.html) should help you
edit:
to secure the availability of this information (in case the link dies or something similar) i will include the original message from the [tutor mailing list](http://mail.python.org/mailman/listinfo/tutor) here:
---
On 8/14/06, Dick Moores wrote:
>
> Actually, my question is, after using IDLE to do some importing of
> modules and initializing of variables, how to return it to it's
> initial condition without closing and reopening it.
>
>
> So, for example after I've done
>
>
>
> ```
> >>> import math, psyco
> >>> a = 4**23
>
> ```
>
> How can I wipe those out without closing IDLE?
> (I used to know how, but I've forgotten.)
>
>
>
Hi Dick,
Usually this entails removing from the "module registry and removing
references to it in the code. If you have a *really* well used module (like
one with config parameters imported into every module), then you'll have an
additional step of removing it from every module. Also, if you have use
"from psyco import ...", then you will not be able to free up the module and
the reference to the module easily (is it from that module, or imported from
a third module? see "if paranoid: code below).
The function below deletes a module by name from the Python interpreter, the
"paranoid" parameter is a list of variable names to remove from every other
module (supposedly being deleted with the module). Be VERY careful with the
paranoid param; it could cause problems for your interpreter if your
functions and classes are named the same in different modules. One common
occurrance of this is "error" for exceptions. A lot of libraries have one
"catch-all" exception called "error" in the module. If you also named your
exception "error" and decided to include that in the paranoid list... there
go a lot of other exception objects.
```
def delete_module(modname, paranoid=None):
from sys import modules
try:
thismod = modules[modname]
except KeyError:
raise ValueError(modname)
these_symbols = dir(thismod)
if paranoid:
try:
paranoid[:] # sequence support
except:
raise ValueError('must supply a finite list for paranoid')
else:
these_symbols = paranoid[:]
del modules[modname]
for mod in modules.values():
try:
delattr(mod, modname)
except AttributeError:
pass
if paranoid:
for symbol in these_symbols:
if symbol[:2] == '__': # ignore special symbols
continue
try:
delattr(mod, symbol)
except AttributeError:
pass
```
Then you should be able to use this like:
```
delete_module('psyco')
```
or
```
delete_module('psyco', ['Psycho', 'KillerError'])
# only delete these symbols from every other module
# (for "from psyco import Psycho, KillerError" statements)
```
-Arcege
|
I know this post has been out of date but I just encountered this issue and was struggling against it for the past few days. Now I came with a conclusion that can perfectly solve this issue. Please see the sample code below:
```
try:
theMod = sys.modules['ModNeedToBeDel']
except:
theMod = None
if theMod:
del sys.modules['ModNeedToBeDel']
#The extra try/except below is because I implemented the block in a module of a sub-package; this ModNeedToBeDel in my case was imported either by the toppest level Main code, or by the other sub-package modules. That's why I need two different try/except.
try:
theMod = sys.modules['UpperFolder.ModNeedToBeDel']
except:
theMod = None
if theMod:
del sys.modules['UpperFolder.ModNeedToBeDel']
import ModNeedToBeDel # or UpperFolder.ModNeedToBeDel here
```
Note that `del sys.modules[theMod]` won't work, because it just deletes the reference, instead of the actual `ModNeedToBeDel`.
Hope this could help someone so that they won't have to struggle on this issue for several days!
|
1,668,223
|
I am in the process of coding an app which has to get the metadata (author,version..etc) out of several modules (.py files) and display them. The user selects a script and the script is executed. (New scripts can be added and old ones be taken of from the target folder just like a plugin system).
Firstly I import a script and I take out the metadata, then I go for the next.
But I want to de-import all the other modules except for the one that the user has selected.
How can I implement this?
I tried these
```
1. del module
2. del sys.modules['module']
```
The latter did not work. I tried #python and got the answer that it was not good to de-import modules, but I want to know a clean way of implementing this. Any ideas/suggestions would help.
|
2009/11/03
|
[
"https://Stackoverflow.com/questions/1668223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200816/"
] |
i think [this post](http://mail.python.org/pipermail/tutor/2006-August/048596.html) should help you
edit:
to secure the availability of this information (in case the link dies or something similar) i will include the original message from the [tutor mailing list](http://mail.python.org/mailman/listinfo/tutor) here:
---
On 8/14/06, Dick Moores wrote:
>
> Actually, my question is, after using IDLE to do some importing of
> modules and initializing of variables, how to return it to it's
> initial condition without closing and reopening it.
>
>
> So, for example after I've done
>
>
>
> ```
> >>> import math, psyco
> >>> a = 4**23
>
> ```
>
> How can I wipe those out without closing IDLE?
> (I used to know how, but I've forgotten.)
>
>
>
Hi Dick,
Usually this entails removing from the "module registry and removing
references to it in the code. If you have a *really* well used module (like
one with config parameters imported into every module), then you'll have an
additional step of removing it from every module. Also, if you have use
"from psyco import ...", then you will not be able to free up the module and
the reference to the module easily (is it from that module, or imported from
a third module? see "if paranoid: code below).
The function below deletes a module by name from the Python interpreter, the
"paranoid" parameter is a list of variable names to remove from every other
module (supposedly being deleted with the module). Be VERY careful with the
paranoid param; it could cause problems for your interpreter if your
functions and classes are named the same in different modules. One common
occurrance of this is "error" for exceptions. A lot of libraries have one
"catch-all" exception called "error" in the module. If you also named your
exception "error" and decided to include that in the paranoid list... there
go a lot of other exception objects.
```
def delete_module(modname, paranoid=None):
from sys import modules
try:
thismod = modules[modname]
except KeyError:
raise ValueError(modname)
these_symbols = dir(thismod)
if paranoid:
try:
paranoid[:] # sequence support
except:
raise ValueError('must supply a finite list for paranoid')
else:
these_symbols = paranoid[:]
del modules[modname]
for mod in modules.values():
try:
delattr(mod, modname)
except AttributeError:
pass
if paranoid:
for symbol in these_symbols:
if symbol[:2] == '__': # ignore special symbols
continue
try:
delattr(mod, symbol)
except AttributeError:
pass
```
Then you should be able to use this like:
```
delete_module('psyco')
```
or
```
delete_module('psyco', ['Psycho', 'KillerError'])
# only delete these symbols from every other module
# (for "from psyco import Psycho, KillerError" statements)
```
-Arcege
|
I recently found this post <https://www.geeksforgeeks.org/reloading-modules-python/> and so for Python 3.4 or later use
```
import importlib
importlib.reload(module)
```
|
1,668,223
|
I am in the process of coding an app which has to get the metadata (author,version..etc) out of several modules (.py files) and display them. The user selects a script and the script is executed. (New scripts can be added and old ones be taken of from the target folder just like a plugin system).
Firstly I import a script and I take out the metadata, then I go for the next.
But I want to de-import all the other modules except for the one that the user has selected.
How can I implement this?
I tried these
```
1. del module
2. del sys.modules['module']
```
The latter did not work. I tried #python and got the answer that it was not good to de-import modules, but I want to know a clean way of implementing this. Any ideas/suggestions would help.
|
2009/11/03
|
[
"https://Stackoverflow.com/questions/1668223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200816/"
] |
Suggestion: Import your modules dynamically using `__import__`
E.g.
```
module_list = ['os', 'decimal', 'random']
for module in module_list:
x = __import__(module)
print 'name: %s - module_obj: %s' % (x.__name__, x)
```
Will produce:
```
name: os - module_obj: <module 'os' from '/usr/lib64/python2.4/os.pyc'>
name: decimal - module_obj: <module 'decimal' from '/usr/lib64/python2.4/decimal.pyc'>
name: random - module_obj: <module 'random' from '/usr/lib64/python2.4/random.pyc'>
```
Though, this won't really remove it from the modules registry. The next time that it is imported, it won't re-read the package/module file and it won't execute it. To accomplish that, you can simply modify the above code snippet like this:
```
import sys
module_list = ['os', 'decimal', 'random', 'test1']
for module_name in module_list:
x = __import__(module_name)
print 'name: %s - module_obj: %s' % (x.__name__, x)
del x
sys.modules.pop(module_name)
```
|
I know this post has been out of date but I just encountered this issue and was struggling against it for the past few days. Now I came with a conclusion that can perfectly solve this issue. Please see the sample code below:
```
try:
theMod = sys.modules['ModNeedToBeDel']
except:
theMod = None
if theMod:
del sys.modules['ModNeedToBeDel']
#The extra try/except below is because I implemented the block in a module of a sub-package; this ModNeedToBeDel in my case was imported either by the toppest level Main code, or by the other sub-package modules. That's why I need two different try/except.
try:
theMod = sys.modules['UpperFolder.ModNeedToBeDel']
except:
theMod = None
if theMod:
del sys.modules['UpperFolder.ModNeedToBeDel']
import ModNeedToBeDel # or UpperFolder.ModNeedToBeDel here
```
Note that `del sys.modules[theMod]` won't work, because it just deletes the reference, instead of the actual `ModNeedToBeDel`.
Hope this could help someone so that they won't have to struggle on this issue for several days!
|
1,668,223
|
I am in the process of coding an app which has to get the metadata (author,version..etc) out of several modules (.py files) and display them. The user selects a script and the script is executed. (New scripts can be added and old ones be taken of from the target folder just like a plugin system).
Firstly I import a script and I take out the metadata, then I go for the next.
But I want to de-import all the other modules except for the one that the user has selected.
How can I implement this?
I tried these
```
1. del module
2. del sys.modules['module']
```
The latter did not work. I tried #python and got the answer that it was not good to de-import modules, but I want to know a clean way of implementing this. Any ideas/suggestions would help.
|
2009/11/03
|
[
"https://Stackoverflow.com/questions/1668223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200816/"
] |
I recently found this post <https://www.geeksforgeeks.org/reloading-modules-python/> and so for Python 3.4 or later use
```
import importlib
importlib.reload(module)
```
|
I know this post has been out of date but I just encountered this issue and was struggling against it for the past few days. Now I came with a conclusion that can perfectly solve this issue. Please see the sample code below:
```
try:
theMod = sys.modules['ModNeedToBeDel']
except:
theMod = None
if theMod:
del sys.modules['ModNeedToBeDel']
#The extra try/except below is because I implemented the block in a module of a sub-package; this ModNeedToBeDel in my case was imported either by the toppest level Main code, or by the other sub-package modules. That's why I need two different try/except.
try:
theMod = sys.modules['UpperFolder.ModNeedToBeDel']
except:
theMod = None
if theMod:
del sys.modules['UpperFolder.ModNeedToBeDel']
import ModNeedToBeDel # or UpperFolder.ModNeedToBeDel here
```
Note that `del sys.modules[theMod]` won't work, because it just deletes the reference, instead of the actual `ModNeedToBeDel`.
Hope this could help someone so that they won't have to struggle on this issue for several days!
|
55,767,411
|
I have an potentially infinite python 'while' loop that I would like to keep running even after the main script/process execution has been completed. Furthermore, I would like to be able to later kill this loop from a unix CLI if needed (ie. kill -SIGTERM PID), so will need the pid of the loop as well. How would I accomplish this? Thanks!
Loop:
```
args = 'ping -c 1 1.2.3.4'
while True:
time.sleep(60)
return_code = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE)
if return_code == 0:
break
```
|
2019/04/19
|
[
"https://Stackoverflow.com/questions/55767411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1998671/"
] |
In python, parent processes attempt to kill all their daemonic child processes when they exit. However, you can use `os.fork()` to create a completely new process:
```
import os
pid = os.fork()
if pid:
#parent
print("Parent!")
else:
#child
print("Child!")
```
|
`Popen` returns an object which has the `pid`. According to the [doc](https://docs.python.org/3/library/subprocess.html#subprocess.Popen)
>
> Popen.pid
> The process ID of the child process.
>
>
> Note that if you set the shell argument to True, this is the process ID of the spawned shell.
>
>
>
You would need to turnoff the `shell=True` to get the pid of the process, otherwise it gives the pid of the shell.
```
args = 'ping -c 1 1.2.3.4'
while True:
time.sleep(60)
with subprocess.Popen(args, shell=False, stdout=subprocess.PIPE) as proc:
print('PID: {}'.format(proc.pid))
...
```
|
10,649,623
|
I have a web app that uses google app engine .In ubuntu ,I start the app engine using
```
./dev_appserver.py /home/me/dev/mycode
```
In the mycode folder ,I have app.yml and the python files of the web app.In the web app code,I have used logging to write values of some variables like
```
import logging
LOG_FILENAME = '/home/me/logs/mylog.txt'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
class Handler(webapp2.RequestHandler):
....
class Welcome(Handler):
def get(self):
if self.user:
logging.debug('rendering welcome page for user')
self.render('welcome.html',username= self.user.name)
else:
logging.debug('redirect to signup')
self.redirect('/signup')
class MainPage(Handler):
def get(self):
self.redirect('/welcome')
app = webapp2.WSGIApplication([('/', MainPage),('/signup', Register),('/welcome', Welcome)], debug=True)
```
I have set `chmod 777` for the logs directory..Still no logs are created there.I am at a loss as to how any log can be viewed when google app engine runs..Since it is in linux,I don't have a `launcher with gui` ..which makes it difficult to see the app engine logs if any are generated
If someone can help me solve this,it would be great.
|
2012/05/18
|
[
"https://Stackoverflow.com/questions/10649623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1291096/"
] |
Did you read this <https://developers.google.com/appengine/articles/logging> as I understand you must not declare your own log file
|
I have the same environment (Ubuntu, python, gae) and ran into similar issues with logging.
You can't log to local file as stated here: <https://developers.google.com/appengine/docs/python/overview>
>
> "The sandbox ensures that apps can only perform actions that do not interfere with the performance and scalability of other apps. For instance, an app cannot write data to the local file system or make arbitrary network connections."
>
>
> "The development server runs your application on your local computer for testing your application. The server simulates the App Engine datastore, services and sandbox restrictions. "
>
>
>
I was able to getting console logging to work as follows:
```
import logging
logging.getLogger().setLevel(logging.DEBUG)
```
|
6,069,690
|
I have a basic python question. I'm working on a class `foo` and I use `__init__():` to do some actions on a value:
```
class foo():
def __init__(self,bar=None):
self.bar=bar
if bar is None:
isSet=False
else:
isSet=True
print isSet
```
When I execute the code I get: `NameError: name 'isSet' is not defined`.
How can I access `isSet`? What am I doing wrong?
regards,
martin
|
2011/05/20
|
[
"https://Stackoverflow.com/questions/6069690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/760797/"
] |
Wrong indentation, it should be this instead, otherwise you're exiting the function.
```
class foo():
def __init__(self,bar=None):
self.bar=bar
if bar is None:
isSet=False
else:
isSet=True
print isSet
```
|
The indentation of the final line makes it execute in the context of the class and not `__init__`. Indent it one more time to make your program work.
|
6,069,690
|
I have a basic python question. I'm working on a class `foo` and I use `__init__():` to do some actions on a value:
```
class foo():
def __init__(self,bar=None):
self.bar=bar
if bar is None:
isSet=False
else:
isSet=True
print isSet
```
When I execute the code I get: `NameError: name 'isSet' is not defined`.
How can I access `isSet`? What am I doing wrong?
regards,
martin
|
2011/05/20
|
[
"https://Stackoverflow.com/questions/6069690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/760797/"
] |
Wrong indentation, it should be this instead, otherwise you're exiting the function.
```
class foo():
def __init__(self,bar=None):
self.bar=bar
if bar is None:
isSet=False
else:
isSet=True
print isSet
```
|
I'd try
```
class foo():
def __init__(self,bar=None):
self.bar = bar
self.is_set = (bar is None)
```
Then inside the class
```
...
def spam(self, eggs, ham):
if self.is_set:
print("Camelot!")
else:
...
```
Have you read [the doc's tutorial's entry about classes](http://docs.python.org/tutorial/classes.html)?
|
6,069,690
|
I have a basic python question. I'm working on a class `foo` and I use `__init__():` to do some actions on a value:
```
class foo():
def __init__(self,bar=None):
self.bar=bar
if bar is None:
isSet=False
else:
isSet=True
print isSet
```
When I execute the code I get: `NameError: name 'isSet' is not defined`.
How can I access `isSet`? What am I doing wrong?
regards,
martin
|
2011/05/20
|
[
"https://Stackoverflow.com/questions/6069690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/760797/"
] |
Wrong indentation, it should be this instead, otherwise you're exiting the function.
```
class foo():
def __init__(self,bar=None):
self.bar=bar
if bar is None:
isSet=False
else:
isSet=True
print isSet
```
|
In your code, `isSet` is a *class* attribute, as opposed to an *instance* attribute. Therefore in the class body you need to define it before referencing it in the `print` statement. Outside the class and in its methods, you must prefix it with the class name and a dot, i.e. `Foo.` in this case. Note that the code in `def __init__()` function body does not execute until you create an instance of the `Foo` class by calling it.
```
class Foo(object):
isSet = None
def __init__(self, bar=None):
self.bar = bar
if bar is None:
Foo.isSet = False
else:
Foo.isSet = True
print isSet
f = Foo()
print Foo.isSet
```
output:
```
None
False
```
|
6,069,690
|
I have a basic python question. I'm working on a class `foo` and I use `__init__():` to do some actions on a value:
```
class foo():
def __init__(self,bar=None):
self.bar=bar
if bar is None:
isSet=False
else:
isSet=True
print isSet
```
When I execute the code I get: `NameError: name 'isSet' is not defined`.
How can I access `isSet`? What am I doing wrong?
regards,
martin
|
2011/05/20
|
[
"https://Stackoverflow.com/questions/6069690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/760797/"
] |
It depends on what you are trying to do. You probably want `isSet` to be a member of `foo`:
```
class foo():
def __init__(self,bar=None):
self.bar=bar
self.isSet=True
if bar is None:
self.isSet=False
f = foo()
print f.isSet
```
|
The indentation of the final line makes it execute in the context of the class and not `__init__`. Indent it one more time to make your program work.
|
6,069,690
|
I have a basic python question. I'm working on a class `foo` and I use `__init__():` to do some actions on a value:
```
class foo():
def __init__(self,bar=None):
self.bar=bar
if bar is None:
isSet=False
else:
isSet=True
print isSet
```
When I execute the code I get: `NameError: name 'isSet' is not defined`.
How can I access `isSet`? What am I doing wrong?
regards,
martin
|
2011/05/20
|
[
"https://Stackoverflow.com/questions/6069690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/760797/"
] |
It depends on what you are trying to do. You probably want `isSet` to be a member of `foo`:
```
class foo():
def __init__(self,bar=None):
self.bar=bar
self.isSet=True
if bar is None:
self.isSet=False
f = foo()
print f.isSet
```
|
I'd try
```
class foo():
def __init__(self,bar=None):
self.bar = bar
self.is_set = (bar is None)
```
Then inside the class
```
...
def spam(self, eggs, ham):
if self.is_set:
print("Camelot!")
else:
...
```
Have you read [the doc's tutorial's entry about classes](http://docs.python.org/tutorial/classes.html)?
|
6,069,690
|
I have a basic python question. I'm working on a class `foo` and I use `__init__():` to do some actions on a value:
```
class foo():
def __init__(self,bar=None):
self.bar=bar
if bar is None:
isSet=False
else:
isSet=True
print isSet
```
When I execute the code I get: `NameError: name 'isSet' is not defined`.
How can I access `isSet`? What am I doing wrong?
regards,
martin
|
2011/05/20
|
[
"https://Stackoverflow.com/questions/6069690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/760797/"
] |
It depends on what you are trying to do. You probably want `isSet` to be a member of `foo`:
```
class foo():
def __init__(self,bar=None):
self.bar=bar
self.isSet=True
if bar is None:
self.isSet=False
f = foo()
print f.isSet
```
|
In your code, `isSet` is a *class* attribute, as opposed to an *instance* attribute. Therefore in the class body you need to define it before referencing it in the `print` statement. Outside the class and in its methods, you must prefix it with the class name and a dot, i.e. `Foo.` in this case. Note that the code in `def __init__()` function body does not execute until you create an instance of the `Foo` class by calling it.
```
class Foo(object):
isSet = None
def __init__(self, bar=None):
self.bar = bar
if bar is None:
Foo.isSet = False
else:
Foo.isSet = True
print isSet
f = Foo()
print Foo.isSet
```
output:
```
None
False
```
|
6,069,690
|
I have a basic python question. I'm working on a class `foo` and I use `__init__():` to do some actions on a value:
```
class foo():
def __init__(self,bar=None):
self.bar=bar
if bar is None:
isSet=False
else:
isSet=True
print isSet
```
When I execute the code I get: `NameError: name 'isSet' is not defined`.
How can I access `isSet`? What am I doing wrong?
regards,
martin
|
2011/05/20
|
[
"https://Stackoverflow.com/questions/6069690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/760797/"
] |
I'd try
```
class foo():
def __init__(self,bar=None):
self.bar = bar
self.is_set = (bar is None)
```
Then inside the class
```
...
def spam(self, eggs, ham):
if self.is_set:
print("Camelot!")
else:
...
```
Have you read [the doc's tutorial's entry about classes](http://docs.python.org/tutorial/classes.html)?
|
The indentation of the final line makes it execute in the context of the class and not `__init__`. Indent it one more time to make your program work.
|
6,069,690
|
I have a basic python question. I'm working on a class `foo` and I use `__init__():` to do some actions on a value:
```
class foo():
def __init__(self,bar=None):
self.bar=bar
if bar is None:
isSet=False
else:
isSet=True
print isSet
```
When I execute the code I get: `NameError: name 'isSet' is not defined`.
How can I access `isSet`? What am I doing wrong?
regards,
martin
|
2011/05/20
|
[
"https://Stackoverflow.com/questions/6069690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/760797/"
] |
In your code, `isSet` is a *class* attribute, as opposed to an *instance* attribute. Therefore in the class body you need to define it before referencing it in the `print` statement. Outside the class and in its methods, you must prefix it with the class name and a dot, i.e. `Foo.` in this case. Note that the code in `def __init__()` function body does not execute until you create an instance of the `Foo` class by calling it.
```
class Foo(object):
isSet = None
def __init__(self, bar=None):
self.bar = bar
if bar is None:
Foo.isSet = False
else:
Foo.isSet = True
print isSet
f = Foo()
print Foo.isSet
```
output:
```
None
False
```
|
The indentation of the final line makes it execute in the context of the class and not `__init__`. Indent it one more time to make your program work.
|
37,906,459
|
I have a text file. The guts of it look like this/ all of it looks like this (has been edited. This was also not what it initially looked like)
```
(0, 16, 0)
(0, 17, 0)
(0, 18, 0)
(0, 19, 0)
(0, 20, 0)
(0, 21, 0)
(0, 22, 0)
(0, 22, 1)
(0, 22, 2)
(0, 23, 0)
(0, 23, 4)
(0, 24, 0)
(0, 25, 0)
(0, 25, 1)
(0, 26, 0)
(0, 26, 3)
(0, 26, 4)
(0, 26, 5)
(0, 26, 9)
(0, 27, 0)
(0, 27, 1)
```
Anyway, how do I put these values into a set on python 2?
My most recent attempt was
```
om_set = set(open('Rye Grass.txt').read()
```
EDIT: This is the code I used to get my text file.
import cv2
import numpy as np
import time
```
om=cv2.imread('spectrum1.png')
om=om.reshape(1,-1,3)
om_list=om.tolist()
om_tuple={tuple(item) for item in om_list[0]}
om_set=set(om_tuple)
im=cv2.imread('1.jpg')
im=cv2.resize(im,(100,100))
im= im.reshape(1,-1,3)
im_list=im.tolist()
im_tuple={tuple(item) for item in im_list[0]}
ColourCount= om_set & set(im_tuple)
with open('Weedlist', 'a') as outputfile:
output = ', '.join([str(tup) for tup in sorted(ColourCount)])
outputfile.write(output)
print 'done'
im=cv2.imread('2.jpg')
im=cv2.resize(im,(100,100))
im= im.reshape(1,-1,3)
im_list=im.tolist()
im_tuple={tuple(item) for item in im_list[0]}
ColourCount= om_set & set(im_tuple)
with open('Weedlist', 'a') as outputfile:
output = ', '.join([str(tup) for tup in sorted(ColourCount)])
outputfile.write(output)
print 'done'
```
|
2016/06/19
|
[
"https://Stackoverflow.com/questions/37906459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6306510/"
] |
As @TimPietzcker suggested and trusting the file to only have these fixed representations of integers in comma separated triplets, surrounded by parentheses, a simple parser in one go (OP's question also had a greed "read" of file into memors):
```
#! /usr/bin/env python
from __future__ import print_function
infile = 'pixel_int_tuple_reps.txt'
split_pits = None
with open(infile, 'rt') as f_i:
split_pits = [z.strip(' ()') for z in f_i.read().strip().split('),')]
if split_pits:
on_set = set(tuple(int(z.strip())
for z in tup.split(', ')) for tup in split_pits)
print(on_set)
```
tramsforms:
```
(0, 19, 0), (0, 20, 0), (0, 21, 1), (0, 22, 0), (0, 24, 3), (0, 27, 0), (0, 29, 2), (0, 35, 2), (0, 36, 1)
```
into:
```
set([(0, 27, 0), (0, 36, 1), (0, 21, 1), (0, 22, 0), (0, 24, 3), (0, 19, 0), (0, 35, 2), (0, 29, 2), (0, 20, 0)])
```
The small snippet:
1. splits the pixel integer triplets into substrings of `0, 19, 0` cleansing a bit the stray parens and spaces away (also taking care of the closing parentheses at the end.
2. if that "worked" - further feeds the rgb split with integer conversion tuples into a set.
I would really think twice, before using eval/exec on that kind of deserialization task.
**Update** as suggested by comments from OP (please update the question!):
1. The file at the OP's site seems to be too big to print (keep in memory)?
2. It is **not** written, as the advertised in question ...
... so until we have further info from OP:
For a theoretical clean 3-int-tuple dump file this answer works (if not too big to load at once and map into a set).
For the concrete task, I may update the answer if sufficient new info has been added to the question ;-)
One way, if the triple "lines" are concat from previous stages with or without a newline separating, but alwayss missing the comma, to change the file reading part either:
1. into a line based reader (when newlines separate) and pull the set generation into the loop always making a union of the new harvested set with the existing (accumulating one) like `s = s | fresh` that is tackling them in "isolation"
or if these "chunks" are added like so `(0, 1, 230)(13, ...` that is `)(` "hitting hard":
2. modify the existing code inside reader and instead of: `f_i.read().strip().split('),')` write `f_i.read().replace(')('), (', ').strip().split('),')` ... that is "fixing" the `)(`part into a `), (`part to be able to continue as if it would be a homogene "structure".
**Update** now parsing the version 2 of the dataset (updated question):
File `pixel_int_tuple_reps_v2.txt`now has:
```
(0, 16, 0)
(0, 17, 0)
(0, 18, 0)
(0, 19, 0)
(0, 20, 0)
(0, 21, 0)
(0, 22, 0)
(0, 22, 1)
(0, 22, 2)
(0, 23, 0)
(0, 23, 4)
(0, 24, 0)
(0, 25, 0)
(0, 25, 1)
(0, 26, 0)
(0, 26, 3)
(0, 26, 4)
(0, 26, 5)
(0, 26, 9)
(0, 27, 0)
(0, 27, 1)
```
The code:
```
#! /usr/bin/env python
from __future__ import print_function
infile = 'pixel_int_tuple_reps_v2.txt'
on_set = set()
with open(infile, 'rt') as f_i:
for line in f_i.readlines():
rgb_line = line.strip().lstrip('(').rstrip(')')
try:
rgb = set([tuple(int(z.strip()) for z in rgb_line.split(', '))])
on_set = on_set.union(rgb)
except:
print("Ignored:" + rgb_line)
pass
print(len(on_set))
for rgb in sorted(on_set):
print(rgb)
```
Now parses this file and first dumps the length of the set and (as is the elements in sorted order):
```
21
(0, 16, 0)
(0, 17, 0)
(0, 18, 0)
(0, 19, 0)
(0, 20, 0)
(0, 21, 0)
(0, 22, 0)
(0, 22, 1)
(0, 22, 2)
(0, 23, 0)
(0, 23, 4)
(0, 24, 0)
(0, 25, 0)
(0, 25, 1)
(0, 26, 0)
(0, 26, 3)
(0, 26, 4)
(0, 26, 5)
(0, 26, 9)
(0, 27, 0)
(0, 27, 1)
```
HTH. Note that there are no duplicates in the provided sample input. Doubling the last data line I still rceived 21 unique elements as output, so I guess now it works as designed ;-)
|
Only need small modification.You can try this.
```
om_set = set(eval(open('abc.txt').read()))
```
**Result**
```
{(0, 19, 0),
(0, 20, 0),
(0, 21, 1),
(0, 22, 0),
(0, 24, 3),
(0, 27, 0),
(0, 29, 2),
(0, 35, 2)}
```
**Edit**
Here is the working of code in in `IPython` prompt.
```
In [1]: file_ = open('abc.txt')
In [2]: text_read = file_.read()
In [3]: print eval(text_read)
((0, 19, 0), (0, 20, 0), (0, 21, 1), (0, 22, 0), (0, 24, 3), (0, 27, 0), (0, 29, 2), (0, 35, 2), (0, 36, 1))
In [4]: type(eval(text_read))
Out[1]: tuple
In [5]: print set(eval(text_read))
set([(0, 27, 0), (0, 36, 1), (0, 21, 1), (0, 22, 0), (0, 24, 3), (0, 19, 0), (0, 35, 2), (0, 29, 2), (0, 20, 0)])
```
|
59,538,746
|
A use case of the `super()` builtin in python is to call an overridden method. Here is a simple example of using `super()` to call `Parent` class's `echo` function:
```py
class Parent():
def echo(self):
print("in Parent")
class Child(Parent):
def echo(self):
super().echo()
print("in Child")
```
I've seen code that passes 2 parameters to `super()`. In that case, the signature looks somehing like `super(subClass, instance)` where `subClass` is the sub class calling `super()` from, and `instance` is the instance the call being made from, ie `self`. So in the above example, the `super()` line would become:
```py
super(Child, self).echo()
```
Looking at [python3 docs](https://docs.python.org/3/library/functions.html#super), these 2 use cases are the same when calling from inside of a class.
Is calling `super()` with 2 parameters completely deprecated as of python3? If this is only deprecated for calling overridden functions, can you show an example why they're needed for other cases?
I'm also interested to know why python needed those 2 arguments? Are they injected/evaluated when making `super()` calls in python3, or they're just not needed in that case?
|
2019/12/31
|
[
"https://Stackoverflow.com/questions/59538746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3411556/"
] |
If you don't pass the arguments, Python 3 makes an effort to provide them for you. It's a little kludgy, but it *usually* works. Essentially, it just assumes the first parameter to your method is `self` (the second argument to `super`), and when the class definition completes, it provides a virtual closure scope for any function that refers to `super` or `__class__` that defines `__class__` as the class you just defined, so no-arg `super()` can check the stack frame to find `__class__` as the first argument.
This usually works, but there are cases where it doesn't:
* In `staticmethod`s (since the first argument isn't actually the class), though `staticmethod`s aren't really supposed to participate in the inheritance hierarchy the same way, so that's not exactly unexpected.
* In functions that take `*args` as the first argument (which was the only safe way to implement any method that accepted arbitrary keyword arguments like `dict` subclasses prior to 3.8, when they introduced positional-only arguments).
* If the `super` call is in a nested scope, which can be implicit, e.g. a generator expression, or comprehension of any kind (`list`, `set`, `dict`), since the nested scope isn't directly attached to the class, so it doesn't get the `__class__` defining magic that methods attached to the class itself get.
There are also rare cases where you might want to explicitly bypass a particular class for resolving the parent method, in which case you'd need to explicitly pass a different class from later in the MRO than the one it would pull by default. This is deep and terrible magic, so I don't recommend it, but I think I've had cause to do it once.
**All of those are relatively rare cases, so most of the time, for code purely targeting Python 3, you're fine using no-arg `super`, and only falling back to explicitly passing arguments when you *can't* use it for whatever reason.** No-arg `super` is cleaner, faster, and during live development can be more correct (if you replace `MyClass`, instances of the old version of the class will have the old version cached and no-arg `super` will continue to work, where looking it up manually in your globals would find the new version of the class and explode), so use it whenever you can.
|
In Python 3, `super()` with zero arguments is already the shortcut for `super(__class__, self)`. See [PEP3135](https://www.python.org/dev/peps/pep-3135/) for complete explanation.
This is not the case for Python 2, so I guess that most code examples you found were actually written for Python 2 (or Python2+3 compatible)
|
65,784,777
|
I have a python script which pushes data to another system. If it cannot push data for whatever reason then it will exit with non-zero status code otherwise it will not.
I am using my python script in my below shell script.
```
export NAME="${CI_COMMIT_REF_NAME//\//-}-1${CI_PIPELINE_IID}"
for environment in dev stage; do
FILE_NAME="${NAME}-${environment}.tgz";
python helper.py push ${environment} master ${FILE_NAME};
python helper.py push ${environment} slave ${FILE_NAME};
done
```
As of now if any one python line fails for any one environment then it doesn't move forward to the next iteration at all (or if first python line fails then it doesn't run second python line) but I want to run all iterations of my for loop and also run second python line if first one fails for whatever reason.
Is there any way I can run all iterations of my for loop irrespective of whether my python script fails for any environment or not and also run second python line if previous one fail and then at the end it should fail if exit status code is non-zero (after running everything) after running everything.
Is this possible to do? Basically somehow I need to store exit code of all the possible python line executions (total 4) and then exit at the end later on.
|
2021/01/19
|
[
"https://Stackoverflow.com/questions/65784777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14431930/"
] |
Use a conditional operator to set a variable.
```
failed=false
for environment in dev stage; do
FILE_NAME="${NAME}-${environment}.tgz";
python helper.py push ${environment} master "${FILE_NAME}" || failed=true
python helper.py push ${environment} slave "${FILE_NAME}" || failed=true
done
if [ "$failed" = true ]
then
exit 1
fi
```
BTW, you probably don't need to export `NAME`. Exporting is only needed if a child process uses the variable, not for variables uses within the script itself.
|
>
> Basically somehow I need to store exit code of all the possible python line
>
>
>
Try this
```
declare -A result
for env in dev stage; do
FILE_NAME="$NAME-$env.tgz"
python helper.py push "$env" master "$FILE_NAME"; result["$FILE_NAME"]=$?
python helper.py push "$env" slave "$FILE_NAME"; result["$FILE_NAME"]=$?
done
For key in ${!result[@]}; do
echo "Exit code for $key is: ${result[$key]}"
((err+=${result[$key]}))
done
exit $err
```
|
44,771,837
|
I looked at some answers, including [this](https://stackoverflow.com/questions/37457277/remove-non-ascii-characters-from-csv-file-using-python) but none seem to answer my question.
Here are some example lines from CSV:
```
_id category
ObjectId(56266da778d34fdc048b470b) [{"group":"Home","id":"53cea0be763f4a6f4a8b459e","name":"Cleaning Services","name_singular":"Cleaning Service"}]
ObjectId(56266e0c78d34f22058b46de) [{"group":"Local","id":"5637a1b178d34f20158b464f","name":"Balloon Dí©cor","name_singular":"Balloon Dí©cor"}]
```
Here is my code:
```
import csv
import sys
from sys import argv
import json
def ReadCSV(csvfile):
with open('newCSVFile.csv','wb') as g:
filewriter = csv.writer(g) #, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
with open(csvfile, 'rb') as f:
reader = csv.reader(f) # ceate reader object
next(reader) # skip first row
for row in reader: #go trhough all the rows
listForExport = [] #initialize list that will have two items: id and list of categories
# ID section
vendorId = str(row[0]) #pull the raw vendor id out of the first column of the csv
vendorId = vendorId[9:33] # slice to remove objectdId lable and parenthases
listForExport.append(vendorId) #add evendor ID to first item in list
# categories section
tempCatList = [] #temporarly list of categories for scond item in listForExport
#this is line 41 where the error stems
categories = json.loads(row[1]) #create's a dict with the categoreis from a given row
for names in categories: # loop through the categorie names using the key 'name'
print names['name']
```
Here's what I get:
```
Cleaning Services
Traceback (most recent call last):
File "csvtesting.py", line 57, in <module>
ReadCSV(csvfile)
File "csvtesting.py", line 41, in ReadCSV
categories = json.loads(row[1]) #create's a dict with the categoreis from a given row
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 9-10: invalid continuation byte
```
So the code pulls out the fist category `Cleaning Services`, but then fails when we get to the non ascii characters.
How do I deal with this? I'm happy to just remove any non-ascii items.
|
2017/06/27
|
[
"https://Stackoverflow.com/questions/44771837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1472743/"
] |
As you open the input csv file in `rb` mode, I assume that you are using a Python2.x version. The good news is that you have no problem in the csv part because the csv reader will read plain bytes without trying to interpret them. But the `json` module will insist in decoding the text into unicode and by default uses utf8. As your input file is not utf8 encoded is chokes and raises a UnicodeDecodeError.
Latin1 has a nice property: the unicode value of any byte is just the value of the byte, so you are sure to decode anything - whether it makes sense then depend of actual encoding being Latin1...
So you could just do:
```
categories = json.loads(row[1], encoding="Latin1")
```
Alternatively, if you want to ignore non ascii characters, you could first convert the byte string to unicode ignoring errors and only then load the json:
```
categories = json.loads(row[1].decode(errors='ignore)) # ignore all non ascii characters
```
|
Most probably you have certain non-ascii characters in your csv content.
```
import re
def remove_unicode(text):
if not text:
return text
if isinstance(text, str):
text = str(text.decode('ascii', 'ignore'))
else:
text = text.encode('ascii', 'ignore')
remove_ctrl_chars_regex = re.compile(r'[^\x20-\x7e]')
return remove_ctrl_chars_regex.sub('', text)
...
vendorId = remove_unicode(row[0])
...
categories = json.loads(remove_unicode(row[1]))
```
|
36,222,454
|
Trying to solve a problem I asked earlier that couldn't be done with postgres sql query. So I moved on to trying to find another way to do it.
Essentially - what I have directory lets call it **server** that has multiple CSV files in it with the UUID as the name of the csv.
```
localhost Server]$ tree
.
├── 503336947449727e6f99de97c0a22a98.csv
├── 503340d499169677a0ad8c97f4c75a6d.csv
├── 5033b53f9462e04e4665f7b18993193d.csv
└── 529993499c47a442cab8a6ccba00dee4.csv
```
Inside that CSV looks like the following:
```
2016-03-24 20:04:00,0.405
2016-03-24 20:05:00,0.769
2016-03-24 20:06:00,1.217
2016-03-24 20:07:00,1.355
2016-03-24 20:08:00,0.369
2016-03-24 20:09:00,0.338
2016-03-24 20:10:00,4.443
2016-03-24 20:11:00,1.195
2016-03-24 20:12:00,0.342
2016-03-24 20:13:00,0.351
2016-03-24 20:14:00,0.646
2016-03-24 20:15:00,0.879
```
Now I am trying to do a couple of things. First take a reference file that has all of the server names and UUID mappings in it.
servers.csv contains the following:
```
server3,50337efc58f19945205d89e9e5a8a3c1
desktop1,503336947449727e6f99de97c0a22a98
serv4,50330e69efa7c4470061855358d11610
server02,52f7df2e6641e211a33f7ff1ffd95514
small-8k,5033b53f9462e04e4665f7b18993193d
small-9k,5033af5b3616a679d20abe9001a7e897
large-64k,5033009b928e1903e3a39ae78a8e2d25
```
Ideally what i need to do is read the servers.csv file into an array then search through the folder and rename files to match the server name. So an example would be as follows:
```
localhost Server]$ tree
.
├── desktop1.csv
├── 503340d499169677a0ad8c97f4c75a6d.csv
├── small-8k.csv
└── 529993499c47a442cab8a6ccba00dee4.csv
```
Additionally - I need to add the headers to each file as the first row to look like this date,server.
So ideally the newly renamed CSV example desktop1.csv would look like the following:
Inside that CSV looks like the following:
```
date,desktop1
2016-03-24 20:04:00,0.405
2016-03-24 20:05:00,0.769
2016-03-24 20:06:00,1.217
2016-03-24 20:07:00,1.355
2016-03-24 20:08:00,0.369
2016-03-24 20:09:00,0.338
2016-03-24 20:10:00,4.443
2016-03-24 20:11:00,1.195
2016-03-24 20:12:00,0.342
2016-03-24 20:13:00,0.351
2016-03-24 20:14:00,0.646
2016-03-24 20:15:00,0.879
```
I have been struggling with this for a couple days... trying to develop which language would be the easiest to do from shell. My guess is a combination of awk and sed will get me there, but struggling with both.
I started researching on python which is a possible solution that could make the renaming possible with glob and all the files renamed. However not versed in python.
I was able to clean up some of the files that were part of the servers.csv file.
```
cut -d, -f1-2 VMInfo.csv | awk 'BEGIN{FS=OFS=","} {for (i=2;i<=NF;i++) gsub(/\-/,"",$i)} 1' | sed 's/"//g' > servers.csv
```
Any help would be greatly appreciated.
UPDATE - @Ed - this is what the output looks like for me.
```
localhost output]$ sh -x testin.sh
+ mv server server.bk
+ mkdir server
+ awk -F, '
NR==FNR { map[$2]=$1; next }
FNR==1 { close(out); out="server/"map[FILENAME]".csv"; print "date,"map[FILENAME] > out }
{ print > out }
' servers.csv server.bk/503336947449727e6f99de97c0a22a98.csv server.bk/503340d499169677a0ad8c97f4c75a6d.csv server.bk/50335a21c2507fc702864fa9ee7e2563.csv server.bk/50335ab3ab5411f88b77900736338bc6.csv server.bk/50338e29d3414fc4c04baa95772e8454.csv server.bk/5033c14e463120a8dcace7baaee17577.csv server.bk/5033c52713310df05c3ab04f6c4cf293.csv server.bk/5033d82b24982b4a8ac9fd73ec1880f7.csv server.bk/5033d9951846c1841437b437f5a97f0a.csv server.bk/5033db62b38f86605f0baeccae5e6cbc.csv server.bk/5033dc788480a7eab4fd0a586477f856.csv server.bk/5033f3c162b5e0e3bd01db1b3faa542d.csv server.bk/529993499c47a442cab8a6ccba00dee4.csv
```
Update @Ed - Still running into the same thing.
```
[localhost output]$ sh -x testin.sh
+ mv server server.bk
+ mkdir server
+ awk -F, '
NR==FNR { map[$2".csv"]=$1; next }
FNR==1 { close(out); out="server/"map[FILENAME]".csv"; print "date,"map[FILENAME] > out }
{ print > out }
' servers.csv server.bk/503336947449727e6f99de97c0a22a98.csv server.bk/503340d499169677a0ad8c97f4c75a6d.csv server.bk/50335a21c2507fc702864fa9ee7e2563.csv server.bk/50335ab3ab5411f88b77900736338bc6.csv server.bk/50338e29d3414fc4c04baa95772e8454.csv server.bk/5033c14e463120a8dcace7baaee17577.csv server.bk/5033c52713310df05c3ab04f6c4cf293.csv server.bk/5033d82b24982b4a8ac9fd73ec1880f7.csv server.bk/5033d9951846c1841437b437f5a97f0a.csv server.bk/5033db62b38f86605f0baeccae5e6cbc.csv server.bk/5033dc788480a7eab4fd0a586477f856.csv server.bk/5033f3c162b5e0e3bd01db1b3faa542d.csv server.bk/529993499c47a442cab8a6ccba00dee4.csv
[localhost output]$ cat servers.csv | grep 5033f3c162b5e0e3bd01db1b3faa542d
vpool02,5033f3c162b5e0e3bd01db1b3faa542d
```
It doesn't seem to be renaming the file to vpool02.csv
|
2016/03/25
|
[
"https://Stackoverflow.com/questions/36222454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5992247/"
] |
It sounds like you need something like this (untested):
```
mv server server.bk &&
mkdir server &&
awk -F, '
NR==FNR { map["server.bk/"$2".csv"]=$1; next }
FNR==1 { close(out); out="server/"map[FILENAME]".csv"; print "date,"map[FILENAME] > out }
{ print > out }
' servers.csv server.bk/*.csv
```
At the end of running the above, your original CSV files will be in the directory named "server.bk" which you can remove if you like by adding `&& rm -rf server.bk` at the end so it's only removed if the awk script succeeded.
If you're considering using a shell loop for this, then read <https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice> first.
|
Here's something I threw together in Python:
```
import csv
import os
import sys
# This is mostly for convenience. Python convention is that all caps
# are "constants", but there's nothing that enforces that
FILEPATH = 'servers'
SERVER_FILE = sys.argv[1] if len(sys.argv) > 1 else 'servers.csv'
with open(SERVER_FILE) as f:
reader = csv.reader(f)
for row in reader:
# This is called unpacking, the csv reader will read
# row as a list of 2 elements, since that's how many you
# have in your csv file. If you change your server.csv file
# format, this line will have to change.
name, uuid = row
try:
# Python needs the `\` line continuation marker to let this
# go over two lines. Note that there can be *no* spaces after
# the `\`
with open(os.path.join(FILEPATH, uuid+'.csv')) as infile,\
open(os.path.join(FILEPATH, name+'.csv'), 'w') as outfile:
# Note that I'm not creating a csv reader or writer here,
# because I'm assuming that there is no comma in the server
# name. If there is, you'd want to create a writer just to
# avoid having to manually escape the field.
outfile.write('date,'+name+'\n')
# After writing the header we can just write the contents
# of the csv file
outfile.write(infile.read())
# And now we delete the old file that has the wrong name
os.unlink(infile.name)
except FileNotFoundError:
# Technically this exception could also be raised if
# the path you were writing to did not exist, but
# since we're writing to the same directory, this should be fine.
print('Warning, no {}.csv file found'.format(uuid))
```
|
36,222,454
|
Trying to solve a problem I asked earlier that couldn't be done with postgres sql query. So I moved on to trying to find another way to do it.
Essentially - what I have directory lets call it **server** that has multiple CSV files in it with the UUID as the name of the csv.
```
localhost Server]$ tree
.
├── 503336947449727e6f99de97c0a22a98.csv
├── 503340d499169677a0ad8c97f4c75a6d.csv
├── 5033b53f9462e04e4665f7b18993193d.csv
└── 529993499c47a442cab8a6ccba00dee4.csv
```
Inside that CSV looks like the following:
```
2016-03-24 20:04:00,0.405
2016-03-24 20:05:00,0.769
2016-03-24 20:06:00,1.217
2016-03-24 20:07:00,1.355
2016-03-24 20:08:00,0.369
2016-03-24 20:09:00,0.338
2016-03-24 20:10:00,4.443
2016-03-24 20:11:00,1.195
2016-03-24 20:12:00,0.342
2016-03-24 20:13:00,0.351
2016-03-24 20:14:00,0.646
2016-03-24 20:15:00,0.879
```
Now I am trying to do a couple of things. First take a reference file that has all of the server names and UUID mappings in it.
servers.csv contains the following:
```
server3,50337efc58f19945205d89e9e5a8a3c1
desktop1,503336947449727e6f99de97c0a22a98
serv4,50330e69efa7c4470061855358d11610
server02,52f7df2e6641e211a33f7ff1ffd95514
small-8k,5033b53f9462e04e4665f7b18993193d
small-9k,5033af5b3616a679d20abe9001a7e897
large-64k,5033009b928e1903e3a39ae78a8e2d25
```
Ideally what i need to do is read the servers.csv file into an array then search through the folder and rename files to match the server name. So an example would be as follows:
```
localhost Server]$ tree
.
├── desktop1.csv
├── 503340d499169677a0ad8c97f4c75a6d.csv
├── small-8k.csv
└── 529993499c47a442cab8a6ccba00dee4.csv
```
Additionally - I need to add the headers to each file as the first row to look like this date,server.
So ideally the newly renamed CSV example desktop1.csv would look like the following:
Inside that CSV looks like the following:
```
date,desktop1
2016-03-24 20:04:00,0.405
2016-03-24 20:05:00,0.769
2016-03-24 20:06:00,1.217
2016-03-24 20:07:00,1.355
2016-03-24 20:08:00,0.369
2016-03-24 20:09:00,0.338
2016-03-24 20:10:00,4.443
2016-03-24 20:11:00,1.195
2016-03-24 20:12:00,0.342
2016-03-24 20:13:00,0.351
2016-03-24 20:14:00,0.646
2016-03-24 20:15:00,0.879
```
I have been struggling with this for a couple days... trying to develop which language would be the easiest to do from shell. My guess is a combination of awk and sed will get me there, but struggling with both.
I started researching on python which is a possible solution that could make the renaming possible with glob and all the files renamed. However not versed in python.
I was able to clean up some of the files that were part of the servers.csv file.
```
cut -d, -f1-2 VMInfo.csv | awk 'BEGIN{FS=OFS=","} {for (i=2;i<=NF;i++) gsub(/\-/,"",$i)} 1' | sed 's/"//g' > servers.csv
```
Any help would be greatly appreciated.
UPDATE - @Ed - this is what the output looks like for me.
```
localhost output]$ sh -x testin.sh
+ mv server server.bk
+ mkdir server
+ awk -F, '
NR==FNR { map[$2]=$1; next }
FNR==1 { close(out); out="server/"map[FILENAME]".csv"; print "date,"map[FILENAME] > out }
{ print > out }
' servers.csv server.bk/503336947449727e6f99de97c0a22a98.csv server.bk/503340d499169677a0ad8c97f4c75a6d.csv server.bk/50335a21c2507fc702864fa9ee7e2563.csv server.bk/50335ab3ab5411f88b77900736338bc6.csv server.bk/50338e29d3414fc4c04baa95772e8454.csv server.bk/5033c14e463120a8dcace7baaee17577.csv server.bk/5033c52713310df05c3ab04f6c4cf293.csv server.bk/5033d82b24982b4a8ac9fd73ec1880f7.csv server.bk/5033d9951846c1841437b437f5a97f0a.csv server.bk/5033db62b38f86605f0baeccae5e6cbc.csv server.bk/5033dc788480a7eab4fd0a586477f856.csv server.bk/5033f3c162b5e0e3bd01db1b3faa542d.csv server.bk/529993499c47a442cab8a6ccba00dee4.csv
```
Update @Ed - Still running into the same thing.
```
[localhost output]$ sh -x testin.sh
+ mv server server.bk
+ mkdir server
+ awk -F, '
NR==FNR { map[$2".csv"]=$1; next }
FNR==1 { close(out); out="server/"map[FILENAME]".csv"; print "date,"map[FILENAME] > out }
{ print > out }
' servers.csv server.bk/503336947449727e6f99de97c0a22a98.csv server.bk/503340d499169677a0ad8c97f4c75a6d.csv server.bk/50335a21c2507fc702864fa9ee7e2563.csv server.bk/50335ab3ab5411f88b77900736338bc6.csv server.bk/50338e29d3414fc4c04baa95772e8454.csv server.bk/5033c14e463120a8dcace7baaee17577.csv server.bk/5033c52713310df05c3ab04f6c4cf293.csv server.bk/5033d82b24982b4a8ac9fd73ec1880f7.csv server.bk/5033d9951846c1841437b437f5a97f0a.csv server.bk/5033db62b38f86605f0baeccae5e6cbc.csv server.bk/5033dc788480a7eab4fd0a586477f856.csv server.bk/5033f3c162b5e0e3bd01db1b3faa542d.csv server.bk/529993499c47a442cab8a6ccba00dee4.csv
[localhost output]$ cat servers.csv | grep 5033f3c162b5e0e3bd01db1b3faa542d
vpool02,5033f3c162b5e0e3bd01db1b3faa542d
```
It doesn't seem to be renaming the file to vpool02.csv
|
2016/03/25
|
[
"https://Stackoverflow.com/questions/36222454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5992247/"
] |
It sounds like you need something like this (untested):
```
mv server server.bk &&
mkdir server &&
awk -F, '
NR==FNR { map["server.bk/"$2".csv"]=$1; next }
FNR==1 { close(out); out="server/"map[FILENAME]".csv"; print "date,"map[FILENAME] > out }
{ print > out }
' servers.csv server.bk/*.csv
```
At the end of running the above, your original CSV files will be in the directory named "server.bk" which you can remove if you like by adding `&& rm -rf server.bk` at the end so it's only removed if the awk script succeeded.
If you're considering using a shell loop for this, then read <https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice> first.
|
```
IFS=,; while read a b;
do
mv $b $a;
sed -i "1i\date,$a" $a;
done < servers.csv
```
p.s. caveat emptor, there is mv and inplace edit. test with a copy first.
|
41,237,314
|
I have a python function (**pyfunc**):
```
def pyfunc(x):
...
return someString
```
I want to apply this function to every item in a mysql table column,
something like:
```
UPDATE tbl SET mycol=pyfunc(mycol);
```
This update includes tens of millions of records.
Is there an efficient way to do this?
**Note: I cannot rewrite this function in sql or any other programming language.**
|
2016/12/20
|
[
"https://Stackoverflow.com/questions/41237314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7319653/"
] |
Even simplier (but for php5.5 and php7):
```
$numery = array_column(
$command->queryAll(),
'phone_number'
);
```
|
Use below loop to get desired result
```
$numery = $command->queryAll();
$number_arr = array();
foreach($numery as $number)
{
array_push($number_arr,$number['phone_number']);
}
print_r($number_arr);
```
|
72,274,548
|
When I run any kubectl command I get following WARNING:
```
W0517 14:33:54.147340 46871 gcp.go:120] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.25+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
```
I have followed the instructions in [the link](https://cloud.google.com/blog/products/containers-kubernetes) several times but the WARNING keeps appearing making kubectl output uncomfortable to read.
OS:
```
cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=22.04
DISTRIB_CODENAME=jammy
DISTRIB_DESCRIPTION="Ubuntu 22.04 LTS"
```
kubectl version:
```
Client Version: v1.24.0
Kustomize Version: v4.5.4
```
gke-gcloud-auth-plugin:
```
Kubernetes v1.23.0-alpha+66064c62c6c23110c7a93faca5fba668018df732
```
gcloud version:
```
Google Cloud SDK 385.0.0
alpha 2022.05.06
beta 2022.05.06
bq 2.0.74
bundled-python3-unix 3.9.12
core 2022.05.06
gsutil 5.10
```
I "login" with:
```
gcloud init
```
and then:
```
gcloud container clusters get-credentials cluster_name --region my-region
```
finally:
```
myyser@mymachine:/$ k get pods -n madeupns
W0517 14:50:10.570103 50345 gcp.go:120] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.25+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
No resources found in madeupns namespace.
```
**How can I remove the WARNING or fix the problem?**
Removing my `.kube/config` and re-running get-credentials didn't work.
|
2022/05/17
|
[
"https://Stackoverflow.com/questions/72274548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1869399/"
] |
I fixed this problem by adding the correct export in `.bashrc`
```
export USE_GKE_GCLOUD_AUTH_PLUGIN=True
```
After sourcing `.bashrc` with `. ~/.bashrc` and reloading cluster config with:
```
gcloud container clusters get-credentials clustername
```
the warning dissapeared:
```
user@laptop:/$ k get svc -A
NAMESPACE NAME TYPE CLUSTER-IP EXTERNAL-IP
kube-system default-http-backend NodePort 10.10.13.157 <none>
kube-system kube-dns ClusterIP 10.10.0.10 <none>
kube-system kube-dns-upstream ClusterIP 10.10.13.92 <none>
kube-system metrics-server ClusterIP 10.10.2.191 <none>
```
|
Got a similar issue, while connecting to a fresh Kubernetes cluster having a version `v1.22.10-gke.600`
```
gcloud container clusters get-credentials my-cluster --zone europe-west6-b --project project
```
and got the below error, as seems like now its become error for the newer version
```
Fetching cluster endpoint and auth data.
CRITICAL: ACTION REQUIRED: gke-gcloud-auth-plugin, which is needed for continued use of kubectl, was not found or is not executable. Install gke-gcloud-auth-plugin for use with kubectl by following https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
```
[](https://i.stack.imgur.com/pPp6N.png)
**fix** that worked for me
```
gcloud components install gke-gcloud-auth-plugin
```
|
72,274,548
|
When I run any kubectl command I get following WARNING:
```
W0517 14:33:54.147340 46871 gcp.go:120] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.25+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
```
I have followed the instructions in [the link](https://cloud.google.com/blog/products/containers-kubernetes) several times but the WARNING keeps appearing making kubectl output uncomfortable to read.
OS:
```
cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=22.04
DISTRIB_CODENAME=jammy
DISTRIB_DESCRIPTION="Ubuntu 22.04 LTS"
```
kubectl version:
```
Client Version: v1.24.0
Kustomize Version: v4.5.4
```
gke-gcloud-auth-plugin:
```
Kubernetes v1.23.0-alpha+66064c62c6c23110c7a93faca5fba668018df732
```
gcloud version:
```
Google Cloud SDK 385.0.0
alpha 2022.05.06
beta 2022.05.06
bq 2.0.74
bundled-python3-unix 3.9.12
core 2022.05.06
gsutil 5.10
```
I "login" with:
```
gcloud init
```
and then:
```
gcloud container clusters get-credentials cluster_name --region my-region
```
finally:
```
myyser@mymachine:/$ k get pods -n madeupns
W0517 14:50:10.570103 50345 gcp.go:120] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.25+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
No resources found in madeupns namespace.
```
**How can I remove the WARNING or fix the problem?**
Removing my `.kube/config` and re-running get-credentials didn't work.
|
2022/05/17
|
[
"https://Stackoverflow.com/questions/72274548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1869399/"
] |
I fixed this problem by adding the correct export in `.bashrc`
```
export USE_GKE_GCLOUD_AUTH_PLUGIN=True
```
After sourcing `.bashrc` with `. ~/.bashrc` and reloading cluster config with:
```
gcloud container clusters get-credentials clustername
```
the warning dissapeared:
```
user@laptop:/$ k get svc -A
NAMESPACE NAME TYPE CLUSTER-IP EXTERNAL-IP
kube-system default-http-backend NodePort 10.10.13.157 <none>
kube-system kube-dns ClusterIP 10.10.0.10 <none>
kube-system kube-dns-upstream ClusterIP 10.10.13.92 <none>
kube-system metrics-server ClusterIP 10.10.2.191 <none>
```
|
You need to do the following things to avoid this warning message now and to avoid errors in the future.
1. Add the correct export in .bashrc. I am using .zshrc instead of .bashrc so added export in .zshrc
```
export USE_GKE_GCLOUD_AUTH_PLUGIN=True
```
2. Reload .bashrc
```
source ~/.bashrc
```
3. Update gcloud to the latest version.
```
gcloud components update
```
4. Run the following command. Replace the CLUSTER\_NAME with the name of your cluster. This will force the kubeconfig for this cluster to be updated to the Client-go Credential Plugin configuration.
```
gcloud container clusters get-credentials CLUSTER_NAME
```
5. Check kubeconfig file by enter the following command. Now you should be able to detect the changes(gke-gcloud-auth-plugin) in the kubeconfig file in the users section in the Root/Home directory
```
cat ~/.kube/config
```
**The reason behind this is:**
kubectl starting the version from v1.26 will no longer have a built-in authentication mechanism for GKE. So GKE users will need to download and use a separate authentication plugin to generate GKE-specific tokens to support the authentication of GKE. To get more details please read [here](https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke).
|
56,335,217
|
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from python by :
```
import pymysql
conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture')
```
then I download django frame and try to use it to connect mysql , what I do is :
create a my.cnf file content is :
```
[client]
database = shfuture
host = localhost
user = root
password = MYSQLTB
default-character-set = utf8
```
change settings.py to :
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': os.path.join(BASE_DIR, 'my.cnf'),
},
}
}
```
then run :
```
python manage.py runserver
```
but got a error :
```
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install the MySQL client?
```
Do I still need to install an addition MySQL in Django virtual env? if I can use the existing MySQL instead
|
2019/05/28
|
[
"https://Stackoverflow.com/questions/56335217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2031764/"
] |
Yes, of course.You need to install 'mysqlclient' package or 'mysql-connector-python' package, with pip.
|
I guess you dont have `mysqlclient` python library installed in virtual environment.
Since you are using Windows, you need to download and install `mysqlclient` python library from [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient)
|
56,335,217
|
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from python by :
```
import pymysql
conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture')
```
then I download django frame and try to use it to connect mysql , what I do is :
create a my.cnf file content is :
```
[client]
database = shfuture
host = localhost
user = root
password = MYSQLTB
default-character-set = utf8
```
change settings.py to :
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': os.path.join(BASE_DIR, 'my.cnf'),
},
}
}
```
then run :
```
python manage.py runserver
```
but got a error :
```
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install the MySQL client?
```
Do I still need to install an addition MySQL in Django virtual env? if I can use the existing MySQL instead
|
2019/05/28
|
[
"https://Stackoverflow.com/questions/56335217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2031764/"
] |
Yes, of course.You need to install 'mysqlclient' package or 'mysql-connector-python' package, with pip.
|
Yes you have to reinstall the mysql for django in the virtual environment again. For windows you can do:-
pip install django mysqlclient
|
56,335,217
|
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from python by :
```
import pymysql
conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture')
```
then I download django frame and try to use it to connect mysql , what I do is :
create a my.cnf file content is :
```
[client]
database = shfuture
host = localhost
user = root
password = MYSQLTB
default-character-set = utf8
```
change settings.py to :
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': os.path.join(BASE_DIR, 'my.cnf'),
},
}
}
```
then run :
```
python manage.py runserver
```
but got a error :
```
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install the MySQL client?
```
Do I still need to install an addition MySQL in Django virtual env? if I can use the existing MySQL instead
|
2019/05/28
|
[
"https://Stackoverflow.com/questions/56335217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2031764/"
] |
Yes, of course.You need to install 'mysqlclient' package or 'mysql-connector-python' package, with pip.
|
Basically you need to put the following code on top of both `manage.py` and `wsgi.py` like this:
```
#!/usr/bin/env python
import os
import sys
**import pymysql**
**pymysql.install\_as\_MySQLdb()**
# rest of the code
```
Also you need to ensure you have `pymysql` installed in your virtual environment.
**FYI:** Using pymysql might not work in **django>=2.2** properly. You will find some solution which might work, like mentioned in [**`this ticket`**](https://github.com/PyMySQL/PyMySQL/issues/790#issuecomment-489318466). Also, django does not support pymysql as mysql connector officially(ticket [**`#12500`**](https://code.djangoproject.com/ticket/12500), [**`#22391`**](https://code.djangoproject.com/ticket/22391)).
|
56,335,217
|
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from python by :
```
import pymysql
conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture')
```
then I download django frame and try to use it to connect mysql , what I do is :
create a my.cnf file content is :
```
[client]
database = shfuture
host = localhost
user = root
password = MYSQLTB
default-character-set = utf8
```
change settings.py to :
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': os.path.join(BASE_DIR, 'my.cnf'),
},
}
}
```
then run :
```
python manage.py runserver
```
but got a error :
```
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install the MySQL client?
```
Do I still need to install an addition MySQL in Django virtual env? if I can use the existing MySQL instead
|
2019/05/28
|
[
"https://Stackoverflow.com/questions/56335217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2031764/"
] |
Yes, of course.You need to install 'mysqlclient' package or 'mysql-connector-python' package, with pip.
|
Both *PyMySQL* and *MySQLdb* are db connectors. I assume that your django framework by default searches for MySQLdb and throws exception because it couldn't find one.
You can either install MySQLdb or follow @ruddra's answer on that. I would recommend you to go with @ruddra's answer incase of development machine. Because there are lot of issues you might(50/50 chances) face while installing and making MySQLdb to work properly.
Read [What is PyMySQL and how does it differ from MySQLdb? Can it affect Django deployment?](https://stackoverflow.com/questions/7224807/what-is-pymysql-and-how-does-it-differ-from-mysqldb-can-it-affect-django-deploy) to understand more on this.
|
56,335,217
|
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from python by :
```
import pymysql
conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture')
```
then I download django frame and try to use it to connect mysql , what I do is :
create a my.cnf file content is :
```
[client]
database = shfuture
host = localhost
user = root
password = MYSQLTB
default-character-set = utf8
```
change settings.py to :
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': os.path.join(BASE_DIR, 'my.cnf'),
},
}
}
```
then run :
```
python manage.py runserver
```
but got a error :
```
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install the MySQL client?
```
Do I still need to install an addition MySQL in Django virtual env? if I can use the existing MySQL instead
|
2019/05/28
|
[
"https://Stackoverflow.com/questions/56335217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2031764/"
] |
I guess you dont have `mysqlclient` python library installed in virtual environment.
Since you are using Windows, you need to download and install `mysqlclient` python library from [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient)
|
Basically you need to put the following code on top of both `manage.py` and `wsgi.py` like this:
```
#!/usr/bin/env python
import os
import sys
**import pymysql**
**pymysql.install\_as\_MySQLdb()**
# rest of the code
```
Also you need to ensure you have `pymysql` installed in your virtual environment.
**FYI:** Using pymysql might not work in **django>=2.2** properly. You will find some solution which might work, like mentioned in [**`this ticket`**](https://github.com/PyMySQL/PyMySQL/issues/790#issuecomment-489318466). Also, django does not support pymysql as mysql connector officially(ticket [**`#12500`**](https://code.djangoproject.com/ticket/12500), [**`#22391`**](https://code.djangoproject.com/ticket/22391)).
|
56,335,217
|
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from python by :
```
import pymysql
conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture')
```
then I download django frame and try to use it to connect mysql , what I do is :
create a my.cnf file content is :
```
[client]
database = shfuture
host = localhost
user = root
password = MYSQLTB
default-character-set = utf8
```
change settings.py to :
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': os.path.join(BASE_DIR, 'my.cnf'),
},
}
}
```
then run :
```
python manage.py runserver
```
but got a error :
```
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install the MySQL client?
```
Do I still need to install an addition MySQL in Django virtual env? if I can use the existing MySQL instead
|
2019/05/28
|
[
"https://Stackoverflow.com/questions/56335217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2031764/"
] |
I guess you dont have `mysqlclient` python library installed in virtual environment.
Since you are using Windows, you need to download and install `mysqlclient` python library from [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient)
|
Both *PyMySQL* and *MySQLdb* are db connectors. I assume that your django framework by default searches for MySQLdb and throws exception because it couldn't find one.
You can either install MySQLdb or follow @ruddra's answer on that. I would recommend you to go with @ruddra's answer incase of development machine. Because there are lot of issues you might(50/50 chances) face while installing and making MySQLdb to work properly.
Read [What is PyMySQL and how does it differ from MySQLdb? Can it affect Django deployment?](https://stackoverflow.com/questions/7224807/what-is-pymysql-and-how-does-it-differ-from-mysqldb-can-it-affect-django-deploy) to understand more on this.
|
56,335,217
|
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from python by :
```
import pymysql
conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture')
```
then I download django frame and try to use it to connect mysql , what I do is :
create a my.cnf file content is :
```
[client]
database = shfuture
host = localhost
user = root
password = MYSQLTB
default-character-set = utf8
```
change settings.py to :
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': os.path.join(BASE_DIR, 'my.cnf'),
},
}
}
```
then run :
```
python manage.py runserver
```
but got a error :
```
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install the MySQL client?
```
Do I still need to install an addition MySQL in Django virtual env? if I can use the existing MySQL instead
|
2019/05/28
|
[
"https://Stackoverflow.com/questions/56335217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2031764/"
] |
Yes you have to reinstall the mysql for django in the virtual environment again. For windows you can do:-
pip install django mysqlclient
|
Basically you need to put the following code on top of both `manage.py` and `wsgi.py` like this:
```
#!/usr/bin/env python
import os
import sys
**import pymysql**
**pymysql.install\_as\_MySQLdb()**
# rest of the code
```
Also you need to ensure you have `pymysql` installed in your virtual environment.
**FYI:** Using pymysql might not work in **django>=2.2** properly. You will find some solution which might work, like mentioned in [**`this ticket`**](https://github.com/PyMySQL/PyMySQL/issues/790#issuecomment-489318466). Also, django does not support pymysql as mysql connector officially(ticket [**`#12500`**](https://code.djangoproject.com/ticket/12500), [**`#22391`**](https://code.djangoproject.com/ticket/22391)).
|
56,335,217
|
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from python by :
```
import pymysql
conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture')
```
then I download django frame and try to use it to connect mysql , what I do is :
create a my.cnf file content is :
```
[client]
database = shfuture
host = localhost
user = root
password = MYSQLTB
default-character-set = utf8
```
change settings.py to :
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': os.path.join(BASE_DIR, 'my.cnf'),
},
}
}
```
then run :
```
python manage.py runserver
```
but got a error :
```
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install the MySQL client?
```
Do I still need to install an addition MySQL in Django virtual env? if I can use the existing MySQL instead
|
2019/05/28
|
[
"https://Stackoverflow.com/questions/56335217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2031764/"
] |
Yes you have to reinstall the mysql for django in the virtual environment again. For windows you can do:-
pip install django mysqlclient
|
Both *PyMySQL* and *MySQLdb* are db connectors. I assume that your django framework by default searches for MySQLdb and throws exception because it couldn't find one.
You can either install MySQLdb or follow @ruddra's answer on that. I would recommend you to go with @ruddra's answer incase of development machine. Because there are lot of issues you might(50/50 chances) face while installing and making MySQLdb to work properly.
Read [What is PyMySQL and how does it differ from MySQLdb? Can it affect Django deployment?](https://stackoverflow.com/questions/7224807/what-is-pymysql-and-how-does-it-differ-from-mysqldb-can-it-affect-django-deploy) to understand more on this.
|
36,188,632
|
this code works on the command line.
```
python -c 'import base64,sys; u,p=sys.argv[1:3]; print base64.encodestring("%s\x00%s\x00%s" % (u,u,p))' user pass
```
output is
dXNlcgB1c2VyAHBhc3M=
I am trying to get this to work in my script
```
test = base64.encodestring("{0}{0}{1}").format(acct_name,pw)
print test
```
output is
ezB9ezB9ezF9
anyone no what i am doing wrong ?
thank you.
|
2016/03/23
|
[
"https://Stackoverflow.com/questions/36188632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3954080/"
] |
You have a mistake in parenthesis. Instead of:
```
test = base64.encodestring("{0}{0}{1}").format(acct_name,pw)
```
(which first encodes "{0}{0}{1}" in base64 and **then** tries to substitute variables using `format`),
you should have
```
test = base64.encodestring("{0}{0}{1}".format(acct_name,pw))
```
(which first substitutes variables using `format` and **then** encodes in base64).
|
Thanks SZYM i am all set. This is the code that gets it to work
```
test = base64.encodestring("{0}\x00{0}\x00{1}".format(acct_name,pw))
```
Turns out the hex \x00 is needed so program getting the hash knows where username stops and password begins.
-ALF
|
14,800,708
|
I am using the PyScripter integrated development environment and taking courses using Python 2.7.
Why does `number = input("some input text")` immediately display the python input dialog when the program is ran? Wouldn't we have to execute it? Because really, it's just setting a variable to a python input. It never says to execute it? Is `number` not just any variable?
There's a mini-forum which the site that I go to has, but have not received an answer in 5 days, so I came here.
|
2013/02/10
|
[
"https://Stackoverflow.com/questions/14800708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2059278/"
] |
Indeed `number` is variable and nothing more. See [documentation on input()](http://docs.python.org/release/3.2/library/functions.html#input).
|
python is just kind off a simple language, it does not need variable declaration for example.
But it's better that it automatically asks your input instead that you have to write the code for starting the variable
|
69,633,739
|
I am pretty new to python, coming from Java and I want to update a variable in an initialized class
This is my full code
```
import datetime import time import threading
from tkinter import * from ibapi.client import EClient, TickAttribBidAsk from ibapi.wrapper import EWrapper, TickTypeEnum from ibapi.contract import Contract
class TestApp(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, self)
def tickPrice(self, reqId, tickType, price, attrib):
print("Tick price. Ticker Id:", reqId, "tickType:", TickTypeEnum.to_str(tickType), "Price:", price, end=' ')
def tickByTickBidAsk(self, reqId: int, time: int, bidPrice: float, askPrice: float, bidSize: int, askSize: int, tickAttribBidAsk: TickAttribBidAsk):
print(bidPrice)
tkinterApp.price1 = bidPrice
class Application:
def runTest(self):
app = TestApp()
app.connect("127.0.0.1", 7497, 0)
contract = Contract()
contract.symbol = "PROG"
contract.secType = "STK"
contract.currency = "USD"
contract.exchange = "SMART"
contract.primaryExchange = "NASDAQ"
time.sleep(1)
app.reqMarketDataType(1)
app.reqTickByTickData(19003, contract, "BidAsk", 0, True)
app.run()
def __init__(self):
t = threading.Thread(target=self.runTest)
t.start()
self.runTest()
class TkinterClass:
ibkrConnection = Application()
root = Tk()
root.title("test")
root.grid_columnconfigure((0, 1), weight=1)
titleTicker = Label(root, text="TICKER", bg='black', fg='white', width=100)
titleRating = Label(root, text="PRICE", bg='black', fg='white', width=100)
ticker1 = Label(root, text="PROG", bg='black', fg='white', width=100)
price1 = Label(root, text=0, bg='black', fg='white', width=100) # To be changed with every tick
titleTicker.grid(row=1, column=1)
titleRating.grid(row=1, column=2)
ticker1.grid(row=2, column=1)
price1.grid(row=2, column=2)
root.mainloop()
tkinterApp = TkinterClass()
```
The def `tickByTickBidAsk` is a callback and is called every ~2 sec
I want to update the `price1` variable in the class `TkinterClass`, but when I try to execute my code, the line `tkinterApp.price1 = bidPrice` gives me a name error: `TkinterClass is not defined`
This is probably a noob mistake I know :)
|
2021/10/19
|
[
"https://Stackoverflow.com/questions/69633739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12496189/"
] |
I played with tk a few years ago, this is how I structured my code. I make a tkinter window and connect to TWS from the tkinter class.
```
from tkinter import *
import threading
from ibapi import wrapper
from ibapi.client import EClient
from ibapi.utils import iswrapper #just for decorator
from ibapi.common import *
from ibapi.ticktype import *
from ibapi.contract import Contract
class TkWdow():
def __init__(self):
root = Tk()
frame = Frame(root)
frame.pack()
button = Button(frame, text="START", fg="green", command=self.start)
button.pack(side=LEFT)
button = Button(frame, text="ReqData", command=self.reqData)
button.pack(side=LEFT)
button = Button(frame, text="QUIT", fg="red", command=self.quit)
button.pack(side=LEFT)
self.output = Text(root, height=50, width=100)
self.output.pack(side=BOTTOM)
self.log("This is where output goes")
root.mainloop()
#root.destroy()
def start(self):
self.client = TestApp(self)
self.log("starting")
self.client.connect("127.0.0.1", 7497, clientId=123)
thread = threading.Thread(target = self.client.run)
thread.start()
def log(self, *args):
for s in args:
self.output.insert(END, str(s) + " ")
self.output.insert(END, "\n")
def quit(self):
self.log("quitting")
self.client.disconnect()
def reqData(self):
self.log("reqData")
cont = Contract()
cont.symbol = "cl"
cont.secType = "FUT"
cont.currency = "USD"
cont.exchange = "nymex"
cont.lastTradeDateOrContractMonth = "202112"
self.client.reqMktData(1, cont, "233", False, False, None)
def cancelMktData(self, reqId:TickerId):
super().cancelMktData(reqId)
self.log('sub cancel')
class TestApp(wrapper.EWrapper, EClient):
def __init__(self, wdow):
self.wdow = wdow
wrapper.EWrapper.__init__(self)
EClient.__init__(self, wrapper=self)
@iswrapper
def nextValidId(self, orderId:int):
self.wdow.log("setting nextValidOrderId: " , orderId)
self.nextValidOrderId = orderId
@iswrapper
def error(self, reqId:TickerId, errorCode:int, errorString:str):
self.wdow.log("Error. Id: " , reqId, " Code: " , errorCode , " Msg: " , errorString)
@iswrapper
def tickString(self, reqId:TickerId, tickType:TickType, value:str):
if tickType == TickTypeEnum.RT_VOLUME:
self.wdow.log(value)#price,size,time
#if __name__ == "__main__":
TkWdow()
```
|
It would probably help if you did something like this:
```
class TkinterClass:
def __init__(self):
self.ibkrConnection = Application()
self.root = Tk()
self.root.title("test")
self.root.grid_columnconfigure((0, 1), weight=1)
self.titleTicker = Label(root, text="TICKER", bg='black', fg='white', width=100)
self.titleRating = Label(root, text="PRICE", bg='black', fg='white', width=100)
self.ticker1 = Label(root, text="PROG", bg='black', fg='white', width=100)
self.price1 = Label(root, text=0, bg='black', fg='white', width=100) # To be changed with every tick
self.titleTicker.grid(row=1, column=1)
self.titleRating.grid(row=1, column=2)
self.ticker1.grid(row=2, column=1)
self.price1.grid(row=2, column=2)
def run(self):
self.root.mainloop()
tkinterApp = TkinterClass()
tkinterApp.run()
```
However, there are still issues:
1. Overwriting the `tkinterApp.price1` `Label` with a number value
To set the label, use: `tkinterApp.price1.config(str(value))` or use a `tkinter` `StringVar` to store the `price1` text, and use that `StringVar` as the `Label` value.
2. Using the `tkinterApp.price1` variable directly in two threads
Tk is likely to be unhappy if you muck about with Tk variables from a background thread. I'd suggest getting some kind of timer running in the foreground thread and poll a variable updated in the background, so you're only updating the Tk variable from the foreground.
Use `root.after(ms, callback)` to schedule a callback in the foreground (before invoking `root.mainloop()`).
I don't believe a `threading.Lock` is required when reading a Python value updated in another thread, but it would be safer to add a `lock()/unlock()` around both update and access logic to be sure.
|
56,697,108
|
I am trying to read a shapefile using geopandas, for which I used `gp.read_file`
```
import geopandas as gp
fl="M:/rathore/vic_5km/L2_data/L2_data/DAMSELFISH_distributions.shp"
data=gp.read_file(fl)
```
I am getting the following error:
`TypeError: invalid path: UnparsedPath(path='M:/rathore/vic_5km/L2_data/L2_data/DAMSELFISH_distributions.shp')`
The traceback to the problem is:
```
----> 1 data=gp.read_file(fl)
c:\python27\lib\site-packages\geopandas\io\file.pyc in read_file(filename, bbox, **kwargs)
75
76 with fiona_env():
---> 77 with reader(path_or_bytes, **kwargs) as features:
78
79 # In a future Fiona release the crs attribute of features will
c:\python27\lib\site-packages\fiona\fiona\env.pyc in wrapper(*args, **kwargs)
395 def wrapper(*args, **kwargs):
396 if local._env:
--> 397 return f(*args, **kwargs)
398 else:
399 if isinstance(args[0], str):
c:\python27\lib\site-packages\fiona\__init__.pyc in open(fp, mode, driver, schema, crs, encoding, layer, vfs, enabled_drivers, crs_wkt, **kwargs)
255 if mode in ('a', 'r'):
256 c = Collection(path, mode, driver=driver, encoding=encoding,
--> 257 layer=layer, enabled_drivers=enabled_drivers, **kwargs)
258 elif mode == 'w':
259 if schema:
c:\python27\lib\site-packages\fiona\fiona\collection.pyc in __init__(self, path, mode, driver, schema, crs, encoding, layer, vsi, archive, enabled_drivers, crs_wkt, ignore_fields, ignore_geometry, **kwargs)
54
55 if not isinstance(path, (string_types, Path)):
---> 56 raise TypeError("invalid path: %r" % path)
57 if not isinstance(mode, string_types) or mode not in ('r', 'w', 'a'):
58 raise TypeError("invalid mode: %r" % mode)
TypeError: invalid path: UnparsedPath(path='M:/rathore/vic_5km/L2_data/L2_data/DAMSELFISH_distributions.shp')
```
There is some problem with fiona I guess but I do not have much idea about.
I have installed `fiona 1.8.6` and `geopandas 0.5.0` version installed in my system. I am using python 2.7
|
2019/06/21
|
[
"https://Stackoverflow.com/questions/56697108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10705248/"
] |
After so many tries, I have created an [issue](https://issuetracker.google.com/issues/135865377) on Google Issue Tracker under [component](https://issuetracker.google.com/issues?q=componentid:409906), also submitted the code sample to the team and they replied as:
>
> Your Worker is package protected, and hence we cannot instantiate it using the default WorkerFactory.
>
>
>
If you looked at Logcat, you would see something like:
```
2019-06-24 10:49:18.501 14687-14786/com.example.workmanager.periodicworksample E/WM-WorkerFactory: Could not instantiate com.example.workmanager.periodicworksample.MyWorker
java.lang.IllegalAccessException: java.lang.Class<com.example.workmanager.periodicworksample.MyWorker> is not accessible from java.lang.Class<androidx.work.WorkerFactory>
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at androidx.work.WorkerFactory.createWorkerWithDefaultFallback(WorkerFactory.java:97)
at androidx.work.impl.WorkerWrapper.runWorker(WorkerWrapper.java:228)
at androidx.work.impl.WorkerWrapper.run(WorkerWrapper.java:127)
at androidx.work.impl.utils.SerialExecutor$Task.run(SerialExecutor.java:75)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
2019-06-24 10:49:18.501 14687-14786/com.example.workmanager.periodicworksample E/WM-WorkerWrapper: Could not create Worker com.example.workmanager.periodicworksample.MyWorker
```
>
> Your Worker needs to be public
>
>
>
And by making My Worker class public I got resolved the issue.
Reference of Google's Reply on the issue:
<https://issuetracker.google.com/issues/135865377#comment4>
|
This seems something similar to what has already been reported on some devices from this OEM. Here's a similar bug on [WorkManager's issuetracker](https://issuetracker.google.com/113676489), there's not much that WorkManager can do in these cases.
As commented in this bug:
>
> ...if a device manufacturer has decided to modify stock Android to force-stop the app, WorkManager will stop working (as will JobScheduler, alarms, broadcast receivers, etc.). There is no way to work around this. Some device manufacturers do this, unfortunately, so in those cases WorkManager will stop working until the next time the app is launched.
>
>
>
Your best option is to open a [new issue](https://issuetracker.google.com/issues/new?component=409906&template=1094197) adding some details and possibly a small sample to reproduce the issue.
|
56,697,108
|
I am trying to read a shapefile using geopandas, for which I used `gp.read_file`
```
import geopandas as gp
fl="M:/rathore/vic_5km/L2_data/L2_data/DAMSELFISH_distributions.shp"
data=gp.read_file(fl)
```
I am getting the following error:
`TypeError: invalid path: UnparsedPath(path='M:/rathore/vic_5km/L2_data/L2_data/DAMSELFISH_distributions.shp')`
The traceback to the problem is:
```
----> 1 data=gp.read_file(fl)
c:\python27\lib\site-packages\geopandas\io\file.pyc in read_file(filename, bbox, **kwargs)
75
76 with fiona_env():
---> 77 with reader(path_or_bytes, **kwargs) as features:
78
79 # In a future Fiona release the crs attribute of features will
c:\python27\lib\site-packages\fiona\fiona\env.pyc in wrapper(*args, **kwargs)
395 def wrapper(*args, **kwargs):
396 if local._env:
--> 397 return f(*args, **kwargs)
398 else:
399 if isinstance(args[0], str):
c:\python27\lib\site-packages\fiona\__init__.pyc in open(fp, mode, driver, schema, crs, encoding, layer, vfs, enabled_drivers, crs_wkt, **kwargs)
255 if mode in ('a', 'r'):
256 c = Collection(path, mode, driver=driver, encoding=encoding,
--> 257 layer=layer, enabled_drivers=enabled_drivers, **kwargs)
258 elif mode == 'w':
259 if schema:
c:\python27\lib\site-packages\fiona\fiona\collection.pyc in __init__(self, path, mode, driver, schema, crs, encoding, layer, vsi, archive, enabled_drivers, crs_wkt, ignore_fields, ignore_geometry, **kwargs)
54
55 if not isinstance(path, (string_types, Path)):
---> 56 raise TypeError("invalid path: %r" % path)
57 if not isinstance(mode, string_types) or mode not in ('r', 'w', 'a'):
58 raise TypeError("invalid mode: %r" % mode)
TypeError: invalid path: UnparsedPath(path='M:/rathore/vic_5km/L2_data/L2_data/DAMSELFISH_distributions.shp')
```
There is some problem with fiona I guess but I do not have much idea about.
I have installed `fiona 1.8.6` and `geopandas 0.5.0` version installed in my system. I am using python 2.7
|
2019/06/21
|
[
"https://Stackoverflow.com/questions/56697108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10705248/"
] |
This seems something similar to what has already been reported on some devices from this OEM. Here's a similar bug on [WorkManager's issuetracker](https://issuetracker.google.com/113676489), there's not much that WorkManager can do in these cases.
As commented in this bug:
>
> ...if a device manufacturer has decided to modify stock Android to force-stop the app, WorkManager will stop working (as will JobScheduler, alarms, broadcast receivers, etc.). There is no way to work around this. Some device manufacturers do this, unfortunately, so in those cases WorkManager will stop working until the next time the app is launched.
>
>
>
Your best option is to open a [new issue](https://issuetracker.google.com/issues/new?component=409906&template=1094197) adding some details and possibly a small sample to reproduce the issue.
|
On Oneplus devices turn off battery optimization. Go to phone setting --> battery--> bettery optimization --> search your app --> turn off batter optimization.
Workmanager works properly. Compay's just mesh up with Android custom Os just to increase their battery back.
|
56,697,108
|
I am trying to read a shapefile using geopandas, for which I used `gp.read_file`
```
import geopandas as gp
fl="M:/rathore/vic_5km/L2_data/L2_data/DAMSELFISH_distributions.shp"
data=gp.read_file(fl)
```
I am getting the following error:
`TypeError: invalid path: UnparsedPath(path='M:/rathore/vic_5km/L2_data/L2_data/DAMSELFISH_distributions.shp')`
The traceback to the problem is:
```
----> 1 data=gp.read_file(fl)
c:\python27\lib\site-packages\geopandas\io\file.pyc in read_file(filename, bbox, **kwargs)
75
76 with fiona_env():
---> 77 with reader(path_or_bytes, **kwargs) as features:
78
79 # In a future Fiona release the crs attribute of features will
c:\python27\lib\site-packages\fiona\fiona\env.pyc in wrapper(*args, **kwargs)
395 def wrapper(*args, **kwargs):
396 if local._env:
--> 397 return f(*args, **kwargs)
398 else:
399 if isinstance(args[0], str):
c:\python27\lib\site-packages\fiona\__init__.pyc in open(fp, mode, driver, schema, crs, encoding, layer, vfs, enabled_drivers, crs_wkt, **kwargs)
255 if mode in ('a', 'r'):
256 c = Collection(path, mode, driver=driver, encoding=encoding,
--> 257 layer=layer, enabled_drivers=enabled_drivers, **kwargs)
258 elif mode == 'w':
259 if schema:
c:\python27\lib\site-packages\fiona\fiona\collection.pyc in __init__(self, path, mode, driver, schema, crs, encoding, layer, vsi, archive, enabled_drivers, crs_wkt, ignore_fields, ignore_geometry, **kwargs)
54
55 if not isinstance(path, (string_types, Path)):
---> 56 raise TypeError("invalid path: %r" % path)
57 if not isinstance(mode, string_types) or mode not in ('r', 'w', 'a'):
58 raise TypeError("invalid mode: %r" % mode)
TypeError: invalid path: UnparsedPath(path='M:/rathore/vic_5km/L2_data/L2_data/DAMSELFISH_distributions.shp')
```
There is some problem with fiona I guess but I do not have much idea about.
I have installed `fiona 1.8.6` and `geopandas 0.5.0` version installed in my system. I am using python 2.7
|
2019/06/21
|
[
"https://Stackoverflow.com/questions/56697108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10705248/"
] |
After so many tries, I have created an [issue](https://issuetracker.google.com/issues/135865377) on Google Issue Tracker under [component](https://issuetracker.google.com/issues?q=componentid:409906), also submitted the code sample to the team and they replied as:
>
> Your Worker is package protected, and hence we cannot instantiate it using the default WorkerFactory.
>
>
>
If you looked at Logcat, you would see something like:
```
2019-06-24 10:49:18.501 14687-14786/com.example.workmanager.periodicworksample E/WM-WorkerFactory: Could not instantiate com.example.workmanager.periodicworksample.MyWorker
java.lang.IllegalAccessException: java.lang.Class<com.example.workmanager.periodicworksample.MyWorker> is not accessible from java.lang.Class<androidx.work.WorkerFactory>
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at androidx.work.WorkerFactory.createWorkerWithDefaultFallback(WorkerFactory.java:97)
at androidx.work.impl.WorkerWrapper.runWorker(WorkerWrapper.java:228)
at androidx.work.impl.WorkerWrapper.run(WorkerWrapper.java:127)
at androidx.work.impl.utils.SerialExecutor$Task.run(SerialExecutor.java:75)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
2019-06-24 10:49:18.501 14687-14786/com.example.workmanager.periodicworksample E/WM-WorkerWrapper: Could not create Worker com.example.workmanager.periodicworksample.MyWorker
```
>
> Your Worker needs to be public
>
>
>
And by making My Worker class public I got resolved the issue.
Reference of Google's Reply on the issue:
<https://issuetracker.google.com/issues/135865377#comment4>
|
On Oneplus devices turn off battery optimization. Go to phone setting --> battery--> bettery optimization --> search your app --> turn off batter optimization.
Workmanager works properly. Compay's just mesh up with Android custom Os just to increase their battery back.
|
6,548,996
|
Eventhough I write in python I think the abstract concept is more interesting to me and others. So pseudocode please if you like :)
I have a list with items from one of my classes. Lets do it with strings and numbers here, it really doesn't matter. Its nested to any depth. (Its not really a list but a container class which is based on a list.)
**Example**:
*[1, 2, 3, ['a', 'b', 'c'] 4 ['d', 'e', [100, 200, 300]] 5, ['a', 'b', 'c'], 6]*
Note that both ['a', 'b', 'c'] are really the same container. If you change one you change the other.
The containers and items can be edited, items inserted and most important containers can be used multiple times. To avoid redundancy its not possible to flatten the list (I think!) because you loose the ability to insert items in one container and it automatically appears in all other containers.
**The Problem:** For the frontend (just commandline with the python "cmd" module) I want to navigate through this structure with a cursor which always points to the current item so it can be read or edited.
The cursor can go left and right (users point of view) and should behave like the list is not a nested list but a flat one.
For a human this is super easy to do. You just pretend that in this list above the sublists don't exist and simply go from left to right and back.
For example if you are at the position of "3" in the list above and go right you get 'a' as next item, then 'b', 'c', and then "4" etc.
Or if you go right from the "300" you get the "5" next.
And backwards:
If you go left from "6" the next is 'c'. If you go left from "5" its "300".
So how do I do that in principle? I have one approach here but its wrong and the question is already so long that I fear most people will not read it :(. I can post it later.
P.S.
Even if its hard to resist: The answer to this question is not "Why do you want to do this, why do you organize your data this way, why don't you [flatten the list| something out of my imagination] first? The problem is exactly what I've described here, nothing else. The data is structured by the nature of the problem this way.
|
2011/07/01
|
[
"https://Stackoverflow.com/questions/6548996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/824997/"
] |
One solution would be to store current index and/or depth information and use it to traverse the nested list. But that seems like a solution that would do a lot of complicated forking -- testing for ends of lists, and so on. Instead, I came up with a compromise. Instead of flattening the list of lists, I created a generator that creates a flat list of indices into the list of lists:
```
def enumerate_nested(nested, indices):
for i, item in enumerate(nested):
if isinstance(item, collections.Iterable) and not isinstance(item, basestring):
for new_indices in enumerate_nested(item, indices + (i,)):
yield new_indices
else:
yield indices + (i,)
```
Then a simple function that extracts an innermost item from the list of lists based on an index tuple:
```
def tuple_index(nested_list, index_tuple):
for i in index_tuple:
nested_list = nested_list[i]
return nested_list
```
Now all you have to do is traverse the flat index list, in whatever way you like.
```
>>> indices = list(enumerate_nested(l, tuple()))
>>> print l
[1, 2, 3, ['a', 'b', 'c'], 4, ['d', 'e', [100, 200, 300]], 5, ['a', 'b', 'c'], 6]
>>> for i in indices:
... print tuple_index(l, i),
...
1 2 3 a b c 4 d e 100 200 300 5 a b c 6
```
---
Since this answer was accepted for the stack-based solution that I posted on ideone in the comments, and since it's preferable not to use external pastebins for answer code, please note that [this answer](https://stackoverflow.com/questions/6558365/convert-list-of-positions-4-1-2-of-arbitrary-length-to-an-index-for-a-nested/6618179#6618179) also contains my stack-based solution.
|
Essentially I would base my own solution on recursion. I would extend the container class with the following:
1. `cursor_position` - Property that stores the index of the highlighted element (or the element that contains the element that contains the highlighted element, or any level of recursion beyond that).
2. `repr_with_cursor` - This method should return a printable version of the container's content, already highlighting the item currently selected.
3. `mov_right` - This method should be invoked when the cursor move right. Returns the new index of the cursor within the element or `None` if the cursor falls "outside" the current container (if you move past hte last element in the container.
4. `mov_left` - Idem, but towards the left.
The way the recursion should work, is that for each method, depending of the *type* of the highlighted method you should have two different behaviours:
* if the cursor is on a **container** it should invoke the method of the "pointed" container.
* if the cursor is on a **non-container** it should perform the 'real thing'.
**EDIT**
I had a spare half an hour so I threw together an example class that implements my idea. It' not feature complete (for example it doesn't handle well when it reaches the either end of the largest container, and requires each instance of the class to be used only once in the largest sequence) but it works enough to demonstrate the concept. **I shall repeat before people comments on that: this is proof-of-concept code, it's not in any way ready to be used!**
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class C(list):
def __init__(self, *args):
self.cursor_position = None
super(C, self).__init__(*args)
def _pointed(self):
'''Return currently pointed item'''
if self.cursor_position == None:
return None
return self[self.cursor_position]
def _recursable(self):
'''Return True if pointed item is a container [C class]'''
return (type(self._pointed()) == C)
def init_pointer(self, end):
'''
Recursively set the pointers of containers in a way to point to the
first non-container item of the nested hierarchy.
'''
assert end in ('left', 'right')
val = 0 if end == 'left' else len(self)-1
self.cursor_position = val
if self._recursable():
self.pointed._init_pointer(end)
def repr_with_cursor(self):
'''
Return a representation of the container with highlighted item.
'''
composite = '['
for i, elem in enumerate(self):
if type(elem) == C:
composite += elem.repr_with_cursor()
else:
if i != self.cursor_position:
composite += str(elem)
else:
composite += '**' + str(elem) + '**'
if i != len(self)-1:
composite += ', '
composite += ']'
return composite
def mov_right(self):
'''
Move pointer to the right.
'''
if self._recursable():
if self._pointed().mov_right() == -1:
if self.cursor_position != len(self)-1:
self.cursor_position += 1
else:
if self.cursor_position != len(self)-1:
self.cursor_position += 1
if self._recursable():
self._pointed().init_pointer('left')
else:
self.cursor_position = None
return -1
def mov_left(self):
'''
Move pointer to the left.
'''
if self._recursable():
if self._pointed().mov_left() == -1:
if self.cursor_position != 0:
self.cursor_position -= 1
else:
if self.cursor_position != 0:
self.cursor_position -= 1
if self._recursable():
self._pointed().init_pointer('right')
else:
self.cursor_position = None
return -1
```
A simple test script:
```
# Create the nested structure
LevelOne = C(('I say',))
LevelTwo = C(('Hello', 'Bye', 'Ciao'))
LevelOne.append(LevelTwo)
LevelOne.append('!')
LevelOne.init_pointer('left')
# The container's content can be seen as both a regualar list or a
# special container.
print(LevelOne)
print(LevelOne.repr_with_cursor())
print('---')
# Showcase the effect of moving the cursor to right
for i in range(5):
print(LevelOne.repr_with_cursor())
LevelOne.mov_right()
print('---')
# Showcase the effect of moving the cursor to left
LevelOne.init_pointer('right')
for i in range(5):
print(LevelOne.repr_with_cursor())
LevelOne.mov_left()
```
It outputs:
```
['I say', ['Hello', 'Bye', 'Ciao'], '!']
[**I say**, [Hello, Bye, Ciao], !]
---
[**I say**, [Hello, Bye, Ciao], !]
[I say, [**Hello**, Bye, Ciao], !]
[I say, [Hello, **Bye**, Ciao], !]
[I say, [Hello, Bye, **Ciao**], !]
[I say, [Hello, Bye, Ciao], **!**]
---
[I say, [Hello, Bye, Ciao], **!**]
[I say, [Hello, Bye, **Ciao**], !]
[I say, [Hello, **Bye**, Ciao], !]
[I say, [**Hello**, Bye, Ciao], !]
[**I say**, [Hello, Bye, Ciao], !]
```
Fun problem! My favourite OS question of the day! :)
|
6,548,996
|
Eventhough I write in python I think the abstract concept is more interesting to me and others. So pseudocode please if you like :)
I have a list with items from one of my classes. Lets do it with strings and numbers here, it really doesn't matter. Its nested to any depth. (Its not really a list but a container class which is based on a list.)
**Example**:
*[1, 2, 3, ['a', 'b', 'c'] 4 ['d', 'e', [100, 200, 300]] 5, ['a', 'b', 'c'], 6]*
Note that both ['a', 'b', 'c'] are really the same container. If you change one you change the other.
The containers and items can be edited, items inserted and most important containers can be used multiple times. To avoid redundancy its not possible to flatten the list (I think!) because you loose the ability to insert items in one container and it automatically appears in all other containers.
**The Problem:** For the frontend (just commandline with the python "cmd" module) I want to navigate through this structure with a cursor which always points to the current item so it can be read or edited.
The cursor can go left and right (users point of view) and should behave like the list is not a nested list but a flat one.
For a human this is super easy to do. You just pretend that in this list above the sublists don't exist and simply go from left to right and back.
For example if you are at the position of "3" in the list above and go right you get 'a' as next item, then 'b', 'c', and then "4" etc.
Or if you go right from the "300" you get the "5" next.
And backwards:
If you go left from "6" the next is 'c'. If you go left from "5" its "300".
So how do I do that in principle? I have one approach here but its wrong and the question is already so long that I fear most people will not read it :(. I can post it later.
P.S.
Even if its hard to resist: The answer to this question is not "Why do you want to do this, why do you organize your data this way, why don't you [flatten the list| something out of my imagination] first? The problem is exactly what I've described here, nothing else. The data is structured by the nature of the problem this way.
|
2011/07/01
|
[
"https://Stackoverflow.com/questions/6548996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/824997/"
] |
I'd let the cursor have a stack of the indices of the arrays.
Examples:
```
[1, 2, 3, ['a', 'b', 'c'], 4 ]
```
If the cursor is at the 1 (at index 0), the cursor's position is [0].
It the cursor is at the 2 (at index 1), the cursor's position is [1].
If the cursor is at the 'a' (at index 3 at the outmost level and index 0 at the second level), the cursor's position would be [3, 0].
If the cursor is at the 'b' (at index 3 at the outmost level and index 1 at the second level), the cursor's position would be [3, 1].
etc.
To move the cursor right, you just increase the rightmost index in the position. So when you go from 'b' to 'c' it will increase from [3, 1] to [3, 2]. If the index then becomes out of range, you pop the rightmost value from the index stack and increase the rightmost value. So if you go from 'c' to 4, you go from [3, 2] to [4].
When moving, if you encounter a position with a nested array, you enter it. So if you go right from 3 (at index [2]), you enter the first element in the array ['a','b','c'], which is at index [3, 0].
Moving left would just do the inverse of moving right.
|
Essentially I would base my own solution on recursion. I would extend the container class with the following:
1. `cursor_position` - Property that stores the index of the highlighted element (or the element that contains the element that contains the highlighted element, or any level of recursion beyond that).
2. `repr_with_cursor` - This method should return a printable version of the container's content, already highlighting the item currently selected.
3. `mov_right` - This method should be invoked when the cursor move right. Returns the new index of the cursor within the element or `None` if the cursor falls "outside" the current container (if you move past hte last element in the container.
4. `mov_left` - Idem, but towards the left.
The way the recursion should work, is that for each method, depending of the *type* of the highlighted method you should have two different behaviours:
* if the cursor is on a **container** it should invoke the method of the "pointed" container.
* if the cursor is on a **non-container** it should perform the 'real thing'.
**EDIT**
I had a spare half an hour so I threw together an example class that implements my idea. It' not feature complete (for example it doesn't handle well when it reaches the either end of the largest container, and requires each instance of the class to be used only once in the largest sequence) but it works enough to demonstrate the concept. **I shall repeat before people comments on that: this is proof-of-concept code, it's not in any way ready to be used!**
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class C(list):
def __init__(self, *args):
self.cursor_position = None
super(C, self).__init__(*args)
def _pointed(self):
'''Return currently pointed item'''
if self.cursor_position == None:
return None
return self[self.cursor_position]
def _recursable(self):
'''Return True if pointed item is a container [C class]'''
return (type(self._pointed()) == C)
def init_pointer(self, end):
'''
Recursively set the pointers of containers in a way to point to the
first non-container item of the nested hierarchy.
'''
assert end in ('left', 'right')
val = 0 if end == 'left' else len(self)-1
self.cursor_position = val
if self._recursable():
self.pointed._init_pointer(end)
def repr_with_cursor(self):
'''
Return a representation of the container with highlighted item.
'''
composite = '['
for i, elem in enumerate(self):
if type(elem) == C:
composite += elem.repr_with_cursor()
else:
if i != self.cursor_position:
composite += str(elem)
else:
composite += '**' + str(elem) + '**'
if i != len(self)-1:
composite += ', '
composite += ']'
return composite
def mov_right(self):
'''
Move pointer to the right.
'''
if self._recursable():
if self._pointed().mov_right() == -1:
if self.cursor_position != len(self)-1:
self.cursor_position += 1
else:
if self.cursor_position != len(self)-1:
self.cursor_position += 1
if self._recursable():
self._pointed().init_pointer('left')
else:
self.cursor_position = None
return -1
def mov_left(self):
'''
Move pointer to the left.
'''
if self._recursable():
if self._pointed().mov_left() == -1:
if self.cursor_position != 0:
self.cursor_position -= 1
else:
if self.cursor_position != 0:
self.cursor_position -= 1
if self._recursable():
self._pointed().init_pointer('right')
else:
self.cursor_position = None
return -1
```
A simple test script:
```
# Create the nested structure
LevelOne = C(('I say',))
LevelTwo = C(('Hello', 'Bye', 'Ciao'))
LevelOne.append(LevelTwo)
LevelOne.append('!')
LevelOne.init_pointer('left')
# The container's content can be seen as both a regualar list or a
# special container.
print(LevelOne)
print(LevelOne.repr_with_cursor())
print('---')
# Showcase the effect of moving the cursor to right
for i in range(5):
print(LevelOne.repr_with_cursor())
LevelOne.mov_right()
print('---')
# Showcase the effect of moving the cursor to left
LevelOne.init_pointer('right')
for i in range(5):
print(LevelOne.repr_with_cursor())
LevelOne.mov_left()
```
It outputs:
```
['I say', ['Hello', 'Bye', 'Ciao'], '!']
[**I say**, [Hello, Bye, Ciao], !]
---
[**I say**, [Hello, Bye, Ciao], !]
[I say, [**Hello**, Bye, Ciao], !]
[I say, [Hello, **Bye**, Ciao], !]
[I say, [Hello, Bye, **Ciao**], !]
[I say, [Hello, Bye, Ciao], **!**]
---
[I say, [Hello, Bye, Ciao], **!**]
[I say, [Hello, Bye, **Ciao**], !]
[I say, [Hello, **Bye**, Ciao], !]
[I say, [**Hello**, Bye, Ciao], !]
[**I say**, [Hello, Bye, Ciao], !]
```
Fun problem! My favourite OS question of the day! :)
|
6,548,996
|
Eventhough I write in python I think the abstract concept is more interesting to me and others. So pseudocode please if you like :)
I have a list with items from one of my classes. Lets do it with strings and numbers here, it really doesn't matter. Its nested to any depth. (Its not really a list but a container class which is based on a list.)
**Example**:
*[1, 2, 3, ['a', 'b', 'c'] 4 ['d', 'e', [100, 200, 300]] 5, ['a', 'b', 'c'], 6]*
Note that both ['a', 'b', 'c'] are really the same container. If you change one you change the other.
The containers and items can be edited, items inserted and most important containers can be used multiple times. To avoid redundancy its not possible to flatten the list (I think!) because you loose the ability to insert items in one container and it automatically appears in all other containers.
**The Problem:** For the frontend (just commandline with the python "cmd" module) I want to navigate through this structure with a cursor which always points to the current item so it can be read or edited.
The cursor can go left and right (users point of view) and should behave like the list is not a nested list but a flat one.
For a human this is super easy to do. You just pretend that in this list above the sublists don't exist and simply go from left to right and back.
For example if you are at the position of "3" in the list above and go right you get 'a' as next item, then 'b', 'c', and then "4" etc.
Or if you go right from the "300" you get the "5" next.
And backwards:
If you go left from "6" the next is 'c'. If you go left from "5" its "300".
So how do I do that in principle? I have one approach here but its wrong and the question is already so long that I fear most people will not read it :(. I can post it later.
P.S.
Even if its hard to resist: The answer to this question is not "Why do you want to do this, why do you organize your data this way, why don't you [flatten the list| something out of my imagination] first? The problem is exactly what I've described here, nothing else. The data is structured by the nature of the problem this way.
|
2011/07/01
|
[
"https://Stackoverflow.com/questions/6548996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/824997/"
] |
One solution would be to store current index and/or depth information and use it to traverse the nested list. But that seems like a solution that would do a lot of complicated forking -- testing for ends of lists, and so on. Instead, I came up with a compromise. Instead of flattening the list of lists, I created a generator that creates a flat list of indices into the list of lists:
```
def enumerate_nested(nested, indices):
for i, item in enumerate(nested):
if isinstance(item, collections.Iterable) and not isinstance(item, basestring):
for new_indices in enumerate_nested(item, indices + (i,)):
yield new_indices
else:
yield indices + (i,)
```
Then a simple function that extracts an innermost item from the list of lists based on an index tuple:
```
def tuple_index(nested_list, index_tuple):
for i in index_tuple:
nested_list = nested_list[i]
return nested_list
```
Now all you have to do is traverse the flat index list, in whatever way you like.
```
>>> indices = list(enumerate_nested(l, tuple()))
>>> print l
[1, 2, 3, ['a', 'b', 'c'], 4, ['d', 'e', [100, 200, 300]], 5, ['a', 'b', 'c'], 6]
>>> for i in indices:
... print tuple_index(l, i),
...
1 2 3 a b c 4 d e 100 200 300 5 a b c 6
```
---
Since this answer was accepted for the stack-based solution that I posted on ideone in the comments, and since it's preferable not to use external pastebins for answer code, please note that [this answer](https://stackoverflow.com/questions/6558365/convert-list-of-positions-4-1-2-of-arbitrary-length-to-an-index-for-a-nested/6618179#6618179) also contains my stack-based solution.
|
I'd let the cursor have a stack of the indices of the arrays.
Examples:
```
[1, 2, 3, ['a', 'b', 'c'], 4 ]
```
If the cursor is at the 1 (at index 0), the cursor's position is [0].
It the cursor is at the 2 (at index 1), the cursor's position is [1].
If the cursor is at the 'a' (at index 3 at the outmost level and index 0 at the second level), the cursor's position would be [3, 0].
If the cursor is at the 'b' (at index 3 at the outmost level and index 1 at the second level), the cursor's position would be [3, 1].
etc.
To move the cursor right, you just increase the rightmost index in the position. So when you go from 'b' to 'c' it will increase from [3, 1] to [3, 2]. If the index then becomes out of range, you pop the rightmost value from the index stack and increase the rightmost value. So if you go from 'c' to 4, you go from [3, 2] to [4].
When moving, if you encounter a position with a nested array, you enter it. So if you go right from 3 (at index [2]), you enter the first element in the array ['a','b','c'], which is at index [3, 0].
Moving left would just do the inverse of moving right.
|
6,548,996
|
Eventhough I write in python I think the abstract concept is more interesting to me and others. So pseudocode please if you like :)
I have a list with items from one of my classes. Lets do it with strings and numbers here, it really doesn't matter. Its nested to any depth. (Its not really a list but a container class which is based on a list.)
**Example**:
*[1, 2, 3, ['a', 'b', 'c'] 4 ['d', 'e', [100, 200, 300]] 5, ['a', 'b', 'c'], 6]*
Note that both ['a', 'b', 'c'] are really the same container. If you change one you change the other.
The containers and items can be edited, items inserted and most important containers can be used multiple times. To avoid redundancy its not possible to flatten the list (I think!) because you loose the ability to insert items in one container and it automatically appears in all other containers.
**The Problem:** For the frontend (just commandline with the python "cmd" module) I want to navigate through this structure with a cursor which always points to the current item so it can be read or edited.
The cursor can go left and right (users point of view) and should behave like the list is not a nested list but a flat one.
For a human this is super easy to do. You just pretend that in this list above the sublists don't exist and simply go from left to right and back.
For example if you are at the position of "3" in the list above and go right you get 'a' as next item, then 'b', 'c', and then "4" etc.
Or if you go right from the "300" you get the "5" next.
And backwards:
If you go left from "6" the next is 'c'. If you go left from "5" its "300".
So how do I do that in principle? I have one approach here but its wrong and the question is already so long that I fear most people will not read it :(. I can post it later.
P.S.
Even if its hard to resist: The answer to this question is not "Why do you want to do this, why do you organize your data this way, why don't you [flatten the list| something out of my imagination] first? The problem is exactly what I've described here, nothing else. The data is structured by the nature of the problem this way.
|
2011/07/01
|
[
"https://Stackoverflow.com/questions/6548996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/824997/"
] |
One solution would be to store current index and/or depth information and use it to traverse the nested list. But that seems like a solution that would do a lot of complicated forking -- testing for ends of lists, and so on. Instead, I came up with a compromise. Instead of flattening the list of lists, I created a generator that creates a flat list of indices into the list of lists:
```
def enumerate_nested(nested, indices):
for i, item in enumerate(nested):
if isinstance(item, collections.Iterable) and not isinstance(item, basestring):
for new_indices in enumerate_nested(item, indices + (i,)):
yield new_indices
else:
yield indices + (i,)
```
Then a simple function that extracts an innermost item from the list of lists based on an index tuple:
```
def tuple_index(nested_list, index_tuple):
for i in index_tuple:
nested_list = nested_list[i]
return nested_list
```
Now all you have to do is traverse the flat index list, in whatever way you like.
```
>>> indices = list(enumerate_nested(l, tuple()))
>>> print l
[1, 2, 3, ['a', 'b', 'c'], 4, ['d', 'e', [100, 200, 300]], 5, ['a', 'b', 'c'], 6]
>>> for i in indices:
... print tuple_index(l, i),
...
1 2 3 a b c 4 d e 100 200 300 5 a b c 6
```
---
Since this answer was accepted for the stack-based solution that I posted on ideone in the comments, and since it's preferable not to use external pastebins for answer code, please note that [this answer](https://stackoverflow.com/questions/6558365/convert-list-of-positions-4-1-2-of-arbitrary-length-to-an-index-for-a-nested/6618179#6618179) also contains my stack-based solution.
|
While I like the idea of flattening the index list, that makes it impossible to modify the length of any sublist while iterating through the nested list. If this is not functionality you need, I would go with that.
Otherwise I would also implement a pointer into the list as a tuple of indices, and rely on recursion. To get you started, here's a class that implements `right()` and reading the value of the pointer via `deref()`. (I'm using `None` to represent a pointer beyond the end of a list.) I'll leave it as an exercise how to implement `left()` and assigning to elements. And you'll have to decide what behavior you want if you replace the element you're currently pointing at with another list. Good luck!
```
def islist(seq):
return isinstance(seq, (list, tuple))
class nav:
def __init__(self, seq):
self.seq = seq
self.ptr = self.first()
def __nonzero__(self):
return bool(self.ptr)
def right(self):
"""Advance the nav to the next position"""
self.ptr = self.next()
def first(self, seq=None):
"""pointer to the first element of a (possibly empty) sequence"""
if seq is None: seq = self.seq
if not islist(seq): return ()
return (0,) + self.first(seq[0]) if seq else None
def next(self, ptr=None, seq=None):
"""Return the next pointer"""
if ptr is None: ptr = self.ptr
if seq is None: seq = self.seq
subnext = None if len(ptr) == 1 else self.next(ptr[1:], seq[ptr[0]])
if subnext is not None: return (ptr[0],) + subnext
ind = ptr[0]+1
return None if ind >= len(seq) else (ind,) + self.first(seq[ind])
def deref(self, ptr=None, seq=None):
"""Dereference given pointer"""
if ptr is None: ptr = self.ptr
if seq is None: seq = self.seq
if not ptr: return None
subseq = seq[ptr[0]]
return subseq if len(ptr) == 1 else self.deref(ptr[1:], subseq)
abc = ['a', 'b', 'c']
a = [1, 2, 3, abc, 4, ['d', 'e', [100, 200, 300]], 5, abc, 6]
n = nav(a)
while n:
print n.ptr, n.deref()
n.right()
```
|
6,548,996
|
Eventhough I write in python I think the abstract concept is more interesting to me and others. So pseudocode please if you like :)
I have a list with items from one of my classes. Lets do it with strings and numbers here, it really doesn't matter. Its nested to any depth. (Its not really a list but a container class which is based on a list.)
**Example**:
*[1, 2, 3, ['a', 'b', 'c'] 4 ['d', 'e', [100, 200, 300]] 5, ['a', 'b', 'c'], 6]*
Note that both ['a', 'b', 'c'] are really the same container. If you change one you change the other.
The containers and items can be edited, items inserted and most important containers can be used multiple times. To avoid redundancy its not possible to flatten the list (I think!) because you loose the ability to insert items in one container and it automatically appears in all other containers.
**The Problem:** For the frontend (just commandline with the python "cmd" module) I want to navigate through this structure with a cursor which always points to the current item so it can be read or edited.
The cursor can go left and right (users point of view) and should behave like the list is not a nested list but a flat one.
For a human this is super easy to do. You just pretend that in this list above the sublists don't exist and simply go from left to right and back.
For example if you are at the position of "3" in the list above and go right you get 'a' as next item, then 'b', 'c', and then "4" etc.
Or if you go right from the "300" you get the "5" next.
And backwards:
If you go left from "6" the next is 'c'. If you go left from "5" its "300".
So how do I do that in principle? I have one approach here but its wrong and the question is already so long that I fear most people will not read it :(. I can post it later.
P.S.
Even if its hard to resist: The answer to this question is not "Why do you want to do this, why do you organize your data this way, why don't you [flatten the list| something out of my imagination] first? The problem is exactly what I've described here, nothing else. The data is structured by the nature of the problem this way.
|
2011/07/01
|
[
"https://Stackoverflow.com/questions/6548996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/824997/"
] |
I'd let the cursor have a stack of the indices of the arrays.
Examples:
```
[1, 2, 3, ['a', 'b', 'c'], 4 ]
```
If the cursor is at the 1 (at index 0), the cursor's position is [0].
It the cursor is at the 2 (at index 1), the cursor's position is [1].
If the cursor is at the 'a' (at index 3 at the outmost level and index 0 at the second level), the cursor's position would be [3, 0].
If the cursor is at the 'b' (at index 3 at the outmost level and index 1 at the second level), the cursor's position would be [3, 1].
etc.
To move the cursor right, you just increase the rightmost index in the position. So when you go from 'b' to 'c' it will increase from [3, 1] to [3, 2]. If the index then becomes out of range, you pop the rightmost value from the index stack and increase the rightmost value. So if you go from 'c' to 4, you go from [3, 2] to [4].
When moving, if you encounter a position with a nested array, you enter it. So if you go right from 3 (at index [2]), you enter the first element in the array ['a','b','c'], which is at index [3, 0].
Moving left would just do the inverse of moving right.
|
While I like the idea of flattening the index list, that makes it impossible to modify the length of any sublist while iterating through the nested list. If this is not functionality you need, I would go with that.
Otherwise I would also implement a pointer into the list as a tuple of indices, and rely on recursion. To get you started, here's a class that implements `right()` and reading the value of the pointer via `deref()`. (I'm using `None` to represent a pointer beyond the end of a list.) I'll leave it as an exercise how to implement `left()` and assigning to elements. And you'll have to decide what behavior you want if you replace the element you're currently pointing at with another list. Good luck!
```
def islist(seq):
return isinstance(seq, (list, tuple))
class nav:
def __init__(self, seq):
self.seq = seq
self.ptr = self.first()
def __nonzero__(self):
return bool(self.ptr)
def right(self):
"""Advance the nav to the next position"""
self.ptr = self.next()
def first(self, seq=None):
"""pointer to the first element of a (possibly empty) sequence"""
if seq is None: seq = self.seq
if not islist(seq): return ()
return (0,) + self.first(seq[0]) if seq else None
def next(self, ptr=None, seq=None):
"""Return the next pointer"""
if ptr is None: ptr = self.ptr
if seq is None: seq = self.seq
subnext = None if len(ptr) == 1 else self.next(ptr[1:], seq[ptr[0]])
if subnext is not None: return (ptr[0],) + subnext
ind = ptr[0]+1
return None if ind >= len(seq) else (ind,) + self.first(seq[ind])
def deref(self, ptr=None, seq=None):
"""Dereference given pointer"""
if ptr is None: ptr = self.ptr
if seq is None: seq = self.seq
if not ptr: return None
subseq = seq[ptr[0]]
return subseq if len(ptr) == 1 else self.deref(ptr[1:], subseq)
abc = ['a', 'b', 'c']
a = [1, 2, 3, abc, 4, ['d', 'e', [100, 200, 300]], 5, abc, 6]
n = nav(a)
while n:
print n.ptr, n.deref()
n.right()
```
|
46,942,411
|
I'm analyzing revision histories, using `git-archive` to get the files at a particular revision (see <https://stackoverflow.com/a/40811494/1168342>).
The approach works, but I'm trying to optimize for projects with many revisions. Much processing is wasted archiving (via tar) and back to a files in another directory (via tar again).
I'm looking for a way to do this without involving `tar`, something like a `git cp $revision $dest/`. Here's what I've explored so far:
* I could use the `git reset $revision --hard` approach with a file copy, but it renders parallelization of the analysis void, unless I create multiple copies of the repo (one for each thread/process).
* There is a [Java project using JGit called Doris](https://github.com/gingerswede/doris) that accomplishes this with low-level operations, but it breaks when there are weird files (e.g., links to other repos). As git has evolved, there are a lot of special cases, so I don't want to do this at a low-level if possible.
* I know there's a git API for Python, but its [archive feature](http://gitpython.readthedocs.io/en/stable/reference.html#module-git.repo.base) also uses tar. For the same reasons as above, I didn't want to code this at too low a level.
|
2017/10/25
|
[
"https://Stackoverflow.com/questions/46942411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1168342/"
] |
Use:
```
mkdir <path> &&
GIT_INDEX_FILE=<path>/.git git --work-tree=<path> checkout <revision> -- . &&
rm <path>/.git
```
The `git checkout` step will overwrite the index, so to make this parallelize well, we can just point the index file into the target. There's one file name that's pretty sure to be safe: `.git`!
(This is like a lighter weight version of `git worktree add` that also avoids recording the new extracted tree as an active work-tree.)
Edit to add a side note (I expect the OP is aware of this, but for future reference): note that `git archive` applies certain `.gitattributes` filters that this technique will not apply. In particular, `git checkout` will not obey `export-ignore` and `export-subst` directives.
|
In JGit the `ArchiveCommand` implements what `git archive` does and also provides several archive file formats out of the box. However, the `ArchiveCommand` can be extended with custom archive formats.
A custom format needs to implement the `Format` interface and register it with `ArchiveCommand::registerFormat`. Even though the corresponding API seems to be designed with a single output file in mind, it should be possible to output the contents to a directory.
|
4,234,823
|
I am trying to open a serial port with python. This is on Ubuntu. I import the openinterface.py and enter in this
```
ser = openinterface.CreateBot(com_port = "/dev/ttyUSB1", mode="full")
```
I get an error saying "unsupported operand types for -: 'str' and 'int'" I tried the same call with single quotes instead of double, and with no quotes at all.
How can I fix this? Or is there an alternative function to use? I only know the basics of Python so maybe its some small syntax thing I am not noticing? Any help would be appreciated, thanks.
|
2010/11/20
|
[
"https://Stackoverflow.com/questions/4234823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508530/"
] |
According to [this page in Russian](http://rus-linux.net/lib.php?name=/MyLDP/hard/irobot/irobot.html), there's a bug with the `openinterface.py` file that tries to subtract one from the port argument. It suggests making this change (removing the `- 1` on line 803) with `sed`:
```
sed -ie "803s/ - 1//" openinterface.py
```
Either try that, or see if there's an updated version of `openinterface.py`.
|
This is what you want if you are using python 3:
```
import serial #import pyserial lib
ser = serial.Serial("/dev/ttyS0", 9600) #specify your port and braudrate
data = ser.read() #read byte from serial device
print(data) #display the read byte
```
|
44,777,408
|
I want to mock a method of a class and use `wraps`, so that it is actually called, but I can inspect the arguments passed to it. I have seen at several places ([here](https://stackoverflow.com/questions/25608107/python-mock-patching-a-method-without-obstructing-implementation) for example) that the usual way to do that is as follows (adapted to show my point):
```
from unittest import TestCase
from unittest.mock import patch
class Potato(object):
def foo(self, n):
return self.bar(n)
def bar(self, n):
return n + 2
class PotatoTest(TestCase):
spud = Potato()
@patch.object(Potato, 'foo', wraps=spud.foo)
def test_something(self, mock):
forty_two = self.spud.foo(n=40)
mock.assert_called_once_with(n=40)
self.assertEqual(forty_two, 42)
```
However, this instantiates the class `Potato`, in order to bind the mock to the instance method `spud.foo`.
What I need is to mock the method `foo` in *all instances of `Potato`*, and wrap them around the original methods. I.e, I need the following:
```
from unittest import TestCase
from unittest.mock import patch
class Potato(object):
def foo(self, n):
return self.bar(n)
def bar(self, n):
return n + 2
class PotatoTest(TestCase):
@patch.object(Potato, 'foo', wraps=Potato.foo)
def test_something(self, mock):
self.spud = Potato()
forty_two = self.spud.foo(n=40)
mock.assert_called_once_with(n=40)
self.assertEqual(forty_two, 42)
```
This of course doesn't work. I get the error:
```
TypeError: foo() missing 1 required positional argument: 'self'
```
It works however if `wraps` is not used, so the problem is not in the mock itself, but in the way it calls the wrapped function. For example, this works (but of course I had to "fake" the returned value, because now `Potato.foo` is never actually run):
```
from unittest import TestCase
from unittest.mock import patch
class Potato(object):
def foo(self, n):
return self.bar(n)
def bar(self, n):
return n + 2
class PotatoTest(TestCase):
@patch.object(Potato, 'foo', return_value=42)#, wraps=Potato.foo)
def test_something(self, mock):
self.spud = Potato()
forty_two = self.spud.foo(n=40)
mock.assert_called_once_with(n=40)
self.assertEqual(forty_two, 42)
```
This works, but it does not run the original function, which I need to run because the return value is used elsewhere (and I cannot fake it from the test).
Can it be done?
**Note** The actual reason behind my needs is that I'm testing a rest api with webtest. From the tests I perform some wsgi requests to some paths, and my framework instantiates some classes and uses their methods to fulfill the request. I want to capture the parameters sent to those methods to do some `asserts` about them in my tests.
|
2017/06/27
|
[
"https://Stackoverflow.com/questions/44777408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1264820/"
] |
In short, you can't do this using `Mock` instances alone.
`patch.object` creates `Mock`'s for the specified instance (Potato), i.e. it replaces `Potato.foo` with a single Mock the moment it is called. Therefore, there is no way to pass instances to the `Mock` as the mock is created before any instances are. To my knowledge getting instance information to the `Mock` at runtime is also very difficult.
To illustrate:
```
from unittest.mock import MagicMock
class MyMock(MagicMock):
def __init__(self, *a, **kw):
super(MyMock, self).__init__(*a, **kw)
print('Created Mock instance a={}, kw={}'.format(a,kw))
with patch.object(Potato, 'foo', new_callable=MyMock, wrap=Potato.foo):
print('no instances created')
spud = Potato()
print('instance created')
```
The output is:
```
Created Mock instance a=(), kw={'name': 'foo', 'wrap': <function Potato.foo at 0x7f5d9bfddea0>}
no instances created
instance created
```
I would suggest monkey-patching your class in order to add the `Mock` to the correct location.
```
from unittest.mock import MagicMock
class PotatoTest(TestCase):
def test_something(self):
old_foo = Potato.foo
try:
mock = MagicMock(wraps=Potato.foo, return_value=42)
Potato.foo = lambda *a,**kw: mock(*a, **kw)
self.spud = Potato()
forty_two = self.spud.foo(n=40)
mock.assert_called_once_with(self.spud, n=40) # Now needs self instance
self.assertEqual(forty_two, 42)
finally:
Potato.foo = old_foo
```
Note that you using `called_with` is problematic as you are calling your functions with an instance.
|
Do you control creation of `Potato` instances, or at least have access to these instances after creating them? You should, else you'd not be able to check particular arg lists.
If so, you can wrap methods of individual instances using
```
spud = dig_out_a_potato()
with mock.patch.object(spud, "foo", wraps=spud.foo) as mock_spud:
# do your thing.
mock_spud.assert_called...
```
|
44,777,408
|
I want to mock a method of a class and use `wraps`, so that it is actually called, but I can inspect the arguments passed to it. I have seen at several places ([here](https://stackoverflow.com/questions/25608107/python-mock-patching-a-method-without-obstructing-implementation) for example) that the usual way to do that is as follows (adapted to show my point):
```
from unittest import TestCase
from unittest.mock import patch
class Potato(object):
def foo(self, n):
return self.bar(n)
def bar(self, n):
return n + 2
class PotatoTest(TestCase):
spud = Potato()
@patch.object(Potato, 'foo', wraps=spud.foo)
def test_something(self, mock):
forty_two = self.spud.foo(n=40)
mock.assert_called_once_with(n=40)
self.assertEqual(forty_two, 42)
```
However, this instantiates the class `Potato`, in order to bind the mock to the instance method `spud.foo`.
What I need is to mock the method `foo` in *all instances of `Potato`*, and wrap them around the original methods. I.e, I need the following:
```
from unittest import TestCase
from unittest.mock import patch
class Potato(object):
def foo(self, n):
return self.bar(n)
def bar(self, n):
return n + 2
class PotatoTest(TestCase):
@patch.object(Potato, 'foo', wraps=Potato.foo)
def test_something(self, mock):
self.spud = Potato()
forty_two = self.spud.foo(n=40)
mock.assert_called_once_with(n=40)
self.assertEqual(forty_two, 42)
```
This of course doesn't work. I get the error:
```
TypeError: foo() missing 1 required positional argument: 'self'
```
It works however if `wraps` is not used, so the problem is not in the mock itself, but in the way it calls the wrapped function. For example, this works (but of course I had to "fake" the returned value, because now `Potato.foo` is never actually run):
```
from unittest import TestCase
from unittest.mock import patch
class Potato(object):
def foo(self, n):
return self.bar(n)
def bar(self, n):
return n + 2
class PotatoTest(TestCase):
@patch.object(Potato, 'foo', return_value=42)#, wraps=Potato.foo)
def test_something(self, mock):
self.spud = Potato()
forty_two = self.spud.foo(n=40)
mock.assert_called_once_with(n=40)
self.assertEqual(forty_two, 42)
```
This works, but it does not run the original function, which I need to run because the return value is used elsewhere (and I cannot fake it from the test).
Can it be done?
**Note** The actual reason behind my needs is that I'm testing a rest api with webtest. From the tests I perform some wsgi requests to some paths, and my framework instantiates some classes and uses their methods to fulfill the request. I want to capture the parameters sent to those methods to do some `asserts` about them in my tests.
|
2017/06/27
|
[
"https://Stackoverflow.com/questions/44777408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1264820/"
] |
In short, you can't do this using `Mock` instances alone.
`patch.object` creates `Mock`'s for the specified instance (Potato), i.e. it replaces `Potato.foo` with a single Mock the moment it is called. Therefore, there is no way to pass instances to the `Mock` as the mock is created before any instances are. To my knowledge getting instance information to the `Mock` at runtime is also very difficult.
To illustrate:
```
from unittest.mock import MagicMock
class MyMock(MagicMock):
def __init__(self, *a, **kw):
super(MyMock, self).__init__(*a, **kw)
print('Created Mock instance a={}, kw={}'.format(a,kw))
with patch.object(Potato, 'foo', new_callable=MyMock, wrap=Potato.foo):
print('no instances created')
spud = Potato()
print('instance created')
```
The output is:
```
Created Mock instance a=(), kw={'name': 'foo', 'wrap': <function Potato.foo at 0x7f5d9bfddea0>}
no instances created
instance created
```
I would suggest monkey-patching your class in order to add the `Mock` to the correct location.
```
from unittest.mock import MagicMock
class PotatoTest(TestCase):
def test_something(self):
old_foo = Potato.foo
try:
mock = MagicMock(wraps=Potato.foo, return_value=42)
Potato.foo = lambda *a,**kw: mock(*a, **kw)
self.spud = Potato()
forty_two = self.spud.foo(n=40)
mock.assert_called_once_with(self.spud, n=40) # Now needs self instance
self.assertEqual(forty_two, 42)
finally:
Potato.foo = old_foo
```
Note that you using `called_with` is problematic as you are calling your functions with an instance.
|
Your question looks identical to [python mock - patching a method without obstructing implementation](https://stackoverflow.com/questions/25608107) to me. <https://stackoverflow.com/a/72446739/9230828> implements what you want (except that it uses a with statement instead of a decorator). `wrap_object.py`:
```
# Copyright (C) 2022, Benjamin Drung <bdrung@posteo.de>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import contextlib
import typing
import unittest.mock
@contextlib.contextmanager
def wrap_object(
target: object, attribute: str
) -> typing.Generator[unittest.mock.MagicMock, None, None]:
"""Wrap the named member on an object with a mock object.
wrap_object() can be used as a context manager. Inside the
body of the with statement, the attribute of the target is
wrapped with a :class:`unittest.mock.MagicMock` object. When
the with statement exits the patch is undone.
The instance argument 'self' of the wrapped attribute is
intentionally not logged in the MagicMock call. Therefore
wrap_object() can be used to check all calls to the object,
but not differentiate between different instances.
"""
mock = unittest.mock.MagicMock()
real_attribute = getattr(target, attribute)
def mocked_attribute(self, *args, **kwargs):
mock.__call__(*args, **kwargs)
return real_attribute(self, *args, **kwargs)
with unittest.mock.patch.object(target, attribute, mocked_attribute):
yield mock
```
Then you can write following unit test:
```py
from unittest import TestCase
from wrap_object import wrap_object
class Potato:
def foo(self, n):
return self.bar(n)
def bar(self, n):
return n + 2
class PotatoTest(TestCase):
def test_something(self):
with wrap_object(Potato, 'foo') as mock:
self.spud = Potato()
forty_two = self.spud.foo(n=40)
mock.assert_called_once_with(n=40)
self.assertEqual(forty_two, 42)
```
|
57,943,053
|
When EMR machine is trying to run a step that includes boto3 initialisation it sometimes get the following error:
`ValueError: Invalid endpoint: https://s3..amazonaws.com`
When I'm trying to set up a new machine it can suddenly work.
Attached the full error:
```
self.client = boto3.client("s3")
File "/usr/local/lib/python3.6/site-packages/boto3/__init__.py", line 83, in client
return _get_default_session().client(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/boto3/session.py", line 263, in client
aws_session_token=aws_session_token, config=config)
File "/usr/local/lib/python3.6/site-packages/botocore/session.py", line 861, in create_client
client_config=config, api_version=api_version)
File "/usr/local/lib/python3.6/site-packages/botocore/client.py", line 76, in create_client
verify, credentials, scoped_config, client_config, endpoint_bridge)
File "/usr/local/lib/python3.6/site-packages/botocore/client.py", line 285, in _get_client_args
verify, credentials, scoped_config, client_config, endpoint_bridge)
File "/usr/local/lib/python3.6/site-packages/botocore/args.py", line 79, in get_client_args
timeout=(new_config.connect_timeout, new_config.read_timeout))
File "/usr/local/lib/python3.6/site-packages/botocore/endpoint.py", line 297, in create_endpoint
raise ValueError("Invalid endpoint: %s" % endpoint_url)
ValueError: Invalid endpoint: https://s3..amazonaws.com
```
Any idea why it happens?
(Versions: boto3==1.7.29, botocore==1.10.29)
|
2019/09/15
|
[
"https://Stackoverflow.com/questions/57943053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6359988/"
] |
It looks like you have an invalid region.
[Check](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/setup-credentials.html) your ~/.aws/config
|
In my case, even though `~/.aws/config` had the region set,
```
$ cat ~/.aws/config
[default]
region = us-east-1
```
the env var `AWS_REGION` was set to an empty string
```
$ env | grep -i aws
AWS_REGION=
```
unset this env var and all was good again
```
$ unset AWS_REGION
$ aws sts get-caller-identity --output text --query Account
777***234534
```
(*apologies for posting on a really old question, it did pop up in a Google search*)
|
57,943,053
|
When EMR machine is trying to run a step that includes boto3 initialisation it sometimes get the following error:
`ValueError: Invalid endpoint: https://s3..amazonaws.com`
When I'm trying to set up a new machine it can suddenly work.
Attached the full error:
```
self.client = boto3.client("s3")
File "/usr/local/lib/python3.6/site-packages/boto3/__init__.py", line 83, in client
return _get_default_session().client(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/boto3/session.py", line 263, in client
aws_session_token=aws_session_token, config=config)
File "/usr/local/lib/python3.6/site-packages/botocore/session.py", line 861, in create_client
client_config=config, api_version=api_version)
File "/usr/local/lib/python3.6/site-packages/botocore/client.py", line 76, in create_client
verify, credentials, scoped_config, client_config, endpoint_bridge)
File "/usr/local/lib/python3.6/site-packages/botocore/client.py", line 285, in _get_client_args
verify, credentials, scoped_config, client_config, endpoint_bridge)
File "/usr/local/lib/python3.6/site-packages/botocore/args.py", line 79, in get_client_args
timeout=(new_config.connect_timeout, new_config.read_timeout))
File "/usr/local/lib/python3.6/site-packages/botocore/endpoint.py", line 297, in create_endpoint
raise ValueError("Invalid endpoint: %s" % endpoint_url)
ValueError: Invalid endpoint: https://s3..amazonaws.com
```
Any idea why it happens?
(Versions: boto3==1.7.29, botocore==1.10.29)
|
2019/09/15
|
[
"https://Stackoverflow.com/questions/57943053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6359988/"
] |
Set the region in your `~/.aws/credentials` or `~/.aws/config` files. You can set the region as an environment variable as well e.g.
In `bash`
```
export AWS_REGION="eu-west-2"
```
or in `Powershell`
```
$Env:AWS_REGION="eu-west-2"
```
|
In my case, even though `~/.aws/config` had the region set,
```
$ cat ~/.aws/config
[default]
region = us-east-1
```
the env var `AWS_REGION` was set to an empty string
```
$ env | grep -i aws
AWS_REGION=
```
unset this env var and all was good again
```
$ unset AWS_REGION
$ aws sts get-caller-identity --output text --query Account
777***234534
```
(*apologies for posting on a really old question, it did pop up in a Google search*)
|
28,572,764
|
I've been reading through the source for the cpython HTTP package for fun and profit, and noticed that in server.py they have the `__all__` variable set but also use a leading underscore for the function `_quote_html(html)`.
Isn't this redundant? Don't both serve to limit what's imported by `from HTTP import *`?
Why do they do both?
|
2015/02/17
|
[
"https://Stackoverflow.com/questions/28572764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029146/"
] |
Aside from the *"private-by-convention"* functions with `_leading_underscores`, there are:
* Quite a few `import`ed names;
* Four class names;
* Three function names *without* leading underscores;
* Two string *"constants"*; and
* One local variable (`nobody`).
If `__all__` wasn't defined to cover only the classes, all of these would also be added to your namespace by a wildcard `from server import *`.
Yes, you could just use one method or the other, but I think the leading underscore is a stronger sign than the exclusion from `__all__`; the latter says *"you probably won't need this often"*, the former says *"keep out unless you know what you're doing"*. They both have their place.
|
`__all__` indeed serves as a limit when doing `from HTTP import *`; prefixing `_` to the name of a function or method is a convention for informing the user that that item should be considered private and thus used at his/her own risk.
|
28,572,764
|
I've been reading through the source for the cpython HTTP package for fun and profit, and noticed that in server.py they have the `__all__` variable set but also use a leading underscore for the function `_quote_html(html)`.
Isn't this redundant? Don't both serve to limit what's imported by `from HTTP import *`?
Why do they do both?
|
2015/02/17
|
[
"https://Stackoverflow.com/questions/28572764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029146/"
] |
`__all__` indeed serves as a limit when doing `from HTTP import *`; prefixing `_` to the name of a function or method is a convention for informing the user that that item should be considered private and thus used at his/her own risk.
|
This is mostly a documentation thing, in a similar vein to comments. A leading underscore is a clearer indication to a person *reading the code* that particular functions or variables aren't part of the public API than having that person check each name against `__all__`. [PEP8](https://www.python.org/dev/peps/pep-0008/#public-and-internal-interfaces) explicitly recommends using both conventions in this way:
>
> To better support introspection, modules should explicitly declare
> the names in their public API using the `__all__` attribute. Setting
> `__all__` to an empty list indicates that the module has no public API.
>
>
> Even with `__all__` set appropriately, internal interfaces (packages,
> modules, classes, functions, attributes or other names) should still
> be prefixed with a single leading underscore.
>
>
>
|
28,572,764
|
I've been reading through the source for the cpython HTTP package for fun and profit, and noticed that in server.py they have the `__all__` variable set but also use a leading underscore for the function `_quote_html(html)`.
Isn't this redundant? Don't both serve to limit what's imported by `from HTTP import *`?
Why do they do both?
|
2015/02/17
|
[
"https://Stackoverflow.com/questions/28572764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029146/"
] |
Aside from the *"private-by-convention"* functions with `_leading_underscores`, there are:
* Quite a few `import`ed names;
* Four class names;
* Three function names *without* leading underscores;
* Two string *"constants"*; and
* One local variable (`nobody`).
If `__all__` wasn't defined to cover only the classes, all of these would also be added to your namespace by a wildcard `from server import *`.
Yes, you could just use one method or the other, but I think the leading underscore is a stronger sign than the exclusion from `__all__`; the latter says *"you probably won't need this often"*, the former says *"keep out unless you know what you're doing"*. They both have their place.
|
This is mostly a documentation thing, in a similar vein to comments. A leading underscore is a clearer indication to a person *reading the code* that particular functions or variables aren't part of the public API than having that person check each name against `__all__`. [PEP8](https://www.python.org/dev/peps/pep-0008/#public-and-internal-interfaces) explicitly recommends using both conventions in this way:
>
> To better support introspection, modules should explicitly declare
> the names in their public API using the `__all__` attribute. Setting
> `__all__` to an empty list indicates that the module has no public API.
>
>
> Even with `__all__` set appropriately, internal interfaces (packages,
> modules, classes, functions, attributes or other names) should still
> be prefixed with a single leading underscore.
>
>
>
|
13,993,617
|
I am currently using Python v2.6 and trying to merge words into a line. My code supposed to read data from a text file, in which I have two rows of data both of which are strings. Then, it takes the second row data every time, which are the words of sentences, those are separated by delimiter strings, such that:
Inside the .txt:
```
"delimiter_string"
"row_1_data" "row_2_data"
"row_1_data" "row_2_data"
"row_1_data" "row_2_data"
"row_1_data" "row_2_data"
"row_1_data" "row_2_data"
"delimiter_string"
"row_1_data" "row_2_data"
"row_1_data" "row_2_data"
...
```
Those "row\_2\_data" will add-up to a sentence later. Sorry for the long introduction btw.
Here is my code:
```
import sys
import re
newLine = ''
for line in sys.stdin:
word = line.split(' ')[1]
if word == '<S>+BSTag':
continue
elif word == '</S>+ESTag':
print newLine
newLine = ''
continue
else:
w = re.sub('\[.*?]', '', word)
if newLine == '':
newLine += w
else:
newLine += ' ' + w
```
"BSTag" is the tag for "Sentence Begins" and "ESTag" is for "Sentence Ends": the so called "delimiters". "re.sub" is used for a special purpose and it works as far as I checked.
The problem is that, when I execute this python script from the command line in linux with the following command: $ cat file.txt | script.py | less, I can not see any output, but just a blank file.
For those who are not familiar with linux, I guess the problem has nothing to do with terminal execution, thus you can neglect that part. Simply, the code does not work as intended and I can not find a single mistake.
Any help will be appreciated, and thanks for reading the long post :)
---
Ok, the problem is solved, which was actually a corpus error instead of a coding one. A very odd entry was detected in the text file, which was causing problems. Removing it solved it. You can use both of these approaches: mine and the one presented by "snurre" if you want a similar text processing.
Cheers.
|
2012/12/21
|
[
"https://Stackoverflow.com/questions/13993617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1839494/"
] |
```
def foo(lines):
output = []
for line in lines:
words = line.split()
if len(words) < 2:
word = words[0]
else:
word = words[1]
if word == '</S>+ESTag':
yield ' '.join(output)
output = []
elif word != '<S>+BSTag':
output.append(words[1])
for sentence in foo(sys.stdin):
print sentence
```
Your regex is a little funky. From what I can tell, it's replacing anything between (and including) a pair of `[` and `]` with `''`, so it ends up printing empty strings.
|
I think the problem is that the script isn't being executed (unless you just excluded the [shebang](http://docs.python.org/2/using/unix.html#miscellaneous) in the code you posted)
Try this
```
cat file.txt | python script.py | less
```
|
47,177,112
|
I manually create PySpark DataFrame as follows:
```
acdata = sc.parallelize([
[('timestamp', 1506340019), ('pk', 111), ('product_pk', 123), ('country_id', 'FR'), ('channel', 'web')]
])
# Convert to tuple
acdata_converted = acdata.map(lambda x: (x[0][1], x[1][1], x[2][1]))
# Define schema
acschema = StructType([
StructField("timestamp", LongType(), True),
StructField("pk", LongType(), True),
StructField("product_pk", LongType(), True),
StructField("country_id", StringType(), True),
StructField("channel", StringType(), True)
])
df = sqlContext.createDataFrame(acdata_converted, acschema)
```
But when I write `df.head()` and do `spark-submit`, I get the following error:
```
org.apache.spark.api.python.PythonException: Traceback (most recent call last):
File "/mnt/yarn/usercache/hdfs/appcache/application_1510134261242_0002/container_1510134261242_0002_01_000003/pyspark.zip/pyspark/worker.py", line 177, in main
process()
File "/mnt/yarn/usercache/hdfs/appcache/application_1510134261242_0002/container_1510134261242_0002_01_000003/pyspark.zip/pyspark/worker.py", line 172, in process
serializer.dump_stream(func(split_index, iterator), outfile)
File "/mnt/yarn/usercache/hdfs/appcache/application_1510134261242_0002/container_1510134261242_0002_01_000003/pyspark.zip/pyspark/serializers.py", line 268, in dump_stream
vs = list(itertools.islice(iterator, batch))
File "/mnt/yarn/usercache/hdfs/appcache/application_1510134261242_0002/container_1510134261242_0002_01_000001/pyspark.zip/pyspark/sql/session.py", line 520, in prepare
File "/mnt/yarn/usercache/hdfs/appcache/application_1510134261242_0002/container_1510134261242_0002_01_000003/pyspark.zip/pyspark/sql/types.py", line 1358, in _verify_type
"length of fields (%d)" % (len(obj), len(dataType.fields)))
ValueError: Length of object (3) does not match with length of fields (12)
at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:193)
at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:234)
at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:152)
at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:63)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
at org.apache.spark.scheduler.Task.run(Task.scala:108)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:335)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
```
What does it mean and how to solve it?
|
2017/11/08
|
[
"https://Stackoverflow.com/questions/47177112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7316807/"
] |
You need to map all 5 fields to match with the schema defined.
```
acdata_converted = acdata.map(lambda x: (x[0][1], x[1][1], x[2][1], x[3][1], x[4][1]))
```
|
I'd do it this way:
```
acdata = sc.parallelize([{'timestamp': 1506340019, 'pk': 111, 'product_pk': 123, 'country_id': 'FR', 'channel': 'web'}, {...}])
# Define schema
acschema = StructType([
StructField("timestamp", LongType(), True),
StructField("pk", LongType(), True),
StructField("product_pk", LongType(), True),
StructField("country_id", StringType(), True),
StructField("channel", StringType(), True)
])
df = sqlContext.createDataFrame(acdata_converted, acschema)
```
Also think if you really need to parallelize data. It's also possible to create DataFrame from dictionary.
|
70,828,210
|
I have `Django` project and want to look the another db (not default db created by `Php Symfony`)
Django can set up two DB in `settins.py`
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
"NAME": config("DB_NAME"),
"USER": config("DB_USER"),
"PASSWORD": config("DB_PASSWORD"),
"HOST": config("DB_HOST"),
"PORT": config("DB_PORT"),
'OPTIONS': {
'charset': 'utf8mb4',
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
},
}
'extern': {
'ENGINE': 'django.db.backends.mysql',
'NAME': config("DB_EXTERN_NAME"),
'USER': config("DB_EXTERN_USER"),
'PASSWORD': config("DB_EXTERN_PASSWORD"),
'HOST': config("DB_EXTERN_HOST"),
'PORT': config("DB_EXTERN_PORT"),
}
}
```
and set `models.py` for example
```
class Area(models.Model):
class Meta:
db_table = 'my_area'
```
However it requires to change the extern database when `python manage.py makemigrations`,`python manage.py migrate`
I just want to reference the extern db not alter.
Is there any good practice??
|
2022/01/24
|
[
"https://Stackoverflow.com/questions/70828210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1942868/"
] |
You may be looking for the [`managed = false`](https://docs.djangoproject.com/en/4.0/ref/models/options/#django.db.models.Options.managed) meta setting on your models. That will cause Django not to try to manage those models (such as creating migrations for them). It's commonly used when working with externally managed databases.
EG:
```
class Area(models.Model):
class Meta:
db_table = 'my_area'
managed = false
```
|
I think what you need do is run
```
python manage.py migrate --database extern
```
|
70,828,210
|
I have `Django` project and want to look the another db (not default db created by `Php Symfony`)
Django can set up two DB in `settins.py`
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
"NAME": config("DB_NAME"),
"USER": config("DB_USER"),
"PASSWORD": config("DB_PASSWORD"),
"HOST": config("DB_HOST"),
"PORT": config("DB_PORT"),
'OPTIONS': {
'charset': 'utf8mb4',
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
},
}
'extern': {
'ENGINE': 'django.db.backends.mysql',
'NAME': config("DB_EXTERN_NAME"),
'USER': config("DB_EXTERN_USER"),
'PASSWORD': config("DB_EXTERN_PASSWORD"),
'HOST': config("DB_EXTERN_HOST"),
'PORT': config("DB_EXTERN_PORT"),
}
}
```
and set `models.py` for example
```
class Area(models.Model):
class Meta:
db_table = 'my_area'
```
However it requires to change the extern database when `python manage.py makemigrations`,`python manage.py migrate`
I just want to reference the extern db not alter.
Is there any good practice??
|
2022/01/24
|
[
"https://Stackoverflow.com/questions/70828210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1942868/"
] |
You may want to generate your models using
```
python manage.py inspectdb --database=extern > models.py
```
This will generate models corresponding to the tables in your database
Check [this link](https://docs.djangoproject.com/en/4.0/howto/legacy-databases/) for more details about legacy databases (django docs)
|
I think what you need do is run
```
python manage.py migrate --database extern
```
|
70,828,210
|
I have `Django` project and want to look the another db (not default db created by `Php Symfony`)
Django can set up two DB in `settins.py`
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
"NAME": config("DB_NAME"),
"USER": config("DB_USER"),
"PASSWORD": config("DB_PASSWORD"),
"HOST": config("DB_HOST"),
"PORT": config("DB_PORT"),
'OPTIONS': {
'charset': 'utf8mb4',
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
},
}
'extern': {
'ENGINE': 'django.db.backends.mysql',
'NAME': config("DB_EXTERN_NAME"),
'USER': config("DB_EXTERN_USER"),
'PASSWORD': config("DB_EXTERN_PASSWORD"),
'HOST': config("DB_EXTERN_HOST"),
'PORT': config("DB_EXTERN_PORT"),
}
}
```
and set `models.py` for example
```
class Area(models.Model):
class Meta:
db_table = 'my_area'
```
However it requires to change the extern database when `python manage.py makemigrations`,`python manage.py migrate`
I just want to reference the extern db not alter.
Is there any good practice??
|
2022/01/24
|
[
"https://Stackoverflow.com/questions/70828210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1942868/"
] |
You may be looking for the [`managed = false`](https://docs.djangoproject.com/en/4.0/ref/models/options/#django.db.models.Options.managed) meta setting on your models. That will cause Django not to try to manage those models (such as creating migrations for them). It's commonly used when working with externally managed databases.
EG:
```
class Area(models.Model):
class Meta:
db_table = 'my_area'
managed = false
```
|
You may want to generate your models using
```
python manage.py inspectdb --database=extern > models.py
```
This will generate models corresponding to the tables in your database
Check [this link](https://docs.djangoproject.com/en/4.0/howto/legacy-databases/) for more details about legacy databases (django docs)
|
43,433,406
|
I am trying to run app not written by me app.
When I write
`python manage.py makemigrations`
I got:
```
Traceback (most recent call last):
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: django_content_type
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
utility.execute()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 341, in execute
django.setup()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 115, in populate
app_config.ready()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\apps.py", line 23, in ready
self.module.autodiscover()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "C:\Users\direwolf\Documents\web\python\alexbog80-motivity-3e5c21f03b3e\app\motivity\admin.py", line 23, in <module>
admin.site.register(Offer, OfferAdmin)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\sites.py", line 110, in register
system_check_errors.extend(admin_obj.check())
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\options.py", line 117, in check
return self.checks_class().check(self, **kwargs)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 520, in check
errors.extend(self._check_list_display(admin_obj))
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 596, in _check_list_display
for index, item in enumerate(obj.list_display)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 596, in <listcomp>
for index, item in enumerate(obj.list_display)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 604, in _check_list_display_item
elif hasattr(model, item):
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\fields.py", line 55, in __get__
return edit_string_for_tags(Tag.objects.usage_for_model(owner))
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\models.py", line 157, in usage_for_model
usage = self.usage_for_queryset(queryset, counts, min_count)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\models.py", line 183, in usage_for_queryset
extra_joins, extra_criteria, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\models.py", line 113, in _get_usage
'content_type_id': ContentType.objects.get_for_model(model).pk,
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\contenttypes\models.py", line 52, in get_for_model
ct = self.get(app_label=opts.app_label, model=opts.model_name)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 379, in get
num = len(clone)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 238, in __len__
self._fetch_all()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 1087, in _fetch_all
self._result_cache = list(self.iterator())
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 54, in __iter__
results = compiler.execute_sql()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py", line 835, in execute_sql
cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: django_content_type
```
What do I do?
upd 1:
`python manage.py migrate` traceback:
```
Traceback (most recent call last):
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: django_content_type
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
utility.execute()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 341, in execute
django.setup()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 115, in populate
app_config.ready()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\apps.py", line 23, in ready
self.module.autodiscover()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "C:\Users\direwolf\Documents\web\python\alexbog80-motivity-3e5c21f03b3e\app\motivity\admin.py", line 23, in <module>
admin.site.register(Offer, OfferAdmin)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\sites.py", line 110, in register
system_check_errors.extend(admin_obj.check())
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\options.py", line 117, in check
return self.checks_class().check(self, **kwargs)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 520, in check
errors.extend(self._check_list_display(admin_obj))
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 596, in _check_list_display
for index, item in enumerate(obj.list_display)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 596, in <listcomp>
for index, item in enumerate(obj.list_display)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 604, in _check_list_display_item
elif hasattr(model, item):
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\fields.py", line 55, in __get__
return edit_string_for_tags(Tag.objects.usage_for_model(owner))
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\models.py", line 157, in usage_for_model
usage = self.usage_for_queryset(queryset, counts, min_count)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\models.py", line 183, in usage_for_queryset
extra_joins, extra_criteria, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\models.py", line 113, in _get_usage
'content_type_id': ContentType.objects.get_for_model(model).pk,
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\contenttypes\models.py", line 52, in get_for_model
ct = self.get(app_label=opts.app_label, model=opts.model_name)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 379, in get
num = len(clone)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 238, in __len__
self._fetch_all()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 1087, in _fetch_all
self._result_cache = list(self.iterator())
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 54, in __iter__
results = compiler.execute_sql()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py", line 835, in execute_sql
cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils
```
.OperationalError: no such table: django\_content\_type
Upd 2:
Offer class in `models.py`
```
class Offer(TimeStampMixin, SEOFieldsMixin):
title = models.CharField(u'Название предложения', max_length=255, blank=False)
discription = models.TextField(u'Красивое описание оффера', null=False, blank=False)
cover = models.ImageField(u'Обложка', blank=False, null=False)
tags = TagAutocompleteField(blank=False, verbose_name='Теги')
active = models.BooleanField(u'Активный?', default=True)
publish = models.BooleanField(u'Показывать на сайте?', default=True)
def preview_image(self):
# try:
thumbnail = get_thumbnail(self.cover, 'x50', crop='center')
# except TypeError:
# return u'Нет картинки'
# except:
# return u'Нет картинки' # if original img not exist
return '<a href="%s/"><img src="%s"/></a>' % (self.id, thumbnail.url)
preview_image.short_description = u'Обложка'
preview_image.allow_tags = True
class Meta:
verbose_name = u'Предложение'
verbose_name_plural = u'Предложения'
ordering = ('-modified_value',)
get_latest_by = 'created_value'
def __unicode__(self):
return u'%s' % self.title
```
I didn't find admin class
only this:
```
from django.contrib import admin
from app.motivity.models import TaskOffer, Offer, UserOffers
class TaskOfferAdmin(admin.TabularInline):
model = TaskOffer
exclude = ['meta_title', 'meta_description', 'meta_keywords']
class OfferAdmin(admin.ModelAdmin):
list_display = ['preview_image','title','tags', 'publish']
list_display_links = ['title']
list_filter = ['tags']
inlines = [TaskOfferAdmin, ]
fields = ['title', 'discription', 'cover', 'tags']
class UserOfferAdmin(admin.ModelAdmin):
pass
admin.site.register(UserOffers, UserOfferAdmin)
admin.site.register(Offer, OfferAdmin)
```
|
2017/04/16
|
[
"https://Stackoverflow.com/questions/43433406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2950593/"
] |
I had the same issue while using **Python 3.6.5** and **Django==2.1.7** on **Mac OS 10.15.2**. I fixed it by manually creating the table `django_content_type` with the columns: `id, app_label, model`
On running `python manage.py migrate` and the error appears, there should be a `*.sqlite3` file created on the path specified on the `DATABASE` key within your `settings.py` file.
**Example:**
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'base_site.sqlite3'),
}
}
```
My Sqlite DB filename is `base_site.sqlite3` and is created at the `BASE_DIR` of the project.
**Steps to follow:**
* Connect to the created SQLite DB using:
```
sqlite3 <DB filename>
```
* Create the table using the following command:
```
CREATE TABLE IF
NOT EXISTS "django_content_type" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"app_label" varchar(100) NOT NULL,
"model" varchar(100) NOT NULL
);
```
* Finally run the migrations using the command below:
```
python manage.py migrate --fake-initial
```
This should run the migrations as expected.
|
It seems like I was using python 3x
And this app was written using python 2x
|
43,433,406
|
I am trying to run app not written by me app.
When I write
`python manage.py makemigrations`
I got:
```
Traceback (most recent call last):
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: django_content_type
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
utility.execute()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 341, in execute
django.setup()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 115, in populate
app_config.ready()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\apps.py", line 23, in ready
self.module.autodiscover()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "C:\Users\direwolf\Documents\web\python\alexbog80-motivity-3e5c21f03b3e\app\motivity\admin.py", line 23, in <module>
admin.site.register(Offer, OfferAdmin)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\sites.py", line 110, in register
system_check_errors.extend(admin_obj.check())
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\options.py", line 117, in check
return self.checks_class().check(self, **kwargs)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 520, in check
errors.extend(self._check_list_display(admin_obj))
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 596, in _check_list_display
for index, item in enumerate(obj.list_display)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 596, in <listcomp>
for index, item in enumerate(obj.list_display)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 604, in _check_list_display_item
elif hasattr(model, item):
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\fields.py", line 55, in __get__
return edit_string_for_tags(Tag.objects.usage_for_model(owner))
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\models.py", line 157, in usage_for_model
usage = self.usage_for_queryset(queryset, counts, min_count)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\models.py", line 183, in usage_for_queryset
extra_joins, extra_criteria, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\models.py", line 113, in _get_usage
'content_type_id': ContentType.objects.get_for_model(model).pk,
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\contenttypes\models.py", line 52, in get_for_model
ct = self.get(app_label=opts.app_label, model=opts.model_name)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 379, in get
num = len(clone)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 238, in __len__
self._fetch_all()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 1087, in _fetch_all
self._result_cache = list(self.iterator())
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 54, in __iter__
results = compiler.execute_sql()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py", line 835, in execute_sql
cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: django_content_type
```
What do I do?
upd 1:
`python manage.py migrate` traceback:
```
Traceback (most recent call last):
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: django_content_type
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
utility.execute()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 341, in execute
django.setup()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 115, in populate
app_config.ready()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\apps.py", line 23, in ready
self.module.autodiscover()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "C:\Users\direwolf\Documents\web\python\alexbog80-motivity-3e5c21f03b3e\app\motivity\admin.py", line 23, in <module>
admin.site.register(Offer, OfferAdmin)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\sites.py", line 110, in register
system_check_errors.extend(admin_obj.check())
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\options.py", line 117, in check
return self.checks_class().check(self, **kwargs)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 520, in check
errors.extend(self._check_list_display(admin_obj))
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 596, in _check_list_display
for index, item in enumerate(obj.list_display)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 596, in <listcomp>
for index, item in enumerate(obj.list_display)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 604, in _check_list_display_item
elif hasattr(model, item):
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\fields.py", line 55, in __get__
return edit_string_for_tags(Tag.objects.usage_for_model(owner))
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\models.py", line 157, in usage_for_model
usage = self.usage_for_queryset(queryset, counts, min_count)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\models.py", line 183, in usage_for_queryset
extra_joins, extra_criteria, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\models.py", line 113, in _get_usage
'content_type_id': ContentType.objects.get_for_model(model).pk,
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\contenttypes\models.py", line 52, in get_for_model
ct = self.get(app_label=opts.app_label, model=opts.model_name)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 379, in get
num = len(clone)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 238, in __len__
self._fetch_all()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 1087, in _fetch_all
self._result_cache = list(self.iterator())
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 54, in __iter__
results = compiler.execute_sql()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py", line 835, in execute_sql
cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils
```
.OperationalError: no such table: django\_content\_type
Upd 2:
Offer class in `models.py`
```
class Offer(TimeStampMixin, SEOFieldsMixin):
title = models.CharField(u'Название предложения', max_length=255, blank=False)
discription = models.TextField(u'Красивое описание оффера', null=False, blank=False)
cover = models.ImageField(u'Обложка', blank=False, null=False)
tags = TagAutocompleteField(blank=False, verbose_name='Теги')
active = models.BooleanField(u'Активный?', default=True)
publish = models.BooleanField(u'Показывать на сайте?', default=True)
def preview_image(self):
# try:
thumbnail = get_thumbnail(self.cover, 'x50', crop='center')
# except TypeError:
# return u'Нет картинки'
# except:
# return u'Нет картинки' # if original img not exist
return '<a href="%s/"><img src="%s"/></a>' % (self.id, thumbnail.url)
preview_image.short_description = u'Обложка'
preview_image.allow_tags = True
class Meta:
verbose_name = u'Предложение'
verbose_name_plural = u'Предложения'
ordering = ('-modified_value',)
get_latest_by = 'created_value'
def __unicode__(self):
return u'%s' % self.title
```
I didn't find admin class
only this:
```
from django.contrib import admin
from app.motivity.models import TaskOffer, Offer, UserOffers
class TaskOfferAdmin(admin.TabularInline):
model = TaskOffer
exclude = ['meta_title', 'meta_description', 'meta_keywords']
class OfferAdmin(admin.ModelAdmin):
list_display = ['preview_image','title','tags', 'publish']
list_display_links = ['title']
list_filter = ['tags']
inlines = [TaskOfferAdmin, ]
fields = ['title', 'discription', 'cover', 'tags']
class UserOfferAdmin(admin.ModelAdmin):
pass
admin.site.register(UserOffers, UserOfferAdmin)
admin.site.register(Offer, OfferAdmin)
```
|
2017/04/16
|
[
"https://Stackoverflow.com/questions/43433406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2950593/"
] |
simply delete your db.sqlite3 file....and reagain run the command--->
py manage.py migrate
then,
py manage.py makemigrations app\_name
finally,
py manage.py migrate...
follow this process wish you will fixed your prblm
|
It seems like I was using python 3x
And this app was written using python 2x
|
43,433,406
|
I am trying to run app not written by me app.
When I write
`python manage.py makemigrations`
I got:
```
Traceback (most recent call last):
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: django_content_type
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
utility.execute()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 341, in execute
django.setup()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 115, in populate
app_config.ready()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\apps.py", line 23, in ready
self.module.autodiscover()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "C:\Users\direwolf\Documents\web\python\alexbog80-motivity-3e5c21f03b3e\app\motivity\admin.py", line 23, in <module>
admin.site.register(Offer, OfferAdmin)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\sites.py", line 110, in register
system_check_errors.extend(admin_obj.check())
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\options.py", line 117, in check
return self.checks_class().check(self, **kwargs)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 520, in check
errors.extend(self._check_list_display(admin_obj))
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 596, in _check_list_display
for index, item in enumerate(obj.list_display)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 596, in <listcomp>
for index, item in enumerate(obj.list_display)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 604, in _check_list_display_item
elif hasattr(model, item):
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\fields.py", line 55, in __get__
return edit_string_for_tags(Tag.objects.usage_for_model(owner))
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\models.py", line 157, in usage_for_model
usage = self.usage_for_queryset(queryset, counts, min_count)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\models.py", line 183, in usage_for_queryset
extra_joins, extra_criteria, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\models.py", line 113, in _get_usage
'content_type_id': ContentType.objects.get_for_model(model).pk,
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\contenttypes\models.py", line 52, in get_for_model
ct = self.get(app_label=opts.app_label, model=opts.model_name)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 379, in get
num = len(clone)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 238, in __len__
self._fetch_all()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 1087, in _fetch_all
self._result_cache = list(self.iterator())
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 54, in __iter__
results = compiler.execute_sql()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py", line 835, in execute_sql
cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: django_content_type
```
What do I do?
upd 1:
`python manage.py migrate` traceback:
```
Traceback (most recent call last):
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: django_content_type
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
utility.execute()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 341, in execute
django.setup()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 115, in populate
app_config.ready()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\apps.py", line 23, in ready
self.module.autodiscover()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "C:\Users\direwolf\Documents\web\python\alexbog80-motivity-3e5c21f03b3e\app\motivity\admin.py", line 23, in <module>
admin.site.register(Offer, OfferAdmin)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\sites.py", line 110, in register
system_check_errors.extend(admin_obj.check())
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\options.py", line 117, in check
return self.checks_class().check(self, **kwargs)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 520, in check
errors.extend(self._check_list_display(admin_obj))
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 596, in _check_list_display
for index, item in enumerate(obj.list_display)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 596, in <listcomp>
for index, item in enumerate(obj.list_display)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 604, in _check_list_display_item
elif hasattr(model, item):
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\fields.py", line 55, in __get__
return edit_string_for_tags(Tag.objects.usage_for_model(owner))
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\models.py", line 157, in usage_for_model
usage = self.usage_for_queryset(queryset, counts, min_count)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\models.py", line 183, in usage_for_queryset
extra_joins, extra_criteria, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tagging\models.py", line 113, in _get_usage
'content_type_id': ContentType.objects.get_for_model(model).pk,
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\contenttypes\models.py", line 52, in get_for_model
ct = self.get(app_label=opts.app_label, model=opts.model_name)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 379, in get
num = len(clone)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 238, in __len__
self._fetch_all()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 1087, in _fetch_all
self._result_cache = list(self.iterator())
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 54, in __iter__
results = compiler.execute_sql()
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py", line 835, in execute_sql
cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils
```
.OperationalError: no such table: django\_content\_type
Upd 2:
Offer class in `models.py`
```
class Offer(TimeStampMixin, SEOFieldsMixin):
title = models.CharField(u'Название предложения', max_length=255, blank=False)
discription = models.TextField(u'Красивое описание оффера', null=False, blank=False)
cover = models.ImageField(u'Обложка', blank=False, null=False)
tags = TagAutocompleteField(blank=False, verbose_name='Теги')
active = models.BooleanField(u'Активный?', default=True)
publish = models.BooleanField(u'Показывать на сайте?', default=True)
def preview_image(self):
# try:
thumbnail = get_thumbnail(self.cover, 'x50', crop='center')
# except TypeError:
# return u'Нет картинки'
# except:
# return u'Нет картинки' # if original img not exist
return '<a href="%s/"><img src="%s"/></a>' % (self.id, thumbnail.url)
preview_image.short_description = u'Обложка'
preview_image.allow_tags = True
class Meta:
verbose_name = u'Предложение'
verbose_name_plural = u'Предложения'
ordering = ('-modified_value',)
get_latest_by = 'created_value'
def __unicode__(self):
return u'%s' % self.title
```
I didn't find admin class
only this:
```
from django.contrib import admin
from app.motivity.models import TaskOffer, Offer, UserOffers
class TaskOfferAdmin(admin.TabularInline):
model = TaskOffer
exclude = ['meta_title', 'meta_description', 'meta_keywords']
class OfferAdmin(admin.ModelAdmin):
list_display = ['preview_image','title','tags', 'publish']
list_display_links = ['title']
list_filter = ['tags']
inlines = [TaskOfferAdmin, ]
fields = ['title', 'discription', 'cover', 'tags']
class UserOfferAdmin(admin.ModelAdmin):
pass
admin.site.register(UserOffers, UserOfferAdmin)
admin.site.register(Offer, OfferAdmin)
```
|
2017/04/16
|
[
"https://Stackoverflow.com/questions/43433406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2950593/"
] |
This issue can occur if you have code that uses contenttypes database information at import time rather than at runtime. For example, if you added code that runs at the module level or class level along the lines of:
```
TERM_CONTENT_TYPE = ContentType.objects.get_for_model(Term)
```
but you only added this *after* running your initial migrations that created that content type tables, then the next person who runs the migrations on a fresh database will get this error.
In this case the solution is to move code like that into places that runs only when a method is called, like into a view or other method.
|
It seems like I was using python 3x
And this app was written using python 2x
|
20,492,625
|
I've written tests for my python code and want to check how much % is covered with tests, so I decided to use python coverage. But I have a problem launching it. I launch my tests with this bash command:
```
export PYTHONPATH=. && python files/test/tests.py
```
My python program is in "files" directory, and tests are in "test", so I can't launch it another way.
Using
```
export PYTHONPATH=. && python coverage files/test/tests.py
```
raises Error. How to correctly use coverage in my situation ?
|
2013/12/10
|
[
"https://Stackoverflow.com/questions/20492625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2876296/"
] |
The correct way to do this is to use an appropriate **coverage** plugin for the unit testing framework/runner you are using:
Here are some combinations:
* [pytest](http://pytest.org/latest/) + [pytest-cov](https://pypi.python.org/pypi/pytest-cov)
* [nose](https://pypi.python.org/pypi/nose/1.3.0) + [nose-cov](https://pypi.python.org/pypi/nose-cov)
There are probably other tools and combinations you can use. But these two are probably the most common (*no reference*).
|
```
coverage run files/test/tests.py
```
|
53,129,263
|
Depend on this tutorials [grpc basic](https://grpc.io/docs/tutorials/basic/python.html)
I clone `https://github.com/grpc/grpc` to local,
`cd example/python/helloworld`
start server `python greeter_server.py`
then start client `python greeter_client.py`,
but get error
```
Traceback (most recent call last):
File "greeter_client.py", line 35, in <module>
run()
File "greeter_client.py", line 30, in run
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
File "/usr/local/lib/python3.7/site-packages/grpc/_channel.py", line 533, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/usr/local/lib/python3.7/site-packages/grpc/_channel.py", line 467, in _end_unary_response_blocking
raise _Rendezvous(state, None, None, deadline) grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with:
status = StatusCode.UNAVAILABLE
details = "Socket closed"
debug_error_string = "{"created":"@1541228979.471085000","description":"Error received from peer","file":"src/core/lib/surface/call.cc","file_line":1017,"grpc_message":"Socket closed","grpc_status":14}"
```
then I execuse `sudo python greeter_client.py`, get the correct result.
Why I should add sudo to get the correct result?
|
2018/11/03
|
[
"https://Stackoverflow.com/questions/53129263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6449456/"
] |
1. I found I set a global http proxy `export http_proxy=http://127.0.0.1:1087`, I closed this proxy, then It was find.
2. update `greeter_client.py`, change `localhost` to `127.0.0.1`. It's find to me.
|
Could you try few options and share your feedback:
**Option - 1**
another port(except 50051) in [client](https://github.com/grpc/grpc/blob/master/examples/python/helloworld/greeter_client.py) and [server](https://github.com/grpc/grpc/blob/master/examples/python/helloworld/greeter_server.py#L36)?
**Option-2**
Try with 0.0.0.0 in [client](https://github.com/grpc/grpc/blob/master/examples/python/helloworld/greeter_client.py)
Thanks,
Dheeraj
|
41,434,350
|
I work on a project and I want to download a csv file from a url. I did some research on the site but none of the solutions presented worked for me.
The url offers you directly to download or open the file of the blow I do not know how to say a python to save the file (it would be nice if I could also rename it)
But when I open the url with this code nothing happens.
```
import urllib
url='https://data.toulouse-metropole.fr/api/records/1.0/download/?dataset=dechets-menagers-et-assimiles-collectes'
testfile = urllib.request.urlopen(url)
```
Any ideas?
|
2017/01/02
|
[
"https://Stackoverflow.com/questions/41434350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6435119/"
] |
Try this. Change "folder" to a folder on your machine
```
import os
import requests
url='https://data.toulouse-metropole.fr/api/records/1.0/download/?dataset=dechets-menagers-et-assimiles-collectes'
response = requests.get(url)
with open(os.path.join("folder", "file"), 'wb') as f:
f.write(response.content)
```
|
You can adapt an example from [the docs](https://docs.python.org/3/howto/urllib2.html)
```
import urllib.request
url='https://data.toulouse-metropole.fr/api/records/1.0/download/?dataset=dechets-menagers-et-assimiles-collectes'
with urllib.request.urlopen(url) as testfile, open('dataset.csv', 'w') as f:
f.write(testfile.read().decode())
```
|
35,780,768
|
I am getting this message when I try to install aws. Anyone have any ideas of what's going on?
```
Exception:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 209, in main
status = self.run(options, args)
File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 317, in run
prefix=options.prefix_path,
File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 725, in install
requirement.uninstall(auto_confirm=True)
File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 756, in uninstall
paths_to_remove.remove(auto_confirm)
File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove
renames(path, new_path)
File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 266, in renames
shutil.move(old, new)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
copy2(src, real_dst)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
copystat(src, dst)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/tmp/pip-TIuiKe-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'
```
The command I'm using is pip install awscli
|
2016/03/03
|
[
"https://Stackoverflow.com/questions/35780768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5505587/"
] |
Pure virtual functions will never cause anything to fail during linking. Instead, pure virtual functions will cause a compilation error if you try to instantiate the object of an abstract type.
Reminder - an abstract type is a type which has (directly or indirectly through inheritance) at least one pure virtual function which was not overridden.
|
This may compile or build, if the solution has been previously built. This means that it is using old object code. Try to do a clean build of your solution, then rebuild it. Once your solution is cleaned. Then try to compile the inherited class. Another thing that may be of concern is that you have declared your inherited class as:
>
> class AImpl : A { ... };
>
>
>
My question on this is how is `AImpl` being inherited from `A`? Are you intending `public`, `protected` or `private` inheritance?
**EDIT**
If you are linking to this as a library and your current solution does not show any compile, build, link errors; this is because your current solution is using the old `lib` or `dll` that was already built. If you go back into your library solution and do a clean build, it should not compile, and thus you won't have a newer version of your library to link to.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.