qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,671,399
<p>I want to create a function that labels the location of certain HTML tags (e.g., italics tags) in a string with respect to the locations of characters in a tagless version of the string. (I intend to use this label data to train a neural network for tag recovery from data that has had the tags stripped out.) The magic function I want to create is <code>label_italics()</code> in the below code.</p> <pre><code>$string = 'Disney movies: &lt;i&gt;Aladdin&lt;/i&gt;, &lt;i&gt;Beauty and the Beast&lt;/i&gt;.'; $string_all_tags_stripped_but_italics = strip_tags($string, '&lt;i&gt;'); // same as $string in this example $string_all_tags_stripped = strip_tags($string); // 'Disney movies: Aladdin, Beauty and the Beast.' $featr_string = $string_all_tags_stripped.' '; // Add a single space at the end $label_string = label_italics($string_all_tags_stripped_but_italics); echo $featr_string; // 'Disney movies: Aladdin, Beauty and the Beast. ' echo $label_string; // '0000000000000001000000101000000000000000000010' </code></pre> <p>If a character is supposed to have an <code>&lt;i&gt;</code> or <code>&lt;/i&gt;</code> tag immediately preceding it, it is labeled with a 1 in <code>$label_string</code>; otherwise, it is labeled with a 0 in <code>$label_string</code>. (I'm thinking I don't need to worry about the difference between <code>&lt;i&gt;</code> and <code>&lt;/i&gt;</code> because the recoverer will simply alternate between <code>&lt;i&gt;</code> and <code>&lt;/i&gt;</code> so as to maintain well-formed markup, but I'm open to reasons as to why I'm wrong about this.)</p> <p>I'm just not sure what the best way to create <code>label_italics()</code> is.</p> <p>I wrote this function that seems to work in most cases, but it also seems a little clunky and I'm posting here in hopes that there is a better way. (If this turns out to be the best way, the below function would be easily generalizable to any HTML tag passed in as a second argument to the function, which could be renamed <code>label_tag()</code>.)</p> <pre><code>function label_italics($stripped) { while ((stripos($stripped, '&lt;i&gt;') || stripos($stripped, '&lt;/i&gt;')) !== FALSE) { $position = stripos($stripped, '&lt;i&gt;'); if (is_numeric($position)) { for ($c = 0; $c &lt; $position; $c++) { $output .= '0'; } $output .= '1'; } $stripped = substr($stripped, $position + 4, NULL); $position = stripos($stripped, '&lt;/i&gt;'); if (is_numeric($position)) { for ($c = 0; $c &lt; $position; $c++) { $output .= '0'; } $output .= '1'; } $stripped = substr($stripped, $position + 5, NULL); } for ($c = 0; $c &lt;= strlen($stripped); $c++) { $output .= '0'; } return $output; } </code></pre> <p>The function produces bad output if the tags are surplus or the markup is badly formed in the input. For example, for the following input:</p> <pre><code>$string = 'Disney movies: &lt;i&gt;&lt;i&gt;Aladdin&lt;/i&gt;, &lt;i&gt;Beauty and the Beast&lt;/i&gt;.'; </code></pre> <p>The following misaligned output is given.</p> <pre><code>Disney movies: Aladdin, Beauty and the Beast. 0000000000000001000000000101000000000000000000010 </code></pre> <p>(I'm also open to reasons why I'm going about the creation of the label data all wrong.)</p>
[ { "answer_id": 74671586, "author": "KIKO Software", "author_id": 3986005, "author_profile": "https://Stackoverflow.com/users/3986005", "pm_score": 1, "selected": false, "text": "function label_italics($string) {\n return preg_replace(['/<i>/', '/<\\/i>/', '/[^#]/', '/##0/', '/#0/'], \n ['#', '#', '0', '2', '1'], $string);\n}\n <i> </i> # 0 ##0 2 #0 1 2 <i></i> # # function label_italics($string) {\n return preg_replace(['/[^<\\/i\\>]/', '/<i>/', '/<\\/i>/', '/i/', '/##0/', '/#0/'], \n ['0', '#', '#', '0', '2', '1'], $string . ' ');\n}\n" }, { "answer_id": 74671799, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": 0, "selected": false, "text": "function label_italics($stripped) {\n $output = '';\n $tag_open = '<i>';\n $tag_close = '</i>';\n\n // Find the positions of the <i> and </i> tags in the input string\n $open_positions = array_keys(str_word_count($stripped, 1, $tag_open));\n $close_positions = array_keys(str_word_count($stripped, 1, $tag_close));\n\n // Create a list of all the tag positions\n $tag_positions = array_merge($open_positions, $close_positions);\n sort($tag_positions);\n\n // Loop through each character in the input string\n for ($i = 0; $i < strlen($stripped); $i++) {\n // If the current character has a tag immediately preceding it, add a 1 to the output string\n if (in_array($i, $tag_positions)) {\n $output .= '1';\n } else {\n $output .= '0';\n }\n }\n return $output;\n}\n str_word_count" }, { "answer_id": 74680168, "author": "Robert K S", "author_id": 4541003, "author_profile": "https://Stackoverflow.com/users/4541003", "pm_score": 0, "selected": false, "text": "$label_string = mb_ereg_replace('#0', '1', mb_ereg_replace('(#)\\1+0', '1', mb_ereg_replace('\\/', '0', mb_ereg_replace('i', '0', mb_ereg_replace('<\\/i>', '#', mb_ereg_replace('<i>', '#', mb_ereg_replace('[^<\\/i\\>]', '0', mb_strtolower($featr_string))))))));" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541003/" ]
74,671,409
<p>I have strings stored in cells of a column in Excel that I would like to concatenate in several pieces, like sentences, with VBA. Here is an example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> </tr> </thead> <tbody> <tr> <td>Jack</td> </tr> <tr> <td>learns</td> </tr> <tr> <td>VBA</td> </tr> <tr> <td>Jack</td> </tr> <tr> <td>sits</td> </tr> <tr> <td>on</td> </tr> <tr> <td>a</td> </tr> <tr> <td>couch</td> </tr> <tr> <td>Jack</td> </tr> <tr> <td>wants</td> </tr> <tr> <td>chocolate</td> </tr> <tr> <td>cake</td> </tr> </tbody> </table> </div> <p>I finally found a way to concatenate <strong>all</strong> strings and save the sentences to a cell:</p> <pre><code>Sub JACK() Dim MP() As String Dim Str As String Dim i As Integer For i = 2 To 10 ReDim Preserve MP(i) MP(i) = Cells(i, 1).Value Next i Str = Join(MP) Cells(1, 2).Value = Str End Sub </code></pre> <p>But I would like to have the sentences that start with &quot;Jack&quot; and end with the row &quot;Jack - 1&quot;, each saved in <strong>seperate</strong> cells. Could anyone help me???</p> <p>Thank you so much!</p>
[ { "answer_id": 74671586, "author": "KIKO Software", "author_id": 3986005, "author_profile": "https://Stackoverflow.com/users/3986005", "pm_score": 1, "selected": false, "text": "function label_italics($string) {\n return preg_replace(['/<i>/', '/<\\/i>/', '/[^#]/', '/##0/', '/#0/'], \n ['#', '#', '0', '2', '1'], $string);\n}\n <i> </i> # 0 ##0 2 #0 1 2 <i></i> # # function label_italics($string) {\n return preg_replace(['/[^<\\/i\\>]/', '/<i>/', '/<\\/i>/', '/i/', '/##0/', '/#0/'], \n ['0', '#', '#', '0', '2', '1'], $string . ' ');\n}\n" }, { "answer_id": 74671799, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": 0, "selected": false, "text": "function label_italics($stripped) {\n $output = '';\n $tag_open = '<i>';\n $tag_close = '</i>';\n\n // Find the positions of the <i> and </i> tags in the input string\n $open_positions = array_keys(str_word_count($stripped, 1, $tag_open));\n $close_positions = array_keys(str_word_count($stripped, 1, $tag_close));\n\n // Create a list of all the tag positions\n $tag_positions = array_merge($open_positions, $close_positions);\n sort($tag_positions);\n\n // Loop through each character in the input string\n for ($i = 0; $i < strlen($stripped); $i++) {\n // If the current character has a tag immediately preceding it, add a 1 to the output string\n if (in_array($i, $tag_positions)) {\n $output .= '1';\n } else {\n $output .= '0';\n }\n }\n return $output;\n}\n str_word_count" }, { "answer_id": 74680168, "author": "Robert K S", "author_id": 4541003, "author_profile": "https://Stackoverflow.com/users/4541003", "pm_score": 0, "selected": false, "text": "$label_string = mb_ereg_replace('#0', '1', mb_ereg_replace('(#)\\1+0', '1', mb_ereg_replace('\\/', '0', mb_ereg_replace('i', '0', mb_ereg_replace('<\\/i>', '#', mb_ereg_replace('<i>', '#', mb_ereg_replace('[^<\\/i\\>]', '0', mb_strtolower($featr_string))))))));" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677698/" ]
74,671,420
<p>The context doesn't matter too much, but I came across the problem that while trying to pop <code>dict</code> objects from a <code>list</code>, it wouldn't delete all of them. I'm doing this to filter for certain values in the <code>dict</code> objects, and I was left with things that should have been removed. Just to see what would happen, I tried deleting every item in the <code>list</code> called <code>accepted_auctions</code> (shown below), but it did not work.</p> <pre><code>for auction in accepted_auctions: accepted_auctions.pop(accepted_auctions.index(auction)) print(len(accepted_auctions)) </code></pre> <p>When I tested this code, <code>print(len(accepted_auctions))</code> printed <code>44</code> into the console.</p> <p>What am I doing wrong?</p>
[ { "answer_id": 74671460, "author": "blackeyeaquarius", "author_id": 20677128, "author_profile": "https://Stackoverflow.com/users/20677128", "pm_score": 3, "selected": true, "text": "# Create an empty list to store the items that we want to keep\nfiltered_auctions = []\n\n# Iterate over the items in the list\nfor auction in accepted_auctions:\n # Check if the item meets the criteria for being kept\n if some_condition(auction):\n # If it does, append it to the filtered list\n filtered_auctions.append(auction)\n\n# Replace the original list with the filtered list\naccepted_auctions = filtered_auctions\n # Keep looping until the list is empty\nwhile accepted_auctions:\n # Pop the first item from the list\n auction = accepted_auctions.pop(0)\n\n # Check if the item meets the criteria for being kept\n if some_condition(auction):\n # If it does, append it to the filtered list\n filtered_auctions.append(auction)\n\n# Replace the original list with the filtered list\naccepted_auctions = filtered_auctions\n" }, { "answer_id": 74671474, "author": "Samwise", "author_id": 3799759, "author_profile": "https://Stackoverflow.com/users/3799759", "pm_score": 2, "selected": false, "text": "accepted_auctions = [a for a in accepted_auctions if something(a)]\n >>> nums = list(range(10))\n>>> nums\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> nums = [n for n in nums if n % 2]\n>>> nums\n[1, 3, 5, 7, 9]\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18106922/" ]
74,671,424
<p>I have decided to remove Visual studio; Because it does not auto-fill for me when I write the code, so I want to know if I delete it will that will affect the previous C# files I wrote in Unity !?</p> <p>I haven't deleted it yet. I also went into the program settings to solve the autofill problem but to no avail.</p>
[ { "answer_id": 74671460, "author": "blackeyeaquarius", "author_id": 20677128, "author_profile": "https://Stackoverflow.com/users/20677128", "pm_score": 3, "selected": true, "text": "# Create an empty list to store the items that we want to keep\nfiltered_auctions = []\n\n# Iterate over the items in the list\nfor auction in accepted_auctions:\n # Check if the item meets the criteria for being kept\n if some_condition(auction):\n # If it does, append it to the filtered list\n filtered_auctions.append(auction)\n\n# Replace the original list with the filtered list\naccepted_auctions = filtered_auctions\n # Keep looping until the list is empty\nwhile accepted_auctions:\n # Pop the first item from the list\n auction = accepted_auctions.pop(0)\n\n # Check if the item meets the criteria for being kept\n if some_condition(auction):\n # If it does, append it to the filtered list\n filtered_auctions.append(auction)\n\n# Replace the original list with the filtered list\naccepted_auctions = filtered_auctions\n" }, { "answer_id": 74671474, "author": "Samwise", "author_id": 3799759, "author_profile": "https://Stackoverflow.com/users/3799759", "pm_score": 2, "selected": false, "text": "accepted_auctions = [a for a in accepted_auctions if something(a)]\n >>> nums = list(range(10))\n>>> nums\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> nums = [n for n in nums if n % 2]\n>>> nums\n[1, 3, 5, 7, 9]\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677692/" ]
74,671,429
<p>I have such .txt file:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Field</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>First</td> <td>1</td> </tr> <tr> <td>Second</td> <td>alfa</td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td>First</td> <td>23</td> </tr> <tr> <td>Second</td> <td>beta</td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td>First</td> <td>55</td> </tr> <tr> <td>Second</td> <td>omega</td> </tr> </tbody> </table> </div> <p>I need to read and transform this file to get data like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>First</th> <th>Second</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>alfa</td> </tr> <tr> <td>23</td> <td>beta</td> </tr> <tr> <td>55</td> <td>omega</td> </tr> </tbody> </table> </div> <p>I start with this:</p> <pre><code>file = './data.txt' df = pd.read_csv(file, sep='\t',header=None, skiprows=89, skipfooter=11, engine='python') df = df.pivot(values=1, columns=0) </code></pre> <p>but it looks as I need to generate some indexes otherwise my pivoted table looks not very well</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>First</th> <th>Second</th> </tr> </thead> <tbody> <tr> <td>1</td> <td></td> </tr> <tr> <td></td> <td>alfa</td> </tr> <tr> <td>23</td> <td></td> </tr> <tr> <td></td> <td>beta</td> </tr> <tr> <td>55</td> <td></td> </tr> <tr> <td></td> <td>omega</td> </tr> </tbody> </table> </div> <p>Is any other solution hot to read that data and get the results that I need?</p>
[ { "answer_id": 74673261, "author": "Andrea S.", "author_id": 14895961, "author_profile": "https://Stackoverflow.com/users/14895961", "pm_score": 0, "selected": false, "text": "import pandas as pd\n\nfile = './data.txt'\ndf = pd.read_csv(file, sep='\\t',header=0, engine='python')\ndf = df.pivot(values='Value', columns='Field')\n\n# for each column on the dataframe, sort the value and ignore the index\nfor col in df.columns:\n df[col] = df[col].sort_values(ignore_index=True)\n\n# drop NaN\ndf.dropna(axis=0, how='all', inplace=True)\n\n# Show dataframe\nprint(df)\n" }, { "answer_id": 74673316, "author": "Jason Baker", "author_id": 3249641, "author_profile": "https://Stackoverflow.com/users/3249641", "pm_score": 2, "selected": true, "text": "df = (\n df.assign(CommonKeys=df.groupby(\"Field\").cumcount())\n .pivot(index=\"CommonKeys\", columns=\"Field\", values=\"Value\")\n .reset_index(drop=True)\n .rename_axis(None, axis=1)\n)\n\nprint(df)\n First Second\n0 1 alfa\n1 23 beta\n2 55 omega\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7347438/" ]
74,671,432
<p>I want to change the font size and color of the a when I hover over p. It is not working. Probably there is a simple solution, but I am struggling with this since a few hours.</p> <p>If anyone has not to complicated links related to this topic I also would be happy</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot; /&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot; /&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt; &lt;title&gt;Document&lt;/title&gt; &lt;style&gt; p:hover div nav a { color: blue; font-size: 22px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;nav&gt; &lt;p&gt;Ceramics&lt;/p&gt; &lt;a href=&quot;&quot;&gt;One&lt;/a&gt; &lt;a href=&quot;&quot;&gt;Two&lt;/a&gt; &lt;a href=&quot;&quot;&gt;Three&lt;/a&gt; &lt;/nav&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 74673261, "author": "Andrea S.", "author_id": 14895961, "author_profile": "https://Stackoverflow.com/users/14895961", "pm_score": 0, "selected": false, "text": "import pandas as pd\n\nfile = './data.txt'\ndf = pd.read_csv(file, sep='\\t',header=0, engine='python')\ndf = df.pivot(values='Value', columns='Field')\n\n# for each column on the dataframe, sort the value and ignore the index\nfor col in df.columns:\n df[col] = df[col].sort_values(ignore_index=True)\n\n# drop NaN\ndf.dropna(axis=0, how='all', inplace=True)\n\n# Show dataframe\nprint(df)\n" }, { "answer_id": 74673316, "author": "Jason Baker", "author_id": 3249641, "author_profile": "https://Stackoverflow.com/users/3249641", "pm_score": 2, "selected": true, "text": "df = (\n df.assign(CommonKeys=df.groupby(\"Field\").cumcount())\n .pivot(index=\"CommonKeys\", columns=\"Field\", values=\"Value\")\n .reset_index(drop=True)\n .rename_axis(None, axis=1)\n)\n\nprint(df)\n First Second\n0 1 alfa\n1 23 beta\n2 55 omega\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20554918/" ]
74,671,472
<p>how can you ensure URL you receive from users is a valid url and not just a <a href="http://nothing.com" rel="nofollow noreferrer">http://nothing.com</a></p> <p>my code looks like this:</p> <pre><code>String urlFromUser = getUrlFromUser(); // might return: http://www.notARealSite.com URL url = new URL(urlFromUser); // this might fail URLConnection urlConnection = url.openConnection(); </code></pre> <p>and try catch is not enough, i want to make sure the site is real</p>
[ { "answer_id": 74671486, "author": "Yiğit", "author_id": 5549860, "author_profile": "https://Stackoverflow.com/users/5549860", "pm_score": 1, "selected": false, "text": "String urlFromUser = getUrlFromUser(); // might return: http://www.notARealSite.com\n\ntry {\n URL url = new URL(urlFromUser);\n URLConnection urlConnection = url.openConnection();\n // If we reached this point, it means the URL is valid and we can use the connection\n} catch (MalformedURLException e) {\n // The URL is not valid. You can either show an error message to the user or \n // try to fix the URL and create a new URL object.\n}\n String urlFromUser = getUrlFromUser(); // might return: http://www.notARealSite.com\n\ntry {\n URL url = new URL(urlFromUser);\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n int responseCode = connection.getResponseCode();\n\n if (responseCode >= 200 && responseCode < 300) {\n // The connection was successful and the URL is valid\n } else {\n // The connection was not successful. The URL might be invalid or there might be\n // some other issue with the connection (e.g. the server is down).\n }\n} catch (MalformedURLException e) {\n // The URL is not valid. You can either show an error message to the user or \n // try to fix the URL and create a new URL object.\n} catch (IOException e) {\n // There was an IO error while trying to open the connection. This could be caused by\n // various factors, such as network issues or issues with the server.\n}\n" }, { "answer_id": 74671512, "author": "ThisIsMe", "author_id": 20671106, "author_profile": "https://Stackoverflow.com/users/20671106", "pm_score": -1, "selected": true, "text": "if(new InetSocketAddress(urlFromUser, 80).isUnresolved()) {\n // URL is a not a valid server address\n}\nelse {\n // URL is valid\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677777/" ]
74,671,475
<p>I'm struggling with some Python homework.</p> <p>I'm really new to Python, and coding in general. I have really basic knowledge in Python, and somewhat acceptable level in JavaScript.</p> <p>My issue: I have to make a graph to represent these two functions:</p> <pre><code>distance = (x**2/2 - np.cos(5*x) - 7) speed = (x + 5*np.sin(5*x)) </code></pre> <p>Between the timestamps 3 and 6 (inclusive)</p> <p>I know I have to use Pandas to make a DataFrame, I know I have to use MatPlotLib to make the actual plot, and I have to use Numpy for the math to work, but I can't get the math to be recognised as mathematical functions because I simply don't know how.</p> <p>This is what the graph should look like: <a href="https://i.stack.imgur.com/LEuuk.png" rel="nofollow noreferrer">Graph for Distance and Speed over Time</a></p> <p>This is what my code looks for now:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np x = 10 time = [3, 6] distance = (x**2/2 - np.cos(5*x) - 7) speed = (x + 5*np.sin(5*x)) values = {'Distance': distance, 'Speed': speed, 'Time': time} df = pd.DataFrame(data= values) df.plot(title='Distance and speed', xlabel='Time (hours)', ylabel='Distance (km) / Speed (km/h)', x='Time') plt.show() </code></pre> <p>x = 10 I know shouldn't be included, but since I'm missing the part that makes the math work, I have to include it to make it &quot;work&quot; and not get an error.</p> <p>I have a vague idea that using Numpy is the answer to my problem, but I don't know how (for now, hopefully).</p> <p>How wrong am I? Can anyone help me?</p>
[ { "answer_id": 74671486, "author": "Yiğit", "author_id": 5549860, "author_profile": "https://Stackoverflow.com/users/5549860", "pm_score": 1, "selected": false, "text": "String urlFromUser = getUrlFromUser(); // might return: http://www.notARealSite.com\n\ntry {\n URL url = new URL(urlFromUser);\n URLConnection urlConnection = url.openConnection();\n // If we reached this point, it means the URL is valid and we can use the connection\n} catch (MalformedURLException e) {\n // The URL is not valid. You can either show an error message to the user or \n // try to fix the URL and create a new URL object.\n}\n String urlFromUser = getUrlFromUser(); // might return: http://www.notARealSite.com\n\ntry {\n URL url = new URL(urlFromUser);\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n int responseCode = connection.getResponseCode();\n\n if (responseCode >= 200 && responseCode < 300) {\n // The connection was successful and the URL is valid\n } else {\n // The connection was not successful. The URL might be invalid or there might be\n // some other issue with the connection (e.g. the server is down).\n }\n} catch (MalformedURLException e) {\n // The URL is not valid. You can either show an error message to the user or \n // try to fix the URL and create a new URL object.\n} catch (IOException e) {\n // There was an IO error while trying to open the connection. This could be caused by\n // various factors, such as network issues or issues with the server.\n}\n" }, { "answer_id": 74671512, "author": "ThisIsMe", "author_id": 20671106, "author_profile": "https://Stackoverflow.com/users/20671106", "pm_score": -1, "selected": true, "text": "if(new InetSocketAddress(urlFromUser, 80).isUnresolved()) {\n // URL is a not a valid server address\n}\nelse {\n // URL is valid\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677721/" ]
74,671,476
<p>How to write a predicate sum 3 max values in list? max3(L,X)</p> <p>Example:</p> <pre><code>max3([1,7,9,3,5],X). X = 21. </code></pre>
[ { "answer_id": 74671486, "author": "Yiğit", "author_id": 5549860, "author_profile": "https://Stackoverflow.com/users/5549860", "pm_score": 1, "selected": false, "text": "String urlFromUser = getUrlFromUser(); // might return: http://www.notARealSite.com\n\ntry {\n URL url = new URL(urlFromUser);\n URLConnection urlConnection = url.openConnection();\n // If we reached this point, it means the URL is valid and we can use the connection\n} catch (MalformedURLException e) {\n // The URL is not valid. You can either show an error message to the user or \n // try to fix the URL and create a new URL object.\n}\n String urlFromUser = getUrlFromUser(); // might return: http://www.notARealSite.com\n\ntry {\n URL url = new URL(urlFromUser);\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n int responseCode = connection.getResponseCode();\n\n if (responseCode >= 200 && responseCode < 300) {\n // The connection was successful and the URL is valid\n } else {\n // The connection was not successful. The URL might be invalid or there might be\n // some other issue with the connection (e.g. the server is down).\n }\n} catch (MalformedURLException e) {\n // The URL is not valid. You can either show an error message to the user or \n // try to fix the URL and create a new URL object.\n} catch (IOException e) {\n // There was an IO error while trying to open the connection. This could be caused by\n // various factors, such as network issues or issues with the server.\n}\n" }, { "answer_id": 74671512, "author": "ThisIsMe", "author_id": 20671106, "author_profile": "https://Stackoverflow.com/users/20671106", "pm_score": -1, "selected": true, "text": "if(new InetSocketAddress(urlFromUser, 80).isUnresolved()) {\n // URL is a not a valid server address\n}\nelse {\n // URL is valid\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20453757/" ]
74,671,484
<p>It seems that once every other week I have the same issue where my React Native project stops building and won't open in Xcode, and I wanted to know what some fixes could be for this. When I try and build in Visual Studio Code the app gets stuck at the <code>⠇ Building the app</code> message. And when I try opening the workspace in Xcode, Xcode stops responding and it gets stuck on the spinning rainbow wheel. For some reason, <code>npx react-native start</code> works just fine, the issue occurs when using <code>npx react-native run-ios</code>.</p> <p>When this happens it takes me hours to troubleshoot and I can't find a consistent fix for this issue. Does anyone have experience with this and know a solution?</p>
[ { "answer_id": 74671486, "author": "Yiğit", "author_id": 5549860, "author_profile": "https://Stackoverflow.com/users/5549860", "pm_score": 1, "selected": false, "text": "String urlFromUser = getUrlFromUser(); // might return: http://www.notARealSite.com\n\ntry {\n URL url = new URL(urlFromUser);\n URLConnection urlConnection = url.openConnection();\n // If we reached this point, it means the URL is valid and we can use the connection\n} catch (MalformedURLException e) {\n // The URL is not valid. You can either show an error message to the user or \n // try to fix the URL and create a new URL object.\n}\n String urlFromUser = getUrlFromUser(); // might return: http://www.notARealSite.com\n\ntry {\n URL url = new URL(urlFromUser);\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n int responseCode = connection.getResponseCode();\n\n if (responseCode >= 200 && responseCode < 300) {\n // The connection was successful and the URL is valid\n } else {\n // The connection was not successful. The URL might be invalid or there might be\n // some other issue with the connection (e.g. the server is down).\n }\n} catch (MalformedURLException e) {\n // The URL is not valid. You can either show an error message to the user or \n // try to fix the URL and create a new URL object.\n} catch (IOException e) {\n // There was an IO error while trying to open the connection. This could be caused by\n // various factors, such as network issues or issues with the server.\n}\n" }, { "answer_id": 74671512, "author": "ThisIsMe", "author_id": 20671106, "author_profile": "https://Stackoverflow.com/users/20671106", "pm_score": -1, "selected": true, "text": "if(new InetSocketAddress(urlFromUser, 80).isUnresolved()) {\n // URL is a not a valid server address\n}\nelse {\n // URL is valid\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17284184/" ]
74,671,511
<p>I've been writing a script to copy some data from an input sheet to a database to keep track of some data. I've managed to successfully write the code for linear arrays (only one row) but when I try to copy an entire 15x15 cells range I get an error stating the parameters are not correct (suggesting the dimension of the arrays are not correct) but I can't seem to understand why.</p> <p>I tried both copying directly the entire 15x15 range and creating a for loop to copy row by row 15 times but I can't mangage to make it work.</p> <p>Here is the main structure:</p> <pre><code> // active spreadsheet and source + target sheets const activeSheet = SpreadsheetApp.getActiveSpreadsheet(); const srcSheet = activeSheet.getSheetByName('Data Entry'); const dstTOTSheet = activeSheet.getSheetByName('DataBaseTOT'); var firstEmptyRowTOT = dstTOTSheet.getLastRow()+1; </code></pre> <p>For loop test:</p> <pre><code> for (var i=0; i=14;i=i+1) { // source cells var RoundInfo = srcSheet.getRange(10+i, 2, 1, 15); // 15x15 B10:P24 // target cells var dstTOTRoundInfo = dstTOTSheet.getRange(firstEmptyRowTOT + i, 21, 1, 15); // I am starting from column 21 because of some other data // set value dstTOTRoundInfo.setValues(RoundInfo); } </code></pre> <p>Direct 15x15 test:</p> <pre><code>// source cells var RoundInfo = srcSheet.getRange(&quot;B10:P24&quot;); // 15x15 B10:P24 // target cells var dstTOTRoundInfo = dstTOTSheet.getRange(firstEmptyRowTOT, 21, 15, 15); // set value dstTOTRoundInfo.setValues(RoundInfo); </code></pre>
[ { "answer_id": 74671486, "author": "Yiğit", "author_id": 5549860, "author_profile": "https://Stackoverflow.com/users/5549860", "pm_score": 1, "selected": false, "text": "String urlFromUser = getUrlFromUser(); // might return: http://www.notARealSite.com\n\ntry {\n URL url = new URL(urlFromUser);\n URLConnection urlConnection = url.openConnection();\n // If we reached this point, it means the URL is valid and we can use the connection\n} catch (MalformedURLException e) {\n // The URL is not valid. You can either show an error message to the user or \n // try to fix the URL and create a new URL object.\n}\n String urlFromUser = getUrlFromUser(); // might return: http://www.notARealSite.com\n\ntry {\n URL url = new URL(urlFromUser);\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n int responseCode = connection.getResponseCode();\n\n if (responseCode >= 200 && responseCode < 300) {\n // The connection was successful and the URL is valid\n } else {\n // The connection was not successful. The URL might be invalid or there might be\n // some other issue with the connection (e.g. the server is down).\n }\n} catch (MalformedURLException e) {\n // The URL is not valid. You can either show an error message to the user or \n // try to fix the URL and create a new URL object.\n} catch (IOException e) {\n // There was an IO error while trying to open the connection. This could be caused by\n // various factors, such as network issues or issues with the server.\n}\n" }, { "answer_id": 74671512, "author": "ThisIsMe", "author_id": 20671106, "author_profile": "https://Stackoverflow.com/users/20671106", "pm_score": -1, "selected": true, "text": "if(new InetSocketAddress(urlFromUser, 80).isUnresolved()) {\n // URL is a not a valid server address\n}\nelse {\n // URL is valid\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18029702/" ]
74,671,516
<p>I can't seem to figure out how to print out what the user has entered for their password once their finished answering the questions.</p> <p>I want to use 4 different for loops for upperCase, lowerCase, numbers, symbols,based on what the user has entered. If anyone has any different ideas please share. It would be a great help. I'm new to programming.</p> <p>Here is what I have so far</p> <pre><code>string upperCase = (&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;) ; string lowerCase = (&quot;abcdefghijklmnopqrstuvwxyz&quot;); string numbers = (&quot;1234567890&quot; ); string specChac = (&quot;!@#$%^&amp;*():&lt;&gt;?/&quot;); string randomPassword = upperCase + lowerCase + numbers + specChac; string allPasswords = &quot;randomPassword&quot;; Random rnd = new Random(); Console.WriteLine(&quot;Welocme to the C# password generator! &quot;); Console.WriteLine(&quot;----------------------------------------&quot;); Console.WriteLine(&quot;How many uppercase letters would you like in your password ?&quot;); int upperAmount = int.Parse(Console.ReadLine()); Console.WriteLine(&quot;How many lowercase letters would you like in your password ?&quot;); int lowerAmount = int.Parse(Console.ReadLine()); Console.WriteLine(&quot;How many numbers would you like in your password ?&quot;); int numAmount = int.Parse(Console.ReadLine()); Console.WriteLine(&quot;How many special characters would you like in your password?&quot;); int charAmount = int.Parse(Console.ReadLine()); </code></pre>
[ { "answer_id": 74671549, "author": "Rodrigo Munoz", "author_id": 14694310, "author_profile": "https://Stackoverflow.com/users/14694310", "pm_score": 2, "selected": false, "text": "// Create a random number generator\nvar random = new Random();\n\n// Create arrays of characters to use in the password\n// you can use your own arrays instead of these.\nvar upperChars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".ToCharArray();\nvar lowerChars = \"abcdefghijklmnopqrstuvwxyz\".ToCharArray();\nvar numChars = \"0123456789\".ToCharArray();\nvar specialChars = \"!@#$%^&*()\".ToCharArray();\n\n// Generate the password\nvar password = Enumerable.Empty<char>();\npassword = password.Concat(Enumerable.Range(0, upperAmount).Select(i => upperChars[random.Next(upperChars.Length)]));\npassword = password.Concat(Enumerable.Range(0, lowerAmount).Select(i => lowerChars[random.Next(lowerChars.Length)]));\npassword = password.Concat(Enumerable.Range(0, numAmount).Select(i => numChars[random.Next(numChars.Length)]));\npassword = password.Concat(Enumerable.Range(0, charAmount).Select(i => specialChars[random.Next(specialChars.Length)]));\n\n// Shuffle the password\npassword = password.OrderBy(c => random.Next());\n\n// Convert the password to a string and display it\nConsole.WriteLine(string.Join(\"\", password));\n\n\n" }, { "answer_id": 74675679, "author": "Max", "author_id": 13523921, "author_profile": "https://Stackoverflow.com/users/13523921", "pm_score": 0, "selected": false, "text": "internal static class RandomPswd\n{\n const int CHAR_UPPER_MIN = 0x41;\n const int CHAR_UPPER_MAX = 0x5a;\n const int CHAR_LOWER_MIN = 0x61;\n const int CHAR_LOWER_MAX = 0x7a;\n const int CHAR_DIGIT_MIN = 0x30;\n const int CHAR_DIGIT_MAX = 0x39;\n const int CHAR_SYMBL_MIN = 0x21;\n const int CHAR_SYMBL_MAX = 0x2f;\n\n\n private static void Shuffle(char[] buffer)\n {\n int seed = GetSeed();\n Random r = new Random(seed);\n\n int n = buffer.Length;\n while (n > 1) {\n int k = r.Next(n--);\n char t = buffer[n];\n buffer[n] = buffer[k];\n buffer[k] = t;\n }\n }\n\n\n private static int GetSeed()\n {\n unchecked\n {\n int hash = (int)DateTime.Now.Ticks * 7302013 ^ Environment.UserName.GetHashCode();\n hash = hash * 7302013 ^ (CHAR_UPPER_MIN.GetHashCode());\n hash = hash * 7302013 ^ (CHAR_UPPER_MAX.GetHashCode());\n hash = hash * 7302013 ^ (CHAR_LOWER_MIN.GetHashCode());\n hash = hash * 7302013 ^ (CHAR_LOWER_MAX.GetHashCode());\n hash = hash * 7302013 ^ (CHAR_DIGIT_MIN.GetHashCode());\n hash = hash * 7302013 ^ (CHAR_DIGIT_MAX.GetHashCode());\n hash = hash * 7302013 ^ (CHAR_SYMBL_MIN.GetHashCode());\n hash = hash * 7302013 ^ (CHAR_SYMBL_MAX.GetHashCode());\n return hash;\n } \n }\n\n public static string Create(int upper, int lower, int digits, int symbols)\n {\n char[] upperChars = new char[upper];\n char[] lowerChars = new char[lower];\n char[] digitChars = new char[digits];\n char[] symblChars = new char[symbols];\n\n int seed = GetSeed();\n Random r = new Random(seed);\n for (int i=0; i<upper; i++) {\n upperChars[i] = (char)r.Next(CHAR_UPPER_MIN, CHAR_UPPER_MAX);\n }\n\n seed = GetSeed();\n r = new Random(seed);\n for (int i = 0; i < lower; i++) {\n lowerChars[i] = (char)r.Next(CHAR_LOWER_MIN, CHAR_LOWER_MAX);\n }\n\n seed = GetSeed();\n r = new Random(seed);\n for (int i = 0; i < digits; i++) {\n digitChars[i] = (char)r.Next(CHAR_DIGIT_MIN, CHAR_DIGIT_MAX);\n }\n\n seed = GetSeed();\n r = new Random(seed);\n for (int i=0; i< symbols; i++) {\n symblChars[i] = (char)r.Next(CHAR_SYMBL_MIN, CHAR_SYMBL_MAX);\n }\n\n char[] buf = new char[upper + lower + digits + symbols];\n upperChars.CopyTo(buf, 0);\n lowerChars.CopyTo(buf, upper);\n digitChars.CopyTo(buf, upper + lower);\n symblChars.CopyTo(buf, upper + lower + digits);\n Shuffle(buf);\n\n return new string(buf);\n }\n}\n \n \nstatic void Main()\n{\n var pw = RandomPswd.Create(12, 8, 7, 5);\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11879103/" ]
74,671,532
<p>I've observed performance differences based on the location of my instantiated <code>StateObject</code>. Specifically, I noticed that when my top-level <code>View</code> owns the <code>StateObject</code>, my app's usage on the main thread decreases by ~5%. For some reason, instantiating this <code>StateObject</code> in a SwiftUI <code>App</code> is less performant. My expectation is that performance would be identical since nothing else changed.</p> <p>While that 5% might not seem like much, the result might be 10-15% higher CPU utilization on some devices. It's worth nothing that in my <code>StateObject</code>, I've defined a <code>CADisplayLink</code> which runs a callback on every frame, so this is where most of the compute gets used.</p> <p>For some reason, this:</p> <pre class="lang-swift prettyprint-override"><code>@main struct MyApp: App { var body: some Scene { WindowGroup { MyView() } } } struct MyView: View { @StateObject var someStateObject = SomeStateObject() var body: some View { Text(&quot;Hello World&quot;) } } </code></pre> <p>Is more performant than this:</p> <pre class="lang-swift prettyprint-override"><code>@main struct MyApp: App { @StateObject var someStateObject = SomeStateObject() var body: some Scene { WindowGroup { MyView() } } } struct MyView: View { var body: some View { Text(&quot;Hello World&quot;) } } </code></pre> <p>Is there something about SwiftUI's <code>App</code> that would create these performance differences?</p>
[ { "answer_id": 74671575, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": -1, "selected": false, "text": "StateObject View" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7396787/" ]
74,671,577
<p>I made a function that is being called recursively, and the condition for it to keep being called is a user input.</p> <p>The recursion is working but the final value of the variable is being returned as None. I am a beginner at Python and i am trying to learn Functions and Recursion before going to Classes, OOP, Wrappers, etc.</p> <p>Here is my code:</p> <p>Main Py:</p> <pre><code>import funcoes_moeda def switch(valor): case = int(input('Escolha uma opcao... (0 para encerrar) : ')) if case == 1: valor = funcoes_moeda.aumentar(valor) print('Valor aumentado: {}'.format(valor)) switch(valor) elif case == 2: pass elif case == 3: pass elif case == 4: pass else: return valor valor = float(input('Insira o valor: ')) print(&quot;Escolha a funcao a ser aplicada no valor inserido: \n&quot; \ &quot;1 - Aumentar Valor \n&quot; \ &quot;2 - Diminuir Valor \n&quot; \ &quot;3 - Dobrar Valor \n&quot; \ &quot;4 - Dividir Valor \n&quot; \ &quot;0 - Encerrar o Prorama&quot; ) valor = switch(valor) print('Funcao foi aplicada. O valor final ficou: {}'.format(valor)) </code></pre> <p>Imported Functions:</p> <pre><code>def aumentar(valor): quantia_aumentada = float(input('Insira a quantidade que voce deseja acrescentar: ')) valor += quantia_aumentada return valor def diminuir(): pass def dobro(): pass def metade(): pass </code></pre> <p>When i tried executing this, what i got was:</p> <blockquote> <p>Insira o valor: 100.00</p> <p>Escolha a funcao a ser aplicada no valor inserido:</p> <p>1 - Aumentar Valor</p> <p>2 - Diminuir Valor</p> <p>3 - Dobrar Valor</p> <p>4 - Dividir Valor</p> <p>0 - Encerrar o Prorama</p> <p>Escolha uma opcao... (0 para encerrar) : 1</p> <p>Insira a quantidade que voce deseja acrescentar: 100.00</p> <p>Valor aumentado: 200.0</p> <p>Escolha uma opcao... (0 para encerrar) : 1</p> <p>Insira a quantidade que voce deseja acrescentar: 100.00</p> <p>Valor aumentado: 300.0</p> <p>Escolha uma opcao... (0 para encerrar) : 0</p> <p>Funcao foi aplicada. O valor final ficou: <em>None</em></p> </blockquote> <p>For a test case, you can use:</p> <p>Chose 100.00, option 1 (2 times is enough), increment 100.00 each call. Expected output: Current value = 300.00 (Because 100 + 100 + 100)</p> <p>But i got None at the last print...</p> <p>Please. What am i doing wrong??? :( Thank you for all the help.</p> <p>PS: I tried going through the following answers, but i was not able to solve this problem because the explanation was for the problems in the question, and i found it was a litle different than mine..</p> <p>1 &gt; <a href="https://stackoverflow.com/questions/59797559/recursive-function-returning-none">Recursive function returning none</a> - Dint understand.</p> <p>2 &gt; <a href="https://stackoverflow.com/questions/47385933/python-recursive-function-returning-none-instead-of-string">python recursive function returning none instead of string</a> - This is treating a CSV file.</p>
[ { "answer_id": 74671652, "author": "Gerg", "author_id": 20677932, "author_profile": "https://Stackoverflow.com/users/20677932", "pm_score": 2, "selected": true, "text": "def switch(valor):\n case = int(input('Escolha uma opcao... (0 para encerrar) : '))\n if case == 1:\n valor = funcoes_moeda.aumentar(valor)\n print('Valor aumentado: {}'.format(valor))\n switch(valor)\n\n elif case == 2:\n pass\n elif case == 3:\n pass\n elif case == 4:\n pass\n else:\n return valor\n\n # Return the value of valor when case is 0\n return valor\n" }, { "answer_id": 74671672, "author": "nokla", "author_id": 20258214, "author_profile": "https://Stackoverflow.com/users/20258214", "pm_score": 0, "selected": false, "text": "import funcoes_moeda\n\ndef switch(valor):\n case = int(input('Escolha uma opcao... (0 para encerrar) : '))\n if case == 1:\n valor = funcoes_moeda.aumentar(valor)\n print('Valor aumentado: {}'.format(valor))\n return switch(valor)\n\n elif case == 2:\n pass\n elif case == 3:\n pass\n elif case == 4:\n pass\n else:\n return valor\n\nvalor = float(input('Insira o valor: '))\nprint(\"Escolha a funcao a ser aplicada no valor inserido: \\n\" \\\n \"1 - Aumentar Valor \\n\" \\\n \"2 - Diminuir Valor \\n\" \\\n \"3 - Dobrar Valor \\n\" \\\n \"4 - Dividir Valor \\n\" \\\n \"0 - Encerrar o Prorama\"\n )\n\nvalor = switch(valor)\n\nprint('Funcao foi aplicada. O valor final ficou: {}'.format(valor))\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8297745/" ]
74,671,589
<p>I have a MyList Component where I search based on date specified and render the detail using Flatlist</p> <pre><code>const MyList =( {date}) =&gt;{ const [list, setList] = useState([]); useEffect(() =&gt; { const url = `https://some-service.com/list?date=${date}` axios.get(url).then((res) =&gt; { setList(res.data.result); }); }, [date]) return ( &lt;FlatList data={list} extraData={list} renderItem={({item}) =&gt; (&lt;RenderItem item={item}/&gt;)} keyExtractor={(item) =&gt; item._id} &gt;&lt;/FlatList&gt; ) } </code></pre> <p>When date is updated in parent it is passed to child component MyList</p> <pre><code>//...some code...// const [date, setDate] = useState(moment().format('YYYY-MM-DD')); return ( &lt;View style={styles.container}&gt; &lt;View style={styles.dateSelector}&gt; &lt;DateSelector date={date} setDate={setDate} /&gt; &lt;/View&gt; &lt;MyList date={date} /&gt; &lt;/View&gt; ); </code></pre> <p>Now when I change the date.. new set of data is fetched and stored in list state.. But FlatList is not getting rerendered to show the changes.</p> <p>NOTE: Below is the sample output of service call. When we make rest call, the result array is having same number of elements, with similar &quot;_id&quot;, &quot;name&quot;.. the only difference is value of &quot;somelist&quot;</p> <p>For Date 2022-12-04</p> <pre><code>{ &quot;status&quot;: &quot;Success&quot;, &quot;result&quot;: [ { &quot;_id&quot;: &quot;638b3ddc1b11677f6202eb4c&quot;, &quot;name&quot;: &quot;John Doe&quot;, &quot;somelist&quot;: [ { &quot;date&quot;: &quot;2022-12-04T00:00:00.000Z&quot;, &quot;status&quot;: &quot;good&quot; } ] }, { &quot;_id&quot;: &quot;638b3ddc1b11677f6202eb4f&quot;, &quot;name&quot;: &quot;Pappu&quot;, &quot;somelist&quot;: [ { &quot;date&quot;: &quot;2022-12-04T00:00:00.000Z&quot;, &quot;status&quot;: &quot;bla&quot; } ] } ..... </code></pre> <p>For Date 2022-12-03</p> <pre><code>{ &quot;status&quot;: &quot;Success&quot;, &quot;result&quot;: [ { &quot;_id&quot;: &quot;638b3ddc1b11677f6202eb4c&quot;, &quot;name&quot;: &quot;John Doe&quot;, &quot;somelist&quot;: [ { &quot;date&quot;: &quot;2022-12-03T00:00:00.000Z&quot;, &quot;status&quot;: &quot;bad&quot; } ] }, { &quot;_id&quot;: &quot;638b3ddc1b11677f6202eb4f&quot;, &quot;name&quot;: &quot;Pappu&quot;, &quot;somelist&quot;: [ { &quot;date&quot;: &quot;2022-12-04T00:00:00.000Z&quot;, &quot;status&quot;: &quot;good&quot; } ] } ..... </code></pre> <p>I have tried using extraData, but still i have having same issue.</p> <pre><code>extraData ={list} </code></pre>
[ { "answer_id": 74671652, "author": "Gerg", "author_id": 20677932, "author_profile": "https://Stackoverflow.com/users/20677932", "pm_score": 2, "selected": true, "text": "def switch(valor):\n case = int(input('Escolha uma opcao... (0 para encerrar) : '))\n if case == 1:\n valor = funcoes_moeda.aumentar(valor)\n print('Valor aumentado: {}'.format(valor))\n switch(valor)\n\n elif case == 2:\n pass\n elif case == 3:\n pass\n elif case == 4:\n pass\n else:\n return valor\n\n # Return the value of valor when case is 0\n return valor\n" }, { "answer_id": 74671672, "author": "nokla", "author_id": 20258214, "author_profile": "https://Stackoverflow.com/users/20258214", "pm_score": 0, "selected": false, "text": "import funcoes_moeda\n\ndef switch(valor):\n case = int(input('Escolha uma opcao... (0 para encerrar) : '))\n if case == 1:\n valor = funcoes_moeda.aumentar(valor)\n print('Valor aumentado: {}'.format(valor))\n return switch(valor)\n\n elif case == 2:\n pass\n elif case == 3:\n pass\n elif case == 4:\n pass\n else:\n return valor\n\nvalor = float(input('Insira o valor: '))\nprint(\"Escolha a funcao a ser aplicada no valor inserido: \\n\" \\\n \"1 - Aumentar Valor \\n\" \\\n \"2 - Diminuir Valor \\n\" \\\n \"3 - Dobrar Valor \\n\" \\\n \"4 - Dividir Valor \\n\" \\\n \"0 - Encerrar o Prorama\"\n )\n\nvalor = switch(valor)\n\nprint('Funcao foi aplicada. O valor final ficou: {}'.format(valor))\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12312638/" ]
74,671,602
<p>I would like to use the MDA (mean direction accuracy) as a custom loss function for a tensorflow neural network.</p> <p>I am trying to implement this as described in here: <a href="https://stackoverflow.com/questions/46876213/custom-mean-directional-accuracy-loss-function-in-keras">Custom Mean Directional Accuracy loss function in Keras</a></p> <pre class="lang-py prettyprint-override"><code>def mda(y_true, y_pred): s = K.equal(K.sign(y_true[1:] - y_true[:-1]), K.sign(y_pred[1:] - y_pred[:-1])) return K.mean(K.cast(s, K.floatx())) </code></pre> <p>The network works fine but when I try to fit my data I am getting this error:</p> <pre><code> ValueError: No gradients provided for any variable </code></pre> <p>I think that this is because I am loosing the gradient info from my pred tensor but I don't know how can implement this.... or if this makes any sense at all.... Finally I want to predict is if some numeric series is going up or down, that is why this function made sense to me.</p>
[ { "answer_id": 74671624, "author": "Reda Bourial", "author_id": 6072029, "author_profile": "https://Stackoverflow.com/users/6072029", "pm_score": 1, "selected": false, "text": "import tensorflow as tf\n\ndef mda(y_true, y_pred):\n s = tf.equal(tf.math.sign(y_true[1:] - y_true[:-1]),\n tf.math.sign(y_pred[1:] - y_pred[:-1]))\n return tf.math.reduce_mean(tf.cast(s, tf.float32))\n\n" }, { "answer_id": 74671976, "author": "AndrzejO", "author_id": 7246805, "author_profile": "https://Stackoverflow.com/users/7246805", "pm_score": 2, "selected": true, "text": "K.equal K.cast sign def mda(y_true, y_pred):\n d = K.abs(K.sign(y_true[1:] - y_true[:-1]) - (K.sign(y_pred[1:] - y_pred[:-1])))\n s = (1. - d) * (d - 1.) * (d - 2.) / 2.\nreturn K.mean(s)\n s 1 K.equal 0" }, { "answer_id": 74672061, "author": "Lord_Rafa", "author_id": 2632307, "author_profile": "https://Stackoverflow.com/users/2632307", "pm_score": 0, "selected": false, "text": "def mda_custom_loss(y_true, y_pred):\n res = tf.math.sign(y_true[1:] - y_true[:-1]) - tf.math.sign(y_pred[1:] - y_pred[:-1])\n s = tf.math.abs(tf.math.sign(res))\n return 1 - tf.math.reduce_mean(tf.math.sign(s))\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2632307/" ]
74,671,615
<p>I am having some issues in finding the correct regular expression</p> <p>lets say I have this list of keywords:</p> <p>keywords = [' b.o.o', ' a.b.a', ' titi']</p> <p>(please keep in mind that there is a blank space before any keyword and this list can contain up to 100keywords so I can't to it without a function) and my dataframe df:</p> <p><a href="https://i.stack.imgur.com/1X4Iy.png" rel="nofollow noreferrer">enter image description here</a></p> <p>I use the following code to extract the matching words, it works partially because it extract even the words that are not an exact match :</p> <pre><code>keywords = [' b.o.o', ' a.b.a', ' titi'] pattern = '(' + '|'.join([fr'\\b({k})\\b' for k in keywords]) + ')' df.withColumn('words', F.expr(f&quot;regexp_extract_all(colB, '{pattern}' ,1))) </code></pre> <p>the output :</p> <p><a href="https://i.stack.imgur.com/IaZYl.png" rel="nofollow noreferrer">enter image description here</a></p> <p>But here is the expected output :</p> <p><a href="https://i.stack.imgur.com/MUFIy.png" rel="nofollow noreferrer">enter image description here</a> As we can see, it does extract words that are not exact match, it does not take into account the dot. For example, this code considers awbwa as a match because if we replace w by a dot it will be a match. I also tried</p> <pre><code>pattern = '(' + '|'.join([fr'\\b({k})\\b' for k in [re.escape(x) for x in keywords]]) + ')' </code></pre> <p>to add a backslash before every dot and before the blank space but it doesnt work.</p> <p>Thank you so much for your help (btw I looked everywhere on stackoverflow and I didnt find an answer to this)</p>
[ { "answer_id": 74671624, "author": "Reda Bourial", "author_id": 6072029, "author_profile": "https://Stackoverflow.com/users/6072029", "pm_score": 1, "selected": false, "text": "import tensorflow as tf\n\ndef mda(y_true, y_pred):\n s = tf.equal(tf.math.sign(y_true[1:] - y_true[:-1]),\n tf.math.sign(y_pred[1:] - y_pred[:-1]))\n return tf.math.reduce_mean(tf.cast(s, tf.float32))\n\n" }, { "answer_id": 74671976, "author": "AndrzejO", "author_id": 7246805, "author_profile": "https://Stackoverflow.com/users/7246805", "pm_score": 2, "selected": true, "text": "K.equal K.cast sign def mda(y_true, y_pred):\n d = K.abs(K.sign(y_true[1:] - y_true[:-1]) - (K.sign(y_pred[1:] - y_pred[:-1])))\n s = (1. - d) * (d - 1.) * (d - 2.) / 2.\nreturn K.mean(s)\n s 1 K.equal 0" }, { "answer_id": 74672061, "author": "Lord_Rafa", "author_id": 2632307, "author_profile": "https://Stackoverflow.com/users/2632307", "pm_score": 0, "selected": false, "text": "def mda_custom_loss(y_true, y_pred):\n res = tf.math.sign(y_true[1:] - y_true[:-1]) - tf.math.sign(y_pred[1:] - y_pred[:-1])\n s = tf.math.abs(tf.math.sign(res))\n return 1 - tf.math.reduce_mean(tf.math.sign(s))\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677638/" ]
74,671,623
<p>I have three tables, <strong>table A</strong> (product), <strong>table B</strong> (invoice) and <strong>table C</strong> (invoices_info) which contains two columns referencing <code>invoice_id</code> and <code>product_id</code>. How can i insert a new entry (a new invoice) while inserting the products to the appropriate table and inserting the invoice info to its table also ?</p> <p>Here are the entity classes : <strong>Product</strong></p> <pre><code>@Entity @Table(name = &quot;product&quot;) public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = &quot;id&quot;) private Long id; @Column(name = &quot;family_id&quot;) private long familyId; @Column(name = &quot;product_name&quot;) private String productName; @Column(name = &quot;product_category&quot;) private String productCategory; @Column(name = &quot;product_quantity&quot;) private int productQuantity; //getters and setters } </code></pre> <p><strong>Invoice</strong></p> <pre><code>@Entity @Table(name = &quot;invoice&quot;) public class Invoice { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = &quot;invoice_id&quot;) private Long id; @Column(name = &quot;provider_id&quot;) private Long providerId; @Column(name = &quot;total&quot;) private int invoiceTotal; @Column(name = &quot;date&quot;) private Date invoiceDate; //getters and setters } </code></pre> <p><strong>InvoiceInfo</strong></p> <pre><code>@Entity @Table(name = &quot;invoice_info&quot;) public class InvoiceInfo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = &quot;item_id&quot;) private long id; @Column(name = &quot;product_id&quot;) private long productId; @Column(name = &quot;invoice_id&quot;) private long invoiceId; //getters and setters } </code></pre>
[ { "answer_id": 74672000, "author": "Emad", "author_id": 1753089, "author_profile": "https://Stackoverflow.com/users/1753089", "pm_score": 2, "selected": true, "text": "// create a new Product entity\nProduct product = new Product();\nproduct.setFamilyId(1);\nproduct.setProductName(\"Product 1\");\nproduct.setProductCategory(\"Category 1\");\nproduct.setProductQuantity(10);\n\n// create a new Invoice entity\nInvoice invoice = new Invoice();\ninvoice.setProviderId(1);\ninvoice.setInvoiceTotal(100);\ninvoice.setInvoiceDate(new Date());\n\n// create a new InvoiceInfo entity\nInvoiceInfo invoiceInfo = new InvoiceInfo();\ninvoiceInfo.setProductId(product.getId());\ninvoiceInfo.setInvoiceId(invoice.getId());\n\n// get the current Hibernate session\nSession session = sessionFactory.getCurrentSession();\n\n// save the Product, Invoice, and InvoiceInfo entities to the database\n// using the persist method\nsession.persist(product);\nsession.persist(invoice);\nsession.persist(invoiceInfo);\n session.commit();\n" }, { "answer_id": 74672103, "author": "Harry Coder", "author_id": 893952, "author_profile": "https://Stackoverflow.com/users/893952", "pm_score": 0, "selected": false, "text": "@ManyToOne @OneToMany @ManyToMany @OneToOne InvoiceInfo Invoice @Entity\n@Table(name = \"product\")\npublic class Product {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"id\")\n private Long id;\n @Column(name = \"family_id\")\n private long familyId; \n @Column(name = \"product_name\")\n private String productName;\n @Column(name = \"product_category\")\n private String productCategory;\n @Column(name = \"product_quantity\") \n private int productQuantity;\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"invoice_id\", referencedColumnName = \"id\")\n private Invoice invoice;\n //getters and setters\n}\n @Entity\n@Table(name = \"invoice\")\npublic class Invoice {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"invoice_id\")\n private Long id;\n @Column(name = \"provider_id\")\n private Long providerId;\n @Column(name = \"total\")\n private int invoiceTotal;\n @Column(name = \"date\")\n private Date invoiceDate;\n @OneToMany(mappedBy = \"product\")\n private List<Product> products;\n //getters and setters\n}\n InvoiceInfo Invoice invoice = invoiceRepository.save(invoice);\nProduct product = new Product();\n// Set the other properties\nproduct.setInvoice(invoice);\nproductRepository.save(product);\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16564712/" ]
74,671,630
<p>I want to loop through the news table and get the title and rating of each row. I tried different options, but I can’t understand why the select method receives all the options at once. I need to get each news block in a loop.</p> <p>I used this way to get table link: Elements elements = document.select(&quot;#hnmain &gt; tbody &gt; tr:nth-child(3) &gt; td &gt; table&quot;);</p> <p>This query doesn't work in a loop because it gets all the elements at once. I need to get the elements sequentially. So that I can do like this: List list = new ArrayList&lt;&gt;();</p> <pre><code>for (Element element: elements){ String title = element... String rating = element... list.add(title); list.add(rating); } </code></pre> <p>Sample data from html:</p> <pre><code>&lt;table border=&quot;0&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot;&gt; &lt;tbody&gt; &lt;tr class=&quot;athing&quot; id=&quot;33582264&quot;&gt; &lt;td align=&quot;right&quot; valign=&quot;top&quot; class=&quot;title&quot;&gt;&lt;span class=&quot;rank&quot;&gt;1.&lt;/span&gt;&lt;/td&gt; &lt;td valign=&quot;top&quot; class=&quot;votelinks&quot;&gt; &lt;center&gt; &lt;a id=&quot;up_33582264&quot; href=&quot;vote?id=33582264&amp;amp;how=up&amp;amp;goto=front%3Fday%3D2022-11-13&quot;&gt; &lt;div class=&quot;votearrow&quot; title=&quot;upvote&quot;&gt;&lt;/div&gt;&lt;/a&gt; &lt;/center&gt;&lt;/td&gt; &lt;td class=&quot;title&quot;&gt;&lt;span class=&quot;titleline&quot;&gt;&lt;a href=&quot;https://upbase.io/&quot;&gt;Show HN: I built my own PM tool after trying Trello, Asana, ClickUp, etc.&lt;/a&gt;&lt;span class=&quot;sitebit comhead&quot;&gt; (&lt;a href=&quot;from?site=upbase.io&quot;&gt;&lt;span class=&quot;sitestr&quot;&gt;upbase.io&lt;/span&gt;&lt;/a&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan=&quot;2&quot;&gt;&lt;/td&gt; &lt;td class=&quot;subtext&quot;&gt;&lt;span class=&quot;subline&quot;&gt; &lt;span class=&quot;score&quot; id=&quot;score_33582264&quot;&gt;632 points&lt;/span&gt; by &lt;a href=&quot;user?id=tonypham&quot; class=&quot;hnuser&quot;&gt;tonypham&lt;/a&gt; &lt;span class=&quot;age&quot; title=&quot;2022-11-13T12:00:06&quot;&gt;&lt;a href=&quot;item?id=33582264&quot;&gt;20 days ago&lt;/a&gt;&lt;/span&gt; &lt;span id=&quot;unv_33582264&quot;&gt;&lt;/span&gt; | &lt;a href=&quot;hide?id=33582264&amp;amp;goto=front%3Fday%3D2022-11-13&quot;&gt;hide&lt;/a&gt; | &lt;a href=&quot;item?id=33582264&quot;&gt;456&amp;nbsp;comments&lt;/a&gt; &lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr class=&quot;spacer&quot; style=&quot;height:5px&quot;&gt;&lt;/tr&gt; &lt;tr class=&quot;athing&quot; id=&quot;33584941&quot;&gt; &lt;td align=&quot;right&quot; valign=&quot;top&quot; class=&quot;title&quot;&gt;&lt;span class=&quot;rank&quot;&gt;2.&lt;/span&gt;&lt;/td&gt; &lt;td valign=&quot;top&quot; class=&quot;votelinks&quot;&gt; &lt;center&gt; &lt;a id=&quot;up_33584941&quot; href=&quot;vote?id=33584941&amp;amp;how=up&amp;amp;goto=front%3Fday%3D2022-11-13&quot;&gt; &lt;div class=&quot;votearrow&quot; title=&quot;upvote&quot;&gt;&lt;/div&gt;&lt;/a&gt; &lt;/center&gt;&lt;/td&gt; &lt;td class=&quot;title&quot;&gt;&lt;span class=&quot;titleline&quot;&gt;&lt;a href=&quot;https://fathy.fr/html2svg&quot;&gt;Forking Chrome to turn HTML into SVG&lt;/a&gt;&lt;span class=&quot;sitebit comhead&quot;&gt; (&lt;a href=&quot;from?site=fathy.fr&quot;&gt;&lt;span class=&quot;sitestr&quot;&gt;fathy.fr&lt;/span&gt;&lt;/a&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre>
[ { "answer_id": 74672000, "author": "Emad", "author_id": 1753089, "author_profile": "https://Stackoverflow.com/users/1753089", "pm_score": 2, "selected": true, "text": "// create a new Product entity\nProduct product = new Product();\nproduct.setFamilyId(1);\nproduct.setProductName(\"Product 1\");\nproduct.setProductCategory(\"Category 1\");\nproduct.setProductQuantity(10);\n\n// create a new Invoice entity\nInvoice invoice = new Invoice();\ninvoice.setProviderId(1);\ninvoice.setInvoiceTotal(100);\ninvoice.setInvoiceDate(new Date());\n\n// create a new InvoiceInfo entity\nInvoiceInfo invoiceInfo = new InvoiceInfo();\ninvoiceInfo.setProductId(product.getId());\ninvoiceInfo.setInvoiceId(invoice.getId());\n\n// get the current Hibernate session\nSession session = sessionFactory.getCurrentSession();\n\n// save the Product, Invoice, and InvoiceInfo entities to the database\n// using the persist method\nsession.persist(product);\nsession.persist(invoice);\nsession.persist(invoiceInfo);\n session.commit();\n" }, { "answer_id": 74672103, "author": "Harry Coder", "author_id": 893952, "author_profile": "https://Stackoverflow.com/users/893952", "pm_score": 0, "selected": false, "text": "@ManyToOne @OneToMany @ManyToMany @OneToOne InvoiceInfo Invoice @Entity\n@Table(name = \"product\")\npublic class Product {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"id\")\n private Long id;\n @Column(name = \"family_id\")\n private long familyId; \n @Column(name = \"product_name\")\n private String productName;\n @Column(name = \"product_category\")\n private String productCategory;\n @Column(name = \"product_quantity\") \n private int productQuantity;\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"invoice_id\", referencedColumnName = \"id\")\n private Invoice invoice;\n //getters and setters\n}\n @Entity\n@Table(name = \"invoice\")\npublic class Invoice {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"invoice_id\")\n private Long id;\n @Column(name = \"provider_id\")\n private Long providerId;\n @Column(name = \"total\")\n private int invoiceTotal;\n @Column(name = \"date\")\n private Date invoiceDate;\n @OneToMany(mappedBy = \"product\")\n private List<Product> products;\n //getters and setters\n}\n InvoiceInfo Invoice invoice = invoiceRepository.save(invoice);\nProduct product = new Product();\n// Set the other properties\nproduct.setInvoice(invoice);\nproductRepository.save(product);\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20667902/" ]
74,671,633
<p>I'm trying to make a list of names based off the last number in the values list. The new list will be ordered based on highest number to lowest number but is a list of the names.</p> <pre><code>folks = {'Leia': [28, 'F', 'W', False, True, 'Unemployed',1], 'Junipero': [15, 'M', 'E', False, False, 'Teacher', 0.21158336054026594], 'Sunita': [110, 'D', 'E', True, False, 'Business', 0.9834949767416051], 'Issur': [17, 'F', 'O', True, False, 'Service', 0.7599396397686616], 'Luitgard': [0, 'D', 'U', True, True, 'Unemployed', 0.8874638219100845], 'Rudy': [112, 'M', 'W', True, True, 'Tradesperson', 0.6035917636433216], 'Ioudith': [20, 'D', 'W', True, True, 'Medical', 0.24957574519928294], 'Helmi': [109, 'D', 'M', False, False, 'Service', 0.20239906854483214], 'Katerina': [108, 'M', 'W', False, True, 'Student', 0.3046268530221382], 'Durai': [106, 'M', 'U', True, False, 'Business', 0.32332997497778493], 'Euphemios': [83, 'M', 'L', True, True, 'Banker', 0.17369577419188664], 'Lorinda': [8, 'F', 'E', False, True, 'Retail', 0.6667783756618852], 'Lasse': [30, 'D', 'U', True, True, 'Business', 0.6716420300452077], 'Adnan': [117, 'D', 'U', True, False, 'Banker', 0.7043759366238305], 'Pavica': [112, 'F', 'L', False, False, 'Business', 0.5875152728319836], 'Adrastos': [118, 'F', 'L', False, True, 'Service', 0.0660146284846359], 'Kobus': [49, 'D', 'S', False, False, 'Service', 0.4738056051140088], 'Daniel': [115, 'D', 'L', False, True, 'Service', 0.5182765931408372], 'Samantha': [97, 'D', 'W', True, True, 'Medical', 0.07082409148069169], 'Sacagawea': [28, 'F', 'U', True, True, 'Medical', 0.29790328657890996], 'Ixchel': [26, 'F', 'S', False, False, 'Business', 0.22593704520870372], 'Nobutoshi': [31, 'M', 'W', False, True, 'Business', 0.37923896100469956], 'Gorou': [55, 'M', 'B', True, True, 'Banker', 0.8684653864827863], 'Keiko': [34, 'M', 'L', False, True, 'Student', 0.02499269016601946], 'Seong-Su': [1, 'M', 'M', False, True, 'Retail', 0.3214997836868769], 'Aya': [41, 'M', 'B', True, True, 'Teacher', 0.3378161065313626], 'Okan': [11, 'D', 'W', True, True, 'Banker', 0.35535128959244744], 'Mai': [31, 'F', 'M', False, False, 'Service', 0.7072299366468716], 'Chaza-el': [84, 'D', 'E', True, True, 'Teacher', 0.263795143996962], 'Estera': [79, 'M', 'U', True, False, 'Tradesperson', 0.09970175216521693], 'Dante': [82, 'M', 'L', True, False, 'Unemployed', 0.2126494288577333], 'Leofric': [68, 'F', 'B', True, False, 'Unemployed', 0.19591887643941486], 'Anabelle': [63, 'M', 'B', False, False, 'Teacher', 0.3558324357405023], 'Harsha': [119, 'D', 'O', False, True, 'Retail', 0.3359989642837887], 'Dionisia': [92, 'F', 'B', True, False, 'Doctor', 0.42704604164789706], 'Rajesh': [55, 'F', 'M', True, False, 'Doctor', 0.485752225148387], 'Scilla': [60, 'F', 'M', False, False, 'Student', 0.7294089528796434], 'Arsenio': [10, 'D', 'L', False, True, 'Teacher', 0.0819890866210915]} def generate_prioritized_list(unordered_people): nums=[] for i in folks: nums.append(folks[i][6]) nums.sort(reverse=True) for i in nums: names=[] for name in folks: if i in folks[name][6]: names.append(folks[i]) for i in names: print(i) print(generate_prioritized_list(folks)) </code></pre> <p>I'm trying to get a list of the names ordered highest to lowest by the last value in the list each persons attributes.</p>
[ { "answer_id": 74671648, "author": "Reda Bourial", "author_id": 6072029, "author_profile": "https://Stackoverflow.com/users/6072029", "pm_score": 0, "selected": false, "text": "# Get the values of the last item in each sublist\nlast_values = [folks[name][-1] for name in folks]\n\n# Sort the values in descending order\nsorted_values = sorted(last_values, reverse=True)\n\n# Create a list of names, sorted by the last value in their sublist\nsorted_names = [name for value in sorted_values\n for name in folks\n if folks[name][-1] == value]\n\n# Print the resulting list\nprint(sorted_names)\n" }, { "answer_id": 74671697, "author": "Paul H", "author_id": 1552748, "author_profile": "https://Stackoverflow.com/users/1552748", "pm_score": 1, "selected": false, "text": "key sorted sorted(folks, key=lambda x: folks[x][-1])[::-1]\n sorted key=lambda x: folks[x][-1] [::-1] ['Leia',\n 'Sunita',\n 'Luitgard',\n 'Gorou',\n 'Issur',\n # ... \n 'Estera',\n 'Arsenio',\n 'Samantha',\n 'Adrastos',\n 'Keiko']\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677867/" ]
74,671,673
<p>I have a Json file, it contains connectionstring. I want to asynchronously read the file and deserialize it to a ConnectionString object and I always get a null result. I'm using .NET Core 6 and System.Text.Json.</p> <p>Here is contents of my Json file:</p> <pre><code>{ &quot;ConnectionStrings&quot;: { &quot;ConnStr&quot;: &quot;Data Source=(local);Initial Catalog=MyData;Integrated Security=False;TrustServerCertificate=True;Persist Security Info=False;Async=True;MultipleActiveResultSets=true;User ID=sa;Password=MySecret;&quot;, &quot;ProviderName&quot;: &quot;SQLServer&quot; } } </code></pre> <p>Here are the contents of my classes:</p> <pre><code>internal class DBConnectionString { [JsonPropertyName(&quot;ConnStr&quot;)] public string ConnStr { get; set; } [JsonPropertyName(&quot;ProviderName&quot;)] public string ProviderName { get; set; } public DBConnectionString() { } } public class DBConnStr { private static string AppSettingFilePath =&gt; &quot;appsettings.json&quot;; public static async Task&lt;string&gt; GetConnectionStringAsync() { string connStr = &quot;&quot;; if (File.Exists((DBConnStr.AppSettingFilePath))) { using (FileStream sr = new FileStream(AppSettingFilePath, FileMode.Open, FileAccess.Read)) { //string json = await sr.ReadToEndAsync(); System.Text.Json.JsonDocumentOptions docOpt = new System.Text.Json.JsonDocumentOptions() { AllowTrailingCommas = true }; using (var document = await System.Text.Json.JsonDocument.ParseAsync(sr, docOpt)) { System.Text.Json.JsonSerializerOptions opt = new System.Text.Json.JsonSerializerOptions() { AllowTrailingCommas = true, PropertyNameCaseInsensitive = true }; System.Text.Json.JsonElement root = document.RootElement; System.Text.Json.JsonElement element = root.GetProperty(&quot;ConnectionStrings&quot;); sr.Position = 0; var dbConStr = await System.Text.Json.JsonSerializer.DeserializeAsync&lt;DBConnectionString&gt;(sr, opt); if (dbConStr != null) { connStr = dbConStr.ConnStr; } } } } return connStr; } } </code></pre> <p>The following is the syntax that I use to call the GetConnectionStringAsync method:</p> <pre><code>string ConnectionString = DBConnStr.GetConnectionStringAsync().Result; </code></pre> <p>When the application is running in debug mode, I checked, on line</p> <blockquote> <p>var dbConStr = await System.Text.Json.JsonSerializer.DeserializeAsync(sr, opt);</p> </blockquote> <p>The DBConnectionString object property is always empty.</p> <p>I also tried the reference on the Microsoft website, <a href="https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-to?pivots=dotnet-6-0" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-to?pivots=dotnet-6-0</a> but it doesn't work succeed.</p> <pre><code>using System.Text.Json; namespace DeserializeFromFileAsync { public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } } public class Program { public static async Task Main() { string fileName = &quot;WeatherForecast.json&quot;; using FileStream openStream = File.OpenRead(fileName); WeatherForecast? weatherForecast = await JsonSerializer.DeserializeAsync&lt;WeatherForecast&gt;(openStream); Console.WriteLine($&quot;Date: {weatherForecast?.Date}&quot;); Console.WriteLine($&quot;TemperatureCelsius: {weatherForecast?.TemperatureCelsius}&quot;); Console.WriteLine($&quot;Summary: {weatherForecast?.Summary}&quot;); } } } </code></pre> <p>Do you have a solution for my problem or a better solution? I appreciate all your help. Thanks</p> <p>Sorry about my English if it's not good, because I'm not fluent in English and use google translate to translate it</p>
[ { "answer_id": 74671648, "author": "Reda Bourial", "author_id": 6072029, "author_profile": "https://Stackoverflow.com/users/6072029", "pm_score": 0, "selected": false, "text": "# Get the values of the last item in each sublist\nlast_values = [folks[name][-1] for name in folks]\n\n# Sort the values in descending order\nsorted_values = sorted(last_values, reverse=True)\n\n# Create a list of names, sorted by the last value in their sublist\nsorted_names = [name for value in sorted_values\n for name in folks\n if folks[name][-1] == value]\n\n# Print the resulting list\nprint(sorted_names)\n" }, { "answer_id": 74671697, "author": "Paul H", "author_id": 1552748, "author_profile": "https://Stackoverflow.com/users/1552748", "pm_score": 1, "selected": false, "text": "key sorted sorted(folks, key=lambda x: folks[x][-1])[::-1]\n sorted key=lambda x: folks[x][-1] [::-1] ['Leia',\n 'Sunita',\n 'Luitgard',\n 'Gorou',\n 'Issur',\n # ... \n 'Estera',\n 'Arsenio',\n 'Samantha',\n 'Adrastos',\n 'Keiko']\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20676149/" ]
74,671,674
<p>When building my code I get the following &quot;undefined reference&quot;-errors, which I cannot get rid of. I've already tried several hints from stack overflow but nothing helps :-(. Maybe you have an idea?</p> <p>I use VSCode with PlatformIO for an Arduino Uno on Mac OS.</p> <blockquote> <p>in function `get7SegBitMap':</p> <p>/Users/christian/Projekt/src/charmap7seg.cpp:70: undefined reference to 'Led7SegmentCharMap::bitMap'<br /> /Users/christian/Projekt/src/charmap7seg.cpp:70: undefined reference to `Led7SegmentCharMap::bitMap' collect2: error: ld returned 1 exit status</p> </blockquote> <p>The hierarchy is:</p> <ul> <li>main.cpp includes ledmatrix.hpp <ul> <li>ledmatrix.cpp includes ledmatrix.hpp</li> <li>ledmatrix.hpp includes charmap7seg.hpp <ul> <li>charmap7seg.cpp includes charmap7seg.hpp</li> </ul> </li> </ul> </li> </ul> <p><strong>charmap7seg.hpp</strong></p> <pre><code>#pragma once #include &lt;Arduino.h&gt; class Led7SegmentCharMap { private: static const uint8_t bitMap[]; // will be initialized in cpp-file uint8_t getCharMapIndex(const unsigned char outChar); public: // Konstruktur Led7SegmentCharMap(); // BitMap zur Darstellung auf der 7-Segment-Anzeige für outChar ermitteln uint8_t get7SegBitMap(const unsigned char outChar); }; int set7SegValue(const LedMatrixPos pos, const uint8_t charBitMap); </code></pre> <p><strong>charmap7seg.cpp</strong></p> <pre><code>#include &lt;Arduino.h&gt; #include &lt;charmap7seg.hpp&gt; // Konstruktur Led7SegmentCharMap::Led7SegmentCharMap() { uint8_t bitMap[] = { ///&lt; charMap contains bitmaps for 7-seg-displays //gfedcba 0b0111111, ///&lt; &quot;0&quot;: Segments f, e, d, c, b, a --&gt; bitMap[0] 0b0000110, ///&lt; &quot;1&quot;: Segments c, b --&gt; bitMap[1] 0b1011011, ///&lt; &quot;2&quot;: Segments g, e, d, b, a --&gt; bitMap[2] (...) } (void)bitMap; // to suppress the compiler warning &quot;unused variable&quot; }; uint8_t Led7SegmentCharMap::get7SegBitMap(const unsigned char outChar) { return bitMap[getCharMapIndex(outChar)]; // &lt;===== this is line 70 }; (...) </code></pre> <p><strong>ledmatrix.hpp</strong></p> <pre><code>#pragma once #include &lt;Arduino.h&gt; #include &lt;charmap7seg.hpp&gt; class LedMatrix { private: Led7SegmentCharMap charMap; (...) public: Led7SegmentCharMap(); // Konstruktor uint8_t get7SegBitMap(const unsigned char outChar); void LedMatrix::display(const String outString); (...) </code></pre> <p><strong>ledmatrix.cpp</strong></p> <pre><code>#include &lt;ledmatrix.hpp&gt; (...) void LedMatrix::display(const String outString) { (...) // get a char out of outString --&gt; outChar uint8_t charBitMap = charMap.get7SegBitMap(outChar); // get 7-seg-&quot;bitmap&quot; (...) }; (...) </code></pre> <p>My expection is that all dependencies are fulfilled (which is not true regarding the error messages). I had some trouble with initializing the bitMap-array. Maybe the undefined reference error is related to that?</p>
[ { "answer_id": 74671704, "author": "Jon Forhan", "author_id": 19760305, "author_profile": "https://Stackoverflow.com/users/19760305", "pm_score": -1, "selected": false, "text": "this->bitMap[] = { ///< charMap contains bitmaps for 7-seg-displays\n //gfedcba\n 0b0111111, ///< \"0\": Segments f, e, d, c, b, a --> bitMap[0]\n 0b0000110, ///< \"1\": Segments c, b --> bitMap[1]\n 0b1011011, ///< \"2\": Segments g, e, d, b, a --> bitMap[2]\n (...)\n }\n" }, { "answer_id": 74675371, "author": "CHarraeus", "author_id": 13268845, "author_profile": "https://Stackoverflow.com/users/13268845", "pm_score": 0, "selected": false, "text": "bitMap class Led7SegmentCharMap {\npublic:\n static const uint8_t bitMap[];\n\n // BitMap zur Darstellung auf der 7-Segment-Anzeige für outChar ermitteln\n uint8_t get7SegBitMap(const unsigned char outChar);\n\nprivate:\n uint8_t getCharMapIndex(const unsigned char outChar);\n};\n const uint8_t Led7SegmentCharMap::bitMap[] = { ///< charMap contains bitmaps for 7-seg-displays\n ///< bzw. den Buchstaben darstellen.\n 0b0111111, ///< \"0\": Segmente f, e, d, c, b, a --> bitMap[0]\n 0b0000110, ///< \"1\": Segmente c, b --> bitMap[1]\n 0b1011011, ///< \"2\": Segmente g, e, d, b, a --> bitMap[2]\n};\n\n// BitMap zur Darstellung auf der 7-Segment-Anzeige aus Zeichen bzw. Index ermitteln\nuint8_t Led7SegmentCharMap::get7SegBitMap(const unsigned char outChar) {\n return bitMap[getCharMapIndex(outChar)];\n};\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13268845/" ]
74,671,685
<p>Sorry, I've only been using python for about an hour, I'm using PyCharm if that has to do with the problem, I don't think it does though.</p> <p>Here is my code:</p> <pre><code>userAge = input(&quot;Hi, how old are you?\n&quot;) longRussiaString = ( &quot;When will you guys stop telling me about how you had to walk uphill both ways for 10 miles to&quot; &quot;get to school amidst the icy tundra of Russia? We get it!&quot;) def reply_detect(): if userAge != 0 - 5: pass else: print(&quot;Wait a minute... Stop lying! I know your brain is too small for this!&quot;) if userAge != 6 - 18: pass else: print(&quot;You're too young to be interested in this. Unless your dad forced you to just like me :(&quot;) if userAge != 19 - 24: pass else: print(&quot;&quot;&quot;Good luck dealing with those &quot;taxes&quot; things or whatever. Wait, you haven't heard of those?&quot;&quot;&quot;) if userAge != 25 - 40: pass else: print(&quot;You post-millennial scumbags... No, just kidding, you guys are the ones carrying our society.&quot;) if userAge != 41 - 55: pass else: print(longRussiaString) def age_reply(): print(f&quot;So, you're {userAge} years old, huh?&quot;) reply_detect() age_reply() </code></pre> <p>I tried to inverse the if loops making a second function to neaten things up a bit, and lots of other things, what happens is that it shows the &quot;So, you're {userAge} years old part, but it ends there and doesn't show me the rest, which is the function &quot;reply_detect&quot;.</p> <p>Thanks!</p>
[ { "answer_id": 74671707, "author": "topsail", "author_id": 1467914, "author_profile": "https://Stackoverflow.com/users/1467914", "pm_score": 1, "selected": true, "text": "0 - 5 userAge >= 0 and userAge <= 5" }, { "answer_id": 74671715, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 1, "selected": false, "text": "0 5 range(0, 6) >>> n = 16\n>>> n in range(0, 17)\nTrue\n>>> n in range(0, 6)\nFalse\n>>> n not in range(0, 6)\nTrue\n>>>\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677930/" ]
74,671,719
<pre><code>while True: try: color1 = str(input(&quot;What should the color of the broken window be, Purple or Sky Blue? &gt; &quot;)).lower().strip() color2 = str(input(&quot;What should the color of the broken window, white Yellow or Pink? &gt; &quot;)).lower().strip() user_info = {&quot;color2&quot;: color1, &quot;color2&quot;: color2,} except ValueError: print(&quot;Choose a valid input please...&quot;) continue else: break </code></pre> <p>Trying to get it to give an error and restart the loop but its not working.</p>
[ { "answer_id": 74671707, "author": "topsail", "author_id": 1467914, "author_profile": "https://Stackoverflow.com/users/1467914", "pm_score": 1, "selected": true, "text": "0 - 5 userAge >= 0 and userAge <= 5" }, { "answer_id": 74671715, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 1, "selected": false, "text": "0 5 range(0, 6) >>> n = 16\n>>> n in range(0, 17)\nTrue\n>>> n in range(0, 6)\nFalse\n>>> n not in range(0, 6)\nTrue\n>>>\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20677970/" ]
74,671,732
<p>I'm trying to run flask-mqtt on raspberry pi. I am running python version 3.7.3 it looks like I can't update python to 3.10 on pi. I don't know if that is necessary. I have installed flask-mqtt with following command</p> <p><code>pip install Flask-MQTT:</code></p> <blockquote> <p>Requirement already satisfied: Flask-MQTT in /home/pi/.local/lib/python2.7/site-packages (1.0.7) <br> Requirement already satisfied: Flask in /usr/lib/python2.7/dist-packages (from Flask-MQTT) (1.0.2) <br> Requirement already satisfied: paho-mqtt in /home/pi/.local/lib/python2.7/site-packages (from Flask-MQTT) (1.6.1) <br> Requirement already satisfied: typing; python_version &lt; &quot;3.5&quot; in /home/pi/.local/lib/python2.7/site-packages (from Flask-MQTT) (3.10.0.0)</p> </blockquote> <p>I have both tried running app.py in virtual environment and directly on pi system everytime I run it i get ModuleNotFoundError like following</p> <blockquote> <p>Traceback (most recent call last): <br> File &quot;app.py&quot;, line 2, in <br> from flask_mqtt import Mqtt <br> ModuleNotFoundError: No module named 'flask_mqtt' <br></p> </blockquote> <p>I am running Raspberry Pi OS (Legacy) on Raspberry Pi model 3 b+</p>
[ { "answer_id": 74671707, "author": "topsail", "author_id": 1467914, "author_profile": "https://Stackoverflow.com/users/1467914", "pm_score": 1, "selected": true, "text": "0 - 5 userAge >= 0 and userAge <= 5" }, { "answer_id": 74671715, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 1, "selected": false, "text": "0 5 range(0, 6) >>> n = 16\n>>> n in range(0, 17)\nTrue\n>>> n in range(0, 6)\nFalse\n>>> n not in range(0, 6)\nTrue\n>>>\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20571767/" ]
74,671,750
<p>I have been trying to use a simple audio audio player for android auto and just stream a audio from a link. But when the function is called the media player cant set the data source from url. and it will return the following error.</p> <p>Code :</p> <pre><code>class HelloWorldScreen(carContext: CarContext) : Screen(carContext) { override fun onGetTemplate(): Template { val mGridIcon = IconCompat.createWithResource( carContext, R.drawable.mainscreenlogo ) val gridItemCar = GridItem.Builder() .setTitle(&quot;Car Info&quot;) .setImage( CarIcon.Builder(mGridIcon).build(), GridItem.IMAGE_TYPE_LARGE ).setOnClickListener(this::player).build() val gridList = ItemList.Builder() .addItem(gridItemCar).build() return GridTemplate.Builder() .setSingleList(gridList) .build() } private fun player(){ var mediaPlayer = MediaPlayer() var audioUrl = &quot;https://url&quot; var customUri: Uri = Uri.parse(audioUrl) mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC) mediaPlayer.setAudioAttributes( AudioAttributes. Builder() .setUsage(AudioAttributes.USAGE_MEDIA) .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) .build() ) if(!mediaPlayer.isPlaying){ try { mediaPlayer.setDataSource(audioUrl) mediaPlayer.prepareAsync() mediaPlayer.setOnPreparedListener { mediaPlayer.start() } } catch (e: Exception) { e.printStackTrace() } Log.d(&quot;Player&quot; , &quot;Audio started playing..&quot;) } else { if (mediaPlayer.isPlaying) { mediaPlayer.stop() mediaPlayer.reset() // mediaPlayer.release() Log.d(&quot;Player&quot; , &quot;Player Released&quot;) mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC) } else { Log.d(&quot;Player&quot; , &quot;Audio not played.. Check Error&quot;) } } }} </code></pre> <p>I used the player function to invoke the player .</p> <p>The Error:</p> <blockquote> <blockquote> <p>E/MediaPlayerNative: Unable to create media player W/System.err: java.io.IOException: setDataSource failed.: status=0x80000000 W/System.err: at android.media.MediaPlayer.nativeSetDataSource(Native Method) W/System.err: at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1173) W/System.err: at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1160) W/System.err: at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1125) W/System.err: at com.auslanka.app.common.HelloWorldService.player(HelloWorldService.kt:42) W/System.err: at com.auslanka.app.common.HelloWorldService.onCreateSession(HelloWorldService.kt:14) W/System.err: at androidx.car.app.CarAppService.onCreateSession(CarAppService.java:283) W/System.err: at androidx.car.app.CarAppBinder.lambda$onAppCreate$0$androidx-car-app-CarAppBinder(CarAppBinder.java:115) W/System.err: at androidx.car.app.CarAppBinder$$ExternalSyntheticLambda6.dispatch(Unknown Source:8) W/System.err: at androidx.car.app.utils.RemoteUtils.lambda$dispatchCallFromHost$0(RemoteUtils.java:149) W/System.err: at androidx.car.app.utils.RemoteUtils$$ExternalSyntheticLambda2.run(Unknown Source:6) W/System.err: at android.os.Handler.handleCallback(Handler.java:883) W/System.err:<br /> at android.os.Handler.dispatchMessage(Handler.java:100) W/System.err: at android.os.Looper.loop(Looper.java:214) W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7356) W/System.err: at java.lang.reflect.Method.invoke(Native Method) W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)</p> </blockquote> </blockquote> <p>Am I doing this wrong, if so a small code guide of how to play audio in android auto will be much appreciated. Thank you.</p>
[ { "answer_id": 74675464, "author": "hassan bazai", "author_id": 14279755, "author_profile": "https://Stackoverflow.com/users/14279755", "pm_score": 1, "selected": false, "text": "// Create a MediaSource instance\nMediaSource source = new MediaSource.Factory(dataSourceFactory)\n .createMediaSource(uri);\n\n// Create an AudioSource instance\nAudioSource audioSource = new AudioSource.Factory(dataSourceFactory)\n .setTag(TAG)\n .createAudioSource();\n\n// Create a media player instance\nSimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(context);\n\n// Prepare the player with the MediaSource\nplayer.prepare(source);\n\n// Set the audio source\nplayer.setAudioSource(audioSource);\n\n// Set the playback parameters\nplayer.setPlaybackParameters(new PlaybackParameters(speed, pitch));\n\n// Start playback\nplayer.playWhenReady(true);\n" }, { "answer_id": 74677496, "author": "Thivanka Sarathchandra", "author_id": 8090228, "author_profile": "https://Stackoverflow.com/users/8090228", "pm_score": 0, "selected": false, "text": "<uses-permission android:name=\"android.permission.INTERNET\"/>\n <application....\n\nandroid:usesCleartextTraffic=\"true\" .../>\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8090228/" ]
74,671,788
<p>I am new to flutter. I am building todo list app by following one of the article. I have managed to find couple of errors already such as asyn and .then method, FieldButton to Text button. I am struggling to fix couple of errors</p> <p>This is the first error message:</p> <pre><code>lib/main.dart:88:24: Error: Undefined name '_todoList'. for (String title in _todoList) { </code></pre> <p>This is the second error message:</p> <pre><code>lib/main.dart:89:22: Error: Method not found: '_buildTodoItem'. _todoWidgets.add(_buildTodoItem(title)); ^^^^^^^^^^^^^^ </code></pre> <p>Here is my full code:</p> <pre><code>import 'package:flutter/material.dart'; void main() { runApp(App()); } class App extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp(title: 'To-Do-List', home: TodoList()); } } class TodoList extends StatefulWidget { @override _TodoListState createState() =&gt; _TodoListState(); } class _TodoListState extends State&lt;TodoList&gt; { final List&lt;String&gt; _todoList = &lt;String&gt;[]; final TextEditingController _textFieldController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('To-Do List'), ), body: ListView(children: _getItems()), floatingActionButton: FloatingActionButton( onPressed: () =&gt; _displayDialog(context), tooltip: 'Add Item', child: Icon(Icons.add), ), ); } void _addTodoItem(String title) { //Wrapping it inside a set state will notify // the app that the state has changed setState(() { _todoList.add(title); }); _textFieldController.clear(); } //Generate list of item widgets Widget _buildTodoItem(String title) { return ListTile( title: Text(title), ); } //Generate a single item widget Future&lt;AlertDialog&gt; _displayDialog(BuildContext context) async { return showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: const Text('Add a task to your List'), content: TextField( controller: _textFieldController, decoration: const InputDecoration(hintText: 'Enter task here'), ), actions: &lt;Widget&gt;[ TextButton( child: const Text('ADD'), onPressed: () { Navigator.of(context).pop(); _addTodoItem(_textFieldController.text); }, ), TextButton( child: const Text('CANCEL'), onPressed: () { Navigator.of(context).pop(); }, ) ], ); }).then((showDialog) =&gt; showDialog ?? false); } } List&lt;Widget&gt; _getItems() { final List&lt;Widget&gt; _todoWidgets = &lt;Widget&gt;[]; for (String title in _todoList) { _todoWidgets.add(_buildTodoItem(title)); } return _todoWidgets; } </code></pre> <p>I have already fixed .then method along with Textbutton. I want to understand how exactly I can find be able to resolve this issue. It's quite confusing to beging with.</p>
[ { "answer_id": 74675464, "author": "hassan bazai", "author_id": 14279755, "author_profile": "https://Stackoverflow.com/users/14279755", "pm_score": 1, "selected": false, "text": "// Create a MediaSource instance\nMediaSource source = new MediaSource.Factory(dataSourceFactory)\n .createMediaSource(uri);\n\n// Create an AudioSource instance\nAudioSource audioSource = new AudioSource.Factory(dataSourceFactory)\n .setTag(TAG)\n .createAudioSource();\n\n// Create a media player instance\nSimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(context);\n\n// Prepare the player with the MediaSource\nplayer.prepare(source);\n\n// Set the audio source\nplayer.setAudioSource(audioSource);\n\n// Set the playback parameters\nplayer.setPlaybackParameters(new PlaybackParameters(speed, pitch));\n\n// Start playback\nplayer.playWhenReady(true);\n" }, { "answer_id": 74677496, "author": "Thivanka Sarathchandra", "author_id": 8090228, "author_profile": "https://Stackoverflow.com/users/8090228", "pm_score": 0, "selected": false, "text": "<uses-permission android:name=\"android.permission.INTERNET\"/>\n <application....\n\nandroid:usesCleartextTraffic=\"true\" .../>\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74671788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7006738/" ]
74,671,815
<p>I am trying to update a DB Table at my college using JDBC and JAVAFx. I have tried everything to get the SQL Update command to work.</p> <p>I have a table where the player_id is the foreign key from the table - Player -, and is a child table to its parent namely - Player and Game Information -.</p> <p>I have set up the schema correctly for both tables as per instructions and am trying to update a record in the 'Player' table based off player_id since it is the foreign key for the 'Player'.</p> <p>I understand this is very rudimentary as a command and have researched 'preparedstatements' in Java, but i was asked to do it this way. The codebelow basically collects a player_id via an input dialogue for which the record is being updated and all the columns are nullable except for the player_id. The code i have is as follows :</p> <pre><code>dbConnect(); JFrame frame; frame = new JFrame(); int searchP_id = Integer.parseInt(JOptionPane.showInputDialog(frame, &quot;Please enter the ID of the Player you would like to update&quot;)); String sql = &quot;UPDATE player SET&quot; +&quot; first_name= '&quot; + first_name + &quot;',&quot; + &quot; last_name= '&quot; + last_name + &quot;',&quot; + &quot; address= '&quot; + address + &quot;',&quot; + &quot; postal_code= '&quot; + postal_code + &quot;',&quot; + &quot; province= '&quot; + province + &quot;',&quot; + &quot; phone_number= '&quot; + phone_number + &quot;'&quot; + &quot; WHERE player_id =&quot; + searchP_id + &quot;;&quot; ; statement.executeUpdate(sql); if (statement != null) { //Close Statement statement.close(); } </code></pre> <p>I tried verifying that i have the command right as per sql statements and when i run this within sqlDeveloper - it updates the record.</p> <p>I have a controller class that basically runs these commands as part of a method that runs during an actionevent onUpdatePlayerButtonClick.</p> <p>I tried checking he syntax and cannot see the problem, but the only error i get whenever running this line is - &lt;&lt; Caused by: Error : 933, Position : 128, Sql = UPDATE player SET first_name= '', last_name= '', address= '', postal_code= '', province= '', phone_number= '' WHERE player_id =1;, OriginalSql = UPDATE player SET first_name= '', last_name= '', address= '', postal_code= '', province= '', phone_number= '' WHERE player_id =1;, Error Msg = ORA-00933: SQL command not properly ended &gt;&gt;.</p> <p>I tried reasearching the error code online and it said that there is a clause added that shouldnot be there and might be casuing the problem -</p> <p>this is a simple UPDATE query so where could it be going wrong ? The DB is getting connected to fine and the Insert command i have within my utility class works too.</p> <p>Thank you for any help provided !</p>
[ { "answer_id": 74671918, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": 1, "selected": false, "text": "String sql = \"UPDATE player SET\" +\n\" first_name= '\" + first_name + \"',\" +\n\" last_name= '\" + last_name + \"',\" +\n\" address= '\" + address + \"',\" +\n\" postal_code= '\" + postal_code + \"',\" +\n\" province= '\" + province + \"',\" +\n\" phone_number= '\" + phone_number + \"'\" +\n\" WHERE player_id =\" + searchP_id + \";\";\n PreparedStatement // Create the UPDATE query with placeholders for the values\nString sql = \"UPDATE player SET\" +\n\" first_name= ?,\" +\n\" last_name= ?,\" +\n\" address= ?,\" +\n\" postal_code= ?,\" +\n\" province= ?,\" +\n\" phone_number= ?\" +\n\" WHERE player_id = ?\";\n\n// Create a PreparedStatement object\nPreparedStatement pstmt = connection.prepareStatement(sql);\n\n// Set the values for the placeholders in the query\npstmt.setString(1, first_name);\npstmt.setString(2, last_name);\npstmt.setString(3, address);\npstmt.setString(4, postal_code);\npstmt.setString(5, province);\npstmt.setString(6, phone_number);\npstmt.setInt(7, searchP_id);\n\n// Execute the UPDATE query\npstmt.executeUpdate();\n\n// Close the PreparedStatement\npstmt.close();\n" }, { "answer_id": 74671950, "author": "Harry Coder", "author_id": 893952, "author_profile": "https://Stackoverflow.com/users/893952", "pm_score": 1, "selected": true, "text": "JDBC dbConnect();\n\nJFrame frame;\nframe = new JFrame();\n\nint searchP_id = Integer.parseInt(JOptionPane.showInputDialog(frame, \"Please enter the ID of the Player you would like to update\"));\n\nString sql = \"UPDATE player\" + \n \" SET first_name = ?, last_name = ?, address = ?,\" + \n \" postal_code = ?, province = ?, phone_number = ?\" +\n \" WHERE player_id = ?\";\n\nPreparedStatement preparedStatement =\n connection.prepareStatement(sql);\n\npreparedStatement.setString(1, \"the_first_name\");\npreparedStatement.setString(2, \"the_last_name\");\npreparedStatement.setString(3, \"the_address\");\npreparedStatement.setString(4, \"the_postal_code\");\npreparedStatement.setString(5, \"the_province\");\npreparedStatement.setString(6, \"the_phone_number\");\npreparedStatement.setLong(7, \"the_player_id\");\n\npreparedStatement.executeUpdate(sql);\n\nif (preparedStatement != null) {\n //Close Statement\n preparedStatement.close();\n}\n JDBC" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74671815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16951322/" ]
74,671,817
<p>i'm sorry if this question is answered already but i don't find it in the search. :-)</p> <p>I'm trying to access a li text value to set an id for this. I tried the following.</p> <p>Below my jquery code</p> <pre><code>$(document).ready(function() { $(&quot;#hinzubutton&quot;).click(function(){ $(&quot;#MyUL&quot;).append('&lt;li&gt; &lt;/li&gt;'); $(&quot;li&quot;).append(Eingabe.value).attr(&quot;id&quot;, &quot;Eingabe&quot;); console.log($(Eingabe).text()); }); </code></pre> <p>this is the body of my HTML Code (jquery file in the head)</p> <pre><code>&lt;body&gt; &lt;h1&gt; Das ist eine Überschrift!&lt;/h1&gt; &lt;ul id=&quot;MyUL&quot;&gt; &lt;/ul&gt; &lt;input type=&quot;text&quot; id=&quot;Eingabe&quot;&gt; &lt;button id=&quot;hinzubutton&quot;&gt; Hinzu &lt;/button&gt; &lt;button id=&quot;loeschbutton&quot;&gt; Löschen &lt;/button&gt; &lt;script src=&quot;/js/test.js&quot;&gt; &lt;/script&gt; &lt;/body&gt; </code></pre> <p>the console.log shows me my entered value correctly but i can't figure out how to get the value to set an own id. Is this possible?</p> <p>If i check the Code on my Browser it looks like this after add an value with the inputfield for example input is 1.</p> <pre><code>&lt;li id=&quot;Eingabe&quot;&gt; ::marker &quot;1&quot; (i want to set an id here if its possible) &quot; &quot; &lt;/li&gt; </code></pre> <p>Thanks a lot.</p> <p>I tried to access the value text but i cant append an id. My first try was to set the .attr(&quot;id&quot;, &quot;li1&quot;) but it doesn't work for me.</p>
[ { "answer_id": 74671918, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": 1, "selected": false, "text": "String sql = \"UPDATE player SET\" +\n\" first_name= '\" + first_name + \"',\" +\n\" last_name= '\" + last_name + \"',\" +\n\" address= '\" + address + \"',\" +\n\" postal_code= '\" + postal_code + \"',\" +\n\" province= '\" + province + \"',\" +\n\" phone_number= '\" + phone_number + \"'\" +\n\" WHERE player_id =\" + searchP_id + \";\";\n PreparedStatement // Create the UPDATE query with placeholders for the values\nString sql = \"UPDATE player SET\" +\n\" first_name= ?,\" +\n\" last_name= ?,\" +\n\" address= ?,\" +\n\" postal_code= ?,\" +\n\" province= ?,\" +\n\" phone_number= ?\" +\n\" WHERE player_id = ?\";\n\n// Create a PreparedStatement object\nPreparedStatement pstmt = connection.prepareStatement(sql);\n\n// Set the values for the placeholders in the query\npstmt.setString(1, first_name);\npstmt.setString(2, last_name);\npstmt.setString(3, address);\npstmt.setString(4, postal_code);\npstmt.setString(5, province);\npstmt.setString(6, phone_number);\npstmt.setInt(7, searchP_id);\n\n// Execute the UPDATE query\npstmt.executeUpdate();\n\n// Close the PreparedStatement\npstmt.close();\n" }, { "answer_id": 74671950, "author": "Harry Coder", "author_id": 893952, "author_profile": "https://Stackoverflow.com/users/893952", "pm_score": 1, "selected": true, "text": "JDBC dbConnect();\n\nJFrame frame;\nframe = new JFrame();\n\nint searchP_id = Integer.parseInt(JOptionPane.showInputDialog(frame, \"Please enter the ID of the Player you would like to update\"));\n\nString sql = \"UPDATE player\" + \n \" SET first_name = ?, last_name = ?, address = ?,\" + \n \" postal_code = ?, province = ?, phone_number = ?\" +\n \" WHERE player_id = ?\";\n\nPreparedStatement preparedStatement =\n connection.prepareStatement(sql);\n\npreparedStatement.setString(1, \"the_first_name\");\npreparedStatement.setString(2, \"the_last_name\");\npreparedStatement.setString(3, \"the_address\");\npreparedStatement.setString(4, \"the_postal_code\");\npreparedStatement.setString(5, \"the_province\");\npreparedStatement.setString(6, \"the_phone_number\");\npreparedStatement.setLong(7, \"the_player_id\");\n\npreparedStatement.executeUpdate(sql);\n\nif (preparedStatement != null) {\n //Close Statement\n preparedStatement.close();\n}\n JDBC" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74671817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16837874/" ]
74,671,824
<pre><code>a = [ [200,300,5000,400],[554,500,1000,652],[800,500,650,800],[950,120,470,500],[500,600,2000,100]] for i in range(len(a)): for j in range(len(a[i])): print(a[i][j], end=' ') print() </code></pre> <p>I am trying to increase each value by 20%, and then print the matrix with the increase, For example, this is the original matrix [200,300],[500,400] and I will increase 20% of each and show the matrix with new values [240,360],[600,480]</p>
[ { "answer_id": 74671918, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": 1, "selected": false, "text": "String sql = \"UPDATE player SET\" +\n\" first_name= '\" + first_name + \"',\" +\n\" last_name= '\" + last_name + \"',\" +\n\" address= '\" + address + \"',\" +\n\" postal_code= '\" + postal_code + \"',\" +\n\" province= '\" + province + \"',\" +\n\" phone_number= '\" + phone_number + \"'\" +\n\" WHERE player_id =\" + searchP_id + \";\";\n PreparedStatement // Create the UPDATE query with placeholders for the values\nString sql = \"UPDATE player SET\" +\n\" first_name= ?,\" +\n\" last_name= ?,\" +\n\" address= ?,\" +\n\" postal_code= ?,\" +\n\" province= ?,\" +\n\" phone_number= ?\" +\n\" WHERE player_id = ?\";\n\n// Create a PreparedStatement object\nPreparedStatement pstmt = connection.prepareStatement(sql);\n\n// Set the values for the placeholders in the query\npstmt.setString(1, first_name);\npstmt.setString(2, last_name);\npstmt.setString(3, address);\npstmt.setString(4, postal_code);\npstmt.setString(5, province);\npstmt.setString(6, phone_number);\npstmt.setInt(7, searchP_id);\n\n// Execute the UPDATE query\npstmt.executeUpdate();\n\n// Close the PreparedStatement\npstmt.close();\n" }, { "answer_id": 74671950, "author": "Harry Coder", "author_id": 893952, "author_profile": "https://Stackoverflow.com/users/893952", "pm_score": 1, "selected": true, "text": "JDBC dbConnect();\n\nJFrame frame;\nframe = new JFrame();\n\nint searchP_id = Integer.parseInt(JOptionPane.showInputDialog(frame, \"Please enter the ID of the Player you would like to update\"));\n\nString sql = \"UPDATE player\" + \n \" SET first_name = ?, last_name = ?, address = ?,\" + \n \" postal_code = ?, province = ?, phone_number = ?\" +\n \" WHERE player_id = ?\";\n\nPreparedStatement preparedStatement =\n connection.prepareStatement(sql);\n\npreparedStatement.setString(1, \"the_first_name\");\npreparedStatement.setString(2, \"the_last_name\");\npreparedStatement.setString(3, \"the_address\");\npreparedStatement.setString(4, \"the_postal_code\");\npreparedStatement.setString(5, \"the_province\");\npreparedStatement.setString(6, \"the_phone_number\");\npreparedStatement.setLong(7, \"the_player_id\");\n\npreparedStatement.executeUpdate(sql);\n\nif (preparedStatement != null) {\n //Close Statement\n preparedStatement.close();\n}\n JDBC" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74671824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7922452/" ]
74,671,829
<p>I have currently started with PROLOG and I want to write a predicate which checks if a given object is in this list or not. If the object is in the list the predicate should return the index of the element. If the element is not found it should return 0.</p> <p>It should work like this: <code>find(3,[1,4,5,3,2,3],N). -&gt; yes. N / 4</code> <code>find(2,[1,3,4,5,6,7],N). -&gt; yes. N / 0</code></p> <p>But I have problems with counting up the index N and maybe someone here can help. I've seen many different ways on how to traverse a list but I found so many different ways and I wasn't able to understand how they work. I would be really happy if someone can provide a solution and explain how it works and why.</p> <p>This is what I wrote so far:</p> <pre><code>find(X, [X|TAIL], N) :- N is 1, write(N). find(X, [], N) :- N is 0, write(N). find(X, [_|TAIL], N) :- find(X, TAIL, N + 1). </code></pre> <p>It is working for the basecases:</p> <pre><code>find(a, [a, b, c, d, e, f, g], N) -&gt; yes. N / 1. find(j, [a, b, c, d, e, f, g], N) -&gt; yes. N / 0. </code></pre> <p>But when it is starting with recursion It is not working anymore and I don't understand what's going wrong.</p> <p>For the recursion case it gives me this: <code> find(b, [a, b, c, d, e, f, g], N) -&gt; no.</code></p> <p>I am thankful for every answer and every comment!</p>
[ { "answer_id": 74673641, "author": "TessellatingHeckler", "author_id": 478656, "author_profile": "https://Stackoverflow.com/users/478656", "pm_score": 0, "selected": false, "text": "find_([], _, _, 0).\nfind_([X|_], X, Counter, Counter).\nfind_([_|T], X, Counter, Result) :-\n succ(Counter, Counter2),\n find_(T, X, Counter2, Result).\n\nfind(X, List, Index) :-\n find_(List, X, 1, Index).\n succ/2 ?- find(b, [a,b,c,d,a,b,c], X).\nX = 2 ;\nX = 6 ;\nX = 0\n" }, { "answer_id": 74674050, "author": "David Krell", "author_id": 12118403, "author_profile": "https://Stackoverflow.com/users/12118403", "pm_score": 0, "selected": false, "text": "find(X [], 0).\nfind(X, [X|_], 1).\nfind(X, [_|Xs], N) :- find(X, Xs, Rest), N is 1 + Rest.\n ?- find(a, [a, b, c, d], N) -> yes. N = 1. ?- find(c, [a, b, c, d], N) -> yes. N = 1. ?- find(d, [a, b, c], N) -> yes. N = 3. ?- find(d, [a, b, c], N) -> yes. N = 0. ?- find(d, [a, b, c], N) find(d, [b,c], Rest) find(d, [b,c], Rest) find(d, [c], Rest) find(d, [c], Rest) find(X, [], 0).\nfind(X, [X|_], 1).\n\nfind(X, [], -N, List) :- list_length(List, LENGTH), N is LENGTH, write(LENGTH).\nfind(X, [X|_], 1, List).\nfind(X, [Y|Xs], N, List) :- find(X, Xs, Rest, List), N is 1 + Rest.\n\nfind(X, [Y|Xs], N) :- find(X, Xs, Rest, [Y|Xs]), N is 1 + Rest.\n\nlist_length([], 0).\nlist_length([X|Xs], LENGTH) :- list_length(Xs, Rest), LENGTH is 1 + Rest.\n" }, { "answer_id": 74677184, "author": "brebs", "author_id": 17628336, "author_profile": "https://Stackoverflow.com/users/17628336", "pm_score": 1, "selected": false, "text": "nth1_once_else_0(Elem, Lst, Nth1) :-\n % Start at element 1\n nth1_once_else_0_(Lst, Elem, 1, Nth1),\n % Stop after finding 1 solution\n !.\n% Otherwise, succeed with 0\nnth1_once_else_0(_Elem, _Lst, 0).\n\n% Using Upto and Nth1 arguments, rather than unnecessary & slow recursion\nnth1_once_else_0_([Elem|_], Elem, Nth1, Nth1).\nnth1_once_else_0_([_|T], Elem, Upto, Nth1) :-\n % Loop through the list elements\n Upto1 is Upto + 1,\n nth1_once_else_0_(T, Elem, Upto1, Nth1).\n ?- nth1_once_else_0(c, [a, b, c, a, b, c], Nth1).\nNth1 = 3.\n\n?- nth1_once_else_0(z, [a, b, c, a, b, c], Nth1).\nNth1 = 0.\n\n?- nth1_once_else_0(Char, [a, b, c, a, b, c], Nth1).\nChar = a,\nNth1 = 1.\n\n?- nth1_once_else_0(Char, [a, b, c, a, b, c], 2).\nChar = b.\n\n?- nth1_once_else_0(b, [a, b, c, a, b, c], 3).\nfalse.\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74671829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12118403/" ]
74,671,835
<p>Every time if my session is invalid i got this output: &quot;Please enter your phone (or bot token): &quot; Is there anyway to pass it or ignore it?</p> <p>I tried to edit telethon source code, but im bad at it))</p>
[ { "answer_id": 74672027, "author": "Marz1k", "author_id": 17545131, "author_profile": "https://Stackoverflow.com/users/17545131", "pm_score": 0, "selected": false, "text": "client = TelegramClient(f\"session\", api_id, api_hash)\nclient.connect()\nprint(client)\nif client.is_user_authorized():\n print(\"VALID\")\nelse:\n print('NO VALID')\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74671835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17545131/" ]
74,671,856
<p>I created a TODO List. I have a input and take the value of the input to append it to an element. With the value of the input i create a new list elemnet with a delete button. Now i have troubles to delete my new created elemnt within the list.</p> <p>this is my js code</p> <pre><code>//create a variable for the button let btn = document.querySelector('.add'); // create a variable for the list let ul = document.querySelector('.list'); //create a variable for the input to get the value let input = document.querySelector('.txt'); // with add button take the value from the input and create a new li elemtn btn.addEventListener('click', function () { let txt = input.value; // create variable for input value let li = document.createElement('li'); // create new list elemnt li.textContent = txt; let but = document.createElement('button'); // create ne button elemnt but.textContent = 'delete'; li.textContent = txt; li.appendChild(but); ul.appendChild(li); }); // try to delte list element from unorderd list but.addEventListener('click', function () { ul.removeChild(li); }); </code></pre> <p>Here the html code</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot; /&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot; /&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt; &lt;title&gt;Document&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;styles.css&quot; /&gt; &lt;/head&gt; &lt;body&gt; &lt;div id=&quot;container&quot;&gt; &lt;input type=&quot;text&quot; class=&quot;txt&quot; /&gt; &lt;button class=&quot;add&quot;&gt;Add to list&lt;/button&gt; &lt;ul class=&quot;list&quot;&gt;&lt;/ul&gt; &lt;/div&gt; &lt;script src=&quot;index.js&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The goal is to delete the list element from the todo app with the delete button</p> <p><a href="https://i.stack.imgur.com/pr2bi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pr2bi.png" alt="todo list with delete button" /></a></p> <p>I tried to add an eventhandler to the delete Button within each List Element. I tried to use removechild but it will not work.</p>
[ { "answer_id": 74671935, "author": "dev", "author_id": 6476490, "author_profile": "https://Stackoverflow.com/users/6476490", "pm_score": 0, "selected": false, "text": "// create the element\nvar newElement = document.createElement('p');\nnewElement.innerHTML = 'Click here to remove me';\n\n// add the element to the DOM\ndocument.body.appendChild(newElement);\n\n// add a click event listener to the element\nnewElement.addEventListener('click', function() {\n // remove the element from the DOM\n document.body.removeChild(newElement);\n});\n\n" }, { "answer_id": 74672050, "author": "Tibrogargan", "author_id": 2487517, "author_profile": "https://Stackoverflow.com/users/2487517", "pm_score": 1, "selected": false, "text": "let document.addEventListener('DOMContentLoaded', function() {\n //create a variable for the button\n let btn = document.querySelector('.add');\n // create a variable for the list\n let ul = document.querySelector('.list');\n //create a variable for the input to get the value\n let input = document.querySelector('.txt');\n\n // with add button take the value from the input and create a new li elemtn\n btn.addEventListener('click', function () {\n let txt = input.value; // create variable for input value\n let li = document.createElement('li'); // create new list elemnt\n li.textContent = txt;\n let but = document.createElement('button'); // create ne button elemnt\n but.textContent = 'delete';\n but.addEventListener('click', function () {\n ul.removeChild(li);\n });\n li.appendChild(but);\n ul.appendChild(li);\n });\n // try to delte list element from unorderd list\n}) <div id=\"container\">\n <input type=\"text\" class=\"txt\" />\n <button class=\"add\">Add to list</button>\n\n <ul class=\"list\"></ul>\n </div>\n <script src=\"index.js\"></script>" }, { "answer_id": 74674551, "author": "DFaking", "author_id": 18270605, "author_profile": "https://Stackoverflow.com/users/18270605", "pm_score": 1, "selected": true, "text": "//create a variable for the button\nlet btn = document.querySelector('.add');\n// create a variable for the list\nlet ul = document.querySelector('.list');\n//create a variable for the input to get the value\nlet input = document.querySelector('.txt');\n\n// create variable for the delete button\nlet but = document.createElement('button');\nbut.textContent = 'delete';\n\n// with add button take the value from the input and create a new li elemtn\nbtn.addEventListener('click', function () {\n let txt = input.value; // create variable for input value\n let li = document.createElement('li'); // create new list elemnt\n li.textContent = txt;\n li.appendChild(but);\n\n ul.appendChild(li);\n});\n\n// delete list element from unordered list when delete button is clicked\nbut.addEventListener('click', function () {\n ul.removeChild(this.parentElement);\n});\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74671856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16850827/" ]
74,671,865
<p>I've been struggling for the past couple days with getting my python code to be more efficient, while also getting the run time to be with in the given specifications of the problem below ( 3 seconds, for any given input). Was told that linear time may help, but was hoping I can get some help on how I'd approach it with my existing code here, would really appreciate the help.</p> <p><strong>This is the given problem</strong>: *Dan has a list of problems suitable for Assignment 4. The difficulties of these problems are stored in a list of integers a. The i-th problem’s difficulty is represented by a[i] (the higher the integer, the more difficult the problem).</p> <p>Dan is too busy eating saltines to worry about Assignment 4 decisions, so he asks Michael the TA to select at least two problems from the list for the assignment. Since there are many possible subsets of the problems to consider and Michael has a life, he decides to consider only sublists (definition follows) of the list of problems.</p> <p>To make grading the assignment easier, Michael wants to pick problems that don’t vary too much in difficulty. What is the smallest difference between the difficulties of the most difficult selected problem and the least difficult selected problem he can achieve by selecting a sublist of length at least 2 of the original list of problems?</p> <p><strong>Definition</strong>: A sublist of a list a is any list you can obtain by removing some (possibly 0) elements from the start of a and then removing some (possibly 0) elements from the end of it. (It’s like the definition of segment from lecture.) .*</p> <p><strong>Input</strong> The input consists of a single line containing the integers in the list a, separated by single spaces.</p> <p><strong>Output</strong> Print a single integer indicating the smallest difference in difficulties Michael can achieve.</p> <p><strong>Constraints</strong> 2 &lt;= len(a) &lt;= 500000 1 &lt;= a[i] &lt;= 10**9</p> <p>Time Limit: Your program must finish running on any valid input within 3 seconds</p> <p><strong>Sample Input 1</strong> 10 6 9 1</p> <p><strong>Sample Output 1</strong> 3</p> <p><strong>My code:</strong></p> <pre><code>import time # import time module arr = list(map(int, input().split(&quot; &quot;))) st = time.time() diff = 10**9 for i in range(len(arr)-1): max_ele = min_ele = arr[i] for j in range(i+1, len(arr)): max_ele = max(max_ele, arr[j]) min_ele = min(min_ele, arr[j]) if max_ele - min_ele &lt;= diff: diff = max_ele - min_ele print(diff) # end = time.time() - st #print(end) ``` ` </code></pre>
[ { "answer_id": 74671928, "author": "Nova", "author_id": 16807831, "author_profile": "https://Stackoverflow.com/users/16807831", "pm_score": 1, "selected": false, "text": "import time # import time module\narr = list(map(int, input().split(\" \")))\n\n# sort the list in ascending order\narr.sort()\n\n# initialize the minimum and maximum elements we have seen so far\nmin_ele = arr[0]\nmax_ele = arr[1]\n\n# initialize the smallest difference between the maximum and minimum element\n# in any sublist of length at least 2\ndiff = max_ele - min_ele\n\n# iterate through the list, starting from the second element\nfor i in range(1, len(arr)):\n # update the minimum and maximum elements\n min_ele = min(min_ele, arr[i])\n max_ele = max(max_ele, arr[i])\n\n # update the smallest difference\n diff = min(diff, max_ele - min_ele)\n\n# print the smallest difference\nprint(diff)\n" }, { "answer_id": 74672086, "author": "Michael", "author_id": 12429692, "author_profile": "https://Stackoverflow.com/users/12429692", "pm_score": 0, "selected": false, "text": "diff=min((abs(a-b) for a,b in zip(arr[:-1],arr[1:])))\n diff=10**9\nfor a,b in zip(arr[:-1],arr[1:]):\n diff=min(diff,abs(a-b))\nreturn diff\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74671865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20379696/" ]
74,671,883
<p>I have a Pandas dataframe such that <code>df['cname']</code>:</p> <pre><code>0 [berkshire, hathaway] 1 [icbc] 2 [saudi, arabian, oil, company, saudi, aramco] 3 [jpmorgan, chase] 4 [china, construction, bank] Name: tokenized_company_name, dtype: object </code></pre> <p>and another Pandas dataframe such that <code>tfidf['output']</code>:</p> <pre><code>[0.7071067811865476, 0.7071067811865476] [1.0] [0.3779598156018814, 0.39838548612653973, 0.39838548612653973, 0.3285496573358837, 0.6570993146717674] [0.7071067811865476, 0.7071067811865476] [0.4225972188244829, 0.510750779645552, 0.7486956870005814] </code></pre> <p>I'm trying to sort each list of tokens in <code>f_sp['tokenized_company_name']</code> by <code>tfidf['output_column']</code> such that I get:</p> <pre><code>0 [berkshire, hathaway] # no difference 1 [icbc] # no difference 2 [aramco, arabian, oil, saudi, company] # re-ordered by decreasing value of tf_sp['output_column'] 3 [chase, jpmorgan] # tied elements should be ordered alphabetically 4 [bank, construction, china] # re-ordered by decreasing value of tf_sp['output_column'] </code></pre> <p>Here's what I've tried so far:</p> <pre><code>(f_sp.apply(lambda x: sorted(x['tokenized_company_name'], key=lambda y: tf_sp.loc[x.name,'output_column'][x['tokenized_company_name'].index(y)], reverse=True), axis=1)) </code></pre> <p>But I get the following error:</p> <pre><code>--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Input In [166], in &lt;cell line: 1&gt;() ----&gt; 1 (f_sp.apply(lambda x: sorted(x['tokenized_company_name'], 2 key=lambda y: tf_sp.loc[x.name,'output_column'][x['tokenized_company_name'].index(y)], 3 reverse=True), axis=1)) File ~\.conda\envs\python37dev\lib\site-packages\pandas\core\frame.py:9555, in DataFrame.apply(self, func, axis, raw, result_type, args, **kwargs) 9544 from pandas.core.apply import frame_apply 9546 op = frame_apply( 9547 self, 9548 func=func, (...) 9553 kwargs=kwargs, 9554 ) -&gt; 9555 return op.apply().__finalize__(self, method=&quot;apply&quot;) File ~\.conda\envs\python37dev\lib\site-packages\pandas\core\apply.py:746, in FrameApply.apply(self) 743 elif self.raw: 744 return self.apply_raw() --&gt; 746 return self.apply_standard() File ~\.conda\envs\python37dev\lib\site-packages\pandas\core\apply.py:873, in FrameApply.apply_standard(self) 872 def apply_standard(self): --&gt; 873 results, res_index = self.apply_series_generator() 875 # wrap results 876 return self.wrap_results(results, res_index) File ~\.conda\envs\python37dev\lib\site-packages\pandas\core\apply.py:889, in FrameApply.apply_series_generator(self) 886 with option_context(&quot;mode.chained_assignment&quot;, None): 887 for i, v in enumerate(series_gen): 888 # ignore SettingWithCopy here in case the user mutates --&gt; 889 results[i] = self.f(v) 890 if isinstance(results[i], ABCSeries): 891 # If we have a view on v, we need to make a copy because 892 # series_generator will swap out the underlying data 893 results[i] = results[i].copy(deep=False) Input In [166], in &lt;lambda&gt;(x) ----&gt; 1 (f_sp.apply(lambda x: sorted(x['tokenized_company_name'], 2 key=lambda y: tf_sp.loc[x.name,'output_column'][x['tokenized_company_name'].index(y)], 3 reverse=True), axis=1)) Input In [166], in &lt;lambda&gt;.&lt;locals&gt;.&lt;lambda&gt;(y) 1 (f_sp.apply(lambda x: sorted(x['tokenized_company_name'], ----&gt; 2 key=lambda y: tf_sp.loc[x.name,'output_column'][x['tokenized_company_name'].index(y)], 3 reverse=True), axis=1)) IndexError: list index out of range </code></pre> <p>Why is this happening? Each list of lists has the same number of elements.</p>
[ { "answer_id": 74671928, "author": "Nova", "author_id": 16807831, "author_profile": "https://Stackoverflow.com/users/16807831", "pm_score": 1, "selected": false, "text": "import time # import time module\narr = list(map(int, input().split(\" \")))\n\n# sort the list in ascending order\narr.sort()\n\n# initialize the minimum and maximum elements we have seen so far\nmin_ele = arr[0]\nmax_ele = arr[1]\n\n# initialize the smallest difference between the maximum and minimum element\n# in any sublist of length at least 2\ndiff = max_ele - min_ele\n\n# iterate through the list, starting from the second element\nfor i in range(1, len(arr)):\n # update the minimum and maximum elements\n min_ele = min(min_ele, arr[i])\n max_ele = max(max_ele, arr[i])\n\n # update the smallest difference\n diff = min(diff, max_ele - min_ele)\n\n# print the smallest difference\nprint(diff)\n" }, { "answer_id": 74672086, "author": "Michael", "author_id": 12429692, "author_profile": "https://Stackoverflow.com/users/12429692", "pm_score": 0, "selected": false, "text": "diff=min((abs(a-b) for a,b in zip(arr[:-1],arr[1:])))\n diff=10**9\nfor a,b in zip(arr[:-1],arr[1:]):\n diff=min(diff,abs(a-b))\nreturn diff\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74671883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2205916/" ]
74,671,893
<p>I have a have a dataset that looks something like this:</p> <pre><code>data &lt;- data.frame(group = c(&quot;09081997&quot;, &quot;13122006&quot;, &quot;09081997&quot;, &quot;22031969&quot;, &quot;09081997&quot;), date1 = c(&quot;2021-08-09&quot;, &quot;2021-08-10&quot;, &quot;2021-08-21&quot;, &quot;2021-07-19&quot;, &quot;2021-07-15&quot;)) </code></pre> <p>There are duplicated numbers in &quot;group&quot; variable. For example, I need to filter between the dates &quot;2021-08-01&quot; to &quot;2021-08-31&quot;. By doing that, I would &quot;delete&quot; the last two numbers from &quot;group&quot;, but I need to keep all duplicates, even if they're not between the time period I want to filter. I'd need to keep all &quot;09081997&quot; registers. At least one of the duplicates would have to be in the time period.</p> <p>Is it possible to do that?</p>
[ { "answer_id": 74671934, "author": "Vinícius Félix", "author_id": 9696037, "author_profile": "https://Stackoverflow.com/users/9696037", "pm_score": 1, "selected": false, "text": "library(dplyr)\nlibrary(lubridate)\n\ndata %>% \n mutate(across(.cols = starts_with(\"date\"),.fns = ymd)) %>% \n add_count(group) %>% \n filter(!(n == 1 & (date1 >= ymd(\"2021-08-01\") & date2 <= ymd(\"2021-08-31\"))))\n\n group date1 date2 n\n1 09081997 2021-08-09 2021-08-31 3\n2 09081997 2021-08-21 2021-08-29 3\n3 22031969 2021-07-19 2021-07-20 1\n4 09081997 2021-07-15 2021-07-19 3\n" }, { "answer_id": 74673039, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 0, "selected": false, "text": "ave grepl '2021-08' pat any date* mode \"logical\" rowSums '2021-08' data[with(data, ave(cbind(date1, date2), group, FUN=\\(x) any(grepl(x, pat='2021-08')))) |> \n `mode<-`('logical') |> rowSums() |> base::`>`(0), ]\n# group date1 date2\n# 1 09081997 2021-08-09 2021-08-31\n# 2 13122006 2021-08-10 2021-08-22\n# 3 09081997 2021-08-21 2021-08-29\n# 5 09081997 2021-07-15 2021-07-19\n data1[with(data1, as.logical(ave(date1, group, FUN=\\(x) any(grepl(x, pat='2021-08'))))), ]\n# group date1\n# 1 09081997 2021-08-09\n# 2 13122006 2021-08-10\n# 3 09081997 2021-08-21\n# 5 09081997 2021-07-15\n grepl data1[with(data1, as.logical(ave(date1, group, FUN=\\(x) any(\n x >= \"2021-03-08\" | x <= \"2021-06-04\"\n)))), ]\n \n data <- structure(list(group = c(\"09081997\", \"13122006\", \"09081997\", \n\"22031969\", \"09081997\"), date1 = c(\"2021-08-09\", \"2021-08-10\", \n\"2021-08-21\", \"2021-07-19\", \"2021-07-15\"), date2 = c(\"2021-08-31\", \n\"2021-08-22\", \"2021-08-29\", \"2021-07-20\", \"2021-07-19\")), class = \"data.frame\", row.names = c(NA, \n-5L))\n\ndata1 <- data[1:2]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74671893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17659253/" ]
74,671,920
<p>I am trying to control the position of two calls of <code>geom_text</code> inside <code>geom_bar</code>, but I just can't get it right.</p> <p>This is what I have so far:</p> <p><a href="https://i.stack.imgur.com/qbp7M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qbp7M.png" alt="enter image description here" /></a></p> <p>However, I would like to change two things in this plot:</p> <ol> <li>Put the letters (first geom_text call) at the top left corner of the bars, just before the error bars. Or perhaps on top of the error bars.</li> <li>Put the numbers (second geom_text call) in the middle of the bars.</li> </ol> <p>Here are my code and dataset sample:</p> <pre><code>library(ggplot2) dat &lt;- structure(list(ObservationId = c(&quot;Control&quot;, &quot;Control&quot;, &quot;Control&quot;, &quot;Control&quot;, &quot;Control&quot;, &quot;Control&quot;, &quot;Control&quot;, &quot;Control&quot;, &quot;Control&quot; ), Treatment = c(&quot;TREATMENT A&quot;, &quot;TREATMENT B&quot;, &quot;UNTREATED&quot;, &quot;TREATMENT A&quot;, &quot;TREATMENT B&quot;, &quot;UNTREATED&quot;, &quot;TREATMENT A&quot;, &quot;TREATMENT B&quot;, &quot;UNTREATED&quot; ), day_class = c(&quot;Time1&quot;, &quot;Time1&quot;, &quot;Time1&quot;, &quot;Time2&quot;, &quot;Time2&quot;, &quot;Time2&quot;, &quot;Time3&quot;, &quot;Time3&quot;, &quot;Time3&quot;), Estimate = c(100, 99.8, 0.7, 97.2, 91.2, 7.2, 94.6, 87.3, 14.5), SE = c(4.2, 4.4, 3.7, 3.6, 4.1, 3.8, 3.7, 4.1, 3.8), df = c(38.5, 42.3, 37.4, 33.5, 37.4, 37.8, 33.9, 38.5, 38.1), lower.CL = c(91.6, 90.9, -6.9, 89.8, 83, -0.4, 87.2, 79, 6.9), upper.CL = c(108.4, 108.7, 8.3, 104.6, 99.5, 14.8, 102.1, 95.7, 22.1), Class = c(&quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;A&quot;, &quot;A&quot;, &quot;B&quot;)), row.names = c(NA, 9L), class = &quot;data.frame&quot;) ggplot(dat, aes(x = Treatment, y = Estimate, group = day_class, fill = day_class)) + theme_bw() + geom_col(position = &quot;dodge&quot;, color = &quot;black&quot;) + geom_errorbar(aes(ymin = lower.CL, ymax = upper.CL), width = 0.2, position = position_dodge(0.9)) + geom_text(aes(label = Class, group = day_class), position = position_dodge(width = 0.9), color = 'blue', size = 5) + geom_text(aes(label = round(Estimate,1), group = day_class), position = position_dodge(width = 0.9), size = 4) </code></pre> <p>How can I achieve those changes?</p>
[ { "answer_id": 74671934, "author": "Vinícius Félix", "author_id": 9696037, "author_profile": "https://Stackoverflow.com/users/9696037", "pm_score": 1, "selected": false, "text": "library(dplyr)\nlibrary(lubridate)\n\ndata %>% \n mutate(across(.cols = starts_with(\"date\"),.fns = ymd)) %>% \n add_count(group) %>% \n filter(!(n == 1 & (date1 >= ymd(\"2021-08-01\") & date2 <= ymd(\"2021-08-31\"))))\n\n group date1 date2 n\n1 09081997 2021-08-09 2021-08-31 3\n2 09081997 2021-08-21 2021-08-29 3\n3 22031969 2021-07-19 2021-07-20 1\n4 09081997 2021-07-15 2021-07-19 3\n" }, { "answer_id": 74673039, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 0, "selected": false, "text": "ave grepl '2021-08' pat any date* mode \"logical\" rowSums '2021-08' data[with(data, ave(cbind(date1, date2), group, FUN=\\(x) any(grepl(x, pat='2021-08')))) |> \n `mode<-`('logical') |> rowSums() |> base::`>`(0), ]\n# group date1 date2\n# 1 09081997 2021-08-09 2021-08-31\n# 2 13122006 2021-08-10 2021-08-22\n# 3 09081997 2021-08-21 2021-08-29\n# 5 09081997 2021-07-15 2021-07-19\n data1[with(data1, as.logical(ave(date1, group, FUN=\\(x) any(grepl(x, pat='2021-08'))))), ]\n# group date1\n# 1 09081997 2021-08-09\n# 2 13122006 2021-08-10\n# 3 09081997 2021-08-21\n# 5 09081997 2021-07-15\n grepl data1[with(data1, as.logical(ave(date1, group, FUN=\\(x) any(\n x >= \"2021-03-08\" | x <= \"2021-06-04\"\n)))), ]\n \n data <- structure(list(group = c(\"09081997\", \"13122006\", \"09081997\", \n\"22031969\", \"09081997\"), date1 = c(\"2021-08-09\", \"2021-08-10\", \n\"2021-08-21\", \"2021-07-19\", \"2021-07-15\"), date2 = c(\"2021-08-31\", \n\"2021-08-22\", \"2021-08-29\", \"2021-07-20\", \"2021-07-19\")), class = \"data.frame\", row.names = c(NA, \n-5L))\n\ndata1 <- data[1:2]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74671920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4272937/" ]
74,671,936
<p>I need to tune the number of hidden layers and their hidden size of a regression model.</p> <p>As I tested before, generic hyperparameter optimization algorithms (grid search and random search) are not enough due to a large number of hyperparameters. Could I use PBT or Bayesian optimization to tune the network structure? In general, is there any optimization methods for tuning the hidden layer size or number of hidden layers except grid search and random search?</p>
[ { "answer_id": 74671934, "author": "Vinícius Félix", "author_id": 9696037, "author_profile": "https://Stackoverflow.com/users/9696037", "pm_score": 1, "selected": false, "text": "library(dplyr)\nlibrary(lubridate)\n\ndata %>% \n mutate(across(.cols = starts_with(\"date\"),.fns = ymd)) %>% \n add_count(group) %>% \n filter(!(n == 1 & (date1 >= ymd(\"2021-08-01\") & date2 <= ymd(\"2021-08-31\"))))\n\n group date1 date2 n\n1 09081997 2021-08-09 2021-08-31 3\n2 09081997 2021-08-21 2021-08-29 3\n3 22031969 2021-07-19 2021-07-20 1\n4 09081997 2021-07-15 2021-07-19 3\n" }, { "answer_id": 74673039, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 0, "selected": false, "text": "ave grepl '2021-08' pat any date* mode \"logical\" rowSums '2021-08' data[with(data, ave(cbind(date1, date2), group, FUN=\\(x) any(grepl(x, pat='2021-08')))) |> \n `mode<-`('logical') |> rowSums() |> base::`>`(0), ]\n# group date1 date2\n# 1 09081997 2021-08-09 2021-08-31\n# 2 13122006 2021-08-10 2021-08-22\n# 3 09081997 2021-08-21 2021-08-29\n# 5 09081997 2021-07-15 2021-07-19\n data1[with(data1, as.logical(ave(date1, group, FUN=\\(x) any(grepl(x, pat='2021-08'))))), ]\n# group date1\n# 1 09081997 2021-08-09\n# 2 13122006 2021-08-10\n# 3 09081997 2021-08-21\n# 5 09081997 2021-07-15\n grepl data1[with(data1, as.logical(ave(date1, group, FUN=\\(x) any(\n x >= \"2021-03-08\" | x <= \"2021-06-04\"\n)))), ]\n \n data <- structure(list(group = c(\"09081997\", \"13122006\", \"09081997\", \n\"22031969\", \"09081997\"), date1 = c(\"2021-08-09\", \"2021-08-10\", \n\"2021-08-21\", \"2021-07-19\", \"2021-07-15\"), date2 = c(\"2021-08-31\", \n\"2021-08-22\", \"2021-08-29\", \"2021-07-20\", \"2021-07-19\")), class = \"data.frame\", row.names = c(NA, \n-5L))\n\ndata1 <- data[1:2]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74671936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14082033/" ]
74,671,990
<p>In TC2000 its possible to use minv3.1 (minimum volume requirement for each of the last 3 bars) which I cannot figure out for pinescript (since its not the same a average volume). How would one create it?</p> <p>I've only tried</p> <p>V[0] &gt; 1000 <strong>and</strong> V[1] &gt; 1000 <strong>and</strong> V[2] &gt; 1000</p> <p>But I'm not sure if that's even correct or the best approach.</p>
[ { "answer_id": 74671934, "author": "Vinícius Félix", "author_id": 9696037, "author_profile": "https://Stackoverflow.com/users/9696037", "pm_score": 1, "selected": false, "text": "library(dplyr)\nlibrary(lubridate)\n\ndata %>% \n mutate(across(.cols = starts_with(\"date\"),.fns = ymd)) %>% \n add_count(group) %>% \n filter(!(n == 1 & (date1 >= ymd(\"2021-08-01\") & date2 <= ymd(\"2021-08-31\"))))\n\n group date1 date2 n\n1 09081997 2021-08-09 2021-08-31 3\n2 09081997 2021-08-21 2021-08-29 3\n3 22031969 2021-07-19 2021-07-20 1\n4 09081997 2021-07-15 2021-07-19 3\n" }, { "answer_id": 74673039, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 0, "selected": false, "text": "ave grepl '2021-08' pat any date* mode \"logical\" rowSums '2021-08' data[with(data, ave(cbind(date1, date2), group, FUN=\\(x) any(grepl(x, pat='2021-08')))) |> \n `mode<-`('logical') |> rowSums() |> base::`>`(0), ]\n# group date1 date2\n# 1 09081997 2021-08-09 2021-08-31\n# 2 13122006 2021-08-10 2021-08-22\n# 3 09081997 2021-08-21 2021-08-29\n# 5 09081997 2021-07-15 2021-07-19\n data1[with(data1, as.logical(ave(date1, group, FUN=\\(x) any(grepl(x, pat='2021-08'))))), ]\n# group date1\n# 1 09081997 2021-08-09\n# 2 13122006 2021-08-10\n# 3 09081997 2021-08-21\n# 5 09081997 2021-07-15\n grepl data1[with(data1, as.logical(ave(date1, group, FUN=\\(x) any(\n x >= \"2021-03-08\" | x <= \"2021-06-04\"\n)))), ]\n \n data <- structure(list(group = c(\"09081997\", \"13122006\", \"09081997\", \n\"22031969\", \"09081997\"), date1 = c(\"2021-08-09\", \"2021-08-10\", \n\"2021-08-21\", \"2021-07-19\", \"2021-07-15\"), date2 = c(\"2021-08-31\", \n\"2021-08-22\", \"2021-08-29\", \"2021-07-20\", \"2021-07-19\")), class = \"data.frame\", row.names = c(NA, \n-5L))\n\ndata1 <- data[1:2]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74671990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20343078/" ]
74,672,009
<p>Hello everyone i need some help over this issue in Django *IntegrityError at /api/course/ (1048, &quot;Column 'category_id' cannot be null&quot;) i got this when i tried to insert a new course *</p> <pre><code> </code></pre> <p>class Course(models.Model):</p> <pre><code>category = models.ForeignKey(CourseCategory, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE , related_name='teacher_courses') title = models.CharField(max_length=150) description = models.TextField() featured_img = models.ImageField(upload_to='course_imgs/',null=True) techs = models.TextField(null=True) class Meta: verbose_name_plural = &quot;3. Courses&quot; def related_content(self): related_content=Course.objects.filter(techs__icontains=self.techs) return serializers.serialize('json',related_content) def tech_list(self): tech_list = self.techs.split(',') return tech_list def __str__(self): return self.title </code></pre> <pre><code> </code></pre> <p>class CourseList(generics.ListCreateAPIView):</p> <pre><code>queryset = models.Course.objects.all() serializer_class = CourseSerializer def get_queryset(self): qs = super().get_queryset() if 'result' in self.request.GET: limit = int(self.request.GET['result']) qs = models.Course.objects.all().order_by('-id')[:limit] if 'category' in self.request.GET: category = self.request.GET['category'] qs = models.Course.objects.filter(techs__icontains=category) if 'skill_name' in self.request.GET and 'teacher' in self.request.GET: skill_name = self.request.GET['skill_name'] teacher = self.request.GET['teacher'] teacher = models.Teacher.objects.filter(id=teacher).first() qs = models.Course.objects.filter(techs__icontains=skill_name,teacher=teacher) return qs </code></pre> <pre><code> </code></pre> <p>class CourseSerializer(serializers.ModelSerializer):</p> <pre><code>class Meta: model = models.Course fields =['id','title','description','category_id','teacher','featured_img','techs','course_chapters','related_content','tech_list'] depth=1 </code></pre> <pre><code> </code></pre> <p>I have been searching the solution for hours but i did not get any way to solve the issue and i expect you to help me thank you</p>
[ { "answer_id": 74671934, "author": "Vinícius Félix", "author_id": 9696037, "author_profile": "https://Stackoverflow.com/users/9696037", "pm_score": 1, "selected": false, "text": "library(dplyr)\nlibrary(lubridate)\n\ndata %>% \n mutate(across(.cols = starts_with(\"date\"),.fns = ymd)) %>% \n add_count(group) %>% \n filter(!(n == 1 & (date1 >= ymd(\"2021-08-01\") & date2 <= ymd(\"2021-08-31\"))))\n\n group date1 date2 n\n1 09081997 2021-08-09 2021-08-31 3\n2 09081997 2021-08-21 2021-08-29 3\n3 22031969 2021-07-19 2021-07-20 1\n4 09081997 2021-07-15 2021-07-19 3\n" }, { "answer_id": 74673039, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 0, "selected": false, "text": "ave grepl '2021-08' pat any date* mode \"logical\" rowSums '2021-08' data[with(data, ave(cbind(date1, date2), group, FUN=\\(x) any(grepl(x, pat='2021-08')))) |> \n `mode<-`('logical') |> rowSums() |> base::`>`(0), ]\n# group date1 date2\n# 1 09081997 2021-08-09 2021-08-31\n# 2 13122006 2021-08-10 2021-08-22\n# 3 09081997 2021-08-21 2021-08-29\n# 5 09081997 2021-07-15 2021-07-19\n data1[with(data1, as.logical(ave(date1, group, FUN=\\(x) any(grepl(x, pat='2021-08'))))), ]\n# group date1\n# 1 09081997 2021-08-09\n# 2 13122006 2021-08-10\n# 3 09081997 2021-08-21\n# 5 09081997 2021-07-15\n grepl data1[with(data1, as.logical(ave(date1, group, FUN=\\(x) any(\n x >= \"2021-03-08\" | x <= \"2021-06-04\"\n)))), ]\n \n data <- structure(list(group = c(\"09081997\", \"13122006\", \"09081997\", \n\"22031969\", \"09081997\"), date1 = c(\"2021-08-09\", \"2021-08-10\", \n\"2021-08-21\", \"2021-07-19\", \"2021-07-15\"), date2 = c(\"2021-08-31\", \n\"2021-08-22\", \"2021-08-29\", \"2021-07-20\", \"2021-07-19\")), class = \"data.frame\", row.names = c(NA, \n-5L))\n\ndata1 <- data[1:2]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9989036/" ]
74,672,015
<p>I need to scrape texts from a website, but could not figure out a way to scrape a specific text for this situation:</p> <pre><code>&lt;td valign=&quot;top&quot; class=&quot;testo_normale&quot;&gt; &lt;font face=&quot;Geneva&quot;&gt; &lt;i&gt;W. Richard Bowen&lt;/i&gt; &lt;br&gt; &quot;Water engineering for the promotion of peace&quot; &lt;br&gt; &quot;1(2009)1-6&quot; &lt;br&gt; &quot;DOI: &quot; &lt;br&gt; &quot;Received:26/08/2008; Accepted: 25/11/2008; &quot; </code></pre> <p>So in the above example, I want to only get <code>Water engineering</code> and <code>1(2009)1-6</code></p> <p>I tried to do that all day but I either get all the texts having tag <code>&lt;br&gt;</code> :</p> <pre><code>&quot;W. Richard Bowen&quot; &quot;Water engineering for the promotion of peace&quot; &quot;1(2009)1-6&quot; &quot;DOI: &quot; &quot;Received:26/08/2008; Accepted: 25/11/2008;&quot; </code></pre> <p>or I get empty output.</p> <p><a href="https://www.deswater.com/vol.php?vol=1&amp;oth=1%7C1-3%7CJanuary%7C2009" rel="nofollow noreferrer">here is website I'm trying to scrape</a>, and a picture of what I want to scrape <a href="https://i.stack.imgur.com/2eHP1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2eHP1.png" alt="and a picture of what I want to scrape" /></a></p> <p>This is my code:</p> <pre><code>from bs4 import BeautifulSoup import requests r = requests.get('https://www.deswater.com/vol.php?vol=1&amp;oth=1|1-3|January|2009') soup = BeautifulSoup(r.content, 'html.parser') s = soup.find('td', class_='testo_normale') lines = s.find_all('br') for line in lines: print(line.text.strip()) </code></pre>
[ { "answer_id": 74672083, "author": "mike16889", "author_id": 7340796, "author_profile": "https://Stackoverflow.com/users/7340796", "pm_score": 0, "selected": false, "text": "import re\n\ndef extract_text(string):\n pattern = r'<br>\\s*(.*?)\\s*(?:<br>|<)'\n regex = re.compile(pattern)\n matches = regex.finditer(string)\n texts = []\n for match in matches:\n texts.append(match.group(1))\n return texts\n\nstring = \"\"\"\n<td valign=\"top\" class=\"testo_normale\">\n <font face=\"Geneva\">\n <i>Mariam B</i>\n <br>\n \"some other text\" \n <br>\n \"1(2009)1-6\"\n <br>\"\"\"\n\ntext = extract_text(string)\nprint(text)\n\n <br> \\s* <br> (.*?) \\s* (?:<br>|<) <br> < <br> <br> < <td valign=\"top\" class=\"testo_normale\"> ... <br>\"Water engineering\" <br>\"1(2009)1-6\"<br>\" Water engineering <br> <br> < <br>" }, { "answer_id": 74672185, "author": "Fazlul", "author_id": 12848411, "author_profile": "https://Stackoverflow.com/users/12848411", "pm_score": 2, "selected": true, "text": "split() from bs4 import BeautifulSoup\n\nhtml ='''\n\n<td valign=\"top\" class=\"testo_normale\">\n <font face=\"Geneva\">\n <i>W. Richard Bowen</i>\n <br>\n \"Water engineering for the promotion of peace\" \n <br>\n \"1(2009)1-6\"\n <br>\n \"DOI: \"\n <br>\n \"Received:26/08/2008; Accepted: 25/11/2008; \"\n \n'''\n\nsoup= BeautifulSoup(html, 'lxml')\n\ntxt = soup.select_one('.testo_normale font')\nprint(' '.join(' '.join(txt.get_text(strip=True).split('\"')).strip().split(':')[0].split()[3:-1]))\n\n#OR \n\nfor u in soup.select('.testo_normale font'):\n txt = ' '.join(' '.join(u.get_text(strip=True).split('\"')).strip().split(':')[0].split()[3:-1])\n print(txt)\n Water engineering for the promotion of peace 1(2009)1-6\n from bs4 import BeautifulSoup\nimport requests\nr = requests.get('https://www.deswater.com/vol.php?vol=1&oth=1|1-3|January|2009')\nsoup = BeautifulSoup(r.content, 'html.parser')\n\nfor u in soup.select('font[face=\"Geneva, Arial, Helvetica, san-serif\"]')[6:]:\n txt = u.contents[2:-1]\n for i in txt:\n print(i.get_text(strip=True))\n Editorial and Obituary for Sidney Loeb by Miriam Balaban\n\n1(2009)vii-viii\nWater engineering for the promotion of peace\n\n1(2009)1-6\nModeling the permeate transient response to perturbations from steady state in a nanofiltration process\n\n1(2009)7-16\nModeling the effect of anti-scalant on CaCO3 precipitation in continuous flow\n\n1(2009)17-24\nAlternative primary energy for power desalting plants in Kuwait: the nuclear option I\n\n1(2009)25-41\nAlternative primary energy for power desalting plants in Kuwait: the nuclear\noption II The steam cycle and its combination with desalting units\n\n1(2009)42-57\nPotential applications of quarry dolomite for post treatment of desalinated water\n\n1(2009)58-67\nSalinity tolerance evaluation methodology for desalination plant discharge\n\n1(2009)68-74\nStudies on a water-based absortion heat transformer for desalination using MED\n\n1(2009)75-81\nEstimation of stream compositions in reverse osmosis seawater desalination systems\n\n1(2009)82-87\nGenetic algorithm-based optimization of a multi-stage flash desalination plant\n\n1(2009)88-106\nNumerical simulation on a dynamic mixing process in ducts of a rotary pressure exchanger for SWRO\n\n1(2009)107-113\nSimulation of an autonomous, two-stage solar organic Rankine cycle system for reverse osmosis desalination\n\n1(2009)114-127\nExperiment and optimal parameters of a solar heating system study on an absorption solar desalination unit\n\n1(2009)128-138\nRoles of various mixed liquor constituents in membrane filtration of activated sludge\n\n1(2009)139-149\nNatural organic matter fouling using a cellulose acetate copolymer ultrafiltration membrane\n\n1(2009)150-156\nProgress of enzyme immobilization and its potential application\n\n1(2009)157-171\nInvestigating microbial activities of constructed wetlands with respect to nitrate and sulfate reduction\n\n1(2009)172-179\nMembrane fouling caused by soluble microbial products in an activated sludge system under starvation\n\n1(2009)180-185\nCharacterization of an ultrafiltration membrane modified by sorption of branched polyethyleneimine\n\n1(2009)186-193\nCombined humic substance coagulation and membrane filtration under saline conditions\n\n1(2009)194-200\nPreparation, characterization and performance of phenolphthalein polyethersulfone ultrafiltration hollow fiber membranes\n\n1(2009)201-207\nApplication of coagulants in pretreatment of fish wastewater using factorial design\n\n1(2009)208-214\nPerformance analysis of a trihybrid NF/RO/MSF desalination plant\n\n1(2009)215-222\nNitrogen speciation by microstill flow injection analysis\n\n1(2009)223-231\nWastewater from a mountain village treated with a constructed wetland\n\n1(2009)232-236\nThe influence of various operating conditions on specific cake resistance in the crossflow microfiltration of yeast suspensions\n\n1(2009)237-247\nOn-line monitoring of floc formation in various flocculants for piggery wastewater treatment\n\n1(2009)248-258\nRigorous steady-state modeling of MSFBR desalination systems\n\n1(2009)259-276\nDetailed numerical simulations of flow mechanics and membrane performance in spacer-filled channels, flat and curved\n\n1(2009)277-288\nRemoval of polycyclic aromatic hydrocarbons from Ismailia Canal water by chlorine, chlorine dioxide and ozone\n\n1(2009)289-298\nWater resources management to satisfy high water demand in the arid Sharm El Sheikh, the Red Sea, Egypt\n\n1(2009)299-306\nEffect of storage of NF membranes on fouling deposits and cleaning efficiency\n\n1(2009)307-311\nLaboratory studies and CFD modeling of photocatalytic degradation of colored textile wastewater by titania nanoparticles\n\n1(2009)312-317\nStartup operation and process control of a two-stage sequencing batch reactor (TSSBR) for biological nitrogen removal via nitrite\n\n1(2009)318-325\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17356493/" ]
74,672,034
<p>the string looks like (37°35'11.2&quot; N 85°30'40.3&quot;W)</p> <p>grep does not work</p> <pre><code> grep -a &quot;(37\°35\'11\.2\&quot; N 85\°30\'40\.3\&quot;W)&quot; file.txt grep &quot;(37\°35\'11\.2\&quot; N 85\°30\'40\.3\&quot;W)&quot; file.txt grep -a &quot;(37°35'11.2\&quot; N 85°30'40.3\&quot;W)&quot; file.txt </code></pre>
[ { "answer_id": 74672083, "author": "mike16889", "author_id": 7340796, "author_profile": "https://Stackoverflow.com/users/7340796", "pm_score": 0, "selected": false, "text": "import re\n\ndef extract_text(string):\n pattern = r'<br>\\s*(.*?)\\s*(?:<br>|<)'\n regex = re.compile(pattern)\n matches = regex.finditer(string)\n texts = []\n for match in matches:\n texts.append(match.group(1))\n return texts\n\nstring = \"\"\"\n<td valign=\"top\" class=\"testo_normale\">\n <font face=\"Geneva\">\n <i>Mariam B</i>\n <br>\n \"some other text\" \n <br>\n \"1(2009)1-6\"\n <br>\"\"\"\n\ntext = extract_text(string)\nprint(text)\n\n <br> \\s* <br> (.*?) \\s* (?:<br>|<) <br> < <br> <br> < <td valign=\"top\" class=\"testo_normale\"> ... <br>\"Water engineering\" <br>\"1(2009)1-6\"<br>\" Water engineering <br> <br> < <br>" }, { "answer_id": 74672185, "author": "Fazlul", "author_id": 12848411, "author_profile": "https://Stackoverflow.com/users/12848411", "pm_score": 2, "selected": true, "text": "split() from bs4 import BeautifulSoup\n\nhtml ='''\n\n<td valign=\"top\" class=\"testo_normale\">\n <font face=\"Geneva\">\n <i>W. Richard Bowen</i>\n <br>\n \"Water engineering for the promotion of peace\" \n <br>\n \"1(2009)1-6\"\n <br>\n \"DOI: \"\n <br>\n \"Received:26/08/2008; Accepted: 25/11/2008; \"\n \n'''\n\nsoup= BeautifulSoup(html, 'lxml')\n\ntxt = soup.select_one('.testo_normale font')\nprint(' '.join(' '.join(txt.get_text(strip=True).split('\"')).strip().split(':')[0].split()[3:-1]))\n\n#OR \n\nfor u in soup.select('.testo_normale font'):\n txt = ' '.join(' '.join(u.get_text(strip=True).split('\"')).strip().split(':')[0].split()[3:-1])\n print(txt)\n Water engineering for the promotion of peace 1(2009)1-6\n from bs4 import BeautifulSoup\nimport requests\nr = requests.get('https://www.deswater.com/vol.php?vol=1&oth=1|1-3|January|2009')\nsoup = BeautifulSoup(r.content, 'html.parser')\n\nfor u in soup.select('font[face=\"Geneva, Arial, Helvetica, san-serif\"]')[6:]:\n txt = u.contents[2:-1]\n for i in txt:\n print(i.get_text(strip=True))\n Editorial and Obituary for Sidney Loeb by Miriam Balaban\n\n1(2009)vii-viii\nWater engineering for the promotion of peace\n\n1(2009)1-6\nModeling the permeate transient response to perturbations from steady state in a nanofiltration process\n\n1(2009)7-16\nModeling the effect of anti-scalant on CaCO3 precipitation in continuous flow\n\n1(2009)17-24\nAlternative primary energy for power desalting plants in Kuwait: the nuclear option I\n\n1(2009)25-41\nAlternative primary energy for power desalting plants in Kuwait: the nuclear\noption II The steam cycle and its combination with desalting units\n\n1(2009)42-57\nPotential applications of quarry dolomite for post treatment of desalinated water\n\n1(2009)58-67\nSalinity tolerance evaluation methodology for desalination plant discharge\n\n1(2009)68-74\nStudies on a water-based absortion heat transformer for desalination using MED\n\n1(2009)75-81\nEstimation of stream compositions in reverse osmosis seawater desalination systems\n\n1(2009)82-87\nGenetic algorithm-based optimization of a multi-stage flash desalination plant\n\n1(2009)88-106\nNumerical simulation on a dynamic mixing process in ducts of a rotary pressure exchanger for SWRO\n\n1(2009)107-113\nSimulation of an autonomous, two-stage solar organic Rankine cycle system for reverse osmosis desalination\n\n1(2009)114-127\nExperiment and optimal parameters of a solar heating system study on an absorption solar desalination unit\n\n1(2009)128-138\nRoles of various mixed liquor constituents in membrane filtration of activated sludge\n\n1(2009)139-149\nNatural organic matter fouling using a cellulose acetate copolymer ultrafiltration membrane\n\n1(2009)150-156\nProgress of enzyme immobilization and its potential application\n\n1(2009)157-171\nInvestigating microbial activities of constructed wetlands with respect to nitrate and sulfate reduction\n\n1(2009)172-179\nMembrane fouling caused by soluble microbial products in an activated sludge system under starvation\n\n1(2009)180-185\nCharacterization of an ultrafiltration membrane modified by sorption of branched polyethyleneimine\n\n1(2009)186-193\nCombined humic substance coagulation and membrane filtration under saline conditions\n\n1(2009)194-200\nPreparation, characterization and performance of phenolphthalein polyethersulfone ultrafiltration hollow fiber membranes\n\n1(2009)201-207\nApplication of coagulants in pretreatment of fish wastewater using factorial design\n\n1(2009)208-214\nPerformance analysis of a trihybrid NF/RO/MSF desalination plant\n\n1(2009)215-222\nNitrogen speciation by microstill flow injection analysis\n\n1(2009)223-231\nWastewater from a mountain village treated with a constructed wetland\n\n1(2009)232-236\nThe influence of various operating conditions on specific cake resistance in the crossflow microfiltration of yeast suspensions\n\n1(2009)237-247\nOn-line monitoring of floc formation in various flocculants for piggery wastewater treatment\n\n1(2009)248-258\nRigorous steady-state modeling of MSFBR desalination systems\n\n1(2009)259-276\nDetailed numerical simulations of flow mechanics and membrane performance in spacer-filled channels, flat and curved\n\n1(2009)277-288\nRemoval of polycyclic aromatic hydrocarbons from Ismailia Canal water by chlorine, chlorine dioxide and ozone\n\n1(2009)289-298\nWater resources management to satisfy high water demand in the arid Sharm El Sheikh, the Red Sea, Egypt\n\n1(2009)299-306\nEffect of storage of NF membranes on fouling deposits and cleaning efficiency\n\n1(2009)307-311\nLaboratory studies and CFD modeling of photocatalytic degradation of colored textile wastewater by titania nanoparticles\n\n1(2009)312-317\nStartup operation and process control of a two-stage sequencing batch reactor (TSSBR) for biological nitrogen removal via nitrite\n\n1(2009)318-325\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/850399/" ]
74,672,118
<p>I am trying to send an activity from the botController.cs and I want to catch it from the bot framework composer. here is the code when I am sending the event activity:</p> <pre><code>var userAccount = new ChannelAccount(&quot;e7h84gd7-fbb5-y3u6-h9d8-f8q3789649ec&quot;, &quot;User&quot;); var botAccount = new ChannelAccount(&quot;274d8t53-7492-98hr-r625-b11e3ht7e6wq&quot;, &quot;Bot&quot;); Activity activity = new Activity { From = userAccount, Recipient = botAccount, Type = ActivityTypes.Event, Name = &quot;Agent_Closed_Session&quot;, }; await turnContext.SendActivityAsync(activity); </code></pre> <p>this is in the bot composer to catch it: <a href="https://i.stack.imgur.com/XAFfq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XAFfq.png" alt="enter image description here" /></a></p> <p>this is the response, it shows that the sender of the event is the bot and the recipient is the user, but in the request, I mentioned that the sender should be the user and the recipient should be the bot <a href="https://i.stack.imgur.com/0Hxr3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Hxr3.png" alt="enter image description here" /></a></p> <p>So in the action in the event activity trigger (response text; testtt) is not performed</p>
[ { "answer_id": 74672154, "author": "affctn", "author_id": 20678271, "author_profile": "https://Stackoverflow.com/users/20678271", "pm_score": 1, "selected": false, "text": "var userAccount = new ChannelAccount(\"e7h84gd7-fbb5-y3u6-h9d8-f8q3789649ec\", \"User\");\nvar botAccount = new ChannelAccount(\"274d8t53-7492-98hr-r625-b11e3ht7e6wq\", \"Bot\");\n\n// Set the From property to the bot account and the Recipient property to the user account\nActivity activity = new Activity\n{\n From = botAccount,\n Recipient = userAccount,\n Type = ActivityTypes.Event,\n Name = \"Agent_Closed_Session\",\n};\n\nawait turnContext.SendActivityAsync(activity);\n" }, { "answer_id": 74673311, "author": "Ravi Raushan", "author_id": 10095532, "author_profile": "https://Stackoverflow.com/users/10095532", "pm_score": 0, "selected": false, "text": "turn.activity.Name == \"Agent_Closed_Session\"\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15556473/" ]
74,672,132
<p>Been beating my head against this and can't get it. Here is the forumla:</p> <pre><code>=IF(E3=E2,F2,F2+1) </code></pre> <p>Pretty simple. All it does is look at the cell above it...if they are the same it doesn't increase the number iteration. If they are different it does. Somehow I can't figure out how to format this in order to make it an ArrayFormula. The only reason I want it to be an Arrayformula is so that rows can be added or removed and the formula would remain intact thus the spreadsheet would be easier to use.</p>
[ { "answer_id": 74672139, "author": "affctn", "author_id": 20678271, "author_profile": "https://Stackoverflow.com/users/20678271", "pm_score": 1, "selected": false, "text": "=ARRAYFORMULA(IF(E3:E=E2:E,F2:F,F2:F+1))\n" }, { "answer_id": 74672224, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 0, "selected": false, "text": "=INDEX(BYROW(E2:INDEX(E:E, MAX(ROW(E:E)*(E:E<>\"\"))), \n LAMBDA(e, IF(OFFSET(e, 1, )=e, OFFSET(e,,1), OFFSET(e,,1)+1))\n" }, { "answer_id": 74672414, "author": "Martín", "author_id": 20363318, "author_profile": "https://Stackoverflow.com/users/20363318", "pm_score": 1, "selected": false, "text": "=BYROW(E3:E,LAMBDA(each,IF(each=\"\",\"\",F2+sum(MAP(E3:each, LAMBDA(c,IF(c=\"\",\"\",IF(c=OFFSET(c,-1,),0,1))))))))\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4056670/" ]
74,672,164
<p>I'm trying to &quot;reference&quot; (or something like it) a non-primary attribute from a table. Say I have two tables from a database called DoctorsOffice.</p> <pre><code>CREATE TABLE DOCTOR ( Doctor_ID varchar(10) NOT NULL, -- PRIMARY KEY Last_name varchar(15) NOT NULL, First_name varchar(20) NOT NULL, Phone_num varchar(15), Specialty varchar(12) NOT NULL, Salary DEC(10, 2), PRIMARY KEY (Doctor_ID) ); CREATE TABLE APPOINTMENT( Appointment_num varchar(9) NOT NULL, -- PRIMARY KEY Test_given varchar(9) NOT NULL, Patient_ssn char(9) NOT NULL, Doctor_name varchar(20) NOT NULL, Doctor_ID varchar(10) NOT NULL, Date Date, Room_num char(2) NOT NULL, PRIMARY KEY (Appointment_num), FOREIGN KEY (Doctor_name) REFERENCES DOCTOR(First_name), -- the above line of code gives me an error FOREIGN KEY (Doctor_ID) REFERENCES DOCTOR(Doctor_ID) ); </code></pre> <p>Foreign keys only reference primary keys from other tables. Still, the relational diagram I'm supposed to follow shows an Appointment table attribute Doctor_ID referencing the primary key Doctor_ID and Doctor_name from the Appointment table referencing First_name from the DOCTOR table. First_name isn't a primary key from the DOCTOR table. So, how would I reference an attribute that isn't a primary key?</p> <p>There are arrows from the Appointment table attributes Doctor_name and Doctor_ID pointing at the primary key DOCTOR_ID and normal attribute First_name from the DOCTOR table.</p> <p><a href="https://i.stack.imgur.com/vfD9V.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vfD9V.jpg" alt="enter image description here" /></a></p>
[ { "answer_id": 74672283, "author": "The Impaler", "author_id": 6436191, "author_profile": "https://Stackoverflow.com/users/6436191", "pm_score": 1, "selected": false, "text": "First_name CREATE TABLE DOCTOR (\n Doctor_ID varchar(10) NOT NULL,\n Last_name varchar(15) NOT NULL,\n First_name varchar(20) UNIQUE NOT NULL, -- UNIQUE NOT NULL makes it a key\n Phone_num varchar(15),\n Specialty varchar(12) NOT NULL,\n Salary DEC(10, 2),\n PRIMARY KEY (Doctor_ID)\n);\n" }, { "answer_id": 74673131, "author": "Ishtmeet Singh", "author_id": 13700920, "author_profile": "https://Stackoverflow.com/users/13700920", "pm_score": -1, "selected": false, "text": "APPOINTMENT First_name DOCTOR First_name DOCTOR Doctor_ID First_name APPOINTMENT Doctor_ID DOCTOR CREATE TABLE APPOINTMENT(\n Appointment_num varchar(9) NOT NULL, -- PRIMARY KEY\n Test_given varchar(9) NOT NULL,\n Patient_ssn char(9) NOT NULL,\n Doctor_name varchar(20) NOT NULL,\n Doctor_ID varchar(10) NOT NULL,\n Date Date,\n Room_num char(2) NOT NULL,\n PRIMARY KEY (Appointment_num),\n FOREIGN KEY (Doctor_ID) REFERENCES DOCTOR(Doctor_ID)\n);\n\n Doctor_ID APPOINTMENT Doctor_ID DOCTOR Doctor_ID APPOINTMENT DOCTOR First_name APPOINTMENT First_name APPOINTMENT" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12283812/" ]
74,672,168
<p>Sorry, I know this has been asked before but I have read all the answers and nothing works! Please help. When I check acutal and expected outputs, they match, but in check50 It gives an error message. Here is the link for check50 results: <a href="https://submit.cs50.io/check50/6d939efb8a55e3fadec1c60952311f6198cd0eb0" rel="nofollow noreferrer">https://submit.cs50.io/check50/6d939efb8a55e3fadec1c60952311f6198cd0eb0</a></p> <pre><code>#include &lt;cs50.h&gt; #include &lt;stdio.h&gt; #include &lt;ctype.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; char crypt(int k,char w) { if ('a'&lt;= w &amp;&amp; w &lt;='z') { return (((w-'a')+ k)%26+'a'); } else if ('A' &lt;= w &amp;&amp; w &lt;= 'Z') { return (((w -'A') + k) % 26 + 'A'); } else { return (w); } } int main(int argc, string argv[]) { //input check if (argc != 2) { printf(&quot;Usage: ./caesar key\n&quot;); return 1; } int lngg = strlen(argv[1]); for (int i = 0; i &lt; lngg; i++) { if (isdigit(argv[1][i]) == 0) { printf(&quot;Usage: ./caesar key\n&quot;); return 1; } } int key = atoi(argv[1])%26; //input string plain = get_string(&quot;plaintext: &quot;); //crpypt starts printf(&quot;ciphertext: &quot;); int lng = strlen(plain)+1; for (int a = 0; a &lt; lng ;a++) { printf(&quot;%c&quot;, crypt(key, plain[a])); } printf(&quot;\n&quot;); } </code></pre> <p>Hi, When I look expected and actual outputs, everything seems perfect but it errors</p>
[ { "answer_id": 74672218, "author": "Andreas Wenzel", "author_id": 12149471, "author_profile": "https://Stackoverflow.com/users/12149471", "pm_score": 2, "selected": true, "text": "printf check50 for(int a=0; a<lng ;a++)\n{\n printf(\"%c\",crypt(key,plain[a]));\n}\n strlen(plain)+1 lng lng strlen(plain)" }, { "answer_id": 74672563, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 0, "selected": false, "text": "// int lng = strlen(plain)+1;\n// for (int a = 0; a < lng ;a++)\n\nfor (int a = 0; plain[a] != '\\0'; a++)\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20678264/" ]
74,672,222
<pre><code>Type Date Cost Shampoo 01/31/2022 $10 Shampoo 01/31/2022 $15 Shampoo 02/22/2019 $15 Conditioner 03/15/2020 $17 Conditioner 05/16/2022 $19 Soap. 01/31/2021 $5 Soap 01/06/2022 $2 Soap 12/31/2019 $3 Soap 10/10/2022 $5 </code></pre> <p>How would I approach summing total cost for specific items in a year, months, quarter and total cost</p> <p>Example Output:</p> <pre><code>Type | Number Items | Year | Total Cost Shampoo | 2 | 2022 | 25 Shampoo | 1. | 2019 | 15 </code></pre> <p>etc...</p> <p>split by month, and quarter</p> <p>Trying summarize and <code>library(lubridate)</code></p>
[ { "answer_id": 74672236, "author": "Vinícius Félix", "author_id": 9696037, "author_profile": "https://Stackoverflow.com/users/9696037", "pm_score": 0, "selected": false, "text": "library(dplyr)\nlibrary(lubridate)\n\nyour_data_frame %>% \n group_by(type, year = year(dmy(Date))) %>% \n summarise(\n number_of_items = n(),\n total_cost = sum(cost,na.rm = TRUE)\n )\n" }, { "answer_id": 74672822, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 1, "selected": false, "text": "library(tidyverse)\nlibrary(lubridate)\n\ndf %>%\n group_by(Type, Date)%>%\n summarise(Number_Items = n(),\n Year = year(mdy(Date[1])),\n Total_Cost = sum(parse_number(Cost)),\n .groups = 'drop')\n\n# A tibble: 8 × 5\n Type Date Number_Items Year Total_Cost\n <chr> <chr> <int> <dbl> <dbl>\n1 Conditioner 03/15/2020 1 2020 17\n2 Conditioner 05/16/2022 1 2022 19\n3 Shampoo 01/31/2022 2 2022 25\n4 Shampoo 02/22/2019 1 2019 15\n5 Soap 01/06/2022 1 2022 2\n6 Soap 10/10/2022 1 2022 5\n7 Soap 12/31/2019 1 2019 3\n8 Soap. 01/31/2021 1 2021 5\n" }, { "answer_id": 74673444, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 0, "selected": false, "text": "library(dplyr)\nlibrary(readr) # parse_number()\nlibrary(lubridate\n\ndf %>% \n mutate(Year = year(mdy(Date))) %>% \n group_by(Year, Type) %>% \n summarise(`Number Items` = n(), \n `Total Cost` = sum(parse_number(Cost)))\n Year Type `Number Items` `Total Cost`\n <dbl> <chr> <int> <dbl>\n1 2019 Shampoo 1 15\n2 2019 Soap 1 3\n3 2020 Conditioner 1 17\n4 2021 Soap. 1 5\n5 2022 Conditioner 1 19\n6 2022 Shampoo 2 25\n7 2022 Soap 2 7\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6063433/" ]
74,672,225
<p>Trying both <code>ng install</code> or <code>npm install</code> fails:</p> <pre><code>The package @ng-bootstrap/ng-bootstrap@13.1.1 will be installed and executed. Would you like to proceed? Yes npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: my-app@0.0.0 npm ERR! Found: @angular/common@15.0.2 npm ERR! node_modules/@angular/common npm ERR! @angular/common@&quot;^15.0.0&quot; from the root project npm ERR! npm ERR! Could not resolve dependency: npm ERR! peer @angular/common@&quot;^14.1.0&quot; from @ng-bootstrap/ng-bootstrap@13.1.1 npm ERR! node_modules/@ng-bootstrap/ng-bootstrap npm ERR! @ng-bootstrap/ng-bootstrap@&quot;13.1.1&quot; from the root project npm ERR! npm ERR! Fix the upstream dependency conflict, or retry npm ERR! this command with --force, or --legacy-peer-deps npm ERR! to accept an incorrect (and potentially broken) dependency resolution. npm ERR! npm ERR! See /home/node/.npm/eresolve-report.txt for a full report. $ npm install @ng-bootstrap/ng-bootstrap npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: hygieia-ui@0.0.0 npm ERR! Found: @angular/common@15.0.2 npm ERR! node_modules/@angular/common npm ERR! @angular/common@&quot;^15.0.0&quot; from the root project npm ERR! npm ERR! Could not resolve dependency: npm ERR! peer @angular/common@&quot;^14.1.0&quot; from @ng-bootstrap/ng-bootstrap@13.1.1 npm ERR! node_modules/@ng-bootstrap/ng-bootstrap npm ERR! @ng-bootstrap/ng-bootstrap@&quot;*&quot; from the root project npm ERR! npm ERR! Fix the upstream dependency conflict, or retry npm ERR! this command with --force, or --legacy-peer-deps npm ERR! to accept an incorrect (and potentially broken) dependency resolution. npm ERR! npm ERR! See /home/node/.npm/eresolve-report.txt for a full report. </code></pre>
[ { "answer_id": 74672236, "author": "Vinícius Félix", "author_id": 9696037, "author_profile": "https://Stackoverflow.com/users/9696037", "pm_score": 0, "selected": false, "text": "library(dplyr)\nlibrary(lubridate)\n\nyour_data_frame %>% \n group_by(type, year = year(dmy(Date))) %>% \n summarise(\n number_of_items = n(),\n total_cost = sum(cost,na.rm = TRUE)\n )\n" }, { "answer_id": 74672822, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 1, "selected": false, "text": "library(tidyverse)\nlibrary(lubridate)\n\ndf %>%\n group_by(Type, Date)%>%\n summarise(Number_Items = n(),\n Year = year(mdy(Date[1])),\n Total_Cost = sum(parse_number(Cost)),\n .groups = 'drop')\n\n# A tibble: 8 × 5\n Type Date Number_Items Year Total_Cost\n <chr> <chr> <int> <dbl> <dbl>\n1 Conditioner 03/15/2020 1 2020 17\n2 Conditioner 05/16/2022 1 2022 19\n3 Shampoo 01/31/2022 2 2022 25\n4 Shampoo 02/22/2019 1 2019 15\n5 Soap 01/06/2022 1 2022 2\n6 Soap 10/10/2022 1 2022 5\n7 Soap 12/31/2019 1 2019 3\n8 Soap. 01/31/2021 1 2021 5\n" }, { "answer_id": 74673444, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 0, "selected": false, "text": "library(dplyr)\nlibrary(readr) # parse_number()\nlibrary(lubridate\n\ndf %>% \n mutate(Year = year(mdy(Date))) %>% \n group_by(Year, Type) %>% \n summarise(`Number Items` = n(), \n `Total Cost` = sum(parse_number(Cost)))\n Year Type `Number Items` `Total Cost`\n <dbl> <chr> <int> <dbl>\n1 2019 Shampoo 1 15\n2 2019 Soap 1 3\n3 2020 Conditioner 1 17\n4 2021 Soap. 1 5\n5 2022 Conditioner 1 19\n6 2022 Shampoo 2 25\n7 2022 Soap 2 7\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/666818/" ]
74,672,270
<p>I have an appendable list of <code>View</code> and I want to add space to between each element of my list.</p> <p>Here is an overview of my code -</p> <pre><code> list = [] function func(){ button(){ list.append( &lt;View style = {1}&gt; ... ... ... &lt;\View&gt; ) } return( &lt;View&gt; &lt;View&gt; &lt;Text onPress = {() =&gt; button()}&gt; + &lt;/Text&gt; &lt;\View&gt; &lt;ScrollView style = {3}&gt; &lt;View style = {2}&gt; {list} &lt;\View&gt; &lt;\ScrollView&gt; &lt;\View&gt; ) } </code></pre> <p>My app currently looks something like this - <a href="https://i.stack.imgur.com/ye2ha.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ye2ha.png" alt="enter image description here" /></a></p> <p>My question is which CSS component should I style - {1}, {2} or {3}?</p> <p>Here is my actual code -</p> <pre><code>import React, { Component, useState, useEffect } from &quot;react&quot;; import { View, Text, StyleSheet, TextInput, ScrollView } from 'react-native'; function WeatherApp(){ const [data, setData] = useState([]) const[i, setI] = useState(0) const dates = [1, 2, 3, 4, 5, 6, 7, 8, 9] const temperatures = [20, 21, 26, 19, 30, 32, 23, 22, 24] const cities = ['LA', 'SAN', 'SFO', 'LGA', 'HND', 'KIX', 'DEN', 'MUC', 'BOM'] const buttonPressed = () =&gt; { if(i &lt; 9){ data.push( &lt;View style = {styles.weatherBoard}&gt; &lt;Text key = {dates[i]} style = {styles.date}&gt;{dates[i]}&lt;/Text&gt; &lt;Text key = {temperatures[i]} style = {styles.temperature}&gt;{temperatures[i]}&lt;/Text&gt; &lt;Text key = {cities[i]} style = {styles.cityName}&gt;{cities[i]}&lt;/Text&gt; &lt;/View&gt; ) setData(data) setI(i =&gt; i + 1) } } useEffect(()=&gt;{}, [i]) return( &lt;View style = {styles.appBackground}&gt; &lt;View style = {styles.searchBar}&gt; &lt;TextInput style = {styles.searchText} placeholder = &quot;Search City&quot;&gt;&lt;/TextInput&gt; &lt;Text onPress={() =&gt; buttonPressed()} style = {styles.addButton}&gt;+&lt;/Text&gt; &lt;/View&gt; {/* ScrollView can only have one view in it */} &lt;ScrollView style = {styles.weatherPanel} &gt; &lt;View&gt; {data} &lt;/View&gt; &lt;/ScrollView&gt; &lt;/View&gt; ) } </code></pre> <p>Here is my css file -</p> <pre><code>const styles = StyleSheet.create({ appBackground:{ flex: 1, backgroundColor: 'black', flexDirection: 'column' }, searchBar:{ flex: 0.1, flexDirection: 'row', backgroundColor: 'white', fontSize: 25 }, searchText:{ flex: 8, borderWidth: 1 }, addButton:{ flex: 2, textAlign: 'center', fontSize: 40, borderWidth: 1 }, // Place where all cities' weather are shown weatherPanel:{ flex: 0.9, flexDirection: 'column', padding: 15 }, // Style for each city weatherBoard:{ flex: 9, backgroundColor: 'blue', borderRadius: 10, padding: 10 }, // Temorary styles - date: { fontSize: 20, color: 'white' }, temperature:{ fontSize: 30 }, cityName:{ fontSize: 30 } }) </code></pre>
[ { "answer_id": 74672413, "author": "Jason Lee", "author_id": 12827322, "author_profile": "https://Stackoverflow.com/users/12827322", "pm_score": 2, "selected": true, "text": "style={{marginTop: 12}} list.append(\n <View style={{marginTop: 12}}> \n ...\n ...\n ...\n </View>\n)\n" }, { "answer_id": 74677665, "author": "Kirill Novikov", "author_id": 2791142, "author_profile": "https://Stackoverflow.com/users/2791142", "pm_score": 0, "selected": false, "text": "ItemSeparatorComponent" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18284412/" ]
74,672,284
<p>The groovy script needs to find the x location of string1 and put them into a list. The final output will be like finaList=[[2,3],[5]]</p> <p>The following scripts are created by me, but it doesn't work</p> <pre><code>checkStr='01xx0x1' i=0 tempaList=[] finalList=[] while (i&lt;checkStr.length()){ if(checkStr[i]=='x'){ tempaList.add(i) }else if(tempaList.length()&gt;1){ finalList.add([tempaList[0],tempaList[-1]]) tempaList=[] }else if (tempaList.length()==1){ finaList.add([tempaList]) tempaList=[] } i=i+1 } println finaList </code></pre>
[ { "answer_id": 74672459, "author": "liuxu", "author_id": 20653168, "author_profile": "https://Stackoverflow.com/users/20653168", "pm_score": -1, "selected": false, "text": "checkStr='01xx0x1'\ni=0\ntempaList=[]\nfinalList=[]\n\nwhile(i<checkStr.length()){\n if(checkStr[i]==\"x\"){\n // println i\n tempaList.add(i)\n }else if (tempaList.size()>1){\n finalList.add([tempaList[0],tempaList[-1]])\n tempaList=[]\n }else if (tempaList.size()==1){\n finalList.add(tempaList)\n tempaList=[]\n }\n i=i+1\n}\n\nprintln finalList\n" }, { "answer_id": 74673517, "author": "aspok", "author_id": 13344100, "author_profile": "https://Stackoverflow.com/users/13344100", "pm_score": 0, "selected": false, "text": "def str ='01xx0x'\nstr.findIndexValues { it == 'x' } // result -> [2, 3, 5]\n tempaList def checkStr = '01xx0x1'\ndef temp = []\ndef end = []\n\nfor (int i=0; i < checkStr.size(); i++) {\n if (checkStr[i] == 'x') {\n temp << i\n } else if (temp.size()) {\n // temp has size (indexes) and we've hit a non-'x' char\n end << temp\n temp = []\n }\n } \n\n// If the final char was an x (or multiple x's), handle that here \nif (temp) {\n end << temp\n}\n\nprintln end // result -> [[2, 3], [5]]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20653168/" ]
74,672,309
<p>I'm just starting to learn Rust and I'm still working on understanding its approach. The particular thing I'm working on is trying to find out if two strings have any characters in common. In another language I might do this by creating two sets of the characters in the strings and performing an intersection on the sets. So far I'm having no luck in creating a <code>HashSet</code> from the characters in a string in Rust. I'm trying variations on this:</p> <pre class="lang-rust prettyprint-override"><code>let lines: Vec&lt;&amp;str&gt; = text_from_file.lines().collect(); let set1 = HashSet::from(lines[0].chars()); </code></pre> <p>With this variation I get the error &quot;the trait bound <code>std::collections::HashSet&lt;_, _&gt;: std::convert::From&lt;&amp;[u8]&gt;</code> is not satisfied&quot;. I don't understand Rust enough yet to know how to interpret this. How can I create a <code>HashSet</code> from the characters in a string?</p>
[ { "answer_id": 74672317, "author": "Stephen Weinberg", "author_id": 727643, "author_profile": "https://Stackoverflow.com/users/727643", "pm_score": 2, "selected": true, "text": "HashSet::from_iter() let lines: Vec<&str> = text_from_file.lines().collect();\nlet set1: HashSet<char> = HashSet::from_iter(lines[0].chars());\n" }, { "answer_id": 74675149, "author": "Finomnis", "author_id": 2902833, "author_profile": "https://Stackoverflow.com/users/2902833", "pm_score": 0, "selected": false, "text": "HashSet::from() lines[0].chars() Chars HashSet let set1: HashSet<char> = lines[0].chars().collect();\n let set1: HashSet<char> = HashSet::from_iter(lines[0].chars());\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76810/" ]
74,672,338
<p>I have a data frame that looks like this.</p> <pre><code>import pandas as pd import numpy as np data = [ ['A',1,2,3,4], ['A',5,6,7,8], ['A',9,10,11,12], ['B',13,14,15,16], ['B',17,18,19,20], ['B',21,22,23,24], ['B',25,26,27,28], ['C',29,30,31,32], ['C',33,34,35,36], ['C',37,38,39,40], ['D',13,14,15,0], ['D',0,18,19,0], ['D',0,0,23,0], ['D',0,0,0,0], ['E',13,14,15,0], ['E',0,18,19,0], ['F',0,0,23,0], ] df = pd.DataFrame(data, columns=['Name', 'num1', 'num2', 'num3', 'num4']) df </code></pre> <p>Then I have the following code to calculate the group by weighted average.</p> <pre><code>weights = [10,20,30,40] df=df.groupby('Name').agg(lambda g: sum(g*weights[:len(g)])/sum(weights[:len(g)])) </code></pre> <p>The problem lies in <code>sum(weights[:len(g)])</code> because all the groups do not have equal rows. As you can see above, <code>group A has 3 rows, B has 4 rows, C has 3 rows, D has 4 rows, E has 2 rows and F has 1 row</code>. Depending upon the rows, it needs to calculate the sum. Now, the above code returns me the weighted average by calculating</p> <p><strong>For Group A, the first column calculates the weighted average as (1 X 10+5 X 20+9 X 30)/60 but it should calculate the weighted average as (1 X20+5 X 30+9 X 40)/90</strong></p> <p><strong>For Group E, the first column calculates the weighted average as (13 X 10+0 X 20)/30 but it should calculate the weighted average as (13 X 30+0 X 40)/70</strong></p> <p><strong>Current Result</strong></p> <p><a href="https://i.stack.imgur.com/IgEjl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IgEjl.png" alt="enter image description here" /></a></p> <p><strong>Expected result</strong></p> <p><a href="https://i.stack.imgur.com/kLwI5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kLwI5.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74672432, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 3, "selected": true, "text": "n = len(weights)\ndf=df.groupby('Name').agg(lambda g: sum(g*weights[n-len(g):])/sum(weights[n-len(g):]))\n df num1 num2 num3 num4\nName \nA 5.9 6.9 7.9 8.9\nB 21.0 22.0 23.0 24.0\nC 33.9 34.9 35.9 36.9\nD 1.3 5.0 12.2 0.0\nE 5.6 16.3 17.3 0.0\nF 0.0 0.0 23.0 0.0\n" }, { "answer_id": 74672637, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 0, "selected": false, "text": "n = len(weights)\npos = n - df.groupby('Name').size()\npos = [weights[posn : n] for posn in pos]\npos = np.concatenate(pos)\n(df\n.set_index('Name')\n.mul(pos, axis=0)\n.assign(wt = pos)\n.groupby('Name')\n.sum()\n.pipe(lambda df: df.filter(like='num')\n .div(df.wt, axis=0)\n )\n)\n\n num1 num2 num3 num4\nName\nA 5.888889 6.888889 7.888889 8.888889\nB 21.000000 22.000000 23.000000 24.000000\nC 33.888889 34.888889 35.888889 36.888889\nD 1.300000 5.000000 12.200000 0.000000\nE 5.571429 16.285714 17.285714 0.000000\nF 0.000000 0.000000 23.000000 0.000000\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16875907/" ]
74,672,372
<p>my current issue with my react native app is that when a user wants to open a lesson (from the lessons array with each object being a lesson with a title,description,img url etc)to make it bigger through a modal, its state does not update. What i Mean by this is that the books title,description,and other attributes won't change if you press on a new lesson. What would be the solution to this?</p> <pre><code>export default function Learn() { const [modalVisible, setModalVisible] = useState(false); const [lessons,setLessons] = useState() useEffect(() =&gt; { async function data() { try { let todos = [] const querySnapshot = await getDocs(collection(db, &quot;lessons&quot;)); querySnapshot.forEach((doc) =&gt; { todos.push(doc.data()) }); setLessons(todos) console.log(lessons) } catch(E) { alert(E) } } data() }, []) return ( &lt;View style={learnStyle.maincont}&gt; &lt;View&gt; &lt;Text style={{fontSize:28,marginTop:20}}&gt;Courses&lt;/Text&gt; &lt;ScrollView style={{paddingBottom:200}}&gt; {lessons &amp;&amp; lessons.map((doc,key) =&gt; &lt;&gt; &lt;Modal animationType=&quot;slide&quot; transparent={true} visible={modalVisible} onRequestClose={() =&gt; { Alert.alert(&quot;Modal has been closed.&quot;); setModalVisible(!modalVisible); }} &gt; &lt;View style={styles.centeredView}&gt; &lt;View style={styles.modalView}&gt; &lt;Image source={{ uri:doc.imgURL }} style={{width:&quot;100%&quot;,height:300}}/&gt; &lt;Text style={{fontWeight:&quot;700&quot;,fontSize:25}}&gt;{doc.title}&lt;/Text&gt; &lt;Text style={{fontWeight:&quot;700&quot;,fontSize:16}}&gt;{doc.desc}&lt;/Text&gt; &lt;Pressable style={[styles.button, styles.buttonClose]} onPress={() =&gt; setModalVisible(!modalVisible)} &gt; &lt;Text style={styles.textStyle}&gt;Hide Modal&lt;/Text&gt; &lt;/Pressable&gt; &lt;/View&gt; &lt;/View&gt; &lt;/Modal&gt; &lt;LessonCard setModalVisible={setModalVisible} title={doc.title} desc={doc.desc} img1={doc.imgURL} modalVisible={modalVisible}/&gt; &lt;/&gt; )} &lt;View style={{height:600,width:&quot;100%&quot;}}&gt;&lt;/View&gt; &lt;/ScrollView&gt; &lt;/View&gt; &lt;/View&gt; ) } </code></pre> <p>What it looks like: <a href="https://i.stack.imgur.com/BKSav.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BKSav.png" alt="what it looks like before you press modal" /></a> <a href="https://i.stack.imgur.com/zdLq6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zdLq6.png" alt="after you press modal" /></a></p> <p>**image 1 is before you press the modal and the 2nd one is after **the main issue though is that if you press cancel and press on another lesson the modal that opens has the the same state(title,imgurl,anddesc) as the first lesson and does not change.</p>
[ { "answer_id": 74672462, "author": "yts", "author_id": 1825352, "author_profile": "https://Stackoverflow.com/users/1825352", "pm_score": 0, "selected": false, "text": "Modal modalVisible true Modal LessonCard Learn {lessons && lessons.map((doc,key) => (\n <LessonCard lesson={doc} key={key} />\n )}\n LessonCard setModalVisible modalVisible const [modalVisible, setModalVisible] = useState(false);\n LessonCard Learn key LessonCard map LessonCard key LessonCard export default function LessonCard({lesson}) {\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15875108/" ]
74,672,395
<p>Very long title but essentially there is a <code>Type 'string' is not assignable to type 'never'.ts(2322) fieldArray.d.ts(7, 5): The expected type comes from property 'name' which is declared here on type 'UseFieldArrayProps&lt;FormValues, never, &quot;id&quot;&gt;'</code> error on the fieldArray definition in react-hook-form that sometimes disappears but is there most of the time and i have no idea why it is there since all examples show it like that and it sometimes without any changes disappears. Does anyone have a clue what the issue is? Why is typescript complaining?</p> <p>I've tried changing versions, reordering the control and name values (it removed the error once and when i swapped them again it came back and no matter how many times i swapped them around again it stayed there).</p> <p>It's one of those errors I have not the slightest clue where it's coming from.</p> <p>Codesandbox link here: <a href="https://codesandbox.io/s/react-hook-form-list-of-numbers-s6zg2p?file=%2Fsrc%2FApp.tsx" rel="nofollow noreferrer">https://codesandbox.io/s/react-hook-form-list-of-numbers-s6zg2p?file=%2Fsrc%2FApp.tsx</a></p> <p>Edit: error is specifically on line 35.</p>
[ { "answer_id": 74672462, "author": "yts", "author_id": 1825352, "author_profile": "https://Stackoverflow.com/users/1825352", "pm_score": 0, "selected": false, "text": "Modal modalVisible true Modal LessonCard Learn {lessons && lessons.map((doc,key) => (\n <LessonCard lesson={doc} key={key} />\n )}\n LessonCard setModalVisible modalVisible const [modalVisible, setModalVisible] = useState(false);\n LessonCard Learn key LessonCard map LessonCard key LessonCard export default function LessonCard({lesson}) {\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8865488/" ]
74,672,405
<p>I have 3 series with data like below</p> <pre><code>s1 = [1,1,3] s2 = [2,3,2] s3 = [4,2,1] </code></pre> <p>I want to create a new series with values such that</p> <p><code>s_new = [124,132,321]</code></p> <p>please note that <code>s_new = int(''.join(s1,s2,s3))</code> I know the above syntax is wrong but you get the idea.</p>
[ { "answer_id": 74672486, "author": "BENY", "author_id": 7964527, "author_profile": "https://Stackoverflow.com/users/7964527", "pm_score": 2, "selected": true, "text": "agg s = pd.DataFrame([s1,s2,s3]).astype(str).agg(''.join).astype(int).tolist()\nOut[334]: [124, 132, 321]\n" }, { "answer_id": 74672509, "author": "Lukicinius Angello Donatella", "author_id": 14389231, "author_profile": "https://Stackoverflow.com/users/14389231", "pm_score": 0, "selected": false, "text": "s1 = [1,1,3]\ns2 = [2,3,2]\ns3 = [4,2,1]\nmatrix = [s1,s2,s3]\ns_new = [\"\" for x in range(len(matrix))];\n\nfor i in range(0,len(matrix)):\n for j in range(0,len(matrix[i])):\n s_new[i]+=str(matrix[j][i])\n \nprint(s_new)\n" }, { "answer_id": 74672623, "author": "Jason Baker", "author_id": 3249641, "author_profile": "https://Stackoverflow.com/users/3249641", "pm_score": 0, "selected": false, "text": "import numpy as np\n\n\ns1 = [1, 1, 3]\ns2 = [2, 3, 2]\ns3 = [4, 2, 1]\n\ns4 = [int(\"\".join(str(i) for i in x)) for x in np.column_stack([s1, s2, s3])]\nprint(s4)\n\n[124, 132, 321]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10758118/" ]
74,672,423
<p>Okay, so I've been driving myself crazy trying to get this to display in SQL. I have a table that stores types of food, the culture they come from, a score, and a boolean value about whether or not they are good. I want to display a record of how many &quot;goods&quot; each culture racks up. Here's the table (don't ask about the database name):</p> <p><a href="https://i.stack.imgur.com/jTOTA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jTOTA.png" alt="enter image description here" /></a></p> <p>So I've tried:</p> <pre><code>SELECT count(good = 1), culture FROM animals_db.foods group by culture; </code></pre> <p>Or</p> <pre><code>SELECT count(good = true), culture FROM animals_db.foods group by culture; </code></pre> <p>But it doesn't present the correct results, it seems to include anything that has any &quot;good&quot; value (1 or 0) at all.</p> <p><a href="https://i.stack.imgur.com/7pGbM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7pGbM.png" alt="enter image description here" /></a></p> <p>How do I get the data I want?</p>
[ { "answer_id": 74672486, "author": "BENY", "author_id": 7964527, "author_profile": "https://Stackoverflow.com/users/7964527", "pm_score": 2, "selected": true, "text": "agg s = pd.DataFrame([s1,s2,s3]).astype(str).agg(''.join).astype(int).tolist()\nOut[334]: [124, 132, 321]\n" }, { "answer_id": 74672509, "author": "Lukicinius Angello Donatella", "author_id": 14389231, "author_profile": "https://Stackoverflow.com/users/14389231", "pm_score": 0, "selected": false, "text": "s1 = [1,1,3]\ns2 = [2,3,2]\ns3 = [4,2,1]\nmatrix = [s1,s2,s3]\ns_new = [\"\" for x in range(len(matrix))];\n\nfor i in range(0,len(matrix)):\n for j in range(0,len(matrix[i])):\n s_new[i]+=str(matrix[j][i])\n \nprint(s_new)\n" }, { "answer_id": 74672623, "author": "Jason Baker", "author_id": 3249641, "author_profile": "https://Stackoverflow.com/users/3249641", "pm_score": 0, "selected": false, "text": "import numpy as np\n\n\ns1 = [1, 1, 3]\ns2 = [2, 3, 2]\ns3 = [4, 2, 1]\n\ns4 = [int(\"\".join(str(i) for i in x)) for x in np.column_stack([s1, s2, s3])]\nprint(s4)\n\n[124, 132, 321]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9883126/" ]
74,672,427
<p>Daily I’m receiving a new table with same format name but different dates, I want to concatenate daily new table data with main_table.</p> <p>I want to concatenate daily new table data with my main table. Note : Dataset is same, schema also same</p>
[ { "answer_id": 74672486, "author": "BENY", "author_id": 7964527, "author_profile": "https://Stackoverflow.com/users/7964527", "pm_score": 2, "selected": true, "text": "agg s = pd.DataFrame([s1,s2,s3]).astype(str).agg(''.join).astype(int).tolist()\nOut[334]: [124, 132, 321]\n" }, { "answer_id": 74672509, "author": "Lukicinius Angello Donatella", "author_id": 14389231, "author_profile": "https://Stackoverflow.com/users/14389231", "pm_score": 0, "selected": false, "text": "s1 = [1,1,3]\ns2 = [2,3,2]\ns3 = [4,2,1]\nmatrix = [s1,s2,s3]\ns_new = [\"\" for x in range(len(matrix))];\n\nfor i in range(0,len(matrix)):\n for j in range(0,len(matrix[i])):\n s_new[i]+=str(matrix[j][i])\n \nprint(s_new)\n" }, { "answer_id": 74672623, "author": "Jason Baker", "author_id": 3249641, "author_profile": "https://Stackoverflow.com/users/3249641", "pm_score": 0, "selected": false, "text": "import numpy as np\n\n\ns1 = [1, 1, 3]\ns2 = [2, 3, 2]\ns3 = [4, 2, 1]\n\ns4 = [int(\"\".join(str(i) for i in x)) for x in np.column_stack([s1, s2, s3])]\nprint(s4)\n\n[124, 132, 321]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20670906/" ]
74,672,441
<p>We are fetching data from API like:</p> <pre><code>&lt;script setup&gt; import { onMounted, inject } from 'vue' let list = []; function init() { axios .post(&quot;/some-link/here&quot;) .then((o) =&gt; { list = o.data.bla; console.log(list); }) .catch((o) =&gt; { //TO DO }); } onMounted(() =&gt; { init(); }); &lt;/script&gt; </code></pre> <p>The <code>console.log</code> shows the list properly.</p> <p>But on the template, it does not update.</p> <pre><code>&lt;p v-for=&quot;(val, index) in list&quot; :key=&quot;index&quot;&gt; {{ val.name }} &lt;/p&gt; </code></pre>
[ { "answer_id": 74672486, "author": "BENY", "author_id": 7964527, "author_profile": "https://Stackoverflow.com/users/7964527", "pm_score": 2, "selected": true, "text": "agg s = pd.DataFrame([s1,s2,s3]).astype(str).agg(''.join).astype(int).tolist()\nOut[334]: [124, 132, 321]\n" }, { "answer_id": 74672509, "author": "Lukicinius Angello Donatella", "author_id": 14389231, "author_profile": "https://Stackoverflow.com/users/14389231", "pm_score": 0, "selected": false, "text": "s1 = [1,1,3]\ns2 = [2,3,2]\ns3 = [4,2,1]\nmatrix = [s1,s2,s3]\ns_new = [\"\" for x in range(len(matrix))];\n\nfor i in range(0,len(matrix)):\n for j in range(0,len(matrix[i])):\n s_new[i]+=str(matrix[j][i])\n \nprint(s_new)\n" }, { "answer_id": 74672623, "author": "Jason Baker", "author_id": 3249641, "author_profile": "https://Stackoverflow.com/users/3249641", "pm_score": 0, "selected": false, "text": "import numpy as np\n\n\ns1 = [1, 1, 3]\ns2 = [2, 3, 2]\ns3 = [4, 2, 1]\n\ns4 = [int(\"\".join(str(i) for i in x)) for x in np.column_stack([s1, s2, s3])]\nprint(s4)\n\n[124, 132, 321]\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20621336/" ]
74,672,444
<p>I was working on a project, and thought, <em>Couldn't there be an easier way to write a list without having to waste 3 minutes and one line of code?</em> I'm probably wasting even more time here, but suppose I want to spell out &quot;Hello, world!&quot;:</p> <pre><code>class Main { public static void main(String[] args) { String[] array = {&quot;H&quot;, &quot;E&quot;, &quot;L&quot;, &quot;L&quot;, &quot;O&quot;, &quot;, &quot;, &quot;W&quot;, &quot;O&quot;, &quot;R&quot;, &quot;L&quot;, &quot;D&quot;, &quot;!&quot;}; for (int i = 0; i &lt; array.length; i++) { System.out.print(array[i] + &quot;-&quot;); // prints &quot;H-E-L-L-O-, -W-O-R-L-D-!-&quot; } } } </code></pre> <p>As you can see there's a nagging dash hanging over the edge at the end of the line. One idea I had was doing this:</p> <pre><code>class Main { public static void main(String[] args) { String[] array = {&quot;H&quot;, &quot;E&quot;, &quot;L&quot;, &quot;L&quot;, &quot;O&quot;, &quot;, &quot;, &quot;W&quot;, &quot;O&quot;, &quot;R&quot;, &quot;L&quot;, &quot;D&quot;, &quot;!&quot;}; System.out.print(array[0]); // enter &quot;H&quot; early for (int i = 1; i &lt; array.length; i++) { // int i = 0 -&gt; int i = 1 System.out.print(&quot;-&quot; + array[i]); // switched order, prints &quot;H-E-L-L-O-, -W-O-R-L-D-!&quot; } } } </code></pre> <p>Yes, this does complete the job, but I feel like the extra line is clunky and awkward in my code. Also, I don't feel it's exactly flexible? If there's something inside the documentary junk or a trick I need, please let me know. :)</p>
[ { "answer_id": 74672495, "author": "Shahood ul Hassan", "author_id": 7983864, "author_profile": "https://Stackoverflow.com/users/7983864", "pm_score": 1, "selected": false, "text": "class Main {\n public static void main(String[] args) {\n String[] array = {\"H\", \"E\", \"L\", \"L\", \"O\", \", \", \"W\", \"O\", \"R\", \"L\", \"D\", \"!\"};\n\n for (int i = 0; i < array.length; i++) { \n System.out.print((i == 0 ? \"\" : \"-\") + array[i]); // prints \"H-E-L-L-O-, -W-O-R-L-D-!\"\n }\n }\n}\n" }, { "answer_id": 74672853, "author": "Sam Cousins", "author_id": 19152535, "author_profile": "https://Stackoverflow.com/users/19152535", "pm_score": 0, "selected": false, "text": "i (i == array.length - 1 ? \"\" : \"-\") \"-\"" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20678048/" ]
74,672,480
<p>I did the following calculations in Julia</p> <pre><code>z = LinRange(-0.09025000000000001,0.19025000000000003,5) d = Normal.(0.05*(1-0.95) .+ 0.95.*z .- 0.0051^2/2, 0.0051 .* (similar(z) .*0 .+1)) minimum(cdf.(d, (z[3]+z[2])/2)) </code></pre> <p>The problem I have is that the last code sometimes gives me the correct result <code>4.418051841202834e-239</code>, sometimes reports the error <code>DomainError with NaN: Normal: the condition σ &gt;= zero(σ) is not satisfied</code>. I think this is because <code>4.418051841202834e-239</code> is too small. But I was wondering why my code can give me different results.</p>
[ { "answer_id": 74673288, "author": "Rimuru", "author_id": 6571922, "author_profile": "https://Stackoverflow.com/users/6571922", "pm_score": 1, "selected": false, "text": "using Pkg\nPkg.add(\"SpecialFunctions\")\nusing SpecialFunctions\n\nz = LinRange(-0.09025000000000001,0.19025000000000003,5)\nd = Normal.(BigFloat.(0.05*(1-0.95)) .+ BigFloat.(0.95)*BigFloat.(z) .- BigFloat(0.0051^2/2), BigFloat.(0.0051) .* (similar(z) .*0 .+1))\nminimum(cdf.(d, (z[3]+z[2])/2))\n" }, { "answer_id": 74674162, "author": "Dan Getz", "author_id": 3580870, "author_profile": "https://Stackoverflow.com/users/3580870", "pm_score": 1, "selected": false, "text": "similar(z) ones(length(z))" }, { "answer_id": 74674445, "author": "Przemyslaw Szufel", "author_id": 9957710, "author_profile": "https://Stackoverflow.com/users/9957710", "pm_score": 1, "selected": false, "text": "similar NaN 0 NaN * 0 == NaN ones(eltype(z),size(z)) Float64 BigFloat setprecision(BigFloat, 128) DoubleFloats using DoubleFloats julia> z = LinRange(df64\"-0.09025000000000001\",df64\"0.19025000000000003\",5)\n5-element LinRange{Double64, Int64}:\n -0.09025000000000001,-0.020125,0.05000000000000001,0.12012500000000002,0.19025000000000003\n\njulia> d = Normal.(0.05*(1-0.95) .+ 0.95.*z .- 0.0051^2/2, 0.0051 .* ones(eltype(z),size(z)))\n5-element Vector{Normal{Double64}}:\n Normal{Double64}(μ=-0.083250505, σ=0.0051)\n Normal{Double64}(μ=-0.016631754999999998, σ=0.0051)\n Normal{Double64}(μ=0.049986995000000006, σ=0.0051)\n Normal{Double64}(μ=0.11660574500000001, σ=0.0051)\n Normal{Double64}(μ=0.18322449500000001, σ=0.0051)\n\njulia> minimum(cdf.(d, (z[3]+z[2])/2))\n4.418051841203009e-239\n" }, { "answer_id": 74675161, "author": "DNF", "author_id": 2749865, "author_profile": "https://Stackoverflow.com/users/2749865", "pm_score": 3, "selected": true, "text": "LinRange range LinRange range LinRange julia> LinRange(-0.09025000000000001,0.19025000000000003,5) .- range(-0.09025000000000001,0.19025000000000003,5)\n0.0:-3.469446951953614e-18:-1.3877787807814457e-17\n 0.0051 .* (similar(z) .*0 .+1)\n ones fill fill(0.0051, size(z))\n convert(eltype(z), 0.0051) fill d = Normal.(0.05*(1-0.95) .+ 0.95.*z .- 0.0051^2/2, 0.0051) # look! just a scalar!\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16844272/" ]
74,672,508
<p>I've a data set with list of names &amp; combinations and need to map with the team.</p> <p>For ex, if the list of name is unique, then it should give me team name.. If the name of combination from team, it should give same team name.. Combination between two teams, then it should say team C.</p> <p>Here is the trix for ref: <a href="https://docs.google.com/spreadsheets/d/1leb0hQ5gb6RclcMb__JYJLqvIFBQD_B3v7c2o4PbICg/edit#gid=0" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1leb0hQ5gb6RclcMb__JYJLqvIFBQD_B3v7c2o4PbICg/edit#gid=0</a></p> <p>I tried lookup, but it is fulling first case but not the people combination. Is there any way I can achieve this. Also, I assume these names are separated by ascii CHAR(10).</p> <p>Let me know any inputs or suggestions so I can fulfil this.</p>
[ { "answer_id": 74673288, "author": "Rimuru", "author_id": 6571922, "author_profile": "https://Stackoverflow.com/users/6571922", "pm_score": 1, "selected": false, "text": "using Pkg\nPkg.add(\"SpecialFunctions\")\nusing SpecialFunctions\n\nz = LinRange(-0.09025000000000001,0.19025000000000003,5)\nd = Normal.(BigFloat.(0.05*(1-0.95)) .+ BigFloat.(0.95)*BigFloat.(z) .- BigFloat(0.0051^2/2), BigFloat.(0.0051) .* (similar(z) .*0 .+1))\nminimum(cdf.(d, (z[3]+z[2])/2))\n" }, { "answer_id": 74674162, "author": "Dan Getz", "author_id": 3580870, "author_profile": "https://Stackoverflow.com/users/3580870", "pm_score": 1, "selected": false, "text": "similar(z) ones(length(z))" }, { "answer_id": 74674445, "author": "Przemyslaw Szufel", "author_id": 9957710, "author_profile": "https://Stackoverflow.com/users/9957710", "pm_score": 1, "selected": false, "text": "similar NaN 0 NaN * 0 == NaN ones(eltype(z),size(z)) Float64 BigFloat setprecision(BigFloat, 128) DoubleFloats using DoubleFloats julia> z = LinRange(df64\"-0.09025000000000001\",df64\"0.19025000000000003\",5)\n5-element LinRange{Double64, Int64}:\n -0.09025000000000001,-0.020125,0.05000000000000001,0.12012500000000002,0.19025000000000003\n\njulia> d = Normal.(0.05*(1-0.95) .+ 0.95.*z .- 0.0051^2/2, 0.0051 .* ones(eltype(z),size(z)))\n5-element Vector{Normal{Double64}}:\n Normal{Double64}(μ=-0.083250505, σ=0.0051)\n Normal{Double64}(μ=-0.016631754999999998, σ=0.0051)\n Normal{Double64}(μ=0.049986995000000006, σ=0.0051)\n Normal{Double64}(μ=0.11660574500000001, σ=0.0051)\n Normal{Double64}(μ=0.18322449500000001, σ=0.0051)\n\njulia> minimum(cdf.(d, (z[3]+z[2])/2))\n4.418051841203009e-239\n" }, { "answer_id": 74675161, "author": "DNF", "author_id": 2749865, "author_profile": "https://Stackoverflow.com/users/2749865", "pm_score": 3, "selected": true, "text": "LinRange range LinRange range LinRange julia> LinRange(-0.09025000000000001,0.19025000000000003,5) .- range(-0.09025000000000001,0.19025000000000003,5)\n0.0:-3.469446951953614e-18:-1.3877787807814457e-17\n 0.0051 .* (similar(z) .*0 .+1)\n ones fill fill(0.0051, size(z))\n convert(eltype(z), 0.0051) fill d = Normal.(0.05*(1-0.95) .+ 0.95.*z .- 0.0051^2/2, 0.0051) # look! just a scalar!\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19264018/" ]
74,672,541
<p>I have alphabets that I want to assign as follows:</p> <p>lowercase items a-z have value of 1-26 uppercase items A-Z have value of 27-52</p> <p>What is the shortest way to implement this</p> <p>[a,B,h,R] Expected Output: [1,28,8,44]</p> <p>How can we go about doing this in Python</p> <p>Thank you</p>
[ { "answer_id": 74672568, "author": "Andrew Ryan", "author_id": 7451892, "author_profile": "https://Stackoverflow.com/users/7451892", "pm_score": 0, "selected": false, "text": "print([ord(item) - 38 if ord(item) < 97 else ord(item) - 96 for item in ['a','B','h','R']])\n" }, { "answer_id": 74672597, "author": "a coder", "author_id": 18254316, "author_profile": "https://Stackoverflow.com/users/18254316", "pm_score": 2, "selected": false, "text": "from string import ascii_letters\nprint([ascii_letters.index(letter) + 1 for letter in [\"a\", \"B\", \"h\", \"R\"]])\n" }, { "answer_id": 74672652, "author": "qeberhard", "author_id": 20479850, "author_profile": "https://Stackoverflow.com/users/20479850", "pm_score": 1, "selected": false, "text": "import string\nfrom collections import OrderedDict\nlower_priorities = OrderedDict(zip(string.ascii_lowercase, range(1,27)))\nupper_priorities = OrderedDict(zip(string.ascii_uppercase, range(27,53)))\n lower_priorities[\"a\"] 1" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12098085/" ]
74,672,587
<p>I have a header that looks like this:</p> <pre class="lang-html prettyprint-override"><code>&lt;header&gt; &lt;div&gt;A&lt;/div&gt; &lt;div&gt;B&lt;/div&gt; &lt;div&gt;C&lt;/div&gt; &lt;/header&gt; </code></pre> <p>Rather than spacing these items evenly, I want all the space to be between A and B, like this:</p> <p><a href="https://i.stack.imgur.com/Z70cw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z70cw.png" alt="Demonstration" /></a></p> <p><strong>Is there any way to do this with plain CSS, without adding extra wrapper elements in HTML?</strong></p> <hr /> <p>I'm very specifically talking about <em>spacing</em>, adding <code>flex-grow: 1</code> to <code>A</code> is cheating In my case both <code>A</code> and <code>B</code> are clickable, and I don't want them smeared across the entire header.</p>
[ { "answer_id": 74672568, "author": "Andrew Ryan", "author_id": 7451892, "author_profile": "https://Stackoverflow.com/users/7451892", "pm_score": 0, "selected": false, "text": "print([ord(item) - 38 if ord(item) < 97 else ord(item) - 96 for item in ['a','B','h','R']])\n" }, { "answer_id": 74672597, "author": "a coder", "author_id": 18254316, "author_profile": "https://Stackoverflow.com/users/18254316", "pm_score": 2, "selected": false, "text": "from string import ascii_letters\nprint([ascii_letters.index(letter) + 1 for letter in [\"a\", \"B\", \"h\", \"R\"]])\n" }, { "answer_id": 74672652, "author": "qeberhard", "author_id": 20479850, "author_profile": "https://Stackoverflow.com/users/20479850", "pm_score": 1, "selected": false, "text": "import string\nfrom collections import OrderedDict\nlower_priorities = OrderedDict(zip(string.ascii_lowercase, range(1,27)))\nupper_priorities = OrderedDict(zip(string.ascii_uppercase, range(27,53)))\n lower_priorities[\"a\"] 1" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388916/" ]
74,672,594
<p>I'm using material top tabs. Problem is, when a state changes in one tab, all other tabs that use the same state render again which slows the app a little. How do I prevent tabs from getting updated unless they are focused / seen ?</p>
[ { "answer_id": 74672568, "author": "Andrew Ryan", "author_id": 7451892, "author_profile": "https://Stackoverflow.com/users/7451892", "pm_score": 0, "selected": false, "text": "print([ord(item) - 38 if ord(item) < 97 else ord(item) - 96 for item in ['a','B','h','R']])\n" }, { "answer_id": 74672597, "author": "a coder", "author_id": 18254316, "author_profile": "https://Stackoverflow.com/users/18254316", "pm_score": 2, "selected": false, "text": "from string import ascii_letters\nprint([ascii_letters.index(letter) + 1 for letter in [\"a\", \"B\", \"h\", \"R\"]])\n" }, { "answer_id": 74672652, "author": "qeberhard", "author_id": 20479850, "author_profile": "https://Stackoverflow.com/users/20479850", "pm_score": 1, "selected": false, "text": "import string\nfrom collections import OrderedDict\nlower_priorities = OrderedDict(zip(string.ascii_lowercase, range(1,27)))\nupper_priorities = OrderedDict(zip(string.ascii_uppercase, range(27,53)))\n lower_priorities[\"a\"] 1" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19860468/" ]
74,672,630
<p>So my issue is that, I want to get user's <strong>id</strong> info from the chat.</p> <p>The chat area what I'm looking for, looks like this...</p> <pre><code>&lt;div id=&quot;chat_area&quot; class=&quot;chat_area&quot; style=&quot;will-change: scroll-position;&quot;&gt; &lt;dl class=&quot;&quot; user_id=&quot;asdf1234&quot;&gt;&lt;dt class=&quot;user_m&quot;&gt;&lt;em class=&quot;pc&quot;&gt;&lt;/em&gt; :&lt;/dt&gt;&lt;dd id=&quot;1&quot;&gt;blah blah&lt;/dd&gt;&lt;/dl&gt; &lt;a href=&quot;javascript:;&quot; user_id=&quot;asdf1234&quot; user_nick=&quot;asdf1234&quot; userflag=&quot;65536&quot; is_mobile=&quot;false&quot; grade=&quot;user&quot;&gt;asdf1234&lt;/a&gt; ... </code></pre> <p>What I want do is to, <br/> Get the part starting with <code>&lt;a href='javascript:'' user_id='asdf1234' ...</code> <br/> so that I can parse this and do some other stuffs.</p> <p>But this webpage is the one I'm currently using, and it can not be proxy(webdriver by selenium).</p> <p>How can I extract that data from the chat?</p>
[ { "answer_id": 74672568, "author": "Andrew Ryan", "author_id": 7451892, "author_profile": "https://Stackoverflow.com/users/7451892", "pm_score": 0, "selected": false, "text": "print([ord(item) - 38 if ord(item) < 97 else ord(item) - 96 for item in ['a','B','h','R']])\n" }, { "answer_id": 74672597, "author": "a coder", "author_id": 18254316, "author_profile": "https://Stackoverflow.com/users/18254316", "pm_score": 2, "selected": false, "text": "from string import ascii_letters\nprint([ascii_letters.index(letter) + 1 for letter in [\"a\", \"B\", \"h\", \"R\"]])\n" }, { "answer_id": 74672652, "author": "qeberhard", "author_id": 20479850, "author_profile": "https://Stackoverflow.com/users/20479850", "pm_score": 1, "selected": false, "text": "import string\nfrom collections import OrderedDict\nlower_priorities = OrderedDict(zip(string.ascii_lowercase, range(1,27)))\nupper_priorities = OrderedDict(zip(string.ascii_uppercase, range(27,53)))\n lower_priorities[\"a\"] 1" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7820717/" ]
74,672,648
<p>I have this dataframe:</p> <pre><code>id check_id 1 10 1 100 2 10 3 34 4 12 1 101 </code></pre> <p>and a list:</p> <pre><code>list=[10,101] </code></pre> <p>I am trying to filter this df like this:</p> <pre><code>df[(df['id']==1) and (df['check_id'].isin(list))] </code></pre> <p>To get this output:</p> <pre><code>id check_id 1 10 1 101 </code></pre> <p>but I get this error msg:</p> <pre><code>The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). </code></pre> <p>I've been trying to solve it but no sucess so far.</p> <p>How can I fix it?</p>
[ { "answer_id": 74672568, "author": "Andrew Ryan", "author_id": 7451892, "author_profile": "https://Stackoverflow.com/users/7451892", "pm_score": 0, "selected": false, "text": "print([ord(item) - 38 if ord(item) < 97 else ord(item) - 96 for item in ['a','B','h','R']])\n" }, { "answer_id": 74672597, "author": "a coder", "author_id": 18254316, "author_profile": "https://Stackoverflow.com/users/18254316", "pm_score": 2, "selected": false, "text": "from string import ascii_letters\nprint([ascii_letters.index(letter) + 1 for letter in [\"a\", \"B\", \"h\", \"R\"]])\n" }, { "answer_id": 74672652, "author": "qeberhard", "author_id": 20479850, "author_profile": "https://Stackoverflow.com/users/20479850", "pm_score": 1, "selected": false, "text": "import string\nfrom collections import OrderedDict\nlower_priorities = OrderedDict(zip(string.ascii_lowercase, range(1,27)))\nupper_priorities = OrderedDict(zip(string.ascii_uppercase, range(27,53)))\n lower_priorities[\"a\"] 1" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18333836/" ]
74,672,655
<p>I need your help to deploy a web application developed with spring, java, jpa, mysql.</p> <p>I have google cloud account.</p> <p>I have deployed a REST service with a .jar file.</p> <p>Do you have any reference to any manual or courses?</p>
[ { "answer_id": 74672568, "author": "Andrew Ryan", "author_id": 7451892, "author_profile": "https://Stackoverflow.com/users/7451892", "pm_score": 0, "selected": false, "text": "print([ord(item) - 38 if ord(item) < 97 else ord(item) - 96 for item in ['a','B','h','R']])\n" }, { "answer_id": 74672597, "author": "a coder", "author_id": 18254316, "author_profile": "https://Stackoverflow.com/users/18254316", "pm_score": 2, "selected": false, "text": "from string import ascii_letters\nprint([ascii_letters.index(letter) + 1 for letter in [\"a\", \"B\", \"h\", \"R\"]])\n" }, { "answer_id": 74672652, "author": "qeberhard", "author_id": 20479850, "author_profile": "https://Stackoverflow.com/users/20479850", "pm_score": 1, "selected": false, "text": "import string\nfrom collections import OrderedDict\nlower_priorities = OrderedDict(zip(string.ascii_lowercase, range(1,27)))\nupper_priorities = OrderedDict(zip(string.ascii_uppercase, range(27,53)))\n lower_priorities[\"a\"] 1" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20079590/" ]
74,672,691
<p>Unless I am overlooking something, I cannot find the solution to the following.</p> <p>If I have the following single element vector:</p> <pre><code>c(&quot;133 45123; 4514;25&quot;) </code></pre> <p>How can I find the position within this element that has the &quot;;&quot; and &quot; &quot;, such that I can then use substr to obtain:</p> <pre><code>45123; </code></pre> <p>Have tried grep, but that seems to work over a vector of multiple elements.</p>
[ { "answer_id": 74672771, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 3, "selected": true, "text": "x <- c(\"133 45123; 4514;25\")\n\nstringr::str_extract(x, \"\\\\w+(?=; )\")\n[1] \"45123\"\n sub(\".*?(\\\\w+); .*\", \"\\\\1\", x)\n[1] \"45123\"\n regmatches(x, regexpr(\"\\\\w+(?=; )\", x, perl = TRUE))\n[1] \"45123\"\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15326829/" ]
74,672,767
<p>I am writing a script that reads two Json files into dictionaries</p> <p>The dictionaries are more or less similar, like this</p> <pre><code>{ &quot;elements&quot;:[ { &quot;element_id&quot;:0, &quot;thedata&quot;:{ &quot;this&quot;: 5 } }, { &quot;element_id&quot;:4, &quot;thedata&quot;:{ &quot;this&quot;: 5 } } { ... } ]} </code></pre> <p>So far I had assumed that the <code>element_id</code> went from 0 and increased 1 by 1 Then the requirements changed and this time they went from 0 and increased 4 by 4 or something like this</p> <p>Anyway, I though so far that both dictionaries would have the same number of elements and the same increasing distance so when I got the elements in my script I wrote something like</p> <pre><code>def process_elements(number): el1_id=thedictionary['elements'][number]['element_id'] el2_id=thedictionary2['elements'][number]['element_id'] assert(el1_id==el2_id) #here work with the data </code></pre> <p>However the requirements have changed again</p> <p>Now the number of elements of one dictionary are not necessarily the same as the other Also it is not guaranteed that one of them start always at 0</p> <p>So now I have to find the elements in both dictionaries with <em>the same element id</em></p> <p>So my question is , in a dictionary like above (that came from a json) is there a <em><strong>quick</strong></em> way to find the element that has a particular <code>element_id</code> and get the element?</p> <p>Something like</p> <pre><code>def process_elements(number): el1_id=thedictionary['elements'][number]['element_id'] n=find_i(thedictionary2,el1_id) #finds the index with the element that has id the same as el1_id el2_id=thedictionary2['elements'][n]['element_id'] assert(el1_id==el2_id) #Of course they are the same since we used find_i #here work with the data </code></pre> <p>It has to be quick since I use it for an animation</p>
[ { "answer_id": 74672771, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 3, "selected": true, "text": "x <- c(\"133 45123; 4514;25\")\n\nstringr::str_extract(x, \"\\\\w+(?=; )\")\n[1] \"45123\"\n sub(\".*?(\\\\w+); .*\", \"\\\\1\", x)\n[1] \"45123\"\n regmatches(x, regexpr(\"\\\\w+(?=; )\", x, perl = TRUE))\n[1] \"45123\"\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4451521/" ]
74,672,781
<p>As I know that templates are expanded at compile time but in below example i am deciding or doing template instantiation at runtime depending on user input but still i am getting expected output.how this running? can someone explain me</p> <pre><code>#include &lt;iostream&gt; using namespace std; template&lt;typename T&gt; class Demo { T Value = 20.67; public: void print(T val) { std::cout &lt;&lt; &quot;value :&quot; &lt;&lt; val &lt;&lt; std::endl; } T getValue() { return Value; } }; int main() { int a; std::cout &lt;&lt; &quot;Enter value for a :&quot;; std::cin &gt;&gt; a; if(a == 10) { Demo&lt;int&gt; demoObj1; demoObj1.print(demoObj1.getValue()); } else { Demo&lt;float&gt; demoObj2; demoObj2.print(demoObj2.getValue()); } } </code></pre> <blockquote> <p>//output:</p> <blockquote> <blockquote> <p>Enter value for a :10<br /> value :20</p> <p>and Enter value for a :7<br /> value :20.67</p> </blockquote> </blockquote> </blockquote>
[ { "answer_id": 74672771, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 3, "selected": true, "text": "x <- c(\"133 45123; 4514;25\")\n\nstringr::str_extract(x, \"\\\\w+(?=; )\")\n[1] \"45123\"\n sub(\".*?(\\\\w+); .*\", \"\\\\1\", x)\n[1] \"45123\"\n regmatches(x, regexpr(\"\\\\w+(?=; )\", x, perl = TRUE))\n[1] \"45123\"\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10931141/" ]
74,672,798
<p><a href="https://i.stack.imgur.com/Vtl7B.png" rel="nofollow noreferrer">enter image description here</a></p> <pre><code>bank_account = None highest = 0 for account, amount in accounts.items(): if amount &gt; highest: -------------&lt; bank_account = account highest = account print(bank_acount, highest) </code></pre> <pre><code>TypeError: '&gt;' not supported between instances of 'int' and 'str' </code></pre> <p>how can I alter my code to make it works</p>
[ { "answer_id": 74672771, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 3, "selected": true, "text": "x <- c(\"133 45123; 4514;25\")\n\nstringr::str_extract(x, \"\\\\w+(?=; )\")\n[1] \"45123\"\n sub(\".*?(\\\\w+); .*\", \"\\\\1\", x)\n[1] \"45123\"\n regmatches(x, regexpr(\"\\\\w+(?=; )\", x, perl = TRUE))\n[1] \"45123\"\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20597938/" ]
74,672,802
<p>Hi i am trying to get ID card details in a component and form an object &quot;idCardDetails&quot;. In JS i was able to dynamicaly add key and values : <code>let myObj = {}; myObj.name = &quot;sid&quot;; myObj.num= 4444;</code></p> <p>I cant create such a dynamic obj in Type script.</p> <p>I tried this in TS angular <code>IdCardDetails: {name: string, empcode: number, bloodgroup: string}; IdCardDetails.name = this.idName; // error cannot set property for undefined </code> Is this a error occurring with rules of Typescript or Angular? what will be solution to dynamicaly create an object? Is it necessary always go with class based object creation in angular?</p>
[ { "answer_id": 74672771, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 3, "selected": true, "text": "x <- c(\"133 45123; 4514;25\")\n\nstringr::str_extract(x, \"\\\\w+(?=; )\")\n[1] \"45123\"\n sub(\".*?(\\\\w+); .*\", \"\\\\1\", x)\n[1] \"45123\"\n regmatches(x, regexpr(\"\\\\w+(?=; )\", x, perl = TRUE))\n[1] \"45123\"\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16477896/" ]
74,672,824
<p>I am using Python 3.9, PyCharm 2022.</p> <p>My purpose (Ultimate goal of this question): create a command line application receive 2 parameters:</p> <ul> <li>Path of directory</li> <li>Extension of files</li> </ul> <p>then get size of files (Per file size, not sum of files size).</p> <pre class="lang-py prettyprint-override"><code>import os import argparse from os import listdir from os.path import isfile, join def main(): parser = argparse.ArgumentParser() parser.add_argument(&quot;path&quot;, help=&quot;Path of directory.&quot;) parser.add_argument(&quot;ext&quot;, help=&quot;Extension of files (for example: jpg, png, exe, mp4, etc.&quot;) args1 = parser.parse_args() args2 = parser.parse_args() print(args1) arr = os.listdir(args1) print(arr) # os.path.getsize(args.path) # bytes_size = os.path.getsize(args1.path) # mb_size = int(bytes_size / 1024 / 1024) # print(mb_size, &quot;MB&quot;) if __name__ == '__main__': main() </code></pre> <p>My command and according error:</p> <pre class="lang-py prettyprint-override"><code>(base) PS C:\Users\donhu\PycharmProjects\pythonProject4&gt; python size.py 'D:' 'jpg' Traceback (most recent call last): File &quot;C:\Users\donhu\PycharmProjects\pythonProject4\size.py&quot;, line 22, in &lt;module&gt; (base) PS C:\Users\donhu\PycharmProjects\pythonProject4&gt; python size.py 'D:' 'jpg' Namespace(path='D:', ext='jpg') Traceback (most recent call last): File &quot;C:\Users\donhu\PycharmProjects\pythonProject4\size.py&quot;, line 23, in &lt;module&gt; main() File &quot;C:\Users\donhu\PycharmProjects\pythonProject4\size.py&quot;, line 13, in main arr = os.listdir(args1) TypeError: listdir: path should be string, bytes, os.PathLike or None, not Namespace (base) PS C:\Users\donhu\PycharmProjects\pythonProject4&gt; </code></pre> <p><a href="https://i.stack.imgur.com/4IHpS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4IHpS.png" alt="enter image description here" /></a> How to fix?</p> <p>Update, I tried something</p> <pre class="lang-py prettyprint-override"><code>import os import argparse from os import listdir from os.path import isfile, join from pathlib import * def main(): parser = argparse.ArgumentParser() parser.add_argument(&quot;path&quot;, help=&quot;Đường dẫn của thư mục&quot;) parser.add_argument(&quot;ext&quot;, help=&quot;Định dạng tập tin cần liệt kê kích thước.&quot;) args1 = parser.parse_args() args2 = parser.parse_args() foo = args1.path # arr = os.listdir('D:/') files = [x for x in foo.iterdir() if x.is_file()] print(files) # os.path.getsize(args.path) # bytes_size = os.path.getsize(args1.path) # mb_size = int(bytes_size / 1024 / 1024) # print(mb_size, &quot;MB&quot;) if __name__ == '__main__': main() </code></pre> <p>but not work.</p>
[ { "answer_id": 74672875, "author": "Alec Cureau", "author_id": 20590353, "author_profile": "https://Stackoverflow.com/users/20590353", "pm_score": 0, "selected": false, "text": "parse_args() Namespace path os.listdir(args1.path)\n" }, { "answer_id": 74673024, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 2, "selected": true, "text": "os listdir stat pathlib pathlib Path import argparse\nfrom pathlib import Path\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"path\", help=\"Đường dẫn của thư mục\")\n parser.add_argument(\"ext\", help=\"Định dạng tập tin cần liệt kê kích thước.\")\n args = parser.parse_args()\n foo = Path(args.path)\n if not foo.is_dir():\n print(\"Error: Must be a directory\")\n exit(1)\n files = [x for x in foo.iterdir() if x.is_file()]\n print(files)\n # os.path.getsize(args.path)\n bytes_size = sum(file.stat().st_size for file in files)\n print(\"total bytes\", bytes_size)\n # mb_size = int(bytes_size / 1024 / 1024)\n # print(mb_size, \"MB\")\n\nif __name__ == '__main__':\n main()\n ext iterdir files = [x for x in foo.glob(f\"*.{args.ext}\") if x.is_file()]\n files = [x for x in foo.glob(f\"**/*.{args.ext}\") if x.is_file()]\n" }, { "answer_id": 74673067, "author": "Dude Eclair", "author_id": 20544495, "author_profile": "https://Stackoverflow.com/users/20544495", "pm_score": -1, "selected": false, "text": "print(type(args1))\n args1.path\nargs1.ext\n arr = os.listdir(args1.path)\n" }, { "answer_id": 74673093, "author": "James Grey", "author_id": 3728901, "author_profile": "https://Stackoverflow.com/users/3728901", "pm_score": 0, "selected": false, "text": "import os\nimport argparse\nfrom pathlib import Path\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"path\", help=\"Path of directory/folder\")\n parser.add_argument(\"ext\", help=\"Extension of file what need get size.\")\n args = parser.parse_args()\n foo = Path(args.path)\n files = [x for x in foo.glob(f\"*.{args.ext}\") if x.is_file()]\n for file in files:\n print(file.__str__(), os.path.getsize(file))\n\n\nif __name__ == '__main__':\n main()\n \n# python size.py \"D:\\\" 'jpg'\n\n# (base) PS C:\\Users\\donhu\\PycharmProjects\\pythonProject4> python size.py \"D:\\\" 'jpg'\n# D:\\1496231_10152440570407564_3432420_o.jpg 241439\n# D:\\15002366_278058419262140_505451777021235_o.jpg 598063\n# D:\\1958485_703442046353041_1444502_n.jpg 63839\n# D:\\277522952_5065319530178162_680264454398630_n.jpg 335423\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3728901/" ]
74,672,848
<p>I am making a chrome extension that aims to pause execution of a tab if it inactive after some time in order to stop if from consuming resources. By &quot;Pause&quot;, I mean something like <code>debugger</code>, however, <code>debugger</code> does not seem to work unless the developer inspector tool is open.</p> <p>Is there anyway to stop a tab from consuming resources until the user goes to that tab and click on something (like the play button on debugger)</p> <p>PS: I want to make this because there a synonym/dictionary website that slowly consumes 5GB of RAM even if it is left inactive for half an hour.</p>
[ { "answer_id": 74672875, "author": "Alec Cureau", "author_id": 20590353, "author_profile": "https://Stackoverflow.com/users/20590353", "pm_score": 0, "selected": false, "text": "parse_args() Namespace path os.listdir(args1.path)\n" }, { "answer_id": 74673024, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 2, "selected": true, "text": "os listdir stat pathlib pathlib Path import argparse\nfrom pathlib import Path\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"path\", help=\"Đường dẫn của thư mục\")\n parser.add_argument(\"ext\", help=\"Định dạng tập tin cần liệt kê kích thước.\")\n args = parser.parse_args()\n foo = Path(args.path)\n if not foo.is_dir():\n print(\"Error: Must be a directory\")\n exit(1)\n files = [x for x in foo.iterdir() if x.is_file()]\n print(files)\n # os.path.getsize(args.path)\n bytes_size = sum(file.stat().st_size for file in files)\n print(\"total bytes\", bytes_size)\n # mb_size = int(bytes_size / 1024 / 1024)\n # print(mb_size, \"MB\")\n\nif __name__ == '__main__':\n main()\n ext iterdir files = [x for x in foo.glob(f\"*.{args.ext}\") if x.is_file()]\n files = [x for x in foo.glob(f\"**/*.{args.ext}\") if x.is_file()]\n" }, { "answer_id": 74673067, "author": "Dude Eclair", "author_id": 20544495, "author_profile": "https://Stackoverflow.com/users/20544495", "pm_score": -1, "selected": false, "text": "print(type(args1))\n args1.path\nargs1.ext\n arr = os.listdir(args1.path)\n" }, { "answer_id": 74673093, "author": "James Grey", "author_id": 3728901, "author_profile": "https://Stackoverflow.com/users/3728901", "pm_score": 0, "selected": false, "text": "import os\nimport argparse\nfrom pathlib import Path\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"path\", help=\"Path of directory/folder\")\n parser.add_argument(\"ext\", help=\"Extension of file what need get size.\")\n args = parser.parse_args()\n foo = Path(args.path)\n files = [x for x in foo.glob(f\"*.{args.ext}\") if x.is_file()]\n for file in files:\n print(file.__str__(), os.path.getsize(file))\n\n\nif __name__ == '__main__':\n main()\n \n# python size.py \"D:\\\" 'jpg'\n\n# (base) PS C:\\Users\\donhu\\PycharmProjects\\pythonProject4> python size.py \"D:\\\" 'jpg'\n# D:\\1496231_10152440570407564_3432420_o.jpg 241439\n# D:\\15002366_278058419262140_505451777021235_o.jpg 598063\n# D:\\1958485_703442046353041_1444502_n.jpg 63839\n# D:\\277522952_5065319530178162_680264454398630_n.jpg 335423\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6727914/" ]
74,672,849
<p>I have two CDK/Cfn stacks which instantiate application load balancers with SSL certificates. I'm using DNS validation which the CDK manages by creating a Lambda function which requests and validates the certificates.</p> <p>Unfortunately, those Lambda functions were manually deleted and now when I try to update my CDK resources, CloudFormation attempts to replace these Lambdas but fails because they no longer exist.</p> <p>I wish that CloudFormation would behave like Terraform and just say &quot;oh that thing I need to replace isn't there, nbd I needed to replace it anyway, so let's carry on&quot; but it does not.</p> <p>Not sure how to get out of this jam. Any help is appreciated.</p>
[ { "answer_id": 74672875, "author": "Alec Cureau", "author_id": 20590353, "author_profile": "https://Stackoverflow.com/users/20590353", "pm_score": 0, "selected": false, "text": "parse_args() Namespace path os.listdir(args1.path)\n" }, { "answer_id": 74673024, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 2, "selected": true, "text": "os listdir stat pathlib pathlib Path import argparse\nfrom pathlib import Path\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"path\", help=\"Đường dẫn của thư mục\")\n parser.add_argument(\"ext\", help=\"Định dạng tập tin cần liệt kê kích thước.\")\n args = parser.parse_args()\n foo = Path(args.path)\n if not foo.is_dir():\n print(\"Error: Must be a directory\")\n exit(1)\n files = [x for x in foo.iterdir() if x.is_file()]\n print(files)\n # os.path.getsize(args.path)\n bytes_size = sum(file.stat().st_size for file in files)\n print(\"total bytes\", bytes_size)\n # mb_size = int(bytes_size / 1024 / 1024)\n # print(mb_size, \"MB\")\n\nif __name__ == '__main__':\n main()\n ext iterdir files = [x for x in foo.glob(f\"*.{args.ext}\") if x.is_file()]\n files = [x for x in foo.glob(f\"**/*.{args.ext}\") if x.is_file()]\n" }, { "answer_id": 74673067, "author": "Dude Eclair", "author_id": 20544495, "author_profile": "https://Stackoverflow.com/users/20544495", "pm_score": -1, "selected": false, "text": "print(type(args1))\n args1.path\nargs1.ext\n arr = os.listdir(args1.path)\n" }, { "answer_id": 74673093, "author": "James Grey", "author_id": 3728901, "author_profile": "https://Stackoverflow.com/users/3728901", "pm_score": 0, "selected": false, "text": "import os\nimport argparse\nfrom pathlib import Path\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"path\", help=\"Path of directory/folder\")\n parser.add_argument(\"ext\", help=\"Extension of file what need get size.\")\n args = parser.parse_args()\n foo = Path(args.path)\n files = [x for x in foo.glob(f\"*.{args.ext}\") if x.is_file()]\n for file in files:\n print(file.__str__(), os.path.getsize(file))\n\n\nif __name__ == '__main__':\n main()\n \n# python size.py \"D:\\\" 'jpg'\n\n# (base) PS C:\\Users\\donhu\\PycharmProjects\\pythonProject4> python size.py \"D:\\\" 'jpg'\n# D:\\1496231_10152440570407564_3432420_o.jpg 241439\n# D:\\15002366_278058419262140_505451777021235_o.jpg 598063\n# D:\\1958485_703442046353041_1444502_n.jpg 63839\n# D:\\277522952_5065319530178162_680264454398630_n.jpg 335423\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1354026/" ]
74,672,877
<p>I have a graph that looks like this</p> <pre><code>A1 A2 A3 A4 A5 \ / \ | / S1 S2 \ / E1 </code></pre> <p>There can be many E nodes. But the essence from the above is: It is a one to many mapping between E and S nodes It is a one to many mapping between S and A nodes The same S1 can also point to another E node, but I want to extract the following relationship:</p> <p>For each E node, get all the S nodes and for each S node we get, get all the A nodes.</p> <p>I know for just E and S, I can do:</p> <pre><code>match (e:E)&lt;--(s:S) return e, collect(distinct s) </code></pre> <p>But I am not sure how to do this with two level of such mapping</p>
[ { "answer_id": 74674085, "author": "Christophe Willemsen", "author_id": 2662355, "author_profile": "https://Stackoverflow.com/users/2662355", "pm_score": 2, "selected": false, "text": "CREATE (e1:E {id: 'e1'})\nCREATE (e2:E {id: 'e2'})\nCREATE (s1:S {id: 's1'})\nCREATE (s2:S {id: 's2'})\nCREATE (a1:A {id: 'a1'})\nCREATE (a2:A {id: 'a2'})\nCREATE (a3:A {id: 'a3'})\nCREATE (a4:A {id: 'a4'})\nCREATE (a5:A {id: 'a5'})\nCREATE (e1)-[:TO]->(s1)\nCREATE (e1)-[:TO]->(s2)\nCREATE (s1)-[:TO]->(a1)\nCREATE (s1)-[:TO]->(a2)\nCREATE (s2)-[:TO]->(a3)\nCREATE (s2)-[:TO]->(a4)\nCREATE (s2)-[:TO]->(a5)\nCREATE (e2)-[:TO]->(s2)\n MATCH path=(e:E)-->(:S)-->(:A)\nRETURN path\n ╒═══════════════════════════════════════════════════════╕\n│\"path\" │\n╞═══════════════════════════════════════════════════════╡\n│[{\"id\":\"e1\"},{},{\"id\":\"s2\"},{\"id\":\"s2\"},{},{\"id\":\"a4\"}]│\n├───────────────────────────────────────────────────────┤\n│[{\"id\":\"e1\"},{},{\"id\":\"s2\"},{\"id\":\"s2\"},{},{\"id\":\"a5\"}]│\n├───────────────────────────────────────────────────────┤\n│[{\"id\":\"e1\"},{},{\"id\":\"s2\"},{\"id\":\"s2\"},{},{\"id\":\"a3\"}]│\n├───────────────────────────────────────────────────────┤\n│[{\"id\":\"e1\"},{},{\"id\":\"s1\"},{\"id\":\"s1\"},{},{\"id\":\"a1\"}]│\n├───────────────────────────────────────────────────────┤\n│[{\"id\":\"e1\"},{},{\"id\":\"s1\"},{\"id\":\"s1\"},{},{\"id\":\"a2\"}]│\n├───────────────────────────────────────────────────────┤\n│[{\"id\":\"e2\"},{},{\"id\":\"s2\"},{\"id\":\"s2\"},{},{\"id\":\"a4\"}]│\n├───────────────────────────────────────────────────────┤\n│[{\"id\":\"e2\"},{},{\"id\":\"s2\"},{\"id\":\"s2\"},{},{\"id\":\"a5\"}]│\n├───────────────────────────────────────────────────────┤\n│[{\"id\":\"e2\"},{},{\"id\":\"s2\"},{\"id\":\"s2\"},{},{\"id\":\"a3\"}]│\n└───────────────────────────────────────────────────────┘\n MATCH path=(e:E)-->(:S)-->(:A)\nRETURN path\nLIMIT 1\n ╒═══════════════════════════════════════════════════════╕\n│\"path\" │\n╞═══════════════════════════════════════════════════════╡\n│[{\"id\":\"e1\"},{},{\"id\":\"s2\"},{\"id\":\"s2\"},{},{\"id\":\"a4\"}]│\n└───────────────────────────────────────────────────────┘\n E MATCH path=(e:E)-->(:S)-->(:A)\nRETURN e, collect(path) AS paths\n ╒═══════════╤══════════════════════════════════════════════════════════════════════╕\n│\"e\" │\"paths\" │\n╞═══════════╪══════════════════════════════════════════════════════════════════════╡\n│{\"id\":\"e1\"}│[[{\"id\":\"e1\"},{},{\"id\":\"s2\"},{\"id\":\"s2\"},{},{\"id\":\"a4\"}],[{\"id\":\"e1\"},│\n│ │{},{\"id\":\"s2\"},{\"id\":\"s2\"},{},{\"id\":\"a5\"}],[{\"id\":\"e1\"},{},{\"id\":\"s2\"}│\n│ │,{\"id\":\"s2\"},{},{\"id\":\"a3\"}],[{\"id\":\"e1\"},{},{\"id\":\"s1\"},{\"id\":\"s1\"},{│\n│ │},{\"id\":\"a1\"}],[{\"id\":\"e1\"},{},{\"id\":\"s1\"},{\"id\":\"s1\"},{},{\"id\":\"a2\"}]│\n│ │] │\n├───────────┼──────────────────────────────────────────────────────────────────────┤\n│{\"id\":\"e2\"}│[[{\"id\":\"e2\"},{},{\"id\":\"s2\"},{\"id\":\"s2\"},{},{\"id\":\"a4\"}],[{\"id\":\"e2\"},│\n│ │{},{\"id\":\"s2\"},{\"id\":\"s2\"},{},{\"id\":\"a5\"}],[{\"id\":\"e2\"},{},{\"id\":\"s2\"}│\n│ │,{\"id\":\"s2\"},{},{\"id\":\"a3\"}]] │\n└───────────┴──────────────────────────────────────────────────────────────────────┘\n nodes() MATCH path=(e:E)-->(:S)-->(:A)\nRETURN nodes(path)\n ╒═════════════════════════════════════╕\n│\"nodes(path)\" │\n╞═════════════════════════════════════╡\n│[{\"id\":\"e1\"},{\"id\":\"s2\"},{\"id\":\"a4\"}]│\n├─────────────────────────────────────┤\n│[{\"id\":\"e1\"},{\"id\":\"s2\"},{\"id\":\"a5\"}]│\n├─────────────────────────────────────┤\n│[{\"id\":\"e1\"},{\"id\":\"s2\"},{\"id\":\"a3\"}]│\n├─────────────────────────────────────┤\n│[{\"id\":\"e1\"},{\"id\":\"s1\"},{\"id\":\"a1\"}]│\n├─────────────────────────────────────┤\n│[{\"id\":\"e1\"},{\"id\":\"s1\"},{\"id\":\"a2\"}]│\n├─────────────────────────────────────┤\n│[{\"id\":\"e2\"},{\"id\":\"s2\"},{\"id\":\"a4\"}]│\n├─────────────────────────────────────┤\n│[{\"id\":\"e2\"},{\"id\":\"s2\"},{\"id\":\"a5\"}]│\n├─────────────────────────────────────┤\n│[{\"id\":\"e2\"},{\"id\":\"s2\"},{\"id\":\"a3\"}]│\n└─────────────────────────────────────┘\n MATCH (e:E)\nRETURN \ne {.*, s: [(e)-->(s:S) | s{.*, a: [(s)-->(a:A) | a{.*}]}]}\n ╒══════════════════════════════════════════════════════════════════════╕\n│\"e\" │\n╞══════════════════════════════════════════════════════════════════════╡\n│{\"s\":[{\"a\":[{\"id\":\"a4\"},{\"id\":\"a5\"},{\"id\":\"a3\"}],\"id\":\"s2\"},{\"a\":[{\"id│\n│\":\"a1\"},{\"id\":\"a2\"}],\"id\":\"s1\"}],\"id\":\"e1\"} │\n├──────────────────────────────────────────────────────────────────────┤\n│{\"s\":[{\"a\":[{\"id\":\"a4\"},{\"id\":\"a5\"},{\"id\":\"a3\"}],\"id\":\"s2\"}],\"id\":\"e2\"│\n│} │\n└──────────────────────────────────────────────────────────────────────┘\n {\n \"s\": [\n {\n \"a\": [\n {\n \"id\": \"a4\"\n },\n {\n \"id\": \"a5\"\n },\n {\n \"id\": \"a3\"\n }\n ],\n \"id\": \"s2\"\n },\n {\n \"a\": [\n {\n \"id\": \"a1\"\n },\n {\n \"id\": \"a2\"\n }\n ],\n \"id\": \"s1\"\n }\n ],\n \"id\": \"e1\"\n}\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/734748/" ]
74,672,920
<p>I'm trying to make a list of employees working in a same department like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>employeeName</th> <th>department</th> <th>employeeName</th> </tr> </thead> <tbody> <tr> <td>Tim</td> <td>2</td> <td>kim</td> </tr> <tr> <td>Tim</td> <td>2</td> <td>Jim</td> </tr> <tr> <td>Kim</td> <td>2</td> <td>Tim</td> </tr> <tr> <td>Kim</td> <td>2</td> <td>Jim</td> </tr> <tr> <td>Jim</td> <td>2</td> <td>Kim</td> </tr> <tr> <td>Jim</td> <td>2</td> <td>Tim</td> </tr> <tr> <td>Aim</td> <td>3</td> <td>Sim</td> </tr> <tr> <td>Sim</td> <td>3</td> <td>Aim</td> </tr> </tbody> </table> </div> <p>But the only thing i can do for now is:</p> <pre><code>SELECT emp_name, dept_code FROM employee WHERE dept_code IN (SELECT dept_code FROM employee); </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>employeeName</th> <th>department</th> </tr> </thead> <tbody> <tr> <td>Tim</td> <td>2</td> </tr> <tr> <td>Kim</td> <td>2</td> </tr> <tr> <td>Jim</td> <td>2</td> </tr> <tr> <td>Aim</td> <td>3</td> </tr> <tr> <td>Sim</td> <td>3</td> </tr> </tbody> </table> </div> <p>How can I make a list pairing with the employee working in a same department? thanks gurus...</p>
[ { "answer_id": 74673367, "author": "Jonas Metzler", "author_id": 18794826, "author_profile": "https://Stackoverflow.com/users/18794826", "pm_score": 2, "selected": false, "text": "CROSS JOIN WHERE SELECT \ne1.emp_name AS employeeName, \ne1.dept_code AS department, \ne2.emp_name AS employeeName\nFROM \nemployee e1\nCROSS JOIN employee e2\nWHERE \ne1.dept_code = e2.dept_code\nAND e1.emp_name <> e2.emp_name\nORDER BY e1.dept_code, e1.emp_name, e2.emp_name;\n LISTAGG GROUP BY SELECT dept_code, \nLISTAGG (emp_name,',') AS employees\nFROM employee\nGROUP BY dept_code;\n WITHIN GROUP SELECT dept_code, \nLISTAGG (emp_name,',') \n WITHIN GROUP (ORDER BY emp_name) AS employees\nFROM employee\nGROUP BY dept_code;\n" }, { "answer_id": 74674444, "author": "p3consulting", "author_id": 4956336, "author_profile": "https://Stackoverflow.com/users/4956336", "pm_score": 0, "selected": false, "text": "SELECT e1.emp_name AS first_emp_name, e1.dept_code, e2.emp_name AS second_emp_name\n FROM employee e1\nJOIN employee e2 ON e1.dept_code = e2.dept_code AND e1.emp_name <> e2.emp_name ;\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20387081/" ]
74,672,925
<p>I have a test.fasta file with the following data:</p> <pre><code>&gt;PPP.0124.1.PC lib=RU01 length=410 description=Protein description goes here 1 serine/threonine MLEAPKFTGIIGLNNNHDNYDLSQGFYHKLGEGSNMSIDSFGSLQLSNGG GSVAMSVSSVGSNDSHTRILNHQGLKRVNGNYSVARSVNRGKVSHGLSDD ALAQ &gt;PPP.14552.PC lib=RU01 length=104 description=Protein description goes here 2 uncharacterized protein LOC11441 MKSVVGMVVSNKMQKSVVVAVDRLFHHKLYDRYVKRTSKFMAHDEHNLCN IGDRVRL &gt;PPP.94014.PC lib=RU01 length=206 description=Protein description goes here 3 some more chemicals and stuff MDLGPTLTLQKGRQRRGKGPYAGVRSRGGRWVSEIRIPKTKTRIWLGSHH SPEKAARAYDAALYCLKGEHGSFNFPNNRGPYLANRSVGSLPVDEIQCIA AEFSCFDDSA </code></pre> <p>I would like to take the ID and the description and output them into a <code>.tsv</code> file, with the first column being the ID and the second column holding the description.</p> <p>Desired output:</p> <pre class="lang-none prettyprint-override"><code>| ID | Description | | -------- | -------------- | | 0124 | Protein description goes here 1 serine/threonine | | 14552 | Protein description goes here 2 uncharacterized protein LOC11441 | | 94014 | Protein description goes here 3 some more chemicals and stuff | </code></pre> <p>Any ideas on a one-line Bash command to achieve this?</p> <p>I currently have this:</p> <pre><code>grep -a '^&gt;' test.fasta | awk '{print $1} </code></pre> <p>which gives me the first lines and the ID's but cant seem to figure out the rest!</p>
[ { "answer_id": 74673367, "author": "Jonas Metzler", "author_id": 18794826, "author_profile": "https://Stackoverflow.com/users/18794826", "pm_score": 2, "selected": false, "text": "CROSS JOIN WHERE SELECT \ne1.emp_name AS employeeName, \ne1.dept_code AS department, \ne2.emp_name AS employeeName\nFROM \nemployee e1\nCROSS JOIN employee e2\nWHERE \ne1.dept_code = e2.dept_code\nAND e1.emp_name <> e2.emp_name\nORDER BY e1.dept_code, e1.emp_name, e2.emp_name;\n LISTAGG GROUP BY SELECT dept_code, \nLISTAGG (emp_name,',') AS employees\nFROM employee\nGROUP BY dept_code;\n WITHIN GROUP SELECT dept_code, \nLISTAGG (emp_name,',') \n WITHIN GROUP (ORDER BY emp_name) AS employees\nFROM employee\nGROUP BY dept_code;\n" }, { "answer_id": 74674444, "author": "p3consulting", "author_id": 4956336, "author_profile": "https://Stackoverflow.com/users/4956336", "pm_score": 0, "selected": false, "text": "SELECT e1.emp_name AS first_emp_name, e1.dept_code, e2.emp_name AS second_emp_name\n FROM employee e1\nJOIN employee e2 ON e1.dept_code = e2.dept_code AND e1.emp_name <> e2.emp_name ;\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19590799/" ]
74,672,964
<pre><code>{ &quot;requireCurlyBraces&quot;: [ &quot;if&quot;, &quot;else&quot;, &quot;for&quot;, &quot;while&quot;, &quot;do&quot; ], &quot;requireSpaceAfterKeywords&quot;: [ &quot;if&quot;, &quot;else&quot;, &quot;for&quot;, &quot;while&quot;, &quot;do&quot;, &quot;switch&quot;, &quot;return&quot; ], &quot;disallowKeywords&quot;: [ &quot;with&quot; ], &quot;disallowKeywordsOnNewLine&quot;: [ &quot;else&quot; ], &quot;requireSpacesInFunctionExpression&quot;: { &quot;beforeOpeningCurlyBrace&quot;: true }, &quot;disallowSpacesInFunctionExpression&quot;: { &quot;beforeOpeningRoundBrace&quot;: true }, &quot;disallowSpaceAfterObjectKeys&quot;: true, &quot;requireMultipleVarDecl&quot;: &quot;onevar&quot;, &quot;disallowMixedSpacesAndTabs&quot;: &quot;smart&quot;, &quot;disallowTrailingWhitespace&quot;: true, &quot;requireSpacesInsideObjectBrackets&quot;: &quot;all&quot;, &quot;requireSpacesInsideArrayBrackets&quot;: &quot;all&quot;, &quot;requireSpacesInConditionalExpression&quot;: true, &quot;requireSpaceBeforeBinaryOperators&quot;: [ &quot;=&quot;, &quot;+=&quot;, &quot;-=&quot;, &quot;*=&quot;, &quot;/=&quot;, &quot;%=&quot;, &quot;&lt;&lt;=&quot;, &quot;&gt;&gt;=&quot;, &quot;&gt;&gt;&gt;=&quot;, &quot;&amp;=&quot;, &quot;|=&quot;, &quot;^=&quot;, &quot;+=&quot;, &quot;+&quot;, &quot;-&quot;, &quot;*&quot;, &quot;/&quot;, &quot;%&quot;, &quot;&lt;&lt;&quot;, &quot;&gt;&gt;&quot;, &quot;&gt;&gt;&gt;&quot;, &quot;&amp;&quot;, &quot;|&quot;, &quot;^&quot;, &quot;&amp;&amp;&quot;, &quot;||&quot;, &quot;===&quot;, &quot;==&quot;, &quot;&gt;=&quot;, &quot;&lt;=&quot;, &quot;&lt;&quot;, &quot;&gt;&quot;, &quot;!=&quot;, &quot;!==&quot; ], &quot;requireSpaceAfterBinaryOperators&quot;: [ &quot;=&quot;, &quot;+=&quot;, &quot;-=&quot;, &quot;*=&quot;, &quot;/=&quot;, &quot;%=&quot;, &quot;&lt;&lt;=&quot;, &quot;&gt;&gt;=&quot;, &quot;&gt;&gt;&gt;=&quot;, &quot;&amp;=&quot;, &quot;|=&quot;, &quot;^=&quot;, &quot;+=&quot;, &quot;+&quot;, &quot;-&quot;, &quot;*&quot;, &quot;/&quot;, &quot;%&quot;, &quot;&lt;&lt;&quot;, &quot;&gt;&gt;&quot;, &quot;&gt;&gt;&gt;&quot;, &quot;&amp;&quot;, &quot;|&quot;, &quot;^&quot;, &quot;&amp;&amp;&quot;, &quot;||&quot;, &quot;===&quot;, &quot;==&quot;, &quot;&gt;=&quot;, &quot;&lt;=&quot;, &quot;&lt;&quot;, &quot;&gt;&quot;, &quot;!=&quot;, &quot;!==&quot; ], &quot;disallowSpaceAfterPrefixUnaryOperators&quot;: [ &quot;++&quot;, &quot;--&quot; ], &quot;disallowSpaceBeforePostfixUnaryOperators&quot;: [ &quot;++&quot;, &quot;--&quot; ], &quot;disallowSpaceBeforeBinaryOperators&quot;: [ &quot;,&quot;, &quot;:&quot; ], &quot;disallowMultipleLineBreaks&quot;: true, &quot;requireLineFeedAtFileEnd&quot;: true, &quot;validateLineBreaks&quot;: &quot;LF&quot; } </code></pre> <p>found this file in owl carousel want to understand importance of this file</p>
[ { "answer_id": 74673367, "author": "Jonas Metzler", "author_id": 18794826, "author_profile": "https://Stackoverflow.com/users/18794826", "pm_score": 2, "selected": false, "text": "CROSS JOIN WHERE SELECT \ne1.emp_name AS employeeName, \ne1.dept_code AS department, \ne2.emp_name AS employeeName\nFROM \nemployee e1\nCROSS JOIN employee e2\nWHERE \ne1.dept_code = e2.dept_code\nAND e1.emp_name <> e2.emp_name\nORDER BY e1.dept_code, e1.emp_name, e2.emp_name;\n LISTAGG GROUP BY SELECT dept_code, \nLISTAGG (emp_name,',') AS employees\nFROM employee\nGROUP BY dept_code;\n WITHIN GROUP SELECT dept_code, \nLISTAGG (emp_name,',') \n WITHIN GROUP (ORDER BY emp_name) AS employees\nFROM employee\nGROUP BY dept_code;\n" }, { "answer_id": 74674444, "author": "p3consulting", "author_id": 4956336, "author_profile": "https://Stackoverflow.com/users/4956336", "pm_score": 0, "selected": false, "text": "SELECT e1.emp_name AS first_emp_name, e1.dept_code, e2.emp_name AS second_emp_name\n FROM employee e1\nJOIN employee e2 ON e1.dept_code = e2.dept_code AND e1.emp_name <> e2.emp_name ;\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20678949/" ]
74,672,989
<p>My Product Schema Look like this.</p> <pre><code>import mongoose from 'mongoose'; const productSchema = new mongoose.Schema( { name: { type: String, required: true }, game: { type: mongoose.Schema.Types.ObjectId, ref: 'Game', required: true, }, category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category', required: true, }, slug: { type: String, required: true, unique: true }, image: { type: String, required: true }, price: { type: Number, required: true }, nominal: { type: Number, required: true }, description: { type: String, required: true }, }, { timestamps: true, } ); const Product = mongoose.models.Product || mongoose.model('Product', productSchema); export default Product; </code></pre> <p>My schema game</p> <pre><code>import mongoose from 'mongoose'; const gameSchema = new mongoose.Schema( { name: { type: String, require: [true, 'Type cant be empty'], }, status: { type: String, enum: ['Y', 'N'], default: 'Y', }, thumbnail: { type: String, require: [true, 'Type cant be empty'], }, }, { timestamps: true } ); const Game = mongoose.models.Game || mongoose.model('Game', gameSchema); export default Game; </code></pre> <p>I want to find a product by the game status is 'Y'</p> <p>I try to do like this</p> <pre><code>const getHandler = async (req: NextApiRequest, res: NextApiResponse) =&gt; { await db.connect(); const options = { status: { $regex: 'Y', $options: 'i' } }; const products = await Product.find({}).populate({ path: 'game', select: 'status', match: options, }); res.send(products); await db.disconnect(); }; </code></pre> <p>but is not work is not filtering. the output is still the same but for the products with a game status is 'N' it shows null</p> <p>I heard that we could use aggregation with $lookup but I still don't know how to that</p>
[ { "answer_id": 74673014, "author": "Saurabh Mistry", "author_id": 6943762, "author_profile": "https://Stackoverflow.com/users/6943762", "pm_score": 0, "selected": false, "text": " const products = await Product.find({}).populate({\n path: 'game',\n model:'Game',\n match: {'status':'Y'}\n select: 'status'\n });\n" }, { "answer_id": 74674670, "author": "Dhaval Italiya", "author_id": 12600501, "author_profile": "https://Stackoverflow.com/users/12600501", "pm_score": 1, "selected": false, "text": "let data = await Product.aggregate([\n{\n $lookup: {\n from: \"Game\", //Your schema name\n localField: \"game\", //field name of product which contains game id\n foreignField: \"_id\", // _id of game\n pipeline: [\n {\n $match: {\n status: \"Y\",\n },\n },\n ],\n as: \"game\", //name of result\n },\n },\n { $unwind: \"$game\" },// this will make your array to object and also it will remove all null entry.\n]);\nconsole.log(data);\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74672989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19969053/" ]
74,673,028
<p>I'm making a Tetris game now. I want to implement it so that if I press the down key , the block falls quickly, and if I press the left and right keys, the block moves quickly. Pressing the key used the pygame.key.get_pressed() function and used pygame.time.set_timer() function to make speed change. The game speed was set to 600 for the interval of pygame.time.set_timer(), but if I press the down key, the block drops quickly because the interval was set to 150 to speed up the game so that the block drops quickly. The problem is to implement the function on the left and right direction keys. It is also possible to move the left and right keys quickly if I change the interval. The problem is that the pygame.time.set_timer() function changes the speed of the entire game, so the block falls quickly as well as the left and right movements of the block. Is there a way to speed up left and right movements without touching the speed of other things? I'd appreciate it if you let me know, thanks!</p> <p><em><strong>code</strong></em></p> <pre><code> elif start: for event in pygame.event.get(): attack_stack = 0 pos = pygame.mouse.get_pos() if event.type == QUIT: done = True elif event.type == USEREVENT: # Set speed if not game_over: keys_pressed = pygame.key.get_pressed() # Soft drop if keys_pressed[K_DOWN]: pygame.time.set_timer(pygame.USEREVENT, 100) elif keys_pressed[K_RIGHT]: pygame.time.set_timer(pygame.USEREVENT, 100) if not is_rightedge1(dx, dy, mino_en, rotation, matrix): ui_variables.move_sound.play() dx += 1 elif keys_pressed[K_LEFT]: pygame.time.set_timer(pygame.USEREVENT, 100) if not is_leftedge1(dx, dy, mino_en, rotation, matrix): ui_variables.move_sound.play() dx -= 1 else: pygame.time.set_timer(pygame.USEREVENT, 600) </code></pre>
[ { "answer_id": 74673014, "author": "Saurabh Mistry", "author_id": 6943762, "author_profile": "https://Stackoverflow.com/users/6943762", "pm_score": 0, "selected": false, "text": " const products = await Product.find({}).populate({\n path: 'game',\n model:'Game',\n match: {'status':'Y'}\n select: 'status'\n });\n" }, { "answer_id": 74674670, "author": "Dhaval Italiya", "author_id": 12600501, "author_profile": "https://Stackoverflow.com/users/12600501", "pm_score": 1, "selected": false, "text": "let data = await Product.aggregate([\n{\n $lookup: {\n from: \"Game\", //Your schema name\n localField: \"game\", //field name of product which contains game id\n foreignField: \"_id\", // _id of game\n pipeline: [\n {\n $match: {\n status: \"Y\",\n },\n },\n ],\n as: \"game\", //name of result\n },\n },\n { $unwind: \"$game\" },// this will make your array to object and also it will remove all null entry.\n]);\nconsole.log(data);\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20108310/" ]
74,673,076
<p>I was in <code>class</code> section of python programming and I am confused here.</p> <p>I have learned that <code>super</code> is used to call the method of <code>parent</code> class but here <code>Employee</code> is not a parent of <code>Programmer</code> yet it's called (showing the result of <code>getLanguage</code> method).</p> <p>What I am missing?</p> <p>This is the code.</p> <pre><code>class Employee: company= &quot;Google&quot; language = &quot;java&quot; def showDetails(self): print(&quot;This is an employee&quot;); def getLanguage(self): print(f&quot;1. The language is {self.language}&quot;); class Programmer: language= &quot;Python&quot; company = &quot;Youtubeeee&quot; def getLanguage(self): super().getLanguage(); print(f&quot;2. The language is {self.language}&quot;) def showDetails(self): print(&quot;This is an programmer&quot;) class Programmer2(Programmer , Employee): language= &quot;C++&quot; def getLanguage(self): super().getLanguage(); print(f&quot;3. The language is {self.language}&quot;) p2 = Programmer2(); p2.getLanguage(); </code></pre> <p>This is the output,</p> <pre><code>1. The language is C++ 2. The language is C++ 3. The language is C++ </code></pre>
[ { "answer_id": 74673125, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 3, "selected": true, "text": "super Programmer Programmer2 Programmer p3 = Programmer()\np3.getLanguage()\n AttributeError: 'super' object has no attribute 'getLanguage' object __mro__ Programmer.__mro__:\n (<class '__main__.Programmer'>, <class 'object'>)\n\nProgrammer2.__mro__:\n (<class '__main__.Programmer2'>, <class '__main__.Programmer'>, \n <class '__main__.Employee'>, <class 'object'>)\n" }, { "answer_id": 74673431, "author": "bb1", "author_id": 15187728, "author_profile": "https://Stackoverflow.com/users/15187728", "pm_score": 1, "selected": false, "text": "super() super(C, obj) C obj obj C super() super p2.getLanguage() Programmer2 super().getLanguage() super(Programmer2, p2).getLanguage() p2 Programmer2 Programmer Employee object getLanguage Programmer2 Programmer getLanguage Programmer super().getLanguage() super(Programmer, p2).getLanguage() super Programmer p2 Programmer2 Programmer Employee object getLanguage Programmer Employee Programmer Employee super().getLanguage() Programmer Employee" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19757319/" ]
74,673,110
<p>trying to iterate through an array list with a for loop and initialized a variable p in the loop. when using the variable as an index to get from the arraylist it is giving me a p cannot be resolved to a variable.</p> <pre><code>for (int p = 0; p &lt; this.playerList.size(); p++); Player tempPlayer = this.playerList.get(p); StandardCard[] tempHoleCards = {gameDeck.getNextCard(), gameDeck.getNextCard()}; tempPlayer.setHoleCards(tempHoleCards); </code></pre> <p>The variable p is already initialized in the loop but cannot be found when using it for the get method for the array list</p>
[ { "answer_id": 74673125, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 3, "selected": true, "text": "super Programmer Programmer2 Programmer p3 = Programmer()\np3.getLanguage()\n AttributeError: 'super' object has no attribute 'getLanguage' object __mro__ Programmer.__mro__:\n (<class '__main__.Programmer'>, <class 'object'>)\n\nProgrammer2.__mro__:\n (<class '__main__.Programmer2'>, <class '__main__.Programmer'>, \n <class '__main__.Employee'>, <class 'object'>)\n" }, { "answer_id": 74673431, "author": "bb1", "author_id": 15187728, "author_profile": "https://Stackoverflow.com/users/15187728", "pm_score": 1, "selected": false, "text": "super() super(C, obj) C obj obj C super() super p2.getLanguage() Programmer2 super().getLanguage() super(Programmer2, p2).getLanguage() p2 Programmer2 Programmer Employee object getLanguage Programmer2 Programmer getLanguage Programmer super().getLanguage() super(Programmer, p2).getLanguage() super Programmer p2 Programmer2 Programmer Employee object getLanguage Programmer Employee Programmer Employee super().getLanguage() Programmer Employee" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20679145/" ]
74,673,119
<p>I m getting typescript error when I tried to upgraded React-router-dom v5 to v6, How can I fix this typescript error. below you can find the code Thanks in advance</p> <p>`</p> <pre><code>export function withRouter(ui: React.ReactElement) { const history = useNavigate(); const routerValues: any = { history: undefined, location: undefined }; const result = ( &lt;MemoryRouter&gt; {ui} &lt;Route path=&quot;*&quot; element={({ history, location }) =&gt; { routerValues.history = history; routerValues.location = location; return null; }} /&gt; &lt;/MemoryRouter&gt; </code></pre> <p><a href="https://i.stack.imgur.com/cDYgi.png" rel="nofollow noreferrer">enter image description here</a>`</p> <p>below you can find entire file code `</p> <pre><code>import React from &quot;react&quot;; import { Reducer } from &quot;@reduxjs/toolkit&quot;; import { Provider } from &quot;react-redux&quot;; import { MemoryRouter, Route, useNavigate } from &quot;react-router-dom&quot;; import buildStore from &quot;../redux/store&quot;; export function withRedux( ui: React.ReactElement, reducer: { [key: string]: Reducer; }, initialState: any ) { const store = buildStore(initialState, true); const dispatchSpy = jest.spyOn(store, &quot;dispatch&quot;); return { result: &lt;Provider store={store}&gt;{ui}&lt;/Provider&gt;, store, dispatchSpy }; } export function withRouter(ui: React.ReactElement) { const history = useNavigate(); const routerValues: any = { history: undefined, location: undefined }; const result = ( &lt;MemoryRouter&gt; {ui} &lt;Route path=&quot;*&quot; element={({ history, location }) =&gt; { routerValues.history = history; routerValues.location = location; return null; }} /&gt; &lt;/MemoryRouter&gt; ); return { result, routerValues }; } </code></pre> <p>`</p> <p>I am passing history and location props which were work fine when I was using react router v5 here is the previous code : `</p> <pre><code>const result = ( &lt;MemoryRouter&gt; {ui} &lt;Route path=&quot;*&quot; render={({ history, location }) =&gt; { routerValues.history = history; routerValues.location = location; return null; }} /&gt; &lt;/MemoryRouter&gt; </code></pre> <p>`</p> <p>After update react router v6 I changed in my code because We know that v6 no longer support render keyword inside route So I Replace it</p> <p>`</p> <pre><code>const result = ( &lt;MemoryRouter&gt; {ui} &lt;Route path=&quot;*&quot; element={({ history, location }) =&gt; { routerValues.history = history; routerValues.location = location; return null; }} /&gt; &lt;/MemoryRouter&gt; ); </code></pre> <p>`</p> <p>But I don't have Idea in v6 How can I pass these props inside route</p>
[ { "answer_id": 74673125, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 3, "selected": true, "text": "super Programmer Programmer2 Programmer p3 = Programmer()\np3.getLanguage()\n AttributeError: 'super' object has no attribute 'getLanguage' object __mro__ Programmer.__mro__:\n (<class '__main__.Programmer'>, <class 'object'>)\n\nProgrammer2.__mro__:\n (<class '__main__.Programmer2'>, <class '__main__.Programmer'>, \n <class '__main__.Employee'>, <class 'object'>)\n" }, { "answer_id": 74673431, "author": "bb1", "author_id": 15187728, "author_profile": "https://Stackoverflow.com/users/15187728", "pm_score": 1, "selected": false, "text": "super() super(C, obj) C obj obj C super() super p2.getLanguage() Programmer2 super().getLanguage() super(Programmer2, p2).getLanguage() p2 Programmer2 Programmer Employee object getLanguage Programmer2 Programmer getLanguage Programmer super().getLanguage() super(Programmer, p2).getLanguage() super Programmer p2 Programmer2 Programmer Employee object getLanguage Programmer Employee Programmer Employee super().getLanguage() Programmer Employee" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17257477/" ]
74,673,132
<p>I have a users table and a column supervised_by where I want the id of the user who created the new user. For example: get the id of the admin in supervised_by column of the user the admin creates. <a href="https://i.stack.imgur.com/cR9YB.png" rel="nofollow noreferrer">users table</a></p> <p>//migration file</p> <pre><code> public function up() { Schema::create('users', function (Blueprint $table) { $table-&gt;id(); $table-&gt;string('name'); $table-&gt;string('email')-&gt;unique(); $table-&gt;timestamp('email_verified_at')-&gt;nullable(); $table-&gt;boolean('verified')-&gt;default(false); $table-&gt;timestamp('verified_at')-&gt;nullable(); $table-&gt;string('password'); $table-&gt;string('is_verified'); $table-&gt;boolean('active')-&gt;nullable(); $table-&gt;integer('supervised_by')-&gt;references('id')-&gt;on('users'); $table-&gt;rememberToken(); $table-&gt;timestamps(); $table-&gt;softDeletes(); }); } </code></pre> <p>usercontroller</p> <pre><code> public function register(Request $request) { $validator = Validator::make($request-&gt;all(), [ 'name' =&gt; 'required|max:180', 'email' =&gt; 'required|email|unique:users', 'password' =&gt; 'required|max:15|min:8', // 'role' =&gt; 'required' ]); if ($validator-&gt;fails()) { return response()-&gt;json([ 'validation_errors' =&gt; $validator-&gt;messages(), ]); } else { $user = User::create([ 'name' =&gt; $request-&gt;name, 'email' =&gt; $request-&gt;email, 'password' =&gt; $request-&gt;password, 'verified' =&gt; false, 'role' =&gt; $request-&gt;role ]); return response()-&gt;json([ 'status' =&gt; 200, 'code' =&gt; 'register', 'message' =&gt; 'Registered successfully! You\'ll be able to log in once you are approved.', 'data' =&gt; null, 'error' =&gt; null, ]); } } </code></pre>
[ { "answer_id": 74673155, "author": "Vicky Maharjan", "author_id": 9135930, "author_profile": "https://Stackoverflow.com/users/9135930", "pm_score": 0, "selected": false, "text": "$admin_id = Auth::user()->id;\n $admin_id = Auth::id();\n use Illuminate\\Support\\Facades\\Auth;\n" }, { "answer_id": 74673160, "author": "Andre Haykal", "author_id": 13967584, "author_profile": "https://Stackoverflow.com/users/13967584", "pm_score": 1, "selected": false, "text": "$user = User::create([\n 'name' => $request->name,\n 'email' => $request->email,\n 'password' => $request->password,\n 'verified' => false,\n 'role' => $request->role,\n 'supervised_by' => auth()->user()->id,\n ]);\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11386553/" ]
74,673,156
<p>So I could print out the odd numbers. However, the output isn't what i want. It should look like 1+3+5+7 = 16 but I could not make it into a single line.</p> <p>I couldn't figure out how to extract the values from the while loop as with my method it only gives the latest odd number which is 7 while 1,3 and 5 could not be taken out</p> <pre><code>num = int(input(&quot;Insert a postive integer:&quot;)) #4 oddNum = 1 total = 0 count = 1 while count &lt;= num: odd = (str(oddNum)) print (odd) total = total + oddNum oddNum = oddNum + 2 count += 1 print (odd + &quot;=&quot; + str(total)) #output will be: ''' 1 3 5 7 7=16 but it should look like 1+3+5+7=16 ''' </code></pre>
[ { "answer_id": 74673209, "author": "Soumendra", "author_id": 5014656, "author_profile": "https://Stackoverflow.com/users/5014656", "pm_score": 0, "selected": false, "text": "oddNum odd num = int(input(\"Insert a positive integer:\"))\noddNum = 1\ntotal = 0\ncount = 1\nodd = \"\"\nwhile count <= num:\n total = total + oddNum\n odd += f\"{oddNum}\"\n oddNum = oddNum + 2\n count += 1\nodd = \"+\".join(odd)\nprint(odd + \"=\" + str(total))\n" }, { "answer_id": 74673240, "author": "phoenixinwater", "author_id": 5786997, "author_profile": "https://Stackoverflow.com/users/5786997", "pm_score": 0, "selected": false, "text": "print(oddNum, end='') num = int(input(\"Insert a postive integer:\")) #4\noddNum = 1\ntotal = 0\ncount = 1\nsequence = ''\nwhile count <= num:\n sequence += (\"+\" if sequence != \"\" else \"\") + str(oddNum)\n total = total + oddNum\n oddNum = oddNum + 2\n count += 1\n\nprint (sequence + \"=\" + str(total))\n num = int(input(\"Insert a postive integer:\")) #4\noddNum = 1\ntotal = 0\ncount = 1\nwhile count <= num:\n if count != 1:\n print('+', end='')\n print (oddNum, end='')\n total = total + oddNum\n oddNum = oddNum + 2\n count += 1\n\nprint (\"=\" + str(total)) \n" }, { "answer_id": 74673315, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 1, "selected": false, "text": "range() .join() f-strings total = sum(odd_nums) num = int(input(\"Insert a postive integer:\")) #4\nodd_nums = range(1, num * 2, 2)\nsum_nums = \"+\".join(map(str, odd_nums))\nprint(f\"{sum_nums}={sum(odd_nums)}\")\n 1+3+5+7=16\n num = int(input(\"Insert a postive integer:\")) #4\n \nprint(f\"{'+'.join(map(str, range(1, num * 2, 2)))}={sum(range(1, num * 2, 2))}\")\n 1+3+5+7=16\n" }, { "answer_id": 74673521, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 0, "selected": false, "text": "(:=) range print sep end print(*(odd:=[*range(1,int(input('Insert a postive integer:'))*2,2)]),sep='+',end='=');print(sum(odd))\n\n# Insert a postive integer:4\n# 1+3+5+7=16\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20679149/" ]
74,673,168
<p>I've built a simple interface for selecting items from a menu, contained in a component called <code>Sodas</code>, and it's displayed in the Parent component: <code>VendingMachine</code>.</p> <p>As it is, <code>Sodas</code> is able to successfully change the state in the <code>VendingMachine</code>, however, the state cannot be changed within the <code>VendingMachine</code> itself.</p> <p>The following code represents the <code>VendingMachine</code> component:</p> <pre><code>import Sodas from './Sodas'; const VendingMachine = () =&gt; { // Track selected soda const [selectedSoda, setSoda] = useState({ sodaName: '', stock: 0 }); const handleSodaSelection = (soda) =&gt; setSoda(soda); // Reset the selected soda const sellSoda = () =&gt; setSoda({ sodaName: '', stock: 0 }); return ( &lt;div&gt; Soda to Purchase: {selectedSoda.sodaName} &lt;Sodas handleSodaSelection={handleSodaSelection} /&gt; &lt;div onClick={sellSoda}&gt;Buy Selected Soda&lt;/div&gt; &lt;/div } </code></pre> <p>The following code represents the <code>Sodas</code> Component</p> <pre><code>function Sodas({ handleSodaSelection }) { // Tracks soda selected, and returns to Parent component const [sodaSelected, setSodaSelected] = useState({ sodaName: '', stock: 0 }); React.useEffect(() =&gt; handleSodaSelection(sodaSelected), [sodaSelected, handleSodaSelection]); return ( &lt;div className='soda_container'&gt; &lt;div onClick={() =&gt; setSodaSelected({ sodaName: 'Cola', stock: 7 })}&gt;Soda&lt;/div&gt; &lt;/div&gt;) } </code></pre> <p>Specifically, the issue is that <code>setSoda</code> does not work within <code>VendingMachine</code> and only works when passed to the <code>Sodas</code> component. I'm not sure if this can only work as a one way relationship or if there is something I'm missing in the syntax.</p> <p>Any help or references to relevant documentation would be greatly appreciated.</p>
[ { "answer_id": 74673209, "author": "Soumendra", "author_id": 5014656, "author_profile": "https://Stackoverflow.com/users/5014656", "pm_score": 0, "selected": false, "text": "oddNum odd num = int(input(\"Insert a positive integer:\"))\noddNum = 1\ntotal = 0\ncount = 1\nodd = \"\"\nwhile count <= num:\n total = total + oddNum\n odd += f\"{oddNum}\"\n oddNum = oddNum + 2\n count += 1\nodd = \"+\".join(odd)\nprint(odd + \"=\" + str(total))\n" }, { "answer_id": 74673240, "author": "phoenixinwater", "author_id": 5786997, "author_profile": "https://Stackoverflow.com/users/5786997", "pm_score": 0, "selected": false, "text": "print(oddNum, end='') num = int(input(\"Insert a postive integer:\")) #4\noddNum = 1\ntotal = 0\ncount = 1\nsequence = ''\nwhile count <= num:\n sequence += (\"+\" if sequence != \"\" else \"\") + str(oddNum)\n total = total + oddNum\n oddNum = oddNum + 2\n count += 1\n\nprint (sequence + \"=\" + str(total))\n num = int(input(\"Insert a postive integer:\")) #4\noddNum = 1\ntotal = 0\ncount = 1\nwhile count <= num:\n if count != 1:\n print('+', end='')\n print (oddNum, end='')\n total = total + oddNum\n oddNum = oddNum + 2\n count += 1\n\nprint (\"=\" + str(total)) \n" }, { "answer_id": 74673315, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 1, "selected": false, "text": "range() .join() f-strings total = sum(odd_nums) num = int(input(\"Insert a postive integer:\")) #4\nodd_nums = range(1, num * 2, 2)\nsum_nums = \"+\".join(map(str, odd_nums))\nprint(f\"{sum_nums}={sum(odd_nums)}\")\n 1+3+5+7=16\n num = int(input(\"Insert a postive integer:\")) #4\n \nprint(f\"{'+'.join(map(str, range(1, num * 2, 2)))}={sum(range(1, num * 2, 2))}\")\n 1+3+5+7=16\n" }, { "answer_id": 74673521, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 0, "selected": false, "text": "(:=) range print sep end print(*(odd:=[*range(1,int(input('Insert a postive integer:'))*2,2)]),sep='+',end='=');print(sum(odd))\n\n# Insert a postive integer:4\n# 1+3+5+7=16\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16451251/" ]
74,673,181
<p>I want to consolidate the data of column B into a single cell ONLY IF the index (ie., Column A) is duplicated.</p> <p>For example:</p> <p><a href="https://i.stack.imgur.com/otMvd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/otMvd.png" alt="enter image description here" /></a></p> <p>Currently, I'm doing manually for each duplicated index by using the following formula:</p> <p><strong>=TEXTJOIN(&quot;, &quot;,TRUE,B4:B6)</strong></p> <p>Is there a better way to do this all at once?</p> <p>Any help is appreciated.</p>
[ { "answer_id": 74673209, "author": "Soumendra", "author_id": 5014656, "author_profile": "https://Stackoverflow.com/users/5014656", "pm_score": 0, "selected": false, "text": "oddNum odd num = int(input(\"Insert a positive integer:\"))\noddNum = 1\ntotal = 0\ncount = 1\nodd = \"\"\nwhile count <= num:\n total = total + oddNum\n odd += f\"{oddNum}\"\n oddNum = oddNum + 2\n count += 1\nodd = \"+\".join(odd)\nprint(odd + \"=\" + str(total))\n" }, { "answer_id": 74673240, "author": "phoenixinwater", "author_id": 5786997, "author_profile": "https://Stackoverflow.com/users/5786997", "pm_score": 0, "selected": false, "text": "print(oddNum, end='') num = int(input(\"Insert a postive integer:\")) #4\noddNum = 1\ntotal = 0\ncount = 1\nsequence = ''\nwhile count <= num:\n sequence += (\"+\" if sequence != \"\" else \"\") + str(oddNum)\n total = total + oddNum\n oddNum = oddNum + 2\n count += 1\n\nprint (sequence + \"=\" + str(total))\n num = int(input(\"Insert a postive integer:\")) #4\noddNum = 1\ntotal = 0\ncount = 1\nwhile count <= num:\n if count != 1:\n print('+', end='')\n print (oddNum, end='')\n total = total + oddNum\n oddNum = oddNum + 2\n count += 1\n\nprint (\"=\" + str(total)) \n" }, { "answer_id": 74673315, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 1, "selected": false, "text": "range() .join() f-strings total = sum(odd_nums) num = int(input(\"Insert a postive integer:\")) #4\nodd_nums = range(1, num * 2, 2)\nsum_nums = \"+\".join(map(str, odd_nums))\nprint(f\"{sum_nums}={sum(odd_nums)}\")\n 1+3+5+7=16\n num = int(input(\"Insert a postive integer:\")) #4\n \nprint(f\"{'+'.join(map(str, range(1, num * 2, 2)))}={sum(range(1, num * 2, 2))}\")\n 1+3+5+7=16\n" }, { "answer_id": 74673521, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 0, "selected": false, "text": "(:=) range print sep end print(*(odd:=[*range(1,int(input('Insert a postive integer:'))*2,2)]),sep='+',end='=');print(sum(odd))\n\n# Insert a postive integer:4\n# 1+3+5+7=16\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12870091/" ]
74,673,241
<p>In my SQL query, I want to check if a column has the string 'test' and safe the value in a new column</p> <p>When I use the new column in GROUP BY, I get error saying it can't find the new column:</p> <pre><code>SELECT CAST([EvtTime] as date) AS myDay, CASE WHEN [result] LIKE '%test%' THEN 1 ELSE 0 END AS testResult, COUNT_BIG(*) AS myCount, [name] FROM [mytable] GROUP BY myDay, testResult </code></pre> <p>I am using SQL Server.</p>
[ { "answer_id": 74673272, "author": "MD Zand", "author_id": 5118861, "author_profile": "https://Stackoverflow.com/users/5118861", "pm_score": 0, "selected": false, "text": "SELECT *,\n COUNT_BIG(*) AS myCount\nFROM (\n SELECT\n CAST([EvtTime] as date) AS myDay,\n CASE WHEN [result] LIKE '%test%' THEN 1 ELSE 0 END AS testResult,\n [name]\n FROM [MyTable]\n) MyInlineView\nGROUP BY myDay, testResult\n" }, { "answer_id": 74673299, "author": "Dale K", "author_id": 1127428, "author_profile": "https://Stackoverflow.com/users/1127428", "pm_score": 3, "selected": true, "text": "CROSS APPLY SELECT\n CAST([EvtTime] as date) AS myDay,\n X.testResult,\n COUNT_BIG(*) AS myCount,\n [name]\nFROM myTable\nCROSS APPLY (VALUES (CASE WHEN [result] LIKE '%test%' THEN 1 ELSE 0 END)) AS X(testResult)\nGROUP BY myDay, testResult\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18443805/" ]
74,673,245
<p>Trying to scrape all the names from this website with Python:</p> <p><a href="https://profile.tmb.state.tx.us/Search.aspx?9e94dec6-c7e7-4054-b5fb-20a1fcdbab53" rel="nofollow noreferrer">https://profile.tmb.state.tx.us/Search.aspx?9e94dec6-c7e7-4054-b5fb-20a1fcdbab53</a></p> <p>The issue is that it limits each search to the top 50 results.</p> <p>Since the last name search allows wildcards, I tried using one search result to narrow down subsequent search results (using prefixes). However, this approach becomes difficult when more than 50 people have the same last name.</p> <p>Any other ideas on how to get every possible name from this website? Thank you!!</p>
[ { "answer_id": 74673337, "author": "Alec Cureau", "author_id": 20590353, "author_profile": "https://Stackoverflow.com/users/20590353", "pm_score": 1, "selected": false, "text": "a a* a aa* ab* ac*" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12076064/" ]
74,673,249
<p>I have a dataframe where the rows contain NaN values. The df contains <strong>original columns</strong> namely <strong>Heading 1 Heading 2 and Heading 3</strong> and <strong>extra columns</strong> called <strong>Unnamed: 1 Unnamed: 2 and Unnamed: 3</strong> as shown:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Heading 1</th> <th>Heading 2</th> <th>Heading 3</th> <th>Unnamed: 1</th> <th>Unnamed: 2</th> <th>Unnamed: 3</th> </tr> </thead> <tbody> <tr> <td>NaN</td> <td>34</td> <td>24</td> <td>45</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>NaN</td> <td>24</td> <td>45</td> <td>11</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>45</td> <td>45</td> <td>33</td> </tr> <tr> <td>4</td> <td>NaN</td> <td>24</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>NaN</td> <td>4</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>34</td> <td>24</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>22</td> <td>34</td> <td>24</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>34</td> <td>NaN</td> <td>45</td> <td>NaN</td> <td>NaN</td> </tr> </tbody> </table> </div> <p>I want to <strong>iterate through each row</strong> and find out the amount of <strong>initial NaN values</strong> in <strong>original columns (Heading 1 Heading 2 and Heading 3)</strong> and the amount of <strong>non NaN values</strong> in the <strong>extra columns (Unnamed: 1 Unnamed: 2 and Unnamed: 3)</strong>. For each and every row this should be calculated and <strong>returned in a dictionary</strong> where the key is the index of the row and the value for that key is a list containing the amount of <strong>initial NaN values</strong> in <strong>original columns</strong> (Heading 1 Heading 2 and Heading 3) and the second element of the list would the amount of <strong>non NaN values</strong> in the <strong>extra columns</strong> (Unnamed: 1 Unnamed: 2 and Unnamed: 3).</p> <p>So the result for the above dataframe would be:</p> <pre><code>{0 : [1, 1], 1 : [2, 2], 2 : [3, 3], 3 : [0, 0], 4 : [2, 0], 5 : [1, 0], 6 : [0, 0], 7 : [1, 1]} </code></pre> <p>Notice how in row 3 and row 7 the original columns contain 1 and 2 NaN respectively but only the initial NaN's are counted and not the in between ones!</p> <h2>UPDATE / RESULTS:</h2> <p>Both @mozaway and @Panda Kim gave the correct solution for the current dataframe but @mozway solution does not work at all for another test dataframe.</p> <p>@Panda Kim gave 2 solutions but both the methods he gave (cumsum() and x.first_valid_index()) are giving slightly different results for the different dataframe.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Heading 1</th> <th>Heading 2</th> <th>Heading 3</th> <th>Unnamed: 1</th> <th>Unnamed: 2</th> <th>Unnamed: 3</th> <th>Unnamed: 4</th> </tr> </thead> <tbody> <tr> <td>NaN</td> <td>34</td> <td>24</td> <td>45</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>NaN</td> <td>24</td> <td>45</td> <td>11</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>45</td> <td>45</td> <td>33</td> <td>NaN</td> </tr> <tr> <td>4</td> <td>NaN</td> <td>24</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>NaN</td> <td>4</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>34</td> <td>24</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>22</td> <td>34</td> <td>24</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>34</td> <td>NaN</td> <td>45</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>12</td> <td>22</td> <td>45</td> </tr> <tr> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>11</td> <td>69</td> </tr> <tr> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>12</td> <td>NaN</td> <td>45</td> </tr> <tr> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>45</td> </tr> <tr> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>44</td> <td>NaN</td> </tr> </tbody> </table> </div> <p>For the above df here are the results:</p> <p>@Panda KIM (first_valid_index())</p> <pre><code>{0: [1, 1], 1: [2, 2], 2: [3, 3], 3: [0, 0], 4: [2, 0], 5: [1, 0], 6: [0, 0], 7: [1, 1], 8: [3, 3], 9: [3, 2], 10: [3, 2], 11: [3, 1], 12: [3, 1]} </code></pre> <p>@Panda Kim (cumsum())</p> <pre><code>{0: [1, 1], 1: [2, 2], 2: [3, 3], 3: [0, 0], 4: [2, 0], 5: [1, 0], 6: [0, 0], 7: [1, 1], 8: [4, 3], 9: [5, 2], 10: [4, 2], 11: [6, 1], 12: [5, 1]} </code></pre> <p>@mozway solution</p> <pre><code>{0: [1, 1], 1: [2, 2], 2: [3, 3], 3: [0, 0], 4: [2, 0], 5: [1, 0], 6: [0, 0], 7: [1, 1], 8: [3, 0], 9: [3, 0], 10: [3, 0], 11: [3, 0], 12: [3, 0]} </code></pre>
[ { "answer_id": 74673337, "author": "Alec Cureau", "author_id": 20590353, "author_profile": "https://Stackoverflow.com/users/20590353", "pm_score": 1, "selected": false, "text": "a a* a aa* ab* ac*" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18567298/" ]
74,673,260
<p>I want to create WebSecurityConfig class that extends WebSecurityConfigurerAdapter, but I always get error &quot;Cannot resolve symbol 'WebSecurityConfigurerAdapter'&quot;. I have already tried to add different dependencies. It's my gradle file</p> <pre><code>dependencies { runtimeOnly 'org.postgresql:postgresql' implementation group: 'org.postgresql', name: 'postgresql', version: '42.5.1' implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '3.0.0' implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-rest', version: '3.0.0' implementation group: 'org.springframework.boot', name: 'spring-boot-starter-tomcat', version: '3.0.0' implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '3.0.0' implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.5' implementation group: 'org.postgresql', name: 'postgresql', version: '42.5.1' implementation group: 'org.springframework.boot', name: 'spring-boot-starter-validation', version: '3.0.0' implementation group: 'org.springframework.security', name: 'spring-security-core', version: '6.0.0' implementation group: 'org.springframework.security', name: 'spring-security-config', version: '6.0.0' implementation group: 'org.springframework.security', name: 'spring-security-web', version: '6.0.0' implementation group: 'org.springframework.security', name: 'spring-security-oauth2-jose', version: '6.0.0' implementation group: 'org.springframework.security', name: 'spring-security-oauth2-resource-server', version: '6.0.0' implementation group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: '3.0.0' implementation group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version: '3.0.0' implementation group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-springsecurity5', version: '3.1.0.RELEASE' } </code></pre> <p>Maybe I don't understand something easy. Can you help me with this,please. I have already spent 2 days on this</p> <p>There is the same question on stack overflow (<a href="https://stackoverflow.com/questions/54177651/cannot-resolve-symbol-websecurityconfigureradapter">Cannot resolve symbol WebSecurityConfigurerAdapter</a>), but it doesn't help me. It's my file with WebSecurityConfig class</p> <pre><code>import nsu.project.springserver.security.jwt.AuthEntryPointJwt; import nsu.project.springserver.security.jwt.AuthTokenFilter; import nsu.project.springserver.security.services.UserDetailsServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { .... } </code></pre>
[ { "answer_id": 74674453, "author": "стасевич", "author_id": 16436722, "author_profile": "https://Stackoverflow.com/users/16436722", "pm_score": 0, "selected": false, "text": "WebSecurityConfigurerAdapter SecurityFilterChain @Bean\npublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {\n http.csrf()\n .disable()\n .authorizeRequests()\n .antMatchers(HttpMethod.DELETE)\n .hasRole(\"ADMIN\")\n .antMatchers(\"/admin/**\")\n .hasAnyRole(\"ADMIN\")\n .antMatchers(\"/user/**\")\n .hasAnyRole(\"USER\", \"ADMIN\")\n .antMatchers(\"/login/**\")\n .anonymous()\n .anyRequest()\n .authenticated()\n .and()\n .httpBasic()\n .and()\n .sessionManagement()\n .sessionCreationPolicy(SessionCreationPolicy.STATELESS);\n\n return http.build();\n}\n DefaultSecurityFilterChain" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17588867/" ]
74,673,300
<p>Im a newbie, Not able to select items in Radio button, inside a ListTile. I tied to use same code without ListTile and working as expected. Looks like combination is not correct or i might be missing something.</p> <pre><code>class _TempState extends State&lt;Temp&gt; { int selectedValue = 0; @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Container( child: Column(children: [ Row( children: [ Expanded( child: Text(&quot;Radio button with ListView&quot;,))],), Expanded( child: ListView.builder( itemCount: 1, itemBuilder: (BuildContext context, int index) { return OrderItem(); }),), ]))));} Widget OrderItem() { int selectedValue = 0; return ListTile( title: Container( child: Column(children: [ Row( children: [ Expanded( child: Text( &quot;Product Type :&quot;, )), Radio&lt;int&gt;( value: 1, groupValue: selectedValue, onChanged: (value) { setState(() { selectedValue = value != null ? value.toInt() : 1; }); }, ), Text('NRML'), Radio&lt;int&gt;( value: 2, groupValue: selectedValue, onChanged: (value) { setState(() { selectedValue = value != null ? value.toInt() : 1; }); }), Text('MARKET'), ],), ]))); }} </code></pre> <p><a href="https://i.stack.imgur.com/o7nNZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o7nNZ.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74674453, "author": "стасевич", "author_id": 16436722, "author_profile": "https://Stackoverflow.com/users/16436722", "pm_score": 0, "selected": false, "text": "WebSecurityConfigurerAdapter SecurityFilterChain @Bean\npublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {\n http.csrf()\n .disable()\n .authorizeRequests()\n .antMatchers(HttpMethod.DELETE)\n .hasRole(\"ADMIN\")\n .antMatchers(\"/admin/**\")\n .hasAnyRole(\"ADMIN\")\n .antMatchers(\"/user/**\")\n .hasAnyRole(\"USER\", \"ADMIN\")\n .antMatchers(\"/login/**\")\n .anonymous()\n .anyRequest()\n .authenticated()\n .and()\n .httpBasic()\n .and()\n .sessionManagement()\n .sessionCreationPolicy(SessionCreationPolicy.STATELESS);\n\n return http.build();\n}\n DefaultSecurityFilterChain" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3397828/" ]
74,673,310
<p>I'm following an online tutorial on how to build a calculator in C program, but it doesn't work even if I follow it step to step. It always give me 0.000000 as the answer. So I copied the tutor's own code to try, but it doesn't work either.</p> <p>Here's my code:</p> <pre><code> double num1; double num2; char op; printf(&quot;Enter a number: &quot;); scanf(&quot;%If&quot;, &amp;num1); printf(&quot;Enter operator: &quot;); scanf(&quot; %c&quot;,&amp;op); printf(&quot;Enter a number: &quot;); scanf(&quot;%If&quot;, &amp;num2); if(op == '+'){ printf(&quot; %f&quot;, num1 + num2); } else if(op == '-'){ printf(&quot; %f&quot;, num1 - num2); } else if (op == '/'){ printf(&quot; %f&quot;, num1 / num2); } else if (op == '*'){ printf(&quot; %f&quot;, num1 * num2); } else { printf(&quot;Invalid Operator&quot;); } </code></pre> <p>Here's the tutorial I'm following: <a href="https://www.mikedane.com/programming-languages/c/building-a-better-calculator/" rel="nofollow noreferrer">https://www.mikedane.com/programming-languages/c/building-a-better-calculator/</a></p> <p>I tried typing the code again, but nothing changes.</p> <p>I really appreciate any help you can provide.</p>
[ { "answer_id": 74674453, "author": "стасевич", "author_id": 16436722, "author_profile": "https://Stackoverflow.com/users/16436722", "pm_score": 0, "selected": false, "text": "WebSecurityConfigurerAdapter SecurityFilterChain @Bean\npublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {\n http.csrf()\n .disable()\n .authorizeRequests()\n .antMatchers(HttpMethod.DELETE)\n .hasRole(\"ADMIN\")\n .antMatchers(\"/admin/**\")\n .hasAnyRole(\"ADMIN\")\n .antMatchers(\"/user/**\")\n .hasAnyRole(\"USER\", \"ADMIN\")\n .antMatchers(\"/login/**\")\n .anonymous()\n .anyRequest()\n .authenticated()\n .and()\n .httpBasic()\n .and()\n .sessionManagement()\n .sessionCreationPolicy(SessionCreationPolicy.STATELESS);\n\n return http.build();\n}\n DefaultSecurityFilterChain" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20632417/" ]
74,673,358
<p>My apologies if this is a duplicate, I couldn't find an answer after searching for a while on Stackoverflow. I am trying to use a nested loop to find any duplicate characters in a string. So far, all I can manage to do is to find one duplicate the string.</p> <p>For example, when I try the string &quot;aabbcde&quot;, the function returns ['a', 'a'], whereas I was expecting ['a', 'a', 'b', 'b'].</p> <p>I obviously have an error in my code, can anybody help point me towards what it could be?</p> <pre><code>const myStr = &quot;aabbcde&quot;; function duplicateCount(text){ const duplicates = []; for (let i = 0; i &lt; text.length; i++) { for (let j = 0; j &lt; text[i].length; j++) { if (text[i] === text[j]) { duplicates.push(text[i]); } } } return duplicates; } duplicateCount(myStr); </code></pre>
[ { "answer_id": 74673466, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 0, "selected": false, "text": "const myStr1 = \"aabbcde\";\nconst myStr2 = \"ffeddbaa\";\n\nconst duplicateCount = str => {\n let map = {}\n for(c of str){\n map[c] = (map[c]??0) + 1 \n }\n let result = []\n for(m in map){\n if(map[m] <= 1){\n continue \n }\n result.push(...Array(map[m]).fill(m))\n }\n return result\n}\n\nconsole.log(duplicateCount(myStr1))\nconsole.log(duplicateCount(myStr2))" }, { "answer_id": 74673473, "author": "Pankti Shah", "author_id": 12364626, "author_profile": "https://Stackoverflow.com/users/12364626", "pm_score": 2, "selected": true, "text": "for (let j = 0; j < text[i].length; j++) const myStr = \"aabbcde\";\n\nfunction duplicateCount(text){\n const duplicates = [];\n for (let i = 0; i < text.length; i++) {\n for (let j = i+1; j < text.length; j++) {\n\n if (text[i] === text[j]) {\n duplicates.push(text[i]);\n }\n }\n }\n return duplicates;\n\n}\n\nconsole.log(duplicateCount(myStr));" }, { "answer_id": 74673535, "author": "score30", "author_id": 12521653, "author_profile": "https://Stackoverflow.com/users/12521653", "pm_score": 0, "selected": false, "text": "const myStr = 'aabbcde';\n\nconst duplicateCount = (str) => {\n const result = [];\n const obj = {};\n str.split('').map((char) => {\n obj[char] = obj[char] + 1 || 1;\n });\n for (key in obj) {\n if (obj[key] > 1) {\n for (let i = 0; i < obj[key]; i++) {\n result.push(key);\n }\n }\n }\n return result;\n};\n\nconsole.log(duplicateCount(myStr));" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5220731/" ]
74,673,377
<p>I have written the following code to generate a <strong>random</strong> list. I want the list to have elements between <strong>0</strong> and <strong>500</strong>, but the <strong>summation</strong> of all elements does not exceed <strong>1300</strong>. I dont know how to continue my code to do that. I have written other codes; for example, to create a list of random vectors and then pick among those that satisfy the condition. But here I want to create such a list in one try.</p> <pre><code>nv = 5 bounds = [(0, 500), (0, 500), (0, 500), (0, 500), (0, 500)] var =[] for j in range(nv): var.append(random.uniform(bounds[j][0], bounds[j][1])) summ = sum(var) if summ &gt; 1300: ???? </code></pre>
[ { "answer_id": 74673408, "author": "Ouroborus", "author_id": 367865, "author_profile": "https://Stackoverflow.com/users/367865", "pm_score": 2, "selected": true, "text": "append while len() < maxLen nv len(bounds) len(var) len(var) var bounds sum() * .uniform() import random\n\nbounds = [(0, 500), (0, 500), (0, 500), (0, 500), (0, 500)]\nvar = []\nrunningSum = 0\nwhile len(var) < len(bounds):\n sample = random.uniform(*bounds[len(var)])\n if runningSum + sample < 1300:\n runningSum += sample\n var.append(sample)\n\nprint(repr(var))\n" }, { "answer_id": 74673873, "author": "Cobra", "author_id": 17580381, "author_profile": "https://Stackoverflow.com/users/17580381", "pm_score": 0, "selected": false, "text": "from random import uniform\n\ndef func1():\n LIMIT = 1_300\n bounds = [(0, 500), (0, 500), (0, 500), (0, 500), (0, 500)]\n\n while sum(result := [uniform(lo, hi) for lo, hi in bounds]) > LIMIT:\n pass\n\n return result\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12385685/" ]
74,673,433
<p>I hope you're doing well, I just need some help with my problem, been stuck at it for a while now and I cannot figure out a work around. I implemented another login for the admin in my project and I use a custom guard and custom middleware for it. This works properly without any problem. The problem started when I try to protect the API routes using passport. For the users which uses the auth:api as the API middleware, everything works fine. But in my custom guard, it returns an HTML response(console.log says it returns HTML but it does not output anything in the UI) instead of json. If I remove the route protection it would work again as intended. I hope you can help me with this one. Thank you!</p> <p>I am using Laravel Passport for the API protection.</p> <p>This is how it looks like without the API route protection(This is how it should be). <a href="https://i.stack.imgur.com/n4cuE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n4cuE.png" alt="enter image description here" /></a></p> <p>This is how it looks like with the route protection <a href="https://i.stack.imgur.com/Jfs78.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jfs78.png" alt="enter image description here" /></a></p> <p>This is what console.log returns with route protection. Without it, it returns the response from the first picture.</p> <p><a href="https://i.stack.imgur.com/2jOA1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2jOA1.png" alt="enter image description here" /></a></p> <p>Here's my code below</p> <p><strong>AdminMiddleware</strong></p> <pre><code>&lt;?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; use Illuminate\Http\Request; class AdminMiddleware { public function handle($request, Closure $next, $guard = null) { if (Auth::guard('admin')-&gt;check()) { return $next($request); } else { return redirect()-&gt;route('admin.login'); } } </code></pre> <p><strong>Kernel.php</strong></p> <pre><code> protected $routeMiddleware = [ 'auth.admin' =&gt; \App\Http\Middleware\AdminMiddleware::class, 'auth' =&gt; \App\Http\Middleware\Authenticate::class, ]; </code></pre> <p><strong>config/auth.php</strong></p> <pre><code>'guards' =&gt; [ 'web' =&gt; [ 'driver' =&gt; 'session', 'provider' =&gt; 'users', ], 'api' =&gt; [ 'driver' =&gt; 'passport', 'provider' =&gt; 'users', 'hash' =&gt; false, ], 'admin' =&gt; [ 'driver' =&gt; 'session', 'provider' =&gt; 'admins', ], 'adminApi' =&gt; [ 'driver' =&gt; 'passport', 'provider' =&gt; 'admins', 'hash' =&gt; false, ] ], </code></pre> <p><strong>routes/api.php</strong></p> <pre><code>Route::group(['middleware' =&gt; ['auth.admin:adminApi']], function(){ Route::get('/fetch-announcements', [AnnouncementController::class, 'showAnnouncement']); Route::post('/store-announcements',[AnnouncementController::class, 'storeAnnouncement']); }); </code></pre> <p><strong>Models/Admin.php</strong></p> <pre><code>&lt;?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; class Admin extends Authenticatable { use HasFactory, HasApiTokens; protected $fillable =[ 'email', ]; protected $hidden = [ 'password', 'remember_token', ]; protected $casts = [ 'email_verified_at' =&gt; 'datetime', ]; } </code></pre> <p><strong>Get Request</strong></p> <pre><code>await axios.get('/api/fetch-announcements', { headers: { 'Accept': 'application/json' } }) .then(response =&gt; { this.announcements = response.data console.log(this.announcements) }) .catch(err =&gt; console.error(err)) </code></pre> <p><strong>EDIT</strong> The API returns a 302 code</p>
[ { "answer_id": 74673408, "author": "Ouroborus", "author_id": 367865, "author_profile": "https://Stackoverflow.com/users/367865", "pm_score": 2, "selected": true, "text": "append while len() < maxLen nv len(bounds) len(var) len(var) var bounds sum() * .uniform() import random\n\nbounds = [(0, 500), (0, 500), (0, 500), (0, 500), (0, 500)]\nvar = []\nrunningSum = 0\nwhile len(var) < len(bounds):\n sample = random.uniform(*bounds[len(var)])\n if runningSum + sample < 1300:\n runningSum += sample\n var.append(sample)\n\nprint(repr(var))\n" }, { "answer_id": 74673873, "author": "Cobra", "author_id": 17580381, "author_profile": "https://Stackoverflow.com/users/17580381", "pm_score": 0, "selected": false, "text": "from random import uniform\n\ndef func1():\n LIMIT = 1_300\n bounds = [(0, 500), (0, 500), (0, 500), (0, 500), (0, 500)]\n\n while sum(result := [uniform(lo, hi) for lo, hi in bounds]) > LIMIT:\n pass\n\n return result\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15799007/" ]
74,673,445
<p>I tried for hours and read many posts but I still can't figure out how to handle this request:</p> <p>I have a table like this :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Gender</th> <th>Marks</th> </tr> </thead> <tbody> <tr> <td>M</td> <td>75</td> </tr> <tr> <td>F</td> <td>88</td> </tr> <tr> <td>M</td> <td>93</td> </tr> <tr> <td>M</td> <td>88</td> </tr> <tr> <td>F</td> <td>98</td> </tr> </tbody> </table> </div> <p>I'd like to select all boys from the table and set the sameMarks column to 1 when the boy marks match the girl marks, otherwise it should be 0.<br /> The output should look like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Gender</th> <th>Marks</th> <th>Same_Marks</th> </tr> </thead> <tbody> <tr> <td>M</td> <td>75</td> <td>0</td> </tr> <tr> <td>M</td> <td>93</td> <td>0</td> </tr> <tr> <td>M</td> <td>88</td> <td>1</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74673467, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 1, "selected": false, "text": "SELECT MAX(Gender) AS Gender,\n Marks,\n CASE WHEN MIN(Gender) = MAX(Gender) THEN 0 ELSE 1 END AS Same_Marks\nFROM yourTable\nGROUP BY Marks;\n" }, { "answer_id": 74673532, "author": "Jonas Metzler", "author_id": 18794826, "author_profile": "https://Stackoverflow.com/users/18794826", "pm_score": 1, "selected": true, "text": "EXISTS CASE WHEN SELECT \ny.gender, y.marks,\nCASE WHEN \n EXISTS(SELECT 1 FROM yourtable WHERE gender <> 'M' and marks = y.marks) \n THEN 1 ELSE 0 END AS Same_Marks\nFROM yourtable y\nWHERE y.gender = 'M';\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18118826/" ]
74,673,476
<p>I am trying to make it so anytime a user enters .&quot;insert word here&quot; the program will recognize this an invalid command and send the user a message saying something like &quot;invalid command type .help for a list of commands&quot;. I already have my active commands working but Im not sure how to catch invalid commands here is my code so far.</p> <pre><code>while (true) { String userInput = scan.nextLine(); if (userInput.equals(&quot;.help&quot;)) { //print list of commands } else if (userInput.equals(&quot;.ping&quot;) { //print pong } //check for any String that starts with . but does not equal the previous commands and return an error message } </code></pre>
[ { "answer_id": 74673497, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 2, "selected": false, "text": "switch while (true) {\n String userInput = scan.nextLine();\n\n switch(userInput) {\n case \".help\":\n // print list of commands\n break;\n\n case \".ping\":\n // print pong\n break;\n\n default:\n // print error message for unknown command\n }\n}\n" }, { "answer_id": 74673549, "author": "Kushagra Rathore", "author_id": 14682443, "author_profile": "https://Stackoverflow.com/users/14682443", "pm_score": 0, "selected": false, "text": "while (true) {\n String userInput = scan.nextLine();\n\n if (userInput.equals(\".help\")) {\n // print list of commands\n } else if (userInput.equals(\".ping\")) {\n // print pong\n } else if (userInput.startsWith(\".\")) {\n System.out.println(\"Invalid command. Type .help for a list of commands.\");\n }\n}\n\n" }, { "answer_id": 74673744, "author": "wvullhorst", "author_id": 3383848, "author_profile": "https://Stackoverflow.com/users/3383848", "pm_score": 0, "selected": false, "text": " while (true) {\n String userInput = scan.nextLine();\n if (userInput.equals(\".help\")) {\n //print list of commands\n } else if (userInput.equals(\".ping\")) {\n //print pong\n } else if(userInput.startsWith(\".\")) {\n // applies if userInput starts with \".\" but is not .help or .ping\n }\n else {\n // applies if userInput does not start with a \".\"\n }\n }\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19918960/" ]
74,673,484
<p>How should access and refresh tokens obtained from the Twitter API v2 be stored and used in a secure manner?</p> <p>I can't just store access_token and refresh_token alone, right? I will need some kind of identifier. And probably save that identifier in the client.</p> <p>Are there any recommended approaches or best practices for this? I would appreciate any guidance.</p>
[ { "answer_id": 74673497, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 2, "selected": false, "text": "switch while (true) {\n String userInput = scan.nextLine();\n\n switch(userInput) {\n case \".help\":\n // print list of commands\n break;\n\n case \".ping\":\n // print pong\n break;\n\n default:\n // print error message for unknown command\n }\n}\n" }, { "answer_id": 74673549, "author": "Kushagra Rathore", "author_id": 14682443, "author_profile": "https://Stackoverflow.com/users/14682443", "pm_score": 0, "selected": false, "text": "while (true) {\n String userInput = scan.nextLine();\n\n if (userInput.equals(\".help\")) {\n // print list of commands\n } else if (userInput.equals(\".ping\")) {\n // print pong\n } else if (userInput.startsWith(\".\")) {\n System.out.println(\"Invalid command. Type .help for a list of commands.\");\n }\n}\n\n" }, { "answer_id": 74673744, "author": "wvullhorst", "author_id": 3383848, "author_profile": "https://Stackoverflow.com/users/3383848", "pm_score": 0, "selected": false, "text": " while (true) {\n String userInput = scan.nextLine();\n if (userInput.equals(\".help\")) {\n //print list of commands\n } else if (userInput.equals(\".ping\")) {\n //print pong\n } else if(userInput.startsWith(\".\")) {\n // applies if userInput starts with \".\" but is not .help or .ping\n }\n else {\n // applies if userInput does not start with a \".\"\n }\n }\n" } ]
2022/12/04
[ "https://Stackoverflow.com/questions/74673484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17870144/" ]