qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,203,348 | <p>I have a case where I need a list of fixtures (similar ones) inside a test case and perform same operation with those fixtures.</p>
<p><strong>For ex:</strong></p>
<pre><code>def testcase(fixture1, fixture2, fixture3):
# do some operation with fixture1
# do the same operation with fixture2
# do the same operation with fixture3
</code></pre>
<p>The thing is I have multiple such fixtures. Around 15 or so.
I'm looking for a way where I can mention these fixtures in a list like
<code>fixtures_list = [fixture1, fixture2, fixture3, ...]</code>
and update the list whenever needed.</p>
<p>And use a for loop inside the test case to perform operations on with the fixture like</p>
<pre><code>for fixture in fixtures_list:
#do something with fixture
</code></pre>
<p>But I'm unable to do it as we must definitely pass the fixture to the test case.</p>
<p>Is there any way to overcome this?</p>
| [
{
"answer_id": 74203472,
"author": "adem.sh",
"author_id": 6187897,
"author_profile": "https://Stackoverflow.com/users/6187897",
"pm_score": 0,
"selected": false,
"text": "import pytest\n\n\nclass Fruit:\n def __init__(self, name):\n self.name = name\n\n def __eq__(self, oth... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4626254/"
] |
74,203,409 | <p>I'm running on <code>linux</code> and want to download pip package for <code>windows</code>.</p>
<p>How can I do it ?</p>
<p>For example:</p>
<p>How can I run this command on linux and get the windows package ?</p>
<pre><code>pip3 download torch --extra-index-url https://download.pytorch.org/whl/cu113
</code></pre>
| [
{
"answer_id": 74203567,
"author": "POURiA",
"author_id": 2749367,
"author_profile": "https://Stackoverflow.com/users/2749367",
"pm_score": 0,
"selected": false,
"text": "python -m pip download --only-binary :all: --dest . --no-cache <package_name> \n"
},
{
"answer_id": 74203671,... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3668129/"
] |
74,203,425 | <p>Here is the data:</p>
<pre><code>set.seed(1234)
df = tribble(
~group,~value,
"a", rnorm(1000, mean = 5),
"b", rnorm(1000, mean = 7, sd = 1.5),
"c", rnorm(1000, mean = 8),
"c", rnorm(1000, mean = 9),
"c", rnorm(1000, mean = 7)
) %>%
unnest(value)
</code></pre>
<p>I use the code below to create box plot and overlying dots:</p>
<pre><code>library(ggplot2)
ggplot(df, aes(x = group, y = value)) +
geom_boxplot(aes(color = group), fill = NA, outlier.shape = NA)+
geom_point(aes(color = group), shape = 21, position = position_jitter(
seed = 1, width = .05
), alpha = 0.1)
</code></pre>
<p>Here is the figure:
<a href="https://i.stack.imgur.com/BgsXj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BgsXj.jpg" alt="enter image description here" /></a></p>
<p>The border color of the overlying points and the border color of the boxes are identical. For example, when the boxplot is orange, the border of points is also orange. I wish to know how could I allow for different colors for the boxplot and overlying points' border. For example, I wish to make colors of the boxplot to be black, blue, brown for groups a, b, and c, respectively. I also want the color of the border of overlying points to be red, green, yellow.</p>
| [
{
"answer_id": 74203567,
"author": "POURiA",
"author_id": 2749367,
"author_profile": "https://Stackoverflow.com/users/2749367",
"pm_score": 0,
"selected": false,
"text": "python -m pip download --only-binary :all: --dest . --no-cache <package_name> \n"
},
{
"answer_id": 74203671,... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4923935/"
] |
74,203,442 | <p>I'm developing the MFC Application (C++)
On i want to open the Labview program inside the MFC application and run top of the other windows on the main application.
So, it does not work on <code>CreateProcess()</code> function.</p>
<pre><code>#define DIR_TEMP_MONITER ".\\Application.exe"
STARTUPINFO stStartup = { NULL, };
PROCESS_INFORMATION stProcess = { NULL, };
stStartup.cb = sizeof( STARTUPINFO );// The size of the structure
stStartup.lpReserved = NULL; // Reserved
stStartup.lpDesktop = NULL; // For NT
stStartup.lpTitle = NULL; // Console app title
stStartup.dwFlags = 0; // Which member is valid
stStartup.cbReserved2 = 0;
stStartup.lpReserved2 = NULL;
::CreateProcess(DIR_TEMP_MONITER, // The name of the executable module
NULL, // Command line string
NULL, // Security descriptor
NULL, // Security descriptor
FALSE, // Handle inheritance option
NORMAL_PRIORITY_CLASS, // High priority class
NULL, // New environment block
NULL, // Current directory name
&stStartup, // Startup information
&stProcess ); // Process information
</code></pre>
<p>I want to make this executable program run on top of the other windows. Is there any other method to do that?</p>
| [
{
"answer_id": 74208865,
"author": "Flaviu_",
"author_id": 3775374,
"author_profile": "https://Stackoverflow.com/users/3775374",
"pm_score": -1,
"selected": false,
"text": "void CMainFrame::OnViewAlwaysontop() \n{\n // TODO: Add your command handler code here\n\n SetWindowPos(&wndT... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17848610/"
] |
74,203,448 | <p>I received a JSON file to transform into a CSV file.</p>
<pre class="lang-json prettyprint-override"><code>[
{
"id": "132465",
"ext_numero_commande": "4500291738L",
"ext_line_items": [
{
"key_0": "10",
"key_1": "10021405 / 531.415.110",
"key_4": "4 Pce"
},
{
"key_0": "20",
"key_1": "10021258 / 531.370.140 / NPK-Nr. 224412",
"key_4": "4 Pce"
},
{
"key_0": "30",
"key_1": "10020895 / 531.219.120 / NPK-Nr. 222111",
"key_4": "10 Pce"
},
{
"key_0": "40",
"key_1": "10028633 / 552.470.110",
"key_4": "3 Pce"
}
],
"ext_prix": [
{
"key_0": "11.17"
},
{
"key_0": "9.01"
},
{
"key_0": "18.63"
},
{
"key_0": "24.15"
}
],
"ext_tag": "Date_livraison",
"ext_jour_livraison": "23-07-2021",
"ext_jour_livraison_1": null
}
]
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>Ext_Numero_Commande</th>
<th>Ext_line items1</th>
<th>Ext_line items 4</th>
<th>Ext_Prix</th>
<th>Ext_Tag</th>
<th>Ext_Jour_Livraison</th>
<th>Ext_Jour_Livraison 1</th>
</tr>
</thead>
<tbody>
<tr>
<td>132465</td>
<td>4500291738L</td>
<td>10</td>
<td>10021405 / 531.415.110</td>
<td>4 Pce</td>
<td>11.17</td>
<td>Date_livraison</td>
<td>23-07-2021</td>
</tr>
<tr>
<td>132465</td>
<td>4500291738L</td>
<td>20</td>
<td>10021258 / 531.370.140 / NPK-Nr. 224412</td>
<td>4 Pce</td>
<td>9.01</td>
<td>Date_livraison</td>
<td>23-07-2021</td>
</tr>
<tr>
<td>132465</td>
<td>4500291738L</td>
<td>30</td>
<td>10020895 / 531.219.120 / NPK-Nr. 222111</td>
<td>10 Pce</td>
<td>18.63</td>
<td>Date_livraison</td>
<td>23-07-2021</td>
</tr>
<tr>
<td>132465</td>
<td>4500291738L</td>
<td>40</td>
<td>10028633 / 552.470.110</td>
<td>3 Pce</td>
<td>24.15</td>
<td>Date_livraison</td>
<td>23-07-2021</td>
</tr>
</tbody>
</table>
</div>
<p>I found the function <code>pd.json_normalize</code>.</p>
<pre class="lang-py prettyprint-override"><code>df=pd.json_normalize(
json_object[0],
record_path=['ext_line_items'],
meta=['id', 'ext_numero_commande', 'ext_tag',
'ext_jour_livraison', 'ext_jour_livraison_1'])
</code></pre>
<p>I have nearly my end result, and I can add the last column <code>["ext_prix"]</code> with the same method and a concatenation function.</p>
<p>Is a function which does it automatically?</p>
<p>I used this function, but it returns an error.</p>
<pre class="lang-py prettyprint-override"><code>df=pd.json_normalize(
json_object[0],
record_path=['ext_line_items','ext_prix'],
meta=['id', 'ext_numero_commande', 'ext_tag',
'ext_jour_livraison', 'ext_jour_livraison_1'])
</code></pre>
| [
{
"answer_id": 74208865,
"author": "Flaviu_",
"author_id": 3775374,
"author_profile": "https://Stackoverflow.com/users/3775374",
"pm_score": -1,
"selected": false,
"text": "void CMainFrame::OnViewAlwaysontop() \n{\n // TODO: Add your command handler code here\n\n SetWindowPos(&wndT... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18406891/"
] |
74,203,478 | <p>I tried to use Chart.js in my Django project , when I Use NPM package it's not working but when I use CDN It work Perfectly</p>
<p>char.js version 3.9.1</p>
<p>here is my index.html file on my project</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{# <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>#}
<script type="application/json" src="/node_modules/chart.js/dist/chart.js"></script>
</head>
<body>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>
</body>
</html>
</code></pre>
<p>my console error in browser is :</p>
<pre><code>(index):17 Uncaught ReferenceError: Chart is not defined
at (index):17:17
</code></pre>
<p>I tried to use chart.min.js in my script but not working.
I also Try previous version of charj.js but still not working.
I also copy code on CDN and put it locally on project but still not working.</p>
| [
{
"answer_id": 74208865,
"author": "Flaviu_",
"author_id": 3775374,
"author_profile": "https://Stackoverflow.com/users/3775374",
"pm_score": -1,
"selected": false,
"text": "void CMainFrame::OnViewAlwaysontop() \n{\n // TODO: Add your command handler code here\n\n SetWindowPos(&wndT... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18466173/"
] |
74,203,490 | <p>is there a filtered view of a collection (a subset of it) in Java, so that adding new item to it can also affect the source collection?</p>
<p>e.g.</p>
<pre><code>List<String> source = new ArrayList<>();
source.add("a");
source.add("b");
List<String> view = source.stream().filter(i -> "b".equals(i)).collect(...);
view.add("c"); // source now contains also "c"
</code></pre>
| [
{
"answer_id": 74206671,
"author": "Wilderness Ranger",
"author_id": 19048941,
"author_profile": "https://Stackoverflow.com/users/19048941",
"pm_score": 2,
"selected": false,
"text": "AbstractCollection"
},
{
"answer_id": 74207635,
"author": "Nowhere Man",
"author_id": 13... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1589188/"
] |
74,203,537 | <pre class="lang-kotlin prettyprint-override"><code>val myQuestion = """
I am creating a multiline string containing paragraphs of text. The text will wrap when put into a TextView.
But as you can see, when defining the text in the editor, if I want to avoid newlines mid-paragraph, I need to write really long lines that require a lot of horizontal scrolling.
Is there some way that I can have line breaks in the editor that don't appear in the actual value of the string?
"""
</code></pre>
| [
{
"answer_id": 74204243,
"author": "Sweeper",
"author_id": 5133585,
"author_profile": "https://Stackoverflow.com/users/5133585",
"pm_score": 2,
"selected": false,
"text": "$"
},
{
"answer_id": 74210585,
"author": "Peter",
"author_id": 851699,
"author_profile": "https:... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/851699/"
] |
74,203,569 | <p>I am learning C# and came across a sample code which are as follows :</p>
<p><strong>Shapes.cs</strong></p>
<pre><code>using System;
public record Position(int X, int Y);
public record Size(int Width, int Height);
public abstract record Shape(Position Position, Size Size)
{
public void Draw() => DisplayShape();
protected virtual void DisplayShape()
{
Console.WriteLine($"Shape with {Position} and {Size}");
}
}
</code></pre>
<p><strong>ConcreteShapes.cs</strong></p>
<pre><code>using System;
public record Rectangle(Position Position, Size Size) : Shape(Position, Size)
{
protected override void DisplayShape()
{
Console.WriteLine($"Rectangle at position {Position} with size {Size}");
}
}
public record Ellipse(Position Position, Size Size) : Shape(Position, Size)
{
protected override void DisplayShape()
{
Console.WriteLine($"Ellipse at position {Position} with size {Size}");
}
}
</code></pre>
<p><strong>Program.cs</strong></p>
<pre><code>Rectangle r1 = new(new Position(33, 22), new Size(200, 100));
Rectangle r2 = r1 with { Position = new Position(100, 22) };
Ellipse e1 = new(new Position(122, 200), new Size(40, 20));
DisplayShapes(r1, r2, e1);
void DisplayShapes(params Shape[] shapes)
{
foreach (var shape in shapes)
{
shape.Draw();
}
}
</code></pre>
<p><strong>Project structure :</strong></p>
<p><a href="https://i.stack.imgur.com/F9FdY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F9FdY.png" alt="enter image description here" /></a></p>
<p><strong>Question :</strong></p>
<p>When I build the project and run the the project with the below command :</p>
<pre><code>dotnet run --project .\RecordsInheritance\RecordsInheritance.csproj
</code></pre>
<p>I am getting output which i.e. DisplayShapes method is getting called and output is displayed.
The C# code in Program.cs is not wrapped inside a namespace and a class and yet it is getting executed correctly like a javascript code.
Can someone explain me how this code is getting executed correctly as the code is not wrapped inside a class and there is no public static method as well ?</p>
| [
{
"answer_id": 74203612,
"author": "Michał Turczyn",
"author_id": 7132550,
"author_profile": "https://Stackoverflow.com/users/7132550",
"pm_score": 0,
"selected": false,
"text": "namespace MyProject;\n// All below does not need braces and indentation, it goes to above namespace\npublic c... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5109928/"
] |
74,203,593 | <p>I do not know exactly how I can bind my form data in JSON string. in my scenario, I use a string field in the database and have some checkbox fields that I have to save in only a single database column using JSON. for that, I created an HTML form, and I don't know how I can bind all data in a database. if someone knows then can guide me</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>documentList: [
{
'IsSpecifications': false,
'IsSpecificationscomment': ''
},
{
'IsDrawSchedule': false,
'IsDrawSchedulecomment': ''
},
{
'TqRfi': false,
'TqRficomment': ''
},
{
'InsEnqReqQouInfor': false,
'InsEnqReqQouInforcomment': ''
},
{
'PanEnqReqQouInfor': false,
'PanEnqReqQouInforcomment': ''
},
{
'PanSubContQuot': false,
'PanSubContQuotcomment': ''
},
{
'MccSchedule': false,
'MccScheduleComment': ''
},
{
'ScPackQuot': false,
'ScPackQuotComment': ''
},
{
'O3rdPartyQuot': false,
'O3rdPartyQuotcomment': ''
},
{
'EquipSchedule': false,
'EquipScheduleComment': ''
},
{
'PointSchedul': false,
'PointSchedulComment': ''
},
{
'ValveSchedul': false,
'ValveSchedulComment': ''
},
{
'IdentRiskOpport': false,
'IdentRiskOpportComment': ''
},
{
'InstSubContQuot': false,
'InstSubContQuotComment': ''
}
];</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="my-3">
<ejs-checkbox label="isSpecifications()" labelPosition="Before"></ejs-checkbox>
</div>
<div class="my-3">
<ejs-checkbox label="Drawings/Schedules" labelPosition="Before"></ejs-checkbox>
</div>
<div class="my-3">
<ejs-checkbox label="TQ’s / RFI’s" labelPosition="Before"></ejs-checkbox>
</div>
<div class="my-3">
<ejs-checkbox
label="Install Enquiry / request to quote information"
labelPosition="Before"
></ejs-checkbox>
</div>
<div class="my-3">
<ejs-checkbox
label="Panel Enquiry / request to quote information"
labelPosition="Before"
></ejs-checkbox>
</div>
<div class="my-3">
<ejs-checkbox label="Panel Sub Contractor Quotation" labelPosition="Before"></ejs-checkbox>
</div>
<div class="my-3">
<ejs-checkbox label="MCC Schedules" labelPosition="Before"></ejs-checkbox>
</div>
<div class="my-3">
<ejs-checkbox label="Other S/C Package Quotations" labelPosition="Before"></ejs-checkbox>
</div>
<div class="my-3">
<ejs-checkbox label="Other 3rd Party Quotations" labelPosition="Before"></ejs-checkbox>
</div>
<div class="my-3">
<ejs-checkbox label="Equipment Schedules" labelPosition="Before"></ejs-checkbox>
</div>
<div class="my-3">
<ejs-checkbox label="Points Schedules" labelPosition="Before"></ejs-checkbox>
</div>
<div class="my-3">
<ejs-checkbox label="Valve Schedules" labelPosition="Before"></ejs-checkbox>
</div>
<div class="my-3">
<ejs-checkbox
label="Identifed Risks and Opportunities (INCL. VALUE ENGINEERING)"
labelPosition="Before"
></ejs-checkbox>
</div>
<div class="my-3">
<ejs-checkbox label="Install Sub Contractor Quotation" labelPosition="Before"></ejs-checkbox>
</div></code></pre>
</div>
</div>
</p>
<p>in the database, I use <strong>documentlist</strong> field in that all my checkbox values save in JSON string.</p>
| [
{
"answer_id": 74203612,
"author": "Michał Turczyn",
"author_id": 7132550,
"author_profile": "https://Stackoverflow.com/users/7132550",
"pm_score": 0,
"selected": false,
"text": "namespace MyProject;\n// All below does not need braces and indentation, it goes to above namespace\npublic c... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18565281/"
] |
74,203,604 | <p>I fail to get the image (logo) in the center of the top bar!! I tried everything, I used <code>align-self: center;</code> , <code>display:block;</code> but no luck!! I don't know what i'm missing here!</p>
<p><a href="https://codesandbox.io/s/sad-raman-npt8zq?file=/index.html" rel="nofollow noreferrer">codesandbox</a> Link to the code for better viewing</p>
<p><strong>The code:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="keywords" content="مرحبا">
<meta name="description" content="">
<style>
.mail {
justify-content: center;
align-content: center;
align-items: center;
}
.headerContainer{
width: 100%;
display: flex;
justify-content: space-between;
align-content: center;
align-items: center;
align-self: center;
margin-bottom: 50px;
background-color: black;
}
.logo-image-cont{
align-content: center;
align-items: center;
align-self: center;
}
.logo-image {
width: 20%;
height: 10%;
}
</style>
</head>
<body>
<div class="mail">
<header class="headerContainer">
<div class="logo-image-cont">
<img
src="https://i.ibb.co/jwjBMnS/Kia-logo.png"
class="logo-image"
/>
</a>
</div>
</header>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74203617,
"author": "Cervus camelopardalis",
"author_id": 10347145,
"author_profile": "https://Stackoverflow.com/users/10347145",
"pm_score": 3,
"selected": true,
"text": ".logo-image-cont {\n display: flex;\n justify-content: center;\n}\n"
},
{
"answer_id": 7420... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17342280/"
] |
74,203,631 | <p>i have a Question about a Query in KQL.
I would like to use a Time at the KQL Query who only shows me the Results between 08:00 and 17:00 Time.</p>
<p>How can i build these at the KQL Query?
Im only find the DateTime Variable but i need only the Time?</p>
<p>Thanks a lot.</p>
<p>Regards,
Phil</p>
| [
{
"answer_id": 74203617,
"author": "Cervus camelopardalis",
"author_id": 10347145,
"author_profile": "https://Stackoverflow.com/users/10347145",
"pm_score": 3,
"selected": true,
"text": ".logo-image-cont {\n display: flex;\n justify-content: center;\n}\n"
},
{
"answer_id": 7420... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18864394/"
] |
74,203,634 | <p>I have a array list of a Model class which has multiple String type variables.
This Array list values is populated from JDBC template result set.</p>
<p>Now I want to iterate this Array List and update some of these model element based upon some conditions.</p>
<p>My Model Class:</p>
<pre><code>import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class WADataModel {
public String STATUS;
public String AUTO_DATE;
public String RECORD_TYPE;
public String VENDOR_NAME;
public String CREATED_DATE;
public String ACTION_CODE;
public String CITY;
public String GROUP_NUMBER;
public String GROUP_POLICY_NUMBER;
public String SUBGROUP_NUMBER;
public String SUBGROUP_POLICY_NUMBER;
public String SYSTEM;
public String PLAN_NUMBER;
}
</code></pre>
<p>My DAO Class:</p>
<pre><code>import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class PlanCrosswalks {
@Autowired
@Qualifier("nemisNamedJdbcTemplate")
private NamedParameterJdbcTemplate nemisJdbcTemplate;
@Autowired
private FetchDatafFromProp fetchDatafFromProp;
@Value("${query.state}")
private String queryState;
public List<WADataModel> doWACrosswalk(List<WADataModel> claimDataList) throws ApplicationExceptions{
RowMapper<WACrosswalkModel> rowMapper = new BeanPropertyRowMapper<>(WACrosswalkModel.class);
List<WACrosswalkModel> statusResult = new ArrayList<>();
Map<String,String> crosswalkQueryMap = new HashMap<>();
Map<String,String> paramMap = new HashMap<>();
crosswalkQueryMap = fetchDatafFromProp.getDataForGeneration();
statusResult = nemisJdbcTemplate.query(crosswalkQueryMap.get(queryState+ Constants.UNDERSCORE + Constants.FETCH_SUB_GROUP_POLICY),paramMap,rowMapper);
for(WADataModel model : claimDataList)
//Here I want to update ClaimDataList elements like SUBGROUP_POLICY_NUMBER,GROUP_POLICY_NUMBER based upon some conditions by iterating whole List.
return claimDataList;
}
</code></pre>
<p>}</p>
<p>I want to iterate "claimDataList" and check whether plan_number is null and update subGroupPolicyNumber accordingly based upon the value of plan_number.</p>
<p>I can iterate List of model but don't know how to update the values in List of model.
Please help me to update the values in "claimDataList"</p>
| [
{
"answer_id": 74203617,
"author": "Cervus camelopardalis",
"author_id": 10347145,
"author_profile": "https://Stackoverflow.com/users/10347145",
"pm_score": 3,
"selected": true,
"text": ".logo-image-cont {\n display: flex;\n justify-content: center;\n}\n"
},
{
"answer_id": 7420... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15153070/"
] |
74,203,656 | <p>I believe my problem can be explained by the following code snippet</p>
<pre><code>#define stingify(str) #str
int main()
{
int a;
printf("%s\n" , stringify(typeof(a)));
return 0;
}
</code></pre>
<p>I want the <code>typeof()</code> macro to be expanded first then the <code>stringify()</code> macro to get my expected output "int" as a string.
Is there any possible way for this?</p>
| [
{
"answer_id": 74204733,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 1,
"selected": false,
"text": "char *typei()\n{\n return \"signed integer\";\n}\n\nchar *typeui()\n{\n return \"unsigned integer\";\n}\n... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4899025/"
] |
74,203,701 | <p>I have the block of code below where I update a list of users in an async foreach block. Then I have to parse that list of users to another service. The problem is even if I set the users value isRegistered to true, when it gets to the _secondService.UpdateUsers function, the value is still false.</p>
<p>The secondService function has to be outside the foreach. I understand it has something to do with the async, but I have also awaited the second service. Is there a workaround for this?</p>
<pre><code> userList.ForEach(async user =>
{
if (user.isRegistered == false)
{
if (await _service.RegisterUser(user))
{
user.isRegistered = true;
}
}
});
await _secondService.UpdateUsers(userList);
</code></pre>
| [
{
"answer_id": 74204098,
"author": "Vida",
"author_id": 1866615,
"author_profile": "https://Stackoverflow.com/users/1866615",
"pm_score": 0,
"selected": false,
"text": "foreach(var user in userList){\n // do stuffs inside\n}\n"
},
{
"answer_id": 74204653,
"author": "Henk",
... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1866615/"
] |
74,203,703 | <p><a href="https://i.stack.imgur.com/q53ut.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q53ut.png" alt="Sample" /></a></p>
<p>Would it be possible to use arrayformular for this condition?
Sum all the rows that PID are the same, the result should be as in the image.</p>
<p>I tried this code, but I think it's too long, and if the PID exceed over 20 rows, it would not work.</p>
<p><code>=IF(A3<>A2,BJ3+IF(A3=A4,BJ4,0)+IF(A3=A5,BJ5,0)+IF(A3=A6,BJ6,0)+IF(A3=A7,BJ7,0)+IF(A3=A8,BJ8,0)+IF(A3=A9,BJ9,0)+IF(A3=A10,BJ10,0)+IF(A3=A11,BJ11,0)+IF(A3=A12,BJ12,0)+IF(A3=A13,BJ13,0)+IF(A3=A14,BJ14,0)+IF(A3=A15,BJ15,0)+IF(A3=A16,BJ16,0)+IF(A3=A17,BJ17,0)+IF(A3=A18,BJ18,0)+IF(A3=A19,BJ19,0)+IF(A3=A20,BJ20,0)+IF(A3=A21,BJ21,0)+IF(A3=A22,BJ22,0),0)</code></p>
| [
{
"answer_id": 74204098,
"author": "Vida",
"author_id": 1866615,
"author_profile": "https://Stackoverflow.com/users/1866615",
"pm_score": 0,
"selected": false,
"text": "foreach(var user in userList){\n // do stuffs inside\n}\n"
},
{
"answer_id": 74204653,
"author": "Henk",
... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18610085/"
] |
74,203,705 | <p>I want to loop through a list and remove a single element at a time:</p>
<pre><code>l1 = ["a", "b"]
for l in l1:
l2 = l1[:]
l2.remove(l)
print(l2)
# ['b']
# ['a']
</code></pre>
<p>The behavior of the code changes when I use the remove call inline:</p>
<pre><code>l1 = ["a", "b"]
for l in l1:
l2 = l1[:].remove(l)
print(l2)
# None
# None
</code></pre>
<p>Any idea what is happening? Is this an artefact of <code>remove()</code> or a more general issue with functions that use mutability of objects?</p>
<p>Thanks</p>
| [
{
"answer_id": 74203772,
"author": "Andi R",
"author_id": 19768538,
"author_profile": "https://Stackoverflow.com/users/19768538",
"pm_score": 2,
"selected": false,
"text": "remove()"
},
{
"answer_id": 74203798,
"author": "alejandroklever",
"author_id": 11217973,
"auth... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11170205/"
] |
74,203,717 | <p>I'm learning python and I'm trying to understand what the for loop means. My assignment is to understand and comment the full code out. I know that the first two lines of code take an input. Can someone tell me what the next lines of code mean? The for loop is extremely confusing. By the way, let's say the input for j_t is 1, 3, 5 and the input for d_t is 2, 4, 6. Hopefully that helps.</p>
<pre><code># to take inputs
j_t = list(map(int, input("Process times: ").split(",")))
d_t = list(map(int, input("Job Due Dates: ").split(",")))
dict_spt = {}
dict_edd = {}
for i in range(len(j_t)):
dict_spt[int(j_t[i])] = int(d_t[i])
dict_edd[int(d_t[i])] = int(j_t[i])
</code></pre>
<p>The above is a segment of the full code. I ran the full code and it allows me to put in input but I need to understand what the for loop actually does/means in plain english.</p>
| [
{
"answer_id": 74203827,
"author": "Claude Shannon",
"author_id": 20102259,
"author_profile": "https://Stackoverflow.com/users/20102259",
"pm_score": 3,
"selected": true,
"text": "input"
},
{
"answer_id": 74203832,
"author": "Leon",
"author_id": 15319257,
"author_prof... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19482155/"
] |
74,203,721 | <p>Want to remove multiple commas [with or without spaces] with a single one. Tried this regex however it failed <code>preg_replace("/\s{1,5},\s{1,5}+/", ", ", $string);</code><br />
Tried other solutions but can't find any solution where space also exists with comma.</p>
<p><strong>Sample input</strong></p>
<pre><code>GUWAHATI, TEZPUR, , BAMUNI HILLS, MAHABHAIRAB TEMPLE, AGNIGARH ,
GUWAHATI, TEZPUR , , BAMUNI HILLS,, MAHABHAIRAB TEMPLE, AGNIGARH,
GUWAHATI, , TEZPUR, , BAMUNI HILLS, MAHABHAIRAB TEMPLE, AGNIGARH
</code></pre>
<p><strong>Expected output</strong></p>
<pre><code>GUWAHATI, TEZPUR, BAMUNI HILLS, MAHABHAIRAB TEMPLE, AGNIGARH
</code></pre>
| [
{
"answer_id": 74203778,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 2,
"selected": false,
"text": "$s = preg_replace('/^[,\\h]+|\\h*(,)(?:\\h*,)+\\h*|[,\\h]+$/m', '$1 ', $s);\n"
},
{
"answer_id": 74203848,
... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/688720/"
] |
74,203,723 | <p>Do I need to restart my payara instance after changing a JNDI variable to apply the changes in the application?</p>
<p>Or is there some kind of automatic reload mechanism?</p>
| [
{
"answer_id": 74203778,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 2,
"selected": false,
"text": "$s = preg_replace('/^[,\\h]+|\\h*(,)(?:\\h*,)+\\h*|[,\\h]+$/m', '$1 ', $s);\n"
},
{
"answer_id": 74203848,
... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10309166/"
] |
74,203,728 | <p>I was trying to write the function insertAfter to insert the element after specific element in the LinkedList . Below is the code. The insertAfter function is not producing the desired output. Can some one help me what mistake I have done in the below insertAfter function that I need to correct.</p>
<pre><code>import java.util.Scanner;
import java.lang.Exception;
import java.lang.StringBuilder;
import java.util.ArrayList;
import java.util.*;
import java.util.regex.*;
import java.util.stream.Collectors;
class SingleLinkedList<T>
{
public class Node
{
public T data;
public Node nextNode;
}
public Node headNode;
public int size;
public SingleLinkedList()
{
headNode = null;
size = 0;
}
public boolean isEmpty()
{
if (headNode == null)
{
return true;
}
return false;
}
public void insertAtHead(T data)
{
Node node = new Node();
node.data = data;
node.nextNode = headNode;
headNode = node;
size++;
}
public void insertAtEnd(T data)
{
if (isEmpty())
{
insertAtHead(data);
return;
}
Node newNode = new Node();
newNode.data = data;
newNode.nextNode = null;
Node last = headNode;
while (last.nextNode != null)
{
last = last.nextNode;
}
last.nextNode = newNode;
size++;
}
public void insertAfter(T data1, T data2)
{
if (isEmpty())
{
System.out.println("The list is empty");
return;
}
Node insertNode = new Node();
insertNode.data = data2;
Node temp = headNode;
while (temp.data != data1)
{
temp = temp.nextNode;
}
insertNode.nextNode = temp;
temp = insertNode;
size++;
}
public void printList()
{
if (isEmpty())
{
System.out.println("The list is empty.");
return;
}
Node temp = headNode;
System.out.println("List : ");
while (temp.nextNode != null)
{
System.out.print(temp.data.toString() + "->");
temp = temp.nextNode;
}
System.out.println(" null");
}
}
public class Solution
{
//static String originalString="AbcDef";
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
SingleLinkedList<Integer> sll = new SingleLinkedList<>();
sll.printList();
for (int i = 0; i <= 10; i++)
{
sll.insertAtEnd(i);
}
sll.printList();
System.out.println("The size of the list is : " + sll.size);
sll.insertAfter(3,72);
sll.printList();
System.out.println("The new size of the list is : " + sll.size);
}
}
</code></pre>
<p>In the insertAfter function I create a temp Node and assign the headNode address. Then I create a while loop and traverse the list until I reach the data element after which I need to insert and update the nextNode address in temp Node. Once the loop breaks I update the new Node next address to the temp Node and update the temp node address with the address of the new Node. It seems correct to me but code provides below output.</p>
<pre><code>The list is empty.
List :
0->1->2->3->4->5->6->7->8->9-> null
The size of the list is : 11
List :
0->1->2->3->4->5->6->7->8->9-> null
The new size of the list is : 12
</code></pre>
| [
{
"answer_id": 74203869,
"author": "Ravindra Ranwala",
"author_id": 4108590,
"author_profile": "https://Stackoverflow.com/users/4108590",
"pm_score": 2,
"selected": true,
"text": "insertAfter"
},
{
"answer_id": 74204127,
"author": "Ali Hamed",
"author_id": 20277138,
"... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10254216/"
] |
74,203,738 | <p>Does any one know how to clear the cache on laravel -9 on server<br>
I tried it and it took me to a 404 error page<br></p>
<pre><code>Route::get('/clear', function() {
Artisan::call('cache:clear');
Artisan::call('config:clear');
Artisan::call('config:cache');
Artisan::call('view:clear');
return "Cleared!";
});
</code></pre>
<p>and</p>
<pre><code>Route::get('clear',[SiteController::class,'clear']);
</code></pre>
<pre><code>public function clear()
{
\Artisan::call('route:clear');
\Artisan::call('config:clear');
\Artisan::call('config:cache');
\Artisan::call('view:clear');
return "Cleared!";
}
</code></pre>
<p>I have tried these 2 code, both are not working. and My new updates are not showing up on the site also
<br>please help me<br> Thanks in advance</p>
| [
{
"answer_id": 74203869,
"author": "Ravindra Ranwala",
"author_id": 4108590,
"author_profile": "https://Stackoverflow.com/users/4108590",
"pm_score": 2,
"selected": true,
"text": "insertAfter"
},
{
"answer_id": 74204127,
"author": "Ali Hamed",
"author_id": 20277138,
"... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9181672/"
] |
74,203,741 | <pre><code>addEventListener('keypress', ({keyCode}) => {
switch(keyCode){
case 87: //up
alert('press')
break;
}
})
</code></pre>
<p>Why is my keypress not working, if I change it to keydown, it works but keypress does not</p>
| [
{
"answer_id": 74203806,
"author": "RenaudC5",
"author_id": 11260991,
"author_profile": "https://Stackoverflow.com/users/11260991",
"pm_score": 0,
"selected": false,
"text": "keypress"
},
{
"answer_id": 74203855,
"author": "Robin",
"author_id": 7387089,
"author_profil... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20289819/"
] |
74,203,774 | <p>I have two lists. I want to compare two lists and change the <code>Selected</code> bool property <code>false</code> to <code>true</code> from <code>firstInstance </code> if the <code>selectedInstance </code> list items should have in the <code>firstInstance </code> list. I have tried below code using <code>IEnumerator</code> but not getting as expected.</p>
<p>I am expecting the output:</p>
<pre><code> List<Data> firstInstance = new List<Data>
{
new Data { AccountNo = 1001,AccountName="AccountName1",BranchName="BranchName1", Selected = false },
new Data { AccountNo = 1101,AccountName="AccountName2",BranchName="BranchName2", Selected = true},
new Data { AccountNo = 1051,AccountName="AccountName3",BranchName="BranchName3", Selected = false },
new Data { AccountNo = 1991,AccountName="AccountName4",BranchName="BranchName4", Selected = true},
new Data { AccountNo = 1234,AccountName="AccountName5",BranchName="BranchName5", Selected = false },
};
</code></pre>
<p>I have tried below code:-</p>
<pre><code>static class Program
{
static void Main(string[] args)
{
List<Data> firstInstance = new List<Data>
{
new Data { AccountNo = 1001,AccountName="AccountName1",BranchName="BranchName1", Selected = false },
new Data { AccountNo = 1101,AccountName="AccountName2",BranchName="BranchName2", Selected = false },
new Data { AccountNo = 1051,AccountName="AccountName3",BranchName="BranchName3", Selected = false },
new Data { AccountNo = 1991,AccountName="AccountName4",BranchName="BranchName4", Selected = false },
new Data { AccountNo = 1234,AccountName="AccountName5",BranchName="BranchName5", Selected = false },
};
List<Data> selectedInstance = new List<Data>
{
new Data { AccountNo = 1991,AccountName="AccountName4",BranchName="BranchName4", Selected = true },
new Data { AccountNo = 1101,AccountName="AccountName2",BranchName="BranchName2", Selected = true }
};
firstInstance.CheckActive(selectedInstance);
}
static void CheckActive(this List<Data> firstInstance, List<Data> selectedInstance)
{
using (IEnumerator<Data> firstEnumerator = firstInstance.GetEnumerator(), secondEnumerator = selectedInstance.GetEnumerator())
{
while (true)
{
if (!firstEnumerator.MoveNext() || !secondEnumerator.MoveNext()) break;
if (firstEnumerator.Current.AccountNo == secondEnumerator.Current.AccountNo) firstEnumerator.Current.Selected = true;
}
}
}
}
class Data
{
public int AccountNo { get; set; }
public string AccountName { get; set; }
public string BranchName { get; set; }
public bool Selected { get; set; }
}
</code></pre>
| [
{
"answer_id": 74204023,
"author": "Shay",
"author_id": 264672,
"author_profile": "https://Stackoverflow.com/users/264672",
"pm_score": 1,
"selected": false,
"text": "var selectedAccounts = selectedInstance.Select(d => d.AccountNo).ToList();\nforeach (var selected in firstInstance.Where(... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7963557/"
] |
74,203,779 | <p>My Java code generates a new path name for an existing file, as part of this, I have to ensure each path segment is no longer than 255 characters because this is illegal for most operating systems.</p>
<pre class="lang-java prettyprint-override"><code>// No path component can be longer than 255 chars
String[] pathComponents = splitPath(newPath);
for(int i=0;i<pathComponents.length - 1;i++) {
if (pathComponents[i]. length() > MAX_FILELENGTH) {
String shortened = pathComponents[i].substring(0, MAX_FILELENGTH - 1);
shortened = shortened.trim();
sb.append(shortened).append(File.separator);
}
else {
sb.append(pathComponents[i]).append(File.separator);
}
}
</code></pre>
<p>This works fine most of the time, but it doesn't work if there are less than 255 Unicode characters but when the Unicode characters are written to the filesystem, some require more than one byte and therefore end up with more than 255 bytes, which isn't caught by test.</p>
<p>I can count bytes instead of characters with</p>
<pre class="lang-java prettyprint-override"><code>if(pathComponents[i].getBytes(StandardCharsets.UTF_8).length > MAX_FILELENGTH)
</code></pre>
<p>I cannot work out a nice way to trim by just the right amount of characters.</p>
| [
{
"answer_id": 74204023,
"author": "Shay",
"author_id": 264672,
"author_profile": "https://Stackoverflow.com/users/264672",
"pm_score": 1,
"selected": false,
"text": "var selectedAccounts = selectedInstance.Select(d => d.AccountNo).ToList();\nforeach (var selected in firstInstance.Where(... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1480018/"
] |
74,203,788 | <p>I have a function I want to mock:</p>
<pre><code>class Base{
public:
void virtual func() { sleep(3); }
};
</code></pre>
<p>My mock would look like:</p>
<pre><code>class Mock: public Base{
public:
MOCK_METHOD(void, func, (), (override));
};
</code></pre>
<p>And the test would look like:</p>
<pre><code>TEST(TestMockSanity, AbleToMock) {
Mock mock;
EXPECT_CALL(mock, func());
}
</code></pre>
<p>however, I have 2 issues:</p>
<ol>
<li><strong>something silly</strong> - error: ‘class testing::internal::TypedExpectation<void()>’ has no member named ‘TIMES’</li>
<li><strong>Important</strong> - How do I change the implemntation of <code>func</code> to <code>sleep(0)</code>?</li>
</ol>
<hr />
<p>./real.hpp</p>
<pre><code>class Real {
public:
Real(){};
virtual ~Real(){};
virtual int run();
virtual int dont_run();
};
</code></pre>
<p>./real.cpp</p>
<pre><code>#include "real.hpp"
int Real::run() { return 0; };
int Real::dont_run() { return 1; };
</code></pre>
<p>./meson.build</p>
<pre><code>project(
'gtest',
'cpp',
default_options : [
'cpp_std=c++14',
],
)
sources = files('main.cpp', 'real.cpp')
executable(
'real',
sources,
install : false,
)
executable(
'mock',
files('real.cpp', 'mock.cpp'),
dependencies: [dependency('gtest'), dependency('gmock')],
install : false,
)
</code></pre>
<p>./mock.cpp</p>
<pre><code>#include "gmock/gmock.h" // MOCK_METHOD
#include "gtest/gtest.h" // TEST
#include "real.hpp"
class MockReal : public Real {
public:
MOCK_METHOD(int, run, (), (override));
MOCK_METHOD(int, dont_run, (), (override));
void delegate(){
ON_CALL(*this, run).WillByDefault([this](){
return 1;
});
ON_CALL(*this, dont_run).WillByDefault([this](){
return 2;
});
}
};
TEST(TestMockSanity, AbleToMock) {
MockReal mock;
EXPECT_EQ(0, mock.run());
EXPECT_EQ(1, mock.dont_run());
mock.delegate();
EXPECT_EQ(1, mock.run());
EXPECT_EQ(2, mock.dont_run());
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
</code></pre>
<p>./main.cpp</p>
<pre><code>#include "real.hpp"
int main() {
Real r;
r.run();
return 0;
}
</code></pre>
<p>subprojects/gtest.wrap</p>
<pre><code>[wrap-file]
directory = googletest-release-1.11.0
source_url = https://github.com/google/googletest/archive/release-1.11.0.tar.gz
source_filename = gtest-1.11.0.tar.gz
source_hash = b4870bf121ff7795ba20d20bcdd8627b8e088f2d1dab299a031c1034eddc93d5
patch_filename = gtest_1.11.0-2_patch.zip
patch_url = https://wrapdb.mesonbuild.com/v2/gtest_1.11.0-2/get_patch
patch_hash = 764530d812ac161c9eab02a8cfaec67c871fcfc5548e29fd3d488070913d4e94
[provide]
gtest = gtest_dep
gtest_main = gtest_main_dep
gmock = gmock_dep
gmock_main = gmock_main_dep
</code></pre>
<p>And I get after running:</p>
<pre><code>[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from TestMockSanity
[ RUN ] TestMockSanity.AbleToMock
GMOCK WARNING:
Uninteresting mock function call - returning default value.
Function call: run()
Returns: 0
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.
GMOCK WARNING:
Uninteresting mock function call - returning default value.
Function call: dont_run()
Returns: 0
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.
../mock.cpp:24: Failure
Expected equality of these values:
1
mock.dont_run()
Which is: 0
GMOCK WARNING:
Uninteresting mock function call - taking default action specified at:
../mock.cpp:11:
Function call: run()
Returns: 1
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.
GMOCK WARNING:
Uninteresting mock function call - taking default action specified at:
../mock.cpp:14:
Function call: dont_run()
Returns: 2
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.
[ FAILED ] TestMockSanity.AbleToMock (0 ms)
[----------] 1 test from TestMockSanity (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[ PASSED ] 0 tests.
[ FAILED ] 1 test, listed below:
[ FAILED ] TestMockSanity.AbleToMock
1 FAILED TEST
</code></pre>
| [
{
"answer_id": 74204027,
"author": "Robin",
"author_id": 11426176,
"author_profile": "https://Stackoverflow.com/users/11426176",
"pm_score": -1,
"selected": false,
"text": "func()"
},
{
"answer_id": 74204478,
"author": "Pepijn Kramer",
"author_id": 16649550,
"author_p... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3512538/"
] |
74,203,791 | <p>Have two DataFrames with identical columns labels. Columns are <code>label, data1, data2, ..., dataN</code>.
Need to take the product of the DataFrames, multiplying data1 * data1, data2 * data2, etc for every possible combination of rows in DataFrame1 with the rows in DataFrame2. As such, want the resulting DataFrame to maintain the label column of both frames in some way</p>
<p>Example:</p>
<p>Frame 1:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>label</th>
<th>d1</th>
<th>d2</th>
<th>d3</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>b</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>
</div>
<p>Frame 2:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>label</th>
<th>d1</th>
<th>d2</th>
<th>d3</th>
</tr>
</thead>
<tbody>
<tr>
<td>c</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>d</td>
<td>10</td>
<td>11</td>
<td>12</td>
</tr>
</tbody>
</table>
</div>
<p>Result:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>label_1</th>
<th>label_2</th>
<th>d1</th>
<th>d2</th>
<th>d3</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>c</td>
<td>7</td>
<td>16</td>
<td>27</td>
</tr>
<tr>
<td>a</td>
<td>d</td>
<td>10</td>
<td>22</td>
<td>36</td>
</tr>
<tr>
<td>b</td>
<td>c</td>
<td>28</td>
<td>40</td>
<td>54</td>
</tr>
<tr>
<td>b</td>
<td>d</td>
<td>40</td>
<td>55</td>
<td>72</td>
</tr>
</tbody>
</table>
</div>
<p>I feel like there is a nice way to do this, but all I can come up with is gross loops with lots of memory reallocation.</p>
| [
{
"answer_id": 74203916,
"author": "Ynjxsjmh",
"author_id": 10315163,
"author_profile": "https://Stackoverflow.com/users/10315163",
"pm_score": 3,
"selected": true,
"text": "dn_x"
},
{
"answer_id": 74204067,
"author": "jezrael",
"author_id": 2901002,
"author_profile":... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16574413/"
] |
74,203,814 | <p>I am trying to remove similar words in a python List by calculating the Levenshtein ratio between them. If the ratio is >0.9 the word should be removed. So I have to create a loop that iterates through the list and compare each word with each other word and then remove them if the ratio is to high. Unfortunately I haven't quite figured out how to implement that in python, since I cannot iterate through a list and remove its contents. My first naive idea was sth. like the code seen below, which doesn't work, since it skips half the elements. Any help would be appreciated.</p>
<pre><code>word_list = ['asf', 'bcd', 'ase', 'cdf', 'asl']
</code></pre>
<p>The Goal here would be to remove the elements 'ase' and 'asl' because they are similar to 'asf'
My first attempt looked like this:</p>
<pre><code>for word in word_list:
for x in word list:
if Levenshtein.ratio(word, x) >= 0.9:
word_list.remove(word)
</code></pre>
| [
{
"answer_id": 74203916,
"author": "Ynjxsjmh",
"author_id": 10315163,
"author_profile": "https://Stackoverflow.com/users/10315163",
"pm_score": 3,
"selected": true,
"text": "dn_x"
},
{
"answer_id": 74204067,
"author": "jezrael",
"author_id": 2901002,
"author_profile":... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20336819/"
] |
74,203,840 | <p>I am trying to represent a basic vector, the following code works in Visual Studio Code.</p>
<p>I am using the following line <code>$\begin{bmatrix}X\\Y\end{bmatrix}$</code></p>
<p>All whitespace removed. It should look like this,</p>
<p><a href="https://i.stack.imgur.com/kDxdg.png" rel="nofollow noreferrer">https://i.stack.imgur.com/kDxdg.png</a></p>
<p>However, when pushed to Github it does not render correctly and instead just renders to entire text letter for letter like it is unsupported. Does anybody know how to get get the following vector to display correctly?</p>
| [
{
"answer_id": 74261826,
"author": "Davide Cervone",
"author_id": 502334,
"author_profile": "https://Stackoverflow.com/users/502334",
"pm_score": 0,
"selected": false,
"text": "$\\left[X\\atopY\\right]$"
},
{
"answer_id": 74368102,
"author": "Jesse H.",
"author_id": 12678... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19253399/"
] |
74,203,892 | <p>Example Snippet:</p>
<pre><code>require "tty-prompt"
require "timeout"
def prompt_with_timeout
prompt = TTY::Prompt.new
timeout_duration = 60
response = ""
Timeout.timeout(timeout_duration, Timeout::Error) do
response = prompt.yes?("Do you agree?")
rescue Timeout::Error => e
puts "Prompt timed out!"
exit 1
end
if response == "yes" || response == "y"
# do something
else
# do something else
end
end
</code></pre>
<p>How would we test the above functionality using RSpec?</p>
<p>I am trying to test the above Timeout functionality using RSpec. I want to write a RSpec test that captures the message from the rescue block.</p>
| [
{
"answer_id": 74205133,
"author": "Roman Van Loo",
"author_id": 9090414,
"author_profile": "https://Stackoverflow.com/users/9090414",
"pm_score": 0,
"selected": false,
"text": "require \"tty-prompt\"\nrequire \"timeout\"\nrequire 'rspec'\n\nTIMEOUT_DURATION = 60\n\ndef prompt_with_timeo... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18835400/"
] |
74,203,928 | <p>I have visual studio 2019.</p>
<ol>
<li>I write some code.</li>
<li>Commit.</li>
<li>Push.</li>
</ol>
<p>Now pending changes are gone.
Is there any way how can I have still all files in pending changes even after push? (all files that differ from main)</p>
| [
{
"answer_id": 74205133,
"author": "Roman Van Loo",
"author_id": 9090414,
"author_profile": "https://Stackoverflow.com/users/9090414",
"pm_score": 0,
"selected": false,
"text": "require \"tty-prompt\"\nrequire \"timeout\"\nrequire 'rspec'\n\nTIMEOUT_DURATION = 60\n\ndef prompt_with_timeo... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16344063/"
] |
74,203,945 | <p>I have one file that looks like below</p>
<pre><code>1234|A|B|C|10|11|12
2345|F|G|H|13|14|15
3456|K|L|M|16|17|18
</code></pre>
<p>I want the output as</p>
<pre><code>1234|A
1234|B
1234|C
2345|F
2345|G
2345|H
3456|K
3456|L
3456|M
</code></pre>
<p>I have tried with the below script.</p>
<pre><code>awk -F"|" '{print $1","$2","$3","$4"}' file.dat | awk -F"," '{OFS=RS;$1=$1}1'
</code></pre>
<p>But the output is generated as below.</p>
<pre><code>1234
A
B
C
2345
F
G
H
3456
K
L
M
</code></pre>
<p>Any help is appreciated.</p>
| [
{
"answer_id": 74204222,
"author": "Jens",
"author_id": 648658,
"author_profile": "https://Stackoverflow.com/users/648658",
"pm_score": 2,
"selected": true,
"text": "$ awk -F\\| '{print $1 \"|\" $2 \"\\n\" $1 \"|\" $3 \"\\n\" $1 \"|\" $4}' file.dat\n1234|A\n1234|B\n1234|C\n2345|F\n2345|G... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6238985/"
] |
74,203,961 | <p>I have a data frame that looks like this:</p>
<pre><code>library(tidyverse)
date = seq(as.Date("2022/1/1"), as.Date("2022/1/12"), by = "day");date
v1 = rnorm(12,0,1);length(date)
v2 = rnorm(12,10,1)
df = data.frame(date,v1,v2);df
date v1 v2
1 2022-01-01 -0.27742001 10.649777
2 2022-01-02 0.45117594 9.552337
3 2022-01-03 -0.57960540 8.377525
4 2022-01-04 0.03795781 9.016521
5 2022-01-05 -0.58670684 10.893805
6 2022-01-06 -0.10260160 10.445416
7 2022-01-07 -0.31061137 9.863794
8 2022-01-08 -0.01944977 8.859400
9 2022-01-09 -0.33269714 10.035201
10 2022-01-10 0.38196430 9.953147
11 2022-01-11 0.72070334 8.328117
12 2022-01-12 -0.71014679 8.046312
</code></pre>
<p>i want to plot the column v2 in the secondary axis.How can i do this in R?</p>
<p>my effort is the following:</p>
<pre><code>p = ggplot()+
geom_line(data =df,aes(x=date,y=v1),size=1)+
scale_x_date(date_labels="%d",date_breaks ="1 day")+
scale_y_continuous(sec.axis = sec_axis(v2, name="v2"));p
</code></pre>
<p>but reports me an error :</p>
<pre><code>Error in `sec_axis()`:
! Can't convert `trans`, a double vector, to a function.
</code></pre>
<p>Any help ?</p>
| [
{
"answer_id": 74204132,
"author": "stefan",
"author_id": 12993861,
"author_profile": "https://Stackoverflow.com/users/12993861",
"pm_score": 3,
"selected": true,
"text": "geom_line"
},
{
"answer_id": 74204510,
"author": "TarJae",
"author_id": 13321647,
"author_profil... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16346449/"
] |
74,203,962 | <p>With 20K records to insert, this is taking about an hour. Is there a way to do a ADO.NET insert in bulk instead of a loop that goes forever?</p>
<pre><code>private async Task InsertReprocessTsk(List<ReprocessTskChngs> reprocessTskChngs)
{
using (SqlConnection conn = new SqlConnection(_connectionString))
{
await conn.OpenAsync();
string insertSql = @"insert into REPROCESS_TSK(CRS, TskLOC, PROCESSED, DATE_ENTERED)
Values(@CRS, @TskLOC, @PROCESSED, GETDATE())";
using SqlTransaction trans = conn.BeginTransaction();
try
{
foreach (ReprocessTskChngs reprocessTskChng in reprocessTskChngs)
{
using (SqlCommand cmd = new SqlCommand(insertSql, conn, trans))
{
cmd.Parameters.Add("@CRS", SqlDbType.SmallInt).Value = reprocessTskChng.CRS;
cmd.Parameters.Add("@TskLOC", SqlDbType.VarChar).Value = reprocessTskChng.TskLOC;
cmd.Parameters.Add("@PROCESSED", SqlDbType.Int).Value = reprocessTskChng.PROCESSED;
await cmd.ExecuteNonQueryAsync();
}
}
await trans.CommitAsync();
}
catch
{
trans.Rollback();
throw;
}
}
}
</code></pre>
<p>I could find ADO.NET bulk copy operations but nothing specific to insert</p>
| [
{
"answer_id": 74204132,
"author": "stefan",
"author_id": 12993861,
"author_profile": "https://Stackoverflow.com/users/12993861",
"pm_score": 3,
"selected": true,
"text": "geom_line"
},
{
"answer_id": 74204510,
"author": "TarJae",
"author_id": 13321647,
"author_profil... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20285480/"
] |
74,203,966 | <p>I have a csv file like these: this csv filled is called df_plane in R</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Situation</th>
<th>flight_uses</th>
<th>People-ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>0</td>
<td>3</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>4</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>4</td>
</tr>
<tr>
<td>3</td>
<td>0</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>0</td>
<td>5</td>
</tr>
<tr>
<td>3</td>
<td>0</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>6</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>6</td>
</tr>
<tr>
<td>3</td>
<td>NA</td>
<td>6</td>
</tr>
<tr>
<td>1</td>
<td>NA</td>
<td>7</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>7</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>7</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>8</td>
</tr>
<tr>
<td>2</td>
<td>0</td>
<td>8</td>
</tr>
<tr>
<td>3</td>
<td>0</td>
<td>8</td>
</tr>
<tr>
<td>1</td>
<td>NA</td>
<td>9</td>
</tr>
<tr>
<td>2</td>
<td>NA</td>
<td>9</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>9</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>10</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>10</td>
</tr>
<tr>
<td>3</td>
<td>0</td>
<td>10</td>
</tr>
<tr>
<td>1</td>
<td>0</td>
<td>11</td>
</tr>
<tr>
<td>2</td>
<td>0</td>
<td>11</td>
</tr>
<tr>
<td>3</td>
<td>0</td>
<td>11</td>
</tr>
</tbody>
</table>
</div>
<p>I would like to find out what percentage of people uses airplane in situation 2. I would like to know if there is a more efficient way than use the code below. Because with the below code I have to calculate it manually.</p>
<pre><code>table(select(df_plane,situation,flight_uses))
</code></pre>
| [
{
"answer_id": 74204133,
"author": "SamR",
"author_id": 12545041,
"author_profile": "https://Stackoverflow.com/users/12545041",
"pm_score": 1,
"selected": true,
"text": "Situation==2"
},
{
"answer_id": 74204147,
"author": "Desmond",
"author_id": 11485370,
"author_prof... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,203,979 | <p>My <strong>HTML</strong> code:</p>
<pre><code><i class="fas fa-desktop-arrow-down fa-fade">&ensp;</i><a href="/app-debug.apk" download>You can download this app from here</a>
</code></pre>
<p>When I run the HTML page, the <code>fontawesome</code> icon doesn't show.</p>
<p>I have also included my kit in my <code>HTML</code> page:</p>
<pre><code><script src="https://kit.fontawesome.com/03d58ba9c7.js" crossorigin="anonymous"></script>
</code></pre>
<p>Where am I going wrong?</p>
| [
{
"answer_id": 74204133,
"author": "SamR",
"author_id": 12545041,
"author_profile": "https://Stackoverflow.com/users/12545041",
"pm_score": 1,
"selected": true,
"text": "Situation==2"
},
{
"answer_id": 74204147,
"author": "Desmond",
"author_id": 11485370,
"author_prof... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,203,987 | <p>I've a div element that acts as a container for other div elements. Those elements display long text that could overflow over many pages. I need that text to be printed after 50mm of the top edge of every physical paper, and only to 20mm prior to the edge of every physical paper. That's why I created the container div element, and tried to set it's top and bottom margins. But my tries failed.</p>
<p>The following video shows the result I need to reach...
<a href="https://www.youtube.com/watch?v=SJ2av3bVtQk" rel="nofollow noreferrer">https://www.youtube.com/watch?v=SJ2av3bVtQk</a>
P.S. My has a background image, and I need that image to be printed from the very top of the page to the very bottom of the page, with no margins applied to it at all.</p>
| [
{
"answer_id": 74236625,
"author": "Shivam kaushal",
"author_id": 13930696,
"author_profile": "https://Stackoverflow.com/users/13930696",
"pm_score": 0,
"selected": false,
"text": "*{\n margin:0;\n padding:0;\n}\n\n.container{\n display:flex;\n flex-direction:column;\n justify-conte... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13389582/"
] |
74,203,992 | <p>I have a .NET MAUI project that was created with VS2022 Preview 2, and it builds without errors or warnings and works as expected in the debugger. Prior to updating Visual Studio to Version 17.4.0 Preview 4.0 I was able to publish the project as a sideloadable MSIX from within VS.</p>
<p>Since updating, I get the following error when I click Create in the Create App Packages wizard:</p>
<pre><code>MSB4057 The target "_GenerateAppxPackage" does not exist in the project.
</code></pre>
<p>The error is listed against the MAUI project's .csproj file.</p>
<p>I've tried creating a separate new, default MAUI project in the new preview - this publishes ok and (as far as I can see) doesn't contain <code>_GenerateAppxPackage</code> anywhere within its files or project structure. So for now I'm assuming this isn't something new that was added with the preview.</p>
<p>I found some references to <code>_GenerateAppxPackage</code> on the web but they appear to refer to Azure integration. My project is a stand-alone data transformation app that doesn't even access the net.</p>
<p>I'm at a loss what to try next. I don't know what this target refers to, where it should "exist" within the project, or what it does. Can anyone help me understand the problem and/or point me to a solution?</p>
<p><strong>Update: 2022-10-28:</strong></p>
<ul>
<li><p>I tried deleting the project structure and creating it from scratch with File -> New Project, then adding back <em>only</em> the .cs and .xaml files. Publishing the recreated project gives me the same error.</p>
</li>
<li><p>I also tried uninstalling the VS preview and re-downloading and installing it. Again, publishing the project gives me the same error.</p>
</li>
</ul>
<p>I still have no idea what is causing this, or even where to start looking.</p>
| [
{
"answer_id": 74446387,
"author": "Alykoff Gali",
"author_id": 1689965,
"author_profile": "https://Stackoverflow.com/users/1689965",
"pm_score": 1,
"selected": false,
"text": "dotnet publish"
}
] | 2022/10/26 | [
"https://Stackoverflow.com/questions/74203992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67316/"
] |
74,204,021 | <p>I'm using {% capture %} in Liquid to capitalize the first letter of each word and this is working as expected. The issue I'm facing is if that sentence contains 'And', I need 'And' <strong>only</strong> to remain lowercase.</p>
<p>I've tried just being quite simple with it by using 'replace' on the final output, but no luck.</p>
<p>Example - I'm capturing 'firstname' on a form - but the user has put in theirs and their partners name all in a mix of up/down case 'jack-ANd-SaLly'</p>
<p>I use the below, which gives me 'Jack And Sally'</p>
<pre><code>{% assign words = contact.data.firstname | replace: '-', ' ' %}
{% assign words = words | split: ' ' %}
{% capture f_name %}
{% for word in words %}
{{ word | capitalize }}
{% endfor %}{% endcapture %}
{{ f_name }}
</code></pre>
<p>I then try this at the end - but I still get 'Jack And Sally'</p>
<pre><code>{{ f_name | replace: ' And ', ' and ' }}
</code></pre>
| [
{
"answer_id": 74446387,
"author": "Alykoff Gali",
"author_id": 1689965,
"author_profile": "https://Stackoverflow.com/users/1689965",
"pm_score": 1,
"selected": false,
"text": "dotnet publish"
}
] | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4875403/"
] |
74,204,031 | <p>My codes was working yesterday but today has not worked.
Error:
**Expected-begin-array-but-was-string-at-line-1-column-28 path $.result **</p>
<p>Mycodes and Classes:</p>
<p>postman result:
<a href="https://i.stack.imgur.com/WjNZ0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WjNZ0.png" alt="enter image description here" /></a></p>
<p>my retrofit:
<a href="https://i.stack.imgur.com/unyvq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/unyvq.png" alt="enter image description here" /></a></p>
<p>my codes and classes:
<a href="https://i.stack.imgur.com/QIfMC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QIfMC.png" alt="enter image description here" /></a></p>
<hr />
<p><a href="https://i.stack.imgur.com/bmfJB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bmfJB.png" alt="enter image description here" /></a></p>
<hr />
<p><a href="https://i.stack.imgur.com/aTQfZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aTQfZ.png" alt="enter image description here" /></a></p>
<hr />
<p><a href="https://i.stack.imgur.com/x9qiB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x9qiB.png" alt="enter image description here" /></a></p>
<p>several times change my codes but nothing result!
Thanks</p>
| [
{
"answer_id": 74204360,
"author": "Leon",
"author_id": 15319257,
"author_profile": "https://Stackoverflow.com/users/15319257",
"pm_score": 0,
"selected": false,
"text": "GsonConverterFactory"
},
{
"answer_id": 74267642,
"author": "Metehandro",
"author_id": 20380509,
... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5863105/"
] |
74,204,039 | <p>Figured it out, i was just missing an return statement</p>
<pre><code>def get_prefix(bot, message):
if message.author.id == 1:
return ["user prefix"]
else:
return ["default prefix"]
</code></pre>
| [
{
"answer_id": 74204360,
"author": "Leon",
"author_id": 15319257,
"author_profile": "https://Stackoverflow.com/users/15319257",
"pm_score": 0,
"selected": false,
"text": "GsonConverterFactory"
},
{
"answer_id": 74267642,
"author": "Metehandro",
"author_id": 20380509,
... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20337001/"
] |
74,204,044 | <p>In my Ros Workspace (ws), there are 3 packages in src folder. And in each package, there is a node (contained in scripts folder) which is written using python. I need to write a roslaunch file that runs all 3 nodes at once.</p>
<p>Folder structure</p>
<pre><code>ws
-src
-pkg1
-scripts/node1.py
-pkg2
-scripts/node2.py
-pkg3
-scripts/node3.py
-launch *#I want to keep the launch file in here.*
</code></pre>
<p>Can someone help me or point me out on how to write the launch file combining multiple packages?</p>
| [
{
"answer_id": 74204360,
"author": "Leon",
"author_id": 15319257,
"author_profile": "https://Stackoverflow.com/users/15319257",
"pm_score": 0,
"selected": false,
"text": "GsonConverterFactory"
},
{
"answer_id": 74267642,
"author": "Metehandro",
"author_id": 20380509,
... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19698020/"
] |
74,204,057 | <p>For context, we have an Azure Virtual Machine that we use to test our app before pushing the changes to production. This VM automatically shutdown every evening to save some energy. Is there a way to make it start when trying to access its DNS name (******.cloudapp.azure.com)? It would be better than starting it at a fixed time every morning but if it is impossible or too complicated, is there a way to make it start at a specified time?</p>
| [
{
"answer_id": 74204360,
"author": "Leon",
"author_id": 15319257,
"author_profile": "https://Stackoverflow.com/users/15319257",
"pm_score": 0,
"selected": false,
"text": "GsonConverterFactory"
},
{
"answer_id": 74267642,
"author": "Metehandro",
"author_id": 20380509,
... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4657751/"
] |
74,204,060 | <p>I'm trying to make a function that does the job of a POS billing section. when an item is clicked to grab and pass the values of an item (name, price, qty ...) to into an object and then the object is passed into the function as an argument. each item should exist only once and if the same item is clicked more than once it should only update the value of the "qty" propertiy by 1 and keep the track. i'm storing all he objects in an array called totalItems. i'm stuck at the qty value updating part it's crashing and getting different kind of issues. please help .</p>
<pre><code>// THIS ARE THE OBJECT PROPERTIES
// {
// img: '',
// name: '',
// price: 0,
// qty: 1
// }
let totalItems = []
const sumTotalItems = (obj) => {
if (totalItems.length) {
totalItems.map((item) => {
if (obj.name === item.name) {
const index = totalItems.indexOf(item)
const newItem = item = {...item, qty: item.qty += 1}
const updatedArray = totalItems.splice(index, 1, newItem)
return totalItems = [...updatedArray]
} else {
return totalItems = [...totalItems, obj]
}
})
} else {
return totalItems = [obj]
}
console.log(totalItems)
}
</code></pre>
| [
{
"answer_id": 74204360,
"author": "Leon",
"author_id": 15319257,
"author_profile": "https://Stackoverflow.com/users/15319257",
"pm_score": 0,
"selected": false,
"text": "GsonConverterFactory"
},
{
"answer_id": 74267642,
"author": "Metehandro",
"author_id": 20380509,
... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20333828/"
] |
74,204,088 | <pre><code>a = [1,2,3,4,4,2,2]
d = {k: v for v, k in enumerate(a)}
print(d)
</code></pre>
<p>Let me rephrase myself.</p>
<p>from the above code what does this line exactly mean.</p>
<pre><code>{k: v for v, k in enumerate(a)}
</code></pre>
| [
{
"answer_id": 74204547,
"author": "Kungfu panda",
"author_id": 15349625,
"author_profile": "https://Stackoverflow.com/users/15349625",
"pm_score": -1,
"selected": true,
"text": "#i have added 10 as a last item in your list for easy understanding.\na = [1,2,3,4,4,2,2,10]\nd = {k: v for ... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20337046/"
] |
74,204,148 | <p>Show the provinces that has more patients identified as 'M' than 'F'. Must only show full province_name</p>
<p><strong>patient table :</strong>
patient_id INT
first_name TEXT
last_name TEXT
gender CHAR(1)
birth_date DATE
city TEXT
province_id CHAR(2)
allergies TEXT
height INT
weight INT</p>
<p><strong>Province_names table:</strong>
province_id CHAR(2)
province_name TEXT</p>
<p>I tried this but it's not working.</p>
<pre><code>`select province_name
from patients p,province_names pn
where p.province_id = pn.province_id
and (count(p.province_id) group by p.patient_id having p.gender = 'M' ) >
(count(p.province_id) group by p.patient_id having p.gender = 'F') `
</code></pre>
| [
{
"answer_id": 74204190,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "SELECT pn.province_name\nFROM province_names pn\nINNER JOIN patients p\n ON p.province_id = pn.province_i... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16457569/"
] |
74,204,167 | <p>I have a WordPress website and following a change of theme I have to modify the structure of a thousand links present on about fifty pages. I would like to do it in SQL via PHPMYADMIN.</p>
<p>Is there a way in SQL to remove the end of all my link with the following structure :</p>
<pre><code>- <a href="https://website.com/cours/les-problemes/lecon/s1-2014-2015-mathematiques-les-problemes/">
- <a href="https://website.com/cours/la-division/lecon/s3-2014-2015-mathematiques-la-division-n-nakatani/">
- <a href="https://website.com/cours/mathematiques-larithmetique/lecon/201819-s5-fa-mathematiques-nathalie-nakatani/">
</code></pre>
<p>In order to only get :</p>
<pre><code>- <a href="https://website.com/cours/les-problemes/">
- <a href="https://website.com/cours/la-division/">
- <a href="https://website.com/cours/mathematiques-larithmetique/">
</code></pre>
<p>I tried to use the answer of this topic : <a href="https://stackoverflow.com/questions/23726256/mysql-replace-string-between-two-known-strings">MYSQL Replace string between two known strings</a> but I did not manage to find a solution to fit my purpose.</p>
<p>I also thought about doing it in two parts :
1- Remove the content between the '<strong>/lecon/</strong>' and the '<strong>"></strong>'.
2- Then remove completely all the iteration of '/lecon/' of my pages, because they only occur on the links that I want to edit.
But my knowledges in SQL are limited and I have no clue of how to do the first part.</p>
<p>My apologizes for my English.</p>
<p>Thanks in avance for any helps !</p>
| [
{
"answer_id": 74204190,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "SELECT pn.province_name\nFROM province_names pn\nINNER JOIN patients p\n ON p.province_id = pn.province_i... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17781472/"
] |
74,204,192 | <p>I'm trying to get todays date in the format %d/%m/%y without converting to a string. I still want to have the date as the data type.</p>
<p>Following code returns an str</p>
<pre><code>today = date.today().strftime('%d/%m/%y')
print(type(today))
</code></pre>
| [
{
"answer_id": 74204190,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "SELECT pn.province_name\nFROM province_names pn\nINNER JOIN patients p\n ON p.province_id = pn.province_i... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1020623/"
] |
74,204,248 | <p>first post here, so hello to everyone!</p>
<p>I'm having trouble with mongoose populate because it's apparently doing nothing. I'm going straight to the code.</p>
<p>Here are my models:</p>
<p>Space</p>
<pre><code>const spaceSchema = Schema(
{
user: {
type: Schema.Types.ObjectId,
required: true,
ref: "User",
},
name: {
type: String,
required: true,
},
days: [{ type: Schema.Types.ObjectId, refPath: "Day" }],
},
{
versionKey: false,
timestamps: true
},
);
const Space = mongoose.model("Space", spaceSchema);
module.exports = Space;
</code></pre>
<p>Day</p>
<pre><code>const daySchema = Schema(
{
space: { type: Schema.Types.ObjectId, refPath: "Space" },
date: {
type: String,
required: true,
},
water: {
type: Boolean,
},
fertilizer: {
type: Boolean,
},
transplant: {
type: Boolean,
},
comment: {
type: String,
},
},
{
versionKey: false,
timestamps: true
},
);
const Day = mongoose.model("Day", daySchema);
module.exports = Day;
</code></pre>
<p>And the part of the controller where I have the getSpace route (/api/spaces/:id):</p>
<pre><code>const getSpace = asyncHandler(async (req, res) => {
const space = await Space.findById(req.params.id).populate("days");
res.status(200).json(space);
});
</code></pre>
<p>And this is the result I get:</p>
<pre><code>{
"_id": "63580115978dbf8f2f5a7a50",
"user": "63501ab84613855834daa4ef",
"name": "spaceName",
"days": []
}
</code></pre>
<p>I tried many things, but all the results were the same.</p>
<p>Let me know if you need any other part of the code.</p>
<p>Thank you all :D</p>
<p>I expect the result to look something like this</p>
<pre><code> "space": {
"_id": "63580115978dbf8f2f5a7a50",
"user": "63501ab84613855834daa4ef",
"name": "spaceName",
"days": [
{
"_id": "63581af565aed8cad3210046",
"space": "63580115978dbf8f2f5a7a50",
"date": "29/10/2022",
"water": true,
"fertilizer": true,
"transplant": false,
"comment": "This is a comment.",
"createdAt": ...,
"updatedAt": ...
},
{
"_id": "63581af565aed8cad3210046",
"space": "63580115978dbf8f2f5a7a50",
"date": "29/10/2022",
"water": false,
"fertilizer": false,
"transplant": true,
"comment": "This is a comment.",
"createdAt": ...,
"updatedAt": ...
}
]
}
</code></pre>
| [
{
"answer_id": 74204190,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "SELECT pn.province_name\nFROM province_names pn\nINNER JOIN patients p\n ON p.province_id = pn.province_i... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13576205/"
] |
74,204,278 | <h1>Data Types</h1>
<ul>
<li><code>Title</code>: string</li>
<li><code>Keywords</code>: string</li>
<li><code>Description</code>: string</li>
</ul>
<h1>Search Requirements:</h1>
<ol>
<li>ALL search terms MUST be found somewhere in the title or keywords or description
<ul>
<li>Don’t search the whole DOCUMENT for terms… but search SEVERAL FIELDS to find a match for the terms.
<ul>
<li>All the fields don’t need to contain all the search terms, but all the search terms must be found</li>
<li>EG: searching for “bake cake” should match:
<ul>
<li>title contains “cake” and description contains “bake” so that BOTH terms are found</li>
</ul>
</li>
<li>Because atlas search grammar did not allow us to do that, we created a concat field: title + keywords into a NEW field</li>
<li>The biggest problem we have seems to follow from the fact that we cannot get a good AND clause on our search terms
<ul>
<li>“bake cake” should match “bake” AND “cake”, instead, using Atlas search without our hacks we will get</li>
<li>“cake cake cake cake” and that ranks higher than “cake bake”!</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>Field boosting is important
<ul>
<li>Matching in the “title” should rank higher than matching in the “description”</li>
</ul>
</li>
<li>Word order matters
<ul>
<li>“bake cake” should boost results where “bake” precedes “cake”</li>
<li>A perfect match is preferred</li>
</ul>
</li>
<li>Keyword stuffing should be penalised.
<ul>
<li>After computing a score, the score should be un-boosted based on frequency of matching the search terms</li>
<li>“bake cake” should rank “bake a cake” HIGHER than “bake a cake bake a cake cake cake cake”</li>
</ul>
</li>
<li>Shorter data should rank higher
<ul>
<li>“cake” as a search term should rank
<ul>
<li>“cake fun” higher than</li>
<li>“cake and fun and baking and frosting”</li>
<li>Because all else equal, the first string is SHORTER than the second string</li>
</ul>
</li>
</ul>
</li>
<li>Stemming matters (plurals in particular)
<ul>
<li>this currently does NOT work in our current implementation b/c we had to hack around Atlas to get proper AND matching for search terms</li>
</ul>
</li>
</ol>
<p>I have tried to achieve the above by using MongoDB Atlas, but have not been successfull. Hence I am looking at alternatives such as ElasticSearch, Solr etc for the same. I am also open to evaluating any other similar platform as well.</p>
| [
{
"answer_id": 74204190,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "SELECT pn.province_name\nFROM province_names pn\nINNER JOIN patients p\n ON p.province_id = pn.province_i... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7140670/"
] |
74,204,298 | <p>I'm looking for a way to visualize the surface between a number of straight lines, which are defined in a dataframe through their intercepts and slopes. The surface I am looking for is the one that encloses the origin (0, 0).</p>
<p>The number of lines may vary (even though in the following simplified example I only have 6), and some of them may be redundant (i.e. they do not enclose the surface I am looking for because other lines are more constraining).</p>
<p>Let's take this simple dataframe:</p>
<pre><code>df <- data.frame("Line" = c("A", "B", "C", "D", "E", "F"),
"Intercept" = c(4, 3, -2.5, -1.5, -5, -.5),
"Slope" = c(-1, 1, 2.4, -.6, -.8, .6))
</code></pre>
<p>Plotting these lines with <code>ggplot2</code>:</p>
<pre><code>ggplot(data = df) +
geom_vline(xintercept = 0) +
geom_hline(yintercept = 0) +
geom_abline(mapping = aes(intercept = Intercept, slope = Slope),
colour = "red") +
coord_cartesian(xlim = c(-6, 6), ylim = c(-6, 6))
</code></pre>
<p>Gives me the following output:</p>
<p><a href="https://i.stack.imgur.com/7Fbyv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7Fbyv.png" alt="ggplot output for diagonal lines with geom_abline()" /></a></p>
<p>Basically I want to find intersections between the lines that enclose the origin (0, 0), disregarding the redundant one (the bottom left in this case, with intercept = -5 and slope = -0.8). Those 5 intersection points would then be used to plot the convex hull.</p>
<p>My main problem lies in finding the intersection points <strong>of the constraining lines</strong> (green points below) in order to be able to find the blue surface.</p>
<p><a href="https://i.stack.imgur.com/Qj6HN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qj6HN.png" alt="ggplot output for diagonal lines with geom_abline including intersection points and surface" /></a></p>
<p><strong>QUESTION:</strong> Any suggestions on how to deal with this in R, ideally in a way that can be extended to larger dataframes (including more constraining and redundant lines)?</p>
<p><strong>ADDITIONAL QUESTION:</strong> <code>geom_abline()</code> does not have a <em>group</em> aesthetic similar to <code>geom_line()</code>, which could be used to identify the line. Does anyone know a workaround to draw straight lines in <code>ggplot2</code> based on slopes and intercepts (or two user-defined points of the line)?</p>
<p>Thanks in advance for any suggestions or (parts of) potential solutions!</p>
| [
{
"answer_id": 74206172,
"author": "Limey",
"author_id": 13434871,
"author_profile": "https://Stackoverflow.com/users/13434871",
"pm_score": 2,
"selected": false,
"text": "combn"
},
{
"answer_id": 74350172,
"author": "Allan Cameron",
"author_id": 12500315,
"author_pro... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330988/"
] |
74,204,305 | <p>I am using AWS Simple Email Service (SES), however I want to have a very tightly restricted policy.
I want to set up a policy to</p>
<ul>
<li>only be able to send emails to a domain (mydomain)</li>
<li>from a specific (internal@mydomain.com) email address</li>
<li>using a specific configuration set (internalonly)</li>
</ul>
<p>I have tried the entry below, but it is not restricting the recipients. I cant see what Im doing wrongly.</p>
<p>Ive been chewing this one for a few days, and need some help. Can anyone point me in the right direction?</p>
<pre><code>{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "ses:SendRawEmail",
"Resource": "arn:aws:ses:eu-west-1:999999999:identity/internal@mydomain.com",
"Condition": {
"StringLike": {
"ses:FromAddress": "internal@mydomain.com"
},
"ForAllValues:StringLike": {
"ses:Recipients": "*@mydomain.com"
}
}
},
{
"Effect": "Allow",
"Action": "ses:SendRawEmail",
"Resource": "arn:aws:ses:eu-west-1:99999999999:configuration-set/internalonly",
"Condition": {
"StringLike": {
"ses:FromAddress": "internal@mydomain.com"
},
"ForAllValues:StringLike": {
"ses:Recipients": "*@mydomain.com"
}
}
}
]
}
</code></pre>
<p>Following applying the policy, I tested this using the details here: <a href="https://docs.aws.amazon.com/ses/latest/dg/send-email-smtp-client-command-line.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/ses/latest/dg/send-email-smtp-client-command-line.html</a></p>
<p>Sample test file ses-internal.txt</p>
<pre><code>EHLO mydomain.com
AUTH LOGIN
Base64EncodedSMTPUserName
Base64EncodedSMTPPassword
MAIL FROM: internal@mydomain.com
RCPT TO: internal@mydomain.com
DATA
X-SES-CONFIGURATION-SET: internalonly
From: PM Access <internal@mydomain.com>
To: luke@otherdomain.com
Subject: Amazon SES SMTP Test to luke
This message was sent using the Amazon SES SMTP interface.
.
QUIT
</code></pre>
<p>Testing: works when it should prevent me sending to luke@otherdomain.com</p>
<pre><code>% openssl s_client -crlf -quiet -starttls smtp -connect email-smtp.<region>.amazonaws.com:587 < ses-internal.txt
depth=4 C = US, O = "Starfield Technologies, Inc.", OU = Starfield Class 2 Certification Authority
verify return:1
depth=3 C = US, ST = Arizona, L = Scottsdale, O = "Starfield Technologies, Inc.", CN = Starfield Services Root Certificate Authority - G2
verify return:1
depth=2 C = US, O = Amazon, CN = Amazon Root CA 1
verify return:1
depth=1 C = US, O = Amazon, OU = Server CA 1B, CN = Amazon
verify return:1
depth=0 CN = email-smtp.<region>.amazonaws.com
verify return:1
250 Ok
250-email-smtp.amazonaws.com
250-8BITMIME
250-STARTTLS
250-AUTH PLAIN LOGIN
250 Ok
334 VXNlcm5hbWU6
334 UGFzc3dvcmQ6
235 Authentication successful.
250 Ok
250 Ok
354 End data with <CR><LF>.<CR><LF>
250 Ok 01020184133e8041-ba607190-5bf0-4610-9280-bbc38b9cb074-000000
451 4.4.2 Timeout waiting for data from client.
</code></pre>
| [
{
"answer_id": 74206189,
"author": "baduker",
"author_id": 6106791,
"author_profile": "https://Stackoverflow.com/users/6106791",
"pm_score": 0,
"selected": false,
"text": "{\n \"Version\":\"2012-10-17\",\n \"Statement\":[\n {\n \"Sid\":\"AuthorizeAWS\",\n \"Effect\":\"Allo... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1727068/"
] |
74,204,311 | <pre><code>#include <iostream>
static float balance = 30000.0;
void deposit(float amount) {
if (amount < 0.0 && amount > 100000.0 ) {
printf("Error invalid amount entered ");
}
else {
balance += amount;
}
}
float withdrawal(float withdrawal) {
if (balance == 0.0)
printf("NO MONEY BROKIE");
if (withdrawal < 17000.0) {
printf("Error invalid amount entered ");
}
if (balance <= withdrawal) {
withdrawal = balance;
balance = 0;
}
balance -= withdrawal;
return withdrawal;
}
void Check() {
printf("Your Account Balance is : %f ", &balance);
}
int main()
{
float amount;
int task;
printf(" 1. Check Balance \n 2. Deposit \n 3. Withdrawal");
printf(" \n\nPlease note :\nThe deposit amount must not be greater than $100,000 ");
printf("\nThe withdrawal amount must not be greater than $17,000 ");
printf("\n\nWhat service would you like to perform : ");
scanf_s("%d", &task);
if (task == 1) {
Check();
}
else if (task == 2) {
printf("Enter the amount you would like to deposit : ");
scanf_s("%f", &amount);
deposit(amount);
printf("Thanks for doing business you have deposited %f ", &amount );
}
else if (task == 3) {
printf("Enter the amount you would like to withdraw : ");
scanf_s("%f", &amount);
float Withdrawal = withdrawal(amount);
printf("Thanks for doing business you have withdrawn : %f ", &Withdrawal);
}
else {
printf("Invalid task number !");
}
}
</code></pre>
<p>I was expecting it to function.
Why is balance 0.0000 when I run and any other errors I might have missed
Im new so
more details more details more details
more details more details why is it asking for more detail ..................................................................................................................</p>
| [
{
"answer_id": 74204346,
"author": "selbie",
"author_id": 104458,
"author_profile": "https://Stackoverflow.com/users/104458",
"pm_score": 2,
"selected": false,
"text": "printf(\"Your Account Balance is : %f \", &balance);\n"
},
{
"answer_id": 74204426,
"author": "Saad Rehman"... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20337161/"
] |
74,204,348 | <p>Suppose to have an array like this:</p>
<pre><code>[1,2,3,4,5,6]
</code></pre>
<p>and another one like this (rotated):</p>
<pre><code>[3,4,5,6,1,2]
</code></pre>
<p>Is there any easy way to tell that they are equal or shall I write a specific method to compare them?</p>
<p><strong>EDIT:</strong> of course, the first array should NOT be equal with:</p>
<pre><code>[4,3,5,6,1,2] // 4 and 3 are swapped
[1,2,4,3,5,6] // 4 and 3 are swapped
</code></pre>
<p>or</p>
<pre><code>[1,2,3,4,5,6,7] // too many items
</code></pre>
| [
{
"answer_id": 74204540,
"author": "hossein sabziani",
"author_id": 4301195,
"author_profile": "https://Stackoverflow.com/users/4301195",
"pm_score": 0,
"selected": false,
"text": "first item of the second"
},
{
"answer_id": 74205042,
"author": "Dmitry Bychenko",
"author_... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261010/"
] |
74,204,352 | <p>I refer to a similar problem <a href="https://stackoverflow.com/questions/72227242/changing-transporterfleet-based-on-programmaticaly-created-schedule">here</a>.</p>
<p>I implemented a programmatically created schedule same as in the example model from AnyLogic Cloud. Then I added the suggested code in the capacity field.</p>
<p>Still, my problem is the following runtime error: "The parameter capacitySchedule cannot be changed dynamically". Does it just basically does not work with the resource pool compared to the Transporter Fleet presented in the similar problem? Unfortunately it does not work with a fake schedule either.</p>
<p>Here are some screenshots from my model. Thanks in advance.</p>
<p><a href="https://i.stack.imgur.com/NedkW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NedkW.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/HWLrW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HWLrW.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74206641,
"author": "Benjamin",
"author_id": 2164728,
"author_profile": "https://Stackoverflow.com/users/2164728",
"pm_score": 1,
"selected": false,
"text": "fakeSchedule"
}
] | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19247020/"
] |
74,204,365 | <p>I have the following two dataframes</p>
<pre><code>df <- data.frame(Groesse=c("A", "B", "C", "D"),
x=c(0, 1, 30, 25),
y=c(0, 90, 85, 20))
df_text <- data.frame(Groesse=c("X", "Y"),
x=c(1, 30),
y=c(105, 105))
</code></pre>
<p>and tried to achieve what I want with the following:</p>
<pre><code>plot <- ggplot(df) +
geom_point(aes(x, y)) +
geom_text(data = df_text, aes(x, y, label = "Groesse")) +
scale_y_continuous(limits = c(0,100), expand = c(0,0)) +
coord_cartesian(clip = "off") +
theme(plot.margin = unit(c(10, 1, 1, 1), "lines"))
plot
</code></pre>
<p>I would like to have the annotations (using <code>geom_text()</code>) to be above the scatterplot, but outside of the plot area. However, my plot is missing the values from <code>geom_text()</code>.</p>
<p><a href="https://i.stack.imgur.com/vpEz2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vpEz2.jpg" alt="Plot without text" /></a></p>
<p>Desired output (just a sketch):</p>
<p><a href="https://i.stack.imgur.com/vKbA4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vKbA4.png" alt="Desired Output" /></a></p>
<p>Any idea how I can add the text outside the plot area without producing two different plots and then combining those in a grid?</p>
| [
{
"answer_id": 74204461,
"author": "SamR",
"author_id": 12545041,
"author_profile": "https://Stackoverflow.com/users/12545041",
"pm_score": 0,
"selected": false,
"text": "gridExtra"
},
{
"answer_id": 74204487,
"author": "Ritchie Sacramento",
"author_id": 2835261,
"aut... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7952111/"
] |
74,204,376 | <p>I'm having a hard time understanding why using a increment operator in a for loop in C++ has a different result than doing 'variable' + 1. The variable in the second case simply isn't remembered after each iteration of the loop:</p>
<p>Take the following code:</p>
<pre><code>#include <iostream>
int main(){
int a{0};
for (int i = 0; i < 5; i++){
std::cout << ++a;
}
return 0;
}
</code></pre>
<p>It outputs as expected:
12345</p>
<p>However, if I instead replace ++a with a + 1:</p>
<pre><code>#include <iostream>
int main(){
int a{0};
for (int i = 0; i < 5; i++){
std::cout << a + 1;
}
return 0;
}
</code></pre>
<p>I get:
11111</p>
<p>Even if I make the 'a' variable static:</p>
<pre><code>static int a{0};
</code></pre>
<p>It still outputs 11111.</p>
<p>Why doesn't 'a + 1' preserve its value after every loop? What would I need to do if I wanted to preserve its value after every iteration without using ++ (for instance, with another operation like a * 2)?</p>
| [
{
"answer_id": 74204417,
"author": "Yves Daoust",
"author_id": 1196549,
"author_profile": "https://Stackoverflow.com/users/1196549",
"pm_score": 1,
"selected": false,
"text": "++a"
},
{
"answer_id": 74204454,
"author": "Jason Liam",
"author_id": 12002570,
"author_prof... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20337080/"
] |
74,204,406 | <p>I am going to make event time list where duplicate date time and starting time of a next event is starts before ending time of a previous event does not exist in the list.
I converted date time to Julian date. And the list is as below:</p>
<pre><code>Before converting to Julian date:
timename starttime endtime
1 20170103 2017/01/03T05:36:05 2017/01/03T13:42:04
2 20170103 2017/01/03T14:00:04 2017/01/03T20:30:07
3 20170112 2017/01/12T16:24:05 2017/01/12T23:42:05
4 20170114 2017/01/14T05:00:05 2017/01/14T09:42:06
5 20170114 2017/01/14T08:24:05 2017/01/14T14:18:05
6 20170117 2017/01/17T21:49:12 2017/01/18T02:30:06
7 20170119 2017/01/19T12:24:05 2017/01/19T18:30:06
8 20170124 2017/01/24T15:36:05 2017/01/25T04:42:07
9 20170125 2017/01/25T16:00:05 2017/01/26T14:30:05
...
</code></pre>
<pre><code>After converting to Julian date:
timename starttime endtime
1 2457756.5 2457756.733391204 2457757.07087963
2 2457756.5 2457757.0833796295 2457757.354247685
3 2457765.5 2457766.1833912036 2457766.4875578703
4 2457767.5 2457767.7083912035 2457767.9042361113
5 2457767.5 2457767.85005787 2457768.0958912037
6 2457770.5 2457771.4091666667 2457771.604236111
7 2457772.5 2457773.016724537 2457773.2709027776
8 2457777.5 2457778.1500578704 2457778.695914352
9 2457778.5 2457779.166724537 2457780.104224537
...
</code></pre>
<p>I want to remove if first row of strattime and endtime includes second row start time. Otherwise, skip. For example, you can see that the 5th row starttime (2017/01/14T08:24:05) is starts before the 4th row endtime (2017/01/14T09:42:06). So it includes 5th row starttime. But I need to remove them and get only times which starts after previous endtime.</p>
<p>Here is my attempt.</p>
<pre><code>import itertools
import pandas as pd
infilename2 = 'D:/My works/C3_jdate/2017.txt'
outfilename2 = 'D:/My works/2017_1.txt'
lines_seen = set()
outfile = open(outfilename2, "w")
df = pd.read_csv(infilename2,sep = '\t', engine='python', header=0)
t = df['timename']
t1 = df['timename']
st = df['starttime']
et = df['endtime']
for i in range(len(df)):
for j in range(i+1, len(df)):
if t[i] != t1[j]:
pass
elif t[i] == t1[j]:
if (st[i]<st[j] and et[i]<=st[j]):
line1 = df.to_string()
if line1 not in lines_seen:
outfile.write(line1)
lines_seen.add(line1)
outfile.close()
</code></pre>
<p>But still, output is the same with input.
Please share any idea for this problem.</p>
| [
{
"answer_id": 74205350,
"author": "Tim",
"author_id": 13577373,
"author_profile": "https://Stackoverflow.com/users/13577373",
"pm_score": 1,
"selected": false,
"text": "# Get time between current start and last end\ntime_from_last_endtime = df[\"starttime\"] - df[\"endtime\"].shift(fill... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19990966/"
] |
74,204,442 | <p>Hi I'd like to check if a value starts with one of the value of a another column.</p>
<pre><code>t1 | t2
----------
3253 | 123
1234 | 000
9876 | 932
</code></pre>
<p>So here for example I should have True for the value 1234 because it starts with <code>123</code>.
I should have false for the other values.</p>
<p>I can't find any solutions.
Thank you in advance for you help !</p>
<p>I already tried :</p>
<pre><code>t1 LIKE (t2 || '%')
starts_with(t1,t2)
starts_with(t1, (select t2))
</code></pre>
| [
{
"answer_id": 74205350,
"author": "Tim",
"author_id": 13577373,
"author_profile": "https://Stackoverflow.com/users/13577373",
"pm_score": 1,
"selected": false,
"text": "# Get time between current start and last end\ntime_from_last_endtime = df[\"starttime\"] - df[\"endtime\"].shift(fill... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20337244/"
] |
74,204,474 | <p>I am new to socket.io. I am working on a real-time notification feature using socket.io. Everything is working fine. But when reloading the browser the socketId of the user is changed and the notification feature is not working. My question is how to track the new socketId when the browser refresh.</p>
<pre><code>//server.js-> socket.io code
const io = new Server(server, {
cors: {
origin: "http://localhost:3000",
},
});
let onlineUsers: any = [];
const addNewUser = (username: any, socketId: any) => {
!onlineUsers.some((user: any) => user.username === username) &&
onlineUsers.push({ username, socketId });
console.log("o", onlineUsers);
};
const getUser = (username: any) => {
return onlineUsers.find((user: any) => user.username === username);
};
io.on("connection", (socket) => {
console.log("a user connected");
console.log(socket.id);
socket.on("newUser", (username: any) => {
console.log("username", username);
// console.log("socketId", socket);
addNewUser(username, socket.id);
});
socket.on("sendNotification", ({ senderName, receiverName, action }) => {
const receiver = getUser(receiverName);
io.to(receiver?.socketId).emit("getNotification", {
senderName,
action,
});
});
socket.on("disconnect", () => {
console.log("user disconnected");
});
});
</code></pre>
<pre><code>//client side socket.io code
useEffect(() => {
setSocket(io("http://localhost:5000"));
}, []);
useEffect(() => {
const userData: any = localStorage.getItem("user");
setUser(JSON.parse(userData)?.name);
// console.log("userId", userId, socket.emit);
if (user) {
socket?.emit("newUser", user);
}
}, [socket, user]);
</code></pre>
<pre><code>//navbar component
React.useEffect(() => {
socket?.on("getNotification", (data: any) => {
console.log("data2", data);
setNotifications((prev): any => [...prev, data]);
});
}, [socket]);
</code></pre>
<p>Please try to elaborate on your answer/ suggestion or reference.</p>
| [
{
"answer_id": 74205350,
"author": "Tim",
"author_id": 13577373,
"author_profile": "https://Stackoverflow.com/users/13577373",
"pm_score": 1,
"selected": false,
"text": "# Get time between current start and last end\ntime_from_last_endtime = df[\"starttime\"] - df[\"endtime\"].shift(fill... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12874095/"
] |
74,204,486 | <p>I have an "On/Off" field (default is Off).
I have a text field, which is Hidden when my On/Off is Off. When it is On, the text field is visible and mandatory.</p>
<p>However when I try to submit form, with On/Off being Off, the form returns error saying required field not filled.</p>
<p>I cannot see the required text field, because the visible property condition of the text field is working as intended.</p>
<p><a href="https://i.stack.imgur.com/TWcgj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TWcgj.png" alt="" /></a></p>
<p>When I turn it On the text field becomes visible and it is highlighted in red as required.</p>
<p><a href="https://i.stack.imgur.com/PLydU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PLydU.png" alt="" /></a></p>
<p>Now why would that happen?</p>
<p>The text fields required and visible properties are both "DataCardValue2.Value = true". So the condtitions for making the field visible and mandatory are the same, but the field is hidden and required...</p>
<p><a href="https://i.stack.imgur.com/MEzoc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MEzoc.png" alt="" /></a>
<a href="https://i.stack.imgur.com/pjlTH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pjlTH.png" alt="" /></a></p>
<p>It is as if the text field's required property is evaluating DataCardValue2.Value as true while the same fields visible property is evaluating DataCardValue2.Value as false.</p>
<p>The text field is NOT set as mandatory on the SharePoint List. I thought that might be it, but then I checked...</p>
<p>ATTEMPT:
I have tried to set the text fields required property to</p>
<p>"Bestilling_Navn_DataCard1.Visible = true"</p>
<p>Bestilling_Navn_DataCard1 is itself. It was required, even when it was Hidden.
I am officially confused :-)</p>
<p>EDIT: Formatting</p>
| [
{
"answer_id": 74226721,
"author": "Ganesh Sanap",
"author_id": 8624276,
"author_profile": "https://Stackoverflow.com/users/8624276",
"pm_score": 1,
"selected": false,
"text": "Required"
}
] | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20109661/"
] |
74,204,496 | <p>I have lots of calls against a REST API that i want handled the same way.
Perform call, check if not authenticated. Refresh Token call again or if we hit rate
limit despite rate limit function. Sleep and perform call again.</p>
<p>I would like to wrap this in a function that can be called in the way</p>
<pre><code> ReturnType returnVal= handleIntegration(ReturnType , functionToBecCalled)
</code></pre>
<p>How can this be achieved?</p>
<p>For the example below something like</p>
<pre><code>CustomersResponse customersReponse = handleIntegration(CustomersResponse , connection.customers.findCustomersResponse())
EmployeesReponse employeesRepsonse = handleIntegration(EmployeeResponse , connection.employees.findEmployeesResponse())
</code></pre>
<p>//Current Code</p>
<pre><code> bucket.consume();
CustomersResponse customersResponse = null;
try {
customersResponse = connection.customers.findCustomersResponse();
} catch (IntegrationException e) {
if (e.getStatusCode() == 401) {
this.newAccessFromRefreshToken();
customersResponse = connection.customers.findCustomersResponse();
}else if (e.getStatusCode() == 429){
Thread.sleep(500);
customersResponse = connection.customers.findCustomersResponse();
}else
throw e;
}
bucket.consume();
EmployeeResponse employeeResponse = null;
try {
employeeResponse = connection.employees.findEmployeesResponse();
} catch (IntegrationException e) {
if (e.getStatusCode() == 401) {
this.newAccessFromRefreshToken();
employeeResponse = connection.employees.findEmployeesResponse();
}else if (e.getStatusCode() == 429){
Thread.sleep(500);
employeeResponse = connection.employees.findEmployeesResponse();
}else
throw e;
}
</code></pre>
| [
{
"answer_id": 74205086,
"author": "Nikos Paraskevopoulos",
"author_id": 2764255,
"author_profile": "https://Stackoverflow.com/users/2764255",
"pm_score": 2,
"selected": true,
"text": "<T> T handleIntegration(Supplier<T> method) {\n bucket.consume(); // I don't know how this fits - BEWA... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1026005/"
] |
74,204,500 | <p>i can think how can you make a list with months from current'octomber' to previous etc etc, this list can have 12 months from now octomber 2022 to november 2021.
not hardcoded, automated.</p>
| [
{
"answer_id": 74204699,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 3,
"selected": true,
"text": "List months = [];\nfor (var i = 0; i < 12; i++) {\n var monthNumber = (DateTime.now().month - i);\n var month... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19778883/"
] |
74,204,502 | <p>i'm getting the following error. i don't know why</p>
<pre><code>ValueError Traceback (most recent call last)
<ipython-input-70-47db790ecefc> in <module>
2 #Y = train_label.to_numpy()
3
----> 4 logreg = LogisticRegression().fit(train_X, train_Y)
4 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/generic.py in __array__(self, dtype)
1991
1992 def __array__(self, dtype: NpDtype | None = None) -> np.ndarray:
-> 1993 return np.asarray(self._values, dtype=dtype)
1994
1995 def __array_wrap__(
ValueError: could not convert string to float: '"840343879668908032"'
</code></pre>
<p>this is the code i tried to execute</p>
<pre><code>X = train_attr.to_numpy()
Y = train_label.to_numpy()
logreg = LogisticRegression().fit(train_X, train_Y)
</code></pre>
| [
{
"answer_id": 74204699,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 3,
"selected": true,
"text": "List months = [];\nfor (var i = 0; i < 12; i++) {\n var monthNumber = (DateTime.now().month - i);\n var month... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20337325/"
] |
74,204,515 | <p>I am a beginner and starting to learn MongoDB, NodeJS and Express by creating a simple blog project. I facing a problem as my data cannot be stored in my MongoDB event though my MongoDB connects properly. There may be a mistake in my coding in index.js. I try to fix it, but it does not store the information that I submit in the blog. Please help me. Thank you.</p>
<p>This is my code in index.js. You can see my full file in this link if you want to test it. <a href="https://drive.google.com/drive/folders/1MF5eTrsN2Ry5nIaf-ay-JJJvc9H4gH9G?usp=sharing" rel="nofollow noreferrer">enter link description here</a></p>
<p>This is my index.js</p>
<pre><code>const express = require('express')
const path = require('path')
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/my_database',{useNewUrlParser: true})
const app = new express()
const ejs = require('ejs')
const BlogPost = require('./models/BlogPost')
app.set('view engine', 'ejs')
app.use(express.static('public'))
const bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))
const { error } = require('console')
app.listen(4000, () => {
console.log('App listening on port 4000')
});
app.get('/',(req,res)=>{
res.render('index')
})
app.get('/about', (req, res) => {
res.render('about');
});
app.get('/contact', (req, res) => {
res.render('contact');
});
app.get('/post',(req,res)=>{
res.render('post')
})
app.get('/posts/new',(req,res)=>{
res.render('create')
})
app.post('/posts/store',(req,res)=>{
BlogPost.create(req.body,(error,blogpost)=>{
res.redirect('/');
});
});
</code></pre>
<p>This what it show in my MongoDB compass</p>
<p><a href="https://i.stack.imgur.com/aYWrA.png" rel="nofollow noreferrer">enter image description here</a></p>
| [
{
"answer_id": 74204699,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 3,
"selected": true,
"text": "List months = [];\nfor (var i = 0; i < 12; i++) {\n var monthNumber = (DateTime.now().month - i);\n var month... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20280089/"
] |
74,204,551 | <p>I want to deal with multi condition with switch. Here is my code:</p>
<pre><code>string i="a1";
switch (i)
{
case string X when X.Contains("a", StringComparison.OrdinalIgnoreCase):
case string Y when Y.Contains("b", StringComparison.OrdinalIgnoreCase):
case string Z when Z.Contains("c", StringComparison.OrdinalIgnoreCase):
case string A when A.Contains("d", StringComparison.OrdinalIgnoreCase):
{
//some logic
break;
}
case string X when X.Contains("e", StringComparison.Ordinal):
{
//some logic
break;
}
}
</code></pre>
<p>As you see, the variable X/Y/Z/A in the switch statement is useless for me while I have to declare them every time.</p>
<p>Is there any way I can achieve it without declaring so many useless variables?</p>
| [
{
"answer_id": 74204597,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "i"
},
{
"answer_id": 74204650,
"author": "Matthew Watson",
"author_id": 106159,
"author_profile": "... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7697261/"
] |
74,204,559 | <p>Take the below code as an example.</p>
<pre><code>import { useEffect, useState } from "react";
export default function Stopwatch(){
const [stopwatch, setStopwatch] = useState(0);
function updateStopwatch(){
console.log("Updating stopwatch from ", stopwatch, " to ", stopwatch+1);
setStopwatch(stopwatch + 1);
}
useEffect(() => {
const interval = setInterval(updateStopwatch, 1000);
return () => clearInterval(interval);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div>
<h1>{stopwatch}</h1>
</div>
);
}
</code></pre>
<p>In this code, the function <code>updateStopwatch</code> will be invoked periodically without depending on any re-rendering of the component ( Although its invocation will cause a re-render ) and each time it will be invoked, it needs to retrieve the current up-to-date value of the state variable stopwatch, so it can update it accordingly. So that the stop watch will keep counting up.</p>
<p>However, what happens is that it only gets the value of <code>stopwatch</code> at the moment the function is declared. It's not really subscribed to a state variable but more like it just reads a constant once. And as a result the count show 1 and is stuck there.</p>
<p>So how can I make such a function get an up-to-date value of a state variable whenever it's invoked?</p>
| [
{
"answer_id": 74204597,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "i"
},
{
"answer_id": 74204650,
"author": "Matthew Watson",
"author_id": 106159,
"author_profile": "... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11942492/"
] |
74,204,560 | <p>Just a little question...</p>
<p>When performing CoreData requests (in objective-C), do I have to make them on the context queue explicitly, or are they assumed to do that by themselves?</p>
<p>In other words can I just write:</p>
<pre><code>NSArray *results = [context executeFetchRequest:request error:nil];
</code></pre>
<p>Or do I have to write (if I want to avoid issues):</p>
<pre><code>__block NSArray *results = nil;
[context performBlockAndWait:^{
results = [context executeFetchRequest:request error:nil];
}];
</code></pre>
<p>Thanks!</p>
| [
{
"answer_id": 74204597,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "i"
},
{
"answer_id": 74204650,
"author": "Matthew Watson",
"author_id": 106159,
"author_profile": "... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4063213/"
] |
74,204,572 | <p>I'm learning typescript and messing around with an API endpoint, I've created a method which takes a value, makes a request to an external API and gets the data, populates the model PortalDetail and returns it back to the front end.</p>
<p>However, the returned data is always null. I have checked the <code>portalUrl</code> and the value exists, so I'm not sure what I'm doing wrong here:</p>
<p>Here is the code in question:</p>
<pre><code>const CheckUri = async (organisationCode: string): Promise<PortalDetail | null> => {
await fetch(`${uris.appCode}${organisationCode}`)
.then(async (data) => {
const portalUrl = await data
.text()
.then((html) => html)
.catch(() => null)
console.log(portalUrl); // This has a value
console.log(data); // So does this
if (data?.status === 200 && portalUrl) {
console.log("inside if"); // This also gets printed
return new PortalDetail(portalUrl, organisationCode);
}
})
.catch(() => {
})
.finally(() => {
})
return null;
}
</code></pre>
<p>Here is the code calling the method:</p>
<pre><code>const CheckOrgnisationCode = async (orgCode: string) => {
if (!orgCode || orgCode.includes(' ')) {
return;
}
console.log("before checkuri method")
var portalDetails = await CheckUri(orgCode);
console.log("finiahes ");
console.log(portalDetails);
if (portalDetails?.portalUrl) {
await StoreData(saved.portalURL, portalDetails?.portalUrl);
await StoreData(saved.portalCode, orgCode);
}
}
</code></pre>
<p>Can someone please explain where I'm going wrong?</p>
| [
{
"answer_id": 74204678,
"author": "Tsvetan Ganev",
"author_id": 8597510,
"author_profile": "https://Stackoverflow.com/users/8597510",
"pm_score": 2,
"selected": false,
"text": "return null\n"
},
{
"answer_id": 74204727,
"author": "bogdanoff",
"author_id": 14112947,
"... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1259536/"
] |
74,204,576 | <p>I'm creating a simple web app that fetches data asynchronously from three web apis. One is for location, one for weather and one for stock images. My files are as follow:</p>
<p>Index.html:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Weather Journal</title>
</head>
<body>
<div id="app">
<div class="holder headline">
Weather Journal App
</div>
<form id="userInfo">
<div class="holder zip">
<label for="city">Enter City here</label>
<input type="text" id="city" placeholder="enter city here" required>
</div>
<div class="holder feel">
<label for="date">Enter departure date</label>
<input type="datetime-local" id="date" required>
<button id="submitBtn" type="submit"> Generate </button>
</div>
</form>
<div class="holder entry">
<div class="title">Details</div>
<div>
<img id="city-pic" src="" alt="your city">
</div>
<div id="entryHolder">
<div><b>Temperature for next 16 days:</b></div>
<ul id="entries">
<div id="temp"></div>
<div id="time"></div>
</ul>
</div>
</div>
</div>
<script src="app.js" type="text/javascript"></script>
</body>
</html>
</code></pre>
<p>app.js:</p>
<pre><code>const present = new Date();
const submitBtn = document.getElementById("submitBtn");
submitBtn.addEventListener("click", (e) => {
e.preventDefault();
const city = document.getElementById("city").value;
const departure = document.getElementById("date").value;
const [depart_date, depart_time] = departure.split("T")
const [depart_year, depart_month, depart_day] = depart_date.split("-")
const [depart_hour, depart_minute] = depart_time.split(":")
const future = new Date(depart_year, depart_month - 1, depart_day, depart_hour, depart_minute);
if (city !== "" || departTime !== "" || future < present) {
document.getElementById("time").innerHTML = `Departure in ${Math.ceil((future - present) / 3600000 / 24)} days`
getCity(geoURL, city, geoUsername)
.then(function (data) {
return getWeather(weatherURL, weatherKey, data["geonames"][0]['lat'], data["geonames"][0]['lng'])
}).then(weatherData => {
return postWeatherData("/addWeather", { temp: weatherData['data'][i]['temp'], datetime: weatherData['data'][i]['datetime'] })
}).then(function () {
return receiveWeatherData()
}).catch(function (error) {
console.log(error);
alert("Please enter a valid city and a valid time");
})
getPictures(city, pixabayURL, pixabayKey)
.then(function (picsData) {
const total = picsData['hits'].length
const picIndex = Math.floor(Math.random() * total)
return postPictureData("/addPicture", { pic: picsData['hits'][picIndex]["webformatURL"] })
})
.then(function () {
return receivePictureData()
}).catch(function (error) {
console.log(error);
alert("No pictures found")
})
}
})
const getCity = async (geoURL, city, geoUsername) => {
const res = await fetch(`${geoURL}q=${city}&username=${geoUsername}`);
try {
const cityData = await res.json();
return cityData;
}
catch (error) {
console.log("error", error);
}
}
const postWeatherData = async (url = "", data = {}) => {
const response = await fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
temp: data.temp,
datetime: data.datetime
})
});
try {
const newData = await response.json();
console.log(newData)
return newData;
}
catch (error) {
console.log(error);
}
}
const receiveWeatherData = async () => {
const request = await fetch("/allWeather");
try {
const allData = await request.json()
const node = document.createElement("li");
const textnode = document.createTextNode("DATE: " + allData['datetime'] + "\t" + "TEMPERATURE: " + allData['temp']);
node.appendChild(textnode);
document.getElementById("entries").appendChild(node);
}
catch (error) {
console.log("error", error)
}
}
const getWeather = async (weatherURL, weatherKey, lat, lon) => {
const res = await fetch(`${weatherURL}&lat=${lat}&lon=${lon}&key=${weatherKey}`);
try {
const weatherData = await res.json();
return weatherData;
}
catch (error) {
console.log("error", error);
}
}
const getPictures = async (city, pixabayURL, pixabayKey) => {
const query = city.split(" ").join("+");
const res = await fetch(`${pixabayURL}key=${pixabayKey}&q=${query}`);
try {
const picsData = await res.json();
return picsData;
}
catch (error) {
console.log("error", error)
}
}
const receivePictureData = async () => {
const request = await fetch("/allPictures");
try {
const allData = await request.json()
document.getElementById("city-pic").src = allData['pic'];
}
catch (error) {
console.log("error", error)
}
}
const postPictureData = async (url = "", data = {}) => {
const response = await fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
pic: data.pic
})
});
try {
const newData = await response.json();
return newData;
}
catch (error) {
console.log(error);
}
}
</code></pre>
<p>server.js:</p>
<pre><code>// Setup empty JS object to act as endpoint for all routes
cityData = {};
weatherData = {};
picturesData = {};
// Require Express to run server and routes
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
// Start up an instance of app
const app = express();
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
app.use(cors())
// Initialize the main project folder
app.use(express.static('dist'));
app.use(express.static('website'));
app.get("/all", function sendData(req, res) {
res.send(cityData);
})
app.get("/allWeather", function sendWeather(req, res) {
res.send(weatherData);
})
app.get("/allPictures", function sendPictures(req, res) {
res.send(picturesData);
})
app.post("/addWeather", (req, res) => {
weatherData['temp'] = req.body.temp;
weatherData['datetime'] = req.body.datetime;
res.send(weatherData);
})
app.post("/addPicture", (req, res) => {
picturesData['pic'] = req.body.pic;
res.send(picturesData);
})
// Setup Server
app.listen(3000, () => {
console.log("App listening on port 3000")
console.log("Go to http://localhost:3000")
})
</code></pre>
<p>The server uses node, express, cors, and body-parser as the tools to create it.</p>
<p>I have not included the api keys or usernames. Right now I need to loop over the weather data that is return from the api (which fetches 16 days of data). The code :</p>
<pre><code>.then(weatherData => {
return postWeatherData("/addWeather", { temp: weatherData['data'][i]['temp'], datetime: weatherData['data'][i]['datetime'] })
</code></pre>
<p>should use the 'i' variable to loop over all the possible 16 entries for a certain location. Right now if run the app with 0 in place of 'i' it just gives the temperature for the next day. I want to get the weather data for 16 days and append it to the html 'ul' that I have in the document. Can someone guide me. This is the last step in the project that I need to complete by 10 november!</p>
<p>EDIT:</p>
<p>I tried using this and subsituted forLoop() instead the 'thens' but i get an error:</p>
<pre><code>const forLoop = async () => {
for (i = 0; i < 16; i++) {
try {
coords = await getCity(geoURL, city, geoUsername)
weatherData = await getWeather(weatherURL, weatherKey, coords["geonames"][0]['lat'], coords["geonames"][0]['lng'])
await postWeatherData("/addWeather", { temp: weatherData['data'][i]['temp'], datetime: weatherData['data'][i]['datetime'] })
await receiveWeatherData(i);
}
catch (error) {
console.log(error);
// alert("Please enter a valid city and a valid time");
}
}
}
</code></pre>
<p>The error is: "16app.js:156 TypeError: Cannot read properties of undefined (reading 'lat')
at forLoop (app.js:150:89)"</p>
| [
{
"answer_id": 74204678,
"author": "Tsvetan Ganev",
"author_id": 8597510,
"author_profile": "https://Stackoverflow.com/users/8597510",
"pm_score": 2,
"selected": false,
"text": "return null\n"
},
{
"answer_id": 74204727,
"author": "bogdanoff",
"author_id": 14112947,
"... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15218468/"
] |
74,204,626 | <p>As part of the SAS Enterprise Guide export as a step in process the outhput file location is very tedious to select. Is there any faster way to do it than clicking through all the folders on my harddrive for every export.
The path is shown but I am not able to edit the path or paste a path here:</p>
<p><a href="https://i.stack.imgur.com/mUXsi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mUXsi.png" alt="enter image description here" /></a></p>
<p>And when i press browse I am still not able to paste a path:
<a href="https://i.stack.imgur.com/zsgNl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zsgNl.png" alt="enter image description here" /></a></p>
<p>Am I doing something wrong, missing a setting or is there some kind of workaround.</p>
<p>Temporary question to Joe:
Like this?
<a href="https://i.stack.imgur.com/Ihqpl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ihqpl.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74208337,
"author": "Negdo",
"author_id": 19646183,
"author_profile": "https://Stackoverflow.com/users/19646183",
"pm_score": 3,
"selected": true,
"text": "%macro ExportExcel(path,file_name,tab_name);\nproc export data=&tab_name\n outfile=\"&path.&file_name..xlsx\"\n ... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13340047/"
] |
74,204,648 | <p>Consider my folder structure having files in these fashion:-</p>
<pre><code>abc.csv
abc.json
bcd.csv
bcd.json
efg.csv
efg.json
</code></pre>
<p>and so on i.e. a pair of csv files and json files having the same names, i have to perform the same operation by reading the same named files , do some operation and proceed to the next pair of files. How do i go about this?
Basically what i have in mind as a pseudo code is:-</p>
<pre><code>for files in folder_name:
df_csv=pd.read_csv('abc.csv')
df_json=pd.read_json('abc.json')
# some script to execute
#now read the next pair and repeat for all files
</code></pre>
| [
{
"answer_id": 74208337,
"author": "Negdo",
"author_id": 19646183,
"author_profile": "https://Stackoverflow.com/users/19646183",
"pm_score": 3,
"selected": true,
"text": "%macro ExportExcel(path,file_name,tab_name);\nproc export data=&tab_name\n outfile=\"&path.&file_name..xlsx\"\n ... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19322609/"
] |
74,204,716 | <p>I can not handle auto row heights resizing.
I tried to use <a href="https://www.javatips.net/api/nebula.widgets.nattable-master/org.eclipse.nebula.widgets.nattable.examples/src/org/eclipse/nebula/widgets/nattable/examples/examples/_102_Configuration/AutomaticRowHeightExample.java" rel="nofollow noreferrer">AutomaticRowHeightExample</a>, but without success.</p>
<p>Another inspiration was <a href="https://www.eclipse.org/forums/index.php/t/781957/" rel="nofollow noreferrer">this</a> question, but also did not worked (see my code example). If I sort/filter, in console output I can see numbers of painted rows <code>i</code> while creating <code>PaintListener</code>, but row heights are not updated.</p>
<p>Creating table:</p>
<pre><code>public class NatTableFactory {
// another code
private NatTable createTable(Composite parent, List<TableLine> tLines, String[][] propertyNames,
PropertyToLabels[] propToLabels, TableParams params, TextMatcherEditor<TableLine>editor, boolean openableParts) {
BodyLayerStack bodyLayerStack =
new BodyLayerStack(
tLines,
tLines.get(0).getLength(),
params.getColumnIndicesForRowHeaders());
DataLayer bodyDataLayer = bodyLayerStack.getBodyDataLayer();
Integer[] rowHeights = getRowHeights(params);
if( rowHeights != null && rowHeights.length > 0 ) {
for( int i = 0; i < rowHeights.length; i++ ) {
if( rowHeights[i] != null )
bodyDataLayer.setRowHeightByPosition(i, (int) (rowHeights[i] * ApplicationSizeManager.getRowSizeCoefficient()));
}
}
Integer[] colWidths = getColumnWidths(params);
if( colWidths != null && colWidths.length > 0 ) {
for( int i = 0; i < colWidths.length; i++ )
if( colWidths[i] != null )
bodyDataLayer.setColumnWidthByPosition(i, colWidths[i]);
}
DataLayer columnHeaderDataLayer = null;
if( propertyNames != null ) {
IDataProvider columnHeaderDataProvider =
new DefaultColumnHeaderDataProvider(propertyNames[0], propToLabels[0].getPropertyToLabels());
columnHeaderDataLayer =
new DefaultColumnHeaderDataLayer(columnHeaderDataProvider);
}
//copy command: include table headers
bodyLayerStack.registerCommandHandler(new CustomCopyDataCommandHandler(bodyLayerStack.getSelectionLayer(), columnHeaderDataLayer, null, params.getColumnHeaderGroups()));
CompositeLayer composite = null;
if( propertyNames != null ) {
ColumnHeaderLayer columnHeaderLayer =
new ColumnHeaderLayer(
columnHeaderDataLayer,
bodyLayerStack,
(SelectionLayer)null);
columnHeaderLayer.addConfiguration(NatTableLayerConfigurations.getColumnHeaderLayerConfiguration(false));
SortHeaderLayer<TableLine> sortHeaderLayer =
new SortHeaderLayer<TableLine>(
columnHeaderLayer,
new GlazedListsSortModel<TableLine>(
bodyLayerStack.getSortedList(),
getSortingColumnPropAccessor(propertyNames[0]),
configRegistry,
columnHeaderDataLayer));
Integer[] hrHeights = params.getHeaderRowHeights();
if( hrHeights != null && hrHeights.length > 0 )
columnHeaderDataLayer.setRowHeightByPosition(0, (int) (hrHeights[0] * ApplicationSizeManager.getRowSizeCoefficient()));
composite = new CompositeLayer(1, 2);
composite.setChildLayer(GridRegion.COLUMN_HEADER, sortHeaderLayer, 0, 0);
composite.setChildLayer(GridRegion.BODY, bodyLayerStack, 0, 1);
} else {
composite = new CompositeLayer(1, 1);
composite.setChildLayer(GridRegion.BODY, bodyLayerStack, 0, 0);
}
composite.addConfiguration(NatTableLayerConfigurations.getCompoositeLayerConfiguration());
NatTable natTable = new NatTable(parent, composite, false);
if( params.getAutoFitColWidthIndices().size() > 0 )
registerAutoResizeColCmdHandler(natTable, composite, bodyLayerStack, params.getAutoFitColWidthIndices());
// register AutoResizeRowCommandHandler
// something wrong here?
registerAutoResizeRowCommandHandler(natTable, composite, bodyLayerStack, params.getAutoFitColWidthIndices());
setNatTableContentTooltip(natTable);
natTable.setConfigRegistry(configRegistry);
natTable.addConfiguration(new SingleClickSortConfiguration());
if(columnHeaderDataLayer!=null)
natTable.addConfiguration(NatTableLayerConfigurations.getCustomComparatorConfiguration(columnHeaderDataLayer));
natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
setNatTableContextMenu(natTable, openableParts);
natTable.addConfiguration(NatTableLayerConfigurations.getNatTableConfiguration());
//
/*
natTable.addConfiguration(new DefaultNatTableStyleConfiguration()
{
{
cellPainter = new LineBorderDecorator(new AutomaticRowHeightTextPainter(5));
}
});*/
natTable.configure();
editor.setFilterator(new TextFilterator<TableLine>() {
@Override
public void getFilterStrings(List<String> baseList, TableLine element) {
for( int i = 0; i < element.getLength(); i++ )
baseList.add("" + element.getObjectByColumnForFilter(i));
}
});
editor.setMode(TextMatcherEditor.REGULAR_EXPRESSION);
bodyLayerStack.getFilterList().setMatcherEditor(editor);
NatTableContentProvider.addNatTableData(natTable, bodyLayerStack.getSelectionLayer(), bodyLayerStack.getBodyDataProvider());
return natTable;
}
// another code
}
</code></pre>
<p>register AutoResizeRowCommandHandler:</p>
<pre><code>// in class NatTableFactory
private void registerAutoResizeRowCommandHandler(NatTable natTable, ILayer commandLayer, ILayer positionLayer, List<Integer> colPositions)
{
natTable.registerCommandHandler(new AutoResizeRowCommandHandler(commandLayer, positionLayer));
PaintListener listener = new PaintListener()
{
@Override
public void paintControl(PaintEvent e)
{
System.out.println("paintControl");
for (int i = 0; i < natTable.getRowCount(); i++)
{
System.out.println(i);
InitializeAutoResizeRowsCommand rowCommand = new InitializeAutoResizeRowsCommand(natTable, i, natTable.getConfigRegistry(), new GCFactory(
natTable));
AutoResizeRowsCommand command = new AutoResizeRowsCommand(rowCommand);
natTable.doCommand(command);
}
}
};
natTable.addPaintListener(listener);
}
</code></pre>
<p>BodyLayerStack:</p>
<pre><code>public BodyLayerStack(List<TableLine> values, int columnCount, Integer[] columnIndicesForRowHeaders)
{
EventList<TableLine> eventList = GlazedLists.eventList(values);
TransformedList<TableLine, TableLine> rowObjectsGlazedList = GlazedLists.threadSafeList(eventList);
// this.filterList = new FilterList<>(rowObjectsGlazedList); //changed to:
// use the SortedList constructor with 'null' for the Comparator
// because the Comparator will be set by configuration
sortedList = new SortedList<>(rowObjectsGlazedList, null);
// wrap the SortedList with the FilterList
filterList = new FilterList<>(sortedList);
bodyDataProvider = new ListDataProvider<TableLine>(filterList, getColumnAccessor(columnCount));
bodyDataLayer = new DataLayer(bodyDataProvider);
IConfigLabelAccumulator cellLabelAccumulator = new IConfigLabelAccumulator() {
@Override
public void accumulateConfigLabels(LabelStack configLabels, int columnPosition, int rowPosition) {
int columnIndex = bodyDataLayer.getColumnIndexByPosition(columnPosition);
int rowIndex = bodyDataLayer.getRowIndexByPosition(rowPosition);
if(isRowHeader(columnIndicesForRowHeaders, columnIndex))
configLabels.addLabel(NatTableFactory.RowHeaderLabel);
else
{
// get dataTypes at actual positions and add/refresh labels
String label = filterList.get(rowIndex).getObjectTypeByColumn(columnIndex);
// adjust label according to autoFitWitdh option
if(filterList.get(rowIndex).isAutoFitColWidth(columnIndex))
label += "_" + NatTableFactory.AutoFitWidthLabel;
else
label += "_" + NatTableFactory.NoAutoFitWidthLabel;
configLabels.addLabel(label);
}
}
};
bodyDataLayer.setConfigLabelAccumulator(cellLabelAccumulator);
GlazedListsEventLayer<TableLine> glazedListsEventLayer = new GlazedListsEventLayer<>(bodyDataLayer, filterList);
selectionLayer = new SelectionLayer(glazedListsEventLayer, false);
selectionLayer.setSelectionModel(getSelectionModel());
selectionLayer.addConfiguration(getSelectionConfiguration());
//
viewportLayer = new ViewportLayer(selectionLayer);
setUnderlyingLayer(new ViewportLayer(selectionLayer));
}
</code></pre>
<p>If I call <code>natTable.doCommand(rowCommand)</code> instead of <code>natTable.doCommand(command)</code> while registering handler, row heights are updated correctly, but table is painted repetitively, scroll bar blinks all the time.</p>
<p>I tried also:</p>
<pre><code>private void registerAutoResizeRowCommandHandler(NatTable natTable, ILayer commandLayer, ILayer positionLayer, List<Integer> colPositions)
{
natTable.registerCommandHandler(new AutoResizeRowCommandHandler(commandLayer, positionLayer));
BodyLayerStack bodyLayerStack = (BodyLayerStack) positionLayer;
natTable.addPaintListener(
new AutoResizeRowPaintListener(
natTable,
bodyLayerStack.getViewportLayer(),
bodyLayerStack.getBodyDataLayer()));
}
</code></pre>
<p>Any idea what did I miss?</p>
| [
{
"answer_id": 74208337,
"author": "Negdo",
"author_id": 19646183,
"author_profile": "https://Stackoverflow.com/users/19646183",
"pm_score": 3,
"selected": true,
"text": "%macro ExportExcel(path,file_name,tab_name);\nproc export data=&tab_name\n outfile=\"&path.&file_name..xlsx\"\n ... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17478980/"
] |
74,204,717 | <p><a href="https://i.stack.imgur.com/RNfcG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RNfcG.jpg" alt="enter image description here" /></a></p>
<p>I want the border to be positioned inside the image,
red background just to show the border.</p>
<pre><code>#example {
border: 50px dotted black;
background: red;
width:600px;
}
img{
width:100%;
height:auto;
}
<div id="example">
<img src="https://images.pexels.com/photos/2246476/pexels-photo-2246476.jpeg?auto=compress&cs=tinysrgb&w=1600">
</div>
</code></pre>
| [
{
"answer_id": 74208337,
"author": "Negdo",
"author_id": 19646183,
"author_profile": "https://Stackoverflow.com/users/19646183",
"pm_score": 3,
"selected": true,
"text": "%macro ExportExcel(path,file_name,tab_name);\nproc export data=&tab_name\n outfile=\"&path.&file_name..xlsx\"\n ... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,204,721 | <p>I have the following issue with the following code. I have tried to implement a collapsible sidebar menu in my development. I have researched many resources online and I tried to customize it for for myself after following along a Youtube tutorial. However, the collapsing functionally seems to work except at the the time of refreshing the page. I have researched other Stackoverflow solutions (i.e session storage) but I couldn't be able to implement it in my case. Can somebody please help?</p>
<p>Here is my HTML page</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> let arrow = document.querySelectorAll(".arrow");
for (var i = 0; i < arrow.length; i++) {
arrow[i].addEventListener("click", (e)=>{
let arrowParent = e.target.parentElement.parentElement;
arrowParent.classList.toggle("showMenu");
})
}
let sidebar = document.querySelector(".sidebar");
let sidebarBtn = document.querySelector(".bx-menu");
sidebarBtn.addEventListener("click" , ()=>{
sidebar.classList.toggle("close");
});
</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
box-sizing: border-box;
margin: 0;
padding: 0;
}
/* fonts */
@import url('https://fonts.googleapis.com/css2?family=Cabin&family=Roboto+Condensed:wght@400;700&display=swap');
html {
font-size: 100%;
} /*16px*/
:root {
/* colors */
--primary-50: #e0fcff;
--primary-100: #bef8fd;
--primary-200: #87eaf2;
--primary-300: #54d1db;
--primary-400: #38bec9;
--primary-500: #2cb1bc;
--primary-600: #14919b;
--primary-700: #0e7c86;
--primary-800: #0a6c74;
--primary-900: #044e54;
/* grey */
--grey-50: #f0f4f8;
--grey-100: #d9e2ec;
--grey-200: #bcccdc;
--grey-300: #9fb3c8;
--grey-400: #829ab1;
--grey-500: #627d98;
--grey-600: #486581;
--grey-700: #334e68;
--grey-800: #243b53;
--grey-900: #102a43;
/* rest of the colors */
--black: #222;
--white: #fff;
--blue: #2336e2;
--red-light: #f8d7da;
--red-dark: #842029;
--green-light: #d1e7dd;
--green-dark: #0f5132;
/* fonts */
--headingFont: 'Roboto Condensed', Sans-Serif;
--bodyFont: 'Cabin', Sans-Serif;
--small-text: 0.875rem;
--extra-small-text: 0.7em;
/* rest of the vars */
--backgroundColor: var(--grey-50);
--textColor: var(--grey-900);
--borderRadius: 0.25rem;
--letterSpacing: 1px;
--transition: 0.3s ease-in-out all;
--max-width: 1120px;
--fixed-width: 500px;
--fluid-width: 90vw;
--breakpoint-lg: 992px;
--nav-height: 6rem;
/* box shadow*/
--shadow-1: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
--shadow-2: 0 4px 6px -1px rgba(0, 0, 0, 0.1),
0 2px 4px -1px rgba(0, 0, 0, 0.06);
--shadow-3: 0 10px 15px -3px rgba(0, 0, 0, 0.1),
0 4px 6px -2px rgba(0, 0, 0, 0.05);
--shadow-4: 0 20px 25px -5px rgba(0, 0, 0, 0.1),
0 10px 10px -5px rgba(0, 0, 0, 0.04);
}
body {
background: var(--backgroundColor);
font-family: var(--bodyFont);
font-weight: 400;
line-height: 1.75;
color: var(--textColor);
}
p {
margin-bottom: 1.5rem;
max-width: 40em;
}
h1,
h2,
h3,
h4,
h5 {
margin: 0;
margin-bottom: 1.38rem;
font-family: var(--headingFont);
font-weight: 400;
line-height: 1.3;
text-transform: capitalize;
letter-spacing: var(--letterSpacing);
}
h1 {
margin-top: 0;
font-size: 3.052rem;
}
h2 {
font-size: 2.441rem;
}
h3 {
font-size: 1.953rem;
}
h4 {
font-size: 1.563rem;
}
h5 {
font-size: 1.25rem;
}
small,
.text-small {
font-size: var(--small-text);
}
a {
text-decoration: none;
letter-spacing: var(--letterSpacing);
}
a,
button {
line-height: 1.15;
}
button:disabled {
cursor: not-allowed;
}
ul {
list-style-type: none;
padding: 0;
}
.sidebar {
position: fixed;
top: 0;
left: 0;
background: var(--white);
height: 100%;
width: 260px;
z-index: 100;
transition: var(--transition);
}
.sidebar.close {
width: 78px;
}
.logo-details {
width: 100px;
height: 60px;
display: flex;
align-items: center;
}
.logo-details span:first-child {
font-size: 30px;
/* color: #94EB58; */
color: var(--primary-600);
height: 50px;
min-width: 78px;
text-align: left;
line-height: 50px;
}
.logo_name img {
width: 140px;
height: 100px;
margin-top: 8px;
transition: 0.3s ease;
transition-delay: 0.1s;
}
.logo_name {
transition-delay: 0s;
opacity: 0;
pointer-events: none;
}
.nav-links {
height: 100%;
padding-top: 30px 0 150px 0;
overflow: auto;
}
.nav-links {
overflow: visible;
}
.nav-links::-webkit-scrollbar{
display: none;
}
.nav-links li {
position: relative;
transition: var(--transition);
}
.nav-links li:hover {
background: var(--green-light);
}
.nav-links li span {
height: 50px;
min-width: 78px;
text-align: center;
line-height: 50px;
color: var(--primary-500);
font-size: 23px;
cursor: pointer;
transition: var(--transition);
}
.nav-links li.showMenu span.arrow {
transform: rotate(-180deg);
}
.sidebar.close .nav-links span.arrow {
display: none;
}
.link_name {
font-size: 18px;
font-weight: 400;
color: var(--grey-700);
transition: var(--transition);
}
.sidebar.close .nav-links li a .link_name{
opacity: 0;
pointer-events: none;
}
.nav-links li a {
display: flex;
align-items: center;
}
.icon-link {
display: flex;
align-items: center;
justify-content: space-between;
}
.sidebar .nav-links li .sub-menu {
padding: 6px 6px 14px 80px;
margin-top: -10px;
background: var(--green-light);
display: none;
}
.sidebar .nav-links li.showMenu .sub-menu{
display: block;
}
.sidebar .nav-links li .sub-menu a {
color: var(--primary-900);
font-size: 15px;
padding: 5px 0;
white-space: nowrap;
opacity: 0.6;
transition: var(--transition);
}
.sidebar .nav-links li .sub-menu a:hover {
opacity: 1;
}
.sidebar.close .nav-links li .sub-menu {
position: absolute;
left: 100%;
top: -10px;
margin-top: 0;
padding: 10px 20px;
border-radius: 0 6px 6px 0;
opacity: 0;
display: block;
pointer-events: none;
transition: 0s;
}
.sidebar.close .nav-links li:hover .sub-menu {
top: 0;
opacity: 1;
pointer-events: auto;
transition: var(--transition);
}
.sidebar .nav-links li .sub-menu.link_name {
display: none;
}
.sidebar.close .nav-links li .sub-menu.link_name {
display: none;
}
.sidebar.close .nav-links li .sub-menu .link_name {
font-size: 18px;
opacity: 1;
display: block;
}
.sidebar .nav-links li .sub-menu.blank {
opacity: 1;
pointer-events: auto;
padding: 3px 20px 6px 16px;
opacity: 0;
pointer-events: none;
}
.sidebar .nav-links li:hover .sub-menu.blank {
top: 50%;
transform: translateY(-50%);
}
.sidebar .profile-details {
position: fixed;
bottom: 0;
width: 260px;
display: flex;
align-items: center;
justify-content: space-between;
background: var(--green-light);
padding: 12px 0;
transition: var(--transition);
}
.sidebar.close .profile-details{
background: none;
}
.sidebar.close .profile-details{
width: 78px;
}
.profile-content {
display: flex;
align-items: center;
}
.sidebar .profile-details img {
height: 52px;
width: 52px;
object-fit: cover;
border-radius: 16px;
margin: 0 14px 0 12px;
background: var(--white);
transition: var(--transition);
}
.sidebar.close .profile-details img{
padding: 10px;
}
.profile_name, .job {
color: var(--grey-700);
font-size: 18px;
font-weight: 500;
white-space: nowrap;
}
.sidebar.close .profile-details i,
.sidebar.close .profile-details .profile_name,
.sidebar.close .profile-details .job{
display: none;
}
.job {
font-size: 12px;
}
.home-section {
position: relative;
background: var(--backgroundColor);
height: 100vh;
left: 260px;
width: calc(100%-260px);
transition: var(--transition);
}
.sidebar.close ~ .home-section {
left: 78px;
width: calc(100% -78px);
}
.home-content {
height: 60px;
display: flex;
align-items: center;
}
.home-content span:first-child,
.text {
color: var(--grey-700);
font-size: 35px;
}
.home-content span:first-child {
margin: 0 15px;
cursor: pointer;
}
.home-section .home-content .text{
font-size: 26px;
font-weight: 600;
}
@media (max-width: 400px) {
.sidebar.close .nav-links li .sub-menu{
display: none;
}
.sidebar{
width: 78px;
}
.sidebar.close{
width: 0;
}
.home-section{
left: 78px;
width: calc(100% - 78px);
z-index: 100;
}
.sidebar.close ~ .home-section{
width: 100%;
left: 0;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="admindashcss.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons+Sharp" rel="stylesheet">
<title>Admin Dashboard</title>
</head>
<body>
<div class="sidebar">
<div class="logo-details">
<span class="material-icons-sharp">radio_button_checked</span>
<span class="logo_name"><img src="images/logowhite.svg" alt=""></span>
</div>
<ul class="nav-links">
<li>
<a href="#">
<span class="material-icons-sharp">grid_view</span>
<span class="link_name">Dashboard</span>
</a>
<!-- <ul class="sub-menu blank">
<li><a class="link_name" href="#">Category</a></li>
</ul> -->
</li>
<li>
<div class="icon-link">
<a href="#">
<span class="material-icons-sharp">contact_page</span>
<span class="link_name">Contacts</span>
</a>
<span class="material-icons-sharp arrow">expand_more</span>
</div>
<ul class="sub-menu">
<li><a class="link_name" href="#">Category</a></li>
<li><a href="#">Customer</a></li>
<li><a href="#">Resources</a></li>
</ul>
</li>
<li>
<div class="icon-link">
<a href="#">
<span class="material-icons-sharp">task</span>
<span class="link_name">Projects</span>
</a>
<span class="material-icons-sharp arrow">expand_more</span>
</div>
<ul class="sub-menu">
<li><a class="link_name" href="#">Projects</a></li>
<li><a href="#">Project details</a></li>
<li><a href="#">Job</a></li>
</ul>
</li>
<li>
<div class="icon-link">
<a href="#">
<span class="material-icons-sharp">payments</span>
<span class="link_name">Invoices</span>
</a>
<span class="material-icons-sharp arrow">expand_more</span>
</div>
<ul class="sub-menu">
<li><a class="link_name" href="#">Invoices</a></li>
<li><a href="#">Recivables</a></li>
<li><a href="#">Paybles</a></li>
</ul>
</li>
<li>
<div class="icon-link">
<a href="#">
<span class="material-icons-sharp">query_stats</span>
<span class="link_name">Queries</span>
</a>
<span class="material-icons-sharp arrow">expand_more</span>
</div>
<ul class="sub-menu">
<li><a class="link_name" href="#">Categories</a></li>
<li><a href="#">Recivables</a></li>
<li><a href="#">Payables</a></li>
<li><a href="#">Gross Profit</a></li>
<li><a href="#">Gross Profit Summary</a></li>
</ul>
</li>
<li>
<div class="icon-link">
<a href="#">
<span class="material-icons-sharp">admin_panel_settings</span>
<span class="link_name">Admin</span>
</a>
<span class="material-icons-sharp arrow">expand_more</span>
</div>
<ul class="sub-menu">
<li><a class="link_name" href="#">Categories</a></li>
<li><a href="#">Settings</a></li>
<li><a href="#">Users</a></li>
<li><a href="#">Documents</a></li>
</ul>
</li>
<li>
<div class="profile-details">
<div class="profile-content">
<img src="images/messi.jpg" alt="profile">
</div>
<div class="name-job">
<div class="profile_name">Brook Beyene</div>
<div class="job">Project Manager</div>
</div>
<span class="material-icons-sharp">logout</span>
</div>
</li>
</ul>
</div>
<section class="home-section">
<div class="home-content">
<span class="material-icons-sharp bx-menu">menu</span>
<span class="text">Drop Down Sidebar</span>
</div>
</section>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>:</p>
| [
{
"answer_id": 74208337,
"author": "Negdo",
"author_id": 19646183,
"author_profile": "https://Stackoverflow.com/users/19646183",
"pm_score": 3,
"selected": true,
"text": "%macro ExportExcel(path,file_name,tab_name);\nproc export data=&tab_name\n outfile=\"&path.&file_name..xlsx\"\n ... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16702082/"
] |
74,204,723 | <p>I want to use the direct translation from k8s secret-keys to SpringBoot properties.
Therefore I have a helm chart (but similar with plain k8s):</p>
<pre><code>apiVersion: v1
data:
app.entry[0].name: {{.Values.firstEntry.name | b64enc }}
kind: Secret
metadata:
name: my-secret
type: Opaque
</code></pre>
<p>With that my intention is that this behaves as if I'd set the spring property file:</p>
<pre><code>app.entry[0].name: "someName"
</code></pre>
<p>But when I do this I get an error:</p>
<pre><code> Invalid value: "[app.entry[0].name]": a valid config key must consist of alphanumeric characters, '-', '_' or '.' (e.g. 'key.name', or 'KEY_NAME', or 'key-name', regex used for validation is '[-._a-zA-Z0-9]+'),
</code></pre>
<p>So, <code>[0]</code> seems not to be allowed as a key name for the secrets.</p>
<p><strong>Any idea how I can inject an array entry into spring directly from a k8s secret name?</strong></p>
<p>Shooting around wildly I tried these that all failed:</p>
<ul>
<li><code> app.entry[0].name: ...</code> -- k8s rejects '['</li>
<li><code> app.entry__0.name: ...</code> -- k8s ok, but Spring does not recognize this as array (I think)</li>
<li><code> "app.entry[0].name": ...</code> -- k8s rejects '['</li>
<li><code> 'app.entry[0].name': ...</code> -- k8s rejects '['</li>
</ul>
| [
{
"answer_id": 74294276,
"author": "Nishan B",
"author_id": 8255039,
"author_profile": "https://Stackoverflow.com/users/8255039",
"pm_score": 0,
"selected": false,
"text": "example : secret-data.json"
},
{
"answer_id": 74338141,
"author": "Martin H.",
"author_id": 1304431... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472245/"
] |
74,204,742 | <p>I have the following DTO:</p>
<pre><code>class Permission
{
public string ObjectId { get; set; }
public string ObjectType { get; set; }
public string Scope { get; set; }
public string? AccountId { get; set; }
public string? GroupId { get; set; }
}
var permissions = new List<Permission>()
{
new(){ ObjectId = "1", ObjectType = "link", Scope = "link:read", AccountId = "1", GroupId = null },
new(){ ObjectId = "1", ObjectType = "link", Scope = "link:read", AccountId = "2", GroupId = null },
new(){ ObjectId = "1", ObjectType = "link", Scope = "link:read", AccountId = null, GroupId = "1" },
new(){ ObjectId = "1", ObjectType = "link", Scope = "link:write", AccountId = "2", GroupId = null },
new(){ ObjectId = "2", ObjectType = "link", Scope = "link:read", AccountId = "1", GroupId = null },
};
</code></pre>
<p>I want the following outcome:</p>
<pre><code>{[
"1": {
"read": {
"accounts": ["1", "2"],
"groups": ["1", "2", "3"]
},
"write": {
"accounts": ["1", "2"],
"groups": ["1", "2", "3"]
}
}
]}
</code></pre>
<p>Basically an array of objects of <code>Permission</code>, grouped by their <code>ObjectId</code> property, and then grouped by each <code>Scope</code> that contains an array of the <code>AccountId</code> or <code>GroupId</code> properties.</p>
<p>Each <code>Permission</code> can have the same <code>ObjectId</code> but different <code>Scope</code>, <code>AccountId</code> and <code>GroupId</code>.</p>
<p>I tried to use <code>GroupBy</code> but that gives me an <code>IGrouping</code> and I'm not sure how to proceed.</p>
| [
{
"answer_id": 74205077,
"author": "Eldar",
"author_id": 12354911,
"author_profile": "https://Stackoverflow.com/users/12354911",
"pm_score": 1,
"selected": false,
"text": "ToDictionary"
},
{
"answer_id": 74205102,
"author": "radoslawik",
"author_id": 12473121,
"author... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,204,766 | <p>I have query which looks like:</p>
<pre><code>SELECT * FROM
( SELECT DISTINCT CASE
WHEN user1_id = 1
THEN user2_id
ELSE user1_id
END userID,conversationId
FROM conversations
WHERE 1 IN (user2_id,user1_id))dt
INNER JOIN users on dt.userID = users.id
</code></pre>
<p>It returns conversationId and information about user from users table. I would like to also add the last message (the one with biggest messageId) from message table on base of conversationId. The last thing would be to sort all the results by messageId</p>
<p>I tried to use another INNER JOIN which looked like :</p>
<pre><code>INNER JOIN message on dt.conversationId = message.conversationId
</code></pre>
<p>Its adding messages to the result but I would like to get only the last one (the one with highest messageId as mentioned). I guess I would have to implement MAX somehow but I dont have idea how. The same thing with sorting all result by messageId so results with the biggest messageId would be first.
Thanks for all suggestions.</p>
| [
{
"answer_id": 74205077,
"author": "Eldar",
"author_id": 12354911,
"author_profile": "https://Stackoverflow.com/users/12354911",
"pm_score": 1,
"selected": false,
"text": "ToDictionary"
},
{
"answer_id": 74205102,
"author": "radoslawik",
"author_id": 12473121,
"author... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20333038/"
] |
74,204,784 | <p>I need to run rasa server on a specific ip address so I specified it in endpoints.yml core_endpoint: url: <a href="http://10.241.251.172:8081" rel="nofollow noreferrer">http://10.241.251.172:8081</a> 1</p>
<p>I start rasa server as follows: rasa run --endpoints endpoints.yml -m models --enable-api --cors “*” --debug</p>
<p>It still starts on Starting Rasa server on <a href="http://0.0.0.0:5005" rel="nofollow noreferrer">http://0.0.0.0:5005</a></p>
<p>How can I force Rasa server to start on a particular IP address. I do not have admin rights.</p>
| [
{
"answer_id": 74205077,
"author": "Eldar",
"author_id": 12354911,
"author_profile": "https://Stackoverflow.com/users/12354911",
"pm_score": 1,
"selected": false,
"text": "ToDictionary"
},
{
"answer_id": 74205102,
"author": "radoslawik",
"author_id": 12473121,
"author... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1716525/"
] |
74,204,798 | <p>How it's possible to rewrite this query with the INNER JOIN</p>
<pre><code> INNER JOIN [TD_DAT_DATe] WITH (NOLOCK)
ON DAT_Date
BETWEEN [Date Début] AND [Date Fin]**
</code></pre>
<pre><code>SELECT
SUBSTRING([Adhésion/Renouvellement],1,1) [Adhésion/Renouvellement],
[Code Evénement],
CAST(DAT_Periode+'01' AS DATE) Période,
COD_CodeProduit CodeProduit,
COUNT(DISTINCT CAST(IdAdhesion AS VARCHAR)+'-'+CAST(DAT_Date AS VARCHAR)) [Exposition NB Jour]
--INTO TF_COD_COntratDeclareGarantiePBIexpo
**FROM #ZZ3 WITH (NOLOCK)
INNER JOIN [TD_DAT_DATe] WITH (NOLOCK)
ON DAT_Date
BETWEEN [Date Début] AND [Date Fin]**
WHERE DAT_Periode >= '202201'
GROUP BY
SUBSTRING([Adhésion/Renouvellement],1,1),
[Code Evénement],
CAST(DAT_Periode+'01' AS DATE),
COD_CodeProduit
</code></pre>
<p>I try many ways to rewrite the query.</p>
| [
{
"answer_id": 74205077,
"author": "Eldar",
"author_id": 12354911,
"author_profile": "https://Stackoverflow.com/users/12354911",
"pm_score": 1,
"selected": false,
"text": "ToDictionary"
},
{
"answer_id": 74205102,
"author": "radoslawik",
"author_id": 12473121,
"author... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4453879/"
] |
74,204,809 | <p>How can I validate a response item is an instance of a collection variable where the collection variable is an array in postman?</p>
<p>Here first I'm making an array from a response from a GET request.</p>
<pre class="lang-js prettyprint-override"><code>let arr = [];
for (item of response.books) {
arr.push(item.isbn);
}
pm.collectionVariables.set("Books_ISBN", arr);
console.log(arr);
</code></pre>
<p>Now I want to evaluate a response data of a POST request with the "Books_ISBN" collection variable.
My POST request response is this</p>
<pre class="lang-json prettyprint-override"><code>{
"books": [
{
"isbn": "9781449325862"
}
]
}
</code></pre>
<p>I'm trying to do that like this but it is showing me error.</p>
<pre class="lang-js prettyprint-override"><code>var response = JSON.parse(responseBody);
pm.test(pm.expect(response.books[0].isbn).to.be.an.instanceof(Books_ISBN));
</code></pre>
<p><a href="https://i.stack.imgur.com/FJ9jB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FJ9jB.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74205077,
"author": "Eldar",
"author_id": 12354911,
"author_profile": "https://Stackoverflow.com/users/12354911",
"pm_score": 1,
"selected": false,
"text": "ToDictionary"
},
{
"answer_id": 74205102,
"author": "radoslawik",
"author_id": 12473121,
"author... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20337434/"
] |
74,204,820 | <p>I have a Pandas DataFrame like below with ID and Target variable (for machine learning model).</p>
<ul>
<li>My DataFrame is really large and unbalanced.</li>
<li>I need to make sampling on my DataFrame because it is really large</li>
<li>Balancing the DataFrame looks like this:
<ul>
<li><p>99.60% - 0</p>
</li>
<li><p>0.40 % - 1</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>TARGET</th>
</tr>
</thead>
<tbody>
<tr>
<td>111</td>
<td>1</td>
</tr>
<tr>
<td>222</td>
<td>1</td>
</tr>
<tr>
<td>333</td>
<td>0</td>
</tr>
<tr>
<td>444</td>
<td>1</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
</tr>
</tbody>
</table>
</div></li>
</ul>
</li>
</ul>
<p>How to sample the data, so as not to lose too many ones (target = 1), which are very rare anyway? In the next step, of course, I will add the remaining variables and perform over sampling, nevertheless at the beginning i need to take sample of data.</p>
<p>How can I do that in Python ?</p>
| [
{
"answer_id": 74205117,
"author": "Nikolay Zakirov",
"author_id": 9023490,
"author_profile": "https://Stackoverflow.com/users/9023490",
"pm_score": 0,
"selected": false,
"text": "stratify"
},
{
"answer_id": 74205258,
"author": "Mohammed Hadani",
"author_id": 14227024,
... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19975739/"
] |
74,204,839 | <p>This is auxiliary to this post: <a href="https://stackoverflow.com/questions/74186093/is-there-better-way-to-iterate-over-nested-loop-for-rows-30000">Is there better way to iterate over nested loop for rows (30000)?</a></p>
<p>I would like to find rows in following table, which contain non dutch bank numbers. I create an extra column in the dataframe in the following code with value 'ja', when a bank number is not dutch, i.e. it does not contain characters 'NL'. Any better ways to loop over the rows?</p>
<pre><code>import pandas as pd
import re
data={'IBAN':['NLAMRO123456789','NLINGB126656723','BGFFEO128856754','NLAMRO123896763','DUDMRO567456722','NLRABO123456712']}
df=pd.DataFrame(data)
df['No Dutch Bank']=None
substring='NL'
row_count=len(df.index)
for i in range (0, row_count):
mainstring=df['IBAN'][i]
if re.search(substring, mainstring) is None:
df['No Dutch Bank'][i]='ja'
df.head()
</code></pre>
<p>So far I have reached to this expression after browsing through internet:</p>
<pre><code>df['No Dutch Bank'] = list(map(lambda x: "None" if x else 'ja', (re.search('NL', x))))
</code></pre>
| [
{
"answer_id": 74205372,
"author": "Tranbi",
"author_id": 13525512,
"author_profile": "https://Stackoverflow.com/users/13525512",
"pm_score": 2,
"selected": true,
"text": "import pandas as pd\n\ndata={'IBAN':['NLAMRO123456789','NLINGB126656723','BGFFEO128856754','NLAMRO123896763','DUDMRO... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12985084/"
] |
74,204,855 | <p>I am using Primefaces <a href="https://www.primefaces.org/showcase-ext/views/documentViewer.jsf" rel="nofollow noreferrer">documentViewer</a> from primefaces-extensions 12 as follows :</p>
<pre><code><pe:documentViewer zoom="page-fit" pagemode="thumbs"
id="iframeViewPdf" width="80%" height="800"
url="/pdfServlet?id=#{param.id}"/>
</code></pre>
<p>My controller writes the bytes to the response as follows :</p>
<pre><code>@RequestMapping(value = "/pdfServlet")
public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
// code here
try{
documentId = request.getParameter("id");
inputStream = myRepository.getFileAsInputStream(documentId);
outputStream = response.getOutputStream();
IOUtils.copy(inputStream, outputStream);
}catch(Exception e){
// all below didn't work
// request.getRequestDispatcher(request.getContextPath() + "/error").forward(request, response);
// response.sendRedirect(request.getContextPath() + "/error");
// throw e;
// what should be done here to redirect to error page / show error message in the page
}finally{
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
}
}
</code></pre>
<p>Above code works fine, but when any exception occurs in the backend I want to handle it in the client side, I tried to throw the exception in the catch part and got no effect.</p>
<p>Note: my application has error page configuration for any exception to forward to error page.</p>
<p>I also tried to redirect/forward to error page in the catch part, but I always gets an exception that cannot forward/redirect after response is committed.</p>
<p>How can I better handle exception in this case?</p>
<p><strong>UPDATE</strong> : below is the response I get in the viewer when loading exception occurs in the backend, is there's any way to call a javascript function instead ?</p>
<p><a href="https://i.stack.imgur.com/7YyTy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7YyTy.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74210220,
"author": "Melloware",
"author_id": 502366,
"author_profile": "https://Stackoverflow.com/users/502366",
"pm_score": 0,
"selected": false,
"text": "web.xml"
},
{
"answer_id": 74260240,
"author": "Mahmoud Saleh",
"author_id": 429377,
"author_pro... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/429377/"
] |
74,204,857 | <p>I'm working on this project and I'm in the process of creating the searchStore() method in User class but I can't think of any way to access the cost of the candies in a certain store.</p>
<p>When the user searches for a store, the program should print the stores that is nearby the landmarks, so if the user visits the lm 4 and lm1, Lolli's and Guccini's store would print. I need to access the cost of the candies in the store to check if the money of the user is enough to buy a candy. If the money is sufficient, then it should print that the user can buy a candy in the store, else it should prompt that the money is not enough to buy a candy.</p>
<p>I tried to create an instance inside the method but that's not correct because if I am to make a new instance, I'm not accessing the cost of the store that I want, but the cost of the instance that I created.</p>
<p>I also tried the getter method in the CandyStore class but it says that I should make the attribute cost static but that is not possible because the cost varies in different stores.</p>
<p>Can someone help me to implement the searchStore method in User class?</p>
<p><strong>MAIN CLASS</strong></p>
<pre><code>package testing;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello World");
User user1 = new User("Mylah", 1, 20f);
User user2 = new User("Meg", 2, 50f);
User user3 = new User("Marga", 3, 25f);
Landmark lm1 = new Landmark("Vista Mall", 1);
Landmark lm2 = new Landmark("Vista Residences", 2);
Landmark lm3 = new Landmark("Vista Park", 3);
Landmark lm4 = new Landmark("Crystal Mall", 4);
Landmark lm5 = new Landmark("Crystal Residences", 5);
Landmark lm6 = new Landmark("Crystal Park", 6);
CandyStore c1 = new CandyStore("Lolli's Store", 1, 15);
CandyStore c2 = new CandyStore("Mary's Store", 2, 25);
CandyStore c3 = new CandyStore("Guccini's Store", 3, 10);
c1.addLandmark(lm4);
c1.addLandmark(lm6);
c2.addLandmark(lm2);
c2.addLandmark(lm3);
c3.addLandmark(lm1);
c3.addLandmark(lm5);
user1.visits(lm4);
user1.visits(lm1);
user1.searchStore();
user1.viewState();
}
}
</code></pre>
<p><strong>USER CLASS</strong></p>
<pre><code>package testing;
public class User {
String name;
int StudentId;
float money;
Landmark[] lm;
int lmCounter;
static int MAX_LM = 3;
User(String n, int id, float m) {
this.name = n;
this.StudentId = id;
this.money = m;
this.lm = new Landmark[User.MAX_LM];
}
void visits(Landmark l) {
if(this.lmCounter < MAX_LM) {
this.lm[this.lmCounter++] = l;
} else {
System.out.println("Please go home, you visited too many places already!\n");
}
}
void searchStore() {
//insert code here
}
void viewState() {
System.out.println("\n======== VIEW STATE ========");
System.out.println("Student ID: " + this.StudentId);
System.out.println("Student Name: " + this.name);
System.out.println("Student's Money: " + this.money);
if(this.lmCounter == 0) {
System.out.println(this.name + " is still in school!\n");
} else {
System.out.println(this.name + " visited :");
for (int i = 0; i < lmCounter; i++) {
Landmark L = lm[i];
int j = i+1;
System.out.println(j + ". " + L.name);
}
}
}
}
</code></pre>
<p><strong>CANDYSTORE CLASS</strong></p>
<pre><code>package testing;
public class CandyStore {
String name;
int StoreId;
float cost; // cost of candies inside the store
int sales;
Landmark[] LM;
int lmCounter;
static int MAX_LM = 3;
CandyStore(String n, int id, float c) {
this.name = n;
this.StoreId = id;
this.cost = c;
this.sales = 0;
this.LM = new Landmark[CandyStore.MAX_LM];
}
void addLandmark(Landmark lm) {
if(this.lmCounter < MAX_LM) {
this.LM[this.lmCounter++] = lm;
} else {
System.out.println("Can't add landmark\n");
}
}
void ViewState() {
System.out.println("\n======== VIEW STATE ========");
System.out.println("Store ID: " + this.StoreId);
System.out.println("Store Name: " + this.name);
System.out.println("Store Sales: " + this.sales);
System.out.println("Landmark nearby");
if(lmCounter == 0) {
System.out.println("The store doesn't have any recognizable landmark\n");
} else {
for(int i = 0; i < lmCounter; i++) {
Landmark l = LM[i];
int j = i+1;
System.out.println(j + ". " + l.name);
}
}
}
}
</code></pre>
<p><strong>LANDMARK CLASS</strong></p>
<pre><code>package testing;
public class Landmark {
int LMid; // landmark number
String name;
Landmark (String n, int id) {
this.name = n;
this.LMid = id;
}
void viewState() {
System.out.println("\n======== VIEW STATE ========");
System.out.println("Landmark Number: " + this.LMid);
System.out.println("Landmark Name: " + this.name);
}
}
</code></pre>
<p>PS. Please show me how to do the code correctly, thank you.</p>
| [
{
"answer_id": 74276386,
"author": "Sergio",
"author_id": 1558552,
"author_profile": "https://Stackoverflow.com/users/1558552",
"pm_score": 0,
"selected": false,
"text": "public class Landmark {\n int LMid; // landmark number\n String name;\n\n // ***\n CandyStore nearbyStore... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17118303/"
] |
74,204,891 | <pre><code>const [admin, setadmin] = useState(false);
const toggleIsLoading = () => {
admin?setadmin(false):setadmin(true)
};
return (
<div className="signup">
<div className="register_head">
<h1>REGISTER YOURSELF</h1>
</div>
<div className="form">
<div>
<label for="options">I'm: </label>
<select className="options">
<option id="emp" value={admin}>
Employee
</option>
<option onClick={toggleIsLoading}>Admin</option>
</select>
</div>
</code></pre>
<p>I want to change <code>admin</code> value to true but it is not working.</p>
<p>I tied several things but state is not changing.</p>
| [
{
"answer_id": 74204938,
"author": "JamesG",
"author_id": 18096860,
"author_profile": "https://Stackoverflow.com/users/18096860",
"pm_score": 0,
"selected": false,
"text": "const toggleIsLoading = () => {\n setAdmin(!admin)\n}\n"
},
{
"answer_id": 74204998,
"author": "Aposto... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16925604/"
] |
74,204,896 | <p>first time posting here!</p>
<p>I have the following scenario:</p>
<ol>
<li>1 Google Sheet with information sorted in tables (Master Data)</li>
<li>1 Google Sheet that =Importrange the data from the Master Data Google Sheet.</li>
</ol>
<p>I need to import one time, or multiple times, some of the rows that are Imported from the Master Data based on the following criteria:
On the Master Data Google Sheet, a column would be present, showing in which Country/Countries the student lives. If the student lives 1 country, import the row once. If it is in 2,3,4... countries, import the same row it 2,3,4... times.</p>
<p>Right now, I am using the following formula:</p>
<p><code>=QUERY({IMPORTRANGE(Reference!A8,Reference!$A$2&Reference!B6)},"select Col6 where Col10='"&'Advanced Settings'!B5&"'")</code></p>
<p>This formula Imports from the Master Data file (<code>Reference!A8</code>), a particular tab (<code>Reference!$A$2)</code> and a particular range in this tab <code>Reference!B6</code>. Finally, it filters the data imported (only the 6th Col of the range, and only if on Col 10 the row has a particular value (<code>Advanced Settings'!B5</code>).</p>
<p>Is there a way to Import the name of the student as many times as countries they live in inside the same Array formula?</p>
<p>Right now, I am just adding more importrange (if there are 3 countries, I will add Importrange three times) with filters, but I would like to make it dynamic for the number of countries, without manual input every time. Also, the number of students imported varies every time so I can't look manually at the number of rows and then add a formula after the last cell of the array formula.</p>
<p>Thanks!
EDIT:
Sample Data and expected result:</p>
<ol>
<li>Sample Data</li>
</ol>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Student Name</th>
<th>Gender</th>
<th>Class Level</th>
<th>Home State</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alexandra</td>
<td>Female</td>
<td>4. Senior</td>
<td>CA</td>
<td>UK, US</td>
</tr>
<tr>
<td>Andrew</td>
<td>Male</td>
<td>1. Freshman</td>
<td>SD</td>
<td>UK</td>
</tr>
<tr>
<td>Anna</td>
<td>Female</td>
<td>1. Freshman</td>
<td>NC</td>
<td>UK, US</td>
</tr>
<tr>
<td>Becky</td>
<td>Female</td>
<td>4. Senior</td>
<td>SD</td>
<td>US</td>
</tr>
<tr>
<td>Benjamin</td>
<td>Male</td>
<td>4. Senior</td>
<td>WI</td>
<td>UK</td>
</tr>
</tbody>
</table>
</div>
<ol start="2">
<li>Filter on both Class Level (4. Senior) and Country</li>
</ol>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Reason for appearing (explanation for you)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alexandra</td>
<td>Appears because Alexandra is Senior, UK</td>
</tr>
<tr>
<td>Alexandra</td>
<td>Appears because Alexandra is Senior, US</td>
</tr>
<tr>
<td>Becky</td>
<td>Appears because Becky is Senior, US</td>
</tr>
<tr>
<td>Benjamin</td>
<td>Appears because Benjamin is Senior, UK</td>
</tr>
</tbody>
</table>
</div>
<p>The expected result here is that Alexandra appears twice as she's Senior and both US and UK.</p>
| [
{
"answer_id": 74204938,
"author": "JamesG",
"author_id": 18096860,
"author_profile": "https://Stackoverflow.com/users/18096860",
"pm_score": 0,
"selected": false,
"text": "const toggleIsLoading = () => {\n setAdmin(!admin)\n}\n"
},
{
"answer_id": 74204998,
"author": "Aposto... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20337496/"
] |
74,204,906 | <p>I am new to <code>LiveData</code> thing in general and I am having a hard time understanding the difference between <code>LiveData<String>()</code> and <code>LiveData<String?>()</code>. I used them interchangeably and nothing seams to break. I know that <code>LiveData.getValue()</code> is marked with <code>@Nullable</code> in Java, so we end up getting <code>String?</code> anyway. So what makes <code>LiveData<String?>()</code> different from <code>LiveData<String>()</code>?</p>
| [
{
"answer_id": 74204938,
"author": "JamesG",
"author_id": 18096860,
"author_profile": "https://Stackoverflow.com/users/18096860",
"pm_score": 0,
"selected": false,
"text": "const toggleIsLoading = () => {\n setAdmin(!admin)\n}\n"
},
{
"answer_id": 74204998,
"author": "Aposto... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13455858/"
] |
74,204,918 | <p>i tried to do a while loop in which after the user inputs 'no' then the loop will stop and end the program but it did not work and i can't find the problem</p>
<pre><code>finish = True
while (finish) :
kg = float(input('Enter kg: '))
total = kg * 2.2
print('The converted kg is: ', total, 'lbs')
question = input('do you want to quit?')
if question == 'Yes' or 'yes' or 'YES':
finish = False
print('Bye-Bye')
else :
print('OK!')
</code></pre>
<p>this is the code and when the user typed 'no' it should end the program</p>
| [
{
"answer_id": 74204938,
"author": "JamesG",
"author_id": 18096860,
"author_profile": "https://Stackoverflow.com/users/18096860",
"pm_score": 0,
"selected": false,
"text": "const toggleIsLoading = () => {\n setAdmin(!admin)\n}\n"
},
{
"answer_id": 74204998,
"author": "Aposto... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19176850/"
] |
74,204,922 | <p>I want to know how to produce a c# executable file on Linux as when I build all I get is a DLL file in the bin folder that I don't know how to execute.
Note: I'm using vscode as my code editor and Manjaro is my Linux distro.</p>
| [
{
"answer_id": 74205657,
"author": "buithienquyet",
"author_id": 7174186,
"author_profile": "https://Stackoverflow.com/users/7174186",
"pm_score": 3,
"selected": true,
"text": "dotnet app_name.dll\n"
},
{
"answer_id": 74205669,
"author": "Sami",
"author_id": 10374580,
... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14854600/"
] |
74,204,923 | <p>I need to keep track of occurrences of items in parsed files in a structure as follows:</p>
<pre><code>data= {'tomate': {'John': 2, 'mike': 2},
'pasta': {'mike': 1},
'wine': {'mike': 1, 'alex': 2}}
</code></pre>
<p>the dictionary starts as empty one. data = {} and its is being populated with values when they are not there and adding up users +1 if the user is there or =1 if the user is not yet there.</p>
<p>This is my code:</p>
<pre><code>def modify(data, key, client):
try:
# if both keys are there
data[key][client] = data[key][client] +1
#print(f"{key} is there. {client} is there.")
except:
try:
data[key][client] = 1
#print(f"{client} not there, but {key}")
except:
data[key]={}
data[key][client] = 1
#print(f"{client} and {key} added")
return data
</code></pre>
<p>It works:</p>
<pre><code>key="wine"
client = "alex"
modify(d, key, client)
</code></pre>
<p>giving:</p>
<pre><code>{'tomate': {'John': 2, 'mike': 2},
'pasta': {'mike': 1},
'wine': {'mike': 1, 'alex': 3}}
</code></pre>
<p>The question is if using try/except is not the way to go, i.e. not pythonic, because I am relying on exceptions for the code to work properly which I feel is a little bit weird and might make the whole code much slower.</p>
<p>Is there any other option to keep track of a counter like this that I might have a look to that might be faster?
Performance is very important of course since I have to count hundreds of millions of times.</p>
<hr />
<p>EDIT 1:
Evaluating the speed of a proposed solution I have this comparison that strikes me since my solution is faster (and I would not expect that):</p>
<p><a href="https://i.stack.imgur.com/ZBXUz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZBXUz.png" alt="enter image description here" /></a></p>
<p>EDIT 2:
This question has been closed despite of very well elaborated answers and being directed to finding a proper way to solve a problem. It is really annoying that people just close questions like this. How can someone say that this questions is opinion-based if we are talking about computing times?</p>
| [
{
"answer_id": 74205082,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": false,
"text": "if-else"
},
{
"answer_id": 74205098,
"author": "Yevhen Kuzmovych",
"author_id": 4727702,
... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7168098/"
] |
74,204,926 | <p>So I'm working an a project where the user should click the link and than should go on the login or create account page. I'm using <code>routing</code> for that but as soon as I put Routes to use route and add the navigation link there my webpage turns <strong>blank</strong>:<a href="https://i.stack.imgur.com/rYFD1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rYFD1.png" alt="enter image description here" /></a>
That was the code and this is the page at the moment:<a href="https://i.stack.imgur.com/UqinF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UqinF.png" alt="enter image description here" /></a>
No error shown no nothing! help pls!</p>
<p>First I used <code>Switch</code> than the webpage didn't allow me to use it, so I changed to <strong>Routes</strong></p>
| [
{
"answer_id": 74205082,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": false,
"text": "if-else"
},
{
"answer_id": 74205098,
"author": "Yevhen Kuzmovych",
"author_id": 4727702,
... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20337580/"
] |
74,204,928 | <p>I'm working with a DateOnly variable and I'm trying to get the DateTime.Now time in a dd/mm/yyyy format, however it's only returning the date on mm/dd/yyyy format.</p>
<p>I strictly need the current date in a dd/mm/yyyy format, and I haven't been able to figure it out how to.</p>
<p>This is an example how I'm working to convert the DateTime.Now to DateOnly type</p>
<pre><code>public class Example
{
public DateOnly? Date{get; set;}
}
public class Process1
{
Example example = new Example();
{
example.Date= DateOnly.FromDateTime(DateTime.Now);
//this is returning the current date in a mm/dd/yyyy format
}
}
</code></pre>
| [
{
"answer_id": 74205082,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": false,
"text": "if-else"
},
{
"answer_id": 74205098,
"author": "Yevhen Kuzmovych",
"author_id": 4727702,
... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16596198/"
] |
74,204,990 | <p>This might be a bit of broad question.</p>
<p>I have an JSON Map Array which i can parse normally. But i would like to MAP multiple Values to a Single key. I am stuck and unsure how to proceed.</p>
<p>My JSON output. I cannot change this.</p>
<pre><code> {
"pos":"1",
"element":"37542",
"title":"Easy On Me",
"inter":"Adele",
"isnew":"0"
},
{
"pos":"66",
"element":"37183",
"title":"Send My Love",
"inter":"Adele",
"isnew":"0"
}
</code></pre>
<p>this is just a snippet of the actual JSON objects</p>
<p>what I would like to do is something like Map<String,List<String,String>></p>
<p>Adele</p>
<ul>
<li>Easy On Me, 37542</li>
<li>Send My Love, 37183</li>
</ul>
<p>Searching online I find a lot of examples how to parse JSON normally, but never found a version where you can iterate through a JSON version like above and pull parts of the map out and add it to another.</p>
<p>any help would be appreciated. Thank you in advance</p>
<pre><code>import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:async';
class SongList {
final List<Song> songs;
SongList({
required this.songs,
});
factory SongList.fromJson(List<dynamic> parsedJson) {
List<Song> songs = <Song>[];
songs = parsedJson.map((i) => Song.fromJson(i)).toList();
return SongList(songs: songs);
}
}
class Song {
final String? pos;
final String? element;
final String? title;
final String? inter;
final String? isnew;
const Song(
{required this.pos,
required this.element,
required this.title,
required this.inter,
required this.isnew});
factory Song.fromJson(Map<String, dynamic> data) {
return Song(
pos: data['pos'] as String?,
element: data['element'] as String?,
title: data['title'] as String?,
inter: data['inter'] as String?,
isnew: data['isnew'] as String?,
);
}
}
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
class Songs extends StatefulWidget {
final String pos;
final String element;
final String title;
final String inter;
final String isnew;
const Songs(
{super.key,
required this.pos,
required this.element,
required this.title,
required this.inter,
required this.isnew});
@override
State<Songs> createState() => _SongsState();
}
class _SongsState extends State<Songs> {
late AudioPlayer player;
@override
void initState() {
super.initState();
player = AudioPlayer();
}
@override
void dispose() {
player.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
var titles = Row(
mainAxisSize: MainAxisSize.min,
children: [
Column(children: [
SizedBox(
height: 25,
width: 200,
child: Text(
widget.title,
style: const TextStyle(fontSize: 14),
textAlign: TextAlign.center,
),
),
SizedBox(
height: 25,
width: 200,
child: Text(
widget.inter,
style: const TextStyle(fontSize: 10),
textAlign: TextAlign.center,
),
),
]),
],
);
return FittedBox(
fit: BoxFit.contain,
child: Card(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Column(
children: [
Center(
child: SizedBox(
height: 50,
width: 50,
child: Align(
alignment: Alignment.center,
child: widget.isnew != "1"
? Text(
widget.pos.toString(),
textAlign: TextAlign.center,
)
: const Text(
"new",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.red),
)))),
],
),
Column(
children: [
SizedBox(
height: 50,
width: 50,
child: Image.network(
'${'http://www.example.com/${widget.element}'}.jpg'),
),
],
),
Column(
children: [
titles,
],
),
Column(
children: [
SizedBox(
height: 50,
width: 50,
child: TextButton(
onPressed: () async {
final url =
'${'http://www.example.com/${widget.element}'}.mp3';
await player.setUrl(url);
player.play();
},
child: Image.asset('assets/images/btn_play.png'),
),
),
],
),
Column(
children: [
SizedBox(
height: 50,
width: 50,
child: TextButton(
// ignore: avoid_print
onPressed: () =>
print('pressed button download!! ${widget.element}'),
child: Image.asset('assets/images/btn_download.png'),
),
),
],
),
],
)));
}
}
Future<SongList> fetchSong() async {
final response = await http
.get(Uri.parse('http://example.com'));
if (response.statusCode == 200) {
return SongList.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to Load Songs');
}
}
//snippet from class that instatiates
late Future<SongList> futureSong;
@override
void initState() {
super.initState();
futureSong = fetchSong();
}
//snippet from class that builds the list
FutureBuilder<SongList>(
future: futureSong,
builder: (context, AsyncSnapshot<SongList> snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.songs.length,
itemBuilder: (context, index) {
if (snapshot.data!.songs[index].element.toString() !=
"null") {
return Songs(
element:
snapshot.data!.songs[index].element.toString(),
inter: snapshot.data!.songs[index].inter.toString(),
isnew: snapshot.data!.songs[index].isnew.toString(),
pos: snapshot.data!.songs[index].pos.toString(),
title: snapshot.data!.songs[index].title.toString());
} else {
return const SizedBox(height: 0);
}
});
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
}
</code></pre>
| [
{
"answer_id": 74205082,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": false,
"text": "if-else"
},
{
"answer_id": 74205098,
"author": "Yevhen Kuzmovych",
"author_id": 4727702,
... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74204990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10516757/"
] |
74,205,002 | <pre><code>class Category_recycler_view (var arrayList: ArrayList<Category_Spinner_model>) :
RecyclerView.Adapter<Category_recycler_view.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.category_spinner_item,parent,false)
val spinner_modal : Category_Spinner_model? = arrayList.get(1)
val ico = v.findViewById<ImageView>(R.id.category_ico)
val text = v.findViewById<TextView>(R.id.category_text)
val dropdown_ico = v.findViewById<ImageView>(R.id.category_dropdowm)
ico?.setImageResource(spinner_modal!!.getIco())
text.text = spinner_modal!!.getTextt()
dropdown_ico.setImageResource(spinner_modal.getDropico())
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val itemsView = arrayList[position]
}
override fun getItemCount(): Int {
return arrayList.size
}
class ViewHolder (Itemview : View) : RecyclerView.ViewHolder(Itemview) {
}
}
</code></pre>
<p>I need every element of the array to display, but i can give only one index at a time how to display every element of the array modal</p>
| [
{
"answer_id": 74208350,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 3,
"selected": true,
"text": "onCreateViewHolder()"
},
{
"answer_id": 74208534,
"author": "Himanshu Yadav Anshu",
"author_id": 1871... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74205002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20099889/"
] |
74,205,019 | <p>How can I calculate the position of the selected item in a LazyRow and use it for centering the item on the screen?
The items will have various sizes depending on their content.</p>
<p>If I go with <code>lazyListState.animateScrollToItem(index)</code> the selected item will be positioned to the left in the LazyRow.
<a href="https://i.stack.imgur.com/SZav3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SZav3.png" alt="Result" /></a></p>
<p>What I want to achieve is to have the selected item centered like this
<a href="https://i.stack.imgur.com/POX91.png" rel="noreferrer"><img src="https://i.stack.imgur.com/POX91.png" alt="Expected" /></a></p>
<p>The code I have currently:</p>
<pre><code>@Composable
fun Test() {
Column {
TestRow(listOf("Angola", "Bahrain", "Afghanistan", "Denmark", "Egypt", "El Salvador", "Fiji", "Japan", "Kazakhstan", "Kuwait", "Laos", "Mongolia"))
TestRow(listOf("Angola", "Bahrain", "Afghanistan"))
}
}
@OptIn(ExperimentalSnapperApi::class)
@Composable
fun TestRow(items: List<String>) {
val selectedIndex = remember { mutableStateOf(0) }
val lazyListState = rememberLazyListState()
val coroutineScope = rememberCoroutineScope()
LazyRow(
modifier = Modifier.fillMaxWidth(),
state = lazyListState,
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
contentPadding = PaddingValues(horizontal = 12.dp),
flingBehavior = rememberSnapperFlingBehavior(
lazyListState = lazyListState,
snapOffsetForItem = SnapOffsets.Start
)
) {
itemsIndexed(items) { index, item ->
TestItem(
content = item,
isSelected = index == selectedIndex.value,
onClick = {
selectedIndex.value = index
coroutineScope.launch {
lazyListState.animateScrollToItem(index)
}
}
)
}
}
}
@Composable
fun TestItem(
content: String,
isSelected: Boolean,
onClick: () -> Unit
) {
Button(
modifier = Modifier.height(40.dp),
colors = ButtonDefaults.buttonColors(
backgroundColor = if (isSelected) Color.Green else Color.Yellow,
contentColor = Color.Black
),
elevation = null,
shape = RoundedCornerShape(5.dp),
contentPadding = PaddingValues(0.dp),
onClick = onClick
) {
Text(
modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),
text = (content).uppercase(),
)
}
}
</code></pre>
<p>The code <code>horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally)</code> is to make sure the LazyRow centers all the items, when there is not enough items for scrolling.
Example with 3 items:
<a href="https://i.stack.imgur.com/0F1sC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0F1sC.png" alt="All centered" /></a></p>
<p>I have tried various suggestions posted at similar questions, but with no luck in finding a solution.
<a href="https://stackoverflow.com/questions/71832396/jetpack-compose-lazylist-possible-to-zoom-the-center-item">jetpack-compose-lazylist-possible-to-zoom-the-center-item</a>
<a href="https://stackoverflow.com/questions/68931565/how-to-focus-a-invisible-item-in-lazycolumn-on-jetpackcompose">how-to-focus-a-invisible-item-in-lazycolumn-on-jetpackcompose</a>
<a href="https://stackoverflow.com/questions/71838922/jetpack-compose-make-the-first-element-in-a-lazyrow-be-aligned-to-the-center-o">/jetpack-compose-make-the-first-element-in-a-lazyrow-be-aligned-to-the-center-o</a></p>
| [
{
"answer_id": 74208361,
"author": "Markram",
"author_id": 7374564,
"author_profile": "https://Stackoverflow.com/users/7374564",
"pm_score": 2,
"selected": false,
"text": "coroutineScope.launch {\n val itemInfo = lazyListState.layoutInfo.visibleItemsInfo.firstOrNull { it.i... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74205019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7374564/"
] |
74,205,024 | <p>I'm wondering in <code>vim</code>, when given a <code>start</code> and <code>end</code> column position, is there a way to yank corresponding content starts from the start position to end.</p>
<p>for example, given a line in vim</p>
<pre><code>aaaabbbbcccc
</code></pre>
<ul>
<li>start = 4</li>
<li>end = 8</li>
</ul>
<p>I want the yanked content is <code>bbbb</code></p>
<p>The <code>visual mode</code> does finish it, but I think there may a vim command for it</p>
| [
{
"answer_id": 74208361,
"author": "Markram",
"author_id": 7374564,
"author_profile": "https://Stackoverflow.com/users/7374564",
"pm_score": 2,
"selected": false,
"text": "coroutineScope.launch {\n val itemInfo = lazyListState.layoutInfo.visibleItemsInfo.firstOrNull { it.i... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74205024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16576016/"
] |
74,205,054 | <p>I've a string with Spanish language and I need to remove some characters '[', ']' etc,. from it. If i use <code>str.Trim('p', 'P', '[', ']')</code> it is not doing the work. Can someone help me?</p>
<pre><code>stirng str="¿Quiere poner en blanco la pantalla? Presione 1 para la pantalla en blanco, presione 2 para mantener la pantalla. Para cancelar esta operación, presione la tecla cancelar [P200] Presione la tecla inferior derecha para ajustar el volumen [P200] Para repetir las instrucciones, presione la tecla inferior izquierda en el teclado"
</code></pre>
| [
{
"answer_id": 74205293,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 1,
"selected": false,
"text": "String.Trim"
},
{
"answer_id": 74205477,
"author": "Chanikya",
"author_id": 8375010,
"author... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74205054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8375010/"
] |
74,205,056 | <p>I have 2 arrays:
<code>int element[3] = {0, 1, 2};</code>
<code>int quantity[3] = {2, 3, 4};</code>
Now I want a result array that will have two zeros, three ones and four twos.
<code>int result[2+3+4] = {0, 0, 1, 1, 1, 2, 2, 2, 2};</code>
How do I do this using loop?</p>
| [
{
"answer_id": 74205293,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 1,
"selected": false,
"text": "String.Trim"
},
{
"answer_id": 74205477,
"author": "Chanikya",
"author_id": 8375010,
"author... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74205056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20150161/"
] |
74,205,104 | <p>I'm learning how classes work in JS and I'm trying to figure out how you can create a sub-class from a class with no constructor arguments and only hardcoded values</p>
<p>I just want the boss class to inherit the hardcoded properties of NPC, I'm changing the array in Boss but I want the logic for the weapon selection to stay the same.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class NPC {
constructor() {
this.weaponsArray = ['Sword', 'Gun', 'Axe']
this.weapon = this.weaponsArray[Math.floor(Math.random * 3)]
}
}
class Boss extends NPC {
constructor() {
super()
this.weaponsArray = ['Mongo Hammer', 'Sword of Death', 'Gun of Pity']
}
}
let bossguy = new Boss()
console.log(bossguy.weapon)</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74205293,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 1,
"selected": false,
"text": "String.Trim"
},
{
"answer_id": 74205477,
"author": "Chanikya",
"author_id": 8375010,
"author... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74205104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19765757/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.