qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,121,754 | <p>I frustated over this code</p>
<pre><code>_GenresListState(this.genres);
</code></pre>
<p>why it keeps showing the alert of _tabController must be initialized, im already put <code>late</code> constructor but the error is still going, this is the code where i put it:</p>
<pre><code>class _GenresListState extends State<GenresList> with SingleTickerProviderStateMixin {
final List<Genre> genres;
_GenresListState(this.genres);
TabController _tabController;
@override
void initState() {
super.initState();
</code></pre>
| [
{
"answer_id": 74122666,
"author": "Boussadjra Brahim",
"author_id": 8172857,
"author_profile": "https://Stackoverflow.com/users/8172857",
"pm_score": 1,
"selected": false,
"text": "allowedProductPaymentMethods"
},
{
"answer_id": 74125504,
"author": "Kalkal",
"author_id":... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74121754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13497264/"
] |
74,121,792 | <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.outside {
/* Note line3, the top and bottom will be the same, why add the flex on the different */
display: flex;
}
.content {
background: skyblue;
display: flex;
flex-wrap: wrap;
}
.item {
width: 20%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outside">
<div class="content">
<div class="item">apple</div>
<div class="item">apple</div>
<div class="item">apple</div>
<div class="item">apple</div>
<div class="item">banana</div>
<div class="item">banana</div>
<div class="item">banana</div>
</div>
</div>
========
<div class="content">
<div class="item">apple</div>
<div class="item">apple</div>
<div class="item">apple</div>
<div class="item">apple</div>
<div class="item">banana</div>
<div class="item">banana</div>
<div class="item">banana</div>
</div></code></pre>
</div>
</div>
</p>
<p>the screenshot is how the two cases work
<a href="https://i.stack.imgur.com/Tyjx8.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>Questions:</p>
<ol>
<li>I don't know why the with of element with class outside do not fill the screen(like the element with class content)</li>
<li>I would like to know on what basis the 20% of item is calculated</li>
</ol>
| [
{
"answer_id": 74121986,
"author": "Deykun",
"author_id": 6743808,
"author_profile": "https://Stackoverflow.com/users/6743808",
"pm_score": 0,
"selected": false,
"text": ".content"
},
{
"answer_id": 74122011,
"author": "Ishtiaq",
"author_id": 10524943,
"author_profile... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74121792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10948264/"
] |
74,121,816 | <p>I have the following function, which produces a sequence of numbers. I would like to turn it into a one-liner in the form of an iterator or a generator. How can I do that?</p>
<pre><code>def one_line_generator():
sum = 0
string = "Hello"
i = 0
while True:
sum += ord(string[i])
yield sum
if i<len(string)-1:
i += 1
else:
i = 0
</code></pre>
| [
{
"answer_id": 74121900,
"author": "AKX",
"author_id": 51685,
"author_profile": "https://Stackoverflow.com/users/51685",
"pm_score": 1,
"selected": false,
"text": "import itertools\n\ndef oneline2(string, i=0):\n return itertools.chain.from_iterable(((i := i + ord(c)) for c in s) for ... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74121816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5969463/"
] |
74,121,843 | <p>I'm working on an MVC Core form where a requester has to define some approvers for his application. When preparing the model for the Get request, I first get the roles for the approvers. Currently, there are always four roles returned:</p>
<ol>
<li>Category Head</li>
<li>Governance Head</li>
<li>Concessions VP</li>
<li>Commercial EVP</li>
</ol>
<p>And here is the <code>HttpGet</code>:</p>
<pre class="lang-cs prettyprint-override"><code>[HttpGet]
public async Task<IActionResult> Create()
{
// omitted for brevity...
// Get the SystemRole models (4 models will be returned)
model.ApprovingRoles = (await serviceLookup.GetAllRolesAsync(ct)).ToList();
}
</code></pre>
<p>The SystemRoleModel is simply:</p>
<pre class="lang-cs prettyprint-override"><code>public class SystemRoleModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool Active { get; set; }
}
</code></pre>
<p>The view is composed of <code>EditorTemplate</code> as follows:</p>
<p><code>Create.cshtml</code> -> <code>LetterEditor.cshtml</code> -> <code>LetterAttachmentEditor.cshtml</code></p>
<p><code>Create.cshtml</code>:</p>
<pre class="lang-html prettyprint-override"><code>@model LetterModel
@{
ViewData["Title"] = "Create RL";
}
@Html.EditorFor(m => m, "LetterEditor", new { ShowApprovers = "1", ShowAttachments = "1", ShowButtons = "1" } )
</code></pre>
<p><code>LetterEditor.cshtml</code>:</p>
<pre class="lang-html prettyprint-override"><code>@model LetterModel
...
<div class="panel-body">
@await Html.PartialAsync("EditorTemplates/LetterAttachmentEditor", new LetterAttachmentUploadViewModel { IsBusy = false, LetterGuid = Model.IdCode.ToString() })
</div>
...
</code></pre>
<p>And finally, <code>LetterAttachmentEditor.cshtml</code>:</p>
<pre class="lang-html prettyprint-override"><code>@model IList<SystemRoleModel>
@for (var i = 0; i < Model.Count; i++)
{
var index = i;
var title = Model[index].Name;
<div class="row">
<div class="col-lg-2 mt-3">
@Html.Label("LetterApprover[" + index + "]", title, new { @class = "control-label" })
</div>
<div class="col-lg-4">
@(Html.Kendo().DropDownList().Name("LetterApprover[" + index + "]")
.DataValueField(nameof(SystemUserModel.Id))
.DataTextField(nameof(SystemUserModel.EmployeeName))
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetUsersByRoleId", "Api", new { roleId = Model[index].Id });
}).ServerFiltering(true);
})
)
</div>
<div class="col-lg-6">
<span asp-validation="" class="text-danger"></span>
@Html.ValidationMessage("LetterApprover[" + index + "]", $"An approver as a {title} is required", new { @class = "text-danger" })
</div>
</div>
}
</code></pre>
<p>Also, <code>LetterModel.cs</code>:</p>
<pre class="lang-cs prettyprint-override"><code>public class LetterModel
{
public LetterModel()
{
Approvers = new List<LetterApproverModel>();
}
// omitted for brevity...
public IList<SystemRoleModel> ApprovingRoles { get; set; } = new List<SystemRoleModel>();
}
</code></pre>
<p>Now, with that all out of the way, here is the final rendered dropdown (minus the kendo fluff):</p>
<pre class="lang-html prettyprint-override"><code><input id="ApprovingRoles_LetterApprover_0_" name="ApprovingRoles.LetterApprover[0]" required="required" type="text" validationmessage="..." data-role="dropdownlist">
<input id="ApprovingRoles_LetterApprover_1_" name="ApprovingRoles.LetterApprover[1]" required="required" type="text" validationmessage="..." data-role="dropdownlist">
<input id="ApprovingRoles_LetterApprover_2_" name="ApprovingRoles.LetterApprover[2]" required="required" type="text" validationmessage="..." data-role="dropdownlist">
<input id="ApprovingRoles_LetterApprover_3_" name="ApprovingRoles.LetterApprover[3]" required="required" type="text" validationmessage="..." data-role="dropdownlist">
</code></pre>
<p><strong>If the user submits this form, I need to receive a list of selected IDs from this array of dropdowns.</strong> I followed an anti-pattern, so I'm hoping the MVC binding will do its magic here. I just need to figure out the name of the model property that I should add of type <code>List<string></code>.</p>
| [
{
"answer_id": 74121900,
"author": "AKX",
"author_id": 51685,
"author_profile": "https://Stackoverflow.com/users/51685",
"pm_score": 1,
"selected": false,
"text": "import itertools\n\ndef oneline2(string, i=0):\n return itertools.chain.from_iterable(((i := i + ord(c)) for c in s) for ... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74121843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/481656/"
] |
74,121,896 | <p>I have a data.frame that looks like this</p>
<pre class="lang-r prettyprint-override"><code>library(tidyverse)
df1 <- tibble(genes=c("AT1G02205","AT1G02160","AT5G02160", "ATCG02160"))
df1
#> # A tibble: 4 × 1
#> genes
#> <chr>
#> 1 AT1G02205
#> 2 AT1G02160
#> 3 AT5G02160
#> 4 ATCG02160
</code></pre>
<p><sup>Created on 2022-10-19 with <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex v2.0.2</a></sup></p>
<p>and I want to extract anything between the letters <code>A</code> and <code>T</code> and create a new column so my new.df looks like</p>
<pre><code>#> genes chr
#> <chr>
#> 1 AT1G02205 Chr1
#> 2 AT1G02160 Chr1
#> 3 AT5G02160 Chr5
#> 4 ATCG02160 ChrC
</code></pre>
<p>So far, I have found a nasty way to do this, but I am sure I could have done better.</p>
<pre><code>``` r
library(tidyverse)
df1 <- tibble(genes=c("AT1G02205","AT1G02160","AT5G02160", "ATCG02160"))
new.df <- df1 |>
mutate(chr=str_extract(genes, "T(.*?)G")) |>
mutate(chr=str_replace_all(chr, c("T"="", "G"=""))) |>
mutate(chr=paste0("Chr",chr))
new.df
#> # A tibble: 4 × 2
#> genes chr
#> <chr> <chr>
#> 1 AT1G02205 Chr1
#> 2 AT1G02160 Chr1
#> 3 AT5G02160 Chr5
#> 4 ATCG02160 ChrC
</code></pre>
<p><sup>Created on 2022-10-19 with <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex v2.0.2</a></sup></p>
| [
{
"answer_id": 74121991,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 3,
"selected": true,
"text": "str_match"
},
{
"answer_id": 74128514,
"author": "akrun",
"author_id": 3732271,
"author_profile": ... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74121896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7179299/"
] |
74,121,898 | <p><img src="https://i.stack.imgur.com/eGe0d.png" alt="enter image description here" /></p>
<p>I am attempting to write a Marco to select the highlighted cell in the image attached (B11), locate the highlighted colon (20th character from the left) and replace it with a dot and loop this to do all 2500 rows in "B"</p>
<p>I am new to writing macros an would appreciate any help you can give me</p>
| [
{
"answer_id": 74121991,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 3,
"selected": true,
"text": "str_match"
},
{
"answer_id": 74128514,
"author": "akrun",
"author_id": 3732271,
"author_profile": ... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74121898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20280227/"
] |
74,121,901 | <p>I use Jinja2 to create a Python class from a template. My template looks like</p>
<pre><code>class {{class_name}}({{base_class_name}}):
def __init__(self, {{ parameters|join(', ') }}):
{{comment}}
super().__init__()
{% for param in parameters%}
self.{{param}} = {{param}}
{%- endfor %}
{# First variant #}
self.parameters1 = {{parameter_list}}
{# Second variant #}
self.parameters2 = {{['self.'] | product(parameters) | map('join') | list}}
</code></pre>
<p>And my python script is defined as</p>
<pre><code>from itertools import product
from pathlib import Path
import jinja2
def create_class_from_template():
templates_path = Path(__file__).parent / 'templates'
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(templates_path))
jinja_env.filters['product'] = product
parameters = ['param1', 'param2', 'param3'] # For first variant
parameter_list = [f'self.{param}' for param in parameters] # For second variant
template_variables = {
'class_name': 'TestClass',
'base_class_name': 'BaseClass',
'comment': '"""My generated class"""',
'parameters': parameters,
'parameter_list': parameter_list
}
template = jinja_env.get_template('class_template.py.jinja2')
my_class = template.render(template_variables)
with open('my_new_class.py', 'w') as file:
file.write(my_class)
create_class_from_template()
</code></pre>
<p>Which creates the following python file</p>
<pre><code>class TestClass(BaseClass):
def __init__(self, param1, param2, param3):
"""My generated class"""
super().__init__()
self.param1 = param1
self.param2 = param2
self.param3 = param3
self.parameters1 = ['self.param1', 'self.param2', 'self.param3']
self.parameters2 = ['self.param1', 'self.param2', 'self.param3']
</code></pre>
<p>But instead of strings the list should contain the members itself, so that it is <code>self.parameters = [self.param1, self.param2, self.param3]</code>.</p>
<p>Does anybody have an idea how I could create such a list using Jinja2 and Python?</p>
| [
{
"answer_id": 74121991,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 3,
"selected": true,
"text": "str_match"
},
{
"answer_id": 74128514,
"author": "akrun",
"author_id": 3732271,
"author_profile": ... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74121901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8770518/"
] |
74,121,919 | <p>I have this cell array</p>
<pre><code>>> FooCellArray
FooCellArray =
1×7 cell array
Columns 1 through 4
{'Foo1'} {'Foo2'} {'Foo3'} {'Foo4'}
Columns 5 through 7
{'Foo5'} {'Foo6'} {'Foo7'}
</code></pre>
<p><code>cell2mat()</code> converts the array into a character array instead of a 1x7 or 7x1 matrix of <code>'Foo1'</code> ... <code>'Foo7'</code>.</p>
<pre><code>>> (cell2mat(FooCellArray))'
ans =
28×1 char array
'F'
'o'
'o'
'1'
'F'
'o'
'o'
'2'
'F'
'o'
'o'
'3'
'F'
'o'
'o'
'4'
....
</code></pre>
<p>Why?</p>
| [
{
"answer_id": 74122778,
"author": "Edric",
"author_id": 88076,
"author_profile": "https://Stackoverflow.com/users/88076",
"pm_score": 2,
"selected": false,
"text": "cell2mat"
},
{
"answer_id": 74127658,
"author": "Hoki",
"author_id": 3460361,
"author_profile": "https... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74121919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/529310/"
] |
74,121,931 | <p>My data set looks like this:</p>
<pre><code>symbol date adjusted
BAC 2000-01-03 13.61120
BAC 2000-01-04 12.80331
BAC 2000-01-05 12.94381
BAC 2000-01-06 14.05027
BAC 2000-01-07 13.68145
BAC 2000-01-10 13.20725
</code></pre>
<p>Under symbol, there are three different stocks. I want to add a column with the daily returns on the asset, but I am stuck on what to do.</p>
| [
{
"answer_id": 74122810,
"author": "Tech Commodities",
"author_id": 9541415,
"author_profile": "https://Stackoverflow.com/users/9541415",
"pm_score": 2,
"selected": false,
"text": "library(dplyr)\n\ndf %>% \n group_by(symbol) %>% \n mutate(return = adjusted - lag(adjusted, 1))\n\n# A t... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74121931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20109633/"
] |
74,121,948 | <p>df looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>description and keybenefits (14)</th>
<th>brand_cooltouch (1711)</th>
<th>brand_easylogic (1712)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Lorem Ipsum cooltouch Lorem Ipsum</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Lorem Ipsum easylogic Lorem Ipsum</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Lorem Ipsum Lorem Ipsum</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>What I want:
When Column description and keybenefits (14) contains the value 'cooltouch' columm brand_cooltouch (1711) needs to be set to value 1 (int).
When Column description and keybenefits (14) contains the value 'easylogic' columm brand_easylogic (1712) needs to be set to value 1 (int).</p>
<p>Output that I want:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>description and keybenefits (14)</th>
<th>brand_cooltouch (1711)</th>
<th>brand_easylogic (1712)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Lorem Ipsum cooltouch Lorem Ipsum</td>
<td>1</td>
<td></td>
</tr>
<tr>
<td>Lorem Ipsum Lorem Ipsum easylogic</td>
<td></td>
<td>1</td>
</tr>
<tr>
<td>Lorem Ipsum Lorem Ipsum</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>Any help is very much appreciated.</p>
| [
{
"answer_id": 74122045,
"author": "Gonçalo Peres",
"author_id": 7109869,
"author_profile": "https://Stackoverflow.com/users/7109869",
"pm_score": 2,
"selected": true,
"text": "pandas.Series.str.contains"
},
{
"answer_id": 74122050,
"author": "Mortz",
"author_id": 4248842... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74121948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20280252/"
] |
74,122,030 | <p>How do I fix the using own name in class file is not allowed error?</p>
<pre><code>
class_name Player
var player = Player.new() # error line
var player_seed= ""
func _on_Button_pressed():
var new_seed = int($ColorRect/LineEdit.text)
player.player_seed = new_seed
</code></pre>
| [
{
"answer_id": 74132662,
"author": "Christopher Willson",
"author_id": 20286778,
"author_profile": "https://Stackoverflow.com/users/20286778",
"pm_score": 2,
"selected": true,
"text": "class_name Player\n\nvar player_seed= \"\"\nfunc _on_Button_pressed():\n var new_seed = int($ColorRe... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18568056/"
] |
74,122,031 | <p>I need to create a function called random_grades that returns a list consisting of 40 random letters from (A-F).
This is the code so far.. but i dont know how to make the output letters and not numbers...</p>
<pre><code>import random
random_grades = [random.randint(5,10) for i in range (40)]
A = 10
B = 9
C = 8
D = 7
E = 6
F = 5
print(random_grades)
</code></pre>
| [
{
"answer_id": 74122079,
"author": "Fra93",
"author_id": 4952549,
"author_profile": "https://Stackoverflow.com/users/4952549",
"pm_score": 1,
"selected": true,
"text": "index -> grade"
},
{
"answer_id": 74122126,
"author": "Serge Ballesta",
"author_id": 3545273,
"auth... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20280343/"
] |
74,122,032 | <p>I don't understand what I'm doing wrong. I would like to show only dropdown menu. The result is like the photo below: I can edit on it and keyboard is showed. What I'm missing?</p>
<p>Aspected (without pointer enabled):</p>
<p><a href="https://i.stack.imgur.com/e2CVC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e2CVC.png" alt="enter image description here" /></a></p>
<p>Result:</p>
<p><a href="https://i.stack.imgur.com/TK0vL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TK0vL.png" alt="enter image description here" /></a></p>
<p><strong>XML layout</strong></p>
<pre><code> <com.google.android.material.textfield.TextInputLayout
android:id="@+id/gender_container"
style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="20dp"
android:layout_marginVertical="10dp"
android:hint="Gender"
app:layout_constraintTop_toBottomOf="@+id/year_of_bird_container">
<AutoCompleteTextView
android:id="@+id/gender_spinner"
android:layout_width="match_parent"
android:inputType="none"
android:layout_height="match_parent"/>
</com.google.android.material.textfield.TextInputLayout>
</code></pre>
<p><strong>From Fragment</strong></p>
<pre><code>private fun setAdapter() {
val genderList = mutableListOf(
Gender.MALE.toString(),
Gender.FEMALE.toString(),
Gender.OTHER.toString(),
Gender.PREFER_NOT_TO_SAY.toString()
)
val adapter = ArrayAdapter(
requireContext(), R.layout.simple_spinner_dropdown_item, genderList
)
binding.genderSpinner.setAdapter(adapter)
}
</code></pre>
| [
{
"answer_id": 74122079,
"author": "Fra93",
"author_id": 4952549,
"author_profile": "https://Stackoverflow.com/users/4952549",
"pm_score": 1,
"selected": true,
"text": "index -> grade"
},
{
"answer_id": 74122126,
"author": "Serge Ballesta",
"author_id": 3545273,
"auth... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10191400/"
] |
74,122,096 | <p>I am currently accessing my database directly when I get a GET-request by using something like this: <code>_context.EXT_PRAMEX_INSERTS.Where(item => item.MatID == MaterialID</code>.
But my database does not change very often so I want to create a data-class that fetches all tables on startup into lists.
And then I just parse the lists when I need to get any of the entries.</p>
<p>I was thinking that I could create a singleton-class that fetches all data on startup and then I just use that instance to get my data. But how do I access the context inside the singleton ? Or is there a better way to accomplish what I am trying to do ?</p>
<pre><code>public sealed class ExternalDatabase
{
private static ExternalDatabase _instance = null;
private static readonly object _instanceLock = new object();
private List<EXT_PramexInserts>? pramexInserts;
private List<EXT_PrototypeEndmills>? prototypeEndmills;
private static List<IProducts> extAll = new List<IProducts>();
ExternalDatabase()
{
pramexInserts = pramexInserts == null ? _context.Set<EXT_PramexInserts>().ToList() : pramexInserts;
prototypeEndmills = prototypeEndmills == null ? _context.Set<EXT_PrototypeEndmills>().ToList() : prototypeEndmills;
if (extAll.Count == 0)
{
extAll = extAll.Union(pramexInserts).ToList().Union(prototypeEndmills).ToList();
}
}
public static ExternalDatabase Instance
{
get
{
lock (_instanceLock)
{
if (_instance == null)
{
_instance = new ExternalDatabase();
}
return _instance;
}
}
}
public List<IProducts> GetExtraData(string materialid)
{
var result = extAll.FindAll(p => p.MaterialID == materialid);
return result;
}
}
</code></pre>
<pre><code>[ApiController]
[Route("DB")]
public class EXT_TablesController : ControllerBase
{
private readonly Context _context;
private static ExternalDatabase data = ExternalDatabase.Instance;
public EXT_TablesController(Context context)
{
_context = context;
}
//...
[HttpPost]
public IEnumerable<IProducts> Post([FromBody] EXT_Request request)
{
string selectedTable = null;
var (MaterialID, Type, Brand) = request;
if (Type != null && Brand != null)
{
selectedTable = $"EXT_{Brand}_{Type}";
switch (selectedTable)
{
case "EXT_PRAMEX_INSERTS":
//var items = _context.EXT_PRAMEX_INSERTS.Where(item => item.MatID == MaterialID);
return data.GetExtraData(MaterialID);
default:
return null;
}
}
return null;
}
}
</code></pre>
| [
{
"answer_id": 74122208,
"author": "Veikedo",
"author_id": 2118133,
"author_profile": "https://Stackoverflow.com/users/2118133",
"pm_score": 1,
"selected": false,
"text": "DbContext"
}
] | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9067048/"
] |
74,122,109 | <p>What's the best/most accurate way to measure a pages load time that would include the time to load all of the pages resources? (Basically trying to get a load time that a real end user might have).</p>
<p>Is it better to use Wget or cURL for this type of task? (The operating system in use will be Windows due to other dependencies)</p>
| [
{
"answer_id": 74122208,
"author": "Veikedo",
"author_id": 2118133,
"author_profile": "https://Stackoverflow.com/users/2118133",
"pm_score": 1,
"selected": false,
"text": "DbContext"
}
] | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20280386/"
] |
74,122,152 | <p>I have database like this
(Example)</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>client_id</th>
<th>photo_type</th>
<th>date</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>license</td>
<td>13.10.2022</td>
</tr>
<tr>
<td>1</td>
<td>ident</td>
<td>12.10.2022</td>
</tr>
<tr>
<td>2</td>
<td>ident</td>
<td>15.10.2022</td>
</tr>
<tr>
<td>2</td>
<td>license</td>
<td>14.10.2022</td>
</tr>
<tr>
<td>3</td>
<td>license</td>
<td>15.10.2022</td>
</tr>
<tr>
<td>4</td>
<td>ident</td>
<td>16.10.2022</td>
</tr>
</tbody>
</table>
</div>
<p>Where client has two types of photos, and i need to delete 1 type of photo(license or ident) by the date column(the oldest one). For example for client_id 1 i need to delete "ident", and for client 2 delete "license"
I need to use this process for a large amount of data
Please could you provide sollution for this process.</p>
| [
{
"answer_id": 74122208,
"author": "Veikedo",
"author_id": 2118133,
"author_profile": "https://Stackoverflow.com/users/2118133",
"pm_score": 1,
"selected": false,
"text": "DbContext"
}
] | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20278725/"
] |
74,122,173 | <p>This is the code what I have tried.</p>
<p>Based on my limited knowledge it cannot display JSON response of Microsoft.Graph API, it just appears the message box with the content of Microsoft.Graph.User.</p>
<p>How can I parse the JsonResponse into the textbox.</p>
<p>Documentation of ListChat:</p>
<p><a href="https://learn.microsoft.com/en-us/graph/api/chat-list?view=graph-rest-1.0" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/graph/api/chat-list?view=graph-rest-1.0</a></p>
<pre><code>private async void button2_Click(object sender, EventArgs e)
{
var scopes = new[] { "Chat.ReadBasic", "Chat.ReadWrite", "Chat.Read" };
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "5xxxx3-3xxa-4xxx1-9xx0c-exxxb0";
// Value from app registration
var clientId = "35xxxx-5xxx2-4xx9-8500-63xxxxaf";
// using Azure.Identity;
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var userName = "xx.xxxx@xxxi.com";
var password = "Axxxxx@";
// https://learn.microsoft.com/dotnet/api/azure.identity.usernamepasswordcredential
var userNamePasswordCredential = new UsernamePasswordCredential(
userName, password, tenantId, clientId, options);
GraphServiceClient graphClient = new GraphServiceClient(userNamePasswordCredential, scopes);
var request = await graphClient.Me.Request().GetAsync();
String txt = request.ToString();
MessageBox.Show(txt);
}
</code></pre>
<p><a href="https://i.stack.imgur.com/uYm6R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uYm6R.png" alt="In Correct Response" /></a></p>
| [
{
"answer_id": 74122531,
"author": "zTim",
"author_id": 17912875,
"author_profile": "https://Stackoverflow.com/users/17912875",
"pm_score": -1,
"selected": true,
"text": "public class Response\n{\n public List<Value> Values {get;set;}\n}\n\npublic class Value\n{\n public string Id ... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19975249/"
] |
74,122,174 | <p>I am trying to use generic functions' ability to specify behaviour based on the first argument of a list.</p>
<p>In other words, I want the list <code>(atypelist 1 2 3)</code> and the list <code>(btypelist 1 2 3)</code> to have their individual behaviour when passed to <code>foo</code>. So far, this is what I came up with:</p>
<pre><code>(deftype atypelist (lst)
`(eq (car ,lst) 'atypelist))
(deftype btypelist (lst)
`(eq (car ,lst) 'btypelist))
(defmethod foo ((lst atypelist))
(format nil "success atypelist: ~S" lst))
(defmethod foo ((lst btypelist))
(format nil "success btypelist: ~S" lst))
</code></pre>
<p>However, when I call <code>(typep (list 'atypelist 1 2 3) 'atypelist)</code> I get the following error:</p>
<pre><code>error while parsing arguments to DEFTYPE ATYPELIST:
too few elements in
()
to satisfy lambda list
(LST):
exactly 1 expected, but got 0
</code></pre>
<p>I am guessing the error is in my definition of <code>atypelist</code>.</p>
<p>Questions:</p>
<ul>
<li><p><strong>Is there a better way to get the functionality I am looking for?</strong></p>
</li>
<li><p><strong>If yes - what is the way?</strong></p>
</li>
<li><p><strong>If not - how to properly define a type on a list/cons that has a particular symbol in the <code>car</code>?</strong></p>
</li>
</ul>
| [
{
"answer_id": 74123319,
"author": "ignis volens",
"author_id": 17026934,
"author_profile": "https://Stackoverflow.com/users/17026934",
"pm_score": 3,
"selected": true,
"text": "deftype"
},
{
"answer_id": 74123337,
"author": "Renzo",
"author_id": 2382734,
"author_prof... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/861493/"
] |
74,122,186 | <p>Got two entities:</p>
<pre><code>class Entity1{
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "entity1Id", unique = true, nullable = false)
private Integer entity1Id;
@OneToMany(mappedBy = "entity1", cascade=CascadeType.ALL,fetch=FetchType.EAGER)
Set<Entity2> entity2set = new Hashset<>();
}
class Entity2 {
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "entity1Id")
private Entity1 entity1;
}
</code></pre>
<p>No matter how I annotate those fields with @JsonIgnore or @JsonIgnoreProperties, I still get infinite recursion when I try to:</p>
<pre><code>Entity1 entity1 = dao.saveEntity1(fields...);
String json = new ObjectMapper().writeValueAsString(entity1);
org.codehaus.jackson.map.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: org.hibernate.Entity1["entity2set"]->org.hibernate.collection.internal.PersistentSet[0]->gis.hibernate.Entity2["entity1"]->gis.hibernate.Entity1["entity2set"]->org.hibernate.collection.internal.PersistentSet[0]-> ...
</code></pre>
<p>What am I doing wrong? Here are the attempts that I tried:</p>
<pre><code>@JsonIgnoreProperties("entity1")
private Set<Entity2> entity2set = new HashSet<>();
together with
@JsonIgnoreProperties("entity2set")
private Entity1 entity1;
@JsonIgnore
private Entity1 entity1; (inside Entity2)
@JsonIgnore
private Set<Entity2> entity2set = new HashSet<>(); (inside Entity1)
</code></pre>
<p>What am I doing wrong?</p>
| [
{
"answer_id": 74123319,
"author": "ignis volens",
"author_id": 17026934,
"author_profile": "https://Stackoverflow.com/users/17026934",
"pm_score": 3,
"selected": true,
"text": "deftype"
},
{
"answer_id": 74123337,
"author": "Renzo",
"author_id": 2382734,
"author_prof... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6509481/"
] |
74,122,193 | <p>So I am trying some thing out with CSS and I got idea to change color of background but only around cursor. It doesn't matter if it is circle or whatever shape. Is it possible to do it with CSS and if not can I do it with JavaScript.</p>
<p>Example so I translate better what I wanted to do.
Imagine screen is black and "CURSOR"(mouse) is torch and as you are moving it around color around is white and all other stays black.</p>
<p>I tried hover but as I expected it changes color of hole screen.</p>
| [
{
"answer_id": 74122325,
"author": "Fran",
"author_id": 12021064,
"author_profile": "https://Stackoverflow.com/users/12021064",
"pm_score": 3,
"selected": true,
"text": "let root = document.documentElement;\n\nroot.addEventListener(\"mousemove\", e => {\n root.style.setProperty('--mouse... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11204752/"
] |
74,122,203 | <p>i have a data frame that look like this :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">a</th>
<th style="text-align: center;">b</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: center;">1</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: center;">2</td>
</tr>
<tr>
<td style="text-align: left;">3</td>
<td style="text-align: center;">3</td>
</tr>
<tr>
<td style="text-align: left;">4</td>
<td style="text-align: center;">4</td>
</tr>
<tr>
<td style="text-align: left;">5</td>
<td style="text-align: center;">5</td>
</tr>
</tbody>
</table>
</div>
<p>i want to implement the following slicing:</p>
<p>if the window is 2 that means i have to take the first 2 elements of column a and the last 2 elements of columns b. Sum them and take the minimum of them (which i have done it). For example in the data frame above it must be</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">a</th>
<th style="text-align: center;">b</th>
<th style="text-align: right;">result</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: center;">4</td>
<td style="text-align: right;">5</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: center;">5</td>
<td style="text-align: right;">7</td>
</tr>
</tbody>
</table>
</div>
<p>and will report 5.</p>
<p>But (and this is the problem) when the window equals the number of rows of the data frame then i want to take the first element of column a and the last element of column b and just sum them. In my data frame that would be 1+5 = 6.</p>
<p>My effort is this but i dont know how to insert this if else in the function</p>
<pre><code>library(tidyverse)
a = seq(1,5,1)
b = seq(1,5,1)
w = tibble(a,b);w
w[1,1]+w[nrow(w),2]
im = function(mat,window){
if(window == nrow(mat))
mat[1,1] + mat[nrow(mat),2]
else
SA = mat%>%
dplyr::select(1)%>%
dplyr::slice_head(n=window)
SB = mat%>%
dplyr::dplyr::select(2)%>%
dplyr::slice_tail(n=window)
margin = min(SA+SB)
return(margin)
}
im(w,5)
</code></pre>
<p>to test it let's say that i have a vector or windows</p>
<pre><code>vec = seq(1,5,1)
</code></pre>
<p>i want to run this function im that i have created for all the elements in the vector vec.</p>
<p>How can i do them in R ?
Any help</p>
| [
{
"answer_id": 74122325,
"author": "Fran",
"author_id": 12021064,
"author_profile": "https://Stackoverflow.com/users/12021064",
"pm_score": 3,
"selected": true,
"text": "let root = document.documentElement;\n\nroot.addEventListener(\"mousemove\", e => {\n root.style.setProperty('--mouse... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16346449/"
] |
74,122,204 | <p>I know this is beyond the standard, but is there an <strong>official</strong> way to get the current function name, in a specific implementation, say SBCL? Sometimes I want to put the current function name in log messages. I believe if there is a consistent way to get the current function name, it makes maintaining the codes easier, at least I don't have to change the log message every time when I change the function name.</p>
<p>Currently I am using a wrapper macro around the defun</p>
<pre><code>(defmacro defun2 (name (&rest args) &body body)
`(defun ,name (,@args)
(let ((fun-name ',name))
,@body)))
(defun2 foo (x y)
(format nil "fun ~a: x is ~a, y is ~a~%"
fun-name x y))
</code></pre>
<p>But I am interested to know if there is any easier way.</p>
| [
{
"answer_id": 74126826,
"author": "sds",
"author_id": 850781,
"author_profile": "https://Stackoverflow.com/users/850781",
"pm_score": 1,
"selected": false,
"text": "error"
},
{
"answer_id": 74128182,
"author": "coredump",
"author_id": 124319,
"author_profile": "https... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1890745/"
] |
74,122,219 | <p>While migrating vue component to React, i am not able to understand that how can i apply those multiple classes in same div tag.</p>
<p><strong>In Vue,</strong></p>
<pre><code><ul>
<li v-for="m in Menus" @click="moveMenu(m)" class="primaryClass"
:class="{'ur-primay__selected':selectedMenu(m)}"> // selectedMenu() is a method
{{m.name}}
</li>
</ul>
</code></pre>
<p>My query is how can i apply this additional non-prop class attribute adding into the tag in React?</p>
<p>I have tried using template literal to add the classes but not able to do that.</p>
| [
{
"answer_id": 74122283,
"author": "Boussadjra Brahim",
"author_id": 8172857,
"author_profile": "https://Stackoverflow.com/users/8172857",
"pm_score": 0,
"selected": false,
"text": "<div className={`${selectedMenu(m)?'ur-primay__selected':''}`}>\n"
},
{
"answer_id": 74125035,
... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7411584/"
] |
74,122,234 | <p>I have a foreach loop, enumerating my models to create a table. In this table, i need to have an edit button for each model where i call a javascript function to show a modal.</p>
<p>I need to pass the model into the javascript function, but i can't get this to work. I've worked out how to dynamically create the variables, but not how to use it as input.</p>
<p>Right now, it's just hardcoded to use 'department1', which is just the first created. I need toggleManageDepartmentModal to be called with (department + @department.Id)</p>
<p><strong>Creating the table</strong></p>
<pre><code>@foreach (var department in Model.PaginatedDepartments())
{
<tr>
<td>@department.Name</td>
<td>@department.Description</td>
<td class="min">@department.Created.ToLocalTime().ToString("dd-MM-yyyy")</td>
<td class="min">
<div class="text-nowrap">
<script>
//Dynamically create variables for each department
eval('var department' + @department.Id + '= @Json.Serialize(department);');
</script>
<button type="button" class="btn btn-secondary btn-sm" onclick="toggleManageDepartmentModal(department1)">
<span class="fa-solid fa-pen-to-square" aria-hidden="true"></span>
Rediger
</button>
</div>
</td>
</tr>
}
</code></pre>
<p><strong>Javascript function to show modal</strong></p>
<pre><code>function toggleManageDepartmentModal(department) {
var model = {
department : department,
controller : 'Admin',
action : 'ManageDepartment'
};
$.ajax({
type: "Post",
url: "/Modals/ShowManageDepartmentModal",
data:model,
success: function (data) {
$("#loadModal").html(data);
$('#modal-manage-department').modal('show')
}
})
}
</code></pre>
<p><strong>I would like to do something like this:</strong></p>
<pre><code><button type="button" class="btn btn-secondary btn-sm" onclick='toggleManageDepartmentModal(Eval("department" + @department.Id))'>
<span class="fa-solid fa-pen-to-square" aria-hidden="true"></span>
Rediger
</button>
</code></pre>
| [
{
"answer_id": 74122283,
"author": "Boussadjra Brahim",
"author_id": 8172857,
"author_profile": "https://Stackoverflow.com/users/8172857",
"pm_score": 0,
"selected": false,
"text": "<div className={`${selectedMenu(m)?'ur-primay__selected':''}`}>\n"
},
{
"answer_id": 74125035,
... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/354107/"
] |
74,122,314 | <p>I have the following data structure:</p>
<p><a href="https://i.stack.imgur.com/kMRJy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kMRJy.png" alt="enter image description here" /></a></p>
<p>The columns "s" and "d" are indicating the transition of the object in column "x". What I want to do is get a transition string per object present in column "x". E.g. with a "new" column as follows:</p>
<p><a href="https://i.stack.imgur.com/7DCgD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7DCgD.png" alt="enter image description here" /></a></p>
<p>Is there a good way to do it using PySpark?</p>
<p>I tried the following PySpark code using <code>udf</code>, but it does not work:</p>
<pre class="lang-py prettyprint-override"><code>from pyspark.sql.functions import udf
from pyspark.sql.functions import array_distinct
from pyspark.sql.types import ArrayType, StringType
create_transition = udf(lambda x: "->".join([i[0] for i in groupby(x)]))
df= df\
.withColumn('list', F.concat(df['s'], F.lit(','), df['d']))\
.groupBy('x').agg(F.collect_list('list').alias('list2'))\
.withColumn("list3", create_transition("list2"))
</code></pre>
| [
{
"answer_id": 74127603,
"author": "ZygD",
"author_id": 2753501,
"author_profile": "https://Stackoverflow.com/users/2753501",
"pm_score": 2,
"selected": true,
"text": "first"
},
{
"answer_id": 74131200,
"author": "stack0114106",
"author_id": 6867048,
"author_profile":... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13762885/"
] |
74,122,317 | <p>I have a problem with the following code when trying to create a proxy to a function with many overloads:</p>
<pre class="lang-js prettyprint-override"><code>// The function to proxy
function original (a: number): boolean;
function original (a: string): boolean;
function original (a: boolean): boolean;
function original (a: number | string | boolean): boolean {
return true;
}
// The proxy
function pass (a: string | number){
return original(a); // here
};
pass(5);
pass('a');
pass(true);
</code></pre>
<p>When trying to create a proxy to the <code>original</code> function TS throw me the following error :</p>
<pre><code>No overload matches this call.
Overload 1 of 3, '(a: number): boolean', gave the following error.
Argument of type 'string | number' is not assignable to parameter of type 'number'.
Type 'string' is not assignable to type 'number'.
Overload 2 of 3, '(a: string): boolean', gave the following error.
Argument of type 'string | number' is not assignable to parameter of type 'string'.
Type 'number' is not assignable to type 'string'.
Overload 3 of 3, '(a: boolean): boolean', gave the following error.
Argument of type 'string | number' is not assignable to parameter of type 'boolean'.
Type 'string' is not assignable to type 'boolean'.(2769)
input.tsx(5, 10): The call would have succeeded against this implementation, but implementation signatures of overloads are not externally visible.
</code></pre>
<p>Few things to know about this :</p>
<ul>
<li>I reduced my bug to this minimal situation where the problem happens</li>
<li>The <code>pass(true)</code> call return an error, so typing seems to work for the <code>pass</code> function</li>
<li>In my situation, the <code>original</code> function is from a module, so if any situation exist without modifications on it would be perfect</li>
</ul>
<p>Here is a <a href="https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABHATjA5jMBDANogCmwC5EwQBbAIwFMUBKUquOXG7MAbgFgAoUSLATI0mHPiKkAzlDRh0jRM1bsufAdHhJUGLHkIklLNh0XKTa3uvCbhOsfsllKtFIgA%20iGXPQejK0yZjVUQAbz5ERBQaKBAUJFkQGh5eAF8%20a0EtRAAHbCkpA2lZLF9Pcmo6enDeSOjY%20JFdcSJ6TkQAeg7EKAALGEK6FFQ%20VJS%20PIKCAFY2ifypAgBybCW53knFxJo2oA" rel="nofollow noreferrer">TS Playground</a> with the previous code.</p>
| [
{
"answer_id": 74122984,
"author": "Mr. Stash",
"author_id": 13625800,
"author_profile": "https://Stackoverflow.com/users/13625800",
"pm_score": 1,
"selected": false,
"text": "function pass (a: string | number){\n if (typeof a === \"number\") {\n return original(a);\n } else if(type... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11803322/"
] |
74,122,339 | <p>I would like to query count days between start_date and end_date with this script</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
EXTRACT (DAY FROM (MAX(controldate) - MIN(controldate))) days
FROM
rpt_a1903_mon_bonus_log;
</code></pre>
<p>Do you have any better script? May you share it with me?</p>
| [
{
"answer_id": 74122468,
"author": "Suprateem Bose",
"author_id": 10177331,
"author_profile": "https://Stackoverflow.com/users/10177331",
"pm_score": 1,
"selected": false,
"text": "DATEDIFF"
}
] | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10737152/"
] |
74,122,369 | <p>I`m trying to get a specific result. The conditions are simple but still...
is query ok?</p>
<ul>
<li>If first letter of source is 'M' or 'm', load 'M' in target</li>
<li>If first letter of source is 'F' or 'f', load as 'F' in target</li>
<li>Else set to NULL</li>
</ul>
<pre><code>case when substr(GENDER,1,1) = 'M' then 'M',
when substr(GENDER,1,1) = 'm' then 'M'
when substr(GENDER,1,1) = 'F' then 'F'
when substr(GENDER,1,1) = 'f' then 'F'
else NULL
</code></pre>
| [
{
"answer_id": 74122811,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 2,
"selected": false,
"text": "case when upper(substr(gender, 1, 1)) in ('M', 'F') then upper(substr(gender, 1, 1))\n else null\nend\n"
},... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20090021/"
] |
74,122,382 | <p>I'm working on a type safe variant of a client/server communication, where I used mapped types to define parameters required to send a request and the return values in a response for that request. Here's an example of each type:</p>
<pre class="lang-js prettyprint-override"><code>export interface IProtocolParameters {
"authenticate": { username: string; password: string };
"getLogLevel": {};
}
</code></pre>
<p>and</p>
<pre class="lang-js prettyprint-override"><code>export interface IProtocolFinalResult {
"authenticate": { activeProfile: ICommShellProfile };
"getLogLevel": { result: string };
</code></pre>
<p>Unfortunately there are APIs which return multiple responses, so I have to collect them in an array. That's why I defined my actual response type and the promise returning it as:</p>
<pre class="lang-js prettyprint-override"><code>export type ResponseType<K extends keyof IProtocolFinalResult> =
Array<IProtocolFinalResult[K]> | IProtocolFinalResult[K];
export type ResponsePromise<K extends keyof IProtocolFinalResult> = Promise<ResponseType<K>>;
</code></pre>
<p>This has the drawback that everywhere I consume such a result I have first to test if it is an array:</p>
<pre class="lang-js prettyprint-override"><code> public async getLogLevel(): Promise<string> {
const response = await MessageScheduler.get.sendSimpleRequest({
requestType: "getLogLevel",
parameters: {},
});
return Array.isArray(response) ? response[0].result : response.result;
}
</code></pre>
<p>which is inconvenient (especially given that I have hundreds of APIs). I'm now looking for a way to improve that by using a conditional type that either returns an array of <code>IProtocolFinalResult[K]</code> or just <code>IProtocolFinalResult[K]</code>, depending on the API.</p>
<p>From the documentation I understand that you can use a conditional type only based on inheritance, not based on another condition (a flag or a mapped type etc.). Any other idea what I could do here?</p>
<p>What I have in mind is something like:</p>
<pre class="lang-js prettyprint-override"><code>export type ResponseType<K extends keyof IProtocolFinalResult> = multiResults.has(K) ? Array<IProtocolFinalResult[K]> : IProtocolFinalResult[K];
</code></pre>
<p>with</p>
<pre class="lang-js prettyprint-override"><code>const multiResults: Set<string> = new Set(["listSomething"]);
</code></pre>
<p>Here's a <a href="https://www.typescriptlang.org/play?module=1#code/JYOwLgpgTgZghgYwgAgJIAUoHsxYVgG3TijgFsJIoBnZAbwFgAoZV5AIgHNKAZLTnhABuEAuwBc9AL4BuZlObNQVeEjSYceQgDFQcAgCUI1AK4Ew9Zmw7cwfAcNET6yKMbNhJ1MFFCdksvKKTGAAngAOKEbU4Vgg1BAAKhEQADwA0sgQAB6QIAAmtADWEKFYMOrYuPgEuiD60R4AfMgAvFZsAIJQpKGpGFVatXqG7uYA2ukAui0APpWaNXUNY2CTU3JMzDmxUBZhkcjRsfEQGmTACRlZuRAFxaXlC9U6I43mLa3I55dpx3EJZKRDJNJqbbbZXYWZTQVQoVAAZTu+SMAEcTMYwMRSBQqNRrjk8oVkCUyhUBotXvVRqYPpYWGw3OjMah8gB+Lw+PybaxMjHeIEQSTpHlscIkciUaDUSQUl5ECW46XrTYKLZMBAEODUWgAWWM1Dg3ARCAAFhB8mZoPTrOETAAjAjABDIBIFBHAMjhAgQNH8sAE273EmPckaeXYyV4poACnylDgwAIMrQSIKfsxkaVNBBAEpJP9Tj8rukWowGdZWG4wCYoCBkCAIAB3b7YC4JGMxtzUQgiAA0rggACsIAgwLm2mWOpXK93exAY+M6IPaZ4OHB7Qh2AEprnRTOpHvpwEgur8PELNQzRarVA2g3m8h9TqjRATebLT6oDGj+qrx-bwAOjdfIPS9H0M28GNl2PPlMUFSQuF4fhBBEMQB2PcUcSlGhJDoNVD0AsBzRATshH0DEJ1aKcK2Qc8ex9QCCH4GNyIISjwSYQ9mCAA" rel="nofollow noreferrer">playground example</a> for this code..</p>
| [
{
"answer_id": 74122652,
"author": "ij7",
"author_id": 20275210,
"author_profile": "https://Stackoverflow.com/users/20275210",
"pm_score": 2,
"selected": true,
"text": "type Foo = \"a\" | \"b\" | \"c\""
},
{
"answer_id": 74122721,
"author": "Jerryh001",
"author_id": 19870... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1137174/"
] |
74,122,384 | <p>given an input ( http parameters ) with markers ( * ) to the tool, I would like to replace the markers with a string, but just one mark at time</p>
<p>the code:</p>
<pre><code>....
inp = input("http params:" ) # aa=bb*&cc=dd*&ee=ff*
attributes = ["AA","BB","CC"]
mark = "*"
for mark in inp:
for attribute in attributes:
data = inp.replace("*", ")("+attribute)
print(data)
....
</code></pre>
<p>I have this output:</p>
<pre><code>aa=bb)(AA&cc=dd)(AA&ee=ff)(AA
aa=bb)(BB&cc=dd)(BB&ee=ff)(BB
aa=bb)(CC&cc=dd)(CC&ee=ff)(CC
[..]
</code></pre>
<p>while I would like to have this:</p>
<pre><code>aa=bb)(AA&cc=dd&ee=ff
aa=bb)(BB&cc=dd&ee=ff
aa=bb)(CC&cc=dd&ee=ff
aa=bb&cc=dd)(AA&ee=ff
aa=bb&cc=dd)(BB&ee=ff
aa=bb&cc=dd)(CC&ee=ff
aa=bb&cc=dd&ee=ff)(AA
aa=bb&cc=dd&ee=ff)(BB
aa=bb&cc=dd&ee=ff)(CC
</code></pre>
| [
{
"answer_id": 74122652,
"author": "ij7",
"author_id": 20275210,
"author_profile": "https://Stackoverflow.com/users/20275210",
"pm_score": 2,
"selected": true,
"text": "type Foo = \"a\" | \"b\" | \"c\""
},
{
"answer_id": 74122721,
"author": "Jerryh001",
"author_id": 19870... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19036123/"
] |
74,122,392 | <p>I have two ASP.NET Core Web API projects called <code>app.account</code> and <code>core.account</code>. I the both projects have some testing API endpoint like this.</p>
<p>In <code>app.account</code>:</p>
<pre><code>namespace app.account.Controllers
{
[ApiController]
public class SubInteractiveStatementController : ControllerBase
{
[HttpPost]
[Route("account/istatement")]
public async Task<ActionResult> Test(Test cif)
{
return Ok("hello gamma");
}
}
}
public class Test
{
public string cif { get; set; }
}
</code></pre>
<p>In <code>core.account</code>:</p>
<pre><code>namespace core.account.Controllers
{
[ApiController]
public class CasaDetailController : ControllerBase
{
[HttpPost]
[Route("account/istatement")]
public async Task<ActionResult> Test(Test cif)
{
return Ok("hello gamma");
}
}
}
</code></pre>
<p>I'm calling the above API endpoint throughout the client side like this:</p>
<pre><code>try {
CommonResponse commonResponse = new();
var data_ = JsonConvert.SerializeObject(test);
var buffer_ = System.Text.Encoding.UTF8.GetBytes(data_);
var byteContent_ = new ByteArrayContent(buffer_);
byteContent_.Headers.ContentType = new MediaTypeHeaderValue("application/json");
//string _urls = "http://localhost:5088/account/istatement";
string _urls = "http://localhost:5035/account/istatement";
var responses_ = await _httpClient.PostAsync(_urls, byteContent_);
if (responses_.StatusCode == HttpStatusCode.OK) {
Console.WriteLine("[GetPrimeryAccount] Response: Success");
string body = await responses_.Content.ReadAsStringAsync();
var rtns = JsonConvert.DeserializeObject < CommonResponse > (body);
}
} catch (global::System.Exception) {
throw;
}
</code></pre>
<p>http://localhost:5088/account/istatement is the app.account API endpoint and http://localhost:5035/account/istatement is the core.account API endpoint.</p>
<p>When I call the <code>app.account</code>, I'm getting the following error.</p>
<blockquote>
<p>{ StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Date: Wed, 19 Oct 2022 08:43:21 GMT
Server: Kestrel
Transfer-Encoding: chunked
}}</p>
</blockquote>
<p>But it's properly calling the <code>core.account</code> API endpoint.</p>
<p>Both URL's are correct, I checked both endpoints using Postman, and that worked properly.</p>
<p>What could be the reason for this? Could it be a HTTP version issue? How can I determine the exact reason for this? Please help. Thanks</p>
| [
{
"answer_id": 74122652,
"author": "ij7",
"author_id": 20275210,
"author_profile": "https://Stackoverflow.com/users/20275210",
"pm_score": 2,
"selected": true,
"text": "type Foo = \"a\" | \"b\" | \"c\""
},
{
"answer_id": 74122721,
"author": "Jerryh001",
"author_id": 19870... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9047822/"
] |
74,122,394 | <p>Please Help i want to add more instance under instance_id.I have Two more instance where i want to run the commands.Instance ID like i-0e946552448dgsd , i-0e946258789itrs.How to add both the IDs under <strong>instance_id</strong> So that the command can be run on both the instances as well.</p>
<p>here is my Lambda function.</p>
<pre><code>import time
import json
import boto3
def lambda_handler(event, context):
# boto3 client
client = boto3.client("ec2")
ssm = boto3.client("ssm")
instance_id = 'i-0e94623888f942c48'
response = ssm.send_command(
InstanceIds=[instance_id],
DocumentName="AWS-RunShellScript",
Parameters={
"commands": ["sh /root/test.sh"]
},
)
# fetching command id for the output
command_id = response["Command"]["CommandId"]
time.sleep(3)
# fetching command output
output = ssm.get_command_invocation(CommandId=command_id, InstanceId=instance_id)
print(output)
return {"statusCode": 200, "body": json.dumps("Thanks!")}
</code></pre>
| [
{
"answer_id": 74122652,
"author": "ij7",
"author_id": 20275210,
"author_profile": "https://Stackoverflow.com/users/20275210",
"pm_score": 2,
"selected": true,
"text": "type Foo = \"a\" | \"b\" | \"c\""
},
{
"answer_id": 74122721,
"author": "Jerryh001",
"author_id": 19870... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18803588/"
] |
74,122,399 | <p>basically, for now I got :</p>
<ul>
<li><p>a list of duplicates [{},{}] base on the key = 'Email'</p>
</li>
<li><p>an object of the email list and the count of every email :</p>
<pre><code> {
email1@email1.com: 2,
email2@email2.com: 4,
email3@email3.com:2
}
</code></pre>
</li>
</ul>
<p>from the code</p>
<pre><code>
let countObj = {};
let key='Email'
let countFunc = key => {
countObj[key] = ++countObj[key] || 1;
}
matchDuplicates.map(dup=>dup['Email']).forEach(countFunc);
</code></pre>
<ul>
<li><p>an array with the duplicates remove, so a collection of unique objects with the code:</p>
<pre><code>const key='Email'
const arrayUniqueByKey = [...new Map(matchDuplicates.map(item =>
[item[key], item])).values()];
</code></pre>
</li>
</ul>
<p>and I would like the actual objects on the right key, example:</p>
<pre><code> {
email1:[
{name: 'john', age:32, Email: 'john@companyName1.com' , company: 'companyName1'},
{name: 'john', age:32, Email: 'john@companyName1.com' , company: 'companyName1'}
],
email2:[
{name: 'peter', age:40, Email: 'peter@email.com', company: 'companyName2'},
{name: 'peter', age:39, Email: 'peter@email.com', company: 'aPreviousCompanyName'},
{name: 'peter', age:38, Email: 'peter@email.com', company: 'aPreviousCompanyName'},
{name: 'peter', age:40, Email: 'peter@email.com', company: 'companyName2'}
],
email3:[
{name: 'nina' , age: 28, Email: 'nina@companyName3.com', company: 'companyName3'},
{name: 'nina', age: 28, Email: 'nina@companyName3.com', company: 'companyName3'}
]
}
</code></pre>
<p>with pure JS only, no package.</p>
<p>why? because it is a very messy data base with very different keys from one to the other</p>
| [
{
"answer_id": 74122652,
"author": "ij7",
"author_id": 20275210,
"author_profile": "https://Stackoverflow.com/users/20275210",
"pm_score": 2,
"selected": true,
"text": "type Foo = \"a\" | \"b\" | \"c\""
},
{
"answer_id": 74122721,
"author": "Jerryh001",
"author_id": 19870... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15744806/"
] |
74,122,405 | <p>I am teaching a simple comparisons on programming, but I have found something odd when I am trying to list all the natural numbers below 10 that are multiples of 3 or 5, when I add the following conditions the number 0 is added, even when specifically is conditional to add numbers if they are different from 0, I have already made invalidate caches and restart to Android Studio. Am I missing something here? Below is the code</p>
<pre><code> fun multiplesOf() {
val arrayOfSelected: ArrayList<Int> = arrayListOf()
for (i in 0..10) {
if (i != 0 && i % 3 == 0 || i % 5 == 0) {
arrayOfSelected.add(i)
}
}
Log.i("TAG", "multiplesOf: $arrayOfSelected")
}
</code></pre>
| [
{
"answer_id": 74122462,
"author": "Some random IT boy",
"author_id": 9248718,
"author_profile": "https://Stackoverflow.com/users/9248718",
"pm_score": 3,
"selected": true,
"text": "i=0"
},
{
"answer_id": 74122467,
"author": "z.y",
"author_id": 19023745,
"author_profi... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10815701/"
] |
74,122,409 | <p>On first screenshot i have my back button, but i don't understand how to make it filled like on second screenshot from Telegram.</p>
<p>p.s. I have navigation controller</p>
<p><a href="https://i.stack.imgur.com/nKNPL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nKNPL.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/NYGyp.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NYGyp.jpg" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74122573,
"author": "Maxim Zakopaylov",
"author_id": 3485139,
"author_profile": "https://Stackoverflow.com/users/3485139",
"pm_score": 0,
"selected": false,
"text": "private var backBtnBarButtonItem: UIBarButtonItem {\n let btn = UIBarButtonItem(customView: *you coustom... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19967313/"
] |
74,122,428 | <p>How to create the dropdown title and the dropdown list menu side by side instead of up and down plotly?</p>
<pre><code>app.layout = dbc.Container([
dbc.Row([
dbc.Col(html.H1("Testing",
className = 'text-center text-primary, mb-4 '
,style={"textDecoration":"underline",'font-weight': 'bold'}),
width=12
),
]),
html.Br(),
html.Br(),
dbc.Row([
dbc.Col([
html.H3('Product'
,style={'font-size': '25px'}
),
dcc.Dropdown(id='product_dd', value= None,
options = [{'label':x, 'value':x}
for x in product_cat],
searchable = True, search_value='',
placeholder= 'Please select ...',
clearable=True
),
html.Br(),
], width=3, md=4),
])
</code></pre>
<p><br><br>
Output:<br></p>
<p><a href="https://i.stack.imgur.com/IqN0H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IqN0H.png" alt="enter image description here" /></a></p>
<p><br><br><br>
Expected output:<br></p>
<p><a href="https://i.stack.imgur.com/9Ebp0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9Ebp0.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74122573,
"author": "Maxim Zakopaylov",
"author_id": 3485139,
"author_profile": "https://Stackoverflow.com/users/3485139",
"pm_score": 0,
"selected": false,
"text": "private var backBtnBarButtonItem: UIBarButtonItem {\n let btn = UIBarButtonItem(customView: *you coustom... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19403948/"
] |
74,122,432 | <p>What is more efficient in Angular, transferring data into a child component with one @Input() decorator or more @Input() decorators?</p>
<p>I have two solutions: send all the data as one object into a child component or send it separately.</p>
<p>for example :</p>
<pre><code><child-component [data]="{ ...product, ...reviews }">
</code></pre>
<p>or</p>
<pre><code><child-component [product]="product data" [reviews]="reviews data" ...so on>.
</code></pre>
<p><strong>My question is about rendering speed. Which approach is more efficient for Angular rendering?</strong></p>
| [
{
"answer_id": 74122599,
"author": "Andrei",
"author_id": 11078857,
"author_profile": "https://Stackoverflow.com/users/11078857",
"pm_score": 1,
"selected": false,
"text": "<child-component [data]=\"{somethin1, something2, ...soemthing3}\">\n"
}
] | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2678346/"
] |
74,122,440 | <p>I have a big array and want to filter it by comparing each two elements.</p>
<p>for ex :</p>
<pre><code>0:
id: "0.0.243"
key: {base: '1.3.0', quote: '1.3.1', sequence: -173}
op:
account_id: "1.2.71"
fee: {amount: 0, asset_id: '1.3.0'}
order_id: "1.7.475"
pays: {amount: 96000, asset_id: '1.3.1'}
receives: {amount: 96000000, asset_id: '1.3.0'}
time: "2022-10-11T13:42:24"
1:
id: "0.0.242"
key: {base: '1.3.0', quote: '1.3.1', sequence: -172}
op:
account_id: "1.2.460"
fee: {amount: 4800, asset_id: '1.3.1'}
order_id: "1.7.709"
pays: {amount: 96000000, asset_id: '1.3.0'}
receives: {amount: 96000, asset_id: '1.3.1'}
time: "2022-10-11T13:42:24"
</code></pre>
<p>so here I need to compare each two elements by it's order_id,</p>
<p>like : <code>1.7.709 > 1.7.475</code></p>
<p>I'm trying like this :</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 trial = histories.filter((history, i, arr) => {
const prev = arr[i - 1];
return history.op.order_id === prev.op.order_id;
});
console.log(trial);</code></pre>
</div>
</div>
</p>
<p>but it doesn't work.
how can I achieve my expected result?</p>
<p>here is array looks like</p>
<p><a href="https://i.stack.imgur.com/AUoWV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AUoWV.png" alt="enter image description here" /></a></p>
<p>I want to filter array by higher order id but have two compare each two elements , like need to check with order id is higher between index 0 and index 1.</p>
| [
{
"answer_id": 74122599,
"author": "Andrei",
"author_id": 11078857,
"author_profile": "https://Stackoverflow.com/users/11078857",
"pm_score": 1,
"selected": false,
"text": "<child-component [data]=\"{somethin1, something2, ...soemthing3}\">\n"
}
] | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20158414/"
] |
74,122,461 | <p>I printed files using os.listdir() and found the files inside the folder i am looking for. I'm now looking for user input to know which files to look in. The files are in years and month and I'm not sure how?</p>
<p><a href="https://i.stack.imgur.com/jchPG.png" rel="nofollow noreferrer">Picture of my code now</a></p>
| [
{
"answer_id": 74122599,
"author": "Andrei",
"author_id": 11078857,
"author_profile": "https://Stackoverflow.com/users/11078857",
"pm_score": 1,
"selected": false,
"text": "<child-component [data]=\"{somethin1, something2, ...soemthing3}\">\n"
}
] | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20280478/"
] |
74,122,501 | <p>So im trying to make an executor but i got that error along with "A namespace cannot directly contain members such as field, methods or statements"</p>
<p>i tried looking into it myself and googling around a bit but couldnt really find a solution to the problem, any help here are of course appreciated as this is a project i would like to get working to 100% as intended.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeAreDevs_API;
namespace ZynTap_Executor
{
ExploitAPI api = new ExploitAPI();
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
Point lastPoint;
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
lastPoint = new Point(e.X, e.Y);
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
this.Left += e.X - lastPoint.X;
this.Top += e.Y - lastPoint.Y;
}
}
private void button2_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Minimized;
}
private void button4_Click(object sender, EventArgs e)
{
fastColoredTextBox1.Clear();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
api.SendLuaScript(fastColoredTextBox1.Text);
}
private void button8_Click(object sender, EventArgs e)
{
api.LaunchExploit();
}
private void button5_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
openFileDialog1.Title = "Open";
fastColoredTextBox1.Text = File.ReadAllText(openFileDialog1.FileName);
}
}
private void button6_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (Stream s = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(fastColoredTextBox1.Text);
}
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
fastColoredTextBox1.Text = File.ReadAllText($"./Scripts/{listBox1.SelectedItem}");
}
private void button7_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();//Clear Items in the LuaScriptList
Functions.PopulateListBox(listBox1, "./Scripts", "*.txt");
Functions.PopulateListBox(listBox1, "./Scripts", "*.lua");
}
}
}
</code></pre>
| [
{
"answer_id": 74122591,
"author": "Alessandro",
"author_id": 6225773,
"author_profile": "https://Stackoverflow.com/users/6225773",
"pm_score": 1,
"selected": false,
"text": "ExploitAPI api = new ExploitAPI();\n"
},
{
"answer_id": 74122664,
"author": "FUZIION",
"author_id... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20280650/"
] |
74,122,504 | <p>I have a dataframe in python pandas with date and time.
I would like to assign an integer according to the predefined interval, for instance:</p>
<pre><code> Name Date Time
F 01/01/22 23:50:00
F1 01/01/22 22:00:00
F2 01/01/22 20:00:00
F3 01/01/22 19:00:00
F4 01/01/22 18:00:00
F5 01/01/22 17:00:00
F6 01/01/22 16:00:00
</code></pre>
<p>I would like to obtain:</p>
<pre><code> Name Date Time Interval
F 01/01/22 23:50:00 1
F1 01/01/22 22:00:00 1
F2 01/01/22 20:00:00 2
F3 01/01/22 19:00:00 2
F4 01/01/22 18:00:00 3
F5 01/01/22 17:00:00 3
F6 01/01/22 16:00:00 4
</code></pre>
<p>The interval should have an integer every 2 consecutive hours. The logic would be to have an integer with an hour in range [from 00:00:00 to 02:00:00]=1, [from 02:00:01 to 04:00:00]=2,[from 04:00:01 to 06:00:00]=3,[from 06:00:01 to 08:00:00]=4,etc...</p>
<p>is it possible in pandas?</p>
<p>Thanks</p>
| [
{
"answer_id": 74122597,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "cut"
},
{
"answer_id": 74122731,
"author": "mozway",
"author_id": 16343464,
"author_profile": "ht... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043636/"
] |
74,122,511 | <p><strong>Want to do</strong></p>
<p>I want to get <strong>android:id = "@+id/drawer_layout2"</strong> at activity which is not linked with <strong>SetContentView</strong> because I want to open navigation? DrawerLayout? with a button. I already know that <strong>drawer.OpenDrawer(GravityCompat.Start)</strong> open it but <strong>drawer</strong> is null.</p>
<p><strong>Relation</strong></p>
<p>MainActivity.cs - activity_main.xml</p>
<p>NaviDrawer.cs - drawer.xml</p>
<p><strong>Error Message</strong></p>
<pre><code>System.NullReferenceException: 'Object reference not set to an instance of an object.'
</code></pre>
<p><strong>Code</strong></p>
<p>MainActivity</p>
<pre><code>public class MainActivity : AppCompatActivity, NavigationView.IOnNavigationItemSelectedListener, TabLayout.IOnTabSelectedListener
{
private Context context;
DrawerLayout m_drawer;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.activity_main);
context = this;
m_drawer = FindViewById<DrawerLayout>(Resource.Id.drawer_layout2);
btn_drawer = FindViewById<Button>(Resource.Id.btn_drawer);
btn_drawer.Click += Btn_Drawer_Click;
}
private void Btn_Drawer_Click(object sender, EventArgs args)
{
m_drawer.OpenDrawer(GravityCompat.Start);
}
</code></pre>
<p>Drawer.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/test"
android:layout_width="match_parent"
android:layout_height="58dp"
android:text="test"
android:textSize="12dp"
android:gravity="center">
</TextView>
</LinearLayout>
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
</code></pre>
| [
{
"answer_id": 74122597,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "cut"
},
{
"answer_id": 74122731,
"author": "mozway",
"author_id": 16343464,
"author_profile": "ht... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20229243/"
] |
74,122,522 | <p>I have a text, for example:</p>
<pre><code>a = '''
- Hello, this is a noname podcast and joining us today is Joe.
- Who's Joe? you would ask...
...
- Anyway, thank you for listening to the noname podcast. Special thanks to Joe, who was joining us today.
'''
</code></pre>
<p>Now I would like to find the repeating parts of this text of a sufficient length. For example, let us set the limit to 4 (so we are looking for strings longer than 4), so the name Joe is left out. So we should have:
<code>['noname podcast', 'joining us today']</code>.</p>
<p>I had an idea of using the <code>difflib</code> for this, but it only works by comparing two texts, so I tried feeding it the same text two times and picking sequences which will appear more than twice with <code>difflib.SequenceMatcher</code>, but it just returns one sequence which is the whole text (not very surprisingly, really).</p>
<p>What would be the correct way to approach this?</p>
| [
{
"answer_id": 74122597,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "cut"
},
{
"answer_id": 74122731,
"author": "mozway",
"author_id": 16343464,
"author_profile": "ht... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9102437/"
] |
74,122,534 | <p>i have some records on mysql db, i tried to group by month, data is correct but time of March month is showing as <strong>"2022-03-22"</strong>, i required as same as other months like <strong>2022-03-01.</strong></p>
<pre><code> time month_name inc_number
2022-01-04 19:58:09 January 39393
2022-02-08 17:36:33 February 90203
2022-03-22 13:40:48 March 82923
2022-04-01 00:14:33 April 23333
2022-05-01 00:31:58 May 33322
2022-06-06 17:21:29 June 33244
2022-07-01 04:19:20 July 90283
2022-08-01 00:07:04 August 8428
2022-09-01 09:40:15 September 10097
2022-10-01 00:30:19 October 6421
2021-12-01 07:12:30 December 8521
</code></pre>
<p>the query im using is below</p>
<pre><code>SELECT
created_on as 'time',
MONTHNAME(created_on) AS 'month_name',
count(distinct id_number) AS "inc_number"
FROM test_reports
WHERE
MONTH(created_on)
GROUP BY MONTH(created_on)
ORDER BY MONTH(created_on)
</code></pre>
<p>Please suggest the way to get all time should be first date of each month.</p>
| [
{
"answer_id": 74122667,
"author": "verhie",
"author_id": 2223525,
"author_profile": "https://Stackoverflow.com/users/2223525",
"pm_score": 1,
"selected": false,
"text": "DATE_FORMAT(created_on, '%Y-%m-01')"
},
{
"answer_id": 74123008,
"author": "user9300309",
"author_id"... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9300309/"
] |
74,122,536 | <p>I have a newly created Spring Boot 3.0 application using Kotlin, which returns 401 on all HTTP calls.</p>
<p>MyApiApplication.kt</p>
<pre><code>package com.my.app.api
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication()
class MyApiApplication
fun main(args: Array<String>) {
runApplication<MyApiApplication>(*args)
}
</code></pre>
<p>TestController.kt</p>
<pre><code>package com.my.app.api
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.time.LocalDateTime
@RestController
@RequestMapping("/api/test")
class TestController {
@GetMapping("/")
fun test(): LocalDateTime {
return LocalDateTime.now()
}
}
</code></pre>
<p>application.properties</p>
<pre><code>server.port=6020
spring.datasource.url=jdbc:postgresql://localhost:6010/mydb
spring.datasource.username=mydb
spring.datasource.password=mydbpass
</code></pre>
<p>pom.xml</p>
<p>
4.0.0
org.springframework.boot
spring-boot-starter-parent
3.0.0-SNAPSHOT
</p>
<pre><code><groupId>com.datadriven.headless.api</groupId>
<artifactId>headless-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>headless-api</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
<kotlin.version>1.7.20</kotlin.version>
<testcontainers.version>1.17.4</testcontainers.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-bom</artifactId>
<version>${testcontainers.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<configuration>
<args>
<arg>-Xjsr305=strict</arg>
</args>
<compilerPlugins>
<plugin>spring</plugin>
<plugin>jpa</plugin>
</compilerPlugins>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-noarg</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<repositories>
...
</repositories>
<pluginRepositories>
...
</pluginRepositories>
</code></pre>
<p>"curl -v localhost:6020/api/test" returns always returns 401. What am I doing wrong?</p>
| [
{
"answer_id": 74123172,
"author": "Panagiotis Bougioukos",
"author_id": 7237884,
"author_profile": "https://Stackoverflow.com/users/7237884",
"pm_score": 1,
"selected": false,
"text": "error"
},
{
"answer_id": 74123401,
"author": "xgb84j",
"author_id": 1398440,
"auth... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1398440/"
] |
74,122,538 | <p>I'm a beginner of flask,when i tried to run app.py on the server,it seemed to be wrong.And it can works on localhost.
I think it's wrong with the database and have tried to change the ip of database,but it not worked.</p>
<pre><code>Traceback (most recent call last):
File "app.py", line 27, in <module>
import auth
File "/tmp/pycharm_project_flaskr/auth.py", line 5, in <module>
from db import get_db, User
File "/tmp/pycharm_project_flaskr/db.py", line 22, in <module>
db.init_app(app)
File "/usr/local/lib/python3.7/site-packages/flask_sqlalchemy/extension.py", line 305, in init_app
engines = self._app_engines.setdefault(app, {})
File "/usr/local/lib/python3.7/weakref.py", line 489, in setdefault
return self.data.setdefault(ref(key, self._remove),default)
TypeError: cannot create weak reference to 'LocalProxy' object
</code></pre>
<p>That's the way about databases.</p>
<pre><code>app = current_app
DB_URI = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy()
db.init_app(app)
</code></pre>
| [
{
"answer_id": 74146015,
"author": "Emily",
"author_id": 20295433,
"author_profile": "https://Stackoverflow.com/users/20295433",
"pm_score": 2,
"selected": false,
"text": "from flask import Flask\n\nimport os\n\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\n... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19782462/"
] |
74,122,553 | <p>I have some Java code that is having an error and can't run.</p>
<p>Here are the task requirements:</p>
<blockquote>
<p>Write a program that asks the user to enter a minimum of twenty-five positive integers
greater than zero and less than 1000. The program should stop asking the user for input
when they enter a zero or a negative number. The program then prints out:</p>
<ol>
<li>The number of positive integers whose value is less than 10</li>
<li>The number of positive integers whose value is equal to or greater than 10
but less than 100</li>
<li>The number of positive integers whose value is equal to or greater than 100
but less than 1000</li>
<li>The program should cater for a wrong input: if the user enters a wrong input (a value
which is not an integer) the program should notify the user that invalid input has been
entered and ask the user to enter positive integers again.</li>
</ol>
</blockquote>
<p>Here is my code:</p>
<pre><code>import java.util.Scanner;
public class task5 {
public static void main(String args[])
{
//alowing the user to enter 25 positive
int number;
Scanner sc=new Scanner(System.in);
System.out.print("Enter first number: ");
number = sc.nextInt();
System.out.print("Enter second number: ");
number = sc.nextInt();
System.out.print("Enter third number: ");
number = sc.nextInt();
System.out.print("Enter fourth number: ");
number = sc.nextInt();
System.out.print("Enter fifth number: ");
number = sc.nextInt();
System.out.print("Enter seventh number: ");
number = sc.nextInt();
System.out.print("Enter eighth number: ");
number = sc.nextInt();
System.out.print("Enter ninth number: ");
number = sc.nextInt();
System.out.print("Enter tenth number: ");
number = sc.nextInt();
System.out.print("Enter eleventh number: ");
number = sc.nextInt();
System.out.print("Enter twelfth number: ");
number = sc.nextInt();
System.out.print("Enter thirteenth number: ");
number = sc.nextInt();
System.out.print("Enter fourteenth number: ");
number = sc.nextInt();
System.out.print("Enter fifteenth number: ");
number = sc.nextInt();
System.out.print("Enter sixteenth number: ");
number = sc.nextInt();
System.out.print("Enter seventeenth number: ");
number = sc.nextInt();
System.out.print("Enter eighteenth number: ");
number = sc.nextInt();
System.out.print("Enter nineteenth number: ");
number = sc.nextInt();
System.out.print("Enter twentieth number: ");
number = sc.nextInt();
System.out.print("Enter twenty-first number: ");
number = sc.nextInt();
System.out.print("Enter twenty-second number: ");
number = sc.nextInt();
System.out.print("Enter twenty-third number: ");
number = sc.nextInt();
System.out.print("Enter twenty-fourth number: ");
number = sc.nextInt();
System.out.print("Enter twenty-fifth number: ");
number = sc.nextInt();
if(number>0 && number<=10)
{
System.out.println("Positive integers from 1 to 10");
else if (number >=10 && number <100)
{
System.out.println("positive integers from 10 to 100");
}
else if (number >=100 && number<1000)
{
System.out.println("Enter positive integers only");
}
}
}
}
</code></pre>
<p>Visual Studio code underlines one of the last 4 brackets, we tried to delete and add brackets and nothing worked.</p>
<p>Here is the error:</p>
<p>Exception in thread "main" java.lang.Error: Unresolved compilation problems:</p>
<blockquote>
<p>Syntax error, insert "}" to complete Statement
Syntax error on token "}", delete this token</p>
</blockquote>
<p>Where is the mistake?</p>
| [
{
"answer_id": 74122827,
"author": "Matteo Albertelli",
"author_id": 20280721,
"author_profile": "https://Stackoverflow.com/users/20280721",
"pm_score": -1,
"selected": false,
"text": " if(number>0 && number<=10)\n {\n System.out.println(\"Positive integers from 1... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12362980/"
] |
74,122,554 | <p><a href="https://i.stack.imgur.com/tUBIo.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I thought I was wrong with jQuery connection but I tested with function(){console.log}
and it worked. but after function addNumber()~ is not work at all...</p>
| [
{
"answer_id": 74122827,
"author": "Matteo Albertelli",
"author_id": 20280721,
"author_profile": "https://Stackoverflow.com/users/20280721",
"pm_score": -1,
"selected": false,
"text": " if(number>0 && number<=10)\n {\n System.out.println(\"Positive integers from 1... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20280713/"
] |
74,122,579 | <p>I have a following code snippet in python.</p>
<pre><code>class Test():
def a(self,dct,res_dct,lst):
url_ls = []
....
return url_ls
def b(self):
....
</code></pre>
<p>I want to access the url_ls from a() to b(). How is it possible?</p>
| [
{
"answer_id": 74122827,
"author": "Matteo Albertelli",
"author_id": 20280721,
"author_profile": "https://Stackoverflow.com/users/20280721",
"pm_score": -1,
"selected": false,
"text": " if(number>0 && number<=10)\n {\n System.out.println(\"Positive integers from 1... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10726514/"
] |
74,122,584 | <p>I have a string and a list of words:</p>
<pre><code>string ="""Ventilation box with reference VE03 with soundproofed box with inspection door
with the following technical characteristics: Air flow: 250 l s Available static pressure:
200 Pa With voltage regulator With characteristics according to project technical data
sheets Model make: CVB 4 180 180N or equivalent Includes flexible anti-vibration tarpaulins
at the air connections and metal dampers and supports Includes cable."""
list1 = ["CVB","1100","250"]
list2 = ["CVB","4","180","180N","RE","147W"]
</code></pre>
<p>I want to check if the string has 2 or more words from the list and if they are near each other (for example 5 positions/words before and after). Using 'list1' has to be false cause 'CVB' and '250' aren't together, but using 'list2' should return true ("CVB","4","180" and "180N" are together).</p>
<p>My actually function only detects if has the word in the string:</p>
<pre><code>count = 0
for word in list1:
if len(re.findall("(?<!\S)" + word + "(?!\S)", string)) > 0:
count+=1
print(count)
</code></pre>
| [
{
"answer_id": 74122827,
"author": "Matteo Albertelli",
"author_id": 20280721,
"author_profile": "https://Stackoverflow.com/users/20280721",
"pm_score": -1,
"selected": false,
"text": " if(number>0 && number<=10)\n {\n System.out.println(\"Positive integers from 1... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20130004/"
] |
74,122,589 | <p>I'm parsing every XBRL files from the SEC through EDGAR in order to retrieve some data (in json format on python).</p>
<p>I have no problem parsing those files. My problem lies in the structure of the XBRL files provided by the SEC, i noticed that some companies use some tags and others dont. Some will use "Revenues" while others won't have any tags pertaining to revenues, i have the same issue with "ShortTermBorrowings"...</p>
<p>Is there a list of XBRL tags from the SEC that are used throughout all companies ?</p>
<p>Thank's</p>
| [
{
"answer_id": 74122827,
"author": "Matteo Albertelli",
"author_id": 20280721,
"author_profile": "https://Stackoverflow.com/users/20280721",
"pm_score": -1,
"selected": false,
"text": " if(number>0 && number<=10)\n {\n System.out.println(\"Positive integers from 1... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20280691/"
] |
74,122,627 | <p>It is not question about how to keep TextField above keyboard (put it inside ScrollView), I wonder how to keep TextField containing View fully be visible above Keyboard. For example behind TextField some info text, which should be visible while user print the text.</p>
<pre><code>VStack { // This all should be above keyboard
TextField(...)
Text("Some hints about entered text")
}
</code></pre>
<p>In screens:
Now I have this (you can see TextField just above keyboard, but we don't see content under TextField)
<a href="https://i.stack.imgur.com/CXgzx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CXgzx.png" alt="enter image description here" /></a></p>
<p>But I want to get this (With "Some additional info" label, which should also pop above keyboard when TextField become first responder):</p>
<p><a href="https://i.stack.imgur.com/6XqBc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6XqBc.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74122827,
"author": "Matteo Albertelli",
"author_id": 20280721,
"author_profile": "https://Stackoverflow.com/users/20280721",
"pm_score": -1,
"selected": false,
"text": " if(number>0 && number<=10)\n {\n System.out.println(\"Positive integers from 1... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1752613/"
] |
74,122,648 | <p>I am working with an SPSS file that has been exported as tab delimited. In SPSS, you can set values to represent different types of missing and the dataset has 98 and 99 to indicate missing.</p>
<p>I want to convert them to NA but only in certain columns (V2 and V3 in the example data, leaving V1 and V4 unchanged).</p>
<pre><code>library(dplyr)
testdf <- data.frame(V1 = c(1, 2, 3, 4),
V2 = c(1, 98, 99, 2),
V3 = c(1, 99, 2, 3),
V4 = c(98, 99, 1, 2))
outdf <- testdf %>%
mutate(across(V2:V3), . = ifelse(. %in% c(98,99), NA, .))
</code></pre>
<p>I haven't used <code>across</code> before and cannot work out how to have the <code>mutate</code> return the <code>ifelse</code> into the same columns. I suspect I am overthinking this, but can't find any similar examples that have both <code>across</code> and <code>ifelse</code>. I need a tidyverse answer, prefer dplyr or tidyr.</p>
| [
{
"answer_id": 74122704,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 3,
"selected": true,
"text": "?across"
},
{
"answer_id": 74122790,
"author": "Quinten",
"author_id": 14282714,
"author_profile":... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4346285/"
] |
74,122,649 | <p>(I'm writing about matrices, but don't worry, this is not a maths question and presumes no maths knowledge.)</p>
<p>I have a <code>Matrix</code> class that has three fields</p>
<pre><code>double[] Data;
int Rows;
int Columns;
</code></pre>
<p>and defines hundreds of mathematical operations.</p>
<p>Additionally, I have a <code>SymmetricMatrix : Matrix</code> subclass that has no instance fields of its own, that offers all of the operations above via inheritance, offers some additional operations (like EigenvalueDecomposition), <em>and finally</em> repeats <em>some</em> definitions with a <code>new</code> keyword to change the return type to <code>SymmetricMatrix</code>.</p>
<p>For example, if <code>Matrix</code> has</p>
<pre><code>public Matrix MatrixMultiplication(Matrix otherMatrix)
public Matrix ScaledBy(double scalar)
</code></pre>
<p>then <code>SymmetricMatrix</code> would simply inherit the <code>MatrixMultiplication</code> but it would change the <code>ScaledBy</code> to return a <code>SymmetricMatrix</code>.</p>
<p>Rather than reimplementing <code>ScaledBy</code> , I define it via</p>
<pre><code>// SymmetricMatrix.cs
public new SymmetricMatrix ScaledBy(double scalar) => base.ScaledBy(scalar).AsSymmetricMatrix()
// Matrix.cs
public SymmetricMatrix AsSymmetricMatrix() => Unsafe.As<SymmetricMatrix>()
</code></pre>
<p>(I'm using <code>new</code> instead of <code>virtual+override</code> for reasons that don't matter for the purposes of this question).</p>
<p>I found this approach to work surprisingly well, and it allows me to be super succinct in defining <code>SymmetricMatrix.cs</code>. The obvious downside is that it may exploit unsupported behavior (?) and that it confuses the debugger I'm using a lot (the runtime type of the result of the cast is <code>Matrix</code> which is not a subclass of its compile time type <code>SymmetricMatrix</code>, and yet, all the operations defined on <code>SymmetricMatrix</code> succeed because the data held by both classes is the same)</p>
<p><strong>Questions</strong></p>
<ol>
<li><p>Do you foresee any problems with my approach that I haven't though of?</p>
</li>
<li><p>Might my approach break with the next dotnet version?</p>
</li>
<li><p>Do you think there are cleaner ways of achieving what I want? I had a few ideas but none seem to work out cleanly. For example, I cannot encode which operations preserve Child classes in the parent class via</p>
</li>
</ol>
<pre><code>class Matrix<T> where T : Matrix
...
T ScaledBy(double other)
</code></pre>
<p>because whether or not an operation preserves a Child class is knowledge only the Child can have. For example, <code>SymmetricPositiveDefiniteMatrix</code> would NOT be preserved by <code>ScaledBy</code>.</p>
<p>Alternatively, I could use encapsulation over inheritance and define</p>
<pre><code>class BaseMatrix
{
...lots of operations
}
...
class Matrix : BaseMatrix
{
private BaseMatrix _baseMatrix;
...lots of "OperationX => new Matrix(_baseMatrix.OperationX)"
}
class SymmetricMatrix : BaseMatrix
{
private BaseMatrix _baseMatrix;
...lots of "OperationX => preserving ? new SymmetricMatrix(_baseMatrix.OperationX) : new Matrix(_baseMatrix.OperationX);"
}
</code></pre>
<p>That's very sad to code up though, because I'd have to manually propagate every change I make to <code>BaseMatrix</code> to, at the moment, four extra classes, and users would have to manually cast <code>SymmetricMatrix</code>s to <code>Matrix</code> in lots of scenarios.</p>
<p>Finally, I could simply not offer subclasses and rather have flags like <code>bool _isSymmetric</code> and encode the operations that preserve symmetry/positivity/... by changing/setting the flags in all my methods. This is sad too, because :</p>
<ol>
<li><p>Users would then be able to write <code>Matrix.EigenvalueDecomposition()</code> just to have this break at runtime with a <code>You have to promise me that your matrix is symmetric because I only implemented EigenvalueDecomposition for that case</code> error</p>
</li>
<li><p>It would be too easy to forget resetting a flag when it's not preserved and then accidentally running an operation that assumes symmetry (which BLAS does by simply ignoring half of the matrix)</p>
</li>
<li><p>I like being able to specify in the type system rather than the comments that, e.g., the matrix I return from <code>CholeskyFactor</code> is lower triangular (conventions differ and some may expect an upper triangular matrix)</p>
</li>
<li><p>Users wouldn't see which flags are currently set so they wouldn't know whether I use the "specialized" version of a given algorithm and likely end up using <code>.SetSymmetric()</code> unnecessarily all over the place just to be safe.</p>
</li>
</ol>
| [
{
"answer_id": 74122841,
"author": "Irwene",
"author_id": 2245256,
"author_profile": "https://Stackoverflow.com/users/2245256",
"pm_score": 2,
"selected": false,
"text": "public abstract class BaseMatrix<TMatrix> where TMatrix : BaseMatrix<TMatrix>\n{\n // Replace with how you actuall... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3437012/"
] |
74,122,656 | <p>I need to convert an array of boolean values indicating whether the store is open on a given day.</p>
<p><em><strong>For example:</strong></em></p>
<p><strong>Case 1:</strong></p>
<pre class="lang-none prettyprint-override"><code>Input data: [true, true, true, true, true, true, true]
Expected output: Every day
</code></pre>
<p><strong>Case 2:</strong></p>
<pre class="lang-none prettyprint-override"><code>Input data: [true, true, true, true, true, false, false]
Expected output: Mon-Fri
</code></pre>
<p><strong>Case 3:</strong></p>
<pre class="lang-none prettyprint-override"><code>Input data: [true, true, false, false, true, true, true]
Expected output: Mon-Tue, Fri-Sun
</code></pre>
<p><strong>Case 4:</strong></p>
<pre class="lang-none prettyprint-override"><code>Input data: [true, false, false, true, false, false, true]
Expected output: Mon, Thu, Sun
</code></pre>
<p><strong>Case 5:</strong></p>
<pre class="lang-none prettyprint-override"><code>Input data: [true, true, false, true, true, true, false]
Expected output: Mon-Tue, Thu-Sat
</code></pre>
<p><strong>Case 6:</strong></p>
<pre class="lang-none prettyprint-override"><code>Input data: [true, false, false, false, false, false, false]
Expected output: Only Monday
</code></pre>
<p>I came up with <a href="https://codesandbox.io/s/days-schedule-ydpboj?file=/src/index.js:668-679" rel="nofollow noreferrer">this</a>, but need help with cases 2-5</p>
<pre><code>const daysLabels = [
{ label: "Monday", short: "Mon" },
{ label: "Tuesday", short: "Tue" },
{ label: "Wednesday", short: "Wed" },
{ label: "Thursday", short: "Thu" },
{ label: "Friday", short: "Fri" },
{ label: "Saturday", short: "Sat" },
{ label: "Sunday", short: "Sun" }
];
const getSchedule = ({ case: days }) => {
let activeDays = [];
for (let i = 0; i < [...days].length; i++) {
const day = [...days][i];
if (day) {
activeDays.push({ ...daysLabels[i], value: day });
}
}
if (activeDays.length === 7) {
return "Every day";
}
if (activeDays.length === 1) {
return `Only ${activeDays[0].label}`;
}
return "#TODO";
};
</code></pre>
<p>Sandbox - <a href="https://codesandbox.io/s/days-schedule-ydpboj?file=/src/index.js:668-679" rel="nofollow noreferrer">link</a></p>
| [
{
"answer_id": 74123260,
"author": "dollar",
"author_id": 20166094,
"author_profile": "https://Stackoverflow.com/users/20166094",
"pm_score": 1,
"selected": false,
"text": "// for index mapping\nlet indexMapping = [\n \"Mon\",\n \"Tue\",\n \"Wed\",\n \"Thu\",\n \"Fri\",\n ... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12307511/"
] |
74,122,711 | <p>I often find that I'd like like to do an operation between the last few dimensions of two arrays, where the first dimensions don't necessarily match. As an example I'd like to do something like:</p>
<pre><code>a = np.random.randn(10, 10, 3, 3)
b = np.random.randn(5, 3)
c = np.einsum('...ij, ,,,j -> ...,,,i', a, b)
</code></pre>
<p>and the result should satisfy <code>c.shape = (10, 10, 5, 3)</code> and <code>c[i, j, k] = a[i, j] @ b[k]</code>. Is there a way to achieve this with the existing interface?</p>
| [
{
"answer_id": 74128452,
"author": "hpaulj",
"author_id": 901925,
"author_profile": "https://Stackoverflow.com/users/901925",
"pm_score": 1,
"selected": false,
"text": "In [82]: c = np.einsum('...ij,...j->...i', a, b)\n---------------------------------------------------------------------... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5043576/"
] |
74,122,747 | <p>I tried counting how many prime there are (except 1 and 0) until there are N number of primes. But somehow my program always ends up looping <strong>INFINITELY</strong></p>
<pre><code>int main (){
int n;
printf("Enter size N: ");
scanf("%d", &n);
int i, j, ctr = 0, flag = 0;
for (i = 2; ctr != n; i++){
for (j = 2; j < i; j++){
if (i%j==0){
flag = 1;
break;
}
}
if(flag!=1){
ctr++;
}
}
}
</code></pre>
| [
{
"answer_id": 74122798,
"author": "Portevent",
"author_id": 8899106,
"author_profile": "https://Stackoverflow.com/users/8899106",
"pm_score": 3,
"selected": true,
"text": "not prime"
},
{
"answer_id": 74123654,
"author": "carce-bo",
"author_id": 18101070,
"author_pro... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17480767/"
] |
74,122,766 | <p>I'm new with linux</p>
<p>I'm trying to get logs between two dates with gawk.</p>
<p>this is my log</p>
<pre><code>Oct 07 11:00:33 abcd
Oct 08 12:00:33 abcd
Oct 09 14:00:33 abcd
Oct 10 21:00:33 abcd
</code></pre>
<p>I can do it when both <code>start</code> and <code>end</code> date are sent</p>
<p>but I have problem when <code>start</code> or <code>end</code> date or <code>both</code> are not sent</p>
<p>and I don't know how to check it .</p>
<p>I've written below code but it has syntax error .</p>
<pre><code>sudo gawk -v year='2022' -v start='' -v end='2022:10:08 21:00:34' '
BEGIN{ gsub(/[:-]/," ", start); gsub(/[:-]/," ", end) }
{ dt=year" "$1" "$2" "$3; gsub(/[:-]/," ", dt) }
if(start && end){mktime(dt)>=mktime(start) && mktime(dt)<=mktime(end)}
else if(end){mktime(dt)<=mktime(end)}
else if(start){mktime(dt)>=mktime(start)} ' log.txt
</code></pre>
<p>How can I modify this code ?</p>
| [
{
"answer_id": 74122798,
"author": "Portevent",
"author_id": 8899106,
"author_profile": "https://Stackoverflow.com/users/8899106",
"pm_score": 3,
"selected": true,
"text": "not prime"
},
{
"answer_id": 74123654,
"author": "carce-bo",
"author_id": 18101070,
"author_pro... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14952975/"
] |
74,122,769 | <p>I am trying to add a ArcGISMapServer connection to my QGIS workspace in QGIS 3.20.2. The option for adding a this connection does not appear in the data source manager or in the add layers option. There is now only an option for adding an ArcGIS Rest Server:</p>
<p><a href="https://i.stack.imgur.com/WjLP3.png" rel="nofollow noreferrer">QGIS 3.20.2 View</a></p>
<p>In previous versions there was an in built option for adding these connections:</p>
<p><a href="https://i.stack.imgur.com/YoSwS.jpg" rel="nofollow noreferrer">Previous QGIS versions option</a></p>
<p>Is there a new method of adding in ArcGIS Map Server connections in more recent versions of QGIS?</p>
| [
{
"answer_id": 74122798,
"author": "Portevent",
"author_id": 8899106,
"author_profile": "https://Stackoverflow.com/users/8899106",
"pm_score": 3,
"selected": true,
"text": "not prime"
},
{
"answer_id": 74123654,
"author": "carce-bo",
"author_id": 18101070,
"author_pro... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20280774/"
] |
74,122,772 | <p>I've got a multidimensionnal array like</p>
<pre><code>var a = [['Dog','Cat'],[1,2]];
</code></pre>
<p>My goal is to get an array like</p>
<pre><code>var b = [['G','X','G','X'], ['Dog','Dog', 'Cat', 'Cat'],[1,1,2,2]];
</code></pre>
<p>For this i'm using a loop but i didn't get the result i need.</p>
<pre><code>for (i=0;i<a.length;i++){
for (j=0;j<a[i].length;j++){
b[0][j] = 'G';
b[1][j] = a[i][j];
b[0][j] = 'X';
b[1][j] = a[i][j];
}
}
</code></pre>
<p>I try to insert the value of a array to b array but i need to duplicate each value and insert a 'G' next a 'X'</p>
<p>It should be (not sure it is correct)</p>
<pre><code>b[] = ['G'],[a[0][0]],[a[1][0]]
b[] = ['X'],[a[0][0]],[a[1][0]]
b[] = ['G'],[a[0][1]],[a[1][1]]
b[] = ['X'],[a[0][1]],[a[1][1]]
</code></pre>
| [
{
"answer_id": 74123104,
"author": "RowBlaBla",
"author_id": 3481690,
"author_profile": "https://Stackoverflow.com/users/3481690",
"pm_score": 2,
"selected": true,
"text": "var a = [['Dog','Cat'],[1,2]];\nvar b = [[],[],[]];\n\nfor (i = 0; i < a[0].length; ++i){\n for (j = 0; j < 2; +... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1892212/"
] |
74,122,780 | <p>I'm trying to use a chrome extension (shortkeys) to create shortcut keys that can press buttons within our warehouse management system (so they can be matched to barcodes).</p>
<p>One of the buttons has no ID, and once it has been clicked the button innertext changes. Ideally I'd like the shortcut to work on either version of the button</p>
<p>It is either</p>
<pre><code><input type="submit" value="Create Shipment" class="btn btn-success pull-right">
</code></pre>
<p>or</p>
<pre><code><a class="btn btn-success" href="/Order/OrderDocumentP/15467" target="_blank">Print Label</a>
</code></pre>
<p>I then have another button to be assigned to a different shortcut key</p>
<pre><code><a class="btn btn-success" href="/Picking/DespatchOrder?OrderId=13413">Despatch</a>
</code></pre>
<p>But I'm sure once I've figured out the first one the next will be easier :)</p>
<p>Any help greatly appreciated, I've been through a number of other questions that are similar but not quite what I'm after and my JS knowledge is pretty rubbish</p>
| [
{
"answer_id": 74123104,
"author": "RowBlaBla",
"author_id": 3481690,
"author_profile": "https://Stackoverflow.com/users/3481690",
"pm_score": 2,
"selected": true,
"text": "var a = [['Dog','Cat'],[1,2]];\nvar b = [[],[],[]];\n\nfor (i = 0; i < a[0].length; ++i){\n for (j = 0; j < 2; +... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10657995/"
] |
74,122,822 | <p>I have 2d array with rgb pixel data (2 row with 3 pixel in a row).</p>
<pre><code>[[[255, 255, 255],[3, 0, 2],[255, 255, 255]],[[255, 255, 255],[3, 0, 2],[255, 255, 255]]]
</code></pre>
<p>How can I get unique pixel? I want to get</p>
<pre><code>[[255, 255, 255], [3, 0, 2]]
</code></pre>
<p>I am trying to use <code>np.unique</code> and <code>np.transpose</code> with <code>np.reshape</code> but I wasn't able to get the desired result.</p>
| [
{
"answer_id": 74122988,
"author": "Guy",
"author_id": 5168011,
"author_profile": "https://Stackoverflow.com/users/5168011",
"pm_score": 2,
"selected": true,
"text": "np.unique"
},
{
"answer_id": 74123085,
"author": "Lazyer",
"author_id": 8282898,
"author_profile": "h... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13246081/"
] |
74,122,830 | <p>The <a href="https://moonbreaker.fandom.com/wiki/Zax_Ja%27kar" rel="nofollow noreferrer">wiki pages</a> that I am trying to parse include the following html:</p>
<pre><code><div
class="pi-smart-data-value pi-data-value pi-font pi-item-spacing pi-border-color"
style="width: calc(1 / 1 * 100%)"
data-source="unique_ability"
>
<b>Captain</b><br /><b>"Back off!"</b><br />Push target on hit.
</div>
</code></pre>
<p>What I would like to parse the content of the div into is an array like this:
<code>["Captain", "Back off!", "Push target on hit."]</code></p>
<p>If I use the <a href="https://cheerio.js.org/interfaces/CheerioAPI.html#text" rel="nofollow noreferrer">text()</a> method from cheerio (<code>const uniqueAbilities = $('[data-source="unique_ability"]').text()</code>) I get a long string like this: <code>Captain"Back off!"Push target on hit.</code> If I use the <a href="https://cheerio.js.org/interfaces/CheerioAPI.html#html" rel="nofollow noreferrer">html()</a> method (<code>const uniqueAbilities = $('[data-source="unique_ability"]').html();</code>) from cheerio I get the HTML content of the node, but I am then unable to parse it as a string.</p>
<p>How would you parse this html into the desired output?</p>
<p>Thanks for the help.</p>
| [
{
"answer_id": 74122988,
"author": "Guy",
"author_id": 5168011,
"author_profile": "https://Stackoverflow.com/users/5168011",
"pm_score": 2,
"selected": true,
"text": "np.unique"
},
{
"answer_id": 74123085,
"author": "Lazyer",
"author_id": 8282898,
"author_profile": "h... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4341439/"
] |
74,122,856 | <p>If I create a UserControl, to create and edit an instance of a data class e.g. Person in C# WindowsForms (call it PersonControl), the framework automatically adds an instance of Person in PersonControl.Designer with some default values for the properties and fills the item controls with those values. This behavior has a number of side effects which I would like to avoid.</p>
<p>Question: is there a defined way to prevent creation of a data class instance in UserControl.Designer?</p>
| [
{
"answer_id": 74122988,
"author": "Guy",
"author_id": 5168011,
"author_profile": "https://Stackoverflow.com/users/5168011",
"pm_score": 2,
"selected": true,
"text": "np.unique"
},
{
"answer_id": 74123085,
"author": "Lazyer",
"author_id": 8282898,
"author_profile": "h... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15198069/"
] |
74,122,861 | <p>UPDATE Vaccine SET VaccineNo = 'Sinovac Dose 1' WHERE VaccineNo = 'SIND01';</p>
<p>The question for this code:
<a href="https://i.stack.imgur.com/QZX1L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QZX1L.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74122988,
"author": "Guy",
"author_id": 5168011,
"author_profile": "https://Stackoverflow.com/users/5168011",
"pm_score": 2,
"selected": true,
"text": "np.unique"
},
{
"answer_id": 74123085,
"author": "Lazyer",
"author_id": 8282898,
"author_profile": "h... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20280879/"
] |
74,122,879 | <p>I am trying to create a row security level over my table for the user department</p>
<pre><code>CREATE TABLE Student_Table
(
Title varchar(10) NULL,
DateofBirth DATE NULL,
BF1 varchar(10) NULL,
Language varchar(20) NULL,
Qualification varchar(20) NULL,
Programme varchar(20) NULL,
Curriculum varchar(20) NULL,
Level int NULL,
Department varchar(max) NULL
)
</code></pre>
<p><code>Department</code> column contains</p>
<pre><code>Level 1: General Staff
Level 2: IT Management
Level 3: Senior Managers
</code></pre>
<p>When I try create users</p>
<pre><code>CREATE USER Manager WITHOUT LOGIN;
CREATE USER Level 1: General staff WITHOUT LOGIN;
CREATE USER Level 2:IT Management WITHOUT LOGIN;
CREATE USER Level 3: Senior Managers WITHOUT LOGIN;
GO
</code></pre>
<p>I get the following errors:</p>
<blockquote>
<p>Msg 102, Level 15, State 1, Line 35<br />
Incorrect syntax near '1'</p>
<p>Msg 102, Level 15, State 1, Line 36<br />
Incorrect syntax near '2'</p>
<p>Msg 102, Level 15, State 1, Line 37<br />
Incorrect syntax near '3'</p>
</blockquote>
<p>Can someone please assist me.</p>
| [
{
"answer_id": 74122988,
"author": "Guy",
"author_id": 5168011,
"author_profile": "https://Stackoverflow.com/users/5168011",
"pm_score": 2,
"selected": true,
"text": "np.unique"
},
{
"answer_id": 74123085,
"author": "Lazyer",
"author_id": 8282898,
"author_profile": "h... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19552980/"
] |
74,122,882 | <p>I have a table with checkbox in every row and filtering mechanism.</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> function toggle(source) {
checkboxes = document.getElementsByName('cbox');
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = source.checked;
}
}
function FilterTable() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("txtFilter");
filter = input.value.toUpperCase();
table = document.getElementById("tblEmployees");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="txtFilter" onkeyup="FilterTable()" />
<table id="tblEmployees">
<thead>
<tr>
<th><input type="checkbox" onClick="toggle(this)"></th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="cbox"/></td>
<td>John 1</td>
</tr>
<tr>
<td><input type="checkbox" name="cbox"/></td>
<td>John 2</td>
</tr>
<tr>
<td><input type="checkbox" name="cbox"/></td>
<td>John 3</td>
</tr>
<tr>
<td><input type="checkbox" name="cbox"/></td>
<td>Mark 1</td>
</tr>
<tr>
<td><input type="checkbox" name="cbox"/></td>
<td>Mark 2</td>
</tr>
</tbody>
</table></code></pre>
</div>
</div>
</p>
<p>Currently, when I check the main checkboxes in the header, all checkbox in the table gets checked, even if the row is hidden when I filter the table.
What I need to do is to check only the checkboxes that are not hidden.</p>
<p>For example, I filter "John". 3 rows will remain visible and the 2 "Mark" records will be hidden. Then, I tick the checkbox in the header, only the 3 "John" records should be checked. So when I clear the filter, the 2 "Mark" records remain unchecked.</p>
| [
{
"answer_id": 74122997,
"author": "Lain",
"author_id": 4728913,
"author_profile": "https://Stackoverflow.com/users/4728913",
"pm_score": 3,
"selected": true,
"text": "style.display"
},
{
"answer_id": 74123015,
"author": "GreyRoofPigeon",
"author_id": 1930721,
"author... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7689261/"
] |
74,122,892 | <p>I am trying to capture subject from following string but excluding <code>\r\n</code> from the matched result using regex. The string:</p>
<pre><code>Sep 20 02:00:00 127.0.0.1 TestHost: Info: MID 123456 Subject "[Notification] - System 1234 [hostname] -\r\n SERVICE_STARTED (INFO)"
</code></pre>
<p>The Expected output should be(Excluding <code>\r\n</code>)</p>
<pre><code>[Notification] - System 1234 [hostname] - SERVICE_STARTED (INFO)
</code></pre>
<p>I tried with following regex in regex101</p>
<pre><code>Subject [\'\"]?(?<subject>((?:\\r\\n)?.*))[\'\"]?$
</code></pre>
<p>But it does not yield me the correct result.</p>
| [
{
"answer_id": 74124201,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 0,
"selected": false,
"text": "const str = 'Sep 20 02:00:00 127.0.0.1 TestHost: Info: MID 123456 Subject \"[Notification] - System 1234 [hostn... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20280851/"
] |
74,122,905 | <p>I have two javascript array, One is Object array and another is string array.</p>
<p>Sample Arrays</p>
<pre><code>const arr1 = [{"key": "Jon", "value" : "King"},
{"key": "Danny", "value" : "Queen"},
{"key": "Cersei", "value" : "False Queen"},
{"key": "Tyrion", "value" : "Hand"}]
const arr2 = ["Jon","Tyrion"]
</code></pre>
<p>I want to console log or print on html output like below. I dont want comma after <code>hand</code>.
Required Output</p>
<pre><code>King, Hand
</code></pre>
<p>Please suggest how can it be done using map or filter.
Oneliners are very much appreciated.</p>
| [
{
"answer_id": 74122992,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 2,
"selected": false,
"text": "const arr1 = [{\"key\": \"Jon\", \"value\" : \"King\"},\n {\"key\": \"Danny\", \"value\" : \"Queen\"}... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4075189/"
] |
74,122,913 | <p>I am very new in DBT and Jinja, and I want to optimise my Case When in SQL working with Jinja.</p>
<p>So, this is my situation:</p>
<pre><code>select *,
case when what_id='006' then what_id else null end as opportunity_id
,case when what_id='a1b' then what_id else null end as billing_acc_id
,case when what_id='a04' then what_id else null end as Internal_Ticket
,case when what_id='001' then what_id else null end as account_id
,case when what_id='500' then what_id else null end as case_id
,case when what_id='a1D' then what_id else null end as Onboarding_process_id
,case when what_id='a02' then what_id else null end as training_id
,case when what_id='00Q' then what_id else null end as lead_id
,case when what_id='003' then what_id else null end as contact_id
from dim_activities
</code></pre>
<p>And I would like to do something like the example we have in jinja/dbt documentation:</p>
<pre><code>{% set payment_methods = ["bank_transfer", "credit_card", "gift_card"] %}
select
order_id,
{% for payment_method in payment_methods %}
sum(case when payment_method = '{{payment_method}}' then amount end) as {{payment_method}}_amount,
{% endfor %}
sum(amount) as total_amount
from app_data.payments
group by 1
</code></pre>
<p>So instead of using many case when, to have this list of each whatid, I want to do like a mapping. But I still need to classify each whatid and the description (example, 006 means opportunity_id).</p>
<p>Any ideas/suggestion to achieve this?</p>
<p>Thanks a lot!!</p>
| [
{
"answer_id": 74123299,
"author": "Simeon",
"author_id": 3218652,
"author_profile": "https://Stackoverflow.com/users/3218652",
"pm_score": 3,
"selected": true,
"text": "74122913.csv"
},
{
"answer_id": 74157634,
"author": "tconbeer",
"author_id": 10813082,
"author_pro... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15494010/"
] |
74,122,943 | <p>There is <code>input</code> with <code>type='file'</code> attribute like this:</p>
<pre><code>function TestComp() {
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const [file] = e.target.files;
//...
};
return <input type='file' onChange={onChange}/>
}
</code></pre>
<p>Got error:</p>
<blockquote>
<p>type 'FileList | null' must have a 'Symbol.iterator' method that returns an iterator.ts(2488)</p>
</blockquote>
<p>The <code>e.target.files</code> TS type is:</p>
<pre><code>interface HTMLInputElement extends HTMLElement {
/**
* Returns a FileList object on a file type input object.
*/
files: FileList | null;
}
</code></pre>
<p>In what scenario, the <code>e.target.files</code> may be <code>null</code>?</p>
| [
{
"answer_id": 74123082,
"author": "Matthieu Riegler",
"author_id": 884123,
"author_profile": "https://Stackoverflow.com/users/884123",
"pm_score": 2,
"selected": true,
"text": "HTMLFileElement"
},
{
"answer_id": 74123248,
"author": "Anis",
"author_id": 6316804,
"auth... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6463558/"
] |
74,122,970 | <p>I have the following json file:</p>
<pre><code>{
"data": {
"start_date": "2022-10-01",
"end_date": "2022-10-04",
"cur": "EUR",
"prizes": {
"2022-10-01": {
"coffee": 0.1448939471560284,
"usd": 1
},
"2022-10-02": {
"coffee": 0.14487923291390148,
"usd":1
},
"2022-10-03": {
"coffee": 0.1454857922753868,
"usd": 1
}
}
}
}
</code></pre>
<p>I want to create a dataframe which looks like this, (so without the <code>usd</code> column):</p>
<pre><code> coffee
2022-10-01 0.144894
2022-10-02 0.144879
2022-10-03 0.145486
</code></pre>
<p><strong>This is what I tried:</strong></p>
<pre><code>path = r'C:\Users\Geo\Desktop\json_files\coffee.json'
df = pd.read_json(path)
df = pd.DataFrame(df['data']['prizes']['2022-10-01']['coffee']).T
print(df)
</code></pre>
<p><strong>This is what I received:</strong></p>
<pre><code> raise ValueError("DataFrame constructor not properly called!")
ValueError: DataFrame constructor not properly called!
</code></pre>
| [
{
"answer_id": 74123030,
"author": "Gonçalo Peres",
"author_id": 7109869,
"author_profile": "https://Stackoverflow.com/users/7109869",
"pm_score": 2,
"selected": false,
"text": "json"
},
{
"answer_id": 74123033,
"author": "mozway",
"author_id": 16343464,
"author_profi... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20176143/"
] |
74,122,974 | <p>There is a list named lists and a dictionary labeled categories.</p>
<pre><code>lists = ["Ferrari", "Rose", "Samsung", "Porsche"]
categories = {"car": {"Ferrari", "Porsche"}, "flower": {"Rose", "Chamomile"}, "phone": {"Apple", "Samsung"}}
</code></pre>
<p>I would like to get a dictionary return with the names given in the list as key and the classification of the names as value.</p>
<p>like this.</p>
<pre><code>{"Ferrari": "car", "Rose": "flower", "Samsung": "phone", "Porsche": "car"}
</code></pre>
<p>and this is my code, but it doesn't work.</p>
<pre><code>def classify(lists: list, categories: dict):
result = {}
for i in range(len(lists)):
if lists== categories.keys():
result[lists] = categories.keys()
return result
</code></pre>
| [
{
"answer_id": 74123064,
"author": "Always Sunny",
"author_id": 1138192,
"author_profile": "https://Stackoverflow.com/users/1138192",
"pm_score": 1,
"selected": false,
"text": "for"
},
{
"answer_id": 74123398,
"author": "blhsing",
"author_id": 6890912,
"author_profile... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20020118/"
] |
74,122,999 | <p>I have a data frame that looks like this:</p>
<pre><code>Samples GENE GEN1 GEN2 GEN3 GEN4 GEN5
Sample1 21.0 160 110 3.90 2.62 16.5
Sample2 21.0 160 110 3.90 2.88 17.0
Sample3 22.8 108 5 3.85 2.32 18.6
</code></pre>
<p>What I pretend is to perform a spearman correlation using the column <code>GENE</code> vs each other columns, ie GENEvsGEN1, GENEvsGEN2, etc.
And obtain a table with the rho and p-values of each column (the results are invented):</p>
<pre><code> rho p-value
GENEvsGEN1 0.01193936 0.34
GENEvsGEN2 0.0113436 0.034
</code></pre>
<p>I know I can obtain it individually using:</p>
<pre><code>res2 <-cor.test(data$GENE, data$GEN1, method = "spearman")
res2
</code></pre>
<p>But I have almost 5000 columns, so doing manually each one is not viable.</p>
<p>Any suggestions about how I can handle it?
Thanks!!</p>
| [
{
"answer_id": 74123241,
"author": "Quinten",
"author_id": 14282714,
"author_profile": "https://Stackoverflow.com/users/14282714",
"pm_score": 2,
"selected": false,
"text": "corr.test"
},
{
"answer_id": 74123293,
"author": "Yacine Hajji",
"author_id": 17049772,
"autho... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74122999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9152842/"
] |
74,123,081 | <p>I have a problem that I am confused. I have a piece of code that executes a Post API command like this:</p>
<pre><code>{
"chargeCriterias": null,
"containerType": "Dry",
"origin": {
"code": "ABC"
},
"destination": {
"code": "DYF"
},
"dateBegin": "2022-10-01T00:00:00",
"dateEnd": "2022-11-30T23:59:59",
"ratesFetcher": "XYZ",
}
</code></pre>
<p>I'm trying to write code to execute a command like this:</p>
<pre><code>public class DataModel
{
public LocationModelBase origin { get; set; }
public LocationModelBase destination { get; set; }
public string dateBegin { get; set; }
public string dateEnd { get; set; }
public string chargeCriterias { get; set; }
public string containerType { get; set; }
public string ratesFetcher { get; set; }
}
public class LocationModelBase
{
public Int32 locationId { get; set; }
public string code { get; set; }
}
var addGetdata = new DataModel();
{
addGetdata.origin.code = "ABC";
addGetdata.destination.code = "DYF";
addGetdata.dateBegin = "2022-10-01T00:00:00";
addGetdata.dateEnd = "2022-11-30T23:59:59";
addGetdata.chargeCriterias = null;
addGetdata.containerType = "Dry";
addGetdata.ratesFetcher = "SSSS";
}
</code></pre>
<p>However I get the error: <code>'Object reference not set to an instance of an object.'</code>.</p>
<p>I have checked the place value: addGetdata.origin and it says null. However I tried the ways but still didn't solve the problem. Where did I go wrong?</p>
<p><a href="https://i.stack.imgur.com/y9bY9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y9bY9.png" alt="enter image description here" /></a></p>
<p>Looking forward to anyone's help or suggestions. Thank you</p>
| [
{
"answer_id": 74123127,
"author": "freefaller",
"author_id": 930393,
"author_profile": "https://Stackoverflow.com/users/930393",
"pm_score": 2,
"selected": true,
"text": "LocationModelBase"
},
{
"answer_id": 74123194,
"author": "Chris B",
"author_id": 2854993,
"autho... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8782190/"
] |
74,123,086 | <p>I am new to mysql and phpmyadmin so excuse my question if it's basic.
I need a query to replace the 15$ to 10$ on all posts and pages post_title, post_excerpt and post_content using the insert method not update method.
also is there any way to undo the query if things went wrong ?</p>
| [
{
"answer_id": 74123127,
"author": "freefaller",
"author_id": 930393,
"author_profile": "https://Stackoverflow.com/users/930393",
"pm_score": 2,
"selected": true,
"text": "LocationModelBase"
},
{
"answer_id": 74123194,
"author": "Chris B",
"author_id": 2854993,
"autho... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12310298/"
] |
74,123,124 | <p>i have an array with couple of values like :</p>
<pre class="lang-js prettyprint-override"><code>let myvar = 17
let myarray = [
{ start: 1, end: 10 },
{ start: 15, end: 22 },
{ start: 44, end: 47 }
]
</code></pre>
<p>I am looking for how to check if a variable is between the start and end of one of the objects in the array.</p>
<p>if myvar = 17, myfunction return true, because 17 is between 15 and 22 (the second object { start 15, end: 22 }), but if myvar = 12, myfunction return false.</p>
| [
{
"answer_id": 74123156,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 4,
"selected": true,
"text": "let data =\n[\n { start: 1, end: 10 },\n { start: 15, end: 22 },\n { start: 44, end: 47 }\n]\n\nlet num = ... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7896062/"
] |
74,123,153 | <p>I've five Product objects with 3 product's availability set to True and rest False, I'm trying to set Checkout Status Button to Out of Stock even if one product has availablity set to False.</p>
<p>Because cart view cannot use slug, <code>{% if product.availability %}</code> is pointless, and can't use 'for loop' or it would create multiple checkout buttons, what's the way to fix this?</p>
<p>Model</p>
<pre><code>class Product(models.Model):
availablity = models.BooleanField()
</code></pre>
<p>View</p>
<pre><code>def cart(request):
products = Product.objects.all()
</code></pre>
<p>Cart template</p>
<pre><code>{% for product in products %}
<p>{product.name}</p>
<p>{product.price}</p>
{% endfor %}
<!--Checkout Status Button-->
{% if product.availability %}
<a href="#">Checkout</a>
{% else %}
<p>Out of stock</p>
{% endif %}
</code></pre>
| [
{
"answer_id": 74123387,
"author": "Hemal Patel",
"author_id": 16250404,
"author_profile": "https://Stackoverflow.com/users/16250404",
"pm_score": 0,
"selected": false,
"text": "def cart(request):\n products = Product.objects.all()\n availibility = True\n for prod in products:\n... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18982716/"
] |
74,123,158 | <p>From what I read and understood, Python logging module by default logs to stderr.</p>
<p>If I run this python code:</p>
<pre class="lang-py prettyprint-override"><code>import logging
logging.info('test')
logging.warning('test')
logging.error('test')
logging.debug('test')
</code></pre>
<p>as</p>
<pre class="lang-bash prettyprint-override"><code>python main.py 1> stdout.txt 2> stderr.txt
</code></pre>
<p>I get my logs in stderr.txt and nothing in stdout.txt - my logs are redirected to stderr.</p>
<p>This default behaviour is problematic when logs are streamed to logging aggregation services such as datadog or papertrail. Since its streamed to stderr, the logs are marked as errors when in reality they are not.</p>
<p>So I tried to create multiple log handlers as follows:</p>
<pre class="lang-py prettyprint-override"><code>import logging
import sys
stdoutHandler = logging.StreamHandler(stream=sys.stdout)
stderrHandler = logging.StreamHandler(stream=sys.stderr)
logging.basicConfig(level=logging.DEBUG, handlers=[stdoutHandler, stderrHandler])
stdoutHandler.setLevel(logging.DEBUG)
stderrHandler.setLevel(logging.ERROR)
logging.info('test')
logging.warning('test')
logging.error('test')
logging.debug('test')
</code></pre>
<p>When I run this code, I get errors in sterr.txt but also all the logs in stdout.txt - I ended up having log duplication error logs appear in both the stderr and stdout streams.</p>
<p>Is there a better way to handle the differentiation of error logs from the rest in Python?</p>
<p>I tried <a href="https://loguru.readthedocs.io/en/stable/overview.html" rel="nofollow noreferrer">loguru</a> package as well, also no luck in stream separation...
Thanks in advance</p>
| [
{
"answer_id": 74162493,
"author": "Pavel Durov",
"author_id": 5321395,
"author_profile": "https://Stackoverflow.com/users/5321395",
"pm_score": 0,
"selected": false,
"text": "import sys\nimport logging\n\n\n\nclass StdoutFilter(logging.Filter):\n def filter(self, record):\n re... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5321395/"
] |
74,123,160 | <pre><code><cfquery datasource = "myDb" name = "compare">
select *
from users
where cnic = #form.cnic#
</cfquery>
<cfif compare.cnic eq form.cnic>
<p> *CNIC already Exists </p>
</cfif>
</code></pre>
| [
{
"answer_id": 74196701,
"author": "Adrian J. Moreno",
"author_id": 11047,
"author_profile": "https://Stackoverflow.com/users/11047",
"pm_score": 0,
"selected": false,
"text": "users"
},
{
"answer_id": 74414682,
"author": "DSAnup",
"author_id": 12727024,
"author_profi... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20281043/"
] |
74,123,161 | <p>I don't know how to describe this question right, so please see the belows code</p>
<pre><code>interface TestParams<T> {
order?: keyof T
attr1?: number
attr2?: string
}
async function Test<T = any>(_obj: TestParams<T>): Promise<T> {
return {} as T
}
</code></pre>
<pre><code>Test({ order: 'id2' })
// function Test<{
// id2: any;
// }>(_obj: TestParams<{
// id2: any;
// }>): Promise<{
// id2: any;
// }>
</code></pre>
<p>Why the <code>T</code> type is <code>{ id2: any; }</code> instead of <code>any</code></p>
<p>The belows is my needs type</p>
<pre><code>function Test<any>(_obj: TestParams<any>): Promise<PostgrestResponse<any>>
</code></pre>
<p><a href="https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/JYOwLgpgTgZghgYwgAgCoQM5gApynAWwwB5UA+ZAbwFgAoZZAeygBNoB+ALmQGsIBPRjDR0GcMGCgBGLshABXAgCNoo5OMkAmWViigA5nQC+dOnAz8QCZDHlWwwRiDSYwpZAF51IfmQAUAPqMSgBW3OhYuPhEpGQAlNzYUIwEwBgQsVRqUBBg8lDOlEbqGCK0JrR0EWB+lEys0NwA5MAsmk3IRnF0APQ9NnYIDk4uWMQ0tH0M062a3HA+ANy9-Ub+QaHhrlGEJBNT08iz80srnfGJyanp42eHx978y5OrZKa01cQLvrX1bFDNWYdLpnWz2RzOT7fdbBMKjHB4XZfHwXZBJFJpDLQoA" rel="nofollow noreferrer">typescript playground</a></p>
<p><strong>Update</strong></p>
<p><a href="https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/JYOwLgpgTgZghgYwgAgCoQM5gApynAWwwB5UA+ZAbwFgAoZZAeygBNoB+ALjTobjDBQAjF2QgArgQBG0Xsn6CATKKxRQAczoBfOnTgYAniATIY442GCMQySFlJkAFAH1GUgFbd0WXPiKlkCAAPSBAWDGRzNhhQCBZkdmRVDWRuAGsIA0YYNDIASm5sKEYCYAwIByo5KAgwcSgbSi15CNRtXVo7MEdKJlZobgByYBZFQeQtPLoAemm0AAsUGQAbRgB3CLADAAcUMuQ1+f5kAEkxCDi4mbmzCysbLuI4EAMnVw8vTBw8QhIAIhGij++UKxVK5SeLzIHVAkFgiBQ3jAqB2KBo9GQgO4EmksgxIwAzNjJDIoO1Ol9SF8UbsnL1mGwoENAeNJkA" rel="nofollow noreferrer">new playground</a></p>
<p><strong>Update</strong></p>
<p>I added <code>U</code> which is <code>keyof T</code>, then implement my needs</p>
<pre><code>interface TestParams<T> {
order?: T
attr1?: number
attr2?: string
}
async function test<T = any, U = keyof T>(_obj: TestParams<T extends undefined ? string : U>): Promise<T> {
return {} as T
}
test({ order: 'id2' })
// The belows type is what I needed
// function test<any>(_obj: TestParams<"id2">): Promise<any>
interface TestType {
id2: number
id3: number
}
test<TestType>({ order: 'id2' })
</code></pre>
<p><a href="https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/JYOwLgpgTgZghgYwgAgCoQM5gApynAWwwB5UA+ZAbwFgAoZZAeygBNoB+ALjTobjDBQAjF2QgArgQBG0Xsn6CATKKxRQAczoBfOnTgYAniATIY442GCMQySFlLIAvPJAGANMgCqT5AGsIBowwaGQAFAD6jFIAVtzoWLj4RA4QAB6QICwYyOZsMKAQLMjsyKoayNyeZACU3NhQjATAGBCkFDT0yFAQYOJQNpRa8tmo2rq0dmChlEys0NwA5MAsigvIWtV0APRbaAAWKDIANowA7tlgBgAOKM3Ip3v8yACSYhCFhdu7ZhZWNpPEOCuMKRGJxTA4PCEEgAImWihhNTqDSaLUBwPGoEgsEQKHiYFQ1xQHQY8O4Emksk6ywAzOTJDIoGMJhDSBDCTcwjNmGwoIt4WsNkA" rel="nofollow noreferrer">playground</a></p>
| [
{
"answer_id": 74123465,
"author": "ij7",
"author_id": 20275210,
"author_profile": "https://Stackoverflow.com/users/20275210",
"pm_score": 0,
"selected": false,
"text": "{ order: 'id2' }"
},
{
"answer_id": 74126627,
"author": "caTS",
"author_id": 18244921,
"author_pro... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8427762/"
] |
74,123,221 | <p>I have one div element and inside it has one button A. and there is button B outside which is hidden by default
so when I click button A, the whole div should hide including button A, and also it should display the hidden button B.
And when I click button B, it should open the div and hide.
How can I achieve this in reactjs.
This is what I have tried, but it is not showing any button on the screen</p>
<pre><code>import React from 'react'
import useState from 'react-dom'
const App = () => {
const [show,setShow]=useState(true)
return(
<>
{show && <div>
Hello
<button>button A</button>
</div>}
<button onClick={()=>setShow(!show)}>button 2</button>
</>
)
</code></pre>
| [
{
"answer_id": 74123620,
"author": "Helphin",
"author_id": 3314078,
"author_profile": "https://Stackoverflow.com/users/3314078",
"pm_score": 0,
"selected": false,
"text": "import React, { useState } from \"react\";\n\nexport default function ToogelButton({ children }) {\n\n // React sta... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10578470/"
] |
74,123,234 | <p>I'm studying Python and I want to apply it while I'm studying bubble sorting. But I can't think of anything.</p>
<p>Given array <strong>arr</strong> and array size <strong>n</strong>, I want to implement it so that the only minimum value comes to arr[0] using bubble.</p>
<p>ex) arr = [4, 2, 3, 1, 5], n = 5,</p>
<p>[4, 2, 3, 1, 5] -> [4, 2, 1, 3, 5] -> [4, 1, 2, 3, 5] -> [1, 4, 2, 3, 5] -> <strong>[1, 4, 2, 3, 5]</strong></p>
<p>return : [1, 4, 2, 3 ,5]</p>
<p>it doesn't working... :(</p>
<pre><code>def bubbling(arr, n):
tmp = min(arr)
index = arr.index(tmp)
for i in range(index):
for j in range(n):
if arr[index] > arr[index - 1]:
arr[index], arr[index-1] = arr[index-1], arr[index]
return arr
bubbling([45, 67, 82, 34, 21, 55], 6))
</code></pre>
| [
{
"answer_id": 74123620,
"author": "Helphin",
"author_id": 3314078,
"author_profile": "https://Stackoverflow.com/users/3314078",
"pm_score": 0,
"selected": false,
"text": "import React, { useState } from \"react\";\n\nexport default function ToogelButton({ children }) {\n\n // React sta... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20281037/"
] |
74,123,245 | <p>Is there a way in <code>javascript</code> (or typescript) to avoid re-writing the same object twice inside an <code>if</code> statement condition?</p>
<p>Something like this:</p>
<pre class="lang-js prettyprint-override"><code>if (A != null || A != B) {
// do something here
}
// something in the form of this:
if (A != null || != B) { // avoid re-writing "A" here
// do something here
}
</code></pre>
<p>Anyone has any suggesgtion or even other questions related to this one?</p>
| [
{
"answer_id": 74123295,
"author": "Mark Reed",
"author_id": 797049,
"author_profile": "https://Stackoverflow.com/users/797049",
"pm_score": 0,
"selected": false,
"text": "if"
},
{
"answer_id": 74123300,
"author": "Matthieu Riegler",
"author_id": 884123,
"author_profi... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19974585/"
] |
74,123,249 | <p>Like in <a href="https://stackoverflow.com/questions/69642889/how-to-use-multiple-cases-in-match-switch-in-other-languages-cases-in-python-3/">this</a> question, I am trying to match an element in a list, and handle the cases accordingly. See the example below.</p>
<pre class="lang-py prettyprint-override"><code>direct_payments = ["creditcard", "debitcard"]
on_credits = ["gift card", "rewards program"]
def print_payment_type(payment_type):
match payment_type:
case in direct_payments:
print("You paid directly!")
case in on_credits:
print("You paid on credits!")
print_payment_type("gift card")
</code></pre>
<p>I want this to print <code>"You paid on credits"</code>. I am convinced that using structural pattern matching is the most readable option in my case. Is there any way to achieve this behaviour? I cannot use <code>"gift card" | "rewards program"</code>, because I need to use the lists elsewhere.</p>
| [
{
"answer_id": 74123513,
"author": "kgkmeekg",
"author_id": 4168707,
"author_profile": "https://Stackoverflow.com/users/4168707",
"pm_score": 2,
"selected": false,
"text": "case"
},
{
"answer_id": 74123976,
"author": "Anton Yang-Wälder",
"author_id": 17723465,
"author... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7770654/"
] |
74,123,251 | <p>Trying to access the alias value on the this () Context, I followed the docs from <a href="https://docs.cypress.io/api/commands/as#Fixture" rel="nofollow noreferrer">https://docs.cypress.io/api/commands/as#Fixture</a></p>
<p>In the .then callback the dataExample parameter is filled OK, but on this.example it is undefined.</p>
<pre class="lang-js prettyprint-override"><code>describe('cy.as and this', function () {
it('Testing cy.as and this', function () {
cy.fixture('example.json').as('example')
.then(function (dataExample) {
cy.log('ACCESSING this, dataExample', this, dataExample);
});
cy.log(`ACCESSING this.example : ${JSON.stringify(this['example'])}`, this);
});
});
</code></pre>
<p>The first log outputs the following: with the dataExample correctly filled, but the contex.example undefined
<a href="https://i.stack.imgur.com/yPxE5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yPxE5.png" alt="logging this and dataExample in the .then" /></a></p>
<p>The second log outside of .then, with this.example also undefined
<a href="https://i.stack.imgur.com/0tGEW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0tGEW.png" alt="this " /></a></p>
<p>If I move the cy.fixture line into a beforeEach() it does work. Cold somebody explain this behavior?</p>
<pre class="lang-js prettyprint-override"><code>describe('alias', () => {
beforeEach(() => {
cy.fixture('example.json').as('example');
});
it('can access all aliases as properties', function () {
expect(this['example']).not.to.eq(undefined); // true
cy.log('THIS', this); // curious => [0]: Context {_runnable: undefined, test: undefined, example: undefined}
cy.log('THIS.example', this['example']); // {name: 'Using fixtures to represent data', email: 'hello@cypress.io',
// body: 'Fixtures are a great way to mock data for responses to routes'}
});
});
</code></pre>
| [
{
"answer_id": 74123513,
"author": "kgkmeekg",
"author_id": 4168707,
"author_profile": "https://Stackoverflow.com/users/4168707",
"pm_score": 2,
"selected": false,
"text": "case"
},
{
"answer_id": 74123976,
"author": "Anton Yang-Wälder",
"author_id": 17723465,
"author... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1119327/"
] |
74,123,254 | <p>I am doing this in python's wonderful plotnine package, but hoping ggplotters may have a solution as well.</p>
<p>Consider the following data and plot:</p>
<pre><code>df = pd.DataFrame({
'label' : ['A','B','C','D'],
'start' : [1, 1.5, 2.5, 1.75],
'end' : [3.85, 2.75, 4.25, 3],
})
p = (ggplot(df, aes(x='label', xend='label', y='start', yend='end'))
+ theme_light()
+ geom_segment()
+ coord_flip()
+ labs(x=None,y=None)
)
p
</code></pre>
<p><a href="https://i.stack.imgur.com/KxGXf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KxGXf.png" alt="enter image description here" /></a></p>
<p>I would like the segments to end with a whisker or a 'T'. Kind of like:</p>
<p><a href="https://i.stack.imgur.com/QTJv8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QTJv8.png" alt="enter image description here" /></a></p>
<p>Can this be done? I have only seen information for arrows (which don't have a 'T' option as far as I can tell).</p>
| [
{
"answer_id": 74123513,
"author": "kgkmeekg",
"author_id": 4168707,
"author_profile": "https://Stackoverflow.com/users/4168707",
"pm_score": 2,
"selected": false,
"text": "case"
},
{
"answer_id": 74123976,
"author": "Anton Yang-Wälder",
"author_id": 17723465,
"author... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7149485/"
] |
74,123,268 | <p>We are implementing a microfrontend, microservices architecture.</p>
<p>App1 is the microfrontend app - ui built on React, backend built on spring boot. It handles the authentication and provides the token to it's child app. The token is generated using Jwts as follows:</p>
<pre><code>Jwts.build().setClaims(claims).setSubject(username).setExpiration(expirationDate)...
</code></pre>
<p>App2 is a child app of the microfrontend setup. It's ui is built on React, backend built on spring boot. App1 attaches App2 via react-iframe while passing the token as follows:</p>
<pre><code><Iframe url={`${urlOfApp2}`?token={jwtToken}} ... />
</code></pre>
<p>App2 on <code>useEffect</code> checks if <code>window.location.search</code> has the <code>token</code> field and use this to set the Authenticcation in its security context. This is done by calling endpoint <code>/user</code> in App2. The App2 backend will then call an endpoint <code>/validate</code> from App1 to check if the token is valid. If it is valid, App2 parses the token and creates an <code>Authentication</code> object and saves it to its context as follows:</p>
<pre><code>final Authentication authentication = new UsernamePasswordAuthenticationToken(username, null, authorities);
SecurityContextHolder.getContext().setAuthentication(authentication);
</code></pre>
<p>This will create the JSESSIONID. So everytime an endpoint from App2 is requested, for example <code>/someendpoint</code>, it will check if the request has the required authority as set in the code above. The security config is as follows:</p>
<pre><code>http...
.antMatchers("/user").permitAll()
.anyRequest().hasAuthority("SOME_AUTHORITY_PARSED_FROM_THE_TOKEN")...
</code></pre>
<p>This works as the <code>/user</code> is called once to check if token is valid and a session on App2 is initialized. So for succeeding requests, it will check if it has the proper authority.</p>
<p>The problem is, the session on App2 has different expiration compared to that set on the token. How can we sync the expiration on the session on App2 with the token provided by App1?</p>
| [
{
"answer_id": 74123513,
"author": "kgkmeekg",
"author_id": 4168707,
"author_profile": "https://Stackoverflow.com/users/4168707",
"pm_score": 2,
"selected": false,
"text": "case"
},
{
"answer_id": 74123976,
"author": "Anton Yang-Wälder",
"author_id": 17723465,
"author... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2657121/"
] |
74,123,276 | <p>Hello looking solution to sort sizes inside my column.
Exmaple :</p>
<pre><code>-- CREATE TEMP TABLE
Create Table #MyTempTable (
size varchar(20)
);
-- insert sample data to TEMP TABLE
insert into #MyTempTable
values
('10.5W'),
('10W'),
('11.5W'),
('11W'),
('12W'),
('5.5W'),
('5W'),
('6.5W'),
('6W'),
('7.5W'),
('7W'),
('8.5W'),
('8W'),
('9.5W'),
('9W'),
('4')
select 'BEFORE',* from #MyTempTable
SELECT 'AFTER',size
FROM #MyTempTable
ORDER BY LEN(size)
</code></pre>
<p>When i order by LEN there is no good sorting like this :</p>
<pre><code>AFTER 5W
AFTER 6W
AFTER 7W
AFTER 8W
AFTER 9W
AFTER 10W
AFTER 11W
AFTER 12W
AFTER 5.5W
AFTER 7.5W
AFTER 6.5W
AFTER 9.5W
AFTER 8.5W
AFTER 10.5W
AFTER 11.5W
</code></pre>
<p>All im' looking for is to sort in proper order. like this :</p>
<pre><code>5W
5.5W
6W
6.5W
7W
7.5W
8W
8.5W
9W
9.5W
10W
10.5W
11W
11.5W
12W
</code></pre>
<p>I seearched a lot of stackoverflow and can't find solution for that because there is not only int and also decimal numbers. So don't know how to get it</p>
| [
{
"answer_id": 74123342,
"author": "Meyssam Toluie",
"author_id": 6203211,
"author_profile": "https://Stackoverflow.com/users/6203211",
"pm_score": 0,
"selected": false,
"text": "order by"
},
{
"answer_id": 74123353,
"author": "Tim Biegeleisen",
"author_id": 1863229,
... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7758442/"
] |
74,123,283 | <p>I was trying to make the border-radius: 20px; but I don't know why the background color overflowed out of the border. Please help me how to solve this one.</p>
<p>Here is the sample codes. Thank you.</p>
<pre><code>.bar{
padding: 20px;
}
.barContainer{
width: 50%;
background-color: #cccccc;
border: 1px solid #111;
border-radius: 20px
}
.per {
text-align: right;
padding: 10px 0;
color: #111;
}
.html {width: 90%; background-color: #f44336;}
.css {width: 80%; background-color: #2196F3;}
.js {width: 65%; background-color: #FEF70F;}
.java {width: 60%; background-color: #808080;}
.php {width: 60%; background-color: #008631;}
</code></pre>
<pre class="lang-html prettyprint-override"><code> <div class="bar">
<div class="topic">HTML</div>
<div class="barContainer">
<div class="per html">90%</div>
</div>
<div class="topic">CSS</div>
<div class="barContainer">
<div class="per css">80%</div>
</div>
<div class="topic">JavaScript</div>
<div class="barContainer">
<div class="per js">50%</div>
</div>
<div class="topic">Java</div>
<div class="barContainer">
<div class="per java">50%</div>
</div>
<div class="topic">PHP and MySQL</div>
<div class="barContainer">
<div class="per php">50%</div>
</div>
</div>
</code></pre>
<p><a href="https://i.stack.imgur.com/tWOcX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tWOcX.png" alt="here is the image" /></a></p>
| [
{
"answer_id": 74123323,
"author": "Tom",
"author_id": 16688813,
"author_profile": "https://Stackoverflow.com/users/16688813",
"pm_score": 1,
"selected": false,
"text": "overflow: hidden"
},
{
"answer_id": 74123331,
"author": "eJeeban Web Design Company",
"author_id": 202... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20271429/"
] |
74,123,291 | <p>I need to get last 6 weeks data from some table, right now the logic that I use is this</p>
<pre><code>WEEK([date column]) BETWEEN WEEK(NOW()) - 6 AND WEEK(NOW())
</code></pre>
<p>It run as I want, but January is near and I realize that this query will not working as it is. I try to run my query on 15th January 2022, I only get data from 1st January to 15th January when I use my logic.</p>
<pre class="lang-none prettyprint-override"><code>TGL MINGGU_KE
2022-01-01 | 1
2022-01-02 | 2
2022-01-03 | 2
2022-01-04 | 2
2022-01-05 | 2
2022-01-06 | 2
2022-01-07 | 2
2022-01-08 | 2
2022-01-09 | 3
2022-01-10 | 3
2022-01-11 | 3
2022-01-12 | 3
2022-01-13 | 3
2022-01-14 | 3
2022-01-15 | 3
</code></pre>
<p>Can I get the last 6 weeks data including last year?</p>
<p>This is my dbfiddle: <a href="https://dbfiddle.uk/o9BeAFJF" rel="nofollow noreferrer">https://dbfiddle.uk/o9BeAFJF</a></p>
| [
{
"answer_id": 74123592,
"author": "Adeel Ahmed",
"author_id": 13811145,
"author_profile": "https://Stackoverflow.com/users/13811145",
"pm_score": 0,
"selected": false,
"text": "Select * from [TableName] where [DateColumn] between\nDATEADD(WEEK,-6,GETDATE()) and GETDATE();\n"
},
{
... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10182450/"
] |
74,123,320 | <p><a href="https://i.stack.imgur.com/1iOKA.png" rel="nofollow noreferrer">enter image description here</a>ı want to set custom event with gtm but ı dont know how to get multple producs name . ı can get one of the items name but ı can not get all of them.</p>
<pre><code>document.getElementsByClassName('cartAndCheckout__items')[0].innerText.split('\nStokta var\n3.329,00 TL')[0]
</code></pre>
<p><a href="https://i.stack.imgur.com/FHZQj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FHZQj.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/av370.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/av370.png" alt="enter image description here" /></a></p>
<p>thats the code ı wrote</p>
| [
{
"answer_id": 74123380,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 2,
"selected": false,
"text": "document.getElementsByClassName"
},
{
"answer_id": 74123583,
"author": "Mark Reed",
"author_id": 7... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20281167/"
] |
74,123,322 | <p>I want to have a "connectionList" where every element a diffrent connection type (TCP,R232) is stored. I made an abstract interface to "Connect" and "Disconnect" but because "Config" needs diffrent parameters in each class, its not possible to implement it into the interface (or is it?).</p>
<p>I made a little visualitation:
<a href="https://i.stack.imgur.com/3V9bh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3V9bh.png" alt="Problem visualitation" /></a></p>
<p>One of my solutions would be to cast before the call like ((TCP)connectionList[0]).Config() but that means that i have to try every possible class type (TCP, RS232, ...) if i want for example to config the "Connection 3".</p>
<p>Im sure there are better solutions then this one.</p>
<p>Code example:</p>
<pre><code>List<IConnection> connectionList = new List<IConnection>();
connectionList.Add(new TCP());
connectionList.Add(new RS232());
connectionList[0].Connect();
connectionList[1].Connect(); // Works
connectionList[0].Config(); //Does not work because not in Interface
public abstract class IConnection
{
public abstract void Connect();
}
public class RS232 : IConnection
{
private int _baudRate;
public void Config(int baudRate) //Diffrent parameters then in TCP
{
_baudRate = baudRate;
}
public override void Connect()
{
Console.WriteLine("RS232 connect()");
}
}
public class TCP : IConnection
{
private int _ipAdress;
public void Config(int ipAdress) //Diffrent parameters then in RS232
{
_ipAdress = ipAdress;
}
public override void Connect()
{
Console.WriteLine("TCP Connect()");
}
}
</code></pre>
| [
{
"answer_id": 74123614,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 1,
"selected": false,
"text": "public interface ICanConnect\n{\n public void Connect();\n public void Disconnect();\n}\n\npublic interfac... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14937119/"
] |
74,123,327 | <p>I wanted to add <code>onClick</code> attribute to the image dynamically. But the click event didn't work.</p>
<p>//Code</p>
<pre><code>const parser = new DOMParser();
const doc = parser.parseFromString(htmlContent,
"text/html"
);
const imageData = doc.querySelectorAll("img");
imageData.forEach((x: any) => {
htmlContent = htmlContent.replace(
x.outerHTML,
'<img width="240" height="160" style="cursor: grab; margin: 10px;" src="' +
x.getAttribute("src") + '"onClick={() => setOpen(true)}/>'
);
});
</code></pre>
<p>Tried,</p>
<pre><code>onClick={handleClick(true)}
const handleClick = (flag: boolean) => {
setOpen(flag)
}
onClick={setOpen(true)}
onClick={() => ' +setOpen(true) + '}
x.addEventListener('onClick', () => setOpen(true));
</code></pre>
<p><strong>htmlContent:</strong></p>
<pre><code><p>new test <img src="https://i.imgur.com/7KpCS0Y.jpg%22" width="100" height="100" id="img_1665468977463_0"></p><p>new new test <img src="https://i.imgur.com/7KpCS0Y.jpg%22" width="100" height="100" id="img_1665468986873_0"></p><p>next level test <img src="https://i.imgur.com/7KpCS0Y.jpg%22" width="100" height="100" id="img_1665468996237_0"></p><p></p><p>format test</p><ol><li><p>one</p></li><li><p>two </p></li><li><p>three</p></li></ol>
</code></pre>
<p>Can i get any help?</p>
| [
{
"answer_id": 74123614,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 1,
"selected": false,
"text": "public interface ICanConnect\n{\n public void Connect();\n public void Disconnect();\n}\n\npublic interfac... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1083030/"
] |
74,123,344 | <p>I would like to create custom Python type hint that would effectively be</p>
<p><code>MyType = Dict[str, <some_type>]</code></p>
<p>Then I would like to be able to spesify <code>MyType</code> like <code>MyType[<some_type>]</code>, for example
<code>MyType[List[str]]</code> which would mean <code>Dict[str, List[str]]</code>.</p>
<p>I haven't been able to figure out how to do this.</p>
<p>I've tried <code>MyType = Dict[str, Any]</code> but I don't know how to make <code>Any</code> be a variable. Any suggestions?</p>
| [
{
"answer_id": 74123423,
"author": "Nikolay Zakirov",
"author_id": 9023490,
"author_profile": "https://Stackoverflow.com/users/9023490",
"pm_score": 3,
"selected": true,
"text": "from typing import TypeVar, Dict, List\nX = TypeVar('X')\nMyType = Dict[str, X]\n\ndef test_f(d: MyType[List[... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18171271/"
] |
74,123,345 | <p>I have a problem with async/await in C#, i need it to get some object called Trades, after i get it, it needs to SAVE it. Problem is, with async/await, it is doing the SAVE first, and then go and get my trade objects. How do i ensure i get the objects first, and then does the saving.... here is my code...</p>
<pre><code> private async void OnRefresh()
{
try
{
var trades = await ExchangeServiceInstance.GetTrades("");
mmTrades = new ObservableCollection<EEtrade>(trades);
tradeListView.ItemsSource = mmTrades;
}
catch { }
}
public async void OnSignalReceived()
{
// THIS NEEDS TO FINISH FIRST, BUT IT DOESN'T
await tradeListView.Dispatcher.InvokeAsync((Action)async delegate
{
if (ExchangeServiceInstance.SelectedTabIndex == CURRENT_TAB_INDEX_ITEM)
{
await Task.Delay(MMConfig.DELAYMILLISEC);
OnRefresh();
}
});
// SOMEHOW THIS GETS CALLED FIRST BEFORE THE ABOVE GETS TO FINISH!
await OnSaveTrades();
}
public async Task<int> OnSaveTrades()
{
foreach (var trade in mmTrades)
{
await ExchangeServiceInstance.OnInsertDoneTrade(trade);
}
return mmTrades.Count;
}
</code></pre>
<p>Any ideas guys? Thanks!</p>
| [
{
"answer_id": 74123493,
"author": "TheTanic",
"author_id": 3888657,
"author_profile": "https://Stackoverflow.com/users/3888657",
"pm_score": 3,
"selected": true,
"text": "OnRefresh"
},
{
"answer_id": 74123538,
"author": "Oliver Weichhold",
"author_id": 88513,
"author... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18987834/"
] |
74,123,389 | <p>I'm using the js-yaml package. It has a function named dump() that will write out a JavaScript data structure in YAML format. I want to specify the order of the keys when it dumps out an object. Here is what their docs say:</p>
<p>sortKeys (default: false) - if true, sort keys when dumping YAML. If a function, use the function to sort the keys.</p>
<p>But there's absolutely no mention of how to use a function to sort the keys. What parameters does it accept? What return values does it expect? It's exactly what I need, but there's no documentation on how to use a function with the sortKeys option.</p>
<p>FYI, I don't want to sort the keys alphabetically. I don't want them to appear in a random order. I don't want them to appear in the order the keys were added. I want total control over which order they appear.</p>
| [
{
"answer_id": 74123493,
"author": "TheTanic",
"author_id": 3888657,
"author_profile": "https://Stackoverflow.com/users/3888657",
"pm_score": 3,
"selected": true,
"text": "OnRefresh"
},
{
"answer_id": 74123538,
"author": "Oliver Weichhold",
"author_id": 88513,
"author... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1738579/"
] |
74,123,411 | <p>I have a dynamically generated iFrame on my page that loads a website using a variable object.</p>
<p>All that is well understood. My challenge now is that in some cases, say if I am viewing on mobile, the frame width exceeds my mobile device width.</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>// STATIC VALUE
let screenSize = {
"height": window.innerHeight,
"width" window.innerWidth:
}
// DYNAMICALLY GENERATED VARIABLE
let frameValue = {
"url": "https://example.com",
"height": 913,
"width": 1600
}
//Using this variable, the iframe property is set as follows using javascript
$('#dynamicFrame').attr('src', frameValue.url);
$('#dynamicFrame').width(frameValue.width);
$('#dynamicFrame').height(frameValue.height);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- HTML DYNAMIC iFRAME -->
<iframe src="" id="dynamicFrame" frameBorder="0" width="100%" height="100%" scrolling="auto"> </iframe></code></pre>
</div>
</div>
</p>
<p>Need:
I would like an algorithm (or perhaps some code) to perhaps scale or zoom the iframe whilst keeping its aspect ratio.</p>
<p>Meaning I want the content to of frameValue.url (example.com) to load in the iframe as it would while considering frameValue.width & frameValue.height.</p>
<p>Notes:
I don't mind having the iframe look smaller or have dark bands around the edge just like when you watch videos on a mobile device or use zoom or Microsoft teams on a mobile device whilst the person sharing the screen is on a desktop device.</p>
<p>Please feel free to comment if you need further explanation. Thank you.</p>
| [
{
"answer_id": 74123566,
"author": "FrankieD",
"author_id": 3614114,
"author_profile": "https://Stackoverflow.com/users/3614114",
"pm_score": 1,
"selected": false,
"text": "#dynamicFrame {\n /* Swap for your desired aspect ratio */\n aspect-ratio 16/9;\n width: 100%;\n height: auto;\... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5146958/"
] |
74,123,437 | <p>Consider following working code of copy a souce sqlite database to target sqlite database:</p>
<pre class="lang-py prettyprint-override"><code># Create two database.
import sqlite3
import pandas as pd
import time
cn_src = sqlite3.connect('source.db')
df=pd.DataFrame({"x":[1,2],"y":[2.0,3.0]})
df.to_sql("A", cn_src, if_exists="replace", index=False)
cn_tgt = sqlite3.connect('target.db')
cn_src.close()
cn_tgt.close()
from sqlalchemy import create_engine, MetaData, event
from sqlalchemy.sql import sqltypes
# create sqlalchemy conneciton
src_engine = create_engine("sqlite:///source.db")
src_metadata = MetaData(bind=src_engine)
exclude_tables = ('sqlite_master', 'sqlite_sequence', 'sqlite_temp_master')
tgt_engine = create_engine("sqlite:///target.db")
tgt_metadata = MetaData(bind=tgt_engine)
@event.listens_for(src_metadata, "column_reflect")
def genericize_datatypes(inspector, tablename, column_dict):
column_dict["type"] = column_dict["type"].as_generic(allow_nulltype=True)
tgt_conn = tgt_engine.connect()
tgt_metadata.reflect()
# delete tables in target database.
for table in reversed(tgt_metadata.sorted_tables):
if table.name not in exclude_tables:
print('dropping table =', table.name)
table.drop()
tgt_metadata.clear()
tgt_metadata.reflect()
src_metadata.reflect()
# copy table
for table in src_metadata.sorted_tables:
if table.name not in exclude_tables:
table.create(bind=tgt_engine)
# Update meta information
tgt_metadata.clear()
tgt_metadata.reflect()
# Copy data
for table in tgt_metadata.sorted_tables:
src_table = src_metadata.tables[table.name]
stmt = table.insert()
for index, row in enumerate(src_table.select().execute()):
print("table =", table.name, "Inserting row", index)
start=time.time()
stmt.execute(row._asdict())
end=time.time()
print(end-start)
</code></pre>
<p>The code was mainly borrowed from other source. The problem is the time <code>end-start</code> is about 0.017 in my computer which is too large. Is there any way to speed up? I have tried set <code>isolation_level=None</code> in <code>create_engine</code> but no luck.</p>
<p>It seems like that <code>Insert</code> object has no <code>executemany</code> method so we can't use bulk inserting.</p>
| [
{
"answer_id": 74129953,
"author": "Gord Thompson",
"author_id": 2144390,
"author_profile": "https://Stackoverflow.com/users/2144390",
"pm_score": 1,
"selected": false,
"text": "execute()"
},
{
"answer_id": 74133902,
"author": "kilasuelika",
"author_id": 4251282,
"aut... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4251282/"
] |
74,123,453 | <p>Let suppose two classes:</p>
<pre><code>Parent = class
public
procedure virtFunc(); virtual;
procedure other();
end;
Child = class(Parent)
public
procedure virtFunc(); override;
end;
</code></pre>
<p>Usually, calling <code>virtFunc</code> on a <code>Child</code> instance from anywhere will call the <code>Child</code> implementation of that method. However, sometimes it's useful to call the same level implementation:</p>
<pre><code>procedure Parent.other();
begin
virtFunc(); // I want to call Parent.virtFunc(), not Child.virtFunc()
end;
</code></pre>
<hr />
<p><strong>What did I tried?</strong></p>
<p><code>Parent(Self).virtFunc()</code></p>
<p><code>(Self as Parent).virtFunc()</code></p>
<p>And obviously, I could (but this is not the question):</p>
<ul>
<li>rename them differently (childFunc vs parentFunc),</li>
<li>remove the <code>virtual</code>.</li>
</ul>
<hr />
<p><strong>How to call the current level (non-polymorphic) version of a method in Delphi?</strong></p>
<p>For those who know c++, I would like some equivalent to <code>Parent::virtFunc()</code></p>
| [
{
"answer_id": 74123740,
"author": "David Heffernan",
"author_id": 505088,
"author_profile": "https://Stackoverflow.com/users/505088",
"pm_score": 4,
"selected": true,
"text": "Parent.virtFunc"
},
{
"answer_id": 74132156,
"author": "vegat4",
"author_id": 18174891,
"au... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74123453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/903651/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.