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
52,169,443
Currently, I'm facing an issue with uploading (using python) EMOJI data to the BIG QUERY This is sample code which I'm trying to upload to BQ: ``` {"emojiCharts":{"emoji_icon":"\ud83d\udc4d","repost": 4, "doc": 4, "engagement": 0, "reach": 0, "impression": 0}} {"emojiCharts":{"emoji_icon":"\ud83d\udc49","repost": 4, "doc": 4, "engagement": 43, "reach": 722, "impression": 4816}} {"emojiCharts":{"emoji_icon":"\u203c","repost": 4, "doc": 4, "engagement": 0, "reach": 0, "impression": 0}} {"emojiCharts":{"emoji_icon":"\ud83c\udf89","repost": 5, "doc": 5, "engagement": 43, "reach": 829, "impression": 5529}} {"emojiCharts":{"emoji_icon":"\ud83d\ude34","repost": 5, "doc": 5, "engagement": 222, "reach": 420, "impression": 2805}} {"emojiCharts":{"emoji_icon":"\ud83d\ude31","repost": 3, "doc": 3, "engagement": 386, "reach": 2868, "impression": 19122}} {"emojiCharts":{"emoji_icon":"\ud83d\udc4d\ud83c\udffb","repost": 5, "doc": 5, "engagement": 43, "reach": 1064, "impression": 7098}} {"emojiCharts":{"emoji_icon":"\ud83d\ude3b","repost": 3, "doc": 3, "engagement": 93, "reach": 192, "impression": 1283}} {"emojiCharts":{"emoji_icon":"\ud83d\ude2d","repost": 6, "doc": 6, "engagement": 212, "reach": 909, "impression": 6143}} {"emojiCharts":{"emoji_icon":"\ud83e\udd84","repost": 8, "doc": 8, "engagement": 313, "reach": 402, "impression": 2681}} {"emojiCharts":{"emoji_icon":"\ud83d\ude18","repost": 7, "doc": 7, "engagement": 0, "reach": 8454, "impression": 56366}} {"emojiCharts":{"emoji_icon":"\ud83d\ude05","repost": 5, "doc": 5, "engagement": 74, "reach": 1582, "impression": 10550}} {"emojiCharts":{"emoji_icon":"\ud83d\ude04","repost": 5, "doc": 5, "engagement": 73, "reach": 3329, "impression": 22206}} ``` Issues is that big query cannot see any of this emoji (`\ud83d\ude04`) and will display only in this format (`\u203c`) Even if the field is **STRING** it displays 2 black rombs, why BQ cannot display emoji as a string without converting it to the actual emoji? **Questions:** Is there are any way to upload EMOJI to Big Query that it will load up correctly? - "**will be used in Google Data Studio**" Should I manually (hardcoded) change all emoji code the acceptable ones, which is the acceptable format?
2018/09/04
[ "https://Stackoverflow.com/questions/52169443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
As user 'numeral' mentions in their comment: > > Check out [charbase.com/1f618-unicode-face-throwing-a-kiss](http://charbase.com/1f618-unicode-face-throwing-a-kiss) What you want is to convert the javascript escape characters to actual unicode data. > > > , you need to change the encoding of the emojis for them to be accurately represented as one character: ``` SELECT "\U0001f604 \U0001f4b8" -- , "\ud83d\udcb8" -- , "\ud83d\ude04" ``` The 2nd and 3d line fail with an error like `Illegal escape sequence: Unicode value \ud83d is invalid at [2:7]`, but the first line gives the correct display in BigQuery and Data Studio: [![enter image description here](https://i.stack.imgur.com/COVg7.png)](https://i.stack.imgur.com/COVg7.png) [![enter image description here](https://i.stack.imgur.com/qls2X.png)](https://i.stack.imgur.com/qls2X.png) Additional thoughts about this: * <https://stackoverflow.com/search?q=%5Cud83d>
Python does not support "surrogate characters" representation which is composed of multiple UTF-16 characters and some emojis (over `0xFFFF`) use them. For example, can be represented by `\U0001f3e6` (UTF-32) in Python and some languages uses `\ud83c\udfe6`. For those values are less than `0xFFFF`, python and other languages both use the same representation, e.g. `\u3020` (〠). To solve the encoding issue, you can manually convert the emoji characters or consider using some libraries, e.g. <https://github.com/hartwork/surrogates> to convert them to UTF-32. Also, BigQueqry Python client's `load_table_from_json` had a bug about those characters whose values are over `0xFFFF`, even you use correct UTF-32 representation. It just released a new version to fix it a couple of days ago. ref: <https://github.com/googleapis/python-bigquery/releases/tag/v2.24.0> Some references about Bank emoji listing different representation: * <https://www.fileformat.info/info/unicode/char/1f3e6/index.htm> * <https://charbase.com/1f3e6-unicode-bank>
68,633,577
I am a beginner in python and I have started with web scraping, I want to extract data from a tourist site I need the names of the hotels, the arrangements available in each hotel and the price but I got stuck in the list of arrangements, each hotel can have several arrangements but it doesn't work and I don't know why. I put at your disposal my code and the output provided if any of you can help me and thank you in advance. ``` from time import sleep from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait PATH = "C:\\Users\\marketing2\\Documents\\chromedriver.exe" driver = webdriver.Chrome(PATH) driver.get('https://tn.tunisiebooking.com/') wait = WebDriverWait(driver, 20) # write script //Your Script Seems fine script = "document.getElementById('ville_des').value ='Sousse';document.getElementById('depart').value ='05/08/2021';document.getElementById('checkin').value ='05/08/2021';document.getElementById('select_ch').value = '1';" # Execute script driver.execute_script(script) # click bouton search btn_rechercher = driver.find_element_by_id('boutonr') btn_rechercher.click() sleep(10) # click bouton details btn_plus = driver.find_element_by_id('plus_res') btn_plus.click() sleep(10) #getting the hotel names and by xpath in a loop hotels=[] pensions=[] for v in range(1, 5): hotel = driver.find_element_by_xpath('/html/body/div[6]/div[2]/div[1]/div/div[2]/div/div[4]/div[' + str(v) + ']/div/div[3]/div[1]/div[1]/span/a/h3').get_attribute('innerHTML') for j in range (1,3): pension= driver.find_element_by_xpath('/html/body/div[6]/div[2]/div[1]/div/div[2]/div/div[4]/div[1]/div/div[3]/div[3]/div[1]/div[1]/form/div[1]/div[' + str(j) + ']/u').get_attribute('innerHTML') pensions.append((pension)) hotels.append((hotel,pensions)) print(hotels) ```
2021/08/03
[ "https://Stackoverflow.com/questions/68633577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16571797/" ]
You are assigning `0` to `stringArray`, `booleanArray` and `numberArray`. A `0` isn't an array, so you can't add values to it like that. ([Assigning values to a primitive type is a noop](https://stackoverflow.com/a/5201148).) Assign an array to those values and use `.push()` on them to add values to those arrays. (Using `[i]` will leave gaps in your array, because each iteration `i` will be incremented but only one of the arrays will get a value at that index, leaving the other two blank.) ```js let data = [ 538, 922, "725", false, 733, 170, 294, "336", false, "538", 79, 390, true, "816", "50", 920, "845", "728", "133", "468", false, true, 520, 747, false, "540", true, true, "262", 625, "614", 316, "978", "865", "506", 552, 187, "444", 676, 544, 840, 691, "50", 21, "926", "10", 37, "704", "36", 978, 830, 438, true, "713", 497, "371", 243, 638, 454, 291, "185", "941", "581", 336, 458, "585", false, 870, "639", "360", 599, "644", "767", 878, "646", 117, "933", 48, 934, "155", "749", 808, 922, 94, "360", "395", false, 407, true, false, "97", "233", 70, "609", false, false, "13", "698", 797, "789" ]; let sortedData = { stringArray: [], booleanArray: [], numberArray: [], } for (let i = 0; i < data.length; i++) { if (typeof data[i] == 'string') { sortedData.stringArray.push(data[i]); } else if (typeof data[i] == 'boolean') { sortedData.booleanArray.push(data[i]); } else if (typeof data[i] == 'number') { sortedData.numberArray.push(data[i]); } } console.log(sortedData); ```
Change the values of zero to an array like this: ``` let sortedData = { stringArray: [], booleanArray: [], numberArray: [], } ``` ``` // set value on array item // || // \/ sortedData.stringArray[i] === 'something' ```
68,633,577
I am a beginner in python and I have started with web scraping, I want to extract data from a tourist site I need the names of the hotels, the arrangements available in each hotel and the price but I got stuck in the list of arrangements, each hotel can have several arrangements but it doesn't work and I don't know why. I put at your disposal my code and the output provided if any of you can help me and thank you in advance. ``` from time import sleep from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait PATH = "C:\\Users\\marketing2\\Documents\\chromedriver.exe" driver = webdriver.Chrome(PATH) driver.get('https://tn.tunisiebooking.com/') wait = WebDriverWait(driver, 20) # write script //Your Script Seems fine script = "document.getElementById('ville_des').value ='Sousse';document.getElementById('depart').value ='05/08/2021';document.getElementById('checkin').value ='05/08/2021';document.getElementById('select_ch').value = '1';" # Execute script driver.execute_script(script) # click bouton search btn_rechercher = driver.find_element_by_id('boutonr') btn_rechercher.click() sleep(10) # click bouton details btn_plus = driver.find_element_by_id('plus_res') btn_plus.click() sleep(10) #getting the hotel names and by xpath in a loop hotels=[] pensions=[] for v in range(1, 5): hotel = driver.find_element_by_xpath('/html/body/div[6]/div[2]/div[1]/div/div[2]/div/div[4]/div[' + str(v) + ']/div/div[3]/div[1]/div[1]/span/a/h3').get_attribute('innerHTML') for j in range (1,3): pension= driver.find_element_by_xpath('/html/body/div[6]/div[2]/div[1]/div/div[2]/div/div[4]/div[1]/div/div[3]/div[3]/div[1]/div[1]/form/div[1]/div[' + str(j) + ']/u').get_attribute('innerHTML') pensions.append((pension)) hotels.append((hotel,pensions)) print(hotels) ```
2021/08/03
[ "https://Stackoverflow.com/questions/68633577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16571797/" ]
You can do it using [`Array.prototype.reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce): ```js let data = [ 538, 922, "725", false, 733, 170, 294, "336", false, "538", 79, 390, true, "816", "50", 920, "845", "728", "133", "468", false, true, 520, 747, false, "540", true, true, "262", 625, "614", 316, "978", "865", "506", 552, 187, "444", 676, 544, 840, 691, "50", 21, "926", "10", 37, "704", "36", 978, 830, 438, true, "713", 497, "371", 243, 638, 454, 291, "185", "941", "581", 336, 458, "585", false, 870, "639", "360", 599, "644", "767", 878, "646", 117, "933", 48, 934, "155", "749", 808, 922, 94, "360", "395", false, 407, true, false, "97", "233", 70, "609", false, false, "13", "698", 797, "789", null, {}, undefined, null, [], x => x * 2 ]; const sortedData = data.reduce((outObj, item) => { const key = item === null // this check is needed because, for historical reasons `typeof(null)` returns 'object' instead of 'null' ? 'nullArray' : typeof(item) + 'Array'; if (outObj.hasOwnProperty(key)) { // if the object already has a key for that data type, push the item in the existing array outObj[key].push(item); } else { // otherwise create the new key and add the item to it outObj[key] = [item]; } return outObj; }, {}); // test console.log(sortedData); ``` This approach has the advantage that you do not need to know in advance how many data types are present in the original array and what they are, as it will automatically create a new key as soon as it encounters a new data type. [EDIT] Just to avoid any misunderstanding: when I say "this approach" I mean the approach of dynamically creating the object keys, which is something you can do regardless of whether you use a simple `for` loop or `Array.prototype.reduce()`. ;)
Change the values of zero to an array like this: ``` let sortedData = { stringArray: [], booleanArray: [], numberArray: [], } ``` ``` // set value on array item // || // \/ sortedData.stringArray[i] === 'something' ```
68,633,577
I am a beginner in python and I have started with web scraping, I want to extract data from a tourist site I need the names of the hotels, the arrangements available in each hotel and the price but I got stuck in the list of arrangements, each hotel can have several arrangements but it doesn't work and I don't know why. I put at your disposal my code and the output provided if any of you can help me and thank you in advance. ``` from time import sleep from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait PATH = "C:\\Users\\marketing2\\Documents\\chromedriver.exe" driver = webdriver.Chrome(PATH) driver.get('https://tn.tunisiebooking.com/') wait = WebDriverWait(driver, 20) # write script //Your Script Seems fine script = "document.getElementById('ville_des').value ='Sousse';document.getElementById('depart').value ='05/08/2021';document.getElementById('checkin').value ='05/08/2021';document.getElementById('select_ch').value = '1';" # Execute script driver.execute_script(script) # click bouton search btn_rechercher = driver.find_element_by_id('boutonr') btn_rechercher.click() sleep(10) # click bouton details btn_plus = driver.find_element_by_id('plus_res') btn_plus.click() sleep(10) #getting the hotel names and by xpath in a loop hotels=[] pensions=[] for v in range(1, 5): hotel = driver.find_element_by_xpath('/html/body/div[6]/div[2]/div[1]/div/div[2]/div/div[4]/div[' + str(v) + ']/div/div[3]/div[1]/div[1]/span/a/h3').get_attribute('innerHTML') for j in range (1,3): pension= driver.find_element_by_xpath('/html/body/div[6]/div[2]/div[1]/div/div[2]/div/div[4]/div[1]/div/div[3]/div[3]/div[1]/div[1]/form/div[1]/div[' + str(j) + ']/u').get_attribute('innerHTML') pensions.append((pension)) hotels.append((hotel,pensions)) print(hotels) ```
2021/08/03
[ "https://Stackoverflow.com/questions/68633577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16571797/" ]
explainations at the code. ```js // data is array with mixed data type let data = [ 123, 12.3, "123", [1,2,3], {'1':[2,3]}, true, false, null, undefined ]; // sfxName : extra suffix for 'grpName' // grpName : type + sfxName // the output key will be > numberArray, booleanArray etc... let sorted = {}, sfxName = '_Array'; for( let n of data ){ const grpName = (n === null) ? n + sfxName : typeof n + sfxName; if (!sorted[grpName]) sorted[grpName] = []; sorted[grpName].push(n); } console.log( sorted ); ```
Change the values of zero to an array like this: ``` let sortedData = { stringArray: [], booleanArray: [], numberArray: [], } ``` ``` // set value on array item // || // \/ sortedData.stringArray[i] === 'something' ```
68,633,577
I am a beginner in python and I have started with web scraping, I want to extract data from a tourist site I need the names of the hotels, the arrangements available in each hotel and the price but I got stuck in the list of arrangements, each hotel can have several arrangements but it doesn't work and I don't know why. I put at your disposal my code and the output provided if any of you can help me and thank you in advance. ``` from time import sleep from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait PATH = "C:\\Users\\marketing2\\Documents\\chromedriver.exe" driver = webdriver.Chrome(PATH) driver.get('https://tn.tunisiebooking.com/') wait = WebDriverWait(driver, 20) # write script //Your Script Seems fine script = "document.getElementById('ville_des').value ='Sousse';document.getElementById('depart').value ='05/08/2021';document.getElementById('checkin').value ='05/08/2021';document.getElementById('select_ch').value = '1';" # Execute script driver.execute_script(script) # click bouton search btn_rechercher = driver.find_element_by_id('boutonr') btn_rechercher.click() sleep(10) # click bouton details btn_plus = driver.find_element_by_id('plus_res') btn_plus.click() sleep(10) #getting the hotel names and by xpath in a loop hotels=[] pensions=[] for v in range(1, 5): hotel = driver.find_element_by_xpath('/html/body/div[6]/div[2]/div[1]/div/div[2]/div/div[4]/div[' + str(v) + ']/div/div[3]/div[1]/div[1]/span/a/h3').get_attribute('innerHTML') for j in range (1,3): pension= driver.find_element_by_xpath('/html/body/div[6]/div[2]/div[1]/div/div[2]/div/div[4]/div[1]/div/div[3]/div[3]/div[1]/div[1]/form/div[1]/div[' + str(j) + ']/u').get_attribute('innerHTML') pensions.append((pension)) hotels.append((hotel,pensions)) print(hotels) ```
2021/08/03
[ "https://Stackoverflow.com/questions/68633577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16571797/" ]
You are assigning `0` to `stringArray`, `booleanArray` and `numberArray`. A `0` isn't an array, so you can't add values to it like that. ([Assigning values to a primitive type is a noop](https://stackoverflow.com/a/5201148).) Assign an array to those values and use `.push()` on them to add values to those arrays. (Using `[i]` will leave gaps in your array, because each iteration `i` will be incremented but only one of the arrays will get a value at that index, leaving the other two blank.) ```js let data = [ 538, 922, "725", false, 733, 170, 294, "336", false, "538", 79, 390, true, "816", "50", 920, "845", "728", "133", "468", false, true, 520, 747, false, "540", true, true, "262", 625, "614", 316, "978", "865", "506", 552, 187, "444", 676, 544, 840, 691, "50", 21, "926", "10", 37, "704", "36", 978, 830, 438, true, "713", 497, "371", 243, 638, 454, 291, "185", "941", "581", 336, 458, "585", false, 870, "639", "360", 599, "644", "767", 878, "646", 117, "933", 48, 934, "155", "749", 808, 922, 94, "360", "395", false, 407, true, false, "97", "233", 70, "609", false, false, "13", "698", 797, "789" ]; let sortedData = { stringArray: [], booleanArray: [], numberArray: [], } for (let i = 0; i < data.length; i++) { if (typeof data[i] == 'string') { sortedData.stringArray.push(data[i]); } else if (typeof data[i] == 'boolean') { sortedData.booleanArray.push(data[i]); } else if (typeof data[i] == 'number') { sortedData.numberArray.push(data[i]); } } console.log(sortedData); ```
You can do it using [`Array.prototype.reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce): ```js let data = [ 538, 922, "725", false, 733, 170, 294, "336", false, "538", 79, 390, true, "816", "50", 920, "845", "728", "133", "468", false, true, 520, 747, false, "540", true, true, "262", 625, "614", 316, "978", "865", "506", 552, 187, "444", 676, 544, 840, 691, "50", 21, "926", "10", 37, "704", "36", 978, 830, 438, true, "713", 497, "371", 243, 638, 454, 291, "185", "941", "581", 336, 458, "585", false, 870, "639", "360", 599, "644", "767", 878, "646", 117, "933", 48, 934, "155", "749", 808, 922, 94, "360", "395", false, 407, true, false, "97", "233", 70, "609", false, false, "13", "698", 797, "789", null, {}, undefined, null, [], x => x * 2 ]; const sortedData = data.reduce((outObj, item) => { const key = item === null // this check is needed because, for historical reasons `typeof(null)` returns 'object' instead of 'null' ? 'nullArray' : typeof(item) + 'Array'; if (outObj.hasOwnProperty(key)) { // if the object already has a key for that data type, push the item in the existing array outObj[key].push(item); } else { // otherwise create the new key and add the item to it outObj[key] = [item]; } return outObj; }, {}); // test console.log(sortedData); ``` This approach has the advantage that you do not need to know in advance how many data types are present in the original array and what they are, as it will automatically create a new key as soon as it encounters a new data type. [EDIT] Just to avoid any misunderstanding: when I say "this approach" I mean the approach of dynamically creating the object keys, which is something you can do regardless of whether you use a simple `for` loop or `Array.prototype.reduce()`. ;)
68,633,577
I am a beginner in python and I have started with web scraping, I want to extract data from a tourist site I need the names of the hotels, the arrangements available in each hotel and the price but I got stuck in the list of arrangements, each hotel can have several arrangements but it doesn't work and I don't know why. I put at your disposal my code and the output provided if any of you can help me and thank you in advance. ``` from time import sleep from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait PATH = "C:\\Users\\marketing2\\Documents\\chromedriver.exe" driver = webdriver.Chrome(PATH) driver.get('https://tn.tunisiebooking.com/') wait = WebDriverWait(driver, 20) # write script //Your Script Seems fine script = "document.getElementById('ville_des').value ='Sousse';document.getElementById('depart').value ='05/08/2021';document.getElementById('checkin').value ='05/08/2021';document.getElementById('select_ch').value = '1';" # Execute script driver.execute_script(script) # click bouton search btn_rechercher = driver.find_element_by_id('boutonr') btn_rechercher.click() sleep(10) # click bouton details btn_plus = driver.find_element_by_id('plus_res') btn_plus.click() sleep(10) #getting the hotel names and by xpath in a loop hotels=[] pensions=[] for v in range(1, 5): hotel = driver.find_element_by_xpath('/html/body/div[6]/div[2]/div[1]/div/div[2]/div/div[4]/div[' + str(v) + ']/div/div[3]/div[1]/div[1]/span/a/h3').get_attribute('innerHTML') for j in range (1,3): pension= driver.find_element_by_xpath('/html/body/div[6]/div[2]/div[1]/div/div[2]/div/div[4]/div[1]/div/div[3]/div[3]/div[1]/div[1]/form/div[1]/div[' + str(j) + ']/u').get_attribute('innerHTML') pensions.append((pension)) hotels.append((hotel,pensions)) print(hotels) ```
2021/08/03
[ "https://Stackoverflow.com/questions/68633577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16571797/" ]
You are assigning `0` to `stringArray`, `booleanArray` and `numberArray`. A `0` isn't an array, so you can't add values to it like that. ([Assigning values to a primitive type is a noop](https://stackoverflow.com/a/5201148).) Assign an array to those values and use `.push()` on them to add values to those arrays. (Using `[i]` will leave gaps in your array, because each iteration `i` will be incremented but only one of the arrays will get a value at that index, leaving the other two blank.) ```js let data = [ 538, 922, "725", false, 733, 170, 294, "336", false, "538", 79, 390, true, "816", "50", 920, "845", "728", "133", "468", false, true, 520, 747, false, "540", true, true, "262", 625, "614", 316, "978", "865", "506", 552, 187, "444", 676, 544, 840, 691, "50", 21, "926", "10", 37, "704", "36", 978, 830, 438, true, "713", 497, "371", 243, 638, 454, 291, "185", "941", "581", 336, 458, "585", false, 870, "639", "360", 599, "644", "767", 878, "646", 117, "933", 48, 934, "155", "749", 808, 922, 94, "360", "395", false, 407, true, false, "97", "233", 70, "609", false, false, "13", "698", 797, "789" ]; let sortedData = { stringArray: [], booleanArray: [], numberArray: [], } for (let i = 0; i < data.length; i++) { if (typeof data[i] == 'string') { sortedData.stringArray.push(data[i]); } else if (typeof data[i] == 'boolean') { sortedData.booleanArray.push(data[i]); } else if (typeof data[i] == 'number') { sortedData.numberArray.push(data[i]); } } console.log(sortedData); ```
explainations at the code. ```js // data is array with mixed data type let data = [ 123, 12.3, "123", [1,2,3], {'1':[2,3]}, true, false, null, undefined ]; // sfxName : extra suffix for 'grpName' // grpName : type + sfxName // the output key will be > numberArray, booleanArray etc... let sorted = {}, sfxName = '_Array'; for( let n of data ){ const grpName = (n === null) ? n + sfxName : typeof n + sfxName; if (!sorted[grpName]) sorted[grpName] = []; sorted[grpName].push(n); } console.log( sorted ); ```
15,021,877
I am developing a GUI with PyQt, to perform visual analysis of the data collected during some experiments. The GUI asks the user to indicate the directory where the data to be analyzed is located: ``` class ExperimentAnalyzer(QtGui.QMainWindow): ## other stuff here def loadExperiment(self): directory = QtGui.QFileDialog.getExistingDirectory(self, "Select Directory") ## load data from directory here ``` The GUI provides a ***play*** functionality, by means of which the user can see how experimental data changes over time. This is implemented through a **QTimer**: ``` def playOrPause(self): ## play if self.appStatus.timer is None: self.appStatus.timer = QtCore.QTimer(self) self.appStatus.timer.connect(self.appStatus.timer, QtCore.SIGNAL("timeout()"), self.nextFrame) self.appStatus.timer.start(40) ## pause else: self.appStatus.timer.stop() self.appStatus.timer = None ``` If I ***play*** the temporal sequence of data, then ***pause***, then try to change the directory to load data from a new experiment, I experience a **segmentation fault**. Using some debug prints, I found out that the application crashes when I call ``` QtGui.QFileDialog.getExistingDirectory(self, "Select Directory") ``` in the ***loadExperiment*** method. I'm pretty new to Qt and I think I'm not handling the timer properly. I'm using PyQt 4.9, Python 2.7.3 on Ubuntu 10.04. **Edit-1**: ----------- After Luke's answer, I went back to my code. Here's the ***nextFrame*** method, invoked every time the timer emits the ***timeout*** signal. It updates a QGraphicsScene element contained in the GUI: ``` def nextFrame(self): image = Image.open("<some jpg>") w, h = image.size imageQt = ImageQt.ImageQt(image) pixMap = QtGui.QPixmap.fromImage(imageQt) self.scene.clear() self.scene.addPixmap(pixMap) self.view.fitInView(QtCore.QRectF(0, 0, w, h), QtCore.Qt.KeepAspectRatio) ``` where the self.scene and the self.view objects have been previously instantiated in the GUI constructor as ``` self.view = QtGui.QGraphicsView(self) self.scene = QtGui.QGraphicsScene() self.view.setScene(self.scene) ``` I found out that commenting this line: ``` # self.scene.addPixmap(pixMap) ``` and repeating the same operations sequence reported above, the segmentation fault does not occur anymore. **Edit-2**: ----------- Running the application with gdb (with python-dbg), it turns out that the segmentation fault occurs after a call to QPainter::drawPixmap. ``` (gdb) bt #0 0xb6861f1d in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #1 0xb685d491 in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #2 0xb693bcd3 in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #3 0xb69390bc in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #4 0xb6945c77 in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #5 0xb68bd424 in QPainter::drawPixmap(QPointF const&, QPixmap const&) () from /usr/lib/i386-linux-gnu/libQtGui.so.4 ``` Therefore, it's not a problem related to timer handling, as I believed in first instance. The segmentation fault happens because I'm doing something wrong with the pixMap.
2013/02/22
[ "https://Stackoverflow.com/questions/15021877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1759574/" ]
You can do in this way: ``` $(function(){ $('.yourelem, .targetDiv').click(function(ev){ $('.targetDiv').slideDown('fast'); ev.stopPropagation(); }); $(document).click(function(){ $('.targetDiv').slideUp('fast'); }); }); ``` [See the action in jsbin](http://jsbin.com/ayuhol/1/edit) ---------------------------------------------------------
Try this : HTML ``` <a id="show" href="#">show</a> <div class="test" style="display: none;"> hey </div> ``` JS ``` $('a#show').click(function(event) { event.stopPropagation(); $('.test').toggle(); }); $('html').click(function() { $('.test').hide(); }); ```
15,021,877
I am developing a GUI with PyQt, to perform visual analysis of the data collected during some experiments. The GUI asks the user to indicate the directory where the data to be analyzed is located: ``` class ExperimentAnalyzer(QtGui.QMainWindow): ## other stuff here def loadExperiment(self): directory = QtGui.QFileDialog.getExistingDirectory(self, "Select Directory") ## load data from directory here ``` The GUI provides a ***play*** functionality, by means of which the user can see how experimental data changes over time. This is implemented through a **QTimer**: ``` def playOrPause(self): ## play if self.appStatus.timer is None: self.appStatus.timer = QtCore.QTimer(self) self.appStatus.timer.connect(self.appStatus.timer, QtCore.SIGNAL("timeout()"), self.nextFrame) self.appStatus.timer.start(40) ## pause else: self.appStatus.timer.stop() self.appStatus.timer = None ``` If I ***play*** the temporal sequence of data, then ***pause***, then try to change the directory to load data from a new experiment, I experience a **segmentation fault**. Using some debug prints, I found out that the application crashes when I call ``` QtGui.QFileDialog.getExistingDirectory(self, "Select Directory") ``` in the ***loadExperiment*** method. I'm pretty new to Qt and I think I'm not handling the timer properly. I'm using PyQt 4.9, Python 2.7.3 on Ubuntu 10.04. **Edit-1**: ----------- After Luke's answer, I went back to my code. Here's the ***nextFrame*** method, invoked every time the timer emits the ***timeout*** signal. It updates a QGraphicsScene element contained in the GUI: ``` def nextFrame(self): image = Image.open("<some jpg>") w, h = image.size imageQt = ImageQt.ImageQt(image) pixMap = QtGui.QPixmap.fromImage(imageQt) self.scene.clear() self.scene.addPixmap(pixMap) self.view.fitInView(QtCore.QRectF(0, 0, w, h), QtCore.Qt.KeepAspectRatio) ``` where the self.scene and the self.view objects have been previously instantiated in the GUI constructor as ``` self.view = QtGui.QGraphicsView(self) self.scene = QtGui.QGraphicsScene() self.view.setScene(self.scene) ``` I found out that commenting this line: ``` # self.scene.addPixmap(pixMap) ``` and repeating the same operations sequence reported above, the segmentation fault does not occur anymore. **Edit-2**: ----------- Running the application with gdb (with python-dbg), it turns out that the segmentation fault occurs after a call to QPainter::drawPixmap. ``` (gdb) bt #0 0xb6861f1d in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #1 0xb685d491 in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #2 0xb693bcd3 in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #3 0xb69390bc in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #4 0xb6945c77 in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #5 0xb68bd424 in QPainter::drawPixmap(QPointF const&, QPixmap const&) () from /usr/lib/i386-linux-gnu/libQtGui.so.4 ``` Therefore, it's not a problem related to timer handling, as I believed in first instance. The segmentation fault happens because I'm doing something wrong with the pixMap.
2013/02/22
[ "https://Stackoverflow.com/questions/15021877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1759574/" ]
You can do in this way: ``` $(function(){ $('.yourelem, .targetDiv').click(function(ev){ $('.targetDiv').slideDown('fast'); ev.stopPropagation(); }); $(document).click(function(){ $('.targetDiv').slideUp('fast'); }); }); ``` [See the action in jsbin](http://jsbin.com/ayuhol/1/edit) ---------------------------------------------------------
Take a look on .blur function of jquery <http://api.jquery.com/blur/> A quick example: ``` $("#myelement").blur(function(){ $(this).hide(); //or $("#targetelement").hide(); }); ```
15,021,877
I am developing a GUI with PyQt, to perform visual analysis of the data collected during some experiments. The GUI asks the user to indicate the directory where the data to be analyzed is located: ``` class ExperimentAnalyzer(QtGui.QMainWindow): ## other stuff here def loadExperiment(self): directory = QtGui.QFileDialog.getExistingDirectory(self, "Select Directory") ## load data from directory here ``` The GUI provides a ***play*** functionality, by means of which the user can see how experimental data changes over time. This is implemented through a **QTimer**: ``` def playOrPause(self): ## play if self.appStatus.timer is None: self.appStatus.timer = QtCore.QTimer(self) self.appStatus.timer.connect(self.appStatus.timer, QtCore.SIGNAL("timeout()"), self.nextFrame) self.appStatus.timer.start(40) ## pause else: self.appStatus.timer.stop() self.appStatus.timer = None ``` If I ***play*** the temporal sequence of data, then ***pause***, then try to change the directory to load data from a new experiment, I experience a **segmentation fault**. Using some debug prints, I found out that the application crashes when I call ``` QtGui.QFileDialog.getExistingDirectory(self, "Select Directory") ``` in the ***loadExperiment*** method. I'm pretty new to Qt and I think I'm not handling the timer properly. I'm using PyQt 4.9, Python 2.7.3 on Ubuntu 10.04. **Edit-1**: ----------- After Luke's answer, I went back to my code. Here's the ***nextFrame*** method, invoked every time the timer emits the ***timeout*** signal. It updates a QGraphicsScene element contained in the GUI: ``` def nextFrame(self): image = Image.open("<some jpg>") w, h = image.size imageQt = ImageQt.ImageQt(image) pixMap = QtGui.QPixmap.fromImage(imageQt) self.scene.clear() self.scene.addPixmap(pixMap) self.view.fitInView(QtCore.QRectF(0, 0, w, h), QtCore.Qt.KeepAspectRatio) ``` where the self.scene and the self.view objects have been previously instantiated in the GUI constructor as ``` self.view = QtGui.QGraphicsView(self) self.scene = QtGui.QGraphicsScene() self.view.setScene(self.scene) ``` I found out that commenting this line: ``` # self.scene.addPixmap(pixMap) ``` and repeating the same operations sequence reported above, the segmentation fault does not occur anymore. **Edit-2**: ----------- Running the application with gdb (with python-dbg), it turns out that the segmentation fault occurs after a call to QPainter::drawPixmap. ``` (gdb) bt #0 0xb6861f1d in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #1 0xb685d491 in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #2 0xb693bcd3 in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #3 0xb69390bc in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #4 0xb6945c77 in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #5 0xb68bd424 in QPainter::drawPixmap(QPointF const&, QPixmap const&) () from /usr/lib/i386-linux-gnu/libQtGui.so.4 ``` Therefore, it's not a problem related to timer handling, as I believed in first instance. The segmentation fault happens because I'm doing something wrong with the pixMap.
2013/02/22
[ "https://Stackoverflow.com/questions/15021877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1759574/" ]
You can do in this way: ``` $(function(){ $('.yourelem, .targetDiv').click(function(ev){ $('.targetDiv').slideDown('fast'); ev.stopPropagation(); }); $(document).click(function(){ $('.targetDiv').slideUp('fast'); }); }); ``` [See the action in jsbin](http://jsbin.com/ayuhol/1/edit) ---------------------------------------------------------
Make variable sel `true`, if we click on the `div`. ``` if(sel) $(".stackExchange").slideDown(800); else $(".stackExchange").slideUp(800); ```
15,021,877
I am developing a GUI with PyQt, to perform visual analysis of the data collected during some experiments. The GUI asks the user to indicate the directory where the data to be analyzed is located: ``` class ExperimentAnalyzer(QtGui.QMainWindow): ## other stuff here def loadExperiment(self): directory = QtGui.QFileDialog.getExistingDirectory(self, "Select Directory") ## load data from directory here ``` The GUI provides a ***play*** functionality, by means of which the user can see how experimental data changes over time. This is implemented through a **QTimer**: ``` def playOrPause(self): ## play if self.appStatus.timer is None: self.appStatus.timer = QtCore.QTimer(self) self.appStatus.timer.connect(self.appStatus.timer, QtCore.SIGNAL("timeout()"), self.nextFrame) self.appStatus.timer.start(40) ## pause else: self.appStatus.timer.stop() self.appStatus.timer = None ``` If I ***play*** the temporal sequence of data, then ***pause***, then try to change the directory to load data from a new experiment, I experience a **segmentation fault**. Using some debug prints, I found out that the application crashes when I call ``` QtGui.QFileDialog.getExistingDirectory(self, "Select Directory") ``` in the ***loadExperiment*** method. I'm pretty new to Qt and I think I'm not handling the timer properly. I'm using PyQt 4.9, Python 2.7.3 on Ubuntu 10.04. **Edit-1**: ----------- After Luke's answer, I went back to my code. Here's the ***nextFrame*** method, invoked every time the timer emits the ***timeout*** signal. It updates a QGraphicsScene element contained in the GUI: ``` def nextFrame(self): image = Image.open("<some jpg>") w, h = image.size imageQt = ImageQt.ImageQt(image) pixMap = QtGui.QPixmap.fromImage(imageQt) self.scene.clear() self.scene.addPixmap(pixMap) self.view.fitInView(QtCore.QRectF(0, 0, w, h), QtCore.Qt.KeepAspectRatio) ``` where the self.scene and the self.view objects have been previously instantiated in the GUI constructor as ``` self.view = QtGui.QGraphicsView(self) self.scene = QtGui.QGraphicsScene() self.view.setScene(self.scene) ``` I found out that commenting this line: ``` # self.scene.addPixmap(pixMap) ``` and repeating the same operations sequence reported above, the segmentation fault does not occur anymore. **Edit-2**: ----------- Running the application with gdb (with python-dbg), it turns out that the segmentation fault occurs after a call to QPainter::drawPixmap. ``` (gdb) bt #0 0xb6861f1d in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #1 0xb685d491 in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #2 0xb693bcd3 in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #3 0xb69390bc in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #4 0xb6945c77 in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #5 0xb68bd424 in QPainter::drawPixmap(QPointF const&, QPixmap const&) () from /usr/lib/i386-linux-gnu/libQtGui.so.4 ``` Therefore, it's not a problem related to timer handling, as I believed in first instance. The segmentation fault happens because I'm doing something wrong with the pixMap.
2013/02/22
[ "https://Stackoverflow.com/questions/15021877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1759574/" ]
Try this : HTML ``` <a id="show" href="#">show</a> <div class="test" style="display: none;"> hey </div> ``` JS ``` $('a#show').click(function(event) { event.stopPropagation(); $('.test').toggle(); }); $('html').click(function() { $('.test').hide(); }); ```
Take a look on .blur function of jquery <http://api.jquery.com/blur/> A quick example: ``` $("#myelement").blur(function(){ $(this).hide(); //or $("#targetelement").hide(); }); ```
15,021,877
I am developing a GUI with PyQt, to perform visual analysis of the data collected during some experiments. The GUI asks the user to indicate the directory where the data to be analyzed is located: ``` class ExperimentAnalyzer(QtGui.QMainWindow): ## other stuff here def loadExperiment(self): directory = QtGui.QFileDialog.getExistingDirectory(self, "Select Directory") ## load data from directory here ``` The GUI provides a ***play*** functionality, by means of which the user can see how experimental data changes over time. This is implemented through a **QTimer**: ``` def playOrPause(self): ## play if self.appStatus.timer is None: self.appStatus.timer = QtCore.QTimer(self) self.appStatus.timer.connect(self.appStatus.timer, QtCore.SIGNAL("timeout()"), self.nextFrame) self.appStatus.timer.start(40) ## pause else: self.appStatus.timer.stop() self.appStatus.timer = None ``` If I ***play*** the temporal sequence of data, then ***pause***, then try to change the directory to load data from a new experiment, I experience a **segmentation fault**. Using some debug prints, I found out that the application crashes when I call ``` QtGui.QFileDialog.getExistingDirectory(self, "Select Directory") ``` in the ***loadExperiment*** method. I'm pretty new to Qt and I think I'm not handling the timer properly. I'm using PyQt 4.9, Python 2.7.3 on Ubuntu 10.04. **Edit-1**: ----------- After Luke's answer, I went back to my code. Here's the ***nextFrame*** method, invoked every time the timer emits the ***timeout*** signal. It updates a QGraphicsScene element contained in the GUI: ``` def nextFrame(self): image = Image.open("<some jpg>") w, h = image.size imageQt = ImageQt.ImageQt(image) pixMap = QtGui.QPixmap.fromImage(imageQt) self.scene.clear() self.scene.addPixmap(pixMap) self.view.fitInView(QtCore.QRectF(0, 0, w, h), QtCore.Qt.KeepAspectRatio) ``` where the self.scene and the self.view objects have been previously instantiated in the GUI constructor as ``` self.view = QtGui.QGraphicsView(self) self.scene = QtGui.QGraphicsScene() self.view.setScene(self.scene) ``` I found out that commenting this line: ``` # self.scene.addPixmap(pixMap) ``` and repeating the same operations sequence reported above, the segmentation fault does not occur anymore. **Edit-2**: ----------- Running the application with gdb (with python-dbg), it turns out that the segmentation fault occurs after a call to QPainter::drawPixmap. ``` (gdb) bt #0 0xb6861f1d in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #1 0xb685d491 in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #2 0xb693bcd3 in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #3 0xb69390bc in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #4 0xb6945c77 in ?? () from /usr/lib/i386-linux-gnu/libQtGui.so.4 #5 0xb68bd424 in QPainter::drawPixmap(QPointF const&, QPixmap const&) () from /usr/lib/i386-linux-gnu/libQtGui.so.4 ``` Therefore, it's not a problem related to timer handling, as I believed in first instance. The segmentation fault happens because I'm doing something wrong with the pixMap.
2013/02/22
[ "https://Stackoverflow.com/questions/15021877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1759574/" ]
Try this : HTML ``` <a id="show" href="#">show</a> <div class="test" style="display: none;"> hey </div> ``` JS ``` $('a#show').click(function(event) { event.stopPropagation(); $('.test').toggle(); }); $('html').click(function() { $('.test').hide(); }); ```
Make variable sel `true`, if we click on the `div`. ``` if(sel) $(".stackExchange").slideDown(800); else $(".stackExchange").slideUp(800); ```
43,222,378
I'm working on my python script to extract multiple strings from a .csv file but I can't recover the Spanish characters (like á, é, í) after I open the file and read the lines. This is my code so far: ``` import csv list_text=[] with open(file, 'rb') as data: reader = csv.reader(data, delimiter='\t') for row in reader: print row[0] list_text.extend(row[0]) print list_text ``` And I get something like this: ``` 'Vivió el sueño, ESPAÑOL...' ['Vivi\xc3\xb3 el sue\xc3\xb1o, ESPA\xc3\x91OL...'] ``` I don't know why it prints it in the correct form but when I append it to the list is not correct. **Edited:** The problem is that I need to recover the characters because, after I read the file, the list has thousands of words in it and I don't need to print it I need to use regex to get rid of the punctuation, but this also deletes the backslash and the word is incomplete.
2017/04/05
[ "https://Stackoverflow.com/questions/43222378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7817760/" ]
When you print a list it shows all the cancelled characters, that way `\n` and other characters don't throw off the list display, so if you print the string it will work properly: ``` 'Vivi\xc3\xb3 el sue\xc3\xb1o, ESPA\xc3\x91OL...'.decode('utf-8') ```
1. use unicodecsv instead of csv , csv doesn't support well unicode 2. open the file with codecs, and 'utf-8' **see code below** ``` import unicodecsv as csv import codecs list_text=[] with codecs.open(file, 'rb','utf-8') as data: reader = csv.reader(data, delimiter='\t') for row in reader: print row[0] list_text.extend(row[0]) print list_text ```
43,222,378
I'm working on my python script to extract multiple strings from a .csv file but I can't recover the Spanish characters (like á, é, í) after I open the file and read the lines. This is my code so far: ``` import csv list_text=[] with open(file, 'rb') as data: reader = csv.reader(data, delimiter='\t') for row in reader: print row[0] list_text.extend(row[0]) print list_text ``` And I get something like this: ``` 'Vivió el sueño, ESPAÑOL...' ['Vivi\xc3\xb3 el sue\xc3\xb1o, ESPA\xc3\x91OL...'] ``` I don't know why it prints it in the correct form but when I append it to the list is not correct. **Edited:** The problem is that I need to recover the characters because, after I read the file, the list has thousands of words in it and I don't need to print it I need to use regex to get rid of the punctuation, but this also deletes the backslash and the word is incomplete.
2017/04/05
[ "https://Stackoverflow.com/questions/43222378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7817760/" ]
The python 2.x `csv` module doesn't support unicode and you did the right thing by opening the file in binary mode and parsing the utf-8 encoded strings instead of decoded unicode strings. Python 2 is kinda strange in that the `str` type (as opposed to the `unicode` type) holds either string or binary data. You got `'Vivi\xc3\xb3 el sue\xc3\xb1o, ESPA\xc3\x91OL...'` which is the binary utf-8 encoding of the unicode. We can decode it to get the unicode version... ``` >>> encoded_text = 'Vivi\xc3\xb3 el sue\xc3\xb1o, ESPA\xc3\x91OL...' >>> text = encoded_text.decode('utf-8') >>> print repr(text) u'Vivi\xf3 el sue\xf1o, ESPA\xd1OL...' >>> print text Vivió el sueño, ESPAÑOL... ``` ...but wait a second, the encoded text prints the same ``` >>> print encoded_text Vivió el sueño, ESPAÑOL... ``` what's up with that? That has everything to do with your display surface which is a utf-8 encoded terminal. In the first case (`print text`), `text` is a unicode string so python has to encode it before sending it to the terminal which sees the utf-8 encoded version. In the second case its just a regular string and python sent it without conversion... but it just so happens it was holding encoded text which the terminal decoded. Finally, when a string is in a list, python prints its `repr` representation, not its `str` value, as in ``` >>> print repr(encoded_text) 'Vivi\xc3\xb3 el sue\xc3\xb1o, ESPA\xc3\x91OL...' ``` To make things right, convert the cells in your rows to unicode after the csv module is done with them. ``` import csv list_text=[] with open(file, 'rb') as data: reader = csv.reader(data, delimiter='\t') for row in reader: row = [cell.decode('utf-8') for cell in row] print row[0] list_text.extend(row[0]) print list_text ```
When you print a list it shows all the cancelled characters, that way `\n` and other characters don't throw off the list display, so if you print the string it will work properly: ``` 'Vivi\xc3\xb3 el sue\xc3\xb1o, ESPA\xc3\x91OL...'.decode('utf-8') ```
43,222,378
I'm working on my python script to extract multiple strings from a .csv file but I can't recover the Spanish characters (like á, é, í) after I open the file and read the lines. This is my code so far: ``` import csv list_text=[] with open(file, 'rb') as data: reader = csv.reader(data, delimiter='\t') for row in reader: print row[0] list_text.extend(row[0]) print list_text ``` And I get something like this: ``` 'Vivió el sueño, ESPAÑOL...' ['Vivi\xc3\xb3 el sue\xc3\xb1o, ESPA\xc3\x91OL...'] ``` I don't know why it prints it in the correct form but when I append it to the list is not correct. **Edited:** The problem is that I need to recover the characters because, after I read the file, the list has thousands of words in it and I don't need to print it I need to use regex to get rid of the punctuation, but this also deletes the backslash and the word is incomplete.
2017/04/05
[ "https://Stackoverflow.com/questions/43222378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7817760/" ]
The python 2.x `csv` module doesn't support unicode and you did the right thing by opening the file in binary mode and parsing the utf-8 encoded strings instead of decoded unicode strings. Python 2 is kinda strange in that the `str` type (as opposed to the `unicode` type) holds either string or binary data. You got `'Vivi\xc3\xb3 el sue\xc3\xb1o, ESPA\xc3\x91OL...'` which is the binary utf-8 encoding of the unicode. We can decode it to get the unicode version... ``` >>> encoded_text = 'Vivi\xc3\xb3 el sue\xc3\xb1o, ESPA\xc3\x91OL...' >>> text = encoded_text.decode('utf-8') >>> print repr(text) u'Vivi\xf3 el sue\xf1o, ESPA\xd1OL...' >>> print text Vivió el sueño, ESPAÑOL... ``` ...but wait a second, the encoded text prints the same ``` >>> print encoded_text Vivió el sueño, ESPAÑOL... ``` what's up with that? That has everything to do with your display surface which is a utf-8 encoded terminal. In the first case (`print text`), `text` is a unicode string so python has to encode it before sending it to the terminal which sees the utf-8 encoded version. In the second case its just a regular string and python sent it without conversion... but it just so happens it was holding encoded text which the terminal decoded. Finally, when a string is in a list, python prints its `repr` representation, not its `str` value, as in ``` >>> print repr(encoded_text) 'Vivi\xc3\xb3 el sue\xc3\xb1o, ESPA\xc3\x91OL...' ``` To make things right, convert the cells in your rows to unicode after the csv module is done with them. ``` import csv list_text=[] with open(file, 'rb') as data: reader = csv.reader(data, delimiter='\t') for row in reader: row = [cell.decode('utf-8') for cell in row] print row[0] list_text.extend(row[0]) print list_text ```
1. use unicodecsv instead of csv , csv doesn't support well unicode 2. open the file with codecs, and 'utf-8' **see code below** ``` import unicodecsv as csv import codecs list_text=[] with codecs.open(file, 'rb','utf-8') as data: reader = csv.reader(data, delimiter='\t') for row in reader: print row[0] list_text.extend(row[0]) print list_text ```
4,673,166
I'm trying to use httplib to send credit card information to authorize.net. When i try to post the request, I get the following traceback: ``` File "./lib/cgi_app.py", line 139, in run res = method() File "/var/www/html/index.py", line 113, in ProcessRegistration conn.request("POST", "/gateway/transact.dll", mystring, headers) File "/usr/local/lib/python2.7/httplib.py", line 946, in request self._send_request(method, url, body, headers) File "/usr/local/lib/python2.7/httplib.py", line 987, in _send_request self.endheaders(body) File "/usr/local/lib/python2.7/httplib.py", line 940, in endheaders self._send_output(message_body) File "/usr/local/lib/python2.7/httplib.py", line 803, in _send_output self.send(msg) File "/usr/local/lib/python2.7/httplib.py", line 755, in send self.connect() File "/usr/local/lib/python2.7/httplib.py", line 1152, in connect self.timeout, self.source_address) File "/usr/local/lib/python2.7/socket.py", line 567, in create_connection raise error, msg gaierror: [Errno -2] Name or service not known ``` I build my request like so: ``` mystring = urllib.urlencode(cardHash) headers = {"Content-Type": "text/xml", "Content-Length": str(len(mystring))} conn = httplib.HTTPSConnection("secure.authorize.net:443", source_address=("myurl.com", 443)) conn.request("POST", "/gateway/transact.dll", mystring, headers) ``` to add another layer to this, it was working on our development server which has httplib 2.6 and without the source\_address parameter in httplib.HTTPSConnection. Any help is greatly appreciated. =========================================================== EDIT: I can run it from command line. Apparently this is some sort of permissions issue. Any ideas what permissions I would need to grant to which users to make this happen? Possibly Apache can't open the port?
2011/01/12
[ "https://Stackoverflow.com/questions/4673166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355689/" ]
> > gaierror: [Errno -2] Name or service not known > > > This error often indicates a failure of your DNS resolver. Does `ping secure.authorize.net` return successful replies from the same server that receives the gaierror? Does the hostname have a typo in it?
pass the port separately from the host: ``` conn = httplib.HTTPSConnection("secure.authorize.net", 443, ....) ```
4,673,166
I'm trying to use httplib to send credit card information to authorize.net. When i try to post the request, I get the following traceback: ``` File "./lib/cgi_app.py", line 139, in run res = method() File "/var/www/html/index.py", line 113, in ProcessRegistration conn.request("POST", "/gateway/transact.dll", mystring, headers) File "/usr/local/lib/python2.7/httplib.py", line 946, in request self._send_request(method, url, body, headers) File "/usr/local/lib/python2.7/httplib.py", line 987, in _send_request self.endheaders(body) File "/usr/local/lib/python2.7/httplib.py", line 940, in endheaders self._send_output(message_body) File "/usr/local/lib/python2.7/httplib.py", line 803, in _send_output self.send(msg) File "/usr/local/lib/python2.7/httplib.py", line 755, in send self.connect() File "/usr/local/lib/python2.7/httplib.py", line 1152, in connect self.timeout, self.source_address) File "/usr/local/lib/python2.7/socket.py", line 567, in create_connection raise error, msg gaierror: [Errno -2] Name or service not known ``` I build my request like so: ``` mystring = urllib.urlencode(cardHash) headers = {"Content-Type": "text/xml", "Content-Length": str(len(mystring))} conn = httplib.HTTPSConnection("secure.authorize.net:443", source_address=("myurl.com", 443)) conn.request("POST", "/gateway/transact.dll", mystring, headers) ``` to add another layer to this, it was working on our development server which has httplib 2.6 and without the source\_address parameter in httplib.HTTPSConnection. Any help is greatly appreciated. =========================================================== EDIT: I can run it from command line. Apparently this is some sort of permissions issue. Any ideas what permissions I would need to grant to which users to make this happen? Possibly Apache can't open the port?
2011/01/12
[ "https://Stackoverflow.com/questions/4673166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355689/" ]
The problem ultimately came down to the fact that selinux was stopping apache from getting that port. Disabling selinux fixed the problems. I had an issue later where i didn't have /var/www/.python-eggs/, so MySQLdb was hosing on import. But after a mkdir, it was fixed.
pass the port separately from the host: ``` conn = httplib.HTTPSConnection("secure.authorize.net", 443, ....) ```
4,673,166
I'm trying to use httplib to send credit card information to authorize.net. When i try to post the request, I get the following traceback: ``` File "./lib/cgi_app.py", line 139, in run res = method() File "/var/www/html/index.py", line 113, in ProcessRegistration conn.request("POST", "/gateway/transact.dll", mystring, headers) File "/usr/local/lib/python2.7/httplib.py", line 946, in request self._send_request(method, url, body, headers) File "/usr/local/lib/python2.7/httplib.py", line 987, in _send_request self.endheaders(body) File "/usr/local/lib/python2.7/httplib.py", line 940, in endheaders self._send_output(message_body) File "/usr/local/lib/python2.7/httplib.py", line 803, in _send_output self.send(msg) File "/usr/local/lib/python2.7/httplib.py", line 755, in send self.connect() File "/usr/local/lib/python2.7/httplib.py", line 1152, in connect self.timeout, self.source_address) File "/usr/local/lib/python2.7/socket.py", line 567, in create_connection raise error, msg gaierror: [Errno -2] Name or service not known ``` I build my request like so: ``` mystring = urllib.urlencode(cardHash) headers = {"Content-Type": "text/xml", "Content-Length": str(len(mystring))} conn = httplib.HTTPSConnection("secure.authorize.net:443", source_address=("myurl.com", 443)) conn.request("POST", "/gateway/transact.dll", mystring, headers) ``` to add another layer to this, it was working on our development server which has httplib 2.6 and without the source\_address parameter in httplib.HTTPSConnection. Any help is greatly appreciated. =========================================================== EDIT: I can run it from command line. Apparently this is some sort of permissions issue. Any ideas what permissions I would need to grant to which users to make this happen? Possibly Apache can't open the port?
2011/01/12
[ "https://Stackoverflow.com/questions/4673166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355689/" ]
As an (obvious) heads up, this same error can also be triggered by including the protocol in the host parameter. For example this code: ``` conn = httplib.HTTPConnection("http://secure.authorize.net", 80, ....) ``` will also cause the "gaierror: [Errno -2] Name or service not known" error, even if all your networking setup is correct.
pass the port separately from the host: ``` conn = httplib.HTTPSConnection("secure.authorize.net", 443, ....) ```
4,673,166
I'm trying to use httplib to send credit card information to authorize.net. When i try to post the request, I get the following traceback: ``` File "./lib/cgi_app.py", line 139, in run res = method() File "/var/www/html/index.py", line 113, in ProcessRegistration conn.request("POST", "/gateway/transact.dll", mystring, headers) File "/usr/local/lib/python2.7/httplib.py", line 946, in request self._send_request(method, url, body, headers) File "/usr/local/lib/python2.7/httplib.py", line 987, in _send_request self.endheaders(body) File "/usr/local/lib/python2.7/httplib.py", line 940, in endheaders self._send_output(message_body) File "/usr/local/lib/python2.7/httplib.py", line 803, in _send_output self.send(msg) File "/usr/local/lib/python2.7/httplib.py", line 755, in send self.connect() File "/usr/local/lib/python2.7/httplib.py", line 1152, in connect self.timeout, self.source_address) File "/usr/local/lib/python2.7/socket.py", line 567, in create_connection raise error, msg gaierror: [Errno -2] Name or service not known ``` I build my request like so: ``` mystring = urllib.urlencode(cardHash) headers = {"Content-Type": "text/xml", "Content-Length": str(len(mystring))} conn = httplib.HTTPSConnection("secure.authorize.net:443", source_address=("myurl.com", 443)) conn.request("POST", "/gateway/transact.dll", mystring, headers) ``` to add another layer to this, it was working on our development server which has httplib 2.6 and without the source\_address parameter in httplib.HTTPSConnection. Any help is greatly appreciated. =========================================================== EDIT: I can run it from command line. Apparently this is some sort of permissions issue. Any ideas what permissions I would need to grant to which users to make this happen? Possibly Apache can't open the port?
2011/01/12
[ "https://Stackoverflow.com/questions/4673166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355689/" ]
> > gaierror: [Errno -2] Name or service not known > > > This error often indicates a failure of your DNS resolver. Does `ping secure.authorize.net` return successful replies from the same server that receives the gaierror? Does the hostname have a typo in it?
The problem ultimately came down to the fact that selinux was stopping apache from getting that port. Disabling selinux fixed the problems. I had an issue later where i didn't have /var/www/.python-eggs/, so MySQLdb was hosing on import. But after a mkdir, it was fixed.
4,673,166
I'm trying to use httplib to send credit card information to authorize.net. When i try to post the request, I get the following traceback: ``` File "./lib/cgi_app.py", line 139, in run res = method() File "/var/www/html/index.py", line 113, in ProcessRegistration conn.request("POST", "/gateway/transact.dll", mystring, headers) File "/usr/local/lib/python2.7/httplib.py", line 946, in request self._send_request(method, url, body, headers) File "/usr/local/lib/python2.7/httplib.py", line 987, in _send_request self.endheaders(body) File "/usr/local/lib/python2.7/httplib.py", line 940, in endheaders self._send_output(message_body) File "/usr/local/lib/python2.7/httplib.py", line 803, in _send_output self.send(msg) File "/usr/local/lib/python2.7/httplib.py", line 755, in send self.connect() File "/usr/local/lib/python2.7/httplib.py", line 1152, in connect self.timeout, self.source_address) File "/usr/local/lib/python2.7/socket.py", line 567, in create_connection raise error, msg gaierror: [Errno -2] Name or service not known ``` I build my request like so: ``` mystring = urllib.urlencode(cardHash) headers = {"Content-Type": "text/xml", "Content-Length": str(len(mystring))} conn = httplib.HTTPSConnection("secure.authorize.net:443", source_address=("myurl.com", 443)) conn.request("POST", "/gateway/transact.dll", mystring, headers) ``` to add another layer to this, it was working on our development server which has httplib 2.6 and without the source\_address parameter in httplib.HTTPSConnection. Any help is greatly appreciated. =========================================================== EDIT: I can run it from command line. Apparently this is some sort of permissions issue. Any ideas what permissions I would need to grant to which users to make this happen? Possibly Apache can't open the port?
2011/01/12
[ "https://Stackoverflow.com/questions/4673166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355689/" ]
As an (obvious) heads up, this same error can also be triggered by including the protocol in the host parameter. For example this code: ``` conn = httplib.HTTPConnection("http://secure.authorize.net", 80, ....) ``` will also cause the "gaierror: [Errno -2] Name or service not known" error, even if all your networking setup is correct.
> > gaierror: [Errno -2] Name or service not known > > > This error often indicates a failure of your DNS resolver. Does `ping secure.authorize.net` return successful replies from the same server that receives the gaierror? Does the hostname have a typo in it?
4,673,166
I'm trying to use httplib to send credit card information to authorize.net. When i try to post the request, I get the following traceback: ``` File "./lib/cgi_app.py", line 139, in run res = method() File "/var/www/html/index.py", line 113, in ProcessRegistration conn.request("POST", "/gateway/transact.dll", mystring, headers) File "/usr/local/lib/python2.7/httplib.py", line 946, in request self._send_request(method, url, body, headers) File "/usr/local/lib/python2.7/httplib.py", line 987, in _send_request self.endheaders(body) File "/usr/local/lib/python2.7/httplib.py", line 940, in endheaders self._send_output(message_body) File "/usr/local/lib/python2.7/httplib.py", line 803, in _send_output self.send(msg) File "/usr/local/lib/python2.7/httplib.py", line 755, in send self.connect() File "/usr/local/lib/python2.7/httplib.py", line 1152, in connect self.timeout, self.source_address) File "/usr/local/lib/python2.7/socket.py", line 567, in create_connection raise error, msg gaierror: [Errno -2] Name or service not known ``` I build my request like so: ``` mystring = urllib.urlencode(cardHash) headers = {"Content-Type": "text/xml", "Content-Length": str(len(mystring))} conn = httplib.HTTPSConnection("secure.authorize.net:443", source_address=("myurl.com", 443)) conn.request("POST", "/gateway/transact.dll", mystring, headers) ``` to add another layer to this, it was working on our development server which has httplib 2.6 and without the source\_address parameter in httplib.HTTPSConnection. Any help is greatly appreciated. =========================================================== EDIT: I can run it from command line. Apparently this is some sort of permissions issue. Any ideas what permissions I would need to grant to which users to make this happen? Possibly Apache can't open the port?
2011/01/12
[ "https://Stackoverflow.com/questions/4673166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355689/" ]
As an (obvious) heads up, this same error can also be triggered by including the protocol in the host parameter. For example this code: ``` conn = httplib.HTTPConnection("http://secure.authorize.net", 80, ....) ``` will also cause the "gaierror: [Errno -2] Name or service not known" error, even if all your networking setup is correct.
The problem ultimately came down to the fact that selinux was stopping apache from getting that port. Disabling selinux fixed the problems. I had an issue later where i didn't have /var/www/.python-eggs/, so MySQLdb was hosing on import. But after a mkdir, it was fixed.
63,587,626
I am receiving the following download error when I attempt to install Jupyter Notebook on Windows: ``` ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: 'C:\\Users\\*redacted*\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python38\\site-packages\\jedi\\third_party\\django-stubs\\django-stubs\\contrib\\contenttypes\\management\\commands\\remove_stale_contenttypes.pyi' ``` I located the `commands` folder and the file `remove_stale_contenttypes.pyi` was not present. I did a file search for my CPU and the file was not found in another location. I have never used python, pip, or jupyter before. I am attempting to install them in preparation for a class.
2020/08/25
[ "https://Stackoverflow.com/questions/63587626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14166558/" ]
Try uninstalling virtualenv or pipenv (whichever you are using) and then reinstalling. If this doesn't work try installing conda. There are two versions of it: Anaconda Miniconda I would recommend going with miniconda as it is a lightweight installation but does not have a GUI. Here is the [link](https://docs.conda.io/en/latest/miniconda.html) to install it. Afterwards to create a virtual environment do this: Go to the conda terminal or cmd and type in `conda create --name myenv`(and change the name of the env to whatever you like). This should create your environment. Afterwards to activate it, type in `conda activate name` (Name is again what you put up there) Thats it. You have now created a conda env. So afterwards, whenever you want to access this enviornment again, use the activate command. As for installing jupyter notebook, first activate your env and the run this: ``` conda install -c conda-forge notebook ``` This should install jupyter notebook in that environment. To access that jupyter notebook again, always activate the enviornment and then type in `jupyter notebook`. If this seems a bit too much for you, you should actually have a program named jupyter notebook(env name) in your computer after you successfully installed jupyter. Just click on that and it will handle everything for you. Please let me know if you have trouble doing this.
The easiest way to setup Jupyter Notebook is using pip if you do not require conda. Since you are new to python, first create a new virtual environment using virtualenv. Installing pip (Ignore if already installed): Download get-pip.py for Windows and run `python get-pip.py` Installing virtualenv: `pip install virtualenv` Creating a new virtual environment: `virtualenv your_env_name` Activate Virtualenv: `your_env_name\Scripts\activate` Installing Jupyter Notebooks: `pip install notebook` You can launch the notebook server using: `jupyter notebook`
63,587,626
I am receiving the following download error when I attempt to install Jupyter Notebook on Windows: ``` ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: 'C:\\Users\\*redacted*\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python38\\site-packages\\jedi\\third_party\\django-stubs\\django-stubs\\contrib\\contenttypes\\management\\commands\\remove_stale_contenttypes.pyi' ``` I located the `commands` folder and the file `remove_stale_contenttypes.pyi` was not present. I did a file search for my CPU and the file was not found in another location. I have never used python, pip, or jupyter before. I am attempting to install them in preparation for a class.
2020/08/25
[ "https://Stackoverflow.com/questions/63587626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14166558/" ]
Make sure the maximum file path length limitation is turned off on your windows machine. In the Registry Editor, use the left sidebar to navigate to the following key: HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem On the right, find a value named LongPathsEnabled and double-click it. If you don’t see the value listed, you’ll need to create it by right-clicking the FileSystem key, choosing New > DWORD (32-bit) Value, and then naming the new value LongPathsEnabled. In the value’s properties window, change the value from 0 to 1 in the “Value data” box, and then click OK. Here is a link to an article describing how to do this: <https://www.howtogeek.com/266621/how-to-make-windows-10-accept-file-paths-over-260-characters/>
Try uninstalling virtualenv or pipenv (whichever you are using) and then reinstalling. If this doesn't work try installing conda. There are two versions of it: Anaconda Miniconda I would recommend going with miniconda as it is a lightweight installation but does not have a GUI. Here is the [link](https://docs.conda.io/en/latest/miniconda.html) to install it. Afterwards to create a virtual environment do this: Go to the conda terminal or cmd and type in `conda create --name myenv`(and change the name of the env to whatever you like). This should create your environment. Afterwards to activate it, type in `conda activate name` (Name is again what you put up there) Thats it. You have now created a conda env. So afterwards, whenever you want to access this enviornment again, use the activate command. As for installing jupyter notebook, first activate your env and the run this: ``` conda install -c conda-forge notebook ``` This should install jupyter notebook in that environment. To access that jupyter notebook again, always activate the enviornment and then type in `jupyter notebook`. If this seems a bit too much for you, you should actually have a program named jupyter notebook(env name) in your computer after you successfully installed jupyter. Just click on that and it will handle everything for you. Please let me know if you have trouble doing this.
63,587,626
I am receiving the following download error when I attempt to install Jupyter Notebook on Windows: ``` ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: 'C:\\Users\\*redacted*\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python38\\site-packages\\jedi\\third_party\\django-stubs\\django-stubs\\contrib\\contenttypes\\management\\commands\\remove_stale_contenttypes.pyi' ``` I located the `commands` folder and the file `remove_stale_contenttypes.pyi` was not present. I did a file search for my CPU and the file was not found in another location. I have never used python, pip, or jupyter before. I am attempting to install them in preparation for a class.
2020/08/25
[ "https://Stackoverflow.com/questions/63587626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14166558/" ]
Make sure the maximum file path length limitation is turned off on your windows machine. In the Registry Editor, use the left sidebar to navigate to the following key: HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem On the right, find a value named LongPathsEnabled and double-click it. If you don’t see the value listed, you’ll need to create it by right-clicking the FileSystem key, choosing New > DWORD (32-bit) Value, and then naming the new value LongPathsEnabled. In the value’s properties window, change the value from 0 to 1 in the “Value data” box, and then click OK. Here is a link to an article describing how to do this: <https://www.howtogeek.com/266621/how-to-make-windows-10-accept-file-paths-over-260-characters/>
The easiest way to setup Jupyter Notebook is using pip if you do not require conda. Since you are new to python, first create a new virtual environment using virtualenv. Installing pip (Ignore if already installed): Download get-pip.py for Windows and run `python get-pip.py` Installing virtualenv: `pip install virtualenv` Creating a new virtual environment: `virtualenv your_env_name` Activate Virtualenv: `your_env_name\Scripts\activate` Installing Jupyter Notebooks: `pip install notebook` You can launch the notebook server using: `jupyter notebook`
49,715,583
I have this python code solving knapsack problem using dynamic programming. this function returns the total cost of best subset but I want it to return the elements of best subset . can anybody help me with this? ``` def knapSack(W, wt, val, n): K = [[0 for x in range(W + 1)] for x in range(n + 1)] # Build table K[][] in bottom up manner for i in range(n + 1): for w in range(W + 1): if i == 0 or w == 0: K[i][w] = 0 elif wt[i - 1] <= w: K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1] [w]) else: K[i][w] = K[i - 1][w] return K[n][W] val = [40, 100, 120,140] wt = [1, 2, 3,4] W = 4 n = len(val) print(knapSack(W, wt, val, n)) ```
2018/04/08
[ "https://Stackoverflow.com/questions/49715583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8238009/" ]
What you can do is instead of returning only K[n][W], return K Then iterate K as : ``` elements=list() dp=K w = W i = n while (i> 0): if dp[w][i] - dp[w - wt(i)][i-1] == val(i): #the element 'i' is in the knapsack element.append(i) i = i-1 //only in 0-1 knapsack w -=wt(i) else: i = i-1 ``` The idea is you reverse iterate the K matrix to determine which elements' values were added to get to the optimum K[W][n] value.
You can add this code to the end of your function to work your way back through the items added: ``` res = K[n][W] print(res) w = W for i in range(n, 0, -1): if res <= 0: break if res == K[i - 1][w]: continue else: print(wt[i - 1]) res = res - val[i - 1] w = w - wt[i - 1] ```
33,008,401
How to define an attribute in a Python 3 enum class that is NOT an enum value? ``` class Color(Enum): red = 0 blue = 1 violet = 2 foo = 'this is a regular attribute' bar = 55 # this is also a regular attribute ``` But this seems to fail for me. It seems that Color tries to include foo and bar as part of its enum values. EDIT: Lest you think I'm not using Enum in a way that's intended... For example, take the official Python documentation's example enum class Planet (docs.python.org/3/library/enum.html#planet). Note that they define the gravitational constant G within the surface\_gravity() method. But this is weird code. A normal programmer would say, set that constant G once, outside the function. But if I try to move G out (but not to global scope, just class scope), then I run into the issue I'm asking about here.
2015/10/08
[ "https://Stackoverflow.com/questions/33008401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5421703/" ]
The point of the `Enum` type is to define enum values, so non-enum values are theoretically out of scope for this type. For constants, you should consider moving them out of the type anyway: They are likely not directly related to the enum values (but rather some logic that builds on those), and also should be a mutable property of the type. Usually, you would just create a constant at module level. If you really need something on the type, then you could add it as a class method: ``` class Color(Enum): red = 0 blue = 1 violet = 2 bar = 55 @classmethod def foo (cls): return 'this is a not really an attribute…' ``` And using the `classproperty` descriptor from [this answer](https://stackoverflow.com/a/5191224/216074), you can also turn this into a property at class level which you can access as if it was a normal attribute: ``` class Color(enum.Enum): red = 0 blue = 1 violet = 2 bar = 55 @classproperty def foo (cls): return 'this is a almost a real attribute' ``` ``` >>> Color.foo 'this is a almost a real attribute' >>> list(Color) [<Color.red: 0>, <Color.blue: 1>, <Color.violet: 2>, <Color.bar: 55>] ```
When building an `enum.Enum` class, **all** regular attributes become members of the enumeration. A different type of value does not make a difference. By regular attributes I mean all objects that are not descriptors (like functions are) and excluded names (using single underscore names, see the [*Allowed members and attributes of enumerations* section](https://docs.python.org/3/library/enum.html#allowed-members-and-attributes-of-enumerations)). If you need additional attributes on the final `enum.Enum` object, add attributes *afterwards*: ``` class Color(Enum): red = 0 blue = 1 violet = 2 Color.foo = 'this is a regular attribute' Color.bar = 55 ``` Demo: ``` >>> from enum import Enum >>> class Color(Enum): ... red = 0 ... blue = 1 ... violet = 2 ... >>> Color.foo = 'this is a regular attribute' >>> Color.bar = 55 >>> Color.foo 'this is a regular attribute' >>> Color.bar 55 >>> Color.red <Color.red: 0> >>> list(Color) [<Color.red: 0>, <Color.blue: 1>, <Color.violet: 2>] ```
60,998,188
I'm trying to write a python 3 code that prints out square matrix from user input. In addition the first row of this matrix must be filled by numbers from 1,n, the second row is the multiplication of the first row by 2, the third by 3, etc., until n-th row, which is created by the first row being multiplied by n. I was able to get my code to print out the square matrix but I do not understand how can I modified it so that it prints according to the earlier description. So, for example for n=3 I should have matrix : 1 2 3 (1st row), 2 4 6 (2nd row) and 3 6 9 (3rd row) but instead I get 1 2 3 (1st row), 4 5 6 (2nd row) and 7 8 9 (3rd row). My code: ``` n = int(input("Enter dimensions of matrix :")) m = n x = 1 columns = [] for row in range(n): inner_column = [] for col in range(m): inner_column.append(x) x = x + 1 columns.append(inner_column) for inner_column in columns: print(' '.join(map(str, inner_column))) ```
2020/04/02
[ "https://Stackoverflow.com/questions/60998188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13111470/" ]
You can sore function in a List. ``` public class NeutralFactory: NPCFactory { private List<Func<int, Creature>> humanoids = new List<Func<int, Creature>> { hp=> new Dwarf(hp), hp=> new Fairy(hp), hp=> new Elf(hp), hp=> new Troll(hp), hp=> new Orc(hp) }; private Random random = new Random(); public Creature CreateHumanoid(int hp = 100) { int index = random.Next(humanoids.Count); return humanoids[index](hp); } } ```
To avoid having to write creation functions for each class, you can use `Activator.CreateInstance`: ```cs using System; using System.Collections.Generic; namespace so60998181 { public class Creature { public int hp; public Creature() { this.hp = 100; } public Creature(int hp) { this.hp = hp; } public override string ToString() { return String.Format("{0}, {1} hp", GetType().Name, hp); } } public class Dwarf : Creature { public Dwarf(int hp) : base(hp) { } } public class Fairy : Creature { public Fairy(int hp) : base(hp / 3) { } } public class Orc : Creature { public Orc(int hp) : base(hp * 4) { } } class Program { private static List<Type> humanoids = new List<Type> { typeof(Dwarf), typeof(Fairy), typeof(Orc) }; private static Random rng = new Random(); private static Creature CreateHumanoid(int hp = 100) { int index = rng.Next(humanoids.Count); var params = new object[] { hp }; return Activator.CreateInstance(t, humanoids[index], null, params, null) as Creature; } static void Main(string[] args) { for (var i = 0; i < 10; i++) { Console.WriteLine(CreateHumanoid(i * 10)); } } } } ``` This outputs e.g. ``` Fairy, 0 hp Orc, 40 hp Fairy, 6 hp Orc, 120 hp Fairy, 13 hp Orc, 200 hp Fairy, 20 hp Fairy, 23 hp Fairy, 26 hp Fairy, 30 hp ``` (poor fairy #1)
60,998,188
I'm trying to write a python 3 code that prints out square matrix from user input. In addition the first row of this matrix must be filled by numbers from 1,n, the second row is the multiplication of the first row by 2, the third by 3, etc., until n-th row, which is created by the first row being multiplied by n. I was able to get my code to print out the square matrix but I do not understand how can I modified it so that it prints according to the earlier description. So, for example for n=3 I should have matrix : 1 2 3 (1st row), 2 4 6 (2nd row) and 3 6 9 (3rd row) but instead I get 1 2 3 (1st row), 4 5 6 (2nd row) and 7 8 9 (3rd row). My code: ``` n = int(input("Enter dimensions of matrix :")) m = n x = 1 columns = [] for row in range(n): inner_column = [] for col in range(m): inner_column.append(x) x = x + 1 columns.append(inner_column) for inner_column in columns: print(' '.join(map(str, inner_column))) ```
2020/04/02
[ "https://Stackoverflow.com/questions/60998188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13111470/" ]
You can sore function in a List. ``` public class NeutralFactory: NPCFactory { private List<Func<int, Creature>> humanoids = new List<Func<int, Creature>> { hp=> new Dwarf(hp), hp=> new Fairy(hp), hp=> new Elf(hp), hp=> new Troll(hp), hp=> new Orc(hp) }; private Random random = new Random(); public Creature CreateHumanoid(int hp = 100) { int index = random.Next(humanoids.Count); return humanoids[index](hp); } } ```
You can use the method `GetConstructor(type[])` to get the constructor which is most likely a `Func` object. If you use the `Invoke` method you get a object back. Last you have to parse it as Creature to return it. ``` public Creature CreateHumanoid( int hp = 100 ) { int index = random.Next( humanoids.Count ); Type t = humanoids[index]; return (Creature) t.GetConstructor( new Type[] { typeof( int ) } ).Invoke( new object[] { hp } ); } ```
60,998,188
I'm trying to write a python 3 code that prints out square matrix from user input. In addition the first row of this matrix must be filled by numbers from 1,n, the second row is the multiplication of the first row by 2, the third by 3, etc., until n-th row, which is created by the first row being multiplied by n. I was able to get my code to print out the square matrix but I do not understand how can I modified it so that it prints according to the earlier description. So, for example for n=3 I should have matrix : 1 2 3 (1st row), 2 4 6 (2nd row) and 3 6 9 (3rd row) but instead I get 1 2 3 (1st row), 4 5 6 (2nd row) and 7 8 9 (3rd row). My code: ``` n = int(input("Enter dimensions of matrix :")) m = n x = 1 columns = [] for row in range(n): inner_column = [] for col in range(m): inner_column.append(x) x = x + 1 columns.append(inner_column) for inner_column in columns: print(' '.join(map(str, inner_column))) ```
2020/04/02
[ "https://Stackoverflow.com/questions/60998188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13111470/" ]
You can sore function in a List. ``` public class NeutralFactory: NPCFactory { private List<Func<int, Creature>> humanoids = new List<Func<int, Creature>> { hp=> new Dwarf(hp), hp=> new Fairy(hp), hp=> new Elf(hp), hp=> new Troll(hp), hp=> new Orc(hp) }; private Random random = new Random(); public Creature CreateHumanoid(int hp = 100) { int index = random.Next(humanoids.Count); return humanoids[index](hp); } } ```
Sounds like a good case for an abstract class. If you don't ever want someone to create just an instance of 'Creature', and instead they should always create a version of a creature, then you want an abstract class. So you could do something like this: ``` public class NeutralFactory : NPCFactory { private Random random = new Random(); private List<Func<int, Creature>> humanoids = new List<Func<int, Creature>> { hp=> new Dwarf(hp), hp=> new Fairy(hp), hp=> new Elf(hp), hp=> new Troll(hp), hp=> new Orc(hp) }; public Creature CreateHumanoid(int hp) { int index = random.Next(humanoids.Count); return humanoids[index](hp); } } public abstract class Creature { public int hp { get; set; } public Creature(int hp) { this.hp = hp; } } ``` You'd then use it like this: ``` public class Orc : Creature { public Orc(int hp) : base(hp) { } } ``` **UPDATE** Added 'humanoids' outside of the create method to avoid creating a list of objects every time. Using a list of Func was taken from OxQ, though the purpose of using an abstract class like this is to ensure someone can't just instantiate 'Creature' on its own and you can use it to create base functionality as well.
60,998,188
I'm trying to write a python 3 code that prints out square matrix from user input. In addition the first row of this matrix must be filled by numbers from 1,n, the second row is the multiplication of the first row by 2, the third by 3, etc., until n-th row, which is created by the first row being multiplied by n. I was able to get my code to print out the square matrix but I do not understand how can I modified it so that it prints according to the earlier description. So, for example for n=3 I should have matrix : 1 2 3 (1st row), 2 4 6 (2nd row) and 3 6 9 (3rd row) but instead I get 1 2 3 (1st row), 4 5 6 (2nd row) and 7 8 9 (3rd row). My code: ``` n = int(input("Enter dimensions of matrix :")) m = n x = 1 columns = [] for row in range(n): inner_column = [] for col in range(m): inner_column.append(x) x = x + 1 columns.append(inner_column) for inner_column in columns: print(' '.join(map(str, inner_column))) ```
2020/04/02
[ "https://Stackoverflow.com/questions/60998188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13111470/" ]
You can use the method `GetConstructor(type[])` to get the constructor which is most likely a `Func` object. If you use the `Invoke` method you get a object back. Last you have to parse it as Creature to return it. ``` public Creature CreateHumanoid( int hp = 100 ) { int index = random.Next( humanoids.Count ); Type t = humanoids[index]; return (Creature) t.GetConstructor( new Type[] { typeof( int ) } ).Invoke( new object[] { hp } ); } ```
To avoid having to write creation functions for each class, you can use `Activator.CreateInstance`: ```cs using System; using System.Collections.Generic; namespace so60998181 { public class Creature { public int hp; public Creature() { this.hp = 100; } public Creature(int hp) { this.hp = hp; } public override string ToString() { return String.Format("{0}, {1} hp", GetType().Name, hp); } } public class Dwarf : Creature { public Dwarf(int hp) : base(hp) { } } public class Fairy : Creature { public Fairy(int hp) : base(hp / 3) { } } public class Orc : Creature { public Orc(int hp) : base(hp * 4) { } } class Program { private static List<Type> humanoids = new List<Type> { typeof(Dwarf), typeof(Fairy), typeof(Orc) }; private static Random rng = new Random(); private static Creature CreateHumanoid(int hp = 100) { int index = rng.Next(humanoids.Count); var params = new object[] { hp }; return Activator.CreateInstance(t, humanoids[index], null, params, null) as Creature; } static void Main(string[] args) { for (var i = 0; i < 10; i++) { Console.WriteLine(CreateHumanoid(i * 10)); } } } } ``` This outputs e.g. ``` Fairy, 0 hp Orc, 40 hp Fairy, 6 hp Orc, 120 hp Fairy, 13 hp Orc, 200 hp Fairy, 20 hp Fairy, 23 hp Fairy, 26 hp Fairy, 30 hp ``` (poor fairy #1)
60,998,188
I'm trying to write a python 3 code that prints out square matrix from user input. In addition the first row of this matrix must be filled by numbers from 1,n, the second row is the multiplication of the first row by 2, the third by 3, etc., until n-th row, which is created by the first row being multiplied by n. I was able to get my code to print out the square matrix but I do not understand how can I modified it so that it prints according to the earlier description. So, for example for n=3 I should have matrix : 1 2 3 (1st row), 2 4 6 (2nd row) and 3 6 9 (3rd row) but instead I get 1 2 3 (1st row), 4 5 6 (2nd row) and 7 8 9 (3rd row). My code: ``` n = int(input("Enter dimensions of matrix :")) m = n x = 1 columns = [] for row in range(n): inner_column = [] for col in range(m): inner_column.append(x) x = x + 1 columns.append(inner_column) for inner_column in columns: print(' '.join(map(str, inner_column))) ```
2020/04/02
[ "https://Stackoverflow.com/questions/60998188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13111470/" ]
You can use the method `GetConstructor(type[])` to get the constructor which is most likely a `Func` object. If you use the `Invoke` method you get a object back. Last you have to parse it as Creature to return it. ``` public Creature CreateHumanoid( int hp = 100 ) { int index = random.Next( humanoids.Count ); Type t = humanoids[index]; return (Creature) t.GetConstructor( new Type[] { typeof( int ) } ).Invoke( new object[] { hp } ); } ```
Sounds like a good case for an abstract class. If you don't ever want someone to create just an instance of 'Creature', and instead they should always create a version of a creature, then you want an abstract class. So you could do something like this: ``` public class NeutralFactory : NPCFactory { private Random random = new Random(); private List<Func<int, Creature>> humanoids = new List<Func<int, Creature>> { hp=> new Dwarf(hp), hp=> new Fairy(hp), hp=> new Elf(hp), hp=> new Troll(hp), hp=> new Orc(hp) }; public Creature CreateHumanoid(int hp) { int index = random.Next(humanoids.Count); return humanoids[index](hp); } } public abstract class Creature { public int hp { get; set; } public Creature(int hp) { this.hp = hp; } } ``` You'd then use it like this: ``` public class Orc : Creature { public Orc(int hp) : base(hp) { } } ``` **UPDATE** Added 'humanoids' outside of the create method to avoid creating a list of objects every time. Using a list of Func was taken from OxQ, though the purpose of using an abstract class like this is to ensure someone can't just instantiate 'Creature' on its own and you can use it to create base functionality as well.
60,579,544
I have a frontend, which is hosted via Firebase. The code uses Firebase authentication and retrieves the token via `user.getIdToken()`. According to answers to similar questions that's the way to go. The backend is written in Python, expects the token and verifies it using the firebase\_admin SDK. On my local machine, I set `FIREBASE_CONFIG` to the path to `firebase-auth.json` that I exported from my project. Everything works as expected. Now I deployed my backend via Google AppEngine. Here I configure `FIREBASE_CONFIG` as JSON string in the app.yaml. The code looks like this: ``` runtime: python37 env_variables: FIREBASE_CONFIG: '{ "type": "service_account", "project_id": "[firebase-project-name]", ... ``` The backend logs the value of `FIREBASE_CONFIG` at startup. In the logs I can see the JSON string is there and `{` is the first character. So everything looks good to me. But if I retrieve the token from the client and try to validate it (same code, that is working locally) it get this error: > > Firebase ID token has incorrect "aud" (audience) claim. Expected > "[backend-appengine-project-name]" but got "[firebase-project-name]". Make sure the ID token > comes from the same Firebase project as the service account used to > authenticate this SDK. > > > Can somebody explain, what I'm missing and how to solve it?
2020/03/07
[ "https://Stackoverflow.com/questions/60579544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110963/" ]
The error message makes it sound like the user of your client app is signed into a different Firebase project than your backend is working with. Taking the error message literally, the client is using "backend-appengine-project-name", but your backend is using "firebase-project-name". Make sure they are both configured to use the same project using the same project ID.
``` final GoogleSignInAccount googleUser = await _googleSignIn.signIn(); final GoogleSignInAuthentication googleAuth = await googleUser.authentication; final AuthCredential credential = GoogleAuthProvider.getCredential( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, ); final FirebaseUser user = (await _auth.signInWithCredential(credential)).user; IdTokenResult idTokenResult = await user.getIdToken(refresh: true); print("userIdToken:" + idTokenResult.token); ```
44,669,963
I'm only starting getting into a python from #C and I have this question that I wasn't able to find an answer to, maybe I wasn't able to form a question right I need this to create two lists when using:**load(positives)** and **load(negatives)**, positives is a path to the file. From #C I'm used to use this kind of structure for not copy the same code again just with another variable, eg. what if I would need 5 lists. With this code i'm only able to access the self.dictionary variable but in no way self.positives and self.negatives I get error AttributeError: 'Analyzer' object has no attribute 'positives' at line 'for p in self.positives:' MAIN QUESTION IS: how to make self.dictionary = [] to create list variables from the argument name - self.positives and self.negatives which i need later in code --- ``` def load(self, dictionary): i = 0 self.dictionary = [] with open(dictionary) as lines: for line in lines: #some more code self.dictionary.append(0) self.dictionary[i] = line i+=1 #later in code for p in self.positives: if text == p: score += 1 for p in self.negatives: if text == p: score -= 1 #structure of a program: class Analyzer(): def load() def init() load(positives) load(negatives) def analyze() for p in self.positives ```
2017/06/21
[ "https://Stackoverflow.com/questions/44669963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8192419/" ]
Integration with Spring and other frameworks available in Intellij IDEA Ultimate, but you're using Community Edition version which supports mainly Java Core features so there's no inspection capable of determining whether or not the field is assigned.
In recent versions of CE you can suppress these when @Autowired annotation is present, by using the light bulb (I'm using version 2022.2)
33,169,619
Having this: ``` a = 12 b = [1, 2, 3] ``` What is the most pythonic way to convert it into this?: ``` [12, 1, 12, 2, 12, 3] ```
2015/10/16
[ "https://Stackoverflow.com/questions/33169619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1468388/" ]
If you want to alternate between `a` and elements of `b`. You can use [`itertools.cycle`](https://docs.python.org/2/library/itertools.html#itertools.cycle) and `zip` , Example - ``` >>> a = 12 >>> b = [1, 2, 3] >>> from itertools import cycle >>> [i for item in zip(cycle([a]),b) for i in item] [12, 1, 12, 2, 12, 3] ```
You can use `itertools.repeat` to create an iterable with the length of `b` then use `zip` to put its item alongside the items of `a` and at last use `chain.from_iterable` function to concatenate the pairs: ``` >>> from itertools import repeat,chain >>> list(chain.from_iterable(zip(repeat(a,len(b)),b))) [12, 1, 12, 2, 12, 3] ``` Also without `itertools` you can use following trick : ``` >>> it=iter(b) >>> [next(it) if i%2==0 else a for i in range(len(b)*2)] [1, 12, 2, 12, 3, 12] ```
33,169,619
Having this: ``` a = 12 b = [1, 2, 3] ``` What is the most pythonic way to convert it into this?: ``` [12, 1, 12, 2, 12, 3] ```
2015/10/16
[ "https://Stackoverflow.com/questions/33169619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1468388/" ]
If you want to alternate between `a` and elements of `b`. You can use [`itertools.cycle`](https://docs.python.org/2/library/itertools.html#itertools.cycle) and `zip` , Example - ``` >>> a = 12 >>> b = [1, 2, 3] >>> from itertools import cycle >>> [i for item in zip(cycle([a]),b) for i in item] [12, 1, 12, 2, 12, 3] ```
``` import itertools as it # fillvalue, which is **a** in this case, will be zipped in tuples with, # elements of b as long as the length of b permits. # chain.from_iterable will then flatten the tuple list into a single list list(it.chain.from_iterable(zip_longest([], b, fillvalue=a))) [12, 1, 12, 2, 12, 3] ```
33,169,619
Having this: ``` a = 12 b = [1, 2, 3] ``` What is the most pythonic way to convert it into this?: ``` [12, 1, 12, 2, 12, 3] ```
2015/10/16
[ "https://Stackoverflow.com/questions/33169619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1468388/" ]
try this: ``` >>> a 12 >>> b [1, 2, 3] >>> reduce(lambda x,y:x+y,[[a] + [x] for x in b]) [12, 1, 12, 2, 12, 3] ```
You can use `itertools.repeat` to create an iterable with the length of `b` then use `zip` to put its item alongside the items of `a` and at last use `chain.from_iterable` function to concatenate the pairs: ``` >>> from itertools import repeat,chain >>> list(chain.from_iterable(zip(repeat(a,len(b)),b))) [12, 1, 12, 2, 12, 3] ``` Also without `itertools` you can use following trick : ``` >>> it=iter(b) >>> [next(it) if i%2==0 else a for i in range(len(b)*2)] [1, 12, 2, 12, 3, 12] ```
33,169,619
Having this: ``` a = 12 b = [1, 2, 3] ``` What is the most pythonic way to convert it into this?: ``` [12, 1, 12, 2, 12, 3] ```
2015/10/16
[ "https://Stackoverflow.com/questions/33169619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1468388/" ]
You can use `itertools.repeat` to create an iterable with the length of `b` then use `zip` to put its item alongside the items of `a` and at last use `chain.from_iterable` function to concatenate the pairs: ``` >>> from itertools import repeat,chain >>> list(chain.from_iterable(zip(repeat(a,len(b)),b))) [12, 1, 12, 2, 12, 3] ``` Also without `itertools` you can use following trick : ``` >>> it=iter(b) >>> [next(it) if i%2==0 else a for i in range(len(b)*2)] [1, 12, 2, 12, 3, 12] ```
``` import itertools as it # fillvalue, which is **a** in this case, will be zipped in tuples with, # elements of b as long as the length of b permits. # chain.from_iterable will then flatten the tuple list into a single list list(it.chain.from_iterable(zip_longest([], b, fillvalue=a))) [12, 1, 12, 2, 12, 3] ```
33,169,619
Having this: ``` a = 12 b = [1, 2, 3] ``` What is the most pythonic way to convert it into this?: ``` [12, 1, 12, 2, 12, 3] ```
2015/10/16
[ "https://Stackoverflow.com/questions/33169619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1468388/" ]
try this: ``` >>> a 12 >>> b [1, 2, 3] >>> reduce(lambda x,y:x+y,[[a] + [x] for x in b]) [12, 1, 12, 2, 12, 3] ```
``` import itertools as it # fillvalue, which is **a** in this case, will be zipped in tuples with, # elements of b as long as the length of b permits. # chain.from_iterable will then flatten the tuple list into a single list list(it.chain.from_iterable(zip_longest([], b, fillvalue=a))) [12, 1, 12, 2, 12, 3] ```
52,821,996
How to do early stopping in lstm. I am using python tensorflow but not keras. I would appreciate if you can provide a sample python code. Regards
2018/10/15
[ "https://Stackoverflow.com/questions/52821996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9023836/" ]
You can do it Using `checkpoints`: ``` from keras.callbacks import EarlyStopping earlyStop=EarlyStopping(monitor="val_loss",verbose=2,mode='min',patience=3) history=model.fit(xTrain,yTrain,epochs=100,batch_size=10,validation_data=(xTest,yTest) ,verbose=2,callbacks=[earlyStop]) ``` Training will stop when "val\_loss" has not decreased(`mode='min'`) even after 3 epochs(`patience=3`) ``` #Didn't realize u were note using keras ```
You can find it with a little search <https://github.com/mmuratarat/handson-ml/blob/master/11_deep_learning.ipynb> ``` max_checks_without_progress = 20 checks_without_progress = 0 best_loss = np.infty .... if loss_val < best_loss: save_path = saver.save(sess, './my_mnist_model.ckpt') best_loss = loss_val check_without_progress = 0 else: check_without_progress +=1 if check_without_progress > max_checks_without_progress: print("Early stopping!") break print("Epoch: {:d} - ".format(epoch), \ "Training Loss: {:.5f}, ".format(loss_train), \ "Training Accuracy: {:.2f}%, ".format(accuracy_train*100), \ "Validation Loss: {:.4f}, ".format(loss_val), \ "Best Loss: {:.4f}, ".format(best_loss), \ "Validation Accuracy: {:.2f}%".format(accuracy_val*100)) ```
51,405,580
I am trying to install behave-parallel using pip install. I have installed programmes previously using pip so I know my Python/script path is correct in my env variables. However I am seeing the following error ``` FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\.....Temp\\pip-install-rjiorrn7\\behave-parallel\\setup.py' ``` how can I resolve this issue ``` C:\Users\.....>pip install behave-parallel Collecting behave-parallel Using cached https://files.pythonhosted.org/packages/05/9d/22f74dd77bc4fa85d391564a232c49b4e99cfdeac7bfdee8151ea4606632/behave-parallel-1.2.4a1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\.........\python\lib\tokenize.py", line 447, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: 'C:\\.........\\AppData\\Local\\Temp\\pip-install-7vgf8_mu\\behave-parallel\\setup.py' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\.........\AppData\Local\Temp\pip-install-7vgf8_mu\behave-parallel\ ```
2018/07/18
[ "https://Stackoverflow.com/questions/51405580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7546921/" ]
The package is simply broken, as it is missing the `setup.py` file. ``` $ tar tzvf behave-parallel-1.2.4a1.tar.gz | grep setup.py $ ``` You might be able to download the source from Github or wherever and package it yourself (`python setup.py bdist_wheel`), then install that wheel (`pip install ../../dist/behave-parallel...whl`).
There is a newer feature for building python packages (see also [PEP 517](https://www.python.org/dev/peps/pep-0517/) and [PEP 518](https://www.python.org/dev/peps/pep-0518/)). A package can now be built without setup.py (with pyproject.toml), but older pip versions are not aware of this feature and raise the error shown in the question. So if you have reason to believe that the library was packaged properly, try updating pip to something newer ([version 19 or newer](https://pip.pypa.io/en/stable/news/#id209) will probably work).
51,405,580
I am trying to install behave-parallel using pip install. I have installed programmes previously using pip so I know my Python/script path is correct in my env variables. However I am seeing the following error ``` FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\.....Temp\\pip-install-rjiorrn7\\behave-parallel\\setup.py' ``` how can I resolve this issue ``` C:\Users\.....>pip install behave-parallel Collecting behave-parallel Using cached https://files.pythonhosted.org/packages/05/9d/22f74dd77bc4fa85d391564a232c49b4e99cfdeac7bfdee8151ea4606632/behave-parallel-1.2.4a1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\.........\python\lib\tokenize.py", line 447, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: 'C:\\.........\\AppData\\Local\\Temp\\pip-install-7vgf8_mu\\behave-parallel\\setup.py' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\.........\AppData\Local\Temp\pip-install-7vgf8_mu\behave-parallel\ ```
2018/07/18
[ "https://Stackoverflow.com/questions/51405580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7546921/" ]
In my case with the same error, the solution was to do ``` pip3 install --upgrade pip ``` It was my pip3 that was in version 9.X were it's now in version 19.X
The package is simply broken, as it is missing the `setup.py` file. ``` $ tar tzvf behave-parallel-1.2.4a1.tar.gz | grep setup.py $ ``` You might be able to download the source from Github or wherever and package it yourself (`python setup.py bdist_wheel`), then install that wheel (`pip install ../../dist/behave-parallel...whl`).
51,405,580
I am trying to install behave-parallel using pip install. I have installed programmes previously using pip so I know my Python/script path is correct in my env variables. However I am seeing the following error ``` FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\.....Temp\\pip-install-rjiorrn7\\behave-parallel\\setup.py' ``` how can I resolve this issue ``` C:\Users\.....>pip install behave-parallel Collecting behave-parallel Using cached https://files.pythonhosted.org/packages/05/9d/22f74dd77bc4fa85d391564a232c49b4e99cfdeac7bfdee8151ea4606632/behave-parallel-1.2.4a1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\.........\python\lib\tokenize.py", line 447, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: 'C:\\.........\\AppData\\Local\\Temp\\pip-install-7vgf8_mu\\behave-parallel\\setup.py' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\.........\AppData\Local\Temp\pip-install-7vgf8_mu\behave-parallel\ ```
2018/07/18
[ "https://Stackoverflow.com/questions/51405580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7546921/" ]
The package is simply broken, as it is missing the `setup.py` file. ``` $ tar tzvf behave-parallel-1.2.4a1.tar.gz | grep setup.py $ ``` You might be able to download the source from Github or wherever and package it yourself (`python setup.py bdist_wheel`), then install that wheel (`pip install ../../dist/behave-parallel...whl`).
Here it seems caused by setup.py not being in the root of my project. (it can't be in root because otherwise the unit test will "discover" setup.py and fail it because it's not a test)
51,405,580
I am trying to install behave-parallel using pip install. I have installed programmes previously using pip so I know my Python/script path is correct in my env variables. However I am seeing the following error ``` FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\.....Temp\\pip-install-rjiorrn7\\behave-parallel\\setup.py' ``` how can I resolve this issue ``` C:\Users\.....>pip install behave-parallel Collecting behave-parallel Using cached https://files.pythonhosted.org/packages/05/9d/22f74dd77bc4fa85d391564a232c49b4e99cfdeac7bfdee8151ea4606632/behave-parallel-1.2.4a1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\.........\python\lib\tokenize.py", line 447, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: 'C:\\.........\\AppData\\Local\\Temp\\pip-install-7vgf8_mu\\behave-parallel\\setup.py' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\.........\AppData\Local\Temp\pip-install-7vgf8_mu\behave-parallel\ ```
2018/07/18
[ "https://Stackoverflow.com/questions/51405580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7546921/" ]
In my case with the same error, the solution was to do ``` pip3 install --upgrade pip ``` It was my pip3 that was in version 9.X were it's now in version 19.X
There is a newer feature for building python packages (see also [PEP 517](https://www.python.org/dev/peps/pep-0517/) and [PEP 518](https://www.python.org/dev/peps/pep-0518/)). A package can now be built without setup.py (with pyproject.toml), but older pip versions are not aware of this feature and raise the error shown in the question. So if you have reason to believe that the library was packaged properly, try updating pip to something newer ([version 19 or newer](https://pip.pypa.io/en/stable/news/#id209) will probably work).
51,405,580
I am trying to install behave-parallel using pip install. I have installed programmes previously using pip so I know my Python/script path is correct in my env variables. However I am seeing the following error ``` FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\.....Temp\\pip-install-rjiorrn7\\behave-parallel\\setup.py' ``` how can I resolve this issue ``` C:\Users\.....>pip install behave-parallel Collecting behave-parallel Using cached https://files.pythonhosted.org/packages/05/9d/22f74dd77bc4fa85d391564a232c49b4e99cfdeac7bfdee8151ea4606632/behave-parallel-1.2.4a1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\.........\python\lib\tokenize.py", line 447, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: 'C:\\.........\\AppData\\Local\\Temp\\pip-install-7vgf8_mu\\behave-parallel\\setup.py' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\.........\AppData\Local\Temp\pip-install-7vgf8_mu\behave-parallel\ ```
2018/07/18
[ "https://Stackoverflow.com/questions/51405580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7546921/" ]
There is a newer feature for building python packages (see also [PEP 517](https://www.python.org/dev/peps/pep-0517/) and [PEP 518](https://www.python.org/dev/peps/pep-0518/)). A package can now be built without setup.py (with pyproject.toml), but older pip versions are not aware of this feature and raise the error shown in the question. So if you have reason to believe that the library was packaged properly, try updating pip to something newer ([version 19 or newer](https://pip.pypa.io/en/stable/news/#id209) will probably work).
Here it seems caused by setup.py not being in the root of my project. (it can't be in root because otherwise the unit test will "discover" setup.py and fail it because it's not a test)
51,405,580
I am trying to install behave-parallel using pip install. I have installed programmes previously using pip so I know my Python/script path is correct in my env variables. However I am seeing the following error ``` FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\.....Temp\\pip-install-rjiorrn7\\behave-parallel\\setup.py' ``` how can I resolve this issue ``` C:\Users\.....>pip install behave-parallel Collecting behave-parallel Using cached https://files.pythonhosted.org/packages/05/9d/22f74dd77bc4fa85d391564a232c49b4e99cfdeac7bfdee8151ea4606632/behave-parallel-1.2.4a1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\.........\python\lib\tokenize.py", line 447, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: 'C:\\.........\\AppData\\Local\\Temp\\pip-install-7vgf8_mu\\behave-parallel\\setup.py' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\.........\AppData\Local\Temp\pip-install-7vgf8_mu\behave-parallel\ ```
2018/07/18
[ "https://Stackoverflow.com/questions/51405580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7546921/" ]
In my case with the same error, the solution was to do ``` pip3 install --upgrade pip ``` It was my pip3 that was in version 9.X were it's now in version 19.X
Here it seems caused by setup.py not being in the root of my project. (it can't be in root because otherwise the unit test will "discover" setup.py and fail it because it's not a test)
2,332,773
I am using newt/snack (a TUI graphical Widgit library for Python based on slang) to have some interactive scripts. However for some target terminals the output of those screens are not very nice. I can change the look of them by changing the `$TERM` variable to remove non printable characters, and to convert them to something more suitable. For example: ``` TERM=linux python myscript.py ``` So far the values I tested for `$TERM`, yielded only moderate success. Is there a known value for $TERM that consistently converts graphical characters: ``` ┌────────────┤ Title ├────────────┐ │ │ │ Some text for the entry window │ │ │ │ foo _______________________ │ │ bar _______________________ │ │ baz _______________________ │ │ │ │ ┌────┐ ┌────────┐ │ │ │ Ok │ │ Cancel │ │ │ └────┘ └────────┘ │ │ │ └─────────────────────────────────┘ ``` into non graphical characters: ``` +------------| Title |------------+ | | | Some text for the entry window | | | | foo _______________________ | | bar _______________________ | | baz _______________________ | | | | +----+ +--------+ | | | Ok | | Cancel | | | +----+ +--------+ | | | +---------------------------------+ ```
2010/02/25
[ "https://Stackoverflow.com/questions/2332773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110488/" ]
short: no - it (newt and slang) simply doesn't **do** that. long: newt uses the function `SLsmg_draw_box` which is shown here for reference: ``` void SLsmg_draw_box (int r, int c, unsigned int dr, unsigned int dc) { if (Smg_Mode == SMG_MODE_NONE) return; if (!dr || !dc) return; This_Row = r; This_Col = c; dr--; dc--; SLsmg_draw_hline (dc); SLsmg_draw_vline (dr); This_Row = r; This_Col = c; SLsmg_draw_vline (dr); SLsmg_draw_hline (dc); SLsmg_draw_object (r, c, SLSMG_ULCORN_CHAR); SLsmg_draw_object (r, c + (int) dc, SLSMG_URCORN_CHAR); SLsmg_draw_object (r + (int) dr, c, SLSMG_LLCORN_CHAR); SLsmg_draw_object (r + (int) dr, c + (int) dc, SLSMG_LRCORN_CHAR); This_Row = r; This_Col = c; } ``` In the `slsmg.c` file, slang does have a table: ``` typedef struct { unsigned char vt100_char; unsigned char ascii; SLwchar_Type unicode; /* may have an ambiguous width */ SLwchar_Type unicode_narrow; /* has a narrow width */ } ACS_Def_Type; static SLCONST ACS_Def_Type UTF8_ACS_Map[] = { {'+', '>', 0x2192, '>'}, /* RIGHTWARDS ARROW [A] */ {',', '<', 0x2190, '<'}, /* LEFTWARDS ARROW [A] */ {'-', '^', 0x2191, 0x2303}, /* UPWARDS ARROW [A] */ {'.', 'v', 0x2193, 0x2304}, /* DOWNWARDS ARROW [A] */ ``` but it will automatically choose the Unicode values if told by the application (newt) to use UTF-8 encoding. newt does that unconditionally, ignoring the terminal and locale information: ``` /** * @brief Initialize the newt library * @return int - 0 for success, else < 0 */ int newtInit(void) { char * MonoValue, * MonoEnv = "NEWT_MONO"; const char *lang; int ret; if ((lang = getenv("LC_ALL")) == NULL) if ((lang = getenv("LC_CTYPE")) == NULL) if ((lang = getenv("LANG")) == NULL) lang = ""; /* slang doesn't support multibyte encodings except UTF-8, avoid character corruption by redrawing the screen */ if (strstr (lang, ".euc") != NULL) trashScreen = 1; (void) strlen(ident); SLutf8_enable(-1); SLtt_get_terminfo(); SLtt_get_screen_size(); ``` Back in `slsmg.c`, the `init_acs()` function will first try to use Unicode (and always succeed if your locale supports UTF-8). If it happens to be something else, the functions proceeds to use whatever information exists in the terminal description. As a rule, if a terminal supports line-drawing characters, every terminal description is written to tell how to draw lines. If you **modified** a terminal description to remove those capabilities, you could get just ASCII (but that's based on just reading the function: slang has numerous hard-coded cases designed to fill in for terminal descriptions which don't behave as slang's author wants, and you might trip over one of those). For what it's worth, the terminfo capabilities used by slang are: **`acsc`**, **`enacs`**, **`rmacs`**, **`smacs`**.
It might be based on your `$LANG` being set to something like `en_US.UTF-8`. Try changing it to `en_US` (assuming your base locale is `en_US`).
41,454,563
I could just write a long-running CLI app and run it, but I'm assuming it wouldn't comply to all the expectations one would have of a standards-compliant linux daemon (responding to SIGTERM, Started by System V init process, Ignore terminal I/O signals, [etc.](https://www.python.org/dev/peps/pep-3143/#id1)) Most ecosystems have some best-practice way of doing this, for example, in python, you can use <https://pypi.python.org/pypi/python-daemon/> Is there some documentation about how to do this with .Net Core?
2017/01/04
[ "https://Stackoverflow.com/questions/41454563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/970673/" ]
I toyed with an idea similar to how .net core web host waits for shutdown in console applications. I was reviewing it on GitHub and was able to extract the gist of how they performed the `Run` <https://github.com/aspnet/Hosting/blob/15008b0b7fcb54235a9de3ab844c066aaf42ea44/src/Microsoft.AspNetCore.Hosting/WebHostExtensions.cs#L86> ```cs public static class ConsoleHost { /// <summary> /// Block the calling thread until shutdown is triggered via Ctrl+C or SIGTERM. /// </summary> public static void WaitForShutdown() { WaitForShutdownAsync().GetAwaiter().GetResult(); } /// <summary> /// Runs an application and block the calling thread until host shutdown. /// </summary> /// <param name="host">The <see cref="IWebHost"/> to run.</param> public static void Wait() { WaitAsync().GetAwaiter().GetResult(); } /// <summary> /// Runs an application and returns a Task that only completes when the token is triggered or shutdown is triggered. /// </summary> /// <param name="host">The <see cref="IConsoleHost"/> to run.</param> /// <param name="token">The token to trigger shutdown.</param> public static async Task WaitAsync(CancellationToken token = default(CancellationToken)) { //Wait for the token shutdown if it can be cancelled if (token.CanBeCanceled) { await WaitAsync(token, shutdownMessage: null); return; } //If token cannot be cancelled, attach Ctrl+C and SIGTERN shutdown var done = new ManualResetEventSlim(false); using (var cts = new CancellationTokenSource()) { AttachCtrlcSigtermShutdown(cts, done, shutdownMessage: "Application is shutting down..."); await WaitAsync(cts.Token, "Application running. Press Ctrl+C to shut down."); done.Set(); } } /// <summary> /// Returns a Task that completes when shutdown is triggered via the given token, Ctrl+C or SIGTERM. /// </summary> /// <param name="token">The token to trigger shutdown.</param> public static async Task WaitForShutdownAsync(CancellationToken token = default (CancellationToken)) { var done = new ManualResetEventSlim(false); using (var cts = CancellationTokenSource.CreateLinkedTokenSource(token)) { AttachCtrlcSigtermShutdown(cts, done, shutdownMessage: string.Empty); await WaitForTokenShutdownAsync(cts.Token); done.Set(); } } private static async Task WaitAsync(CancellationToken token, string shutdownMessage) { if (!string.IsNullOrEmpty(shutdownMessage)) { Console.WriteLine(shutdownMessage); } await WaitForTokenShutdownAsync(token); } private static void AttachCtrlcSigtermShutdown(CancellationTokenSource cts, ManualResetEventSlim resetEvent, string shutdownMessage) { Action ShutDown = () => { if (!cts.IsCancellationRequested) { if (!string.IsNullOrWhiteSpace(shutdownMessage)) { Console.WriteLine(shutdownMessage); } try { cts.Cancel(); } catch (ObjectDisposedException) { } } //Wait on the given reset event resetEvent.Wait(); }; AppDomain.CurrentDomain.ProcessExit += delegate { ShutDown(); }; Console.CancelKeyPress += (sender, eventArgs) => { ShutDown(); //Don't terminate the process immediately, wait for the Main thread to exit gracefully. eventArgs.Cancel = true; }; } private static async Task WaitForTokenShutdownAsync(CancellationToken token) { var waitForStop = new TaskCompletionSource<object>(); token.Register(obj => { var tcs = (TaskCompletionSource<object>)obj; tcs.TrySetResult(null); }, waitForStop); await waitForStop.Task; } } ``` I tried adapting something like a `IConsoleHost` but quickly realized I was over-engineering it. Extracted the main parts into something like `await ConsoleUtil.WaitForShutdownAsync();` that operated like `Console.ReadLine` This then allowed the utility to be used like this ```cs public class Program { public static async Task Main(string[] args) { //relevant code goes here //... //wait for application shutdown await ConsoleUtil.WaitForShutdownAsync(); } } ``` from there creating a *systemd* as in the following link should get you the rest of the way [Writing a Linux daemon in C#](https://developers.redhat.com/blog/2017/06/07/writing-a-linux-daemon-in-c/)
I'm not sure it is production grade, but for a quick and dirty console app this works well: ```cs await Task.Delay(-1); //-1 indicates infinite timeout ```
41,454,563
I could just write a long-running CLI app and run it, but I'm assuming it wouldn't comply to all the expectations one would have of a standards-compliant linux daemon (responding to SIGTERM, Started by System V init process, Ignore terminal I/O signals, [etc.](https://www.python.org/dev/peps/pep-3143/#id1)) Most ecosystems have some best-practice way of doing this, for example, in python, you can use <https://pypi.python.org/pypi/python-daemon/> Is there some documentation about how to do this with .Net Core?
2017/01/04
[ "https://Stackoverflow.com/questions/41454563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/970673/" ]
Implementing Linux Daemon or service for `windows` quite easy with single codebase using Visual Studio 2019. Just create project using `WorkerService` template. In my case I have [`Coraval`](https://docs.coravel.net/) library to schedule the tasks. `Program.cs` class ``` public class Program { public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.File(@"C:\temp\Workerservice\logfile.txt").CreateLogger(); IHost host = CreateHostBuilder(args).Build(); host.Services.UseScheduler(scheduler => { scheduler .Schedule<ReprocessInvocable>() .EveryThirtySeconds(); }); host.Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args).UseSystemd() //.UseWindowsService() .ConfigureServices(services => { services.AddScheduler(); services.AddTransient<ReprocessInvocable>(); }); } ``` `ReprocessInvocable.cs` class ``` public class ReprocessInvocable : IInvocable { private readonly ILogger<ReprocessInvocable> _logger; public ReprocessInvocable(ILogger<ReprocessInvocable> logger) { _logger = logger; } public async Task Invoke() { //your code goes here _logger.LogInformation("Information - Worker running at: {time}", DateTimeOffset.Now); _logger.LogWarning("Warning - Worker running at: {time}", DateTimeOffset.Now); _logger.LogCritical("Critical - Worker running at: {time}", DateTimeOffset.Now); Log.Information("Invoke has called at: {time}", DateTimeOffset.Now); } } ``` For `linux daemon` use `UseSystemd` and for `windows service` use `UseWindowsService` as per the above code.
Have you tried **Thread.Sleep (Timeout.Infinite)** ? ``` using System; using System.IO; using System.Threading; namespace Daemon { class Program { static int Main(string[] args) { if (Environment.OSVersion.Platform == PlatformID.Win32NT) { Log.Critical("Windows is not supported!"); return 1; } Agent.Init(); Agent.Start(); if (Agent.Settings.DaemonMode || args.FirstOrDefault() == "daemon") { Log.Info("Daemon started."); Thread.Sleep(Timeout.Infinite); } Agent.Stop(); } } } ```
41,454,563
I could just write a long-running CLI app and run it, but I'm assuming it wouldn't comply to all the expectations one would have of a standards-compliant linux daemon (responding to SIGTERM, Started by System V init process, Ignore terminal I/O signals, [etc.](https://www.python.org/dev/peps/pep-3143/#id1)) Most ecosystems have some best-practice way of doing this, for example, in python, you can use <https://pypi.python.org/pypi/python-daemon/> Is there some documentation about how to do this with .Net Core?
2017/01/04
[ "https://Stackoverflow.com/questions/41454563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/970673/" ]
If you're trying to find something more robust, I found an implementation on Github that looks promising: [.NET Core Application blocks for message-based communication](https://github.com/dotnet-architecture/Messaging/). It uses `Host`, `HostBuilder`, `ApplicationServices`, `ApplicationEnvironment`, etc classes to implement a messaging service. It doesn't quite look ready for black box reuse, but it seems like it could be a good starting point. ``` var host = new HostBuilder() .ConfigureServices(services => { var settings = new RabbitMQSettings { ServerName = "192.168.80.129", UserName = "admin", Password = "Pass@word1" }; }) .Build(); Console.WriteLine("Starting..."); await host.StartAsync(); var messenger = host.Services.GetRequiredService<IRabbitMQMessenger>(); Console.WriteLine("Running. Type text and press ENTER to send a message."); Console.CancelKeyPress += async (sender, e) => { Console.WriteLine("Shutting down..."); await host.StopAsync(new CancellationTokenSource(3000).Token); Environment.Exit(0); }; ... ```
I'm not sure it is production grade, but for a quick and dirty console app this works well: ```cs await Task.Delay(-1); //-1 indicates infinite timeout ```
41,454,563
I could just write a long-running CLI app and run it, but I'm assuming it wouldn't comply to all the expectations one would have of a standards-compliant linux daemon (responding to SIGTERM, Started by System V init process, Ignore terminal I/O signals, [etc.](https://www.python.org/dev/peps/pep-3143/#id1)) Most ecosystems have some best-practice way of doing this, for example, in python, you can use <https://pypi.python.org/pypi/python-daemon/> Is there some documentation about how to do this with .Net Core?
2017/01/04
[ "https://Stackoverflow.com/questions/41454563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/970673/" ]
I toyed with an idea similar to how .net core web host waits for shutdown in console applications. I was reviewing it on GitHub and was able to extract the gist of how they performed the `Run` <https://github.com/aspnet/Hosting/blob/15008b0b7fcb54235a9de3ab844c066aaf42ea44/src/Microsoft.AspNetCore.Hosting/WebHostExtensions.cs#L86> ```cs public static class ConsoleHost { /// <summary> /// Block the calling thread until shutdown is triggered via Ctrl+C or SIGTERM. /// </summary> public static void WaitForShutdown() { WaitForShutdownAsync().GetAwaiter().GetResult(); } /// <summary> /// Runs an application and block the calling thread until host shutdown. /// </summary> /// <param name="host">The <see cref="IWebHost"/> to run.</param> public static void Wait() { WaitAsync().GetAwaiter().GetResult(); } /// <summary> /// Runs an application and returns a Task that only completes when the token is triggered or shutdown is triggered. /// </summary> /// <param name="host">The <see cref="IConsoleHost"/> to run.</param> /// <param name="token">The token to trigger shutdown.</param> public static async Task WaitAsync(CancellationToken token = default(CancellationToken)) { //Wait for the token shutdown if it can be cancelled if (token.CanBeCanceled) { await WaitAsync(token, shutdownMessage: null); return; } //If token cannot be cancelled, attach Ctrl+C and SIGTERN shutdown var done = new ManualResetEventSlim(false); using (var cts = new CancellationTokenSource()) { AttachCtrlcSigtermShutdown(cts, done, shutdownMessage: "Application is shutting down..."); await WaitAsync(cts.Token, "Application running. Press Ctrl+C to shut down."); done.Set(); } } /// <summary> /// Returns a Task that completes when shutdown is triggered via the given token, Ctrl+C or SIGTERM. /// </summary> /// <param name="token">The token to trigger shutdown.</param> public static async Task WaitForShutdownAsync(CancellationToken token = default (CancellationToken)) { var done = new ManualResetEventSlim(false); using (var cts = CancellationTokenSource.CreateLinkedTokenSource(token)) { AttachCtrlcSigtermShutdown(cts, done, shutdownMessage: string.Empty); await WaitForTokenShutdownAsync(cts.Token); done.Set(); } } private static async Task WaitAsync(CancellationToken token, string shutdownMessage) { if (!string.IsNullOrEmpty(shutdownMessage)) { Console.WriteLine(shutdownMessage); } await WaitForTokenShutdownAsync(token); } private static void AttachCtrlcSigtermShutdown(CancellationTokenSource cts, ManualResetEventSlim resetEvent, string shutdownMessage) { Action ShutDown = () => { if (!cts.IsCancellationRequested) { if (!string.IsNullOrWhiteSpace(shutdownMessage)) { Console.WriteLine(shutdownMessage); } try { cts.Cancel(); } catch (ObjectDisposedException) { } } //Wait on the given reset event resetEvent.Wait(); }; AppDomain.CurrentDomain.ProcessExit += delegate { ShutDown(); }; Console.CancelKeyPress += (sender, eventArgs) => { ShutDown(); //Don't terminate the process immediately, wait for the Main thread to exit gracefully. eventArgs.Cancel = true; }; } private static async Task WaitForTokenShutdownAsync(CancellationToken token) { var waitForStop = new TaskCompletionSource<object>(); token.Register(obj => { var tcs = (TaskCompletionSource<object>)obj; tcs.TrySetResult(null); }, waitForStop); await waitForStop.Task; } } ``` I tried adapting something like a `IConsoleHost` but quickly realized I was over-engineering it. Extracted the main parts into something like `await ConsoleUtil.WaitForShutdownAsync();` that operated like `Console.ReadLine` This then allowed the utility to be used like this ```cs public class Program { public static async Task Main(string[] args) { //relevant code goes here //... //wait for application shutdown await ConsoleUtil.WaitForShutdownAsync(); } } ``` from there creating a *systemd* as in the following link should get you the rest of the way [Writing a Linux daemon in C#](https://developers.redhat.com/blog/2017/06/07/writing-a-linux-daemon-in-c/)
The best I could come up with is based on the answer to two other questions: [Killing gracefully a .NET Core daemon running on Linux](https://stackoverflow.com/questions/38291567/killing-gracefully-a-net-core-daemon-running-on-linux) and [Is it possible to await an event instead of another async method?](https://stackoverflow.com/questions/12858501/is-it-possible-to-await-an-event-instead-of-another-async-method/) ``` using System; using System.Runtime.Loader; using System.Threading.Tasks; namespace ConsoleApp1 { public class Program { private static TaskCompletionSource<object> taskToWait; public static void Main(string[] args) { taskToWait = new TaskCompletionSource<object>(); AssemblyLoadContext.Default.Unloading += SigTermEventHandler; Console.CancelKeyPress += new ConsoleCancelEventHandler(CancelHandler); //eventSource.Subscribe(eventSink) or something... taskToWait.Task.Wait(); AssemblyLoadContext.Default.Unloading -= SigTermEventHandler; Console.CancelKeyPress -= new ConsoleCancelEventHandler(CancelHandler); } private static void SigTermEventHandler(AssemblyLoadContext obj) { System.Console.WriteLine("Unloading..."); taskToWait.TrySetResult(null); } private static void CancelHandler(object sender, ConsoleCancelEventArgs e) { System.Console.WriteLine("Exiting..."); taskToWait.TrySetResult(null); } } } ```
41,454,563
I could just write a long-running CLI app and run it, but I'm assuming it wouldn't comply to all the expectations one would have of a standards-compliant linux daemon (responding to SIGTERM, Started by System V init process, Ignore terminal I/O signals, [etc.](https://www.python.org/dev/peps/pep-3143/#id1)) Most ecosystems have some best-practice way of doing this, for example, in python, you can use <https://pypi.python.org/pypi/python-daemon/> Is there some documentation about how to do this with .Net Core?
2017/01/04
[ "https://Stackoverflow.com/questions/41454563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/970673/" ]
I toyed with an idea similar to how .net core web host waits for shutdown in console applications. I was reviewing it on GitHub and was able to extract the gist of how they performed the `Run` <https://github.com/aspnet/Hosting/blob/15008b0b7fcb54235a9de3ab844c066aaf42ea44/src/Microsoft.AspNetCore.Hosting/WebHostExtensions.cs#L86> ```cs public static class ConsoleHost { /// <summary> /// Block the calling thread until shutdown is triggered via Ctrl+C or SIGTERM. /// </summary> public static void WaitForShutdown() { WaitForShutdownAsync().GetAwaiter().GetResult(); } /// <summary> /// Runs an application and block the calling thread until host shutdown. /// </summary> /// <param name="host">The <see cref="IWebHost"/> to run.</param> public static void Wait() { WaitAsync().GetAwaiter().GetResult(); } /// <summary> /// Runs an application and returns a Task that only completes when the token is triggered or shutdown is triggered. /// </summary> /// <param name="host">The <see cref="IConsoleHost"/> to run.</param> /// <param name="token">The token to trigger shutdown.</param> public static async Task WaitAsync(CancellationToken token = default(CancellationToken)) { //Wait for the token shutdown if it can be cancelled if (token.CanBeCanceled) { await WaitAsync(token, shutdownMessage: null); return; } //If token cannot be cancelled, attach Ctrl+C and SIGTERN shutdown var done = new ManualResetEventSlim(false); using (var cts = new CancellationTokenSource()) { AttachCtrlcSigtermShutdown(cts, done, shutdownMessage: "Application is shutting down..."); await WaitAsync(cts.Token, "Application running. Press Ctrl+C to shut down."); done.Set(); } } /// <summary> /// Returns a Task that completes when shutdown is triggered via the given token, Ctrl+C or SIGTERM. /// </summary> /// <param name="token">The token to trigger shutdown.</param> public static async Task WaitForShutdownAsync(CancellationToken token = default (CancellationToken)) { var done = new ManualResetEventSlim(false); using (var cts = CancellationTokenSource.CreateLinkedTokenSource(token)) { AttachCtrlcSigtermShutdown(cts, done, shutdownMessage: string.Empty); await WaitForTokenShutdownAsync(cts.Token); done.Set(); } } private static async Task WaitAsync(CancellationToken token, string shutdownMessage) { if (!string.IsNullOrEmpty(shutdownMessage)) { Console.WriteLine(shutdownMessage); } await WaitForTokenShutdownAsync(token); } private static void AttachCtrlcSigtermShutdown(CancellationTokenSource cts, ManualResetEventSlim resetEvent, string shutdownMessage) { Action ShutDown = () => { if (!cts.IsCancellationRequested) { if (!string.IsNullOrWhiteSpace(shutdownMessage)) { Console.WriteLine(shutdownMessage); } try { cts.Cancel(); } catch (ObjectDisposedException) { } } //Wait on the given reset event resetEvent.Wait(); }; AppDomain.CurrentDomain.ProcessExit += delegate { ShutDown(); }; Console.CancelKeyPress += (sender, eventArgs) => { ShutDown(); //Don't terminate the process immediately, wait for the Main thread to exit gracefully. eventArgs.Cancel = true; }; } private static async Task WaitForTokenShutdownAsync(CancellationToken token) { var waitForStop = new TaskCompletionSource<object>(); token.Register(obj => { var tcs = (TaskCompletionSource<object>)obj; tcs.TrySetResult(null); }, waitForStop); await waitForStop.Task; } } ``` I tried adapting something like a `IConsoleHost` but quickly realized I was over-engineering it. Extracted the main parts into something like `await ConsoleUtil.WaitForShutdownAsync();` that operated like `Console.ReadLine` This then allowed the utility to be used like this ```cs public class Program { public static async Task Main(string[] args) { //relevant code goes here //... //wait for application shutdown await ConsoleUtil.WaitForShutdownAsync(); } } ``` from there creating a *systemd* as in the following link should get you the rest of the way [Writing a Linux daemon in C#](https://developers.redhat.com/blog/2017/06/07/writing-a-linux-daemon-in-c/)
Have you tried **Thread.Sleep (Timeout.Infinite)** ? ``` using System; using System.IO; using System.Threading; namespace Daemon { class Program { static int Main(string[] args) { if (Environment.OSVersion.Platform == PlatformID.Win32NT) { Log.Critical("Windows is not supported!"); return 1; } Agent.Init(); Agent.Start(); if (Agent.Settings.DaemonMode || args.FirstOrDefault() == "daemon") { Log.Info("Daemon started."); Thread.Sleep(Timeout.Infinite); } Agent.Stop(); } } } ```
41,454,563
I could just write a long-running CLI app and run it, but I'm assuming it wouldn't comply to all the expectations one would have of a standards-compliant linux daemon (responding to SIGTERM, Started by System V init process, Ignore terminal I/O signals, [etc.](https://www.python.org/dev/peps/pep-3143/#id1)) Most ecosystems have some best-practice way of doing this, for example, in python, you can use <https://pypi.python.org/pypi/python-daemon/> Is there some documentation about how to do this with .Net Core?
2017/01/04
[ "https://Stackoverflow.com/questions/41454563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/970673/" ]
I toyed with an idea similar to how .net core web host waits for shutdown in console applications. I was reviewing it on GitHub and was able to extract the gist of how they performed the `Run` <https://github.com/aspnet/Hosting/blob/15008b0b7fcb54235a9de3ab844c066aaf42ea44/src/Microsoft.AspNetCore.Hosting/WebHostExtensions.cs#L86> ```cs public static class ConsoleHost { /// <summary> /// Block the calling thread until shutdown is triggered via Ctrl+C or SIGTERM. /// </summary> public static void WaitForShutdown() { WaitForShutdownAsync().GetAwaiter().GetResult(); } /// <summary> /// Runs an application and block the calling thread until host shutdown. /// </summary> /// <param name="host">The <see cref="IWebHost"/> to run.</param> public static void Wait() { WaitAsync().GetAwaiter().GetResult(); } /// <summary> /// Runs an application and returns a Task that only completes when the token is triggered or shutdown is triggered. /// </summary> /// <param name="host">The <see cref="IConsoleHost"/> to run.</param> /// <param name="token">The token to trigger shutdown.</param> public static async Task WaitAsync(CancellationToken token = default(CancellationToken)) { //Wait for the token shutdown if it can be cancelled if (token.CanBeCanceled) { await WaitAsync(token, shutdownMessage: null); return; } //If token cannot be cancelled, attach Ctrl+C and SIGTERN shutdown var done = new ManualResetEventSlim(false); using (var cts = new CancellationTokenSource()) { AttachCtrlcSigtermShutdown(cts, done, shutdownMessage: "Application is shutting down..."); await WaitAsync(cts.Token, "Application running. Press Ctrl+C to shut down."); done.Set(); } } /// <summary> /// Returns a Task that completes when shutdown is triggered via the given token, Ctrl+C or SIGTERM. /// </summary> /// <param name="token">The token to trigger shutdown.</param> public static async Task WaitForShutdownAsync(CancellationToken token = default (CancellationToken)) { var done = new ManualResetEventSlim(false); using (var cts = CancellationTokenSource.CreateLinkedTokenSource(token)) { AttachCtrlcSigtermShutdown(cts, done, shutdownMessage: string.Empty); await WaitForTokenShutdownAsync(cts.Token); done.Set(); } } private static async Task WaitAsync(CancellationToken token, string shutdownMessage) { if (!string.IsNullOrEmpty(shutdownMessage)) { Console.WriteLine(shutdownMessage); } await WaitForTokenShutdownAsync(token); } private static void AttachCtrlcSigtermShutdown(CancellationTokenSource cts, ManualResetEventSlim resetEvent, string shutdownMessage) { Action ShutDown = () => { if (!cts.IsCancellationRequested) { if (!string.IsNullOrWhiteSpace(shutdownMessage)) { Console.WriteLine(shutdownMessage); } try { cts.Cancel(); } catch (ObjectDisposedException) { } } //Wait on the given reset event resetEvent.Wait(); }; AppDomain.CurrentDomain.ProcessExit += delegate { ShutDown(); }; Console.CancelKeyPress += (sender, eventArgs) => { ShutDown(); //Don't terminate the process immediately, wait for the Main thread to exit gracefully. eventArgs.Cancel = true; }; } private static async Task WaitForTokenShutdownAsync(CancellationToken token) { var waitForStop = new TaskCompletionSource<object>(); token.Register(obj => { var tcs = (TaskCompletionSource<object>)obj; tcs.TrySetResult(null); }, waitForStop); await waitForStop.Task; } } ``` I tried adapting something like a `IConsoleHost` but quickly realized I was over-engineering it. Extracted the main parts into something like `await ConsoleUtil.WaitForShutdownAsync();` that operated like `Console.ReadLine` This then allowed the utility to be used like this ```cs public class Program { public static async Task Main(string[] args) { //relevant code goes here //... //wait for application shutdown await ConsoleUtil.WaitForShutdownAsync(); } } ``` from there creating a *systemd* as in the following link should get you the rest of the way [Writing a Linux daemon in C#](https://developers.redhat.com/blog/2017/06/07/writing-a-linux-daemon-in-c/)
Implementing Linux Daemon or service for `windows` quite easy with single codebase using Visual Studio 2019. Just create project using `WorkerService` template. In my case I have [`Coraval`](https://docs.coravel.net/) library to schedule the tasks. `Program.cs` class ``` public class Program { public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.File(@"C:\temp\Workerservice\logfile.txt").CreateLogger(); IHost host = CreateHostBuilder(args).Build(); host.Services.UseScheduler(scheduler => { scheduler .Schedule<ReprocessInvocable>() .EveryThirtySeconds(); }); host.Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args).UseSystemd() //.UseWindowsService() .ConfigureServices(services => { services.AddScheduler(); services.AddTransient<ReprocessInvocable>(); }); } ``` `ReprocessInvocable.cs` class ``` public class ReprocessInvocable : IInvocable { private readonly ILogger<ReprocessInvocable> _logger; public ReprocessInvocable(ILogger<ReprocessInvocable> logger) { _logger = logger; } public async Task Invoke() { //your code goes here _logger.LogInformation("Information - Worker running at: {time}", DateTimeOffset.Now); _logger.LogWarning("Warning - Worker running at: {time}", DateTimeOffset.Now); _logger.LogCritical("Critical - Worker running at: {time}", DateTimeOffset.Now); Log.Information("Invoke has called at: {time}", DateTimeOffset.Now); } } ``` For `linux daemon` use `UseSystemd` and for `windows service` use `UseWindowsService` as per the above code.
41,454,563
I could just write a long-running CLI app and run it, but I'm assuming it wouldn't comply to all the expectations one would have of a standards-compliant linux daemon (responding to SIGTERM, Started by System V init process, Ignore terminal I/O signals, [etc.](https://www.python.org/dev/peps/pep-3143/#id1)) Most ecosystems have some best-practice way of doing this, for example, in python, you can use <https://pypi.python.org/pypi/python-daemon/> Is there some documentation about how to do this with .Net Core?
2017/01/04
[ "https://Stackoverflow.com/questions/41454563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/970673/" ]
The best I could come up with is based on the answer to two other questions: [Killing gracefully a .NET Core daemon running on Linux](https://stackoverflow.com/questions/38291567/killing-gracefully-a-net-core-daemon-running-on-linux) and [Is it possible to await an event instead of another async method?](https://stackoverflow.com/questions/12858501/is-it-possible-to-await-an-event-instead-of-another-async-method/) ``` using System; using System.Runtime.Loader; using System.Threading.Tasks; namespace ConsoleApp1 { public class Program { private static TaskCompletionSource<object> taskToWait; public static void Main(string[] args) { taskToWait = new TaskCompletionSource<object>(); AssemblyLoadContext.Default.Unloading += SigTermEventHandler; Console.CancelKeyPress += new ConsoleCancelEventHandler(CancelHandler); //eventSource.Subscribe(eventSink) or something... taskToWait.Task.Wait(); AssemblyLoadContext.Default.Unloading -= SigTermEventHandler; Console.CancelKeyPress -= new ConsoleCancelEventHandler(CancelHandler); } private static void SigTermEventHandler(AssemblyLoadContext obj) { System.Console.WriteLine("Unloading..."); taskToWait.TrySetResult(null); } private static void CancelHandler(object sender, ConsoleCancelEventArgs e) { System.Console.WriteLine("Exiting..."); taskToWait.TrySetResult(null); } } } ```
Have you tried **Thread.Sleep (Timeout.Infinite)** ? ``` using System; using System.IO; using System.Threading; namespace Daemon { class Program { static int Main(string[] args) { if (Environment.OSVersion.Platform == PlatformID.Win32NT) { Log.Critical("Windows is not supported!"); return 1; } Agent.Init(); Agent.Start(); if (Agent.Settings.DaemonMode || args.FirstOrDefault() == "daemon") { Log.Info("Daemon started."); Thread.Sleep(Timeout.Infinite); } Agent.Stop(); } } } ```
41,454,563
I could just write a long-running CLI app and run it, but I'm assuming it wouldn't comply to all the expectations one would have of a standards-compliant linux daemon (responding to SIGTERM, Started by System V init process, Ignore terminal I/O signals, [etc.](https://www.python.org/dev/peps/pep-3143/#id1)) Most ecosystems have some best-practice way of doing this, for example, in python, you can use <https://pypi.python.org/pypi/python-daemon/> Is there some documentation about how to do this with .Net Core?
2017/01/04
[ "https://Stackoverflow.com/questions/41454563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/970673/" ]
If you're trying to find something more robust, I found an implementation on Github that looks promising: [.NET Core Application blocks for message-based communication](https://github.com/dotnet-architecture/Messaging/). It uses `Host`, `HostBuilder`, `ApplicationServices`, `ApplicationEnvironment`, etc classes to implement a messaging service. It doesn't quite look ready for black box reuse, but it seems like it could be a good starting point. ``` var host = new HostBuilder() .ConfigureServices(services => { var settings = new RabbitMQSettings { ServerName = "192.168.80.129", UserName = "admin", Password = "Pass@word1" }; }) .Build(); Console.WriteLine("Starting..."); await host.StartAsync(); var messenger = host.Services.GetRequiredService<IRabbitMQMessenger>(); Console.WriteLine("Running. Type text and press ENTER to send a message."); Console.CancelKeyPress += async (sender, e) => { Console.WriteLine("Shutting down..."); await host.StopAsync(new CancellationTokenSource(3000).Token); Environment.Exit(0); }; ... ```
Have you tried **Thread.Sleep (Timeout.Infinite)** ? ``` using System; using System.IO; using System.Threading; namespace Daemon { class Program { static int Main(string[] args) { if (Environment.OSVersion.Platform == PlatformID.Win32NT) { Log.Critical("Windows is not supported!"); return 1; } Agent.Init(); Agent.Start(); if (Agent.Settings.DaemonMode || args.FirstOrDefault() == "daemon") { Log.Info("Daemon started."); Thread.Sleep(Timeout.Infinite); } Agent.Stop(); } } } ```
41,454,563
I could just write a long-running CLI app and run it, but I'm assuming it wouldn't comply to all the expectations one would have of a standards-compliant linux daemon (responding to SIGTERM, Started by System V init process, Ignore terminal I/O signals, [etc.](https://www.python.org/dev/peps/pep-3143/#id1)) Most ecosystems have some best-practice way of doing this, for example, in python, you can use <https://pypi.python.org/pypi/python-daemon/> Is there some documentation about how to do this with .Net Core?
2017/01/04
[ "https://Stackoverflow.com/questions/41454563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/970673/" ]
I toyed with an idea similar to how .net core web host waits for shutdown in console applications. I was reviewing it on GitHub and was able to extract the gist of how they performed the `Run` <https://github.com/aspnet/Hosting/blob/15008b0b7fcb54235a9de3ab844c066aaf42ea44/src/Microsoft.AspNetCore.Hosting/WebHostExtensions.cs#L86> ```cs public static class ConsoleHost { /// <summary> /// Block the calling thread until shutdown is triggered via Ctrl+C or SIGTERM. /// </summary> public static void WaitForShutdown() { WaitForShutdownAsync().GetAwaiter().GetResult(); } /// <summary> /// Runs an application and block the calling thread until host shutdown. /// </summary> /// <param name="host">The <see cref="IWebHost"/> to run.</param> public static void Wait() { WaitAsync().GetAwaiter().GetResult(); } /// <summary> /// Runs an application and returns a Task that only completes when the token is triggered or shutdown is triggered. /// </summary> /// <param name="host">The <see cref="IConsoleHost"/> to run.</param> /// <param name="token">The token to trigger shutdown.</param> public static async Task WaitAsync(CancellationToken token = default(CancellationToken)) { //Wait for the token shutdown if it can be cancelled if (token.CanBeCanceled) { await WaitAsync(token, shutdownMessage: null); return; } //If token cannot be cancelled, attach Ctrl+C and SIGTERN shutdown var done = new ManualResetEventSlim(false); using (var cts = new CancellationTokenSource()) { AttachCtrlcSigtermShutdown(cts, done, shutdownMessage: "Application is shutting down..."); await WaitAsync(cts.Token, "Application running. Press Ctrl+C to shut down."); done.Set(); } } /// <summary> /// Returns a Task that completes when shutdown is triggered via the given token, Ctrl+C or SIGTERM. /// </summary> /// <param name="token">The token to trigger shutdown.</param> public static async Task WaitForShutdownAsync(CancellationToken token = default (CancellationToken)) { var done = new ManualResetEventSlim(false); using (var cts = CancellationTokenSource.CreateLinkedTokenSource(token)) { AttachCtrlcSigtermShutdown(cts, done, shutdownMessage: string.Empty); await WaitForTokenShutdownAsync(cts.Token); done.Set(); } } private static async Task WaitAsync(CancellationToken token, string shutdownMessage) { if (!string.IsNullOrEmpty(shutdownMessage)) { Console.WriteLine(shutdownMessage); } await WaitForTokenShutdownAsync(token); } private static void AttachCtrlcSigtermShutdown(CancellationTokenSource cts, ManualResetEventSlim resetEvent, string shutdownMessage) { Action ShutDown = () => { if (!cts.IsCancellationRequested) { if (!string.IsNullOrWhiteSpace(shutdownMessage)) { Console.WriteLine(shutdownMessage); } try { cts.Cancel(); } catch (ObjectDisposedException) { } } //Wait on the given reset event resetEvent.Wait(); }; AppDomain.CurrentDomain.ProcessExit += delegate { ShutDown(); }; Console.CancelKeyPress += (sender, eventArgs) => { ShutDown(); //Don't terminate the process immediately, wait for the Main thread to exit gracefully. eventArgs.Cancel = true; }; } private static async Task WaitForTokenShutdownAsync(CancellationToken token) { var waitForStop = new TaskCompletionSource<object>(); token.Register(obj => { var tcs = (TaskCompletionSource<object>)obj; tcs.TrySetResult(null); }, waitForStop); await waitForStop.Task; } } ``` I tried adapting something like a `IConsoleHost` but quickly realized I was over-engineering it. Extracted the main parts into something like `await ConsoleUtil.WaitForShutdownAsync();` that operated like `Console.ReadLine` This then allowed the utility to be used like this ```cs public class Program { public static async Task Main(string[] args) { //relevant code goes here //... //wait for application shutdown await ConsoleUtil.WaitForShutdownAsync(); } } ``` from there creating a *systemd* as in the following link should get you the rest of the way [Writing a Linux daemon in C#](https://developers.redhat.com/blog/2017/06/07/writing-a-linux-daemon-in-c/)
If you're trying to find something more robust, I found an implementation on Github that looks promising: [.NET Core Application blocks for message-based communication](https://github.com/dotnet-architecture/Messaging/). It uses `Host`, `HostBuilder`, `ApplicationServices`, `ApplicationEnvironment`, etc classes to implement a messaging service. It doesn't quite look ready for black box reuse, but it seems like it could be a good starting point. ``` var host = new HostBuilder() .ConfigureServices(services => { var settings = new RabbitMQSettings { ServerName = "192.168.80.129", UserName = "admin", Password = "Pass@word1" }; }) .Build(); Console.WriteLine("Starting..."); await host.StartAsync(); var messenger = host.Services.GetRequiredService<IRabbitMQMessenger>(); Console.WriteLine("Running. Type text and press ENTER to send a message."); Console.CancelKeyPress += async (sender, e) => { Console.WriteLine("Shutting down..."); await host.StopAsync(new CancellationTokenSource(3000).Token); Environment.Exit(0); }; ... ```
41,454,563
I could just write a long-running CLI app and run it, but I'm assuming it wouldn't comply to all the expectations one would have of a standards-compliant linux daemon (responding to SIGTERM, Started by System V init process, Ignore terminal I/O signals, [etc.](https://www.python.org/dev/peps/pep-3143/#id1)) Most ecosystems have some best-practice way of doing this, for example, in python, you can use <https://pypi.python.org/pypi/python-daemon/> Is there some documentation about how to do this with .Net Core?
2017/01/04
[ "https://Stackoverflow.com/questions/41454563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/970673/" ]
Implementing Linux Daemon or service for `windows` quite easy with single codebase using Visual Studio 2019. Just create project using `WorkerService` template. In my case I have [`Coraval`](https://docs.coravel.net/) library to schedule the tasks. `Program.cs` class ``` public class Program { public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.File(@"C:\temp\Workerservice\logfile.txt").CreateLogger(); IHost host = CreateHostBuilder(args).Build(); host.Services.UseScheduler(scheduler => { scheduler .Schedule<ReprocessInvocable>() .EveryThirtySeconds(); }); host.Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args).UseSystemd() //.UseWindowsService() .ConfigureServices(services => { services.AddScheduler(); services.AddTransient<ReprocessInvocable>(); }); } ``` `ReprocessInvocable.cs` class ``` public class ReprocessInvocable : IInvocable { private readonly ILogger<ReprocessInvocable> _logger; public ReprocessInvocable(ILogger<ReprocessInvocable> logger) { _logger = logger; } public async Task Invoke() { //your code goes here _logger.LogInformation("Information - Worker running at: {time}", DateTimeOffset.Now); _logger.LogWarning("Warning - Worker running at: {time}", DateTimeOffset.Now); _logger.LogCritical("Critical - Worker running at: {time}", DateTimeOffset.Now); Log.Information("Invoke has called at: {time}", DateTimeOffset.Now); } } ``` For `linux daemon` use `UseSystemd` and for `windows service` use `UseWindowsService` as per the above code.
I'm not sure it is production grade, but for a quick and dirty console app this works well: ```cs await Task.Delay(-1); //-1 indicates infinite timeout ```
62,328,661
I do understand that higher order functions are functions that take functions as parameters or return functions. I also know that decorators are functions that add some functionality to other functions. What are they exactly. Are they the functions that are passed in as parameters or are they the higher order functions themselves? note: if you will give an example give it in python
2020/06/11
[ "https://Stackoverflow.com/questions/62328661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13675368/" ]
A higher order function is a function that takes a function as an argument OR\* returns a function. A decorator in Python is (typically) an example of a higher-order function, but there are decorators that aren't (class decorators\*\*, and decorators that aren't functions), and there are higher-order functions that aren't decorators, for example those that take two required arguments that are functions. Not decorator, not higher-order function: ========================================= ``` def hello(who): print("Hello", who) ``` Not decorator, but higher-order function: ========================================= ``` def compose(f, g): def wrapper(*args, **kwargs): return g(f(*args, **kwargs)) return wrapper ``` Decorator, not higher-order function: ===================================== ``` def classdeco(cls): cls.__repr__ = lambda self: "WAT" return cls # Usage: @classdeco class Foo: pass ``` Decorator, higher-order function: ================================= ``` def log_calls(fn): def wrapper(*args, **kwargs): print("Calling", fn.__name__) return fn(*args, **kwargs) return wrapper ``` --- \* Not XOR \*\* Whether or not you consider class decorators to be higher-order functions, because classes are callable etc. is up for debate, I guess..
A higher-order function is a function that either takes a function as an argument or returns a function. Decorator *syntax* is a syntactic shortcut: ``` @f def g(...): ... ``` is just a convenient shorthand for ``` def g(...): ... g = f(g) ``` As such, a decorator really is simply a function that takes another function as an argument. It would be more accurate to talk about using `f` *as* a decorator than to say that `f` *is* a decorator.
59,505,322
I am going through a Django tutorial but it's an old one. The videos were all made using Django 1.11 and Python 3.6. Problem is I have installed python3.8 in my machine. So I was trying to create virtualenv with python version 3.6. But as python 3.6 is not available in my machine, I couldn't do that. At this point I was wondering even if it is actually possible to have both python 3.6 and python 3.8 in a machine at same time. Kindly someone help me with this problem or point me to the right resource to understand more on this problem.
2019/12/27
[ "https://Stackoverflow.com/questions/59505322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11748245/" ]
It is possible to have two versions of python installed on the same machine. You might have to do some path manipulation to get things working, depending on the specifics of your setup. You can also probably just follow along with the tutorial using python 3.8 even if the tutorial it-self uses 3.6. You can also use the python launcher to manage multiple versions of python installed on the same machine: <https://docs.python.org/3/using/windows.html#python-launcher-for-windows>
Yes. You can have both versions installed on single machine. All u need to do is to download Python3.6 from its Official site, set your Interpreter to python3.6 and u r all set.
25,502,666
I want to execute a linux shell in python, for example: ``` import os cmd='ps -ef | grep java | grep -v grep' p=os.popen(cmd) print p.read() ``` the code works well in python2.7,but it doesn't work well in python2.4 or python2.6 the problem is: when the environment is 2.4 or 2.6,for each process in linux it only returns one line. for exmaple: this is what i want(and this is just what is returned in 2.7): ``` 59996 17038 17033 0 14:08 pts/3 00:00:02 java -Xms64m -Xmx256m classpath=/home/admin/axxxX xxxx//xxxxxxxx .... root 85751 85750 0 12:25 XXXXX XXXXXXX XXXXXXXX ``` but it actually returns like this(in 2.4 2.6): ``` 59996 17038 17033 0 14:08 pts/3 00:00:02 java -Xms64m -Xmx256m classpath=/home/admin/ax\n root 85751 85750 0 12:25 XXXXX XXXXXXX XXXXXXXX\n ``` that means it cut each item and then there is only one line for each item left,and it adds an `\n` for each item in the result, which is what i don't want to see i have try other method like `subprocess.Popen` or `commands.getstatusoutput(command)`, but the results are the same -- i get only get one line for each item(process) Info: 1. if i execute the shell directly on the ssh of linux, the result is good 2. if i execute `ps -ef |grep java |grep -v grep >>1.txt`, make the result into txtFile,the result is also ok the python script will be executed on so many machines,so it is not proper to update all the machines to python2.7 or newer version I am a little bit worried because the deadline will come soon, and i need help. Looking forward to your answers, thanks very much
2014/08/26
[ "https://Stackoverflow.com/questions/25502666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3978288/" ]
You're making an unwarranted assumption about the behavior of `read`. Use [subprocess.Popen](https://docs.python.org/2.7/library/subprocess.html#popen-objects) (and especially its `communicate` method) to read the whole thing. It was introduced in 2.4. Use the string `splitlines` method as necessary if you want individual lines.
`ps` usually clips its output according to the terminal width but, because you are piping the output to `grep`, `ps` can not determine the width, and so it determines that from various things such as the terminal type, environment variables, or command line options such as `--cols`. You might find that you get different results depending on how you execute your python script. In an interactive session you will most likely see that the output of the pipeline is clipped to your terminal width. If you run the script from the command line you will probably see the full output. Are your tests for the different versions of python being run on the same machine, and in the same manner (interactive vs. command line)? I suspect that some inconsistency here might be causing the different output. Fortunately you can tell `ps` to use unlimited width using the `-ww` command line option: ``` import os cmd='ps -efww | grep java | grep -v grep' p = os.popen(cmd) print p.read() ``` With this you should receive the full `ps` output. Although `subprocess.Popen()` should produce the same result (since `ps` is doing the clipping) you should use it instead of `os.popen()` - when used with `subprocess.communicate()` you can avoid possible deadlocks.
71,662,125
Context ------- The instructions on [the Linux/MacOS instructions](https://github.com/lava-nc/lava#linuxmacos) to setup your device for the Lava neuromorphic computing framework by Intel provide a few pip commands, a git clone command and some poetry instructions. I am used to be able to integrate `pip` commands in an `environment.yml` for conda, and I thought the git clone command could also be included in the `environment.yml` file. However, I am not yet sure how to integrate the poetry commands. Question -------- Hence, I would like to ask: *How can I convert the following installation script into a (single) `conda` environment yaml file?*: ``` cd $HOME pip install -U pip pip install "poetry>=1.1.13" git clone git@github.com:lava-nc/lava.git cd lava poetry config virtualenvs.in-project true poetry install source .venv/bin/activate pytest ``` Attempts -------- I have been able to install the Lava software successfully in a single environment.yml using: ``` # run: conda env create --file lava_environment.yml # include new packages: conda env update --file lava_environment.yml name: lava channels: - conda-forge - conda dependencies: - anaconda - conda: # Run python tests. - pytest=6.1.2 - pip - pip: # Auto generate docstrings - pyment # Run pip install on .tar.gz file in GitHub repository. - https://github.com/lava-nc/lava/releases/download/v0.3.0/lava-nc-0.3.0.tar.gz ``` Which I've installed with: ``` conda env create --file lava_environment.yml ``` However, that [installs it from a binary](https://github.com/lava-nc/lava#windowsmacoslinux) instead of from source.
2022/03/29
[ "https://Stackoverflow.com/questions/71662125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7437143/" ]
Just add the "slideUp" class in your HTML markup: ``` <div class="box slideUp"> ``` NB: the `style="display: none;"` attribute on that element is then no longer needed, nor do you have to execute `$('.box').show()`. Updated snippet: ```js $(".openNav").click(function() { $('.box').toggleClass("slideUp") }); ``` ```css .clickbox { width: 100px; height: 100px; background: #343434; margin: 0 auto; color: #fff; } .openNav { color: #fff; } .box { width: 200px; height: 200px; background: orange; margin: 0 auto; margin-top: 3%; overflow: hidden; transition: all 0.2s ease-in-out; } .box.slideUp { height: 0; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="clickbox"><a href="javascript:;" class="openNav">dddd</a></div> <div class="box slideUp"><a href="javascript:;" class="openNav">dddd</a</div> ```
Try this code: ```js $(".openNav").click(function() { $('.box').slideToggle("fast"); }); ``` ```css .clickbox { width: 100px; height: 100px; background: #343434; margin: 0 auto; color: #fff; } .openNav { color: #fff; } .box { width: 200px; height: 200px; background: orange; margin: 0 auto; margin-top: 3%; overflow: hidden; transition: all 0.2s ease-in-out; } .box.slideUp { height: 0; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="clickbox"><a href="javascript:;" class="openNav">dddd</a></div> <div class="box" style="display: none;"><a href="javascript:;" class="openNav">dddd</a</div> ```
71,662,125
Context ------- The instructions on [the Linux/MacOS instructions](https://github.com/lava-nc/lava#linuxmacos) to setup your device for the Lava neuromorphic computing framework by Intel provide a few pip commands, a git clone command and some poetry instructions. I am used to be able to integrate `pip` commands in an `environment.yml` for conda, and I thought the git clone command could also be included in the `environment.yml` file. However, I am not yet sure how to integrate the poetry commands. Question -------- Hence, I would like to ask: *How can I convert the following installation script into a (single) `conda` environment yaml file?*: ``` cd $HOME pip install -U pip pip install "poetry>=1.1.13" git clone git@github.com:lava-nc/lava.git cd lava poetry config virtualenvs.in-project true poetry install source .venv/bin/activate pytest ``` Attempts -------- I have been able to install the Lava software successfully in a single environment.yml using: ``` # run: conda env create --file lava_environment.yml # include new packages: conda env update --file lava_environment.yml name: lava channels: - conda-forge - conda dependencies: - anaconda - conda: # Run python tests. - pytest=6.1.2 - pip - pip: # Auto generate docstrings - pyment # Run pip install on .tar.gz file in GitHub repository. - https://github.com/lava-nc/lava/releases/download/v0.3.0/lava-nc-0.3.0.tar.gz ``` Which I've installed with: ``` conda env create --file lava_environment.yml ``` However, that [installs it from a binary](https://github.com/lava-nc/lava#windowsmacoslinux) instead of from source.
2022/03/29
[ "https://Stackoverflow.com/questions/71662125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7437143/" ]
Just add the "slideUp" class in your HTML markup: ``` <div class="box slideUp"> ``` NB: the `style="display: none;"` attribute on that element is then no longer needed, nor do you have to execute `$('.box').show()`. Updated snippet: ```js $(".openNav").click(function() { $('.box').toggleClass("slideUp") }); ``` ```css .clickbox { width: 100px; height: 100px; background: #343434; margin: 0 auto; color: #fff; } .openNav { color: #fff; } .box { width: 200px; height: 200px; background: orange; margin: 0 auto; margin-top: 3%; overflow: hidden; transition: all 0.2s ease-in-out; } .box.slideUp { height: 0; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="clickbox"><a href="javascript:;" class="openNav">dddd</a></div> <div class="box slideUp"><a href="javascript:;" class="openNav">dddd</a</div> ```
```html <div class="clickbox"><a href="javascript:;" class="openNav">dddd</a></div> <div class="box"><a href="javascript:;" class="openNav">dddd</a</div> ``` ```js $(".openNav").click(function() { $('.box').show(); $('.box').toggleClass("slideUp") }); ``` ```css .clickbox { width: 100px; height: 100px; background: #343434; margin: 0 auto; color: #fff; } .openNav { color: #fff; } .box { width: 200px; height: 0px; background: orange; margin: 0 auto; margin-top: 3%; overflow: hidden; transition: all 0.2s ease-in-out; } .box.slideUp { height: 200px; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="clickbox"><a href="javascript:;" class="openNav">dddd</a></div> <div class="box" style="display: none;"><a href="javascript:;">dddd</a</div> ```
71,662,125
Context ------- The instructions on [the Linux/MacOS instructions](https://github.com/lava-nc/lava#linuxmacos) to setup your device for the Lava neuromorphic computing framework by Intel provide a few pip commands, a git clone command and some poetry instructions. I am used to be able to integrate `pip` commands in an `environment.yml` for conda, and I thought the git clone command could also be included in the `environment.yml` file. However, I am not yet sure how to integrate the poetry commands. Question -------- Hence, I would like to ask: *How can I convert the following installation script into a (single) `conda` environment yaml file?*: ``` cd $HOME pip install -U pip pip install "poetry>=1.1.13" git clone git@github.com:lava-nc/lava.git cd lava poetry config virtualenvs.in-project true poetry install source .venv/bin/activate pytest ``` Attempts -------- I have been able to install the Lava software successfully in a single environment.yml using: ``` # run: conda env create --file lava_environment.yml # include new packages: conda env update --file lava_environment.yml name: lava channels: - conda-forge - conda dependencies: - anaconda - conda: # Run python tests. - pytest=6.1.2 - pip - pip: # Auto generate docstrings - pyment # Run pip install on .tar.gz file in GitHub repository. - https://github.com/lava-nc/lava/releases/download/v0.3.0/lava-nc-0.3.0.tar.gz ``` Which I've installed with: ``` conda env create --file lava_environment.yml ``` However, that [installs it from a binary](https://github.com/lava-nc/lava#windowsmacoslinux) instead of from source.
2022/03/29
[ "https://Stackoverflow.com/questions/71662125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7437143/" ]
Just add the "slideUp" class in your HTML markup: ``` <div class="box slideUp"> ``` NB: the `style="display: none;"` attribute on that element is then no longer needed, nor do you have to execute `$('.box').show()`. Updated snippet: ```js $(".openNav").click(function() { $('.box').toggleClass("slideUp") }); ``` ```css .clickbox { width: 100px; height: 100px; background: #343434; margin: 0 auto; color: #fff; } .openNav { color: #fff; } .box { width: 200px; height: 200px; background: orange; margin: 0 auto; margin-top: 3%; overflow: hidden; transition: all 0.2s ease-in-out; } .box.slideUp { height: 0; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="clickbox"><a href="javascript:;" class="openNav">dddd</a></div> <div class="box slideUp"><a href="javascript:;" class="openNav">dddd</a</div> ```
```js $(".openNav").click(function() { $('.box').slideToggle(); }); ``` ```css .clickbox { width: 200px; height: 200px; background: yellow; margin: 0 auto; color: #fff; } .openNav { color: #fff; border:1px solid blue; } .box { width: 400px; height: 400px; background: orange; margin: 0 auto; margin-top: 3%; overflow: hidden; transition: all 0.2s ease-in-out; } .box.slideUp { height: 0; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="clickbox"><a href="javascript:;" class="openNav">Hello All How Are You!</a></div> <div class="box" style="display: none;"><a href="javascript:;" class="openNav">Hello All How Are You!</a</di ```
71,662,125
Context ------- The instructions on [the Linux/MacOS instructions](https://github.com/lava-nc/lava#linuxmacos) to setup your device for the Lava neuromorphic computing framework by Intel provide a few pip commands, a git clone command and some poetry instructions. I am used to be able to integrate `pip` commands in an `environment.yml` for conda, and I thought the git clone command could also be included in the `environment.yml` file. However, I am not yet sure how to integrate the poetry commands. Question -------- Hence, I would like to ask: *How can I convert the following installation script into a (single) `conda` environment yaml file?*: ``` cd $HOME pip install -U pip pip install "poetry>=1.1.13" git clone git@github.com:lava-nc/lava.git cd lava poetry config virtualenvs.in-project true poetry install source .venv/bin/activate pytest ``` Attempts -------- I have been able to install the Lava software successfully in a single environment.yml using: ``` # run: conda env create --file lava_environment.yml # include new packages: conda env update --file lava_environment.yml name: lava channels: - conda-forge - conda dependencies: - anaconda - conda: # Run python tests. - pytest=6.1.2 - pip - pip: # Auto generate docstrings - pyment # Run pip install on .tar.gz file in GitHub repository. - https://github.com/lava-nc/lava/releases/download/v0.3.0/lava-nc-0.3.0.tar.gz ``` Which I've installed with: ``` conda env create --file lava_environment.yml ``` However, that [installs it from a binary](https://github.com/lava-nc/lava#windowsmacoslinux) instead of from source.
2022/03/29
[ "https://Stackoverflow.com/questions/71662125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7437143/" ]
Try this code: ```js $(".openNav").click(function() { $('.box').slideToggle("fast"); }); ``` ```css .clickbox { width: 100px; height: 100px; background: #343434; margin: 0 auto; color: #fff; } .openNav { color: #fff; } .box { width: 200px; height: 200px; background: orange; margin: 0 auto; margin-top: 3%; overflow: hidden; transition: all 0.2s ease-in-out; } .box.slideUp { height: 0; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="clickbox"><a href="javascript:;" class="openNav">dddd</a></div> <div class="box" style="display: none;"><a href="javascript:;" class="openNav">dddd</a</div> ```
```js $(".openNav").click(function() { $('.box').slideToggle(); }); ``` ```css .clickbox { width: 200px; height: 200px; background: yellow; margin: 0 auto; color: #fff; } .openNav { color: #fff; border:1px solid blue; } .box { width: 400px; height: 400px; background: orange; margin: 0 auto; margin-top: 3%; overflow: hidden; transition: all 0.2s ease-in-out; } .box.slideUp { height: 0; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="clickbox"><a href="javascript:;" class="openNav">Hello All How Are You!</a></div> <div class="box" style="display: none;"><a href="javascript:;" class="openNav">Hello All How Are You!</a</di ```
71,662,125
Context ------- The instructions on [the Linux/MacOS instructions](https://github.com/lava-nc/lava#linuxmacos) to setup your device for the Lava neuromorphic computing framework by Intel provide a few pip commands, a git clone command and some poetry instructions. I am used to be able to integrate `pip` commands in an `environment.yml` for conda, and I thought the git clone command could also be included in the `environment.yml` file. However, I am not yet sure how to integrate the poetry commands. Question -------- Hence, I would like to ask: *How can I convert the following installation script into a (single) `conda` environment yaml file?*: ``` cd $HOME pip install -U pip pip install "poetry>=1.1.13" git clone git@github.com:lava-nc/lava.git cd lava poetry config virtualenvs.in-project true poetry install source .venv/bin/activate pytest ``` Attempts -------- I have been able to install the Lava software successfully in a single environment.yml using: ``` # run: conda env create --file lava_environment.yml # include new packages: conda env update --file lava_environment.yml name: lava channels: - conda-forge - conda dependencies: - anaconda - conda: # Run python tests. - pytest=6.1.2 - pip - pip: # Auto generate docstrings - pyment # Run pip install on .tar.gz file in GitHub repository. - https://github.com/lava-nc/lava/releases/download/v0.3.0/lava-nc-0.3.0.tar.gz ``` Which I've installed with: ``` conda env create --file lava_environment.yml ``` However, that [installs it from a binary](https://github.com/lava-nc/lava#windowsmacoslinux) instead of from source.
2022/03/29
[ "https://Stackoverflow.com/questions/71662125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7437143/" ]
```html <div class="clickbox"><a href="javascript:;" class="openNav">dddd</a></div> <div class="box"><a href="javascript:;" class="openNav">dddd</a</div> ``` ```js $(".openNav").click(function() { $('.box').show(); $('.box').toggleClass("slideUp") }); ``` ```css .clickbox { width: 100px; height: 100px; background: #343434; margin: 0 auto; color: #fff; } .openNav { color: #fff; } .box { width: 200px; height: 0px; background: orange; margin: 0 auto; margin-top: 3%; overflow: hidden; transition: all 0.2s ease-in-out; } .box.slideUp { height: 200px; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="clickbox"><a href="javascript:;" class="openNav">dddd</a></div> <div class="box" style="display: none;"><a href="javascript:;">dddd</a</div> ```
```js $(".openNav").click(function() { $('.box').slideToggle(); }); ``` ```css .clickbox { width: 200px; height: 200px; background: yellow; margin: 0 auto; color: #fff; } .openNav { color: #fff; border:1px solid blue; } .box { width: 400px; height: 400px; background: orange; margin: 0 auto; margin-top: 3%; overflow: hidden; transition: all 0.2s ease-in-out; } .box.slideUp { height: 0; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="clickbox"><a href="javascript:;" class="openNav">Hello All How Are You!</a></div> <div class="box" style="display: none;"><a href="javascript:;" class="openNav">Hello All How Are You!</a</di ```
56,456,656
I'm a newbie to data science with python. So, I wanted to play around with the following data "<https://www.ssa.gov/OACT/babynames/limits.html>." The main problem here is that instead of giving me one file containing the data for all years, it contains a separate file for each year. Furthermore, each separate file also lacks column headings. FYI, the data contains the names, genders and some identification number of all registered US citizens from 1910 onwards. The data is available to the public (intended to aid demographers tracking trends in popular names). Thus, one major problem I'm facing is the need to edit more than 100 files directly (manually, open each and edit) so as to ensure that all column headings are the same (which is required for a function like concat to work). Another big problem is the sheer magnitude of the task. It's very, very inefficient to use concat for 100\* files, as well as use up more than 100 lines of code in just scanning/reading your data Of course, 'concat' was built for this, but I think it's quite inefficient to use it for around 130 files. Regarding the missing column headings, I've manually edited some files, but there are just too many to be edited directly. ``` names2010 = pd.read_csv("../yob2010.txt") names2011 = pd.read_csv("../yob2011.txt") names = pd.concat([names2010, names2011]) ``` intuitively, this is what I want to avoid> ``` #rough notation names = pd.concat([names1910, names1911 ..., names2017, names2018]) ``` this is just for two years' worth of data. I need to create a single data frame consisting of all data from the years 1910 to 2018. update: I've figured out how to combine all different .txt files, but still need to resolve for column headings. ``` dataframes = pd.read_csv("../yob1910.txt") for year in range(1911, 2019): temp_frame = pd.read_csv("../yob{}.txt".format(year)) dataframes = pd.concat([temp_frame, dataframes]) ```
2019/06/05
[ "https://Stackoverflow.com/questions/56456656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11557970/" ]
I saw people running into this issue on Windows by not realizing that in File Explorer file extensions are hidden by default, so while they wanted to create a file called "config", they actually created a file called "config.txt" and that's not found by kubectl.
I ended up deleting windows and install Ubuntu. Windows was a nightmare.
56,456,656
I'm a newbie to data science with python. So, I wanted to play around with the following data "<https://www.ssa.gov/OACT/babynames/limits.html>." The main problem here is that instead of giving me one file containing the data for all years, it contains a separate file for each year. Furthermore, each separate file also lacks column headings. FYI, the data contains the names, genders and some identification number of all registered US citizens from 1910 onwards. The data is available to the public (intended to aid demographers tracking trends in popular names). Thus, one major problem I'm facing is the need to edit more than 100 files directly (manually, open each and edit) so as to ensure that all column headings are the same (which is required for a function like concat to work). Another big problem is the sheer magnitude of the task. It's very, very inefficient to use concat for 100\* files, as well as use up more than 100 lines of code in just scanning/reading your data Of course, 'concat' was built for this, but I think it's quite inefficient to use it for around 130 files. Regarding the missing column headings, I've manually edited some files, but there are just too many to be edited directly. ``` names2010 = pd.read_csv("../yob2010.txt") names2011 = pd.read_csv("../yob2011.txt") names = pd.concat([names2010, names2011]) ``` intuitively, this is what I want to avoid> ``` #rough notation names = pd.concat([names1910, names1911 ..., names2017, names2018]) ``` this is just for two years' worth of data. I need to create a single data frame consisting of all data from the years 1910 to 2018. update: I've figured out how to combine all different .txt files, but still need to resolve for column headings. ``` dataframes = pd.read_csv("../yob1910.txt") for year in range(1911, 2019): temp_frame = pd.read_csv("../yob{}.txt".format(year)) dataframes = pd.concat([temp_frame, dataframes]) ```
2019/06/05
[ "https://Stackoverflow.com/questions/56456656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11557970/" ]
Generally if you want to configure your kubectl to use your GKE cluster, you have to run below commands to copy k8s configuration to local. 1.First list your cluster names (under NAME column) and recognize zone (under Location column) ``` $ gcloud container clusters list ``` 2.Then run below command to copy k8s config to local ``` $ gcloud container clusters get-credentials <cluster-name> --zone <zone> ``` 3.Then check config ``` $ kubectl config view ```
I ended up deleting windows and install Ubuntu. Windows was a nightmare.
56,456,656
I'm a newbie to data science with python. So, I wanted to play around with the following data "<https://www.ssa.gov/OACT/babynames/limits.html>." The main problem here is that instead of giving me one file containing the data for all years, it contains a separate file for each year. Furthermore, each separate file also lacks column headings. FYI, the data contains the names, genders and some identification number of all registered US citizens from 1910 onwards. The data is available to the public (intended to aid demographers tracking trends in popular names). Thus, one major problem I'm facing is the need to edit more than 100 files directly (manually, open each and edit) so as to ensure that all column headings are the same (which is required for a function like concat to work). Another big problem is the sheer magnitude of the task. It's very, very inefficient to use concat for 100\* files, as well as use up more than 100 lines of code in just scanning/reading your data Of course, 'concat' was built for this, but I think it's quite inefficient to use it for around 130 files. Regarding the missing column headings, I've manually edited some files, but there are just too many to be edited directly. ``` names2010 = pd.read_csv("../yob2010.txt") names2011 = pd.read_csv("../yob2011.txt") names = pd.concat([names2010, names2011]) ``` intuitively, this is what I want to avoid> ``` #rough notation names = pd.concat([names1910, names1911 ..., names2017, names2018]) ``` this is just for two years' worth of data. I need to create a single data frame consisting of all data from the years 1910 to 2018. update: I've figured out how to combine all different .txt files, but still need to resolve for column headings. ``` dataframes = pd.read_csv("../yob1910.txt") for year in range(1911, 2019): temp_frame = pd.read_csv("../yob{}.txt".format(year)) dataframes = pd.concat([temp_frame, dataframes]) ```
2019/06/05
[ "https://Stackoverflow.com/questions/56456656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11557970/" ]
Generally if you want to configure your kubectl to use your GKE cluster, you have to run below commands to copy k8s configuration to local. 1.First list your cluster names (under NAME column) and recognize zone (under Location column) ``` $ gcloud container clusters list ``` 2.Then run below command to copy k8s config to local ``` $ gcloud container clusters get-credentials <cluster-name> --zone <zone> ``` 3.Then check config ``` $ kubectl config view ```
I saw people running into this issue on Windows by not realizing that in File Explorer file extensions are hidden by default, so while they wanted to create a file called "config", they actually created a file called "config.txt" and that's not found by kubectl.
53,421,991
I am using Visual Studio Code as my IDE for building web applications using Python's Django web development framework. I am developing on a 2018 MacBook Pro. I am able to launch my web applications by launching them in the terminal using: ``` python3 manage.py runserver ``` However, I want to be able to launch my application through the debugger. To try and do this, I navigated to the debug section, created the launch.json file, and changed my configuration in the drop down to Python: Django. Here is are my configurations from the file. ``` { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "console": "integratedTerminal", "args": [ "runserver", "--noreload", "--nothreading" ], "django": true }, ``` When I try to run the debugger using the green play arrow, I get the following exception: > > **Exception has occurred: ImportError** > Couldn't import Django. Are you > sure it's installed and available on your PYTHONPATH environment > variable? Did you forget to activate a virtual environment? File > "/Users/justinoconnor/Desktop/Rapid > Prototyping/Projects/hello\_django/manage.py", line 14, in > ) from exc > > > Launching the VS Code debugger with this configuration should be the same as running python manage.py runserver --noreload --nothreading, but it is not working. I'm thinking it is because on the MacBook I have to use the "python3" command rather than "python", but I did not see anything in the documentation that would allow me to specify this in the launch.json configuration file. Does anyone know how to resolve this so that when I run the debugger it automatically executes/saves my project? I don't understand why this is not working when I can type python3 manage.py runserver into the terminal and it will execute just fine.
2018/11/21
[ "https://Stackoverflow.com/questions/53421991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5644892/" ]
Use the command `virtualenv -p python3 venv` (or replace "venv" with your virtual environment name) in the terminal to create the virtual environment with python3 as the default when "python" is used in the terminal (e.g. `python manage.py ...`). The `-p` is used to specify a specific version of python.
The issue was that I used the "python" command instead of the "python3" command when creating the virtual environment for my project. This was causing the debugger to execute the wrong command when trying run the local server. I was able to create a new virtual environment using the command ... ``` python3 -m venv env ``` ... that the Visual Studio Code debugger was able to successfully recognize when debugging using the "Python: Django" drop down configuration.
53,421,991
I am using Visual Studio Code as my IDE for building web applications using Python's Django web development framework. I am developing on a 2018 MacBook Pro. I am able to launch my web applications by launching them in the terminal using: ``` python3 manage.py runserver ``` However, I want to be able to launch my application through the debugger. To try and do this, I navigated to the debug section, created the launch.json file, and changed my configuration in the drop down to Python: Django. Here is are my configurations from the file. ``` { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "console": "integratedTerminal", "args": [ "runserver", "--noreload", "--nothreading" ], "django": true }, ``` When I try to run the debugger using the green play arrow, I get the following exception: > > **Exception has occurred: ImportError** > Couldn't import Django. Are you > sure it's installed and available on your PYTHONPATH environment > variable? Did you forget to activate a virtual environment? File > "/Users/justinoconnor/Desktop/Rapid > Prototyping/Projects/hello\_django/manage.py", line 14, in > ) from exc > > > Launching the VS Code debugger with this configuration should be the same as running python manage.py runserver --noreload --nothreading, but it is not working. I'm thinking it is because on the MacBook I have to use the "python3" command rather than "python", but I did not see anything in the documentation that would allow me to specify this in the launch.json configuration file. Does anyone know how to resolve this so that when I run the debugger it automatically executes/saves my project? I don't understand why this is not working when I can type python3 manage.py runserver into the terminal and it will execute just fine.
2018/11/21
[ "https://Stackoverflow.com/questions/53421991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5644892/" ]
Same issue caused to my VS Code environment even launching VS Code after activating venv (Python virtual environment). The VS Code also displayed the Python Environment option "Python 3.7.3 64 bit" on the Status Bar. On first sight, this python environment option looks correct. But, my issue resolved after applying Boregore's comment. Python Environment option related with **venv** python needs to be selected as an interpreter. I selected the correct Python Environment option related with venv (in my case i.e. ~/.virtualenvs/djangodev/bin/python), by applying following steps, 1. Select a Python 3 interpreter by opening the Command Palette (Ctrl+Shift+P). 2. Start typing the Python: Select Interpreter command to search, then select the command. You can also use the Select Python Environment option on the Status Bar if available (it may already show a selected interpreter, too) 3. Select Python Environment option showing venv path (in my case, i.e. ~/.virtualenvs/djangodev/bin/python) 4. Now, VS Code displays the Python Environment option related with venv, (in my case, i.e. "Python 3.7.3 64 bit **('djangodev': venv)**" on the Status Bar. 5. Re-run debug steps. (Many thanks to Boregore for providing solution, this is just a re-elaboration of his comment to the actual question)
The issue was that I used the "python" command instead of the "python3" command when creating the virtual environment for my project. This was causing the debugger to execute the wrong command when trying run the local server. I was able to create a new virtual environment using the command ... ``` python3 -m venv env ``` ... that the Visual Studio Code debugger was able to successfully recognize when debugging using the "Python: Django" drop down configuration.
53,421,991
I am using Visual Studio Code as my IDE for building web applications using Python's Django web development framework. I am developing on a 2018 MacBook Pro. I am able to launch my web applications by launching them in the terminal using: ``` python3 manage.py runserver ``` However, I want to be able to launch my application through the debugger. To try and do this, I navigated to the debug section, created the launch.json file, and changed my configuration in the drop down to Python: Django. Here is are my configurations from the file. ``` { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "console": "integratedTerminal", "args": [ "runserver", "--noreload", "--nothreading" ], "django": true }, ``` When I try to run the debugger using the green play arrow, I get the following exception: > > **Exception has occurred: ImportError** > Couldn't import Django. Are you > sure it's installed and available on your PYTHONPATH environment > variable? Did you forget to activate a virtual environment? File > "/Users/justinoconnor/Desktop/Rapid > Prototyping/Projects/hello\_django/manage.py", line 14, in > ) from exc > > > Launching the VS Code debugger with this configuration should be the same as running python manage.py runserver --noreload --nothreading, but it is not working. I'm thinking it is because on the MacBook I have to use the "python3" command rather than "python", but I did not see anything in the documentation that would allow me to specify this in the launch.json configuration file. Does anyone know how to resolve this so that when I run the debugger it automatically executes/saves my project? I don't understand why this is not working when I can type python3 manage.py runserver into the terminal and it will execute just fine.
2018/11/21
[ "https://Stackoverflow.com/questions/53421991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5644892/" ]
Same issue caused to my VS Code environment even launching VS Code after activating venv (Python virtual environment). The VS Code also displayed the Python Environment option "Python 3.7.3 64 bit" on the Status Bar. On first sight, this python environment option looks correct. But, my issue resolved after applying Boregore's comment. Python Environment option related with **venv** python needs to be selected as an interpreter. I selected the correct Python Environment option related with venv (in my case i.e. ~/.virtualenvs/djangodev/bin/python), by applying following steps, 1. Select a Python 3 interpreter by opening the Command Palette (Ctrl+Shift+P). 2. Start typing the Python: Select Interpreter command to search, then select the command. You can also use the Select Python Environment option on the Status Bar if available (it may already show a selected interpreter, too) 3. Select Python Environment option showing venv path (in my case, i.e. ~/.virtualenvs/djangodev/bin/python) 4. Now, VS Code displays the Python Environment option related with venv, (in my case, i.e. "Python 3.7.3 64 bit **('djangodev': venv)**" on the Status Bar. 5. Re-run debug steps. (Many thanks to Boregore for providing solution, this is just a re-elaboration of his comment to the actual question)
Use the command `virtualenv -p python3 venv` (or replace "venv" with your virtual environment name) in the terminal to create the virtual environment with python3 as the default when "python" is used in the terminal (e.g. `python manage.py ...`). The `-p` is used to specify a specific version of python.
860,140
What is the best way to find out the user that a python process is running under? I could do this: ``` name = os.popen('whoami').read() ``` But that has to start a whole new process. ``` os.environ["USER"] ``` works sometimes, but sometimes that environment variable isn't set.
2009/05/13
[ "https://Stackoverflow.com/questions/860140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83898/" ]
``` import getpass print(getpass.getuser()) ``` See the documentation of the [getpass](https://docs.python.org/3/library/getpass.html) module. > > getpass.getuser() > > > Return the “login name” of the user. Availability: Unix, Windows. > > > This function checks the environment variables LOGNAME, USER, > LNAME and USERNAME, in order, and > returns the value of the first one > which is set to a non-empty string. If > none are set, the login name from the > password database is returned on > systems which support the pwd module, > otherwise, an exception is raised. > > >
This should work under Unix. ``` import os print(os.getuid()) # numeric uid import pwd print(pwd.getpwuid(os.getuid())) # full /etc/passwd info ```
2,664,099
I've found numerous posts on stackoverflow on how to store user passwords. However, I need to know what is the best way to store a password that my application needs to communicate with another application via the web? Currently, our web app needs to transmit data to a remote website. To upload the data, our web app reads the password from a text file and creates the header with payloads and submits via https. This password in plain text on the file system is the issue. Is there any way to store the password more securely? This is a linux os and the application is written in python and is not compiled. Further clarification: There are no users involved in this process at all. The password stored in the file system is used by the other web app to authenticate the web app that is making the request. To put it in the words of a commenter below: "In this case, the application is the client to another remote application."
2010/04/18
[ "https://Stackoverflow.com/questions/2664099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use a two-way key encryption algorithms like RSA, The password is stored encrypted (by a key, which is stored in the user's brain) on the filesystem, but to decode the password, the user must enter the key.
I don't think you are understanding the answers provided. You don't ever store a plain-text password anywhere, nor do you transmit it to another device. > > You wrote: Sorry, but the issue is storing a > password on the file system... This > password is needed to authenticate by > the other web app. > > > You can't count on file system protections to keep plain-text safe which is why others have responded that you need SHA or similar. If you think that a hashed password can't be sufficient for authentication, you don't understand the relevant algorithm: 1. get password P from user 2. store encrypted (e.g. salted hash) password Q someplace relatively secure 3. forget P (even clear the buffer you used to read it) 4. send Q to remote host H 5. H gets password P' from user when needed 6. H computes Q' from P', compares Q' to Q for equality
2,664,099
I've found numerous posts on stackoverflow on how to store user passwords. However, I need to know what is the best way to store a password that my application needs to communicate with another application via the web? Currently, our web app needs to transmit data to a remote website. To upload the data, our web app reads the password from a text file and creates the header with payloads and submits via https. This password in plain text on the file system is the issue. Is there any way to store the password more securely? This is a linux os and the application is written in python and is not compiled. Further clarification: There are no users involved in this process at all. The password stored in the file system is used by the other web app to authenticate the web app that is making the request. To put it in the words of a commenter below: "In this case, the application is the client to another remote application."
2010/04/18
[ "https://Stackoverflow.com/questions/2664099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use a two-way key encryption algorithms like RSA, The password is stored encrypted (by a key, which is stored in the user's brain) on the filesystem, but to decode the password, the user must enter the key.
Is your web application hosted on a farm? If not then a technology such as [DPAPI](http://msdn.microsoft.com/en-us/library/ms995355.aspx) will allow you to encrypt the password so that it can only be decrypted on the machine it was encrypted on. From memory there can be problems with using it on a web farm though, as you need to go and re-encrypt the value for each server. If it is a web farm then you probably want to use some form of RSA encryption as has been suggested in other answers. EDIT: DPAPI is only good if you are hosting on windows of course...
2,664,099
I've found numerous posts on stackoverflow on how to store user passwords. However, I need to know what is the best way to store a password that my application needs to communicate with another application via the web? Currently, our web app needs to transmit data to a remote website. To upload the data, our web app reads the password from a text file and creates the header with payloads and submits via https. This password in plain text on the file system is the issue. Is there any way to store the password more securely? This is a linux os and the application is written in python and is not compiled. Further clarification: There are no users involved in this process at all. The password stored in the file system is used by the other web app to authenticate the web app that is making the request. To put it in the words of a commenter below: "In this case, the application is the client to another remote application."
2010/04/18
[ "https://Stackoverflow.com/questions/2664099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I don't think you will find a foolproof way to do this. I would suggest a combination of things to achieve 'security by obscurity': * store the password file on a different computer than the one which will use it * store the file path in a separate config file on the app nachine * use permissions to limit access to the config and password files to your process only * audit file access if your system allows it (keep a log of who touched the files) * give the folders and files innocuous names (/usr/joe/kittens.txt?) * block physical access to the computer(s) (offsite hosting, or locked closet, or something)
At the very least you should use permissions (if you are on a filesystem which supports them) to ensure that you are the only one able to read the file. In addition, if your app is compiled, it would not be too difficult to encrypt the password with a hard-coded passphrase. If the code is not compiled this method wouldn't really be helpful, as a would-be attacker could just read the source and determine the encryption.
2,664,099
I've found numerous posts on stackoverflow on how to store user passwords. However, I need to know what is the best way to store a password that my application needs to communicate with another application via the web? Currently, our web app needs to transmit data to a remote website. To upload the data, our web app reads the password from a text file and creates the header with payloads and submits via https. This password in plain text on the file system is the issue. Is there any way to store the password more securely? This is a linux os and the application is written in python and is not compiled. Further clarification: There are no users involved in this process at all. The password stored in the file system is used by the other web app to authenticate the web app that is making the request. To put it in the words of a commenter below: "In this case, the application is the client to another remote application."
2010/04/18
[ "https://Stackoverflow.com/questions/2664099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I don't think you will find a foolproof way to do this. I would suggest a combination of things to achieve 'security by obscurity': * store the password file on a different computer than the one which will use it * store the file path in a separate config file on the app nachine * use permissions to limit access to the config and password files to your process only * audit file access if your system allows it (keep a log of who touched the files) * give the folders and files innocuous names (/usr/joe/kittens.txt?) * block physical access to the computer(s) (offsite hosting, or locked closet, or something)
Is your web application hosted on a farm? If not then a technology such as [DPAPI](http://msdn.microsoft.com/en-us/library/ms995355.aspx) will allow you to encrypt the password so that it can only be decrypted on the machine it was encrypted on. From memory there can be problems with using it on a web farm though, as you need to go and re-encrypt the value for each server. If it is a web farm then you probably want to use some form of RSA encryption as has been suggested in other answers. EDIT: DPAPI is only good if you are hosting on windows of course...
2,664,099
I've found numerous posts on stackoverflow on how to store user passwords. However, I need to know what is the best way to store a password that my application needs to communicate with another application via the web? Currently, our web app needs to transmit data to a remote website. To upload the data, our web app reads the password from a text file and creates the header with payloads and submits via https. This password in plain text on the file system is the issue. Is there any way to store the password more securely? This is a linux os and the application is written in python and is not compiled. Further clarification: There are no users involved in this process at all. The password stored in the file system is used by the other web app to authenticate the web app that is making the request. To put it in the words of a commenter below: "In this case, the application is the client to another remote application."
2010/04/18
[ "https://Stackoverflow.com/questions/2664099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
From the question it seems you need to store password in such a way, that it can be read and used in an automated transaction with another site. You could encrypt the password and store it encrypted in the file, then decrypt it using a key stored elsewhere in your system before using it. This makes difficulties to someone that gets access to the file from using the password, as they now have to find the key and encryption algorithm used, so they can decrypt it. As defense, more lesser defense is always better than one strong defense that fails when breached. Moreover, I would also secure the file containing the password, rather than the password itself. Configure your webserver to disable possibility to serve the file containing the password, and try to set the process needing the file to run under a separate account, so you can restrict the access to the file to account running the process and admin accounts only.
Is your web application hosted on a farm? If not then a technology such as [DPAPI](http://msdn.microsoft.com/en-us/library/ms995355.aspx) will allow you to encrypt the password so that it can only be decrypted on the machine it was encrypted on. From memory there can be problems with using it on a web farm though, as you need to go and re-encrypt the value for each server. If it is a web farm then you probably want to use some form of RSA encryption as has been suggested in other answers. EDIT: DPAPI is only good if you are hosting on windows of course...
2,664,099
I've found numerous posts on stackoverflow on how to store user passwords. However, I need to know what is the best way to store a password that my application needs to communicate with another application via the web? Currently, our web app needs to transmit data to a remote website. To upload the data, our web app reads the password from a text file and creates the header with payloads and submits via https. This password in plain text on the file system is the issue. Is there any way to store the password more securely? This is a linux os and the application is written in python and is not compiled. Further clarification: There are no users involved in this process at all. The password stored in the file system is used by the other web app to authenticate the web app that is making the request. To put it in the words of a commenter below: "In this case, the application is the client to another remote application."
2010/04/18
[ "https://Stackoverflow.com/questions/2664099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
From the question it seems you need to store password in such a way, that it can be read and used in an automated transaction with another site. You could encrypt the password and store it encrypted in the file, then decrypt it using a key stored elsewhere in your system before using it. This makes difficulties to someone that gets access to the file from using the password, as they now have to find the key and encryption algorithm used, so they can decrypt it. As defense, more lesser defense is always better than one strong defense that fails when breached. Moreover, I would also secure the file containing the password, rather than the password itself. Configure your webserver to disable possibility to serve the file containing the password, and try to set the process needing the file to run under a separate account, so you can restrict the access to the file to account running the process and admin accounts only.
You can store it as a result of hash algorithm, this is one way algorithm (eg. MD5 or SHA). On authentication you calc MD5 of password typed by user and checking equality with your stored MD5 password hash for this user. If is equal password is ok. For more information about hasing algorithms you can visit: * <http://en.wikipedia.org/wiki/Secure_Hash_Algorithm> * <http://en.wikipedia.org/wiki/MD5>
2,664,099
I've found numerous posts on stackoverflow on how to store user passwords. However, I need to know what is the best way to store a password that my application needs to communicate with another application via the web? Currently, our web app needs to transmit data to a remote website. To upload the data, our web app reads the password from a text file and creates the header with payloads and submits via https. This password in plain text on the file system is the issue. Is there any way to store the password more securely? This is a linux os and the application is written in python and is not compiled. Further clarification: There are no users involved in this process at all. The password stored in the file system is used by the other web app to authenticate the web app that is making the request. To put it in the words of a commenter below: "In this case, the application is the client to another remote application."
2010/04/18
[ "https://Stackoverflow.com/questions/2664099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
From the question it seems you need to store password in such a way, that it can be read and used in an automated transaction with another site. You could encrypt the password and store it encrypted in the file, then decrypt it using a key stored elsewhere in your system before using it. This makes difficulties to someone that gets access to the file from using the password, as they now have to find the key and encryption algorithm used, so they can decrypt it. As defense, more lesser defense is always better than one strong defense that fails when breached. Moreover, I would also secure the file containing the password, rather than the password itself. Configure your webserver to disable possibility to serve the file containing the password, and try to set the process needing the file to run under a separate account, so you can restrict the access to the file to account running the process and admin accounts only.
I don't think you are understanding the answers provided. You don't ever store a plain-text password anywhere, nor do you transmit it to another device. > > You wrote: Sorry, but the issue is storing a > password on the file system... This > password is needed to authenticate by > the other web app. > > > You can't count on file system protections to keep plain-text safe which is why others have responded that you need SHA or similar. If you think that a hashed password can't be sufficient for authentication, you don't understand the relevant algorithm: 1. get password P from user 2. store encrypted (e.g. salted hash) password Q someplace relatively secure 3. forget P (even clear the buffer you used to read it) 4. send Q to remote host H 5. H gets password P' from user when needed 6. H computes Q' from P', compares Q' to Q for equality
2,664,099
I've found numerous posts on stackoverflow on how to store user passwords. However, I need to know what is the best way to store a password that my application needs to communicate with another application via the web? Currently, our web app needs to transmit data to a remote website. To upload the data, our web app reads the password from a text file and creates the header with payloads and submits via https. This password in plain text on the file system is the issue. Is there any way to store the password more securely? This is a linux os and the application is written in python and is not compiled. Further clarification: There are no users involved in this process at all. The password stored in the file system is used by the other web app to authenticate the web app that is making the request. To put it in the words of a commenter below: "In this case, the application is the client to another remote application."
2010/04/18
[ "https://Stackoverflow.com/questions/2664099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
At the very least you should use permissions (if you are on a filesystem which supports them) to ensure that you are the only one able to read the file. In addition, if your app is compiled, it would not be too difficult to encrypt the password with a hard-coded passphrase. If the code is not compiled this method wouldn't really be helpful, as a would-be attacker could just read the source and determine the encryption.
You can store it as a result of hash algorithm, this is one way algorithm (eg. MD5 or SHA). On authentication you calc MD5 of password typed by user and checking equality with your stored MD5 password hash for this user. If is equal password is ok. For more information about hasing algorithms you can visit: * <http://en.wikipedia.org/wiki/Secure_Hash_Algorithm> * <http://en.wikipedia.org/wiki/MD5>
2,664,099
I've found numerous posts on stackoverflow on how to store user passwords. However, I need to know what is the best way to store a password that my application needs to communicate with another application via the web? Currently, our web app needs to transmit data to a remote website. To upload the data, our web app reads the password from a text file and creates the header with payloads and submits via https. This password in plain text on the file system is the issue. Is there any way to store the password more securely? This is a linux os and the application is written in python and is not compiled. Further clarification: There are no users involved in this process at all. The password stored in the file system is used by the other web app to authenticate the web app that is making the request. To put it in the words of a commenter below: "In this case, the application is the client to another remote application."
2010/04/18
[ "https://Stackoverflow.com/questions/2664099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
At the very least you should use permissions (if you are on a filesystem which supports them) to ensure that you are the only one able to read the file. In addition, if your app is compiled, it would not be too difficult to encrypt the password with a hard-coded passphrase. If the code is not compiled this method wouldn't really be helpful, as a would-be attacker could just read the source and determine the encryption.
[Protecting the Automatic Logon Password](https://msdn.microsoft.com/en-us/library/aa378826.aspx) The LsaStorePrivateData function can be used by server applications to store client and machine passwords. Windows only
2,664,099
I've found numerous posts on stackoverflow on how to store user passwords. However, I need to know what is the best way to store a password that my application needs to communicate with another application via the web? Currently, our web app needs to transmit data to a remote website. To upload the data, our web app reads the password from a text file and creates the header with payloads and submits via https. This password in plain text on the file system is the issue. Is there any way to store the password more securely? This is a linux os and the application is written in python and is not compiled. Further clarification: There are no users involved in this process at all. The password stored in the file system is used by the other web app to authenticate the web app that is making the request. To put it in the words of a commenter below: "In this case, the application is the client to another remote application."
2010/04/18
[ "https://Stackoverflow.com/questions/2664099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
From the question it seems you need to store password in such a way, that it can be read and used in an automated transaction with another site. You could encrypt the password and store it encrypted in the file, then decrypt it using a key stored elsewhere in your system before using it. This makes difficulties to someone that gets access to the file from using the password, as they now have to find the key and encryption algorithm used, so they can decrypt it. As defense, more lesser defense is always better than one strong defense that fails when breached. Moreover, I would also secure the file containing the password, rather than the password itself. Configure your webserver to disable possibility to serve the file containing the password, and try to set the process needing the file to run under a separate account, so you can restrict the access to the file to account running the process and admin accounts only.
At the very least you should use permissions (if you are on a filesystem which supports them) to ensure that you are the only one able to read the file. In addition, if your app is compiled, it would not be too difficult to encrypt the password with a hard-coded passphrase. If the code is not compiled this method wouldn't really be helpful, as a would-be attacker could just read the source and determine the encryption.
49,524,189
Comparing two lists is tough, there are numerous posts on this subject. But what if I have a list of lists? Simplified to extreme: ``` members=[['john',1964,'NY'], \ ['anna',1991,'CA'], \ ['bert',2001,'AL'], \ ['eddy',1990,'OH']] cash =[['john',200], \ ['dirk',200], \ ['anna',300], \ ['eddy',150]] ``` What I need are differences and intersections: ``` a =[['john',1964,'NY'], \ ['anna',1991,'CA'], \ ['eddy',1990,'OH']] #BOTH in members and cash b =[['bert',2001,'AL']] #in members only ``` Usually I handle this with a loop, but I feel it is time to switch to a more pythonic way. The big problem is that I have to fish out the whole (sub)list while comparing just it's first element. The only way I imagine is to make two sets of names, compare these and recreate the lists (of lists) from the sets of differences. Not much better than a loop.
2018/03/28
[ "https://Stackoverflow.com/questions/49524189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8407665/" ]
You'll need a nested list comprehension. Additionally, you can get rid of punctuation using `re.sub`. ``` import re data = ["How are you. Don't wait for me", "this is all fine"] words = [ re.sub([^a-z\s], '', j.lower()).split() for i in data for j in nlp(i).sents ] ``` Or, ``` words = [] for i in data: ... # do something here for j in nlp(i).sents: words.append(re.sub([^a-z\s], '', j.lower()).split()) ```
There is a much simpler way for list comprehension. You can first join the strings with a period '.' and split them again. ``` [x.split() for x in '.'.join(s).split('.')] ``` It will give the desired result. ``` [["How", "are","you"],["Don't", "wait", "for", "me"],["this","is","all","fine"]] ``` For Pandas dataframes, you may get an object, and hence a list of lists after `tolist` function in return. Just extract the first element. For example, ``` import pandas as pd def splitwords(s): s1 = [x.split() for x in '.'.join(s).split('.')] return s1 df = pd.DataFrame(s) result = df.apply(splitwords).tolist()[0] ``` Again, it will give you the preferred result. Hope it helps ;)
18,423,941
I have an excel sheet that has a lot of data in it in one column in the form of a python dictionary from a sql database. I don't have access to the original database and I can't import the CSV back into sql with the local infile command due to the fact that the keys/values on each row of the CSV are not in the same order. When I export the excel sheet to CSV I get: ``` "{""first_name"":""John"",""last_name"":""Smith"",""age"":30}" "{""first_name"":""Tim"",""last_name"":""Johnson"",""age"":34}" ``` What is the best way to remove the " before and after the curly brackets as well as the extra " around the keys/values? I also need to leave the integers alone that don't have quotes around them. I am trying to then import this into python with the json module so that I can print specific keys but I can't import them with the doubled double quotes. I ultimately need the data saved in a file that looks like: ``` {"first_name":"John","last_name":"Smith","age":30} {"first_name":"Tim","last_name":"Johnson","age":34} ``` Any help is most appreciated!
2013/08/24
[ "https://Stackoverflow.com/questions/18423941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/802136/" ]
If the input file is just as shown, and of the small size you mention, you can load the whole file in memory, make the substitutions, and then save it. IMHO, you don't need a RegEx to do this. The easiest to read code that does this is: ``` with open(filename) as f: input= f.read() input= str.replace('""','"') input= str.replace('"{','{') input= str.replace('}"','}') with open(filename, "w") as f: f.write(input) ``` I tested it with the sample input and it produces: ``` {"first_name":"John","last_name":"Smith","age":30} {"first_name":"Tim","last_name":"Johnson","age":34} ``` Which is exactly what you want. If you want, you can also pack the code and write ``` with open(inputFilename) as if: with open(outputFilename, "w") as of: of.write(if.read().replace('""','"').replace('"{','{').replace('}"','}')) ``` but I think the first one is much clearer and both do exactly the same.
I think you are overthinking the problem, why don't replace data? ``` l = list() with open('foo.txt') as f: for line in f: l.append(line.replace('""','"').replace('"{','{').replace('}"','}')) s = ''.join(l) print s # or save it to file ``` It generates: ``` {"first_name":"John","last_name":"Smith","age":30} {"first_name":"Tim","last_name":"Johnson","age":34} ``` Use a `list` to store intermediate lines and then invoke `.join` for improving performance as explained in [Good way to append to a string](https://stackoverflow.com/questions/4435169/good-way-to-append-to-a-string)
18,423,941
I have an excel sheet that has a lot of data in it in one column in the form of a python dictionary from a sql database. I don't have access to the original database and I can't import the CSV back into sql with the local infile command due to the fact that the keys/values on each row of the CSV are not in the same order. When I export the excel sheet to CSV I get: ``` "{""first_name"":""John"",""last_name"":""Smith"",""age"":30}" "{""first_name"":""Tim"",""last_name"":""Johnson"",""age"":34}" ``` What is the best way to remove the " before and after the curly brackets as well as the extra " around the keys/values? I also need to leave the integers alone that don't have quotes around them. I am trying to then import this into python with the json module so that I can print specific keys but I can't import them with the doubled double quotes. I ultimately need the data saved in a file that looks like: ``` {"first_name":"John","last_name":"Smith","age":30} {"first_name":"Tim","last_name":"Johnson","age":34} ``` Any help is most appreciated!
2013/08/24
[ "https://Stackoverflow.com/questions/18423941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/802136/" ]
Easy: `text = re.sub(r'"(?!")', '', text)` ------------------------------------ Given the input file: TEST.TXT: `"{""first_name"":""John"",""last_name"":""Smith"",""age"":30}"` `"{""first_name"":""Tim"",""last_name"":""Johnson"",""age"":34}"` The script: ```py import re f = open("TEST.TXT","r") text_in = f.read() text_out = re.sub(r'"(?!")', '', text_in) print(text_out) ``` produces the following output: `{"first_name":"John","last_name":"Smith","age":30}` `{"first_name":"Tim","last_name":"Johnson","age":34}`
I think you are overthinking the problem, why don't replace data? ``` l = list() with open('foo.txt') as f: for line in f: l.append(line.replace('""','"').replace('"{','{').replace('}"','}')) s = ''.join(l) print s # or save it to file ``` It generates: ``` {"first_name":"John","last_name":"Smith","age":30} {"first_name":"Tim","last_name":"Johnson","age":34} ``` Use a `list` to store intermediate lines and then invoke `.join` for improving performance as explained in [Good way to append to a string](https://stackoverflow.com/questions/4435169/good-way-to-append-to-a-string)
18,423,941
I have an excel sheet that has a lot of data in it in one column in the form of a python dictionary from a sql database. I don't have access to the original database and I can't import the CSV back into sql with the local infile command due to the fact that the keys/values on each row of the CSV are not in the same order. When I export the excel sheet to CSV I get: ``` "{""first_name"":""John"",""last_name"":""Smith"",""age"":30}" "{""first_name"":""Tim"",""last_name"":""Johnson"",""age"":34}" ``` What is the best way to remove the " before and after the curly brackets as well as the extra " around the keys/values? I also need to leave the integers alone that don't have quotes around them. I am trying to then import this into python with the json module so that I can print specific keys but I can't import them with the doubled double quotes. I ultimately need the data saved in a file that looks like: ``` {"first_name":"John","last_name":"Smith","age":30} {"first_name":"Tim","last_name":"Johnson","age":34} ``` Any help is most appreciated!
2013/08/24
[ "https://Stackoverflow.com/questions/18423941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/802136/" ]
This should do it: ``` with open('old.csv') as old, open('new.csv', 'w') as new: new.writelines(re.sub(r'"(?!")', '', line) for line in old) ```
I think you are overthinking the problem, why don't replace data? ``` l = list() with open('foo.txt') as f: for line in f: l.append(line.replace('""','"').replace('"{','{').replace('}"','}')) s = ''.join(l) print s # or save it to file ``` It generates: ``` {"first_name":"John","last_name":"Smith","age":30} {"first_name":"Tim","last_name":"Johnson","age":34} ``` Use a `list` to store intermediate lines and then invoke `.join` for improving performance as explained in [Good way to append to a string](https://stackoverflow.com/questions/4435169/good-way-to-append-to-a-string)
18,423,941
I have an excel sheet that has a lot of data in it in one column in the form of a python dictionary from a sql database. I don't have access to the original database and I can't import the CSV back into sql with the local infile command due to the fact that the keys/values on each row of the CSV are not in the same order. When I export the excel sheet to CSV I get: ``` "{""first_name"":""John"",""last_name"":""Smith"",""age"":30}" "{""first_name"":""Tim"",""last_name"":""Johnson"",""age"":34}" ``` What is the best way to remove the " before and after the curly brackets as well as the extra " around the keys/values? I also need to leave the integers alone that don't have quotes around them. I am trying to then import this into python with the json module so that I can print specific keys but I can't import them with the doubled double quotes. I ultimately need the data saved in a file that looks like: ``` {"first_name":"John","last_name":"Smith","age":30} {"first_name":"Tim","last_name":"Johnson","age":34} ``` Any help is most appreciated!
2013/08/24
[ "https://Stackoverflow.com/questions/18423941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/802136/" ]
If the input file is just as shown, and of the small size you mention, you can load the whole file in memory, make the substitutions, and then save it. IMHO, you don't need a RegEx to do this. The easiest to read code that does this is: ``` with open(filename) as f: input= f.read() input= str.replace('""','"') input= str.replace('"{','{') input= str.replace('}"','}') with open(filename, "w") as f: f.write(input) ``` I tested it with the sample input and it produces: ``` {"first_name":"John","last_name":"Smith","age":30} {"first_name":"Tim","last_name":"Johnson","age":34} ``` Which is exactly what you want. If you want, you can also pack the code and write ``` with open(inputFilename) as if: with open(outputFilename, "w") as of: of.write(if.read().replace('""','"').replace('"{','{').replace('}"','}')) ``` but I think the first one is much clearer and both do exactly the same.
You can actual use the csv module and regex to do this: ``` st='''\ "{""first_name"":""John"",""last_name"":""Smith"",""age"":30}" "{""first_name"":""Tim"",""last_name"":""Johnson"",""age"":34}"\ ''' import csv, re data=[] reader=csv.reader(st, dialect='excel') for line in reader: data.extend(line) s=re.sub(r'(\w+)',r'"\1"',''.join(data)) s=re.sub(r'({[^}]+})',r'\1\n',s).strip() print s ``` Prints ``` {"first_name":"John","last_name":"Smith","age":"30"} {"first_name":"Tim","last_name":"Johnson","age":"34"} ```
18,423,941
I have an excel sheet that has a lot of data in it in one column in the form of a python dictionary from a sql database. I don't have access to the original database and I can't import the CSV back into sql with the local infile command due to the fact that the keys/values on each row of the CSV are not in the same order. When I export the excel sheet to CSV I get: ``` "{""first_name"":""John"",""last_name"":""Smith"",""age"":30}" "{""first_name"":""Tim"",""last_name"":""Johnson"",""age"":34}" ``` What is the best way to remove the " before and after the curly brackets as well as the extra " around the keys/values? I also need to leave the integers alone that don't have quotes around them. I am trying to then import this into python with the json module so that I can print specific keys but I can't import them with the doubled double quotes. I ultimately need the data saved in a file that looks like: ``` {"first_name":"John","last_name":"Smith","age":30} {"first_name":"Tim","last_name":"Johnson","age":34} ``` Any help is most appreciated!
2013/08/24
[ "https://Stackoverflow.com/questions/18423941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/802136/" ]
Easy: `text = re.sub(r'"(?!")', '', text)` ------------------------------------ Given the input file: TEST.TXT: `"{""first_name"":""John"",""last_name"":""Smith"",""age"":30}"` `"{""first_name"":""Tim"",""last_name"":""Johnson"",""age"":34}"` The script: ```py import re f = open("TEST.TXT","r") text_in = f.read() text_out = re.sub(r'"(?!")', '', text_in) print(text_out) ``` produces the following output: `{"first_name":"John","last_name":"Smith","age":30}` `{"first_name":"Tim","last_name":"Johnson","age":34}`
You can actual use the csv module and regex to do this: ``` st='''\ "{""first_name"":""John"",""last_name"":""Smith"",""age"":30}" "{""first_name"":""Tim"",""last_name"":""Johnson"",""age"":34}"\ ''' import csv, re data=[] reader=csv.reader(st, dialect='excel') for line in reader: data.extend(line) s=re.sub(r'(\w+)',r'"\1"',''.join(data)) s=re.sub(r'({[^}]+})',r'\1\n',s).strip() print s ``` Prints ``` {"first_name":"John","last_name":"Smith","age":"30"} {"first_name":"Tim","last_name":"Johnson","age":"34"} ```
18,423,941
I have an excel sheet that has a lot of data in it in one column in the form of a python dictionary from a sql database. I don't have access to the original database and I can't import the CSV back into sql with the local infile command due to the fact that the keys/values on each row of the CSV are not in the same order. When I export the excel sheet to CSV I get: ``` "{""first_name"":""John"",""last_name"":""Smith"",""age"":30}" "{""first_name"":""Tim"",""last_name"":""Johnson"",""age"":34}" ``` What is the best way to remove the " before and after the curly brackets as well as the extra " around the keys/values? I also need to leave the integers alone that don't have quotes around them. I am trying to then import this into python with the json module so that I can print specific keys but I can't import them with the doubled double quotes. I ultimately need the data saved in a file that looks like: ``` {"first_name":"John","last_name":"Smith","age":30} {"first_name":"Tim","last_name":"Johnson","age":34} ``` Any help is most appreciated!
2013/08/24
[ "https://Stackoverflow.com/questions/18423941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/802136/" ]
This should do it: ``` with open('old.csv') as old, open('new.csv', 'w') as new: new.writelines(re.sub(r'"(?!")', '', line) for line in old) ```
You can actual use the csv module and regex to do this: ``` st='''\ "{""first_name"":""John"",""last_name"":""Smith"",""age"":30}" "{""first_name"":""Tim"",""last_name"":""Johnson"",""age"":34}"\ ''' import csv, re data=[] reader=csv.reader(st, dialect='excel') for line in reader: data.extend(line) s=re.sub(r'(\w+)',r'"\1"',''.join(data)) s=re.sub(r'({[^}]+})',r'\1\n',s).strip() print s ``` Prints ``` {"first_name":"John","last_name":"Smith","age":"30"} {"first_name":"Tim","last_name":"Johnson","age":"34"} ```
46,164,770
Keywords [have to](https://mail.python.org/pipermail/python-dev/2012-March/117441.html) be strings ``` >>> def foo(**kwargs): ... pass ... >>> foo(**{0:0}) TypeError: foo() keywords must be strings ``` But by some black magic, namespaces are able to bypass that ``` >>> from types import SimpleNamespace >>> SimpleNamespace(**{0:0}) namespace() ``` Why? And *how*? **Could you implement a Python function that can receive integers in the `kwargs` mapping?**
2017/09/11
[ "https://Stackoverflow.com/questions/46164770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
> > Could you implement a Python function that can receive integers in the kwargs mapping? > > > No, you can't. The Python evaluation loop handles calling functions defined in Python code differently from calling a callable object defined in C code. The Python evaluation loop code that handles keyword argument expansion has firmly closed the door on non-string keyword arguments. But `SimpleNamespace` is not a Python-defined callable, it is defined [entirely in C code](https://github.com/python/cpython/blob/v3.6.2/Objects/namespaceobject.c). It accepts keyword arguments directly, without any validation, which is why you can pass in a dictionary with non-string keyword arguments. That's perhaps a bug; you are supposed to use the [C-API argument parsing functions](https://docs.python.org/3/c-api/arg.html), which all do guard against non-string keyword arguments. `SimpleNamespace` was initially designed just as a container for the [`sys.implementation` data](https://docs.python.org/3/library/sys.html#sys.implementation)\*, and wasn't really designed for other uses. There might be other such exceptions, but they'll all be C-defined callables, not Python functions. --- \* The [`time.get_clock_info()` method](https://docs.python.org/3/library/time.html#time.get_clock_info) also runs an instance of the `SimpleNamespace` class; it's the only other place that the type is currently used.
No, kwargs cannot be integers. This answer, however, is designed as a (very) short history lesson rather than technical answer (for that, please see @MartijnPierter's answer). The check was originally added in 2010, in [issue 8419](https://bugs.python.org/issue8419) ([commit fb88636199c12f63d6c8c89f311cdafc91f30d2f](https://github.com/python/cpython/commit/fb88636199c12f63d6c8c89f311cdafc91f30d2f)) for Python 3.2 (and I believe Python 2.7.4 as well, but don't quote me on that), and simply checked that call kwargs were strings (and raised a value error if they weren't). It also added `PyArg_ValidateKeywordArguments` to C-api, which simply performed the above check. In 2017, [issue 29951](https://bugs.python.org/issue29951) changed the error text for Python 3.7 from "keyword arguments must be strings" to "keywords must be strings" in [PR 916](https://github.com/python/cpython/pull/916) ([commit 64c8f705c0121a4b45ca2c3bc7b47b282e9efcd8](https://github.com/python/cpython/commit/64c8f705c0121a4b45ca2c3bc7b47b282e9efcd8)). The error remained a `ValueError` and it did **not** change the behaviour in any way, and was simply a small change to the error descriptor.
46,164,770
Keywords [have to](https://mail.python.org/pipermail/python-dev/2012-March/117441.html) be strings ``` >>> def foo(**kwargs): ... pass ... >>> foo(**{0:0}) TypeError: foo() keywords must be strings ``` But by some black magic, namespaces are able to bypass that ``` >>> from types import SimpleNamespace >>> SimpleNamespace(**{0:0}) namespace() ``` Why? And *how*? **Could you implement a Python function that can receive integers in the `kwargs` mapping?**
2017/09/11
[ "https://Stackoverflow.com/questions/46164770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
SimpleNamespace now rejects integer keyword keys. As Martijn supposed, [the original behavior was a bug](https://bugs.python.org/issue31655). It seems that it was fixed by [bpo-31655: Validate keyword names in SimpleNamespace constructor](https://github.com/python/cpython/commit/79ba471488b936abda5ba5234b1ea90cbc94cae6) in v3.9.0b2, and then [backported to 3.6](https://github.com/python/cpython/pull/3909#issuecomment-334962097).
No, kwargs cannot be integers. This answer, however, is designed as a (very) short history lesson rather than technical answer (for that, please see @MartijnPierter's answer). The check was originally added in 2010, in [issue 8419](https://bugs.python.org/issue8419) ([commit fb88636199c12f63d6c8c89f311cdafc91f30d2f](https://github.com/python/cpython/commit/fb88636199c12f63d6c8c89f311cdafc91f30d2f)) for Python 3.2 (and I believe Python 2.7.4 as well, but don't quote me on that), and simply checked that call kwargs were strings (and raised a value error if they weren't). It also added `PyArg_ValidateKeywordArguments` to C-api, which simply performed the above check. In 2017, [issue 29951](https://bugs.python.org/issue29951) changed the error text for Python 3.7 from "keyword arguments must be strings" to "keywords must be strings" in [PR 916](https://github.com/python/cpython/pull/916) ([commit 64c8f705c0121a4b45ca2c3bc7b47b282e9efcd8](https://github.com/python/cpython/commit/64c8f705c0121a4b45ca2c3bc7b47b282e9efcd8)). The error remained a `ValueError` and it did **not** change the behaviour in any way, and was simply a small change to the error descriptor.
71,277,152
``` "127.0.0.1": { "nmaprun": { "@scanner": "nmap", "@args": "nmap -v -sS -sV -sC -A -O -oX nmap 127.0.0.1 1-1024", "@start": "1645467733", "@startstr": "Mon Feb 21 23:52:13 2022", "@version": "7.91", "@xmloutputversion": "1.05", "scaninfo": { "@type": "syn", "@protocol": "tcp", "@numservices": "1000", "@services": "1,3-4,6-7,9,13,17,19-26, }, "verbose": { "@level": "1" }, "debugging": { "@level": "0" }, "runstats": { "finished": { "@time": "1645467744", "@timestr": "Mon Feb 21 23:52:24 2022", "@summary": "Nmap done at Mon Feb 21 23:52:24 2022; 1 IP address (1 host up) scanned in 12.14 seconds", "@elapsed": "12.14", "@exit": "success" } } } } } ``` I have this scan output from Nmap. I want to parse the entire JSON and replace the '@' character with ''. how can I do this in python?
2022/02/26
[ "https://Stackoverflow.com/questions/71277152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13668217/" ]
I would guess that `Contest` does not implement `IEquatable<Contest>` or otherwise override `Equals(object)`. Therefore `Assert.Equal` will only work when the objects are reference equal. If you don't want to do this, you can create your own `IEqualityComparer<Contest>` and use the overload `Assert.Equal(expectedRanking, input, equalityComparer)`. Best of luck
I'd suggest to use the [Fluent Assertions](https://fluentassertions.com/introduction) library for this kind of assert checks in unit tests. Instead of rigid equality, you are looking for *equivalency*. Then your assert becomes: ```cs input.Should().BeEquivalentTo(expectedRanking); ``` and this doesn't look for references, only values!
9,921,976
I have a list iteration in python defined like this: ``` for i in range(5): for j in range(5): if i != j: print i , j ``` So for each element in my defined range [0..5] I want to get each element i, but also all other elements which are not i. This code does exactly as I expect, but is there a cleaner way of doing this?
2012/03/29
[ "https://Stackoverflow.com/questions/9921976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1220022/" ]
Use [`itertools.permutations`](http://docs.python.org/library/itertools.html#itertools.permutations): ``` import itertools as it for i, j in it.permutations(range(5), 2): print i, j ```
[(x,y)for x in range(5) for y in range(5) if x!=y]
48,339,383
My python script is not running under my Crontab. But when i try to run it from the Terminal it works perfectly. I have placed this in the python script at the top: ``` #!/usr/bin/python ``` Also I tried: ``` #!/usr/bin/env python ``` I did my file executable: ``` chmod a+x vida.py ``` Added to my crontab and added PATH: ``` USER=gg SHELL=/bin/sh PATH=/usr/local/sbin/:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin/:/home/gg/DC.bin/:/home/gg/GNSSMET/DC/:usr/bin:/usr/bin/X11:/:/home/gg/GNSSMET/DC/bin/:/home/gg/:/usr/lib/python2.7/: PYTHONPATH=/usr/bin/:/usr/lib/python2.7/ */1 * * * * gg /usr/bin/python /home/gg/vida.py 2>&1 >>/home/gg/out1.txt ``` I checked the log via `grep CRON /var/log/syslog` ``` Jan 19 13:37:01 gg-pc CRON[26500]: (gg) CMD ( /usr/bin/python /home/gg/vida.py 2>&1 >>/home/gg/out1.txt) ``` I even run a dummy python script from using crontab and it worked like charm (simple Hello, World!). But when it comes to my script the output file `out1.txt` is created (which is empty) but does not run the actual script. I even checked all of the solutions presented on StackOverflow, none did work. So here is my python script: ``` #!/usr/bin/env python from datetime import * import os import sys gamitRinexDir = '/home/gg/GAMIT/rinex' stalist = ['ankr','argi','aut1','beug','brst','bucu','busk','ganm','gism','glsv','gmlk','gope','hofn','ingl','ista','joze', 'kiru','krcy','ktvl','mas1','mate','mets','mkps','morp','nico','onsa','orhn','orid','pdel','penc','polv','pots','puyv', 'sofi','vis0','vlns','wtzr','yebe','zeck','zimm'] letlist = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X'] seslist = ['0','1','2','3','4','5','6','7','8','9'] tnow = datetime.now() dback = timedelta(hours=2) tnow = tnow -dback wlength = 4 os.system('rm ' + gamitRinexDir + '/*') wlett = [] updir = [] doylist = [] yrlist = [] for i in range(wlength): delta = timedelta(hours=i+1) tback = tnow -delta wlett.append(letlist[tback.hour]) doystr = 'doy ' + str(tnow.year) + ' ' + str(tnow.month) + ' ' + str(tnow.day) + ' ' + '> /home/gg/sil.sil' os.system(doystr) fid = open('/home/gg/sil.sil') line = fid.readline().split() doynum = '%03d' % (int(line[5])) x = str(tnow.year) yrnum = x[2:4] updir.append(yrnum+doynum) doylist.append(doynum) yrlist.append(yrnum) dirname = '/home/gg/REPO/nrtdata/' for i in range(len(wlett)): adirname = dirname + updir[i]+'/' + wlett[i] for sta in stalist: fname = adirname + '/' + sta + doylist[i] + wlett[i].lower() + '.' + yrlist[i]+'d.Z' fname2 = gamitRinexDir + '/' + sta + doylist[i] + seslist[i] + '.' + yrlist[i]+'d.Z' os.system('cp ' + fname + ' ' + fname2) udoy = list(set(doylist)) dcmd = '' for gun in udoy: dcmd = dcmd + gun + ' ' CmdGamit = 'sh_gamit -d ' + x + ' ' + dcmd + ' ' + '-orbit IGSU -expt expt -eops usnd -gnss G -nopngs -metutil Z' print(CmdGamit) mainCmd = 'cd /home/gg/GAMIT/;'+CmdGamit os.system(mainCmd) filestocopy1 = 'met_*' filestocopy2 = 'hexpta.*' filestocopy3 = 'uexpt*' ndirname = ' /home/gg/REPO_GAMIT/' + doynum + '_'+ wlett[-1] os.system('mkdir ' + ndirname) cleancmd1 = 'mv /home/gg/GAMIT/'+doynum +'/'+filestocopy1 + ' ' + ndirname cleancmd2 = 'mv /home/gg/GAMIT/'+doynum +'/'+filestocopy2 + ' ' + ndirname cleancmd3 = 'mv /home/gg/GAMIT/'+doynum +'/'+filestocopy3 + ' ' + ndirname cleancmd4 = 'rm -r /home/gg/GAMIT/'+doynum os.system(cleancmd1) os.system(cleancmd2) os.system(cleancmd3) os.system(cleancmd4) ``` Please show me some pointers, I am seriously stuck here.
2018/01/19
[ "https://Stackoverflow.com/questions/48339383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9239574/" ]
You should change you crontab line as such to get `stdout` and `stderr` saved to the file: ``` */1 * * * * gg /usr/bin/python /home/gg/vida.py >> /home/gg/out1.txt 2>&1 ``` Simply read `out1.txt` after crontab has run the line to see what's wrong Edit after your comment: Based on the error you've shared, I believe you're not actually writing anything in the `/home/gg/sil.sil` file: ``` doystr = 'doy ' + str(tnow.year) + ' ' + str(tnow.month) + ' ' + str(tnow.day) + ' ' + '> /home/gg/sil.sil' os.system(doystr) ``` `doystr` does not evaluate to a shell command, I think you need to write the variable as below to write to the file. ``` doystr = 'echo "doy ' + str(tnow.year) + ' ' + str(tnow.month) + ' ' + str(tnow.day) + '" ' + '> /home/gg/sil.sil' ```
syntax: minutes hour dom mon dow user command 55 16 \* \* \* root /root/anaconda/bin/python /root/path/file\_name.py &>> /root/output/output.log
65,699,603
I want to use some function of ximgproc, so I uninstalled opencv-python and re-installed opencv-contrib-python ``` (venv) C:\Users\Administrator\PycharmProjects\eps>pip uninstall opencv-contrib-python opencv-python Skipping opencv-contrib-python as it is not installed. Uninstalling opencv-python-4.5.1.48: Would remove: c:\users\administrator\pycharmprojects\eps\venv\lib\site-packages\cv2\* c:\users\administrator\pycharmprojects\eps\venv\lib\site-packages\opencv_python-4.5.1.48.dist-info\* Proceed (y/n)? y Successfully uninstalled opencv-python-4.5.1.48 (venv) C:\Users\Administrator\PycharmProjects\eps>pip install opencv-contrib-python Collecting opencv-contrib-python Using cached https://files.pythonhosted.org/packages/01/07/4da5e3a2262c033bd10d7f6275b6fb6c77396b2058cedd02e61dbcc4a56d/opencv_contrib_python-4.5.1.48-cp36-cp36m-win_amd64.whl Requirement already satisfied: numpy>=1.13.3 in c:\users\administrator\pycharmprojects\eps\venv\lib\site-packages (from opencv-contrib-python) (1.18.2) Installing collected packages: opencv-contrib-python Successfully installed opencv-contrib-python-4.5.1.48 ``` However, I could not import ximgproc still. Is there anything I forgot ?
2021/01/13
[ "https://Stackoverflow.com/questions/65699603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11702897/" ]
Can you check which packages you have intalled with `pip list`? Even though you uninstalled opencv-python, you also need to uninstall `opencv-python-headless, opencv-contrib-python-headless` packages. As @skvark says > > never install both package > > >
Install opencv and opencv-contrib modules separately. Command for standard desktop environment: ``` $ pip install opencv-python opencv-contrib-python ```
13,262,575
Making a turn based game using python 3. I want 2 characters (foe & enemy) to attack, pause based on random+speed, then attack again if they are still alive. The problem I am running into is the time.sleep freezes both modules, not 1 or the other. Any suggestions to make this work effectively? ``` from multiprocessing import Process import time import random def timing1(): speed=60#SPEED IS NORMALLY A KEY FROM LIST, USING 60 FOR EXAMPLE sleeptime=36/((random.randint(1,20)+speed)/5) print (sleeptime) time.sleep(sleeptime) input('HERO ACTION') def timing2(): speed=45 sleeptime=36/((random.randint(1,20)+speed)/5) print (sleeptime) time.sleep(sleeptime) input('FOE ACTION') if __name__ == '__main__': p1=Process(target=timing1) p1.start() p2=Process(target=timing2) p2.start() p1.join() p2.join() ```
2012/11/07
[ "https://Stackoverflow.com/questions/13262575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1804903/" ]
Edit the [netbeans.conf](http://wiki.netbeans.org/FaqNetbeansConf) file (located in the /etc folder of your NetBeans installation), look for the line that starts with "netbeans\_default\_options=". Edit the fontsize parameter if present. If not, add something like "--fontsize 11" (without the quote) at the end of the line. [Source](http://wiki.netbeans.org/FaqFontSize)
How about using a screen magnifier? on Windows 7, [Sysinternals ZoomIt](https://technet.microsoft.com/en-us/sysinternals/zoomit.aspx) works fine. Nearly every Linux desktop has one as well.
13,262,575
Making a turn based game using python 3. I want 2 characters (foe & enemy) to attack, pause based on random+speed, then attack again if they are still alive. The problem I am running into is the time.sleep freezes both modules, not 1 or the other. Any suggestions to make this work effectively? ``` from multiprocessing import Process import time import random def timing1(): speed=60#SPEED IS NORMALLY A KEY FROM LIST, USING 60 FOR EXAMPLE sleeptime=36/((random.randint(1,20)+speed)/5) print (sleeptime) time.sleep(sleeptime) input('HERO ACTION') def timing2(): speed=45 sleeptime=36/((random.randint(1,20)+speed)/5) print (sleeptime) time.sleep(sleeptime) input('FOE ACTION') if __name__ == '__main__': p1=Process(target=timing1) p1.start() p2=Process(target=timing2) p2.start() p1.join() p2.join() ```
2012/11/07
[ "https://Stackoverflow.com/questions/13262575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1804903/" ]
`Alt` + `scroll wheel` will increase / decrease the font size of the main code window
My overall NetBeans (8.0) window and fonts was annoyingly and unpleasantly small so I found that Options/Appearance/Look and Feel - Windows Classic was the only one that could be used on a Windows 10.
13,262,575
Making a turn based game using python 3. I want 2 characters (foe & enemy) to attack, pause based on random+speed, then attack again if they are still alive. The problem I am running into is the time.sleep freezes both modules, not 1 or the other. Any suggestions to make this work effectively? ``` from multiprocessing import Process import time import random def timing1(): speed=60#SPEED IS NORMALLY A KEY FROM LIST, USING 60 FOR EXAMPLE sleeptime=36/((random.randint(1,20)+speed)/5) print (sleeptime) time.sleep(sleeptime) input('HERO ACTION') def timing2(): speed=45 sleeptime=36/((random.randint(1,20)+speed)/5) print (sleeptime) time.sleep(sleeptime) input('FOE ACTION') if __name__ == '__main__': p1=Process(target=timing1) p1.start() p2=Process(target=timing2) p2.start() p1.join() p2.join() ```
2012/11/07
[ "https://Stackoverflow.com/questions/13262575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1804903/" ]
For Linux: <http://cristian-radulescu.ro/article/fix-netbeans-big-fonts-on-ubuntu.html> That post recommends adding ``` --laf Nimbus -J-Dswing.aatext=true -J-Dawt.useSystemAAFontSettings=lcd ``` It certainly works on Ubuntu 12.04. I don't know if the same settings will work for Windows7 (but they could because they are Java settings, not OS settings).
How about using a screen magnifier? on Windows 7, [Sysinternals ZoomIt](https://technet.microsoft.com/en-us/sysinternals/zoomit.aspx) works fine. Nearly every Linux desktop has one as well.
13,262,575
Making a turn based game using python 3. I want 2 characters (foe & enemy) to attack, pause based on random+speed, then attack again if they are still alive. The problem I am running into is the time.sleep freezes both modules, not 1 or the other. Any suggestions to make this work effectively? ``` from multiprocessing import Process import time import random def timing1(): speed=60#SPEED IS NORMALLY A KEY FROM LIST, USING 60 FOR EXAMPLE sleeptime=36/((random.randint(1,20)+speed)/5) print (sleeptime) time.sleep(sleeptime) input('HERO ACTION') def timing2(): speed=45 sleeptime=36/((random.randint(1,20)+speed)/5) print (sleeptime) time.sleep(sleeptime) input('FOE ACTION') if __name__ == '__main__': p1=Process(target=timing1) p1.start() p2=Process(target=timing2) p2.start() p1.join() p2.join() ```
2012/11/07
[ "https://Stackoverflow.com/questions/13262575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1804903/" ]
Try this: ![enter image description here](https://i.stack.imgur.com/ItbBH.png) Size of font can be set via settings
I have a NetBeans plugin called 'UI-Editor' that you can use to customize virtually all Swing Settings (including Font types, sizes, and colors). Go to Tools->Plugins and search for UI-Editor. Or go here: <http://plugins.netbeans.org/plugin/55618/?show=true>
13,262,575
Making a turn based game using python 3. I want 2 characters (foe & enemy) to attack, pause based on random+speed, then attack again if they are still alive. The problem I am running into is the time.sleep freezes both modules, not 1 or the other. Any suggestions to make this work effectively? ``` from multiprocessing import Process import time import random def timing1(): speed=60#SPEED IS NORMALLY A KEY FROM LIST, USING 60 FOR EXAMPLE sleeptime=36/((random.randint(1,20)+speed)/5) print (sleeptime) time.sleep(sleeptime) input('HERO ACTION') def timing2(): speed=45 sleeptime=36/((random.randint(1,20)+speed)/5) print (sleeptime) time.sleep(sleeptime) input('FOE ACTION') if __name__ == '__main__': p1=Process(target=timing1) p1.start() p2=Process(target=timing2) p2.start() p1.join() p2.join() ```
2012/11/07
[ "https://Stackoverflow.com/questions/13262575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1804903/" ]
I have a NetBeans plugin called 'UI-Editor' that you can use to customize virtually all Swing Settings (including Font types, sizes, and colors). Go to Tools->Plugins and search for UI-Editor. Or go here: <http://plugins.netbeans.org/plugin/55618/?show=true>
How about using a screen magnifier? on Windows 7, [Sysinternals ZoomIt](https://technet.microsoft.com/en-us/sysinternals/zoomit.aspx) works fine. Nearly every Linux desktop has one as well.
13,262,575
Making a turn based game using python 3. I want 2 characters (foe & enemy) to attack, pause based on random+speed, then attack again if they are still alive. The problem I am running into is the time.sleep freezes both modules, not 1 or the other. Any suggestions to make this work effectively? ``` from multiprocessing import Process import time import random def timing1(): speed=60#SPEED IS NORMALLY A KEY FROM LIST, USING 60 FOR EXAMPLE sleeptime=36/((random.randint(1,20)+speed)/5) print (sleeptime) time.sleep(sleeptime) input('HERO ACTION') def timing2(): speed=45 sleeptime=36/((random.randint(1,20)+speed)/5) print (sleeptime) time.sleep(sleeptime) input('FOE ACTION') if __name__ == '__main__': p1=Process(target=timing1) p1.start() p2=Process(target=timing2) p2.start() p1.join() p2.join() ```
2012/11/07
[ "https://Stackoverflow.com/questions/13262575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1804903/" ]
For Linux: <http://cristian-radulescu.ro/article/fix-netbeans-big-fonts-on-ubuntu.html> That post recommends adding ``` --laf Nimbus -J-Dswing.aatext=true -J-Dawt.useSystemAAFontSettings=lcd ``` It certainly works on Ubuntu 12.04. I don't know if the same settings will work for Windows7 (but they could because they are Java settings, not OS settings).
My overall NetBeans (8.0) window and fonts was annoyingly and unpleasantly small so I found that Options/Appearance/Look and Feel - Windows Classic was the only one that could be used on a Windows 10.
13,262,575
Making a turn based game using python 3. I want 2 characters (foe & enemy) to attack, pause based on random+speed, then attack again if they are still alive. The problem I am running into is the time.sleep freezes both modules, not 1 or the other. Any suggestions to make this work effectively? ``` from multiprocessing import Process import time import random def timing1(): speed=60#SPEED IS NORMALLY A KEY FROM LIST, USING 60 FOR EXAMPLE sleeptime=36/((random.randint(1,20)+speed)/5) print (sleeptime) time.sleep(sleeptime) input('HERO ACTION') def timing2(): speed=45 sleeptime=36/((random.randint(1,20)+speed)/5) print (sleeptime) time.sleep(sleeptime) input('FOE ACTION') if __name__ == '__main__': p1=Process(target=timing1) p1.start() p2=Process(target=timing2) p2.start() p1.join() p2.join() ```
2012/11/07
[ "https://Stackoverflow.com/questions/13262575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1804903/" ]
Try this: ![enter image description here](https://i.stack.imgur.com/ItbBH.png) Size of font can be set via settings
Go to, *Tools -> Options -> Appearance* Check the box which says ***'Override default fonts by'***. Choose the Font Size. This should change the font of Project Window. Doesn't significantly affect the overall font. Note : Im using Netbeans 8.2