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
20,289,373
I am developing a program in python and have reached a point I don't know how to solve. My intention is to use a `with` statement, an avoid the usage of try/except. So far, my idea is being able to use the `continue` statement as it would be used inside the `except`. However, I don't seem to succeed. Let's supposse this is my code: ``` def A(object): def __enter__: return self def __exit__: return True with A(): print "Ok" raise Exception("Excp") print "I want to get here" print "Outside" ``` Reading the docs I have found out that by returning True inside the `__exit__` method, I can prevent the exception from passing, as with the `pass` statement. However, this will immediately skip everything left to do in the with, which I'm trying to avoid as I want everything to be executed, even if an exception is raised. So far I haven't been able to find a way to do this. Any advice would be appreciated. Thank you very much.
2013/11/29
[ "https://Stackoverflow.com/questions/20289373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It's not possible. The only two options are (a) let the exception propagate by returning a false-y value or (b) swallow the exception by returning True. There is no way to resume the code block from where the exception was thrown. Either way, your `with` block is over.
You can't. The `with` statement's purpose is to handle cleanup automatically (which is why exceptions can be suppressed *when exiting it*), not to act as Visual Basic's infamous `On Error Resume Next`. If you want to continue the execution of a block after an exception is raised, you need to wrap whatever raises the exception in a `try/except` statement.
20,289,373
I am developing a program in python and have reached a point I don't know how to solve. My intention is to use a `with` statement, an avoid the usage of try/except. So far, my idea is being able to use the `continue` statement as it would be used inside the `except`. However, I don't seem to succeed. Let's supposse this is my code: ``` def A(object): def __enter__: return self def __exit__: return True with A(): print "Ok" raise Exception("Excp") print "I want to get here" print "Outside" ``` Reading the docs I have found out that by returning True inside the `__exit__` method, I can prevent the exception from passing, as with the `pass` statement. However, this will immediately skip everything left to do in the with, which I'm trying to avoid as I want everything to be executed, even if an exception is raised. So far I haven't been able to find a way to do this. Any advice would be appreciated. Thank you very much.
2013/11/29
[ "https://Stackoverflow.com/questions/20289373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It's not possible. The only two options are (a) let the exception propagate by returning a false-y value or (b) swallow the exception by returning True. There is no way to resume the code block from where the exception was thrown. Either way, your `with` block is over.
Though most of the answers are correct, I'm afraid none suits my problem (I know I didn't provide my whole code, sorry about that). I've solved the problem taking another approach. I wanted to be able to handle a NameError ("variable not declared") inside a With. If that occurred, I would look inside my object for that variable, and continue. I'm now using globals() to declare the variable. It's not the best, but it actually works and let's the with continue as no exception is being risen. Thank you all!
20,289,373
I am developing a program in python and have reached a point I don't know how to solve. My intention is to use a `with` statement, an avoid the usage of try/except. So far, my idea is being able to use the `continue` statement as it would be used inside the `except`. However, I don't seem to succeed. Let's supposse this is my code: ``` def A(object): def __enter__: return self def __exit__: return True with A(): print "Ok" raise Exception("Excp") print "I want to get here" print "Outside" ``` Reading the docs I have found out that by returning True inside the `__exit__` method, I can prevent the exception from passing, as with the `pass` statement. However, this will immediately skip everything left to do in the with, which I'm trying to avoid as I want everything to be executed, even if an exception is raised. So far I haven't been able to find a way to do this. Any advice would be appreciated. Thank you very much.
2013/11/29
[ "https://Stackoverflow.com/questions/20289373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can't. The `with` statement's purpose is to handle cleanup automatically (which is why exceptions can be suppressed *when exiting it*), not to act as Visual Basic's infamous `On Error Resume Next`. If you want to continue the execution of a block after an exception is raised, you need to wrap whatever raises the exception in a `try/except` statement.
Though most of the answers are correct, I'm afraid none suits my problem (I know I didn't provide my whole code, sorry about that). I've solved the problem taking another approach. I wanted to be able to handle a NameError ("variable not declared") inside a With. If that occurred, I would look inside my object for that variable, and continue. I'm now using globals() to declare the variable. It's not the best, but it actually works and let's the with continue as no exception is being risen. Thank you all!
73,642,679
I have a function in C which is integrated into python as a library. The python looks something like this: ``` import ctypes import numpy as np lib=ctypes.cdll.LoadLibrary("./array.so") lib.eq.argtypes=(ctypes.c_int, ctypes.POINTER(ctypes.c_float), ctypes.POINTER(ctypes.c_float)) params = parameters.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) results = np.zeros(5).ctypes.data_as(ctypes.POINTER(ctypes.c_float)) lib.get_results(ctypes.c_int(5),params,results) ``` And the C code in array.c looks something like: ``` void get_results(int size, float params[], float results[5]) { 'do some calculations which use params' results[0] = ... results[1] = ... results[2] = ... results[3] = ... results[4] = ... } ``` How would one access the array(pointer) `results` in python? I couldn't figure it out since the void function in C doesn't actually return any value.
2022/09/08
[ "https://Stackoverflow.com/questions/73642679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18335909/" ]
You were close. The input arrays need to be `dtypes=np.float32` (or `ct.c_float`) to match the C 32-bit `float` parameters. `results` is changed in-place so print the updated `results` after the function call. You can also use `ndpointer` to declare the *exact* type of arrays expected, so `ctypes` can check the the correct array type is passed. In your original code `np.zeros(5)` defaults to `np.float64` type. **test.c** ```c #ifdef _WIN32 # define API __declspec(dllexport) #else # define API #endif API void get_results(int size, float params[], float results[5]) { // Make some kind of calculation for(int i = 0; i < size; ++i) { results[0] += params[i]; results[1] += params[i] * 2; results[2] += params[i] * 3; results[3] += params[i] * 4; results[4] += params[i] * 5; } } ``` **test.py** ```py import ctypes as ct import numpy as np lib = ct.CDLL('./test') # Since you are using numpy, we can use ndpointer to declare # the exact type of numpy array expected. In this case, # params is a one-dimensional array of any size, and # results is a one-dimensional array of exactly 5 elements. # Both need to be of np.float32 type to match C float. lib.get_results.argtypes = (ct.c_int, np.ctypeslib.ndpointer(dtype=np.float32, ndim=1), np.ctypeslib.ndpointer(dtype=np.float32, shape=(5,))) lib.get_results.restype = None params = np.array([1,2,3], dtype=np.float32) results = np.zeros(5, dtype=np.float32) lib.get_results(len(params), params, results) print(results) ``` Output: ```none [ 6. 12. 18. 24. 30.] ```
My suggestion: ```py import ctypes import numpy as np from os.path import abspath from ctypes import cdll, c_void_p, c_int params = np.ascontiguousarray(np.zeros(5, dtype=np.float64)) results = np.ascontiguousarray(np.zeros(5, dtype=np.float64)) lib = cdll.LoadLibrary(abspath('array.so')) # loading the compiled binary shared C library, which should be located in the same directory as this Python script; absolute path is more important for Linux β€” not necessary for MacOS f = lib.get_results # assigning the C interface function to this Python variable "f" f.arguments = [ c_int, c_void_p, c_void_p ] # declaring the data types for C function arguments f.restype = c_int # declaring the data types for C function return value res = f(params.size, c_void_p(params.ctypes.data), c_void_p(results.ctypes.data)) # calling the C interface function print(res) print(results) ``` ```c int get_results(int size, double * params, double * results) { /* do some calculations which use params */ results[0] = ...; results[1] = ...; results[2] = ...; results[3] = ...; results[4] = ...; return whatever; } ```
73,224,353
**Context** An empty list: `my_list = []` I also have a list of lists of strings: words\_list = `[['this', '', 'is'], ['a', 'list', ''], ['of', 'lists']]` But note that there are some elements in the lists that are null. **Ideal output** I want to randomly choose a non null element from each list in `words_list` and append that to `my_list` as an element. e.g. ``` >> my_list ['this', 'list', 'of'] ``` **What I currently have** ``` for i in words_list: my_list.append(random.choice(words)) ``` **My issue** but it throws this error: ``` File "random_word_match.py", line 56, in <module> get_random_word(lines) File "random_word_match.py", line 51, in get_random_word word_list.append(random.choice(words)) File "/Users/nathancahn/miniconda3/envs/linguafranca/lib/python3.7/random.py", line 261, in choice raise IndexError('Cannot choose from an empty sequence') from None IndexError: Cannot choose from an empty sequence ``` **What I don't want** I don't want to only append the first non null element I don't want null values in `my_list`
2022/08/03
[ "https://Stackoverflow.com/questions/73224353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10587373/" ]
Maybe you can try to start thinking this way: The idea is quite simple - just go through the list of words, and choose the non-empty word then passing to *choice*. ```py >>> for word in words_list: wd = choice([w for w in word if w]) # if w is non-null, choice will pick it... print(wd) # then just add those non-null word into your my_list --- leave as exercise. # Like this: >>> for word in words_list: wd = choice([w for w in word if w]) my_list.append(wd) >>> my_list ['this', 'a', 'lists'] # Later, you could even simplify this into a List Comprehension. ```
Try below code and see if it works for you: ``` import random my_list = [] words_list = [['this', '', 'is'], ['a', 'list', ''], ['of', 'lists']] for sublist in words_list: filtered_list = list(filter(None, sublist)) my_list.append(random.choice(filtered_list)) print(my_list) ```
73,224,353
**Context** An empty list: `my_list = []` I also have a list of lists of strings: words\_list = `[['this', '', 'is'], ['a', 'list', ''], ['of', 'lists']]` But note that there are some elements in the lists that are null. **Ideal output** I want to randomly choose a non null element from each list in `words_list` and append that to `my_list` as an element. e.g. ``` >> my_list ['this', 'list', 'of'] ``` **What I currently have** ``` for i in words_list: my_list.append(random.choice(words)) ``` **My issue** but it throws this error: ``` File "random_word_match.py", line 56, in <module> get_random_word(lines) File "random_word_match.py", line 51, in get_random_word word_list.append(random.choice(words)) File "/Users/nathancahn/miniconda3/envs/linguafranca/lib/python3.7/random.py", line 261, in choice raise IndexError('Cannot choose from an empty sequence') from None IndexError: Cannot choose from an empty sequence ``` **What I don't want** I don't want to only append the first non null element I don't want null values in `my_list`
2022/08/03
[ "https://Stackoverflow.com/questions/73224353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10587373/" ]
You can use list comprehension: ```py from random import choice words_list = [['this', '', 'is'], ['a', 'list', ''], ['of', 'lists']] output = [choice([word for word in words if word]) for words in words_list] print(output) # ['is', 'a', 'lists'] ```
Try below code and see if it works for you: ``` import random my_list = [] words_list = [['this', '', 'is'], ['a', 'list', ''], ['of', 'lists']] for sublist in words_list: filtered_list = list(filter(None, sublist)) my_list.append(random.choice(filtered_list)) print(my_list) ```
73,224,353
**Context** An empty list: `my_list = []` I also have a list of lists of strings: words\_list = `[['this', '', 'is'], ['a', 'list', ''], ['of', 'lists']]` But note that there are some elements in the lists that are null. **Ideal output** I want to randomly choose a non null element from each list in `words_list` and append that to `my_list` as an element. e.g. ``` >> my_list ['this', 'list', 'of'] ``` **What I currently have** ``` for i in words_list: my_list.append(random.choice(words)) ``` **My issue** but it throws this error: ``` File "random_word_match.py", line 56, in <module> get_random_word(lines) File "random_word_match.py", line 51, in get_random_word word_list.append(random.choice(words)) File "/Users/nathancahn/miniconda3/envs/linguafranca/lib/python3.7/random.py", line 261, in choice raise IndexError('Cannot choose from an empty sequence') from None IndexError: Cannot choose from an empty sequence ``` **What I don't want** I don't want to only append the first non null element I don't want null values in `my_list`
2022/08/03
[ "https://Stackoverflow.com/questions/73224353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10587373/" ]
Maybe you can try to start thinking this way: The idea is quite simple - just go through the list of words, and choose the non-empty word then passing to *choice*. ```py >>> for word in words_list: wd = choice([w for w in word if w]) # if w is non-null, choice will pick it... print(wd) # then just add those non-null word into your my_list --- leave as exercise. # Like this: >>> for word in words_list: wd = choice([w for w in word if w]) my_list.append(wd) >>> my_list ['this', 'a', 'lists'] # Later, you could even simplify this into a List Comprehension. ```
The `random` module contains a function `choices` that's a little more flexible than `choice`. It will take a list of weights that determine the odds of picking a particular element; if the weight is zero, it won't be selected. ``` for words in words_list: weights = [w != '' for w in words] if any(weights): my_list.extend(random.choices(words, weights)) >>> my_list ['is', 'list', 'of'] ```
73,224,353
**Context** An empty list: `my_list = []` I also have a list of lists of strings: words\_list = `[['this', '', 'is'], ['a', 'list', ''], ['of', 'lists']]` But note that there are some elements in the lists that are null. **Ideal output** I want to randomly choose a non null element from each list in `words_list` and append that to `my_list` as an element. e.g. ``` >> my_list ['this', 'list', 'of'] ``` **What I currently have** ``` for i in words_list: my_list.append(random.choice(words)) ``` **My issue** but it throws this error: ``` File "random_word_match.py", line 56, in <module> get_random_word(lines) File "random_word_match.py", line 51, in get_random_word word_list.append(random.choice(words)) File "/Users/nathancahn/miniconda3/envs/linguafranca/lib/python3.7/random.py", line 261, in choice raise IndexError('Cannot choose from an empty sequence') from None IndexError: Cannot choose from an empty sequence ``` **What I don't want** I don't want to only append the first non null element I don't want null values in `my_list`
2022/08/03
[ "https://Stackoverflow.com/questions/73224353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10587373/" ]
You can use list comprehension: ```py from random import choice words_list = [['this', '', 'is'], ['a', 'list', ''], ['of', 'lists']] output = [choice([word for word in words if word]) for words in words_list] print(output) # ['is', 'a', 'lists'] ```
The `random` module contains a function `choices` that's a little more flexible than `choice`. It will take a list of weights that determine the odds of picking a particular element; if the weight is zero, it won't be selected. ``` for words in words_list: weights = [w != '' for w in words] if any(weights): my_list.extend(random.choices(words, weights)) >>> my_list ['is', 'list', 'of'] ```
46,600,413
New to programming and currently working with python. I am trying to take a user inputted string (containing letters, numbers and special characters), I then need to split it multiple times at different points to reform new strings. I have done research on the splitting of strings (and lists) and feel I understand it but I still know there must be a better way to do this than I can think of. This is what I currently have ``` ass=input("Enter Assembly Number: ") #Sample Input 1 - BF90UQ70321-14 #Sample Input 2 - BS73OA91136-43 ass0=ass[0] ass1=ass[1] ass2=ass[2] ass3=ass[3] ass4=ass[4] ass5=ass[5] ass6=ass[6] ass7=ass[7] ass8=ass[8] ass9=ass[9] ass10=ass[10] ass11=ass[11] ass12=ass[12] ass13=ass[13] code1=ass0+ass2+ass3+ass4+ass5+ass6+ass13 code2=ass0+ass2+ass3+ass4+ass5+ass6+ass9 code3=ass1+ass4+ass6+ass7+ass12+ass6+ass13 code4=ass1+ass2+ass4+ass5+ass6+ass9+ass12 # require 21 different code variations ``` Please tell me that there is a better way to do this. Thank you
2017/10/06
[ "https://Stackoverflow.com/questions/46600413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8660214/" ]
change your jquery code to ``` $('#forgotPassword').click(function() { var base_url = '<?php echo base_url()?>'; $('#forgotPasswordEmailError').text(''); var email = $('#forgotPasswordEmail').val(); console.log(email); if(email == ''){ $('#forgotPasswordEmailError').text('Email is required'); }else{ $.ajax({ url : base_url + 'Home/forgotPassword', type : 'POST', data : {email : email}, dataType:'json', success: function(data) { console.log(data); //location.reload(); } }); } }); ``` change your controller code like ``` public function forgotPassword() { $email = $this->input->post('email'); $response = ["email" => $email]; echo json_encode($response); } ```
Instead of ``` echo $email; ``` use: ``` $response = ["email" => $email]; return json_encode($response); ``` And parse JSON, on client side, using `JSON.parse`.
46,600,413
New to programming and currently working with python. I am trying to take a user inputted string (containing letters, numbers and special characters), I then need to split it multiple times at different points to reform new strings. I have done research on the splitting of strings (and lists) and feel I understand it but I still know there must be a better way to do this than I can think of. This is what I currently have ``` ass=input("Enter Assembly Number: ") #Sample Input 1 - BF90UQ70321-14 #Sample Input 2 - BS73OA91136-43 ass0=ass[0] ass1=ass[1] ass2=ass[2] ass3=ass[3] ass4=ass[4] ass5=ass[5] ass6=ass[6] ass7=ass[7] ass8=ass[8] ass9=ass[9] ass10=ass[10] ass11=ass[11] ass12=ass[12] ass13=ass[13] code1=ass0+ass2+ass3+ass4+ass5+ass6+ass13 code2=ass0+ass2+ass3+ass4+ass5+ass6+ass9 code3=ass1+ass4+ass6+ass7+ass12+ass6+ass13 code4=ass1+ass2+ass4+ass5+ass6+ass9+ass12 # require 21 different code variations ``` Please tell me that there is a better way to do this. Thank you
2017/10/06
[ "https://Stackoverflow.com/questions/46600413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8660214/" ]
change your jquery code to ``` $('#forgotPassword').click(function() { var base_url = '<?php echo base_url()?>'; $('#forgotPasswordEmailError').text(''); var email = $('#forgotPasswordEmail').val(); console.log(email); if(email == ''){ $('#forgotPasswordEmailError').text('Email is required'); }else{ $.ajax({ url : base_url + 'Home/forgotPassword', type : 'POST', data : {email : email}, dataType:'json', success: function(data) { console.log(data); //location.reload(); } }); } }); ``` change your controller code like ``` public function forgotPassword() { $email = $this->input->post('email'); $response = ["email" => $email]; echo json_encode($response); } ```
hi maybe i can help someone, i had the same problem, in my case the error was here "url : base\_url + 'Home/forgotPassword'" in this example i have to pass all way like this url : /anotherdirectory/Home/forgotPassword.php', take a look in your "url" $.ajax({ url : "change here fo works"', type : 'POST', data : {email : email}, dataType:'json', success: function(data) { console.log(data); //location.reload(); }
33,146,316
Sorry, I'm a newbie of nodejs. I'd like to try the package `win32ole` in nodejs under Windows7, but when I run the installation command `npm install win32ole` in a command prompt window opened as administrator, many errors pop up. My configuration is: * Windows 7 64 bit (version 6.1.7601) * Microsoft Visual Studio Express 2015 for Windows Desktop - ENU (imho having to install 20GB of software to try to make node-gyp work is like a certification of failure for a certain IT model) * Microsoft .NET Framework 4.6 * both Python 2.7.9 and 3.4.3 installed, but I made `python` command point to 2.7.9 * nodejs version 4.2.1 * npm version 2.14.7 * node-gyp 3.0.3 * `PYTHON` environment variable set to `C:\Python27\python.exe` * told to `node-gyp` where to find Python with command `node-gyp --python C:\Python27\` * told to `npm` where to find Python with command `npm config set python C:\Python27\python.exe` Here's the console output: ``` C:\Windows\system32 >npm install win32ole Impossibile trovare il percorso specificato. npm WARN engine win32ole@0.1.3: wanted: {"node":">= 0.8.18 && < 0.9.0"} (current: {"node":"4.2.1","npm":"2.14.7"}) \ > ref@1.2.0 install C:\Windows\system32\node_modules\win32ole\node_modules\ref > node-gyp rebuild C:\Windows\system32\node_modules\win32ole\node_modules\ref >if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild ) else (node rebuild ) Impossibile trovare il percorso specificato. gyp: Call to 'node -e "require('nan')"' returned exit status 1. while trying to load binding.gyp gyp ERR! configure error gyp ERR! stack Error: `gyp` failed with exit code: 1 gyp ERR! stack at ChildProcess.onCpExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:355:16) gyp ERR! stack at emitTwo (events.js:87:13) gyp ERR! stack at ChildProcess.emit (events.js:172:7) gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12) gyp ERR! System Windows_NT 6.1.7601 gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" gyp ERR! cwd C:\Windows\system32\node_modules\win32ole\node_modules\ref gyp ERR! node -v v4.2.1 gyp ERR! node-gyp -v v3.0.3 gyp ERR! not ok npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "win32ole" npm ERR! node v4.2.1 npm ERR! npm v2.14.7 npm ERR! code ELIFECYCLE npm ERR! ref@1.2.0 install: `node-gyp rebuild` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the ref@1.2.0 install script 'node-gyp rebuild'. npm ERR! This is most likely a problem with the ref package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! node-gyp rebuild npm ERR! You can get their info via: npm ERR! npm owner ls ref npm ERR! There is likely additional logging output above. npm ERR! Please include the following file with any support request: npm ERR! C:\Windows\system32\npm-debug.log ``` Any clue on what I'm doing wrong? **FOLLOW UP** I guess there is nothing I'm doing wrong, the package `node-gyp` under Windows, as pointed out in a comment, has some issues: <https://github.com/nodejs/node-gyp/issues/629>
2015/10/15
[ "https://Stackoverflow.com/questions/33146316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/694360/" ]
It's not possible with up to date node.js versions. Use [node winax](https://www.npmjs.com/package/winax)
First of all you have a **warning** due to the node version ``` npm WARN engine win32ole@0.1.3: wanted: {"node":">= 0.8.18 && < 0.9.0"} (current: {"node":"4.2.1","npm":"2.14.7"}) ``` It should be lower than 0.9.0 Have you installed **node-gyp**? I'm seeing a lot of error complaining it. If not you can install it with this command ``` npm install -g node-gyp ```
6,119,038
I'm writing a bash script that fires up python and then enters some simple commands before exiting. I've got it firing up python ok, but how do I make the script simulate keyboard input in the python shell, as though a person were doing it?
2011/05/25
[ "https://Stackoverflow.com/questions/6119038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193601/" ]
Use a "here" document. It looks like this ``` command << HERE text that someone types in more text HERE ``` You don'th have to use "HERE", you can use something that has a little more meaning relative to the context of your code.
Have you tried `echo "Something for input" | python myPythonScript.py` ?
6,119,038
I'm writing a bash script that fires up python and then enters some simple commands before exiting. I've got it firing up python ok, but how do I make the script simulate keyboard input in the python shell, as though a person were doing it?
2011/05/25
[ "https://Stackoverflow.com/questions/6119038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193601/" ]
Have you tried `echo "Something for input" | python myPythonScript.py` ?
I haven't used python, but normally I echo a command string and pipe it to the interpreter binary like so: ``` $ echo '<?php echo "2+2\n"; ?>' | /usr/bin/php 2+2 ``` I'm assuming you can do the same w/ python.
6,119,038
I'm writing a bash script that fires up python and then enters some simple commands before exiting. I've got it firing up python ok, but how do I make the script simulate keyboard input in the python shell, as though a person were doing it?
2011/05/25
[ "https://Stackoverflow.com/questions/6119038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193601/" ]
Use a "here" document. It looks like this ``` command << HERE text that someone types in more text HERE ``` You don'th have to use "HERE", you can use something that has a little more meaning relative to the context of your code.
I haven't used python, but normally I echo a command string and pipe it to the interpreter binary like so: ``` $ echo '<?php echo "2+2\n"; ?>' | /usr/bin/php 2+2 ``` I'm assuming you can do the same w/ python.
6,119,038
I'm writing a bash script that fires up python and then enters some simple commands before exiting. I've got it firing up python ok, but how do I make the script simulate keyboard input in the python shell, as though a person were doing it?
2011/05/25
[ "https://Stackoverflow.com/questions/6119038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193601/" ]
Use a "here" document. It looks like this ``` command << HERE text that someone types in more text HERE ``` You don'th have to use "HERE", you can use something that has a little more meaning relative to the context of your code.
If you really need to simulate typing into the Python interpreter, rather than piping a command to python, you can probably do this with [`expect`](http://www.nist.gov/el/msid/expect.cfm) `expect` should be available in your distribution's repository. For details, ``` man expect ```
6,119,038
I'm writing a bash script that fires up python and then enters some simple commands before exiting. I've got it firing up python ok, but how do I make the script simulate keyboard input in the python shell, as though a person were doing it?
2011/05/25
[ "https://Stackoverflow.com/questions/6119038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193601/" ]
If you really need to simulate typing into the Python interpreter, rather than piping a command to python, you can probably do this with [`expect`](http://www.nist.gov/el/msid/expect.cfm) `expect` should be available in your distribution's repository. For details, ``` man expect ```
I haven't used python, but normally I echo a command string and pipe it to the interpreter binary like so: ``` $ echo '<?php echo "2+2\n"; ?>' | /usr/bin/php 2+2 ``` I'm assuming you can do the same w/ python.
28,377,690
Complete noob with python 3. I have some code and can't figure out for the life of me why I keep getting the output I do. For some reason the elif statements aren't getting recognized. Here is the output first and the code down below: ``` 3 Your fortune for today is: Please press enter to end ``` ``` #Program for fortune cookies var1 = "It's going to be a good day" var2 = "You'll have a long life" var3 = "Your life will be short" var4 = "Things will be good" var5 = "Life will be fun" import random randNum = random.randint(1, 5) statement = "" print(randNum) if randNum == 1: statement = var1 elif randNum == 2: statement = var2 elif randNum == 3: statement == var3 elif randNum == 4: statement == var4 elif randNum == 5: statement == var5 print("Your fortune for today is: ", statement) input("Please press enter to end") ```
2015/02/07
[ "https://Stackoverflow.com/questions/28377690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2288612/" ]
You are not assigning `varx` to `statement` (in some cases, 3, 4 and 5th cases), but comparing. Just change all: ``` statement == varx ``` To: ``` statement = var3 ``` Except from that, it seems to work.
The Problem is for example ```js statement == var5 ``` assignment statement. Good luck!
28,377,690
Complete noob with python 3. I have some code and can't figure out for the life of me why I keep getting the output I do. For some reason the elif statements aren't getting recognized. Here is the output first and the code down below: ``` 3 Your fortune for today is: Please press enter to end ``` ``` #Program for fortune cookies var1 = "It's going to be a good day" var2 = "You'll have a long life" var3 = "Your life will be short" var4 = "Things will be good" var5 = "Life will be fun" import random randNum = random.randint(1, 5) statement = "" print(randNum) if randNum == 1: statement = var1 elif randNum == 2: statement = var2 elif randNum == 3: statement == var3 elif randNum == 4: statement == var4 elif randNum == 5: statement == var5 print("Your fortune for today is: ", statement) input("Please press enter to end") ```
2015/02/07
[ "https://Stackoverflow.com/questions/28377690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2288612/" ]
You are not assigning `varx` to `statement` (in some cases, 3, 4 and 5th cases), but comparing. Just change all: ``` statement == varx ``` To: ``` statement = var3 ``` Except from that, it seems to work.
Check the lines: ``` elif randNum == 3: statement == var3 elif randNum == 4: statement == var4 elif randNum == 5: statement == var5 ``` '==' is for checking equality, '=' is for assigning variables.
28,377,690
Complete noob with python 3. I have some code and can't figure out for the life of me why I keep getting the output I do. For some reason the elif statements aren't getting recognized. Here is the output first and the code down below: ``` 3 Your fortune for today is: Please press enter to end ``` ``` #Program for fortune cookies var1 = "It's going to be a good day" var2 = "You'll have a long life" var3 = "Your life will be short" var4 = "Things will be good" var5 = "Life will be fun" import random randNum = random.randint(1, 5) statement = "" print(randNum) if randNum == 1: statement = var1 elif randNum == 2: statement = var2 elif randNum == 3: statement == var3 elif randNum == 4: statement == var4 elif randNum == 5: statement == var5 print("Your fortune for today is: ", statement) input("Please press enter to end") ```
2015/02/07
[ "https://Stackoverflow.com/questions/28377690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2288612/" ]
Check the lines: ``` elif randNum == 3: statement == var3 elif randNum == 4: statement == var4 elif randNum == 5: statement == var5 ``` '==' is for checking equality, '=' is for assigning variables.
The Problem is for example ```js statement == var5 ``` assignment statement. Good luck!
35,437,380
I installed Dato's `GraphLab Create` to run with `python 27` first directly from its executable then manually via `pip` ([instructions here](https://dato.com/products/create/)) for troubleshooting. Code: ``` import graphlab graphlab.SFrame() ``` Output: ``` [INFO] Start server at: ipc:///tmp/graphlab_server-4908 - Server binary: C:\Users\Remi\Anaconda2\envs\dato-env\lib\site-packages\graphlab\unity_server.exe - Server log: C:\Users\Remi\AppData\Local\Temp\graphlab_server_1455637156.log.0 [INFO] GraphLab Server Version: 1.8.1 ``` Now, attempt to load a .csv file as an Sframe: ``` csvsf = graphlab.Sframe('file.csv') ``` complains: ``` AttributeError Traceback (most recent call last) <ipython-input-5-68278493c023> in <module>() ----> 1 sf = graphlab.Sframe('file.csv') AttributeError: 'module' object has no attribute 'Sframe' ``` Any idea(s) how to pinpoint the issue? Thanks so much. Note: Uninstalled an already present `python 34` version
2016/02/16
[ "https://Stackoverflow.com/questions/35437380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4992716/" ]
capitalization error, it should be SFrame, not Sframe
You can only load a graplab package ('file.gl') by `graphlab.SFrame()`. Instead to load a csv file use `csvf = graphlab.SFrame.read_csv('file.csv')` for more information and other data types read this docs <https://dato.com/products/create/docs/graphlab.data_structures.html>
49,651,351
I have a similar issues like [How to upload a bytes image on Google Cloud Storage from a Python script](https://stackoverflow.com/questions/46078088/how-to-upload-a-bytes-image-on-google-cloud-storage-from-a-python-script/47140336#comment86305324_47140336). I tried this ``` from google.cloud import storage import cv2 from tempfile import TemporaryFile import google.auth credentials, project = google.auth.default() client = storage.Client() # https://console.cloud.google.com/storage/browser/[bucket-id]/ bucket = client.get_bucket('document') # Then do other things... image=cv2.imread('/Users/santhoshdc/Documents/Realtest/15.jpg') with TemporaryFile() as gcs_image: image.tofile(gcs_image) blob = bucket.get_blob(gcs_image) print(blob.download_as_string()) blob.upload_from_string('New contents!') blob2 = bucket.blob('document/operations/15.png') blob2.upload_from_filename(filename='gcs_image') ``` This is the error that's posing up ``` > Traceback (most recent call last): File > "/Users/santhoshdc/Documents/ImageShapeSize/imageGcloudStorageUpload.py", > line 13, in <module> > blob = bucket.get_blob(gcs_image) File "/Users/santhoshdc/.virtualenvs/test/lib/python3.6/site-packages/google/cloud/storage/bucket.py", > line 388, in get_blob > **kwargs) File "/Users/santhoshdc/.virtualenvs/test/lib/python3.6/site-packages/google/cloud/storage/blob.py", > line 151, in __init__ > name = _bytes_to_unicode(name) File "/Users/santhoshdc/.virtualenvs/test/lib/python3.6/site-packages/google/cloud/_helpers.py", > line 377, in _bytes_to_unicode > raise ValueError('%r could not be converted to unicode' % (value,)) ValueError: <_io.BufferedRandom name=7> could not be > converted to unicode ``` Can anyone guide me what's going wrong or what I'm doing incorrectly?
2018/04/04
[ "https://Stackoverflow.com/questions/49651351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9596737/" ]
As suggested by @A.Queue [in](https://pastebin.com/Jr6k3SW2)(gets deleted after 29 days) ``` from google.cloud import storage import cv2 from tempfile import TemporaryFile client = storage.Client() bucket = client.get_bucket('test-bucket') image=cv2.imread('example.jpg') with TemporaryFile() as gcs_image: image.tofile(gcs_image) gcs_image.seek(0) blob = bucket.blob('example.jpg') blob.upload_from_file(gcs_image) ``` The file got uploaded,but uploading a `numpy ndarray` doesn't get saved as an image file on the `google-cloud-storage` PS: `numpy array` has to be convert into any image format before saving. This is fairly simple, use the `tempfile` created to store the image, here's the code. ``` with NamedTemporaryFile() as temp: #Extract name to the temp file iName = "".join([str(temp.name),".jpg"]) #Save image to temp file cv2.imwrite(iName,duplicate_image) #Storing the image temp file inside the bucket blob = bucket.blob('ImageTest/Example1.jpg') blob.upload_from_filename(iName,content_type='image/jpeg') #Get the public_url of the saved image url = blob.public_url ```
You are calling `blob = bucket.get_blob(gcs_image)` which makes no sense. `get_blob()` is supposed to get a string argument, namely the name of the blob you want to get. A *name*. But you pass a file object. I propose this code: ``` with TemporaryFile() as gcs_image: image.tofile(gcs_image) gcs_image.seek(0) blob = bucket.blob('documentation-screenshots/operations/15.png') blob.upload_from_file(gcs_image) ```
58,134,808
I'd like to install some special sub-package from a package. For example, I want to create package with pkg\_a and pkg\_b. But I want to allow the user to choose which he wants to install. What I'd like to do: ``` git clone https://github.com/pypa/sample-namespace-packages.git cd sample-namespace-packages touch setup.py ``` setup-py: ``` import setuptools setup( name='native', version='1', packages=setuptools.find_packages() ) ``` ``` # for all packages pip install -e native #Successfully installed native # for specific # Throws ERROR: native.pkg_a is not a valid editable requirement. # It should either be a path to a local project pip install -e native.pkg_a native.pkg_b # for specific cd native pip install -e pkg_a # Successfully installed example-pkg-a ``` I've seen this in another questions answer so it must be possible: [Python install sub-package from package](https://stackoverflow.com/questions/45324189/python-install-sub-package-from-package) Also I've read the [Packaging namespace packages documentation](https://packaging.python.org/guides/packaging-namespace-packages/) and tried to do the trick with the [repo](https://github.com/pypa/sample-namespace-packages) I've tried some variants with an additional setup.py in the native directory, but I can't handle it and I am thankful for all help. Update ------ In addition to the answer from sinoroc I've made an own repo. I created a package Nmspc, with subpackages NmspcPing and NmspcPong. But I want to allow the user to choose which he wants to install. Also it must to be possible to install the whole package. What I'd like to do is something like that: ``` git clone https://github.com/cj-prog/Nmspc.git cd Nmspc # for all packages pip install Nmspc # Test import python3 -c "import nmspc; import nmspc.pong" ``` ``` # for specific pip install -e Nmspc.pong # or pip install -e pong # Test import python3 -c "import pong;" ```
2019/09/27
[ "https://Stackoverflow.com/questions/58134808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5872512/" ]
A solution for your use case seems to be similar to the one I gave here: <https://stackoverflow.com/a/58024830/11138259>, as well as the one you linked in your question: [Python install sub-package from package](https://stackoverflow.com/questions/45324189/python-install-sub-package-from-package). Here is an example... The directory tree might look like this: ``` . β”œβ”€β”€ Nmspc β”‚Β Β  β”œβ”€β”€ nmspc β”‚Β Β  β”‚Β Β  └── _nmspc β”‚Β Β  β”‚Β Β  └── __init__.py β”‚Β Β  └── setup.py β”œβ”€β”€ NmspcPing β”‚Β Β  β”œβ”€β”€ nmspc β”‚Β Β  β”‚Β Β  └── ping β”‚Β Β  β”‚Β Β  └── __init__.py β”‚Β Β  └── setup.py └── NmspcPong β”œβ”€β”€ nmspc β”‚Β Β  └── pong β”‚Β Β  └── __init__.py └── setup.py ``` 3 Python projects: * *NmspcPing* provides `nmspc.ping` * *NmspcPong* provides `nmspc.pong` * *Nmspc* depends on the other two projects (and also provides `nmspc._nmspc` see below for details) They are all *namespace packages*. They are built using the instructions from the [Python Packaging User Guide on "Packaging namespace packages, Native namespace packages"](https://packaging.python.org/guides/packaging-namespace-packages/#native-namespace-packages). There is another example [here](https://github.com/pypa/sample-namespace-packages/tree/master/native). The project *Nmspc* is basically empty, no actual code, but the important part is to add the other two *NmspcPing* and *NmspcPong* as *installation requirements*. Another thing to note, is that for convenience it is also a *namespace package* with `nmspc._nmspc` being kind of hidden (the leading underscore is the naming convention for hidden things in Python). `NmspcPing/setup.py` (and similarly `NmspcPong/setup.py`): ``` #!/usr/bin/env python3 import setuptools setuptools.setup( name='NmspcPing', version='1.2.3', packages=['nmspc.ping',], ) ``` `Nmspc/setup.py`: ``` #!/usr/bin/env python3 import setuptools setuptools.setup( name='Nmspc', version='1.2.3', packages=['nmspc._nmspc',], install_requires=['NmspcPing', 'NmspcPong',], ) ``` Assuming you are in the root directory, you can install these for development like this: ``` $ python3 -m pip install -e NmspcPing $ python3 -m pip install -e NmspcPong $ python3 -m pip install -e Nmspc ``` And then you should be able to use them like this: ``` $ python3 -c "import nmspc.ping; import nmspc.pong; import nmspc._nmspc;" ``` --- **Update** This can be simplified: ``` . β”œβ”€β”€ NmspcPing β”‚Β Β  β”œβ”€β”€ nmspc β”‚Β Β  β”‚Β Β  └── ping β”‚Β Β  β”‚Β Β  └── __init__.py β”‚Β Β  └── setup.py β”œβ”€β”€ NmspcPong β”‚Β Β  β”œβ”€β”€ nmspc β”‚Β Β  β”‚Β Β  └── pong β”‚Β Β  β”‚Β Β  └── __init__.py β”‚Β Β  └── setup.py └── setup.py ``` `setup.py` ``` #!/usr/bin/env python3 import setuptools setuptools.setup( name='Nmspc', version='1.2.3', install_requires=['NmspcPing', 'NmspcPong',], ) ``` Use it like this: ``` $ python3 -m pip install ./NmspcPing ./NmspcPong/ . $ python3 -c "import nmspc.ping; import nmspc.pong;" ```
If the projects are not installed from an index such as *PyPI*, it is not possible to take advantage of the `install_requires` feature. Something like this could be done instead: ``` . β”œβ”€β”€ NmspcPing β”‚Β Β  β”œβ”€β”€ nmspc.ping β”‚Β Β  β”‚Β Β  └── __init__.py β”‚Β Β  └── setup.py β”œβ”€β”€ NmspcPong β”‚Β Β  β”œβ”€β”€ nmspc.pong β”‚Β Β  β”‚Β Β  └── __init__.py β”‚Β Β  └── setup.py └── setup.py ``` `NmspcPing/setup.py` (and similarly `NmspcPong/setup.py`) ``` import setuptools setuptools.setup( name='NmspcPing', version='1.2.3', package_dir={'nmspc.ping': 'nmspc.ping'}, packages=['nmspc.ping'], ) ``` `setup.py` ``` import setuptools setuptools.setup( name='Nmspc', version='1.2.3', package_dir={ 'nmspc.ping': 'NmspcPing/nmspc.ping', 'nmspc.pong': 'NmspcPong/nmspc.pong', }, packages=['nmspc.ping', 'nmspc.pong'], ) ``` This allows to install from the root folder in any of the following combinations: ``` $ python3 -m pip install . $ python3 -m pip install ./NmspcPing $ python3 -m pip install ./NmspcPong $ python3 -m pip install ./NmspcPing ./NmspcPong ```
61,933,414
``` import tkinter as tk from tkinter import filedialog, Text from subprocess import call import os root = tk.Tk() def buttonClick(): print('Button is clicked') def openAgenda(): call("cd '/media/emilia/Linux/Programming/PycharmProjects/SmartschoolSelenium' && python3 SeleniumMain.py", shell=True) return canvas = tk.Canvas(root, height=700, width=700, bg='#263D42') canvas.pack() frame = tk.Frame(root, bg='white') frame.place(relwidth=0.8, relheight=0.8, relx=0.1, rely=0.1) openFile = tk.Button(root, text='Open file', padx=10, pady=5, fg="white", bg='#263D42', command=openAgenda) openFile.pack() root.mainloop() ``` the script it calls opens a new browser window, after finishing entering text in that window, it opens a new browser windows and loops. meanwhile the tkinter button stays clicked, visually.
2020/05/21
[ "https://Stackoverflow.com/questions/61933414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13588940/" ]
You should include the necessary JavaScript resource like this: ``` <script src='https://www.google.com/recaptcha/api.js'></script> ``` Besides, set the right site key in the `data-sitekey` attribute. The result is like this in IE: [![enter image description here](https://i.stack.imgur.com/mnuEK.png)](https://i.stack.imgur.com/mnuEK.png) If it still doesn't work in IE 11, you could use F12 dev tools to check if there's any error in console.
Actually it was loading loading first time in IE. So, I tried with making url different everytime by appending current datetime. "<https://www.google.com/recaptcha/api.js?render=>" + EncodeUrl(SiteKey) + "&time="+CurrTime() It started working.
1,046,656
I have a very simple python script that **should** scan a text file, which contains lines formatted as *id*='*value*' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code: ``` import os,sys from os import * from sys import * vals = {} f = open(sys.argv[1], 'r') for line in val_f: t = line.split('=') t[1].strip('\'') vals.append(t[0], t[1]) print vals f.close() ``` when i try to run it i get: > > Traceback (most recent call last): > > File "chval.py", line 9, in ? > f = open(sys.argv[1], 'r') TypeError: an integer is required > > > I'm using python 2.4... because i've been challenged to not use anything newer, is there something about open() that I don't know about? Why does it want an integer? anything after that line is untested. in short: why is it giving me the error and how do i fix it?
2009/06/25
[ "https://Stackoverflow.com/questions/1046656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125946/" ]
Also of note is that starting with Python 2.6 the built-in function open() is now an alias for the io.open() function. It was even considered removing the built-in open() in Python 3 and requiring the usage of io.open, in order to avoid accidental namespace collisions resulting from things such as "from blah import \*". In Python 2.6+ you can write (and can also consider this style to be good practice): ``` import io filehandle = io.open(sys.argv[1], 'r') ```
Providing these parameters resolved my issue: ``` with open('tomorrow.txt', mode='w', encoding='UTF-8', errors='strict', buffering=1) as file: file.write(result) ```
1,046,656
I have a very simple python script that **should** scan a text file, which contains lines formatted as *id*='*value*' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code: ``` import os,sys from os import * from sys import * vals = {} f = open(sys.argv[1], 'r') for line in val_f: t = line.split('=') t[1].strip('\'') vals.append(t[0], t[1]) print vals f.close() ``` when i try to run it i get: > > Traceback (most recent call last): > > File "chval.py", line 9, in ? > f = open(sys.argv[1], 'r') TypeError: an integer is required > > > I'm using python 2.4... because i've been challenged to not use anything newer, is there something about open() that I don't know about? Why does it want an integer? anything after that line is untested. in short: why is it giving me the error and how do i fix it?
2009/06/25
[ "https://Stackoverflow.com/questions/1046656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125946/" ]
Don't do `import * from wherever` without a good reason (and there aren't many). Your code is picking up the os.open() function instead of the built-in open() function. If you really want to use os.open(), do `import os` then call `os.open(....)`. Whichever open you want to call, read the documentation about what arguments it requires.
you have `from os import *` I also got the same error, remove that line and change it to `import os` and behind the os lib functions, add os.[function]
1,046,656
I have a very simple python script that **should** scan a text file, which contains lines formatted as *id*='*value*' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code: ``` import os,sys from os import * from sys import * vals = {} f = open(sys.argv[1], 'r') for line in val_f: t = line.split('=') t[1].strip('\'') vals.append(t[0], t[1]) print vals f.close() ``` when i try to run it i get: > > Traceback (most recent call last): > > File "chval.py", line 9, in ? > f = open(sys.argv[1], 'r') TypeError: an integer is required > > > I'm using python 2.4... because i've been challenged to not use anything newer, is there something about open() that I don't know about? Why does it want an integer? anything after that line is untested. in short: why is it giving me the error and how do i fix it?
2009/06/25
[ "https://Stackoverflow.com/questions/1046656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125946/" ]
Because you did `from os import *`, you are (accidenally) using os.open, which indeed requires an integer flag instead of a textual "r" or "w". Take out that line and you'll get past that error.
Don't do `import * from wherever` without a good reason (and there aren't many). Your code is picking up the os.open() function instead of the built-in open() function. If you really want to use os.open(), do `import os` then call `os.open(....)`. Whichever open you want to call, read the documentation about what arguments it requires.
1,046,656
I have a very simple python script that **should** scan a text file, which contains lines formatted as *id*='*value*' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code: ``` import os,sys from os import * from sys import * vals = {} f = open(sys.argv[1], 'r') for line in val_f: t = line.split('=') t[1].strip('\'') vals.append(t[0], t[1]) print vals f.close() ``` when i try to run it i get: > > Traceback (most recent call last): > > File "chval.py", line 9, in ? > f = open(sys.argv[1], 'r') TypeError: an integer is required > > > I'm using python 2.4... because i've been challenged to not use anything newer, is there something about open() that I don't know about? Why does it want an integer? anything after that line is untested. in short: why is it giving me the error and how do i fix it?
2009/06/25
[ "https://Stackoverflow.com/questions/1046656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125946/" ]
Because you did `from os import *`, you are (accidenally) using os.open, which indeed requires an integer flag instead of a textual "r" or "w". Take out that line and you'll get past that error.
you have `from os import *` I also got the same error, remove that line and change it to `import os` and behind the os lib functions, add os.[function]
1,046,656
I have a very simple python script that **should** scan a text file, which contains lines formatted as *id*='*value*' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code: ``` import os,sys from os import * from sys import * vals = {} f = open(sys.argv[1], 'r') for line in val_f: t = line.split('=') t[1].strip('\'') vals.append(t[0], t[1]) print vals f.close() ``` when i try to run it i get: > > Traceback (most recent call last): > > File "chval.py", line 9, in ? > f = open(sys.argv[1], 'r') TypeError: an integer is required > > > I'm using python 2.4... because i've been challenged to not use anything newer, is there something about open() that I don't know about? Why does it want an integer? anything after that line is untested. in short: why is it giving me the error and how do i fix it?
2009/06/25
[ "https://Stackoverflow.com/questions/1046656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125946/" ]
Also of note is that starting with Python 2.6 the built-in function open() is now an alias for the io.open() function. It was even considered removing the built-in open() in Python 3 and requiring the usage of io.open, in order to avoid accidental namespace collisions resulting from things such as "from blah import \*". In Python 2.6+ you can write (and can also consider this style to be good practice): ``` import io filehandle = io.open(sys.argv[1], 'r') ```
you have `from os import *` I also got the same error, remove that line and change it to `import os` and behind the os lib functions, add os.[function]
1,046,656
I have a very simple python script that **should** scan a text file, which contains lines formatted as *id*='*value*' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code: ``` import os,sys from os import * from sys import * vals = {} f = open(sys.argv[1], 'r') for line in val_f: t = line.split('=') t[1].strip('\'') vals.append(t[0], t[1]) print vals f.close() ``` when i try to run it i get: > > Traceback (most recent call last): > > File "chval.py", line 9, in ? > f = open(sys.argv[1], 'r') TypeError: an integer is required > > > I'm using python 2.4... because i've been challenged to not use anything newer, is there something about open() that I don't know about? Why does it want an integer? anything after that line is untested. in short: why is it giving me the error and how do i fix it?
2009/06/25
[ "https://Stackoverflow.com/questions/1046656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125946/" ]
Providing these parameters resolved my issue: ``` with open('tomorrow.txt', mode='w', encoding='UTF-8', errors='strict', buffering=1) as file: file.write(result) ```
you have `from os import *` I also got the same error, remove that line and change it to `import os` and behind the os lib functions, add os.[function]
1,046,656
I have a very simple python script that **should** scan a text file, which contains lines formatted as *id*='*value*' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code: ``` import os,sys from os import * from sys import * vals = {} f = open(sys.argv[1], 'r') for line in val_f: t = line.split('=') t[1].strip('\'') vals.append(t[0], t[1]) print vals f.close() ``` when i try to run it i get: > > Traceback (most recent call last): > > File "chval.py", line 9, in ? > f = open(sys.argv[1], 'r') TypeError: an integer is required > > > I'm using python 2.4... because i've been challenged to not use anything newer, is there something about open() that I don't know about? Why does it want an integer? anything after that line is untested. in short: why is it giving me the error and how do i fix it?
2009/06/25
[ "https://Stackoverflow.com/questions/1046656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125946/" ]
Don't do `import * from wherever` without a good reason (and there aren't many). Your code is picking up the os.open() function instead of the built-in open() function. If you really want to use os.open(), do `import os` then call `os.open(....)`. Whichever open you want to call, read the documentation about what arguments it requires.
that's because you should do: ``` open(sys.argv[2], "w", encoding="utf-8") ``` or ``` open(sys.argv[2], "w") ```
1,046,656
I have a very simple python script that **should** scan a text file, which contains lines formatted as *id*='*value*' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code: ``` import os,sys from os import * from sys import * vals = {} f = open(sys.argv[1], 'r') for line in val_f: t = line.split('=') t[1].strip('\'') vals.append(t[0], t[1]) print vals f.close() ``` when i try to run it i get: > > Traceback (most recent call last): > > File "chval.py", line 9, in ? > f = open(sys.argv[1], 'r') TypeError: an integer is required > > > I'm using python 2.4... because i've been challenged to not use anything newer, is there something about open() that I don't know about? Why does it want an integer? anything after that line is untested. in short: why is it giving me the error and how do i fix it?
2009/06/25
[ "https://Stackoverflow.com/questions/1046656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125946/" ]
Also of note is that starting with Python 2.6 the built-in function open() is now an alias for the io.open() function. It was even considered removing the built-in open() in Python 3 and requiring the usage of io.open, in order to avoid accidental namespace collisions resulting from things such as "from blah import \*". In Python 2.6+ you can write (and can also consider this style to be good practice): ``` import io filehandle = io.open(sys.argv[1], 'r') ```
From <http://www.tutorialspoint.com/python/os_open.htm> you could also keep your import and use file = os.open( "foo.txt", mode ) and the mode could be : ``` os.O_RDONLY: open for reading only os.O_WRONLY: open for writing only os.O_RDWR : open for reading and writing os.O_NONBLOCK: do not block on open os.O_APPEND: append on each write os.O_CREAT: create file if it does not exist os.O_TRUNC: truncate size to 0 os.O_EXCL: error if create and file exists os.O_SHLOCK: atomically obtain a shared lock os.O_EXLOCK: atomically obtain an exclusive lock os.O_DIRECT: eliminate or reduce cache effects os.O_FSYNC : synchronous writes os.O_NOFOLLOW: do not follow symlinks ```
1,046,656
I have a very simple python script that **should** scan a text file, which contains lines formatted as *id*='*value*' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code: ``` import os,sys from os import * from sys import * vals = {} f = open(sys.argv[1], 'r') for line in val_f: t = line.split('=') t[1].strip('\'') vals.append(t[0], t[1]) print vals f.close() ``` when i try to run it i get: > > Traceback (most recent call last): > > File "chval.py", line 9, in ? > f = open(sys.argv[1], 'r') TypeError: an integer is required > > > I'm using python 2.4... because i've been challenged to not use anything newer, is there something about open() that I don't know about? Why does it want an integer? anything after that line is untested. in short: why is it giving me the error and how do i fix it?
2009/06/25
[ "https://Stackoverflow.com/questions/1046656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125946/" ]
Because you did `from os import *`, you are (accidenally) using os.open, which indeed requires an integer flag instead of a textual "r" or "w". Take out that line and you'll get past that error.
that's because you should do: ``` open(sys.argv[2], "w", encoding="utf-8") ``` or ``` open(sys.argv[2], "w") ```
1,046,656
I have a very simple python script that **should** scan a text file, which contains lines formatted as *id*='*value*' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code: ``` import os,sys from os import * from sys import * vals = {} f = open(sys.argv[1], 'r') for line in val_f: t = line.split('=') t[1].strip('\'') vals.append(t[0], t[1]) print vals f.close() ``` when i try to run it i get: > > Traceback (most recent call last): > > File "chval.py", line 9, in ? > f = open(sys.argv[1], 'r') TypeError: an integer is required > > > I'm using python 2.4... because i've been challenged to not use anything newer, is there something about open() that I don't know about? Why does it want an integer? anything after that line is untested. in short: why is it giving me the error and how do i fix it?
2009/06/25
[ "https://Stackoverflow.com/questions/1046656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125946/" ]
Don't do `import * from wherever` without a good reason (and there aren't many). Your code is picking up the os.open() function instead of the built-in open() function. If you really want to use os.open(), do `import os` then call `os.open(....)`. Whichever open you want to call, read the documentation about what arguments it requires.
From <http://www.tutorialspoint.com/python/os_open.htm> you could also keep your import and use file = os.open( "foo.txt", mode ) and the mode could be : ``` os.O_RDONLY: open for reading only os.O_WRONLY: open for writing only os.O_RDWR : open for reading and writing os.O_NONBLOCK: do not block on open os.O_APPEND: append on each write os.O_CREAT: create file if it does not exist os.O_TRUNC: truncate size to 0 os.O_EXCL: error if create and file exists os.O_SHLOCK: atomically obtain a shared lock os.O_EXLOCK: atomically obtain an exclusive lock os.O_DIRECT: eliminate or reduce cache effects os.O_FSYNC : synchronous writes os.O_NOFOLLOW: do not follow symlinks ```
1,597,732
Folks, I know there have been lots of threads about forcing the download dialog to pop up, but none of the solutions worked for me yet. My app sends mail to the user's email account, notifying them that "another user sent them a message". Those messages might have links to Excel files. When the user clicks on a link in their GMail/Yahoo Mail/Outlook to that Excel file, I want the File Save dialog to pop up. Problem: when I right-click and do "Save As" on IE, i get a Save As dialog. When I just click the link (which many of my clients will do as they are not computer-savvy), I get an IE error message: "IE cannot download file ... from ...". May be relevant: on GMail where I'm testing this, every link is a "target=\_blank" link (forced by Google). All other browsers work fine in all cases. Here are my headers (captured through Fiddler): ``` HTTP/1.1 200 OK Proxy-Connection: Keep-Alive Connection: Keep-Alive Content-Length: 15872 Via: **** // proxy server name Expires: 0 Date: Tue, 20 Oct 2009 22:41:37 GMT Content-Type: application/vnd.ms-excel Server: Apache/2.2.11 (Unix) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i mod_python/3.3.1 Python/2.5.2 SVN/1.4.6 mod_apreq2-20051231/2.6.0 mod_perl/2.0.4 Perl/v5.10.0 Cache-Control: private Pragma: no-cache Last-Modified: Tue, 20 Oct 2009 22:41:37 GMT Content-Disposition: attachment; filename="myFile.xls" Vary: Accept-Encoding Keep-Alive: timeout=5, max=100 ``` I want IE's regular left-click behavior to work. Any ideas?
2009/10/20
[ "https://Stackoverflow.com/questions/1597732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16668/" ]
This will check for versions of IE and set headers accordingly. ``` // assume you have a full path to file stored in $filename if (!is_file($filename)) { die('The file appears to be invalid.'); } $filepath = str_replace('\\', '/', realpath($filename)); $filesize = filesize($filepath); $filename = substr(strrchr('/'.$filepath, '/'), 1); $extension = strtolower(substr(strrchr($filepath, '.'), 1)); // use this unless you want to find the mime type based on extension $mime = array('application/octet-stream'); header('Content-Type: '.$mime); header('Content-Disposition: attachment; filename="'.$filename.'"'); header('Content-Transfer-Encoding: binary'); header('Content-Length: '.sprintf('%d', $filesize)); header('Expires: 0'); // check for IE only headers if (preg_match('~MSIE|Internet Explorer~i', $_SERVER['HTTP_USER_AGENT']) || (strpos($_SERVER['HTTP_USER_AGENT'], 'Trident/7.0; rv:11.0') !== false)) { header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); } else { header('Pragma: no-cache'); } $handle = fopen($filepath, 'rb'); fpassthru($handle); fclose($handle); ```
If you're trying to get the file to download every time, change the content type to 'application/octet-stream'. Try it without the pragma statement.
1,597,732
Folks, I know there have been lots of threads about forcing the download dialog to pop up, but none of the solutions worked for me yet. My app sends mail to the user's email account, notifying them that "another user sent them a message". Those messages might have links to Excel files. When the user clicks on a link in their GMail/Yahoo Mail/Outlook to that Excel file, I want the File Save dialog to pop up. Problem: when I right-click and do "Save As" on IE, i get a Save As dialog. When I just click the link (which many of my clients will do as they are not computer-savvy), I get an IE error message: "IE cannot download file ... from ...". May be relevant: on GMail where I'm testing this, every link is a "target=\_blank" link (forced by Google). All other browsers work fine in all cases. Here are my headers (captured through Fiddler): ``` HTTP/1.1 200 OK Proxy-Connection: Keep-Alive Connection: Keep-Alive Content-Length: 15872 Via: **** // proxy server name Expires: 0 Date: Tue, 20 Oct 2009 22:41:37 GMT Content-Type: application/vnd.ms-excel Server: Apache/2.2.11 (Unix) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i mod_python/3.3.1 Python/2.5.2 SVN/1.4.6 mod_apreq2-20051231/2.6.0 mod_perl/2.0.4 Perl/v5.10.0 Cache-Control: private Pragma: no-cache Last-Modified: Tue, 20 Oct 2009 22:41:37 GMT Content-Disposition: attachment; filename="myFile.xls" Vary: Accept-Encoding Keep-Alive: timeout=5, max=100 ``` I want IE's regular left-click behavior to work. Any ideas?
2009/10/20
[ "https://Stackoverflow.com/questions/1597732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16668/" ]
If you're trying to get the file to download every time, change the content type to 'application/octet-stream'. Try it without the pragma statement.
Your no-cache directives (Vary, Expires, Pragma) are causing the problem. See <http://blogs.msdn.com/ieinternals/archive/2009/10/02/Internet-Explorer-cannot-download-over-HTTPS-when-no-cache.aspx>
1,597,732
Folks, I know there have been lots of threads about forcing the download dialog to pop up, but none of the solutions worked for me yet. My app sends mail to the user's email account, notifying them that "another user sent them a message". Those messages might have links to Excel files. When the user clicks on a link in their GMail/Yahoo Mail/Outlook to that Excel file, I want the File Save dialog to pop up. Problem: when I right-click and do "Save As" on IE, i get a Save As dialog. When I just click the link (which many of my clients will do as they are not computer-savvy), I get an IE error message: "IE cannot download file ... from ...". May be relevant: on GMail where I'm testing this, every link is a "target=\_blank" link (forced by Google). All other browsers work fine in all cases. Here are my headers (captured through Fiddler): ``` HTTP/1.1 200 OK Proxy-Connection: Keep-Alive Connection: Keep-Alive Content-Length: 15872 Via: **** // proxy server name Expires: 0 Date: Tue, 20 Oct 2009 22:41:37 GMT Content-Type: application/vnd.ms-excel Server: Apache/2.2.11 (Unix) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i mod_python/3.3.1 Python/2.5.2 SVN/1.4.6 mod_apreq2-20051231/2.6.0 mod_perl/2.0.4 Perl/v5.10.0 Cache-Control: private Pragma: no-cache Last-Modified: Tue, 20 Oct 2009 22:41:37 GMT Content-Disposition: attachment; filename="myFile.xls" Vary: Accept-Encoding Keep-Alive: timeout=5, max=100 ``` I want IE's regular left-click behavior to work. Any ideas?
2009/10/20
[ "https://Stackoverflow.com/questions/1597732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16668/" ]
Just use: ``` header('Content-Disposition: attachment'); ``` That's all. (Facebook does the same.)
If you're trying to get the file to download every time, change the content type to 'application/octet-stream'. Try it without the pragma statement.
1,597,732
Folks, I know there have been lots of threads about forcing the download dialog to pop up, but none of the solutions worked for me yet. My app sends mail to the user's email account, notifying them that "another user sent them a message". Those messages might have links to Excel files. When the user clicks on a link in their GMail/Yahoo Mail/Outlook to that Excel file, I want the File Save dialog to pop up. Problem: when I right-click and do "Save As" on IE, i get a Save As dialog. When I just click the link (which many of my clients will do as they are not computer-savvy), I get an IE error message: "IE cannot download file ... from ...". May be relevant: on GMail where I'm testing this, every link is a "target=\_blank" link (forced by Google). All other browsers work fine in all cases. Here are my headers (captured through Fiddler): ``` HTTP/1.1 200 OK Proxy-Connection: Keep-Alive Connection: Keep-Alive Content-Length: 15872 Via: **** // proxy server name Expires: 0 Date: Tue, 20 Oct 2009 22:41:37 GMT Content-Type: application/vnd.ms-excel Server: Apache/2.2.11 (Unix) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i mod_python/3.3.1 Python/2.5.2 SVN/1.4.6 mod_apreq2-20051231/2.6.0 mod_perl/2.0.4 Perl/v5.10.0 Cache-Control: private Pragma: no-cache Last-Modified: Tue, 20 Oct 2009 22:41:37 GMT Content-Disposition: attachment; filename="myFile.xls" Vary: Accept-Encoding Keep-Alive: timeout=5, max=100 ``` I want IE's regular left-click behavior to work. Any ideas?
2009/10/20
[ "https://Stackoverflow.com/questions/1597732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16668/" ]
This will check for versions of IE and set headers accordingly. ``` // assume you have a full path to file stored in $filename if (!is_file($filename)) { die('The file appears to be invalid.'); } $filepath = str_replace('\\', '/', realpath($filename)); $filesize = filesize($filepath); $filename = substr(strrchr('/'.$filepath, '/'), 1); $extension = strtolower(substr(strrchr($filepath, '.'), 1)); // use this unless you want to find the mime type based on extension $mime = array('application/octet-stream'); header('Content-Type: '.$mime); header('Content-Disposition: attachment; filename="'.$filename.'"'); header('Content-Transfer-Encoding: binary'); header('Content-Length: '.sprintf('%d', $filesize)); header('Expires: 0'); // check for IE only headers if (preg_match('~MSIE|Internet Explorer~i', $_SERVER['HTTP_USER_AGENT']) || (strpos($_SERVER['HTTP_USER_AGENT'], 'Trident/7.0; rv:11.0') !== false)) { header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); } else { header('Pragma: no-cache'); } $handle = fopen($filepath, 'rb'); fpassthru($handle); fclose($handle); ```
Your no-cache directives (Vary, Expires, Pragma) are causing the problem. See <http://blogs.msdn.com/ieinternals/archive/2009/10/02/Internet-Explorer-cannot-download-over-HTTPS-when-no-cache.aspx>
1,597,732
Folks, I know there have been lots of threads about forcing the download dialog to pop up, but none of the solutions worked for me yet. My app sends mail to the user's email account, notifying them that "another user sent them a message". Those messages might have links to Excel files. When the user clicks on a link in their GMail/Yahoo Mail/Outlook to that Excel file, I want the File Save dialog to pop up. Problem: when I right-click and do "Save As" on IE, i get a Save As dialog. When I just click the link (which many of my clients will do as they are not computer-savvy), I get an IE error message: "IE cannot download file ... from ...". May be relevant: on GMail where I'm testing this, every link is a "target=\_blank" link (forced by Google). All other browsers work fine in all cases. Here are my headers (captured through Fiddler): ``` HTTP/1.1 200 OK Proxy-Connection: Keep-Alive Connection: Keep-Alive Content-Length: 15872 Via: **** // proxy server name Expires: 0 Date: Tue, 20 Oct 2009 22:41:37 GMT Content-Type: application/vnd.ms-excel Server: Apache/2.2.11 (Unix) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i mod_python/3.3.1 Python/2.5.2 SVN/1.4.6 mod_apreq2-20051231/2.6.0 mod_perl/2.0.4 Perl/v5.10.0 Cache-Control: private Pragma: no-cache Last-Modified: Tue, 20 Oct 2009 22:41:37 GMT Content-Disposition: attachment; filename="myFile.xls" Vary: Accept-Encoding Keep-Alive: timeout=5, max=100 ``` I want IE's regular left-click behavior to work. Any ideas?
2009/10/20
[ "https://Stackoverflow.com/questions/1597732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16668/" ]
This will check for versions of IE and set headers accordingly. ``` // assume you have a full path to file stored in $filename if (!is_file($filename)) { die('The file appears to be invalid.'); } $filepath = str_replace('\\', '/', realpath($filename)); $filesize = filesize($filepath); $filename = substr(strrchr('/'.$filepath, '/'), 1); $extension = strtolower(substr(strrchr($filepath, '.'), 1)); // use this unless you want to find the mime type based on extension $mime = array('application/octet-stream'); header('Content-Type: '.$mime); header('Content-Disposition: attachment; filename="'.$filename.'"'); header('Content-Transfer-Encoding: binary'); header('Content-Length: '.sprintf('%d', $filesize)); header('Expires: 0'); // check for IE only headers if (preg_match('~MSIE|Internet Explorer~i', $_SERVER['HTTP_USER_AGENT']) || (strpos($_SERVER['HTTP_USER_AGENT'], 'Trident/7.0; rv:11.0') !== false)) { header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); } else { header('Pragma: no-cache'); } $handle = fopen($filepath, 'rb'); fpassthru($handle); fclose($handle); ```
Just use: ``` header('Content-Disposition: attachment'); ``` That's all. (Facebook does the same.)
1,597,732
Folks, I know there have been lots of threads about forcing the download dialog to pop up, but none of the solutions worked for me yet. My app sends mail to the user's email account, notifying them that "another user sent them a message". Those messages might have links to Excel files. When the user clicks on a link in their GMail/Yahoo Mail/Outlook to that Excel file, I want the File Save dialog to pop up. Problem: when I right-click and do "Save As" on IE, i get a Save As dialog. When I just click the link (which many of my clients will do as they are not computer-savvy), I get an IE error message: "IE cannot download file ... from ...". May be relevant: on GMail where I'm testing this, every link is a "target=\_blank" link (forced by Google). All other browsers work fine in all cases. Here are my headers (captured through Fiddler): ``` HTTP/1.1 200 OK Proxy-Connection: Keep-Alive Connection: Keep-Alive Content-Length: 15872 Via: **** // proxy server name Expires: 0 Date: Tue, 20 Oct 2009 22:41:37 GMT Content-Type: application/vnd.ms-excel Server: Apache/2.2.11 (Unix) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i mod_python/3.3.1 Python/2.5.2 SVN/1.4.6 mod_apreq2-20051231/2.6.0 mod_perl/2.0.4 Perl/v5.10.0 Cache-Control: private Pragma: no-cache Last-Modified: Tue, 20 Oct 2009 22:41:37 GMT Content-Disposition: attachment; filename="myFile.xls" Vary: Accept-Encoding Keep-Alive: timeout=5, max=100 ``` I want IE's regular left-click behavior to work. Any ideas?
2009/10/20
[ "https://Stackoverflow.com/questions/1597732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16668/" ]
Just use: ``` header('Content-Disposition: attachment'); ``` That's all. (Facebook does the same.)
Your no-cache directives (Vary, Expires, Pragma) are causing the problem. See <http://blogs.msdn.com/ieinternals/archive/2009/10/02/Internet-Explorer-cannot-download-over-HTTPS-when-no-cache.aspx>
12,460,943
I have a list of log files, where each line in each file has a timestamp and the lines are pre-sorted ascending within each file. The different files can have overlapping time ranges, and my goal is to blend them together into one large file, sorted by timestamp. There can be ties in the sorting, in which case I want to next line to come from whatever file is listed first in my input list. I've seen examples of how to do this using `fileinput` (see [here](https://stackoverflow.com/questions/6653371/merging-and-sorting-log-files-in-python)), but this seems to read all the files into memory. Owing to the large size of my files this will be a problem. Because my files are pre-sorted, it seems there should be a way to merge them using a method that only has to consider the most recent unexplored line from each file.
2012/09/17
[ "https://Stackoverflow.com/questions/12460943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/233446/" ]
Why roll your own if there is `heapq.merge()` in the standard library? Unfortunately it doesn't provide a key argument -- you have to do the decorate - merge - undecorate dance yourself: ``` from itertools import imap from operator import itemgetter import heapq def extract_timestamp(line): """Extract timestamp and convert to a form that gives the expected result in a comparison """ return line.split()[1] # for example with open("log1.txt") as f1, open("log2.txt") as f2: sources = [f1, f2] with open("merged.txt", "w") as dest: decorated = [ ((extract_timestamp(line), line) for line in f) for f in sources] merged = heapq.merge(*decorated) undecorated = imap(itemgetter(-1), merged) dest.writelines(undecorated) ``` Every step in the above is "lazy". As I avoid `file.readlines()` the lines in the files are read as needed. Likewise the decoration process which uses generator expressions rather than list-comps. `heapq.merge()` is lazy, too -- it needs one item per input iterator simultaneously to do the necessary comparisons. Finally I'm using `itertools.imap()`, the lazy variant of the map() built-in to undecorate. (In Python 3 map() has become lazy, so you can use that)
You want to implement a file-based [merge sort](http://en.wikipedia.org/wiki/Merge_sort). Read a line from both files, output the older line, then read another line from that file. Once one of the files is exhausted, output all the remaining lines from the other file.
63,214,706
I'm working on a database with a graphical interface, I made an insert and delete method connected to the database, now I'm working on creating a search method but unfortunately not working for an unexpected error. The code Is a little bit long : ``` import sqlite3 from Tkinter import * global all,root, main_text, num_ent, nom_ent, search_ent def showall(): all = True con = sqlite3.connect("repertoire.db") cur = con.cursor() request = 'select * from blinta' cur.execute(request) table = str(cur.fetchall()).replace(')', '\n').replace('(', '').replace(',', '').replace('[', '').replace(']', '') return table con.commit() con.close() def delete(): con = sqlite3.connect("repertoire.db") cur = con.cursor() request = ' DELETE FROM blinta WHERE id=?' cur.execute(request, (ident.get(),)) con.commit() con.close() main_text.configure(state='normal') main_text.delete(1.0, END) main_text.insert(1.0, showall()) main_text.configure(state='disabled') ident.delete(0,END) def insert(): con = sqlite3.connect("repertoire.db") cur = con.cursor() request = 'insert into blinta (nom,numero) values(?,?)' cur.execute(request, (nom_ent.get(), num_ent.get())) con.commit() con.close() main_text.config(state='normal') main_text.delete(1.0, END) main_text.insert(1.0, showall()) main_text.config(state='disabled') num_ent.delete(0, END) nom_ent.delete(0, END) def search(): all=False con = sqlite3.connect("repertoire.db") cur = con.cursor() request = "select * from blinta where nom = ?" noun = search_ent.get() args=(noun,) cur.execute(request,args) selected = str(cur.fetchall()).replace(')', '\n').replace('(', '').replace(',', '').replace('[', '').replace(']', '') return selected con.commit() con.close() root = Tk() root.config(bg='#D2B024') root.geometry('450x650+900+0') root.minsize(450, 650) root.maxsize(450, 650) main_text = Text(root, bg='#CBCAC5', fg='black', width=30, height=40, state='normal') main_text.grid(column=1, row=1, rowspan=50, padx=9, pady=3) main_text.delete(1.0, END) if all == True : main_text.insert(1.0, showall()) else : main_text.insert(1.0, search()) main_text.config(state='disabled') nomlbl=Label(root,text='Enter noun to insert',bg='#D2B024').grid(row=1,column=2) nom_ent = Entry(root) nom_ent.grid(row=2, column=2) num_lbl=Label(root, text='Enter number to insert', bg='#D2B024').grid(row=3, column=2) num_ent = Entry(root) num_ent.grid(row=4, column=2) insert_btn = Button(relief='flat', fg='black', width=7, text='insert', font=("heveltica Bold", 15), command=insert).grid(row=5, column=2, columnspan=2, padx=50) Label(root,text='_______________________',bg='#D2B024').grid(row=6,column=2) idlbl=Label(root,text='Enter id to delete',bg='#D2B024').grid(row=7,column=2) ident=Entry(root) ident.grid(row=8,column=2) delete_btn = Button(relief='flat', fg='black', width=7, text='delete', font=("heveltica Bold", 15), command=delete).grid(row=9, column=2, columnspan=2, padx=0) Label(root,text='_______________________',bg='#D2B024').grid(row=10,column=2) search_lbl=Label(root,text='Enter noun to search',bg='#D2B024').grid(row=11,column=2) search_btn = Button(relief='flat', fg='black', width=7, text='search', font=("heveltica Bold", 15), command=search).grid(row=13, column=2, columnspan=2, padx=0) global search_ent search_ent = Entry(root) search_ent.grid(row=12, column=2) root.mainloop() ``` All the problem is related to the search function where the entry search\_ent is not defined and I m sure it is on the global scope The error is: ``` Traceback (most recent call last): File "C:/Users/asus/Documents/python/Projet/managment system/main.py", line 70, in <module> main_text.insert(1.0, search()) File "C:/Users/asus/Documents/python/Projet/managment system/main.py", line 51, in search noun = search_ent.get() NameError: name 'search_ent' is not defined ```
2020/08/02
[ "https://Stackoverflow.com/questions/63214706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13421322/" ]
you can give your search function an input. global statement is for an outer scope. for example when you want to make a function in another function. you can [check here](https://www.python-course.eu/python3_global_vs_local_variables.php). and now about your code. here is a simple way that I have said the idea: ``` import sqlite3 from tkinter import * global all,root, main_text, num_ent, nom_ent, search_ent def showall(): all = True con = sqlite3.connect("repertoire.db") cur = con.cursor() request = 'select * from blinta' cur.execute(request) table = str(cur.fetchall()).replace(')', '\n').replace('(', '').replace(',', '').replace('[', '').replace(']', '') return table con.commit() con.close() def delete(): con = sqlite3.connect("repertoire.db") cur = con.cursor() request = ' DELETE FROM blinta WHERE id=?' cur.execute(request, (ident.get(),)) con.commit() con.close() main_text.configure(state='normal') main_text.delete(1.0, END) main_text.insert(1.0, showall()) main_text.configure(state='disabled') ident.delete(0,END) def insert(): con = sqlite3.connect("repertoire.db") cur = con.cursor() request = 'insert into blinta (nom,numero) values(?,?)' cur.execute(request, (nom_ent.get(), num_ent.get())) con.commit() con.close() main_text.config(state='normal') main_text.delete(1.0, END) main_text.insert(1.0, showall()) main_text.config(state='disabled') num_ent.delete(0, END) nom_ent.delete(0, END) def search(search_ent): all=False con = sqlite3.connect("repertoire.db") cur = con.cursor() request = "select * from blinta where nom = ?" noun = search_ent.get() args=(noun,) cur.execute(request,args) selected = str(cur.fetchall()).replace(')', '\n').replace('(', '').replace(',', '').replace('[', '').replace(']', '') return selected con.commit() con.close() root = Tk() root.config(bg='#D2B024') root.geometry('450x650+900+0') root.minsize(450, 650) root.maxsize(450, 650) main_text = Text(root, bg='#CBCAC5', fg='black', width=30, height=40, state='normal') main_text.grid(column=1, row=1, rowspan=50, padx=9, pady=3) main_text.delete(1.0, END) search_ent = Entry(root) search_ent.grid(row=12, column=2) if all == True : main_text.insert(1.0, showall()) else : main_text.insert(1.0, search(search_ent)) main_text.config(state='disabled') nomlbl=Label(root,text='Enter noun to insert',bg='#D2B024').grid(row=1,column=2) nom_ent = Entry(root) nom_ent.grid(row=2, column=2) num_lbl=Label(root, text='Enter number to insert', bg='#D2B024').grid(row=3, column=2) num_ent = Entry(root) num_ent.grid(row=4, column=2) insert_btn = Button(relief='flat', fg='black', width=7, text='insert', font=("heveltica Bold", 15), command=insert).grid(row=5, column=2, columnspan=2, padx=50) Label(root,text='_______________________',bg='#D2B024').grid(row=6,column=2) idlbl=Label(root,text='Enter id to delete',bg='#D2B024').grid(row=7,column=2) ident=Entry(root) ident.grid(row=8,column=2) delete_btn = Button(relief='flat', fg='black', width=7, text='delete', font=("heveltica Bold", 15), command=delete).grid(row=9, column=2, columnspan=2, padx=0) Label(root,text='_______________________',bg='#D2B024').grid(row=10,column=2) search_lbl=Label(root,text='Enter noun to search',bg='#D2B024').grid(row=11,column=2) search_btn = Button(relief='flat', fg='black', width=7, text='search', font=("heveltica Bold", 15), command=lambda: search(search_ent)).grid(row=13, column=2, columnspan=2, padx=0) root.mainloop() ``` check `search()` carefully.
I slightly redisigned your code, and it seems to work. I changed the location of the `root`, `search_ent` and `main_text`, now it's before the functions, so there won't be an error. ``` import sqlite3 from tkinter import * global all,root, main_text, num_ent, nom_ent, search_ent global search_ent root = Tk() root.config(bg='#D2B024') root.geometry('450x650+900+0') root.minsize(450, 650) root.maxsize(450, 650) search_ent = Entry(root) search_ent.grid(row=12, column=2) main_text = Text(root, bg='#CBCAC5', fg='black', width=30, height=40, state='normal') main_text.grid(column=1, row=1, rowspan=50, padx=9, pady=3) main_text.delete(1.0, END) def showall(): all = True con = sqlite3.connect("repertoire.db") cur = con.cursor() request = 'select * from blinta' cur.execute(request) table = str(cur.fetchall()).replace(')', '\n').replace('(', '').replace(',', '').replace('[', '').replace(']', '') return table con.commit() con.close() def delete(): con = sqlite3.connect("repertoire.db") cur = con.cursor() request = ' DELETE FROM blinta WHERE id=?' cur.execute(request, (ident.get(),)) con.commit() con.close() main_text.configure(state='normal') main_text.delete(1.0, END) main_text.insert(1.0, showall()) main_text.configure(state='disabled') ident.delete(0,END) def insert(): con = sqlite3.connect("repertoire.db") cur = con.cursor() request = 'insert into blinta (nom,numero) values(?,?)' cur.execute(request, (nom_ent.get(), num_ent.get())) con.commit() con.close() main_text.config(state='normal') main_text.delete(1.0, END) main_text.insert(1.0, showall()) main_text.config(state='disabled') num_ent.delete(0, END) nom_ent.delete(0, END) def search(): all=False con = sqlite3.connect("repertoire.db") cur = con.cursor() request = "select * from blinta where nom = ?" noun = search_ent.get() args=(noun,) cur.execute(request,args) selected = str(cur.fetchall()).replace(')', '\n').replace('(', '').replace(',', '').replace('[', '').replace(']', '') return selected con.commit() con.close() insert_btn = Button(relief='flat', fg='black', width=7, text='insert', font=("heveltica Bold", 15), command=insert).grid(row=5, column=2, columnspan=2, padx=50) Label(root,text='_______________________',bg='#D2B024').grid(row=6,column=2) idlbl=Label(root,text='Enter id to delete',bg='#D2B024').grid(row=7,column=2) ident=Entry(root) ident.grid(row=8,column=2) delete_btn = Button(relief='flat', fg='black', width=7, text='delete', font=("heveltica Bold", 15), command=delete).grid(row=9, column=2, columnspan=2, padx=0) Label(root,text='_______________________',bg='#D2B024').grid(row=10,column=2) search_lbl=Label(root,text='Enter noun to search',bg='#D2B024').grid(row=11,column=2) search_btn = Button(relief='flat', fg='black', width=7, text='search', font=("heveltica Bold", 15), command=search).grid(row=13, column=2, columnspan=2, padx=0) if all == True : main_text.insert(1.0, showall()) else : main_text.insert(1.0, search()) main_text.config(state='disabled') nomlbl=Label(root,text='Enter noun to insert',bg='#D2B024').grid(row=1,column=2) nom_ent = Entry(root) nom_ent.grid(row=2, column=2) num_lbl=Label(root, text='Enter number to insert', bg='#D2B024').grid(row=3, column=2) num_ent = Entry(root) num_ent.grid(row=4, column=2) root.mainloop() ```
63,940,493
I want to compare every element of two matrices with the same dimensions. I want to know, if one of the elements in the first matrix is smaller than another with the same indices in the second one. I want to fill a third matrice with the values of the first, but every entry, where my criteria applies, should be a 0. Below I will show my approach: ``` a = ([1, 2, 3], [3, 4, 5], [5, 6, 7]) b = ([2, 3, 1], [3, 5, 4], [4, 4, 4]) c = np.zeros(a.shape) for i, a_i in enumerate(a): a_1 = a_i for i, b_i in enumerate(b): b_1 = b_i if a_1 < b_1: c[i] = 0 else: c[i] = a_1 ``` I am very sorry if i made any simple mistakes here, but i am new to python and SO. I found some posts on how to find entrys that match, but I dont know if there is a solution where could use that method. I appreciate any help, thank you.
2020/09/17
[ "https://Stackoverflow.com/questions/63940493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14285969/" ]
When you `map` over `question`: ``` question.map(function (quest){ ``` The `quest` variable will be each element of that array. Which in this case that element is: ``` [ { questions: "question1", answer1: "answer1", answer2: "answer2" }, { questions: "question2", answer1: "answer1", answer2: "answer2" } ] ``` An array of objects. So referencing an element of that array (such as `quest[0]`) would be: ``` { questions: "question1", answer1: "answer1", answer2: "answer2" } ``` Which indeed isn't an array and has no `.map()`. It sounds like you wanted to `map` over `quest`, not an element of it: ``` quest.map(function(ques){ return quest.questions; }) ``` Ultimately it looks like your variable naming is confusing you here. You have something called `question` which contains an array, each of which contains an array, each of which contains a property called `questions`. The plurality/singularity of those is dizzying. Perhaps `question` should really be `questionGroups`? It's an array of arrays. Each "group" is an array of questions. Each of which should have a property called `question`. Variable naming is important, and helps prevent confusion when writing your own code. So in this case it might be something like: ``` const [questionGroups, setQuestionGroups] = useState([]); // then later... questionGroups.map(function (questionGroup){ questionGroup.map(function (question){ return question.question; }) }) ```
In short objects doesn't have .map() function. Do this instead: `question.map(function (quest){ return quest.questions; });`
19,405,223
I hope not to make a fool of myself by re-asking this question, but I just can't figure out why my fixtures are not loaded when running test. I am using python 2.7.5 and Django 1.5.3. I can load my fixtures with `python manage.py testserver test_winning_answers`, with a location of `survey/fixtures/test_winning_answers.json`. ``` Creating test database for alias 'default'... Installed 13 object(s) from 1 fixture(s) Validating models... 0 errors found ``` My test class is doing the correct import: ``` from django.test import TestCase class QuestionWinningAnswersTest(TestCase): fixtures = ['test_winning_answers.json'] ... ``` But when trying to run the test command, it cannot find them: ``` python manage.py test survey.QuestionWinningAnswersTest -v3 ... Checking '/django/mysite/survey/fixtures' for fixtures... ... No json fixture 'initial_data' in '/django/mysite/survey/fixtures'. ... Installed 0 object(s) from 0 fixture(s) ... ``` I suspect I am missing something obvious, but cannot quite figure it out... any suggestion would be appreciated. Thanks!
2013/10/16
[ "https://Stackoverflow.com/questions/19405223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1014862/" ]
This will perform well if you have index on VersionColumn ``` SELECT * FROM MainTable m INNER JOIN JoinedTable j on j.ForeignID = m.ID CROSS APPLY (SELECT TOP 1 * FROM SubQueryTable sq WHERE sq.ForeignID = j.ID ORDER BY VersionColumn DESC) sj ```
**Answer** : Hi, Below query I have created as per your requirement using Country, State and City tables. > > > ``` > SELECT * FROM ( > SELECT m.countryName, j.StateName,c.CityName , ROW_NUMBER() OVER(PARTITION BY c.stateid ORDER BY c.cityid desc) AS 'x' > FROM CountryMaster m > INNER JOIN StateMaster j on j.CountryID = m.CountryID > INNER JOIN dbo.CityMaster c ON j.StateID = c.StateID > ) AS numbered WHERE x = 1 > > ``` > > **Below is your solution and above is only for your reference.** > > > ``` > SELECT * FROM ( > SELECT m.MainTablecolumnNm, j.JoinedTablecolumnNm,c.SubQueryTableColumnName , ROW_NUMBER() > OVER(PARTITION BY sj.ForeignID ORDER BY c.sjID desc) AS 'abc' > FROM MainTable m > INNER JOIN JoinedTable j on j.ForeignID = m.ID > INNER JOIN SubQueryTable sj ON sj.ForeignID = j.ID > ) AS numbered WHERE abc = 1 > > ``` > > **Thank you, Vishal Patel**
8,373,710
I have recently started using a Mac OS X Lion system and tried to use Vim in terminal. I previously had a .vimrc file in my Ubuntu system and had `F2` and `F5` keys mapped to pastetoggle and run python interpreter. Here are the two lines I have for it: ``` set pastetoggle=<F2> map <buffer> <F5> :wa<CR>:!/usr/bin/env python % <CR> ``` It's working just fine in Ubuntu but no longer works in Mac. (The above two lines are in .vimrc under my home dir.) I have turned off the Mac specific functions in my preference so the function keys are not been used for things like volume. Right now pressing `F5` seems to capitalize all letters until next word, and `F2` seems to delete next line and insert O..... Is there something else I need to do to have it working as expected? In addition, I had been using solarized as my color scheme and tried to have the same color scheme now in Mac. It seems that the scheme command is being read from .vimrc, but the colors are stil the default colors. Even though the .vim/colors files are just the same as before. Is this a related error that I need to fix? Perhaps another setting file being read after my own? (I looked for \_vimrc and .gvimrc, none exists.) Thanks!
2011/12/04
[ "https://Stackoverflow.com/questions/8373710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/501330/" ]
I finally got my function mappings working by resorting to adding mappings like this: ``` if has('mac') && ($TERM == 'xterm-256color' || $TERM == 'screen-256color') map <Esc>OP <F1> map <Esc>OQ <F2> map <Esc>OR <F3> map <Esc>OS <F4> map <Esc>[16~ <F5> map <Esc>[17~ <F6> map <Esc>[18~ <F7> map <Esc>[19~ <F8> map <Esc>[20~ <F9> map <Esc>[21~ <F10> map <Esc>[23~ <F11> map <Esc>[24~ <F12> endif ``` Answers to these questions were helpful, if you need to verify that these escape sequences match your terminal's or set your own: [mapping function keys in vim](https://stackoverflow.com/questions/3519532/mapping-function-keys-in-vim) [Binding special keys as vim shortcuts](https://stackoverflow.com/questions/9950944/binding-special-keys-as-vim-shortcuts) It probably depends on terminal emulators behaving consistently (guffaw), but @Mark Carey's suggestion wasn't enough for me (I wish it was so simple). With iTerm2 on OS X, I'd already configured it for `xterm-256color` and tmux for `screen-256color`, and function mappings still wouldn't work. So the `has('mac')` might be unnecessary if these sequences from iTerm2 are xterm-compliant, I haven't checked yet so left it in my own config for now. You might want some `imap` versions too. Note that you shouldn't use `noremap` variants since you **do** want these mappings to cascade (to trigger whatever you've mapped `<Fx>` to).
Regarding your colorscheme/solarized question - make sure you set up Terminal (or iTerm2, which I prefer) with the solarized profiles available in the full solarized distribution that you can download here: <http://ethanschoonover.com/solarized/files/solarized.zip>. Then the only other issue you may run into is making sure you set your $TERM `xterm-256color` or `screen-256color` if you use screen or tmux. You can take a look at my [dotfiles](https://github.com/prognostikos/dotfiles) for a working setup, but don't forget to setup your Terminal/iTerm color profiles as a first step.
8,373,710
I have recently started using a Mac OS X Lion system and tried to use Vim in terminal. I previously had a .vimrc file in my Ubuntu system and had `F2` and `F5` keys mapped to pastetoggle and run python interpreter. Here are the two lines I have for it: ``` set pastetoggle=<F2> map <buffer> <F5> :wa<CR>:!/usr/bin/env python % <CR> ``` It's working just fine in Ubuntu but no longer works in Mac. (The above two lines are in .vimrc under my home dir.) I have turned off the Mac specific functions in my preference so the function keys are not been used for things like volume. Right now pressing `F5` seems to capitalize all letters until next word, and `F2` seems to delete next line and insert O..... Is there something else I need to do to have it working as expected? In addition, I had been using solarized as my color scheme and tried to have the same color scheme now in Mac. It seems that the scheme command is being read from .vimrc, but the colors are stil the default colors. Even though the .vim/colors files are just the same as before. Is this a related error that I need to fix? Perhaps another setting file being read after my own? (I looked for \_vimrc and .gvimrc, none exists.) Thanks!
2011/12/04
[ "https://Stackoverflow.com/questions/8373710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/501330/" ]
Regarding your colorscheme/solarized question - make sure you set up Terminal (or iTerm2, which I prefer) with the solarized profiles available in the full solarized distribution that you can download here: <http://ethanschoonover.com/solarized/files/solarized.zip>. Then the only other issue you may run into is making sure you set your $TERM `xterm-256color` or `screen-256color` if you use screen or tmux. You can take a look at my [dotfiles](https://github.com/prognostikos/dotfiles) for a working setup, but don't forget to setup your Terminal/iTerm color profiles as a first step.
I used the following in my vimrc to copy and paste ``` if &term =~ "xterm.*" let &t_ti = &t_ti . "\e[?2004h" let &t_te = "\e[?2004l" . &t_te function XTermPasteBegin(ret) set pastetoggle=<Esc>[201~ set paste return a:ret endfunction map <expr> <Esc>[200~ XTermPasteBegin("i") imap <expr> <Esc>[200~ XTermPasteBegin("") cmap <Esc>[200~ <nop> cmap <Esc>[201~ <nop> endif ``` I got it from here <https://stackoverflow.com/a/7053522>
8,373,710
I have recently started using a Mac OS X Lion system and tried to use Vim in terminal. I previously had a .vimrc file in my Ubuntu system and had `F2` and `F5` keys mapped to pastetoggle and run python interpreter. Here are the two lines I have for it: ``` set pastetoggle=<F2> map <buffer> <F5> :wa<CR>:!/usr/bin/env python % <CR> ``` It's working just fine in Ubuntu but no longer works in Mac. (The above two lines are in .vimrc under my home dir.) I have turned off the Mac specific functions in my preference so the function keys are not been used for things like volume. Right now pressing `F5` seems to capitalize all letters until next word, and `F2` seems to delete next line and insert O..... Is there something else I need to do to have it working as expected? In addition, I had been using solarized as my color scheme and tried to have the same color scheme now in Mac. It seems that the scheme command is being read from .vimrc, but the colors are stil the default colors. Even though the .vim/colors files are just the same as before. Is this a related error that I need to fix? Perhaps another setting file being read after my own? (I looked for \_vimrc and .gvimrc, none exists.) Thanks!
2011/12/04
[ "https://Stackoverflow.com/questions/8373710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/501330/" ]
I finally got my function mappings working by resorting to adding mappings like this: ``` if has('mac') && ($TERM == 'xterm-256color' || $TERM == 'screen-256color') map <Esc>OP <F1> map <Esc>OQ <F2> map <Esc>OR <F3> map <Esc>OS <F4> map <Esc>[16~ <F5> map <Esc>[17~ <F6> map <Esc>[18~ <F7> map <Esc>[19~ <F8> map <Esc>[20~ <F9> map <Esc>[21~ <F10> map <Esc>[23~ <F11> map <Esc>[24~ <F12> endif ``` Answers to these questions were helpful, if you need to verify that these escape sequences match your terminal's or set your own: [mapping function keys in vim](https://stackoverflow.com/questions/3519532/mapping-function-keys-in-vim) [Binding special keys as vim shortcuts](https://stackoverflow.com/questions/9950944/binding-special-keys-as-vim-shortcuts) It probably depends on terminal emulators behaving consistently (guffaw), but @Mark Carey's suggestion wasn't enough for me (I wish it was so simple). With iTerm2 on OS X, I'd already configured it for `xterm-256color` and tmux for `screen-256color`, and function mappings still wouldn't work. So the `has('mac')` might be unnecessary if these sequences from iTerm2 are xterm-compliant, I haven't checked yet so left it in my own config for now. You might want some `imap` versions too. Note that you shouldn't use `noremap` variants since you **do** want these mappings to cascade (to trigger whatever you've mapped `<Fx>` to).
see this answer: <https://stackoverflow.com/a/10524999/210923> essentially changing my TERM type to xterm-256color allowed me to map the function keys properly.
8,373,710
I have recently started using a Mac OS X Lion system and tried to use Vim in terminal. I previously had a .vimrc file in my Ubuntu system and had `F2` and `F5` keys mapped to pastetoggle and run python interpreter. Here are the two lines I have for it: ``` set pastetoggle=<F2> map <buffer> <F5> :wa<CR>:!/usr/bin/env python % <CR> ``` It's working just fine in Ubuntu but no longer works in Mac. (The above two lines are in .vimrc under my home dir.) I have turned off the Mac specific functions in my preference so the function keys are not been used for things like volume. Right now pressing `F5` seems to capitalize all letters until next word, and `F2` seems to delete next line and insert O..... Is there something else I need to do to have it working as expected? In addition, I had been using solarized as my color scheme and tried to have the same color scheme now in Mac. It seems that the scheme command is being read from .vimrc, but the colors are stil the default colors. Even though the .vim/colors files are just the same as before. Is this a related error that I need to fix? Perhaps another setting file being read after my own? (I looked for \_vimrc and .gvimrc, none exists.) Thanks!
2011/12/04
[ "https://Stackoverflow.com/questions/8373710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/501330/" ]
see this answer: <https://stackoverflow.com/a/10524999/210923> essentially changing my TERM type to xterm-256color allowed me to map the function keys properly.
I used the following in my vimrc to copy and paste ``` if &term =~ "xterm.*" let &t_ti = &t_ti . "\e[?2004h" let &t_te = "\e[?2004l" . &t_te function XTermPasteBegin(ret) set pastetoggle=<Esc>[201~ set paste return a:ret endfunction map <expr> <Esc>[200~ XTermPasteBegin("i") imap <expr> <Esc>[200~ XTermPasteBegin("") cmap <Esc>[200~ <nop> cmap <Esc>[201~ <nop> endif ``` I got it from here <https://stackoverflow.com/a/7053522>
8,373,710
I have recently started using a Mac OS X Lion system and tried to use Vim in terminal. I previously had a .vimrc file in my Ubuntu system and had `F2` and `F5` keys mapped to pastetoggle and run python interpreter. Here are the two lines I have for it: ``` set pastetoggle=<F2> map <buffer> <F5> :wa<CR>:!/usr/bin/env python % <CR> ``` It's working just fine in Ubuntu but no longer works in Mac. (The above two lines are in .vimrc under my home dir.) I have turned off the Mac specific functions in my preference so the function keys are not been used for things like volume. Right now pressing `F5` seems to capitalize all letters until next word, and `F2` seems to delete next line and insert O..... Is there something else I need to do to have it working as expected? In addition, I had been using solarized as my color scheme and tried to have the same color scheme now in Mac. It seems that the scheme command is being read from .vimrc, but the colors are stil the default colors. Even though the .vim/colors files are just the same as before. Is this a related error that I need to fix? Perhaps another setting file being read after my own? (I looked for \_vimrc and .gvimrc, none exists.) Thanks!
2011/12/04
[ "https://Stackoverflow.com/questions/8373710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/501330/" ]
I finally got my function mappings working by resorting to adding mappings like this: ``` if has('mac') && ($TERM == 'xterm-256color' || $TERM == 'screen-256color') map <Esc>OP <F1> map <Esc>OQ <F2> map <Esc>OR <F3> map <Esc>OS <F4> map <Esc>[16~ <F5> map <Esc>[17~ <F6> map <Esc>[18~ <F7> map <Esc>[19~ <F8> map <Esc>[20~ <F9> map <Esc>[21~ <F10> map <Esc>[23~ <F11> map <Esc>[24~ <F12> endif ``` Answers to these questions were helpful, if you need to verify that these escape sequences match your terminal's or set your own: [mapping function keys in vim](https://stackoverflow.com/questions/3519532/mapping-function-keys-in-vim) [Binding special keys as vim shortcuts](https://stackoverflow.com/questions/9950944/binding-special-keys-as-vim-shortcuts) It probably depends on terminal emulators behaving consistently (guffaw), but @Mark Carey's suggestion wasn't enough for me (I wish it was so simple). With iTerm2 on OS X, I'd already configured it for `xterm-256color` and tmux for `screen-256color`, and function mappings still wouldn't work. So the `has('mac')` might be unnecessary if these sequences from iTerm2 are xterm-compliant, I haven't checked yet so left it in my own config for now. You might want some `imap` versions too. Note that you shouldn't use `noremap` variants since you **do** want these mappings to cascade (to trigger whatever you've mapped `<Fx>` to).
I used the following in my vimrc to copy and paste ``` if &term =~ "xterm.*" let &t_ti = &t_ti . "\e[?2004h" let &t_te = "\e[?2004l" . &t_te function XTermPasteBegin(ret) set pastetoggle=<Esc>[201~ set paste return a:ret endfunction map <expr> <Esc>[200~ XTermPasteBegin("i") imap <expr> <Esc>[200~ XTermPasteBegin("") cmap <Esc>[200~ <nop> cmap <Esc>[201~ <nop> endif ``` I got it from here <https://stackoverflow.com/a/7053522>
67,712,314
Can anyone see what im doing wrong here? works fine locally, but when running it in docker it cant seem to find my modules ... The **init**.py files are emtpy if that info could help. Im no expert in docker and non of the tips I've googled/stackoverflowed so far has panned out, such as adding pythonpath env in the dockerfile. Error log from docker: ``` Traceback (most recent call last): File "/usr/local/bin/uvicorn", line 8, in <module> sys.exit(main()) File "/usr/local/lib/python3.7/site-packages/click/core.py", line 829, in __call__ return self.main(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/click/core.py", line 782, in main rv = self.invoke(ctx) File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1066, in invoke return ctx.invoke(self.callback, **ctx.params) File "/usr/local/lib/python3.7/site-packages/click/core.py", line 610, in invoke return callback(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/uvicorn/main.py", line 331, in main run(**kwargs) File "/usr/local/lib/python3.7/site-packages/uvicorn/main.py", line 354, in run server.run() File "/usr/local/lib/python3.7/site-packages/uvicorn/main.py", line 382, in run loop.run_until_complete(self.serve(sockets=sockets)) File "uvloop/loop.pyx", line 1456, in uvloop.loop.Loop.run_until_complete File "/usr/local/lib/python3.7/site-packages/uvicorn/main.py", line 389, in serve config.load() File "/usr/local/lib/python3.7/site-packages/uvicorn/config.py", line 288, in load self.loaded_app = import_from_string(self.app) File "/usr/local/lib/python3.7/site-packages/uvicorn/importer.py", line 23, in import_from_string raise exc from None File "/usr/local/lib/python3.7/site-packages/uvicorn/importer.py", line 20, in import_from_string module = importlib.import_module(module_str) File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "./main.py", line 3, in <module> from routers.user import router as user_router ModuleNotFoundError: No module named 'routers' ``` Dockerfile: ``` FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7 RUN apt-get update RUN apt-get install -y --no-install-recommends # install requirements RUN pip3 install fastapi[all] uvicorn[standard] # Move files COPY ./* /app # attemt to fix a python ModuleNotFoundError WORKDIR /app #ENV PATH=$PATH:/app ENV PYTHONPATH "${PYTHONPATH}:/app" CMD [ "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "15400"] ``` Docker-compose.yml: ``` version: '3' services: core_api: build: . container_name: "core-api-container" ports: - "8000:15400" volumes: - ./app/:/app ``` file structure: ``` API/ --__init__.py --Dockerfile --docker-compose.yml --main.py --routers/ --__init__.py --user.py --x.py ``` main.py: ``` from fastapi import FastAPI from routers.user import router as user_router from routers.x import router as x_router app = FastAPI() app.include_router(user_router) app.include_router(x_router) ```
2021/05/26
[ "https://Stackoverflow.com/questions/67712314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14994913/" ]
After running `docker container run -it your-docker-container bash` and checked the files, it seems docker does not copy the file hierarchy as i expected. all files was under the same folder /app. none of my subfolder from the project in my local files were added, just the files those contained. No wonder i got ModuleNotFoundError. To fix this i simply made a new project and put all my python files in the same directoy, and edited them all to import correctly. There is probably a simpler way to fix this, but cba. to figure that out at this time.
I had almost the same issue with this and I try to fix it not by changing the directory structure of my application or how I copy the files but by running the application directly using gunicorn. I run it with the following command : `gunicorn -k uvicorn.workers.UvicornWorker run:app` that can either be updated in the entrypoint of your docker file or in the command section of compose if you are using docker-compose.
71,907,288
Question ======== What is the shortest and most efficient (preferrable most efficient) way of reading in a single depth folder and creating a file tree that consists of the longest substrings of each file? start with this --------------- ``` . β”œβ”€β”€ hello β”œβ”€β”€ lima_peru β”œβ”€β”€ limabeans β”œβ”€β”€ limes β”œβ”€β”€ limit β”œβ”€β”€ what_are_those β”œβ”€β”€ what_is_bofa └── what_is_up ``` end with this ------------- ``` . β”œβ”€β”€ hello β”œβ”€β”€ lim β”‚Β Β  β”œβ”€β”€ lima β”‚Β Β  β”‚Β Β  β”œβ”€β”€ lima_peru β”‚Β Β  β”‚Β Β  └── limabeans β”‚Β Β  β”œβ”€β”€ limes β”‚Β Β  └── limit └── what_ β”œβ”€β”€ what_are_those └── what_is_ β”œβ”€β”€ what_is_bofa └── what_is_up ``` Framing ======= I feel like I know how to do the naive version of this problem but I wanted to see what the best way to do this in **python** would be. Format ====== ```py def longest_substrings_filetree(old_directory: str, new_directory: str): ... ```
2022/04/18
[ "https://Stackoverflow.com/questions/71907288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17356304/" ]
You are using the same input `ID` in `colorId` when you select the same group the second time. However, you need unique input `ID`s in shiny. I have added a counter to change it. Try this. ``` library(shinyjs) # useShinyjs library(ggplot2) library(RColorBrewer) library(shiny) ui <- fluidPage( titlePanel("Reprex"), sidebarLayout( sidebarPanel( useShinyjs(), fluidRow(column(9, fileInput('manifest', 'Choose File', accept = c('text/csv', 'text/comma-separated-values,text/plain', '.csv'))), column(3, actionButton("load_button", "Load", width = "100%"))), fluidRow(column(5, selectInput(inputId = "group_palette_input", label = "Palette Selector", choices = NULL)), column(5, selectInput(inputId = "column_input", label = "Column Selector", choices = rownames(brewer.pal.info)))), uiOutput("group_colors"), width=4), mainPanel( tabsetPanel(id = "tabs", tabPanel("Plot") ) ) ) ) server <- function(input, output, session) { cntr <- reactiveValues(val=0) # Load the demo data on initialization and press the load button to update the file # data <- reactiveValues() # observeEvent(eventExpr = input$load_button, ignoreInit = FALSE, ignoreNULL = FALSE, { # manifestName = ifelse(is.null(input$manifest$datapath), "file.csv", input$manifest$datapath) # man = read.table(manifestName, sep = "\t", header = T, check.names=F, strip.white = T) # data$manifest <- man[man$include, ] # }) datamanifest <- reactive({ req(input$manifest) read.csv(input$manifest$datapath, header = TRUE) }) # Update column selector observeEvent(datamanifest(), { freezeReactiveValue(input, "column_input") updateSelectInput(inputId = "column_input", choices = names(datamanifest()), selected = "group") # All files should have a group column }) # Update palette selector observeEvent(datamanifest(), { freezeReactiveValue(input, "group_palette_input") updateSelectInput(inputId = "group_palette_input", choices = rownames(brewer.pal.info), selected = "Dark2") }) groupIncludeManualPaletteInput <- eventReactive(groups(), { req(input$group_palette_input) cntr$val <- cntr$val + 1 fullColors = brewer.pal(length(groups()), input$group_palette_input) lapply(1:length(groups()), function(groupIndex) { colorId = paste0(groups()[groupIndex], "_color", cntr$val) fluidRow(column(5, textInput(inputId = colorId, label = NULL, value = fullColors[groupIndex])), column(1, checkboxInput(inputId = as.character(groups()[groupIndex]), # Numeric column causes issues, need to wrap with as.character label = groups()[groupIndex], value = TRUE), style='padding:0px;')) # Removing padding puts the two columns closer together }) # End lapply }) groups <- eventReactive(input$column_input, {sort(unique(datamanifest()[[input$column_input]]))}) # Update groupIncludeManualPaletteInput observeEvent(input$group_palette_input, { groupColorIds = paste0(groups(), "_color",cntr$val) fullColors = brewer.pal(length(groups()), input$group_palette_input) for (groupColorIndex in seq_along(groupColorIds)) { updateTextInput(session, groupColorIds[groupColorIndex], value = fullColors[groupColorIndex]) } }) # Vector of booleans to mask the included groups includedGroups <- eventReactive(groups(), {unlist(map(as.character(groups()), ~input[[.x]]))}) # unlist() allows includedGroups to be used as an index variable # Vector of characters of group names that are included currentGroups <- eventReactive(includedGroups(), {groups()[includedGroups()]}) # Vector of characters of color names that are included currentColors <- reactive(unlist(map(groups(), ~input[[paste0(.x, "_color")]])[includedGroups()])) output$group_colors <- renderUI(groupIncludeManualPaletteInput()) # Make the borders of these textboxes match the color they describe # This is run twice when it works, but only once when it doesn't as a simple observe # As an observeEvent on groups(), only activates once and temporarily shows the border color; Adding in the req(input[[colorId]]) doesn't help # Same thing when the observation is on the groupIncludeManualPaletteInput() # Doubling the js code doesn't work # In the html, I can see that the border color is not being set # observing currentColors() is a dud too # Adding an if statement in the javascript doesn't change behavior. observe({ lapply(seq_along(groups()), function(groupIndex) { colorId = paste0(groups()[groupIndex], "_color",cntr$val) cat("Made it into Loop,", input[[colorId]], '\n') cat(colorId, ': ', input[[colorId]], '\n\n') runjs(paste0("document.getElementById('", colorId, "').style.borderColor ='", input[[colorId]] ,"'")) runjs(paste0("document.getElementById('", colorId, "').style.borderWidth = 'thick'")) }) }) } shinyApp(ui, server) ```
Following up with @YBS's response to my comment, I resorted to precomputing all the fields that could be made with the input file and using `conditionalPanel()` to selectively show them. This has the theoretical disadvantage that another file cannot be loaded in, but in practice I'm not seeing it. But I can use @YBS's answer, a counter, to fix that should it ever stop being theoretical. I also changed the section that makes the fields into a regular reactive dependent solely on data$manifest. I also changed the update function for the colors so they fits inside an observe instead of observeEvent. No other changes were necessary, but I hit a snag when I over-engineered around what I thought was a big update.
3,510,846
Sorry if the question is bit confusing. This is similar to [this question](https://stackoverflow.com/questions/2553668/how-to-remove-list-of-words-from-strings) I think this the above question is close to what I want, but in Clojure. There is [another](https://stackoverflow.com/questions/3136689/find-and-replace-string-values-in-python-list) question I need something like this but instead of '[br]' in that question, there is a list of strings that need to be searched and removed. Hope I made myself clear. I think that this is due to the fact that strings in python are immutable. I have a list of noise words that need to be removed from a list of strings. If I use the list comprehension, I end up searching the same string again and again. So, only "of" gets removed and not "the". So my modified list looks like this ``` places = ['New York', 'the New York City', 'at Moscow' and many more] noise_words_list = ['of', 'the', 'in', 'for', 'at'] for place in places: stuff = [place.replace(w, "").strip() for w in noise_words_list if place.startswith(w)] ``` I would like to know as to what mistake I'm doing.
2010/08/18
[ "https://Stackoverflow.com/questions/3510846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24382/" ]
Here is my stab at it. This uses regular expressions. ``` import re pattern = re.compile("(of|the|in|for|at)\W", re.I) phrases = ['of New York', 'of the New York'] map(lambda phrase: pattern.sub("", phrase), phrases) # ['New York', 'New York'] ``` Sans `lambda`: ``` [pattern.sub("", phrase) for phrase in phrases] ``` **Update** Fix for the bug pointed out by [gnibbler](https://stackoverflow.com/users/174728/gnibbler) (thanks!): ``` pattern = re.compile("\\b(of|the|in|for|at)\\W", re.I) phrases = ['of New York', 'of the New York', 'Spain has rain'] [pattern.sub("", phrase) for phrase in phrases] # ['New York', 'New York', 'Spain has rain'] ``` @prabhu: the above change avoids snipping off the trailing "*in*" from "Spain". To verify run both versions of the regular expressions against the phrase "Spain has rain".
``` >>> import re >>> noise_words_list = ['of', 'the', 'in', 'for', 'at'] >>> phrases = ['of New York', 'of the New York'] >>> noise_re = re.compile('\\b(%s)\\W'%('|'.join(map(re.escape,noise_words_list))),re.I) >>> [noise_re.sub('',p) for p in phrases] ['New York', 'New York'] ```
3,510,846
Sorry if the question is bit confusing. This is similar to [this question](https://stackoverflow.com/questions/2553668/how-to-remove-list-of-words-from-strings) I think this the above question is close to what I want, but in Clojure. There is [another](https://stackoverflow.com/questions/3136689/find-and-replace-string-values-in-python-list) question I need something like this but instead of '[br]' in that question, there is a list of strings that need to be searched and removed. Hope I made myself clear. I think that this is due to the fact that strings in python are immutable. I have a list of noise words that need to be removed from a list of strings. If I use the list comprehension, I end up searching the same string again and again. So, only "of" gets removed and not "the". So my modified list looks like this ``` places = ['New York', 'the New York City', 'at Moscow' and many more] noise_words_list = ['of', 'the', 'in', 'for', 'at'] for place in places: stuff = [place.replace(w, "").strip() for w in noise_words_list if place.startswith(w)] ``` I would like to know as to what mistake I'm doing.
2010/08/18
[ "https://Stackoverflow.com/questions/3510846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24382/" ]
Here is my stab at it. This uses regular expressions. ``` import re pattern = re.compile("(of|the|in|for|at)\W", re.I) phrases = ['of New York', 'of the New York'] map(lambda phrase: pattern.sub("", phrase), phrases) # ['New York', 'New York'] ``` Sans `lambda`: ``` [pattern.sub("", phrase) for phrase in phrases] ``` **Update** Fix for the bug pointed out by [gnibbler](https://stackoverflow.com/users/174728/gnibbler) (thanks!): ``` pattern = re.compile("\\b(of|the|in|for|at)\\W", re.I) phrases = ['of New York', 'of the New York', 'Spain has rain'] [pattern.sub("", phrase) for phrase in phrases] # ['New York', 'New York', 'Spain has rain'] ``` @prabhu: the above change avoids snipping off the trailing "*in*" from "Spain". To verify run both versions of the regular expressions against the phrase "Spain has rain".
Since you would like to know what you are doing wrong, this line: ``` stuff = [place.replace(w, "").strip() for w in noise_words_list if place.startswith(w)] ``` takes place, and then begins to loop over words. First it checks for "of". Your place (e.g. "of the New York") is checked to see if it starts with "of". It is transformed (call to replace and strip) and added to the result list. The crucial thing here is that result is never examined again. For every word you iterate over in the comprehension, a new result is added to the result list. So the next word is "the" and your place ("of the New York") doesn't start with "the", so no new result is added. I assume the result you got eventually is the concatenation of your place variables. A simpler to read and understand procedural version would be (untested): ``` results = [] for place in places: for word in words: if place.startswith(word): place = place.replace(word, "").strip() results.append(place) ``` Keep in mind that `replace()` will remove the word anywhere in the string, even if it occurs as a simple substring. You can avoid this by using regexes with a pattern something like `^the\b`.
3,510,846
Sorry if the question is bit confusing. This is similar to [this question](https://stackoverflow.com/questions/2553668/how-to-remove-list-of-words-from-strings) I think this the above question is close to what I want, but in Clojure. There is [another](https://stackoverflow.com/questions/3136689/find-and-replace-string-values-in-python-list) question I need something like this but instead of '[br]' in that question, there is a list of strings that need to be searched and removed. Hope I made myself clear. I think that this is due to the fact that strings in python are immutable. I have a list of noise words that need to be removed from a list of strings. If I use the list comprehension, I end up searching the same string again and again. So, only "of" gets removed and not "the". So my modified list looks like this ``` places = ['New York', 'the New York City', 'at Moscow' and many more] noise_words_list = ['of', 'the', 'in', 'for', 'at'] for place in places: stuff = [place.replace(w, "").strip() for w in noise_words_list if place.startswith(w)] ``` I would like to know as to what mistake I'm doing.
2010/08/18
[ "https://Stackoverflow.com/questions/3510846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24382/" ]
Here is my stab at it. This uses regular expressions. ``` import re pattern = re.compile("(of|the|in|for|at)\W", re.I) phrases = ['of New York', 'of the New York'] map(lambda phrase: pattern.sub("", phrase), phrases) # ['New York', 'New York'] ``` Sans `lambda`: ``` [pattern.sub("", phrase) for phrase in phrases] ``` **Update** Fix for the bug pointed out by [gnibbler](https://stackoverflow.com/users/174728/gnibbler) (thanks!): ``` pattern = re.compile("\\b(of|the|in|for|at)\\W", re.I) phrases = ['of New York', 'of the New York', 'Spain has rain'] [pattern.sub("", phrase) for phrase in phrases] # ['New York', 'New York', 'Spain has rain'] ``` @prabhu: the above change avoids snipping off the trailing "*in*" from "Spain". To verify run both versions of the regular expressions against the phrase "Spain has rain".
Without regexp you could do like this: ``` places = ['of New York', 'of the New York'] noise_words_set = {'of', 'the', 'at', 'for', 'in'} stuff = [' '.join(w for w in place.split() if w.lower() not in noise_words_set) for place in places ] print stuff ```
3,510,846
Sorry if the question is bit confusing. This is similar to [this question](https://stackoverflow.com/questions/2553668/how-to-remove-list-of-words-from-strings) I think this the above question is close to what I want, but in Clojure. There is [another](https://stackoverflow.com/questions/3136689/find-and-replace-string-values-in-python-list) question I need something like this but instead of '[br]' in that question, there is a list of strings that need to be searched and removed. Hope I made myself clear. I think that this is due to the fact that strings in python are immutable. I have a list of noise words that need to be removed from a list of strings. If I use the list comprehension, I end up searching the same string again and again. So, only "of" gets removed and not "the". So my modified list looks like this ``` places = ['New York', 'the New York City', 'at Moscow' and many more] noise_words_list = ['of', 'the', 'in', 'for', 'at'] for place in places: stuff = [place.replace(w, "").strip() for w in noise_words_list if place.startswith(w)] ``` I would like to know as to what mistake I'm doing.
2010/08/18
[ "https://Stackoverflow.com/questions/3510846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24382/" ]
``` >>> import re >>> noise_words_list = ['of', 'the', 'in', 'for', 'at'] >>> phrases = ['of New York', 'of the New York'] >>> noise_re = re.compile('\\b(%s)\\W'%('|'.join(map(re.escape,noise_words_list))),re.I) >>> [noise_re.sub('',p) for p in phrases] ['New York', 'New York'] ```
Since you would like to know what you are doing wrong, this line: ``` stuff = [place.replace(w, "").strip() for w in noise_words_list if place.startswith(w)] ``` takes place, and then begins to loop over words. First it checks for "of". Your place (e.g. "of the New York") is checked to see if it starts with "of". It is transformed (call to replace and strip) and added to the result list. The crucial thing here is that result is never examined again. For every word you iterate over in the comprehension, a new result is added to the result list. So the next word is "the" and your place ("of the New York") doesn't start with "the", so no new result is added. I assume the result you got eventually is the concatenation of your place variables. A simpler to read and understand procedural version would be (untested): ``` results = [] for place in places: for word in words: if place.startswith(word): place = place.replace(word, "").strip() results.append(place) ``` Keep in mind that `replace()` will remove the word anywhere in the string, even if it occurs as a simple substring. You can avoid this by using regexes with a pattern something like `^the\b`.
3,510,846
Sorry if the question is bit confusing. This is similar to [this question](https://stackoverflow.com/questions/2553668/how-to-remove-list-of-words-from-strings) I think this the above question is close to what I want, but in Clojure. There is [another](https://stackoverflow.com/questions/3136689/find-and-replace-string-values-in-python-list) question I need something like this but instead of '[br]' in that question, there is a list of strings that need to be searched and removed. Hope I made myself clear. I think that this is due to the fact that strings in python are immutable. I have a list of noise words that need to be removed from a list of strings. If I use the list comprehension, I end up searching the same string again and again. So, only "of" gets removed and not "the". So my modified list looks like this ``` places = ['New York', 'the New York City', 'at Moscow' and many more] noise_words_list = ['of', 'the', 'in', 'for', 'at'] for place in places: stuff = [place.replace(w, "").strip() for w in noise_words_list if place.startswith(w)] ``` I would like to know as to what mistake I'm doing.
2010/08/18
[ "https://Stackoverflow.com/questions/3510846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24382/" ]
Without regexp you could do like this: ``` places = ['of New York', 'of the New York'] noise_words_set = {'of', 'the', 'at', 'for', 'in'} stuff = [' '.join(w for w in place.split() if w.lower() not in noise_words_set) for place in places ] print stuff ```
``` >>> import re >>> noise_words_list = ['of', 'the', 'in', 'for', 'at'] >>> phrases = ['of New York', 'of the New York'] >>> noise_re = re.compile('\\b(%s)\\W'%('|'.join(map(re.escape,noise_words_list))),re.I) >>> [noise_re.sub('',p) for p in phrases] ['New York', 'New York'] ```
3,510,846
Sorry if the question is bit confusing. This is similar to [this question](https://stackoverflow.com/questions/2553668/how-to-remove-list-of-words-from-strings) I think this the above question is close to what I want, but in Clojure. There is [another](https://stackoverflow.com/questions/3136689/find-and-replace-string-values-in-python-list) question I need something like this but instead of '[br]' in that question, there is a list of strings that need to be searched and removed. Hope I made myself clear. I think that this is due to the fact that strings in python are immutable. I have a list of noise words that need to be removed from a list of strings. If I use the list comprehension, I end up searching the same string again and again. So, only "of" gets removed and not "the". So my modified list looks like this ``` places = ['New York', 'the New York City', 'at Moscow' and many more] noise_words_list = ['of', 'the', 'in', 'for', 'at'] for place in places: stuff = [place.replace(w, "").strip() for w in noise_words_list if place.startswith(w)] ``` I would like to know as to what mistake I'm doing.
2010/08/18
[ "https://Stackoverflow.com/questions/3510846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24382/" ]
Without regexp you could do like this: ``` places = ['of New York', 'of the New York'] noise_words_set = {'of', 'the', 'at', 'for', 'in'} stuff = [' '.join(w for w in place.split() if w.lower() not in noise_words_set) for place in places ] print stuff ```
Since you would like to know what you are doing wrong, this line: ``` stuff = [place.replace(w, "").strip() for w in noise_words_list if place.startswith(w)] ``` takes place, and then begins to loop over words. First it checks for "of". Your place (e.g. "of the New York") is checked to see if it starts with "of". It is transformed (call to replace and strip) and added to the result list. The crucial thing here is that result is never examined again. For every word you iterate over in the comprehension, a new result is added to the result list. So the next word is "the" and your place ("of the New York") doesn't start with "the", so no new result is added. I assume the result you got eventually is the concatenation of your place variables. A simpler to read and understand procedural version would be (untested): ``` results = [] for place in places: for word in words: if place.startswith(word): place = place.replace(word, "").strip() results.append(place) ``` Keep in mind that `replace()` will remove the word anywhere in the string, even if it occurs as a simple substring. You can avoid this by using regexes with a pattern something like `^the\b`.
56,401,685
### Concepts of objects in python classes While reading about old style and new style classes in Python , term object occurs many times. What is exactly an object? Is it a base class or simply an object or a parameter ? for e.g. : New style for creating a class in python ``` class Class_name(object): pass ``` If object is just another class which is base class for Class\_name (inheritance) then what will be termed as object in python ?
2019/05/31
[ "https://Stackoverflow.com/questions/56401685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5084760/" ]
All objects in python are ultimately derived from "object". You don't need to be explicit about it in python 3, but it's common to explicitly derive from object.
Object is a generic term. It could be a class, a string, or any type. (and probably many other things) As an example look at the term OOP, "Object oriented programming". Object has the same meaning here.
56,401,685
### Concepts of objects in python classes While reading about old style and new style classes in Python , term object occurs many times. What is exactly an object? Is it a base class or simply an object or a parameter ? for e.g. : New style for creating a class in python ``` class Class_name(object): pass ``` If object is just another class which is base class for Class\_name (inheritance) then what will be termed as object in python ?
2019/05/31
[ "https://Stackoverflow.com/questions/56401685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5084760/" ]
From [[Python 2.Docs]: Built-in Functions - class object](https://docs.python.org/2/library/functions.html#object) (**emphasis** is mine): > > Return a new featureless object. **[object](https://docs.python.org/2/library/functions.html#object) is a base for all new style classes**. It has the methods that are common to all instances of new style classes. > > > You could also check [[Python]: New-style Classes](https://www.python.org/doc/newstyle) (and referenced *URL*s) for more details. > > > ```py > >>> import sys > >>> sys.version > '2.7.10 (default, Mar 8 2016, 15:02:46) [MSC v.1600 64 bit (AMD64)]' > >>> > >>> class OldStyle(): > ... pass > ... > >>> > >>> class NewStyle(object): > ... pass > ... > >>> > >>> dir(OldStyle) > ['__doc__', '__module__'] > >>> > >>> dir(NewStyle) > ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] > >>> > >>> old_style = OldStyle() > >>> new_style = NewStyle() > >>> > >>> type(old_style) > <type 'instance'> > >>> > >>> type(new_style) > <class '__main__.ClassNewStyle'> > > ``` > > In the above example, *old\_style* and *new\_style* are instances (or may be referred to as ***object***s), so I guess the answer to your question is: depends on the context.
Object is a generic term. It could be a class, a string, or any type. (and probably many other things) As an example look at the term OOP, "Object oriented programming". Object has the same meaning here.
56,401,685
### Concepts of objects in python classes While reading about old style and new style classes in Python , term object occurs many times. What is exactly an object? Is it a base class or simply an object or a parameter ? for e.g. : New style for creating a class in python ``` class Class_name(object): pass ``` If object is just another class which is base class for Class\_name (inheritance) then what will be termed as object in python ?
2019/05/31
[ "https://Stackoverflow.com/questions/56401685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5084760/" ]
An Object is something in any Object Oriented language including Python, C#, Java and even JavaScript these days. Objects are also prevalent in 3d modeling software but are not per se the same thing. An Object is an INSTANTIATED class. A class is a blueprint for creating object. Almost everything in Python is an object. In reference to how you seem to be regarding to exclusivity of objects in python, yes, there is an object class. C# has them too and possibly others where you would use it not dissimilar to creating a string or int.
Object is a generic term. It could be a class, a string, or any type. (and probably many other things) As an example look at the term OOP, "Object oriented programming". Object has the same meaning here.
56,401,685
### Concepts of objects in python classes While reading about old style and new style classes in Python , term object occurs many times. What is exactly an object? Is it a base class or simply an object or a parameter ? for e.g. : New style for creating a class in python ``` class Class_name(object): pass ``` If object is just another class which is base class for Class\_name (inheritance) then what will be termed as object in python ?
2019/05/31
[ "https://Stackoverflow.com/questions/56401685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5084760/" ]
From [[Python 2.Docs]: Built-in Functions - class object](https://docs.python.org/2/library/functions.html#object) (**emphasis** is mine): > > Return a new featureless object. **[object](https://docs.python.org/2/library/functions.html#object) is a base for all new style classes**. It has the methods that are common to all instances of new style classes. > > > You could also check [[Python]: New-style Classes](https://www.python.org/doc/newstyle) (and referenced *URL*s) for more details. > > > ```py > >>> import sys > >>> sys.version > '2.7.10 (default, Mar 8 2016, 15:02:46) [MSC v.1600 64 bit (AMD64)]' > >>> > >>> class OldStyle(): > ... pass > ... > >>> > >>> class NewStyle(object): > ... pass > ... > >>> > >>> dir(OldStyle) > ['__doc__', '__module__'] > >>> > >>> dir(NewStyle) > ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] > >>> > >>> old_style = OldStyle() > >>> new_style = NewStyle() > >>> > >>> type(old_style) > <type 'instance'> > >>> > >>> type(new_style) > <class '__main__.ClassNewStyle'> > > ``` > > In the above example, *old\_style* and *new\_style* are instances (or may be referred to as ***object***s), so I guess the answer to your question is: depends on the context.
All objects in python are ultimately derived from "object". You don't need to be explicit about it in python 3, but it's common to explicitly derive from object.
56,401,685
### Concepts of objects in python classes While reading about old style and new style classes in Python , term object occurs many times. What is exactly an object? Is it a base class or simply an object or a parameter ? for e.g. : New style for creating a class in python ``` class Class_name(object): pass ``` If object is just another class which is base class for Class\_name (inheritance) then what will be termed as object in python ?
2019/05/31
[ "https://Stackoverflow.com/questions/56401685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5084760/" ]
From [[Python 2.Docs]: Built-in Functions - class object](https://docs.python.org/2/library/functions.html#object) (**emphasis** is mine): > > Return a new featureless object. **[object](https://docs.python.org/2/library/functions.html#object) is a base for all new style classes**. It has the methods that are common to all instances of new style classes. > > > You could also check [[Python]: New-style Classes](https://www.python.org/doc/newstyle) (and referenced *URL*s) for more details. > > > ```py > >>> import sys > >>> sys.version > '2.7.10 (default, Mar 8 2016, 15:02:46) [MSC v.1600 64 bit (AMD64)]' > >>> > >>> class OldStyle(): > ... pass > ... > >>> > >>> class NewStyle(object): > ... pass > ... > >>> > >>> dir(OldStyle) > ['__doc__', '__module__'] > >>> > >>> dir(NewStyle) > ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] > >>> > >>> old_style = OldStyle() > >>> new_style = NewStyle() > >>> > >>> type(old_style) > <type 'instance'> > >>> > >>> type(new_style) > <class '__main__.ClassNewStyle'> > > ``` > > In the above example, *old\_style* and *new\_style* are instances (or may be referred to as ***object***s), so I guess the answer to your question is: depends on the context.
An Object is something in any Object Oriented language including Python, C#, Java and even JavaScript these days. Objects are also prevalent in 3d modeling software but are not per se the same thing. An Object is an INSTANTIATED class. A class is a blueprint for creating object. Almost everything in Python is an object. In reference to how you seem to be regarding to exclusivity of objects in python, yes, there is an object class. C# has them too and possibly others where you would use it not dissimilar to creating a string or int.
63,046,777
I have in my utils.py the following functions which I use for debugging info ... ``` say = print log = print ``` I want to declare them in such a way, so that I can switch them ON/OFF. If possible on per module basis. F.e. let say I want to test something and enable/disable printing ... I don't want to use logging, because it is too cumbersome and requires more typing.. I'm using this for quick debugging and eventually delete those prints --- in utils.py ``` say = print log = print def nope(*args, **kwargs): return None ``` in blah.py ``` from utils import * class ABC: def abc(self): say(111) ``` in ipython : ``` from blah import * a = ABC() a.abc() 111 say(222) 222 say = nope a.abc(111) 111 say(222) None ```
2020/07/23
[ "https://Stackoverflow.com/questions/63046777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1019129/" ]
You can always redefine say/log to do nothing later on. ``` Python 3.8.2 (default, Apr 27 2020, 15:53:34) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> say = print >>> say("hello") hello >>> def say(*args, **kwargs): ... return None ... >>> say("hello") >>> ```
You could used `sys.stdout.write("\033[K")` to overwrite/clear the previous line at the terminal when you don't want it logged or like: ``` def removeLine(dontWant): if dontWant == True: sys.stdout.write("\033[K") ``` where dontWant is set within the module or class or as a glob even or whatever based on when you want it and then removeLine is call after every log event.
63,046,777
I have in my utils.py the following functions which I use for debugging info ... ``` say = print log = print ``` I want to declare them in such a way, so that I can switch them ON/OFF. If possible on per module basis. F.e. let say I want to test something and enable/disable printing ... I don't want to use logging, because it is too cumbersome and requires more typing.. I'm using this for quick debugging and eventually delete those prints --- in utils.py ``` say = print log = print def nope(*args, **kwargs): return None ``` in blah.py ``` from utils import * class ABC: def abc(self): say(111) ``` in ipython : ``` from blah import * a = ABC() a.abc() 111 say(222) 222 say = nope a.abc(111) 111 say(222) None ```
2020/07/23
[ "https://Stackoverflow.com/questions/63046777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1019129/" ]
You can always redefine say/log to do nothing later on. ``` Python 3.8.2 (default, Apr 27 2020, 15:53:34) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> say = print >>> say("hello") hello >>> def say(*args, **kwargs): ... return None ... >>> say("hello") >>> ```
At the end this is what I wrote : <https://github.com/vsraptor/quick-debug/blob/master/debug.py> Quick debugging : if you are like me and are not used to a debugger or logging is too cumbersome, then this is for you.
55,437,583
I would like to convert HTML code to JavaScript. Currently I can send a message from the HTML file to a python server, which is then reversed and sent back to the HTML through socket io. I used this tutorial: <https://tutorialedge.net/python/python-socket-io-tutorial/> What I want to do now is rather than send the message by clicking a button on a web page I can instead run a JavaScript file from the command line, so > > node **index.js** > > > My **index.js** is below: ``` <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script> <script> const socket = io("http://localhost:8080"); function sendMsg() { socket.emit("message", "HELLO WORLD"); } socket.on("message", function(data) { console.log(data); }); </script> ``` When running **index.js** I receive this error: ``` /home/name/Desktop/Research/server_practice/name/tutorialedge/js_communicate/index_1.js:1 (function (exports, require, module, __filename, __dirname) { <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script> SyntaxError: Unexpected token < at createScript (vm.js:80:10) at Object.runInThisContext (vm.js:139:10) at Module._compile (module.js:616:28) at Object.Module._extensions..js (module.js:663:10) at Module.load (module.js:565:32) at tryModuleLoad (module.js:505:12) at Function.Module._load (module.js:497:3) at Function.Module.runMain (module.js:693:10) at startup (bootstrap_node.js:188:16) at bootstrap_node.js:609:3 ``` **In the error output, the caret is pointing at the second part of quotes:** ``` socket.io/2.2.0/socket.io.js"> ^ ``` I am pretty sure this is a syntax issue in combination with using socket io, but I am not sure what exactly is the problem. I believe I am using some sort of pseudo HTML/JavaScript code, which is why I am getting an error. I am new to JavaScript, but I need to use it because it contains APIs that I need. For clarity, this is the working HTML code from the tutorial, **index.html**: ``` <!-- index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head> <body> <button onClick="sendMsg()">Hit Me</button> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script> <script> const socket = io("http://localhost:8080"); function sendMsg() { socket.emit("message", "HELLO WORLD"); } socket.on("message", function(data) { console.log(data); }); </script> </body> </html> ``` And here is the python server code, **server.py** ``` from aiohttp import web import socketio # creates a new Async Socket IO Server sio = socketio.AsyncServer() # Creates a new Aiohttp Web Application app = web.Application() # Binds our Socket.IO server to our Web App # instance sio.attach(app) # we can define aiohttp endpoints just as we normally # would with no change async def index(request): with open('index.html') as f: return web.Response(text=f.read(), content_type='text/html') # If we wanted to create a new websocket endpoint, # use this decorator, passing in the name of the # event we wish to listen out for @sio.on('message') async def print_message(sid, message): print("Socket ID: " , sid) print(message) # await a successful emit of our reversed message # back to the client await sio.emit('message', message[::-1]) # We bind our aiohttp endpoint to our app # router app.router.add_get('/', index) # We kick off our server if __name__ == '__main__': web.run_app(app) ``` The end goal is to have multiple data streams from JavaScript being sent to Python to be analyzed and sent back to JavaScript to be outputted through an API.
2019/03/31
[ "https://Stackoverflow.com/questions/55437583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8973785/" ]
Script tags don't work in node. You need to use require to import modules. You can use the [socket.io client](https://www.npmjs.com/package/socket.io-client) module to connect to socket io using node. Note that you'll have to `npm install` it before use Example connection code adapted from socket.io client readme: ```js var socket = require('socket.io-client')('http://localhost:8080'); socket.on('connect', function(){}); function sendMsg() { socket.emit("message", "HELLO WORLD"); } socket.on("message", function(data) { console.log(data); }); socket.on('disconnect', function(){}); ```
`<script>` tags are HTML tags - you can't have them in a JavaScript file. Just place your JavaScript: ``` const socket = io("http://localhost:8080"); function sendMsg() { socket.emit("message", "HELLO WORLD"); } socket.on("message", function(data) { console.log(data); }); ```
27,925,447
I have the following dataframe. ``` c1 c2 v1 v2 0 a a 1 2 1 a a 2 3 2 b a 3 1 3 b a 4 5 5 c d 5 0 ``` I wish to have the following output. ``` c1 c2 v1 v2 0 a a 2 3 1 b a 4 5 2 c d 5 0 ``` The rule. First group dataframe by c1, c2. Then into each group, keep the row with the maximun value in column v2. Finally, output the original dataframe with all the rows not satisfying the previous rule dropped. What is the better way to obtain this result? Thanks. Going around, I have found also [this solution based on apply method](https://stackoverflow.com/questions/27488080/python-pandas-filter-rows-after-groupby)
2015/01/13
[ "https://Stackoverflow.com/questions/27925447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2063033/" ]
I wanted to add a comment, but my reputation doesn't allow me :). So I will risk posting an incomplete answer here.. As a common practice, when you have a form to submit, you should use @using (Html.BeginForm()). This will take care of all the technicalities of having a form and avoid unnecessary errors (which I can't identify in your code, sorry!!). Also, you can try putting a breakpoint at the Create action to see if it gets called properly.
The proper way to redirect is to return RedirectResult. In your case it seems to be: ``` [HttpGet] public ActionResult Create(Clients client) { if (ModelState.IsValid) { _db.Clients.Add(client); _db.SaveChanges(); } return new RedirectResult("Index"); } ``` Update: To allow redirection you should use HTTP GET instead of POST. Add FormMethod.Get to your form parameters and change the attribute: ``` @using (Html.BeginForm("Login", "Account", FormMethod.Get)) { // ... <input type="submit" value="Sign In"> } ```
15,587,311
``` def parabola(h, k, xCoordinates): ``` h is the x coordinate where the parabola touches the x axis and k is the y coordinate where the parabola intersects the y axis and xCoordinates is a list of x coordinates along the major axis. The function returns a list of y coordinates using the equation shown below. There will be one y coordinate for each x coordinate in the list of x coordinates. ``` y(x, h, k) = a(x βˆ’ h)2, where a =k/h2 ``` I know how to work in python as i already compute the area , ``` def computeArea(y_vals, h): i=1 total=y_vals[0]+y_vals[-1] for y in y_vals[1:-1]: if i%2 == 0: total+=2*y else: total+=4*y i+=1 return total*(h/3.0) y_values=[13, 45.3, 12, 1, 476, 0] interval=1.2 area=computeArea(y_values, interval) print "The area is", area ``` But the question above is hurting me because its pure mathmatics , i just want little bit help
2013/03/23
[ "https://Stackoverflow.com/questions/15587311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` pricing::pricing(void) { m(10,0.0,0.01,50); } ``` This attempts to *call* `m` as though it were a function (if it had overloaded `operator()`, you would be able to do this, which is what the error is talking about). To initialise `m` instead, use the member initialization list: ``` pricing::pricing(void) : m(10,0.0,0.01,50) { } ``` This colon syntax is used to initialise members of an object in the constructor. You simply list members by their names and initialize them with either `( expression-list )` or `{ initializer-list }` syntax.
pricing.cpp ``` #include "pricing.h" pricing::pricing() : m(10,0.0,0.01,50) { } double pricing::expectedValue() { return m.samplePaths[2][3]; } ``` pricing.h ``` #ifndef PRICING_H #define PRICING_H #include "monteCarlo.h" #include <vector> class pricing { public: pricing(); double euroCall(); std::vector<double> samplePathing; double expectedValue(); private: monteCarlo m; }; #endif ``` montecarlo.cpp looks like: ``` #include "monteCarlo.h" #include "randomWalk.h" #include <iostream> monteCarlo::monteCarlo(int trails, double drift, double volidatity, int density) { for (int i = 0; i < trails; i++) { std::cout << "Trail number " << i+1 << std::endl; randomWalk r(drift,volidatity,density); r.seed(); samplePaths.emplace_back(r.samplePath); std::cout << "\n" << std::endl; } } ``` and finally montecarlo.h is: ``` #ifndef MONTECARLO_H #define MONTECARLO_H #include <vector> class monteCarlo { public: monteCarlo(int, double, double, int); std::vector< std::vector<double> > samplePaths; }; #endif ``` I would use some very basic rules: 1. use include guards 2. Include only headers that are really needed in headers 3. Include the header as the first file in the implementation. 4. Do not use "using namespace" in a header 5. If possible, use forward declarations instead of includes 3) makes sure, that the header contains all necessary include files
15,820,247
Raymond Hettinger surprised quite a few people when he showed slides 36 and 37. <https://speakerdeck.com/pyconslides/transforming-code-into-beautiful-idiomatic-python-by-raymond-hettinger> -- Many people knew that the with statement could be used for opening files, but not these new things. Looking at python 3.3 docs on threading, only at the very bottom, section 16.2.8, is it even mentioned. From the lecture it was implied that using the 'with' operator was best practice. * How is one supposed to figure out if 'with' is supported, what it can be tied to, etc? * Also, how should 'with' be referred to? (threading with statement, python threading lock with statement,...), what is the vernacular to search and see if 'with' is supported (we can ask if something is iterable, do we ask if it's 'withable')? ref: * <http://docs.python.org/2/reference/compound_stmts.html#with> 7.5 * <http://docs.python.org/2/reference/datamodel.html#context-managers> 3.4.10 * <http://docs.python.org/3.1/library/threading.html> 16.2.8
2013/04/04
[ "https://Stackoverflow.com/questions/15820247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/411046/" ]
First, you don't ask if something is "withable", you ask if it's a "context manager".\* For example, in the docs you linked (which are from 3.1, not 3.3, by the way): > > Currently, `Lock`, `RLock`, `Condition`, `Semaphore`, and `BoundedSemaphore` objects may be used as `with` statement context managers. > > > Meanwhile, if you want to search in the interactive interpreter, there are two obvious things to do: ``` if hasattr(x, '__exit__'): print('x is a context manager') try: with x: pass except AttributeError: pass else: print('x is a context manager') ``` Meanwhile: > > `help(open)` … makes no mention of it > > > Well, yeah, because `open` isn't a context manager, it's a function that happens to return something that is a context manager. In 3.3, it can return a variety of different things depending on its parameters; in 2.7, it only returns one thing (a `file`), but `help` tells you exactly what it returns, and you can then use `help` on whichever one is appropriate for your use case, or just look at its attributes, to see that it defines `__exit__`. At any rate, realistically, just remember that EAFTP applies to debugging and prototyping as well as to your final code. Try writing something with a `with` statement first. If the expression you're trying to use as a context manager isn't one, you'll get an exception as soon as you try to run that code, which is pretty easy to debug. (It will generally be an `AttributeError` about the lack of `__exit__`, but even if it isn't, the fact that the traceback says it's from your `with` line ought to tell you the problem.) And if you have an object that seems like it *should* be usable as a context manager, and isn't, you might want to consider filing a bug/bringing it up on the mailing lists/etc. (There are some classes in the stdlib that weren't context managers until someone complained.) One last thing: If you're using a type that has a `close` method, but isn't a context manager, just use `contextlib.closing` around it: ``` with closing(legacy_file_like_object): ``` … or ``` with closing(legacy_file_like_object_producer()) as f: ``` In fact, you should really look at everything in [`contextlib`](http://docs.python.org/2/library/contextlib.html). `@contextmanager` is very nifty, and `nested` is handy if you need to backport 2.7/3.x code to 2.5, and, while `closing` is trivial to write (if you have `@contextmanager`), using the stdlib function makes your intentions clear. --- \* Actually, there was a bit of a debate about the naming, and it recurs every so often on the mailing lists. But the docs and `help('with')` both give a nearly-precise definition, the "context manager" is the result of evaluating the "context expression". So, in `with foo(bar) as baz, qux as quux:`, `foo(bar)` and `qux` are both context managers. (Or maybe in some way the two of them make up a single context manager.)
afaik any class/object that that implements `__exit__` method (you may also need to implement `__enter__`) ``` >>>dir(file) #notice it includes __enter__ and __exit__ ``` so ``` def supportsWith(some_ob): if "__exit__" in dir(some_ob): #could justas easily used hasattr return True ```
15,820,247
Raymond Hettinger surprised quite a few people when he showed slides 36 and 37. <https://speakerdeck.com/pyconslides/transforming-code-into-beautiful-idiomatic-python-by-raymond-hettinger> -- Many people knew that the with statement could be used for opening files, but not these new things. Looking at python 3.3 docs on threading, only at the very bottom, section 16.2.8, is it even mentioned. From the lecture it was implied that using the 'with' operator was best practice. * How is one supposed to figure out if 'with' is supported, what it can be tied to, etc? * Also, how should 'with' be referred to? (threading with statement, python threading lock with statement,...), what is the vernacular to search and see if 'with' is supported (we can ask if something is iterable, do we ask if it's 'withable')? ref: * <http://docs.python.org/2/reference/compound_stmts.html#with> 7.5 * <http://docs.python.org/2/reference/datamodel.html#context-managers> 3.4.10 * <http://docs.python.org/3.1/library/threading.html> 16.2.8
2013/04/04
[ "https://Stackoverflow.com/questions/15820247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/411046/" ]
First, you don't ask if something is "withable", you ask if it's a "context manager".\* For example, in the docs you linked (which are from 3.1, not 3.3, by the way): > > Currently, `Lock`, `RLock`, `Condition`, `Semaphore`, and `BoundedSemaphore` objects may be used as `with` statement context managers. > > > Meanwhile, if you want to search in the interactive interpreter, there are two obvious things to do: ``` if hasattr(x, '__exit__'): print('x is a context manager') try: with x: pass except AttributeError: pass else: print('x is a context manager') ``` Meanwhile: > > `help(open)` … makes no mention of it > > > Well, yeah, because `open` isn't a context manager, it's a function that happens to return something that is a context manager. In 3.3, it can return a variety of different things depending on its parameters; in 2.7, it only returns one thing (a `file`), but `help` tells you exactly what it returns, and you can then use `help` on whichever one is appropriate for your use case, or just look at its attributes, to see that it defines `__exit__`. At any rate, realistically, just remember that EAFTP applies to debugging and prototyping as well as to your final code. Try writing something with a `with` statement first. If the expression you're trying to use as a context manager isn't one, you'll get an exception as soon as you try to run that code, which is pretty easy to debug. (It will generally be an `AttributeError` about the lack of `__exit__`, but even if it isn't, the fact that the traceback says it's from your `with` line ought to tell you the problem.) And if you have an object that seems like it *should* be usable as a context manager, and isn't, you might want to consider filing a bug/bringing it up on the mailing lists/etc. (There are some classes in the stdlib that weren't context managers until someone complained.) One last thing: If you're using a type that has a `close` method, but isn't a context manager, just use `contextlib.closing` around it: ``` with closing(legacy_file_like_object): ``` … or ``` with closing(legacy_file_like_object_producer()) as f: ``` In fact, you should really look at everything in [`contextlib`](http://docs.python.org/2/library/contextlib.html). `@contextmanager` is very nifty, and `nested` is handy if you need to backport 2.7/3.x code to 2.5, and, while `closing` is trivial to write (if you have `@contextmanager`), using the stdlib function makes your intentions clear. --- \* Actually, there was a bit of a debate about the naming, and it recurs every so often on the mailing lists. But the docs and `help('with')` both give a nearly-precise definition, the "context manager" is the result of evaluating the "context expression". So, in `with foo(bar) as baz, qux as quux:`, `foo(bar)` and `qux` are both context managers. (Or maybe in some way the two of them make up a single context manager.)
Objects that work with Python's `with` statement are called *context managers*. In typically Pythonic fashion, whether an object is a context manager depends only on whether you can do "context manager-y" things with it. (This strategy is called [duck typing](http://en.wikipedia.org/wiki/Duck_typing).) So what constitutes "context manager-y" behavior? There are exactly two things: (1) doing some standard set-up on entering a `with` block, and (2) doing some standard "tear-down", and maybe also some damage control if things go awry, before exiting the block. That's it. The details are provided in [PEP 343](http://www.python.org/dev/peps/pep-0343/), which introduced the `with` statement, and in the documentation you linked in the question. A `with` block, step by step ---------------------------- But let's run through this step by step. To start, we need a "context manager". That's any object that provides set-up and tear-down behavior encapsulated in methods respectively called `__enter__` and `__exit__`. If an object provides these methods, it qualifies as a context manager, albeit possibly a poor one if the methods don't do sensible things. So what happens behind the scenes when the interpreter sees a `with` block? First, the interpreter looks for `__enter__` and `__exit__` methods on the object provided after the `with` statement. If the methods don't exist, then we don't have a context manager, so the interpreter throws an exception. But if the methods do exist, all is well. We have our context manager, so we move into the block. The interpreter then executes the context manager's `__enter__` method and assigns the result to the variable that follows the `as` statement (if there is one, otherwise the result is thrown away). Next, the body of the `with` block is executed. When that's done, the context manager's `__exit__` statement is passed a (possibly empty) dictionary of information about any exceptions that occurred while executing the bock's body, and the `__exit__` method is executed to clean things up. Here's a line-by-line walk-through: ``` with man as x: # 1) Look for `man.__enter__` and `man.__exit__`, then ... # 2) Execute `x = man.__enter__()`, then ... do_something(x) # 3) Execute the code in the body of the block, ... # 4) If something blows up, note it (in `err`), ... # 5) Last, this (always!) happens: `man.__exit__(**err)`. carry_on() ``` And that's that. What's the point? ----------------- The only subtlety here is that the context manager's `__exit__` method is *always* executed, even if an uncaught exception is thrown in the body of the `with` block. In that case, the exception information is passed to the `__exit__` method (in a dictionary I called `err` in the example above), which should use that information to provide damage control. So a `with` block is just an abstraction that lets us shunt off set-up, tear-down, and damage-control code (i.e., "context management") into a couple of methods, which can then be called behind the scenes. This both encourages us to factor out boilerplate and provides more concise, readable code that highlights the core control flow and hides implementation details.
46,439,557
I have a .txt file, each line is in the format like this 1 2,10 3,20 2 6,87 . . . This file actually represents a graph, line 1 says that Vertex 1 have directed edge to vertex 2 and the length is 10, vertex 1 also have directed edge to vertex 3 and the length is 20. Line 2 says that Vertex 2 only have one directed edge to vertex 6, and the length is 87. I want to do Dajkstra's shortest path algorithm. I don't want to define vertex class, edge class, etc., rather, I want to store each line into a 2-d array, so that by using index, I can get the graph info. If it were in python, I would store the whole file into a nested list [[(2,10) (3,20)], [(6,87)], ...], so that without making vertex, edge class, I can easily access all necessary graph info by indexing the list. My question is, how to do this in Java? 2-D array not good because each line might have different number of integers. ArrayList might be good, but how to read the whole txt file into such arraylist efficently?
2017/09/27
[ "https://Stackoverflow.com/questions/46439557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8680259/" ]
Providing you have a method that takes `[FromBody]TestStatus status` as a parameter. * Click on **Body** tab and select **raw**, then JSON(application/json). * Use this Json: ``` { "TestStatus": "expiredTest" } ``` * Send! I think above is your case as you stated: "take enum object as a body". Below are some more trivial ingredients: If you have a parameter like `[FromBody]MyClass class` and its definition as ``` public class MyClass { public Guid Id { get; set; } public TestStatus ClassStatus { get; set; } } ``` Then you modify your Json as: ``` { "Id": "28fa119e-fd61-461e-a727-08d504b9ee0b", "ClassStatus": "expiredTest" } ```
Just pass 0,1,2... interger in the json body to pass enum objects. Choose 0 if required to pass the first enum object. Exmple: { "employee": 0 }
46,439,557
I have a .txt file, each line is in the format like this 1 2,10 3,20 2 6,87 . . . This file actually represents a graph, line 1 says that Vertex 1 have directed edge to vertex 2 and the length is 10, vertex 1 also have directed edge to vertex 3 and the length is 20. Line 2 says that Vertex 2 only have one directed edge to vertex 6, and the length is 87. I want to do Dajkstra's shortest path algorithm. I don't want to define vertex class, edge class, etc., rather, I want to store each line into a 2-d array, so that by using index, I can get the graph info. If it were in python, I would store the whole file into a nested list [[(2,10) (3,20)], [(6,87)], ...], so that without making vertex, edge class, I can easily access all necessary graph info by indexing the list. My question is, how to do this in Java? 2-D array not good because each line might have different number of integers. ArrayList might be good, but how to read the whole txt file into such arraylist efficently?
2017/09/27
[ "https://Stackoverflow.com/questions/46439557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8680259/" ]
With a method taking the enum as the body, the enum value needs to be entered without curly brackets, simply ``` "expiredTest" ``` or ``` 2 ``` directly in the Body tab (with `raw` and `JSON(application/json)` and an `ASP.NET Core backend`).
Just pass 0,1,2... interger in the json body to pass enum objects. Choose 0 if required to pass the first enum object. Exmple: { "employee": 0 }
47,483,015
I have these settings ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 465 EMAIL_USE_TLS = True SMTP_SSL = True ``` Speaking to Godaddy I have found out these are the ports and settings ``` smtpout.secureserver.net ssl 465 587 TLS ON 3535 TLS ON 25 TLS ON 80 TLS ON or TLS OFF ``` I have tried all the combinations. If I set TLS to True I am getting ``` STARTTLS extension not supported by the server. ``` If I set to 465 I am getting [![Connetion Closed](https://i.stack.imgur.com/koqnf.png)](https://i.stack.imgur.com/koqnf.png) If I set other combinations like ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 25 EMAIL_USE_TLS = False ``` [![Invalid Address](https://i.stack.imgur.com/iwXh1.png)](https://i.stack.imgur.com/iwXh1.png) For verification, I used Google Mail settings to test if the email sending via python works, and it is working. Now I want to switch to GoDaddy and I know for the email we use TLS to log in even for POP3 download and it is working, so I am not sure why python / Django option is not working. Can you please help? I have called Godaddy, they cannot help because it is a software issue - all their settings and ports are working, so I have no one to ask.
2017/11/25
[ "https://Stackoverflow.com/questions/47483015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333598/" ]
This worked for me with my GoDaddy email. Since GoDaddy sets up your email in Office365, you can use smtp.office365.com. settings.py ``` EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_HOST_USER = 'myemail@GoDaddyDomain.com' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = 'myPassword' EMAIL_PORT = 587 EMAIL_USE_SSL = False EMAIL_USE_TLS = True ``` method in views.py that handles sending email. The email variable is from a user form. ``` from django.conf import settings from django.core.mail import EmailMessage def send_email(subject, body, email): try: email_msg = EmailMessage(subject, body, settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], reply_to=[email]) email_msg.send() return "Message sent :)" except: return "Message failed, try again later :(" ```
I found this code worked for me.. Hope this will be useful to somebody. I was using SMTP godaddy webmail..you can put this code into your django setting file. Since you cannot set Both SSL and TSL together... if you do so you get the error something as, **At one time either SSL or TSL can be true....** setting.py ``` # Emailing details EMAIL_HOST = 'md-97.webhostbox.net' EMAIL_HOST_USER = 'mailer@yourdomain' EMAIL_HOST_PASSWORD = 'your login password' EMAIL_PORT = 465 EMAIL_USE_SSL = True ```
47,483,015
I have these settings ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 465 EMAIL_USE_TLS = True SMTP_SSL = True ``` Speaking to Godaddy I have found out these are the ports and settings ``` smtpout.secureserver.net ssl 465 587 TLS ON 3535 TLS ON 25 TLS ON 80 TLS ON or TLS OFF ``` I have tried all the combinations. If I set TLS to True I am getting ``` STARTTLS extension not supported by the server. ``` If I set to 465 I am getting [![Connetion Closed](https://i.stack.imgur.com/koqnf.png)](https://i.stack.imgur.com/koqnf.png) If I set other combinations like ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 25 EMAIL_USE_TLS = False ``` [![Invalid Address](https://i.stack.imgur.com/iwXh1.png)](https://i.stack.imgur.com/iwXh1.png) For verification, I used Google Mail settings to test if the email sending via python works, and it is working. Now I want to switch to GoDaddy and I know for the email we use TLS to log in even for POP3 download and it is working, so I am not sure why python / Django option is not working. Can you please help? I have called Godaddy, they cannot help because it is a software issue - all their settings and ports are working, so I have no one to ask.
2017/11/25
[ "https://Stackoverflow.com/questions/47483015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333598/" ]
This worked for me with my GoDaddy email. Since GoDaddy sets up your email in Office365, you can use smtp.office365.com. settings.py ``` EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_HOST_USER = 'myemail@GoDaddyDomain.com' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = 'myPassword' EMAIL_PORT = 587 EMAIL_USE_SSL = False EMAIL_USE_TLS = True ``` method in views.py that handles sending email. The email variable is from a user form. ``` from django.conf import settings from django.core.mail import EmailMessage def send_email(subject, body, email): try: email_msg = EmailMessage(subject, body, settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], reply_to=[email]) email_msg.send() return "Message sent :)" except: return "Message failed, try again later :(" ```
I managed to decide to access the site <https://sso.secureserver.net/?app=emailsetup&realm=pass&> It seems that when accessing, you can enable email for external use. ``` EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER='aXXXX@xxxx' EMAIL_HOST_PASSWORD='AsgGSDAGSasdsagas' DEFAULT_FROM_EMAIL='aXXXX@xxxx' EMAIL_PORT=465 EMAIL_USE_SSL=True EMAIL_USE_TLS=False ``` It worked for me
47,483,015
I have these settings ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 465 EMAIL_USE_TLS = True SMTP_SSL = True ``` Speaking to Godaddy I have found out these are the ports and settings ``` smtpout.secureserver.net ssl 465 587 TLS ON 3535 TLS ON 25 TLS ON 80 TLS ON or TLS OFF ``` I have tried all the combinations. If I set TLS to True I am getting ``` STARTTLS extension not supported by the server. ``` If I set to 465 I am getting [![Connetion Closed](https://i.stack.imgur.com/koqnf.png)](https://i.stack.imgur.com/koqnf.png) If I set other combinations like ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 25 EMAIL_USE_TLS = False ``` [![Invalid Address](https://i.stack.imgur.com/iwXh1.png)](https://i.stack.imgur.com/iwXh1.png) For verification, I used Google Mail settings to test if the email sending via python works, and it is working. Now I want to switch to GoDaddy and I know for the email we use TLS to log in even for POP3 download and it is working, so I am not sure why python / Django option is not working. Can you please help? I have called Godaddy, they cannot help because it is a software issue - all their settings and ports are working, so I have no one to ask.
2017/11/25
[ "https://Stackoverflow.com/questions/47483015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333598/" ]
This worked for me with my GoDaddy email. Since GoDaddy sets up your email in Office365, you can use smtp.office365.com. settings.py ``` EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_HOST_USER = 'myemail@GoDaddyDomain.com' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = 'myPassword' EMAIL_PORT = 587 EMAIL_USE_SSL = False EMAIL_USE_TLS = True ``` method in views.py that handles sending email. The email variable is from a user form. ``` from django.conf import settings from django.core.mail import EmailMessage def send_email(subject, body, email): try: email_msg = EmailMessage(subject, body, settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], reply_to=[email]) email_msg.send() return "Message sent :)" except: return "Message failed, try again later :(" ```
It's been a while but, maybe the answer can help somebody else. I just talked to GoDaddy about the issue and the needed configration they told me was like, ``` EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = env('EMAIL_HOST_USER') DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') EMAIL_PORT = 80 EMAIL_USE_SSL = False EMAIL_USE_TLS = True ``` these are the django config settings but, I'm sure that it can be copied to other platforms. Also, the email dns configration they provided was, [![email dns config](https://i.stack.imgur.com/QXrem.png)](https://i.stack.imgur.com/QXrem.png)
47,483,015
I have these settings ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 465 EMAIL_USE_TLS = True SMTP_SSL = True ``` Speaking to Godaddy I have found out these are the ports and settings ``` smtpout.secureserver.net ssl 465 587 TLS ON 3535 TLS ON 25 TLS ON 80 TLS ON or TLS OFF ``` I have tried all the combinations. If I set TLS to True I am getting ``` STARTTLS extension not supported by the server. ``` If I set to 465 I am getting [![Connetion Closed](https://i.stack.imgur.com/koqnf.png)](https://i.stack.imgur.com/koqnf.png) If I set other combinations like ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 25 EMAIL_USE_TLS = False ``` [![Invalid Address](https://i.stack.imgur.com/iwXh1.png)](https://i.stack.imgur.com/iwXh1.png) For verification, I used Google Mail settings to test if the email sending via python works, and it is working. Now I want to switch to GoDaddy and I know for the email we use TLS to log in even for POP3 download and it is working, so I am not sure why python / Django option is not working. Can you please help? I have called Godaddy, they cannot help because it is a software issue - all their settings and ports are working, so I have no one to ask.
2017/11/25
[ "https://Stackoverflow.com/questions/47483015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333598/" ]
This worked for me with my GoDaddy email. Since GoDaddy sets up your email in Office365, you can use smtp.office365.com. settings.py ``` EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_HOST_USER = 'myemail@GoDaddyDomain.com' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = 'myPassword' EMAIL_PORT = 587 EMAIL_USE_SSL = False EMAIL_USE_TLS = True ``` method in views.py that handles sending email. The email variable is from a user form. ``` from django.conf import settings from django.core.mail import EmailMessage def send_email(subject, body, email): try: email_msg = EmailMessage(subject, body, settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], reply_to=[email]) email_msg.send() return "Message sent :)" except: return "Message failed, try again later :(" ```
use 'smtpout.asia.secureserver.net' as EMAIL\_HOST in Django settings.py. you can refer to the GoDaddy email help page link. <https://in.godaddy.com/help/mail-server-addresses-and-ports-for-business-email-24071>
47,483,015
I have these settings ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 465 EMAIL_USE_TLS = True SMTP_SSL = True ``` Speaking to Godaddy I have found out these are the ports and settings ``` smtpout.secureserver.net ssl 465 587 TLS ON 3535 TLS ON 25 TLS ON 80 TLS ON or TLS OFF ``` I have tried all the combinations. If I set TLS to True I am getting ``` STARTTLS extension not supported by the server. ``` If I set to 465 I am getting [![Connetion Closed](https://i.stack.imgur.com/koqnf.png)](https://i.stack.imgur.com/koqnf.png) If I set other combinations like ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 25 EMAIL_USE_TLS = False ``` [![Invalid Address](https://i.stack.imgur.com/iwXh1.png)](https://i.stack.imgur.com/iwXh1.png) For verification, I used Google Mail settings to test if the email sending via python works, and it is working. Now I want to switch to GoDaddy and I know for the email we use TLS to log in even for POP3 download and it is working, so I am not sure why python / Django option is not working. Can you please help? I have called Godaddy, they cannot help because it is a software issue - all their settings and ports are working, so I have no one to ask.
2017/11/25
[ "https://Stackoverflow.com/questions/47483015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333598/" ]
This worked for me with my GoDaddy email. Since GoDaddy sets up your email in Office365, you can use smtp.office365.com. settings.py ``` EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_HOST_USER = 'myemail@GoDaddyDomain.com' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = 'myPassword' EMAIL_PORT = 587 EMAIL_USE_SSL = False EMAIL_USE_TLS = True ``` method in views.py that handles sending email. The email variable is from a user form. ``` from django.conf import settings from django.core.mail import EmailMessage def send_email(subject, body, email): try: email_msg = EmailMessage(subject, body, settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], reply_to=[email]) email_msg.send() return "Message sent :)" except: return "Message failed, try again later :(" ```
In my case, this way work for me: #settings.py ``` EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST='smtpout.secureserver.net' EMAIL_PORT=465 EMAIL_USE_SSL=True EMAIL_USE_TLS=False EMAIL_HOST_USER='your@domain' EMAIL_HOST_PASSWORD='yourpass' ADMIN_EMAIL='your@domain' ```
47,483,015
I have these settings ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 465 EMAIL_USE_TLS = True SMTP_SSL = True ``` Speaking to Godaddy I have found out these are the ports and settings ``` smtpout.secureserver.net ssl 465 587 TLS ON 3535 TLS ON 25 TLS ON 80 TLS ON or TLS OFF ``` I have tried all the combinations. If I set TLS to True I am getting ``` STARTTLS extension not supported by the server. ``` If I set to 465 I am getting [![Connetion Closed](https://i.stack.imgur.com/koqnf.png)](https://i.stack.imgur.com/koqnf.png) If I set other combinations like ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 25 EMAIL_USE_TLS = False ``` [![Invalid Address](https://i.stack.imgur.com/iwXh1.png)](https://i.stack.imgur.com/iwXh1.png) For verification, I used Google Mail settings to test if the email sending via python works, and it is working. Now I want to switch to GoDaddy and I know for the email we use TLS to log in even for POP3 download and it is working, so I am not sure why python / Django option is not working. Can you please help? I have called Godaddy, they cannot help because it is a software issue - all their settings and ports are working, so I have no one to ask.
2017/11/25
[ "https://Stackoverflow.com/questions/47483015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333598/" ]
I found this code worked for me.. Hope this will be useful to somebody. I was using SMTP godaddy webmail..you can put this code into your django setting file. Since you cannot set Both SSL and TSL together... if you do so you get the error something as, **At one time either SSL or TSL can be true....** setting.py ``` # Emailing details EMAIL_HOST = 'md-97.webhostbox.net' EMAIL_HOST_USER = 'mailer@yourdomain' EMAIL_HOST_PASSWORD = 'your login password' EMAIL_PORT = 465 EMAIL_USE_SSL = True ```
In my case, this way work for me: #settings.py ``` EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST='smtpout.secureserver.net' EMAIL_PORT=465 EMAIL_USE_SSL=True EMAIL_USE_TLS=False EMAIL_HOST_USER='your@domain' EMAIL_HOST_PASSWORD='yourpass' ADMIN_EMAIL='your@domain' ```
47,483,015
I have these settings ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 465 EMAIL_USE_TLS = True SMTP_SSL = True ``` Speaking to Godaddy I have found out these are the ports and settings ``` smtpout.secureserver.net ssl 465 587 TLS ON 3535 TLS ON 25 TLS ON 80 TLS ON or TLS OFF ``` I have tried all the combinations. If I set TLS to True I am getting ``` STARTTLS extension not supported by the server. ``` If I set to 465 I am getting [![Connetion Closed](https://i.stack.imgur.com/koqnf.png)](https://i.stack.imgur.com/koqnf.png) If I set other combinations like ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 25 EMAIL_USE_TLS = False ``` [![Invalid Address](https://i.stack.imgur.com/iwXh1.png)](https://i.stack.imgur.com/iwXh1.png) For verification, I used Google Mail settings to test if the email sending via python works, and it is working. Now I want to switch to GoDaddy and I know for the email we use TLS to log in even for POP3 download and it is working, so I am not sure why python / Django option is not working. Can you please help? I have called Godaddy, they cannot help because it is a software issue - all their settings and ports are working, so I have no one to ask.
2017/11/25
[ "https://Stackoverflow.com/questions/47483015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333598/" ]
I managed to decide to access the site <https://sso.secureserver.net/?app=emailsetup&realm=pass&> It seems that when accessing, you can enable email for external use. ``` EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER='aXXXX@xxxx' EMAIL_HOST_PASSWORD='AsgGSDAGSasdsagas' DEFAULT_FROM_EMAIL='aXXXX@xxxx' EMAIL_PORT=465 EMAIL_USE_SSL=True EMAIL_USE_TLS=False ``` It worked for me
In my case, this way work for me: #settings.py ``` EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST='smtpout.secureserver.net' EMAIL_PORT=465 EMAIL_USE_SSL=True EMAIL_USE_TLS=False EMAIL_HOST_USER='your@domain' EMAIL_HOST_PASSWORD='yourpass' ADMIN_EMAIL='your@domain' ```
47,483,015
I have these settings ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 465 EMAIL_USE_TLS = True SMTP_SSL = True ``` Speaking to Godaddy I have found out these are the ports and settings ``` smtpout.secureserver.net ssl 465 587 TLS ON 3535 TLS ON 25 TLS ON 80 TLS ON or TLS OFF ``` I have tried all the combinations. If I set TLS to True I am getting ``` STARTTLS extension not supported by the server. ``` If I set to 465 I am getting [![Connetion Closed](https://i.stack.imgur.com/koqnf.png)](https://i.stack.imgur.com/koqnf.png) If I set other combinations like ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 25 EMAIL_USE_TLS = False ``` [![Invalid Address](https://i.stack.imgur.com/iwXh1.png)](https://i.stack.imgur.com/iwXh1.png) For verification, I used Google Mail settings to test if the email sending via python works, and it is working. Now I want to switch to GoDaddy and I know for the email we use TLS to log in even for POP3 download and it is working, so I am not sure why python / Django option is not working. Can you please help? I have called Godaddy, they cannot help because it is a software issue - all their settings and ports are working, so I have no one to ask.
2017/11/25
[ "https://Stackoverflow.com/questions/47483015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333598/" ]
It's been a while but, maybe the answer can help somebody else. I just talked to GoDaddy about the issue and the needed configration they told me was like, ``` EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = env('EMAIL_HOST_USER') DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') EMAIL_PORT = 80 EMAIL_USE_SSL = False EMAIL_USE_TLS = True ``` these are the django config settings but, I'm sure that it can be copied to other platforms. Also, the email dns configration they provided was, [![email dns config](https://i.stack.imgur.com/QXrem.png)](https://i.stack.imgur.com/QXrem.png)
In my case, this way work for me: #settings.py ``` EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST='smtpout.secureserver.net' EMAIL_PORT=465 EMAIL_USE_SSL=True EMAIL_USE_TLS=False EMAIL_HOST_USER='your@domain' EMAIL_HOST_PASSWORD='yourpass' ADMIN_EMAIL='your@domain' ```
47,483,015
I have these settings ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 465 EMAIL_USE_TLS = True SMTP_SSL = True ``` Speaking to Godaddy I have found out these are the ports and settings ``` smtpout.secureserver.net ssl 465 587 TLS ON 3535 TLS ON 25 TLS ON 80 TLS ON or TLS OFF ``` I have tried all the combinations. If I set TLS to True I am getting ``` STARTTLS extension not supported by the server. ``` If I set to 465 I am getting [![Connetion Closed](https://i.stack.imgur.com/koqnf.png)](https://i.stack.imgur.com/koqnf.png) If I set other combinations like ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 25 EMAIL_USE_TLS = False ``` [![Invalid Address](https://i.stack.imgur.com/iwXh1.png)](https://i.stack.imgur.com/iwXh1.png) For verification, I used Google Mail settings to test if the email sending via python works, and it is working. Now I want to switch to GoDaddy and I know for the email we use TLS to log in even for POP3 download and it is working, so I am not sure why python / Django option is not working. Can you please help? I have called Godaddy, they cannot help because it is a software issue - all their settings and ports are working, so I have no one to ask.
2017/11/25
[ "https://Stackoverflow.com/questions/47483015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333598/" ]
use 'smtpout.asia.secureserver.net' as EMAIL\_HOST in Django settings.py. you can refer to the GoDaddy email help page link. <https://in.godaddy.com/help/mail-server-addresses-and-ports-for-business-email-24071>
In my case, this way work for me: #settings.py ``` EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST='smtpout.secureserver.net' EMAIL_PORT=465 EMAIL_USE_SSL=True EMAIL_USE_TLS=False EMAIL_HOST_USER='your@domain' EMAIL_HOST_PASSWORD='yourpass' ADMIN_EMAIL='your@domain' ```
11,027,749
What's going on? I tried iPython and the regular Python interpreter, both show ^[[A and ^[[B for the up and down arrows instead of previous commands. **Platform:** Ubuntu 12.04. **Python:** 2.7.3 installed with pythonbrew **Terminal:** iTerm 2 on Mac OSX 10.6, connected over SSH. Has never worked in the Python shell over SSH, but works locally. Running locale outputs: ``` LANG=en_US.UTF-8 LANGUAGE=en_US:en LC_CTYPE="en_US.UTF-8" LC_NUMERIC="en_US.UTF-8" LC_TIME="en_US.UTF-8" LC_COLLATE="en_US.UTF-8" LC_MONETARY="en_US.UTF-8" LC_MESSAGES="en_US.UTF-8" LC_PAPER="en_US.UTF-8" LC_NAME="en_US.UTF-8" LC_ADDRESS="en_US.UTF-8" LC_TELEPHONE="en_US.UTF-8" LC_MEASUREMENT="en_US.UTF-8" LC_IDENTIFICATION="en_US.UTF-8" LC_ALL= ```
2012/06/14
[ "https://Stackoverflow.com/questions/11027749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1377021/" ]
Since you installed Python with pythonbrew, you must install the `libreadline-dev` package in your package manager *then* recompile Python. The package is named `libreadline-dev` or something similar in most Linux distributions (Ubuntu, Debian, Fedora...). This step is not required on Gentoo or Arch systems, which always include dev support for libraries. This step is also not necessary for Python that you install from the package manager. **Footnote:** The locale is irrelevant. The terminal emulator is irrelevant. SSH is irrelevant. I have never seen these factors affect line editing capabilities, although I suppose anything's possible. **Footnote 2:** I'm going to submit a patch to the docs for pythonbrew, this is not the first time someone has complained about readline missing. **Update:** [Pull request](https://github.com/utahta/pythonbrew/pull/87) **Update 2:** Merged.
`libreadline-dev` was not enough, what solved it for me is to install the `readline` package: ``` pip install readline ```
3,663,762
In my models.py, I want to have an optional field to a foreign key. I tried this: ``` field = models.ForeignKey(MyModel, null=True, blank=True, default=None) ``` I am getting this error: ``` model.mymodel_id may not be NULL ``` I am using sqlite. In case it is helpful, here is the exception location: ``` /usr/lib/python2.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 200 ```
2010/09/08
[ "https://Stackoverflow.com/questions/3663762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/440221/" ]
If it was previously not null and you synced it before then resyncing won't change it. Either drop the table, use a migration tool such as South, or alter the column in SQL directly.
I believe that it has to be both `null=True` and `blank=True`.
3,663,762
In my models.py, I want to have an optional field to a foreign key. I tried this: ``` field = models.ForeignKey(MyModel, null=True, blank=True, default=None) ``` I am getting this error: ``` model.mymodel_id may not be NULL ``` I am using sqlite. In case it is helpful, here is the exception location: ``` /usr/lib/python2.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 200 ```
2010/09/08
[ "https://Stackoverflow.com/questions/3663762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/440221/" ]
If it was previously not null and you synced it before then resyncing won't change it. Either drop the table, use a migration tool such as South, or alter the column in SQL directly.
I'm not sure on this one, but I think you need to lose the "default=None" and do a reset/syncdb. The default overrides the null/blank info. I.e. if you give a blank in the admin it will store None (whose representation may vary from DB to DB). I would need to look at the code/docs to be more certain.
3,663,762
In my models.py, I want to have an optional field to a foreign key. I tried this: ``` field = models.ForeignKey(MyModel, null=True, blank=True, default=None) ``` I am getting this error: ``` model.mymodel_id may not be NULL ``` I am using sqlite. In case it is helpful, here is the exception location: ``` /usr/lib/python2.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 200 ```
2010/09/08
[ "https://Stackoverflow.com/questions/3663762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/440221/" ]
If it was previously not null and you synced it before then resyncing won't change it. Either drop the table, use a migration tool such as South, or alter the column in SQL directly.
I have the same problem, and drilled down to the table creation process itself (because the problems arise in doing tests too.) For a model like this: ``` class MyModel(models.Model): owner = models.ForeignKey(User, null=True, blank=True) ``` the generated sql (with `./manage.py sql`) is: ``` CREATE TABLE `app_mymodel` ( `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `owner_id` integer ) ALTER TABLE `app_mymodel` ADD CONSTRAINT `owner_id_refs_id_34553282` FOREIGN KEY (`owner_id`) REFERENCES `auth_user` (`id`); ``` So it seems that the table itself allows Null values, but the FK constraint at the DB level is in fact constraining the values to be actual refences, so no NULL values... Is it a bug in Django? **EDIT:** It turns out that a table created with the former command **will** accept NULL values in the FK column, and in fact has `DEFAULT NULL` on the column spec when written out with `SHOW CREATE TABLE app_mymodel;`. It's strange, but I can't replicate the errors now.
3,663,762
In my models.py, I want to have an optional field to a foreign key. I tried this: ``` field = models.ForeignKey(MyModel, null=True, blank=True, default=None) ``` I am getting this error: ``` model.mymodel_id may not be NULL ``` I am using sqlite. In case it is helpful, here is the exception location: ``` /usr/lib/python2.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 200 ```
2010/09/08
[ "https://Stackoverflow.com/questions/3663762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/440221/" ]
I believe that it has to be both `null=True` and `blank=True`.
I'm not sure on this one, but I think you need to lose the "default=None" and do a reset/syncdb. The default overrides the null/blank info. I.e. if you give a blank in the admin it will store None (whose representation may vary from DB to DB). I would need to look at the code/docs to be more certain.
3,663,762
In my models.py, I want to have an optional field to a foreign key. I tried this: ``` field = models.ForeignKey(MyModel, null=True, blank=True, default=None) ``` I am getting this error: ``` model.mymodel_id may not be NULL ``` I am using sqlite. In case it is helpful, here is the exception location: ``` /usr/lib/python2.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 200 ```
2010/09/08
[ "https://Stackoverflow.com/questions/3663762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/440221/" ]
I believe that it has to be both `null=True` and `blank=True`.
I have the same problem, and drilled down to the table creation process itself (because the problems arise in doing tests too.) For a model like this: ``` class MyModel(models.Model): owner = models.ForeignKey(User, null=True, blank=True) ``` the generated sql (with `./manage.py sql`) is: ``` CREATE TABLE `app_mymodel` ( `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `owner_id` integer ) ALTER TABLE `app_mymodel` ADD CONSTRAINT `owner_id_refs_id_34553282` FOREIGN KEY (`owner_id`) REFERENCES `auth_user` (`id`); ``` So it seems that the table itself allows Null values, but the FK constraint at the DB level is in fact constraining the values to be actual refences, so no NULL values... Is it a bug in Django? **EDIT:** It turns out that a table created with the former command **will** accept NULL values in the FK column, and in fact has `DEFAULT NULL` on the column spec when written out with `SHOW CREATE TABLE app_mymodel;`. It's strange, but I can't replicate the errors now.
36,648,800
I have a BaseEntity class, which defines a bunch (a lot) of non-required properties and has most of functionality. I extend this class in two others, which have some extra methods, as well as initialize one required property. ``` class BaseEntity(object): def __init__(self, request_url): self.clearAllFilters() super(BaseEntity, self).__init__(request_url=request_url) @property def filter1(self): return self.filter1 @filter1.setter def filter1(self, some_value): self.filter1 = some_value ... def clearAllFilters(self): self.filter1 = None self.filter2 = None ... def someCommonAction1(self): ... class DefinedEntity1(BaseEntity): def __init__(self): super(BaseEntity, self).__init__(request_url="someUrl1") def foo(): ... class DefinedEntity2(BaseEntity): def __init__(self): super(ConsensusSequenceApi, self).__init__(request_url="someUrl2") def bar(self): ... ``` What I would like is to initialize a BaseEntity object once, with all the filters specified, and then use it to create each of the DefinedEntities, i.e. ``` baseObject = BaseEntity(None) baseObject.filter1 = "boo" baseObject.filter2 = "moo" entity1 = baseObject.create(DefinedEntity1) ``` Looking for pythonic ideas, since I've just switched from statically typed language and still trying to grasp the power of python.
2016/04/15
[ "https://Stackoverflow.com/questions/36648800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2521764/" ]
One way to do it: ``` import copy class A(object): def __init__(self, sth, blah): self.sth = sth self.blah = blah def do_sth(self): print(self.sth, self.blah) class B(A): def __init__(self, param): self.param = param def do_sth(self): print(self.param, self.sth, self.blah) a = A("one", "two") almost_b = copy.deepcopy(a) almost_b.__class__ = B B.__init__(almost_b, "three") almost_b.do_sth() # it would print "three one two" ``` Keep in mind that Python is an extremely open language with lot of dynamic modification possibilities and it is better not to abuse them. From clean code point of view I would use just a plain old call to superconstructor.
I had the same problem as the OP and was able to use the idea from RadosΕ‚aw Łazarz above of explicitly setting the **class** attribute of the object to the subclass, but without the deep copy: ``` class A: def __init__(a) : pass def amethod(a) : return 'aresult' class B(A): def __init__(b) : pass def bmethod(self) : return 'bresult' a=A() print(f"{a} of class {a.__class__} is {'' if isinstance(a,B) else ' not'} an instance of B") a.__class__=B # here is where the magic happens! print(f"{a} of class {a.__class__} is {'' if isinstance(a,B) else ' not'} an instance of B") print(f"a.amethod()={a.amethod()} a.bmethod()={a.bmethod()}") ``` Output: ``` <__main__.A object at 0x00000169F74DBE88> of class <class '__main__.A'> is not an instance of B <__main__.B object at 0x00000169F74DBE88> of class <class '__main__.B'> is an instance of B a.amethod()=aresult a.bmethod()=bresult ```
61,738,541
The first line works, but the second doesn't: ``` print(np.fromfunction(lambda x, y: 10 * x + y , (3, 5), dtype=int)) print(np.fromfunction(lambda x, y: str(10 * x + y), (3, 5), dtype=str)) [[ 0 1 2 3 4] [10 11 12 13 14] [20 21 22 23 24]] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/cygdrive/c/Users/pafh2/OneDrive/dev/reverb/t.py", line 439, in <module> print(np.fromfunction(lambda x, y: str(10 * x + y), (3, 5), dtype=str)) File "/usr/lib/python3.7/site-packages/numpy/core/numeric.py", line 2027, in fromfunction args = indices(shape, dtype=dtype) File "/usr/lib/python3.7/site-packages/numpy/core/numeric.py", line 1968, in indices res[i] = arange(dim, dtype=dtype).reshape( ValueError: no fill-function for data-type. >>> ``` Which page of the Numpy documentation explains the difference? StackOverflow won't let me post, telling me, "It looks like your post is mostly code; please add some more details." So now everyone has to read this pointless paragraph I've just added. Now it says I've still not written enough "details", though I really have, so here's more added spam to appease the the StackOverflow spam-filter "A.I.".
2020/05/11
[ "https://Stackoverflow.com/questions/61738541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
They are both text files with code in them. The difference isn't in the files, but in how your webserver treats them. It is configured to run files with a `.php` extension though a PHP engine, and to serve up `.html` files directly.
You have to open the php file through an apache (or other php-handling) server. For instance, if you use XAMPP, and have index.php in the XAMPP directory, you would open a browser and go to localhost/index.php. The server then converts it into html, which a browser can handle.
24,821,340
First of all an introduction to my development environment: ``` OS: Windows. SDK: Microsoft Visual Studio 2008. ``` Earlier today I was facing the problem of trying to define a Timer inside a class. My class is interfacing a Python embedded module and a C++ backend, My problem is that I need to receive some time event on the python module. Also it is important to notice that there will be only one instance of this class. The main problem is that when I define a timer using: ``` /* Null, 0, mseconds, CALLBACK_METHOD */ SetTimer(NULL, 0, 100, (TIMERPROC) OnTimer); ``` The method activated on the timer event (OnTimer) needs to be a static method on my Class (and then I cannot access any non-static methods or variables inside that class). Reading some code on codeproject I have found: <http://www.codeproject.com/Articles/4817/How-to-use-SetTimer-with-callback-to-a-non-static> I have a similar implementation but without the lines: ``` void * CSleeperThread::pObject; ``` and ``` CSleeperThread *pSomeClass = (CSleeperThread*)pObject; // cast the void pointer pSomeClass->TimerProc(hwnd, uMsg, idEvent, dwTime); // call non-static function ``` Is this the only way to implement the functionality I'm looking for? Is there an easier way I may have skipped on my information gathering process?
2014/07/18
[ "https://Stackoverflow.com/questions/24821340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3227543/" ]
Create a static map of your Class object: ``` static std::map<UINT_PTR, CMyClass*> m_CMyClassMap; //declaration ``` At the time of object creation insert the object in this map: ``` CMyClass myClassObj; CMyClassMap.insert(std::pair<int, CMyClass*>(0, &myClassObj)); ``` Now you can use it in static methods to access its non static members. ``` int a = m_CMyClassMap[0]->m_someNonStaticMember; ```
So long as there is only one instance of this class, there is an easy (if somewhat ugly) solution: Declare your class object and then store a pointer to it in a global object. E.g., ``` MyClass myObject; MyClass* self = &myObject; ``` Then inside your static member, you can use self->myMethod() or self->myData to refer to non static items.
14,140,902
I've run into a nasty little problem connecting to an Oracle schema via SQLAlchemy using a service name. Here is my code as a script. (items between angle brackets are place holders for real values for security reasons) ``` from sqlalchemy import create_engine if __name__ == "__main__": engine = create_engine("oracle+cx_oracle://<username>:<password>@<host>/devdb") result = engine.execute("create table test_table (id NUMBER(6), name VARCHAR2(15) not NULL)") result = engine.execute("drop table test_table") ``` Where 'devdb' is a service name and not an SID. The result of running this script is the stack trace. ``` (oracle-test)[1]jgoodell@jgoodell-MBP:python$ python example.py Traceback (most recent call last): File "example.py", line 8, in <module> result = engine.execute("create table test_table (id NUMBER(6), name VARCHAR2(15) not NULL)") File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/base.py", line 1621, in execute connection = self.contextual_connect(close_with_result=True) File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/base.py", line 1669, in contextual_connect self.pool.connect(), File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 272, in connect return _ConnectionFairy(self).checkout() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 425, in __init__ rec = self._connection_record = pool._do_get() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 777, in _do_get con = self._create_connection() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 225, in _create_connection return _ConnectionRecord(self) File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 318, in __init__ self.connection = self.__connect() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 368, in __connect connection = self.__pool._creator() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/strategies.py", line 80, in connect return dialect.connect(*cargs, **cparams) File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/default.py", line 279, in connect return self.dbapi.connect(*cargs, **cparams) sqlalchemy.exc.DatabaseError: (DatabaseError) ORA-12505: TNS:listener does not currently know of SID given in connect descriptor None None ``` If 'devdb' were an SID and not a service name this example would work just fine, I've been trying different permutations of the connection string but haven't found anything that works. There also does not appear to be anything in the SQLAlchemy documentation that explicitly explains how to handle SID's verses service names for Oracle connections.
2013/01/03
[ "https://Stackoverflow.com/questions/14140902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165435/" ]
I've found the answer you have to use the same connection string that would be used in a tnsnames.ora file in the connection string after the '@" like so ``` from sqlalchemy import create_engine if __name__ == "__main__": engine = create_engine("oracle+cx_oracle://<username>:<password>@(DESCRIPTION = (LOAD_BALANCE=on) (FAILOVER=ON) (ADDRESS = (PROTOCOL = TCP)(HOST = <host>)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = devdb)))") result = engine.execute("create table test_table (id NUMBER(6), name VARCHAR2(15) not NULL)") result = engine.execute("drop table test_table") ``` This example runs just fine, and you can comment out the drop statement and check the DB to see that the table was created.
cx\_Oracle supports the passing of a service\_name to the makedsn function. <http://cx-oracle.sourceforge.net/html/module.html?highlight=makedsn#cx_Oracle.makedsn> It would be nice if the create\_engine() API passed the service\_name through to the underlying call it makes to makedsn...something like this: ``` oracle = create_engine('oracle://user:pw@host:port', service_name='myservice') TypeError: Invalid argument(s) 'service_name' sent to create_engine(), using configuration OracleDialect_cx_oracle/QueuePool/Engine. Please check that the keyword arguments are appropriate for this combination of components. ```
14,140,902
I've run into a nasty little problem connecting to an Oracle schema via SQLAlchemy using a service name. Here is my code as a script. (items between angle brackets are place holders for real values for security reasons) ``` from sqlalchemy import create_engine if __name__ == "__main__": engine = create_engine("oracle+cx_oracle://<username>:<password>@<host>/devdb") result = engine.execute("create table test_table (id NUMBER(6), name VARCHAR2(15) not NULL)") result = engine.execute("drop table test_table") ``` Where 'devdb' is a service name and not an SID. The result of running this script is the stack trace. ``` (oracle-test)[1]jgoodell@jgoodell-MBP:python$ python example.py Traceback (most recent call last): File "example.py", line 8, in <module> result = engine.execute("create table test_table (id NUMBER(6), name VARCHAR2(15) not NULL)") File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/base.py", line 1621, in execute connection = self.contextual_connect(close_with_result=True) File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/base.py", line 1669, in contextual_connect self.pool.connect(), File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 272, in connect return _ConnectionFairy(self).checkout() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 425, in __init__ rec = self._connection_record = pool._do_get() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 777, in _do_get con = self._create_connection() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 225, in _create_connection return _ConnectionRecord(self) File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 318, in __init__ self.connection = self.__connect() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 368, in __connect connection = self.__pool._creator() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/strategies.py", line 80, in connect return dialect.connect(*cargs, **cparams) File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/default.py", line 279, in connect return self.dbapi.connect(*cargs, **cparams) sqlalchemy.exc.DatabaseError: (DatabaseError) ORA-12505: TNS:listener does not currently know of SID given in connect descriptor None None ``` If 'devdb' were an SID and not a service name this example would work just fine, I've been trying different permutations of the connection string but haven't found anything that works. There also does not appear to be anything in the SQLAlchemy documentation that explicitly explains how to handle SID's verses service names for Oracle connections.
2013/01/03
[ "https://Stackoverflow.com/questions/14140902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165435/" ]
I've found the answer you have to use the same connection string that would be used in a tnsnames.ora file in the connection string after the '@" like so ``` from sqlalchemy import create_engine if __name__ == "__main__": engine = create_engine("oracle+cx_oracle://<username>:<password>@(DESCRIPTION = (LOAD_BALANCE=on) (FAILOVER=ON) (ADDRESS = (PROTOCOL = TCP)(HOST = <host>)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = devdb)))") result = engine.execute("create table test_table (id NUMBER(6), name VARCHAR2(15) not NULL)") result = engine.execute("drop table test_table") ``` This example runs just fine, and you can comment out the drop statement and check the DB to see that the table was created.
``` import cx_Oracle dsnStr = cx_Oracle.makedsn('myhost','port','MYSERVICENAME') connect_str = 'oracle://user:password@' + dsnStr.replace('SID', 'SERVICE_NAME') ``` The makedns will create a TNS like this: > > (DESCRIPTION=(ADDRESS\_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=myhost)(PORT=1530)))(CONNECT\_DATA=(SID=MYSERVICENAME))) > > > replacing "SID" with "SERVICE\_TYPE" got it to work for me. --- If you are using flask, sqlalchemy, and oracle: ``` from flask import Flask from flask_sqlalchemy import SQLAlchemy import cx_Oracle app = Flask(__name__) dnsStr = cx_Oracle.makedsn('my.host.com', '1530', 'my.service.name') dnsStr = dnsString.replace('SID', 'SERVICE_NAME') app.config['SQLALCHEMY_DATABASE_URI'] = 'oracle://myschema:mypassword@' + dnsStr db = SQLAlchemy(app) ```
14,140,902
I've run into a nasty little problem connecting to an Oracle schema via SQLAlchemy using a service name. Here is my code as a script. (items between angle brackets are place holders for real values for security reasons) ``` from sqlalchemy import create_engine if __name__ == "__main__": engine = create_engine("oracle+cx_oracle://<username>:<password>@<host>/devdb") result = engine.execute("create table test_table (id NUMBER(6), name VARCHAR2(15) not NULL)") result = engine.execute("drop table test_table") ``` Where 'devdb' is a service name and not an SID. The result of running this script is the stack trace. ``` (oracle-test)[1]jgoodell@jgoodell-MBP:python$ python example.py Traceback (most recent call last): File "example.py", line 8, in <module> result = engine.execute("create table test_table (id NUMBER(6), name VARCHAR2(15) not NULL)") File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/base.py", line 1621, in execute connection = self.contextual_connect(close_with_result=True) File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/base.py", line 1669, in contextual_connect self.pool.connect(), File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 272, in connect return _ConnectionFairy(self).checkout() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 425, in __init__ rec = self._connection_record = pool._do_get() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 777, in _do_get con = self._create_connection() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 225, in _create_connection return _ConnectionRecord(self) File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 318, in __init__ self.connection = self.__connect() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 368, in __connect connection = self.__pool._creator() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/strategies.py", line 80, in connect return dialect.connect(*cargs, **cparams) File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/default.py", line 279, in connect return self.dbapi.connect(*cargs, **cparams) sqlalchemy.exc.DatabaseError: (DatabaseError) ORA-12505: TNS:listener does not currently know of SID given in connect descriptor None None ``` If 'devdb' were an SID and not a service name this example would work just fine, I've been trying different permutations of the connection string but haven't found anything that works. There also does not appear to be anything in the SQLAlchemy documentation that explicitly explains how to handle SID's verses service names for Oracle connections.
2013/01/03
[ "https://Stackoverflow.com/questions/14140902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165435/" ]
I've found the answer you have to use the same connection string that would be used in a tnsnames.ora file in the connection string after the '@" like so ``` from sqlalchemy import create_engine if __name__ == "__main__": engine = create_engine("oracle+cx_oracle://<username>:<password>@(DESCRIPTION = (LOAD_BALANCE=on) (FAILOVER=ON) (ADDRESS = (PROTOCOL = TCP)(HOST = <host>)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = devdb)))") result = engine.execute("create table test_table (id NUMBER(6), name VARCHAR2(15) not NULL)") result = engine.execute("drop table test_table") ``` This example runs just fine, and you can comment out the drop statement and check the DB to see that the table was created.
The module sqlalchemy now can handle oracle service\_names. Have a look: ``` from sqlalchemy.engine import create_engine DIALECT = 'oracle' SQL_DRIVER = 'cx_oracle' USERNAME = 'your_username' #enter your username PASSWORD = 'your_password' #enter your password HOST = 'subdomain.domain.tld' #enter the oracle db host url PORT = 1521 # enter the oracle port number SERVICE = 'your_oracle_service_name' # enter the oracle db service name ENGINE_PATH_WIN_AUTH = DIALECT + '+' + SQL_DRIVER + '://' + USERNAME + ':' + PASSWORD +'@' + HOST + ':' + str(PORT) + '/?service_name=' + SERVICE engine = create_engine(ENGINE_PATH_WIN_AUTH) #test query import pandas as pd test_df = pd.read_sql_query('SELECT * FROM global_name', engine) ```
14,140,902
I've run into a nasty little problem connecting to an Oracle schema via SQLAlchemy using a service name. Here is my code as a script. (items between angle brackets are place holders for real values for security reasons) ``` from sqlalchemy import create_engine if __name__ == "__main__": engine = create_engine("oracle+cx_oracle://<username>:<password>@<host>/devdb") result = engine.execute("create table test_table (id NUMBER(6), name VARCHAR2(15) not NULL)") result = engine.execute("drop table test_table") ``` Where 'devdb' is a service name and not an SID. The result of running this script is the stack trace. ``` (oracle-test)[1]jgoodell@jgoodell-MBP:python$ python example.py Traceback (most recent call last): File "example.py", line 8, in <module> result = engine.execute("create table test_table (id NUMBER(6), name VARCHAR2(15) not NULL)") File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/base.py", line 1621, in execute connection = self.contextual_connect(close_with_result=True) File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/base.py", line 1669, in contextual_connect self.pool.connect(), File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 272, in connect return _ConnectionFairy(self).checkout() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 425, in __init__ rec = self._connection_record = pool._do_get() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 777, in _do_get con = self._create_connection() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 225, in _create_connection return _ConnectionRecord(self) File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 318, in __init__ self.connection = self.__connect() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 368, in __connect connection = self.__pool._creator() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/strategies.py", line 80, in connect return dialect.connect(*cargs, **cparams) File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/default.py", line 279, in connect return self.dbapi.connect(*cargs, **cparams) sqlalchemy.exc.DatabaseError: (DatabaseError) ORA-12505: TNS:listener does not currently know of SID given in connect descriptor None None ``` If 'devdb' were an SID and not a service name this example would work just fine, I've been trying different permutations of the connection string but haven't found anything that works. There also does not appear to be anything in the SQLAlchemy documentation that explicitly explains how to handle SID's verses service names for Oracle connections.
2013/01/03
[ "https://Stackoverflow.com/questions/14140902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165435/" ]
``` import cx_Oracle dsnStr = cx_Oracle.makedsn('myhost','port','MYSERVICENAME') connect_str = 'oracle://user:password@' + dsnStr.replace('SID', 'SERVICE_NAME') ``` The makedns will create a TNS like this: > > (DESCRIPTION=(ADDRESS\_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=myhost)(PORT=1530)))(CONNECT\_DATA=(SID=MYSERVICENAME))) > > > replacing "SID" with "SERVICE\_TYPE" got it to work for me. --- If you are using flask, sqlalchemy, and oracle: ``` from flask import Flask from flask_sqlalchemy import SQLAlchemy import cx_Oracle app = Flask(__name__) dnsStr = cx_Oracle.makedsn('my.host.com', '1530', 'my.service.name') dnsStr = dnsString.replace('SID', 'SERVICE_NAME') app.config['SQLALCHEMY_DATABASE_URI'] = 'oracle://myschema:mypassword@' + dnsStr db = SQLAlchemy(app) ```
cx\_Oracle supports the passing of a service\_name to the makedsn function. <http://cx-oracle.sourceforge.net/html/module.html?highlight=makedsn#cx_Oracle.makedsn> It would be nice if the create\_engine() API passed the service\_name through to the underlying call it makes to makedsn...something like this: ``` oracle = create_engine('oracle://user:pw@host:port', service_name='myservice') TypeError: Invalid argument(s) 'service_name' sent to create_engine(), using configuration OracleDialect_cx_oracle/QueuePool/Engine. Please check that the keyword arguments are appropriate for this combination of components. ```
14,140,902
I've run into a nasty little problem connecting to an Oracle schema via SQLAlchemy using a service name. Here is my code as a script. (items between angle brackets are place holders for real values for security reasons) ``` from sqlalchemy import create_engine if __name__ == "__main__": engine = create_engine("oracle+cx_oracle://<username>:<password>@<host>/devdb") result = engine.execute("create table test_table (id NUMBER(6), name VARCHAR2(15) not NULL)") result = engine.execute("drop table test_table") ``` Where 'devdb' is a service name and not an SID. The result of running this script is the stack trace. ``` (oracle-test)[1]jgoodell@jgoodell-MBP:python$ python example.py Traceback (most recent call last): File "example.py", line 8, in <module> result = engine.execute("create table test_table (id NUMBER(6), name VARCHAR2(15) not NULL)") File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/base.py", line 1621, in execute connection = self.contextual_connect(close_with_result=True) File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/base.py", line 1669, in contextual_connect self.pool.connect(), File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 272, in connect return _ConnectionFairy(self).checkout() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 425, in __init__ rec = self._connection_record = pool._do_get() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 777, in _do_get con = self._create_connection() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 225, in _create_connection return _ConnectionRecord(self) File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 318, in __init__ self.connection = self.__connect() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/pool.py", line 368, in __connect connection = self.__pool._creator() File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/strategies.py", line 80, in connect return dialect.connect(*cargs, **cparams) File "/Users/jgoodell/.virtualenvs/oracle-test/lib/python2.6/site-packages/sqlalchemy/engine/default.py", line 279, in connect return self.dbapi.connect(*cargs, **cparams) sqlalchemy.exc.DatabaseError: (DatabaseError) ORA-12505: TNS:listener does not currently know of SID given in connect descriptor None None ``` If 'devdb' were an SID and not a service name this example would work just fine, I've been trying different permutations of the connection string but haven't found anything that works. There also does not appear to be anything in the SQLAlchemy documentation that explicitly explains how to handle SID's verses service names for Oracle connections.
2013/01/03
[ "https://Stackoverflow.com/questions/14140902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165435/" ]
The module sqlalchemy now can handle oracle service\_names. Have a look: ``` from sqlalchemy.engine import create_engine DIALECT = 'oracle' SQL_DRIVER = 'cx_oracle' USERNAME = 'your_username' #enter your username PASSWORD = 'your_password' #enter your password HOST = 'subdomain.domain.tld' #enter the oracle db host url PORT = 1521 # enter the oracle port number SERVICE = 'your_oracle_service_name' # enter the oracle db service name ENGINE_PATH_WIN_AUTH = DIALECT + '+' + SQL_DRIVER + '://' + USERNAME + ':' + PASSWORD +'@' + HOST + ':' + str(PORT) + '/?service_name=' + SERVICE engine = create_engine(ENGINE_PATH_WIN_AUTH) #test query import pandas as pd test_df = pd.read_sql_query('SELECT * FROM global_name', engine) ```
cx\_Oracle supports the passing of a service\_name to the makedsn function. <http://cx-oracle.sourceforge.net/html/module.html?highlight=makedsn#cx_Oracle.makedsn> It would be nice if the create\_engine() API passed the service\_name through to the underlying call it makes to makedsn...something like this: ``` oracle = create_engine('oracle://user:pw@host:port', service_name='myservice') TypeError: Invalid argument(s) 'service_name' sent to create_engine(), using configuration OracleDialect_cx_oracle/QueuePool/Engine. Please check that the keyword arguments are appropriate for this combination of components. ```
36,234,988
I feel it is a more general question, but here is an example I am considering: I have a python class which during its initialization goes through a zip archive and extracts some data. Should the code-chunk below be written explicitly inside the "def init" or should it be made as a method outside which will be called inside the "def init"? Which approach is the most 'Pythonic' one? ``` with ZipFile(filename, "r") as archive: for item in archive.namelist(): match = self.pattern.match(item) if match: uid = match.group(2) time = match.group(3) else: raise BadZipFile("bad archive") ```
2016/03/26
[ "https://Stackoverflow.com/questions/36234988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3286832/" ]
If you want to execute the statements you are showing in more then one place, then there's really no discussion. Without a method or a function for this task, you will be violating the [DRY](http://c2.com/cgi/wiki?DontRepeatYourself) principle. Otherwise... well I'd write a method regardless. The task you are showing is nicely self contained and should be abstracted under a descriptive name. It will make your `__init__` method easier to maintain and easier to read. You should also consider writing the code you are showing as a module level function accepting a pattern as an argument, because besides the `self.pattern` attribute the task does not seem to have a strong connection to the data and methods of your class instances (from what we now).
It is perfectly fine for `__init__()` to call other functions, including methods of the same class.
52,827,722
What is the naming convention in python community to set names for project folders and subfolders? ``` my-great-python-project my_great_python_project myGreatPythonProject MyGreatPythonProject ``` I find mixed up in the github. Appreciate your expert opinion.
2018/10/16
[ "https://Stackoverflow.com/questions/52827722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5164382/" ]
There are three conventions, which you might find confusing. 1. The standard [PEP8](https://www.python.org/dev/peps/pep-0008/) defines a standard for how to name packages and modules: > > Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged. > > > 2. Actually, nobody cares about the recommendation about not using underscores Even though it's in PEP8, many packages use underscores and the community doesn't consider it poor practice. So you see many names like `sqlalchemy_searchable`, etc. Although you can create a folder with a name which does not match your package name, it's generally a bad idea to do so because it makes things more confusing. So you'll usually use all-lowercase names with underscores for your folders. 3. Package naming on pypi The name of a package when it's installed doesn't need to match the name it's published to on pypi (the source for `pip` installs). Packages on `pypi` tend to be named with hyphens, not underscores. e.g. [flask-cors](https://pypi.org/project/Flask-Cors/), which installs the package `flask_cors`. However, you'll note that if you follow-up on this example that [flask-cors's GitHub repo](https://github.com/corydolphin/flask-cors) defines the package code in a `flask_cors/` directory. This is the norm. It gets a bit messy though, because `pip` package installation is case-insensitive and treats underscores and hyphens equivalently. So `Flask-Cors`, `fLASK_cOrs`, etc are all "equivalent". Personally, I don't like playing games with this -- I recommend just naming packages on pypi in all-lowercase with hyphens, which is what most people do. --- Disclaimer: I don't own or maintain `sqlalchemy-searchable` or `flask-cors`, but at time of writing they're good examples of packages with underscores in their names.
> > Python packages should also have short, all-lowercase names, although the use of underscores is discouraged. [Pep 8 Style Guide](https://www.python.org/dev/peps/pep-0008/#naming-conventions) > > > This is the recommendation for packages, which is the main folder containing modules, for testing, setup, and script files, \*.py and \_\_init\_\_.py. Therefore, I am assuming the folder is the package and as such, should be all lower case with no underscore (see the link [Some Package Github](https://github.com/ctb/SomePackage) ).
52,827,722
What is the naming convention in python community to set names for project folders and subfolders? ``` my-great-python-project my_great_python_project myGreatPythonProject MyGreatPythonProject ``` I find mixed up in the github. Appreciate your expert opinion.
2018/10/16
[ "https://Stackoverflow.com/questions/52827722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5164382/" ]
Here is an example of how we might organize a repository called `altimeter-valport-lcm` which contains the package `altimeter_valeport_lcm`. The package contains the module `altimeter_valeport_lcm.parser`: ``` altimeter-valeport-lcm/ β”œβ”€β”€ altimeter_valeport_lcm β”‚ β”œβ”€β”€ __init__.py β”‚ β”œβ”€β”€ __main__.py β”‚ β”œβ”€β”€ parser.py β”‚ └── snake_case.py β”œβ”€β”€ README.rst └── setup.py ``` --- [**NOTE**]: * All lowercase for choosing the package name. * The repository should use the same name as the package, except that the repository substitutes dashes (-) for underscores (\_). [Read More.](https://oep.readthedocs.io/en/latest/oep-0003.html)
> > Python packages should also have short, all-lowercase names, although the use of underscores is discouraged. [Pep 8 Style Guide](https://www.python.org/dev/peps/pep-0008/#naming-conventions) > > > This is the recommendation for packages, which is the main folder containing modules, for testing, setup, and script files, \*.py and \_\_init\_\_.py. Therefore, I am assuming the folder is the package and as such, should be all lower case with no underscore (see the link [Some Package Github](https://github.com/ctb/SomePackage) ).
52,827,722
What is the naming convention in python community to set names for project folders and subfolders? ``` my-great-python-project my_great_python_project myGreatPythonProject MyGreatPythonProject ``` I find mixed up in the github. Appreciate your expert opinion.
2018/10/16
[ "https://Stackoverflow.com/questions/52827722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5164382/" ]
There are three conventions, which you might find confusing. 1. The standard [PEP8](https://www.python.org/dev/peps/pep-0008/) defines a standard for how to name packages and modules: > > Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged. > > > 2. Actually, nobody cares about the recommendation about not using underscores Even though it's in PEP8, many packages use underscores and the community doesn't consider it poor practice. So you see many names like `sqlalchemy_searchable`, etc. Although you can create a folder with a name which does not match your package name, it's generally a bad idea to do so because it makes things more confusing. So you'll usually use all-lowercase names with underscores for your folders. 3. Package naming on pypi The name of a package when it's installed doesn't need to match the name it's published to on pypi (the source for `pip` installs). Packages on `pypi` tend to be named with hyphens, not underscores. e.g. [flask-cors](https://pypi.org/project/Flask-Cors/), which installs the package `flask_cors`. However, you'll note that if you follow-up on this example that [flask-cors's GitHub repo](https://github.com/corydolphin/flask-cors) defines the package code in a `flask_cors/` directory. This is the norm. It gets a bit messy though, because `pip` package installation is case-insensitive and treats underscores and hyphens equivalently. So `Flask-Cors`, `fLASK_cOrs`, etc are all "equivalent". Personally, I don't like playing games with this -- I recommend just naming packages on pypi in all-lowercase with hyphens, which is what most people do. --- Disclaimer: I don't own or maintain `sqlalchemy-searchable` or `flask-cors`, but at time of writing they're good examples of packages with underscores in their names.
Here is an example of how we might organize a repository called `altimeter-valport-lcm` which contains the package `altimeter_valeport_lcm`. The package contains the module `altimeter_valeport_lcm.parser`: ``` altimeter-valeport-lcm/ β”œβ”€β”€ altimeter_valeport_lcm β”‚ β”œβ”€β”€ __init__.py β”‚ β”œβ”€β”€ __main__.py β”‚ β”œβ”€β”€ parser.py β”‚ └── snake_case.py β”œβ”€β”€ README.rst └── setup.py ``` --- [**NOTE**]: * All lowercase for choosing the package name. * The repository should use the same name as the package, except that the repository substitutes dashes (-) for underscores (\_). [Read More.](https://oep.readthedocs.io/en/latest/oep-0003.html)
58,475,837
I am trying to learn the functional programming way of doing things in python. I am trying to serialize a list of strings in python using the following code ``` S = ["geeks", "are", "awesome"] reduce(lambda x, y: (str(len(x)) + '~' + x) + (str(len(y)) + '~' + y), S) ``` I am expecting: ``` 5~geeks3~are7~awesome ``` But I am seeing: ``` 12~5~geeks3~are7~awesome ``` Can someone point out why? Thanks in advance!
2019/10/20
[ "https://Stackoverflow.com/questions/58475837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6101835/" ]
`reduce` function on each current iteration relies on previous item/calculation (the nature of all ***reduce*** routines), that's why you got `12` at the start of the resulting string: on the 1st pass the item was `5~geeks3~are` with length `12` and that was used/prepended on next iteration. Instead, you can go with simple *consecutive* approach: ``` lst = ["geeks", "are", "awesome"] res = ''.join('{}~{}'.format(str(len(s)), s) for s in lst) print(res) # 5~geeks3~are7~awesome ```
The `reduce` function is for aggregation. What you're trying to do is mapping instead. You can use the `map` function for the purpose: ``` ''.join(map(lambda x: str(len(x)) + '~' + x, S)) ``` This returns: ``` 5~geeks3~are7~awesome ```
58,475,837
I am trying to learn the functional programming way of doing things in python. I am trying to serialize a list of strings in python using the following code ``` S = ["geeks", "are", "awesome"] reduce(lambda x, y: (str(len(x)) + '~' + x) + (str(len(y)) + '~' + y), S) ``` I am expecting: ``` 5~geeks3~are7~awesome ``` But I am seeing: ``` 12~5~geeks3~are7~awesome ``` Can someone point out why? Thanks in advance!
2019/10/20
[ "https://Stackoverflow.com/questions/58475837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6101835/" ]
You need to add the `initializer` parameter - an empty string to the `reduce()` function. It will be the first argument passed to the `lambda` function before the values from the list. ``` from functools import reduce S = ["geeks", "are", "awesome"] reduce(lambda x, y: x + f'{len(y)}~{y}', S, '') # 5~geeks3~are7~awesome ``` Equivalent to: ``` ((('' + '5~geeks') + '3~are') + '7~awesome') # 5~geeks3~are7~awesome ```
The `reduce` function is for aggregation. What you're trying to do is mapping instead. You can use the `map` function for the purpose: ``` ''.join(map(lambda x: str(len(x)) + '~' + x, S)) ``` This returns: ``` 5~geeks3~are7~awesome ```
58,475,837
I am trying to learn the functional programming way of doing things in python. I am trying to serialize a list of strings in python using the following code ``` S = ["geeks", "are", "awesome"] reduce(lambda x, y: (str(len(x)) + '~' + x) + (str(len(y)) + '~' + y), S) ``` I am expecting: ``` 5~geeks3~are7~awesome ``` But I am seeing: ``` 12~5~geeks3~are7~awesome ``` Can someone point out why? Thanks in advance!
2019/10/20
[ "https://Stackoverflow.com/questions/58475837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6101835/" ]
`reduce` function on each current iteration relies on previous item/calculation (the nature of all ***reduce*** routines), that's why you got `12` at the start of the resulting string: on the 1st pass the item was `5~geeks3~are` with length `12` and that was used/prepended on next iteration. Instead, you can go with simple *consecutive* approach: ``` lst = ["geeks", "are", "awesome"] res = ''.join('{}~{}'.format(str(len(s)), s) for s in lst) print(res) # 5~geeks3~are7~awesome ```
* here is the solution for `pyton3.7+` using `fstring`. ```py >>> S = ["geeks", "are", "awesome"] >>> ''.join(f'{len(s)}~{s}' for s in S) '5~geeks3~are7~awesome' ```