date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/19
692
2,193
<issue_start>username_0: Is it possible to replace parts of a string with the content of an include file? For example, this is my string ``` $string = 'The article title goes here bla bla bla... {{ADD_AUTHOR_DETAILS_}}The article body goes here... '; ``` Basically, I want to replace `{{ADD_AUTHOR_DETAILS_}}` with the content of an `include` file. The include file contains html tags, text, etc... Is this possible in php and if yes, how? **EDIT** Some are asking what's inside the include file (php file). This is a sample ``` php if ( !empty($artistphoto) ) { ? ![<?php echo $artistname; ?>](<?php echo $config['path']['artist_image'] . $artistphoto; ?>)php } else { ? php } ?[php echo $artistname; ?](<?php echo $config['reference']['library_author'] . $artisthref; ?>) ```<issue_comment>username_1: You can use [file\_get\_contents](http://php.net/manual/en/function.file-get-contents.php) to load the contents of a file, then use [str\_replace](http://php.net/manual/en/function.str-replace.php) to replace the part of your string. ``` $myString = 'This is a lovely string... But [REPLACE_THIS]'; $fileContents = file_get_contents('my_replacement.txt'); $myString = str_replace('[REPLACE_THIS]', $fileContents, $myString); ``` Upvotes: 2 <issue_comment>username_2: You can use output buffering functions. See [ob\_start()](http://php.net/manual/en/function.ob-start.php) and [ob\_get\_clean()](http://php.net/manual/en/function.ob-get-clean.php) ``` php ob_start(); include('path/to/your/file.php'); $content = ob_get_clean(); $string = '<pThe article title goes here bla bla bla...{{ADD_AUTHOR_DETAILS_}}The article body goes here... '; echo str_replace('{{ADD_AUTHOR_DETAILS_}}', $content, $string); ``` OP said "include" not file\_get\_contents, though perhaps the other answer maybe what you're looking for. Upvotes: 3 [selected_answer]<issue_comment>username_3: You can replace multiple substrings with strtr. ``` php $string = '@@HEADING@@, welcome, @@BODY@@, thankyou.'; $output = strtr($string, array( '@@HEADING@@' = file_get_contents('/tmp/heading.txt'), '@@BODY@@' => file_get_contents('/tmp/body.txt') )); print $output; ``` Upvotes: 1
2018/03/19
8,469
18,235
<issue_start>username_0: I am new to BeautifulSoup and trying to extract the table. I have followed documentation to do a nested for loop to extract the cell data but it only returns the first three rows. Here is my code: ``` from six.moves import urllib from bs4 import BeautifulSoup import pandas as pd def get_url_content(url): try: html=urllib.request.urlopen(url) except urllib.error.HTTPError as e: return None try: soup=BeautifulSoup(html.read(),'html.parser') except AttributeError as e: return None return soup URL="http://www.megamillions.com/winning-numbers/search?startDate=1/1/2017&endDate=3/31/2018" soup=get_url_content(URL) for tr in soup.find_all('tr'): for td in tr.find_all('td'): print td.text ``` I also tried adding if statement before the second loop as: ``` if tr.parentGenerator=='tbody': ``` but it returns empty list.<issue_comment>username_1: The site is dymamic, which means you need to use a browser manipulation tool such as `selenium`. Then, extract text from multiple class names for each search: ``` import urllib import re from bs4 import BeautifulSoup as soup from selenium import webdriver def get_table(): d = webdriver.Chrome('path/to/driver') #or webdriver.Firefox(), depending on your browser d.get('http://www.megamillions.com/winning-numbers/search?startDate=1/1/2017&endDate=3/31/2018') table = [i.text for i in soup(d.page_source, 'lxml').find_all('td', {'class':re.compile('dates|number|mega|details')})] final_table = [table[i:i+9] for i in range(0, len(table), 9)] last_data = [dict(zip(['draw_date', 'balls', 'megaball', 'megaplier', 'details'], [a, b, c, d, e])) for a, *b, c, d, e in final_table] return last_data print(get_table()) ``` Output: ``` [{'draw_date': '12/29/2017', 'balls': ['4', '10', '18', '28', '62'], 'megaball': '7', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '12/26/2017', 'balls': ['10', '12', '20', '38', '41'], 'megaball': '25', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '12/22/2017', 'balls': ['1', '20', '30', '33', '42'], 'megaball': '16', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '12/19/2017', 'balls': ['28', '37', '39', '42', '58'], 'megaball': '2', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '12/15/2017', 'balls': ['4', '12', '36', '44', '57'], 'megaball': '19', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '12/12/2017', 'balls': ['8', '23', '24', '25', '27'], 'megaball': '9', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '12/8/2017', 'balls': ['6', '37', '46', '60', '70'], 'megaball': '24', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '12/5/2017', 'balls': ['14', '15', '37', '42', '67'], 'megaball': '22', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '12/1/2017', 'balls': ['16', '22', '40', '41', '59'], 'megaball': '8', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '11/28/2017', 'balls': ['10', '17', '47', '51', '61'], 'megaball': '5', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '11/24/2017', 'balls': ['16', '36', '54', '61', '64'], 'megaball': '22', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '11/21/2017', 'balls': ['3', '7', '22', '27', '50'], 'megaball': '3', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '11/17/2017', 'balls': ['3', '26', '55', '58', '70'], 'megaball': '15', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '11/14/2017', 'balls': ['1', '14', '21', '22', '28'], 'megaball': '19', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '11/10/2017', 'balls': ['6', '23', '38', '42', '58'], 'megaball': '24', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '11/7/2017', 'balls': ['1', '54', '60', '68', '69'], 'megaball': '11', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '11/3/2017', 'balls': ['10', '22', '42', '61', '69'], 'megaball': '3', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '10/31/2017', 'balls': ['6', '28', '31', '52', '53'], 'megaball': '12', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '10/27/2017', 'balls': ['17', '27', '41', '51', '52'], 'megaball': '13', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '10/24/2017', 'balls': ['20', '24', '34', '56', '64'], 'megaball': '6', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '10/20/2017', 'balls': ['6', '23', '63', '66', '73'], 'megaball': '9', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '10/17/2017', 'balls': ['31', '45', '49', '56', '70'], 'megaball': '11', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '10/13/2017', 'balls': ['2', '7', '18', '26', '31'], 'megaball': '12', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '10/10/2017', 'balls': ['7', '16', '24', '61', '62'], 'megaball': '2', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '10/6/2017', 'balls': ['21', '33', '36', '45', '56'], 'megaball': '12', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '10/3/2017', 'balls': ['12', '18', '19', '25', '67'], 'megaball': '7', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '9/29/2017', 'balls': ['25', '51', '62', '73', '74'], 'megaball': '7', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '9/26/2017', 'balls': ['1', '10', '57', '66', '75'], 'megaball': '4', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '9/22/2017', 'balls': ['5', '39', '54', '63', '66'], 'megaball': '15', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '9/19/2017', 'balls': ['9', '28', '31', '50', '61'], 'megaball': '10', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '9/15/2017', 'balls': ['18', '24', '34', '38', '58'], 'megaball': '3', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '9/12/2017', 'balls': ['26', '37', '41', '54', '65'], 'megaball': '3', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '9/8/2017', 'balls': ['4', '5', '14', '26', '73'], 'megaball': '14', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '9/5/2017', 'balls': ['11', '17', '59', '70', '72'], 'megaball': '1', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '9/1/2017', 'balls': ['4', '13', '31', '50', '64'], 'megaball': '12', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '8/29/2017', 'balls': ['2', '13', '17', '35', '73'], 'megaball': '3', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '8/25/2017', 'balls': ['17', '38', '42', '51', '65'], 'megaball': '11', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '8/22/2017', 'balls': ['24', '35', '46', '50', '51'], 'megaball': '7', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '8/18/2017', 'balls': ['1', '31', '34', '40', '75'], 'megaball': '6', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '8/15/2017', 'balls': ['7', '16', '20', '66', '73'], 'megaball': '7', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '8/11/2017', 'balls': ['23', '33', '53', '56', '58'], 'megaball': '6', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '8/8/2017', 'balls': ['11', '17', '50', '52', '74'], 'megaball': '14', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '8/4/2017', 'balls': ['9', '17', '25', '63', '71'], 'megaball': '4', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '8/1/2017', 'balls': ['20', '22', '52', '57', '73'], 'megaball': '7', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '7/28/2017', 'balls': ['4', '6', '31', '49', '52'], 'megaball': '11', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '7/25/2017', 'balls': ['2', '5', '26', '58', '60'], 'megaball': '6', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '7/21/2017', 'balls': ['18', '31', '36', '50', '74'], 'megaball': '10', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '7/18/2017', 'balls': ['8', '12', '23', '51', '73'], 'megaball': '6', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '7/14/2017', 'balls': ['11', '12', '24', '32', '73'], 'megaball': '1', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '7/11/2017', 'balls': ['7', '18', '24', '55', '74'], 'megaball': '10', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '7/7/2017', 'balls': ['2', '9', '11', '28', '60'], 'megaball': '10', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '7/4/2017', 'balls': ['16', '39', '47', '53', '71'], 'megaball': '15', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '6/30/2017', 'balls': ['10', '38', '51', '55', '64'], 'megaball': '6', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '6/27/2017', 'balls': ['4', '21', '45', '52', '57'], 'megaball': '14', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '6/23/2017', 'balls': ['12', '20', '53', '66', '74'], 'megaball': '11', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '6/20/2017', 'balls': ['2', '15', '41', '49', '63'], 'megaball': '3', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '6/16/2017', 'balls': ['18', '22', '26', '30', '44'], 'megaball': '9', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '6/13/2017', 'balls': ['27', '51', '62', '68', '75'], 'megaball': '8', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '6/9/2017', 'balls': ['3', '16', '28', '33', '37'], 'megaball': '9', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '6/6/2017', 'balls': ['3', '5', '16', '49', '75'], 'megaball': '5', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '6/2/2017', 'balls': ['7', '42', '57', '69', '72'], 'megaball': '10', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '5/30/2017', 'balls': ['5', '20', '32', '37', '67'], 'megaball': '5', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '5/26/2017', 'balls': ['25', '26', '28', '37', '56'], 'megaball': '5', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '5/23/2017', 'balls': ['6', '13', '17', '33', '60'], 'megaball': '14', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '5/19/2017', 'balls': ['1', '4', '5', '24', '30'], 'megaball': '1', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '5/16/2017', 'balls': ['4', '35', '39', '56', '72'], 'megaball': '11', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '5/12/2017', 'balls': ['28', '34', '41', '42', '47'], 'megaball': '13', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '5/9/2017', 'balls': ['6', '29', '45', '69', '73'], 'megaball': '11', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '5/5/2017', 'balls': ['4', '23', '33', '47', '53'], 'megaball': '7', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '5/2/2017', 'balls': ['5', '14', '42', '43', '58'], 'megaball': '1', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '4/28/2017', 'balls': ['6', '13', '18', '20', '31'], 'megaball': '13', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '4/25/2017', 'balls': ['3', '13', '33', '40', '50'], 'megaball': '2', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '4/21/2017', 'balls': ['1', '12', '13', '32', '34'], 'megaball': '10', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '4/18/2017', 'balls': ['8', '29', '30', '43', '64'], 'megaball': '6', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '4/14/2017', 'balls': ['5', '10', '55', '60', '73'], 'megaball': '12', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '4/11/2017', 'balls': ['19', '34', '35', '38', '49'], 'megaball': '8', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '4/7/2017', 'balls': ['30', '33', '43', '47', '69'], 'megaball': '15', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '4/4/2017', 'balls': ['13', '24', '34', '35', '55'], 'megaball': '9', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '3/31/2017', 'balls': ['17', '24', '27', '32', '58'], 'megaball': '10', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '3/28/2017', 'balls': ['30', '33', '35', '37', '46'], 'megaball': '10', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '3/24/2017', 'balls': ['5', '28', '37', '61', '69'], 'megaball': '1', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '3/21/2017', 'balls': ['4', '45', '53', '73', '75'], 'megaball': '7', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '3/17/2017', 'balls': ['11', '27', '31', '58', '60'], 'megaball': '10', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '3/14/2017', 'balls': ['16', '23', '28', '33', '59'], 'megaball': '13', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '3/10/2017', 'balls': ['26', '38', '42', '58', '70'], 'megaball': '5', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '3/7/2017', 'balls': ['3', '30', '45', '53', '68'], 'megaball': '11', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '3/3/2017', 'balls': ['14', '26', '39', '48', '51'], 'megaball': '9', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '2/28/2017', 'balls': ['20', '33', '45', '58', '69'], 'megaball': '4', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '2/24/2017', 'balls': ['12', '29', '33', '42', '68'], 'megaball': '14', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '2/21/2017', 'balls': ['9', '21', '30', '32', '75'], 'megaball': '9', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '2/17/2017', 'balls': ['4', '56', '58', '67', '75'], 'megaball': '8', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '2/14/2017', 'balls': ['7', '11', '33', '60', '68'], 'megaball': '15', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '2/10/2017', 'balls': ['32', '39', '51', '62', '75'], 'megaball': '14', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '2/7/2017', 'balls': ['23', '28', '37', '56', '71'], 'megaball': '12', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '2/3/2017', 'balls': ['3', '6', '29', '30', '64'], 'megaball': '3', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '1/31/2017', 'balls': ['3', '14', '27', '62', '72'], 'megaball': '4', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '1/27/2017', 'balls': ['17', '37', '53', '54', '61'], 'megaball': '8', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '1/24/2017', 'balls': ['8', '42', '54', '63', '67'], 'megaball': '11', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '1/20/2017', 'balls': ['7', '9', '24', '41', '53'], 'megaball': '14', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '1/17/2017', 'balls': ['20', '31', '54', '56', '59'], 'megaball': '3', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '1/13/2017', 'balls': ['10', '44', '58', '74', '75'], 'megaball': '11', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '1/10/2017', 'balls': ['11', '20', '40', '41', '59'], 'megaball': '15', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '1/6/2017', 'balls': ['6', '10', '44', '47', '54'], 'megaball': '6', 'megaplier': '5', 'details': 'Details'}, {'draw_date': '1/3/2017', 'balls': ['14', '16', '23', '49', '53'], 'megaball': '12', 'megaplier': '2', 'details': 'Details'}] ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You don't need any browser simulator if you wish to go for newly released [Requests\_HTML](http://html.python-requests.org/) library which is able to handle dynamically generated items. Given that, you can try like below: ``` import requests_html URL = "http://www.megamillions.com/winning-numbers/search?startDate=1/1/2017&endDate=3/31/2018" with requests_html.HTMLSession() as session: r = session.get(URL) r.html.render(sleep=5) table = r.html.find("table#table", first=True) for items in table.find("tr")[2:]: data = [item.text for item in items.find("th,td")[:-1]] print(data) ``` Partial Output: ``` ['Draw Date', 'Balls', 'Mega Ball', 'Megaplier'] ['12/29/2017', '4', '10', '18', '28', '62', '7', '2'] ['12/26/2017', '10', '12', '20', '38', '41', '25', '4'] ['12/22/2017', '1', '20', '30', '33', '42', '16', '4'] ['12/19/2017', '28', '37', '39', '42', '58', '2', '3'] ['12/15/2017', '4', '12', '36', '44', '57', '19', '4'] ['12/12/2017', '8', '23', '24', '25', '27', '9', '2'] ['12/8/2017', '6', '37', '46', '60', '70', '24', '2'] ['12/5/2017', '14', '15', '37', '42', '67', '22', '4'] ['12/1/2017', '16', '22', '40', '41', '59', '8', '4'] ['11/28/2017', '10', '17', '47', '51', '61', '5', '2'] ['11/24/2017', '16', '36', '54', '61', '64', '22', '3'] ['11/21/2017', '3', '7', '22', '27', '50', '3', '3'] ['11/17/2017', '3', '26', '55', '58', '70', '15', '4'] ``` Upvotes: 2 <issue_comment>username_3: Even though the table is loaded dynamically, you can use `requests` module to get its contents. Go to the `XHR` in the `Network` tab in the Developer tools. An AJAX request is send to `http://www.megamillions.com/Media/Static/winning-numbers/winning-numbers.json` returns all the data you want in the form of JSON. To get the JSON you can use this: ``` import requests r = requests.get('http://www.megamillions.com/Media/Static/winning-numbers/winning-numbers.json') data = r.json() ``` As you can see that JSON is in the following format (items starting from today's date): ``` {'nextDraw': {'IsPending': False, 'JackpotAnnuityAmount': 345000000, 'JackpotCashAmount': 206500000, 'MegaBall': 11, 'Megaplier': 3, 'NextDrawDate': '2018-03-21T03:00:00', 'NextJackpotAnnuityAmount': 377000000, 'NextJackpotCashAmount': 225700000}, 'numbersList': [{'DrawDate': '2018-03-16T00:00:00', 'GameName': 'MegaMillions', 'MegaBall': 11, 'Megaplier': 3, 'WhiteBall1': 26, 'WhiteBall2': 52, 'WhiteBall3': 33, 'WhiteBall4': 1, 'WhiteBall5': 13}, ... ... ``` You can get whatever you want from the `data` variable in this way: ``` for item in data['numbersList']: date = item['DrawDate'] megaball = item['MegaBall'] megaplier = item['Megaplier'] # and similarly other items print(date, megaball, megaplier) ``` Partial output: ``` 2018-03-16T00:00:00 11 3 2018-03-13T00:00:00 17 5 2018-03-09T00:00:00 22 4 2018-03-06T00:00:00 22 5 2018-03-02T00:00:00 8 4 2018-02-27T00:00:00 23 3 2018-02-23T00:00:00 9 4 2018-02-20T00:00:00 14 3 ... ... ``` Upvotes: 0
2018/03/19
412
1,305
<issue_start>username_0: I have a column in a data frame with mixed date formats. How do I segregate it according to the different date formats. For e.g I want something like this df1 = dataframe[dataframe['Cl\_date'] is '%d%b%y'] df2 = dataframe[dataframe['Cl\_date'] is '%b%y] Please help<issue_comment>username_1: First, ensure that you've converted the `Cl_date` column in datetime format like this: ``` df['Cl_date'] = pd.to_datetime(df['Cl_date']) ``` Then, using `select_dtypes` function you can select the column with date format. ``` df1 = df.select_dtypes(include=[np.datetime64]) ``` Upvotes: -1 <issue_comment>username_2: Convert the date column to string and then filter by the number of characters in the string (assuming the formats are each of a different length). ``` # setup import pandas as pd; from datetime import datetime, timedelta; today = datetime.now().date(); yesterday = today-timedelta(days=1) yesterday = yesterday.strftime('%B-%y') d = {'Date': [today,yesterday],'Value': [100,200]} df = pd.DataFrame(columns=['Date','Value'],data=d) # convert the column to string df['Date'] = df['Date'].astype('str') # filter by # of chars # for %y-%m-%d df1 = df.loc[df['Date'].str.len()==10] # for %B-%y df2 = df.loc[df['Date'].str.len()==8] ``` Upvotes: 1 [selected_answer]
2018/03/19
1,418
4,303
<issue_start>username_0: I have Javascript array that looks like this: ``` fruitsGroups: [ "apple0", "banana0", "pear0", ] ``` How can I increase the number of each item in this array? ``` fruitsGroups: [ "apple0", "apple1", "apple2", "banana0", "banana1", "banana2", "pear0", "pear1", "pear2" ] ```<issue_comment>username_1: I think your looking for something like that? ``` var fruitsGroups = [ "apple0", "banana0", "pear0", ]; console.log(fruitsGroups); var newFruits = []; $.each(fruitsGroups, function(i, j) { var n = parseInt(j.substring(j.length - 1)); for(var k = 0; k < 3; k++) { newFruits.push(j.substring(0, j.length - 1) + (n + k)); } }); console.log(newFruits); ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You could create function that uses `reduce()` method and returns new array. ```js function mult(data, n) { return data.reduce((r, e) => { return r.push(e, ...Array.from(Array(n), (_, i) => { const [text, n] = e.split(/(\d+)/); return text + (+n + i + 1) })), r }, []); } console.log(mult(["apple0", "banana0", "pear0"], 2)) console.log(mult(["apple4", "banana2", "pear0"], 3)) ``` Upvotes: 1 <issue_comment>username_3: I have tried this for you, it might help as per my understanding. Naive Approach ```js var a = ['apple0','banana0','pearl0'] var fruitGroups = [] for(var i=0; i < a.length; i++){ for(var j = 0; j ``` Upvotes: 0 <issue_comment>username_4: [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) the original array. For each item, create a sub array, and [fill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) it with the current item. Then map the sub array and [replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) the digit/s of each item with the index. Flatten the sub arrays, by [spreading](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) into [`Array.concat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat): ```js const fruitsGroups = [ "apple0", "banana0", "pear0", ]; const len = 3; // map the original array, and use concat to flatten the sub arrays const result = [].concat(...fruitsGroups.map((item) => new Array(len) // create a new sub array with the requested size .fill(item) // fill it with the item .map((s, i) => s.replace(/\d+/, i)) // map the strings in the sub array, and replace the number with the index )); console.log(result); ``` Upvotes: 0 <issue_comment>username_5: Since we have 2018 already, another approach using Array.map and destructuring: ``` const groups = [ "apple0", "banana0", "pear0", ]; [].concat(...groups.map(item => [ item, item.replace(0, 1), item.replace(0, 2) ] )) // result: ["apple0", "apple1", "apple2", // "banana0", "banana1", "banana2", // "pear0", "pear1", "pear2"] ``` Explanation: `groups.map(item => [item, item.replace(0, 1), item.replace(0, 2)])` takes each array item one by one (`apple0`, then `banana0`, …) and replaces it with an array of: * `item` – the item itself (`apple0`) * `item.replace(0, 1)` – the item with zero replaced by `1` (`apple1`) * `item.replace(0, 2)` – the item with zero replaced by `2` (`apple2`) so the array looks like… ``` [ ["apple0", "apple1", "apple2"], ["banana0", "banana1", "banana2"], ["pear0", "pear1", "pear2"], ] ``` …and then we need to flatten it, that's the `[].concat(...` part. It basically takes array items (the three dots, [read more about destructuring here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring)), and merges them into an empty array. If you want to replace any digit, not just zero, use regular expression: ``` "apple0".replace(/\d$/, 1) // -> "apple1" "apple9".replace(/\d$/, 1) // -> "apple1" ``` * `\d` – any number character * `$` - end of line * the surrounding slashes tell JS that it's a regular expression, you could use `new RegExp("\d$")` instead, too Upvotes: 2
2018/03/19
1,524
4,633
<issue_start>username_0: I'd like to create a top view of a sine graph in dots in Maple, such that the max height is shown with the dots closest together and then the min is shown with the dots furthest apart. It can be lines rather than dots. Is it possible in Maple? I can use MATLAB too if someone only knows how to do it in MATLAB. I tried this: ``` plot3d(sin(x),linestyle=dot); ``` and this is what I get (I have moved it so that it is top view): ![Fig1](https://i.stack.imgur.com/ui8kT.png) but I want something like this: ![Fig2](https://i.stack.imgur.com/u3HxW.png) or this (sine graph below the dots aligned with the max/min): ![Fix3](https://i.stack.imgur.com/ZUAWL.png)<issue_comment>username_1: I think your looking for something like that? ``` var fruitsGroups = [ "apple0", "banana0", "pear0", ]; console.log(fruitsGroups); var newFruits = []; $.each(fruitsGroups, function(i, j) { var n = parseInt(j.substring(j.length - 1)); for(var k = 0; k < 3; k++) { newFruits.push(j.substring(0, j.length - 1) + (n + k)); } }); console.log(newFruits); ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You could create function that uses `reduce()` method and returns new array. ```js function mult(data, n) { return data.reduce((r, e) => { return r.push(e, ...Array.from(Array(n), (_, i) => { const [text, n] = e.split(/(\d+)/); return text + (+n + i + 1) })), r }, []); } console.log(mult(["apple0", "banana0", "pear0"], 2)) console.log(mult(["apple4", "banana2", "pear0"], 3)) ``` Upvotes: 1 <issue_comment>username_3: I have tried this for you, it might help as per my understanding. Naive Approach ```js var a = ['apple0','banana0','pearl0'] var fruitGroups = [] for(var i=0; i < a.length; i++){ for(var j = 0; j ``` Upvotes: 0 <issue_comment>username_4: [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) the original array. For each item, create a sub array, and [fill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) it with the current item. Then map the sub array and [replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) the digit/s of each item with the index. Flatten the sub arrays, by [spreading](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) into [`Array.concat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat): ```js const fruitsGroups = [ "apple0", "banana0", "pear0", ]; const len = 3; // map the original array, and use concat to flatten the sub arrays const result = [].concat(...fruitsGroups.map((item) => new Array(len) // create a new sub array with the requested size .fill(item) // fill it with the item .map((s, i) => s.replace(/\d+/, i)) // map the strings in the sub array, and replace the number with the index )); console.log(result); ``` Upvotes: 0 <issue_comment>username_5: Since we have 2018 already, another approach using Array.map and destructuring: ``` const groups = [ "apple0", "banana0", "pear0", ]; [].concat(...groups.map(item => [ item, item.replace(0, 1), item.replace(0, 2) ] )) // result: ["apple0", "apple1", "apple2", // "banana0", "banana1", "banana2", // "pear0", "pear1", "pear2"] ``` Explanation: `groups.map(item => [item, item.replace(0, 1), item.replace(0, 2)])` takes each array item one by one (`apple0`, then `banana0`, …) and replaces it with an array of: * `item` – the item itself (`apple0`) * `item.replace(0, 1)` – the item with zero replaced by `1` (`apple1`) * `item.replace(0, 2)` – the item with zero replaced by `2` (`apple2`) so the array looks like… ``` [ ["apple0", "apple1", "apple2"], ["banana0", "banana1", "banana2"], ["pear0", "pear1", "pear2"], ] ``` …and then we need to flatten it, that's the `[].concat(...` part. It basically takes array items (the three dots, [read more about destructuring here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring)), and merges them into an empty array. If you want to replace any digit, not just zero, use regular expression: ``` "apple0".replace(/\d$/, 1) // -> "apple1" "apple9".replace(/\d$/, 1) // -> "apple1" ``` * `\d` – any number character * `$` - end of line * the surrounding slashes tell JS that it's a regular expression, you could use `new RegExp("\d$")` instead, too Upvotes: 2
2018/03/19
1,022
3,633
<issue_start>username_0: I've written some automation tests where I use syntax like - ``` try { // Test case steps and validations } finally { // Clean up related to test } ``` NOTE: This does not have `catch` block as my tests do not expect exceptions. If test fails in `try` as well as `finally` block, only failures of `finally` are returned on console but not of `try`. Simple example here(TestNG is used here for assertions) - ``` try { Assert.assertEquals(true, false, "Boolean values did not match"); } finally { Assert.assertEquals(100, 10, "Integer values did not match"); } ``` In this case, only details of finally failures are returned. This does not help to identify actual failure of test looking at the console. I would like to understand why Java does not return both failure details on console which can help user to identify failure cause at very first look.<issue_comment>username_1: Because under the hood `Assert.assertEquals()` uses `Assert.fail()` to throw an `AssertionError` to signal the error. The exception in `finally` block will replace and discard the one thrown in `try` block as per [14.20.2. Execution of try-finally and try-catch-finally](https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.20.2). Upvotes: 1 <issue_comment>username_2: The same thing can be observed with throwing exceptions: ``` try { throw new RuntimeException("Message 1"); } finally { throw new RuntimeException("Message 2"); } ``` Here, only `Message 2` is printed: ``` Exception in thread "main" java.lang.RuntimeException: Message 2 ``` This is because when `finally` throws an exception, any exceptions in `try` is "discarded and forgotten": JLS section 14.20.2 > > * If the run-time type of V is not assignment compatible with a catchable exception class of any catch clause of the try statement, > then the finally block is executed. Then there is a choice: > > > + If the finally block completes normally, then the try statement completes abruptly because of a throw of the value V. > + If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (**and the throw of value > V is discarded and forgotten**). > > > Upvotes: 3 [selected_answer]<issue_comment>username_3: That is because a new exception thrown from a `finally` block *replaces* the exception thrown from the `try` block, as documented in the Java Language Specification, section [14.20.2. Execution of try-finally and try-catch-finally](https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.20.2): > > If execution of the `try` block completes abruptly because of a `throw` of a value `V`, then there is a choice: > > > [...] > > > If the `finally` block completes abruptly for reason `S`, then the `try` statement completes abruptly for reason `S` (and **the `throw` of value `V` is discarded and forgotten**). > > > Since the `finally` block doesn't even know of the original exception, it cannot do anything about it. However, if you `catch` the original exception, you can include it as a *suppressed* exception (Java 7+), but it's a bit convoluted: ``` AssertionError originalError = null; try { Assert.assertEquals(true, false, "Boolean values did not match"); } catch (AssertionError e) { originalError = e; throw e; } finally { try { Assert.assertEquals(100, 10, "Integer values did not match"); } catch (AssertionError e) { if (originalError == null) throw e; originalError.addSuppressed(e); throw originalError; } } ``` Upvotes: 1
2018/03/19
1,118
3,804
<issue_start>username_0: I'm using a case statement to calculate two columns, `primary_specialty` and `secondary_specialty`. This works well, however, I'd like to then perform a `GROUP BY` on the `pd.id` and receive the following error: `column "pppd.created_at" must appear in the GROUP BY clause or be used in an aggregate function`. The desired output is a single row for each `pd` with a column for `primary_specialty` and `secondary_specialty` ``` SELECT pd.id, pd.npi, pppd.created_at AS "date_submitted", pppd.converted_at AS "date_approved", dp.created_at AS "date_profile_created", t.description AS "npi_specialty", case when ds.ordinal = 1 then s.name end as "primary_specialty", case when ds.ordinal = 2 then s.name end as "secondary_specialty" FROM potential_doctors AS pd INNER JOIN patient_profile_potential_doctors as pppd on pd.id = pppd.potential_doctor_id INNER JOIN doctor_taxonomies AS dt on pd.id = dt.potential_doctor_id INNER JOIN taxonomies AS t on dt.taxonomy_id = t.id INNER JOIN doctor_profiles AS dp on pd.npi = dp.npi INNER JOIN doctor_specialties AS ds on dp.id = ds.doctor_profile_id INNER JOIN specialties AS s on ds.specialty_id = s.id ```<issue_comment>username_1: If you group by one or more column, you can only select those columns or an aggregated function. Because you are grouping many rows, you could have many "primary\_specialty" for each pd.id. If you assume though, from your database schema, that you will have only one distinct value in the set, you could use an aggregated function (like MAX) to get the value you want. Something like this: ``` SELECT pd.id, MAX(case when ds.ordinal = 1 then s.name end) as "primary_specialty", MAX(case when ds.ordinal = 2 then s.name end) as "secondary_specialty" ``` Upvotes: 0 <issue_comment>username_2: This may be the query that you want: ``` SELECT pd.id, pd.npi, pppd.created_at AS "date_submitted", pppd.converted_at AS "date_approved", dp.created_at AS "date_profile_created", t.description AS "npi_specialty", max(case when ds.ordinal = 1 then s.name end) as "primary_specialty", max(case when ds.ordinal = 2 then s.name end) as "secondary_specialty" FROM potential_doctors AS pd INNER JOIN patient_profile_potential_doctors as pppd on pd.id = pppd.potential_doctor_id INNER JOIN doctor_taxonomies AS dt on pd.id = dt.potential_doctor_id INNER JOIN taxonomies AS t on dt.taxonomy_id = t.id INNER JOIN doctor_profiles AS dp on pd.npi = dp.npi INNER JOIN doctor_specialties AS ds on dp.id = ds.doctor_profile_id INNER JOIN specialties AS s on ds.specialty_id = s.id GROUP BY pd.id, pd.npi, pppd.created_at, pppd.converted_at, t.description ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Use **DISTINCT ON** (pd.id) instead of **GROUP BY** ``` SELECT DISTINCT ON (pd.id) pd.id, pd.npi, pppd.created_at AS "date_submitted", pppd.converted_at AS "date_approved", dp.created_at AS "date_profile_created", t.description AS "npi_specialty", case when ds.ordinal = 1 then s.name end as "primary_specialty", case when ds.ordinal = 2 then s.name end as "secondary_specialty" FROM potential_doctors AS pd INNER JOIN patient_profile_potential_doctors as pppd on pd.id = pppd.potential_doctor_id INNER JOIN doctor_taxonomies AS dt on pd.id = dt.potential_doctor_id INNER JOIN taxonomies AS t on dt.taxonomy_id = t.id INNER JOIN doctor_profiles AS dp on pd.npi = dp.npi INNER JOIN doctor_specialties AS ds on dp.id = ds.doctor_profile_id INNER JOIN specialties AS s on ds.specialty_id = s.id ``` Upvotes: 2
2018/03/19
894
2,711
<issue_start>username_0: I am trying to create a trigger that will update a table called VIDEO after the table DETAILRENTAL is updated. I am trying to use IF ELSE conditionals to satisfy multiple situations. This is what I have coded: ``` CREATE OR REPLACE TRIGGER TRG_VIDEORENTAL_UP AFTER UPDATE OF DETAIL_RETURNDATE ON DETAILRENTAL FOR EACH ROW BEGIN IF :NEW.DETAIL_RETURNDATE IS NULL THEN UPDATE VIDEO SET VID_STATUS = 'OUT' WHERE :NEW.VID_NUM = VID_NUM; ELSEIF :NEW.DETAIL_RETURNDATE > SYSDATE UPDATE VIDEO SET VID_STATUS = 'OUT' WHERE:NEW.VID_NUM = VID_NUM; ELSEIF :NEW.DETAIL_RETURNDATE < SYSDATE OR :NEW.DETAIL_RETURNDATE = SYSDATE UPDATE VIDEO SET VID_STATUS = 'IN' WHERE :NEW.VID_NUM = VID_NUM; ELSE :NEW.DETAIL_RETURNDATE = '01/01/01' UPDATE VIDEO SET VID_STATUS = 'LOST' WHERE :NEW.VID_NUM = VID_NUM ; END IF; end; ``` This is the error message I get when I run this code: > > *Error at line 8: PLS-00103: Encountered the symbol "" when expecting one of the following: := . ( @ % ;* > > > I already tested each conditional to ensure that each statement works individually but it does not seem to work together.<issue_comment>username_1: Oracle uses `ELSIF`, not `ELSEIF` for multiple conditions. That is probably the cause of the error. Upvotes: 1 <issue_comment>username_2: In addition to `ELSEIF` [needing to be `ELSIF`](https://docs.oracle.com/en/database/oracle/oracle-database/12.2/lnpls/plsql-control-statements.html#GUID-B7DD4E62-3ED2-41E9-AAE5-90A78788BB31) as @Gordon pointed out, those `ELSIF` conditions still need a `THEN`: ``` ELSIF :NEW.DETAIL_RETURNDATE > SYSDATE THEN UPDATE VIDEO ... ELSIF :NEW.DETAIL_RETURNDATE < SYSDATE OR :NEW.DETAIL_RETURNDATE = SYSDATE THEN UPDATE VIDEO ... ``` and your final `ELSE` either needs to be an `ELSIF` plus `THEN`: ``` ELSIF :NEW.DETAIL_RETURNDATE = '01/01/01' THEN UPDATE VIDEO ... ``` or remove that condition: ``` ELSE UPDATE VIDEO ... ``` depending on the logic you actually need. If you do need the condition, and thus the `ELSIF`, then the way you are comparing the date in that condition is wrong too; `'01/01/01'` is a string not a date, so you are relying on implicit conversion using the session's NLS settings, which you may not control. Use `to_date()` with a suitable format mask, or [an ANSI date literal](https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/Literals.html#GUID-8F4B3F82-8821-4071-84D6-FBBA21C05AC1): ``` ELSIF :NEW.DETAIL_RETURNDATE = DATE '2001-01-01' THEN UPDATE VIDEO ... ``` Upvotes: 0
2018/03/19
480
1,632
<issue_start>username_0: I've set a function to execute in my backend after a certain amount of time, using a setTimeOut. Oddly, if I set the timeout to be less than 60000 ms, the code executes. Anything greater than or equal to that, then the code within the `setTimeout` does not run. After searching online, I think it may have something to do with "The This Problem" as shown in this link: <https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#The_this_problem> Based on that article, I was under the impression that I need to use `.bind`, but I am really not too familiar with this and am struggling to get the proper syntax. My question is, should I be using `.bind()` to fix this issue and if so what is the proper way to add it to the code? As a current example here is what a version of my code looks like. With this code, the `setTimeout` with 6000 ms works, but the one with 60,000 does not. Happy to provide more information. // In Front End ``` userComplete(a, b); ``` // In Backend ``` export function userComplete (a,b) { setTimeout(() => { addData(a.proj_sub_id, b, a.proj_instance_id); }, 60000); setTimeout(() => { addData(a.proj_sub_id, b, a.proj_instance_id); }, 6000); ```<issue_comment>username_1: Try using `setInterval` instead. <https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval> Upvotes: -1 <issue_comment>username_2: You can try passing the function to setTimeout directly and in the function userComplete just call your addData method and try if it works. ``` setTimeout(userComplete,60000); ``` Upvotes: -1
2018/03/19
773
2,833
<issue_start>username_0: I'm looking to add a new column to a pre-existing table which is filled with values. The new column is going to be `NOT NULL`, and so for each pre-existing row it will need a value. I'm looking for the initial values on this column to be calculated based off other values in the table at the time of column creation, and *only* at the time of column creation. I have a very specific use case, so I'm not looking for a workaround. I'll give a very boiled-down example of what I'm looking for: Say I have this data: ``` CREATE TABLE numbers ( value1 INTEGER NOT NULL, value2 INTEGER NOT NULL ); INSERT INTO numbers(value1, value2) VALUES (10, 20), (2, 5); ``` I wish to create a new column `value3` on the `numbers` table which, at the time of creation, is always equal to the sum of its corresponding `value1` and `value2` columns. E.g.: ``` ALTER TABLE numbers ADD COLUMN value3 INTEGER; /* ... some more logic which calculates the initial values ... */ ALTER TABLE numbers ALTER COLUMN value3 SET NOT NULL; ``` And after this is done, I'd like the following data: ``` -- The 3rd value will be the sum of the first 2 values SELECT * FROM numbers; value1 | value2 | value3 -------+--------+------- 10 | 20 | 30 2 | 5 | 7 ``` I'll later need to update the data, perhaps ruining the relationship `value3 === (value1 + value2)`: ``` UPDATE numbers SET value3=9823 WHERE value1=10; ``` How can I implement the step of inserting calculated initial values into the `value3` column?<issue_comment>username_1: You have two options to do so: 1. If you need the computed value to be stored on database a trigger. ``` CREATE OR REPLACE FUNCTION sum_columns() RETURNS trigger AS $BODY$ BEGIN NEW.value := new.value1+new.value2; RETURN NEW; END; $BODY$ LANGUAGE plpgsql; CREATE TRIGGER calculated_colum AFTER INSERT OR UPDATE ON numbers FOR EACH ROW EXECUTE PROCEDURE sum_columns(); ``` 2. If you don't need the computed value to be stored on database you can use a functional index ``` CREATE INDEX sum_columns_idx ON numbers ((value1+value2)); ``` Upvotes: 0 <issue_comment>username_2: I discovered a simple way! The following adds the `value3` column with the desired initial values: ``` ALTER TABLE numbers ADD COLUMN value3 INTEGER; -- Exclude the NOT NULL constraint here UPDATE numbers SET value3=value1+value2; -- Insert data with a regular UPDATE ALTER TABLE numbers ALTER COLUMN value3 SET NOT NULL; -- Now set the NOT NULL constraint ``` This method is good when postgres has a native function for the calculation you want to apply to the new column. E.g. in this case the calculation I want is "sum", and postgres does that via the `+` operator. This method will be more complex for operations not natively provided by postgres. Upvotes: 6 [selected_answer]
2018/03/19
763
2,614
<issue_start>username_0: I have the following YAML contract: ``` request: method: GET url: /get response: status: 200 body: name: 'Name' code: '123' asOfDate: '1994-05-25T04:00:00.000Z' matchers: body: - path: "$[*].name" type: by_type - path: "$[*].code" type: by_regex value: '[0-9]{3}' - path: "$[*].asOfDate" type: by_regex predefined: iso_date_time ``` Which generates the following test code: ``` // and: DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); assertThatJson(parsedJson).field("['code']").isEqualTo("123"); assertThatJson(parsedJson).field("['asOfDate']").isEqualTo("1994-05-25T04:00:00.000Z"); assertThatJson(parsedJson).field("['name']").isEqualTo("Name"); // and: assertThat((Object) parsedJson.read("$[*].name")).isInstanceOf(java.util.List.class); assertThat((java.lang.Iterable) parsedJson.read("$[*].code", java.util.Collection.class)).allElementsMatch("[0-9]{3}"); assertThat((java.lang.Iterable) parsedJson.read("$[*].asOfDate", java.util.Collection.class)).allElementsMatch("ignore"); ``` My issue is that I do not want the contract to force the code to match values exactly (the first three asserts). I only want the contract to generate the last three asserts (the ones that check for correct typing). Is there something I am not writing correctly in the YAML contract? Worth noting that removing "asOfDate" from the response body generates the asserts I want, but if I remove "name" and "code", no asserts will be generated at all.<issue_comment>username_1: I think your paths are wrong. You should write `$.name`, `$.code` and `$.asOfDate`. Then SC-Contract will remove these entries from automatic generation. Upvotes: 1 <issue_comment>username_2: If you only want to use checks from response->matchers->body and don't want to use checks from response->body, you can do a trick that Marcin suggested: ``` request: method: GET url: /get response: status: 200 body: name: $.name code: $.code asOfDate: $.asOfDate matchers: body: - path: "$[*].name" type: by_type - path: "$[*].code" type: by_regex value: '[0-9]{3}' - path: "$[*].asOfDate" type: by_regex predefined: iso_date_time ``` As a result, you will have no asserts like: ``` assertThatJson(parsedJson).field("['name']").isEqualTo("Name"); ``` but only: ``` assertThat(parsedJson.read("$[*].code", String.class)).matches("[0-9]{3}"); ``` Upvotes: 0
2018/03/19
757
2,769
<issue_start>username_0: I am playing with React and trying to save the text that user type to the input to the `state`. I have added to the textarea an `onChange` attribute for setting the state. However, when I start typing, I see error in the console stating `TypeError: _this.setState is not a function`. I've tried different ways of trying to fix it, but still don't have it. ``` const NewItemForm = props => ( this.setState({ item\_msg: e.target.value })} /> ) class App extends Component { constructor () { super(); this.state = { item_msg: '' } } handleSubmit(e){ e.preventDefault(); console.log(this.state.item_msg); } render() { return ( ); } } export default App; ```<issue_comment>username_1: Functional components do not have lifecycle methods and... `state` :) ``` const NewItemForm = props => ( this.setState({ item\_msg: e.target.value })} /> ) ``` This won't work: ``` onChange={e => this.setState({ item_msg: e.target.value })} /> ``` What you need is to pass callback: ``` const NewItemForm = props => ( ) class App extends Component { constructor () { super(); this.state = { item_msg: '' } this.handleSubmit = this.handleSubmit.bind(this); this.handleInputChange = this.handleInputChange.bind(this); } handleSubmit(e){ e.preventDefault(); console.log(this.state.item_msg); } handleInputChange(e) { this.setState({ item_msg: e.target.value }) } render() { return ( ); } } ``` I get where you are coming from, but `NewItemForm` will get transpiled to React Element so `this` will reference that Element, not the `App` component. [React without JSX](https://reactjs.org/docs/react-without-jsx.html) Upvotes: 3 [selected_answer]<issue_comment>username_2: Functional components are stateless so you can't call `setState` within them. You can pass a callback from your parent component that sets state in the parent component as follows: ``` handleChange = e => this.setState({ item_msg: e.target.value }); ``` And then in your `NewItemForm` component: ``` ``` Upvotes: 2 <issue_comment>username_3: NewItemForm is function component and function comopent does not have lifecycle method use class component. Upvotes: 1 <issue_comment>username_4: You need to either use arrow function or bind the function in constructor like below ``` constructor(props) { super(props); this.state = { date: new Date() }; this.tick = this.tick.bind(this); } setInterval(()=>this.tick, 1000); ``` or Use arrow function ``` setInterval(()=>this.setState({ date: new Date(), }), 1000); ``` Upvotes: 0
2018/03/19
682
2,458
<issue_start>username_0: Hi I am using Fabric Java SDK and able to run the EndToEndIT.java test cases . The test file loads chaincode as **example\_cc.go** I want the chaincode as **example\_cc.java** and load the chaincode as java file rather than go I am stuck and not sure how to do this . I want to know the equivalent **java** code for the **go** chaincode and a way to call it in the EndToEndIT.java test file Please list out the steps to run the same . Thanks !<issue_comment>username_1: Functional components do not have lifecycle methods and... `state` :) ``` const NewItemForm = props => ( this.setState({ item\_msg: e.target.value })} /> ) ``` This won't work: ``` onChange={e => this.setState({ item_msg: e.target.value })} /> ``` What you need is to pass callback: ``` const NewItemForm = props => ( ) class App extends Component { constructor () { super(); this.state = { item_msg: '' } this.handleSubmit = this.handleSubmit.bind(this); this.handleInputChange = this.handleInputChange.bind(this); } handleSubmit(e){ e.preventDefault(); console.log(this.state.item_msg); } handleInputChange(e) { this.setState({ item_msg: e.target.value }) } render() { return ( ); } } ``` I get where you are coming from, but `NewItemForm` will get transpiled to React Element so `this` will reference that Element, not the `App` component. [React without JSX](https://reactjs.org/docs/react-without-jsx.html) Upvotes: 3 [selected_answer]<issue_comment>username_2: Functional components are stateless so you can't call `setState` within them. You can pass a callback from your parent component that sets state in the parent component as follows: ``` handleChange = e => this.setState({ item_msg: e.target.value }); ``` And then in your `NewItemForm` component: ``` ``` Upvotes: 2 <issue_comment>username_3: NewItemForm is function component and function comopent does not have lifecycle method use class component. Upvotes: 1 <issue_comment>username_4: You need to either use arrow function or bind the function in constructor like below ``` constructor(props) { super(props); this.state = { date: new Date() }; this.tick = this.tick.bind(this); } setInterval(()=>this.tick, 1000); ``` or Use arrow function ``` setInterval(()=>this.setState({ date: new Date(), }), 1000); ``` Upvotes: 0
2018/03/19
443
1,793
<issue_start>username_0: I want to be able to set the @JMSlistener destination from an application.properties my code looks like this ``` @Service public class ListenerService { private Logger log = Logger.getLogger(ListenerService.class); @Autowired QueueProperties queueProperties; public ListenerService(QueueProperties queueProperties) { this.queueProperties = queueProperties; } @JmsListener(destination = queueProperties.getQueueName() ) public void listenQueue(String requestJSON) throws JMSException { log.info("Received " + requestJSON); } } ``` but when building I get ``` Error:(25, 60) java: element value must be a constant expression ```<issue_comment>username_1: You can't reference a field within the current bean, but you can reference another bean in the application context using a SpEL expression... ``` @SpringBootApplication public class So49368515Application { public static void main(String[] args) { SpringApplication.run(So49368515Application.class, args); } @Bean public ApplicationRunner runner(JmsTemplate template, Foo foo) { return args -> template.convertAndSend(foo.getDestination(), "test"); } @JmsListener(destination = "#{@foo.destination}") public void listen(Message in) { System.out.println(in); } @Bean public Foo foo() { return new Foo(); } public class Foo { public String getDestination() { return "foo"; } } } ``` You can also use property placeholders `${...}`. Upvotes: 5 [selected_answer]<issue_comment>username_2: Using property placeholder is much easier. ``` @JmsListener(destination = "${mq.queue}") public void onMessage(Message data) { } ``` Upvotes: 3
2018/03/19
514
1,964
<issue_start>username_0: I want to know in my app (by code) in which app store my user is (like england / france / spain ect). I already read that we can do this with the locale : <https://developer.apple.com/documentation/foundation/nslocale/1643060-countrycode> But I would like to do it with the Apple Store. For legal purpose I don't want to display the same content for an european than for an american. Has someone already done it ? Thanks !<issue_comment>username_1: You can't restrict IAP(so you don't have information about the Apple Store used) for specific country. What you can do is disable/enable items by checking country ID. there are different way for check it, for me the best is by checking user carrier ID. For example: ``` func checkCellularNumber() -> Bool { let networkInfo = CTTelephonyNetworkInfo() guard let info = networkInfo.subscriberCellularProvider else {return false} if let carrier = info.isoCountryCode { print("Carrier code = \(carrier)"); return true } return false } ``` Upvotes: 3 <issue_comment>username_2: From iOS13 `SKStorefront` class property `countryCode` can be used to get three-letter code representing the country associated with the App Store storefront. For iOS version below 13 only viable solution was to get `priceLocale` from `SKProduct`. Upvotes: 4 <issue_comment>username_3: If you're on iOS 13+, This will give you the 3 letter country code for the store: ``` import StoreKit let country = SKPaymentQueue.default().storefront?.countryCode ``` More information on it's usage can be found in the [SKStoreFront documentation](https://developer.apple.com/documentation/storekit/skstorefront). UPDATE: Occasionally, this method returns nil, which is why storefront is an optional. So it's not 100% reliable. I was using with thousands of users, and it was working 95% of the time. I'm not entirely sure under what circumstances it is nil however. Upvotes: 3
2018/03/19
541
1,915
<issue_start>username_0: I would like to know if GCP's DataProc supports [WebHCat](https://cwiki.apache.org/confluence/display/Hive/WebHCat). [Googling](https://www.google.co.uk/search?q=gcp%20dataproc%20webhcat&oq=gcp%20dataproc%20webhcat&aqs=chrome..69i57.7173j0j1&sourceid=chrome&ie=UTF-8) hasn't turned up anything. So, does GCP DataProc support/provide WebHCat and if so what is the URL endpoint?<issue_comment>username_1: You can't restrict IAP(so you don't have information about the Apple Store used) for specific country. What you can do is disable/enable items by checking country ID. there are different way for check it, for me the best is by checking user carrier ID. For example: ``` func checkCellularNumber() -> Bool { let networkInfo = CTTelephonyNetworkInfo() guard let info = networkInfo.subscriberCellularProvider else {return false} if let carrier = info.isoCountryCode { print("Carrier code = \(carrier)"); return true } return false } ``` Upvotes: 3 <issue_comment>username_2: From iOS13 `SKStorefront` class property `countryCode` can be used to get three-letter code representing the country associated with the App Store storefront. For iOS version below 13 only viable solution was to get `priceLocale` from `SKProduct`. Upvotes: 4 <issue_comment>username_3: If you're on iOS 13+, This will give you the 3 letter country code for the store: ``` import StoreKit let country = SKPaymentQueue.default().storefront?.countryCode ``` More information on it's usage can be found in the [SKStoreFront documentation](https://developer.apple.com/documentation/storekit/skstorefront). UPDATE: Occasionally, this method returns nil, which is why storefront is an optional. So it's not 100% reliable. I was using with thousands of users, and it was working 95% of the time. I'm not entirely sure under what circumstances it is nil however. Upvotes: 3
2018/03/19
1,600
5,117
<issue_start>username_0: So i'm moving to writing my sass to the BEM convention. I've used the [sass-lint configuration generator](https://sasstools.github.io/make-sass-lint-config/) to create my config and only edited the `class-name-format`'s `- convention:` to `strictbem` however I'm still having some issues with it. Maybe I'm misinterpreting BEM? **Error:** > > [sass-lint] Class '`.bus__tyre--front`' should be written in BEM (Block > Element Modifier) format (class-name-format) > > > > **Sass:** ``` .bus { position: relative; &__tyre { position: absolute; &--front { bottom: -22px; right: 3%; width: 17%; } } } ``` **sass-lint.yml:** ``` # sass-lint config generated by make-sass-lint-config v0.1.2 # # The following scss-lint Linters are not yet supported by sass-lint: # DisableLinterReason, ElsePlacement, PropertyCount, SelectorDepth # SpaceAroundOperator, TrailingWhitespace, UnnecessaryParentReference, Compass::* # # The following settings/values are unsupported by sass-lint: # Linter Indentation, option "allow_non_nested_indentation" # Linter Indentation, option "character" # Linter NestingDepth, option "ignore_parent_selectors" # Linter PropertySortOrder, option "min_properties" # Linter PropertySortOrder, option "separate_groups" # Linter SpaceBeforeBrace, option "allow_single_line_padding" # Linter VendorPrefix, option "identifier_list" files: include: '**/*.scss' options: formatter: stylish merge-default-rules: false rules: bem-depth: - 0 - max-depth: 1 border-zero: - 1 - convention: zero brace-style: - 1 - allow-single-line: true class-name-format: - 1 - convention: strictbem clean-import-paths: - 1 - filename-extension: false leading-underscore: false empty-line-between-blocks: - 1 - ignore-single-line-rulesets: true extends-before-declarations: 1 extends-before-mixins: 1 final-newline: - 1 - include: true force-attribute-nesting: 1 force-element-nesting: 1 force-pseudo-nesting: 1 function-name-format: - 1 - allow-leading-underscore: true convention: hyphenatedlowercase hex-length: - 1 - style: short hex-notation: - 1 - style: lowercase id-name-format: - 1 - convention: hyphenatedlowercase indentation: - 1 - size: 2 leading-zero: - 1 - include: false mixin-name-format: - 1 - allow-leading-underscore: true convention: hyphenatedlowercase mixins-before-declarations: 1 nesting-depth: - 1 - max-depth: 3 no-color-keywords: 1 no-color-literals: 1 no-css-comments: 1 no-debug: 1 no-duplicate-properties: 1 no-empty-rulesets: 1 no-extends: 0 no-ids: 1 no-important: 1 no-invalid-hex: 1 no-mergeable-selectors: 1 no-misspelled-properties: - 1 - extra-properties: [] no-qualifying-elements: - 1 - allow-element-with-attribute: false allow-element-with-class: false allow-element-with-id: false no-trailing-zero: 1 no-transition-all: 0 no-url-protocols: 1 no-vendor-prefixes: - 1 - additional-identifiers: [] excluded-identifiers: [] placeholder-in-extend: 1 placeholder-name-format: - 1 - convention: hyphenatedlowercase property-sort-order: - 1 - ignore-custom-properties: false property-units: - 1 - global: - ch - em - ex - rem - cm - in - mm - pc - pt - px - q - vh - vw - vmin - vmax - deg - grad - rad - turn - ms - s - Hz - kHz - dpi - dpcm - dppx - '%' per-property: {} quotes: - 1 - style: single shorthand-values: - 1 - allowed-shorthands: - 1 - 2 - 3 single-line-per-selector: 1 space-after-bang: - 1 - include: false space-after-colon: - 1 - include: true space-after-comma: - 1 - include: true space-before-bang: - 1 - include: true space-before-brace: - 1 - include: true space-before-colon: 1 space-between-parens: - 1 - include: false trailing-semicolon: 1 url-quotes: 1 variable-for-property: - 0 - properties: [] variable-name-format: - 1 - allow-leading-underscore: true convention: hyphenatedlowercase zero-unit: 1 ```<issue_comment>username_1: Judging by [#335](https://github.com/brigade/scss-lint/issues/335) and [#319](https://github.com/brigade/scss-lint/issues/319) in the scss-lint repo, it looks like you need to change: ``` class-name-format: - 1 - convention: strictbem ``` to: ``` class-name-format: - 1 - convention: hyphenatedbem ``` I hope that helps! Upvotes: 3 [selected_answer]<issue_comment>username_2: Instead of `hyphenated_BEM` it should be `hyphenatedbem`. [Example from the sass-lint docs](https://github.com/sasstools/sass-lint/blob/develop/docs/rules/class-name-format.md#example-7) Upvotes: 2
2018/03/19
796
3,151
<issue_start>username_0: I have some experience with ReactJS but now I am trying to start using Redux and I have encoutered several problems. I already know how to create actions, consts, reducers, how to connect them to one single store, but I don't actually now how to use it with React. For example I have a form to gather user's data and I want it all passed to Redux store. So I guess the main question would be how do I trigger the action in ReactJS?<issue_comment>username_1: To bind redux to react there is a package called [react-redux](https://github.com/reactjs/react-redux). The description of which is official react bindings for redux. You can connect the actions to react by using `mapDispatchToProps`, which will map your actions as props. Then you can call those actions as props. When you call those actions as props, the actions will be triggered and redux state will change. To access the state you have to use `mapStateToProps`, which will give you the state as props. You can use `connect` method to connect `mapStateToProps` and `mapDispatchToProps` to react. I think it would be easier if you do a tutorial. [This](https://egghead.io/courses/getting-started-with-redux) is a tutorial by <NAME>, creator of Redux. Upvotes: 2 <issue_comment>username_2: You'll want to use [react-redux](https://github.com/reactjs/react-redux). For example, here's a small counter: ``` import { connect } from "react-redux"; import { increment } from "actions"; import PropTypes from "prop-types"; import React from "react"; function counter ({ count, increment }) { return {count} ; } counter.propTypes = { count: PropTypes.number.isRequired, increment: PropTypes.func.isRequired }; export default connect( (state) => ({ count: state.data.count }), { increment } )(counter); ``` The `(state) => ({ })` bit passes a property called `count` to the component's props. The `{ increment }` passes your `increment` function in the props. Be sure to include the `{ increment }` part in the `connect`; if you don't, your redux action won't be dispatched. Upvotes: 2 <issue_comment>username_3: when using `react-redux`, you'll get a component enhancer called `connect`. ``` class Component extends React.Component { render() { return ( {this.props.a} ) } } export default connect(function mapStateToProps(state) { return { a: state.store.a } }, { onClickButton: incrementAction })(Component) ``` What I'm doing here is taking a global store value (`state.store.a` - `state` is the global store, `.store` is the store from a combined store, and `a` is the value), and telling the React component to listen for changes on this variable (transparently through `connect`). Additionally, I'm wrapping an action creator `incrementAction` (and renaming it to `onClickButton`). If you're using a middleware like `redux-thunk`, this will automatically pass in `store.dispatch` as an arg. Otherwise, this is a standard action creator. both of these will be available inside the component as props (the args are descriptively named `mapStateToProps` and `mapDispatchToProps`) Upvotes: 3 [selected_answer]
2018/03/19
782
2,491
<issue_start>username_0: Given an RDD, what's the best way to sort it and then consume it in discrete sized chunks? For example: ``` JavaRDD baseRdd = sc.parallelize(Arrays.asList(1,2,5,3,4)); JavaRDD sorted = baseRdd.sortBy(x -> x, true, 5); // returns 1, 2 List first = sorted.take(2); // returns 1, 2. How to skip 2 and then take? List second = sorted.take(2); ``` What I would really like is to consume `1, 2` on the first call to `take(2)`, and then have some sort of "skip" parameter that gets passed into the second `take(2)` to return `3, 4`? Since that "skip" function doesn't seem to exist in the current RDD functionality, what would be the most efficient way to split up the sorted RDD into chunks of known size that can be independently acted on?<issue_comment>username_1: ``` rdd1=sc.parallelize((1,2,3,4,5,6,7,8)) rdd2=rdd1.take(2) ``` Now you filter your initial rdd based on rdd2 ``` rdd1.filter(lambda line:line not in rdd2).take(2) ``` This gives [3, 4] *Using PySpark* Upvotes: 0 <issue_comment>username_2: To make it efficient, don't forget you can cache your RDD at any point. This will avoid recomputing the sorted RDD from the text file every time we call `take`. As we will be using the `sorted` RDD multiple times, we will cache it: ``` JavaRDD sorted = baseRdd.sortBy(x -> x, true, 5).cache(); ``` --- Then to take elements from a given index to another index, we can combine `zipWithIndex` and `filter`. `zipWithIndex` transforms the RDD into an RDD of tuples where the first part of the tuple is the element of the sorted RDD and the second part is its index. Once we have these indexed records, we can filter them thanks to their index (let's say offset = 2 and window = 2): ``` List nth = sorted.zipWithIndex() .filter(x -> x.\_2() >= offset && x.\_2() < offset + window) .map(x -> x.\_1()) .collect(); ``` which returns: ``` [3, 4] ``` --- The final result would be: ``` JavaRDD sorted = baseRdd.sortBy(x -> x, true, 5).zipWithIndex().cache(); Integer offset = 2; Integer window = 2; List nth = sorted .filter(x -> x.\_2() >= offset && x.\_2() < offset + window) .map(x -> x.\_1()) .collect(); ``` Here I've cached the rdd only after zipping it with index in order not to perform the zipping part each time we perform this action on a different window. You can then map this `nth` creation snippet into a loop or a map depending on how you want to create the different window lists. Upvotes: 3 [selected_answer]
2018/03/19
758
2,523
<issue_start>username_0: I have a page ([codepen](https://codepen.io/RobertGelb/pen/QmKvry)) which utilizes both bootstrap & flexbox (i have good reasons for that): ``` body { display: flex; flex-direction: column; } ``` When the user clicks the YES radio box, a bit of JavaScript shows another label with YES/NO question. When that happens is that the `Email Address` textbox at the top expands even through though nothing has changed for it. This is caused by flexbox, I suspect. The `Are you a fantastic human being` is also reflowed. Is there a way to stop both the label and the textbox from changing size? P.S. If anyone is wondering why I didn't use SO's snippet utility, the problem only appears when the Results page is full width of the browser and Codepen lets you do that.<issue_comment>username_1: ``` rdd1=sc.parallelize((1,2,3,4,5,6,7,8)) rdd2=rdd1.take(2) ``` Now you filter your initial rdd based on rdd2 ``` rdd1.filter(lambda line:line not in rdd2).take(2) ``` This gives [3, 4] *Using PySpark* Upvotes: 0 <issue_comment>username_2: To make it efficient, don't forget you can cache your RDD at any point. This will avoid recomputing the sorted RDD from the text file every time we call `take`. As we will be using the `sorted` RDD multiple times, we will cache it: ``` JavaRDD sorted = baseRdd.sortBy(x -> x, true, 5).cache(); ``` --- Then to take elements from a given index to another index, we can combine `zipWithIndex` and `filter`. `zipWithIndex` transforms the RDD into an RDD of tuples where the first part of the tuple is the element of the sorted RDD and the second part is its index. Once we have these indexed records, we can filter them thanks to their index (let's say offset = 2 and window = 2): ``` List nth = sorted.zipWithIndex() .filter(x -> x.\_2() >= offset && x.\_2() < offset + window) .map(x -> x.\_1()) .collect(); ``` which returns: ``` [3, 4] ``` --- The final result would be: ``` JavaRDD sorted = baseRdd.sortBy(x -> x, true, 5).zipWithIndex().cache(); Integer offset = 2; Integer window = 2; List nth = sorted .filter(x -> x.\_2() >= offset && x.\_2() < offset + window) .map(x -> x.\_1()) .collect(); ``` Here I've cached the rdd only after zipping it with index in order not to perform the zipping part each time we perform this action on a different window. You can then map this `nth` creation snippet into a loop or a map depending on how you want to create the different window lists. Upvotes: 3 [selected_answer]
2018/03/19
689
2,171
<issue_start>username_0: I have text strings that look like this: `yryr%(DENHP@Germany)` I want my output to look like this: `yryr__DENHP_Germany_` (I'd also like to replace periods and commas). These are actually variables in a pandas dataframe, and I'm trying to match parentheses at the minute... here's what I'm trying but it isn't quite working. Could someone please help? `df_q_raw.columns = df_q_raw.columns.str.replace(['\.\%r'\('r'\)'], '')`<issue_comment>username_1: ``` rdd1=sc.parallelize((1,2,3,4,5,6,7,8)) rdd2=rdd1.take(2) ``` Now you filter your initial rdd based on rdd2 ``` rdd1.filter(lambda line:line not in rdd2).take(2) ``` This gives [3, 4] *Using PySpark* Upvotes: 0 <issue_comment>username_2: To make it efficient, don't forget you can cache your RDD at any point. This will avoid recomputing the sorted RDD from the text file every time we call `take`. As we will be using the `sorted` RDD multiple times, we will cache it: ``` JavaRDD sorted = baseRdd.sortBy(x -> x, true, 5).cache(); ``` --- Then to take elements from a given index to another index, we can combine `zipWithIndex` and `filter`. `zipWithIndex` transforms the RDD into an RDD of tuples where the first part of the tuple is the element of the sorted RDD and the second part is its index. Once we have these indexed records, we can filter them thanks to their index (let's say offset = 2 and window = 2): ``` List nth = sorted.zipWithIndex() .filter(x -> x.\_2() >= offset && x.\_2() < offset + window) .map(x -> x.\_1()) .collect(); ``` which returns: ``` [3, 4] ``` --- The final result would be: ``` JavaRDD sorted = baseRdd.sortBy(x -> x, true, 5).zipWithIndex().cache(); Integer offset = 2; Integer window = 2; List nth = sorted .filter(x -> x.\_2() >= offset && x.\_2() < offset + window) .map(x -> x.\_1()) .collect(); ``` Here I've cached the rdd only after zipping it with index in order not to perform the zipping part each time we perform this action on a different window. You can then map this `nth` creation snippet into a loop or a map depending on how you want to create the different window lists. Upvotes: 3 [selected_answer]
2018/03/19
482
1,930
<issue_start>username_0: I am trying to encrypt a string using my own password key. After generate encrypted text i need to save it to text file to later use. Also i need to read that encrypted text end decrypt it. It will be great if some one can give me a solution to do this thing in Java SE App.<issue_comment>username_1: How about Spring's TextEncryptor. Its not strictly SE but it might still be good enough for your use case. ``` import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import org.apache.commons.io.IOUtils; import org.springframework.security.crypto.encrypt.Encryptors; import org.springframework.security.crypto.encrypt.TextEncryptor; public class Main { public static void main(String[] args) throws IOException { TextEncryptor te = Encryptors.text("12345abc", "<PASSWORD>"); //password, salt.... in hex File file = new File("someFile.txt"); FileWriter fw = new FileWriter(file); String encryptedText = te.encrypt("hellow world!"); fw.append(encryptedText); fw.close(); String text = IOUtils.toString(new FileInputStream(file)); System.out.println(te.decrypt(text)); } } ``` Upvotes: 1 [selected_answer]<issue_comment>username_2: The cipher-descipher is very simple, the concept is the following one: Message - function - cipher Message. The function (that it contains the password) can choose one of the existent (complicated and insecure) ones or to invent it your same one. The function should complete that it is inyectiva and sobreyectiva and the treatment will be a XOR between the message and the function. The descipher is the inverse of this process. The secret this in the function that you have chosen (password). To see the principles of Kerckhoffs and one-time pad of <NAME>. I also recommend you to see some java book that speaks of FILE I/O. Upvotes: -1
2018/03/19
861
2,340
<issue_start>username_0: I have a table like this: ``` CREATE TABLE `test` ( `id` int(11) NOT NULL AUTO_INCREMENT, `x` varchar(45) DEFAULT NULL, `y` varchar(45) DEFAULT NULL, `z` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1; ``` with this data: ``` INSERT INTO test(id, x, y, z) VALUES (1, '1', 'A', 'A'); INSERT INTO test(id, x, y, z) VALUES (2, '1', 'B', 'B'); INSERT INTO test(id, x, y, z) VALUES (3, '1', 'A', 'B'); INSERT INTO test(id, x, y, z) VALUES (4, '2', 'A', 'A'); INSERT INTO test(id, x, y, z) VALUES (5, '2', 'A', 'A'); INSERT INTO test(id, x, y, z) VALUES (6, '2', 'A', 'A'); INSERT INTO test(id, x, y, z) VALUES (7, '3', 'B', 'A'); INSERT INTO test(id, x, y, z) VALUES (8, '4', 'B', 'B'); INSERT INTO test(id, x, y, z) VALUES (9, '5', 'C', 'C'); INSERT INTO test(id, x, y, z) VALUES (10, '5', 'C', 'C'); INSERT INTO test(id, x, y, z) VALUES (11, '5', 'A', 'B'); ``` im looking about what must be the query in order to get this result: ``` x y/z count 1 y A 2 1 y B 1 1 z A 1 1 z B 2 2 y A 3 2 z A 3 3 y B 1 3 z A 1 4 y B 1 4 z B 1 5 y C 2 5 y A 1 5 z C 2 5 z B 1 ``` i have tried with lot of combinations with group by, distinct but i'm unable to get the desired result.<issue_comment>username_1: I think you want a `union all` and `group by`: ``` select x, which, val, count(*) as cnt from ((select x, 'y' as which, y as val from test) union all (select x, 'z' as which, z as val from test) ) xyz group by x, which, val; ``` [Here](http://www.sqlfiddle.com/#!9/4a4928/4) is a SQL Fiddle. Upvotes: 2 [selected_answer]<issue_comment>username_2: Here give this a try. It will create a table for you with two fields that has one row for every x value. The first field is the x value and the second is a comma separated string of the y/z combinations and their counts. Does that work for you? ``` select x, y+','+z combo, count(*) cnt into #A from test group by x , y+','+z select x, combo+','+cast(a.cnt as varchar) data into #B from #A a Select distinct t2.x, substring((Select ', '+t1.data From #b t1 Where T1.x= T2.x ORDER BY T1.x For XML PATH ('')),2, 1000) data From #b T2 ``` Upvotes: 0
2018/03/19
576
2,263
<issue_start>username_0: I am trying to create a user that only has access to a few views and procedures. The user seems to be created fine, but when I attempt to log in to the user account using the connection string below, I get the error `Login failed for user 'Interface_Admin'`. ``` User ID=Interface_Admin;Password=<PASSWORD>;Integrated Security=False;server=SQL02;database=TESTDB;Trusted_Connection=False; ``` My code to create the user and grant permissions is below. ``` USE TESTDB GO IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N'Interface_Admin') DROP USER Interface_Admin IF EXISTS (SELECT * FROM master.dbo.syslogins WHERE name = 'Interface_Admin_Login') DROP LOGIN Interface_Admin_Login IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N'Interface_Users') DROP ROLE Interface_Users -- Create role and add user accounts CREATE ROLE Interface_Users CREATE LOGIN Interface_Admin_Login WITH PASSWORD = '<PASSWORD>' CREATE USER Interface_Admin FROM LOGIN Interface_Admin_Login EXEC sp_addrolemember @rolename='Interface_Users', @membername='Interface_Admin' GO -- Grant permissions -- Views GRANT SELECT ON Vw_Interface_Main TO Interface_Users; -- Procedures GRANT EXECUTE ON Proc_GetNextFileSequence TO Interface_Users; GRANT EXECUTE ON Proc_OutboundFiles TO Interface_Users; GRANT EXECUTE ON Proc_InsertOrUpdateFile TO Interface_Users; ```<issue_comment>username_1: So, I think this is down to a misunderstanding on my part, but I was able to resolve this by giving the same name to both the user and the login. ``` -- Create role and add user accounts CREATE ROLE Interface_Users CREATE LOGIN Interface_Admin WITH PASSWORD = '<PASSWORD>' CREATE USER Interface_Admin FROM LOGIN Interface_Admin EXEC sp_addrolemember @rolename='Interface_Users', @membername='Interface_Admin' GO ``` Upvotes: 0 <issue_comment>username_2: Your original script has Create Login with `Interface_Admin_Login`, but then User Id in the connection string is `Interface_Admin`. Logins should be done with the Login name, not user name. Login = access to the instance, users are used to handle permissions within each database. Generally users are created with the same name as the login to avoid confusion. Upvotes: 2 [selected_answer]
2018/03/19
526
1,757
<issue_start>username_0: How can I generate completely static binaries with clang? I have used the following command: ``` clang -flto -o -fuse-ld=lld -static-libgcc -lc -Bstatic -m32 ``` And yet, the generated output depends on a certain `.so` file: ``` $ ldd linux-gate.so.1 => (0xf77dd000) libc.so.6 => /lib/libc.so.6 (0xf75f0000) /lib/ld-linux.so.2 (0x5663b000) ``` [The following answer](https://stackoverflow.com/a/34463943/915843) tries to answer the question but doesn't directly address the problem. **Is it even possible, to generate completely independent binaries?** Or should I have resort to using other different C library implementations other than `libgcc`? If yes, then how do I link it with clang if I have the source code, of for example `newlib`?<issue_comment>username_1: Just compile it using the clang's -static flag. On your case, try: ``` clang -flto -o -static -m32 ``` The results on my test program show: ``` [root@interserver ogrerobot.com]# ldd ./CppUtilsSpikes not a dynamic executable ``` Upvotes: 3 <issue_comment>username_2: If you, like me, got here expecting Darwin would behave somewhat similarly to Linux, [that unfortunately isn't the case](https://developer.apple.com/library/archive/qa/qa1118/_index.html) > > Apple fully supports static libraries; if you want to create one, just > start with the appropriate Xcode project or target template. > > > Apple does not support statically linked binaries on Mac OS X. A > statically linked binary assumes binary compatibility at the kernel > system call interface, and we do not make any guarantees on that > front. Rather, we strive to ensure binary compatibility in each > dynamically linked system library and framework. > > > Upvotes: 1
2018/03/19
1,333
5,615
<issue_start>username_0: I'm building a XLSX processor that transforms a XLSX into a CSV file. Because the files can get quite big, I'm using the event-based approach using XSSFSheetXMLHandler This works perfectly fine, but my XLSX files contains long numbers (13 digits) which are unique identification numbers, not real numbers. When running my code on a Windows machine it correctly extracts the numbers, but when running on a Linux machine it converts it to E-notation. For example: the source value is 7401075293087. On windows this is correctly extracted into my CSV, but on Linux the value comes through as 7.40108E+12 The problem with the XSSFSheetXMLHandler is that it reads the XLSX under the covers and then throws events that are caught by a SheetContentsHandler that you need to implement. Once of the method in the SheetContentsHandler is a cell method with the signature: cell(String cellReference, String formattedValue, XSSFComment comment) As your can see, this method already received the formatted cell (so in my case it receives "7.40108E+12"). All the rest of the logic happens under the covers. Based on my investigations I believe the solution lies in defining a custom DataFormatter that will specifically treat 13 digit integers as a string, instead of formatting them as E-notation. Unfortunately my plan didn't work as expected and I couldn't find an help online. Below is an extract of my code. I tried the following in the processSheet method: ``` Locale locale = new Locale.Builder().setLanguage("en").setRegion("ZA").build(); DataFormatter formatter = new DataFormatter(locale); Format format = new MessageFormat("{0,number,full}"); formatter.addFormat("#############", format); ``` Here's an extract of my code: The main body of the code: ``` public void process(String Filename)throws IOException, OpenXML4JException, ParserConfigurationException, SAXException { ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(this.xlsxPackage); XSSFReader xssfReader = new XSSFReader(this.xlsxPackage); StylesTable styles = xssfReader.getStylesTable(); XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData(); while (iter.hasNext()) { InputStream stream = iter.next(); String sheetName = iter.getSheetName(); outStream = new FileOutputStream(Filename); logger.info(sheetName); this.output = new PrintWriter(Filename); processSheet(styles, strings, new SheetToCSV(), stream); logger.info("Done with Sheet :"+sheetName); output.flush(); stream.close(); outStream.close(); output.close(); ++index; } } public void processSheet(StylesTable styles,ReadOnlySharedStringsTable strings,SheetContentsHandler sheetHandler, InputStream sheetInputStream) throws IOException, ParserConfigurationException, SAXException { InputSource sheetSource = new InputSource(sheetInputStream); try { XMLReader sheetParser = SAXHelper.newXMLReader(); ContentHandler handler = new XSSFSheetXMLHandler(styles, null, strings, sheetHandler, formatter, false); sheetParser.setContentHandler(handler); sheetParser.parse(sheetSource); } catch(ParserConfigurationException e) { throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage()); } } ``` And here's the custom handler: ``` private class SheetToCSV implements SheetContentsHandler { private boolean firstCellOfRow = false; private int currentRow = -1; private int currentCol = -1; private void outputMissingRows(int number) { for (int i=0; i ```<issue_comment>username_1: DZONE wrote a cracking article on this: <https://dzone.com/articles/simple-string-representation-of-java-decimal-numbe> Another answer from StackOverflow is: ``` Row row = sheet.getRow(0); Object o = getCellValue(row.getCell(0)); System.out.println(new BigDecimal(o.toString()).toPlainString()); ``` REF: [Apache POI DataFormatter Returns Scientific Notation](https://stackoverflow.com/questions/46431561/apache-poi-dataformatter-returns-scientific-notation) I didn't test your actual problem on a linux machine.. however I hope this provides some answers in the midst of the night! Upvotes: 1 <issue_comment>username_2: Cannot reproducing if the file is generated using `Excel` and the cells containing the 13 digit numbers are formatted using number format `0` or `#`, **not** `General`. But what is meant with "running on a Linux machine"? If I am creating the `*.xlsx` file using `Libreoffice Calc` having the cells containing the 13 digit numbers formatted using number format `General`, then `Calc` will showing them as 13 digit numbers but `Excel` will not. For showing the numbers 13 digit in `Excel` the cells must be formatted using number format `0` or `#`. The `apache poi` `DataFormatter` is made to work like `Excel` would do. And `Excel` shows values from 12 digits on as scientific notation when formatted using `General`. You could changing this behavior using: ``` ... public void processSheet( StylesTable styles, ReadOnlySharedStringsTable strings, SheetContentsHandler sheetHandler, InputStream sheetInputStream) throws IOException, SAXException { DataFormatter formatter = new DataFormatter(); formatter.addFormat("General", new java.text.DecimalFormat("#.###############")); ... ``` Upvotes: 3 [selected_answer]
2018/03/19
598
2,149
<issue_start>username_0: I'm having trouble correctly accessing data in Google Maps API php. Heres what example data looks in php: ``` {"destination_addresses":["Destination address"],"origin_addresses":["Origin address"],"rows":[{"elements":[{"distance":{"text":"3.3 km","value":3314},"duration":{"text":"6 mins","value":334},"status":"OK"}]}],"status":"OK"} ``` Heres my .js: ``` $(function(){ $("#button").click(function(){ var start = $("#start").val(); //gets start and end values from input fields, and passes them to .php which is not visible here. var end = $("#end").val(); $.ajax({url: "googlemaps.php", method: "GET", data : { "start" : start, "end" : end }, success: function(result) { print(result); }, error: function(xhr){ alert("Error: " + xhr.status + " " + xhr.statusText); } }); }); }); function print(result){ var length = ""; for(var i = 0;i < result.rows.length;i++){ length += result.rows[i].text+ " "; $("#div").html(length); }} ``` It should calculate the distance between two addresses, and it currently returns unidentified (which is ok), since ``` length += result.rows[i].text+ " "; ``` is not correct. I have no idea how to access value "text":"3.3 km", or it's equivalent in my code. I know it is an object inside "distance", which is an array item of "elements", which is an array item of "rows".<issue_comment>username_1: Its structured like: `rows[0].elements[0].distance.text` You might not need the loop, but if you were to use it you would do something like. ``` for (var i = 0;i < result.rows.length; i++) { for (var k = 0;k < result.rows[i].elements.length; k++) { length += result.rows[i].elements[k].distance.text + " "; } } $("#div").html(length); ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: If your array is `result`, then you can access the distance by using this: ``` var distance = result['rows'][0]['elements'][0]['distance']['text']; ``` Upvotes: 0
2018/03/19
644
1,785
<issue_start>username_0: I would like to know why select count distinct return zero result. I have also checked various answers at here but it's not answer for my case. MySQL version 5.6 Link to check <http://sqlfiddle.com/#!9/276302/3/0> **Sample schema:** ``` CREATE TABLE IF NOT EXISTS `employees` ( `id` int(6) unsigned NOT NULL, `name` varchar(3) NOT NULL, `salary` varchar(200) NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8; INSERT INTO `employees` (`id`, `name`, `salary`) VALUES ('1', 'a', 6), ('2', 'b', 5), ('3', 'c', 5), ('4', 'd', 4); ``` **Query:** ``` SELECT COUNT(DISTINCT(salary)) FROM employees; ``` Guys, do you have any idea ?<issue_comment>username_1: Your salary column is type VARCHAR, try using INT or another appropriate data type. See here: <http://sqlfiddle.com/#!9/875bde/1/0> Upvotes: -1 <issue_comment>username_2: you need to change the datatype of salary from varchar to int. OR you need to include salary values in " ". Upvotes: 0 <issue_comment>username_3: ``` select count(ds) from (SELECT distinct(salary) as ds FROM employees) as s; ``` Upvotes: 1 <issue_comment>username_4: In my opinion it is a bug of this specific version of [MySQL 5.6](http://sqlfiddle.com/#!9/276302/3/0). But it will work for [MariaDB](http://dbfiddle.uk/?rdbms=mariadb_10.2&fiddle=5e825761accbb2a68d4cb650131bb71e) or [MySQL 5.7](https://www.db-fiddle.com/f/5taBEKJ24TgMiYpoGYtYy2/1) The other answers suggest that it is the problem with datatype.But if we remove `DISTINCT`: ``` SELECT COUNT(salary) FROM employees; -- 4 ``` [DBFiddle Demo MySQL 5.6](http://sqlfiddle.com/#!9/276302/5) Upvotes: 2 <issue_comment>username_5: This is [a known and long-standing bug](https://bugs.mysql.com/bug.php?id=30402#c392551) in MySQL. :-( Upvotes: 0
2018/03/19
418
1,345
<issue_start>username_0: I have to add a new line in the existing csv at the specific line number. I am using following command ``` sed -i '' '3i\ Line to add in csv\n' data.csv ``` But it is adding the line as Line to add in csv**n**<issue_comment>username_1: Simply use : ``` sed -i '' '3i\ Line to add in csv\ ' data.csv ``` [sed](/questions/tagged/sed "show questions tagged 'sed'") is not good for using `\n`, [perl](/questions/tagged/perl "show questions tagged 'perl'") handle this better with the same syntax most of the time than [sed](/questions/tagged/sed "show questions tagged 'sed'") Ex : ``` perl -i -pe 's///' file ``` (for substitutions) Upvotes: 1 <issue_comment>username_2: In the shell `\n` has no particular meaning, it just means *literal n*. Instead: ``` sed -i '' '3i\ Line to add in csv\ ' data.csv ``` Upvotes: 3 [selected_answer]<issue_comment>username_1: Using the [ed](/questions/tagged/ed "show questions tagged 'ed'") command for fun ([sed](/questions/tagged/sed "show questions tagged 'sed'") ancestor): File : ------ ``` $ cat file a b c d e f ``` [ed](/questions/tagged/ed "show questions tagged 'ed'") command : ----------------------------------------------------------------- ``` $ ed -s file< ``` Edited file : ------------- ``` $ cat file a b Line to add in csv c d e f ``` Upvotes: 0
2018/03/19
1,498
5,264
<issue_start>username_0: Trying to find a pseudo class that'll target a like this: ``` ``` I've tried `:blank` and `:empty` but neither can detect it. Is it just not possible to do? <https://jsfiddle.net/q3o1y74k/3/><issue_comment>username_1: `:empty` indeed only works for *totally empty* elements. Whitespace content means it is not empty, a single space or linebreak is already enough. Only HTML comments are considered to be 'no content'. For more info see here: <https://css-tricks.com/almanac/selectors/e/empty/> The `:blank` selector is in the works, it will match whitespace, see here: <https://css-tricks.com/almanac/selectors/b/blank/>. But it seems to have no browser support yet. *Update:* See **[here](https://stackoverflow.com/q/6813227/1220550)** for possible solutions to this involving jQuery. Upvotes: 1 <issue_comment>username_2: The problem with your approach is that your container is not actually empty. > > The :empty pseudo-class represents an element that has no children at > all. In terms of the document tree, only element nodes and content > nodes (such as DOM text nodes, CDATA nodes, and entity references) > whose data has a non-zero length must be considered as affecting > emptiness; > > > As you have empty spaces this pseudo class will not do the trick. The :blank pseudo class should be the right one, because this is its definition: > > This blank pseudo-class matches elements that only contain content > which consists of whitespace but are not empty. > > > the problem is that this pseudo class isn't implemented by any browser yet as you can check in the link below. So you will need to wait until it get implemented to be able to use this selector. This pretty much explains the behavior you are facing <https://css4-selectors.com/selector/css4/blank-pseudo-class/> The best approach here is just to be sure that your div will actually be empty, so your approach will work. the best that you can do is to define an empty class like this: ``` .empty{ display:none; } ``` and then add this JS code here, it will append the empty class to your blank items: ``` (function($){ $.isBlank = function(html, obj){ return $.trim(html) === "" || obj.length == 0; }; $('div').each(function() { if($.isBlank( $(this).html(), $(this).contents().filter(function() { return (this.nodeType !== Node.COMMENT_NODE); }) )) { $(this).addClass('empty'); } }); })(jQuery); ``` check it working here, <https://jsfiddle.net/29eup5uw/> Upvotes: 1 <issue_comment>username_3: You just can't without JavaScript/jQuery implementation. `:empty` selector works with empty tags (so without even **any** space in them) or with self-closing tags like . Reference: <https://www.w3schools.com/cssref/css_selectors.asp> If you want to use JavaScript implementation, I guess here you will find the answer: [How do I check if an HTML element is empty using jQuery?](https://stackoverflow.com/questions/6813227/how-do-i-check-if-an-html-element-is-empty-using-jquery) Upvotes: 0 <issue_comment>username_4: As the others mentioned, this isn't possible with CSS *yet*. You can check to see if there's only whitespace with JavaScript however. Here's a simple JS only solution, "empty" divs that match are blue, while divs that have text are red. Updated to add an `empty` class to the empty divs, which would allow you to target them easily with the selector `.empty` in your CSS. The JS only "empty" comparison would look like this: ``` if(element.innerHTML.replace(/^\s*/, "").replace(/\s*$/, "") == "") ``` And if you're using jQuery it would be a bit easier: ``` if( $.trim( $(element).text() ) == "" ){ ``` ```js var navs = document.querySelectorAll(".nav-previous"); for( i=0; i < navs.length; i++ ){ if(navs[i].innerHTML.replace(/^\s*/, "").replace(/\s*$/, "") == "") { navs[i].style.background = 'blue'; navs[i].classList.add( 'empty' ); } else { navs[i].style.background = 'red'; } } ``` ```css .nav-previous { padding: 10px; border: 1px solid #000; } .nav-previous.empty { border: 5px solid green; } ``` ```html Not Empty ``` Upvotes: 2 [selected_answer]<issue_comment>username_5: `:empty` alone is enough. ========================= By [the current *Selectors Level 4* specification](https://drafts.csswg.org/selectors/#the-empty-pseudo), **`:empty` can match elements that only contain text nodes that only contain whitespace** as well as completely empty ones. It’s just there aren’t many that support it as per the current specification. > > The `:empty` pseudo-class represents an element that has no children **except, optionally, *document white space characters*.** > > > From [the MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/:empty): > > Note: In Selectors Level 4, the `:empty` pseudo-class was changed to act like `:-moz-only-whitespace`, but no browser currently supports this yet. > > > > > The `:-moz-only-whitespace` CSS pseudo-class matches elements that only contain text nodes that only contain whitespace. (This includes elements with empty text nodes and elements with no child nodes.) > > > Upvotes: 2
2018/03/19
385
1,415
<issue_start>username_0: I've renamed my app folder to aplicativo and changed the namespace to aplicativo. Everything works but artisan make commands. I changed namespace through composer.json ``` "psr-4": { "aplicativo\\": "aplicativo/", } ``` Plus command: ``` artisan app:name aplicativo ```<issue_comment>username_1: You won't get this to work. You can rename the namespace (as you did with the command), but you can't rename the directory because it's hardcoded as `app`. You can see the [source](https://github.com/laravel/framework/blob/5.6/src/Illuminate/Foundation/Application.php#L292) here. Upvotes: 0 <issue_comment>username_2: Then... if your using composer try this command ``` composer dump-autoload ``` Upvotes: 0 <issue_comment>username_3: The good news is that Laravel has now added support for custom App path. You can override the App path by adding the following code in `bootstrap/app.php` (or provider). ```php /*...*/ $app = new Illuminate\Foundation\Application( $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__) ); // override the app path since we move the app folder to somewhere else $app->useAppPath($app->basePath('src')); ``` Similarly, you can change other paths (database, language, storage, etc.). You can find all the available methods [here](https://github.com/laravel/framework/blob/9.x/src/Illuminate/Foundation/Application.php#L354). Upvotes: 1
2018/03/19
1,751
6,277
<issue_start>username_0: **Section 1** I have an issue in " Displaying 1 - 5 of 10 records ". I have a piece of code which works only on first page, when i click on second page then it show the same result " Displaying 1 - 5 of 10 records " Instead of " Displaying 10 of 10 records ". **Code In Controller** ``` $total=$config["total_rows"]; $per_page=$config['per_page']; $curpage=floor(($this->uri->segment(1)/$config['per_page']) + 1); $result_start = ($curpage - 1) * $per_page + 1; if ($result_start == 0) $result_start= 1; // *it happens only for the first run* $result_end = $result_start+$per_page-1; if ($result_end < $per_page) // happens when records less than per page { $result_end = $per_page; } else if ($result_end > $total) // happens when result end is greater than total records { $result_end = $total;} $data['show']="displaying $result_start to $result_end of $total"; ``` I don't know whats wrong with it, I have tried other code which I find from different websites, but they are not working properly. **Section 2** I have a filter section, where user can filter product by Size, Color and Price, How to achieve this section? **My main/ Index Controller** ``` public function index($page=1) { $config = array(); $keyword = $this->input->post('search'); if ($keyword === null){ $keyword = $this->session->userdata('search');} else{ $this->session->set_userdata('search',$keyword);} $config["base_url"] = base_url(); $config["total_rows"] = $this->crt->total_items($keyword); $config['use_page_numbers'] =true; $config['cur_tag_open'] = ''; $config['cur\_tag\_close'] = ''; $config["per_page"] =5; $config["uri_segment"] = 1; $this->pagination->initialize($config); $page = ($page - 1) * $config['per_page']; // showing x to y of z records $total=$config["total_rows"]; $per_page=$config['per_page']; $curpage=floor(($this->uri->segment(1)/$config['per_page']) + 1); $result_start = ($curpage - 1) * $per_page + 1; if ($result_start == 0) $result_start= 1; // *it happens only for the first run* $result_end = $result_start+$per_page-1; if ($result_end < $per_page) // happens when records less than per page { $result_end = $per_page; } else if ($result_end > $total) // happens when result end is greater than total records { $result_end = $total;} $data['show']="displaying $result_start to $result_end of $total"; $data['sidebar']=$this->crt->sidebar_cat(); $data['products']=$this->crt->get_product($config["per_page"], $page,$keyword); $data["links"] = $this->pagination->create_links(); $this->load->view('header'); $this->load->view('index',$data); $this->load->view('footer'); } ``` **My Model** ``` // Paginitions for Items function total_items($keyword) { //return $this->db->count_all("product"); $this->db->like('product_name',$keyword); $this->db->from('product'); return $this->db->count_all_results(); } //Fetching Products public function get_product($limit,$start,$keyword){ // $this->db->where('Is_Hidden',0); // $this->db->select('*'); // $this->db->from('product'); $this->db->order_by('product_id', 'DESC'); $this->db->limit($limit, $start); $this->db->like('product_name',$keyword); $query = $this->db->get_where('product'); if(!$query->num_rows()>0) { echo 'No product available ==================== '; } else { foreach ($query->result() as $row) { $data[] = $row; } return $data; } } ``` How I can get the Filter section? **UPDATE 1** **Section 1** issue has been fixed by replacing those two lines ``` $curpage=floor(($this->uri->segment(1)/$config['per_page']) + 1); if ($result_start == 0) $result_start= 1; // ``` **TO** ``` $curpage=$this->uri->segment(1); if ($result_start == 0 || $result_start<0) $result_start= 1; // ``` **Update 2** I somehow did the filter section but now I am stuck in the ajax issue. Issue is that When color or size checkbox is empty then it throw error of foreach loop. I only need to control the empty or null section, like if the checkbox is unchecked then it will not send / post the value to the controller... My Ajax Code is ``` function clr(){ var selected = new Array(); var size = new Array(); var url="php echo base_url('Cart/filt_color');?"; // alert(url); $("input:checkbox[name=color]:checked").each(function() { selected.push($(this).val()); //console.log(selected); }); // Sizes $("input:checkbox[name=size]:checked").each(function() { size.push($(this).val()); //console.log(selected); }); $.ajax({ url:url, method:"post", data:{'colors':selected,'sizes':size}, success:function(data) { // //console.log(data); $("#mdv").html(data); } }); } ``` I have tried many check like, `undefined`, or `==''` or `data.length <-1` etc. The `data.length` will did some check but i am not able to check the variable separately like, there are two variable I am send in `data: color,size` **How can I check the variable separately like:** `if(data.color.length < 0 )` .<issue_comment>username_1: When you initialize the pagination config try to use the the controller/method in `$config[base_url]` and get the page number from `$this->uri->segment(3)` Upvotes: 0 <issue_comment>username_2: Answered is [Here](https://stackoverflow.com/questions/49877680/ajax-call-repeat-post-data?noredirect=1#comment86840412_49877680), All the details and code are posted in the mentioned link question. Upvotes: -1 [selected_answer]
2018/03/19
316
1,126
<issue_start>username_0: I have 4 tabs with a list in order to give them the title. I want to access the titles of each tab, but I can only access the whole HTMLcollection. Using react. ``` import React from 'react'; import {Component} from 'react'; class tabs extends Component { render() { return ( * Class 1 * Class 2 * Class 3 * Class 4 {console.log(document.getElementsByTagName("li"))}; //full collection with length of 4 {console.log(document.getElementsByTagName("li").length)}; //0 {console.log(document.getElementsByTagName("li").item(0).innerHTML)}; //"Cannot read property 'innerHTML' of null" ) } } export default tabs; ```<issue_comment>username_1: When you initialize the pagination config try to use the the controller/method in `$config[base_url]` and get the page number from `$this->uri->segment(3)` Upvotes: 0 <issue_comment>username_2: Answered is [Here](https://stackoverflow.com/questions/49877680/ajax-call-repeat-post-data?noredirect=1#comment86840412_49877680), All the details and code are posted in the mentioned link question. Upvotes: -1 [selected_answer]
2018/03/19
369
1,158
<issue_start>username_0: I'm trying to install php unit version 6.5. I already have 7.0.1 install and I have attempted to install phpunit versions 6.5 with: ``` brew install [email protected] ``` Brew tells me that the older version is installed but `phpunit --version` is 7.0.1. Trying `brew switch phpunit 6.5`, I get the message: ``` Error: phpunit does not have a version "6.5" in the Cellar. Versions available: 7.0.1 ``` What steps do I need to take to switch versions to 6.5?<issue_comment>username_1: 1. If I am not mistaking, this is because the current version is [6.5.6](http://formulae.brew.sh/formula/[email protected]) and not just 6.5 2. If this fails, maybe try doing a manual install from their archived package, instructions can be found [here](https://phpunit.de/manual/current/en/installation.html) 3. If you still don't succeed, you could also try with composer to manage your project packages Upvotes: 2 [selected_answer]<issue_comment>username_2: I've installed manually: ``` $ wget https://phar.phpunit.de/phpunit-6.5.phar $ chmod +x phpunit-6.5.phar $ sudo mv phpunit-6.5.phar /usr/local/bin/phpunit $ phpunit --version ``` Upvotes: 3
2018/03/19
852
2,595
<issue_start>username_0: This code gets rid of all the duplicate variables. Is there a way to make the array search in this function case insensitive? ```js var x = ["AAA", "aaa", "bbb", "BBB"]; function unique(list) { var result = []; $.each(list, function(i, e) { if ($.inArray(e, result) == -1) result.push(e); }); return result; } // Output should be AAA, bbb console.log(unique(x)); ``` Associated [JSFiddle here](https://jsfiddle.net/anbrtogo/4/)<issue_comment>username_1: You could use a lookuptable with only lowercase entries: ``` function unique(arr){ const before = new Set, result = []; for(const str of arr){ const lower = str.toLowerCase(); if(!before.has(lower)){ before.add(lower); result.push(str); } } return result; } ``` That in a oneliner: ``` const unique = arr => (set => arr.filter(el => (lower => !set.has(lower) && set.add(lower))(el.toLowerCase()))(new Set); ``` Upvotes: 0 <issue_comment>username_2: * You don't need jQuery. * Use the function `findIndex` and convert to lowerCase every element for each comparison. ```js var x = ["AAA", "aaa", "bbb", "BBB"]; function unique(list) { var result = []; list.forEach(function(e) { if (result.findIndex(function(r) { return r.toLowerCase() === e.toLowerCase(); }) === -1) result.push(e); }); return result; } console.log(unique(x)) ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ``` Using arrow functions: ```js var x = ["AAA", "aaa", "bbb", "BBB"]; function unique(list) { var result = []; list.forEach((e) => { if (result.findIndex((r) => r.toLowerCase() === e.toLowerCase()) === -1) result.push(e); }); return result; } console.log(unique(x)) ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Just add .toLowerCase to everything ``` var x = ["AAA", "aaa", "bbb", "BBB"]; function unique(list) { var result = []; $.each(list, function(i, e) { if ($.inArray(e.toLowerCase(), result) == -1) result.push(e.toLowerCase()); }); return result; } alert(unique(x)); ``` Upvotes: -1 <issue_comment>username_4: just a little tweaking and you will be there ``` function unique(list) { var result = []; $.each(list, function(i, e) { if($.inArray(e, list)){ result.push(e)}; }); return result; } ``` that works fine no need to case change [![testing the code](https://i.stack.imgur.com/oY7rE.png)](https://i.stack.imgur.com/oY7rE.png) Upvotes: -1
2018/03/19
852
2,697
<issue_start>username_0: I am trying to call the propDetails function and pass an ID to it. Then pass the same ID to the Static controller but I keep on getting an error: "id = id" (second ID doesn't exist). I am sorry for this silly question and I can't figure out what I am doing wrong... ``` function propDetails(id) { var $detailDiv = $('#detailsDiv'), url = $(this).data('url'); $.get( '@Url.Action("PropDetails", "Static", new { id = id })', function(data) { $('#detailsDiv').html(data); }); } ``` Any guidance would be greatly appreciate.<issue_comment>username_1: You could use a lookuptable with only lowercase entries: ``` function unique(arr){ const before = new Set, result = []; for(const str of arr){ const lower = str.toLowerCase(); if(!before.has(lower)){ before.add(lower); result.push(str); } } return result; } ``` That in a oneliner: ``` const unique = arr => (set => arr.filter(el => (lower => !set.has(lower) && set.add(lower))(el.toLowerCase()))(new Set); ``` Upvotes: 0 <issue_comment>username_2: * You don't need jQuery. * Use the function `findIndex` and convert to lowerCase every element for each comparison. ```js var x = ["AAA", "aaa", "bbb", "BBB"]; function unique(list) { var result = []; list.forEach(function(e) { if (result.findIndex(function(r) { return r.toLowerCase() === e.toLowerCase(); }) === -1) result.push(e); }); return result; } console.log(unique(x)) ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ``` Using arrow functions: ```js var x = ["AAA", "aaa", "bbb", "BBB"]; function unique(list) { var result = []; list.forEach((e) => { if (result.findIndex((r) => r.toLowerCase() === e.toLowerCase()) === -1) result.push(e); }); return result; } console.log(unique(x)) ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Just add .toLowerCase to everything ``` var x = ["AAA", "aaa", "bbb", "BBB"]; function unique(list) { var result = []; $.each(list, function(i, e) { if ($.inArray(e.toLowerCase(), result) == -1) result.push(e.toLowerCase()); }); return result; } alert(unique(x)); ``` Upvotes: -1 <issue_comment>username_4: just a little tweaking and you will be there ``` function unique(list) { var result = []; $.each(list, function(i, e) { if($.inArray(e, list)){ result.push(e)}; }); return result; } ``` that works fine no need to case change [![testing the code](https://i.stack.imgur.com/oY7rE.png)](https://i.stack.imgur.com/oY7rE.png) Upvotes: -1
2018/03/19
1,165
3,633
<issue_start>username_0: So, I have a *list of strings* that are all formatted in *Month* *DayNumber*, like ``` ['March 1', 'March 9', 'April 14', 'March 12'] ``` I need to sort the list so all the dates are in the order they would be in a calendar. Any tips? Is there a built-in method that might be able to help me, or should I design a custom sort using a lambda?<issue_comment>username_1: You may want to review this question: [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) After parsing you could sort by date based on the values obtained from parsing string into datetime objects (which are sortable). Upvotes: 2 [selected_answer]<issue_comment>username_2: **Possibilities**: * Use a dictionary and use `key/value` * Use string matching (regex) * Many more ... Or **google** and use any of these: * [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) * [Convert string into Date type on Python](https://stackoverflow.com/questions/9504356/convert-string-into-date-type-on-python?noredirect=1&lq=1) * [how to convert a string date into datetime format in python?](https://stackoverflow.com/questions/19068269/how-to-convert-a-string-date-into-datetime-format-in-python?noredirect=1&lq=1) To provide **a** possible solution: ``` Input_list = [{'month':'March', 'day':30}, {'month':'March', 'day':10}] newlist = sorted(Input_list, key=lambda k: k['month']) ``` Upvotes: 0 <issue_comment>username_3: You can also leverage the calendar module: ``` from calendar import month_name months = list(month_name) def parser (text): """Parses 'englishmonthname_whitespace_day-number' into string 'monthNR.dayNr'. Will pad a zero to allow for string based sorting.""" try: month,day = text.split() monthAsIdx = months.index(month.strip()) return '{:02d}.{:02d}'.format(monthAsIdx,int(day)) # return index in list.days except (ValueError, IndexError): # ValueError if not enough elements in string, # IndexError if not in list of month names return "99.99" # put last - all errors are put last w/o specific reordering dates = ['TooFew', 'EnoughBut NotInList', 'March 1', 'March 9', 'April 14', 'March 12'] for n in dates: print(parser(n)) sortedDates = sorted(dates, key=lambda x: parser(x)) print(sortedDates) ``` Output: ``` # result of parser() 99.99 99.99 03.01 03.09 04.14 03.12 # sorted by key/lambda ['March 1', 'March 9', 'March 12', 'April 14', 'TooFew', 'EnoughBut NotInList'] ``` Upvotes: 1 <issue_comment>username_4: One way is to use `numpy.argsort` combined with `datetime` library. ``` import numpy as np from datetime import datetime lst = ['March 1', 'March 9', 'April 14', 'March 12'] arr = np.array(lst) res = arr[np.argsort([datetime.strptime(i+' 2018', '%B %d %Y') for i in lst])].tolist() ``` Result: ``` ['March 1', 'March 9', 'March 12', 'April 14'] ``` This is possible because, internally, dates are just numeric data. In this case, we attach an arbitrary year 2018 to create `datetime` objects. Upvotes: 1 <issue_comment>username_5: You can use pandas module. Install it with pip. You can do something like this: ``` import pandas as pd dates = ['March 1', 'March 9', 'April 14', 'March 12'] df = pd.DataFrame(dates) df = pd.to_datetime(df[0], format="%B %d") df=df.sort_values() print (df) ``` This datetime format can be very useful like for example if you want the day or the month of an element of the list just do: ``` df.month df.day ``` Upvotes: 1
2018/03/19
1,261
3,756
<issue_start>username_0: I would like to send a linked (not embedded) image by email. [i.e: <http://www.konbini.com/wp-content/blogs.dir/3/files/2018/03/a9a08770bba415c3b9a14cb162.jpg]> Do you know what kind of html code have to write in the email? I want to place the code within the body of the email. I tried this but it's not working: `![](https://www.konbini.com/wp-content/blogs.dir/3/files/2018/03/a9a08770bba415c3b9a14cb162.jpg)` I am using Outlook or Gmail also. Thank you ! M<issue_comment>username_1: You may want to review this question: [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) After parsing you could sort by date based on the values obtained from parsing string into datetime objects (which are sortable). Upvotes: 2 [selected_answer]<issue_comment>username_2: **Possibilities**: * Use a dictionary and use `key/value` * Use string matching (regex) * Many more ... Or **google** and use any of these: * [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) * [Convert string into Date type on Python](https://stackoverflow.com/questions/9504356/convert-string-into-date-type-on-python?noredirect=1&lq=1) * [how to convert a string date into datetime format in python?](https://stackoverflow.com/questions/19068269/how-to-convert-a-string-date-into-datetime-format-in-python?noredirect=1&lq=1) To provide **a** possible solution: ``` Input_list = [{'month':'March', 'day':30}, {'month':'March', 'day':10}] newlist = sorted(Input_list, key=lambda k: k['month']) ``` Upvotes: 0 <issue_comment>username_3: You can also leverage the calendar module: ``` from calendar import month_name months = list(month_name) def parser (text): """Parses 'englishmonthname_whitespace_day-number' into string 'monthNR.dayNr'. Will pad a zero to allow for string based sorting.""" try: month,day = text.split() monthAsIdx = months.index(month.strip()) return '{:02d}.{:02d}'.format(monthAsIdx,int(day)) # return index in list.days except (ValueError, IndexError): # ValueError if not enough elements in string, # IndexError if not in list of month names return "99.99" # put last - all errors are put last w/o specific reordering dates = ['TooFew', 'EnoughBut NotInList', 'March 1', 'March 9', 'April 14', 'March 12'] for n in dates: print(parser(n)) sortedDates = sorted(dates, key=lambda x: parser(x)) print(sortedDates) ``` Output: ``` # result of parser() 99.99 99.99 03.01 03.09 04.14 03.12 # sorted by key/lambda ['March 1', 'March 9', 'March 12', 'April 14', 'TooFew', 'EnoughBut NotInList'] ``` Upvotes: 1 <issue_comment>username_4: One way is to use `numpy.argsort` combined with `datetime` library. ``` import numpy as np from datetime import datetime lst = ['March 1', 'March 9', 'April 14', 'March 12'] arr = np.array(lst) res = arr[np.argsort([datetime.strptime(i+' 2018', '%B %d %Y') for i in lst])].tolist() ``` Result: ``` ['March 1', 'March 9', 'March 12', 'April 14'] ``` This is possible because, internally, dates are just numeric data. In this case, we attach an arbitrary year 2018 to create `datetime` objects. Upvotes: 1 <issue_comment>username_5: You can use pandas module. Install it with pip. You can do something like this: ``` import pandas as pd dates = ['March 1', 'March 9', 'April 14', 'March 12'] df = pd.DataFrame(dates) df = pd.to_datetime(df[0], format="%B %d") df=df.sort_values() print (df) ``` This datetime format can be very useful like for example if you want the day or the month of an element of the list just do: ``` df.month df.day ``` Upvotes: 1
2018/03/19
1,236
4,082
<issue_start>username_0: Is it possible to programmatically request business partner with access assets business owns. Facebook business-manager-api describes [best practices](https://developers.facebook.com/docs/marketing-api/businessmanager/bestpractice) to work with business-manager-api. Would be very handly if our app can request partnership to client or agencies business managers programmatically. > > Update > So after digging documentation, playing with Facebook Graph API and asking on official Q/A groups we came to conclusion, that at this moment Facebook API doesn't provide any endpoint to request business partnership. So we refactor our flow and now we will request access to business's ad accounts. I will accept answer as correct, cause at this moment this is the only possible solution > > ><issue_comment>username_1: You may want to review this question: [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) After parsing you could sort by date based on the values obtained from parsing string into datetime objects (which are sortable). Upvotes: 2 [selected_answer]<issue_comment>username_2: **Possibilities**: * Use a dictionary and use `key/value` * Use string matching (regex) * Many more ... Or **google** and use any of these: * [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) * [Convert string into Date type on Python](https://stackoverflow.com/questions/9504356/convert-string-into-date-type-on-python?noredirect=1&lq=1) * [how to convert a string date into datetime format in python?](https://stackoverflow.com/questions/19068269/how-to-convert-a-string-date-into-datetime-format-in-python?noredirect=1&lq=1) To provide **a** possible solution: ``` Input_list = [{'month':'March', 'day':30}, {'month':'March', 'day':10}] newlist = sorted(Input_list, key=lambda k: k['month']) ``` Upvotes: 0 <issue_comment>username_3: You can also leverage the calendar module: ``` from calendar import month_name months = list(month_name) def parser (text): """Parses 'englishmonthname_whitespace_day-number' into string 'monthNR.dayNr'. Will pad a zero to allow for string based sorting.""" try: month,day = text.split() monthAsIdx = months.index(month.strip()) return '{:02d}.{:02d}'.format(monthAsIdx,int(day)) # return index in list.days except (ValueError, IndexError): # ValueError if not enough elements in string, # IndexError if not in list of month names return "99.99" # put last - all errors are put last w/o specific reordering dates = ['TooFew', 'EnoughBut NotInList', 'March 1', 'March 9', 'April 14', 'March 12'] for n in dates: print(parser(n)) sortedDates = sorted(dates, key=lambda x: parser(x)) print(sortedDates) ``` Output: ``` # result of parser() 99.99 99.99 03.01 03.09 04.14 03.12 # sorted by key/lambda ['March 1', 'March 9', 'March 12', 'April 14', 'TooFew', 'EnoughBut NotInList'] ``` Upvotes: 1 <issue_comment>username_4: One way is to use `numpy.argsort` combined with `datetime` library. ``` import numpy as np from datetime import datetime lst = ['March 1', 'March 9', 'April 14', 'March 12'] arr = np.array(lst) res = arr[np.argsort([datetime.strptime(i+' 2018', '%B %d %Y') for i in lst])].tolist() ``` Result: ``` ['March 1', 'March 9', 'March 12', 'April 14'] ``` This is possible because, internally, dates are just numeric data. In this case, we attach an arbitrary year 2018 to create `datetime` objects. Upvotes: 1 <issue_comment>username_5: You can use pandas module. Install it with pip. You can do something like this: ``` import pandas as pd dates = ['March 1', 'March 9', 'April 14', 'March 12'] df = pd.DataFrame(dates) df = pd.to_datetime(df[0], format="%B %d") df=df.sort_values() print (df) ``` This datetime format can be very useful like for example if you want the day or the month of an element of the list just do: ``` df.month df.day ``` Upvotes: 1
2018/03/19
224
796
<issue_start>username_0: I am currently coding a website for a school project, and I have boxes that grow on a mouse hover that are in a div. An example of one grow div: ``` Experience Sample text. ``` In here, I need a `-` to list my industry certifications, but then it won't validate. So I was trying this: ``` Experience - Sample Sample ``` But then this doesn't validate. What should I do instead, or is there another good alternative to a list that looks good?<issue_comment>username_1: You are including an UL inside of a LI, you need revert. First you need add UL and inside of this tag, add the LI you need. ```html Experience * Sample 1 * Sample 2 * Sample 3 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: UL wraps LIs. ``` * .... ``` Upvotes: 0
2018/03/19
2,272
6,008
<issue_start>username_0: I have plotted a scatter graph in R, comparing expected to observed values,using the following script: ``` library(ggplot2) library(dplyr) r<-read_csv("Uni/MSci/Project/DATA/new data sheets/comparisons/for comarison graphs/R Regression/GAcAs.csv") x<-r[1] y<-r[2] ggplot()+geom_point(aes(x=x,y=y))+ scale_size_area() + xlab("Expected") + ylab("Observed") + ggtitle("G - As x Ac")+ xlim(0, 40)+ylim(0, 40) ``` My plot is as follows: [![enter image description here](https://i.stack.imgur.com/y2PCx.png)](https://i.stack.imgur.com/y2PCx.png) I then want to add an orthogonal regression line (as there could be errors in both the expected and observed values). I have calculated the beta value using the following: ``` v <- prcomp(cbind(x,y))$rotation beta <- v[2,1]/v[1,1] ``` Is there a way to add an orthogonal regression line to my plot?<issue_comment>username_1: I'm not sure I completely understand the question, but if you want line segments to show errors along both x and y axis, you can do this using `geom_segment`. Something like this: ``` library(ggplot2) df <- data.frame(x = rnorm(10), y = rnorm(10), w = rnorm(10, sd=.1)) ggplot(df, aes(x = x, y = y, xend = x, yend = y)) + geom_point() + geom_segment(aes(x = x - w, xend = x + w)) + geom_segment(aes(y = y - w, yend = y + w)) ``` Upvotes: 0 <issue_comment>username_2: Borrowed from this [blog post](https://onunicornsandgenes.blog/2013/05/31/how-to-draw-the-line-with-ggplot2/) & this [answer](https://stackoverflow.com/a/30399576/786542). Basically, you will need `Deming` function from `MethComp` or `prcomp` from `stats` packages together with a custom function `perp.segment.coord`. Below is an example taken from above mentioned blog post. ```r library(ggplot2) library(MethComp) data(airquality) airquality <- na.exclude(airquality) # Orthogonal, total least squares or Deming regression deming <- Deming(y=airquality$Wind, x=airquality$Temp)[1:2] deming #> Intercept Slope #> 24.8083259 -0.1906826 # Check with prcomp {stats} r <- prcomp( ~ airquality$Temp + airquality$Wind ) slope <- r$rotation[2,1] / r$rotation[1,1] slope #> [1] -0.1906826 intercept <- r$center[2] - slope*r$center[1] intercept #> airquality$Wind #> 24.80833 # https://stackoverflow.com/a/30399576/786542 perp.segment.coord <- function(x0, y0, ortho){ # finds endpoint for a perpendicular segment from the point (x0,y0) to the line # defined by ortho as y = a + b*x a <- ortho[1] # intercept b <- ortho[2] # slope x1 <- (x0 + b*y0 - a*b)/(1 + b^2) y1 <- a + b*x1 list(x0=x0, y0=y0, x1=x1, y1=y1) } perp.segment <- perp.segment.coord(airquality$Temp, airquality$Wind, deming) perp.segment <- as.data.frame(perp.segment) # plot plot.y <- ggplot(data = airquality, aes(x = Temp, y = Wind)) + geom_point() + geom_abline(intercept = deming[1], slope = deming[2]) + geom_segment(data = perp.segment, aes(x = x0, y = y0, xend = x1, yend = y1), colour = "blue") + theme_bw() ``` [![enter image description here](https://i.stack.imgur.com/aEzH5.png)](https://i.stack.imgur.com/aEzH5.png) Created on 2018-03-19 by the [reprex package](http://reprex.tidyverse.org) (v0.2.0). Upvotes: 3 [selected_answer]<issue_comment>username_3: The `MethComp` package seems to be no longer maintained (was removed from CRAN). [Russel88/COEF](https://github.com/Russel88/COEF) allows to use `stat_`/`geom_summary` with `method="tls"` to add an orthogonal regression line. Based on this and [wikipedia:Deming\_regression](https://en.wikipedia.org/wiki/Deming_regression) I created the following functions, which allow to use noise ratios other than 1: ```r deming.fit <- function(x, y, noise_ratio = sd(y)/sd(x)) { if(missing(noise_ratio) || is.null(noise_ratio)) noise_ratio <- eval(formals(sys.function(0))$noise_ratio) # this is just a complicated way to write `sd(y)/sd(x)` delta <- noise_ratio^2 x_name <- deparse(substitute(x)) s_yy <- var(y) s_xx <- var(x) s_xy <- cov(x, y) beta1 <- (s_yy - delta*s_xx + sqrt((s_yy - delta*s_xx)^2 + 4*delta*s_xy^2)) / (2*s_xy) beta0 <- mean(y) - beta1 * mean(x) res <- c(beta0 = beta0, beta1 = beta1) names(res) <- c("(Intercept)", x_name) class(res) <- "Deming" res } deming <- function(formula, data, R = 100, noise_ratio = NULL, ...){ ret <- boot::boot( data = model.frame(formula, data), statistic = function(data, ind) { data <- data[ind, ] args <- rlang::parse_exprs(colnames(data)) names(args) <- c("y", "x") rlang::eval_tidy(rlang::expr(deming.fit(!!!args, noise_ratio = noise_ratio)), data, env = rlang::current_env()) }, R=R ) class(ret) <- c("Deming", class(ret)) ret } predictdf.Deming <- function(model, xseq, se, level) { pred <- as.vector(tcrossprod(model$t0, cbind(1, xseq))) if(se) { preds <- tcrossprod(model$t, cbind(1, xseq)) data.frame( x = xseq, y = pred, ymin = apply(preds, 2, function(x) quantile(x, probs = (1-level)/2)), ymax = apply(preds, 2, function(x) quantile(x, probs = 1-((1-level)/2))) ) } else { return(data.frame(x = xseq, y = pred)) } } # unrelated hlper function to create a nicer plot: fix_plot_limits <- function(p) p + coord_cartesian(xlim=ggplot_build(p)$layout$panel_params[[1]]$x.range, ylim=ggplot_build(p)$layout$panel_params[[1]]$y.range) ``` Demonstration: ```r library(ggplot2) #devtools::install_github("Russel88/COEF") library(COEF) fix_plot_limits( ggplot(data.frame(x = (1:5) + rnorm(100), y = (1:5) + rnorm(100)*2), mapping = aes(x=x, y=y)) + geom_point() ) + geom_smooth(method=deming, aes(color="deming"), method.args = list(noise_ratio=2)) + geom_smooth(method=lm, aes(color="lm")) + geom_smooth(method = COEF::tls, aes(color="tls")) ``` ![](https://i.stack.imgur.com/VGDpJ.png) Created on 2019-12-04 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0) Upvotes: 2
2018/03/19
606
2,252
<issue_start>username_0: So basically, I have this JavaScript variable which stores this certain value, and I need to put this variable in MySQL Query statement. Source Code: ``` var Pollution_Reading = 25; DatabaseConnection.query('INSERT INTO Air_Pollution_Record (Air_Pollution_Reading) VALUES ('"Pollution_Reading"')'); ``` I've tried every way that I know, but I still can't insert the value that the variable is holding into the database. What should I do?<issue_comment>username_1: ``` DatabaseConnection.query('INSERT INTO Air_Pollution_Record (Air_Pollution_Reading) VALUES ('+Pollution_Reading+')'); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Try doing this: ``` //reading post data const useremail = req.body.useremail; const password = <PASSWORD>; //save into db start var sql = "INSERT INTO `users` (`UserName`, `UserPassword`) VALUES ('"+useremail+"','"+ password+"')"; ``` Upvotes: 2 <issue_comment>username_3: you can try this format of **template literals**. Gives you **Easy** and **Clean** code. ``` const sql = `INSERT INTO query_form (name, email, query_title, query_description) VALUES ('${name}', '${email}', '${query_title}', '${query_description}')`; ``` Upvotes: 2 <issue_comment>username_4: const sql = "INSERT INTO `users` (`UserName`, `UserPassword`) VALUES ('"+useremail+"','"+ password+"')"; This method and also above are good but naive if you have quotes in your input variable like single or double quotes. It will match the single quote with the input string and you will get error as it will not consider the remaining input. So, after a long painful research I found a fix for quotes input strings as well. The solution is to not use values front hand and pass them inside con.query() method directly. ``` let query = `INSERT INTO gfg_table (name, address) VALUES (?, ?);`; // Value to be inserted let userName = "Pratik"; let userAddress = "My Address"; // Creating queries db_con.query(query, [userName, userAddress], (err, rows) => { if (err) throw err; console.log("Row inserted with id = " + rows.insertId); }); ``` Reference: <https://www.geeksforgeeks.org/node-js-mysql-insert-into-table/> Upvotes: 1
2018/03/19
1,104
4,578
<issue_start>username_0: I have alot of button in my application. They are placed next to each other. All of the methods are IMvxAsyncCommand type. I figured out some missmatches after tests done by users. I have found duplicate operations - two diffrent buttons are called in almost same time. What did I do is created my own SafeAsyncCommand class and inheret from MvxAsyncCommand. My goal is to create delay between executes - I want to prevent double click in given delay in below case 0.5s. There is my work: ``` public static class SafeCommandSettings { public static bool CanExecute { get; private set; } public static TimeSpan Delay => TimeSpan.FromMilliseconds(500); static SafeCommandSettings() { CanExecute = true; } public static async void Pause() { if (!CanExecute) return; CanExecute = false; await Task.Delay(Delay); CanExecute = true; } } public class SafeAsyncCommand : MvxAsyncCommand { public SafeAsyncCommand(Func execute, Func canExecute = null, bool allowConcurrentExecutions = false) : base(execute, canExecute, allowConcurrentExecutions) { } public SafeAsyncCommand(Func execute, Func canExecute = null, bool allowConcurrentExecutions = false) : base(execute, canExecute, allowConcurrentExecutions) { } protected override async Task ExecuteAsyncImpl(object parameter) { if (!SafeCommandSettings.CanExecute) return; SafeCommandSettings.Pause(); await base.ExecuteAsyncImpl(parameter); } } public class SafeAsyncCommand : MvxAsyncCommand { public SafeAsyncCommand(Func execute, Func canExecute = null, bool allowConcurrentExecutions = false) : base(execute, canExecute, allowConcurrentExecutions) { } public SafeAsyncCommand(Func execute, Func canExecute = null, bool allowConcurrentExecutions = false) : base(execute, canExecute, allowConcurrentExecutions) { } protected override async Task ExecuteAsyncImpl(object parameter) { if (!SafeCommandSettings.CanExecute) return; SafeCommandSettings.Pause(); await base.ExecuteAsyncImpl(parameter); } } ``` I thought this is working but I saw users were able to do it again. Do I miss some knowledge about async methods or static thread safe? Thanks in advance<issue_comment>username_1: Instead of delaying things, consider using `AsyncLock` by <NAME> or lookup `Interlocked.CompareExchange`. As far as I can tell from here, you shouldn't use a static `CanExecute` in your case, as it locks all commands using your "safe" command at once. And there is the possibility of race conditions, since you aren't changing the value of `CanExecute` locked. Upvotes: 3 [selected_answer]<issue_comment>username_2: In order to do so you can take advantage of [MvxNotifyTask](https://www.mvvmcross.com/documentation/fundamentals/mvxnotifytask) that is a wrapper of the `Task` that watches for different task states and you'll run on your command and do something like this (notice that you don't need the command to be `MvxAsyncCommand`): ``` public MvxNotifyTask MyNotifyTaskWrapper { get; private set; } public MvxCommand MyCommand { get; private set; } private void InitializeCommands() { // this command is executed only if the task has not started (its wrapper is null) or the task is not in progress (its wrapper is not IsNotCompleted) this.MyCommand = new MvxCommand(() => this.MyNotifyTaskWrapper = MvxNotifyTask.Create(() => this.MyLogicAsync()), () => this.MyNotifyTaskWrapper == null || !this.MyNotifyTaskWrapper.IsNotCompleted); } private async Task MyLogicAsync() { // my async logic } ``` So as soon the async process is started the command can't be executed again preventing duplicate operations, and you can start it again when that task completes. If you have to disable multiple commands execution when running some task just add the same `CanExecute` condition on the different commands or mix conditions of different `MvxNotifyTask` Also check that the `MvxNotifyTask` raises property-changed notifications that you can subscribe to or bind to in your view displaying a "loading" or something like that when performing the operation. *Note: if you are using Mvx < 5.5 you won't have `MvxNotifyTask` but you can use [NotifyTaskCompletion](https://github.com/StephenCleary/AsyncEx/wiki/NotifyTaskCompletion) done by <NAME> that is almost the same as `MvxNotifyTask` and it is from where `MvxNotifyTask` was based on.* HIH Upvotes: 2
2018/03/19
522
1,618
<issue_start>username_0: I am using Keycloak with my Spring Boot application. I want to use Okta as Identity Provider without success, this configuration: Spring configuration: ``` security.oauth2.resource.userInfoUri=https://dev-XXXXXX.oktapreview.com/oauth2/default/v1/userinfo security.oauth2.resource.tokenInfoUri=https://dev-XXXXXX.oktapreview.com/oauth2/default/v1/introspect security.oauth2.resource.preferTokenInfo=false security.oauth2.client.accessTokenUri=https://dev-XXXXXX.oktapreview.com/oauth2/default/v1/token security.oauth2.client.userAuthorizationUri=https://dev-XXXXXX.oktapreview.com/oauth2/default/v1/authorize security.oauth2.client.clientId=CLIENT_ID security.oauth2.client.scope=openid profile email ``` Okta Identity Provider configuration: [![enter image description here](https://i.stack.imgur.com/4vk9B.png)](https://i.stack.imgur.com/4vk9B.png) But this configuration is always leading me to HTTP 400: [![enter image description here](https://i.stack.imgur.com/NNk3o.png)](https://i.stack.imgur.com/NNk3o.png) What I am missing?<issue_comment>username_1: I cannot answer it with surety, but have you added redirect-url to the trusted origins of Okta dashboard? <https://developer.okta.com/code/javascript/okta_sign-in_widget?_ga=2.16453941.2053718723.1521541302-1766190875.1521541302> Upvotes: 0 <issue_comment>username_2: You should configure your Spring Boot to work with Keycloak and then Keycloak to work with Okta. The following article describes how to configure Keycloak with Okta SAML Provider <https://ultimatesecurity.pro/post/okta-saml/> Upvotes: 3 [selected_answer]
2018/03/19
674
2,484
<issue_start>username_0: I am using an Excel Macro that detects two worksheets and writes them to CSV format in their current SharePoint directory. However, upon executing the macro, it proceeds to open the newly created files within the same workbook and gives me the following error: > > Run-time error '1004': > > > Sorry, we couldn't find C:\ProgramFiles(x86)\Google\Chrome\Application... > > > Is it possible it was moved, renamed or deleted? > > > Can I perform the "Save As" without opening the new file and avoiding the given error? To be clear, it performs the core function just fine, as the new CSV files are properly written to the Sharepoint folder, I simply want to avoid the error message. Macro code is as below: ``` Sub Export() ' ' Export Macro ' Export Rules and Privileges to 'Rules.csv' and Privileges.csv' ' ' Keyboard Shortcut: Ctrl+Shift+E ' Dim ws As Worksheet Dim path As String path = ActiveWorkbook.path & "\" For Each ws In Worksheets If ws.Name Like "Rules" Then ws.Activate ws.SaveAs Filename:=path & "Rules.csv", FileFormat:=xlCSV, CreateBackup:=True End If If ws.Name Like "Privileges" Then ws.Activate ws.SaveAs Filename:=path & "Privileges.csv", FileFormat:=xlCSV, CreateBackup:=True End If Next Range("B9").Select Application.Run "RulesWorkbook.xlsm!Export" Range("B4").Select End Sub ```<issue_comment>username_1: Thank you to FreeMan for the solution in getting rid of the error message. While I did not figure out how to prevent Excel from opening the newly generated programs, I was able to side-step that by closing the workbook upon macro execution. Updated code for the macro is below: ``` Sub Export() ' ' Export Macro ' Export SecurityRules and Privileges to 'Rules.csv' and 'Privileges.csv' ' ' Keyboard Shortcut: Ctrl+Shift+E ' Dim ws As Worksheet Dim path As String path = ActiveWorkbook.path & "\" For Each ws In Worksheets If ws.Name Like "Rules" Then ws.SaveAs Filename:=path & "Rules.csv", FileFormat:=xlCSV, CreateBackup:=True End If If ws.Name Like "Privileges" Then ws.SaveAs Filename:=path & "Privileges.csv", FileFormat:=xlCSV, CreateBackup:=True End If Next Application.DisplayAlerts = False ActiveWorkbook.Close Application.DisplayAlerts = True End Sub ``` Upvotes: 2 <issue_comment>username_2: Adding the following just before the Save As line helped for me, not sure why ActiveWorkbook.Sheets("Sheet1").Copy Upvotes: 0
2018/03/19
488
1,588
<issue_start>username_0: I try at the moment to re-color a clicked link from purple back to black. It **works** if I add following code directly into the html file: ``` window.onload = function() { document.getElementById("url").style.color = "#000000"; }; </code></pre> <p></p> <p>But I dont want to have that function in the HTML instead I put it into my .JS file. But it <strong>doesn't work.</strong></p> <pre><code> function changeColor() { document.getElementById("url").style.color = "#000000"; } </code></pre> <p>and then call it like this in the body:</p> <pre><code><script> changeColor(); //doesn't work $(document).ready( function () { changeColor(); //also doesn't work }); ``` Any idea what is wrong?<issue_comment>username_1: The js file must not have `...` but pure code ``` changeColor(); //doesn't work $(document).ready( function () { changeColor(); //also doesn't work }); ``` and be sure you have a proper path in your html for include you js files . eg : ``` ``` Upvotes: 1 <issue_comment>username_2: You can do this with jQuery: ``` $(document).ready(function() { $("#url").css("color: #000000"); }); ``` make sure you included the file correctly. Upvotes: 0 <issue_comment>username_3: Be sure that you are using the correct path of javascript file and if you want to use jQuery do not forget that you need the library. Try this one : ```js window.init = changeColor(); function changeColor() { document.getElementById("url").style.color = "#000000"; } ``` ```html [Hello](#) ``` Upvotes: 2 [selected_answer]
2018/03/19
351
1,078
<issue_start>username_0: I have a properly working CTE query. I'm using this query in an application which does select on top of it and giving error > > Incorrect syntax near WITH > > > Is there any way I can do select on top of WITH? ``` select(columns) from (WITH CTE AS( #code )) ```<issue_comment>username_1: Unfortunately SQL Server does not support this kind of syntax **[DBFiddle Demo](http://dbfiddle.uk/?rdbms=postgres_10&fiddle=d908c140a3bd9e3d3f4f4c63a84d806f)**. You need to rewrite your query: ``` WITH CTE AS( #code ) SELECT * FROM CTE; ``` Or wrap you query with view and select from it instead. Upvotes: 3 [selected_answer]<issue_comment>username_2: You declare the CTE first, then you select from it in the following statement ``` ;WITH cte AS ( select 1 AS col ) SELECT col FROM cte ``` Upvotes: 2 <issue_comment>username_3: Remove the with Clause and do ``` select col1, col2, col3 from (select col1, col2, col3 from table ) as CTE ``` only drawback is that the derived table can be used only once not like a true CTE Upvotes: 0
2018/03/19
832
3,456
<issue_start>username_0: I have to build a calculator and i am making some validations, the code is kinda long so i will only put the part that is breaking it. It is a validation that makes the multiplication, it breaks when trying to multiply a negative number, every other operation is done correctly but the multiplication: ``` else if(resulttxt.getText().toString().contains("*")){ String resultarray=resulttxt.getText().toString(); String[] split=resultarray.split("\\*"); finalresult = Double.valueOf(split[0]) * Double.valueOf(split[1]); if (finalresult<0){ negative=true; }else{ negative=false; } resulttxt.setText(String.valueOf(finalresult)); ``` resulttxt is received from a TextView that gets it's data from cliking on the numbers or the signs which are also TextViews (not buttons but they do have the On click listener)the operation is done when ciclking on the = sign. This throws an error if for example i try to do -6\*45: ``` java.lang.NumberFormatException: Invalid double: "6*45" ``` Like i said everything works with the addition,substraction and division it is only the multiplication that breaks.<issue_comment>username_1: I tried executing your code in the compiler : ``` String resulttxt = "-6*45"; boolean negative = false; if(resulttxt.contains("*")){ String resultarray=resulttxt; String[] split=resultarray.split("\\*"); double finalresult = Double.valueOf(split[0]) * Double.valueOf(split[1]); if (finalresult<0){ negative=true; }else{ negative=false; } System.out.println(finalresult); } ``` Every thing worked fine for, please verify datatype used in your program. addition, multiplication and division works fine. "-6+45, -6\*45 and -6/45"(any other combination. I just used the same) However for subtraction as the pattern is "-6-45" the above logic will fail and throw number format exception. This is because if you split "\-", the "-" is first character in string and there is nothing before it. Thus your split will fail. So to avoid this you can always take last index of character to split using substring function. Upvotes: 2 <issue_comment>username_2: Try this instead : ``` String s1 = resultarray.substring(0,resultarray.indexOf("*")); String s2 = resultarray.substring(resultarray.indexOf("*")+1,resultarray.length()); double d1= Double.valueOf(s1); double d2= Double.valueOf(s2); ``` Hope this helps Upvotes: 0 <issue_comment>username_3: OMG dudes... this is what was the problem: I had this validation at the end of the other operations, so BEFORE even going to the multiplication part it entered the "-" validation when it checks ``` if(resulttxt.contains("-")){ ``` because it is a negative value so it does have a "-"... so it entered as a substraction instead as a multiplication because of that... To solve it i had to put the substraction validation at the bottom of all of them. So thank you for the guys who suggested me to check the line where the error was thrown i wouldn't have known logcat actually tells you were the mistake is and to my surprise it was on the substraction validation which to me was a "WTF" moment and then i realized what i just told you. Upvotes: 2 [selected_answer]
2018/03/19
1,707
5,862
<issue_start>username_0: I need to **get** the **4-5-4 Calendar Week from a Date**. Is there any utility like Georgian Calendar in Java for 4-5-4 Retail Calendar? If not, how can I create one? What all logic is needed? What is 53rd Week in case of Leap Year? For example, if I pass a date (DD-MM-YYY) `04-03-2018` as input I should get `March Week 1` as output. Or, if I give `01-04-2018` as input I should get `March Week 5` as output. Please help me by providing a way to build this utility.<issue_comment>username_1: No support built-in =================== Neither the modern *java.time* classes nor the legacy date-time classes (`Date`/`Calendar`) directly support the [National Retail Federation 4-5-4 Calendar](https://nrf.com/resources/4-5-4-calendar). Implement `Chronology` ====================== I suspect the best way to solve this problem is to implement a [`Chronology`](https://docs.oracle.com/javase/9/docs/api/java/time/chrono/Chronology.html) for the *java.time* framework. Java 8 and later bundle five implementations (`HijrahChronology`, [`IsoChronology`](https://docs.oracle.com/javase/9/docs/api/java/time/chrono/IsoChronology.html), `JapaneseChronology`, `MinguoChronology`, `ThaiBuddhistChronology`). Their source is available in the *OpenJDK* project. The [*ThreeTen-Extra*](http://www.threeten.org/threeten-extra/) project provides [ten more chronologies](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/chrono/package-summary.html) (`AccountingChronology`, `BritishCutoverChronology`, `CopticChronology`, `DiscordianChronology`, `EthiopicChronology`, `InternationalFixedChronology`, `JulianChronology`, `PaxChronology`, `Symmetry010Chronology`, `Symmetry454Chronology`) whose source code might help. Upvotes: 2 <issue_comment>username_2: The following class should do it: ``` public class NrfMonthWeek { public static NrfMonthWeek getWeek(LocalDate date) { // Determine NRF calendar year. // The year begins on the Sunday in the interval Jan 29 through Feb 4. LocalDate firstDayOfNrfYear = date.with(MonthDay.of(Month.JANUARY, 29)) .with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)); if (date.isBefore(firstDayOfNrfYear)) { // previous NRF year firstDayOfNrfYear = date.minusYears(1) .with(MonthDay.of(Month.JANUARY, 29)) .with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)); } // 1-based week of NRF year int weekOfNrfYear = (int) ChronoUnit.WEEKS.between(firstDayOfNrfYear, date) + 1; assert 1 <= weekOfNrfYear && weekOfNrfYear <= 53 : weekOfNrfYear; YearMonth firstMonthOfNrfYear = YearMonth.from(firstDayOfNrfYear) .with(Month.FEBRUARY); if (weekOfNrfYear == 53) { // Special case: the last week of a 53 weeks year belongs to // the last month, January; this makes it a 5 weeks month. return new NrfMonthWeek(firstMonthOfNrfYear.plusMonths(11), 5); } else { // 1-based month of NRF year (1 = February through 12 = January). // A little math trickery to make the 4-5-4 pattern real. int monthOfNrfYear = (weekOfNrfYear * 3 + 11) / 13; // Number of weeks before the NRF month: 0 for February, 4 for March, 9 for April, etc. int weeksBeforeMonth = (monthOfNrfYear * 13 - 12) / 3; int weekOfMonth = weekOfNrfYear - weeksBeforeMonth; return new NrfMonthWeek( firstMonthOfNrfYear.plusMonths(monthOfNrfYear - 1), weekOfMonth); } } private YearMonth month; /** 1 through 5 */ private int weekOfMonth; public NrfMonthWeek(YearMonth month, int weekOfMonth) { this.month = Objects.requireNonNull(month); if (weekOfMonth < 1 || weekOfMonth > 5) { throw new IllegalArgumentException("Incorrect week number " + weekOfMonth); } this.weekOfMonth = weekOfMonth; } @Override public String toString() { return month.getMonth().getDisplayName(TextStyle.FULL, Locale.US) + " Week " + weekOfMonth; } } ``` Let’s try it. Here I pass the two dates from your question to the `getWeek` method: ``` System.out.println(NrfMonthWeek.getWeek(LocalDate.of(2018, Month.MARCH, 4))); System.out.println(NrfMonthWeek.getWeek(LocalDate.of(2018, Month.APRIL, 1))); ``` This prints the desired: ``` March Week 1 March Week 5 ``` Though only month and week are printed, also the year is contained in the object returned from `getWeek`. The formulas for calculating the month and week-of-month are cryptic. I have no really good argument why they work, though such an argument could probably be constructed. I have tested them with all relevant values, and you are free to do the same. Other than that, using java.time, the modern Java date and time API, it wasn’t too bad. If that were me, I would have finer validation in the `NrfMonthWeek` constructor, only allowing week 5 in the months that may have 5 weeks. I am leaving that to you. And I would have a pretty thorough unit test. Please check whether my understanding agrees with yours: If I have understood correctly from the [example calendars](https://nrf.com/resources/4-5-4-calendar) that username_1 linked to [in his answer](https://stackoverflow.com/a/49371198/5772882), the NRF 4-5-4 year starts with February. Its weeks begin on Sunday, and the first week of the year is the first week that contains at least 4 days of February. In other words, the week that contains February 4. In yet other words, the week that begins on a Sunday in the interval January 29 through February 4. Months March, June, September and December always have 5 weeks. In case of a 53 weeks year also January has 5 weeks. Upvotes: 3 [selected_answer]
2018/03/19
866
3,381
<issue_start>username_0: I need to display a map of circles and polygons, and each circle or polygon may be different colors. My initial plan was to subclass MKCircle and MKPolygon and add an instance variable for my Region class (which has information that will determine the color of the shape on the map) but that is not possible to subclass either of those Any ideas? Here is what I have so far: ``` // draw the regions func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { if overlay is MKCircle { // display circles on the map let circle = MKCircleRenderer(overlay: overlay) circle.strokeColor = UIColor.red // THIS SHOULD BE CONDITIONAL (sometimes red, sometimes green -> depends on a class that I have called region) circle.fillColor = UIColor(red: 255, green: 0, blue: 0, alpha: 0.1) circle.lineWidth = 1 return circle } else if overlay is MKPolygon { // display polygons on the map let poly = MKPolygonRenderer(overlay: overlay) poly.strokeColor = UIColor.red // THIS SHOULD BE CONDITIONAL (sometimes red, sometimes green -> depends on a class that I have called region) poly.fillColor = UIColor(red: 255, green: 0, blue: 0, alpha: 0.1) poly.lineWidth = 1 return poly } else { return MKPolylineRenderer() } } ```<issue_comment>username_1: You say you can't subclass MKCircle or MKPolygon, so you have no way to pass extra info associated with this overlay into the delegate method in the `overlay` parameter. But what you *can* do is write your own NSObject subclass that conforms to the MKOverlay protocol. Now you can add any instance property you like. For simplicity, your MKOverlay adopter can itself wrap an MKCircle or MKPolygon but there is no actual need for this. Upvotes: 0 <issue_comment>username_2: I know its an old thread, but I thought I'll share how I did this I used stored properties of extensions to create a variable which could differentiate between if the MKCircle was for a member or a place as I required it Here is the sample code: ``` extension MKCircle { enum type { case place case member } private static var savedCircleType: type = .member var circleType : type { get{ return MKCircle.savedCircleType } set(newValue) { MKCircle.savedCircleType = newValue } } } ``` When adding annotation, do this ``` let circle = MKCircle(center: currentLocationPin.coordinate, radius: 200) circle.circleType = .member // or .place in my case self.mapView.addOverlay(circle) self.mapView.addAnnotation(currentLocationPin) ``` And finally in the MKMapView delegate ``` func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { if overlay is MKCircle { let circleRenderer = MKCircleRenderer(overlay: overlay) let color: UIColor = (circleRenderer.circle.circleType == .place) ? .themeGreen : .red circleRenderer.strokeColor = color circleRenderer.fillColor = color.withAlphaComponent(0.3) circleRenderer.lineWidth = 2.0 return circleRenderer } else { return MKPolylineRenderer() } } ``` Result : <https://i.stack.imgur.com/ApH9I.jpg> Upvotes: 1
2018/03/19
580
1,741
<issue_start>username_0: I want to create a new column for the text data (every row for that column is one description) after removing all numbers (such as 189, 98001), special characters ( ‘ , \_, “, (, ) ), and letters with numbers or special characters (e21x16, e267, e4, e88889, entry778, id2, n27th, pv3, ). So I wrote the function below. However, the returned results still contain numbers, and special characters. Basically, my goal is to keep only English words, and abbreviations. Does anyone know why my function is not working. ``` def standardize_text(df, text_field): df[text_field] = df[text_field].str.lower() df[text_field] = df[text_field].str.replace(r'(', '') df[text_field] = df[text_field].str.replace(r')', '') df[text_field] = df[text_field].str.replace(r',', '') df[text_field] = df[text_field].str.replace(r'_', '') df[text_field] = df[text_field].str.replace(r"'", "") df[text_field] = df[text_field].str.replace(r"^[a-z]+\[0-9]+$", "") df[text_field] = df[text_field].str.replace(r"^[0-9]{1,2,3,4,5}$", "") return df ```<issue_comment>username_1: You either have to set the `inplace` parameter of the `replace` function to true or assign the returned df to the `df` variable Upvotes: -1 <issue_comment>username_2: Use a library named 'textcleaner'. See [repository](https://github.com/YugantM/textcleaner) and [link](https://pypi.org/project/textcleaner/). This [article](https://medium.com/@yuganthadiyal/textcleaner-a-data-pre-processing-library-1a234eec02dd) might help you. ``` !pip install textcleaner import textcleaner as tc ``` or ``` from textcleaner import * ``` now just call `main_cleaner()` it will return you list of words with all the basic pre-processing. Upvotes: 1
2018/03/19
468
1,826
<issue_start>username_0: I have seen the documentation & pricing calculator but, not getting clear Idea if bucket is charged externally for data transfers / (Bandwidth consumed) or not. Its showing ``` Storage cost $0.026 per GB-month Retrieval cost Free Class A operations (Create/ delete ) $0.005 per 1,000 ops Class B operations (Downloads) $0.0004 per 1,000 ops ``` Does this retrieval cost means no extra charges will be levied for any amount of data transfer/ bandwidth used for files stored .<issue_comment>username_1: You are charged for bandwidth. [Retrieval cost](https://cloud.google.com/storage/pricing#archival-pricing) is a separate charge associated with Nearline and Coldline storage. "A retrieval cost applies when you read data or metadata that is stored as Nearline Storage or Coldline Storage. This cost is in addition to any network charges associated with reading the data." Upvotes: 1 <issue_comment>username_2: The "retrieval cost" is a special charge that is specific to nearline and coldline objects. Because these tiers are designed around data being seldomly read, there is a fee to read objects stored under these tiers in addition to any other costs. Bandwidth consumption, when reading from GCS, is a network usage fee. It's a bit complicated, but basically you're paying for GCS to send the data somewhere. This may be free if you're sending the data to a nearby GCP service, or otherwise the cost will be based on where the data is being stored and where the data is being read from. For example, if the data is being stored in Iowa, it will be more expensive to read it from China than it will be to read it from Oregon. For more details, see <https://cloud.google.com/storage/pricing> or [contact the sales team](https://cloud.google.com/contact/). Upvotes: 3 [selected_answer]
2018/03/19
458
1,790
<issue_start>username_0: I'm converting my open source app as a package and it always throws error ``` PHP Fatal error: Class 'Laracommerce\Tests\TestCase' not found in .... on line 18 ``` [![enter image description here](https://i.stack.imgur.com/q4owD.png)](https://i.stack.imgur.com/q4owD.png) Based on other comments on every search I made, I just need to define it in my package composer.json's `autoload-dev` the location of my tests but still getting the error.<issue_comment>username_1: You are charged for bandwidth. [Retrieval cost](https://cloud.google.com/storage/pricing#archival-pricing) is a separate charge associated with Nearline and Coldline storage. "A retrieval cost applies when you read data or metadata that is stored as Nearline Storage or Coldline Storage. This cost is in addition to any network charges associated with reading the data." Upvotes: 1 <issue_comment>username_2: The "retrieval cost" is a special charge that is specific to nearline and coldline objects. Because these tiers are designed around data being seldomly read, there is a fee to read objects stored under these tiers in addition to any other costs. Bandwidth consumption, when reading from GCS, is a network usage fee. It's a bit complicated, but basically you're paying for GCS to send the data somewhere. This may be free if you're sending the data to a nearby GCP service, or otherwise the cost will be based on where the data is being stored and where the data is being read from. For example, if the data is being stored in Iowa, it will be more expensive to read it from China than it will be to read it from Oregon. For more details, see <https://cloud.google.com/storage/pricing> or [contact the sales team](https://cloud.google.com/contact/). Upvotes: 3 [selected_answer]
2018/03/19
486
2,017
<issue_start>username_0: My initial FormGroup contains some FormControls and a FormArray, which should populate FormGroups dynamically ``` myForm: formBuilder.group({ .... noOfSomething: ['', Validators.required], something: this.formBuilder.array([]) }), ``` I can create a FormGroup inside the Form array by a addButton and remove it by a remove button. but my requirement is when the value of "noOfSomething"(which is a number) changes ,than according to the value of "noOfSomething" that many form group should be added to the FormArray. and the I can fill of the FormGroups inside of that FormArray. I am not sure how to initialize it and loop through it in the template.<issue_comment>username_1: You are charged for bandwidth. [Retrieval cost](https://cloud.google.com/storage/pricing#archival-pricing) is a separate charge associated with Nearline and Coldline storage. "A retrieval cost applies when you read data or metadata that is stored as Nearline Storage or Coldline Storage. This cost is in addition to any network charges associated with reading the data." Upvotes: 1 <issue_comment>username_2: The "retrieval cost" is a special charge that is specific to nearline and coldline objects. Because these tiers are designed around data being seldomly read, there is a fee to read objects stored under these tiers in addition to any other costs. Bandwidth consumption, when reading from GCS, is a network usage fee. It's a bit complicated, but basically you're paying for GCS to send the data somewhere. This may be free if you're sending the data to a nearby GCP service, or otherwise the cost will be based on where the data is being stored and where the data is being read from. For example, if the data is being stored in Iowa, it will be more expensive to read it from China than it will be to read it from Oregon. For more details, see <https://cloud.google.com/storage/pricing> or [contact the sales team](https://cloud.google.com/contact/). Upvotes: 3 [selected_answer]
2018/03/19
1,039
4,366
<issue_start>username_0: I am looking for solution to get data in background mode even app is terminated. There are lots of tutorials and answers available for this questions, but my questions is different than other. I haven't find any proper solution on stackoverflow, so posted this question. I have scenario which I can explain. I'm using realm database which store event date, name, time, address etc. Now the thing is that, I want to write a code which are execute in background, In this code I want to get all event data and compare their date with today's date. And based on days remaining between these days fire local notification to remind user about how many days are remaining for specific event. > > I want to call this background fetch method exactly 8 AM in local time everyday. > > > I haven't write any code due to confused with Background fetch and implementation. Can anyone know how to implement this ? Help will be appreciated.<issue_comment>username_1: Apple documentation states that there is no guarantee when background fetch is performed. It's up to the system to decide. > > The system waits until network and power conditions are good, so you should be able to retrieve adequate amounts of data quickly. > > > The guaranteed way to wake your app is to send at 8 am VoIP push notification from the server. It is guaranteed that the app will be wakened upon receiving a push, and you'll be able to execute the jobs you need. For more details, <https://medium.com/ios-expert-series-or-interview-series/voip-push-notifications-using-ios-pushkit-5bc4a8f4d587> Upvotes: 2 <issue_comment>username_2: It is not possible to wake up the app from suspended mode in iOS except with push notification (for this server has to send push notification). Upvotes: 1 <issue_comment>username_3: I have got solution to fix issue. As per I have talked, > > I want to write a code which are execute in background, In this code I > want to get all event data and compare their date with today's date. > And based on days remaining between these days fire local notification > to remind user about how many days are remaining for specific event. > > > So, when I getting response from API, I'm creating local notification for all events with unique id, which are fire and repeat daily at specific time, where I have display event time and remaining days of event. Upvotes: 2 <issue_comment>username_4: This is something which is not documented anywhere. IMHO and experience with iOS, Apple must be recording user activities since the start of the iOS era. ScreenTime is a product of those recordings only that apple was able to create and visualize the data to present a user facing app that very beautifully restricts, manages and displays your activities. In WWDC 2018, it was even quoted that apple will even detect, if the user opens your app at let's say 9 PM daily before going to bed, iOS will allow every possible resource (battery, internet, processing time etc) to that app at 9 PM. But you need to understand your user activities before you do this. Let's take an example of: **News App:** A majority of users would check the news in the morning (If they are not instagram addicts). At this time even apple should be biased to open your app with background fetch. Unless of-course there is too much of a resource crunch **A Game:** Many games allow provide a restriction time by calling it "recharge" or "re-fill" the energy of a character before user can play another round. This is done so that the addicted person would buy gems to remove that restriction and hence monetize the idea. But if you know that the refill process is completed before 8:00 AM in the morning or user plays your game daily at 8:00 AM configure background fetch accordingly. Background fetch works with interval rather than specific time. ``` // Fetch data once an hour. UIApplication.shared.setMinimumBackgroundFetchInterval(3600) ``` Lastly why don't you try [silent push notifications](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/pushing_background_updates_to_your_app)? Based on your question, I think silent notification is enough to wake your app after a push notification from the server, download some data and do your calculation and provide a local notification. Upvotes: 0
2018/03/19
1,044
4,230
<issue_start>username_0: ``` MessageSenderId = mAuth.getCurrentUser().getUid(); MessageRecieverId = getIntent().getStringExtra("visit_user_id"); private void sendMessage() { String messageText = messageArea.getText().toString(); if (TextUtils.isEmpty(messageText)) { Toast.makeText(getApplicationContext(), "Can't Send Blank Message", Toast.LENGTH_SHORT).show(); } else { String message_sender_ref = "Messages/" + MessageSenderId + "/" + MessageRecieverId; String message_reciver_ref = "Messages/" + MessageRecieverId + "/" + MessageSenderId; Map messageTextBody = new HashMap<>(); messageTextBody.put("message", messageText); messageTextBody.put("seen", false); messageTextBody.put("type", "text"); messageTextBody.put("time", ServerValue.TIMESTAMP); messageTextBody.put("from", MessageSenderId); DatabaseReference user_message_key = rootRef.child("Messages").child(MessageSenderId).child(MessageRecieverId).push(); String message_push_id = user_message_key.getKey(); Map messageBodyDetails = new HashMap(); messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody); messageBodyDetails.put(message_reciver_ref + "/" + message_push_id, messageTextBody); rootRef.updateChildren(messageBodyDetails, new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { if (databaseError != null) { Log.d("Chat_Log", databaseError.getMessage().toString()); } messageArea.setText(""); } }); } } private void fetchMessages() { rootRef.child("Messages").child(MessageSenderId).child(MessageRecieverId).addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { ListView listView = (ListView) findViewById(R.id.messageList); ArrayAdapter adapter; adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple\_list\_item\_1, android.R.id.text1, messagesList); String message = dataSnapshot.getValue().toString(); message = dataSnapshot.child("message").getValue().toString(); messagesList.add(message); adapter.notifyDataSetChanged(); listView.setAdapter(adapter); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); } ``` I'm trying to make a chat application since months but i'm stuck at a certain point from weeks... The problem is i'm able to fetch the messages i send and display on my listview. But i'm not able to fetch the messages sent by the other user... Everything is getting stored in database but i'm not able to fetch it... Many people suggested me to add a breakpoint and check. I don't know what that means... Can anyone help me out checking that. like where do i put what code for checking the exact problem in the logcat Please help me out<issue_comment>username_1: You should click whit left mouse button as shown here: [![enter image description here](https://i.stack.imgur.com/NhFOO.png)](https://i.stack.imgur.com/NhFOO.png) Then Run the application in Debug Mode by click on debug button [![enter image description here](https://i.stack.imgur.com/cjbKf.png)](https://i.stack.imgur.com/cjbKf.png) [Here](https://www.youtube.com/watch?v=Vo5PXWnKtQ4) you can find a video how to do it. Upvotes: 1 <issue_comment>username_2: Using `breakpoints` is a common practice when it comes to debugging. You can simply click on the line that you think that it creates to problem, as username_1 explained. Using a log statement, it means that you can print a meesage directly to the logcat. This is an example: ``` Log.d("TAG", "My message!"); ``` You can achieve the same thing using: ``` System.out.println("My message!"); ``` Upvotes: 1 [selected_answer]
2018/03/19
424
1,612
<issue_start>username_0: I have two tables: Products ``` Id Integer Name Character Varying(200) ``` Orders ``` Id Integer Product_Id integer Started Timestamp ``` I need to fetch all orders with the product id and name together. I've tried using inner join like this: ``` select orders.id, orders.started, products.id, products.name from orders inner join products on products.id = order.product_id ``` But it don't show some orders that have no product linked (service orders). What i'm doing wrong?<issue_comment>username_1: You would need to do a LEFT JOIN on your Product table from the Orders table. ``` SELECT [Your Columns] FROM Orders o LEFT OUTER JOIN Products p ON o.ProductID = p.ID ``` A left join will still retrieve all rows from Orders, and will retrieve the data from the Product table when there is a match. When there is no ProductID in the Products table, the data you're trying to pull from the Products table will simply be NULL. Using an inner join requires that the column(s) joined on be present in both tables. For example, if you have a Orders.ProductID = 7, Products must have a row with ID = 7 otherwise your query won't return a row for that Order. Upvotes: 0 <issue_comment>username_2: When you don't always have elements on the second table, you should use the "left join" -> it will retrive all rows from the left table, even if the right table doesnt have a matching row. Like this: ``` select orders.id, orders.started, products.id, products.name from orders left join products on products.id = order.product.id ``` Upvotes: 2 [selected_answer]
2018/03/19
631
2,487
<issue_start>username_0: I took a programming class in python so I know the basics of the language. A project I'm currently attempting involves submiting a form repeatedly untill the request is successful. In order to achieve a faster success using the program, I thought cutting the browser out of the program by directly sending and recieving data from the server would be faster. Also the website I'm creating the program for has a tendency to crash but I'm pretty sure i could still receive and send response to the server. Currently, im just researching different resources I could use to complete the task. I understand mechanize is easy to fill forms and submit them, but it requires a browser. So my question is what would be the best resource to use within python to communicate directly with the server without a browser. I apologize if any of my knowledge is flawed. I did take the class but I'm still relatively new to the language.<issue_comment>username_1: Yes, there are plenty of ways to do this, but the easiest is the third party library called [requests](http://docs.python-requests.org/en/master/). With that installed, you can do for example: ``` requests.post("https://mywebsite/path", {"key: "value"}) ``` Upvotes: 1 <issue_comment>username_2: I see from your tags that you've already decided to use requests. Here's how to perform a basic POST request using requests: > > Typically, you want to send some form-encoded data — much like an HTML > form. To do this, simply pass a dictionary to the data argument. Your > dictionary of data will automatically be form-encoded when the request > is made > > > ``` import requests payload = {'key1': 'value1', 'key2': 'value2'} response = requests.post("http://httpbin.org/post", data=payload) print(response.text) ``` I took this example from [requests official documentation](http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests) I suggest you to read it and try also other examples available in order to become more confident and decide what approach suits your task best. Upvotes: 0 <issue_comment>username_3: You can try this below. ``` from urllib.parse import urlencode from urllib.request import Request, urlopen url = 'https://httpbin.org/post' # Set destination URL here post_fields = {'foo': 'bar'} # Set POST fields here request = Request(url, urlencode(post_fields).encode()) json = urlopen(request).read().decode() print(json) ``` Upvotes: 0
2018/03/19
598
2,178
<issue_start>username_0: I'm trying to edit a a plugins stylesheet. Yet I can't find any file containing the appropriate CSS. When I use Chromes developer tool, it says its styled directly in the index site. Yet i can't find it. I've looked through functions.php as well. The possibility to use !important rules, won't work in my particular examples because i'm dependent on being able to overrule the css in jQuery. The most important thing is to change the `display: inline-block;` to `display: none;` without using !important Screenshot below [![screenshot](https://i.stack.imgur.com/AV4z6.png)](https://i.stack.imgur.com/AV4z6.png)<issue_comment>username_1: Yes, there are plenty of ways to do this, but the easiest is the third party library called [requests](http://docs.python-requests.org/en/master/). With that installed, you can do for example: ``` requests.post("https://mywebsite/path", {"key: "value"}) ``` Upvotes: 1 <issue_comment>username_2: I see from your tags that you've already decided to use requests. Here's how to perform a basic POST request using requests: > > Typically, you want to send some form-encoded data — much like an HTML > form. To do this, simply pass a dictionary to the data argument. Your > dictionary of data will automatically be form-encoded when the request > is made > > > ``` import requests payload = {'key1': 'value1', 'key2': 'value2'} response = requests.post("http://httpbin.org/post", data=payload) print(response.text) ``` I took this example from [requests official documentation](http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests) I suggest you to read it and try also other examples available in order to become more confident and decide what approach suits your task best. Upvotes: 0 <issue_comment>username_3: You can try this below. ``` from urllib.parse import urlencode from urllib.request import Request, urlopen url = 'https://httpbin.org/post' # Set destination URL here post_fields = {'foo': 'bar'} # Set POST fields here request = Request(url, urlencode(post_fields).encode()) json = urlopen(request).read().decode() print(json) ``` Upvotes: 0
2018/03/19
1,183
3,775
<issue_start>username_0: I'd like to reduce the size of this if statement so it can iterate continuously until around 20, with the pattern I have below: ``` if (i >= 0 && i <= 3) { $('.timeline__bar').css({ transform: 'translateX(-0vw)', }); } if (i > 3 && i <= 7) { $('.timeline__bar').css({ transform: 'translateX(-92vw)', }); } if (i > 7 && i <= 11) { $('.timeline__bar').css({ transform: 'translateX(-184vw)', }); } //ect ect until 20 ``` The amount I'm transforming everytime is -92 vh units and I'm sure theres a loop pattern I can hook into too but I'm unsure how to do this.<issue_comment>username_1: Use `else if` instead of `if` for the last two `if` statements. This will give you a better performance by a tiny bit. Upvotes: 1 <issue_comment>username_2: You can also check this approach and remove the additional checkings from the statements ``` var size; if (i <= 3 && i > 0) { size = '0vw'; } else if (i <= 7) { size = '-92vw'; } else if(i <= 11) { size = '-184vw'; } $('.timeline__bar').css({ transform: `translateX(${size})`, }); ``` Upvotes: 1 <issue_comment>username_3: Try something like this ``` function trans(num) { $('.timeline__bar').css({ transform: 'translateX(-'+(Math.floor(num/4)*92)+'vw)', }); } ``` UPDATE: I was using parseInt, but changed to Math.floor since it is more performant if you loop. Upvotes: 3 [selected_answer]<issue_comment>username_4: Try this.(inside for loop or wherever you are using that lot's of ifs) ``` j = Math.floor(i/4); param = "translateX(-" + j*92 + "vw)"; $('.timeline__bar').css({ transform: param, }); ``` Upvotes: 1 <issue_comment>username_5: It would be better if you use `if` and `else if`, making it not work unnecessary code. And remove unecessary conditions, which are checked in the previous `if`: ``` if (i >= 0 && i <= 3) { $('.timeline__bar').css({ transform: 'translateX(-0vw)', }); } else if (i <= 7) { //only one condition here is what you need. :) $('.timeline__bar').css({ transform: 'translateX(-92vw)', }); } //... ``` To make it "cleaner" you can create a function too: ``` function translateTBar(value){ $('.timeline__bar').css({ transform: 'translateX(-' + value + 'vw)'}); } if( i >= 0 && i <= 3) { translateTBar(0); } else if( i <= 7) { translateTBar(92); } else if( i <= 11) { translateTBar(184); } //... ``` Upvotes: 0 <issue_comment>username_6: Is this what you look for, where to have an outer check for `>= 0`, and use `else if` within. By using `else if` instead of separate `if` statements, you only need to check if it is `i <= n`, and when it validates to true, it step into that statement and then step out of the `if/else if` chain. ``` if (i >= 0) { if (i <= 3) { $('.timeline__bar').css({ transform: 'translateX(-0vw)', }); } else if (i <= 7) { $('.timeline__bar').css({ transform: 'translateX(-92vw)', }); } else if (i <= 11) { $('.timeline__bar').css({ transform: 'translateX(-184vw)', }); } else if (i <= 15) { $('.timeline__bar').css({ transform: 'translateX(-276vw)', }); } else if (i <= 19) { $('.timeline__bar').css({ transform: 'translateX(-368vw)', }); } } ``` Upvotes: 1 <issue_comment>username_7: Factor out the common code and set a variable and use else if ``` var translateX = '-0vw' if (i > 3 && i <= 7) { translateX = '-92vw' } else if (i > 7 && i <= 11) { translateX = '-184vw' } $('.timeline__bar').css({ transform: 'translateX(' + translateX + ')', }); ``` Upvotes: 0
2018/03/19
1,274
3,757
<issue_start>username_0: How to treat `/` as part of word and grep exact match? ``` $ echo "aa/bb/cc dd/ee/ff" | grep -w aa/bb aa/bb/cc dd/ee/ff $ ``` I want grep to match the whole string without exception to `/`. In the above example, I don't want it to match `aa/bb/cc` string, but match only if there is any `aa/bb` Expected outputs: ``` $ echo "aa/bb/cc dd/ee/ff" | grep aa/bb $ $ echo "aa/bb dd/ee/ff" | grep aa/bb aa/bb dd/ee/ff $ echo "kk/ll aa/bb dd/ee/ff" | grep aa/bb kk/ll aa/bb dd/ee/ff $ echo "kk/ll dd/ee/ff aa/bb" | grep aa/bb kk/ll dd/ee/ff aa/bb $ echo "kk/ll dd/ee/ff aa/bb/cc" | grep aa/bb $ $ echo "kk/ll dd/ee/ff a-aa/bb" | grep aa/bb $ ```<issue_comment>username_1: Use `else if` instead of `if` for the last two `if` statements. This will give you a better performance by a tiny bit. Upvotes: 1 <issue_comment>username_2: You can also check this approach and remove the additional checkings from the statements ``` var size; if (i <= 3 && i > 0) { size = '0vw'; } else if (i <= 7) { size = '-92vw'; } else if(i <= 11) { size = '-184vw'; } $('.timeline__bar').css({ transform: `translateX(${size})`, }); ``` Upvotes: 1 <issue_comment>username_3: Try something like this ``` function trans(num) { $('.timeline__bar').css({ transform: 'translateX(-'+(Math.floor(num/4)*92)+'vw)', }); } ``` UPDATE: I was using parseInt, but changed to Math.floor since it is more performant if you loop. Upvotes: 3 [selected_answer]<issue_comment>username_4: Try this.(inside for loop or wherever you are using that lot's of ifs) ``` j = Math.floor(i/4); param = "translateX(-" + j*92 + "vw)"; $('.timeline__bar').css({ transform: param, }); ``` Upvotes: 1 <issue_comment>username_5: It would be better if you use `if` and `else if`, making it not work unnecessary code. And remove unecessary conditions, which are checked in the previous `if`: ``` if (i >= 0 && i <= 3) { $('.timeline__bar').css({ transform: 'translateX(-0vw)', }); } else if (i <= 7) { //only one condition here is what you need. :) $('.timeline__bar').css({ transform: 'translateX(-92vw)', }); } //... ``` To make it "cleaner" you can create a function too: ``` function translateTBar(value){ $('.timeline__bar').css({ transform: 'translateX(-' + value + 'vw)'}); } if( i >= 0 && i <= 3) { translateTBar(0); } else if( i <= 7) { translateTBar(92); } else if( i <= 11) { translateTBar(184); } //... ``` Upvotes: 0 <issue_comment>username_6: Is this what you look for, where to have an outer check for `>= 0`, and use `else if` within. By using `else if` instead of separate `if` statements, you only need to check if it is `i <= n`, and when it validates to true, it step into that statement and then step out of the `if/else if` chain. ``` if (i >= 0) { if (i <= 3) { $('.timeline__bar').css({ transform: 'translateX(-0vw)', }); } else if (i <= 7) { $('.timeline__bar').css({ transform: 'translateX(-92vw)', }); } else if (i <= 11) { $('.timeline__bar').css({ transform: 'translateX(-184vw)', }); } else if (i <= 15) { $('.timeline__bar').css({ transform: 'translateX(-276vw)', }); } else if (i <= 19) { $('.timeline__bar').css({ transform: 'translateX(-368vw)', }); } } ``` Upvotes: 1 <issue_comment>username_7: Factor out the common code and set a variable and use else if ``` var translateX = '-0vw' if (i > 3 && i <= 7) { translateX = '-92vw' } else if (i > 7 && i <= 11) { translateX = '-184vw' } $('.timeline__bar').css({ transform: 'translateX(' + translateX + ')', }); ``` Upvotes: 0
2018/03/19
1,032
3,294
<issue_start>username_0: How do I make a PDF with C# application? I would like to make an application which creates a PDF document, but it could be Excel too. I wish to make a file which contains tables and header.<issue_comment>username_1: Use `else if` instead of `if` for the last two `if` statements. This will give you a better performance by a tiny bit. Upvotes: 1 <issue_comment>username_2: You can also check this approach and remove the additional checkings from the statements ``` var size; if (i <= 3 && i > 0) { size = '0vw'; } else if (i <= 7) { size = '-92vw'; } else if(i <= 11) { size = '-184vw'; } $('.timeline__bar').css({ transform: `translateX(${size})`, }); ``` Upvotes: 1 <issue_comment>username_3: Try something like this ``` function trans(num) { $('.timeline__bar').css({ transform: 'translateX(-'+(Math.floor(num/4)*92)+'vw)', }); } ``` UPDATE: I was using parseInt, but changed to Math.floor since it is more performant if you loop. Upvotes: 3 [selected_answer]<issue_comment>username_4: Try this.(inside for loop or wherever you are using that lot's of ifs) ``` j = Math.floor(i/4); param = "translateX(-" + j*92 + "vw)"; $('.timeline__bar').css({ transform: param, }); ``` Upvotes: 1 <issue_comment>username_5: It would be better if you use `if` and `else if`, making it not work unnecessary code. And remove unecessary conditions, which are checked in the previous `if`: ``` if (i >= 0 && i <= 3) { $('.timeline__bar').css({ transform: 'translateX(-0vw)', }); } else if (i <= 7) { //only one condition here is what you need. :) $('.timeline__bar').css({ transform: 'translateX(-92vw)', }); } //... ``` To make it "cleaner" you can create a function too: ``` function translateTBar(value){ $('.timeline__bar').css({ transform: 'translateX(-' + value + 'vw)'}); } if( i >= 0 && i <= 3) { translateTBar(0); } else if( i <= 7) { translateTBar(92); } else if( i <= 11) { translateTBar(184); } //... ``` Upvotes: 0 <issue_comment>username_6: Is this what you look for, where to have an outer check for `>= 0`, and use `else if` within. By using `else if` instead of separate `if` statements, you only need to check if it is `i <= n`, and when it validates to true, it step into that statement and then step out of the `if/else if` chain. ``` if (i >= 0) { if (i <= 3) { $('.timeline__bar').css({ transform: 'translateX(-0vw)', }); } else if (i <= 7) { $('.timeline__bar').css({ transform: 'translateX(-92vw)', }); } else if (i <= 11) { $('.timeline__bar').css({ transform: 'translateX(-184vw)', }); } else if (i <= 15) { $('.timeline__bar').css({ transform: 'translateX(-276vw)', }); } else if (i <= 19) { $('.timeline__bar').css({ transform: 'translateX(-368vw)', }); } } ``` Upvotes: 1 <issue_comment>username_7: Factor out the common code and set a variable and use else if ``` var translateX = '-0vw' if (i > 3 && i <= 7) { translateX = '-92vw' } else if (i > 7 && i <= 11) { translateX = '-184vw' } $('.timeline__bar').css({ transform: 'translateX(' + translateX + ')', }); ``` Upvotes: 0
2018/03/19
997
2,731
<issue_start>username_0: I have tried to make like this block but wasn't able to make as in the design. How can I make it? Can you help me? Here is desired block [![enter image description here](https://i.stack.imgur.com/ud0HM.jpg)](https://i.stack.imgur.com/ud0HM.jpg) and code I have tried: ```css .section-1 { background: green; height: 100px; } .section-2 { display: flex; align-items: center; } .col-img { margin-top: -40px; position: relative; } .col-img:after { top: 40px; position: absolute; right: 100%; width: 10px; background: purple; content: ''; bottom: 0; } .col-img img{ width: 100%; vertical-align: top; } .section-2 .col { width: 50%; } ``` ```html Lorem ipsum dolor, sit amet consectetur adipisicing elit. Harum voluptatem beatae quia facilis nobis, dolore quidem nostrum! Blanditiis eveniet dolor a, laudantium repudiandae rem commodi ea adipisci. Eius, obcaecati rerum. ![](http://via.placeholder.com/650x650) ```<issue_comment>username_1: You will want to use the [CSS3 `transform`](https://www.w3schools.com/cssref/css3_pr_transform.asp) property, to skew your image. You can use either the `skewX()` or `skewY()` functions, or you can `rotate()`. ``` .col-img { transform:rotate(25deg); } ``` Hope this helps. Upvotes: 0 <issue_comment>username_2: I would consider multiple background and some border like this like this: ```css body { margin:0; } .box { padding:40px calc(100% - 250px) 10px 20px; box-sizing:border-box; border-top:30px solid lightblue; border-bottom:5px solid yellow; height:350px; background: linear-gradient(120deg, lightblue 280px,transparent 280px)0 0/100% 40px no-repeat, linear-gradient(120deg,white 250px,yellow 250px,yellow 280px,transparent 280px)0 0/100% 100% no-repeat, url(https://lorempixel.com/1000/1000/) 0 0/cover no-repeat; } ``` ```html lorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum ``` Or more easier way with more element and some transformation: ```css body { margin:0; } .box { box-sizing:border-box; border-top:30px solid lightblue; border-bottom:5px solid yellow; height:100vh; display:flex; background:url(https://lorempixel.com/1000/1000/) 0 0/cover no-repeat; } .content { padding:20px 5px 0 30px; box-sizing:border-box; width:40%; border-top:20px solid lightblue; background:linear-gradient(yellow,yellow) 100% 0/10px 100% no-repeat; transform:skew(-20deg); transform-origin:top left; background-color:#fff; } .content span{ display:inline-block; transform:skew(20deg); } ``` ```html lorem ipsum lorem ipsum lorem ipsum lorem ipsum ``` Upvotes: 2 [selected_answer]
2018/03/19
1,375
4,687
<issue_start>username_0: I am trying to install virtualbox5.2 on a RHEL 7 VM When I try to rebuild kernels modules I get the following error: ``` [root@myserver~]# /usr/lib/virtualbox/vboxdrv.sh setup vboxdrv.sh: Stopping VirtualBox services. vboxdrv.sh: Building VirtualBox kernel modules. This system is currently not set up to build kernel modules. Please install the Linux kernel "header" files matching the current kernel for adding new hardware support to the system. The distribution packages containing the headers are probably: kernel-devel kernel-devel-3.10.0-693.11.1.el7.x86_64 ``` I tried install kernet-devel and got success message ``` Installed: kernel-devel.x86_64 0:3.10.0-693.21.1.el7 Complete! ``` But still the setup fails. Any idea what is missing here?<issue_comment>username_1: `yum install kernel-devel-3.10.0-693.11.1.el7.x86_64` fixed the issue. Upvotes: 0 <issue_comment>username_2: First run in terminal: `uname -r` then you will get name and information about current kernel (CURRENT\_KERNEL). Now you can install with command: `yum install kernel-devel-CURRENT_KERNEL` Note: replace CURRENT\_KERNEL with string you get from `uname -r`. Upvotes: 4 <issue_comment>username_3: The same message happened when I tried to upgrade VirtualBox 5.2.12 Guest Additions on my Kali Linux (GNU/Linux Rolling version). I fixed it by following steps: 1. Do apt update/upgrade to keep your system up-to-date. Do not forget to reboot the system. 2. Run "apt-get install linux-headers-$(uname -r)". 3. Run VBoxLinuxAdditions.run from terminal, error message gone and Guest Additions will be installed successfully. 4. Reboot system, Guest Additions works fine. Upvotes: 2 <issue_comment>username_4: username_2 is right. Your installed kernel-devel must have suffix string exactly the same as the `uname -r` output. Besides, the logs during the vboxdrv.sh setup also shows the wanted version of the kernel-devel. So to your case, You will run the command:`sudo yum install kernel-devel-3.10.0-693.11.1.el7.x86_64` Upvotes: 1 <issue_comment>username_5: `sudo yum install -y "kernel-devel-$(uname -r)"` Substitute `dnf` on Fedora. I didn't need to do a reboot, but ymmv. Edit for 2020: Centos/RHEL 8 now also use `dnf` instead of `yum`. I haven't had occasion to test this on those distros, so the same YMMV disclaimer still applies. Upvotes: 4 <issue_comment>username_6: I got here looking for the same answer for CentOS 6, and the above answers worked with slight modification (so, for anyone else that lands here too)... ``` yum install -y kernel-devel kernel-devel-$(uname -r) ``` So, "yum" instead of "apt-get" Also, some Linux use "linux-headers" instead of "kernel-devel" but the principle seems to be the same. Upvotes: 2 <issue_comment>username_7: The kernel your were using was kernel-devel-3.10.0-693.**11**.1.el7.x86\_64 is slightly different with the one that you installed kernel-devel.x86\_64 0:3.10.0-693.**21**.1.el7 . In my case, there are several different version installed on my OS, and "sudo yum install kernel-devel" always install the newest one for me. Then I work it out by setting my default kernel version as same as yum installed for me. You can check the kernel you have installed on your OS by following command: ``` sudo awk -F\' '$1=="menuentry " {print i++ " : " $2}' /etc/grub2.cfg ``` Then just set the kernel version you choose to use as same as yum choose for you,by following command:(notice that the number at last is pick up from preceding command result), ``` sudo grub2-set-default 0 ``` generate the grub2 config with 'gurb2-mkconfig' command, and then reboot the server. ``` sudo grub2-mkconfig -o /boot/grub2/grub.cfg sudo reboot ``` Upvotes: 2 <issue_comment>username_8: to solve this problem I ran `yum update -y`. I think this is the fastest way to solve it. Another solution is to configure the repos with the installation DVD, so you can install the kernel-headers of your current version of CentOS. My History: * `yum install epel-release` * `yum install perl gcc dkms kernel-devel kernel-headers make bzip2` * `yum groupinstall "Development tools"` * `yum update -y` * `reboot` After that, I mount de VBoxGuestAdditions and I ran the process Upvotes: 1 <issue_comment>username_9: A little late to the party but I just ran into this problem myself and here's what I did to resolve the issue. ``` yum update -y yum install -y redhat-lsb-core net-tools kernel-headers kernel-devel epel-release yum groupinstall -y "Development Tools" reboot ``` Ensure your system has been fully updated when you ran yum update -y before continuing! Cheers Upvotes: 0
2018/03/19
1,025
2,707
<issue_start>username_0: I know "\v" means vertical tab or whitespaces (LF,CR, etc) in regex, so I've used [^\v] instead of [\V] to indicate any character which is not vertical whitespace. But I found the case that [^\v] didn't work in notepad++ 7.5. Example text source ( ffmpeg log ) ``` frame=13920 fps= 86 q=-1.0 size= 96512kB time=00:07:44.47 bitrate=1702.2kbits/s speed=2.88x frame=14068 fps= 87 q=-1.0 size= 98048kB time=00:07:49.41 bitrate=1711.1kbits/s speed= 2.9x frame=14116 fps= 87 q=-1.0 Lsize= 98954kB time=00:07:51.06 bitrate=1720.9kbits/s speed=2.91x video:86252kB audio:3826kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 9.852874% ``` I want to capture the value of latest or last speed of ffmpeg process, so I applied a regex like follows ``` (?s).*speed=\s*\K([^\v]*)(?=x.*$) ``` and returned capture value in notepad++ is ``` 2.91x video:86252kB audio:3826kB subtitle:0kB other streams:0kB global headers:0kB mu ``` but, [regex101.com result](https://regex101.com/r/LCxVPB/3) is "2.91", the value I expected. So I tried [\V] like follows ``` (?s).*speed=\s*\K([\V]*)(?=x.*$) ``` Then, both all returned the same captured value I expected, "2.91". [regex101's result](https://regex101.com/r/LCxVPB/4) Therefore, I'm wondering about the difference between [\V], [^\v] and why notepad++ matched so differently. Thank you:-)<issue_comment>username_1: The expression you want is probably this: ``` speed=\s*(\d+(?:.\d+)?)x? ``` For strings of the form `speed= 2.9x` and `speed=19.2x` and `speed= 1x` Upvotes: 0 <issue_comment>username_2: Notepad++ uses [Boost regex library](http://www.boost.org/doc/libs/1_65_0/libs/regex/doc/html/boost_regex/syntax/perl_syntax.html), and in regex101, you are using [PCRE regex flavor](https://pcre.org/pcre.txt). In PCRE, `[^\v]` seems to be parsed as a "non-vertical whitespace", but Boost parses `\v` inside a character class as a `VT` symbol, `\x0B`. The `[^\v]` negated character class matches any chars but `VT`. Use `[^\r\n]` as a workaround that will work in most cases across a lot of regex flavors: ``` (?s).*speed=\s*\K([^\r\n]*)(?=x.*$) ^^^^^^^ ``` Or, in your case, use a `(?s:...)` modifier group with the first `.*` to make `.` match vertical whitespace, while the other `.*` will not match line breaks: ``` (?s:.*)speed=\s*\K(.*)(?=x.*$) ^^^^^^^ ``` See [Mode Modifiers within Non-Capture Groups](http://www.rexegg.com/regex-disambiguation.html#nocap-with-modifier) to learn more about `(?smix:...)` constructs. [![enter image description here](https://i.stack.imgur.com/V4Mww.png)](https://i.stack.imgur.com/V4Mww.png) Upvotes: 2 [selected_answer]
2018/03/19
490
1,710
<issue_start>username_0: I would like to learn how to print only the return value of a function. I.E. ``` def dude(): print("Hello") return 1 ``` I would like to print only the return value and not the all of the functions process. I would like to use the function and be able to use a different command to get just the values of return,without suppresing print.As `print(dude())` prints Hello and the return value.<issue_comment>username_1: Decorate your dude! ``` def dude_is_decorated(f): def wrap(*args, **kwargs): import os import sys nothing = open(os.devnull, 'w') sys.stdout = nothing sys.stderr = nothing # remove if you want your exceptions to print output = f() nothing.close() sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ return output return wrap @dude_is_decorated def dude(): print("Hello") return 1 print(dude()) ``` output: > > 1 > > > Upvotes: 1 <issue_comment>username_2: This seems to work better: ``` def dude(x,y): z= x+y: print ("Hello") return z print(str(dude(2,3))[1:len(str(dude(2,3)))-1]) ``` While it is ugly, It works and does not break anything else and I can make it a function. It can output just the values , it would just need more work for separating values to be used by another bit of code. It is still ugly and I was hoping for a simple solution like print(dude(2,3).return) that would be clean. I find this very useful for more complex mathematical calculations I have made. With a tiny bit of work I made this a function that automatically outputs single and multiple values. the premise remained the same , str(dude()) was the easy solution. Upvotes: -1 [selected_answer]
2018/03/19
415
1,549
<issue_start>username_0: I have a table called "Tk20F7\_agg" that I am trying to export as a .txt file with custom specifications. The code is below but when I run it, I get this error: "The Microsoft Access database engine could not find the object 'Tk2020181903#txt.'" ``` TempName01 = "Tk20" & Format(Date, "yyyyddmm") ExportPath = DLookup("Export_Path", "OmniDB_system01") Application.FileDialog(msoFileDialogSaveAs).Title = "Export Tk20 File7 (Testing)" Application.FileDialog(msoFileDialogSaveAs).InitialFileName = TempName01 & ".txt" intChoice = Application.FileDialog(msoFileDialogSaveAs).Show If intChoice <> 0 Then strPath = Application.FileDialog(msoFileDialogSaveAs).SelectedItems(1) End If DoCmd.TransferText acExportDelim, "Tk20_File7_spec", "Tk20F7_Agg", TempName01 & ".txt", True ``` Any help on fixing this would be greatly appreciated!<issue_comment>username_1: In my experience, I've found that this particular (and rather misleading) error message can be produced when the structure of a query or table is modified and the associated Export Specification is not updated to reflect the changes. To resolve the error, I would suggest exporting the target object 'manually' using the Export Text File wizard, and re-save the Export Specification. Upvotes: 3 [selected_answer]<issue_comment>username_2: I will also add for other readers - the key here is "with custom specifications". Without those - - one can reconfigure a table/query and a saved export will work because it is just called by the object name. Upvotes: 1
2018/03/19
492
1,759
<issue_start>username_0: For some reason I'm getting this error. Below are the specs and then what I did. > > Visual Studio 2017 v15.6.2 > > > SQL Server 2008 v10.50.4 > > > I opened the package manager console and added the following packages... ``` Install-Package Microsoft.EntityFrameworkCore.SqlServer Install-Package Microsoft.EntityFrameworkCore.Tools ``` and then I ran ``` Scaffold-DbContext "Server=ph2srv76;Database=AVDRS;Integrated Security=True;Trusted_Connection=True;" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -force ``` but during the build I get the following errors... [![enter image description here](https://i.stack.imgur.com/C0j5b.png)](https://i.stack.imgur.com/C0j5b.png)<issue_comment>username_1: Those are just warnings (yellow), not errors(red) - you can safely ignore them Upvotes: 3 [selected_answer]<issue_comment>username_2: In case anyone else gets this I solved it by checking and fixing the following: 1. Make sure that the user id you are using in the scaffold-dbcontext actually has permissions on the tables you want to scaffold. If not the scaffold cannot find them. 2. Make sure the tables have primary keys or EF cannot scaffold them. Makes sense if you think about it. After the above the scaffold worked for me! Upvotes: 2 <issue_comment>username_3: I hate to post the obvious, but in my case (same error) I was targeting specific tables to model (with -t option) and didn't realize that the table names are case sensitive. Doh! Upvotes: 3 <issue_comment>username_4: In my case, I used -table option. I got the same error when I do this: -Tables "REPORT, REPORT\_TYPE, SAVED\_REPORT" The correct way is this: -Tables "REPORT", "REPORT\_TYPE", "SAVED\_REPORT" Upvotes: 0
2018/03/19
723
3,120
<issue_start>username_0: Actually my app have 2 themes (pink and blue), handled by ResourceDictionary in App.xaml Switching a switch in settings page change programmatically the values of the ResourceDictionary and the elements change as wanted (background, text colors etc). It's maybe not the prettiest way but it works.. But i have a problem to change background colors of the Tabbar in android. [![enter image description here](https://i.stack.imgur.com/auVZG.png)](https://i.stack.imgur.com/auVZG.png) The color value of it is set in the Android project (colorPrimary from styles.xml and Tabbar.axml). But i can't find * How to change or access this value from my PCL project. * Or how to change, in Android project, the value of that colorPrimary each time the settings switch value is changed. * Or also, the best solution, **make the tabbar transparent** and make it overlap the current background (if i set `Color.Transparent` it just become white now) The tabbed page code is as been created by Xamarin forms project. ``` public MainPage() { Page centerPage, rightPage, leftPage; string TitleCenter = "S'exercer"; string TitleLeft = "Comprendre"; string TitleRight = "Aller plus loin"; switch (Device.RuntimePlatform) { case Device.iOS: centerPage = new NavigationPage(new Center_Main()) { Title = TitleCenter }; rightPage = new NavigationPage(new Right_Main()) { Title = TitleRight }; leftPage = new NavigationPage(new Left_Main()) { Title = TitleLeft }; centerPage.Icon = "tab_feed.png"; rightPage.Icon = "tab_about.png"; leftPage.Icon = "offline_logo.png"; break; default: centerPage = new Center_Main() { Title = TitleCenter // Nothing tab related here }; rightPage = new Right_Main() { Title = TitleRight }; leftPage = new Left_Main() { Title = TitleLeft }; break; } ``` Thanks<issue_comment>username_1: Maybe if you go straight into the color that fills in the Tabbar this way: xaml: ``` ``` MainPage. ``` Application.Current.Resources ["primary_colour"] = Color.Green; ``` Upvotes: 0 <issue_comment>username_2: Using Xaml it is something like this: ``` ``` Programatically: ``` TabbedPage page=new Tabbedpage(){ BarBackgroundColor=Color.Blue}; ``` You can do the following in your tabbedPage constructor : ``` public MainPage() { BarBackgroundColor=Color.Blue; } ``` **Note:** Can be used with static resources just put it in place of the color name. Something like this ``` <... BarBackgroundColor={StaticResource color_name}> ``` Upvotes: 3 [selected_answer]
2018/03/19
384
1,370
<issue_start>username_0: I have a code (for which performance is crucial) that I can compile in single and double precision. We use a lot of physical constants throughout the code that come out of a `namespace Constants`. What is the most elegant way of providing the constants in the preferred precision, as I cannot template a namespace? ``` namespace Constants { const double meaning_of_life = 42.; } template TF multiply\_number(const TF a) { return Constants::meaning\_of\_life\*a; } int main() { double a = multiply\_number(5.); // With the call below, a cast is done in multiply\_number. float b = multiply\_number(6.); return 0; } ```<issue_comment>username_1: Maybe if you go straight into the color that fills in the Tabbar this way: xaml: ``` ``` MainPage. ``` Application.Current.Resources ["primary_colour"] = Color.Green; ``` Upvotes: 0 <issue_comment>username_2: Using Xaml it is something like this: ``` ``` Programatically: ``` TabbedPage page=new Tabbedpage(){ BarBackgroundColor=Color.Blue}; ``` You can do the following in your tabbedPage constructor : ``` public MainPage() { BarBackgroundColor=Color.Blue; } ``` **Note:** Can be used with static resources just put it in place of the color name. Something like this ``` <... BarBackgroundColor={StaticResource color_name}> ``` Upvotes: 3 [selected_answer]
2018/03/19
5,427
13,105
<issue_start>username_0: I'm new in keras and deep learning field. In fact, I built a deep autoencoder using keras library based on ionosphere data set, which contains a mixed data frame (float, strings"objects", integers..) so I tried to replace all object colunms to float or integer type since the autoencoder refuses being fed with object samples. The training set contains 10000 samples with 48 columns and the validation set contains 5000 samples. I didn't do any normalization of the input data because I thought isn't really necessary for autoencoder model. I used a binary cross entropy loss function, am not sure if that could be the reason of having a constant loss and a constant accuracy values during training. I tried different number of epochs but I got the same thing. I tried also to change the batch size but no change. Can any one help me find the problem please. ``` input_size = 48 hidden_size1 = 30 hidden_size2 = 20 code_size = 10 batch_size = 80 checkpointer = ModelCheckpoint(filepath="model.h5", verbose=0, save_best_only=True) tensorboard = TensorBoard(log_dir='./logs', histogram_freq=0, write_graph=True, write_images=True) input_enc = Input(shape=(input_size,)) hidden_1 = Dense(hidden_size1, activation='relu')(input_enc) hidden_11 = Dense(hidden_size2, activation='relu')(hidden_1) code = Dense(code_size, activation='relu')(hidden_11) hidden_22 = Dense(hidden_size2, activation='relu')(code) hidden_2 = Dense(hidden_size1, activation='relu')(hidden_22) output_enc = Dense(input_size, activation='sigmoid')(hidden_2) autoencoder_yes = Model(input_enc, output_enc) autoencoder_yes.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) history = autoencoder_yes.fit(df_noyau_yes, df_noyau_yes, epochs=200, batch_size=batch_size, shuffle = True, validation_data=(df_test_yes, df_test_yes), verbose=1, callbacks=[checkpointer, tensorboard]).history Epoch 176/200 80/7412 [..............................] - ETA: 2s - loss: -15302256.0000 - acc: 0.4357 320/7412 [>.............................] - ETA: 2s - loss: -16773740.2500 - acc: 0.4448 480/7412 [>.............................] - ETA: 2s - loss: -16924116.1667 - acc: 0.4444 720/7412 [=>............................] - ETA: 2s - loss: -17179484.1111 - acc: 0.4460 960/7412 [==>...........................] - ETA: 2s - loss: -17382038.5833 - acc: 0.4463 1120/7412 [===>..........................] - ETA: 1s - loss: -17477103.7857 - acc: 0.4466 1360/7412 [====>.........................] - ETA: 1s - loss: -17510808.8824 - acc: 0.4466 1520/7412 [=====>........................] - ETA: 1s - loss: -17337536.3158 - acc: 0.4462 1680/7412 [=====>........................] - ETA: 1s - loss: -17221621.6190 - acc: 0.4466 1840/7412 [======>.......................] - ETA: 1s - loss: -17234479.0870 - acc: 0.4467 2000/7412 [=======>......................] - ETA: 1s - loss: -17336909.4000 - acc: 0.4469 2160/7412 [=======>......................] - ETA: 1s - loss: -17338357.2222 - acc: 0.4467 2320/7412 [========>.....................] - ETA: 1s - loss: -17434196.3103 - acc: 0.4465 2560/7412 [=========>....................] - ETA: 1s - loss: -17306412.6875 - acc: 0.4463 2720/7412 [==========>...................] - ETA: 1s - loss: -17229429.4118 - acc: 0.4463 2880/7412 [==========>...................] - ETA: 1s - loss: -17292270.6667 - acc: 0.4461 3040/7412 [===========>..................] - ETA: 1s - loss: -17348734.3684 - acc: 0.4463 3200/7412 [===========>..................] - ETA: 1s - loss: -17343675.9750 - acc: 0.4461 3360/7412 [============>.................] - ETA: 1s - loss: -17276183.1429 - acc: 0.4461 3520/7412 [=============>................] - ETA: 1s - loss: -17222447.5455 - acc: 0.4463 3680/7412 [=============>................] - ETA: 1s - loss: -17179892.1304 - acc: 0.4463 3840/7412 [==============>...............] - ETA: 1s - loss: -17118994.1667 - acc: 0.4462 4080/7412 [===============>..............] - ETA: 1s - loss: -17064828.6275 - acc: 0.4461 4320/7412 [================>.............] - ETA: 0s - loss: -16997390.4074 - acc: 0.4460 4480/7412 [=================>............] - ETA: 0s - loss: -17022740.0357 - acc: 0.4461 4640/7412 [=================>............] - ETA: 0s - loss: -17008629.1552 - acc: 0.4460 4880/7412 [==================>...........] - ETA: 0s - loss: -16969480.9836 - acc: 0.4459 5040/7412 [===================>..........] - ETA: 0s - loss: -17028253.4921 - acc: 0.4457 5200/7412 [====================>.........] - ETA: 0s - loss: -17035566.0308 - acc: 0.4456 5360/7412 [====================>.........] - ETA: 0s - loss: -17057620.4776 - acc: 0.4456 5600/7412 [=====================>........] - ETA: 0s - loss: -17115849.8857 - acc: 0.4457 5760/7412 [======================>.......] - ETA: 0s - loss: -17117196.7500 - acc: 0.4458 5920/7412 [======================>.......] - ETA: 0s - loss: -17071744.5676 - acc: 0.4458 6080/7412 [=======================>......] - ETA: 0s - loss: -17073121.6184 - acc: 0.4459 6320/7412 [========================>.....] - ETA: 0s - loss: -17075835.3797 - acc: 0.4461 6560/7412 [=========================>....] - ETA: 0s - loss: -17081048.5610 - acc: 0.4460 6800/7412 [==========================>...] - ETA: 0s - loss: -17109489.2471 - acc: 0.4460 7040/7412 [===========================>..] - ETA: 0s - loss: -17022715.4545 - acc: 0.4460 7200/7412 [============================>.] - ETA: 0s - loss: -17038501.4222 - acc: 0.4460 7360/7412 [============================>.] - ETA: 0s - loss: -17041619.7174 - acc: 0.4461 7412/7412 [==============================] - 3s 357us/step - loss: -17015624.9390 - acc: 0.4462 - val_loss: -26101260.3556 - val_acc: 0.4473 Epoch 200/200 80/7412 [..............................] - ETA: 2s - loss: -16431795.0000 - acc: 0.4367 240/7412 [..............................] - ETA: 2s - loss: -16439401.0000 - acc: 0.4455 480/7412 [>.............................] - ETA: 2s - loss: -16591146.5000 - acc: 0.4454 640/7412 [=>............................] - ETA: 2s - loss: -16914542.8750 - acc: 0.4457 880/7412 [==>...........................] - ETA: 2s - loss: -16552313.2727 - acc: 0.4460 1120/7412 [===>..........................] - ETA: 1s - loss: -16839956.4286 - acc: 0.4459 1280/7412 [====>.........................] - ETA: 1s - loss: -16965753.3750 - acc: 0.4461 1440/7412 [====>.........................] - ETA: 1s - loss: -17060988.4444 - acc: 0.4461 1680/7412 [=====>........................] - ETA: 1s - loss: -17149844.2381 - acc: 0.4462 1840/7412 [======>.......................] - ETA: 1s - loss: -17049971.6957 - acc: 0.4462 2080/7412 [=======>......................] - ETA: 1s - loss: -17174574.2692 - acc: 0.4462 2240/7412 [========>.....................] - ETA: 1s - loss: -17131009.5357 - acc: 0.4463 2480/7412 [=========>....................] - ETA: 1s - loss: -17182876.8065 - acc: 0.4461 2720/7412 [==========>...................] - ETA: 1s - loss: -17115984.6176 - acc: 0.4460 2880/7412 [==========>...................] - ETA: 1s - loss: -17115818.8611 - acc: 0.4459 3120/7412 [===========>..................] - ETA: 1s - loss: -17123591.0256 - acc: 0.4459 3280/7412 [============>.................] - ETA: 1s - loss: -17114971.6585 - acc: 0.4459 3440/7412 [============>.................] - ETA: 1s - loss: -17072177.0698 - acc: 0.4462 3600/7412 [=============>................] - ETA: 1s - loss: -17025446.1333 - acc: 0.4460 3840/7412 [==============>...............] - ETA: 1s - loss: -16969630.0625 - acc: 0.4462 4080/7412 [===============>..............] - ETA: 1s - loss: -16961362.9608 - acc: 0.4461 4320/7412 [================>.............] - ETA: 0s - loss: -16969639.5000 - acc: 0.4461 4480/7412 [=================>............] - ETA: 0s - loss: -16946814.6964 - acc: 0.4462 4640/7412 [=================>............] - ETA: 0s - loss: -16941803.2586 - acc: 0.4461 4880/7412 [==================>...........] - ETA: 0s - loss: -16915578.2623 - acc: 0.4462 5040/7412 [===================>..........] - ETA: 0s - loss: -16916479.5714 - acc: 0.4464 5200/7412 [====================>.........] - ETA: 0s - loss: -16896774.5846 - acc: 0.4463 5360/7412 [====================>.........] - ETA: 0s - loss: -16956822.5075 - acc: 0.4462 5600/7412 [=====================>........] - ETA: 0s - loss: -17015829.3286 - acc: 0.4461 5760/7412 [======================>.......] - ETA: 0s - loss: -17024089.8750 - acc: 0.4460 5920/7412 [======================>.......] - ETA: 0s - loss: -17034422.1216 - acc: 0.4462 6160/7412 [=======================>......] - ETA: 0s - loss: -17042738.7273 - acc: 0.4462 6320/7412 [========================>.....] - ETA: 0s - loss: -17041053.0886 - acc: 0.4462 6480/7412 [=========================>....] - ETA: 0s - loss: -17046979.9012 - acc: 0.4461 6640/7412 [=========================>....] - ETA: 0s - loss: -17041165.7590 - acc: 0.4461 6800/7412 [==========================>...] - ETA: 0s - loss: -17070702.2824 - acc: 0.4460 7040/7412 [===========================>..] - ETA: 0s - loss: -17031330.6364 - acc: 0.4460 7280/7412 [============================>.] - ETA: 0s - loss: -17027056.8132 - acc: 0.4461 7412/7412 [==============================] - 3s 363us/step - loss: -17015624.9908 - acc: 0.4462 - val_loss: -26101260.3556 - val_acc: 0.4473 Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) (None, 48) 0 _________________________________________________________________ dense_1 (Dense) (None, 30) 1470 _________________________________________________________________ dense_2 (Dense) (None, 20) 620 _________________________________________________________________ dense_3 (Dense) (None, 10) 210 _________________________________________________________________ dense_4 (Dense) (None, 20) 220 _________________________________________________________________ dense_5 (Dense) (None, 30) 630 _________________________________________________________________ dense_6 (Dense) (None, 48) 1488 ================================================================= Total params: 4,638 Trainable params: 4,638 Non-trainable params: 0 _________________________________________________________________ None ```<issue_comment>username_1: I took a quick look at the dataset you're using. One problem I could find is that your data contains negative values, but your autoencoder has a sigmoid activation function on the last layer. Thus your output is mapped to the range between zero and one. So you'll need to either normalize the data or change the activation function on the last layer to for example tanh, if your values are between -1 and 1. Also I'm not sure why you should use binary cross-entropy, as the loss function, I think mean squared error (mse) would be more suitable here. According to <https://stats.stackexchange.com/a/296277> binary cross-entropy may be asymmetric in some unwanted cases. Upvotes: 0 <issue_comment>username_2: You may already have fixed your issue, but I want to clarify what probably went wrong with your autoencoder so other people that have the same problem can understand what is happening. The main issue is that you didn't normalize your input data and you used sigmoid function as activation in the last layer. What this means is that you have an input that can range between `-infinity` and `+infinity` while your output data can only vary between `0` and `1`. An autoencoder is a Neural Network that tries to learn the identity function. What this means is that if you have an input `[0, 1, 2, 3]`, you want the network to output `[0, 1, 2, 3]`. What happened in your case is that you used sigmoid as an Activation Function in the last layer, which means that every value this layer receives, it will apply a sigmoid function. As said before, the sigmoid function squashes values between `0` and `1`. So if you have `[0, 1, 2, 3]` as inputs, even if your hidden layer learns the identity function (which I think would be impossible in this case), the output would be `sigmoid([0, 1, 2, 3])`, which results in `[0.5, 0.73, 0.88, 0.95]` approximately. If you think about it, it's impossible that this autoencoder learns to replicate its inputs if the range of the inputs exceeds the `0` to `1` range, because when the loss function try to compare the result with the original data, it will always mismatch. In this case, the best thing you can do is to normalize your inputs so it varies between `0` and `1` just like your outputs. Upvotes: 2
2018/03/19
994
2,897
<issue_start>username_0: I have a navbar that contains elements, and I'm not able to center them in the middle of the navbar. I do not want to use bootstrap. Whatever I do, it still starts from the left side. I originally had the ul as the .topnav but it still wasn't centering the elements. HTML: ``` * [Home](index.html) * [Products](javascript:void(0)) [Computers](#) [Tablets](#) [Cell Phones](#) [Wearable Technologies](#) [Accessories](#) * [Brands](javascript:void(0)) [Apple](#) [Samsung](#) [Lenovo](#) [Dell](#) [HP](#) [Sony](#) [Panasonic](#) [Motorola](#) [HTC](#) * [Deals](deals.html) ``` CSS: ``` .topnav{ list-style-type: none; margin: 0 auto; padding: 0; overflow: hidden; background-color: #333; text-align:center; align-items: center; } .topnav ul{ list-style-type: none; margin: 0 auto; } .topnav li { float: left; } .topnav li a, .dropbtn { display: inline-block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; width:100px; } .topnav li a:hover, .dropdown:hover .dropbtn { background-color: #111; } li.dropdown { display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } .topnav .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; text-align: left; } .topnav .dropdown-content a:hover {background-color: #f1f1f1;} .dropdown:hover .dropdown-content { display: block; } ``` JSFiddle: <https://jsfiddle.net/29r9d18a/1/><issue_comment>username_1: Update the class definition ``` .topnav ul{ list-style-type: none; margin: 0 auto; display:inline-block; } ``` [Updated jsFiddle](https://jsfiddle.net/29r9d18a/7/) Upvotes: 1 <issue_comment>username_2: ``` .topnav ul{ list-style-type: none; margin: 0; display: inline-block; -webkit-padding-start: 0; } ``` You will no longer need the `auto` x-margin on the `ul` element with `inline-block` positioning and the parents center aligning, but you may want to override Safari's auto padding which will push it to the right slightly on Macs. Upvotes: 1 [selected_answer]<issue_comment>username_3: **Use display: flex AND text-align: center** ``` .topnav{ list-style-type: none; margin: 0 auto; padding: 0; overflow: hidden; background-color: #333; display: flex; //HERE text-align: center !important; //HERE } ``` Upvotes: 0 <issue_comment>username_4: change the '.topnav ul' class to the following in your css code : ``` .topnav ul{ list-style-type: none; margin: 0 auto; margin-left: 27%; } ``` This will shift your list to a bit right side and thus show it on the center. Upvotes: 0
2018/03/19
568
2,298
<issue_start>username_0: I am getting the following error: > > Unable to resolve service for type 'IMyRepository' while attempting to activate 'MyController'. > > > I understand that my application is failing on the dependency injection. However I'm not sure how to correct this error. My IMyRepository looks lie this: ``` public interface IMyRepository { public Delete(Guid Id); public Get(Guid Id); //etc.. } ``` We set the following interface up when we created the unit tests. ``` public IMyRepositoryFactory { IRepository CreateRepository(); } ``` The constructor in my Controller: ``` private readonly IRepository _repo; public MyController(IRepository repo) { _repo = repo; } ``` I can pass the factory into the constructor, however that would require me to redo the unit testing modules since they are all passing IRepository to the controller. ``` Ex. (In Startup ConfigureServices) services.AddTransient(); ``` I would prefer to leave the controller constructors and testing classes as is. So is there a way to setup DI in this scenario (Where I am passing the IRepository to the controller)? EDIT: ``` public class ConcreteRepositoryFactory : IMyRepositoryFactory { public ConcreteRepositoryFactory(string connString); public IMyRepository CreateRepository(); } ```<issue_comment>username_1: You are adding a Transcient `IMyRepositoryFactory` linked to a `ConcreteRepositoryFactory`. So you cannot inject a IRepository class in your controller, because asp.net Core doesn't know your IRepository class in the transcient injections. You have to inject instead the `ConcreteRepositoryFactory` class to your controller like this : `public MyController(ConcreteRepositoryFactory repo)` And you can store in your readonly property as `IMyRepositoryFactory _repo`. Upvotes: 1 <issue_comment>username_2: I'm not exactly clear on what you're trying to achieve here. Simplistically, you need to bind an implementation of `IMyRepository` if you want to inject `IMyRepository`: ``` services.AddScoped(); ``` If you're saying you want to inject the implementation via a factory, you can simply provide a factory to the service registration: ``` services.AddScoped(p => p.GetRequiredService().CreateRepository()); ``` Upvotes: 3 [selected_answer]
2018/03/19
597
2,370
<issue_start>username_0: Im creating a website right now using Angular 5 and CouchDB. In my database.service.ts a method looks like this: ``` import {HttpClient} from '@angular/common/http'; const auth = my database adress; constructor(private http: HttpClient) {} createUser(id: string, email_: string, password_: string, firstname: string, surname_: string, role: string): any { const obj: object = { name: firstname, surname: surname_, role, email: email_, password: <PASSWORD>_, theme: 'indigo', projects: {}, widgets: {} }; return this.http.put(auth + '/' + id, JSON.parse(JSON.stringify(obj))) .map((res: Response) => res); } ``` And im calling the method when the user should be created like this: ``` this.databaseService.createUser(id, email, password, firstname, surname, this.role) .subscribe(result => {}, err => { console.log(err); alert('No connection to database available!'); }); ``` This works absolutely fine in Chrome but not in Firefox! The PUT did not even get executed in Firefox so it can't be a problem with the CouchDB (i captured the traffic via wireshark and npcap). GET and POST works fine in firefox, but PUT not. The headers look got ("Accept": 'application/json' etc..) and i have no clue whats's wrong. It should be at least executing, or am i wrong? Thanks for your help.<issue_comment>username_1: You are adding a Transcient `IMyRepositoryFactory` linked to a `ConcreteRepositoryFactory`. So you cannot inject a IRepository class in your controller, because asp.net Core doesn't know your IRepository class in the transcient injections. You have to inject instead the `ConcreteRepositoryFactory` class to your controller like this : `public MyController(ConcreteRepositoryFactory repo)` And you can store in your readonly property as `IMyRepositoryFactory _repo`. Upvotes: 1 <issue_comment>username_2: I'm not exactly clear on what you're trying to achieve here. Simplistically, you need to bind an implementation of `IMyRepository` if you want to inject `IMyRepository`: ``` services.AddScoped(); ``` If you're saying you want to inject the implementation via a factory, you can simply provide a factory to the service registration: ``` services.AddScoped(p => p.GetRequiredService().CreateRepository()); ``` Upvotes: 3 [selected_answer]
2018/03/19
361
1,368
<issue_start>username_0: I have an tag input like this ``` Valor total ``` and i need to put a limit like `maxlength="15,4"` being much more specific i need this in my input `999999999999999,9999` or something like this mask `###############,####` i iv tried to look at web but all sugest dosent work in my case.. i dont now why.. so i ask here.. its can be in angular, jquery<issue_comment>username_1: You are adding a Transcient `IMyRepositoryFactory` linked to a `ConcreteRepositoryFactory`. So you cannot inject a IRepository class in your controller, because asp.net Core doesn't know your IRepository class in the transcient injections. You have to inject instead the `ConcreteRepositoryFactory` class to your controller like this : `public MyController(ConcreteRepositoryFactory repo)` And you can store in your readonly property as `IMyRepositoryFactory _repo`. Upvotes: 1 <issue_comment>username_2: I'm not exactly clear on what you're trying to achieve here. Simplistically, you need to bind an implementation of `IMyRepository` if you want to inject `IMyRepository`: ``` services.AddScoped(); ``` If you're saying you want to inject the implementation via a factory, you can simply provide a factory to the service registration: ``` services.AddScoped(p => p.GetRequiredService().CreateRepository()); ``` Upvotes: 3 [selected_answer]
2018/03/19
463
1,715
<issue_start>username_0: I could see spark connectors & guidelines for consuming events from Event Hub using Scala in Azure Databricks. **But, How can we consume events in event Hub from azure databricks using pySpark?** any suggestions/documentation details would help. thanks<issue_comment>username_1: Below is the snippet for reading events from event hub from pyspark on azure data-bricks. ``` // With an entity path val with = "Endpoint=sb://SAMPLE;SharedAccessKeyName=KEY_NAME;SharedAccessKey=KEY;EntityPath=EVENTHUB_NAME" # Source with default settings connectionString = "Valid EventHubs connection string." ehConf = { 'eventhubs.connectionString' : connectionString } df = spark \ .readStream \ .format("eventhubs") \ .options(**ehConf) \ .load() readInStreamBody = df.withColumn("body", df["body"].cast("string")) display(readInStreamBody) ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: I think there is slight modification that is required if you are using spark version **2.4.5** or greater and version of the Azure event Hub Connector **2.3.15** or above For **2.3.15** version and above, the configuration dictionary requires that connection string be encrypted, So you need to pass it as shown in the code snippet below. ``` connectionString = "Endpoint=sb://SAMPLE;SharedAccessKeyName=KEY_NAME;SharedAccessKey=KEY;EntityPath=EVENTHUB_NAME" ehConf = {} ehConf['eventhubs.connectionString'] = sc._jvm.org.apache.spark.eventhubs.EventHubsUtils.encrypt(connectionString) df = spark \ .readStream \ .format("eventhubs") \ .options(**ehConf) \ .load() readInStreamBody = df.withColumn("body", df["body"].cast("string")) display(readInStreamBody) ``` Upvotes: 2
2018/03/19
857
3,552
<issue_start>username_0: I am using UIImagePickerController to use my camera like so: ``` @objc func toggle() { if UIImagePickerController.isSourceTypeAvailable(.camera) { //Define UIImagePickerController variable let imagePicker = UIImagePickerController() //Assign the delegate imagePicker.delegate = self //Set image picker source type imagePicker.sourceType = .camera //Allow Photo Editing imagePicker.allowsEditing = true //Present camera UIApplication.topViewController()?.present(imagePicker, animated: true, completion: nil) } } ``` Now I am trying to capture the image taken using the didFinishPickingMediaWithInfo method, I got this example online: ``` func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let imageUrl = info[UIImagePickerControllerOriginalImage] as! NSURL let imageName = imageUrl.lastPathComponent let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let photoURL = NSURL(fileURLWithPath: documentDirectory) let localPath = photoURL.appendingPathComponent(imageName!) let image = info[UIImagePickerControllerOriginalImage]as! UIImage let data = UIImagePNGRepresentation(image) do { try data?.write(to: localPath!, options: Data.WritingOptions.atomic) } catch { // Catch exception here and act accordingly } UIApplication.topViewController()?.dismiss(animated: true, completion: nil); } ``` But I changed UIImagePickerControllerReferenceURL to UIImagePickerControllerOriginalImage as UIImagePickerControllerReferenceURL is nil. but after I change that I get this fatal error: > > Could not cast value of type 'UIImage' (0x1b6b02b58) to 'NSURL' > > > How do I save the image take from the camera? What am I doing wrong?<issue_comment>username_1: Write your code as following this will give you image. ``` let image = info[UIImagePickerControllerOriginalImage] as! UIImage ``` UIImagePickerControllerOriginalImage return image not NSURL Write following code to get image url in iOS 11. From iOS 11 UIImagePickerControllerImageURL is available, earlier there are UIImagePickerControllerMediaURL key to get image url. ``` if #available(iOS 11.0, *) { if let imageURL = info[UIImagePickerControllerImageURL] as? URL { print(imageURL) } } else { if let imageUrl = info[UIImagePickerControllerMediaURL] as? URL { print(imageUrl) } } ``` I hope this will help you. Upvotes: 4 [selected_answer]<issue_comment>username_2: The one who are searching for complete method to implement for **Swift 4.2+** ``` func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage{ imageView.image = pickedImage } imgPicker.dismiss(animated: true, completion: nil) } ``` This will return you the `original image` according to new syntax For **Image URL** and **Media URL**, Use the respective ``` let imgURL = info[UIImagePickerController.InfoKey.imageURL] let mediaURL = info[UIImagePickerController.InfoKey.mediaURL] ``` Upvotes: 2
2018/03/19
968
3,001
<issue_start>username_0: I have a list of tuples `seg = [(874, 893), (964, 985), (1012, 1031)]` and an index. I want to check if the index is inside the range of those tuples, for example, `876` is while `870` is not. My code to do so is the following: ``` if [x for (x, y) in seg if x <= index <= y]: print ("index inside the segment") ``` However, I also want to return if the index is in the first second ... segment of the list seg. For example, for the `index = 876` to return `1` and for the `index = 1015` to return `3`. How can I do so?<issue_comment>username_1: You can use [`enumerate`](https://docs.python.org/3/library/functions.html?highlight=enumerate#enumerate) + [`next`](https://docs.python.org/3/library/functions.html#next) with generator expression: ``` >>> seg = [(874, 893), (964, 985), (1012, 1031)] >>> index = 876 >>> next((i for i, (s,f) in enumerate(seg) if s <= index <= f), None) 0 ``` --- Or, if you want to iterate over: ``` >>> for i in (i for i, (s,f) in enumerate(seg) if s <= index <= f): ... print("in segment:", i) ... in segment: 0 ``` --- *thanks `@jpp` for the hint about [the default option of the `next` function.](https://docs.python.org/3/library/functions.html#next) (It can be used in cases where the given index is not in any of the ranges represented by the tuples)* Upvotes: 4 [selected_answer]<issue_comment>username_2: Assuming the following: List is ordered First number is less than second number no overlapping ``` index=870 seg = [(874, 893), (964, 985), (1012, 1031)] for i, t in enumerate(seg): if index >= t[0] and index <= t[1]: print i ``` Upvotes: 1 <issue_comment>username_3: As others have pointed out, you can use [`enumerate()`](https://docs.python.org/3/library/functions.html#enumerate) to get the indexes. I'd also argue that if you are treating the tuples as ranges, you should make them [ranges](https://docs.python.org/3/library/stdtypes.html#range). This then makes the check to see if the value is inside the range very intuitive: `value in range`. ``` import itertools seg = [(874, 893), (964, 985), (1012, 1031)] ranges = list(itertools.starmap(range, seg)) def test(value): for i, valueRange in enumerate(ranges): if value in valueRange: return i # + 1 if you want to index from 1 as indicated. # You could add some special case handling here if there is no match, like: # throw NoSuchRangeException("The given value was not inside any of the ranges.") print(test(876)) # 0 print(test(1015)) # 1 ``` Obviously using ranges has some cost (if you are in Python 2.x, this is comparatively huge because it will make actual lists of all the values, and unfortunately `xrange()` return objects without `__contains__()` implemented). If you are doing this kind of thing in lots of places, it's much nicer, however. You may be able to just replace your tuple construction with range construction, depending on the situation, rather than doing the starmap. Upvotes: 2
2018/03/19
261
1,062
<issue_start>username_0: I have a form with an existing data source. This data source has a one to many relationship to another table that is **not** an existing data source. Even though this second table contains multiple records (one to many), the field in the table that I want is duplicated across all records. Therefore I want to add this second table as a data source, but only return one record from it. If I add the second table directly, than my form contains a line for each record instead of just one.<issue_comment>username_1: Use the property LinkType=ExistJoin on the datasource for your second table. See the TransactionLog form for example. Upvotes: 1 <issue_comment>username_2: This problem was solved by creating a view to use as the new datasource. This view defined a calculated column that was based on a method that contained a query string that used TOP 1. The details in much more detail are at <NAME>'s blog: <https://community.dynamics.com/ax/b/goshoom/archive/2015/06/29/join-first-line-in-ax-2012>. Upvotes: 3 [selected_answer]
2018/03/19
418
1,370
<issue_start>username_0: I have created the following ggplot using the code below. I need to remove the red vertical line on the right. Any help would be appreciated. [![enter image description here](https://i.stack.imgur.com/qVd4a.jpg)](https://i.stack.imgur.com/qVd4a.jpg) ``` ggplot(model.1, aes(x = time, y = activity)) + geom_line(aes(group = id), alpha = .3) + geom_line(data = data, alpha = .9, size = 1, colour="red4") + theme(panel.background = element_blank(),axis.line=element_line(colour="black"))+ scale_x_continuous(expand=c(0,0)) + theme(axis.line = element_line(colour = "black"), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), panel.background = element_blank())+ labs( x = "Time", y = "Activity", color = NULL ) ```<issue_comment>username_1: It looks like the red vertical line is part of your data, I could be wrong though. If it is you can filter it: ``` filtered_data <- data %>% filter(time < 1) ``` And then use that within the geom\_line function. Upvotes: 0 <issue_comment>username_2: You could try moving the group into the `ggplot` layer: ``` ggplot(model.1,aes(x = time, y = activity, group=id)) ``` And remove it from the `geom_line` layer. I had a similar problem, and this got rid of the vertical line. Upvotes: 1
2018/03/19
536
2,105
<issue_start>username_0: It seems I have a unwanted file in a directory. The file is an MS Word file, with a filename that begins with ~$, which I understand is a locked file, probably created by MS Word. But, the file remains after MS Word is closed. I have the Windows explorer setup to show hidden files, but it does now show this unwanted file, so I can't delete it. Nor do I see it when using the command line. C# Directory.GetFiles gets and counts this file, causing an incorrect file count. I want to delete this file. But I need to see it to delete it. How can I get rid of this unwanted file?<issue_comment>username_1: Alternatively, you could ignore the files: ``` var files = Directory.GetFiles(directory).Where(name => !name.StartsWith("~$")); ``` Upvotes: 1 <issue_comment>username_2: The `~$` files are lock/recovery files that Word creates while you have a file actively open for editing. If you are **very sure** Word is not running **and** that it was shut down properly, you can safely delete these files. If it's possible Word was not shut down properly, you may still want these files in order to recover unsaved work. > > I have the Windows explorer setup to show hidden files, but it does now show this unwanted file > > > I can't reproduce this. I just verified on my own system that setting explorer to show hidden files did indeed show the `~$` file. Windows can remember these settings per-folder, so please check that you really do have explorer set to show hidden files for the appropriate folder. If that fails, you can also try using [`Directory.GetFileSystemInfos()`](https://learn.microsoft.com/en-us/dotnet/api/system.io.directoryinfo.getfilesysteminfos), which will give you a class that includes both the name and an `Attributes` property you can use to filter out or show hidden files: ``` var files = Directory.GetFileSystemInfo("path here") .Where(fsi => fsi.Attributes != null && fsi.Attributes.Hidden && fsi.Name.StartsWith("~$")) .Select(fsi => fsi.FullName); foreach(var file in files) { File.Delete(file); } ``` Upvotes: 0
2018/03/19
727
2,844
<issue_start>username_0: I would like to use Gradle tasks to execute java commands for the [salesforce dataloader](https://github.com/forcedotcom/dataloader) so that we can have our data loading tasks in a self-contained project. I've installed the dataloader into my local maven repo and set up my gradle project as follows: build.gradle: ``` apply plugin: 'groovy' repositories { mavenCentral() mavenLocal() } dependencies { compile gradleApi() compile 'com.force:dataloader:42.0.0' compile 'org.codehaus.groovy:groovy-all:2.4.7' } task generateKey(type: JavaExec) { classpath sourceSets.main.runtimeClasspath main = 'com.salesforce.dataloader.security.EncryptionUtil' args '-g', 'seedText' } ``` The Problem ----------- When I execute `gradle generateKey`, the task completes successfully but none of the output from the EncryptionUtil is shown. I suspect this is because the dataloader uses a log4j logger and not printing directly to standard out? Is there some further configuration I need to do? I've also tried a task that calls `EncryptionUtil.main('-g', 'seedText')` directly, but that also won't show any output unless I run the task in --info mode. Thanks for your help! I appreciate feedback and any options I'm not thinking of. We're a gradle shop but maybe there is a better solution.<issue_comment>username_1: Alternatively, you could ignore the files: ``` var files = Directory.GetFiles(directory).Where(name => !name.StartsWith("~$")); ``` Upvotes: 1 <issue_comment>username_2: The `~$` files are lock/recovery files that Word creates while you have a file actively open for editing. If you are **very sure** Word is not running **and** that it was shut down properly, you can safely delete these files. If it's possible Word was not shut down properly, you may still want these files in order to recover unsaved work. > > I have the Windows explorer setup to show hidden files, but it does now show this unwanted file > > > I can't reproduce this. I just verified on my own system that setting explorer to show hidden files did indeed show the `~$` file. Windows can remember these settings per-folder, so please check that you really do have explorer set to show hidden files for the appropriate folder. If that fails, you can also try using [`Directory.GetFileSystemInfos()`](https://learn.microsoft.com/en-us/dotnet/api/system.io.directoryinfo.getfilesysteminfos), which will give you a class that includes both the name and an `Attributes` property you can use to filter out or show hidden files: ``` var files = Directory.GetFileSystemInfo("path here") .Where(fsi => fsi.Attributes != null && fsi.Attributes.Hidden && fsi.Name.StartsWith("~$")) .Select(fsi => fsi.FullName); foreach(var file in files) { File.Delete(file); } ``` Upvotes: 0
2018/03/19
790
2,767
<issue_start>username_0: Currently attempting to have special characters, primarily '.' a number, however, it seems enums require letters only. Is there a way to use special characters? Currently trying to make a file saver and many file types have numbers in them, an example being: ``` public enum FileType { 7z(".7z"), ace(".ace"), apk(".apk"), bz2(".bz2"), crx(".crx"), dd(".dd"), deb(".deb"), gz(".gz"), gzip(".gzip"), jar(".jar"), rar(".rar"), rpm(".rpm"), sit(".sit"), sitx(".sitx"), snb(".snb"), tar(".tar"), tar.gz(".tar.gz"), tqz(".tqz"), zip(".zip"), zipx(".zipx"); public final String FILESUFFIX; FileType(String FileSuffix) { this.FILESUFFIX = FileSuffix; } public String getSuffix() { return FILESUFFIX; } } ``` I have looked throughout StackOverflow, however, I haven't found a way that suited me. I do not understand how to do 'maps' or the other fancy stuff, so is there an alternate way to simple get something like `mp4` to be an Enum?<issue_comment>username_1: this value declared in the enum **7z** is invalid same as you can not declare a variable with the name 7z since that will be an ***invalid java identifier*** <https://docs.oracle.com/cd/E19798-01/821-1841/bnbuk/index.html> alternative to that you can play with underscores,and something better is use UPPER\_CASE ``` public enum FileType { _7Z(".7z"), _ACE(".ace"), _APK(".apk"), _BZ2(".bz2"), _CRX(".crx"), etc etc ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Enum identifiers follow the same [rules as other Java identifiers](https://www.geeksforgeeks.org/java-identifiers/): > > The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign) and ‘\_‘ (underscore). > > > Identifiers should not start with digits([0-9]). For example “123geeks” is a not a valid java identifier. > > > Java identifiers are case-sensitive > > > From your example, `mp4` is a valid identifier, but `7z` is not (because it starts with a number) Note: by convention, enum identifiers are typically all uppercase. Upvotes: 2 <issue_comment>username_3: ``` package com.ecom.test; enum SpecialChars { PIPELINE_SYMBOL("|"), FORWARD_SLASH("/"); private String value; private SpecialChars(String value) { this.value = value; } public String toString() { return this.value; // will return , or ' instead of COMMA or APOSTROPHE } } public class Test1 { public static void main(String[] args) { System.out.println(SpecialChars.PIPELINE_SYMBOL); System.out.println(SpecialChars.FORWARD_SLASH); } } ``` Upvotes: 1
2018/03/19
1,115
3,627
<issue_start>username_0: I have the following data frame ``` design <- read.table(text = "block position 1 1 1 2 1 3 1 4 2 1 2 2 2 3 2 4", header = TRUE) ``` I want to randomly assign four treatments within one block. I could do this for example with the following code: ``` treatment <- letters[1:4] set.seed(2) design$treatment <- as.vector(replicate(2,sample(treatment, length(treatment)))) ``` resulting in the following data frame ``` > design block position treatment 1 1 a 1 2 c 1 3 b 1 4 d 2 1 d 2 2 c 2 3 a 2 4 b ``` Problem: in the example above the treatment c is two times at position 2. One treatment should not be two times at the same position. How can I achieve this? **More general:** Is there an easy solution for sampling with constrain?<issue_comment>username_1: The following method should ensure (1) randomness of treatments, and (2) non-identical treatments at the same position for different blocks. 1. We calculate all permutations of `letters[1:4]` using `gtools::permutations`. We store the set of permutations in a matrix `perm`. ``` # Calculate all permutations of letters[1:4] library(gtools); treatment <- letters[1:4]; perm <- permutations(length(treatment), length(treatment), treatment); ``` 2. We create an empty `treatment` vector that will be filled successively block by block. ``` design$treatment <- ""; ``` 3. We now randomly draw a permutation from `perm` for the first `block`. Once we have drawn a permutation, we remove all permutations from `perm` (i.e. our set of permutations) that have *any* identical entries at the same positions. We then randomly draw a permutation from the reduced set of permutations for the second `block`. And so on. ``` set.seed(2017); for (i in 1:length(unique(design$block))) { smpl <- perm[sample(nrow(perm), 1), ]; design$treatment[seq(1 + 4 * (i - 1), 4 * i)] <- smpl; # Remove all permutations with duplicated letters j <- 1; while (j <= nrow(perm)) { if (any(perm[j, ] == smpl)) perm <- perm[-j, ] else j <- j + 1; } } design; # block position treatment #1 1 1 d #2 1 2 c #3 1 3 a #4 1 4 b #5 2 1 b #6 2 2 a #7 2 3 d #8 2 4 c ``` Remove `set.seed(...)` to use a random seed. Upvotes: 3 [selected_answer]<issue_comment>username_2: This solution works for a larger number of treatments and is based on the [answer of username_1](https://stackoverflow.com/a/49372815/6152316). Only 1000 permutations are calculated instead of all possible permutations. ``` n_treat <- 20 # make large design file design <- data.frame(block = rep(1:4, each = n_treat), position = rep(1:n_treat, 4)) # Calculate some (not all) random permutations treatment <- 1:n_treat perm <- t(replicate(1000,sample(treatment, length(treatment), replace = F))) # Create empty treatment vector design$treatment <- "" # loop through all blocks, # randomly draw a permutation from perm, # remove permutations with identiacal entries at the same position. set.seed(2017); for (i in 1:length(unique(design$block))) { smpl <- perm[sample(nrow(perm), 1), ]; design$treatment[seq(1 + n_treat * (i - 1), n_treat * i)] <- smpl; # Remove all permutations with duplicated letters j <- 1; while (j <= nrow(perm)) { if (any(perm[j, ] == smpl)) perm <- perm[-j, ] else j <- j + 1; } } ``` Upvotes: 1
2018/03/19
549
2,100
<issue_start>username_0: Our team is trying to execute ``` `java -jar network-bootstrapper.jar ` ``` to bootstrap a Corda node. The documentation on [Bootstrapping the network](https://docs.corda.net/head/setting-up-a-corda-network.html#bootstrapping-the-network) instructs the reader to: ``` To use it, create a directory containing a node.conf file for each node >you want to create. Then run the following command: java -jar network-bootstrapper.jar For example running the command on a directory containing these files : . ├── notary.conf // The notary's node.conf file ├── partya.conf // Party A's node.conf file └── partyb.conf // Party B's node.conf file Would generate directories containing three nodes: notary, partya and partyb. ``` We have 1. Created a root directory. 2. Placed the network-bootstrapper.jar in the root directory. 3. Created a notary.conf 4. Created a partya.conf 5. Executed `java -jar network-bootstrapper.jar` This results in "No nodes found."<issue_comment>username_1: Reviewing NetworkBootstrapper source we realized that the documentation was incorrect ... 1. The exception was a little misleading. The correction to the 'No nodes found' exception was placing the corda.jar in the nodes-root-dir. 2. Step 1 gets you further. The second issue to resolve is creating the .conf file with the right naming convention. The documentation indicates that the naming convention for the node (entities) is [node directory name].conf. The NetworkBootstrapper code base revealed that the naming convention that it expected was [node directory name]\_node.config. Upvotes: 2 [selected_answer]<issue_comment>username_2: The bootstrapper reported `No nodes found` because the nodes' `node.conf` files did not end in the suffix `_node.config`. The docs are being updated to reflect this requirement in this pull request: github.com/corda/corda/pull/2848. The first step listed in username_1's answer - placing the Corda JAR in the nodes folder - is not necessary. The bootstrapper will automatically extract its own copy of the Corda JAR as required. Upvotes: 0
2018/03/19
439
1,850
<issue_start>username_0: I'm trying to start a new activity using intent and on finishing the activity, I want my previous activity to retain its data. I already have other activities passing some data into this main activity but on starting this new activity, when I go back, all that data disappears and gives me a null pointer exception. > > Is it possible to retain the data from the previous activity? I > searched about it and found I could make a singleton class but it's > usage is still unclear to me. > > > *P.S.: The real problem is I'm trying to pass a String ArrayList from this activity to the main activity but on doing so, the previous data (being passed on from previous activities) on the main activity disappears.*<issue_comment>username_1: Reviewing NetworkBootstrapper source we realized that the documentation was incorrect ... 1. The exception was a little misleading. The correction to the 'No nodes found' exception was placing the corda.jar in the nodes-root-dir. 2. Step 1 gets you further. The second issue to resolve is creating the .conf file with the right naming convention. The documentation indicates that the naming convention for the node (entities) is [node directory name].conf. The NetworkBootstrapper code base revealed that the naming convention that it expected was [node directory name]\_node.config. Upvotes: 2 [selected_answer]<issue_comment>username_2: The bootstrapper reported `No nodes found` because the nodes' `node.conf` files did not end in the suffix `_node.config`. The docs are being updated to reflect this requirement in this pull request: github.com/corda/corda/pull/2848. The first step listed in username_1's answer - placing the Corda JAR in the nodes folder - is not necessary. The bootstrapper will automatically extract its own copy of the Corda JAR as required. Upvotes: 0
2018/03/19
638
2,374
<issue_start>username_0: As you can see in the code section below, once you click on one the buttons the text in the field changes **but the event does not get fired (and it does not run alertTextInput() method)**, when you type text directly under the text field the event is triggered as expected. How can I activate the event manually by using a code or using a method that changes the text and triggers the event? thank you! ```js const changeTextButton = document.querySelector("#change-text"); const clearButton = document.querySelector("#clear"); const inputField = document.querySelector("#query"); changeTextButton.addEventListener("click", changeText); clearButton.addEventListener("click", clear); inputField.addEventListener("input", alertTextInput); function changeText() { inputField.value = "Demo Text!!"; inputField.dispatchEvent(new Event("input")) } function clear() { inputField.value = ""; inputField.dispatchEvent(new Event("input")) } function alertTextInput() { alert(inputField.value); } ``` ```html Change the text programmatically Clear ```<issue_comment>username_1: Try this to manually dispatch the event, see [EventTarget.dispatchEvent()](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent): ``` inputField.dispatchEvent(new Event("input")) ``` Upvotes: 6 [selected_answer]<issue_comment>username_2: If I understand correctly you want the input text to change AND the alert to appear when clicking "change" button. As the changeText() function just changes the text you should not expect an alert to appear. You could just add the alertTextInput() function to the bottom of changeText(). ``` function changeText() { inputField.value = "Demo Text!!"; alertTextInput(); } ``` Upvotes: 1 <issue_comment>username_3: From [React Doc](https://github.com/facebook/react/issues/2244) > > React expects to hear the `input` event > > > So trigger the `input` event after set the value. [This is how to trigger](https://stackoverflow.com/questions/35659430/how-do-i-programmatically-trigger-an-input-event-without-jquery?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa). The Final code is: ``` var event = new Event('input', { 'bubbles': true, 'cancelable': true }); inputElement.value = '0.2' inputElement.dispatchEvent(event); ``` Upvotes: 4
2018/03/19
605
2,077
<issue_start>username_0: I am building a Flask app and I am having some troubles with one of the HTML-templates. What I want to do is a sort of 3x3 tile layout for news stories, all tiles of equal height and width. This is my html code: ``` {% extends "base.html" %} {% block app_content %} {% for result in results[:3] %} {% include '\_result.html' %} {%endfor %} {% for result in results[3:6] %} {% include '\_result.html' %} {%endfor %} {% for result in results[6:9] %} {% include '\_result.html' %} {%endfor %} {% endblock %} ``` The problem is that I am getting three nice and evenly sized columns, but the rows are not of equal height. My guess is that it has to do with the nested columns (having col-lg-12 and then col-lg-4). Is there any way to get all the rows the same height?<issue_comment>username_1: Try this to manually dispatch the event, see [EventTarget.dispatchEvent()](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent): ``` inputField.dispatchEvent(new Event("input")) ``` Upvotes: 6 [selected_answer]<issue_comment>username_2: If I understand correctly you want the input text to change AND the alert to appear when clicking "change" button. As the changeText() function just changes the text you should not expect an alert to appear. You could just add the alertTextInput() function to the bottom of changeText(). ``` function changeText() { inputField.value = "Demo Text!!"; alertTextInput(); } ``` Upvotes: 1 <issue_comment>username_3: From [React Doc](https://github.com/facebook/react/issues/2244) > > React expects to hear the `input` event > > > So trigger the `input` event after set the value. [This is how to trigger](https://stackoverflow.com/questions/35659430/how-do-i-programmatically-trigger-an-input-event-without-jquery?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa). The Final code is: ``` var event = new Event('input', { 'bubbles': true, 'cancelable': true }); inputElement.value = '0.2' inputElement.dispatchEvent(event); ``` Upvotes: 4
2018/03/19
498
1,742
<issue_start>username_0: I'm trying to check if WordPress user is logged in or not from an external PHP file and here is my code ``` php /*Load up wordpress externally*/ define( 'WP_USE_THEMES', false ); define( 'COOKIE_DOMAIN', false ); define( 'DISABLE_WP_CRON', true ); require('../../trading/wp-load.php'); if ( is_user_logged_in() ){ $user = wp_get_current_user(); print_r($user); }else{ echo 'logged out'; } </code ``` ?> I always get 'logged out' message, even though the user is logged in. Any idea how can I fix this? Thanks<issue_comment>username_1: When is this custom php file loaded? According to the [`Action Reference`](https://codex.wordpress.org/Plugin_API/Action_Reference) - You need to wait until at least the [`init`](https://codex.wordpress.org/Plugin_API/Action_Reference/init) hook before the user is authenticated. I would try: ``` add_action( 'init', 'FDI_logged_in' ); function FDI_logged_in(){ if( is_user_logged_in() ){ $user = wp_get_current_user(); print_r( $user ); } else { echo 'logged out'; } } ``` Upvotes: 0 <issue_comment>username_2: I thought your code was correct so I tested it (changing only the line "require('../../trading/wp-load.php');" to match my installation) and **it worked as expected** so code itself is correct and something else is wrong. For WordPress (in a standard configuration) to know a user is logged it must receive a cookie. Can you add a ``` var_dump( $_COOKIE ); ``` to your script and verify a cookie like ''wordpress\_logged\_in\_ ...' is being received. WordPress has hooks so user verification can be customised. Of course in a customised installation the above may not be true. Upvotes: 2 [selected_answer]
2018/03/19
772
2,455
<issue_start>username_0: This is the code it is supposed to simulate the rolls of 2 dice 5 times. ``` import java.util.*; public class RollDice { static double die1; static double die2; static double sum; public static void main (String[] args) { String output = ""; for (int i =0; i<5; i= i+1) { die1 = (Math.random()*6)+1; die1 = (int) die1; die2 = (Math.random()*6)+1; die2 = (int)die2; System.out.println("die 1 "+ die1+" die 2 "+ die2); sum = die1+die2; System.out.println("The sum is "+ sum); if(i>5) break; } } } ``` I need to calculate the average for all the rolls not the average for each so the output shows the rolls the sum and the average of all the rolls.<issue_comment>username_1: If by average you mean the average across all the dice rolls, you can get it summing up all the rolls and dividing by 10. ``` static double total = 0; // in your for loop total += sum; // after the loop System.out.println("Average: "+(total/10)); ``` Upvotes: 0 <issue_comment>username_2: It can be something like this: ``` public class RollDice { public void main(String[] args) { int total; for(int i = 1; i < 6; i++) { int die1 = roll (); int die2 = roll(); System.out.println("die 1 = " + die1 + " and die2 = " + die2); int sum = die1 + die2; System.out.println("the sum is " + sum); total += sum; } double avg = total / 5.0d; System.out.println("the avg is " + avg); } public int roll() { return Math.floor(Math.random()*6 + 1.0d); } } ``` Upvotes: -1 <issue_comment>username_3: You can simplify ``` die1 = (Math.random()*6)+1; die1 = (int) die1; ``` To ``` die1 = (int) ((Math.random() * 6) + 1); ``` But you don't need to cast it to an integer if you want exact values, thats going to truncate (get rid of) your decimal places. To sum all rolls, ``` int total = 0; int maxRolls = Integer.MAX_VALUE; //lol for (int roll = 1; roll <= maxRolls; roll++) { // roll your dice total += (die1 + die2); } ``` To Average ``` double average = (total / maxRolls); ``` To Output ``` System.out.println("Total: " + total + " Average: " + average + " Rolls: " + maxRolls); ``` You're welcome, now do your own homework Upvotes: 2 [selected_answer]
2018/03/19
582
1,848
<issue_start>username_0: I try to create request in func and after call the func and return responсe json. But because request is async response arrived after func returns any data. How handle request finishing?<issue_comment>username_1: If by average you mean the average across all the dice rolls, you can get it summing up all the rolls and dividing by 10. ``` static double total = 0; // in your for loop total += sum; // after the loop System.out.println("Average: "+(total/10)); ``` Upvotes: 0 <issue_comment>username_2: It can be something like this: ``` public class RollDice { public void main(String[] args) { int total; for(int i = 1; i < 6; i++) { int die1 = roll (); int die2 = roll(); System.out.println("die 1 = " + die1 + " and die2 = " + die2); int sum = die1 + die2; System.out.println("the sum is " + sum); total += sum; } double avg = total / 5.0d; System.out.println("the avg is " + avg); } public int roll() { return Math.floor(Math.random()*6 + 1.0d); } } ``` Upvotes: -1 <issue_comment>username_3: You can simplify ``` die1 = (Math.random()*6)+1; die1 = (int) die1; ``` To ``` die1 = (int) ((Math.random() * 6) + 1); ``` But you don't need to cast it to an integer if you want exact values, thats going to truncate (get rid of) your decimal places. To sum all rolls, ``` int total = 0; int maxRolls = Integer.MAX_VALUE; //lol for (int roll = 1; roll <= maxRolls; roll++) { // roll your dice total += (die1 + die2); } ``` To Average ``` double average = (total / maxRolls); ``` To Output ``` System.out.println("Total: " + total + " Average: " + average + " Rolls: " + maxRolls); ``` You're welcome, now do your own homework Upvotes: 2 [selected_answer]
2018/03/19
1,902
6,508
<issue_start>username_0: I'm trying to create a blobstore entry from an image data-uri object, but am getting stuck. Basically, I'm posting via ajax the data-uri as text, an example of the payload: ``` data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPA... ``` I'm trying to receive this payload with the following handler. I'm assuming I need to convert the `data-uri` back into an image before storing? So am using the PIL library. My python handler is as follows: ``` import os import urllib import webapp2 from google.appengine.ext.webapp import template from google.appengine.ext import blobstore from google.appengine.ext.webapp import blobstore_handlers from google.appengine.api import images class ImageItem(db.Model): section = db.StringProperty(required=False) description = db.StringProperty(required=False) img_url = db.StringProperty() blob_info = blobstore.BlobReferenceProperty() when = db.DateTimeProperty(auto_now_add=True) #Paste upload handler class PasteUpload(webapp2.RequestHandler): def post(self): from PIL import Image import io import base64 data = self.request.body #file_name = data['file_name'] img_data = data.split('data:image/png;base64,')[1] #Convert base64 to jpeg bytes f = Image.open(io.BytesIO(base64.b64decode(img_data))) img = ImageItem(description=self.request.get('description'), section=self.request.get('section') ) img.blob_info = f.key() img.img_url = images.get_serving_url( f.key() ) img.put() ``` This is likely all kinds of wrong. I get the following error when posting: ``` img.blob_info = f.key() AttributeError: 'PngImageFile' object has no attribute 'key' ``` What am I doing wrong here? Is there an easier way to do this? I'm guessing I don't need to convert the `data-uri` into an image to store as a blob? I also want this Handler to return the URL of the image created in the blobstore.<issue_comment>username_1: An image object (<https://cloud.google.com/appengine/docs/standard/python/refdocs/google.appengine.api.images>) isn't a Datastore entity, so it has no key. You need to actually save the image to blobstore[2] or Google Cloud Storage[1] then get a serving url for your image. [1] <https://cloud.google.com/appengine/docs/standard/python/googlecloudstorageclient/setting-up-cloud-storage> [2] <https://cloud.google.com/appengine/docs/standard/python/blobstore/> Upvotes: 0 <issue_comment>username_2: There are a couple of ways to view your question and the sample code you posted, and it's a little confusing what you need because you are mixing strategies and technologies. **POST base64 to `_ah/upload/...`** Your service uses `create_upload_url()` to make a one-time upload URL/session for your client. Your client makes a POST to that URL and the data never touches your service (no HTTP-request-size restrictions, no CPU-time spent handling the POST). An App Engine internal "blob service" receives that POST and saves the body as a Blob in the Blobstore. App Engine then hands control back to your service in the `BlobstoreUploadHandler` class you write and then you can determine how you want to respond to the successful POST. In the case of the example/tutorial, `PhotoUploadHandler` redirects the client to the photo that was just uploaded. That POST from your client must be encoded as `multipart/mixed` and use the fields shown in the example HTML . The multipart form can take the optional parameter, `Content-Transfer-Encoding`, and the App Engine internal handler will properly decode base64 data. From `blob_upload.py`: ``` base64_encoding = (form_item.headers.get('Content-Transfer-Encoding') == 'base64') ... if base64_encoding: blob_file = cStringIO.StringIO(base64.urlsafe_b64decode(blob_file.read())) ... ``` Here's a complete multipart form I tested with cURL, based on the fields used in the example. I found out how to do this over at [Is there a way to pass the content of a file to curl?](https://stackoverflow.com/questions/31061379/is-there-a-way-to-pass-the-content-of-a-file-to-curl): **myconfig.txt**: ``` header = "Content-length: 435" header = "Content-type: multipart/mixed; boundary=XX data-binary = "@myrequestbody.txt" ``` **myrequestbody.txt**: ``` --XX Content-Disposition: form-data; name="file"; filename="test.gif" Content-Type: image/gif Content-Transfer-Encoding: base64 R0lGODdhDwAPAIEAAAAAzMzM/////wAAACwAAAAADwAPAAAIcQABCBxIsODAAAACAAgAIACAAAAiSgwAIACAAAACAAgAoGPHACBDigwAoKTJkyhTqlwpQACAlwIEAJhJc6YAAQByChAAoKfPn0CDCh1KtKhRAAEAKF0KIACApwACBAAQIACAqwECAAgQAIDXr2DDAggIADs= --XX Content-Disposition: form-data; name="submit" Submit --XX-- ``` and then run like: ``` curl --config myconfig.txt "http://127.0.0.1:8080/_ah/upload/..." ``` You'll need to create/mock-up the multipart form in your client. Also, as an alternative to Blobstore, you can use Cloud Storage if you want to save a little on storage costs or have some need to share the data without your API. Follow the documentation for [Setting Up Google Cloud Storage](https://cloud.google.com/appengine/docs/standard/python/googlecloudstorageclient/setting-up-cloud-storage), and then modify your service to create the upload URL for your bucket of choice: ``` create_upload_url(gs_bucket_name=...) ``` It's a little more complicated than just that, but reading the section *Using the Blobstore API with Google Cloud Storage* in the Blobstore document will get you pointed in the right direction. **POST base64 directly to your service/handler** Kind of like you coded in the original post, your service receives the POST from your client and you then decide if you need to manipulate the image and where you want to store it (Datastore, Blobstore, Cloud Storage). If you need to manipulate the image, then using PIL is good: ``` from io import BytesIO from PIL import Image from StringIO import StringIO data = self.request.body #file_name = data['file_name'] img_data = data.split('data:image/png;base64,')[1] # Decode base64 and open as Image img = Image.open(BytesIO(base64.b64decode(img_data))) # Create thumbnail img.thumbnail((128, 128)) # Save img output as blob-able string output = StringIO() img.save(output, format=img.format) img_blob = output.getvalue() # now you choose how to save img_blob ``` If you don't need to manipulate the image, just stop at `b64decode()`: ``` img_blob = base64.b64decode(img_data) ``` Upvotes: 2
2018/03/19
666
2,442
<issue_start>username_0: html Code ``` ``` js function: ``` function delete_image() { var status = confirm("Are you sure you want to delete ?"); if(status==true) { var file = $("#delete_file").val(); $.ajax({ type:"POST", url:"php/del.php", data:{file:file}, success(html){ alert('Deleted'); } }); } } ``` **Php code:** ``` php if(isset($_POST['file'])) { $filename = $_POST['file']; unlink($filename); echo"done"; } ? ```<issue_comment>username_1: First, you don't check the return value of `unlink`. I returns a boolean value as simply described [here](https://www.w3schools.com/php/func_filesystem_unlink.asp). Second, make sure you give the real file path to unlink. Upvotes: -1 <issue_comment>username_2: If your HTML is not wrapped in single quotes and `echo`ed like: ``` echo ' '; ``` The value of `'.$image.'` will be a string literal and not the value of the variable. > > You should also be careful of your PHP code as one could manipulate > the `POST` request and delete your files. > > > But ignoring that and if you are indeed echoing out a path to the file. You should then do some basic sanity checking in the PHP code. ``` php // enable error reporting error_reporting(E_ALL); ini_set('display_errors', '1'); if (isset($_POST['file'])) { $filename = $_POST['file']; if (!file_exists($filename)) { die('File does not exist!'); } // if (!is_writable($filename)) { die('Wont be able to delete file!'); } elseif(!unlink($filename)) { die('Could not delete file!'); } echo "Deleted"; } ? ``` The issue is **most likely** the javascript success callback `success(html) {` breaking your js code (check console), it should be like: ``` function delete_image() { var status = confirm("Are you sure you want to delete ?"); if(status==true) { var file = $("#delete_file").val(); $.ajax({ type: "POST", url: "php/del.php", data: {file:file}, success: function (html) { alert(html); // maybe something better.. }, // this would help you debug it too error: function (jqXHR, error) { alert('Error:' + jqXHR.status + ' - ' + error); } }); } } ``` Upvotes: 0
2018/03/19
883
3,575
<issue_start>username_0: Problem in retrieving firebase database to an android app. ---------------------------------------------------------- [Here is the image of firebase realtime database updating from from raspberry pi](https://i.stack.imgur.com/LiAHP.png) --- error: Failed to convert value of type java.util.HashMap to String ------------------------------------------------------------------ Below is my **MainActivity.java** ``` public class MainActivity extends AppCompatActivity { private TextView tempvalue; private TextView humidvalue; private FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance(); private DatabaseReference mRootReference = firebaseDatabase.getReference(); private DatabaseReference mChildReference = mRootReference.child("user").child(""); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tempvalue = (TextView)findViewById(R.id.tempvalue); humidvalue = (TextView)findViewById(R.id.humidvalue); } @Override protected void onStart() { super.onStart(); mChildReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String Temperature = dataSnapshot.getValue(String.class); String Humidity = dataSnapshot.getValue(String.class); tempvalue.setText(Temperature); humidvalue.setText(Humidity); } @Override public void onCancelled(DatabaseError databaseError) { } }); }} ``` --- [output error while i'm running it into my phone(usb-debugging)](https://i.stack.imgur.com/nEnJf.png) \*<issue_comment>username_1: First, you don't check the return value of `unlink`. I returns a boolean value as simply described [here](https://www.w3schools.com/php/func_filesystem_unlink.asp). Second, make sure you give the real file path to unlink. Upvotes: -1 <issue_comment>username_2: If your HTML is not wrapped in single quotes and `echo`ed like: ``` echo ' '; ``` The value of `'.$image.'` will be a string literal and not the value of the variable. > > You should also be careful of your PHP code as one could manipulate > the `POST` request and delete your files. > > > But ignoring that and if you are indeed echoing out a path to the file. You should then do some basic sanity checking in the PHP code. ``` php // enable error reporting error_reporting(E_ALL); ini_set('display_errors', '1'); if (isset($_POST['file'])) { $filename = $_POST['file']; if (!file_exists($filename)) { die('File does not exist!'); } // if (!is_writable($filename)) { die('Wont be able to delete file!'); } elseif(!unlink($filename)) { die('Could not delete file!'); } echo "Deleted"; } ? ``` The issue is **most likely** the javascript success callback `success(html) {` breaking your js code (check console), it should be like: ``` function delete_image() { var status = confirm("Are you sure you want to delete ?"); if(status==true) { var file = $("#delete_file").val(); $.ajax({ type: "POST", url: "php/del.php", data: {file:file}, success: function (html) { alert(html); // maybe something better.. }, // this would help you debug it too error: function (jqXHR, error) { alert('Error:' + jqXHR.status + ' - ' + error); } }); } } ``` Upvotes: 0
2018/03/19
560
2,067
<issue_start>username_0: Every documentation from Visual Studio (2013, 15 17) says the Visual Studio Experimental Instance will have its own register entries in the Registry Editor under xxExp and xxExp\_Config Keys. I can't find those Keys/Folders under HKEY\_CURRENT\_USER/SOFTWARE/Microsot/Visual Studio, but i know they exist as i can create/edit them using WritableSettingsStore. Can someone tell me where they are?<issue_comment>username_1: Visual Studio now uses a private registry, which can be found at ``` %localappdata%\Microsoft\VisualStudio\15.0_INSTANCE_IDExp\privateregistry.bin ``` (Replace `INSTANCE_ID` by the VS instance ID) It can be loaded in `regedit.exe`, but it's not possible to edit the keys from there I think. Upvotes: 2 [selected_answer]<issue_comment>username_2: You should read through the following topic: [Changes in Visual Studio 2017 extensibility](https://learn.microsoft.com/en-us/visualstudio/extensibility/breaking-changes-2017) In particular the section that talks about the Visual Studio registry. As Jose mentioned, I've already posted instructions on using regedit to read/edit this privateregistry.bin at: [Access Visual Studio 2017's private registry hive](https://stackoverflow.com/questions/42916299/access-visual-studio-2017s-private-registry-hive) The above is also documented in the help topic: [Tools for detecting and managing Visual Studio instances](https://learn.microsoft.com/en-us/visualstudio/install/tools-for-managing-visual-studio-instances#editing-the-registry-for-a-visual-studio-instance) And an alternative to using regedit, would be to use the new vsregedit.exe utility, which is installed with VS, but I could only find mentioned in the documentation at: [Controlling notifications in the Visual Studio IDE](https://learn.microsoft.com/en-us/visualstudio/install/controlling-updates-to-visual-studio-deployments) You can learn more about vsregedit.exe, by running it from your developer command prompt with the /? switch. Sincerely, username_2 Microsoft Developer Support Upvotes: 0
2018/03/19
207
791
<issue_start>username_0: I have a VMSS which is not connected to a load balancer running windows 2016 server edition operating system. How can I RDP into this setup? Is port 3389 open by default?<issue_comment>username_1: If you use Azure image to create VMSS, you can **create a windows VM work as a jumpbox** in that same Vnet. If you use image which upload from your local, **please make sure you have enable RDP first**, then you can use another VM to RDP it via internal IP address. If you image does not enable RDP, please re-prepare your image and enable RDP, then upload to Azure to create a new VMSS. Upvotes: 3 [selected_answer]<issue_comment>username_2: Another way to do this is to go to your vnet, search for your vm scale set and you should be able to see the IP. Upvotes: 1
2018/03/19
1,377
4,663
<issue_start>username_0: It's quite annoying since upgrading to Android Studio 3.0.1 such that the "Back/Forward" buttons are not displayed in tool bar at the top in IDE any more. I know, I can select "Navigation-> Back/Forward", but obviously, it's very annoying if you Back/Forward frequently; Also, the short cut by keys are not looking a good choice for my situation. I want to show those 2 button in the IDE,or say, I prefer to click around with MICE! Digging around the settings in IDE and seemed not able to figure out how to achieve this SIMPLE goal. Any hints/help will be highly appreciated. To me, removing those simple buttons dramatically reduces the usability of the IDE! Thanks,<issue_comment>username_1: In my **Android Studio 3.0.1** installation, the buttons you seek are already in the main toolbar (see where the red arrow points): ![navigation buttons in AS 3.0.1 main toolbar](https://i.stack.imgur.com/q9fBl.png) To configure the contents of the toolbars, right-click over an open area in the toolbar panel and choose "Customize Menus and Toolbars..." from the context menu: ![AS 3.0.1 toolbar context menu](https://i.stack.imgur.com/pMz69.png) That will bring up a dialog where you can see the contents of the main toolbar and manipulate those contents: ![Menus and Toolbars dialog](https://i.stack.imgur.com/CRjOg.png) In **Android Studio 3.3 Canary 13**: Open View and then click Toolbar if it is unchecked. You will now get your toolbar with back and forward navigate buttons. [![View Menu](https://i.stack.imgur.com/fkVG4.png)](https://i.stack.imgur.com/fkVG4.png) Best of Luck! Upvotes: 7 [selected_answer]<issue_comment>username_2: For me it was simply going to the View tab and make sure Toolbar is checked. Voila! Friendly arrows back. credit to @cro comment [how to show Back/Forward buttons in Android Studio 3.0.1 IDE](https://stackoverflow.com/questions/49369494/how-to-show-back-forward-buttons-in-android-studio-3-0-1-ide#comment86807030_49371856) Upvotes: 3 <issue_comment>username_3: Click on "View" option in android studio(in top bar) and then click on "Toolbar" option. Upvotes: 5 <issue_comment>username_4: Let use shortcut, if you use `Ubuntu Linux`, go `setting` --> `keyboard` --> `navigation`, change shortcut `ctrl` + `alt` + `left/right` to other. Default on `AS` is `ctrl` + `alt` + `left` Upvotes: 0 <issue_comment>username_5: In Windows, just go to View> Appearance> Make sue Toolbar is checked. This is as per AS version 3.6.3 Upvotes: 2 <issue_comment>username_6: From Android Studio 4.0 you can go at the menu: View -> Appearance -> Toolbar Upvotes: 4 <issue_comment>username_7: Eesy. View -> Appearance -> Toolbar. For Android Studio 4.2 Upvotes: 2 <issue_comment>username_8: Simple step you can find in screenshot. [![enter image description here](https://i.stack.imgur.com/XbBhn.png)](https://i.stack.imgur.com/XbBhn.png) Just we need to enable toolbar Upvotes: 1 <issue_comment>username_9: This is missing atleast in **Android studio Girafee | 2022.3.1 Beta 5**. Hope they will add it in future updates. Added a feature request to google here in Google issue tracker. Please upvote if you want that feature. <https://issuetracker.google.com/287713653> **Update:** Now in **Girafee** the main toolbar is customizable in the new UI, you have to go to Settings > Appearance & Behavior > Menus and Toolbars. > Main Toolbar Left and here you can see **Back** and **Forward** button. [![enter image description here](https://i.stack.imgur.com/TYeTM.png)](https://i.stack.imgur.com/TYeTM.png) Upvotes: 1 <issue_comment>username_10: In Android Studio Giraffe(2023) and enabled new UI, If someone facing issue, follow below steps. `File --> Settings --> Appearance & Behavior --> Menus and Toolbars.` Add the navigation actions `(Main Menu > Navigate > Back and Forward)` to `Main Toolbar Right` or `Main Toolbar Left` Upvotes: 3 <issue_comment>username_11: For Android Studio Giraffe | 2022.3.1, You need to perform below steps: 1. Goto the **Preferences/Settings**. 2. Choose **Appearance & Behaviour** from the left menu: [![enter image description here](https://i.stack.imgur.com/HZ9Ev.png)](https://i.stack.imgur.com/HZ9Ev.png) 3. Select **Menus and Toolbars** and then open **Navigate**: [![enter image description here](https://i.stack.imgur.com/T9zvh.png)](https://i.stack.imgur.com/T9zvh.png) 4. Select **Back** and **Forward** buttons and *drag and drop* it to **Main Toolbar Left** or **Right**: [![enter image description here](https://i.stack.imgur.com/obXLq.gif)](https://i.stack.imgur.com/obXLq.gif) 5. Press **Apply** and then press **OK** to get the buttons. Upvotes: 2
2018/03/19
667
2,293
<issue_start>username_0: The testcase shall assert that the method `tagcache()` of a resource is called, to ensure the resource's tag cache is updated. I know that the method is called, yet the test fails because: ``` Expected: to be called at least once Actual: never called - unsatisfied and active ``` But why? ``` void TagModel::tagResource(Tag *tag, Resource *r) { if ( tag ){ tag->addToResource(r); } } void Tag::addToResource(Resource *r) { if ( !r ){ return; } addToResource(r->id()); r->tagcache()->add(this->id(),this->name()); } class ResourceMock : public Resource { public: MOCK_CONST_METHOD0(tagcache,TagCache *(void)); }; TEST(tagmodel,tag_resource){ TagModel m; Tag *t = m.createTag("tag"); ResourceMock mockres; EXPECT_CALL(mockres,tagcache()).Times(AtLeast(1)); m.tagResource(t,&mockres); } ``` Update: Resource definition ``` class Resource { mutable TagCache *tagcache_ = nullptr; public: virtual ~Resource(){ if ( tagcache_){ delete tagcache_; } } TagCache *tagcache() const{ if ( !tagcache_){ tagcache_ = new TagCache; } return tagcache_; } }; ```<issue_comment>username_1: `Resource::tagcache()` is not `virtual`, so ``` ResourceMock mockres; Resource *r = &mockres // [..] r->tagcache()->add(this->id(),this->name()); ``` would call the `tagcache` from base class, not the one from mock. Upvotes: 3 [selected_answer]<issue_comment>username_2: With these changes it is working. But the test itself is not good; Too many dependencies. I should mock the TagCache as well, and maybe move TagModel to a fixture. ``` TEST(tagmodel,tag_resource){ TagModel m; Tag *t = m.createTag("tag"); ResourceMock mockres; TagCache cache; EXPECT_CALL(mockres,tagCache()) .Times(AtLeast(1)) .WillOnce(Return(&cache)); // must not return a nullptr default value, because the 'tagResource' will call the cache. m.tagResource(t,&mockres); } mutable QSharedPointer tagcache\_; // Would like to add 'final' keyword, but the mock must be able to override this method. virtual TagCache \*tagCache() const{ if ( tagcache\_.isNull() ){ tagcache\_ = QSharedPointer(new TagCache); } return tagcache\_.data(); } ``` Upvotes: 0
2018/03/19
717
2,119
<issue_start>username_0: The Code I have so far only does for 1 index however I want it to read all existing indexes within the array. element array can carry many groups of numbers for example Array ["2,2,5" , "5,2,1"] contains 2 indexes [0] and [1] ``` var element = Array[0] let splitData = element.components(separatedBy: ",") // split data will always contain 3 values. var value1 = splitData[0] var value2 = splitData[1] var value3 = splitData[2] print("value 1 is : " + value1 + " value 2 is : " + value2 + " value 3 is: " + value3) ``` the output of this code when `Array ["2,2,5" , "5,2,1"]` is : ``` value 1 is : 2 value 2 is : 2 value 3 is : 5 ``` As the output suggests how can i iterate through all indexes of Array to display each of their 3 values. I want the output to be : ``` value 1 is : 2 value 2 is : 2 value 3 is : 5 value 1 is : 5 value 2 is : 2 value 3 is : 1 ``` I believe I need to use a for loop however I am unsure how to apply it to this. I am quite new to coding. Any help will be Appreciated<issue_comment>username_1: ``` for i in 0.. ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: here are two solutions you can use, depending on what is the best result for you. 1) If your goal is to transform an array like `["3,4,5", "5,6", "1", "4,9,0"]` into a **flattened** version `["3", "4", "5", "5", "6", "1", "4", "9", "0"]` you can do it easily with the `flatMap` operator in the following way: ``` let myArray = ["3,4,5", "5,6", "1", "4,9,0"] let flattenedArray = myArray.flatMap { $0.components(separatedBy: ",") } ``` Then you can iterate on it like every other array, ``` for (index, element) in myArray.enumerated() { print("value \(index) is: \(element)") } ``` 2) If you just want to iterate over it **and keep the levels** you can use the following code. ``` let myArray = ["3,4,5", "5,6", "1", "4,9,0"] for elementsSeparatedByCommas in myArray { let elements = elementsSeparatedByCommas.components(separatedBy: ",") print(elements.enumerated().map { "value \($0) is: \($1)" }.joined(separator: " ")) } ``` Hope that helps! Upvotes: 3
2018/03/19
527
1,568
<issue_start>username_0: I build an embedded linux with YOCTO for the KARO TX6S-8035 target. I use the Mfgtools-TX6-2018-01 tool to flash images into the board but when i boot the device i have the following error: **Kernel panic - not syncing: Requested init /linuxrc failed (error -2)**. How can i fix this? Here is the result of printenv from U-BOOT: [printenv](https://pastebin.com/7jvaM0wV) `And the serial output from the board:` [serial output](https://pastebin.com/amumfBvJ)<issue_comment>username_1: ``` for i in 0.. ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: here are two solutions you can use, depending on what is the best result for you. 1) If your goal is to transform an array like `["3,4,5", "5,6", "1", "4,9,0"]` into a **flattened** version `["3", "4", "5", "5", "6", "1", "4", "9", "0"]` you can do it easily with the `flatMap` operator in the following way: ``` let myArray = ["3,4,5", "5,6", "1", "4,9,0"] let flattenedArray = myArray.flatMap { $0.components(separatedBy: ",") } ``` Then you can iterate on it like every other array, ``` for (index, element) in myArray.enumerated() { print("value \(index) is: \(element)") } ``` 2) If you just want to iterate over it **and keep the levels** you can use the following code. ``` let myArray = ["3,4,5", "5,6", "1", "4,9,0"] for elementsSeparatedByCommas in myArray { let elements = elementsSeparatedByCommas.components(separatedBy: ",") print(elements.enumerated().map { "value \($0) is: \($1)" }.joined(separator: " ")) } ``` Hope that helps! Upvotes: 3