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
71,398,447
In below code 21 is hour and 53 is min and 10 is wait time in this code I want to send message in loop frequently but I failed. I also tried for loop but it is not working. Any body know how to send 100 message in whatsapp using python please help me ``` import pywhatkit from flask import Flask while 1: pywhatkit.se...
2022/03/08
[ "https://Stackoverflow.com/questions/71398447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18126137/" ]
Use ``` final response = await http.post(Uri.parse(url), body: { "fecha_inicio": _fechaInicioBBDD, "fecha_fin": _fechaFinalBBDD, "latitud": _controllerLatitud.text, "longitud": _controllerLongitud.text, "calle": _controllerDireccion.text, "descripcion": _controllerDescripcion.text,...
The documentation for [`http.post`](https://pub.dev/documentation/http/latest/http/post.html) states: > > `body` sets the body of the request. It can be a `String`, a `List<int>` or a `Map<String, String>`. > > > Since you are passing a `Map`, all keys and values in your `Map` are required to be `String`s. You sh...
71,398,447
In below code 21 is hour and 53 is min and 10 is wait time in this code I want to send message in loop frequently but I failed. I also tried for loop but it is not working. Any body know how to send 100 message in whatsapp using python please help me ``` import pywhatkit from flask import Flask while 1: pywhatkit.se...
2022/03/08
[ "https://Stackoverflow.com/questions/71398447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18126137/" ]
When you are doing: ``` double.parse(_horas.toString()) ``` this is converting `_horas` to a `String` and then *again* to a `double`. Instead, only call `toString()`: ``` "activar_x_antes": _horas.toString() ```
The documentation for [`http.post`](https://pub.dev/documentation/http/latest/http/post.html) states: > > `body` sets the body of the request. It can be a `String`, a `List<int>` or a `Map<String, String>`. > > > Since you are passing a `Map`, all keys and values in your `Map` are required to be `String`s. You sh...
71,398,447
In below code 21 is hour and 53 is min and 10 is wait time in this code I want to send message in loop frequently but I failed. I also tried for loop but it is not working. Any body know how to send 100 message in whatsapp using python please help me ``` import pywhatkit from flask import Flask while 1: pywhatkit.se...
2022/03/08
[ "https://Stackoverflow.com/questions/71398447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18126137/" ]
Let's take a closer look at why this is happening. You have value `_horas = 4.0`; which is a `double`, you are trying to convert it to `String` to send it to the server. However, you are using `double. parse`. Let's look at the [parse](https://api.flutter.dev/flutter/dart-core/double/parse.html) doc. it says "Parse s...
The documentation for [`http.post`](https://pub.dev/documentation/http/latest/http/post.html) states: > > `body` sets the body of the request. It can be a `String`, a `List<int>` or a `Map<String, String>`. > > > Since you are passing a `Map`, all keys and values in your `Map` are required to be `String`s. You sh...
53,913,303
Im trying to implement a menu in my tool. But i couldn't implement a switch case in python. i know that python has only dictionary mapping. How to call parameterised methods in those switch case? For example, I have this program `def Choice(i): switcher = { 1: subdomain(host), 2: reverseLookup(host), 3: lambda: 't...
2018/12/24
[ "https://Stackoverflow.com/questions/53913303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10829002/" ]
Switch cases can be implemented using dictionary mapping in Python like so: ``` def Choice(i): switcher = {1: subdomain, 2: reverseLookup} func = switcher.get(i, 'Invalid') if func != 'Invalid': print(func(host)) ``` There is a dictionary `switcher` which helps on mapping to the right function ba...
**try this ....** ``` def Choice(i): switcher = { 1: subdomain(host), 2: reverseLookup(host), 3: lambda: 'two' } func = switcher.get(i, lambda:'Invalid') print(func()) if __name__ == "__main__": argument=0 print Choice(argument) ```
53,913,303
Im trying to implement a menu in my tool. But i couldn't implement a switch case in python. i know that python has only dictionary mapping. How to call parameterised methods in those switch case? For example, I have this program `def Choice(i): switcher = { 1: subdomain(host), 2: reverseLookup(host), 3: lambda: 't...
2018/12/24
[ "https://Stackoverflow.com/questions/53913303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10829002/" ]
I think the problem is because the first two functions are getting called when the `switcher` dictionary is created. You can avoid that by making all of the values `lambda` function definitions as shown below: ``` def choice(i): switcher = { 1: lambda: subdomain(host), 2: lambda: reverseLoo...
**try this ....** ``` def Choice(i): switcher = { 1: subdomain(host), 2: reverseLookup(host), 3: lambda: 'two' } func = switcher.get(i, lambda:'Invalid') print(func()) if __name__ == "__main__": argument=0 print Choice(argument) ```
53,913,303
Im trying to implement a menu in my tool. But i couldn't implement a switch case in python. i know that python has only dictionary mapping. How to call parameterised methods in those switch case? For example, I have this program `def Choice(i): switcher = { 1: subdomain(host), 2: reverseLookup(host), 3: lambda: 't...
2018/12/24
[ "https://Stackoverflow.com/questions/53913303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10829002/" ]
There is an option that is obvious to get correct..: ``` def choice(i, host): # you should normally pass all variables used in the function if i == 1: print(subdomain(host)) elif i == 2: print(reverseLookup(host)) elif i == 3: print('two') else: print('Invalid') ``` i...
**try this ....** ``` def Choice(i): switcher = { 1: subdomain(host), 2: reverseLookup(host), 3: lambda: 'two' } func = switcher.get(i, lambda:'Invalid') print(func()) if __name__ == "__main__": argument=0 print Choice(argument) ```
53,913,303
Im trying to implement a menu in my tool. But i couldn't implement a switch case in python. i know that python has only dictionary mapping. How to call parameterised methods in those switch case? For example, I have this program `def Choice(i): switcher = { 1: subdomain(host), 2: reverseLookup(host), 3: lambda: 't...
2018/12/24
[ "https://Stackoverflow.com/questions/53913303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10829002/" ]
I think the problem is because the first two functions are getting called when the `switcher` dictionary is created. You can avoid that by making all of the values `lambda` function definitions as shown below: ``` def choice(i): switcher = { 1: lambda: subdomain(host), 2: lambda: reverseLoo...
Switch cases can be implemented using dictionary mapping in Python like so: ``` def Choice(i): switcher = {1: subdomain, 2: reverseLookup} func = switcher.get(i, 'Invalid') if func != 'Invalid': print(func(host)) ``` There is a dictionary `switcher` which helps on mapping to the right function ba...
53,913,303
Im trying to implement a menu in my tool. But i couldn't implement a switch case in python. i know that python has only dictionary mapping. How to call parameterised methods in those switch case? For example, I have this program `def Choice(i): switcher = { 1: subdomain(host), 2: reverseLookup(host), 3: lambda: 't...
2018/12/24
[ "https://Stackoverflow.com/questions/53913303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10829002/" ]
I think the problem is because the first two functions are getting called when the `switcher` dictionary is created. You can avoid that by making all of the values `lambda` function definitions as shown below: ``` def choice(i): switcher = { 1: lambda: subdomain(host), 2: lambda: reverseLoo...
There is an option that is obvious to get correct..: ``` def choice(i, host): # you should normally pass all variables used in the function if i == 1: print(subdomain(host)) elif i == 2: print(reverseLookup(host)) elif i == 3: print('two') else: print('Invalid') ``` i...
40,527,051
I'm trying to make my program allow the user to input vectors of the form (x,y,z) using python's built in input() function. If entered normally in python with out using the input() function it indexes each vector separately. For example, ``` >>> z = (1,2,3), (4,5,6), (7,8,9) >>> z[1] (4, 5, 6) ``` But when I try to...
2016/11/10
[ "https://Stackoverflow.com/questions/40527051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7141092/" ]
In Python 3, `input` always returns a string. You need to convert the string. For this type of input I recommend using `liter_eval` from the module `ast`: ``` import ast vectors = ast.literal_eval('(1,2,3), (4,5,6), (7,8,9)') vectors[1] #(4, 5, 6) ```
In your example, `z` is just a string as input by the user. This string is: `"(1,2,3), (4,5,6), (7,8,9)"` so the second element, `z[1]` is just giving you `"1"`. If you want an actual vector object you would have to write code to parse the string input by the user. For example, you could delimit based on parentheses...
40,527,051
I'm trying to make my program allow the user to input vectors of the form (x,y,z) using python's built in input() function. If entered normally in python with out using the input() function it indexes each vector separately. For example, ``` >>> z = (1,2,3), (4,5,6), (7,8,9) >>> z[1] (4, 5, 6) ``` But when I try to...
2016/11/10
[ "https://Stackoverflow.com/questions/40527051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7141092/" ]
In Python 3, `input` always returns a string. You need to convert the string. For this type of input I recommend using `liter_eval` from the module `ast`: ``` import ast vectors = ast.literal_eval('(1,2,3), (4,5,6), (7,8,9)') vectors[1] #(4, 5, 6) ```
you can use eval with input function to the get the same as first. ``` eval(input('Please enter the vector') ```
40,527,051
I'm trying to make my program allow the user to input vectors of the form (x,y,z) using python's built in input() function. If entered normally in python with out using the input() function it indexes each vector separately. For example, ``` >>> z = (1,2,3), (4,5,6), (7,8,9) >>> z[1] (4, 5, 6) ``` But when I try to...
2016/11/10
[ "https://Stackoverflow.com/questions/40527051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7141092/" ]
In your example, `z` is just a string as input by the user. This string is: `"(1,2,3), (4,5,6), (7,8,9)"` so the second element, `z[1]` is just giving you `"1"`. If you want an actual vector object you would have to write code to parse the string input by the user. For example, you could delimit based on parentheses...
you can use eval with input function to the get the same as first. ``` eval(input('Please enter the vector') ```
44,155,564
When trying to plot a graph with pyplot I am running the following code: ``` from matplotlib import pyplot as plt x = [6, 5, 4] y = [3, 4, 5] plt.plot(x, y) plt.show() ``` This is returning the following error: ``` --------------------------------------------------------------------------- AttributeError ...
2017/05/24
[ "https://Stackoverflow.com/questions/44155564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8058705/" ]
I had this exact error and in my case it turned out to be that both `pip` and `conda` had installed copies of `matplotlib`. In a 'mixed' environment with `pip` used to fill gaps in Anaconda, `pip` can automatically install upgrades to (already-installed) dependencies of the package you asked to install, creating duplic...
I have solved my problem although I am not entirely sure why this has solved it. I used `pip uninstall matplotlib`, to remove the python install, and also updated my `~/.zshrc` and `~/.bash_profile` paths to contain: HomeBrew: `export PATH=/usr/local/bin:$PATH` Python: `export PATH=/usr/local/share/python:$PATH` ...
44,155,564
When trying to plot a graph with pyplot I am running the following code: ``` from matplotlib import pyplot as plt x = [6, 5, 4] y = [3, 4, 5] plt.plot(x, y) plt.show() ``` This is returning the following error: ``` --------------------------------------------------------------------------- AttributeError ...
2017/05/24
[ "https://Stackoverflow.com/questions/44155564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8058705/" ]
I have solved my problem although I am not entirely sure why this has solved it. I used `pip uninstall matplotlib`, to remove the python install, and also updated my `~/.zshrc` and `~/.bash_profile` paths to contain: HomeBrew: `export PATH=/usr/local/bin:$PATH` Python: `export PATH=/usr/local/share/python:$PATH` ...
I have had a similar kind of problem what I did was trying to upgrade my matplotlib using ``` pip install -U matplotlib ``` and then reopen anaconda to see it working
44,155,564
When trying to plot a graph with pyplot I am running the following code: ``` from matplotlib import pyplot as plt x = [6, 5, 4] y = [3, 4, 5] plt.plot(x, y) plt.show() ``` This is returning the following error: ``` --------------------------------------------------------------------------- AttributeError ...
2017/05/24
[ "https://Stackoverflow.com/questions/44155564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8058705/" ]
I had this exact error and in my case it turned out to be that both `pip` and `conda` had installed copies of `matplotlib`. In a 'mixed' environment with `pip` used to fill gaps in Anaconda, `pip` can automatically install upgrades to (already-installed) dependencies of the package you asked to install, creating duplic...
I have had a similar kind of problem what I did was trying to upgrade my matplotlib using ``` pip install -U matplotlib ``` and then reopen anaconda to see it working
18,153,913
I used `python -mtimeit` to test and found out it takes more time to `from Module import Sth` comparing to `import Module` E.g. ``` $ python -mtimeit "import math; math.sqrt(4)" 1000000 loops, best of 3: 0.618 usec per loop $ python -mtimeit "from math import sqrt; sqrt(4)" 1000000 loops, best of 3: 1.11 usec per loo...
2013/08/09
[ "https://Stackoverflow.com/questions/18153913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2325350/" ]
There are two issues here. The first step is to figure out which part is faster: the import statement, or the call. So, let's do that: ``` $ python -mtimeit 'import math' 1000000 loops, best of 3: 0.555 usec per loop $ python -mtimeit 'from math import sqrt' 1000000 loops, best of 3: 1.22 usec per loop $ python -mtim...
This is not an answer, but some information. It needed formatting so I didn't include it as a comment. Here is the bytecode for 'from math import sqrt': ``` >>> from math import sqrt >>> import dis >>> def f(n): return sqrt(n) ... >>> dis.dis(f) 1 0 LOAD_GLOBAL 0 (sqrt) 3 LOAD_F...
51,481,021
My friend told me about [Josephus problem](https://en.wikipedia.org/wiki/Josephus_problem), where you have `41` people sitting in the circle. Person number `1` has a sword, kills person on the right and passes the sword to the next person. This goes on until there is only one person left alive. I came up with this solu...
2018/07/23
[ "https://Stackoverflow.com/questions/51481021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9274224/" ]
I see two serious bugs. 1. I guarantee that `del ppList[::i]` does nothing resembling what you hope it does. 2. When you wrap around the circle, it is important to know if you killed the last person in the list (first in list kills again) or didn't (first person in list dies). And contrary to your assertion that it w...
The problem is you are not considering the guy in the end if he is not killed. Example, if there are 9 people, after killing 8, 9 has the sword, but you are just starting with 1, instead of 9 in the next loop. As someone mentioned already, it is not working for smaller numbers also. Actually if you look close, you're k...
61,975,308
I am trying to read the url code using URLLIB. Here is my code: ``` import urllib url = "https://www.facebook.com/fads0000fass" r = urllib.request.urlopen(url) p = r.code if(p == "HTTP Error 404: Not Found" ): print("hello") else: print("null") ``` The url I am using will show error code 404 but I...
2020/05/23
[ "https://Stackoverflow.com/questions/61975308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13288913/" ]
I'm not sure that's what you're asking. ``` import urllib.request url = "https://www.facebook.com/fads0000fass" try: r = urllib.request.urlopen(url) p = r.code except urllib.error.HTTPError: print("hello") ```
In order to reach your if statement, your code needs exception handling. An exception is being raised when you call `urlopen` on line 7. See the first step of your traceback. ``` File "gd.py", line 7, in <module> r = urllib.request.urlopen(url) ``` The exception happens here, which causes your code to exit, so fur...
71,902,562
I have started the Yolo5 Training with custom data The command I have used: ``` !python train.py --img 640 --batch-size 32 --epochs 5 --data /content/drive/MyDrive/yolov5_dataset/dataset_Trafic/data.yaml --cfg /content/drive/MyDrive/yolov5/models/yolov5s.yaml --name Model ``` Training started as below & completed:...
2022/04/17
[ "https://Stackoverflow.com/questions/71902562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2707200/" ]
#### Case 1 Here we consider the statement: ``` Animal a1 = func1(); ``` The call expression `func1()` is an **rvlalue** of type `Animal`. And from C++17 onwards, due to [mandatory copy elison](https://en.cppreference.com/w/cpp/language/copy_elision#Mandatory_elision_of_copy/move_operations): > > Under the follo...
In C++17 there is a new set of rules about temporary materialization. In a simple explanation an expression that evaluates to a prvalue (a temporary) doesn't immediately create an object, but is instead a recipe for creating an object. So in your example `Animal()` doesn't create an object straight away so that's why ...
4,175,697
I am writting a daemon server using python, sometimes there are python runtime errors, for example some variable type is not correct. That error will not cause the process to exit. Is it possible for me to redirect such runtime error to a log file?
2010/11/14
[ "https://Stackoverflow.com/questions/4175697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197036/" ]
It looks like you are asking two questions. To prevent your process from exiting on errors, you need to catch all [`exception`](http://www.python.org/doc//current/library/exceptions.html)s that are raised using [`try...except...finally`](http://www.python.org/doc//current/reference/compound_stmts.html#try). You also ...
Look at the `traceback` module. If you catch a `RuntimeError`, you can write it to the log (look at the `logging` module for that).
17,860,717
Spent almost more than 30 mins of my time in trying all different possibly. Finally now I'm exhausted. Can someone please help me on this quote problem ``` def remote_shell_func_execute(): with settings(host_string='[email protected]',warn_only=True): process = run("subprocess.Popen(\["/root/test/shell_...
2013/07/25
[ "https://Stackoverflow.com/questions/17860717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2436055/" ]
Just use a single quoted string. ``` run('subprocess.Popen(\["/root/test/shell_script_for_test.sh func2"\],shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)') ``` Or escape the inner `"`. ``` run("subprocess.Popen(\[\"/root/test/shell_script_for_test.sh func2\"\],shell=True,stdin=subpr...
When you escape quotes, the escape backslash must go directly before the quote character: ``` "[\"/..." ``` Alternatively, use single quotes for the string, this avoids the need for escaping at all: ``` '["/...' ```
7,314,925
I'm saving data to a PostgreSQL backend through Django. Many of the fields in my models are DecimalFields set to arbitrarily high max\_digits and decimal\_places, corresponding to numeric columns in the database backend. The data in each column have a precision (or number of decimal places) that is not known *a priori*...
2011/09/06
[ "https://Stackoverflow.com/questions/7314925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/929783/" ]
If you need perfect parity forwards and backwards, you'll need to use a CharField. Any number-based database field is going to interact with your data muxing it in some way or another. Now, I know you mentioned not being able to know the digit length of the data points, and a CharField requires some length. You can eit...
Since I asked this question awhile ago and the answer remains the same, I'll share what I found should it be helpful to anyone in a similar position. Django doesn't have the ability to take advantage of the PostgreSQL Numerical column type with arbitrary precision. In order to preserve the display precision of data I u...
46,258,924
I am trying to recreate some code from MatLab using numpy, and I cannot find out how to store a variable amount of matrices. In MatLab I used the following code: ``` for i = 1:rows K{i} = zeros(5,4); %create 5x4 matrix K{i}(1,1)= ET(i,1); %put knoop i in table K{i}(1,3)= ET(i,2); %put knoop j in table ...
2017/09/16
[ "https://Stackoverflow.com/questions/46258924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8620430/" ]
In the MATLAB code you are using a Cell array. Cells are generic containers. The equivalent in Python is a regular [list](https://docs.python.org/2/tutorial/introduction.html#lists) - not a numpy structure. You can create your numpy arrays and then store them in a list like so: ``` import numpy as np array1 = np.array...
How about something like this: ``` import numpy as np myList = [] for i in range(100): mtrx = np.zeros((5,4)) mtrx[1,2] = 7 mtrx[3,0] = -5 myList.append(mtrx) ```
1,242,904
I use CMake to build my application. How can I find where the python site-packages directory is located? I need the path in order to compile an extension to python. CMake has to be able to find the path on all three major OS as I plan to deploy my application on Linux, Mac and Windows. I tried using ``` include(Find...
2009/08/07
[ "https://Stackoverflow.com/questions/1242904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/134397/" ]
You can execute external processes in cmake with [execute\_process](http://www.cmake.org/cmake/help/cmake2.6docs.html#command:execute_process) (and get the output into a variable if needed, as it would be here).
I suggest to use `get_python_lib(True)` if you are making this extension as a dynamic library. This first parameter should be true if you need the platform specific location (in 64bit linux machines, this could be `/usr/lib64` instead of `/usr/lib`)
1,242,904
I use CMake to build my application. How can I find where the python site-packages directory is located? I need the path in order to compile an extension to python. CMake has to be able to find the path on all three major OS as I plan to deploy my application on Linux, Mac and Windows. I tried using ``` include(Find...
2009/08/07
[ "https://Stackoverflow.com/questions/1242904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/134397/" ]
You can execute external processes in cmake with [execute\_process](http://www.cmake.org/cmake/help/cmake2.6docs.html#command:execute_process) (and get the output into a variable if needed, as it would be here).
Slightly updated version that I used for [lcm](https://github.com/lcm-proj-lcm): ``` execute_process( COMMAND "${PYTHON_EXECUTABLE}" -c "if True: from distutils import sysconfig as sc print(sc.get_python_lib(prefix='', plat_specific=True))" OUTPUT_VARIABLE PYTHON_SITE OUTPUT_STRIP_TRAILING_WHITESPACE) `...
1,242,904
I use CMake to build my application. How can I find where the python site-packages directory is located? I need the path in order to compile an extension to python. CMake has to be able to find the path on all three major OS as I plan to deploy my application on Linux, Mac and Windows. I tried using ``` include(Find...
2009/08/07
[ "https://Stackoverflow.com/questions/1242904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/134397/" ]
You can execute external processes in cmake with [execute\_process](http://www.cmake.org/cmake/help/cmake2.6docs.html#command:execute_process) (and get the output into a variable if needed, as it would be here).
Since CMake 3.12 you can use [FindPython](https://cmake.org/cmake/help/latest/module/FindPython.html) module which populates `Python_SITELIB` and `Python_SITEARCH` variables for architecture independent and specific libraries, respectively. Example: ``` find_package(Python ${PYTHON_VERSION} REQUIRED COMPONENTS Develo...
1,242,904
I use CMake to build my application. How can I find where the python site-packages directory is located? I need the path in order to compile an extension to python. CMake has to be able to find the path on all three major OS as I plan to deploy my application on Linux, Mac and Windows. I tried using ``` include(Find...
2009/08/07
[ "https://Stackoverflow.com/questions/1242904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/134397/" ]
Slightly updated version that I used for [lcm](https://github.com/lcm-proj-lcm): ``` execute_process( COMMAND "${PYTHON_EXECUTABLE}" -c "if True: from distutils import sysconfig as sc print(sc.get_python_lib(prefix='', plat_specific=True))" OUTPUT_VARIABLE PYTHON_SITE OUTPUT_STRIP_TRAILING_WHITESPACE) `...
I suggest to use `get_python_lib(True)` if you are making this extension as a dynamic library. This first parameter should be true if you need the platform specific location (in 64bit linux machines, this could be `/usr/lib64` instead of `/usr/lib`)
1,242,904
I use CMake to build my application. How can I find where the python site-packages directory is located? I need the path in order to compile an extension to python. CMake has to be able to find the path on all three major OS as I plan to deploy my application on Linux, Mac and Windows. I tried using ``` include(Find...
2009/08/07
[ "https://Stackoverflow.com/questions/1242904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/134397/" ]
Since CMake 3.12 you can use [FindPython](https://cmake.org/cmake/help/latest/module/FindPython.html) module which populates `Python_SITELIB` and `Python_SITEARCH` variables for architecture independent and specific libraries, respectively. Example: ``` find_package(Python ${PYTHON_VERSION} REQUIRED COMPONENTS Develo...
I suggest to use `get_python_lib(True)` if you are making this extension as a dynamic library. This first parameter should be true if you need the platform specific location (in 64bit linux machines, this could be `/usr/lib64` instead of `/usr/lib`)
55,598,548
I'm trying to update my Spyder to fix some error in my Spyder 3.2.3. But when I called `conda update spyder` mentioned in (<https://github.com/spyder-ide/spyder/issues/9019#event-2225858161>), the Anaconda prompt showed as follow: ![enter image description here](https://i.stack.imgur.com/IFWTL.png) and the Spyder wa...
2019/04/09
[ "https://Stackoverflow.com/questions/55598548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11335756/" ]
Fortunately I have fixed my Spyder by using command 'conda install --revision 2', and updated my Spyder to version 3.3.4 in the Anaconda Navigator. The `conda list --version` can show each rev before, so I used command `conda install --revision 2` to restore the environment to what it was before I updated conda. After...
I reinstalled the package that's causing inconsistency and then the problem is gone. My inconsistency error: [![My Inconsistency Error](https://i.stack.imgur.com/ACgYe.png)](https://i.stack.imgur.com/ACgYe.png) What I did: ``` conda install -c conda-forge mkl-service ```
55,598,548
I'm trying to update my Spyder to fix some error in my Spyder 3.2.3. But when I called `conda update spyder` mentioned in (<https://github.com/spyder-ide/spyder/issues/9019#event-2225858161>), the Anaconda prompt showed as follow: ![enter image description here](https://i.stack.imgur.com/IFWTL.png) and the Spyder wa...
2019/04/09
[ "https://Stackoverflow.com/questions/55598548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11335756/" ]
This worked with python3.8 and spyder4.1.5: ``` conda install pyqt --force-reinstall ```
Fortunately I have fixed my Spyder by using command 'conda install --revision 2', and updated my Spyder to version 3.3.4 in the Anaconda Navigator. The `conda list --version` can show each rev before, so I used command `conda install --revision 2` to restore the environment to what it was before I updated conda. After...
55,598,548
I'm trying to update my Spyder to fix some error in my Spyder 3.2.3. But when I called `conda update spyder` mentioned in (<https://github.com/spyder-ide/spyder/issues/9019#event-2225858161>), the Anaconda prompt showed as follow: ![enter image description here](https://i.stack.imgur.com/IFWTL.png) and the Spyder wa...
2019/04/09
[ "https://Stackoverflow.com/questions/55598548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11335756/" ]
This worked with python3.8 and spyder4.1.5: ``` conda install pyqt --force-reinstall ```
I reinstalled the package that's causing inconsistency and then the problem is gone. My inconsistency error: [![My Inconsistency Error](https://i.stack.imgur.com/ACgYe.png)](https://i.stack.imgur.com/ACgYe.png) What I did: ``` conda install -c conda-forge mkl-service ```
64,832,243
I'm trying to install apache airflow with pip, so I enter "pip install apache-airflow". but somehow i got an error that i don't understand. Could you please help me with this? for a little bit context, I'm using macOS catalina and python 3.8.2. I have tried to upgrade my pip, but the error still there. These are the...
2020/11/14
[ "https://Stackoverflow.com/questions/64832243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14607085/" ]
I looked into similar errors and here are a few possible fixes: 1. If you installed Python3.8 via `Brew`, try to uninstall it and install a new version that you build from source. 2. Try `sudo python3.8 -m pip install apache-airflow`. 3. Upgrade to Python 3.8.5 as per [this post](https://stackoverflow.com/questions/64...
I faced exact same issue, here's how I solved it. I explicitly used python 3.8.5 as pointed in [Meghdeep Ray's answer](https://stackoverflow.com/a/64867996/2508468) I also exported the `export ARCHFLAGS="-arch x86_64"` environment variable still inspired by [Meghdeep Ray's answer](https://stackoverflow.com/a/64867996...
1,417,473
I'm trying to call a function in a Python script from my main C++ program. The python function takes a string as the argument and returns nothing (ok.. 'None'). It works perfectly well (never thought it would be that easy..) as long as the previous call is finished before the function is called again, otherwise there ...
2009/09/13
[ "https://Stackoverflow.com/questions/1417473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144746/" ]
When you say "as long as the previous call is finished before the function is called again", I can only assume that you have multiple threads calling from C++ into Python. The python is not thread safe, so this is going to fail! Read up on the Global Interpreter Lock (GIL) in the Python manual. Perhaps the following l...
Thank you for your help! Yes you're right, there are several C threads. Never thought I'd need mutex for the interpreter itself - the GIL is a completly new concept for me (and isn't even once mentioned in the whole tutorial). After reading the reference (for sure not the easiest part of it, although the PyGILState\_...
23,900,878
Is it possible to mock a module in python using `unittest.mock`? I have a module named `config`, while running tests I want to mock it by another module `test_config`. how can I do that ? Thanks. config.py: ``` CONF_VAR1 = "VAR1" CONF_VAR2 = "VAR2" ``` test\_config.py: ``` CONF_VAR1 = "test_VAR1" CONF_VAR2 = "test...
2014/05/28
[ "https://Stackoverflow.com/questions/23900878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2085665/" ]
If you're always accessing the variables in config.py like this: ``` import config ... config.VAR1 ``` You can replace the `config` module imported by whatever module you're actually trying to test. So, if you're testing a module called `foo`, and it imports and uses `config`, you can say: ``` from mock import patc...
Consider this following setup configuration.py: ``` import os class Config(object): CONF_VAR1 = "VAR1" CONF_VAR2 = "VAR2" class TestConfig(object): CONF_VAR1 = "test_VAR1" CONF_VAR2 = "test_VAR2" if os.getenv("TEST"): config = TestConfig else: config = Config ``` now everywhere else in yo...
23,900,878
Is it possible to mock a module in python using `unittest.mock`? I have a module named `config`, while running tests I want to mock it by another module `test_config`. how can I do that ? Thanks. config.py: ``` CONF_VAR1 = "VAR1" CONF_VAR2 = "VAR2" ``` test\_config.py: ``` CONF_VAR1 = "test_VAR1" CONF_VAR2 = "test...
2014/05/28
[ "https://Stackoverflow.com/questions/23900878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2085665/" ]
**foo.py:** ``` import config VAR1 = config.CONF_VAR1 def bar(): return VAR1 ``` **test.py:** ``` import unittest import unittest.mock as mock import test_config class Test(unittest.TestCase): def test_one(self): with mock.patch.dict('sys.modules', config=test_config): import foo ...
Consider this following setup configuration.py: ``` import os class Config(object): CONF_VAR1 = "VAR1" CONF_VAR2 = "VAR2" class TestConfig(object): CONF_VAR1 = "test_VAR1" CONF_VAR2 = "test_VAR2" if os.getenv("TEST"): config = TestConfig else: config = Config ``` now everywhere else in yo...
23,900,878
Is it possible to mock a module in python using `unittest.mock`? I have a module named `config`, while running tests I want to mock it by another module `test_config`. how can I do that ? Thanks. config.py: ``` CONF_VAR1 = "VAR1" CONF_VAR2 = "VAR2" ``` test\_config.py: ``` CONF_VAR1 = "test_VAR1" CONF_VAR2 = "test...
2014/05/28
[ "https://Stackoverflow.com/questions/23900878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2085665/" ]
If you want to mock an entire module just mock the import where the module is used. `myfile.py` ``` import urllib ``` `test_myfile.py` ``` import mock import unittest class MyTest(unittest.TestCase): @mock.patch('myfile.urllib') def test_thing(self, urllib): urllib.whatever.return_value = 4 ```
Consider this following setup configuration.py: ``` import os class Config(object): CONF_VAR1 = "VAR1" CONF_VAR2 = "VAR2" class TestConfig(object): CONF_VAR1 = "test_VAR1" CONF_VAR2 = "test_VAR2" if os.getenv("TEST"): config = TestConfig else: config = Config ``` now everywhere else in yo...
23,900,878
Is it possible to mock a module in python using `unittest.mock`? I have a module named `config`, while running tests I want to mock it by another module `test_config`. how can I do that ? Thanks. config.py: ``` CONF_VAR1 = "VAR1" CONF_VAR2 = "VAR2" ``` test\_config.py: ``` CONF_VAR1 = "test_VAR1" CONF_VAR2 = "test...
2014/05/28
[ "https://Stackoverflow.com/questions/23900878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2085665/" ]
If you're always accessing the variables in config.py like this: ``` import config ... config.VAR1 ``` You can replace the `config` module imported by whatever module you're actually trying to test. So, if you're testing a module called `foo`, and it imports and uses `config`, you can say: ``` from mock import patc...
If your application ("app.py" say) looks like ``` import config print config.var1, config.var2 ``` And gives the output: ``` $ python app.py VAR1 VAR2 ``` You can use `mock.patch` to patch the individual config variables: ``` from mock import patch with patch('config.var1', 'test_VAR1'): import app ``` Th...
23,900,878
Is it possible to mock a module in python using `unittest.mock`? I have a module named `config`, while running tests I want to mock it by another module `test_config`. how can I do that ? Thanks. config.py: ``` CONF_VAR1 = "VAR1" CONF_VAR2 = "VAR2" ``` test\_config.py: ``` CONF_VAR1 = "test_VAR1" CONF_VAR2 = "test...
2014/05/28
[ "https://Stackoverflow.com/questions/23900878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2085665/" ]
**foo.py:** ``` import config VAR1 = config.CONF_VAR1 def bar(): return VAR1 ``` **test.py:** ``` import unittest import unittest.mock as mock import test_config class Test(unittest.TestCase): def test_one(self): with mock.patch.dict('sys.modules', config=test_config): import foo ...
If your application ("app.py" say) looks like ``` import config print config.var1, config.var2 ``` And gives the output: ``` $ python app.py VAR1 VAR2 ``` You can use `mock.patch` to patch the individual config variables: ``` from mock import patch with patch('config.var1', 'test_VAR1'): import app ``` Th...
23,900,878
Is it possible to mock a module in python using `unittest.mock`? I have a module named `config`, while running tests I want to mock it by another module `test_config`. how can I do that ? Thanks. config.py: ``` CONF_VAR1 = "VAR1" CONF_VAR2 = "VAR2" ``` test\_config.py: ``` CONF_VAR1 = "test_VAR1" CONF_VAR2 = "test...
2014/05/28
[ "https://Stackoverflow.com/questions/23900878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2085665/" ]
If you want to mock an entire module just mock the import where the module is used. `myfile.py` ``` import urllib ``` `test_myfile.py` ``` import mock import unittest class MyTest(unittest.TestCase): @mock.patch('myfile.urllib') def test_thing(self, urllib): urllib.whatever.return_value = 4 ```
If your application ("app.py" say) looks like ``` import config print config.var1, config.var2 ``` And gives the output: ``` $ python app.py VAR1 VAR2 ``` You can use `mock.patch` to patch the individual config variables: ``` from mock import patch with patch('config.var1', 'test_VAR1'): import app ``` Th...
23,900,878
Is it possible to mock a module in python using `unittest.mock`? I have a module named `config`, while running tests I want to mock it by another module `test_config`. how can I do that ? Thanks. config.py: ``` CONF_VAR1 = "VAR1" CONF_VAR2 = "VAR2" ``` test\_config.py: ``` CONF_VAR1 = "test_VAR1" CONF_VAR2 = "test...
2014/05/28
[ "https://Stackoverflow.com/questions/23900878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2085665/" ]
If you're always accessing the variables in config.py like this: ``` import config ... config.VAR1 ``` You can replace the `config` module imported by whatever module you're actually trying to test. So, if you're testing a module called `foo`, and it imports and uses `config`, you can say: ``` from mock import patc...
**foo.py:** ``` import config VAR1 = config.CONF_VAR1 def bar(): return VAR1 ``` **test.py:** ``` import unittest import unittest.mock as mock import test_config class Test(unittest.TestCase): def test_one(self): with mock.patch.dict('sys.modules', config=test_config): import foo ...
23,900,878
Is it possible to mock a module in python using `unittest.mock`? I have a module named `config`, while running tests I want to mock it by another module `test_config`. how can I do that ? Thanks. config.py: ``` CONF_VAR1 = "VAR1" CONF_VAR2 = "VAR2" ``` test\_config.py: ``` CONF_VAR1 = "test_VAR1" CONF_VAR2 = "test...
2014/05/28
[ "https://Stackoverflow.com/questions/23900878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2085665/" ]
If you're always accessing the variables in config.py like this: ``` import config ... config.VAR1 ``` You can replace the `config` module imported by whatever module you're actually trying to test. So, if you're testing a module called `foo`, and it imports and uses `config`, you can say: ``` from mock import patc...
If you want to mock an entire module just mock the import where the module is used. `myfile.py` ``` import urllib ``` `test_myfile.py` ``` import mock import unittest class MyTest(unittest.TestCase): @mock.patch('myfile.urllib') def test_thing(self, urllib): urllib.whatever.return_value = 4 ```
23,900,878
Is it possible to mock a module in python using `unittest.mock`? I have a module named `config`, while running tests I want to mock it by another module `test_config`. how can I do that ? Thanks. config.py: ``` CONF_VAR1 = "VAR1" CONF_VAR2 = "VAR2" ``` test\_config.py: ``` CONF_VAR1 = "test_VAR1" CONF_VAR2 = "test...
2014/05/28
[ "https://Stackoverflow.com/questions/23900878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2085665/" ]
**foo.py:** ``` import config VAR1 = config.CONF_VAR1 def bar(): return VAR1 ``` **test.py:** ``` import unittest import unittest.mock as mock import test_config class Test(unittest.TestCase): def test_one(self): with mock.patch.dict('sys.modules', config=test_config): import foo ...
If you want to mock an entire module just mock the import where the module is used. `myfile.py` ``` import urllib ``` `test_myfile.py` ``` import mock import unittest class MyTest(unittest.TestCase): @mock.patch('myfile.urllib') def test_thing(self, urllib): urllib.whatever.return_value = 4 ```
50,601,935
I'm debugging my python application using VSCode. I have a main python file from where I start the debugger. I'm able to put breakpoints in this file, but if I want to put breakpoints in other files which are called by the main file, I get them as 'Unverified breakpoint' and the debugger ignores them. How can I chan...
2018/05/30
[ "https://Stackoverflow.com/questions/50601935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1616955/" ]
This may be a result of the "[justMyCode](https://code.visualstudio.com/docs/python/debugging#_justmycode)" configuration option, as it defaults to true. While the description from the provider is "...restricts debugging to user-written code only. Set to False to also enable debugging of standard library functions.", ...
The imports for the other modules were inside strings and called using the `execute` function. That's why VSCode couldn't very the breakpoints in the other files as it didn't know that these other files are used by the main file..
16,068,532
So this happened to me: ``` thing = ModelClass() thing.foo = bar() thing.do_Stuff() thing.save() #works fine thing.decimal_field = decimal_value thing.save() #error here ``` Traceback follows: ``` TypeError at /journey/collaborators/2/ unsupported operand type(s) for ** or pow(): 'Decimal' and 'str' 274. ...
2013/04/17
[ "https://Stackoverflow.com/questions/16068532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742082/" ]
Linking turned on will throw away any methods, attributes, properties... that are not used at the time of compilation. This is problem for example with reflection approach. Your problem - very large package can be solved by: 1. reducing library code - removing unused code manually and linking off - probably don't wan...
Use the Json.Net provided by the [Xamarin Component Store](http://components.xamarin.com/view/json.net/). I have used this component for multiple projects and my Release builds with linking enabled come in between 4-8 MB.
16,068,532
So this happened to me: ``` thing = ModelClass() thing.foo = bar() thing.do_Stuff() thing.save() #works fine thing.decimal_field = decimal_value thing.save() #error here ``` Traceback follows: ``` TypeError at /journey/collaborators/2/ unsupported operand type(s) for ** or pow(): 'Decimal' and 'str' 274. ...
2013/04/17
[ "https://Stackoverflow.com/questions/16068532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742082/" ]
Linking turned on will throw away any methods, attributes, properties... that are not used at the time of compilation. This is problem for example with reflection approach. Your problem - very large package can be solved by: 1. reducing library code - removing unused code manually and linking off - probably don't wan...
This problem can be solved by adding the System assembly to the "Skip linking assemblies" list under Mono Android Options for the project. This added < 1 Mb to the size of the APK for me.
4,413,912
Why is `print` a keyword in python and not a function?
2010/12/10
[ "https://Stackoverflow.com/questions/4413912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/538442/" ]
The `print` statement in Python 2.x has some special syntax which would not be available for an ordinary function. For example you can use a trailing `,` to suppress the output of a final newline or you can use `>>` to redirect the output to a file. But all this wasn't convincing enough even to Guido van Rossum himself...
I will throw in my thoughts on this: In Python 2.x `print` is not a statement by mistake, or because printing to `stdout` is such a basic thing to do. Everything else is so thought-through or has at least understandable reasons that a mistake of that order would seem odd. If communicating with `stdout` would have been...
4,413,912
Why is `print` a keyword in python and not a function?
2010/12/10
[ "https://Stackoverflow.com/questions/4413912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/538442/" ]
Because Guido has decided that he made a mistake. :) It has since been corrected: try Python 3, which dedicates a [section of its release notes](http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function) to describing the change to a function. For the whole background, see [PEP 3105](https://www.pyth...
`print` **was** a statement in Python because it was a statement in ABC, the main inspiration for Python (although it was called `WRITE` there). That in turn probably had a statement instead of a function as it was a teaching language and as such inspired by basic. Python on the other hand, turned out to be more than a...
4,413,912
Why is `print` a keyword in python and not a function?
2010/12/10
[ "https://Stackoverflow.com/questions/4413912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/538442/" ]
It is now a function in Python 3.
The `print` statement in Python 2.x has some special syntax which would not be available for an ordinary function. For example you can use a trailing `,` to suppress the output of a final newline or you can use `>>` to redirect the output to a file. But all this wasn't convincing enough even to Guido van Rossum himself...
4,413,912
Why is `print` a keyword in python and not a function?
2010/12/10
[ "https://Stackoverflow.com/questions/4413912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/538442/" ]
Because Guido has decided that he made a mistake. :) It has since been corrected: try Python 3, which dedicates a [section of its release notes](http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function) to describing the change to a function. For the whole background, see [PEP 3105](https://www.pyth...
An answer that draws from what I appreciate about the `print` statement, but not necessarily from the official Python history... Python is, to some extent, a *scripting language*. Now, there are lots of definitions of "scripting language", but the one I'll use here is: a language designed for efficient use of short or...
4,413,912
Why is `print` a keyword in python and not a function?
2010/12/10
[ "https://Stackoverflow.com/questions/4413912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/538442/" ]
`print` **was** a statement in Python because it was a statement in ABC, the main inspiration for Python (although it was called `WRITE` there). That in turn probably had a statement instead of a function as it was a teaching language and as such inspired by basic. Python on the other hand, turned out to be more than a...
The `print` statement in Python 2.x has some special syntax which would not be available for an ordinary function. For example you can use a trailing `,` to suppress the output of a final newline or you can use `>>` to redirect the output to a file. But all this wasn't convincing enough even to Guido van Rossum himself...
4,413,912
Why is `print` a keyword in python and not a function?
2010/12/10
[ "https://Stackoverflow.com/questions/4413912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/538442/" ]
It is now a function in Python 3.
An answer that draws from what I appreciate about the `print` statement, but not necessarily from the official Python history... Python is, to some extent, a *scripting language*. Now, there are lots of definitions of "scripting language", but the one I'll use here is: a language designed for efficient use of short or...
4,413,912
Why is `print` a keyword in python and not a function?
2010/12/10
[ "https://Stackoverflow.com/questions/4413912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/538442/" ]
Because Guido has decided that he made a mistake. :) It has since been corrected: try Python 3, which dedicates a [section of its release notes](http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function) to describing the change to a function. For the whole background, see [PEP 3105](https://www.pyth...
It is now a function in Python 3.
4,413,912
Why is `print` a keyword in python and not a function?
2010/12/10
[ "https://Stackoverflow.com/questions/4413912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/538442/" ]
It is now a function in Python 3.
I will throw in my thoughts on this: In Python 2.x `print` is not a statement by mistake, or because printing to `stdout` is such a basic thing to do. Everything else is so thought-through or has at least understandable reasons that a mistake of that order would seem odd. If communicating with `stdout` would have been...
4,413,912
Why is `print` a keyword in python and not a function?
2010/12/10
[ "https://Stackoverflow.com/questions/4413912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/538442/" ]
Because Guido has decided that he made a mistake. :) It has since been corrected: try Python 3, which dedicates a [section of its release notes](http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function) to describing the change to a function. For the whole background, see [PEP 3105](https://www.pyth...
I will throw in my thoughts on this: In Python 2.x `print` is not a statement by mistake, or because printing to `stdout` is such a basic thing to do. Everything else is so thought-through or has at least understandable reasons that a mistake of that order would seem odd. If communicating with `stdout` would have been...
4,413,912
Why is `print` a keyword in python and not a function?
2010/12/10
[ "https://Stackoverflow.com/questions/4413912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/538442/" ]
`print` **was** a statement in Python because it was a statement in ABC, the main inspiration for Python (although it was called `WRITE` there). That in turn probably had a statement instead of a function as it was a teaching language and as such inspired by basic. Python on the other hand, turned out to be more than a...
An answer that draws from what I appreciate about the `print` statement, but not necessarily from the official Python history... Python is, to some extent, a *scripting language*. Now, there are lots of definitions of "scripting language", but the one I'll use here is: a language designed for efficient use of short or...
71,214,931
I want to access items from a new dictionary called `conversations` by implementing a for loop. ``` {" conversations": [ {"tag": "greeting", "user": ["Hi", " What's your name?", " How are you?", "Hello", "Good day"], "response": ["Hello, my name is Rosie. Nice to see you", "Good to see you again", " How can I help you...
2022/02/22
[ "https://Stackoverflow.com/questions/71214931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18273393/" ]
You should use the `json` module to load in JSON data as opposed to reading in the file line-by-line. Whatever procedure you build yourself is likely to be fragile and less efficient. Here is the looping structure that you're looking for: ```py import json with open('input.json') as input_file: data = json.load(...
Try this out: ``` import json dialogue_text = json.load(open("dialogue.txt", encoding='utf8')) for conversation in dialogue_text[" conversations"]: for user in conversation['user']: print(user) ``` Output: ```none Hi What's your name? How are you? Hello Good day Bye See you Goodbye Thanks Thank you T...
72,393,418
I am working with python and numpy! I have a txt file with integers, space seperated, and each row of the file must be a row in an array or dataframe. The problem is that not every row has the same size! I know the size that i want them to have and i want to put to the missing values the number zero! As is not comma se...
2022/05/26
[ "https://Stackoverflow.com/questions/72393418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19207300/" ]
Forbidden often correlated to SSL/TLS certificate verification failure. Please try using the `requests.get` by setting the `verify=False` as following Fixing the SSL certificate issue ``` requests.get("https://www.example.com/insert.php?network=testnet&id=1245300&c=2803824&lat=7555457", verify=False) ``` Fixing the...
Somehow I overcomplicated it and when I tried the absolute minimum that works. ``` import requests headers = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36' } response = requests.get("http://www.example.com/insert.php?network=test...
62,801,244
I am working on a project where i have to use Mouse as a paintbrush. I have used `cv2.setMouseCallback()` function but it returned the following error. here is the part of my code ``` import cv2 import numpy as np # mouse callback function def draw_circle(event,x,y,flags,param): if event == cv2.EVENT_LBUTTONDBLCL...
2020/07/08
[ "https://Stackoverflow.com/questions/62801244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7976921/" ]
The error is resolved I removed the previously installed OpenCV (which is installed using pip `pip install opencv-python`) and reinstalled it using `sudo apt install libopencv-dev python3-opencv`
for me, also worked with the pip3 installations. Just made a fresh virtual env, and installed opencv-python and opencv-contrib-python.
62,801,244
I am working on a project where i have to use Mouse as a paintbrush. I have used `cv2.setMouseCallback()` function but it returned the following error. here is the part of my code ``` import cv2 import numpy as np # mouse callback function def draw_circle(event,x,y,flags,param): if event == cv2.EVENT_LBUTTONDBLCL...
2020/07/08
[ "https://Stackoverflow.com/questions/62801244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7976921/" ]
The error is resolved I removed the previously installed OpenCV (which is installed using pip `pip install opencv-python`) and reinstalled it using `sudo apt install libopencv-dev python3-opencv`
add the same namedWindow worked for me ``` cv2.namedWindow("video") cv2.imshow("video", image) cv2.setMouseCallback("video", drawLine) ```
62,801,244
I am working on a project where i have to use Mouse as a paintbrush. I have used `cv2.setMouseCallback()` function but it returned the following error. here is the part of my code ``` import cv2 import numpy as np # mouse callback function def draw_circle(event,x,y,flags,param): if event == cv2.EVENT_LBUTTONDBLCL...
2020/07/08
[ "https://Stackoverflow.com/questions/62801244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7976921/" ]
add the same namedWindow worked for me ``` cv2.namedWindow("video") cv2.imshow("video", image) cv2.setMouseCallback("video", drawLine) ```
for me, also worked with the pip3 installations. Just made a fresh virtual env, and installed opencv-python and opencv-contrib-python.
30,013,383
I want to be able to get from `[2, 3]` and `3 : [2, 3, 2, 3, 2, 3]`. (Like `3 * a` in python where a is a list) Is there a quick and efficient way to do this in Javascript ? I do this with a `for` loop, but it lacks visibility and I guess efficiency. I would like for it to work with every types of element. For insta...
2015/05/03
[ "https://Stackoverflow.com/questions/30013383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4859055/" ]
You can use this (very readable :P) function: ``` function repeat(arr, n){ var a = []; for (var i=0;i<n;[i++].push.apply(a,arr)); return a; } ``` `repeat([2,3], 3)` returns an array `[2, 3, 2, 3, 2, 3]`. Basically, it's this: ``` function repeat(array, times){ var newArray = []; for (var i=0; i < times; ...
There is not. This is a very Pythonic idea. You could devise a function to do it, but I doubt there is any computational benefit because you would just be using a loop or some weird misuse of string functions.
28,314,014
I have written this code in python ``` import os files = os.listdir(".") x = "" for file in files: x = ("\"" + file + "\" ") f = open("files.txt", "w") f.write(x) f.close() ``` this works and I get a single string with all the files in a directory as `"foo.txt" "bar.txt" "baz.txt"` but I don't like the for loop....
2015/02/04
[ "https://Stackoverflow.com/questions/28314014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337134/" ]
1. You can write string literals using both `'single'` and `"double-quotes"`; you don't have to escape one inside the other. 2. You can use the `format` function to apply quotes before you `join`. 3. You should use the `with` statement when opening files to save you from having to `close` it explicitly. Thus: ``` imp...
``` import os files = os.listdir(".") x = " ".join('"%s"'%f for f in files) with open("files.txt", "w") as f: f.write(x) ```
28,314,014
I have written this code in python ``` import os files = os.listdir(".") x = "" for file in files: x = ("\"" + file + "\" ") f = open("files.txt", "w") f.write(x) f.close() ``` this works and I get a single string with all the files in a directory as `"foo.txt" "bar.txt" "baz.txt"` but I don't like the for loop....
2015/02/04
[ "https://Stackoverflow.com/questions/28314014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337134/" ]
``` import os files = os.listdir(".") x = " ".join('"%s"'%f for f in files) with open("files.txt", "w") as f: f.write(x) ```
You can use `with` to writer file. ``` import os files = os.listdir('.') x = ' '.join(['"%s"'%f for f in files]) with open("files.txt", "w") as f: f.write(x) ```
28,314,014
I have written this code in python ``` import os files = os.listdir(".") x = "" for file in files: x = ("\"" + file + "\" ") f = open("files.txt", "w") f.write(x) f.close() ``` this works and I get a single string with all the files in a directory as `"foo.txt" "bar.txt" "baz.txt"` but I don't like the for loop....
2015/02/04
[ "https://Stackoverflow.com/questions/28314014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337134/" ]
1. You can write string literals using both `'single'` and `"double-quotes"`; you don't have to escape one inside the other. 2. You can use the `format` function to apply quotes before you `join`. 3. You should use the `with` statement when opening files to save you from having to `close` it explicitly. Thus: ``` imp...
You can use `with` to writer file. ``` import os files = os.listdir('.') x = ' '.join(['"%s"'%f for f in files]) with open("files.txt", "w") as f: f.write(x) ```
58,223,422
I'm currently trying to find an effective way of running a machine learning task over a set amount of cores using `tensorflow`. From the information I found there were two main approaches to doing this. The first of which was using the two tensorflow variables intra\_op\_parallelism\_threads and inter\_op\_parallelism...
2019/10/03
[ "https://Stackoverflow.com/questions/58223422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8776042/" ]
**first check the index labels and columns** ``` fact.index fact.columns ``` If you need to convert index to columns use: Use: ``` fact.reset_index() ``` **Then you can use:** ``` fact.groupby(['store_id', 'month'])['quantity'].mean() ``` Output: ``` store_id month 174 8 1 354 7 1...
need to add "**as\_index=True**" ex: "count\_in = df.groupby(['time\_in','id'], **as\_index=True**)['time\_in'].count()"
58,791,530
I am making a poem generator in python, and I am currently working on how poems are outputted to the user. I would like to make it so every line that is outputted will have a comma follow after. I thought I could achieve this easily by using the .join function, but it seems to attach to letters rather than the end of t...
2019/11/10
[ "https://Stackoverflow.com/questions/58791530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12334091/" ]
Just use the `+` or `+=` operator for strings, for example: ``` trailing_punct = ',' # can be '!', '?', etc. line1 += trailing_punct # or line1 = line1 + trailing_punct ``` `+=` can be used to modify the string "in place" (note that under the covers, it does create a new object and assign to it, so `id(line1)` will...
It seems your `line1` and `line2`are lists of strings, so I'll start by assuming that: ``` line1 = ["Moonlight", "is", "winter"] line2 = ["The", "waters", "scent", "fallen", "snow"] ``` You are using the default behaviour of the `print` function when given several string arguments to add the space between words: `pr...
18,788,493
I would like to extract filename from url in R. For now I do it as follows, but maybe it can be done shorter like in python. assuming path is just string. ``` path="http://www.exanple.com/foo/bar/fooXbar.xls" ``` in R: ``` tail(strsplit(path,"[/]")[[1]],1) ``` in Python: ``` path.split("/")[-1:] ``` Maybe some...
2013/09/13
[ "https://Stackoverflow.com/questions/18788493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/953553/" ]
There's a function for that... ``` basename(path) [1] "fooXbar.xls" ```
@SimonO101 has the most robust answer IMO, but some other options: Since regular expressions are greedy, you can use that to your advantage ``` sub('.*/', '', path) # [1] "fooXbar.xls" ``` Also, you shouldn't need the `[]` around the `/` in your `strsplit`. ``` > tail(strsplit(path,"/")[[1]],1) [1] "fooXbar.xls" ...
68,608,899
I want python to be printing a bunch of numbers like 1 to 10000. Then I want to decide when to stop the numbers from printing and the last number printed will be my number. something like. ``` for item in range(10000): print (item) number = input("") ``` But the problem is that it waits for me to place the...
2021/08/01
[ "https://Stackoverflow.com/questions/68608899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13472873/" ]
Catch `KeyboardInterrupt` exception when you interrupts the code by `Ctrl`+`C`: ``` import time try: for item in range(10000): print(item) time.sleep(1) except KeyboardInterrupt: print(f'Last item: {item}') ```
You can use the keyboard module: ``` import keyboard # using module keyboard i=0 while i<10000: # making a loop try: # used try so that if user pressed other than the given key error will not be shown print(i) if keyboard.is_pressed('q'): # if key 'q' is pressed print('Last number:...
22,081,361
I'm wondering if there's a way to fill under a pyplot curve with a vertical gradient, like in this quick mockup: ![image](https://i.imgur.com/ZoWCwRb.png) I found this hack on StackOverflow, and I don't mind the polygons if I could figure out how to make the color map vertical: [How to fill rainbow color under a curv...
2014/02/27
[ "https://Stackoverflow.com/questions/22081361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2774479/" ]
There may be a better way, but here goes: ``` from matplotlib import pyplot as plt x = range(10) y = range(10) z = [[z] * 10 for z in range(10)] num_bars = 100 # more bars = smoother gradient plt.contourf(x, y, z, num_bars) background_color = 'w' plt.fill_between(x, y, y2=max(y), color=background_color) plt.show(...
There is an alternative solution closer to the sketch in the question. It's given on Henry Barthes' blog <http://pradhanphy.blogspot.com/2014/06/filling-between-curves-with-color.html>. This applies an imshow to each of the patches, I've copied the code in case the link changes, ``` import numpy as np import matplotli...
53,494,637
I'm trying to build a Flask app that has Kafka as an interface. I used a Python connector, [kafka-python](https://kafka-python.readthedocs.io/en/master/index.html) and a Docker image for Kafka, [spotify/kafkaproxy](https://hub.docker.com/r/spotify/kafkaproxy/) . Below is the docker-compose file. ``` version: '3.3' se...
2018/11/27
[ "https://Stackoverflow.com/questions/53494637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4306852/" ]
**UPDATE** As mentioned by cricket\_007, given that you are using the docker-compose provided below, you should use `kafka:29092` to connect to Kafka from another container. So your code would look like this: ``` from kafka import KafkaConsumer, KafkaProducer TOPICS = ['PROFILE_CREATED', 'IMG_RATED'] BOOTSTRAP_SERVE...
I managed to get this up-and-running using a [network](https://docs.docker.com/compose/networking/) named `stream_net` between all services. ``` # for local development version: "3.7" services: zookeeper: image: confluentinc/cp-zookeeper:latest environment: ZOOKEEPER_CLIENT_PORT: 2181 ZOOKEEPER_...
65,734,652
I open a binary file with Python3 and want to print byte-by-byte in hex. However, all online resource only mention printing a "byte array" in hex. Please tell me how to print only 1 single byte, thanks. ```py #!/usr/bin/env python3 if __name__ == "__main__": with open("./datasets/data.bin", 'rb') as file: ...
2021/01/15
[ "https://Stackoverflow.com/questions/65734652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1417929/" ]
Try this one: ```py print(hex(byte[0])) ```
Using an `f-string` like this just prints two hex digits for each byte: ```py print(f'{byte[0]:02x}') ```
26,897,208
``` from pythonds.basic.stack import Stack rStack = Stack() def toStr(n,base): convertString = "0123456789ABCDEF" while n > 0: if n < base: rStack.push(convertString[n]) else: rStack.push(convertString[n % base]) n = n // base res = "" while not rStack.i...
2014/11/12
[ "https://Stackoverflow.com/questions/26897208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3448561/" ]
You are right that this particular function is **not** recursive. However, the context is, that on the previous slide there was a recursive function, and in this one they want to show a glimpse of how it *behaves* internally. They later say: > > The previous example [i.e. the one in question - B.] gives us some insig...
Because you're using a stack structure. If you consider how function calling is implemented, recursion is essentially an easy way to get the compiler to manage a stack of invocations for you. This function does all the stack handling manually, but it is still conceptually a recursive function, just one where the stac...
26,897,208
``` from pythonds.basic.stack import Stack rStack = Stack() def toStr(n,base): convertString = "0123456789ABCDEF" while n > 0: if n < base: rStack.push(convertString[n]) else: rStack.push(convertString[n % base]) n = n // base res = "" while not rStack.i...
2014/11/12
[ "https://Stackoverflow.com/questions/26897208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3448561/" ]
A *recursive algorithm*, by definition, [is a method where the solution to a problem depends on solutions to smaller instances of the same problem](https://en.wikipedia.org/wiki/Recursion_%28computer_science%29). Here, the problem is to convert a number to a string in a given notation. The "stockpiling" of data the f...
Because you're using a stack structure. If you consider how function calling is implemented, recursion is essentially an easy way to get the compiler to manage a stack of invocations for you. This function does all the stack handling manually, but it is still conceptually a recursive function, just one where the stac...
26,897,208
``` from pythonds.basic.stack import Stack rStack = Stack() def toStr(n,base): convertString = "0123456789ABCDEF" while n > 0: if n < base: rStack.push(convertString[n]) else: rStack.push(convertString[n % base]) n = n // base res = "" while not rStack.i...
2014/11/12
[ "https://Stackoverflow.com/questions/26897208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3448561/" ]
You are right that this particular function is **not** recursive. However, the context is, that on the previous slide there was a recursive function, and in this one they want to show a glimpse of how it *behaves* internally. They later say: > > The previous example [i.e. the one in question - B.] gives us some insig...
A *recursive algorithm*, by definition, [is a method where the solution to a problem depends on solutions to smaller instances of the same problem](https://en.wikipedia.org/wiki/Recursion_%28computer_science%29). Here, the problem is to convert a number to a string in a given notation. The "stockpiling" of data the f...
15,196,321
my project is to identify a sentiment either positive or negative ( sentiment analysis ) in Arabic language,to do this task I used NLTK and python, when I enter tweets in arabic an error occurs ``` >>> pos_tweets = [(' أساند كل عون أمن شريف', 'positive'), ('ما أحلى الثورة التونسية', 'positive'), ...
2013/03/04
[ "https://Stackoverflow.com/questions/15196321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2048995/" ]
You're on the right track with your `delete_model` method. When the django admin performs an action on multiple objects at once it uses the [update function](https://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once). However, as you see in the docs these actions are performed at the da...
Your method should be ``` class profilesAdmin(admin.ModelAdmin): #... def _profile_delete(self, sender, instance, **kwargs): # do something def delete_model(self, request, object): # do something ``` You should add a reference to current object as the first argument in every method sign...
15,196,321
my project is to identify a sentiment either positive or negative ( sentiment analysis ) in Arabic language,to do this task I used NLTK and python, when I enter tweets in arabic an error occurs ``` >>> pos_tweets = [(' أساند كل عون أمن شريف', 'positive'), ('ما أحلى الثورة التونسية', 'positive'), ...
2013/03/04
[ "https://Stackoverflow.com/questions/15196321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2048995/" ]
You're on the right track with your `delete_model` method. When the django admin performs an action on multiple objects at once it uses the [update function](https://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once). However, as you see in the docs these actions are performed at the da...
The main issue is that the Django admin's bulk delete uses SQL, not instance.delete(), as noted elsewhere. For an admin-only solution, the following solution preserves the Django admin's "do you really want to delete these" interstitial. The most general solution is to override the queryset returned by the model's man...
15,196,321
my project is to identify a sentiment either positive or negative ( sentiment analysis ) in Arabic language,to do this task I used NLTK and python, when I enter tweets in arabic an error occurs ``` >>> pos_tweets = [(' أساند كل عون أمن شريف', 'positive'), ('ما أحلى الثورة التونسية', 'positive'), ...
2013/03/04
[ "https://Stackoverflow.com/questions/15196321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2048995/" ]
You're on the right track with your `delete_model` method. When the django admin performs an action on multiple objects at once it uses the [update function](https://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once). However, as you see in the docs these actions are performed at the da...
you try overriding delete\_model method failed because when you delete multiple objects the django use `QuerySet.delete()`,for efficiency reasons your model’s `delete()` method will not be called. you can see it there <https://docs.djangoproject.com/en/1.9/ref/contrib/admin/actions/> watch the beginning Warning Ad...
15,196,321
my project is to identify a sentiment either positive or negative ( sentiment analysis ) in Arabic language,to do this task I used NLTK and python, when I enter tweets in arabic an error occurs ``` >>> pos_tweets = [(' أساند كل عون أمن شريف', 'positive'), ('ما أحلى الثورة التونسية', 'positive'), ...
2013/03/04
[ "https://Stackoverflow.com/questions/15196321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2048995/" ]
The main issue is that the Django admin's bulk delete uses SQL, not instance.delete(), as noted elsewhere. For an admin-only solution, the following solution preserves the Django admin's "do you really want to delete these" interstitial. The most general solution is to override the queryset returned by the model's man...
Your method should be ``` class profilesAdmin(admin.ModelAdmin): #... def _profile_delete(self, sender, instance, **kwargs): # do something def delete_model(self, request, object): # do something ``` You should add a reference to current object as the first argument in every method sign...
15,196,321
my project is to identify a sentiment either positive or negative ( sentiment analysis ) in Arabic language,to do this task I used NLTK and python, when I enter tweets in arabic an error occurs ``` >>> pos_tweets = [(' أساند كل عون أمن شريف', 'positive'), ('ما أحلى الثورة التونسية', 'positive'), ...
2013/03/04
[ "https://Stackoverflow.com/questions/15196321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2048995/" ]
You can use the [delete\_queryset](https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.delete_queryset) which is coming from [Django 2.1](https://docs.djangoproject.com/en/2.1/) onward for bulk delete objects and the [delete\_model](https://docs.djangoproject.com/en/2.1/ref/contrib/...
Your method should be ``` class profilesAdmin(admin.ModelAdmin): #... def _profile_delete(self, sender, instance, **kwargs): # do something def delete_model(self, request, object): # do something ``` You should add a reference to current object as the first argument in every method sign...
15,196,321
my project is to identify a sentiment either positive or negative ( sentiment analysis ) in Arabic language,to do this task I used NLTK and python, when I enter tweets in arabic an error occurs ``` >>> pos_tweets = [(' أساند كل عون أمن شريف', 'positive'), ('ما أحلى الثورة التونسية', 'positive'), ...
2013/03/04
[ "https://Stackoverflow.com/questions/15196321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2048995/" ]
The main issue is that the Django admin's bulk delete uses SQL, not instance.delete(), as noted elsewhere. For an admin-only solution, the following solution preserves the Django admin's "do you really want to delete these" interstitial. The most general solution is to override the queryset returned by the model's man...
you try overriding delete\_model method failed because when you delete multiple objects the django use `QuerySet.delete()`,for efficiency reasons your model’s `delete()` method will not be called. you can see it there <https://docs.djangoproject.com/en/1.9/ref/contrib/admin/actions/> watch the beginning Warning Ad...
15,196,321
my project is to identify a sentiment either positive or negative ( sentiment analysis ) in Arabic language,to do this task I used NLTK and python, when I enter tweets in arabic an error occurs ``` >>> pos_tweets = [(' أساند كل عون أمن شريف', 'positive'), ('ما أحلى الثورة التونسية', 'positive'), ...
2013/03/04
[ "https://Stackoverflow.com/questions/15196321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2048995/" ]
You can use the [delete\_queryset](https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.delete_queryset) which is coming from [Django 2.1](https://docs.djangoproject.com/en/2.1/) onward for bulk delete objects and the [delete\_model](https://docs.djangoproject.com/en/2.1/ref/contrib/...
The main issue is that the Django admin's bulk delete uses SQL, not instance.delete(), as noted elsewhere. For an admin-only solution, the following solution preserves the Django admin's "do you really want to delete these" interstitial. The most general solution is to override the queryset returned by the model's man...
15,196,321
my project is to identify a sentiment either positive or negative ( sentiment analysis ) in Arabic language,to do this task I used NLTK and python, when I enter tweets in arabic an error occurs ``` >>> pos_tweets = [(' أساند كل عون أمن شريف', 'positive'), ('ما أحلى الثورة التونسية', 'positive'), ...
2013/03/04
[ "https://Stackoverflow.com/questions/15196321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2048995/" ]
You can use the [delete\_queryset](https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.delete_queryset) which is coming from [Django 2.1](https://docs.djangoproject.com/en/2.1/) onward for bulk delete objects and the [delete\_model](https://docs.djangoproject.com/en/2.1/ref/contrib/...
you try overriding delete\_model method failed because when you delete multiple objects the django use `QuerySet.delete()`,for efficiency reasons your model’s `delete()` method will not be called. you can see it there <https://docs.djangoproject.com/en/1.9/ref/contrib/admin/actions/> watch the beginning Warning Ad...
51,861,677
I am trying to solve the problem called [R2](https://open.kattis.com/problems/r2) on kattis but for some reason, while the program (written in python) runs in the IDLE, I am met with a run time error in kattis with the judgement being a valueerror. Here's my code: ``` R1 = int(input('input R1 ')) S = int(input('input...
2018/08/15
[ "https://Stackoverflow.com/questions/51861677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10216731/" ]
``` nums = input().split(' ') r2 = 2*int(nums[1]) - int(nums[0]) print(r2) ``` The problem states that the two numbers will be input on a single line. You are attempting to capture two numbers input on two separate lines by calling `input` twice.
Darrahts pointed one problem out. The 2nd Problem is: `input([prompt])` writes the prompt to the standard output, however you should only write your solution to standard output.
30,205,473
I have the following JSON structure. I am attempting to extract the following information from the "brow\_eventdetails" section. * ATime * SBTime * CTime My question is is there any easy way to do this without using regular expression. In other words my question is the a nested JSON format that I can extract by some ...
2015/05/13
[ "https://Stackoverflow.com/questions/30205473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/316082/" ]
You need to parse again the json string of `json_data['message']` then just access the desired values, one way to do it: ``` # since the string value of `message` itself isn't a valid json string # discard it, and parse it with json again brow_eventdetails = json.loads(json_data['message'].replace('brow_eventdetails:'...
Parse this string value using json.loads as you would with every other string that contains JSON.
34,818,960
I need to highlight a specific word in a text within a tkinter frame. In order to find the word, I put a balise like in html. So in a text like "hello i'm in the |house|" I want to highlight the word "house". My frame is defined like that: `class FrameCodage(Frame): self.t2Codage = Text(self, height=20, width=50)` ...
2016/01/15
[ "https://Stackoverflow.com/questions/34818960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5464538/" ]
Instead of this: ``` class FrameCodage(Frame): self.t2Codage = Text(self, height=20, width=50) ``` ... do this: ``` class FrameCodage(Frame): self.t2Codage = CustomText(self, height=20, width=50) ``` Next, create a "highlight" tag, and configure it however you want: ``` self.t2Codage.tag_configure("highl...
Below is widget I created to deal with this, hope it helps. ``` try: import tkinter as tk except ImportError: import Tkinter as tk class code_editor(tk.Text): def __init__(self, parent, case_insensetive = True, current_line_colour = '', word_end_at = r""" .,{}[]()=+-*/\|<>%""", tags = {}, *args, **kwargs): ...
14,670,768
Hi I'm new to django and python. I want to extend django `User` model and add a `create_user` method in a model, then I call this `create_user` method from view. However, I got an error msg. My model: ``` from django.db import models from django.contrib.auth.models import User class Basic(models.Model): user = m...
2013/02/03
[ "https://Stackoverflow.com/questions/14670768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/204127/" ]
Try ``` Basic.create_ck_user('fb', fb_id, fb_token) ``` You don't assign to strings when you call a function/method. You assign to variables. But since you are using positional arguments in your function definition then you don't even need them. Assigning to a string will never work anyway... strings are immutable...
Just look here: <https://docs.djangoproject.com/en/dev/topics/auth/default/#creating-users> You can find a lot of answers just looking at the documentation.
30,183,795
I know the normal way to use APScheduler is "python setup.py install". But I want to embed it into my program directly, so the user don't need install it when using my program. ``` class BaseScheduler(six.with_metaclass(ABCMeta)): _trigger_plugins = dict((ep.name, ep) for ep in iter_entry_points('apscheduler.triggers...
2015/05/12
[ "https://Stackoverflow.com/questions/30183795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/620853/" ]
You can instantiate the triggers directly, without going through their aliases. That eliminates the need to install APScheduler or setuptools. Does this answer your question?
I find a way to work around this problem. 1. use 'pip install apscheduler' to install locally 2. goto the installed directory and cp that directory to your lib directory 3. use 'pip uninstall apscheduler' to remove it. 4. make you code to import the apscheduler from your lib directory. 5. done.
11,174,997
(Python 2.7)I need to print the bfs of a binary tree with a given preorder and inorder and a max lenght of the strings of preorder and inorder. I know how it works, for example: preorder:ABCDE inorder:CBDAE max length:5 ``` A / \ B E / \ C...
2012/06/24
[ "https://Stackoverflow.com/questions/11174997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1419828/" ]
I guess essentially the question is how to get all the parent-leftChild pairs and parent-rightChild pairs of the tree from given preorder and inorder To get the parent-leftChild pairs, you need to check: 1) if node1 is right after node2 in preorder; 2) if node2 is in front of node1 in inorder For your example preorde...
To add children to any node, just get the node that you want to add children to and call setLeftChild or setRightChild on it.
11,174,997
(Python 2.7)I need to print the bfs of a binary tree with a given preorder and inorder and a max lenght of the strings of preorder and inorder. I know how it works, for example: preorder:ABCDE inorder:CBDAE max length:5 ``` A / \ B E / \ C...
2012/06/24
[ "https://Stackoverflow.com/questions/11174997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1419828/" ]
To add children to any node, just get the node that you want to add children to and call setLeftChild or setRightChild on it.
If you're using BFS - you ideally want to be using a graph - an excellent library is [networkx](http://networkx.lanl.gov/index.html) An example: ``` import networkx as nx g = nx.DiGraph() g.add_edge('A', 'B') g.add_edge('A', 'E') g.add_edge('B', 'C') g.add_edge('B', 'D') print 'A' + ''.join(node[1] for node in (nx....
11,174,997
(Python 2.7)I need to print the bfs of a binary tree with a given preorder and inorder and a max lenght of the strings of preorder and inorder. I know how it works, for example: preorder:ABCDE inorder:CBDAE max length:5 ``` A / \ B E / \ C...
2012/06/24
[ "https://Stackoverflow.com/questions/11174997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1419828/" ]
I guess essentially the question is how to get all the parent-leftChild pairs and parent-rightChild pairs of the tree from given preorder and inorder To get the parent-leftChild pairs, you need to check: 1) if node1 is right after node2 in preorder; 2) if node2 is in front of node1 in inorder For your example preorde...
If you're using BFS - you ideally want to be using a graph - an excellent library is [networkx](http://networkx.lanl.gov/index.html) An example: ``` import networkx as nx g = nx.DiGraph() g.add_edge('A', 'B') g.add_edge('A', 'E') g.add_edge('B', 'C') g.add_edge('B', 'D') print 'A' + ''.join(node[1] for node in (nx....
61,590,927
I have a rather simple program using `dask`: ``` import dask.array as darray import numpy as np X = np.array([[1.,2.,3.], [4.,5.,6.], [7.,8.,9.]]) arr = darray.from_array(X) arr = arr[:,0] a = darray.min(arr) b = darray.max(arr) quantiles = darray.linspace(a, b, 4) print(np.array(quantiles...
2020/05/04
[ "https://Stackoverflow.com/questions/61590927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2595776/" ]
Simply use `dnf` ```sh dnf -y install gcc-toolset-9-gcc gcc-toolset-9-gcc-c++ source /opt/rh/gcc-toolset-9/enable ``` ref: <https://centos.pkgs.org/8/centos-appstream-x86_64/gcc-toolset-9-gcc-9.1.1-2.4.el8.x86_64.rpm.html> Note: `source` won't work inside a Dockerfile so prefer to use: ``` ENV PATH=/opt/rh/gcc-too...
this command work for me ``` dnf install gcc --best --allowerasing ```
55,422,150
This is my first time using python and matplotlib and I'd like to plot data from a CSV file. The CSV file is in the form of: ``` 10/03/2018 00:00,454.95,594.86 ``` with about 4000 rows. I'd like to plot the data from the second column vs the datetime for each row and the data from the third column vs the datetime ...
2019/03/29
[ "https://Stackoverflow.com/questions/55422150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11245101/" ]
Just use promises (or callbacks) ================================ I know that everyone hates JavaScript and so these anti-idiomatic transpilers and new language "features" exist to make JavaScript look like C# and whatnot but, honestly, it's just easier to use the language the way that it was originally designed (othe...
Here's my updated function that works properly and synchronously, getting the data one by one and adding it to the database before moving to the next one. I have made it by customizing @coolAJ86 answer and I've marked that as the correct one but thought it would be helpful for people stumbling across this thread to s...
48,685,715
The problem is very simple: I want to call a script from a rule and I would like that rule to both: * Perform stdout and stderr redirection * Access the snakemake variables from the script(variable can be both lists and literals) If I use the `shell:` then, I can perform the I/O redirection but I cannot use the `...
2018/02/08
[ "https://Stackoverflow.com/questions/48685715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1935611/" ]
If possible, I suggest you use the [argparse](https://docs.python.org/3/library/argparse.html) module to parse the input of your script, so that it can parse a list of arguments as such, using the `nargs="*"` option: ```python def main(): """Main function of the program.""" parser = argparse.ArgumentParser( ...
You can access the log filenames within the python script with the snakemake.log varaibale, which is a list containing both filenames: ``` snakemake.log = [ LOG_FILES+'/create_hdf5/sample_1.out', LOG_FILES+'/create_hdf5/sample_1.err' ] ``` you can thus use this within your script to create log files for logging, e.g...
65,095,357
When I am adding new functions to a file I can't import them neither if I just run the script in terminal or if I launch `ipython` and try importing a function there. I have no `.pyc` files. It looks as if there is some kind of caching going on. I never actually faced such an issue even though have been working with va...
2020/12/01
[ "https://Stackoverflow.com/questions/65095357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3815432/" ]
We can use `pd.to_datetime` here with `errors='coerce'` to ignore the faulty dates. Then use the `dt.year` to calculate the difference: ``` df['date_until'] = pd.to_datetime(df['date_until'], format='%d.%m.%y', errors='coerce') df['diff_year'] = df['date_until'].dt.year - df['year'] ``` ``` year date_until diff_...
For everybody who is trying to replace values just like I wanted to in the first place, here is how you could solve it: ``` for i in range(len(df)): if pd.isna(df['date_until'].iloc[i]): df['date_until'].iloc[i] = f'30.06.{df["year"].iloc[i] +1}' if df['date_until'].iloc[i] == '-': df['date_unt...
47,726,913
I am trying to run the following code here to save information to the database. I have seen other messages - but - it appears that the solutions are for older versions of `Python/DJango` (as they do not seem to be working on the versions I am using now: `Python 3.6.3` and `DJango 1.11.7` ``` if form.is_valid(): tr...
2017/12/09
[ "https://Stackoverflow.com/questions/47726913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2707727/" ]
Just change ``` str(e.message) ``` to ``` str(e) ```
**some change** > > str(e.message) > > > **to** > > HttpResponse(e.message) > > >
60,543,957
I have a project folder with different cloud functions folders e.g. ``` Project_Folder -Cloud-Function-Folder1 -main.py -requirements.txt -cloudbuild.yaml -Cloud-Function-Folder2 -main.py -requirements.txt -cloudbuild.yaml -Cloud-Function-Folder3 ...
2020/03/05
[ "https://Stackoverflow.com/questions/60543957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6508416/" ]
It's more complex et you have to play with limit and constraint of Cloud Build. I do this: * get the directory updated since the previous commit * loop on this directory and do what I want --- **Hypothesis 1**: all the subfolders are deployed by using the same commands So, for this I put a `cloudbuild.yaml` at the...
If you create a single source repo and change your code as one cloud function you have to create a single ['cloudbuild.yaml' configuration file](https://cloud.google.com/cloud-build/docs/build-config). You need to connect this single repo to Cloud Build. Then create a [build trigger](https://cloud.google.com/cloud-buil...
60,543,957
I have a project folder with different cloud functions folders e.g. ``` Project_Folder -Cloud-Function-Folder1 -main.py -requirements.txt -cloudbuild.yaml -Cloud-Function-Folder2 -main.py -requirements.txt -cloudbuild.yaml -Cloud-Function-Folder3 ...
2020/03/05
[ "https://Stackoverflow.com/questions/60543957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6508416/" ]
This is quite straightforward, however you need to control the behavior on the Build Trigger side of things and not on the `cloudbuild.yaml`. Conceptually, you want to limit the cloud build trigger behavior and limit it to certain changes within a repo. As such, make use of the regEx glob include filter in the Build T...
If you create a single source repo and change your code as one cloud function you have to create a single ['cloudbuild.yaml' configuration file](https://cloud.google.com/cloud-build/docs/build-config). You need to connect this single repo to Cloud Build. Then create a [build trigger](https://cloud.google.com/cloud-buil...
60,543,957
I have a project folder with different cloud functions folders e.g. ``` Project_Folder -Cloud-Function-Folder1 -main.py -requirements.txt -cloudbuild.yaml -Cloud-Function-Folder2 -main.py -requirements.txt -cloudbuild.yaml -Cloud-Function-Folder3 ...
2020/03/05
[ "https://Stackoverflow.com/questions/60543957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6508416/" ]
you can do this by creating a folder for each of the functions like this ``` Project_Folder -Cloud-Function-Folder1 -main.py -requirements.txt -cloudbuild.yaml -Cloud-Function-Folder2 -main.py -requirements.txt -cloudbuild.yaml -Cloud-Function-Folder3 ...
If you create a single source repo and change your code as one cloud function you have to create a single ['cloudbuild.yaml' configuration file](https://cloud.google.com/cloud-build/docs/build-config). You need to connect this single repo to Cloud Build. Then create a [build trigger](https://cloud.google.com/cloud-buil...
60,543,957
I have a project folder with different cloud functions folders e.g. ``` Project_Folder -Cloud-Function-Folder1 -main.py -requirements.txt -cloudbuild.yaml -Cloud-Function-Folder2 -main.py -requirements.txt -cloudbuild.yaml -Cloud-Function-Folder3 ...
2020/03/05
[ "https://Stackoverflow.com/questions/60543957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6508416/" ]
It's more complex et you have to play with limit and constraint of Cloud Build. I do this: * get the directory updated since the previous commit * loop on this directory and do what I want --- **Hypothesis 1**: all the subfolders are deployed by using the same commands So, for this I put a `cloudbuild.yaml` at the...
This is quite straightforward, however you need to control the behavior on the Build Trigger side of things and not on the `cloudbuild.yaml`. Conceptually, you want to limit the cloud build trigger behavior and limit it to certain changes within a repo. As such, make use of the regEx glob include filter in the Build T...
60,543,957
I have a project folder with different cloud functions folders e.g. ``` Project_Folder -Cloud-Function-Folder1 -main.py -requirements.txt -cloudbuild.yaml -Cloud-Function-Folder2 -main.py -requirements.txt -cloudbuild.yaml -Cloud-Function-Folder3 ...
2020/03/05
[ "https://Stackoverflow.com/questions/60543957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6508416/" ]
It's more complex et you have to play with limit and constraint of Cloud Build. I do this: * get the directory updated since the previous commit * loop on this directory and do what I want --- **Hypothesis 1**: all the subfolders are deployed by using the same commands So, for this I put a `cloudbuild.yaml` at the...
you can do this by creating a folder for each of the functions like this ``` Project_Folder -Cloud-Function-Folder1 -main.py -requirements.txt -cloudbuild.yaml -Cloud-Function-Folder2 -main.py -requirements.txt -cloudbuild.yaml -Cloud-Function-Folder3 ...
30,857,579
To be more specific: Is there a way for a python program to continue running even after it's closed (like automatic open at a certain time)? Or like a gmail notification? This is for an alarm project, and I want it to ring/open itself even if the user closes the window. Is there a way for this to happen/get scripted? I...
2015/06/16
[ "https://Stackoverflow.com/questions/30857579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4343751/" ]
You can implement a global `operator>>` for your `Numbers` class, eg: ``` std::istream& operator>>(std::istream &strm, Number &n) { int value; strm >> value; // or however you need to read the value... n = Number(value); return strm; } ``` Or: ``` class Number { //... friend std::istream& op...
You will probably have to return `number` at the end of function `getNumbersFromUser` to avoid memory leakage. Secondly, the line `cin >> number[i]` means that you are taking input in a variable of type `Number` which is not allowed. It is only allowed for primitive data type (int, char double etc.) or some built in ob...