qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,396,942
<p>Use case: ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits.</p> <p>If the function is passed a valid PIN string, return true, else return false.</p> <p>My code is working for all the randomly generated pins except for:</p> <p>'12.0' '1234.0' '111-' '44444-'</p> <pre><code>def validate_pin(pin): numbers = '0123456789' if len(pin) != 4 and len(pin) != 6: return False else: for i in range(len(pin)): if pin[i] in numbers: return True else: break return False </code></pre> <p>Any idea why this would be? These characters do not live within my created variable.</p>
[ { "answer_id": 74397036, "author": "Temba", "author_id": 3593621, "author_profile": "https://Stackoverflow.com/users/3593621", "pm_score": 3, "selected": true, "text": "def validate_pin(pin):\nnumbers = '0123456789'\nif len(pin) != 4 and len(pin) != 6:\n return False\nelse:\n for i in range(len(pin)):\n if pin[i] not in numbers:\n return False\n # if pin[i] in numbers:\n # return True\n # else:\n # break\n return True\n" }, { "answer_id": 74397046, "author": "rnorris", "author_id": 487056, "author_profile": "https://Stackoverflow.com/users/487056", "pm_score": 1, "selected": false, "text": "else:\n for i in range(len(pin)):\n if pin[i] in numbers:\n return True\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74396942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20473556/" ]
74,396,954
<p>I have a list of wallet addresses in my template. When I tried deleting an address by clicking on the delete button, it returns an error message. I think it is an error from the way my template was structured. But, I don't really know. When I try deleting an address by manually inputting the id of the address in the delete view URL, it gets deleted. Here is the error message that is returned.</p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\fields\__init__.py&quot;, line 2018, in get_prep_value return int(value) The above exception (invalid literal for int() with base 10: 'Btc') was the direct cause of the following exception: File &quot;C:\Users\admin\Documents\Django\env\lib\site-packages\django\core\handlers\exception.py&quot;, line 55, in inner response = get_response(request) File &quot;C:\Users\admin\Documents\Django\env\lib\site-packages\django\core\handlers\base.py&quot;, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File &quot;C:\Users\admin\Documents\Django\env\lib\site-packages\django\contrib\auth\decorators.py&quot;, line 23, in _wrapped_view return view_func(request, *args, **kwargs) File &quot;C:\Users\admin\Documents\Django\crypto\dashboard\views.py&quot;, line 275, in del_wallet wallet.delete() File &quot;C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\base.py&quot;, line 1137, in delete return collector.delete() File &quot;C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\deletion.py&quot;, line 475, in delete query.update_batch( File &quot;C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\sql\subqueries.py&quot;, line 78, in update_batch self.get_compiler(using).execute_sql(NO_RESULTS) File &quot;C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\sql\compiler.py&quot;, line 1819, in execute_sql cursor = super().execute_sql(result_type) File &quot;C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\sql\compiler.py&quot;, line 1382, in execute_sql sql, params = self.as_sql() File &quot;C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\sql\compiler.py&quot;, line 1785, in as_sql val = field.get_db_prep_save(val, connection=self.connection) File &quot;C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\fields\related.py&quot;, line 1146, in get_db_prep_save return self.target_field.get_db_prep_save(value, connection=connection) File &quot;C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\fields\__init__.py&quot;, line 925, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False) File &quot;C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\fields\__init__.py&quot;, line 2703, in get_db_prep_value value = self.get_prep_value(value) File &quot;C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\fields\__init__.py&quot;, line 2020, in get_prep_value raise e.__class__( Exception Type: ValueError at /dashboard/wallet/2/delete/ Exception Value: Field 'id' expected a number but got 'Btc'. </code></pre> <p>views.py</p> <pre><code>@login_required def wallet(request): user = request.user wallet=Wallet(user=user) object_list = Wallet.objects.filter(user=user) # Paginator paginator = Paginator(object_list, 2) page = request.GET.get('page') try: ref = paginator.page(page) except PageNotAnInteger: ref = paginator.page(1) except EmptyPage: ref = paginator.page(paginator.num_pages) if request.method == 'POST': if 'add' in request.POST: form = WalletForm(request.POST, instance=wallet) if form.is_valid(): form.save() messages.success(request, (&quot;New wallet address successfully added.&quot;)) return redirect(&quot;dashboard:wallet&quot;) else: form = WalletForm(instance=user) context = { 'form': form, 'ref': ref, # 'refe': refe # 'del_wallet': del_wallet } return render(request, 'dashboard/wallet.html', context) @login_required def del_wallet(request, pk): wallet = get_object_or_404(Wallet, id=pk) wallet.delete() return redirect(&quot;dashboard:wallet&quot;) </code></pre> <p>The first view <code>wallet</code> is responsible for letting users add new wallet, and also responsible for displaying the wallets. The adding wallet logic is done by the use of a popup modal. The second view <code>del_wallet</code> is responsible for handling the delete logic.</p> <p>urls.py</p> <pre><code>urlpatterns = [ path('wallet', wallet, name=&quot;wallet&quot;), path('wallet/&lt;str:pk&gt;/delete/', del_wallet, name=&quot;del_wallet&quot;), ] </code></pre> <p>By typing out the URL and specifying an id, the wallet address with the id gets deleted. Like, calling <em>http://localhost&quot;5000/wallet/2/delete/</em> deletes the address with id of 2. But clicking on the delete button attached to each wallet, returns back the error message specified above. I added print statement to check the details of the wallet that pops up each time I click the delete button. It logs the correct wallet being clicked with its id, but yet it returns an error message. I can't seem to figure out what is causing the error.</p> <p>wallet.html</p> <pre><code>&lt;h3 class=&quot;h5 text-primary pt-1 pt-lg-3 mt-4&quot;&gt;Available Wallets&lt;/h3&gt; &lt;div class=&quot;table-responsive&quot;&gt; &lt;table class=&quot;table table-dark table-striped&quot;&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;SN&lt;/th&gt; &lt;th&gt;Type&lt;/th&gt; &lt;th&gt;Address&lt;/th&gt; &lt;th&gt;Delete&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;!-- --&gt; {% for i in ref %} &lt;tr&gt; &lt;td style=&quot;line-height: 1.3; padding-top: 1.6em;&quot;&gt;{{ forloop.counter }}&lt;/td&gt; &lt;td style=&quot;padding-top: 20px;&quot;&gt;{{ i.get_type_display }}&lt;/td&gt; &lt;td style=&quot;padding-top: 20px;&quot;&gt;{{ i.address }}&lt;/td&gt; &lt;td class=&quot;view&quot; data-bs-toggle=&quot;modal&quot; data-bs-target=&quot;#wallet{{ i.pk }}&quot;&gt; &lt;a style=&quot;text-decoration: none;&quot; href=&quot;#wallet{{ i.pk }}&quot;&gt; Delete &lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;!-- DELETE MODAL --&gt; &lt;div class=&quot;modal fade&quot; id=&quot;wallet{{ i.pk }}&quot; tabindex=&quot;-1&quot; role=&quot;dialog&quot; style=&quot;margin-top: 10em;&quot;&gt; &lt;div class=&quot;modal-dialog modal-sm&quot; role=&quot;document&quot;&gt; &lt;div class=&quot;modal-content&quot; style=&quot;background: #141822;&quot;&gt; &lt;div class=&quot;modal-body&quot;&gt; &lt;h6&gt;Confirm Delete&lt;/h6&gt; &lt;p&gt;Are you sure you want to delete &lt;span style=&quot;color: rgb(10, 223, 165);&quot;&gt; {{ i.type }} - {{ i.address }} &lt;/span&gt; wallet? &lt;/p&gt; &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary btn-sm w-100&quot;&gt; &lt;a href=&quot;/dashboard/wallet/{{ i.pk }}/delete/&quot; style=&quot;text-decoration: none;&quot;&gt; Confirm &lt;/a&gt; &lt;/button&gt;&lt;br&gt; &lt;button type=&quot;button&quot; class=&quot;btn btn-warning btn-sm w-100 mt-2&quot; data-bs-dismiss=&quot;modal&quot;&gt; Close &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; {% empty %} &lt;tr&gt; &lt;td&gt;You haven't added a wallet address yet.&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p>models.py</p> <pre><code>class Wallet(models.Model): wallet = ( ('Btc', 'Bitcoin'), ('Eth', 'Ethereum'), ('Trc20', 'Tether-UDST'), ('Ltc', 'Litecoin') ) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) type = models.CharField(choices=wallet, default='Btc') address = models.CharField(max_length=80) </code></pre> <p>Please, what is likely the cause of the error. I've read up many posts online, but none seems to help in resolving my problem.</p>
[ { "answer_id": 74397036, "author": "Temba", "author_id": 3593621, "author_profile": "https://Stackoverflow.com/users/3593621", "pm_score": 3, "selected": true, "text": "def validate_pin(pin):\nnumbers = '0123456789'\nif len(pin) != 4 and len(pin) != 6:\n return False\nelse:\n for i in range(len(pin)):\n if pin[i] not in numbers:\n return False\n # if pin[i] in numbers:\n # return True\n # else:\n # break\n return True\n" }, { "answer_id": 74397046, "author": "rnorris", "author_id": 487056, "author_profile": "https://Stackoverflow.com/users/487056", "pm_score": 1, "selected": false, "text": "else:\n for i in range(len(pin)):\n if pin[i] in numbers:\n return True\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74396954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15298459/" ]
74,396,966
<p>I'm trying to click &quot;Create New Network&quot; by using selenium.</p> <pre><code>&lt;button type=&quot;button&quot; id=&quot;dt-refreshBtn&quot; class=&quot;btn wc-btn--link&quot; data-label=&quot;Create New Network&quot; role=&quot;link&quot;&gt;&lt;span class=&quot;icon-button&quot; data-testid=&quot;dnxButton-iconButtonContainer&quot; data-awt=&quot;networkListing-button-createNew&quot;&gt;&lt;i class=&quot;dnac-icon-add-circle&quot; data-testid=&quot;dnxButton-icon&quot; title=&quot;Create New Network&quot;&gt;&lt;/i&gt;&lt;span class=&quot;dnx-btn-icon-label&quot; data-testid=&quot;dnxButton-iconLabel&quot;&gt;Create New Network&lt;/span&gt;&lt;/span&gt;&lt;/button&gt; &lt;span class=&quot;icon-button&quot; data-testid=&quot;dnxButton-iconButtonContainer&quot; data-awt=&quot;networkListing-button-createNew&quot;&gt;&lt;i class=&quot;dnac-icon-add-circle&quot; data-testid=&quot;dnxButton-icon&quot; title=&quot;Create New Network&quot;&gt;&lt;/i&gt;&lt;span class=&quot;dnx-btn-icon-label&quot; data-testid=&quot;dnxButton-iconLabel&quot;&gt;Create New Network&lt;/span&gt;&lt;/span&gt; &lt;i class=&quot;dnac-icon-add-circle&quot; data-testid=&quot;dnxButton-icon&quot; title=&quot;Create New Network&quot;&gt;&lt;/i&gt; &lt;span class=&quot;dnx-btn-icon-label&quot; data-testid=&quot;dnxButton-iconLabel&quot;&gt;Create New Network&lt;/span&gt; </code></pre> <p><a href="https://i.stack.imgur.com/4dpgu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4dpgu.png" alt="enter image description here" /></a></p> <p>I tried several scripts to find the location of &quot;Create New Network&quot; button, but got failed with below reason.</p> <ol> <li>Message: no such element: Unable to locate element:</li> <li>AttributeError: 'list' object has no attribute 'send_keys'</li> <li>'list' object has no attribute 'click'</li> </ol> <p>here are scripts I've tried.</p> <pre><code>driver.find_element(By.CSS_SELECTOR, &quot;[title='Create New Network']&quot;).click() driver.find_element(By.CSS_SELECTOR, &quot;[data-awt='networkListing-button-createNew']&quot;).click() driver.find_element(By.CSS_SELECTOR, &quot;[id='dt-refreshBtn']&quot;).click() driver.find_element(By.CSS_SELECTOR, &quot;[class='dnx-btn-icon-label']&quot;).click() driver.find_elements(By.XPATH, &quot;//*[@class='dnx-btn-icon-label']&quot;).send_keys(Keys.ENTER) driver.find_elements(By.XPATH, &quot;//button[@class='btn wc-btn--link']&quot;)[0].send_keys(Keys.ENTER) driver.find_elements(By.XPATH, &quot;//*[@id='dt-refreshBtn']&quot;).send_keys(Keys.ENTER) driver.find_element(By.ID, &quot;dt-refreshBtn&quot;).send_keys(Keys.ENTER) driver.find_element(By.CSS_SELECTOR, &quot;[data-testid='dnxButton-icon']&quot;).send_keys(Keys.ENTER) driver.find_element(By.CSS_SELECTOR, &quot;[data-testid='dnxButton-iconLabel']&quot;).send_keys(Keys.ENTER) driver.find_elements(By.CSS_SELECTOR, &quot;[data-awt='networkListing-button-createNew']&quot;).click() driver.find_element(By.CSS_SELECTOR, &quot;[title='Create New Network']&quot;).click() driver.find_elements(By.XPATH, &quot;//*[@id='dt-refreshBtn']&quot;).click() </code></pre> <p>could you please help this one ?</p>
[ { "answer_id": 74397036, "author": "Temba", "author_id": 3593621, "author_profile": "https://Stackoverflow.com/users/3593621", "pm_score": 3, "selected": true, "text": "def validate_pin(pin):\nnumbers = '0123456789'\nif len(pin) != 4 and len(pin) != 6:\n return False\nelse:\n for i in range(len(pin)):\n if pin[i] not in numbers:\n return False\n # if pin[i] in numbers:\n # return True\n # else:\n # break\n return True\n" }, { "answer_id": 74397046, "author": "rnorris", "author_id": 487056, "author_profile": "https://Stackoverflow.com/users/487056", "pm_score": 1, "selected": false, "text": "else:\n for i in range(len(pin)):\n if pin[i] in numbers:\n return True\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74396966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20473570/" ]
74,396,999
<p>I have no idea why this is happening, but it looks like a variable has two values, one correct and one unexpected value. When I print a variable in the console log, it shows at first the correct variable and right after it prints again another unexpected value. Is it a bug in AppScript, or something off that I cannot see?</p> <p>Some extract of the code:</p> <pre><code>function funx(){ var ss = SpreadsheetApp.openById('xxx'); var sheet = ss.getSheetByName('Data'); var list = sheet.getRange(3,5,sheet.getLastRow(),1).getRichTextValues(); var additionalList = sheet.getRange(3,3,sheet.getLastRow(),2).getValues(); //need another list because rich text value does not get numbers for (var i=0;i&lt;list.length;i++){ let datex = new Date(additionalList[i][0]); Logger.log(datex); // this prints only one value and this is the correct value let date = getFDate(datex)} } function getFDate(rowDate){ Logger.log(rowDate); // this prints two values. The first one is same as datex. The second one looks like a previous date which run when I called this function in the previous loop iteration. var year = rowDate.getFullYear(); var month = (1 + rowDate.getMonth()).toString(); month = month.length &gt;1 ? month : '0' + month; var day = rowDate.getDate().toString(); day = day.length &gt; 1 ? day : '0' + day; var dateReturn = month + '/' + day + '/' + year; return dateReturn; } </code></pre> <p>The Logger.log prints two values!</p> <p>5:58:48 PM Info Wed Nov 30 00:00:00 GMT-08:00 2022 -&gt; result of Logger.log(datex). This is the expected value</p> <p>5:58:48 PM Info Wed Nov 30 00:00:00 GMT-08:00 2022 -&gt; result of Logger.log(rowDate). This is the expected value</p> <p>5:58:48 PM Info 2022-11-08T22:14:48.343+0000 -&gt; result of Logger.log(rowDate). This is unexpected.</p> <p>I purposely changed the name of the variable &quot;datex&quot; to make sure it is nowhere else in the code.</p> <p><em><strong>_____ REASON OF ISSUE:</strong></em></p> <p><strong>In another function as part of an IF statement that was never met, there was a Logger.log(getFDate(...)). I thought it was completely unrelated. But removing that fixed the issue. Looks like calling that function in a Logger.log caused its malfunction.</strong></p>
[ { "answer_id": 74397128, "author": "Cooper", "author_id": 7215091, "author_profile": "https://Stackoverflow.com/users/7215091", "pm_score": 0, "selected": false, "text": "function funx() {\n var ss = SpreadsheetApp.openById('xxx');\n var sheet = ss.getSheetByName('Data');\n var list = sheet.getRange(3, 5, sheet.getLastRow() - 2).getValues();// third parameter is the number of rows in the range not the last row in the range\n var additionalList = sheet.getRange(3, 3, sheet.getLastRow() - 2, 2).getValues();\n for (var i = 0; i < list.length; i++) {\n let datex = new Date(additionalList[i][0]);\n let date = getFDate(datex)\n }\n}\n" }, { "answer_id": 74397341, "author": "Filippo", "author_id": 3818716, "author_profile": "https://Stackoverflow.com/users/3818716", "pm_score": 2, "selected": true, "text": "Logger.log(\"DETECTED A CHANGE. Due Date changed by someone else: \"+data[\"issues\"][0].changelog[\"histories\"][id].displayName+\" on date: \"+getFDate(data[\"issues\"][0].changelog[\"histories\"][id].created));\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74396999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3818716/" ]
74,397,005
<p>I have a custom DialogFragment, and was trying to use AlertDialog in onCreateDialog(). The AlertDialog only has title, singleChoiceItem, positiveButton, etc. But I would like to add an extra button on the top left to be a back button that I could add a onClickListener. How could I do that? Thanks!</p>
[ { "answer_id": 74397128, "author": "Cooper", "author_id": 7215091, "author_profile": "https://Stackoverflow.com/users/7215091", "pm_score": 0, "selected": false, "text": "function funx() {\n var ss = SpreadsheetApp.openById('xxx');\n var sheet = ss.getSheetByName('Data');\n var list = sheet.getRange(3, 5, sheet.getLastRow() - 2).getValues();// third parameter is the number of rows in the range not the last row in the range\n var additionalList = sheet.getRange(3, 3, sheet.getLastRow() - 2, 2).getValues();\n for (var i = 0; i < list.length; i++) {\n let datex = new Date(additionalList[i][0]);\n let date = getFDate(datex)\n }\n}\n" }, { "answer_id": 74397341, "author": "Filippo", "author_id": 3818716, "author_profile": "https://Stackoverflow.com/users/3818716", "pm_score": 2, "selected": true, "text": "Logger.log(\"DETECTED A CHANGE. Due Date changed by someone else: \"+data[\"issues\"][0].changelog[\"histories\"][id].displayName+\" on date: \"+getFDate(data[\"issues\"][0].changelog[\"histories\"][id].created));\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7560138/" ]
74,397,044
<p>Still new to python and this problem is driving me crazy I know I'm missing something really obvious but I just can't figure it out :/ Here is the problem:</p> <ol> <li><p>Write a function called main that prompts/asks the user to enter two integer values.</p> </li> <li><p>Write a value returning function named max that accepts two integer values as arguments and returns the value that is the greater of the two. For example, if 30 and 25 are passed as arguments to the function, the function should return 30.</p> </li> <li><p>Call the max function in the main function</p> </li> <li><p>The main function should display the value that is the greater of the two.</p> </li> </ol> <p>This is my code, unsure of where I went wrong</p> <pre><code>def main(): num1 = int(input('Enter the first number')) num2 = int(input('Enter the second number')) return num1, num2 max(n1, n2) print(max) def max(n1, n2): return max main() </code></pre>
[ { "answer_id": 74397128, "author": "Cooper", "author_id": 7215091, "author_profile": "https://Stackoverflow.com/users/7215091", "pm_score": 0, "selected": false, "text": "function funx() {\n var ss = SpreadsheetApp.openById('xxx');\n var sheet = ss.getSheetByName('Data');\n var list = sheet.getRange(3, 5, sheet.getLastRow() - 2).getValues();// third parameter is the number of rows in the range not the last row in the range\n var additionalList = sheet.getRange(3, 3, sheet.getLastRow() - 2, 2).getValues();\n for (var i = 0; i < list.length; i++) {\n let datex = new Date(additionalList[i][0]);\n let date = getFDate(datex)\n }\n}\n" }, { "answer_id": 74397341, "author": "Filippo", "author_id": 3818716, "author_profile": "https://Stackoverflow.com/users/3818716", "pm_score": 2, "selected": true, "text": "Logger.log(\"DETECTED A CHANGE. Due Date changed by someone else: \"+data[\"issues\"][0].changelog[\"histories\"][id].displayName+\" on date: \"+getFDate(data[\"issues\"][0].changelog[\"histories\"][id].created));\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20473614/" ]
74,397,068
<p>I know that the code below works.</p> <pre class="lang-cpp prettyprint-override"><code> int* pn; pn = new int; </code></pre> <p>So I tried to apply it in same way, in my custom class.</p> <pre class="lang-cpp prettyprint-override"><code>class Matrix { private: typedef struct ex_node* ex_pointer; typedef struct ex_node { int ex_data; ex_pointer next; }; public: void examplefunction() { ex_pointer node; node = new ex_node; //error here } }; </code></pre> <p>The error says that I cannot assign &quot;ex_node*&quot; type value to &quot;ex_pointer&quot;type entity.</p> <p>But ex_pointer is defined as ex_node*.</p> <p>Is ex_pointer different type from ex_node*? How can I remove this error?</p>
[ { "answer_id": 74397128, "author": "Cooper", "author_id": 7215091, "author_profile": "https://Stackoverflow.com/users/7215091", "pm_score": 0, "selected": false, "text": "function funx() {\n var ss = SpreadsheetApp.openById('xxx');\n var sheet = ss.getSheetByName('Data');\n var list = sheet.getRange(3, 5, sheet.getLastRow() - 2).getValues();// third parameter is the number of rows in the range not the last row in the range\n var additionalList = sheet.getRange(3, 3, sheet.getLastRow() - 2, 2).getValues();\n for (var i = 0; i < list.length; i++) {\n let datex = new Date(additionalList[i][0]);\n let date = getFDate(datex)\n }\n}\n" }, { "answer_id": 74397341, "author": "Filippo", "author_id": 3818716, "author_profile": "https://Stackoverflow.com/users/3818716", "pm_score": 2, "selected": true, "text": "Logger.log(\"DETECTED A CHANGE. Due Date changed by someone else: \"+data[\"issues\"][0].changelog[\"histories\"][id].displayName+\" on date: \"+getFDate(data[\"issues\"][0].changelog[\"histories\"][id].created));\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19435802/" ]
74,397,087
<p>I am new to Laravel. I am now able to register users, log them in. But after login, I don't want to display register and login pages. I want to display logout link. This is easy for me with core php. I want something similar like the one below.</p> <pre><code>&lt;?php if(isset($_SESSION['id'])){ ?&gt; &lt;a href=&quot;index.php&quot;&gt;Home&lt;/a&gt; &lt;a href=&quot;dashboard.php&quot;&gt;Dashboard&lt;/a&gt; &lt;a href=&quot;logout.php&quot;&gt;Logout&lt;/a&gt; &lt;?php }else{ ?&gt; &lt;a href=&quot;index.php&quot;&gt;Home&lt;/a&gt; &lt;a href=&quot;register.php&quot;&gt;Register&lt;/a&gt; &lt;a href=&quot;login&quot;&gt;Login&lt;/a&gt; &lt;?php } ?&gt; </code></pre>
[ { "answer_id": 74397128, "author": "Cooper", "author_id": 7215091, "author_profile": "https://Stackoverflow.com/users/7215091", "pm_score": 0, "selected": false, "text": "function funx() {\n var ss = SpreadsheetApp.openById('xxx');\n var sheet = ss.getSheetByName('Data');\n var list = sheet.getRange(3, 5, sheet.getLastRow() - 2).getValues();// third parameter is the number of rows in the range not the last row in the range\n var additionalList = sheet.getRange(3, 3, sheet.getLastRow() - 2, 2).getValues();\n for (var i = 0; i < list.length; i++) {\n let datex = new Date(additionalList[i][0]);\n let date = getFDate(datex)\n }\n}\n" }, { "answer_id": 74397341, "author": "Filippo", "author_id": 3818716, "author_profile": "https://Stackoverflow.com/users/3818716", "pm_score": 2, "selected": true, "text": "Logger.log(\"DETECTED A CHANGE. Due Date changed by someone else: \"+data[\"issues\"][0].changelog[\"histories\"][id].displayName+\" on date: \"+getFDate(data[\"issues\"][0].changelog[\"histories\"][id].created));\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3239115/" ]
74,397,119
<p>I have the following strings:</p> <pre><code>x &lt;- &quot;??????????DRHRTRHLAK??????????&quot; x2 &lt;- &quot;????????????????????TRCYHIDPHH&quot; x3 &lt;- &quot;FKDHKHIDVK????????????????????TRCYHIDPHH&quot; x4 &lt;- &quot;FKDHKHIDVK????????????????????&quot; </code></pre> <p>What I want to do is to replace all the <code>?</code> characters with another string</p> <pre><code>rep &lt;- &quot;ndqeegillkkkkfpssyvv&quot; </code></pre> <p>Resulting in:</p> <pre><code>ndqeegillkDRHRTRHLAKkkkfpssyvv # x ndqeegillkkkkfpssyvvTRCYHIDPHH # x2 FKDHKHIDVKndqeegillkkkkfpssyvvTRCYHIDPHH # x3 FKDHKHIDVKndqeegillkkkkfpssyvv # x4 </code></pre> <p>Basically, keeping the order of <code>rep</code> in the replacement with the interleaving characters <code>DRHRTRHLAK</code> in <code>x</code>.</p> <p>The total length of <code>rep</code> is the same as the total length of <code>?</code>, 20 characters.</p> <p>Note that I don't want to split <code>rep</code> manually again as an extra step.</p> <p>I tried this but failed:</p> <pre><code>&gt;gsub(pattern = &quot;\\?+&quot;, replacement = rep, x = x) [1] &quot;ndqeegillkkkkfpssyvvDRHRTRHLAKndqeegillkkkkfpssyvv&quot; </code></pre>
[ { "answer_id": 74397167, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 1, "selected": false, "text": "substr()" }, { "answer_id": 74397182, "author": "Ricardo Semião e Castro", "author_id": 13048728, "author_profile": "https://Stackoverflow.com/users/13048728", "pm_score": 1, "selected": false, "text": "rep" }, { "answer_id": 74397370, "author": "thelatemail", "author_id": 496803, "author_profile": "https://Stackoverflow.com/users/496803", "pm_score": 3, "selected": true, "text": "x <- c(\n \"??????????DRHRTRHLAK??????????\",\n \"????????????????????TRCYHIDPHH\",\n \"FKDHKHIDVK????????????????????TRCYHIDPHH\"\n)\nrep <- \"ndqeegillkkkkfpssyvv\"\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8391698/" ]
74,397,123
<p>How can I join all the lines?</p> <p>Desired output:</p> <pre><code>$ echo 'one\ntwo' | tr '\n' '' onetwo </code></pre> <p>Actual output:</p> <pre><code>tr: empty string2 </code></pre> <p>I have also tried <code>paste -sd '' -</code> but get</p> <pre><code>paste: no delimiters specified </code></pre> <p>also <code>sed</code></p> <pre><code>$ echo 'one\ntwo' | sed 's/\n//' one two </code></pre>
[ { "answer_id": 74397158, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 3, "selected": true, "text": "tr" }, { "answer_id": 74397162, "author": "theonlygusti", "author_id": 3310334, "author_profile": "https://Stackoverflow.com/users/3310334", "pm_score": 0, "selected": false, "text": "$ echo 'one\\ntwo' | perl -p -e 's/\\n//'\nonetwo \n" }, { "answer_id": 74398103, "author": "oguz ismail", "author_id": 10248678, "author_profile": "https://Stackoverflow.com/users/10248678", "pm_score": 2, "selected": false, "text": "paste -sd '\\0' -\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3310334/" ]
74,397,175
<p>I have an array of extensions and an array of file names:</p> <pre class="lang-rb prettyprint-override"><code>exts = ['.zip', '.tgz', '.sql'] files = ['file1.txt', 'file2.doc', 'file2.tgz', 'file3.sql', 'file6.foo', 'file4.zip'] </code></pre> <p>I want to filter the file names by one or more matching extensions. In this case, the result would be:</p> <pre class="lang-rb prettyprint-override"><code>[&quot;file1.zip&quot;, &quot;file2.tgz&quot;, &quot;file3.sql&quot;, &quot;file4.zip&quot;] </code></pre> <p>I know I can do this with a nested loop:</p> <pre class="lang-rb prettyprint-override"><code>exts.each_with_object([]) do |ext, arr| files.each do |file| arr &lt;&lt; entry if file.include?(ext) end end </code></pre> <p>This feels ugly to me. With select, I can avoid the feeling of nested loops:</p> <pre class="lang-rb prettyprint-override"><code>files.select { |file| exts.each { |ext| file.include?(ext) } } </code></pre> <p>This works and feels better. Is there still a more elegant way that I'm missing?</p>
[ { "answer_id": 74397539, "author": "Steve K", "author_id": 125965, "author_profile": "https://Stackoverflow.com/users/125965", "pm_score": 0, "selected": false, "text": "select" }, { "answer_id": 74398388, "author": "spickermann", "author_id": 2483313, "author_profile": "https://Stackoverflow.com/users/2483313", "pm_score": 2, "selected": false, "text": "Enumerable#grep" }, { "answer_id": 74403063, "author": "Sergio Tulentsev", "author_id": 125816, "author_profile": "https://Stackoverflow.com/users/125816", "pm_score": 0, "selected": false, "text": "exts = ['.zip', '.tgz', '.sql'].to_set\nfiles.select { |file| exts.include?(File.extname(file)) }\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125965/" ]
74,397,224
<p>I'm looking for solution - group array of objects by value based on matched pattern of other array value.</p> <p>have sample array</p> <pre><code>data = [ { &quot;Application&quot;: &quot;Chrome - 567&quot; }, { &quot;Application&quot;: &quot;File Transfer Protocol - 45&quot; }, { &quot;Application&quot;: &quot;Google APIs - 3618&quot; }, { &quot;Application&quot;: &quot;Google Generic - 943&quot; }, { &quot;Application&quot;: &quot;Google Search - 54&quot; }, { &quot;Application&quot;: &quot;Microsoft - 2821&quot; }, { &quot;Application&quot;: &quot;Microsoft DFSR (Distributed File System Replication) - 3722&quot; }, { &quot;Application&quot;: &quot;Microsoft Remote Procedure Call - 742&quot; }, { &quot;Application&quot;: &quot;Telegram- 2235&quot; }, { &quot;Application&quot;: &quot;Facebook Videos - 2250&quot; }, { &quot;Application&quot;: &quot;Facebook - 690&quot; } ] </code></pre> <blockquote> <p>Other array</p> </blockquote> <pre><code>var Appdata = [Google, Facebook, Instagram, Microsoft, Telegram] </code></pre> <blockquote> <p>expected result</p> </blockquote> <pre><code>result = [ { &quot;Application&quot;: &quot;Chrome - 567&quot; }, { &quot;Application&quot;: &quot;File Transfer Protocol - 45&quot; }, { &quot;Application&quot;: &quot;Google&quot; }, { &quot;Application&quot;: &quot;Microsoft&quot; }, { &quot;Application&quot;: &quot;Telegram&quot; }, { &quot;Application&quot;: &quot;Facebook&quot; } ] </code></pre> <p>there are two separate array <code>data</code> and <code>Appdata</code> in <code>data</code> array if we match the string of <code>Appdata</code> array then it should replace with <code>Appdata</code> array value in original <code>data</code> array</p> <p>kindly helps to find the solution for this array.</p>
[ { "answer_id": 74397377, "author": "Rocky Sims", "author_id": 4123400, "author_profile": "https://Stackoverflow.com/users/4123400", "pm_score": 0, "selected": false, "text": "const data = [\n {\"Application\": \"Chrome - 567\"},\n {\"Application\": \"File Transfer Protocol - 45\"},\n {\"Application\": \"Google APIs - 3618\"},\n {\"Application\": \"Google Generic - 943\"},\n {\"Application\": \"Google Search - 54\"},\n {\"Application\": \"Microsoft - 2821\"},\n {\"Application\": \"Microsoft DFSR (Distributed File System Replication) - 3722\"},\n {\"Application\": \"Microsoft Remote Procedure Call - 742\"},\n {\"Application\": \"Telegram- 2235\"},\n {\"Application\": \"Facebook Videos - 2250\"},\n {\"Application\": \"Facebook - 690\"}\n];\nconst appData = ['Google', 'Facebook', 'Instagram', 'Microsoft', 'Telegram'];\n\nfor (let datum of data) {\n let appStr = datum.Application;\n for (let appDatum of appData) {\n if (appStr.includes(appDatum)) {\n datum.Application = appDatum;\n break;\n }\n }\n}\n\nconst foundByAppStr = {};\nconst dataWithoutRepeats = data.filter(datum => {\n const appStr = datum.Application;\n const keep = !foundByAppStr[appStr];\n foundByAppStr[appStr] = true;\n return keep;\n});\n\nconsole.log(dataWithoutRepeats);" }, { "answer_id": 74397524, "author": "Layhout", "author_id": 17308201, "author_profile": "https://Stackoverflow.com/users/17308201", "pm_score": -1, "selected": false, "text": "const data = [\n {\n \"Application\": \"Chrome - 567\"\n },\n {\n \"Application\": \"File Transfer Protocol - 45\"\n },\n {\n \"Application\": \"Google APIs - 3618\"\n },\n {\n \"Application\": \"Google Generic - 943\"\n },\n {\n \"Application\": \"Google Search - 54\"\n },\n {\n \"Application\": \"Microsoft - 2821\"\n },\n {\n \"Application\": \"Microsoft DFSR (Distributed File System Replication) - 3722\"\n },\n {\n \"Application\": \"Microsoft Remote Procedure Call - 742\"\n },\n {\n \"Application\": \"Telegram- 2235\"\n },\n {\n \"Application\": \"Facebook Videos - 2250\"\n },\n {\n \"Application\": \"Facebook - 690\"\n }\n]\n\nconst Appdata = [\"Google\", \"Facebook\", \"Instagram\", \"Microsoft\", \"Telegram\"];\n\nconst result = [...new Set(data.reduce((p, c) => {\n const found = Appdata.find(a => c.Application.includes(a));\n found !== undefined ? p.push(found) : p.push(c.Application);\n return p\n}, []))].map(r => ({ Application: r }));\n\nconsole.log(result);" }, { "answer_id": 74397619, "author": "m0squito", "author_id": 14311762, "author_profile": "https://Stackoverflow.com/users/14311762", "pm_score": -1, "selected": false, "text": "const data = [{\n \"Application\": \"Chrome - 567\"\n }, \n {\n \"Application\": \"File Transfer Protocol - 45\"\n },\n {\n \"Application\": \"Google APIs - 3618\"\n },\n {\n \"Application\": \"Google Generic - 943\"\n },\n {\n \"Application\": \"Google Search - 54\"\n }, \n {\n \"Application\": \"Microsoft - 2821\"\n },\n {\n \"Application\": \"Microsoft DFSR (Distributed File System Replication) - 3722\"\n },\n {\n \"Application\": \"Microsoft Remote Procedure Call - 742\"\n }, \n {\n \"Application\": \"Telegram- 2235\"\n }, \n {\n \"Application\": \"Facebook Videos - 2250\"\n },\n {\n \"Application\": \"Facebook - 690\"\n }\n];\nconst appData = ['Google', 'Facebook', 'Instagram', 'Microsoft', 'Telegram'];\n\nconst result = data.map(dataEntry => {\n const found = appData.find(it => dataEntry.Application.includes(it))\n if(found){\n dataEntry.Application = found\n return dataEntry\n } else return dataEntry\n})\nconst filtered = result.reduce((acc, current) => {\n if(!acc.find(data => data.Application === current.Application))\n return acc.concat([current])\n else return acc\n}, [])\n\nconsole.log(filtered);" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6333900/" ]
74,397,250
<p>I made very little changes to an App working properly before. And I tried to run it and got <code>Can not extract resource from com.android.aaptcompiler.ParsedResource@16fe6971.</code> error.</p> <p>I have no idea what is wrong, I did some search and found out it might be I needed to add <code>/</code> before every <code>'</code> in strings.xml, and I did, but I still get the error, please what's the cause and how do I fix it??</p> <p>Here's the Build Output error message;</p> <pre><code>FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:mergeDebugResources'. &gt; A failure occurred while executing com.android.build.gradle.internal.res.ResourceCompilerRunnable &gt; Resource compilation failed (Failed to compile values resource file C:\Users\asuma\OneDrive\Desktop\Compose,PlayStoreProjects\Think_Healthy\Keto2.0\app\build\intermediates\incremental\debug\mergeDebugResources\merged.dir\values\values.xml. Cause: java.lang.IllegalStateException: Can not extract resource from com.android.aaptcompiler.ParsedResource@16fe6971.). Check logs for more details. * Try: &gt; Run with --info or --debug option to get more log output. &gt; Run with --scan to get full insights. * Exception is: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:mergeDebugResources'. at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.lambda$executeIfValid$1(ExecuteActionsTaskExecuter.java:145) at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:282) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:143) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:131) at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:77) at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46) at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:51) at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57) at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56) at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52) at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204) at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:199) at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66) at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59) at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:53) at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:73) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52) at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:74) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:402) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:389) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:382) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:368) at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.lambda$run$0(DefaultPlanExecutor.java:127) at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:191) at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:182) at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:124) at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64) at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48) at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:61) Caused by: org.gradle.workers.internal.DefaultWorkerExecutor$WorkExecutionException: A failure occurred while executing com.android.build.gradle.internal.res.ResourceCompilerRunnable at org.gradle.workers.internal.DefaultWorkerExecutor$WorkItemExecution.waitForCompletion(DefaultWorkerExecutor.java:342) at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForItemsAndGatherFailures(DefaultAsyncWorkTracker.java:142) at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForItemsAndGatherFailures(DefaultAsyncWorkTracker.java:94) at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForAll(DefaultAsyncWorkTracker.java:80) at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForCompletion(DefaultAsyncWorkTracker.java:68) at org.gradle.api.internal.tasks.execution.TaskExecution$2.run(TaskExecution.java:247) at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:29) at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:26) at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66) at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59) at org.gradle.internal.operations.DefaultBuildOperationRunner.run(DefaultBuildOperationRunner.java:47) at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:68) at org.gradle.api.internal.tasks.execution.TaskExecution.executeAction(TaskExecution.java:224) at org.gradle.api.internal.tasks.execution.TaskExecution.executeActions(TaskExecution.java:207) at org.gradle.api.internal.tasks.execution.TaskExecution.executeWithPreviousOutputFiles(TaskExecution.java:190) at org.gradle.api.internal.tasks.execution.TaskExecution.execute(TaskExecution.java:168) at org.gradle.internal.execution.steps.ExecuteStep.executeInternal(ExecuteStep.java:89) at org.gradle.internal.execution.steps.ExecuteStep.access$000(ExecuteStep.java:40) at org.gradle.internal.execution.steps.ExecuteStep$1.call(ExecuteStep.java:53) at org.gradle.internal.execution.steps.ExecuteStep$1.call(ExecuteStep.java:50) at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204) at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:199) at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66) at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59) at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:53) at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:73) at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:50) at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:40) at org.gradle.internal.execution.steps.RemovePreviousOutputsStep.execute(RemovePreviousOutputsStep.java:68) at org.gradle.internal.execution.steps.RemovePreviousOutputsStep.execute(RemovePreviousOutputsStep.java:38) at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:48) at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:36) at org.gradle.internal.execution.steps.CancelExecutionStep.execute(CancelExecutionStep.java:41) at org.gradle.internal.execution.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:74) at org.gradle.internal.execution.steps.TimeoutStep.execute(TimeoutStep.java:55) at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:51) at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:29) at org.gradle.internal.execution.steps.CaptureStateAfterExecutionStep.execute(CaptureStateAfterExecutionStep.java:61) at org.gradle.internal.execution.steps.CaptureStateAfterExecutionStep.execute(CaptureStateAfterExecutionStep.java:42) at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:60) at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:27) at org.gradle.internal.execution.steps.BuildCacheStep.executeWithoutCache(BuildCacheStep.java:188) at org.gradle.internal.execution.steps.BuildCacheStep.lambda$execute$1(BuildCacheStep.java:75) at org.gradle.internal.Either$Right.fold(Either.java:175) at org.gradle.internal.execution.caching.CachingState.fold(CachingState.java:59) at org.gradle.internal.execution.steps.BuildCacheStep.execute(BuildCacheStep.java:73) at org.gradle.internal.execution.steps.BuildCacheStep.execute(BuildCacheStep.java:48) at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:38) at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:27) at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:36) at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:22) at org.gradle.internal.execution.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:109) at org.gradle.internal.execution.steps.SkipUpToDateStep.lambda$execute$2(SkipUpToDateStep.java:56) at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:56) at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:38) at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:73) at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:44) at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:37) at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:27) at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:89) at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:50) at org.gradle.internal.execution.steps.ValidateStep.execute(ValidateStep.java:114) at org.gradle.internal.execution.steps.ValidateStep.execute(ValidateStep.java:57) at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:76) at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:50) at org.gradle.internal.execution.steps.SkipEmptyWorkStep.lambda$execute$2(SkipEmptyWorkStep.java:93) at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:93) at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:34) at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsStartedStep.execute(MarkSnapshottingInputsStartedStep.java:38) at org.gradle.internal.execution.steps.LoadPreviousExecutionStateStep.execute(LoadPreviousExecutionStateStep.java:43) at org.gradle.internal.execution.steps.LoadPreviousExecutionStateStep.execute(LoadPreviousExecutionStateStep.java:31) at org.gradle.internal.execution.steps.AssignWorkspaceStep.lambda$execute$0(AssignWorkspaceStep.java:40) at org.gradle.api.internal.tasks.execution.TaskExecution$3.withWorkspace(TaskExecution.java:284) at org.gradle.internal.execution.steps.AssignWorkspaceStep.execute(AssignWorkspaceStep.java:40) at org.gradle.internal.execution.steps.AssignWorkspaceStep.execute(AssignWorkspaceStep.java:30) at org.gradle.internal.execution.steps.IdentityCacheStep.execute(IdentityCacheStep.java:37) at org.gradle.internal.execution.steps.IdentityCacheStep.execute(IdentityCacheStep.java:27) at org.gradle.internal.execution.steps.IdentifyStep.execute(IdentifyStep.java:44) at org.gradle.internal.execution.steps.IdentifyStep.execute(IdentifyStep.java:33) at org.gradle.internal.execution.impl.DefaultExecutionEngine$1.execute(DefaultExecutionEngine.java:76) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:142) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:131) at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:77) at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46) at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:51) at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57) at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56) at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52) at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204) at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:199) at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66) at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59) at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:53) at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:73) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52) at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:74) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:402) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:389) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:382) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:368) at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.lambda$run$0(DefaultPlanExecutor.java:127) at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:191) at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:182) at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:124) at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64) at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48) at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:61) Caused by: com.android.aaptcompiler.ResourceCompilationException: Resource compilation failed (Failed to compile values resource file C:\Users\asuma\OneDrive\Desktop\Compose,PlayStoreProjects\Think_Healthy\Keto2.0\app\build\intermediates\incremental\debug\mergeDebugResources\merged.dir\values\values.xml. Cause: java.lang.IllegalStateException: Can not extract resource from com.android.aaptcompiler.ParsedResource@16fe6971.). Check logs for more details. at com.android.aaptcompiler.ResourceCompiler.compileResource(ResourceCompiler.kt:129) at com.android.build.gradle.internal.res.ResourceCompilerRunnable$Companion.compileSingleResource(ResourceCompilerRunnable.kt:34) at com.android.build.gradle.internal.res.ResourceCompilerRunnable.run(ResourceCompilerRunnable.kt:15) at com.android.build.gradle.internal.profile.ProfileAwareWorkAction.execute(ProfileAwareWorkAction.kt:74) at org.gradle.workers.internal.DefaultWorkerServer.execute(DefaultWorkerServer.java:63) at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.create(NoIsolationWorkerFactory.java:66) at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.create(NoIsolationWorkerFactory.java:62) at org.gradle.internal.classloader.ClassLoaderUtils.executeInClassloader(ClassLoaderUtils.java:97) at org.gradle.workers.internal.NoIsolationWorkerFactory$1.lambda$execute$0(NoIsolationWorkerFactory.java:62) at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:44) at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:41) at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204) at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:199) at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66) at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59) at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:53) at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:73) at org.gradle.workers.internal.AbstractWorker.executeWrappedInBuildOperation(AbstractWorker.java:41) at org.gradle.workers.internal.NoIsolationWorkerFactory$1.execute(NoIsolationWorkerFactory.java:59) at org.gradle.workers.internal.DefaultWorkerExecutor.lambda$submitWork$2(DefaultWorkerExecutor.java:206) at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runExecution(DefaultConditionalExecutionQueue.java:214) at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runBatch(DefaultConditionalExecutionQueue.java:164) at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.run(DefaultConditionalExecutionQueue.java:131) ... 3 more Caused by: com.android.aaptcompiler.ResourceCompilationException: Failed to compile values resource file C:\Users\asuma\OneDrive\Desktop\Compose,PlayStoreProjects\Think_Healthy\Keto2.0\app\build\intermediates\incremental\debug\mergeDebugResources\merged.dir\values\values.xml at com.android.aaptcompiler.ResourceCompiler.compileTable(ResourceCompiler.kt:192) at com.android.aaptcompiler.ResourceCompiler.access$compileTable(ResourceCompiler.kt:1) at com.android.aaptcompiler.ResourceCompiler$getCompileMethod$1.invoke(ResourceCompiler.kt:138) at com.android.aaptcompiler.ResourceCompiler$getCompileMethod$1.invoke(ResourceCompiler.kt:138) at com.android.aaptcompiler.ResourceCompiler.compileResource(ResourceCompiler.kt:123) ... 27 more Caused by: java.lang.IllegalStateException: Can not extract resource from com.android.aaptcompiler.ParsedResource@16fe6971. at com.android.aaptcompiler.TableExtractor.extractResourceValues(TableExtractor.kt:270) at com.android.aaptcompiler.TableExtractor.extract(TableExtractor.kt:181) at com.android.aaptcompiler.ResourceCompiler.compileTable(ResourceCompiler.kt:188) ... 31 more * Get more help at https://help.gradle.org BUILD FAILED in 39s 23 actionable tasks: 1 executed, 22 up-to-date </code></pre> <p>And Here's Logcat error message;</p> <pre><code>E FATAL EXCEPTION: main Process: com.think_healthy.keto, PID: 22211 java.lang.NoSuchMethodError: No static method SuccessScreen(Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function1;Landroidx/compose/runtime/Composer;I)V in class Lcom/think_healthy/keto/ui/screens/success/SuccessScreenKt; or its super classes (declaration of 'com.think_healthy.keto.ui.screens.success.SuccessScreenKt' appears in /data/app/com.think_healthy.keto-CU0UjuIPk-d0iGfocS1y_w==/base.apk!classes7.dex) at com.think_healthy.keto.KetoNavHostKt$KetoNavHost$1$2.invoke(KetoNavHost.kt:70) at com.think_healthy.keto.KetoNavHostKt$KetoNavHost$1$2.invoke(KetoNavHost.kt:69) </code></pre>
[ { "answer_id": 74485573, "author": "Edwin", "author_id": 15976878, "author_profile": "https://Stackoverflow.com/users/15976878", "pm_score": 3, "selected": true, "text": "'" }, { "answer_id": 74573658, "author": "Yohanes Getient", "author_id": 16583898, "author_profile": "https://Stackoverflow.com/users/16583898", "pm_score": 2, "selected": false, "text": "<color name=\"purple_500\">##FF6200EE</color>" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15976878/" ]
74,397,254
<p>Maybe without using <code>as</code>: How can I</p> <pre><code>type F = 'a' | 'b' | 'c' type R = '11' | '22' | '33' type P = `${F}${R}` const p: P = `a11` // is there a better way to parse this string? function getFR(p: P): [F, R] { return [p[0] as F, p.slice(1) as R] } console.log(getFR(p)) </code></pre>
[ { "answer_id": 74485573, "author": "Edwin", "author_id": 15976878, "author_profile": "https://Stackoverflow.com/users/15976878", "pm_score": 3, "selected": true, "text": "'" }, { "answer_id": 74573658, "author": "Yohanes Getient", "author_id": 16583898, "author_profile": "https://Stackoverflow.com/users/16583898", "pm_score": 2, "selected": false, "text": "<color name=\"purple_500\">##FF6200EE</color>" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3994249/" ]
74,397,270
<p>So I'm having trouble with writing this Cipher Function in one line. I've tried using the result methods with the if and else statements. For instance I know that the I need to do the else statement first before the if statement buts I could be wrong. So I'm trying to figure this out. How would I write this function in 1 return statement?</p> <pre><code>def cipher(self): string = &quot;&quot; for i in self.string: if i.isalpha(): if i.isupper(): alphabet = (ord(i) - 65 + len(self.string)) % (26) alphabet += 65 if i.islower(): alphabet = (ord(i) - 97 + len(self.string)) % (26) alphabet += 97 letter = chr(alphabet) else: letter = i string += letter return string </code></pre> <p>return string I've tried multiple times but it would always show an error</p>
[ { "answer_id": 74397346, "author": "Alexander", "author_id": 17829451, "author_profile": "https://Stackoverflow.com/users/17829451", "pm_score": 0, "selected": false, "text": "text = \"Hello World\"\ndef cipher(text):\n return ''.join(\n [i if not i.isalpha() else\n chr((((ord(i) - 65 + len(text)) % 26) + 65)\n if i.isupper() else\n (((ord(i)-97 + len(text)) %26) +97))\n for i in text])\ncipher(text)\n" }, { "answer_id": 74397350, "author": "Michael Delgado", "author_id": 3888719, "author_profile": "https://Stackoverflow.com/users/3888719", "pm_score": 2, "selected": true, "text": "In [7]: string = \"hello my #1 person!\"\n\nIn [8]: ''.join([(chr((ord(i) - (65 if i.isupper() else 97) + len(string)) % (26) + (65 if i.isupper() else 97)) if i.isalpha() else i) for i in string])\nOut[8]: 'axeeh fr #1 ixklhg!'\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20473802/" ]
74,397,272
<p>I would like to know how would I use python to join certain lines in a large text file, that come after a certain string. For example my file is:</p> <pre><code>ID 1 ABCDE FGHIJ KLMNO ID 2 ABCDE FGHIJ ID 3 ABCDE FGHIJ KLMNO PQRST </code></pre> <p>And I would like to join the lines following each “ID”, but the number of lines after each varies. So I’d like my file to be</p> <pre><code>ID 1 ABCDEFGHIJKLMNO ID 2 ABCDEFGHIJ ID 3 ABCDEFGHIJKLMNOPQRST </code></pre> <p>The actual file has thousands of “ID” lines, so I’d like to find out how to identify the pattern to use.</p> <p>I have not tried anything yet. I’m not sure where to start.</p>
[ { "answer_id": 74397328, "author": "AVManerikar", "author_id": 16744609, "author_profile": "https://Stackoverflow.com/users/16744609", "pm_score": -1, "selected": false, "text": "data = f.readlines()\nout = []\ncurr_cat_line = ''\n\nfor line in data:\n if line.find('ID')!=-1:\n out.append(line)\n if curr_cat_line !='': out.append(curr_cat_line)\n curr_cat_line = ''\n curr_cat_line = curr_cat_line + line\n" }, { "answer_id": 74397353, "author": "Ben Grossmann", "author_id": 2476977, "author_profile": "https://Stackoverflow.com/users/2476977", "pm_score": 0, "selected": false, "text": "results = []\ncurrent = []\nids = []\n\nwith open(\"test.txt\",'r') as f:\n for line in f:\n if line[:2] == 'ID':\n ids.append(line)\n results.append(''.join(current) + '\\n')\n current = []\n else:\n current.append(line.strip())\nresults.append(''.join(current))\n" }, { "answer_id": 74397439, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 0, "selected": false, "text": "re.sub" }, { "answer_id": 74397493, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 0, "selected": false, "text": "itertools.groupby" }, { "answer_id": 74397641, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 0, "selected": false, "text": "'ID '" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20473708/" ]
74,397,278
<p>I am trying to get a simple react app (create react app) with react-router-dom to work inside a WordPress site using the ReactPress plugin.</p> <p>Taking code straight from the ReactPress documentation, I have the React app working on localhost, but cannot get the routing to work within Wordpress.</p> <p>I have tried everything I've been able to find on the web -- fiddling with .htaccess, adding actions to stop WordPress routing, adding &quot;homepage&quot; to package.json, clearing the permalink cache, etc, but nothing has worked.</p> <p>The pages render fine if I place it straight in the App function. But when they are in Routes/Route, it stops working.</p> <p>I don't get any errors in production; I just get an empty div where the pages should render and a noscript message like below:</p> <p>Inspecting WordPress site:</p> <pre><code> &lt;noscript&gt;You need to enable JavaScript to run this app.&lt;/noscript&gt; &lt;div id=&quot;root&quot;&gt; &lt;div class=&quot;App&quot;&gt; &lt;h1 id=&quot;root&quot;&gt;Welcome to ReactPress with React Router!!!&lt;/h1&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Any ideas what is wrong?</p> <p>index.js</p> <pre><code>import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; import { BrowserRouter } from 'react-router-dom'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( &lt;React.StrictMode&gt; &lt;BrowserRouter&gt; &lt;App /&gt; &lt;/BrowserRouter&gt; &lt;/React.StrictMode&gt; ); </code></pre> <p>App.js</p> <pre><code>import React, { Component } from 'react'; import { Routes, Route, Link } from 'react-router-dom'; function Home() { return ( &lt;&gt; &lt;main&gt; &lt;h2&gt;Welcome to the homepage!&lt;/h2&gt; &lt;p&gt;You can do this, I believe in you.&lt;/p&gt; &lt;/main&gt; &lt;nav&gt; &lt;Link to=&quot;/about&quot;&gt;About&lt;/Link&gt; &lt;/nav&gt; &lt;/&gt; ); } function About() { return ( &lt;&gt; &lt;main&gt; &lt;h2&gt;Who are we?&lt;/h2&gt; &lt;p&gt; That feels like an existential question, don't you think? &lt;/p&gt; &lt;/main&gt; &lt;nav&gt; &lt;Link to=&quot;/&quot;&gt;Home&lt;/Link&gt; &lt;/nav&gt; &lt;/&gt; ); } export default function App() { return ( &lt;div className=&quot;App&quot;&gt; &lt;h1&gt;Welcome to ReactPress with React Router!!!&lt;/h1&gt; &lt;Routes&gt; &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt; &lt;Route path=&quot;/about&quot; element={&lt;About /&gt;} /&gt; &lt;/Routes&gt; &lt;/div&gt; ); } </code></pre> <p>package.json</p> <pre><code>{ &quot;name&quot;: &quot;wp-react-test-react&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;private&quot;: true, &quot;dependencies&quot;: { &quot;@reduxjs/toolkit&quot;: &quot;^1.9.0&quot;, &quot;@testing-library/jest-dom&quot;: &quot;^5.16.5&quot;, &quot;@testing-library/react&quot;: &quot;^13.4.0&quot;, &quot;@testing-library/user-event&quot;: &quot;^13.5.0&quot;, &quot;axios&quot;: &quot;^1.1.3&quot;, &quot;lodash&quot;: &quot;^4.17.21&quot;, &quot;react&quot;: &quot;^18.2.0&quot;, &quot;react-dom&quot;: &quot;^18.2.0&quot;, &quot;react-redux&quot;: &quot;^8.0.5&quot;, &quot;react-router-dom&quot;: &quot;^6.4.3&quot;, &quot;react-scripts&quot;: &quot;^5.0.1&quot;, &quot;redux&quot;: &quot;^4.2.0&quot;, &quot;web-vitals&quot;: &quot;^2.1.4&quot; }, &quot;scripts&quot;: { &quot;start&quot;: &quot;react-scripts start&quot;, &quot;build&quot;: &quot;PUBLIC_URL=/wp-content/reactpress/apps/wp-react-test-react/build react-scripts build&quot;, &quot;test&quot;: &quot;react-scripts test&quot;, &quot;eject&quot;: &quot;react-scripts eject&quot; }, &quot;eslintConfig&quot;: { &quot;extends&quot;: [ &quot;react-app&quot;, &quot;react-app/jest&quot; ] }, &quot;browserslist&quot;: { &quot;production&quot;: [ &quot;&gt;0.2%&quot;, &quot;not dead&quot;, &quot;not op_mini all&quot; ], &quot;development&quot;: [ &quot;last 1 chrome version&quot;, &quot;last 1 firefox version&quot;, &quot;last 1 safari version&quot; ] } } </code></pre>
[ { "answer_id": 74397328, "author": "AVManerikar", "author_id": 16744609, "author_profile": "https://Stackoverflow.com/users/16744609", "pm_score": -1, "selected": false, "text": "data = f.readlines()\nout = []\ncurr_cat_line = ''\n\nfor line in data:\n if line.find('ID')!=-1:\n out.append(line)\n if curr_cat_line !='': out.append(curr_cat_line)\n curr_cat_line = ''\n curr_cat_line = curr_cat_line + line\n" }, { "answer_id": 74397353, "author": "Ben Grossmann", "author_id": 2476977, "author_profile": "https://Stackoverflow.com/users/2476977", "pm_score": 0, "selected": false, "text": "results = []\ncurrent = []\nids = []\n\nwith open(\"test.txt\",'r') as f:\n for line in f:\n if line[:2] == 'ID':\n ids.append(line)\n results.append(''.join(current) + '\\n')\n current = []\n else:\n current.append(line.strip())\nresults.append(''.join(current))\n" }, { "answer_id": 74397439, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 0, "selected": false, "text": "re.sub" }, { "answer_id": 74397493, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 0, "selected": false, "text": "itertools.groupby" }, { "answer_id": 74397641, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 0, "selected": false, "text": "'ID '" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8521990/" ]
74,397,307
<p>Holla!</p> <p>I have a list of 60 large-size 2d arrays (30000,30000).</p> <p>The goal is to compare each array with every other array and count the total number of exactly the same arrays in the entire list.</p> <p>I am working on this logic, however, it is counting the number of same arrays individually and not what I want:</p> <pre><code>import numpy as np import pandas as pd import scipy.sparse as sp ## I am using this dummy setup, to begin with (rather than the large data) # creating 4 dummy arrays a = np.zeros((6,6)) a[1,2] = 1 a[2,5] = 1 a[3,2] = 1 a[4,1] = 1 print(a) b = np.zeros((6,6)) b[1,2] = 1 b[2,5] = 1 b[3,2] = 1 b[4,1] = 1 c = np.zeros((6,6)) c[1,3] = 1 c[2,5] = 1 d = np.zeros((6,6)) d[1,3] = 1 d[2,4] = 1 # storing the arrays in a list list2d = [a,b,c,d] #loop through the list to count the number of arrays with exactly same values n = len(list2d) for i in range(n): count = 0 for j in range(n): if (list2d[i] == list2d[j]).all() and i != j: count += 1 print('list2d[',i,'] is the same as list2d[',j,']') else: print('list2d[',i,'] is not the same as list2d[',j,']') print('total number of same arrays || count = ',count) </code></pre> <p>Another option is working with sparse matrices and storing them in a list. However, I'm not sure whether we can compare or check for equity on the entire list with 60 sparse arrays.</p> <pre><code># again finalizing a logic on a dummy setup a_sparse = sp.csr_matrix(a) b_sparse = sp.csr_matrix(b) c_sparse = sp.csr_matrix(c) d_sparse = sp.csr_matrix(d) print(a_sparse) # #list of sparse matrices list_sparse = [a_sparse,b_sparse,c_sparse,d_sparse] ## compare the list of sparse arrays and count the total number of exactly same arrays ## also, print/ store all the equal arrays </code></pre> <p>Any suggestions and/or feedback for getting the correct logic is appreciated. Cheers!</p>
[ { "answer_id": 74397328, "author": "AVManerikar", "author_id": 16744609, "author_profile": "https://Stackoverflow.com/users/16744609", "pm_score": -1, "selected": false, "text": "data = f.readlines()\nout = []\ncurr_cat_line = ''\n\nfor line in data:\n if line.find('ID')!=-1:\n out.append(line)\n if curr_cat_line !='': out.append(curr_cat_line)\n curr_cat_line = ''\n curr_cat_line = curr_cat_line + line\n" }, { "answer_id": 74397353, "author": "Ben Grossmann", "author_id": 2476977, "author_profile": "https://Stackoverflow.com/users/2476977", "pm_score": 0, "selected": false, "text": "results = []\ncurrent = []\nids = []\n\nwith open(\"test.txt\",'r') as f:\n for line in f:\n if line[:2] == 'ID':\n ids.append(line)\n results.append(''.join(current) + '\\n')\n current = []\n else:\n current.append(line.strip())\nresults.append(''.join(current))\n" }, { "answer_id": 74397439, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 0, "selected": false, "text": "re.sub" }, { "answer_id": 74397493, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 0, "selected": false, "text": "itertools.groupby" }, { "answer_id": 74397641, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 0, "selected": false, "text": "'ID '" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19259213/" ]
74,397,312
<p>I get data from access database but they are not in column order.</p> <p><a href="https://i.stack.imgur.com/zndvf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zndvf.png" alt="enter image description here" /></a><a href="https://i.stack.imgur.com/Avw44.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Avw44.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/Wwcvm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wwcvm.png" alt="enter image description here" /></a></p> <p>I tried to put them in the order 1,2,3,4,5 and they are messed up, I have to fix like the picture above to display properly.</p> <p>I really don't understand why.</p>
[ { "answer_id": 74397328, "author": "AVManerikar", "author_id": 16744609, "author_profile": "https://Stackoverflow.com/users/16744609", "pm_score": -1, "selected": false, "text": "data = f.readlines()\nout = []\ncurr_cat_line = ''\n\nfor line in data:\n if line.find('ID')!=-1:\n out.append(line)\n if curr_cat_line !='': out.append(curr_cat_line)\n curr_cat_line = ''\n curr_cat_line = curr_cat_line + line\n" }, { "answer_id": 74397353, "author": "Ben Grossmann", "author_id": 2476977, "author_profile": "https://Stackoverflow.com/users/2476977", "pm_score": 0, "selected": false, "text": "results = []\ncurrent = []\nids = []\n\nwith open(\"test.txt\",'r') as f:\n for line in f:\n if line[:2] == 'ID':\n ids.append(line)\n results.append(''.join(current) + '\\n')\n current = []\n else:\n current.append(line.strip())\nresults.append(''.join(current))\n" }, { "answer_id": 74397439, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 0, "selected": false, "text": "re.sub" }, { "answer_id": 74397493, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 0, "selected": false, "text": "itertools.groupby" }, { "answer_id": 74397641, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 0, "selected": false, "text": "'ID '" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20473826/" ]
74,397,333
<pre><code>#include&lt;stdio.h&gt; #include&lt;string.h&gt; #define ROWS 6 #define LENGTH 30 int main (void) { int wordcount[ROWS]; // Incraments word count. i.e. Word 1, Word 2, Word 3... char word[LENGTH]; // Stores users string for(int i = 1; i &lt; ROWS; i++) { if(i == 1) { printf(&quot;Word %d: &quot;, i); scanf(&quot;%d %s&quot;, &amp;wordcount[i], &amp;word[0]); // Input ends here. Prints out the rest of the array with &quot;no&quot; values. i++; } if(i == 2) { printf(&quot;Word %d: &quot;, i); scanf(&quot;%d %s&quot;, &amp;wordcount[i], &amp;word[1]); i++; } if(i == 3) { printf(&quot;Word %d: &quot;, i); scanf(&quot;%d %s&quot;, &amp;wordcount[i], &amp;word[2]); i++; } if(i == 4) { printf(&quot;Word %d: &quot;, i); scanf(&quot;%d %s&quot;, &amp;wordcount[i], &amp;word[3]); i++; } if(i == 5) { printf(&quot;Word %d: &quot;, i); scanf(&quot;%d %s&quot;, &amp;wordcount[i], &amp;word[4]); } break; } return 0; } </code></pre> <p>I've tried multiple loops, changing syntax and placement, but nothing makes sense to me anymore. I AM NOT ALLOWED TO USE POINTERS, GLOBAL VARIABLES, OR ANY OTHER LIB FUNCTIONS BESIDES <code>scanf()</code>, <code>printf()</code>, <code>fgets()</code>, or <code>strlen()</code>. I have to make multiple functions to get user input, reverse the string, and find out whether or not it's a palindrome... but I can't seem to get past part 1.</p>
[ { "answer_id": 74397328, "author": "AVManerikar", "author_id": 16744609, "author_profile": "https://Stackoverflow.com/users/16744609", "pm_score": -1, "selected": false, "text": "data = f.readlines()\nout = []\ncurr_cat_line = ''\n\nfor line in data:\n if line.find('ID')!=-1:\n out.append(line)\n if curr_cat_line !='': out.append(curr_cat_line)\n curr_cat_line = ''\n curr_cat_line = curr_cat_line + line\n" }, { "answer_id": 74397353, "author": "Ben Grossmann", "author_id": 2476977, "author_profile": "https://Stackoverflow.com/users/2476977", "pm_score": 0, "selected": false, "text": "results = []\ncurrent = []\nids = []\n\nwith open(\"test.txt\",'r') as f:\n for line in f:\n if line[:2] == 'ID':\n ids.append(line)\n results.append(''.join(current) + '\\n')\n current = []\n else:\n current.append(line.strip())\nresults.append(''.join(current))\n" }, { "answer_id": 74397439, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 0, "selected": false, "text": "re.sub" }, { "answer_id": 74397493, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 0, "selected": false, "text": "itertools.groupby" }, { "answer_id": 74397641, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 0, "selected": false, "text": "'ID '" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20473803/" ]
74,397,345
<p>I'm trying to convert a BST to an Array.</p> <pre><code>void treeToArr(Node *root, int *ptr, int index) { if (root == NULL) { return; } storeInArray(root-&gt;left,ptr,index); ptr[index++] = root-&gt;value; storeInArray(root-&gt;right,ptr,index); } </code></pre> <p>When running this, I noticed that the index number kept changing, it went from 0 to 1 to 0 to 1 to 2 to 3. I just want it to increase normally [1,2,3,4..]. I'm new to C and i'm unsure why it's doing this.</p> <p>Note that when I call this function, index is 0.</p>
[ { "answer_id": 74397895, "author": "Fe2O3", "author_id": 17592432, "author_profile": "https://Stackoverflow.com/users/17592432", "pm_score": 0, "selected": false, "text": "int index;" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20304864/" ]
74,397,351
<p>I am new to dataweave 2.0 and am trying to use the scan method to extract some text from a string coming back from a http request.</p> <p>I am trying to extract text with the following regex:</p> <pre><code>\\\&quot;(NewLABEL.[a-z]*) </code></pre> <p>This does what i expect in <a href="https://regexr.com/" rel="nofollow noreferrer">regexr.com</a> and displays the correct selection. However once passed into the scan method like so:</p> <pre><code>$.message scan(/\\\&quot;(NewLABEL.[a-zA-Z]*)/), </code></pre> <p>The full text string is as follows</p> <pre><code>Field \&quot;NewLABEL.title\&quot; of required type \&quot;String!\&quot; was not provided. </code></pre> <p>is returns a blank array.</p> <p>Any ideas?</p>
[ { "answer_id": 74397895, "author": "Fe2O3", "author_id": 17592432, "author_profile": "https://Stackoverflow.com/users/17592432", "pm_score": 0, "selected": false, "text": "int index;" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20473898/" ]
74,397,384
<p>I am trying to find a way to send the id of the clicked button to the backend. The problem is that I am creating lots of buttons with one method but the id is different.</p> <pre><code>@foreach (var item in Model.showManager.GetMovies()) { i++; @if (Model.user.IsAdmin == true) { &lt;input class=&quot;btn_confirm&quot; type=&quot;submit&quot; id=i value=&quot;Delete&quot;/&gt; } } </code></pre> <p>The point is that every button is created with different id and I want to send that id to the backend.</p>
[ { "answer_id": 74397895, "author": "Fe2O3", "author_id": 17592432, "author_profile": "https://Stackoverflow.com/users/17592432", "pm_score": 0, "selected": false, "text": "int index;" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20045530/" ]
74,397,391
<p>Hi I have an array of objects like below:</p> <pre><code>let tbrows = [{&quot;rowindx&quot;:0,&quot;speciescnt&quot;:2},{&quot;rowindx&quot;:0,&quot;speciescnt&quot;:3},{&quot;rowindx&quot;:1,&quot;speciescnt&quot;:2},{&quot;rowindx&quot;:1,&quot;speciescnt&quot;:3}] </code></pre> <p>I want to get the maximum value of speciecnt for each row (i.e. after filtering the array) I would like it to be</p> <pre><code>let tbrows = [{&quot;rowindx&quot;:0,&quot;speciescnt&quot;:3},{&quot;rowindx&quot;:1,&quot;speciescnt&quot;:3}]; </code></pre> <p>I am using the following code that I found on the web to filter an array but it only filters on one attribute of object.</p> <pre><code>const max2 = tbrows.reduce((op, item) =&gt; op = op &gt; item.speciescnt? op : item.speciescnt, 0); </code></pre>
[ { "answer_id": 74397895, "author": "Fe2O3", "author_id": 17592432, "author_profile": "https://Stackoverflow.com/users/17592432", "pm_score": 0, "selected": false, "text": "int index;" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/819073/" ]
74,397,418
<p>I need to make a function named f3Groups() that accepts one argument. As well as a list named cgList to represent the whole class, containing 3 lists representing the 3 groups. cgList can be an empty list but there cannot be any empty group, for example cgList = [] when there is no student in this class. Return the cgList but I have no idea how to do that. So far I have only made a function printing out list of user inputs.</p> <pre><code>def get_student_list(): stdlist = [] while True: iStr = input('Please enter a new student name, (&quot;quit&quot; if no more student)') if iStr == &quot;quit&quot;: return stdlist if iStr == &quot;&quot;: print(&quot;Empty student name is not allowed.&quot;) else: stdlist.append(iStr) stdList = get_student_list() print(&quot;The whole class list is&quot;) for x in stdList: print(x, end=' ') `` I want 7 user inputs. User input 1, 4 and 7 in one list group. User input 2 and 5 in one group. User input 3 and 6 in one group. After that print them horizontally. ``The whole class list is ['Student a', 'Student b', 'Student c', 'Student d', 'Student e'. 'Student f', 'Student g'] Group 1: ['Student a', 'Student d', 'Student g'] Group 2: ['Student b', 'Student e'] Group 3: ['Student c', 'Student f'] ` The above is the output I want. Is there a way to do it? </code></pre>
[ { "answer_id": 74397895, "author": "Fe2O3", "author_id": 17592432, "author_profile": "https://Stackoverflow.com/users/17592432", "pm_score": 0, "selected": false, "text": "int index;" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20470075/" ]
74,397,430
<p>I have the following mapping</p> <pre><code>mapping = {'sum12':2, 'sum6':1, 'avg12':2, 'avg6':1, 'diff':3, 'mean':4} </code></pre> <p>and I have a dataframe with variables like</p> <pre><code> var1 var2 0 abc_sum12 mean_jkl 1 pqr_sum6 pqr_avg6 2 diff_xyz qwerty </code></pre> <p>If any of the substrings are present in the strings in the dataframe, I want to replace them with their corresponding values. If no substring is present, I want to replace it with <code>np.nan</code>. At present, the only solution I can think of is going through every row, checking if any of the substrings is present in every string, and replacing it with the specific number corresponding with that substring. Is there a better way to do it.</p> <p>The output in the end would be</p> <pre><code> var1 var2 0 2 4.0 1 1 1.0 2 3 NaN </code></pre>
[ { "answer_id": 74397487, "author": "Chris", "author_id": 4718350, "author_profile": "https://Stackoverflow.com/users/4718350", "pm_score": 3, "selected": true, "text": "qwerty" }, { "answer_id": 74397572, "author": "Ben Grossmann", "author_id": 2476977, "author_profile": "https://Stackoverflow.com/users/2476977", "pm_score": 1, "selected": false, "text": "mapping = {'sum12':2, 'sum6':1,\n 'avg12':2, 'avg6':1,\n 'diff':3, 'mean':4}\n\ndf = pd.DataFrame(\n{'var1': {0: 'abc_sum12', 1: 'pqr_sum6', 2: 'diff_xyz'},\n 'var2': {0: 'mean_jkl', 1: 'pqr_avg6', 2: 'qwerty'}})\n\ndf_new[:] = np.nan\ndf_new = df_new.astype('float')\n\nfor name,col in df.items():\n for key,val in mapping.items():\n df_new[name][col.str.contains(key)] = val\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5485288/" ]
74,397,549
<p>I have an array of objects as show below, I'm going to <em>filter</em> out the objects and add into another object of objects (the reason is that I will be storing it into firestore and it only accepts non-arrays) so I'm just going to keep things indexed with numbers but how do I automatically add an object into the list of objects if the object name is not there? (Default object with a value in string)</p> <pre><code>let data = [ {name: Cat, choice: one, Date: 11/11/22, Time: 503, food: chicken}, {name: Dog, Date: 11/11/22, Time: 802, food: veggies}, {name: Cat, choice: two, Date: 11/11/22, Time: 105, food: beef} ] for(let i = 0; i&lt;data.length-1; i++) { let savingData = [] if(data[i].choice == &quot;undefined&quot; || &quot;null&quot;) { data[i].choice = &quot;zero&quot;; } savingData.push({ name: data[i].name choice: data[i].choice //missing choices will default to zero as string food: data[i].food }); } for(let j = 0; j&lt;savingData.length-1; j++) { let objectSavingData = Object.assign({}, savingData[j]); } </code></pre> <p>Does not work - did I miss something? or maybe the error is not in this portion of code.. (data structure changed due to its lengthyness, data has arrays of 150+ and object names of over 40, I just simplified it to this but all the data entry are in string)</p>
[ { "answer_id": 74397631, "author": "An Nguyen", "author_id": 5492310, "author_profile": "https://Stackoverflow.com/users/5492310", "pm_score": 2, "selected": true, "text": "const data = [\n { name: \"Cat\", choice: \"one\", Date: \"11/11/22\", Time: 503, food: \"chicken\" },\n { name: \"Dog\", Date: \"11/11/22\", Time: 802, food: \"veggies\" },\n { name: \"Cat\", choice: \"two\", Date: \"11/11/22\", Time: 105, food: \"beef\" }\n]\n\nconst savingData = data.map((record) => {\n const { name, choice = 0, Date: date, Time: time, food } = record;\n return { name, choice, date, time, food };\n});\n\nconsole.log(savingData);" }, { "answer_id": 74397862, "author": "nikunj", "author_id": 4387651, "author_profile": "https://Stackoverflow.com/users/4387651", "pm_score": 0, "selected": false, "text": "`let savingData = [] ;` >>> this need to be declared before 'for loop';\n`i<data.length-1; >>> i<data.length`\n`let objectSavingData = Object.assign({}, savingData[j]);` - you are \n assigning new object to objectSavingData...also object.assing just \n merge/overwrite properties.this will not work\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19380192/" ]
74,397,589
<p><code>pdt.startTime</code> is datetime</p> <p><code>s_first.FromTimeOfDay</code> is a time</p> <p>I want to subtract the time drom the datetime. When i run the code below, Snowflake gives me this error <code>invalid type [CAST(S_FIRST.FROMTIMEOFDAY AS TIMESTAMP_NTZ(9))] for parameter 'TO_TIMESTAMP_NTZ'</code></p> <pre><code>select (pdt.StartTime - (SELECT s_first.FromTimeOfDay::datetime FROM Shift s_first)) from RAW_CPMS_AAR.POWERBI_DowntimeTable AS PDT </code></pre> <p>When i try this:</p> <pre><code>select (pdt.StartTime::TIMESTAMP_NTZ(9) - (SELECT s_first.FromTimeOfDay::TIMESTAMP_NTZ(9) FROM Shift s_first)) from RAW_CPMS_AAR.POWERBI_DowntimeTable AS PDT </code></pre> <p>I get more or less the same error: <code>invalid type [CAST(S_FIRST.FROMTIMEOFDAY AS TIMESTAMP_NTZ(9))] for parameter 'TO_TIMESTAMP_NTZ'</code></p> <p>How do I convert the time into a datetime format so that I can subtract the two. It doesnt seem to me that there is a clear way to convert time into datetime in snowflake.</p>
[ { "answer_id": 74397631, "author": "An Nguyen", "author_id": 5492310, "author_profile": "https://Stackoverflow.com/users/5492310", "pm_score": 2, "selected": true, "text": "const data = [\n { name: \"Cat\", choice: \"one\", Date: \"11/11/22\", Time: 503, food: \"chicken\" },\n { name: \"Dog\", Date: \"11/11/22\", Time: 802, food: \"veggies\" },\n { name: \"Cat\", choice: \"two\", Date: \"11/11/22\", Time: 105, food: \"beef\" }\n]\n\nconst savingData = data.map((record) => {\n const { name, choice = 0, Date: date, Time: time, food } = record;\n return { name, choice, date, time, food };\n});\n\nconsole.log(savingData);" }, { "answer_id": 74397862, "author": "nikunj", "author_id": 4387651, "author_profile": "https://Stackoverflow.com/users/4387651", "pm_score": 0, "selected": false, "text": "`let savingData = [] ;` >>> this need to be declared before 'for loop';\n`i<data.length-1; >>> i<data.length`\n`let objectSavingData = Object.assign({}, savingData[j]);` - you are \n assigning new object to objectSavingData...also object.assing just \n merge/overwrite properties.this will not work\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14322212/" ]
74,397,693
<p>How to say find the word &quot;Apple&quot; or &quot;Orange&quot; by using or in the criteria instead of typing +countif as another criteria? I mean adding OR in the same criteria.</p> <pre><code>=countif(A1:A100,&quot;apple|Orange&quot;) </code></pre>
[ { "answer_id": 74401838, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 3, "selected": true, "text": "=SUMPRODUCT(REGEXMATCH(A1:A100, \"apple|Orange\"))\n" }, { "answer_id": 74415135, "author": "Hassan Almaateeq", "author_id": 14934463, "author_profile": "https://Stackoverflow.com/users/14934463", "pm_score": 0, "selected": false, "text": "arrayformula(countifs(REGEXMATCH(A1:A100,\" (?i)apple|orange\"), true, B1:B100, \"banana\"))" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14934463/" ]
74,397,694
<p>When I upload a <code>.mp3</code> audio file or a <code>.jpg</code> picture to Firebase Cloud Storage I get this error:</p> <pre><code>TypeError: Cannot read properties of undefined (reading 'byteLength') </code></pre> <p>What is <code>byteLength</code>?</p> <p>I tried uploading a <code>.jpg</code> with raw <code>uploadString</code>. The file appeared in Storage but it was only 15B when it should have been 100KB.</p> <p>The documentation <a href="https://firebase.google.com/docs/storage/web/upload-files" rel="nofollow noreferrer">Upload files with Cloud Storage on Web</a> doesn't say anything about specifying MIME types when uploading files.</p> <p>Writing to the Storage emulator executes without errors but no files appear.</p> <p>Here's the Firebase Cloud Function I'm using.</p> <pre class="lang-js prettyprint-override"><code>import { initializeApp } from &quot;firebase/app&quot;; import * as functions from &quot;firebase-functions&quot;; import { getStorage, ref, uploadBytes, uploadString, connectStorageEmulator } from &quot;firebase/storage&quot;; const firebaseConfig = { apiKey: &quot;...&quot;, authDomain: &quot;my-awesome-app.firebaseapp.com&quot;, databaseURL: &quot;https://my-awesome-app.firebaseio.com&quot;, projectId: &quot;my-awesome-app&quot;, storageBucket: &quot;my-awesome-app.appspot.com&quot;, messagingSenderId: &quot;...&quot;, appId: &quot;...&quot; }; const app = initializeApp(firebaseConfig); export const ByteMe = functions.firestore.document('ByteMe/{userID}').onUpdate((change, context) =&gt; { const storage = getStorage(); const storageRef = ref(storage, 'gs://my-awesome-app.appspot.com/Pictures/bootchkas.jpg'); connectStorageEmulator(storage, &quot;localhost&quot;, 9199); // comment out to write to the cloud async function uploadPicture() { try { uploadString(storageRef, './bootchkas.jpg').then((snapshot) =&gt; { console.log('Uploaded a raw string!'); }); } catch (error) { console.error(error); } } return uploadPicture(); }); </code></pre>
[ { "answer_id": 74398108, "author": "Alexander N.", "author_id": 3946096, "author_profile": "https://Stackoverflow.com/users/3946096", "pm_score": 1, "selected": false, "text": "./bootchkas.jpg" }, { "answer_id": 74438476, "author": "Thomas David Kehoe", "author_id": 5153354, "author_profile": "https://Stackoverflow.com/users/5153354", "pm_score": 1, "selected": true, "text": "uploadString" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5153354/" ]
74,397,722
<p>So it to loop and subMenu on sidebar component, but instead of the subMenu showUp under the parents menu, it showUp on the Right side of the parents menu as pic below: <a href="https://i.stack.imgur.com/csdnC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/csdnC.png" alt="enter image description here" /></a></p> <p>here is my code on how i try to loop the subMenu and The parents item to the react component:</p> <pre><code>return ( &lt;div className=&quot; my-4 border-gray-100 pb-4&quot;&gt; {items.map(({ icon: Icon, iconArrow: IconArrow, ...item }, index) =&gt; { if (item.subMenu) { return ( &lt;div&gt; &lt;Link href={item.link}&gt; &lt;a onClick={(e) =&gt; onMouseClick(e, item.link)} className=&quot;flex mb-2 justify-start items-center gap-4 pl-5 hover:bg-gray-900 p-2 rounded-md group cursor-pointer hover:shadow-lg m-auto&quot; &gt; &lt;Icon className=&quot;text-2xl text-white group-hover:text-red&quot; /&gt; &lt;h3 className=&quot;text-base text-white group-hover:text-red font-semibold &quot;&gt; {item.label} &lt;/h3&gt; {item.subMenu &amp;&amp; dropdown ? ( &lt;&gt; &lt;IconArrow className=&quot;pl-0 text-2xl text-white group-hover:text-red&quot; /&gt; &lt;/&gt; ) : ( &lt;&gt;&lt;/&gt; )}{&quot; &quot;} {item.subMenu &amp;&amp; dropdown ? ( &lt;div&gt; {item.subMenu.map((subitem, index) =&gt; { return &lt;&gt;makan&lt;/&gt;; })} &lt;/div&gt; ) : ( &lt;&gt;&lt;/&gt; )} &lt;/a&gt; &lt;/Link&gt; &lt;/div&gt; ); } else { return ( // eslint-disable-next-line react/jsx-key &lt;div&gt; &lt;Link href={item.link}&gt; &lt;a onClick={(e) =&gt; onMouseClick(e, item.link)} className=&quot;flex mb-2 justify-start items-center gap-4 pl-5 hover:bg-gray-900 p-2 rounded-md group cursor-pointer hover:shadow-lg m-auto&quot; &gt; &lt;Icon className=&quot;text-2xl text-white group-hover:text-red&quot; /&gt; &lt;h3 className=&quot;text-base text-white group-hover:text-red font-semibold &quot;&gt; {item.label} &lt;/h3&gt; &lt;/a&gt; &lt;/Link&gt; &lt;/div&gt; ); } })} &lt;/div&gt; ); }; </code></pre> <p>Can Some one tell me where did i do wrong here, here is where i call the sidebar component into the sidebar:</p> <pre><code> return ( &lt;div className=&quot;h-full px-4 pt-8 bg-yellow flex flex-col peer-focus:left-0 peer:transition ease-out delay-150 duration-200&quot;&gt; &lt;div className=&quot;flex flex-col justify-start item-center mb-4&quot;&gt; &lt;Image src={Logo_Nabati} width={123} height={75} alt=&quot;logo Nabati&quot; /&gt; &lt;/div&gt; &lt;Sidebarcomponent items={menuItems} /&gt;; &lt;/div&gt; ); </code></pre>
[ { "answer_id": 74398108, "author": "Alexander N.", "author_id": 3946096, "author_profile": "https://Stackoverflow.com/users/3946096", "pm_score": 1, "selected": false, "text": "./bootchkas.jpg" }, { "answer_id": 74438476, "author": "Thomas David Kehoe", "author_id": 5153354, "author_profile": "https://Stackoverflow.com/users/5153354", "pm_score": 1, "selected": true, "text": "uploadString" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16136595/" ]
74,397,789
<p>I have this react app, I need to deploy into a google cloud storage thru google cloud build, I'm trying to do it adding a cloudbuild.yaml and add some steps to run the npm</p> <p>This is what I have:</p> <pre><code>steps: - name: bash script: | npm install --force - name: bash script: | npm run build - name: &quot;gcr.io/google.com/cloudsdktool/cloud-sdk&quot; entrypoint: gcloud args: [&quot;storage&quot;, &quot;cp&quot;, &quot;/dist/*&quot;, &quot;gs://bucket&quot;] timeout: 1200s options: logging: CLOUD_LOGGING_ONLY </code></pre> <p>but cloud build show me an error:</p> <p><code> Step #0: script: line 2: npm: not found</code></p> <pre><code></code></pre>
[ { "answer_id": 74398108, "author": "Alexander N.", "author_id": 3946096, "author_profile": "https://Stackoverflow.com/users/3946096", "pm_score": 1, "selected": false, "text": "./bootchkas.jpg" }, { "answer_id": 74438476, "author": "Thomas David Kehoe", "author_id": 5153354, "author_profile": "https://Stackoverflow.com/users/5153354", "pm_score": 1, "selected": true, "text": "uploadString" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133649/" ]
74,397,794
<p>what should i repair? it's error.</p> <p><code>characterList[index]['real_name'].toUpperCase()</code></p> <p>How can fix the error?</p>
[ { "answer_id": 74398108, "author": "Alexander N.", "author_id": 3946096, "author_profile": "https://Stackoverflow.com/users/3946096", "pm_score": 1, "selected": false, "text": "./bootchkas.jpg" }, { "answer_id": 74438476, "author": "Thomas David Kehoe", "author_id": 5153354, "author_profile": "https://Stackoverflow.com/users/5153354", "pm_score": 1, "selected": true, "text": "uploadString" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17572000/" ]
74,397,817
<p>I am aware of a similar issue <a href="https://stackoverflow.com/questions/65659966/how-to-fix-error-psycopg2-errors-notnullviolation-null-value-in-column-id-v">How to fix error: (psycopg2.errors.NotNullViolation) null value in column &quot;id&quot; violates not-null constraint?</a> but the answers there did not fix my error</p> <p>I have the following sqlalchemy structure connected to a postgres database</p> <pre><code>class Injury(db.Model): __tablename__ = &quot;injury&quot; id = Column(Integer, primary_key=True) name = Column(String) description = Column(String) </code></pre> <p>The DDL looks like</p> <pre><code>create table injury ( id bigint not null constraint idx_182837_injury_pkey primary key constraint injury_id_key unique, name text, description text, ); </code></pre> <p>However, upon trying to insert something into the database like the following</p> <pre><code>injury = Injury(name='name', description='desc') session.add(injury) session.commit() </code></pre> <p>The following error occurs</p> <pre><code>Error '(psycopg2.errors.NotNullViolation) null value in column &quot;id&quot; of relation &quot;injury&quot; violates not-null constraint </code></pre> <p>Upon opening up my debugger, I can verify that the <code>id</code> attribute in the <code>injury</code> object before I commit is <code>None</code></p> <p>Why is this occurring? Shouldn't <code>primary_key=True</code> in my schema tell postgres that it is responsible for making the id? I tried playing around with <code>SEQUENCE</code> and <code>IDENTITY</code> but I was getting the same error</p>
[ { "answer_id": 74397874, "author": "Eric Kong", "author_id": 15723533, "author_profile": "https://Stackoverflow.com/users/15723533", "pm_score": 1, "selected": false, "text": "id SERIAL PRIMARY KEY\n" }, { "answer_id": 74403875, "author": "Malice", "author_id": 16179502, "author_profile": "https://Stackoverflow.com/users/16179502", "pm_score": 1, "selected": true, "text": "pg_loader" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16179502/" ]
74,397,821
<p>When I click on the button: Remover, the line is hidden. When I click the Adicionar button again, the line that was hidden is added. I want the line along with the data to be definitively deleted when I click on the button: Remover.</p> <p>I've tried using several methods and I can't solve it, can anyone help?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const form = document.getElementById("agenda-de-contatos"); let linhas = ""; form.addEventListener("submit", function (e) { e.preventDefault(); const inputNomeContato = document.getElementById("nome-do-contato"); const inputNumeroTelefone = document.getElementById("numero-de-telefone"); let linha = "&lt;tr&gt;"; linha += `&lt;td&gt;${inputNomeContato.value}&lt;/td&gt;`; linha += `&lt;td&gt;${inputNumeroTelefone.value}&lt;/td&gt;`; linha += `&lt;td&gt;&lt;button class='excluir' onclick="deleteRow(this.parentNode.parentNode.rowIndex)"&gt;Remover&lt;/button&gt;&lt;/td&gt;`; linha += "&lt;/tr&gt;"; linhas += linha; const corpoTabela = document.querySelector("tbody"); corpoTabela.innerHTML = linhas; }); function deleteRow(id) { document.getElementById("tabela").deleteRow(id); }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Roboto', sans-serif; } body { background-color: #e7e7e7; padding-top: 100px; } header { display: flex; align-items: center; margin-bottom: 40px; } header img { height: 36px; margin-right: 16px; } header h1 { font-size: 40px; font-weight: bold; } .container { max-width: 960px; width: 100%; margin: 0 auto; } form { display: flex; max-width: 640px; width: 100%; justify-content: space-around; margin-bottom: 56px; } form input { font-size: 16px; background-color: #fff; border: none; border-bottom: 2px solid #000; padding: 16px; margin: 0 auto; } form button { background-color: #297fc3; color: #fff; font-size: 16px; font-weight: bold; border: none; cursor: pointer; padding: 16px; margin: 0 auto; } table { width: 100%; } table th { border-bottom: 2px solid #000; padding: 16px; font-size: 24; font-weight: bold; } table td { padding: 16px 0; text-align: center; font-size: 18px; border-bottom: 1px solid rgba(0, 0, 0, 0.1); } table td img { height: 30px; } button:hover { background-color: #258ddd; } input:focus, textarea:focus { outline-color: #297fc3; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&amp;display=swap" rel="stylesheet"&gt; &lt;div class="container"&gt; &lt;header&gt; &lt;img src="./images/contatos.png" alt="agenda de contatos" /&gt; &lt;h1&gt;Agenda de contatos&lt;/h1&gt; &lt;/header&gt; &lt;form id="agenda-de-contatos"&gt; &lt;input type="" id="nome-do-contato" required placeholder="Nome do contato" /&gt; &lt;input type="tel" id="numero-de-telefone" pattern="(\(?[0-9]{2}\)?)([0-9]{4,5})-?([0-9]{4})" required placeholder="Telefone (xx) xxxx-xxxx" title="Número de telefone precisa ser no formato (xx) xxxx-xxxx" required="required" /&gt; &lt;button type="submit"&gt;Adicionar&lt;/button&gt; &lt;/form&gt; &lt;table id="tabela" cellspacing="0"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Nome do contato&lt;/th&gt; &lt;th&gt;Número de telefone&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt;&lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74397974, "author": "Surya R Praveen", "author_id": 714707, "author_profile": "https://Stackoverflow.com/users/714707", "pm_score": 0, "selected": false, "text": "table td {\n padding: 16px 0;\n text-align: center;\n font-size: 18px;\n border-bottom: 1px solid rgba(0, 0, 0, 0.1);\n}\n" }, { "answer_id": 74397990, "author": "Nishanth", "author_id": 5225976, "author_profile": "https://Stackoverflow.com/users/5225976", "pm_score": 2, "selected": true, "text": "linhas" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11881527/" ]
74,397,840
<p>I am sending an <code>id</code> in my js code and I want to pass that variable to my controller. Any advice on how I can do that?</p> <pre><code>&lt;input class=&quot;btn_confirm&quot; type=&quot;submit&quot; id={i} onclick=&quot;id_click(this.id)&quot; value=&quot;Delete&quot; /&gt; </code></pre> <pre><code>var id; function id_click(clicked_id) { id = clicked_id; } </code></pre> <p>I tried different things but nothing worked out.</p>
[ { "answer_id": 74397974, "author": "Surya R Praveen", "author_id": 714707, "author_profile": "https://Stackoverflow.com/users/714707", "pm_score": 0, "selected": false, "text": "table td {\n padding: 16px 0;\n text-align: center;\n font-size: 18px;\n border-bottom: 1px solid rgba(0, 0, 0, 0.1);\n}\n" }, { "answer_id": 74397990, "author": "Nishanth", "author_id": 5225976, "author_profile": "https://Stackoverflow.com/users/5225976", "pm_score": 2, "selected": true, "text": "linhas" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11108472/" ]
74,397,866
<p>I've been scratching my head and searching the internet for an explanation to this.</p> <p>I started with my full code and boiled it down to the following that illustrates my problem:</p> <pre><code>function foo (param: string) { if (param === 'bar') { return { one: 'bar' } } return { two: 'baz' } } </code></pre> <p>Why does this give me:</p> <pre><code>declare function foo(param: string): { one: string; two?: undefined; } | { two: string; one?: undefined; }; </code></pre> <p>and not</p> <pre><code>declare function foo(param: string): { one: string; } | { two: string; }; </code></pre> <p>At first I thought it was a difference between functions and arrow functions, but <a href="https://github.com/microsoft/TypeScript/issues/45247" rel="nofollow noreferrer">this issue</a> taught me otherwise and pointed me in the direction that it might be an inference issue.</p> <p>Then I came across <a href="https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types" rel="nofollow noreferrer">Distributive Conditional Types </a> and thought it might have something to do with it but having read <a href="https://stackoverflow.com/a/55383816/9735558">this answer</a> (and hopefully understood it correctly) made me think that it was not.</p> <p>I have now read a lot of other resources too, but I can't figure out what I'm missing or why I can't put all the pieces together to form an understanding of this.</p> <p><a href="https://www.typescriptlang.org/play?target=1&amp;jsx=1&amp;ts=4.8.4#code/GYVwdgxgLglg9mABFApgZyogFABwIYBOeAtgFyIYExgDmAlIgN4BQibiMw2+RxiAvIMQByYHDjCGLdjMQEUUEASTTZahCnKjxw1msQBfPWyPG5CpSrMyoAdzhaARoV0yjBoA" rel="nofollow noreferrer">Playground link</a></p>
[ { "answer_id": 74397974, "author": "Surya R Praveen", "author_id": 714707, "author_profile": "https://Stackoverflow.com/users/714707", "pm_score": 0, "selected": false, "text": "table td {\n padding: 16px 0;\n text-align: center;\n font-size: 18px;\n border-bottom: 1px solid rgba(0, 0, 0, 0.1);\n}\n" }, { "answer_id": 74397990, "author": "Nishanth", "author_id": 5225976, "author_profile": "https://Stackoverflow.com/users/5225976", "pm_score": 2, "selected": true, "text": "linhas" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9735558/" ]
74,397,871
<p>Write a function, max index, that takes a list as a parameter and returns the index of the largest number in the list. When writing the function, you are given the following rules:</p> <ul> <li>You are not allowed to use the max function</li> <li>You are not allowed to use any list methods</li> <li>You must use a Pythonic FOR loop. This means you CANNOT use the range function or enumerate function in your loop</li> <li>If the largest number appears more than once, you should return the smallest index</li> </ul> <p>This is so wrong because it fails to loop through the list and I also don't know how to compare the two indexes in case the largest value appears more than once in the list.</p> <pre><code>def max_index(lon): &quot;&quot;&quot; input is a list of numbers. returns the index of the largest number in the list &quot;&quot;&quot; max = lon[0] index = 0 for n in lon: if n&gt;max: max = n index+=1 return index </code></pre>
[ { "answer_id": 74397974, "author": "Surya R Praveen", "author_id": 714707, "author_profile": "https://Stackoverflow.com/users/714707", "pm_score": 0, "selected": false, "text": "table td {\n padding: 16px 0;\n text-align: center;\n font-size: 18px;\n border-bottom: 1px solid rgba(0, 0, 0, 0.1);\n}\n" }, { "answer_id": 74397990, "author": "Nishanth", "author_id": 5225976, "author_profile": "https://Stackoverflow.com/users/5225976", "pm_score": 2, "selected": true, "text": "linhas" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20474373/" ]
74,397,924
<p>I'm using reactjs and trying to change style of a Div when user scroll from top to position (top + 300px). If scrolling down from this position, it will <code>display: block</code> else is <code>none</code>. How do I do this with react? I searched here but all results are not answered mine.</p> <p>I tried some methods with useRef, handleOnScroll like below function but it doesn't work.</p> <pre class="lang-js prettyprint-override"><code>const handleScroll = (e) =&gt; { const scrolledFromTop = contentRef.current?.scrollTop; setActive(scrolledFromTop &gt; 300); }; </code></pre> <pre><code>&lt;div ref={contentRef} onScroll={handleScroll}&gt; ... &lt;/div&gt; </code></pre>
[ { "answer_id": 74397974, "author": "Surya R Praveen", "author_id": 714707, "author_profile": "https://Stackoverflow.com/users/714707", "pm_score": 0, "selected": false, "text": "table td {\n padding: 16px 0;\n text-align: center;\n font-size: 18px;\n border-bottom: 1px solid rgba(0, 0, 0, 0.1);\n}\n" }, { "answer_id": 74397990, "author": "Nishanth", "author_id": 5225976, "author_profile": "https://Stackoverflow.com/users/5225976", "pm_score": 2, "selected": true, "text": "linhas" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20436639/" ]
74,397,949
<p>There is a custom <strong>class A</strong> with properties <strong>Name</strong> and <strong>Amount</strong></p> <p>There is a <strong>nested List</strong> of iterations of <strong>List A</strong>.</p> <p>To get each unique <strong>A</strong> and its total amount, count etc. I use following code: `</p> <pre><code>public void GetStatistic() { var result = NestedListofListA.SelectMany(iteration =&gt; iteration) .GroupBy(a =&gt; a.Name) .Select(a =&gt; new { a.Key, Count = a.Count(), Amount = a.Sum(a =&gt; a.Amount), Min = a.Min(a =&gt; a.Amount), Max = a.Max(a =&gt; a.Amount) }) .OrderBy(a =&gt; a.key); } </code></pre> <p>`The problem is, if nested list count is over about 3 millions iterations I get System.OverflowException: 'Arithmetic operation resulted in an overflow.'</p> <p>Amount, Min and Max for sure can't exceed int.MaxValue with just 3 million iterations, I'm not sure what causing the problem.</p> <p>I can workaround the problem by creating a unique list of A from nested list</p> <p><code>var uniqueAList = NestedListofA.SelectMany(list =&gt; list).DistinctBy(a =&gt; a.Name).ToList();</code></p> <p>and then use nested foreach to get the same statistic but the code is larger and slower</p> <p>I tried to explicitly convert anonymous class properties to long to be sure the problem is not related to it but it didn't help</p> <p><strong>UPDATE:</strong> With the following fix the code is working:</p> <pre><code>Amount = a.Sum(a =&gt; (long)a.Amount) </code></pre> <p>Thanks to user @vivek nuna</p>
[ { "answer_id": 74398099, "author": "vivek nuna", "author_id": 6527049, "author_profile": "https://Stackoverflow.com/users/6527049", "pm_score": 2, "selected": true, "text": "SUM" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19775889/" ]
74,397,958
<p>Using <code>gsub()</code>, I want to replace &quot;\n\n&quot; to &quot;&quot; in this text:</p> <pre><code>mystring&lt;-&quot;People Storm Seonul Airport as Citizens Leave\\n\\nCHOI JEONGHO\\n\\nSEOUL, South Korea, Jan. 31&quot; </code></pre> <p>But, when I ran <code>gsub(&quot;[\r\\n]&quot;, &quot; &quot;, mystring)</code>, it deletes all n in the text.</p> <p>The output was:</p> <pre><code>&quot;People Storm Seo ul Airport as Citize s Leave CHOI JEO GHO SEOUL, South Korea, Ja . 31&quot; </code></pre> <p>Could you teach me why it is so and how to delete only &quot;\n\n&quot;?</p>
[ { "answer_id": 74398004, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": true, "text": "n" }, { "answer_id": 74398010, "author": "Matt", "author_id": 12967938, "author_profile": "https://Stackoverflow.com/users/12967938", "pm_score": 0, "selected": false, "text": "stringr" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19907346/" ]
74,397,978
<p>I make a JS stopwatch that has format H:m:s:ms when it reached 60 min it always increase to 61,62 and so on</p> <p>i am using setInterval here is my code:</p> <pre><code>n = 3600; td = setInterval(function () { n++; let hours = parseInt(n / 3600); var m = parseInt(n / 60) var s = parseInt(n / 60 % 60); var M = parseInt(n % 60); // let hours = Math.floor(((n[ids] / 1000) / 60) / 60) % 24 // let m = Math.floor((n[ids] / 1000) / 60) % 60 // let s = Math.floor(n[ids] / 1000) % 60 // let M = Math.floor(n[ids] % 1000) $(&quot;#display0&quot;).html(toDub(hours) + &quot;:&quot; + toDub(m) + &quot;:&quot; + toDub(s) + &quot;:&quot; + toDub(M)) }, 1000 / 60); </code></pre> <p><strong>full source code</strong>: <a href="https://jsfiddle.net/greycat/danvL42s/2/" rel="nofollow noreferrer">https://jsfiddle.net/greycat/danvL42s/2/</a></p> <p>I am sure there is something wrong with my <strong>m</strong> variable.</p> <p>Anyone can help me out?</p>
[ { "answer_id": 74398827, "author": "Vivekanand Vishvkarma", "author_id": 19443694, "author_profile": "https://Stackoverflow.com/users/19443694", "pm_score": 0, "selected": false, "text": "n =0;\ntd = setInterval(function() {\n n++;\n let hours = parseInt(n / 3600000);\n var m = parseInt(n %3600000 / 60000)\n var s = parseInt(n %3600000 %60000/ 1000);\n var M = parseInt(n %3600000 %60000% 1000); \n $(\"#display0\").html(toDub(hours) + \":\" + toDub(m) + \":\" + toDub(s) + \":\" + toDub(M));\n if(m==60) {\n n=0;\n }\n}, 1);\n" }, { "answer_id": 74398931, "author": "Dennis Quan", "author_id": 12226091, "author_profile": "https://Stackoverflow.com/users/12226091", "pm_score": 2, "selected": true, "text": "var M = parseInt(n % 60); \nvar s = parseInt(n / 60 % 60);\nvar m = parseInt(n / 60**2 % 60); \nvar hours = parseInt(n / 60**3 % 60); \n" }, { "answer_id": 74399016, "author": "waheed", "author_id": 1731865, "author_profile": "https://Stackoverflow.com/users/1731865", "pm_score": 1, "selected": false, "text": "function toDub(n){\n return n < 10 ? \"0\" + n : \"\" + n\n}\n\n$(document).on('click', '.start01', function(event) {\n $(this).attr(\"style\", \"display:none\");\n var ids = parseInt($(this).attr('id').substring(5));\n $(\"#stop\" + ids).attr(\"style\", \"display:block\")\n // console.log(n[ids])\n n = 0;\n td = setInterval(function () \n {\n n++;\n let hours = parseInt(n / 216000);\n var m = parseInt(n / 3600)\n var s = parseInt(n / 60 % 60);\n var M = parseInt(n % 60);\n\n // let hours = Math.floor(((n[ids] / 1000) / 60) / 60) % 24\n // let m = Math.floor((n[ids] / 1000) / 60) % 60\n // let s = Math.floor(n[ids] / 1000) % 60\n // let M = Math.floor(n[ids] % 1000)\n\n $(\"#display0\").html(toDub(hours) + \":\" + toDub(m) + \":\" + toDub(s) + \":\" + toDub(M))\n }, 1000 / 60);\n });" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74397978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10371195/" ]
74,398,053
<p>I want to get the indices for a list of filters in polars and get a sparse matrix from it, how can I parallel the process? This is what I have right now, a pretty naive and brute force way for achieving what I need, but this is having some serious performance issue</p> <pre class="lang-py prettyprint-override"><code>def get_sparse_matrix(exprs: list[pl.Expr]) -&gt; scipy.sparse.csc_matrix: df = df.with_row_count('_index') rows: list[int] = [] cols: list[int] = [] for col, expr in enumerate(exprs): r = self.df.filter(expr)['_index'] rows.extend(r) cols.extend([col] * len(r)) X = csc_matrix((np.ones(len(rows)), (rows, cols)), shape= (len(self.df), len(rules))) return X </code></pre> <p>Example Input:</p> <pre class="lang-py prettyprint-override"><code># df is a polars dataframe with size 8 * 3 df = pl.DataFrame( [[1,2,3,4,5,6,7,8], [3,4,5,6,7,8,9,10], [5,6,7,8,9,10,11,12], [5,6,41,8,21,10,51,12], ]) # three polars expressions exprs = [pl.col('column_0') &gt; 3, pl.col('column_1') &lt; 6, pl.col('column_4') &gt; 11] </code></pre> <p>Example output: X is a sparse matrix of size <code>8 (number of records) X 3 (number of expressions)</code>, where the element at <code>i,j</code> equals to 1 if <code>i</code>th record matches the <code>j</code>th expression</p>
[ { "answer_id": 74402339, "author": "alexp", "author_id": 10120952, "author_profile": "https://Stackoverflow.com/users/10120952", "pm_score": 2, "selected": false, "text": "import polars as pl\nfrom scipy.sparse import csc_matrix\nimport numpy as np\n\ndf = pl.DataFrame(\n [[1,2,3,4,5,6,7,8], \n [3,4,5,6,7,8,9,10], \n [5,6,7,8,9,10,11,12],\n [5,6,41,8,21,10,51,12],\n])\n\n\nexprs = [(pl.col('column_0') > 3).cast(pl.Int8), \n (pl.col('column_1') < 6).cast(pl.Int8), \n (pl.col('column_3') > 11).cast(pl.Int8)]\n\nX = df.select(exprs)\ncsc_matrix(X.to_numpy())\n" }, { "answer_id": 74406047, "author": "braaannigan", "author_id": 5387991, "author_profile": "https://Stackoverflow.com/users/5387991", "pm_score": 1, "selected": false, "text": "GroupBy" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5257450/" ]
74,398,071
<p>I have a large dataframe with (104959, 298) rows and columns</p> <p>in the string column I have multiple substrings that I need to replace</p> <p>I've tried</p> <pre><code>df.EVENT_DTL.replace(['SPOUSE_2','SPOUSE_nan','PARENT_2','PARENT_nan','GRANDPARENT_2','GRANDPARENT_nan','CHILD_2', 'CHILD_nan','RELATIVE_2','RELATIVE_nan','LOVER_2','LOVER_nan','FRIEND_2','FRIEND_nan', '세부 대인관계문제 기타 상세_nan','세부 대인관계문제 기타 상세_','대인관계문제_1', '애인 관련_2','애인 관련_nan','직장 내_2','직장 내_nan','소외 문제_2','소외 문제_nan', '수면제_2','수면제_nan','진통제_2','진통제_nan','병원에서 처방 받은 약물_2', '병원에서 처방 받은 약물_nan','기타약물_nan','농약_2','농약_nan','살충제_2','살충제_nan', '제초제_2','제초제_nan','쥐약_2','쥐약_nan','화학약품_nan','목매달기_2','목매달기_nan', '가스 질식_2','가스 질식_nan','물에 뛰어들기_2','물에 뛰어들기_nan','뛰어내림_2', '뛰어내림_nan','칼, 송곳으로 찌르기_2','칼, 송곳으로 찌르기_nan','세부 동거자 기타 상세_nan'],&quot;&quot;) </code></pre> <p>(I'm trying to delete all of the substrings above)</p> <p>but it causes a memory error.</p> <p>I've found a method to replace multiple substrings in a string but haven't found way to replace substrings in a dataframe</p>
[ { "answer_id": 74402339, "author": "alexp", "author_id": 10120952, "author_profile": "https://Stackoverflow.com/users/10120952", "pm_score": 2, "selected": false, "text": "import polars as pl\nfrom scipy.sparse import csc_matrix\nimport numpy as np\n\ndf = pl.DataFrame(\n [[1,2,3,4,5,6,7,8], \n [3,4,5,6,7,8,9,10], \n [5,6,7,8,9,10,11,12],\n [5,6,41,8,21,10,51,12],\n])\n\n\nexprs = [(pl.col('column_0') > 3).cast(pl.Int8), \n (pl.col('column_1') < 6).cast(pl.Int8), \n (pl.col('column_3') > 11).cast(pl.Int8)]\n\nX = df.select(exprs)\ncsc_matrix(X.to_numpy())\n" }, { "answer_id": 74406047, "author": "braaannigan", "author_id": 5387991, "author_profile": "https://Stackoverflow.com/users/5387991", "pm_score": 1, "selected": false, "text": "GroupBy" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20376341/" ]
74,398,074
<p>I'm trying to build a <code>View</code> which a list of children of an object, and I want those children to be modifiable. The data changes, but the view doesn't react.</p> <p>Here is the stripped down example.</p> <pre class="lang-swift prettyprint-override"><code>class ObjectOne: ObservableObject { @Published var children: [ObjectTwo] init() { self.children = [] } } </code></pre> <pre><code>class ObjectTwo: ObservableObject { @Published var value: Value var id = UUID() init(value: Value) { self.value = value } } </code></pre> <pre class="lang-swift prettyprint-override"><code>struct ContentView: View { @ObservedObject var object: ObjectOne = ObjectOne() var body: some View { VStack { Button { self.object.children.append(ObjectTwo(value: .one)) } label: { Text(&quot;Add Object&quot;) } Text(&quot;Objects:&quot;) ForEach(self.object.children, id: \.id) { object in HStack { Text(String(object.value.rawValue)) Spacer() Button { if object.value == .one { object.value = .two } else { object.value = .one } } label: { Text(&quot;Toggle&quot;) } } } } } } </code></pre> <p>Adding objects works and the list updates, but modifying the <code>value</code> of the <code>ObjectTwo</code> doesn't update the view.</p>
[ { "answer_id": 74402339, "author": "alexp", "author_id": 10120952, "author_profile": "https://Stackoverflow.com/users/10120952", "pm_score": 2, "selected": false, "text": "import polars as pl\nfrom scipy.sparse import csc_matrix\nimport numpy as np\n\ndf = pl.DataFrame(\n [[1,2,3,4,5,6,7,8], \n [3,4,5,6,7,8,9,10], \n [5,6,7,8,9,10,11,12],\n [5,6,41,8,21,10,51,12],\n])\n\n\nexprs = [(pl.col('column_0') > 3).cast(pl.Int8), \n (pl.col('column_1') < 6).cast(pl.Int8), \n (pl.col('column_3') > 11).cast(pl.Int8)]\n\nX = df.select(exprs)\ncsc_matrix(X.to_numpy())\n" }, { "answer_id": 74406047, "author": "braaannigan", "author_id": 5387991, "author_profile": "https://Stackoverflow.com/users/5387991", "pm_score": 1, "selected": false, "text": "GroupBy" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7102356/" ]
74,398,090
<p>In <a href="https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/IO/TextReader.cs,e64583ea204ca037" rel="nofollow noreferrer">.NET's TextReader class</a>, there are two methods that, by default, simply return -1:</p> <p><code>public virtual int Peek() { return -1; }</code></p> <p><code>public virtual int Read() { return -1; }</code></p> <p>I am trying to follow the source code of <a href="https://source.dot.net/#System.Console/System/Console.cs,bc8fd98a32c60ffd" rel="nofollow noreferrer">Console.ReadLine()</a>; it seems to call Peek() and Read() through <a href="https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/IO/TextReader.cs,91b2c7adbdc4b165" rel="nofollow noreferrer">TextReader's ReadLine() method</a>.</p> <p>In regards to the TextReader.ReadLine() method, how are Read() and Peek() overridden such that they can return values other than -1?</p>
[ { "answer_id": 74402339, "author": "alexp", "author_id": 10120952, "author_profile": "https://Stackoverflow.com/users/10120952", "pm_score": 2, "selected": false, "text": "import polars as pl\nfrom scipy.sparse import csc_matrix\nimport numpy as np\n\ndf = pl.DataFrame(\n [[1,2,3,4,5,6,7,8], \n [3,4,5,6,7,8,9,10], \n [5,6,7,8,9,10,11,12],\n [5,6,41,8,21,10,51,12],\n])\n\n\nexprs = [(pl.col('column_0') > 3).cast(pl.Int8), \n (pl.col('column_1') < 6).cast(pl.Int8), \n (pl.col('column_3') > 11).cast(pl.Int8)]\n\nX = df.select(exprs)\ncsc_matrix(X.to_numpy())\n" }, { "answer_id": 74406047, "author": "braaannigan", "author_id": 5387991, "author_profile": "https://Stackoverflow.com/users/5387991", "pm_score": 1, "selected": false, "text": "GroupBy" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11813067/" ]
74,398,095
<p>Input:</p> <pre><code>val list1 = List( Map(&quot;ID&quot; -&gt; &quot;123&quot;, &quot;NAME&quot; -&gt; &quot;P1&quot;, &quot;PID&quot; -&gt; &quot;321&quot;), Map(&quot;ID&quot; -&gt; &quot;456&quot;, &quot;NAME&quot; -&gt; &quot;P2&quot;, &quot;PID&quot; -&gt; &quot;333&quot;) ) val list2 = List( Map(&quot;ID&quot; -&gt; &quot;123&quot;, &quot;ADDRESS&quot; -&gt; &quot;A1&quot;) ) val list3 = List( Map(&quot;PID&quot; -&gt; &quot;321&quot;, &quot;PHONE&quot; -&gt; &quot;2222&quot;), Map(&quot;PID&quot; -&gt; &quot;789&quot;, &quot;PHONE&quot; -&gt; &quot;4444&quot;) ) </code></pre> <p>Output:</p> <pre><code>List( Map( &quot;ID&quot; -&gt; &quot;123&quot;, &quot;NAME&quot; -&gt; &quot;P1&quot;, &quot;PID&quot; -&gt; &quot;321&quot;, &quot;ADDRESS&quot; -&gt; &quot;A1&quot;, &quot;PHONE&quot; -&gt; &quot;2222&quot; ) ) </code></pre> <p>I tried iterating list over flatmate and map, but it had bad time complexity. Expecting a solution in more functional programming approach, not using loop. Thanks in advance for helping with providing solution.</p> <pre><code>list1 .flatMap { l1 =&gt; list2 .flatMap { l2 =&gt; list3 .map { l3 =&gt; if ((l1.ID === l2.ID) &amp;&amp; (l1.PID === l3.PID)) { val data = Map( &quot;ID&quot; -&gt; l1.ID, &quot;NAME&quot; -&gt; l1.NAME, &quot;PID&quot; -&gt; l1.PID, &quot;ADDRESS&quot; -&gt; l2.ADDRESS, &quot;PHONE&quot; -&gt; l3.PHONE, ) val temp = List(data) temp } } } } </code></pre>
[ { "answer_id": 74402339, "author": "alexp", "author_id": 10120952, "author_profile": "https://Stackoverflow.com/users/10120952", "pm_score": 2, "selected": false, "text": "import polars as pl\nfrom scipy.sparse import csc_matrix\nimport numpy as np\n\ndf = pl.DataFrame(\n [[1,2,3,4,5,6,7,8], \n [3,4,5,6,7,8,9,10], \n [5,6,7,8,9,10,11,12],\n [5,6,41,8,21,10,51,12],\n])\n\n\nexprs = [(pl.col('column_0') > 3).cast(pl.Int8), \n (pl.col('column_1') < 6).cast(pl.Int8), \n (pl.col('column_3') > 11).cast(pl.Int8)]\n\nX = df.select(exprs)\ncsc_matrix(X.to_numpy())\n" }, { "answer_id": 74406047, "author": "braaannigan", "author_id": 5387991, "author_profile": "https://Stackoverflow.com/users/5387991", "pm_score": 1, "selected": false, "text": "GroupBy" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20474532/" ]
74,398,098
<p>I cannot load a new URL in flutter Webview... I have issues using <code>then</code> and <code>Future</code> in flutter <code>Webview</code> Controller...</p> <p>In a flutter <code>Webview</code>, I would like to load the <code>initialUrl</code>, then programmatically retrieve some information from that web page... All works well so far... But then I want the <code>Webview </code>to automatically load another webpage... but I am not sure how to use the <code>controller </code> and the <code>Completer </code>to do that</p> <p>Snippet:</p> <pre><code>WebView( initialUrl: 'https://flutter.dev', onWebViewCreated: (WebViewController webViewController) { _controller.complete(webViewController); }, onPageFinished: (String url) async{ if (url == 'https://flutter.dev') { // *** I retrieve some data, then I want to navigate *** _controller!.loadUrl('https://google.com'); // *** ERROR HERE *** } }, ) </code></pre> <p>I tried using the <code>controller </code>directly,</p> <pre><code>_controller!.loadUrl('https://google.com'); </code></pre> <p>it works if I don't use a <code>Completer </code>and instead I just assign the <code>controller</code></p> <pre><code>_controller = webViewController; </code></pre> <p>but does not seem a recommended option:</p> <p>I found other examples using a <code>FutureBuilder</code>, but I am not trying to build anything</p> <p>Here is the full code, in case useful:</p> <pre><code>import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; import 'dart:async'; void main() { runApp( const MaterialApp( home: WebViewApp(), ), ); } class WebViewApp extends StatefulWidget { const WebViewApp({super.key}); @override State&lt;WebViewApp&gt; createState() =&gt; _WebViewAppState(); } class _WebViewAppState extends State&lt;WebViewApp&gt; { final Completer&lt;WebViewController&gt; _controller = Completer&lt;WebViewController&gt;(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Flutter WebView'),), body: WebView( initialUrl: 'https://flutter.dev', onWebViewCreated: (WebViewController webViewController) { _controller.complete(webViewController); }, onPageFinished: (String url) async{ if (url == 'https://flutter.dev') { // *** I retrieve some data, then I want to navigate *** _controller!.loadUrl('https://google.com'); // *** ERROR HERE *** } }, ), ); } } </code></pre>
[ { "answer_id": 74425843, "author": "Saed Nabil", "author_id": 10660823, "author_profile": "https://Stackoverflow.com/users/10660823", "pm_score": 3, "selected": true, "text": "onPageFinished" }, { "answer_id": 74474255, "author": "Onur Kağan Aldemir", "author_id": 7335273, "author_profile": "https://Stackoverflow.com/users/7335273", "pm_score": 1, "selected": false, "text": "import 'dart:io';\n\nimport 'package:flutter/material.dart';\nimport 'package:webview_flutter/webview_flutter.dart';\n\nclass SamplePage extends StatefulWidget {\n const SamplePage({super.key});\n\n @override\n State<SamplePage> createState() => _SamplePageState();\n}\n\nclass _SamplePageState extends State<SamplePage> {\n late WebViewController _webViewController;\n Iterable<String> urlStrings = [\n 'https://www.google.com/',\n 'https://www.yahoo.com/',\n 'https://www.bing.com/',\n 'https://flutter.dev/',\n 'https://altavista.com/'\n ];\n late Iterator<String> urlIterator;\n\n @override\n void initState() {\n super.initState();\n // init url iterator.\n urlIterator = urlStrings.iterator;\n urlIterator.moveNext();\n\n // Enable virtual display.\n if (Platform.isAndroid) WebView.platform = AndroidWebView();\n }\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n body: WebView(\n onWebViewCreated: (controller) => setState(() => _webViewController = controller),\n initialUrl: urlIterator.current,\n onPageFinished: (url) {\n urlIterator.moveNext();\n _webViewController.loadUrl(urlIterator.current);\n },\n ),\n );\n }\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14728030/" ]
74,398,109
<p>Since I am a newbie, please tell me how I should add labels for each bar toward the right. And it would be kind of you to explain the code too... Thank you.</p> <p>This is the dataframe that I have used:</p> <pre><code> BG_donated Qty Hospital Location Contact 0 A- 25 Badr Al Sama Hospital Sohar 43445995 1 A+ 64 Aster Al Raffah Saham 58939595 2 B+ 41 Ibri Hospital Ibri 74823847 3 B- 35 Apollo Hospital Hamriyah 63947392 4 O- 51 Sultan Qaboos University Hospital Seeb 95821774 5 O+ 30 Al Hayat International Hospital Al Ghubra 44721402 6 AB- 46 KIMS Oman Hospital Darsait 37190481 7 AB+ 41 NMC Healthcare Specialty Hospital Ruwi 92810482 </code></pre> <p>This is the code for the horizontal bar graph:</p> <pre><code>y = df3['Qty'].sort_values() w = df3['Hospital'] c = ['coral', 'salmon', 'indianred', 'brown', 'crimson', 'aquamarine', 'lightseagreen', 'slategray'] mplt.title('Analysis Report I',size = 30) mplt.xlabel('Amount of Blood Donated',size = 15) mplt.ylabel('Hospitals',size = 15) mplt.barh(w,y,color = c) mplt.show() </code></pre> <p>And this is the output:</p> <p><a href="https://i.stack.imgur.com/g6CVA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g6CVA.png" alt="enter image description here" /></a></p> <p>Here is what I want it to look like: <a href="https://i.stack.imgur.com/L5EC7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L5EC7.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74398467, "author": "li Ju", "author_id": 20150045, "author_profile": "https://Stackoverflow.com/users/20150045", "pm_score": 3, "selected": true, "text": " mplt.text(values, i, '%s' %values)\" to your code.\n" }, { "answer_id": 74402504, "author": "li Ju", "author_id": 20150045, "author_profile": "https://Stackoverflow.com/users/20150045", "pm_score": 0, "selected": false, "text": "y = df3['Qty'].sort_values()\nw = df3['Hospital']\nb = df3['BG_donated']\nc = ['coral', 'salmon', 'indianred', 'brown', 'crimson', 'aquamarine', \n 'lightseagreen', 'slategray']\nmplt.title('Analysis Report I',size = 30)\nmplt.xlabel('Amount of Blood Donated',size = 15)\nmplt.ylabel('Hospitals',size = 15)\nmplt.barh(w,y,color = c)\n\nfor i,values in enumerate(y):\n mplt.text(values, i, f\"{b[i]}\")\nmplt.show()\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19705530/" ]
74,398,168
<p>I have something equivalent to this:</p> <pre><code>class Main { public static class Data { private void foo() {} } public &lt;D extends Data&gt; D process(D data) { data.foo(); return data; } } </code></pre> <p>The compiler complains:</p> <blockquote> <p><em>The method foo() from the type Main.Data is not visible</em></p> </blockquote> <p>I don't see why this shouldn't work. It compiles fine if I don't use generics in <code>process</code>:</p> <pre><code> public Data process(Data data) { data.foo(); return data; } </code></pre> <p>I want to use generics here so I can keep a fluent interface that returns the exact subclass of Data that is passed in, but I also want to keep Data's base members private to the outer class.</p> <p>Why is this happening and what are my options?</p>
[ { "answer_id": 74398467, "author": "li Ju", "author_id": 20150045, "author_profile": "https://Stackoverflow.com/users/20150045", "pm_score": 3, "selected": true, "text": " mplt.text(values, i, '%s' %values)\" to your code.\n" }, { "answer_id": 74402504, "author": "li Ju", "author_id": 20150045, "author_profile": "https://Stackoverflow.com/users/20150045", "pm_score": 0, "selected": false, "text": "y = df3['Qty'].sort_values()\nw = df3['Hospital']\nb = df3['BG_donated']\nc = ['coral', 'salmon', 'indianred', 'brown', 'crimson', 'aquamarine', \n 'lightseagreen', 'slategray']\nmplt.title('Analysis Report I',size = 30)\nmplt.xlabel('Amount of Blood Donated',size = 15)\nmplt.ylabel('Hospitals',size = 15)\nmplt.barh(w,y,color = c)\n\nfor i,values in enumerate(y):\n mplt.text(values, i, f\"{b[i]}\")\nmplt.show()\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/964243/" ]
74,398,172
<p>I've been having a strong headache with this problem, because I know for a fact should be a simple solution but I can't find the right answer.</p> <p>The idea is that I have two <code>UIViews</code> (let's call them A and B). All I want to do is to swap their positions on button press, by the A view going down to B position, and B view going up to A position.</p> <p><a href="https://ibb.co/pfK7SnR" rel="nofollow noreferrer">Here's what I'm trying to achieve.</a></p> <p>I'm trying to achieve that by just swapping the <code>.center</code> of the elements that I need (as A and B are both <code>UIViews</code> that cointains a bunch of elements inside them). This is inside an animation block - <code>UIView.animate</code></p> <p>However, what is currently happening is that the animation is performing in exactly the opposite way: <strong>The A view would go up the screen, then re-appear in the bottom side of the screen and end up in the desired position</strong> (B initial position). <strong>Same thing with the B view, it's currently going all the way to the bottom of the screen, then re-appear at the top, and finish the animation in the desired position</strong> (A initial position).</p> <p><a href="https://ibb.co/ynJXCS6" rel="nofollow noreferrer">This is what is currently happening.</a></p> <p>This is my code so far (note that <code>ownAccountTransferView</code> is defined in another file, and below code is placed in my UIViewController that stores that view). I call this function on button press, after swapping the the data (like labels and such) between the two cards.</p> <pre><code>fileprivate func performSwitchAnimation() { // NOTE: ownAccountTransferView is a reference to my view, think of it like self.view let fromAccountCardCenter = self.ownAccountTransferView.fromAccountCardView.center let fromAccountTypeLabelCenter = self.ownAccountTransferView.fromAccountTypeLabel.center let fromAccountTypeViewCenter = self.ownAccountTransferView.fromAccountTypeView.center let fromAccountBalanceLabelCenter = self.ownAccountTransferView.fromAccountBalanceLabel.center let fromAccountNameLabelCenter = self.ownAccountTransferView.fromAccountNameLabel.center let fromAccountChevronCenter = self.ownAccountTransferView.fromAccountChevronView.center let toAccountCardCenter = self.ownAccountTransferView.toAccountCardView.center let toAccountTypeLabelCenter = self.ownAccountTransferView.toAccountTypeLabel.center let toAccountTypeViewCenter = self.ownAccountTransferView.toAccountTypeView.center let toAccountBalanceLabelCenter = self.ownAccountTransferView.toAccountBalanceLabel.center let toAccountNameLabelCenter = self.ownAccountTransferView.toAccountNameLabel.center let toAccountChevronCenter = self.ownAccountTransferView.toAccountChevronView.center UIView.animate(withDuration: 1, delay: 0, options: []) { self.ownAccountTransferView.switchAccountsButton.isUserInteractionEnabled = false self.ownAccountTransferView.fromAccountCardView.center = toAccountCardCenter self.ownAccountTransferView.fromAccountTypeLabel.center = toAccountTypeLabelCenter self.ownAccountTransferView.fromAccountTypeView.center = toAccountTypeViewCenter self.ownAccountTransferView.fromAccountBalanceLabel.center = toAccountBalanceLabelCenter self.ownAccountTransferView.fromAccountNameLabel.center = toAccountNameLabelCenter self.ownAccountTransferView.fromAccountChevronView.center = toAccountChevronCenter self.ownAccountTransferView.toAccountCardView.center = fromAccountCardCenter self.ownAccountTransferView.toAccountTypeLabel.center = fromAccountTypeLabelCenter self.ownAccountTransferView.toAccountTypeView.center = fromAccountTypeViewCenter self.ownAccountTransferView.toAccountBalanceLabel.center = fromAccountBalanceLabelCenter self.ownAccountTransferView.toAccountNameLabel.center = fromAccountNameLabelCenter self.ownAccountTransferView.toAccountChevronView.center = fromAccountChevronCenter } completion: { isDone in if isDone { self.ownAccountTransferView.switchAccountsButton.isUserInteractionEnabled = true } } } </code></pre> <p>So, how can I make the animation work the way I want - <strong>A view going to the bottom and B view going to the top</strong>?</p> <p>Thanks in advance.</p> <p><strong>UPDATE: I fixed it by ussing transform.</strong> Tried messing around with animating constraints A LOT, tried every possible interaction between top/bottom constraints, but it would either not do anything at all or just bug my view and send it to hell. I even was insisting with animating constraints in support calls with my coworkers. And so were they. However, after googling despair measures, I ended up using <code>viewController.myView.myLabel.transform = CGAffineTransform(translationX: 0, y: 236)</code>.</p> <p>Of course, you can reduce this to: <code>view.transform = CGAffineTransform(translationX: 0, y: 236)</code>. The value is arbitrary, and I'm not sure if it can some day break or cause undesired behaviour. I tested it on iPhone 8 and iPhone 13, and in both the animations performs just ok (A view goes down, B goes up, click switch and do the opposite, etc...).</p> <p>Side note: If you gonna use this, <strong>you need to NOT copy/paste the values when you need your views to &quot;come back&quot; to where they were at the beginning</strong>. I used 236 and -236 for A and B respectively, but to restore them I need to use -2 and 2 or it super bugs out. Idk why tho. But it works! Thanks all</p>
[ { "answer_id": 74398467, "author": "li Ju", "author_id": 20150045, "author_profile": "https://Stackoverflow.com/users/20150045", "pm_score": 3, "selected": true, "text": " mplt.text(values, i, '%s' %values)\" to your code.\n" }, { "answer_id": 74402504, "author": "li Ju", "author_id": 20150045, "author_profile": "https://Stackoverflow.com/users/20150045", "pm_score": 0, "selected": false, "text": "y = df3['Qty'].sort_values()\nw = df3['Hospital']\nb = df3['BG_donated']\nc = ['coral', 'salmon', 'indianred', 'brown', 'crimson', 'aquamarine', \n 'lightseagreen', 'slategray']\nmplt.title('Analysis Report I',size = 30)\nmplt.xlabel('Amount of Blood Donated',size = 15)\nmplt.ylabel('Hospitals',size = 15)\nmplt.barh(w,y,color = c)\n\nfor i,values in enumerate(y):\n mplt.text(values, i, f\"{b[i]}\")\nmplt.show()\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6861143/" ]
74,398,176
<p>I want to create a MySQL syntax to select a field based on a variable, what I have is:</p> <pre><code>book_category = &quot;science&quot; mycursor_a.execute((&quot;SELECT {book_categories} FROM research_papers WHERE book_Name = %s&quot;, (book,)).format(book_categories = book_category)) </code></pre> <p>but I get the following error:</p> <pre><code>AttributeError: 'tuple' object has no attribute 'format' </code></pre>
[ { "answer_id": 74398467, "author": "li Ju", "author_id": 20150045, "author_profile": "https://Stackoverflow.com/users/20150045", "pm_score": 3, "selected": true, "text": " mplt.text(values, i, '%s' %values)\" to your code.\n" }, { "answer_id": 74402504, "author": "li Ju", "author_id": 20150045, "author_profile": "https://Stackoverflow.com/users/20150045", "pm_score": 0, "selected": false, "text": "y = df3['Qty'].sort_values()\nw = df3['Hospital']\nb = df3['BG_donated']\nc = ['coral', 'salmon', 'indianred', 'brown', 'crimson', 'aquamarine', \n 'lightseagreen', 'slategray']\nmplt.title('Analysis Report I',size = 30)\nmplt.xlabel('Amount of Blood Donated',size = 15)\nmplt.ylabel('Hospitals',size = 15)\nmplt.barh(w,y,color = c)\n\nfor i,values in enumerate(y):\n mplt.text(values, i, f\"{b[i]}\")\nmplt.show()\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1188943/" ]
74,398,213
<p>I have this regular expression <code>r'\b28\b'</code>. In this expression <code>28</code> should be dynamic. In other words, 28 is a dynamic value which the user enters. So, instead of 28 it can have 5. In that case, the expression would be <code>r'\b5\b'</code>.</p> <p>I tried the below two approaches but they are not working.</p> <ol> <li>r&quot;r'\b&quot; + room_number + r&quot;\b'&quot;</li> <li>&quot;r'\b&quot; + room_number + &quot;\b'&quot;</li> </ol> <p>I want to know how can I do it? Can someone please help me with it?</p>
[ { "answer_id": 74398283, "author": "BrokenBenchmark", "author_id": 17769815, "author_profile": "https://Stackoverflow.com/users/17769815", "pm_score": 1, "selected": false, "text": "re.escape" }, { "answer_id": 74398295, "author": "ljdyer", "author_id": 17568469, "author_profile": "https://Stackoverflow.com/users/17568469", "pm_score": 3, "selected": true, "text": "r" }, { "answer_id": 74399655, "author": "JL Peyret", "author_id": 1394353, "author_profile": "https://Stackoverflow.com/users/1394353", "pm_score": 1, "selected": false, "text": "import re\n\ndata = \"\"\"\nLook for 28\nLook for 42\n\"\"\"\n\ntarget = 28\npatre = re.compile(rf\"\\b{target}\\b\")\n\n\nfor line in data.splitlines():\n if patre.search(line):\n print(line)\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20443528/" ]
74,398,215
<p>We have a POST api and we can send multiple files in a request.</p> <p>I created a csv file with all file Names. Its updating same filename each json object.</p> <p>How can i get the unique filename in json object from csv? Or is there any approch to get unique files from a file?</p> <p><strong>Request:</strong></p> <pre><code>[ { &quot;filePath&quot;: &quot;Filename1&quot;, &quot;orgId&quot;: &quot;org123&quot;, &quot;Domain&quot;: &quot;abcd.com&quot;, }, { &quot;filePath&quot;: &quot;Filename2&quot;, &quot;orgId&quot;: &quot;org123&quot;, &quot;Domain&quot;: &quot;abcd.com&quot;, },{ &quot;filePath&quot;: &quot;Filename3&quot;, &quot;orgId&quot;: &quot;org123&quot;, &quot;Domain&quot;: &quot;abcd.com&quot;, },{ &quot;filePath&quot;: &quot;Filename4&quot;, &quot;orgId&quot;: &quot;org123&quot;, &quot;Domain&quot;: &quot;abcd.com&quot;, },{ &quot;filePath&quot;: &quot;Filename5&quot;, &quot;orgId&quot;: &quot;org123&quot;, &quot;Domain&quot;: &quot;abcd.com&quot;, } ] </code></pre> <p><a href="https://i.stack.imgur.com/A3Gu8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A3Gu8.png" alt="CSV config" /></a></p> <p><a href="https://i.stack.imgur.com/qEJuk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qEJuk.png" alt="CSV file" /></a></p> <p><a href="https://i.stack.imgur.com/C5sbz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C5sbz.png" alt="Jmete Sampler" /></a></p>
[ { "answer_id": 74410721, "author": "Dmitri T", "author_id": 2897748, "author_profile": "https://Stackoverflow.com/users/2897748", "pm_score": 1, "selected": false, "text": "{\n \"filePath\": \"filename from CSV here\",\n \"orgId\": \"org123\",\n \"Domain\": \"abcd.com\",\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6582190/" ]
74,398,231
<p>I found some weird behaviour during the creation of classes and objects in python3.</p> <p>I dislike typing every time &quot;self&quot; word and constructors during writing classes if my class is very simple so I made the class 'Foo' that copies static variables and turns them into the new object's attributes.</p> <p>At the beginning I was making 'Foo' subclasses without methods and then everything worked fine - the objects were distinct. However, after adding a method to the subclass, I found out that the self value somehow points to wrong object.</p> <p>Here is the code I made:</p> <pre><code>from copy import deepcopy class Foo: def __init__(self): for i in filter(lambda x: &quot;__&quot; not in x, self.__dir__()): self.__setattr__(i, deepcopy(self.__getattribute__(i))) class Bar(Foo): val = [] def func(self): print(&quot;Self ID:&quot;, id(self)) print(self.val) obj = Bar() obj.val.append(2) print(&quot;Object ID:&quot;, id(obj)) print(obj.val) obj.func() # Prints: # # Object ID: 2507794284496 # [2] # Self ID: 2507794283248 # [] # # While it should print same ID and [2] in both lists </code></pre> <p>I am sure that I forgot something important during creation of the Foo class because if I remove &quot;(Foo)&quot; part then IDs and the lists are the same.</p> <p>Could someone explain me what is wrong? Thank you in advance for help! &lt;3</p>
[ { "answer_id": 74398492, "author": "hadi purnomo", "author_id": 9002661, "author_profile": "https://Stackoverflow.com/users/9002661", "pm_score": -1, "selected": false, "text": "class Bar(Foo):\n def __init__(self):\n super().__init__(self)\n self.val = []\n\n def func(self):\n print(\"Self ID:\", id(self))\n print(self.val)\n" }, { "answer_id": 74398531, "author": "user2357112", "author_id": 2357112, "author_profile": "https://Stackoverflow.com/users/2357112", "pm_score": 2, "selected": false, "text": "self.func" }, { "answer_id": 74398745, "author": "Amae Saeki", "author_id": 9630049, "author_profile": "https://Stackoverflow.com/users/9630049", "pm_score": 1, "selected": true, "text": "from copy import deepcopy\n\n\nclass Foo:\n def __init__(self):\n for i in filter(lambda x: \"__\" not in x, self.__dir__()):\n attr = self.__getattribute__(i)\n if attr.__class__.__name__ != 'method':\n self.__setattr__(i, deepcopy(attr))\n\n\nclass Bar(Foo):\n val = []\n\n def func(self):\n print(\"Self ID:\", id(self))\n print(self.val)\n\n\nobj = Bar()\nobj.val.append(2)\nprint(\"Object ID:\", id(obj))\nprint(obj.val)\nobj.func()\n\n# Object ID: 2785572945632\n# [2]\n# Self ID: 2785572945632\n# [2]\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9630049/" ]
74,398,250
<pre><code>[[1.0, 1.0], [1.0, 10.0], [1.0, 11.0], [1.0, 12.0], [1.0, 13.0]], [[2.0, 1.0], [2.0, 10.0], [2.0, 11.0], [2.0, 12.0], [2.0, 13.0]], [[3.0, 1.0], [3.0, 10.0], [3.0, 11.0], [3.0, 12.0], [3.0, 13.0]], [[4.0, 1.0], [4.0, 10.0], [4.0, 11.0], [4.0, 12.0], [4.0, 13.0]], [[4.0, 1.0], [4.0, 10.0], [4.0, 11.0], [4.0, 12.0], [4.0, 13.0]]] </code></pre> <p>If I have a list like this, how do I return the duplicate rows as different groups?</p> <p>I don't know how to compare if two lists are same when there are sub-list in them.</p> <p>For this problem, the ideal output would be:</p> <p>[[[4.0, 1.0], [4.0, 10.0], [4.0, 11.0], [4.0, 12.0], [4.0, 13.0]],</p> <p>[[4.0, 1.0], [4.0, 10.0], [4.0, 11.0], [4.0, 12.0], [4.0, 13.0]]]</p>
[ { "answer_id": 74398492, "author": "hadi purnomo", "author_id": 9002661, "author_profile": "https://Stackoverflow.com/users/9002661", "pm_score": -1, "selected": false, "text": "class Bar(Foo):\n def __init__(self):\n super().__init__(self)\n self.val = []\n\n def func(self):\n print(\"Self ID:\", id(self))\n print(self.val)\n" }, { "answer_id": 74398531, "author": "user2357112", "author_id": 2357112, "author_profile": "https://Stackoverflow.com/users/2357112", "pm_score": 2, "selected": false, "text": "self.func" }, { "answer_id": 74398745, "author": "Amae Saeki", "author_id": 9630049, "author_profile": "https://Stackoverflow.com/users/9630049", "pm_score": 1, "selected": true, "text": "from copy import deepcopy\n\n\nclass Foo:\n def __init__(self):\n for i in filter(lambda x: \"__\" not in x, self.__dir__()):\n attr = self.__getattribute__(i)\n if attr.__class__.__name__ != 'method':\n self.__setattr__(i, deepcopy(attr))\n\n\nclass Bar(Foo):\n val = []\n\n def func(self):\n print(\"Self ID:\", id(self))\n print(self.val)\n\n\nobj = Bar()\nobj.val.append(2)\nprint(\"Object ID:\", id(obj))\nprint(obj.val)\nobj.func()\n\n# Object ID: 2785572945632\n# [2]\n# Self ID: 2785572945632\n# [2]\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317476/" ]
74,398,260
<p>The project uses Spring-Security OAUTH 2. An Angular application is used as a web client. And as a Keycloak authorization server. The Angular application sends requests to the Spring application via the Spring GateWay.</p> <p>When I try to send a Get request, I get an error</p> <pre><code>has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. </code></pre> <p>file Pom.xml</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;2.7.2&lt;/version&gt; &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;groupId&gt;com.amrut.prabhu&lt;/groupId&gt; &lt;artifactId&gt;spring-cloud-gateway-keycloak-oauth2&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;name&gt;Spring Cloud Gateway Oauth2 With Keycloak&lt;/name&gt; &lt;description&gt;spring cloud gateway with keycloak oauth2&lt;/description&gt; &lt;properties&gt; &lt;java.version&gt;17&lt;/java.version&gt; &lt;spring-cloud.version&gt;2021.0.1&lt;/spring-cloud.version&gt; &lt;lombok.version&gt;1.18.22&lt;/lombok.version&gt; &lt;logback-access-spring-boot-starter.version&gt;3.1.2&lt;/logback-access-spring-boot-starter.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-oauth2-client&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt; &lt;artifactId&gt;spring-cloud-starter-gateway&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.projectlombok&lt;/groupId&gt; &lt;artifactId&gt;lombok&lt;/artifactId&gt; &lt;version&gt;${lombok.version}&lt;/version&gt; &lt;optional&gt;true&lt;/optional&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;dependencyManagement&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt; &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt; &lt;version&gt;${spring-cloud.version}&lt;/version&gt; &lt;type&gt;pom&lt;/type&gt; &lt;scope&gt;import&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/dependencyManagement&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt;</code></pre> </div> </div> </p> <p>SecurityConfig</p> <pre><code>@Configuration public class SecurityConfig { @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http, ServerLogoutSuccessHandler handler) { http .cors() .and() .csrf().disable() .authorizeExchange() .pathMatchers(&quot;/actuator/**&quot;, &quot;/&quot;,&quot;/logout.html&quot;) .permitAll() .and() .authorizeExchange() .anyExchange() .authenticated() .and() .oauth2Login() // to redirect to oauth2 login page. .and() .logout() .logoutSuccessHandler(handler) ; return http.build(); } @Bean public ServerLogoutSuccessHandler keycloakLogoutSuccessHandler(ReactiveClientRegistrationRepository repository) { OidcClientInitiatedServerLogoutSuccessHandler oidcLogoutSuccessHandler = new OidcClientInitiatedServerLogoutSuccessHandler(repository); oidcLogoutSuccessHandler.setPostLogoutRedirectUri(&quot;{baseUrl}/logout.html&quot;); return oidcLogoutSuccessHandler; } } </code></pre> <p>I tried to register in the Spring Gateway properties file, from this post <a href="https://stackoverflow.com/questions/61189793/spring-gateway-request-blocked-by-cors-no-acces0control-allow-orgin-header">cors</a></p> <pre><code>spring: cloud: gateway: default-filters: - TokenRelay - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin globalcors: corsConfigurations: '[/**]': allowedOrigins: &quot;*&quot; allowedMethods: &quot;*&quot; allowedHeaders: &quot;*&quot; </code></pre> <p>I also tried to determine the global configuration of CORS, according to this article</p> <p><a href="https://www.baeldung.com/spring-webflux-cors" rel="nofollow noreferrer">baeldung.com</a></p> <pre><code>@Configuration @EnableWebFlux public class CorsGlobalConfiguration implements WebFluxConfigurer { @Override public void addCorsMappings(CorsRegistry corsRegistry) { corsRegistry.addMapping(&quot;/**&quot;) .allowedOrigins(&quot;http://localhost:4200&quot;) .allowedMethods(&quot;PUT&quot;) .allowedMethods(&quot;GET&quot;) .allowedHeaders(&quot;Baeldung-Allowed&quot;, &quot;Baledung-Another-Allowed&quot;) .exposedHeaders(&quot;Baeldung-Allowed&quot;, &quot;Baeldung-Exposed&quot;) .maxAge(3600); } } </code></pre> <p>I still get an error What am I doing wrong? I add all the necessary headers. What else does he need? And the @CrossOrigin annotation on the method always worked before.</p> <p>The following two options also did not help solve the problem:</p> <pre><code>@Configuration public class CorsWebFilterConfig { @Bean CorsWebFilter corsWebFilter() { CorsConfiguration corsConfig = new CorsConfiguration(); corsConfig.setAllowedOrigins(Arrays.asList(&quot;http://localhost:4200&quot;)); corsConfig.setMaxAge(8000L); corsConfig.addAllowedMethod(&quot;PUT&quot;); corsConfig.addAllowedMethod(&quot;GET&quot;); // corsConfig.addAllowedHeader(&quot;Baeldung-Allowed&quot;); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); source.registerCorsConfiguration(&quot;/**&quot;, corsConfig); return new CorsWebFilter(source); } } </code></pre> <p>OR</p> <pre><code>@Configuration public class CorsWebFilterConfig implements WebFilter { @Override public Mono&lt;Void&gt; filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) { ServerHttpRequest request = serverWebExchange.getRequest(); ServerHttpResponse response = serverWebExchange.getResponse(); HttpHeaders headers = response.getHeaders(); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, &quot;http://localhost:4200&quot;); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, &quot;POST, GET, PUT, OPTIONS, DELETE, PATCH&quot;); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, &quot;true&quot;); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, &quot;*&quot;); headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, &quot;*&quot;); headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, &quot;18000L&quot;); if (request.getMethod() == HttpMethod.OPTIONS) { response.setStatusCode(HttpStatus.OK); return Mono.empty();//HERE } return webFilterChain.filter(serverWebExchange); } } </code></pre> <p>The annotation on the method does not work either</p> <pre><code>@CrossOrigin(origins = &quot;http://localhost:4200&quot;) </code></pre> <p>Here are the contents of the network tab, the first request is OPTIONS, the second is GET</p> <pre><code>Request URL: http://10.151.68.8:8484/auth/realms/demo/protocol/openid-connect/auth?response_type=code&amp;client_id=spring-gateway-client&amp;scope=message.write&amp;state=dnAY-OwNUBGKuvZE5-3AH3L6v9W8OA5V67bD-U2YgiA%3D&amp;redirect_uri=http://localhost:9090/login/oauth2/code/keycloak Request Method: OPTIONS Status Code: 200 OK Remote Address: 10.151.68.8:8484 Referrer Policy: no-referrer Response Connection: keep-alive Content-Length: 25 Content-Type: application/json Date: Wed, 16 Nov 2022 07:34:59 GMT Referrer-Policy: no-referrer Strict-Transport-Security: max-age=31536000; includeSubDomains X-Content-Type-Options: nosniff X-Frame-Options: SAMEORIGIN X-XSS-Protection: 1; mode=block Request Accept: */* Accept-Encoding: gzip, deflate Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7 Access-Control-Request-Headers: authorization Access-Control-Request-Method: GET Connection: keep-alive Host: 10.151.68.8:8484 Origin: null Sec-Fetch-Mode: cors User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 </code></pre> <p>For some reason, the Origin = null field in the request Perhaps this is the reason for cors? It turns out that Gateway sends a verification request to the authorization server with Origin = null and receives a cors error.</p>
[ { "answer_id": 74398492, "author": "hadi purnomo", "author_id": 9002661, "author_profile": "https://Stackoverflow.com/users/9002661", "pm_score": -1, "selected": false, "text": "class Bar(Foo):\n def __init__(self):\n super().__init__(self)\n self.val = []\n\n def func(self):\n print(\"Self ID:\", id(self))\n print(self.val)\n" }, { "answer_id": 74398531, "author": "user2357112", "author_id": 2357112, "author_profile": "https://Stackoverflow.com/users/2357112", "pm_score": 2, "selected": false, "text": "self.func" }, { "answer_id": 74398745, "author": "Amae Saeki", "author_id": 9630049, "author_profile": "https://Stackoverflow.com/users/9630049", "pm_score": 1, "selected": true, "text": "from copy import deepcopy\n\n\nclass Foo:\n def __init__(self):\n for i in filter(lambda x: \"__\" not in x, self.__dir__()):\n attr = self.__getattribute__(i)\n if attr.__class__.__name__ != 'method':\n self.__setattr__(i, deepcopy(attr))\n\n\nclass Bar(Foo):\n val = []\n\n def func(self):\n print(\"Self ID:\", id(self))\n print(self.val)\n\n\nobj = Bar()\nobj.val.append(2)\nprint(\"Object ID:\", id(obj))\nprint(obj.val)\nobj.func()\n\n# Object ID: 2785572945632\n# [2]\n# Self ID: 2785572945632\n# [2]\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18723075/" ]
74,398,276
<p>I'm in Odoo15 and i want to modify the header in Odoo view</p> <p>I have <strong>Quotations / S00156</strong> like in the image, but the client want only the first 3 numbers, should look something like this <strong>Quotations / S156</strong></p> <p>How can I modify this in Odoo? I only have to modify the way it looks like in this view. Thanks! :)</p> <p><a href="https://i.stack.imgur.com/cku8v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cku8v.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74398492, "author": "hadi purnomo", "author_id": 9002661, "author_profile": "https://Stackoverflow.com/users/9002661", "pm_score": -1, "selected": false, "text": "class Bar(Foo):\n def __init__(self):\n super().__init__(self)\n self.val = []\n\n def func(self):\n print(\"Self ID:\", id(self))\n print(self.val)\n" }, { "answer_id": 74398531, "author": "user2357112", "author_id": 2357112, "author_profile": "https://Stackoverflow.com/users/2357112", "pm_score": 2, "selected": false, "text": "self.func" }, { "answer_id": 74398745, "author": "Amae Saeki", "author_id": 9630049, "author_profile": "https://Stackoverflow.com/users/9630049", "pm_score": 1, "selected": true, "text": "from copy import deepcopy\n\n\nclass Foo:\n def __init__(self):\n for i in filter(lambda x: \"__\" not in x, self.__dir__()):\n attr = self.__getattribute__(i)\n if attr.__class__.__name__ != 'method':\n self.__setattr__(i, deepcopy(attr))\n\n\nclass Bar(Foo):\n val = []\n\n def func(self):\n print(\"Self ID:\", id(self))\n print(self.val)\n\n\nobj = Bar()\nobj.val.append(2)\nprint(\"Object ID:\", id(obj))\nprint(obj.val)\nobj.func()\n\n# Object ID: 2785572945632\n# [2]\n# Self ID: 2785572945632\n# [2]\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19883757/" ]
74,398,278
<p>I am using reactjs. On the frontend I am getting the time in format &quot;mm:ss&quot; example data:</p> <pre><code>const data [{ duration: &quot;00:10&quot; //I want 10 }, { duration: &quot;20:00&quot; //I want 1200 }, { duration: &quot;30:00&quot; // I want 1800 }] </code></pre> <p>I tried this and a lot but could not work</p> <pre><code>moment.duration(&quot;30:00&quot;).asSeconds() </code></pre> <p>These duration are in mm:ss format and I want them to convert to just seconds. How can I do that either using Javascript or moment js?</p> <p>Thanks</p>
[ { "answer_id": 74398492, "author": "hadi purnomo", "author_id": 9002661, "author_profile": "https://Stackoverflow.com/users/9002661", "pm_score": -1, "selected": false, "text": "class Bar(Foo):\n def __init__(self):\n super().__init__(self)\n self.val = []\n\n def func(self):\n print(\"Self ID:\", id(self))\n print(self.val)\n" }, { "answer_id": 74398531, "author": "user2357112", "author_id": 2357112, "author_profile": "https://Stackoverflow.com/users/2357112", "pm_score": 2, "selected": false, "text": "self.func" }, { "answer_id": 74398745, "author": "Amae Saeki", "author_id": 9630049, "author_profile": "https://Stackoverflow.com/users/9630049", "pm_score": 1, "selected": true, "text": "from copy import deepcopy\n\n\nclass Foo:\n def __init__(self):\n for i in filter(lambda x: \"__\" not in x, self.__dir__()):\n attr = self.__getattribute__(i)\n if attr.__class__.__name__ != 'method':\n self.__setattr__(i, deepcopy(attr))\n\n\nclass Bar(Foo):\n val = []\n\n def func(self):\n print(\"Self ID:\", id(self))\n print(self.val)\n\n\nobj = Bar()\nobj.val.append(2)\nprint(\"Object ID:\", id(obj))\nprint(obj.val)\nobj.func()\n\n# Object ID: 2785572945632\n# [2]\n# Self ID: 2785572945632\n# [2]\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6838854/" ]
74,398,301
<p>There are 2 lists. What I am trying to do is to find the occurrence of first list elements and will hold the values of second list for a key in first list and in the end, it will become dictionary holding specific keys from list 1 and values from list 2</p> <p>Input:</p> <pre><code>list1 = ['A', 'A', 'B', 'B', 'C', 'D'] list2 = [1, 2, 3, 4, 5, 6] </code></pre> <p>Expected Output:</p> <pre><code>{'A': [1, 2], 'B': [3, 4], 'C': [5], 'D':[6]} </code></pre> <p>Current Output:</p> <pre><code>{'A': [1, 2], 'B': [4], 'C': []} </code></pre> <p>What I tried so far,</p> <pre><code>values = [list2[0]] key = list1[0] dic = {} for i in range(1, len(list1)): if list1[i] == list1[i - 1]: values.append(list2[i]) elif list1[i] != list1[i - 1]: dic.update({key: values}) values = [] key = list1[i] print(dic) </code></pre> <p>List 1 and List 2 are always equal in length and sorted</p>
[ { "answer_id": 74398492, "author": "hadi purnomo", "author_id": 9002661, "author_profile": "https://Stackoverflow.com/users/9002661", "pm_score": -1, "selected": false, "text": "class Bar(Foo):\n def __init__(self):\n super().__init__(self)\n self.val = []\n\n def func(self):\n print(\"Self ID:\", id(self))\n print(self.val)\n" }, { "answer_id": 74398531, "author": "user2357112", "author_id": 2357112, "author_profile": "https://Stackoverflow.com/users/2357112", "pm_score": 2, "selected": false, "text": "self.func" }, { "answer_id": 74398745, "author": "Amae Saeki", "author_id": 9630049, "author_profile": "https://Stackoverflow.com/users/9630049", "pm_score": 1, "selected": true, "text": "from copy import deepcopy\n\n\nclass Foo:\n def __init__(self):\n for i in filter(lambda x: \"__\" not in x, self.__dir__()):\n attr = self.__getattribute__(i)\n if attr.__class__.__name__ != 'method':\n self.__setattr__(i, deepcopy(attr))\n\n\nclass Bar(Foo):\n val = []\n\n def func(self):\n print(\"Self ID:\", id(self))\n print(self.val)\n\n\nobj = Bar()\nobj.val.append(2)\nprint(\"Object ID:\", id(obj))\nprint(obj.val)\nobj.func()\n\n# Object ID: 2785572945632\n# [2]\n# Self ID: 2785572945632\n# [2]\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15749060/" ]
74,398,311
<p>I have a lot of categorical columns and want to convert values in those columns to numerical values so that I will be able to apply ML model.</p> <p>Now by data looks something like below.</p> <p>Column 1- Good/bad/poor/not reported column 2- Red/amber/green column 3- 1/2/3 column 4- Yes/No</p> <p>Now I have already assigned numerical values of 1,2,3,4 to good, bad, poor, not reported in column 1 .</p> <p>So, now can I give the same numerical values like 1,2,3 to red,green, amber etc in column 2 and in a similar fashion to other columns or will doing that confuse model when I implement it</p>
[ { "answer_id": 74398610, "author": "ai_10111", "author_id": 17209580, "author_profile": "https://Stackoverflow.com/users/17209580", "pm_score": 0, "selected": false, "text": "red = 100\namber = 010\ngreen = 001\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19476450/" ]
74,398,314
<p>Please find the attached Groovy code which I am using to get the particular filed from the response body.</p> <p>Query 1 :</p> <p>It is retrieving the results when the I am using the correct Index value like if the data.RenewalDetails[o], will give output as Value 1 and if the data.RenewalDetails[1], output as Value 2.</p> <p>But in my real case, I will never know about number of blocks in the response, so I want to get all the values that are satisficing the condition, I tried data.RenewalDetails[*] but it is not working. Can you please help ?</p> <p>Query 2:</p> <p>Apart from the above condition, I want to add one more filter, where &quot;FamilyCode&quot;: &quot;PREMIUM&quot; in the Itemdetails, Can you help on the same ?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>def BoundId = new groovy.json.JsonSlurper().parseText('{"data":{"RenewalDetails":[{"ExpiryDetails":{"duration":"xxxxx","destination":"LHR","from":"AUH","value":2,"segments":[{"valudeid":"xxx-xx6262-xxxyyy-1111-11-11-1111"}]},"Itemdetails":[{"BoundId":"Value1","isexpired":true,"FamilyCode":"PREMIUM","availabilityDetails":[{"travelID":"AAA-AB1234-AAABBB-2022-11-10-1111","quota":"X","scale":"XXX","class":"X"}]}]},{"ExpiryDetails":{"duration":"xxxxx","destination":"LHR","from":"AUH","value":2,"segments":[{"valudeid":"xxx-xx6262-xxxyyy-1111-11-11-1111"}]},"Itemdetails":[{"BoundId":"Value2","isexpired":true,"FamilyCode":"PREMIUM","availabilityDetails":[{"travelID":"AAA-AB1234-AAABBB-2022-11-10-1111","quota":"X","scale":"XXX","class":"X"}]}]}]},"warnings":[{"code":"xxxx","detail":"xxxxxxxx","title":"xxxxxxxx"}]}') .data.RenewalDetails[0].Itemdetails.find { itemDetail -&gt; itemDetail.availabilityDetails[0].travelID.length() == 33 }?.BoundId println "Hello " + BoundId</code></pre> </div> </div> </p>
[ { "answer_id": 74398610, "author": "ai_10111", "author_id": 17209580, "author_profile": "https://Stackoverflow.com/users/17209580", "pm_score": 0, "selected": false, "text": "red = 100\namber = 010\ngreen = 001\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19685966/" ]
74,398,335
<p>I write a odoo program in python, this way request type <strong>text/plain</strong> is working. And <strong>application/json</strong> request work in any other odoo version(Odoo 15,Odoo 16) .But odoo 13 application/json request not working.</p> <p><strong>My odoo python controller code here:-</strong></p> <pre><code>class CamsAttendance(http.Controller): @http.route('/sample/sample_json/', method=[&quot;POST&quot;], csrf=False, auth='public', type=&quot;http&quot;) def generate_attendance(self, **params): data = json.loads(request.httprequest.data) json_object = json.dumps(data) sample = json.loads(json_object) print(sample['sample_code']) return &quot;process competed&quot; //example </code></pre> <p>view the image on request and response data via postman:- <a href="https://i.stack.imgur.com/tc164.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tc164.png" alt="enter image description here" /></a></p> <p><strong>Request application/json data:-</strong> (sample request)</p> <pre><code>{ &quot;sample_code&quot;:&quot;sample_code&quot; } </code></pre> <p><strong>Response data:-</strong></p> <pre><code>{ &quot;jsonrpc&quot;: &quot;2.0&quot;, &quot;id&quot;: null, &quot;error&quot;: { &quot;code&quot;: 200, &quot;message&quot;: &quot;Odoo Server Error&quot;, &quot;data&quot;: { &quot;name&quot;: &quot;werkzeug.exceptions.BadRequest&quot;, &quot;debug&quot;: &quot;Traceback (most recent call last):\n File \&quot;C:\\odoo 13\\Odoo 13.0\\server\\odoo\\http.py\&quot;, line 624, in _handle_exception\n return super(JsonRequest, self)._handle_exception(exception)\n File \&quot;C:\\odoo 13\\Odoo 13.0\\server\\odoo\\http.py\&quot;, line 310, in _handle_exception\n raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])\n File \&quot;C:\\odoo 13\\Odoo 13.0\\server\\odoo\\tools\\pycompat.py\&quot;, line 14, in reraise\n raise value\n File \&quot;C:\\odoo 13\\Odoo 13.0\\server\\odoo\\http.py\&quot;, line 669, in dispatch\n result = self._call_function(**self.params)\n File \&quot;C:\\odoo 13\\Odoo 13.0\\server\\odoo\\http.py\&quot;, line 318, in _call_function\n raise werkzeug.exceptions.BadRequest(msg % params)\nwerkzeug.exceptions.BadRequest: 400 Bad Request: &lt;function CamsAttendance.generate_attendance at 0x0644C930&gt;, /cams/biometric-api3.0: Function declared as capable of handling request of type 'http' but called with a request of type 'json'\n&quot;, &quot;message&quot;: &quot;400 Bad Request: &lt;function CamsAttendance.generate_attendance at 0x0644C930&gt;, /cams/biometric-api3.0: Function declared as capable of handling request of type 'http' but called with a request of type 'json'&quot;, &quot;arguments&quot;: [], &quot;exception_type&quot;: &quot;internal_error&quot;, &quot;context&quot;: {} } } } </code></pre> <p><strong>Another way try :-</strong> I note the error ** 'http' but called with a request of type 'json'&quot;** in the response and i change the code contoroller code on @http.route('/sample/sample_json/', method=[&quot;POST&quot;], csrf=False, auth='public', <strong>type=&quot;json&quot;</strong>)</p> <p>But,</p> <p><strong>Response:-</strong></p> <pre><code>{ &quot;jsonrpc&quot;: &quot;2.0&quot;, &quot;id&quot;: null, &quot;result&quot;: &quot;process competed&quot; } </code></pre> <p>** but i want :-** &quot;process competed</p> <p>Mainly this problem Odoo 13 only. And i what process the code and expecting text message the response</p>
[ { "answer_id": 74398610, "author": "ai_10111", "author_id": 17209580, "author_profile": "https://Stackoverflow.com/users/17209580", "pm_score": 0, "selected": false, "text": "red = 100\namber = 010\ngreen = 001\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19718656/" ]
74,398,345
<p>I had a technical test for an entry-level job 2 days ago. It went well apart from the last assessment. I will go over the assessment with the CTO tomorrow and was hoping I could get help to get my head around this one, so I do not sound clueless. It was something like this:</p> <p><em><strong>Given string as an argument, give us palindrome method that would check if a palindrome of a minimum 3 characters can be created by removing 1 or 2 characters. The string has no special characters, numbers or whitespace basically only letters (eg: str = &quot;abecbea&quot;) If true, print letters removed, if false print &quot;not possible&quot;</strong></em></p> <p>&quot;remove 1 or 2 characters&quot; and &quot;print letters removed&quot; is giving me a headache legit</p> <p>I have tried a lot of different things but for the last 2 days but i am completely stuck! [EDIT]</p> <p>Ideas i started with below</p> <pre><code> def is_palindrome(s) s == s.reverse &amp;&amp; s.length &gt;= 3 end def possible_palin_by_removing_one_char(s) array_chars = s.chars first_char = array_chars[0] last_char = array_chars[-1] while first_char &lt; last_char if first_char != last_char first_char += 1 last_char -= 1 else if is_palindrome puts ???? else puts &quot;not possible&quot; end end end end </code></pre> <p>or</p> <pre><code>def palindrome?(string) deleted_chars = [] candidates = 0.upto(string.length-1).map do |index| array_chars = string.chars deleted_chars &lt;&lt; array_chars.delete_at(index) array_chars end if candidates.any? { |c| c.reverse == c } &amp;&amp; string.length &gt;= 3 puts &quot;It is a palindrome with letters '#{deleted_chars.join(&quot;,&quot;)}' removed !&quot; # puts deleted_chars else if string.length &lt;= 3 puts &quot;String '#{string}' is too short&quot; else puts &quot;This is not possible to create palindrome with string '#{string}'&quot; end end end palindrome?(&quot;abcecbae&quot;) </code></pre> <p>I would love someone to help me solve this one Thanks heaps for your help</p>
[ { "answer_id": 74405756, "author": "steenslag", "author_id": 290394, "author_profile": "https://Stackoverflow.com/users/290394", "pm_score": 2, "selected": false, "text": "ar = str.chars" }, { "answer_id": 74405832, "author": "Konstantin Strukov", "author_id": 8008340, "author_profile": "https://Stackoverflow.com/users/8008340", "pm_score": 1, "selected": false, "text": "Enumerable#permutation" }, { "answer_id": 74427167, "author": "PaulineTW", "author_id": 16621883, "author_profile": "https://Stackoverflow.com/users/16621883", "pm_score": 0, "selected": false, "text": "def palindrome_check(str)\n length = str.length\n # convert to array of chars\n chars = str.chars\n\n # check if palindrome by deleting 1 characters\n length.times do |i|\n char = chars.delete_at(i)\n return \"Letter '#{char}' has been removed from String '#{str}' to create palindrome\" if chars == chars.reverse\n\n # return the array to original condition\n chars.insert(i, char)\n end\n\n # only do remove 2 characters check if length > 4, as otherwise removing would result in a string less than 3 characters\n if length > 4\n length.times do |i|\n length.times do |j|\n # avoid repeating the same checks\n next if j <= i\n # since j is always greater than i, remove j first to avoid affecting which character is at position i\n char_two = chars.delete_at(j)\n char_one = chars.delete_at(i)\n\n return \"Letters '#{[char_one, char_two].join(' and ')}' has been removed from String '#{str}' to create palindrome\" if chars == chars.reverse\n\n # return the array to original condition\n chars.insert(i, char_one)\n chars.insert(j, char_two)\n end\n end\n end\n\n return \"'#{str}' can't be a Palindrome\"\nend\n\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16621883/" ]
74,398,350
<p><a href="https://i.stack.imgur.com/0yDsf.png" rel="nofollow noreferrer">https://i.stack.imgur.com/0yDsf.png</a></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>year</th> <th>month</th> <th>no_of_people</th> <th>avg</th> </tr> </thead> <tbody> <tr> <td>2005</td> <td>1</td> <td>Overall</td> <td>8</td> </tr> <tr> <td>2005</td> <td>2</td> <td>Overall</td> <td>5.0</td> </tr> <tr> <td>2005</td> <td>3</td> <td>Overall</td> <td>2.7</td> </tr> <tr> <td>2005</td> <td>4</td> <td>Overall</td> <td>4.1</td> </tr> <tr> <td>2005</td> <td>5</td> <td>Overall</td> <td>6.8</td> </tr> <tr> <td>2005</td> <td>6</td> <td>Overall</td> <td>5.2</td> </tr> <tr> <td>2005</td> <td>7</td> <td>Overall</td> <td>4.7</td> </tr> <tr> <td>2005</td> <td>8</td> <td>Overall</td> <td>4.4</td> </tr> <tr> <td>2005</td> <td>9</td> <td>Overall</td> <td>3.8</td> </tr> <tr> <td>2005</td> <td>10</td> <td>Overall</td> <td>7</td> </tr> <tr> <td>2005</td> <td>11</td> <td>Overall</td> <td>4.9</td> </tr> <tr> <td>2005</td> <td>12</td> <td>Overall</td> <td>6.5</td> </tr> </tbody> </table> </div> <p>My issue lies in essentially calculating the avg of three months (123, 456, etc) and displaying this new value as quarterly average of Q1/2/3/4 (indicating Quarters). Sorry for formatting, but an ideal output would be something like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>year</th> <th>quarter</th> <th>no_of_people</th> <th>avg</th> </tr> </thead> <tbody> <tr> <td>2005</td> <td>Q1</td> <td>Overall</td> <td>xxx</td> </tr> <tr> <td>2005</td> <td>Q2</td> <td>Overall</td> <td>xxx</td> </tr> </tbody> </table> </div> <p>Not sure how to even begin with this query and how to group the months into quarters. Any thanks would be very much appreciated!</p>
[ { "answer_id": 74398680, "author": "Akina", "author_id": 10138734, "author_profile": "https://Stackoverflow.com/users/10138734", "pm_score": 2, "selected": true, "text": "CREATE TABLE test (\n `year` YEAR,\n `month` TINYINT,\n sub_housing_type VARCHAR(8),\n `avg` DECIMAL(3,1));\nINSERT INTO test VALUES\n(2005, 1, 'Overall', 90.1),\n(2005, 2, 'Overall', 88.9),\n(2005, 3, 'Overall', 88.9),\n(2005, 4, 'Overall', 90.2),\n(2005, 5, 'Overall', 86.8),\n(2005, 6, 'Overall', 87),\n(2005, 7, 'Overall', 84.8),\n(2005, 8, 'Overall', 88.1),\n(2005, 9, 'Overall', 88.9),\n(2005, 10, 'Overall', 87.5),\n(2005, 11, 'Overall', 89.1),\n(2005, 12, 'Overall', 83.7);\nSELECT * FROM test;\n" }, { "answer_id": 74398730, "author": "FanoFN", "author_id": 10910692, "author_profile": "https://Stackoverflow.com/users/10910692", "pm_score": 0, "selected": false, "text": "date" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20474812/" ]
74,398,384
<blockquote> <p>I am new at flutter. I am currently using FlutterFlow to develop and for custom coding I am using Flutter on VS code.<br /> I think I am doing something wrong while installing flutter (check flutter doctor) that's why I am getting this error.<br /> Please let me know what is going wrong.<br /> FYI - App runs on emulator and I am able to do USB debug but not able to make APK.</p> </blockquote> <p><strong>Terminal</strong> -</p> <pre><code>parthsheth@Parths-MacBook-Air fineappl-pat % flutter build apk Building with sound null safety Target android_aot_release_android-arm failed: ProcessException: Bad CPU type in executable Command: /Users/parthsheth/Developer/flutter/bin/cache/artifacts/engine/android-arm-release/darwin-x64/gen_snapshot --deterministic --snapshot_kind=app-aot-elf --elf=/Users/parthsheth/Developer/New pat/fineappl-pat/.dart_tool/flutter_build/17315c88eac0b66d5360d145b85fb5b9/armeabi-v7a/app.so --strip --no-sim-use-hardfp --no-use-integer-division /Users/parthsheth/Developer/New pat/fineappl-pat/.dart_tool/flutter_build/17315c88eac0b66d5360d145b85fb5b9/app.dill Target android_aot_release_android-arm64 failed: ProcessException: Bad CPU type in executable Command: /Users/parthsheth/Developer/flutter/bin/cache/artifacts/engine/android-arm64-release/darwin-x64/gen_snapshot --deterministic --snapshot_kind=app-aot-elf --elf=/Users/parthsheth/Developer/New pat/fineappl-pat/.dart_tool/flutter_build/17315c88eac0b66d5360d145b85fb5b9/arm64-v8a/app.so --strip /Users/parthsheth/Developer/New pat/fineappl-pat/.dart_tool/flutter_build/17315c88eac0b66d5360d145b85fb5b9/app.dill Target android_aot_release_android-x64 failed: ProcessException: Bad CPU type in executable Command: /Users/parthsheth/Developer/flutter/bin/cache/artifacts/engine/android-x64-release/darwin-x64/gen_snapshot --deterministic --snapshot_kind=app-aot-elf --elf=/Users/parthsheth/Developer/New pat/fineappl-pat/.dart_tool/flutter_build/17315c88eac0b66d5360d145b85fb5b9/x86_64/app.so --strip /Users/parthsheth/Developer/New pat/fineappl-pat/.dart_tool/flutter_build/17315c88eac0b66d5360d145b85fb5b9/app.dill FAILURE: Build failed with an exception. * Where: Script '/Users/parthsheth/Developer/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 1165 * What went wrong: Execution failed for task ':app:compileFlutterBuildRelease'. &gt; Process 'command '/Users/parthsheth/Developer/flutter/bin/flutter'' finished with non-zero exit value 1 * Try: &gt; Run with --stacktrace option to get the stack trace. &gt; Run with --info or --debug option to get more log output. &gt; Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 8s Running Gradle task 'assembleRelease'... 9.7s Gradle task assembleRelease failed with exit code 1 </code></pre> <blockquote> <p>I don't know if this a system error or code error.<br /> Let me know what other information y'all to address the problem.</p> </blockquote> <p><strong>Flutter Doctor</strong> -</p> <pre><code>parthsheth@Parths-MacBook-Air ~ % flutter doctor Doctor summary (to see all details, run flutter doctor -v): [!] Flutter (Channel master, 3.5.0-12.0.pre.130, on macOS 13.0 22A380 darwin-arm64, locale en-IN) ✗ Downloaded executables cannot execute on host. See https://github.com/flutter/flutter/issues/6207 for more information [✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0) [✓] Xcode - develop for iOS and macOS (Xcode 14.0) [✓] Chrome - develop for the web [✓] Android Studio (version 2021.3) [✓] VS Code (version 1.71.2) [✓] Connected device (2 available) [✓] HTTP Host Availability ! Doctor found issues in 1 category. </code></pre>
[ { "answer_id": 74398680, "author": "Akina", "author_id": 10138734, "author_profile": "https://Stackoverflow.com/users/10138734", "pm_score": 2, "selected": true, "text": "CREATE TABLE test (\n `year` YEAR,\n `month` TINYINT,\n sub_housing_type VARCHAR(8),\n `avg` DECIMAL(3,1));\nINSERT INTO test VALUES\n(2005, 1, 'Overall', 90.1),\n(2005, 2, 'Overall', 88.9),\n(2005, 3, 'Overall', 88.9),\n(2005, 4, 'Overall', 90.2),\n(2005, 5, 'Overall', 86.8),\n(2005, 6, 'Overall', 87),\n(2005, 7, 'Overall', 84.8),\n(2005, 8, 'Overall', 88.1),\n(2005, 9, 'Overall', 88.9),\n(2005, 10, 'Overall', 87.5),\n(2005, 11, 'Overall', 89.1),\n(2005, 12, 'Overall', 83.7);\nSELECT * FROM test;\n" }, { "answer_id": 74398730, "author": "FanoFN", "author_id": 10910692, "author_profile": "https://Stackoverflow.com/users/10910692", "pm_score": 0, "selected": false, "text": "date" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19472423/" ]
74,398,396
<p>I wanted to delete each line after clicking its corresponding delete. I couldn't track the parent-child things. What is wrong in my code?</p> <p>My HTML</p> <pre><code> &lt;div class=&quot;li&quot;&gt; &lt;li&gt; Apple &lt;button&gt;Delete&lt;/button&gt;&lt;/li&gt; &lt;li&gt; Ball &lt;button&gt;Delete&lt;/button&gt;&lt;/li&gt; &lt;li&gt; Cat &lt;button&gt;Delete&lt;/button&gt;&lt;/li&gt; &lt;li&gt; Dog &lt;button&gt;Delete&lt;/button&gt;&lt;/li&gt; &lt;/div&gt; </code></pre> <p>JS</p> <pre><code>let btn = document.querySelectorAll('button') console.log(btn) btn.forEach(element =&gt; { element.addEventListener(&quot;click&quot;, function(){ console.log(&quot;Hi there boys.&quot;) let prnt = document.querySelectorAll('.li li') for(let i = 0; i&lt;prnt.length; ++i) { // console.log(prnt[i].parentNode.children) prnt.removeChild(prnt[i].parentNode.firstElementChild) } }) }) </code></pre>
[ { "answer_id": 74398680, "author": "Akina", "author_id": 10138734, "author_profile": "https://Stackoverflow.com/users/10138734", "pm_score": 2, "selected": true, "text": "CREATE TABLE test (\n `year` YEAR,\n `month` TINYINT,\n sub_housing_type VARCHAR(8),\n `avg` DECIMAL(3,1));\nINSERT INTO test VALUES\n(2005, 1, 'Overall', 90.1),\n(2005, 2, 'Overall', 88.9),\n(2005, 3, 'Overall', 88.9),\n(2005, 4, 'Overall', 90.2),\n(2005, 5, 'Overall', 86.8),\n(2005, 6, 'Overall', 87),\n(2005, 7, 'Overall', 84.8),\n(2005, 8, 'Overall', 88.1),\n(2005, 9, 'Overall', 88.9),\n(2005, 10, 'Overall', 87.5),\n(2005, 11, 'Overall', 89.1),\n(2005, 12, 'Overall', 83.7);\nSELECT * FROM test;\n" }, { "answer_id": 74398730, "author": "FanoFN", "author_id": 10910692, "author_profile": "https://Stackoverflow.com/users/10910692", "pm_score": 0, "selected": false, "text": "date" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20464620/" ]
74,398,429
<p>I want to show pagination on my page based on the data from the resource collection.</p> <p>I have done this code for get data in collection and paginate.</p> <pre><code> return auth()-&gt;user()-&gt;hasRole('admin') ? ArticleResource::collection(Article::latest()-&gt;paginate(5)) : ArticleResource::collection(auth()-&gt;user()-&gt;articles()-&gt;latest()-&gt;paginate(5)); </code></pre>
[ { "answer_id": 74398680, "author": "Akina", "author_id": 10138734, "author_profile": "https://Stackoverflow.com/users/10138734", "pm_score": 2, "selected": true, "text": "CREATE TABLE test (\n `year` YEAR,\n `month` TINYINT,\n sub_housing_type VARCHAR(8),\n `avg` DECIMAL(3,1));\nINSERT INTO test VALUES\n(2005, 1, 'Overall', 90.1),\n(2005, 2, 'Overall', 88.9),\n(2005, 3, 'Overall', 88.9),\n(2005, 4, 'Overall', 90.2),\n(2005, 5, 'Overall', 86.8),\n(2005, 6, 'Overall', 87),\n(2005, 7, 'Overall', 84.8),\n(2005, 8, 'Overall', 88.1),\n(2005, 9, 'Overall', 88.9),\n(2005, 10, 'Overall', 87.5),\n(2005, 11, 'Overall', 89.1),\n(2005, 12, 'Overall', 83.7);\nSELECT * FROM test;\n" }, { "answer_id": 74398730, "author": "FanoFN", "author_id": 10910692, "author_profile": "https://Stackoverflow.com/users/10910692", "pm_score": 0, "selected": false, "text": "date" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20211778/" ]
74,398,433
<pre class="lang-cs prettyprint-override"><code> protected void Page_Load(object sender, EventArgs e) { } protected void cusCustom_ServerValidate(object source, ServerValidateEventArgs args) { var dropDownValue = drpState.SelectedItem.Text; if (dropDownValue == &quot;&quot; &amp;&amp; args.Value.Length &lt; 1 ) { args.IsValid = false; } else { args.IsValid = true; } } ---------------------------------------- &lt;asp:DropDownList ID=&quot;drpState&quot; runat=&quot;server&quot; CausesValidation=&quot;True&quot;&gt; &lt;asp:ListItem&gt;&lt;/asp:ListItem&gt; &lt;asp:ListItem Value=&quot;IL&quot;&gt;Illinois&lt;/asp:ListItem&gt; &lt;asp:ListItem Value=&quot;IN&quot;&gt;Indiana&lt;/asp:ListItem&gt; &lt;asp:ListItem Value=&quot;IA&quot;&gt;Iowa&lt;/asp:ListItem&gt; &lt;/asp:DropDownList&gt; &lt;asp:TextBox ID=&quot;txtRegion&quot; runat=&quot;server&quot;&gt;&lt;/asp:TextBox&gt; &lt;asp:Button ID=&quot;btnSubmit&quot; ValidationGroup=&quot;test&quot; auto Text=&quot;Submit&quot; OnClientClick=&quot; validateFields()&quot; runat=&quot;server&quot; /&gt; &lt;asp:CustomValidator ValidationGroup=&quot;test&quot; ID=&quot;CustomValidator&quot; OnServerValidate=&quot;cusCustom_ServerValidate&quot; ForeColor=&quot;Red&quot; ErrorMessage=&quot;Please fill all fields.&quot; ValidateEmptyText =&quot;true&quot; ControlToValidate=&quot;txtRegion&quot; runat=&quot;server&quot;&gt; &lt;/asp:CustomValidator&gt; </code></pre> <p>I have two fields textbox and drop down and after that I have asp custom validator when both fields are empty and I try to submit that it fire error. But the error still shows after page refresh how can I remove it?</p>
[ { "answer_id": 74398515, "author": "Jan", "author_id": 2582968, "author_profile": "https://Stackoverflow.com/users/2582968", "pm_score": 2, "selected": false, "text": "public DummyClass {\n public string Name {get;set;}\n}\n" }, { "answer_id": 74398641, "author": "Defria Manda", "author_id": 2840333, "author_profile": "https://Stackoverflow.com/users/2840333", "pm_score": 0, "selected": false, "text": "void Main()\n{\n // Using Newtonsoft.Json\n var result = \" {\\\"Distance\\\":0.0,\\\"BookingLink\\\":null,\\\"Images\\\":null,\\\"HotelID\\\":105304,\\\"Name\\\":\\\"Hyatt Regency Century Plaza\\\",\\\"AirportCode\\\": \\\"\\\"}\";\n var hotel = JsonConvert.DeserializeObject<Hotel>(result);\n Console.WriteLine(hotel.Name);\n}\n\n// Create the object class structure based on your JSON string results\npublic class Hotel\n{\n public double Distance { get; set; }\n public string BookingLink { get; set; }\n public object Images { get; set; }\n public int HotelID { get; set; }\n public string Name { get; set; }\n public string AirportCode { get; set; }\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16233808/" ]
74,398,466
<p>I tried this</p> <pre><code>if ($('nav li.menu-item-has-children:has(ul)')) $ ('nav li.menu-item-has-children a').append ( &quot;&lt;span class=\&quot;plus-minus\&quot;&gt;+&lt;/span&gt;&quot;); </code></pre> <p>but all the anchor tags child menus are also getting the same HTML element Added</p> <p>this is the menu structute</p> <pre><code>&lt;ul id=&quot;primary-menu&quot; class=&quot;menu&quot;&gt; &lt;li class=&quot;menu-item &quot;&gt;&lt;a href=&quot;home/&quot;&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;menu-item&quot; &gt;&lt;a href=&quot;about&quot;&gt;About &lt;span class=\&quot;plus-minus\&quot;&gt;+&lt;/span&gt;&lt;/a&gt; &lt;ul class=&quot;sub-menu&quot;&gt; &lt;li class=&quot;menu-item&quot;&gt;&lt;a href=&quot;basics/&quot;&gt;Basic&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class=&quot;menu-item menu-item-has-children&quot;&gt;&lt;a href=&quot;products&quot; aria-current=&quot;page&quot;&gt;Products&lt;/a&gt; &lt;ul class=&quot;sub-menu&quot;&gt; &lt;li class=&quot;menu-item&quot;&gt;&lt;a href=&quot;Product-1&quot;&gt;Product-1&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;menu-item &quot;&gt;&lt;a href=&quot;Product-2&quot;&gt;Product-2&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;menu-item &quot;&gt;&lt;a href=&quot;Product-3&quot;&gt;Product-3&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;menu-item &quot;&gt;&lt;a href=&quot;Product-4&quot;&gt;Product-4&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;menu-item &quot;&gt;&lt;a href=&quot;Product-5&quot;&gt;Product-5&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;menu-item &quot;&gt;&lt;a href=&quot;Product-6&quot;&gt;Product-6&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class=&quot;menu-item&quot;&gt;&lt;a href=&quot;contact-us/&quot;&gt;Contact Us&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>i want it to be</p> <pre><code>&lt;ul id=&quot;primary-menu&quot; class=&quot;menu&quot;&gt; &lt;li class=&quot;menu-item &quot;&gt;&lt;a href=&quot;home/&quot;&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;menu-item&quot; &gt;&lt;a href=&quot;about&quot;&gt;About &lt;span class=\&quot;plus-minus\&quot;&gt;+&lt;/span&gt; &lt;/a&gt; &lt;ul class=&quot;sub-menu&quot;&gt; &lt;li class=&quot;menu-item&quot;&gt;&lt;a href=&quot;basics/&quot;&gt;Basic&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class=&quot;menu-item menu-item-has-children&quot;&gt;&lt;a href=&quot;products&quot; aria-current=&quot;page&quot;&gt;Products &lt;span class=\&quot;plus-minus\&quot;&gt;+&lt;/span&gt;&lt;/a&gt; &lt;ul class=&quot;sub-menu&quot;&gt; &lt;li class=&quot;menu-item&quot;&gt;&lt;a href=&quot;Product-1&quot;&gt;Product-1&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;menu-item &quot;&gt;&lt;a href=&quot;Product-2&quot;&gt;Product-2&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;menu-item &quot;&gt;&lt;a href=&quot;Product-3&quot;&gt;Product-3&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;menu-item &quot;&gt;&lt;a href=&quot;Product-4&quot;&gt;Product-4&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;menu-item &quot;&gt;&lt;a href=&quot;Product-5&quot;&gt;Product-5&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;menu-item &quot;&gt;&lt;a href=&quot;Product-6&quot;&gt;Product-6&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class=&quot;menu-item&quot;&gt;&lt;a href=&quot;contact-us/&quot;&gt;Contact Us&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; if ($('nav li.menu-item-has-children:has(ul)')) $ ('nav li.menu-item-has-children a').append ( &quot;&lt;span class=\&quot;plus-minus\&quot;&gt;+&lt;/span&gt;&quot;); </code></pre>
[ { "answer_id": 74398515, "author": "Jan", "author_id": 2582968, "author_profile": "https://Stackoverflow.com/users/2582968", "pm_score": 2, "selected": false, "text": "public DummyClass {\n public string Name {get;set;}\n}\n" }, { "answer_id": 74398641, "author": "Defria Manda", "author_id": 2840333, "author_profile": "https://Stackoverflow.com/users/2840333", "pm_score": 0, "selected": false, "text": "void Main()\n{\n // Using Newtonsoft.Json\n var result = \" {\\\"Distance\\\":0.0,\\\"BookingLink\\\":null,\\\"Images\\\":null,\\\"HotelID\\\":105304,\\\"Name\\\":\\\"Hyatt Regency Century Plaza\\\",\\\"AirportCode\\\": \\\"\\\"}\";\n var hotel = JsonConvert.DeserializeObject<Hotel>(result);\n Console.WriteLine(hotel.Name);\n}\n\n// Create the object class structure based on your JSON string results\npublic class Hotel\n{\n public double Distance { get; set; }\n public string BookingLink { get; set; }\n public object Images { get; set; }\n public int HotelID { get; set; }\n public string Name { get; set; }\n public string AirportCode { get; set; }\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9456137/" ]
74,398,490
<p>I have a dataframe which contains double quote (&quot;) and comma in value. I am trying to export the dataframe into csv but unfortunately double quote is not displayed properly in exported csv.</p> <p>I managed to handle all other special characters by setting &quot;quoteAll&quot; to true.</p> <p>In csv, if you replace the single double quote with two double quotes, it works fine. But when I export to csv with below code, it replaces &quot; with &quot; in exported csv.</p> <pre><code>%scala import org.apache.spark.sql.functions.regexp_replace val df = Seq((1, &quot;A,B,C,\&quot;DEF\&quot;&quot;), (2, &quot;DEF&quot;)).toDF(&quot;ID&quot;, &quot;Val&quot;) val updatedDf = df.columns.foldLeft(df)((acc, colname) =&gt; acc.withColumn(colname,regexp_replace(acc(s&quot;`$colname`&quot;), &quot;\&quot;&quot;, &quot;\&quot;\&quot;&quot;))) deltaDS.coalesce(1).write .option(&quot;header&quot;, true) .option(&quot;encoding&quot;, &quot;utf-8&quot;) .option(&quot;quoteAll&quot;, true) .mode(&quot;Overwrite&quot;).csv(&quot;[Location to store csv]&quot;) </code></pre> <p><strong>Output:</strong></p> <p><a href="https://i.stack.imgur.com/AfoP6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AfoP6.png" alt="enter image description here" /></a></p> <p><strong>Expected Output:</strong></p> <p><a href="https://i.stack.imgur.com/WpRsS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WpRsS.png" alt="enter image description here" /></a></p> <p>How can I handle this ?</p>
[ { "answer_id": 74398515, "author": "Jan", "author_id": 2582968, "author_profile": "https://Stackoverflow.com/users/2582968", "pm_score": 2, "selected": false, "text": "public DummyClass {\n public string Name {get;set;}\n}\n" }, { "answer_id": 74398641, "author": "Defria Manda", "author_id": 2840333, "author_profile": "https://Stackoverflow.com/users/2840333", "pm_score": 0, "selected": false, "text": "void Main()\n{\n // Using Newtonsoft.Json\n var result = \" {\\\"Distance\\\":0.0,\\\"BookingLink\\\":null,\\\"Images\\\":null,\\\"HotelID\\\":105304,\\\"Name\\\":\\\"Hyatt Regency Century Plaza\\\",\\\"AirportCode\\\": \\\"\\\"}\";\n var hotel = JsonConvert.DeserializeObject<Hotel>(result);\n Console.WriteLine(hotel.Name);\n}\n\n// Create the object class structure based on your JSON string results\npublic class Hotel\n{\n public double Distance { get; set; }\n public string BookingLink { get; set; }\n public object Images { get; set; }\n public int HotelID { get; set; }\n public string Name { get; set; }\n public string AirportCode { get; set; }\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2988458/" ]
74,398,502
<p>I'm new to c and I'm trying to make a function to return the max between two numbers, and I don't know why it does not work, it does not show anything</p> <pre><code>int max(int num1, int num2) { int result; if (num1 &gt; num2) result = num1; else result = num2; return result; } int main() { int result = max(1,2); printf(&quot;%c&quot;, result); } </code></pre>
[ { "answer_id": 74398537, "author": "hknjj", "author_id": 1925445, "author_profile": "https://Stackoverflow.com/users/1925445", "pm_score": 2, "selected": false, "text": "printf(\"%d\", result);\n" }, { "answer_id": 74398560, "author": "SouL SprayGod", "author_id": 19771597, "author_profile": "https://Stackoverflow.com/users/19771597", "pm_score": 2, "selected": false, "text": "#include <stdio.h>\n\nint max(int num1, int num2) {\n int result;\n if (num1 > num2)\n result = num1;\n else\n result = num2;\n return result;\n}\nint main() {\n int result = max(1, 2);\n\n printf(\"%d\", result);\n return 0;\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19205134/" ]
74,398,534
<p>I'm using this <a href="https://github.com/bokuweb/re-resizable" rel="nofollow noreferrer">re-resizable</a> library to achieve the resize functionality. The requirement is to achieve the one-side resizing, which means if I resize from the right side of the div, only that side should expand to the right. The left side should stay in the same position.</p> <p>I've read the docs and played around with the props but no luck. Thank you.</p> <p>Here is my <a href="https://codesandbox.io/s/lucid-bessie-ejptco?file=/src/App.js" rel="nofollow noreferrer">codesandbox</a>.</p>
[ { "answer_id": 74398537, "author": "hknjj", "author_id": 1925445, "author_profile": "https://Stackoverflow.com/users/1925445", "pm_score": 2, "selected": false, "text": "printf(\"%d\", result);\n" }, { "answer_id": 74398560, "author": "SouL SprayGod", "author_id": 19771597, "author_profile": "https://Stackoverflow.com/users/19771597", "pm_score": 2, "selected": false, "text": "#include <stdio.h>\n\nint max(int num1, int num2) {\n int result;\n if (num1 > num2)\n result = num1;\n else\n result = num2;\n return result;\n}\nint main() {\n int result = max(1, 2);\n\n printf(\"%d\", result);\n return 0;\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12267640/" ]
74,398,546
<p>I have a state which is used to render some components conditionally, I have the following structure:</p> <pre class="lang-js prettyprint-override"><code> const SearchScreen = () =&gt; { const [isSearchBarFocused, setIsSearchBarFocused] = React.useState(false); return ( &lt;&gt; &lt;SearchBar onFocus={setIsSearchBarFocused} /&gt; {isSearchBarFocuse ? &lt;SearchSuggestionList isSearchBarFocused={isSearchBarFocused} setIsSearchBarFocused={setIsSearchBarFocused} /&gt; : null} &lt;/&gt; ) } </code></pre> <p>As you can see in the code above, the state seter is shared by both components, when the <code>&lt;SearchBar /&gt;</code> is focused the state changes to <code>true</code> and when an option is selected from the <code>&lt;SearchSuggestionList /&gt;</code> the state change to <code>false</code>. The problem with this approach is that I need to run some API calls and other inner state updates in <code>&lt;SearchSuggestionList /&gt;</code> component but this is unmounted due to the conditional rendering then some processes are not reached to be carried out.</p> <p>then how would I execute code that is inside a component that can be unmounted?</p>
[ { "answer_id": 74399414, "author": "kaledev", "author_id": 20419301, "author_profile": "https://Stackoverflow.com/users/20419301", "pm_score": -1, "selected": false, "text": "const SearchScreen = () => {\n const [isSearchBarFocused, setIsSearchBarFocused] = React.useState(false);\n\n return (\n <>\n <SearchBar onFocus={setIsSearchBarFocused} />\n {isSearchBarFocused && <SearchSuggestionList isSearchBarFocused={isSearchBarFocused} setIsSearchBarFocused={setIsSearchBarFocused} />}\n </>\n )\n\n}\n" }, { "answer_id": 74399582, "author": "Anh Le Hoang", "author_id": 16315750, "author_profile": "https://Stackoverflow.com/users/16315750", "pm_score": 1, "selected": false, "text": "SearchScreen" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8582246/" ]
74,398,563
<p>I'm unable to use polars dataframes with scikitlearn for ML training.</p> <p>Currently I'm doing all the dataframe preprocessing in polars and during model training i'm converting it into a pandas one in order for it to work.</p> <p>Is there any method to directly use polars dataframe as it is for ML training without changing it to pandas?</p>
[ { "answer_id": 74399414, "author": "kaledev", "author_id": 20419301, "author_profile": "https://Stackoverflow.com/users/20419301", "pm_score": -1, "selected": false, "text": "const SearchScreen = () => {\n const [isSearchBarFocused, setIsSearchBarFocused] = React.useState(false);\n\n return (\n <>\n <SearchBar onFocus={setIsSearchBarFocused} />\n {isSearchBarFocused && <SearchSuggestionList isSearchBarFocused={isSearchBarFocused} setIsSearchBarFocused={setIsSearchBarFocused} />}\n </>\n )\n\n}\n" }, { "answer_id": 74399582, "author": "Anh Le Hoang", "author_id": 16315750, "author_profile": "https://Stackoverflow.com/users/16315750", "pm_score": 1, "selected": false, "text": "SearchScreen" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20474952/" ]
74,398,569
<p>I am stuck on an issue. Let's say I have a home page. From this home page, I want to route to either page A or page B.</p> <p>I have a list of items on the home page and what I need to do is when I click on any item in the list, it makes a GET API call, and based on one field in the response which is a boolean, I either need to redirect to page A or page B.</p> <p>Basically, I need to call an API on the click of the item and get the response before it is routed to either Page A or Page B.</p> <p>Many thanks in advance</p>
[ { "answer_id": 74398678, "author": "Sparsh Jain", "author_id": 11662604, "author_profile": "https://Stackoverflow.com/users/11662604", "pm_score": 1, "selected": false, "text": "import {useRouter} from \"next/router\";\n\nexport default function Page() {\n const router = useRouter()\n\n async function route() {\n let res = await apiFunctionCall();\n if (res) {\n await router.replace({\n pathname: '/page1'\n })\n } else {\n await router.replace({\n pathname: 'page2'\n })\n }\n }\n}\n" }, { "answer_id": 74398802, "author": "ANISH SAJI KUMAR", "author_id": 12309235, "author_profile": "https://Stackoverflow.com/users/12309235", "pm_score": 0, "selected": false, "text": "res" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14833974/" ]
74,398,573
<p>I need to read an XML file that has chars in some node contents and I need to keep that chars as is and avoid converting them into new lines. Those nodes have xmldsig signatures and converting chars into new lines invalidate the signatures.</p> <p>I have tried loading the XML with XmlDocument.Load, XmlReader, StreamReader and the special chars ends up converted into new lines.</p> <hr /> <p>UPDATE with an XML sample</p> <pre><code>&lt;?xml version=&quot;1.0&quot;?&gt; &lt;catalog&gt; &lt;book&gt; &lt;description&gt;description&amp;#13; with&amp;#13; several&amp;#13; lines&amp;#13; &lt;/description&gt; &lt;/book&gt; &lt;Signature xmlns=&quot;http://www.w3.org/2000/09/xmldsig#&quot;&gt; ... &lt;/Signature&gt; &lt;/catalog&gt; </code></pre>
[ { "answer_id": 74398700, "author": "ANISH SAJI KUMAR", "author_id": 12309235, "author_profile": "https://Stackoverflow.com/users/12309235", "pm_score": -1, "selected": false, "text": "&#13;" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12380224/" ]
74,398,581
<p>Scenario: When the user clicks on it, the data should be passed into <code>someFunction()</code>.</p> <pre class="lang-html prettyprint-override"><code>&lt;span id=&quot;someid&quot; onClick={() =&gt; someFunction()} data-video-page=&quot;some data&quot; class=&quot;dot&quot; /&gt;` </code></pre> <p>I tried using <code>getAttributes()</code>, <code>querySelector()</code> methods until now to get the data from data attributes. But one of them are working, in fact they are returning none.</p>
[ { "answer_id": 74398629, "author": "ANISH SAJI KUMAR", "author_id": 12309235, "author_profile": "https://Stackoverflow.com/users/12309235", "pm_score": 0, "selected": false, "text": "data*" }, { "answer_id": 74398699, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 3, "selected": true, "text": "React.js" }, { "answer_id": 74399008, "author": "Mhmdrz_A", "author_id": 5953610, "author_profile": "https://Stackoverflow.com/users/5953610", "pm_score": 0, "selected": false, "text": "const someFunction = console.log;\n\nfunction App() {\n return (\n <span id=\"someid\" \n onClick={(e) => {\n const videoPage = event.target.dataset['videoPage'];\n someFunction(videoPage)\n }} \n data-video-page=\"some data\" \n className=\"dot\" \n >\n click me\n </span>\n )\n}\n\nReactDOM.render(<App />, document.getElementById('root'));" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18445570/" ]
74,398,582
<p>My question is this.</p> <p>I would like to add custom annotation to spring boot and designate it as declared without declaring a specific logic.</p> <p>Suppose you have the following code:</p> <pre><code>@MyCustomAnnotation @Controller public class ExController { @RequestMapping(value = &quot;/index&quot;, method = RequestMethod.GET) public String index(Model model){ return &quot;index&quot;; } } </code></pre> <p>I want the above code to perform the following logic.</p> <pre><code>@MyCustomAnnotation @Controller public class ExController { @RequestMapping(value = &quot;/index&quot;, method = RequestMethod.GET) public String index(Model model){ //Code added because it has an annotation model.addAttribute(&quot;key&quot;,&quot;value&quot;); //Code added because it has an annotation return &quot;index&quot;; } } </code></pre> <p>I've been thinking about Reflection and other methods, but I can't think of the right way</p> <p>Can someone grateful give a solution or keyword for this problem?</p>
[ { "answer_id": 74398629, "author": "ANISH SAJI KUMAR", "author_id": 12309235, "author_profile": "https://Stackoverflow.com/users/12309235", "pm_score": 0, "selected": false, "text": "data*" }, { "answer_id": 74398699, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 3, "selected": true, "text": "React.js" }, { "answer_id": 74399008, "author": "Mhmdrz_A", "author_id": 5953610, "author_profile": "https://Stackoverflow.com/users/5953610", "pm_score": 0, "selected": false, "text": "const someFunction = console.log;\n\nfunction App() {\n return (\n <span id=\"someid\" \n onClick={(e) => {\n const videoPage = event.target.dataset['videoPage'];\n someFunction(videoPage)\n }} \n data-video-page=\"some data\" \n className=\"dot\" \n >\n click me\n </span>\n )\n}\n\nReactDOM.render(<App />, document.getElementById('root'));" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19825816/" ]
74,398,584
<pre><code>/Users/avinashkasukurthi/Developer/Flutter Projects/zopnote/consumer-app/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'gRPC-C++' from project 'Pods') warning: Run script build phase 'Create Symlinks to Header Folders' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking &quot;Based on dependency analysis&quot; in the script phase. (in target 'gRPC-C++' from project 'Pods') warning: Run script build phase 'Run Script' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking &quot;Based on dependency analysis&quot; in the script phase. (in target 'Runner' from project 'Runner') warning: Run script build phase 'Thin Binary' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking &quot;Based on dependency analysis&quot; in the script phase. (in target 'Runner' from project 'Runner') Result bundle written to path: /var/folders/vv/l96pnk5d49z96x0w400w0r0m0000gn/T/flutter_tools.jlRzPP/flutter_ios_build_temp_dira4jNaQ/temporary_xcresult_bundle </code></pre> <p>Could not build the application for the simulator. Error launching application on iPhone 13.</p>
[ { "answer_id": 74398629, "author": "ANISH SAJI KUMAR", "author_id": 12309235, "author_profile": "https://Stackoverflow.com/users/12309235", "pm_score": 0, "selected": false, "text": "data*" }, { "answer_id": 74398699, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 3, "selected": true, "text": "React.js" }, { "answer_id": 74399008, "author": "Mhmdrz_A", "author_id": 5953610, "author_profile": "https://Stackoverflow.com/users/5953610", "pm_score": 0, "selected": false, "text": "const someFunction = console.log;\n\nfunction App() {\n return (\n <span id=\"someid\" \n onClick={(e) => {\n const videoPage = event.target.dataset['videoPage'];\n someFunction(videoPage)\n }} \n data-video-page=\"some data\" \n className=\"dot\" \n >\n click me\n </span>\n )\n}\n\nReactDOM.render(<App />, document.getElementById('root'));" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18458940/" ]
74,398,596
<p>I'm using vanilla JS and I want to persist data on <code>localStorage</code> when page refreshes:</p> <p><strong>main.js</strong></p> <pre><code>localStorage.setItem(&quot;language&quot;, &quot;ar&quot;); const toEnglish = (e) =&gt; { if (e.target.closest(&quot;.english&quot;)) { localStorage.setItem(&quot;language&quot;, &quot;en&quot;); } }; document.addEventListener(&quot;click&quot;, (e) =&gt; toEnglish(e)); </code></pre> <p>however, after setting <code>language</code> to <code>en</code> on <code>localStorage</code>, if the page refreshes the value resets to <code>ar</code>, i wonder why it doesn't persist the value like in <code>reactJS</code> ?</p>
[ { "answer_id": 74398629, "author": "ANISH SAJI KUMAR", "author_id": 12309235, "author_profile": "https://Stackoverflow.com/users/12309235", "pm_score": 0, "selected": false, "text": "data*" }, { "answer_id": 74398699, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 3, "selected": true, "text": "React.js" }, { "answer_id": 74399008, "author": "Mhmdrz_A", "author_id": 5953610, "author_profile": "https://Stackoverflow.com/users/5953610", "pm_score": 0, "selected": false, "text": "const someFunction = console.log;\n\nfunction App() {\n return (\n <span id=\"someid\" \n onClick={(e) => {\n const videoPage = event.target.dataset['videoPage'];\n someFunction(videoPage)\n }} \n data-video-page=\"some data\" \n className=\"dot\" \n >\n click me\n </span>\n )\n}\n\nReactDOM.render(<App />, document.getElementById('root'));" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20403738/" ]
74,398,603
<p>I am creating cloudFormation stack for s3 bucket (with the help of yaml template file). Is there a way by which we can automatically delete the created buckets? Can we configure the yaml templates such that the s3 bucket gets deleted after some time of its creation? If not what is the best way to programmaticaly delete the s3 buckets?</p> <p>Tried to add</p> <pre><code>DeletionPolicy: Delete </code></pre> <p>But it is for retention of deleted files.</p>
[ { "answer_id": 74398629, "author": "ANISH SAJI KUMAR", "author_id": 12309235, "author_profile": "https://Stackoverflow.com/users/12309235", "pm_score": 0, "selected": false, "text": "data*" }, { "answer_id": 74398699, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 3, "selected": true, "text": "React.js" }, { "answer_id": 74399008, "author": "Mhmdrz_A", "author_id": 5953610, "author_profile": "https://Stackoverflow.com/users/5953610", "pm_score": 0, "selected": false, "text": "const someFunction = console.log;\n\nfunction App() {\n return (\n <span id=\"someid\" \n onClick={(e) => {\n const videoPage = event.target.dataset['videoPage'];\n someFunction(videoPage)\n }} \n data-video-page=\"some data\" \n className=\"dot\" \n >\n click me\n </span>\n )\n}\n\nReactDOM.render(<App />, document.getElementById('root'));" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317320/" ]
74,398,650
<pre><code>protocol Readable {} extension Readable { func text() -&gt; String? { &quot;in protocol&quot; } } struct Book: Readable { func text() -&gt; String { &quot;in struct&quot; } } let book: Book? = Book() print(type(of: book?.text)) print(type(of: book!.text)) print(book?.text()) print(book!.text()) </code></pre> <p>output is:</p> <pre><code>Optional&lt;() -&gt; String&gt; () -&gt; String Optional(&quot;in protocol&quot;) in struct </code></pre> <p>sample code above. Why two func is the same, but print results are different</p> <p>Anyone have idea?</p> <p>I adjust this will always call from struct</p> <p><a href="https://i.stack.imgur.com/Fhi7P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Fhi7P.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74398629, "author": "ANISH SAJI KUMAR", "author_id": 12309235, "author_profile": "https://Stackoverflow.com/users/12309235", "pm_score": 0, "selected": false, "text": "data*" }, { "answer_id": 74398699, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 3, "selected": true, "text": "React.js" }, { "answer_id": 74399008, "author": "Mhmdrz_A", "author_id": 5953610, "author_profile": "https://Stackoverflow.com/users/5953610", "pm_score": 0, "selected": false, "text": "const someFunction = console.log;\n\nfunction App() {\n return (\n <span id=\"someid\" \n onClick={(e) => {\n const videoPage = event.target.dataset['videoPage'];\n someFunction(videoPage)\n }} \n data-video-page=\"some data\" \n className=\"dot\" \n >\n click me\n </span>\n )\n}\n\nReactDOM.render(<App />, document.getElementById('root'));" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20475036/" ]
74,398,681
<p>So I have been trying to figure out how to rerender the items map with new items when I click the &quot;Mark Read&quot; button. I tried putting the items in a useState and updating the state on button click, but the issue with that is when I set the state it's always one render behind because set state is async. How would I go about implementing this?</p> <pre class="lang-js prettyprint-override"><code>const Main: React.FC&lt;MainProps&gt; = (props) =&gt; { // Get All Feeds const feeds = trpc.feed.getAllFeeds.useQuery(); // Get Items let unsorteditems; if (props.FeedType == &quot;one&quot;) { unsorteditems = trpc.feed.getItemsFromFeed.useQuery({ feedId: props.feedId, }); } else if (props.FeedType == &quot;readalready&quot;) { unsorteditems = trpc.feed.getReadItems.useQuery(); } else { unsorteditems = trpc.feed.getFeedItemsFromAllFeeds.useQuery(); } // Sort Items than add title, logo, and markedAsRead const sorteditems = unsorteditems.data?.sort( (objA, objB) =&gt; Number(objB.createdAt) - Number(objA.createdAt) // Replace in other order to sort in reverse ); let items = sorteditems?.map((item) =&gt; { const feed = feeds.data?.find((feed) =&gt; feed.id == item.feedId); return { ...item, feedTitle: feed?.title, feedLogoUrl: feed?.LogoUrl, markedAsRead: false, }; }); const feedName = items?.[0]?.feedTitle; // Mark Read function const markreadmutation = trpc.feed.markReadUsingUpsert.useMutation(); const onClickMarkRead = async (itemId: string) =&gt; { markreadmutation.mutate({ itemId: itemId }); }; // I tried this but it didn't work, and I can't use state because its async and dosent update in time function updateItems(index: number) { const newItems = items?.map((item, i) =&gt; { if (i == index) { return { ...item, markedAsRead: true, }; } else { return item; } }); items = newItems; } return ( &lt;&gt; {/* I removed alot of code here to make it easier to understand so css may look weird */} {/* &lt;!-- Main --&gt; */} &lt;div className=&quot;basis-5/12 border-l border-slate-300/40&quot;&gt; &lt;h1 className=&quot;sticky top-0 z-50 border-b border-slate-300/40 bg-opacity-60 bg-clip-padding py-2 pl-2 text-xl font-bold backdrop-blur-xl backdrop-filter&quot;&gt; {props.FeedType == &quot;one&quot; ? feedName : props.FeedType == &quot;all&quot; ? &quot;All Feeds&quot; : props.FeedType == &quot;readalready&quot; ? &quot;Recently Read&quot; : &quot;Woops&quot;} &lt;/h1&gt; &lt;div&gt; {items?.length == 0 &amp;&amp; &lt;p&gt;No Items&lt;/p&gt;} {items?.map((item, i) =&gt; ( &lt;div className={`border-slate-300/4 relative flex h-28 flex-col border-b ${ item.markedAsRead ? &quot;bg-gray-200&quot; : &quot;bg-white&quot; }`} key={item.id} &gt; {/* ^^^ If item is marked read it will be grayed out ^^^ */} &lt;button onClick={() =&gt; { // THIS BUTTON // When I click this is should rerender the map with the item marked as read onClickMarkRead(item.id); updateItems(i); }} &gt; [Mark Read] &lt;/button&gt; &lt;/div&gt; ))} &lt;/div&gt; &lt;/div&gt; &lt;/&gt; ); }; </code></pre>
[ { "answer_id": 74398873, "author": "DimitarM", "author_id": 9719646, "author_profile": "https://Stackoverflow.com/users/9719646", "pm_score": 2, "selected": true, "text": "const [items, setItems] = useState([]);\n\nconst getItems = useCallback( async() => {\n const fetchedItems = await yourFetchFunction();\n setItems(fetchedItems);\n}, []);\n\nuseEffect(() => {\n getItems();\n}, [getItems]);\n" }, { "answer_id": 74399587, "author": "DimitarM", "author_id": 9719646, "author_profile": "https://Stackoverflow.com/users/9719646", "pm_score": 0, "selected": false, "text": "const onClickMarkRead = async (itemId: string, index: number) => {\n await markreadmutation.mutate({ itemId: itemId });\n updateItems(index);\n};\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16375164/" ]
74,398,684
<p>I have a pandas df of different permutations of values: (toy version below, but my actual df contains more columns and rows)</p> <p>My goal is to remove the rows that contain duplicate values across rows but critically with also checking all columns.</p> <pre><code>import itertools check = list(itertools.permutations([1, 2, 3])) test = pd.DataFrame(check, columns =['A', 'B', 'C']) index A B C 0 1 2 3 1 1 3 2 2 2 1 3 3 2 3 1 4 3 1 2 5 3 2 1 </code></pre> <p>Desired output:</p> <pre><code>index A B C 0 1 2 3 3 2 3 1 4 3 1 2 </code></pre> <p>For example, I want to drop row <code>1</code> because both it and row <code>0</code> contain a 1 in the A column. I also want to drop row <code>2</code> because it and row <code>0</code> contain a 3 in the C column. And I want to drop row <code>5</code> because it and row <code>4</code> contain a 3 in the A column <em>and</em> because it and row <code>0</code> contain a 2 in the B column.</p> <p>In other words, I am trying to generate a dataframe that contains unique <em>combinations</em>. Not permutations.</p>
[ { "answer_id": 74398873, "author": "DimitarM", "author_id": 9719646, "author_profile": "https://Stackoverflow.com/users/9719646", "pm_score": 2, "selected": true, "text": "const [items, setItems] = useState([]);\n\nconst getItems = useCallback( async() => {\n const fetchedItems = await yourFetchFunction();\n setItems(fetchedItems);\n}, []);\n\nuseEffect(() => {\n getItems();\n}, [getItems]);\n" }, { "answer_id": 74399587, "author": "DimitarM", "author_id": 9719646, "author_profile": "https://Stackoverflow.com/users/9719646", "pm_score": 0, "selected": false, "text": "const onClickMarkRead = async (itemId: string, index: number) => {\n await markreadmutation.mutate({ itemId: itemId });\n updateItems(index);\n};\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12708740/" ]
74,398,714
<p>I have Angular application. I want to open a Bootstrap popup modal when user clicks on a link in the footer. Below is <a href="https://getbootstrap.com/docs/4.3/components/modal/" rel="nofollow noreferrer">my Bootstrap modal code</a>.</p> <pre><code>&lt;button type=&quot;button&quot; class=&quot;btn btn-primary&quot; data-toggle=&quot;modal&quot; data-target=&quot;#exampleModalCenter&quot;&gt; Launch demo modal &lt;/button&gt; &lt;div class=&quot;modal fade&quot; id=&quot;exampleModalCenter&quot; tabindex=&quot;-1&quot; role=&quot;dialog&quot; aria-labelledby=&quot;exampleModalCenterTitle&quot; aria-hidden=&quot;true&quot;&gt; &lt;div class=&quot;modal-dialog modal-dialog-centered&quot; role=&quot;document&quot;&gt; &lt;div class=&quot;modal-content&quot;&gt; &lt;div class=&quot;modal-header&quot;&gt; &lt;h5 class=&quot;modal-title&quot; id=&quot;exampleModalCenterTitle&quot;&gt;Modal title&lt;/h5&gt; &lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;modal&quot; aria-label=&quot;Close&quot;&gt; &lt;span aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;div class=&quot;modal-body&quot;&gt; ... &lt;/div&gt; &lt;div class=&quot;modal-footer&quot;&gt; &lt;button type=&quot;button&quot; class=&quot;btn btn-secondary&quot; data-dismiss=&quot;modal&quot;&gt;Close&lt;/button&gt; &lt;button type=&quot;button&quot; class=&quot;btn btn-primary&quot;&gt;Save changes&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Below is <code>footer.component.html</code> file</p> <pre><code>&lt;footer class=&quot;text-center text-lg-start bg-light text-muted fixed-bottom&quot;&gt; &lt;div class=&quot;text-center p-2&quot; style=&quot;background-color: gray;&quot;&gt; Copyright 2001-2022. All rights reserved. For internal use only. &lt;a class=&quot;text-reset&quot; data-toggle=&quot;collapse&quot; [attr.data-target]=&quot;'#exampleModalCenter'&quot;&gt;Terms of Use | &lt;/a&gt; &lt;a class=&quot;text-reset&quot; href=&quot;https://mdbootstrap.com/&quot;&gt;Privacy Statement&lt;/a&gt; &lt;/div&gt; &lt;/footer&gt; </code></pre> <p>Where do I need to keep the modal code, in <code>footer.component</code> or separate component? How can I open this when user clicks anchor link <em>Terms of Use</em> in the footer ?</p> <p>I am using these versions:</p> <pre><code>&quot;bootstrap&quot;: &quot;5.2&quot;, &quot;@angular/core&quot;: &quot;^14.2.0&quot; </code></pre>
[ { "answer_id": 74399936, "author": "Fabian Strathaus", "author_id": 17298437, "author_profile": "https://Stackoverflow.com/users/17298437", "pm_score": 2, "selected": false, "text": "constructor(private modalService: NgbModal) {}" }, { "answer_id": 74404023, "author": "R15", "author_id": 8977696, "author_profile": "https://Stackoverflow.com/users/8977696", "pm_score": 2, "selected": true, "text": "ng add @ng-bootstrap/ng-bootstrap\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8977696/" ]
74,398,741
<p>Im trying to create a cost calculator script. It basically shows if the manual input is for example 10$ and if you choose week, month or year it multiples with 52 for week, 12 for month and 1 for year so it shows the cost total in year.</p> <p>In the code snippet there are 2 variables for a house and car. For house it works fine and thats what I could do so far. I also need to add more fields like a car in example. And I want to be able to fill the cost for house and car and more fields and when I hit calculate button, it should be showing all the costs like house cost + car cost + other fields..</p> <p>so far I could only make it work for the house, if you fill the car field it doesn't add in the total, how can I make it work and add more fields if I want and they should be also working.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var btn = document.querySelector('#calculate'); btn.addEventListener('click', function () { var num1 = Number(document.querySelector('#num1').value), rlt = document.querySelector('p.answer'); var method = document.querySelector('option[name="method"]:checked').value; var answer = 0; if ('week' === method) { answer = num1 * (52); } else if ('month' === method) { answer = num1 * (12); } else if ('year' === method) { answer = num1; } rlt.innerHTML = answer; });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;div class="container"&gt; &lt;div class="input-control"&gt; &lt;label style="Float:left;" for="num1"&gt; &lt;input type="text" id="num1" autofocus&gt; $&lt;/label&gt; &lt;label style="Float:left;" for="dropdown"&gt; &lt;select&gt; &lt;option name="method" id="method_week" value="week"&gt;Week&lt;/option&gt; &lt;option name="method" id="method_month" value="month"&gt;Month&lt;/option&gt; &lt;option name="method" id="method_year" value="year"&gt;Year&lt;/option&gt; &lt;/select&gt; &lt;/label&gt; &lt;div style="clear:both;"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="input-control"&gt; &lt;label style="Float:left;" for="num2"&gt; &lt;input type="text" id="num2" autofocus&gt; $&lt;/label&gt; &lt;label style="Float:left;" for="dropdown"&gt; &lt;select&gt; &lt;option name="method" id="method_week" value="week"&gt;Week&lt;/option&gt; &lt;option name="method" id="method_month" value="month"&gt;Month&lt;/option&gt; &lt;option name="method" id="method_year" value="year"&gt;Year&lt;/option&gt; &lt;/select&gt; &lt;/label&gt; &lt;div style="clear:both;"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="input-control button"&gt; &lt;button id="calculate"&gt;Calculate&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="container result"&gt; Answer &lt;p class="answer"&gt;0&lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74399936, "author": "Fabian Strathaus", "author_id": 17298437, "author_profile": "https://Stackoverflow.com/users/17298437", "pm_score": 2, "selected": false, "text": "constructor(private modalService: NgbModal) {}" }, { "answer_id": 74404023, "author": "R15", "author_id": 8977696, "author_profile": "https://Stackoverflow.com/users/8977696", "pm_score": 2, "selected": true, "text": "ng add @ng-bootstrap/ng-bootstrap\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7889113/" ]
74,398,744
<p>I have found solutions in different languages, but not Python. Having limited experience in coding except Python and R, I can't translate them properly.</p> <p>I have a list of files like this:</p> <pre><code>file_list1 = ['/home/qrs/sample1.csv', '/home/abc/sample1.csv', '/home/mno/sample13.csv', '/home/xyz/sample2.csv'] </code></pre> <p>I also have a list of folders like:</p> <pre><code>change_folder = ['mno', 'xyz'] </code></pre> <p>Now i want to filter the file list where folders do not match as those in the folder list. The intended result would be:</p> <pre><code>file_list2 = ['/home/qrs/sample1.csv', '/home/abc/sample1.csv'] </code></pre> <p>I have tried:</p> <pre><code>file_list2 = [x for x in file_list1 if change_folder not in x] </code></pre> <p>This only works if I have just one pattern, not for multiple patterns. Please help.</p> <p>Edit: Got some of the answer in another question. However, the answer gotten here also includes elements that cater specifically to filtering path strings, which will be valuable for future visitors.</p>
[ { "answer_id": 74398959, "author": "Abdul Niyas P M", "author_id": 6699447, "author_profile": "https://Stackoverflow.com/users/6699447", "pm_score": 3, "selected": true, "text": "Path.parts" }, { "answer_id": 74399221, "author": "LiiVion", "author_id": 19328707, "author_profile": "https://Stackoverflow.com/users/19328707", "pm_score": 1, "selected": false, "text": "file_list1 = ['/home/qrs/sample1.csv', '/home/abc/sample1.csv', '/home/mno/sample13.csv', '/home/xyz/sample2.csv']\nchange_folder = ['mno', 'xyz']\noutput_list = file_list1.copy()\n\nfor i in range(len(file_list1)): # loop through paths\n for folder in change_folder: # loop through folders\n if folder in file_list1[i]: # checks if the folder string is inside the path string\n output_list.pop(output_list.index(file_list1[i])) # pops the path out of the output list\nprint(output_list)\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8379944/" ]
74,398,760
<p>I am using <code>FRENCH</code> Language in my mobile.</p> <pre><code>DateFormat('MMMMEEEEd').format(DateTime.now()) </code></pre> <p>It prints <code>vendredi 11 novembre</code></p> <p>Expected output =&gt; <code>Vendredi 11 novembre</code></p> <p>Is there any way to capitalize first letter without using string methods?</p> <p><strong>I don't want to capitalize the first letter of string with <code>toUpperCase()</code> method</strong></p>
[ { "answer_id": 74399784, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 0, "selected": false, "text": "final data = \"vendredi 11 novembre\";\n\nif (data.length > 1) { //just making sure string length\n final result = data[0].toUpperCase() + data.substring(1);\n\n print(result); //Vendredi 11 novembre\n}\n" }, { "answer_id": 74401035, "author": "seiya", "author_id": 5956799, "author_profile": "https://Stackoverflow.com/users/5956799", "pm_score": 1, "selected": false, "text": "import 'package:intl/intl.dart';\nimport 'package:intl/date_symbol_data_local.dart';\n\nvoid main(){\n getDate(String lang){\n switch (lang){\n case 'fr':\n String date;\n initializeDateFormatting('fr_FR', null).then((_) => {\n date = DateFormat.MMMMEEEEd(lang).format(DateTime.now()),\n date = date.replaceRange(\n 0,\n 1, \n date.substring(0,1).toUpperCase(),\n ),\n print(date)\n });\n break;\n case 'en':\n initializeDateFormatting('en_US', null).then((_) => {\n print(DateFormat.MMMMEEEEd(lang).format(DateTime.now()))\n });\n break;\n }\n }\n \n getDate('fr');\n getDate('en');\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7758318/" ]
74,398,764
<pre><code>data = {'customer1': ['milk', 'bread'], 'customer2': ['butter'], 'customer3': ['beer', 'diapers'], 'customer4': ['milk', 'bread', 'butter'], 'customer5': ['bread']} </code></pre> <p>I want the Python function output to be</p> <pre><code>{'milk': 2, 'bread': 3, 'butter': 2, 'beer': 1, 'diapers': 1} </code></pre> <p>and then also build a histogram on this data</p> <pre><code>res = dict() for key in customer_data.keys(): res[key] = len(set([sub[key] for sub in customer_data])) </code></pre>
[ { "answer_id": 74399784, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 0, "selected": false, "text": "final data = \"vendredi 11 novembre\";\n\nif (data.length > 1) { //just making sure string length\n final result = data[0].toUpperCase() + data.substring(1);\n\n print(result); //Vendredi 11 novembre\n}\n" }, { "answer_id": 74401035, "author": "seiya", "author_id": 5956799, "author_profile": "https://Stackoverflow.com/users/5956799", "pm_score": 1, "selected": false, "text": "import 'package:intl/intl.dart';\nimport 'package:intl/date_symbol_data_local.dart';\n\nvoid main(){\n getDate(String lang){\n switch (lang){\n case 'fr':\n String date;\n initializeDateFormatting('fr_FR', null).then((_) => {\n date = DateFormat.MMMMEEEEd(lang).format(DateTime.now()),\n date = date.replaceRange(\n 0,\n 1, \n date.substring(0,1).toUpperCase(),\n ),\n print(date)\n });\n break;\n case 'en':\n initializeDateFormatting('en_US', null).then((_) => {\n print(DateFormat.MMMMEEEEd(lang).format(DateTime.now()))\n });\n break;\n }\n }\n \n getDate('fr');\n getDate('en');\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20239434/" ]
74,398,788
<p>I am learning rust by implementing a raytracer. I have a working prototype that is single threaded and I am trying to make it multithreaded.</p> <p>In my code, I have a sampler which is basically a wrapper around <code>StdRng::seed_from_u64(123)</code> (this will change when I will add different types of samplers) that is mutable because of <code>StdRNG</code>. I need to have a repeatable behaviour that is why i am seeding the random number generator.</p> <p>In my rendering loop I use the sampler in the following way</p> <pre><code> let mut sampler = create_sampler(&amp;self.sampler_value); let sample_count = sampler.sample_count(); println!(&quot;Rendering ...&quot;); let progress_bar = get_progress_bar(image.size()); // Generate multiple rays for each pixel in the image for y in 0..image.size_y { for x in 0..image.size_x { image[(x, y)] = (0..sample_count) .into_iter() .map(|_| { let pixel = Vec2::new(x as f32, y as f32) + sampler.next2f(); let ray = self.camera.generate_ray(&amp;pixel); self.integrator.li(self, &amp;mut sampler, &amp;ray) }) .sum::&lt;Vec3&gt;() / (sample_count as f32); progress_bar.inc(1); } } </code></pre> <p>When I replace <code>into_iter</code> by <code>par_into_iter</code> the compiler tells me <strong>cannot borrow <code>sampler</code> as mutable, as it is a captured variable in a <code>Fn</code> closure</strong></p> <p>What should I do in this situation?</p> <p>Thanks!</p> <p>P.s. If it is of any use, this is the repo : <a href="https://github.com/jgsimard/rustrt" rel="nofollow noreferrer">https://github.com/jgsimard/rustrt</a></p>
[ { "answer_id": 74400113, "author": "rodrigo", "author_id": 865874, "author_profile": "https://Stackoverflow.com/users/865874", "pm_score": 0, "selected": false, "text": "&mut Sampler" }, { "answer_id": 74404633, "author": "Kevin Reid", "author_id": 99692, "author_profile": "https://Stackoverflow.com/users/99692", "pm_score": 1, "selected": false, "text": "std::hash::Hasher" }, { "answer_id": 74410928, "author": "Bob Parker", "author_id": 7718534, "author_profile": "https://Stackoverflow.com/users/7718534", "pm_score": 0, "selected": false, "text": "ChaCha8Rng" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7718534/" ]
74,398,855
<p>I am trying to make a program that returns <code>[&quot;1-5&quot;]</code> if I give <code>[1,2,3,4,5]</code>.</p> <p>I have made it but I can't filter it. So I want a code that will <strong>filter my output code</strong>. Or <strong>any code that is better than mine</strong>.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let array = [1,2,3,5,6,7,8,10,11, 34, 56,57,]; let x = []; for(let i = 0; i &lt; array.length; i++){ for(let j = 0; j &lt; array.length; j++){ if(array[i] + j == array[j]){ x.push(array[i] + "-" + array[j]); } if(array[j] &gt; array[i] + j &amp;&amp; array[j + 1]){ let y = array.slice(j, array.length) array = y; i, j = 0; } if(array[i] - array[i + 1] != -1 &amp;&amp; array[i + 1] - array[i] != 1 &amp;&amp; array[i + 1] != undefined){ x.push(array[i]); } } } console.log(x);</code></pre> </div> </div> </p>
[ { "answer_id": 74398924, "author": "Kristian", "author_id": 3706717, "author_profile": "https://Stackoverflow.com/users/3706717", "pm_score": 0, "selected": false, "text": "[\"smallestelement-largestelement\"]" }, { "answer_id": 74399071, "author": "JamesG", "author_id": 18096860, "author_profile": "https://Stackoverflow.com/users/18096860", "pm_score": 0, "selected": false, "text": "let min = Number.MAX_VALUE\nlet max = Number.MIN_VALUE\n\narr.forEach((element) => {\n if(element > max) max = element\n if(element < min) min = element\n}\n\nconsole.log(`${min} - ${max}`)\n" }, { "answer_id": 74399095, "author": "dakab", "author_id": 2083613, "author_profile": "https://Stackoverflow.com/users/2083613", "pm_score": 0, "selected": false, "text": "sort()" }, { "answer_id": 74399159, "author": "Stephen Quan", "author_id": 881441, "author_profile": "https://Stackoverflow.com/users/881441", "pm_score": 1, "selected": true, "text": "${start}-${last}" }, { "answer_id": 74399184, "author": "shawn-mcgee", "author_id": 3736000, "author_profile": "https://Stackoverflow.com/users/3736000", "pm_score": 1, "selected": false, "text": "function detectRange(a) {\n // clone a\n const b = [...a]\n // remove first value\n const min = max = b.splice(0, 1)[0]\n\n // compute range\n const range = b.reduce(({min, max}, i) => {\n if(i < min) min = i\n if(i > max) max = i\n return { min, max }\n }, {min, max})\n\n return range\n}\n\nfunction detectRanges(a) {\n // clone a\n const b = [...a]\n // remove first value\n const min = max = b.splice(0, 1)[0]\n\n // init ranges array\n const ranges = [ ]\n // compute ranges\n const range = b.reduce(({min, max}, i) => {\n if(i === max + 1) {\n return {min , max: i}\n } else {\n ranges.push({min, max})\n return {min: i, max: i}\n }\n }, {min, max})\n // push the remaining range onto the array\n ranges.push(range)\n\n return ranges\n}\n\nfunction printRange(r) {\n console.log(`[\"${r.min}-${r.max}\"]`)\n}\n\nfunction printRanges(r) {\n r.forEach(i => {\n printRange(i)\n })\n}\n\n// detect and print range of whole array\nprintRange(detectRange([1, 2, 3, 5, 6, 7, 8, 10, 11, 34, 56, 57]))\n// detect and print only contiguous ranges within array\nprintRanges(detectRanges([1, 2, 3, 5, 6, 7, 8, 10, 11, 34, 56, 57]))" }, { "answer_id": 74399857, "author": "Layhout", "author_id": 17308201, "author_profile": "https://Stackoverflow.com/users/17308201", "pm_score": 0, "selected": false, "text": "const array = [1, 2, 3, 5, 6, 7, 8, 10, 11, 34, 56, 57];\n\nlet s = null, d = 0;\n\nconst result = array.sort((a, b) => a - b).reduce((p, c, i, arr) => {\n d++;\n if (!s) s = c;\n if (arr[i + 1] - s > d) {\n s === c ? p.push(s) : p.push(`${s}-${c}`);\n s = null;\n d = 0;\n }\n if (!arr[i + 1]) s === c ? p.push(s) : p.push(`${s}-${c}`);\n\n return p;\n}, []);\n\nconsole.log(result);" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17249101/" ]
74,398,875
<p>You need to show the user's name in the heading. The heading should say <code>Hello, (user)</code> when the user enters their name into the text box which is a simple form input and presses the button.</p> <p>To display the user's name, you'll need to read the user's name from the query string. You need to read the query string when the page is loaded, not when the button is pressed.</p> <p>I need to implement this using javascript and query string but I haven't got a clue how.</p> <pre><code>&lt;form&gt; &lt;input type=&quot;text&quot; name=&quot;user_name&quot; placeholder=&quot;Enter your name!&quot; /&gt; &lt;button type=&quot;submit&quot;&gt;Apply!&lt;/button&gt; &lt;/form&gt; </code></pre>
[ { "answer_id": 74398924, "author": "Kristian", "author_id": 3706717, "author_profile": "https://Stackoverflow.com/users/3706717", "pm_score": 0, "selected": false, "text": "[\"smallestelement-largestelement\"]" }, { "answer_id": 74399071, "author": "JamesG", "author_id": 18096860, "author_profile": "https://Stackoverflow.com/users/18096860", "pm_score": 0, "selected": false, "text": "let min = Number.MAX_VALUE\nlet max = Number.MIN_VALUE\n\narr.forEach((element) => {\n if(element > max) max = element\n if(element < min) min = element\n}\n\nconsole.log(`${min} - ${max}`)\n" }, { "answer_id": 74399095, "author": "dakab", "author_id": 2083613, "author_profile": "https://Stackoverflow.com/users/2083613", "pm_score": 0, "selected": false, "text": "sort()" }, { "answer_id": 74399159, "author": "Stephen Quan", "author_id": 881441, "author_profile": "https://Stackoverflow.com/users/881441", "pm_score": 1, "selected": true, "text": "${start}-${last}" }, { "answer_id": 74399184, "author": "shawn-mcgee", "author_id": 3736000, "author_profile": "https://Stackoverflow.com/users/3736000", "pm_score": 1, "selected": false, "text": "function detectRange(a) {\n // clone a\n const b = [...a]\n // remove first value\n const min = max = b.splice(0, 1)[0]\n\n // compute range\n const range = b.reduce(({min, max}, i) => {\n if(i < min) min = i\n if(i > max) max = i\n return { min, max }\n }, {min, max})\n\n return range\n}\n\nfunction detectRanges(a) {\n // clone a\n const b = [...a]\n // remove first value\n const min = max = b.splice(0, 1)[0]\n\n // init ranges array\n const ranges = [ ]\n // compute ranges\n const range = b.reduce(({min, max}, i) => {\n if(i === max + 1) {\n return {min , max: i}\n } else {\n ranges.push({min, max})\n return {min: i, max: i}\n }\n }, {min, max})\n // push the remaining range onto the array\n ranges.push(range)\n\n return ranges\n}\n\nfunction printRange(r) {\n console.log(`[\"${r.min}-${r.max}\"]`)\n}\n\nfunction printRanges(r) {\n r.forEach(i => {\n printRange(i)\n })\n}\n\n// detect and print range of whole array\nprintRange(detectRange([1, 2, 3, 5, 6, 7, 8, 10, 11, 34, 56, 57]))\n// detect and print only contiguous ranges within array\nprintRanges(detectRanges([1, 2, 3, 5, 6, 7, 8, 10, 11, 34, 56, 57]))" }, { "answer_id": 74399857, "author": "Layhout", "author_id": 17308201, "author_profile": "https://Stackoverflow.com/users/17308201", "pm_score": 0, "selected": false, "text": "const array = [1, 2, 3, 5, 6, 7, 8, 10, 11, 34, 56, 57];\n\nlet s = null, d = 0;\n\nconst result = array.sort((a, b) => a - b).reduce((p, c, i, arr) => {\n d++;\n if (!s) s = c;\n if (arr[i + 1] - s > d) {\n s === c ? p.push(s) : p.push(`${s}-${c}`);\n s = null;\n d = 0;\n }\n if (!arr[i + 1]) s === c ? p.push(s) : p.push(`${s}-${c}`);\n\n return p;\n}, []);\n\nconsole.log(result);" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20475206/" ]
74,398,929
<p>i have a String <strong>&quot;iye&quot;</strong> and i want make it distinct and also i have a <strong>array [&quot;hi&quot;, &quot;bye&quot;, &quot;bebe&quot;]</strong> and i want to make each element of the array and get the distinct characters only so my array would be like this <strong>[&quot;hi&quot;, &quot;bye&quot;, &quot;be&quot;]</strong> an then at last i want to take each element from that distinct array and count how many characters of <strong>distinctArray[i]</strong> are present in the distinct String <strong>&quot;iye&quot;</strong> and i will store that count for each element of distinct array in same order respectively to the elements of distinct array for e.g</p> <p><strong>sample input = &quot;iyee&quot; and [&quot;hi&quot;, &quot;bye&quot;, &quot;bebe&quot;]</strong></p> <p><strong>sample ouput = [1, 2, 1]</strong></p> <p>below is my solution not working for larger inputs</p> <pre><code> static int[] mathProfessor(String B,String[] a){ List&lt;String&gt; distinct = new ArrayList&lt;String&gt;(); int[] arr = new int[a.length]; // store each value of names array as distinct value for (int i = 0; i &lt; a.length; i++) { StringBuilder str = new StringBuilder(); a[i].chars().distinct().forEach(c -&gt; str.append((char) c)); distinct.add(str.toString()); } // System.out.println(&quot;distinct list: &quot; + distinct.toString()); // store the count int count = 0; for (int i = 0; i &lt; distinct.size(); i++) { String s = distinct.get(i); for (int j = 0; j &lt; B.length(); j++) { if (s.contains(Character.toString(B.charAt(j)))) count++; } arr[i] = count; count = 0; } return arr; } </code></pre>
[ { "answer_id": 74398924, "author": "Kristian", "author_id": 3706717, "author_profile": "https://Stackoverflow.com/users/3706717", "pm_score": 0, "selected": false, "text": "[\"smallestelement-largestelement\"]" }, { "answer_id": 74399071, "author": "JamesG", "author_id": 18096860, "author_profile": "https://Stackoverflow.com/users/18096860", "pm_score": 0, "selected": false, "text": "let min = Number.MAX_VALUE\nlet max = Number.MIN_VALUE\n\narr.forEach((element) => {\n if(element > max) max = element\n if(element < min) min = element\n}\n\nconsole.log(`${min} - ${max}`)\n" }, { "answer_id": 74399095, "author": "dakab", "author_id": 2083613, "author_profile": "https://Stackoverflow.com/users/2083613", "pm_score": 0, "selected": false, "text": "sort()" }, { "answer_id": 74399159, "author": "Stephen Quan", "author_id": 881441, "author_profile": "https://Stackoverflow.com/users/881441", "pm_score": 1, "selected": true, "text": "${start}-${last}" }, { "answer_id": 74399184, "author": "shawn-mcgee", "author_id": 3736000, "author_profile": "https://Stackoverflow.com/users/3736000", "pm_score": 1, "selected": false, "text": "function detectRange(a) {\n // clone a\n const b = [...a]\n // remove first value\n const min = max = b.splice(0, 1)[0]\n\n // compute range\n const range = b.reduce(({min, max}, i) => {\n if(i < min) min = i\n if(i > max) max = i\n return { min, max }\n }, {min, max})\n\n return range\n}\n\nfunction detectRanges(a) {\n // clone a\n const b = [...a]\n // remove first value\n const min = max = b.splice(0, 1)[0]\n\n // init ranges array\n const ranges = [ ]\n // compute ranges\n const range = b.reduce(({min, max}, i) => {\n if(i === max + 1) {\n return {min , max: i}\n } else {\n ranges.push({min, max})\n return {min: i, max: i}\n }\n }, {min, max})\n // push the remaining range onto the array\n ranges.push(range)\n\n return ranges\n}\n\nfunction printRange(r) {\n console.log(`[\"${r.min}-${r.max}\"]`)\n}\n\nfunction printRanges(r) {\n r.forEach(i => {\n printRange(i)\n })\n}\n\n// detect and print range of whole array\nprintRange(detectRange([1, 2, 3, 5, 6, 7, 8, 10, 11, 34, 56, 57]))\n// detect and print only contiguous ranges within array\nprintRanges(detectRanges([1, 2, 3, 5, 6, 7, 8, 10, 11, 34, 56, 57]))" }, { "answer_id": 74399857, "author": "Layhout", "author_id": 17308201, "author_profile": "https://Stackoverflow.com/users/17308201", "pm_score": 0, "selected": false, "text": "const array = [1, 2, 3, 5, 6, 7, 8, 10, 11, 34, 56, 57];\n\nlet s = null, d = 0;\n\nconst result = array.sort((a, b) => a - b).reduce((p, c, i, arr) => {\n d++;\n if (!s) s = c;\n if (arr[i + 1] - s > d) {\n s === c ? p.push(s) : p.push(`${s}-${c}`);\n s = null;\n d = 0;\n }\n if (!arr[i + 1]) s === c ? p.push(s) : p.push(`${s}-${c}`);\n\n return p;\n}, []);\n\nconsole.log(result);" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13337068/" ]
74,398,950
<p>I have this code:</p> <pre><code>public static void main(String[] args) throws ParseException { String fecha = &quot;2022-11-08 10:28:04.282551-06&quot;; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(&quot;yyyy-MM-dd HH:mm:ss.SSSZ&quot;); Date e = simpleDateFormat.parse(fecha); SimpleDateFormat newSimpleDateFormat = new SimpleDateFormat(&quot;yyyy-MM-dd HH:mm:ss.SSS&quot;); System.out.println(newSimpleDateFormat.format(e)); } </code></pre> <p>And this error:</p> <pre><code>Exception in thread &quot;main&quot; java.text.ParseException: Unparseable date: &quot;2022-11-08 10:28:04.282551-06&quot; at java.text.DateFormat.parse(DateFormat.java:366) at Ejemplos.main(Ejemplos.java:11) </code></pre> <p>I want my new date like this: <strong>2022-11-08 10:28:04.282551</strong> This values after dot *282551 *sometimes can be less, for example: *282 *or <em>2825</em> and sometimes there is not a dot, for example: <em>2022-11-08 10:28:04-06</em></p>
[ { "answer_id": 74399110, "author": "Dinuka Silva", "author_id": 20457576, "author_profile": "https://Stackoverflow.com/users/20457576", "pm_score": 0, "selected": false, "text": "public static void main(String[] args) throws ParseException {\n String fecha = \"2022-11-08 10:28:04.282551-06\";\n String[] parts = fecha.split(\"\\\\.\");\n String part1 = parts[0];\n String part2 = parts[1];\n\n SimpleDateFormat simpleDateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n System.out.println(simpleDateFormat.parse(part1));\n\n}\n" }, { "answer_id": 74399831, "author": "user16320675", "author_id": 16320675, "author_profile": "https://Stackoverflow.com/users/16320675", "pm_score": 2, "selected": true, "text": "Date" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20333373/" ]
74,398,955
<p>why localStorage is not defined</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> const [bookmark, setBookmark] = useState([]); const { showBookmark, setShowBookmark } = useContext(Context); const addToBookmark = (id) =&gt; { if (!bookmark.includes(id)) setBookmark(bookmark.concat(id)); }; const removeBookmark = (id) =&gt; { let index = bookmark.indexOf(id); let temp = [...bookmark.slice(0, index), ...bookmark.slice(index + 1)]; setBookmark(temp); }; let findBookmark = data1.ayat.filter((e) =&gt; bookmark.includes(e.nomor)); useEffect(() =&gt; { localStorage.setItem('list', JSON.stringify(findBookmark)); }, [findBookmark]); findBookmark = JSON.parse(localStorage.getItem('list')) || '[]';</code></pre> </div> </div> </p> <p>So, I want to make bookmark feature in my project where I get the data from <code>data1</code>. When I click <code>addBookmark</code> it will save data as per <code>id</code> to <code>localStorage</code> and it works, but when I use <code>getItem</code> from localStorage errors appear:</p> <pre><code>ReferenceError: localStorage is not defined </code></pre> <p>and then <code>findBookmark.map()</code></p>
[ { "answer_id": 74399055, "author": "Bobby Thomas", "author_id": 7632852, "author_profile": "https://Stackoverflow.com/users/7632852", "pm_score": -1, "selected": false, "text": "window.localStorage" }, { "answer_id": 74399719, "author": "Ali Iqbal", "author_id": 20321054, "author_profile": "https://Stackoverflow.com/users/20321054", "pm_score": 0, "selected": false, "text": "localStorage" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20066668/" ]
74,398,962
<p>as you know, some apps have splash screen. I have learned the make splash screen with native codes on Flutter.</p> <p>For example: android/app/src/main/res/drawable/launch_background.xml</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;!-- Modify this file to customize your launch splash screen --&gt; &lt;layer-list xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt; &lt;item android:drawable=&quot;@color/background&quot; /&gt; &lt;item&gt; &lt;bitmap android:gravity=&quot;center&quot; android:src=&quot;@drawable/hwalogo&quot; /&gt; &lt;/item&gt; &lt;/layer-list&gt; </code></pre> <p>So,I will have splash screen without dart. Also, iOS side has too. Before the that, I was creating splash screen like homepage or login. My question is which one should I use to be more suitable? Many Thanks..</p>
[ { "answer_id": 74399009, "author": "Arijeet", "author_id": 15387120, "author_profile": "https://Stackoverflow.com/users/15387120", "pm_score": 1, "selected": false, "text": "import 'package:flutter/material.dart';\nimport '../constants/constants.dart';\n\nclass SplashScreen extends StatefulWidget {\n const SplashScreen({super.key});\n\n @override\n State<StatefulWidget> createState() => _SplashScreenState();\n}\n\nclass _SplashScreenState extends State<SplashScreen> {\n bool? loginCheck; //checking the shared preference and navigating accordingly\n @override\n void initState() {\n super.initState();\n loginCheck = prefs!.getBool('login');\n navigate();\n }\n\n @override\n Widget build(BuildContext context) {\n return const Material(\n child: Center(child: Text('Loading....')),\n );\n }\n\n navigate() async {\n if (loginCheck == true) {\n Future(() => Navigator.of(context).pushReplacementNamed('/home'));\n } else {\n Future(() => Navigator.of(context).pushReplacementNamed('/login'));\n }\n }\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18849295/" ]
74,398,977
<p>I have values ​​in an array object called farms. In this case, we are using the farms.map function. However, this warning occurred, and when I searched the documentation, it was telling me to write a unique value for key.</p> <pre><code>Warning: Each child in a list should have a unique &quot;key&quot; prop. in React native? </code></pre> <p>So I wrote v.placeId in the key in the TargetCon component, but the warning was not resolved. How do I fix it?</p> <p>this is my code</p> <pre><code> farms = [ { placeId: 272, name: 'hamburger', }, { placeId: 273, name: 'coffee', }, ]; const TargetFarm = () =&gt; { const {farms} = useSelector((state: RootState) =&gt; state.post); return ( &lt;SeCotainer platform={tablet}&gt; {farms.map(v =&gt; { return ( &lt;&gt; &lt;TargetCon key={v.placeId.toString()}&gt; &lt;TargetTxt platform={tablet}&gt;{v.name}&lt;/TargetTxt&gt; &lt;/TargetCon&gt; &lt;/&gt; ); })} &lt;/SeCotainer&gt; ); }; export default TargetFarm; </code></pre>
[ { "answer_id": 74398993, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 3, "selected": true, "text": "return (\n <React.Fragment key={v.placeId.toString()}>\n <TargetCon>\n <TargetTxt platform={tablet}>{v.name}</TargetTxt>\n </TargetCon>\n </React.Fragment>\n);\n" }, { "answer_id": 74399024, "author": "Robert S", "author_id": 11578082, "author_profile": "https://Stackoverflow.com/users/11578082", "pm_score": 0, "selected": false, "text": " farms = [\n{\n placeId: 272,\n name: 'hamburger',\n},\n{\n placeId: 273,\n name: 'coffee',\n},\n];\n\nconst TargetFarm = () => {\nconst {farms} = useSelector((state: RootState) => state.post);\n\nreturn (\n <SeCotainer platform={tablet}>\n {farms.map(v => {\n return (\n <>\n <React.Fragment key={`targetcon_${index}`}>\n <TargetCon key={v.placeId.toString()}>\n <TargetTxt platform={tablet}>{v.name}</TargetTxt>\n </TargetCon>\n </React.Fragment>\n </>\n );\n })}\n </SeCotainer>\n);\n};\n\nexport default TargetFarm;\n" }, { "answer_id": 74399105, "author": "hoangthienan", "author_id": 359776, "author_profile": "https://Stackoverflow.com/users/359776", "pm_score": 1, "selected": false, "text": "index" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19476497/" ]
74,398,981
<p>i got work to fix error when computing but i still dont have idea how to fix it because i'm still newbie</p> <blockquote> <p>Odoo Server Error</p> <p>Traceback (most recent call last): File &quot;/home/equipAccounting/equip/odoo/addons/base/models/ir_http.py&quot;, line 237, in _dispatch result = request.dispatch() File &quot;/home/equipAccounting/equip/odoo/http.py&quot;, line 683, in dispatch result = self._call_function(**self.params) File &quot;/home/equipAccounting/equip/odoo/http.py&quot;, line 359, in _call_function return checked_call(self.db, args, *kwargs) File &quot;/home/equipAccounting/equip/odoo/service/model.py&quot;, line 94, in wrapper return f(dbname, args, *kwargs) File &quot;/home/equipAccounting/equip/odoo/http.py&quot;, line 347, in checked_call result = self.endpoint(*a, **kw) File &quot;/home/equipAccounting/equip/odoo/http.py&quot;, line 912, in call return self.method(*args, **kw) File &quot;/home/equipAccounting/equip/odoo/http.py&quot;, line 531, in response_wrap response = f(*args, **kw) File &quot;/home/equipAccounting/equip/addons/basic/web/controllers/main.py&quot;, line 1393, in call_button action = self._call_kw(model, method, args, kwargs) File &quot;/home/equipAccounting/equip/addons/basic/web/controllers/main.py&quot;, line 1381, in _call_kw return call_kw(request.env[model], method, args, kwargs) File &quot;/home/equipAccounting/equip/odoo/api.py&quot;, line 396, in call_kw result = _call_kw_multi(method, model, args, kwargs) File &quot;/home/equipAccounting/equip/odoo/api.py&quot;, line 383, in _call_kw_multi result = method(recs, args, *kwargs) File &quot;/home/equipAccounting/equip/addons/core/treasury_forecast/models/treasury_bank_forecast.py&quot;, line 290, in compute_bank_balances self.env.cr.execute(main_query) File &quot;/usr/local/lib/python3.8/dist-packages/decorator.py&quot;, line 232, in fun return caller(func, (extras + args), *kw) File &quot;/home/equipAccounting/equip/odoo/sql_db.py&quot;, line 101, in check return f(self, args, *kwargs) File &quot;/home/equipAccounting/equip/odoo/sql_db.py&quot;, line 298, in execute res = self._obj.execute(query, params) Exception</p> <p>The above exception was the direct cause of the following exception:</p> <p>Traceback (most recent call last): File &quot;/home/equipAccounting/equip/odoo/http.py&quot;, line 639, in _handle_exception return super(JsonRequest, self)._handle_exception(exception) File &quot;/home/equipAccounting/equip/odoo/http.py&quot;, line 315, in _handle_exception raise exception.with_traceback(None) from new_cause psycopg2.errors.SyntaxError: syntax error at or near &quot;)&quot; LINE 9:<br /> WHERE abs.journal_id IN ()</p> </blockquote> <p>and here is the code :</p> <pre><code>def get_bank_fc_query(self, fc_journal_list, date_start, date_end,company_domain): query = &quot;&quot;&quot; UNION SELECT CAST('FBK' AS text) AS type, absl.id AS ID, am.date, absl.payment_ref as name, am.company_id, absl.amount_main_currency as amount, absl.cf_forecast, abs.journal_id, NULL as kind FROM account_bank_statement_line absl LEFT JOIN account_move am ON (absl.move_id = am.id) LEFT JOIN account_bank_statement abs ON (absl.statement_id = abs.id) WHERE abs.journal_id IN {} AND am.date BETWEEN '{}' AND '{}' AND am.company_id in {} &quot;&quot;&quot; .format(str(fc_journal_list), date_start, date_end,company_domain) return query def get_acc_move_query(self, date_start, date_end, company_domain): query = &quot;&quot;&quot; UNION SELECT CAST('FPL' AS text) AS type, aml.id AS ID,aml.treasury_date AS date, am.name AS name, aml.company_id, aml.amount_residual AS amount, NULL AS cf_forecast, NULL AS journal_id, am.move_type as kind FROM account_move_line aml LEFT JOIN account_move am ON (aml.move_id = am.id) WHERE am.state NOT IN ('draft') AND aml.treasury_planning AND aml.amount_residual != 0 AND aml.treasury_date BETWEEN '{}' AND '{}' AND aml.company_id in {} &quot;&quot;&quot; .format(date_start, date_end, company_domain) return query </code></pre> <p>Thanks in advance</p>
[ { "answer_id": 74398993, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 3, "selected": true, "text": "return (\n <React.Fragment key={v.placeId.toString()}>\n <TargetCon>\n <TargetTxt platform={tablet}>{v.name}</TargetTxt>\n </TargetCon>\n </React.Fragment>\n);\n" }, { "answer_id": 74399024, "author": "Robert S", "author_id": 11578082, "author_profile": "https://Stackoverflow.com/users/11578082", "pm_score": 0, "selected": false, "text": " farms = [\n{\n placeId: 272,\n name: 'hamburger',\n},\n{\n placeId: 273,\n name: 'coffee',\n},\n];\n\nconst TargetFarm = () => {\nconst {farms} = useSelector((state: RootState) => state.post);\n\nreturn (\n <SeCotainer platform={tablet}>\n {farms.map(v => {\n return (\n <>\n <React.Fragment key={`targetcon_${index}`}>\n <TargetCon key={v.placeId.toString()}>\n <TargetTxt platform={tablet}>{v.name}</TargetTxt>\n </TargetCon>\n </React.Fragment>\n </>\n );\n })}\n </SeCotainer>\n);\n};\n\nexport default TargetFarm;\n" }, { "answer_id": 74399105, "author": "hoangthienan", "author_id": 359776, "author_profile": "https://Stackoverflow.com/users/359776", "pm_score": 1, "selected": false, "text": "index" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7769113/" ]
74,398,991
<p>I have a switch case structure like this:</p> <pre><code>var dict = new Dictionary&lt;string, string&gt; { {&quot;title&quot;, &quot;title.val&quot;}, {&quot;phone&quot;, &quot;phone.val&quot;}, {&quot;address&quot;, &quot;address.val&quot;}, {&quot;e_mail&quot;, &quot;email.val&quot;}, {&quot;work_phone&quot;, &quot;workphone.val&quot;} }; foreach (var p in dict) { string str = ___ANY_METHOD___(p.Value); if (!string.IsNullOrEmpty(str)) { switch (p.Key) { case &quot;title&quot;: _trp.Name = str; break; case &quot;phone&quot;: _trp.Phone = str; break; case &quot;address&quot;: _trp.Address = str; break; case &quot;e_mail&quot;: _trp.Email = str; break; case &quot;work_phone&quot;: _trp.WorkPhone = str; break; } } } </code></pre> <p>Due to the difference in the incoming values, there is no error in the switch case structure and the program runs smoothly as it is. But as it stands, the code snippet looks pretty ugly. Is there a better way to assign the same value to <code>prs.Name, prs.Phone, prs.Address, prs.Email, prs.WorkPhone</code> objects in the switch case structure?</p>
[ { "answer_id": 74400008, "author": "Hady_Khann", "author_id": 14682350, "author_profile": "https://Stackoverflow.com/users/14682350", "pm_score": -1, "selected": false, "text": "case \"title\" or \"phone\" or \"address\" or \"e_mail\" or \"work_phone\":\n\ncase \"title\",\"phone\",\"address\",\"e_mail\",\"work_phone\":\n" }, { "answer_id": 74401009, "author": "Palle Due", "author_id": 5516339, "author_profile": "https://Stackoverflow.com/users/5516339", "pm_score": 1, "selected": false, "text": "if (!string.IsNullOrEmpty(dict[\"title\"])\n _trp.Name = ___ANY_METHOD___(dict[\"title\"])[0].ToString();\nif (!string.IsNullOrEmpty(dict[\"phone\"])\n _trp.Phone = ___ANY_METHOD___(dict[\"phone\"])[0].ToString();\nif (!string.IsNullOrEmpty(dict[\"address\"])\n _trp.Address = ___ANY_METHOD___(dict[\"address\"])[0].ToString();\nif (!string.IsNullOrEmpty(dict[\"e_mail\"])\n _trp.Email = ___ANY_METHOD___(dict[\"e_mail\"])[0].ToString();\nif (!string.IsNullOrEmpty(dict[\"work_phone\"])\n _trp.WorkPhone = ___ANY_METHOD___(dict[\"work_phone\"])[0].ToString();\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74398991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1104951/" ]