qid
int64 4
22.2M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,461,593
|
<h2>Background</h2>
<p>I am trying to create an embedded schema that needs to save information about orders.
Sometimes orders have no <code>customer_id</code> and that is fine (for the application).</p>
<pre><code>defmodule Order do
use Ecto.Schema
embedded_schema do
field(:customer_id, :integer | nil)
field(:stage, enum: [:bought | :in_shop_cart | :canceled])
field(:details, :string)
end
end
</code></pre>
<h2>Problem</h2>
<p>The issue here is that I get a compile error for <code>customer_id</code>:</p>
<pre><code>(CompileError) misplaced operator |/2
The | operator is typically used between brackets as the cons operator:
[head | tail]
where head is a single element and the tail is the remaining of a list.
It is also used to update maps and structs, via the %{map | key: value} notation,
and in typespecs, such as @type and @spec, to express the union of two types
</code></pre>
<p>I understand the issue here is the use of <code> :integer | nil</code>. This is not a list, so the advice I get is not usable.</p>
<h2>Question</h2>
<p>How can I represent optional values in my embedded schema ? (specifically <code>:something | nil</code>)</p>
|
[
{
"answer_id": 74461930,
"author": "BenFenner",
"author_id": 14837782,
"author_profile": "https://Stackoverflow.com/users/14837782",
"pm_score": 0,
"selected": false,
"text": "num = 6.6\nnum.is_a?(Integer)\n=> false\nnum.is_a?(Float)\n=> true\n"
},
{
"answer_id": 74461949,
"author": "engineersmnky",
"author_id": 1978251,
"author_profile": "https://Stackoverflow.com/users/1978251",
"pm_score": 2,
"selected": false,
"text": "gets"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74461593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1337392/"
] |
74,461,607
|
<p>I am working with <code>jira</code> api and in one of request I get the response with date field in format like this: <code>2022-10-26T09:34:00.000+0000</code>. I need to convert this to <code>LocalDate</code> but I do not know how to to this with this strange format.
Here are some of formats I already tried:</p>
<pre><code>DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
DateTimeFormatter.ISO_LOCAL_DATE_TIME
</code></pre>
<p>but both cannot deserialize this <code>+</code> sign at the end of the date.</p>
<p><code>Text '2022-10-27T09:34:00.000+0000' could not be parsed, unparsed text found at index 24</code></p>
|
[
{
"answer_id": 74461930,
"author": "BenFenner",
"author_id": 14837782,
"author_profile": "https://Stackoverflow.com/users/14837782",
"pm_score": 0,
"selected": false,
"text": "num = 6.6\nnum.is_a?(Integer)\n=> false\nnum.is_a?(Float)\n=> true\n"
},
{
"answer_id": 74461949,
"author": "engineersmnky",
"author_id": 1978251,
"author_profile": "https://Stackoverflow.com/users/1978251",
"pm_score": 2,
"selected": false,
"text": "gets"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74461607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20036372/"
] |
74,461,698
|
<p>I receive input data like that into a web service developed using a Genexus Procedure:
<code>SmsMessageSid=SM7e1ab417617176ec9936788235aaf020&NumMedia=0&ProfileName=Checho&SmsSid=SM7e1ab417617176ec9936788235aaf045&WaId=5699999999&SmsStatus=received&Body=**Este+es+un+texto+lago+que+incluye+%3A+%25+.+%F0%9F%99%82+%28emoji%29**&To=whatsapp%3A%2B189898886&NumSegments=1&ReferralNumMedia=0&MessageSid=SM7e1ab417617176ec9936788235aaf020&AccountSid=ACfda172076a87805952e99b3be82007d9&From=whatsapp%3A%2B56975495288&ApiVersion=2010-04-01</code></p>
<p>I need access to Body parameter, but it has url format.
It's necessary to convert body's value to a clear text.</p>
<p>Regards!</p>
<p>Genexus has URLEncode function, but it's necessary the reverse function.
<a href="https://i.stack.imgur.com/aH9UW.png" rel="nofollow noreferrer">Genexus functions</a></p>
|
[
{
"answer_id": 74464895,
"author": "ealmeida",
"author_id": 320646,
"author_profile": "https://Stackoverflow.com/users/320646",
"pm_score": 1,
"selected": false,
"text": "&pattern = '&Body=\\w*&' //CHECK THIS!!\n&rslt = &url.Matches(&pattern)\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74461698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20358404/"
] |
74,461,707
|
<p>Let's say I have a DataFrame <code>df=pd.DataFrame({'a':[1,2,np.nan,3,4,5,3], 'b':[11,22,22,11,22,22,22]})</code></p>
<pre><code> a b
0 1.0 11
1 2.0 22
2 NaN 22
3 3.0 11
4 4.0 22
5 5.0 22
6 3.0 22
</code></pre>
<p>I want compute a reduced dataframe where I group by <code>b</code>, and where my column depends on the groupwise mean. Specifically, I want the column to contain the</p>
<p><strong>number of elements in <code>a</code> that are smaller than the group wise mean</strong>.</p>
<p>For this I found a solution which seems like it could be improved because I am guessing it recomputed the mean 2 times for the '11' group and 5 times for the '22' group:</p>
<p><strong>Slow solution</strong> using groupby, agg and NamedAgg:</p>
<p><code>df.groupby('b').agg(c=pd.NamedAgg(column='a', aggfunc=lambda x: sum(i<x.mean() for i in x)))</code></p>
<pre><code>dff=df.groupby('b').agg(c=pd.NamedAgg(column='a', aggfunc=lambda x: sum(i<x.mean() for i in x)))
print(dff)
c
b
11 1
22 2
</code></pre>
<p>Do you know a better way where the mean is only computed once per group?</p>
<p>I have searched parameters in pandas merge, concat, join, agg, apply etc. But I think there must be a savant combination of these that would achieve what I am trying to do.</p>
|
[
{
"answer_id": 74464895,
"author": "ealmeida",
"author_id": 320646,
"author_profile": "https://Stackoverflow.com/users/320646",
"pm_score": 1,
"selected": false,
"text": "&pattern = '&Body=\\w*&' //CHECK THIS!!\n&rslt = &url.Matches(&pattern)\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74461707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20520568/"
] |
74,461,737
|
<p>I am trying to load an HTML form in a webview that has some callbacks on button clicks which I am trying to handle in a javascript handler but are not getting invoked.</p>
<p>Library used</p>
<pre><code>flutter_inappwebview: ^5.7.1
</code></pre>
<p>This is how I defined the webview.</p>
<pre><code>InAppWebView(
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
useShouldOverrideUrlLoading: true,
mediaPlaybackRequiresUserGesture: false,
),
android: AndroidInAppWebViewOptions(
useHybridComposition: true,
),
ios: IOSInAppWebViewOptions(
allowsInlineMediaPlayback: true,
)
),
initialUrlRequest: URLRequest(
url: Uri.dataFromString(
'about:blank',
mimeType: 'text/html',
)),
onWebViewCreated: (controller) {
controller.addJavaScriptHandler(
handlerName: 'showToast',
callback: (data) {
AppUtils.showMessage(data);
print('data -$data');
});
setState((){
_controller = controller;
});
loadForm();
},
onLoadStop: (controller,uri){
},
onConsoleMessage: (controller, message) {
print('on Console message - $message');
},
)
</code></pre>
<p>And in load form I am using an html page which looks like</p>
<pre><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">
<title>Test</title>
</head>
<script>
isAppReady = false;
window.addEventListener("flutterInAppWebViewPlatformReady", function (event) {
isAppReady = true;
});
function buttonClick() {
if (isAppReady) {
window.flutter_inappwebview.callHandler('showToast', 'result');
}
}
</script>
<body>
<button onclick="buttonClick()" type="button">Show</button>
</body>
</html>
</code></pre>
<p>Now The event listener is never invoked hence the boolean value is app ready and is not changed. Any help regarding why it is not getting invoked is appreciated</p>
|
[
{
"answer_id": 74464895,
"author": "ealmeida",
"author_id": 320646,
"author_profile": "https://Stackoverflow.com/users/320646",
"pm_score": 1,
"selected": false,
"text": "&pattern = '&Body=\\w*&' //CHECK THIS!!\n&rslt = &url.Matches(&pattern)\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74461737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10488726/"
] |
74,461,758
|
<p>I am trying to write down a CSV using python with multiple lines inside the same cell. For example i want the next result:</p>
<p><a href="https://i.stack.imgur.com/LN3YC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LN3YC.png" alt="enter image description here" /></a></p>
<p>But I am getting this result:</p>
<p><a href="https://i.stack.imgur.com/f51My.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f51My.png" alt="enter image description here" /></a></p>
<p>I have tried several ways to insert a "\n" between both elements of the cell but not working. My last attempt was the next piece of code:</p>
<pre><code>f=open("prueba.csv","a",newline="")
header=["Prueba","Prueba2"]
writer=csv.writer(f)
writer.writerow(header)
prueba11="123"
prueba21="123"
prueba22="124"
prueba1=prueba11
prueba2=prueba21+"\n"+(prueba22)
prueba_write2=str(prueba2)
prueba_write1=str(prueba1)
row=[prueba_write1,prueba_write2]
writer.writerow(row)
f.close()
</code></pre>
<p>Does somebody know if it is a easy way to get the desired result?
Thanks!</p>
|
[
{
"answer_id": 74464895,
"author": "ealmeida",
"author_id": 320646,
"author_profile": "https://Stackoverflow.com/users/320646",
"pm_score": 1,
"selected": false,
"text": "&pattern = '&Body=\\w*&' //CHECK THIS!!\n&rslt = &url.Matches(&pattern)\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74461758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10640450/"
] |
74,461,782
|
<p>I'm pretty new to c# (and fwiw, moq) and I'm trying learn our product by writing unit tests. We have the following method in a database repository class:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using Dapper;
using Newtonsoft.Json;
using Serilog;
public bool UpdateInactiveWidgets(List<Widgets> widgets)
{
int rowsUpdated;
using (var conn = new SqlConnection(connectionString))
{
rowsUpdated= conn.Execute(@"UPDATE dbo.Widgets
SET [Status] = 'Inactive'
WHERE ID = @ID", widgets);
}
return rowsUpdated == widgets.Count ? true : false;
}
</code></pre>
<p>I'd like to write a unit test for this, but I can't seem to get the mock connection going.
Based on other posts about mocking a connection, I've added the following to my unit test:</p>
<pre><code> [Fact]
public void Update_Inactive_Widgets()
{
var repo = new WidgetRepository();
var inActiveWidgets = new List<Widgets>()
{ //logic to create 2 widgets };
var connectionMock = new Mock<IDbConnection>();
connectionMock.Setup(m => m.Execute(It.IsAny<string>(),It.IsAny<object>(),null,null,null)).Returns(2);
var result = repo.UpdateInactiveWidgets(inActiveWidgets );
Assert.Equal(inActiveWidgets.Count,result);
</code></pre>
<p>The unit test fails on the connectionMock.Setup line with this error:</p>
<blockquote>
<p>System.NotSupportedException: 'Unsupported expression: m =>
m.Execute(It.IsAny(), It.IsAny(), null, null, null)
Extension methods (here: SqlMapper.Execute) may not be used in setup /
verification expressions.'</p>
</blockquote>
<p>I've found this article and am still making my way through to see how I can apply the points to my example: <a href="https://taurit.pl/moq-extension-methods-may-not-be-used-in-setup-verification-expressions/" rel="nofollow noreferrer">https://taurit.pl/moq-extension-methods-may-not-be-used-in-setup-verification-expressions/</a></p>
<p>But if you have any suggestions I'd appreciate it. I apologize in advance if I'm missing something basic.</p>
<p><strong>Edit 2</strong></p>
<p>If I made the connection a global variable in the class... and move the logic that connects outside the method under test would that help?</p>
<p>Sample pseudocode:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using Dapper;
using Newtonsoft.Json;
using Serilog;
public UpdateInactiveWidgets()
{
var _conn;
}
public Connect_db()
{
_conn = new SqlConnection(connectionString);
}
public DisConnect_db()
{
//some logic to kill the db connection?
}
public bool UpdateInactiveWidgets(List<Widgets> widgets)
{
int rowsUpdated;
//would the using() still be applicable?
using (_conn)
{
rowsUpdated= _conn.Execute(@"UPDATE dbo.Widgets
SET [Status] = 'Inactive'
WHERE ID = @ID", widgets);
}
return rowsUpdated == widgets.Count ? true : false;
}
</code></pre>
|
[
{
"answer_id": 74461871,
"author": "Jeanot Zubler",
"author_id": 14906662,
"author_profile": "https://Stackoverflow.com/users/14906662",
"pm_score": 1,
"selected": false,
"text": "public bool UpdateInactiveWidgets(List<Widgets> widgets, IDbConnection connection)\n{\n int rowsUpdated;\n using (connection) \n { \n rowsUpdated= _conn.Execute(@\"UPDATE dbo.Widgets\n SET [Status] = 'Inactive'\n WHERE ID = @ID\", widgets);\n }\n return rowsUpdated == widgets.Count ? true : false; \n}\n"
},
{
"answer_id": 74462577,
"author": "DevFlamur",
"author_id": 9814906,
"author_profile": "https://Stackoverflow.com/users/9814906",
"pm_score": 0,
"selected": false,
"text": "moq"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74461782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1078009/"
] |
74,461,838
|
<p>Image on the left, text on the right. Image size is unknown. I want to display the image in its original size. I want the text at least 10-character wide (i.e., not too narrow).</p>
<p>If I resize the browser window to make it narrow, when the text cannot become narrower, the page shows horizontal scroll bar. Can I at this point reduce the image width instead? Again, image size is not fixed. I wonder if this can be done with CSS only, or if I use JavaScript.</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.item {
display: flex;
}
.rightText {
margin-top: 0;
margin-left: 1em;
min-width: 10em;
}
</style>
</head>
<body>
<div class="item">
<img src="https://www.asahicom.jp/and/data/wp-content/uploads/2018/08/1-1.jpg"/>
<div class="rightText">
きこえるかしらひずめの音ゆるやかな丘をぬってかけてくる馬車
きこえるかしらひずめの音ゆるやかな丘をぬってかけてくる馬車
きこえるかしらひずめの音ゆるやかな丘をぬってかけてくる馬車
きこえるかしらひずめの音ゆるやかな丘をぬってかけてくる馬車
</div>
</div>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 74461871,
"author": "Jeanot Zubler",
"author_id": 14906662,
"author_profile": "https://Stackoverflow.com/users/14906662",
"pm_score": 1,
"selected": false,
"text": "public bool UpdateInactiveWidgets(List<Widgets> widgets, IDbConnection connection)\n{\n int rowsUpdated;\n using (connection) \n { \n rowsUpdated= _conn.Execute(@\"UPDATE dbo.Widgets\n SET [Status] = 'Inactive'\n WHERE ID = @ID\", widgets);\n }\n return rowsUpdated == widgets.Count ? true : false; \n}\n"
},
{
"answer_id": 74462577,
"author": "DevFlamur",
"author_id": 9814906,
"author_profile": "https://Stackoverflow.com/users/9814906",
"pm_score": 0,
"selected": false,
"text": "moq"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74461838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/455796/"
] |
74,461,909
|
<p>I have <code>items</code> object as below. And I would like to find the object whose <code>created</code> is the newest.</p>
<pre><code>const items = [
{ id: 'djw8701', created: '2019-10-05T11:06:20.208Z', url: 'url1' },
{ id: 'djw8702', created: '2019-10-15T12:06:21.208Z', url: 'url2' },
{ id: 'djw8703', created: '2019-10-20T13:06:22.208Z', url: 'url3' }
]
</code></pre>
<p>I would like to compare the objects in the array and get one with newest date <code>items[2]</code></p>
<p>My approach below returns nothing.</p>
<pre><code>items?.reduce((curr, acc) => {
if (curr.created < acc.created) {
return { ...acc };
}
})
</code></pre>
|
[
{
"answer_id": 74462008,
"author": "c_thane",
"author_id": 10832339,
"author_profile": "https://Stackoverflow.com/users/10832339",
"pm_score": 1,
"selected": false,
"text": "if (new Date(curr.deliveryDate) < new Date(acc.deliveryDate))\n"
},
{
"answer_id": 74462013,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": 3,
"selected": true,
"text": "new Date()"
},
{
"answer_id": 74462179,
"author": "axiac",
"author_id": 4265352,
"author_profile": "https://Stackoverflow.com/users/4265352",
"pm_score": 1,
"selected": false,
"text": "const deliveries = [\n { id: 'HgP6cJB01', deliveryDate: '2022-10-05T11:06:20.208Z', url: 'some link1' },\n { id: 'HgP6cJB02', deliveryDate: '2022-10-15T12:06:21.208Z', url: 'some link2' },\n { id: 'HgP6cJB03', deliveryDate: '2022-10-20T13:06:22.208Z', url: 'some link3' }\n];\n\nconst oldest = deliveries.reduce(\n (acc, curr) => acc.deliveryDate < curr.deliveryDate ? curr : acc\n);\n\nconsole.log(oldest);"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74461909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12343741/"
] |
74,461,916
|
<p>I have data coming from an API that provides an object with a year. I'm creating headings with possible years, and then I'd like to display the data of the object if it matches that year. There can be multiple objects that match the same year.</p>
<p>What I'm doing currently, but with no avail:</p>
<p>Simplified example:</p>
<pre><code>export default function App() {
const years = [2020, 2019, 2018];
const data = [{ year: 2019, test: "test" }];
return (
<div>
{years.map((year) => (
<h1>{year}</h1>
{data.map(d => (
<div>{d}</div>
))}
))}
</div>
);
}
</code></pre>
<p>This doesnt display anything. What could I be missing? Should I filter instead of check for a condition? The code doesn't seem to loop inside a loop (map inside a map). Should I be able to do this, considering the syntax, as this returns:</p>
<blockquote>
<p>Unexpected token, expected "," (11:8)</p>
</blockquote>
|
[
{
"answer_id": 74462573,
"author": "mahdikmg",
"author_id": 11590227,
"author_profile": "https://Stackoverflow.com/users/11590227",
"pm_score": 2,
"selected": false,
"text": "<div>\n {years.map((year) => <>\n <h1>{year}</h1>\n {data.map(d => (\n <div>{d.year}</div>\n ))}\n </>)}\n</div>\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74461916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4942596/"
] |
74,461,918
|
<p>how to round BottomAppBar in flutter I want to Circle top left and top right like this</p>
<p><img src="https://i.stack.imgur.com/8pdnQ.png" alt="enter image description here" /></p>
<pre><code> bottomNavigationBar: BottomAppBar(
color: Colors.green[200]?.withOpacity(0.8),
child: Container(
height: MediaQuery.of(context).size.height/9,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.white),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50))),
),
onPressed: () {},
child: Icon(
Icons.store,
color: Colors.black87,
size: 50,
),
),
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.white),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50))),
),
onPressed: () {},
child: Icon(
Icons.home,
color: Colors.black87,
size: 50,
),
),
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.white),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50))),
),
onPressed: () {},
child: Icon(
Icons.settings,
color: Colors.black87,
size: 50,
),
)
],
)
),
)
</code></pre>
|
[
{
"answer_id": 74462041,
"author": "manhtuan21",
"author_id": 8921450,
"author_profile": "https://Stackoverflow.com/users/8921450",
"pm_score": 1,
"selected": false,
"text": " bottomNavigationBar: ClipRRect(\n borderRadius: BorderRadius.only(\n topLeft: Radius.circular(30.0),\n topRight: Radius.circular(30.0),\n ),\n child: BottomAppBar(\n color: Colors.green[200]?.withOpacity(0.8),\n child: Container(\n height: MediaQuery.of(context).size.height / 9,\n child: Row(\n mainAxisAlignment: MainAxisAlignment.spaceEvenly,\n children: [\n ElevatedButton(\n style: ButtonStyle(\n backgroundColor: MaterialStateProperty.all(Colors.white),\n shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(50))),\n ),\n onPressed: () {},\n child: Icon(\n Icons.store,\n color: Colors.black87,\n size: 50,\n ),\n ),\n ElevatedButton(\n style: ButtonStyle(\n backgroundColor: MaterialStateProperty.all(Colors.white),\n shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(50))),\n ),\n onPressed: () {},\n child: Icon(\n Icons.home,\n color: Colors.black87,\n size: 50,\n ),\n ),\n ElevatedButton(\n style: ButtonStyle(\n backgroundColor: MaterialStateProperty.all(Colors.white),\n shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(50))),\n ),\n onPressed: () {},\n child: Icon(\n Icons.settings,\n color: Colors.black87,\n size: 50,\n ),\n )\n ],\n )),\n ),\n ),\n"
},
{
"answer_id": 74462151,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 0,
"selected": false,
"text": "ClipRRect"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74461918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16559390/"
] |
74,461,923
|
<p>the problem is I want to change the src of img tag by using the button which executes if, else function. but I think my code is unprofessional and there is a better way to do the same job.</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 smile = true
let test = () => {
if (smile == true) {
document.getElementById("image").src = "https://images.freeimages.com/images/large-previews/adb/fruit-in-a-bowl-1637721.jpg";
smile = false
}
else {
document.getElementById("image").src = "https://images.freeimages.com/images/large-previews/a33/fresh-red-ripe-strawberries-1641723.jpg";
smile = true
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <img id="image" src="https://images.freeimages.com/images/large-previews/a33/fresh-red-ripe-strawberries-1641723.jpg" width="160" height="120">
<button type="button" onclick="test()">over here </button></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74462486,
"author": "Mazen Alhrazi",
"author_id": 6798139,
"author_profile": "https://Stackoverflow.com/users/6798139",
"pm_score": 0,
"selected": false,
"text": "img.onclick = () => { ... }"
},
{
"answer_id": 74462983,
"author": "HackerFrosch",
"author_id": 20357737,
"author_profile": "https://Stackoverflow.com/users/20357737",
"pm_score": 2,
"selected": true,
"text": "data-smile=\"false\""
},
{
"answer_id": 74463808,
"author": "Peter Seliger",
"author_id": 2627243,
"author_profile": "https://Stackoverflow.com/users/2627243",
"pm_score": 0,
"selected": false,
"text": "data-*"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74461923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17620112/"
] |
74,461,952
|
<p>Why can't I save ArrayList size as a variable?</p>
<pre><code>public static ArrayList <Integer > merge(ArrayList <Integer > list1,
ArrayList <Integer > list2 ) {
if (list1.size() >= list2.size()) {
int maxSize = list1.size();
} else {
int maxSize = list2.size();
}
for (int i = 0; i < maxSize; i++) {
if (i <= list2.size()) {
int nextInList2 = list2.get(i);
list1.add(i, nextInList2);
}
}
System.out.println(list1);
return (list1);
</code></pre>
<p>in:
int maxSize = list1.size();
I assume that it's not saving the variable as I want to.</p>
<p>I assume that</p>
<pre><code>list1.size()
</code></pre>
<p>is an integer</p>
|
[
{
"answer_id": 74462030,
"author": "Reg",
"author_id": 1169349,
"author_profile": "https://Stackoverflow.com/users/1169349",
"pm_score": 4,
"selected": true,
"text": "int maxSize = 0;\nif (list1.size() >= list2.size()) {\n maxSize = list1.size(); \n} else {\n maxSize = list2.size();\n}\n\n// Now maxSize can be used as you wish :)\nfor (int i = 0; i < maxSize; i++) { ...\n"
},
{
"answer_id": 74462094,
"author": "so-random-dude",
"author_id": 6785908,
"author_profile": "https://Stackoverflow.com/users/6785908",
"pm_score": 2,
"selected": false,
"text": "maxSize"
},
{
"answer_id": 74464091,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 0,
"selected": false,
"text": "if"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74461952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20071783/"
] |
74,461,973
|
<p>I am passing the data from parent to child component and the normal text input is populated which the data received from the parent but this isn't working with the dropdowns.</p>
<p>Code block where I pass data to the variable <strong>enteredName</strong> is working just as I want it to work.</p>
<pre><code> <span class="p-float-label">
<input #nameID="ngModel" [(ngModel)]="enteredName" [style]="{'width':'100%'}" [textContent]="name" id="nameID"
maxlength="256" name="nameID" pInputText required type="text" />
<label for="nameID">Name</label>
</span>
</code></pre>
<p>But when I pass the "<strong>selectedRecorderType</strong>" it dosent appear as the option selected from the dropdown.</p>
<p>Below is the code for it.</p>
<pre><code> <span class="p-float-label">
<p-dropdown [options]="recorderType" name="recorderTypeID" id="recorderTypeID" optionLabel="name"
[autoDisplayFirst]="false" #recorderTypeID="ngModel" [(ngModel)]="selectedRecoderType"
[disabled]="(!userCanAdd && !userCanModify)" (onChange)="onChangeRecorderType($event)" [required]=true [style]="{'width': '100%'}" appendTo="body">
</p-dropdown>
<label for="recorderTypeID">Recorder Type</label>
</span>
</code></pre>
<p>Below is the component TS File
I changed the variable from "<strong>selectedRecorder</strong>" to "<strong>selectedRecoderType</strong>", but then I am still with the same problem.
Can I know what wrong am I doing.</p>
<p><strong>P.S I have updated the Screenshot below as well.</strong></p>
<pre><code> this.enteredName = "hey";
this.selectedRecoderType = "Hello";
</code></pre>
<p><strong>EDIT</strong></p>
<p>this.enteredName = "hey";
this.selectedRecoderType = "HELLO";</p>
<p><a href="https://i.stack.imgur.com/eSB5e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eSB5e.png" alt="[](https://i.stack.imgur.com/PO7RM.png)" /></a></p>
|
[
{
"answer_id": 74462030,
"author": "Reg",
"author_id": 1169349,
"author_profile": "https://Stackoverflow.com/users/1169349",
"pm_score": 4,
"selected": true,
"text": "int maxSize = 0;\nif (list1.size() >= list2.size()) {\n maxSize = list1.size(); \n} else {\n maxSize = list2.size();\n}\n\n// Now maxSize can be used as you wish :)\nfor (int i = 0; i < maxSize; i++) { ...\n"
},
{
"answer_id": 74462094,
"author": "so-random-dude",
"author_id": 6785908,
"author_profile": "https://Stackoverflow.com/users/6785908",
"pm_score": 2,
"selected": false,
"text": "maxSize"
},
{
"answer_id": 74464091,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 0,
"selected": false,
"text": "if"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74461973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20328812/"
] |
74,462,028
|
<p>Environment: .NET 6 WebAPI app</p>
<p>I have two classes, base an derived, that both can be used to serialize the output of a certain method as JSON and send it to client. They look like this:</p>
<pre><code>public class Base
{
public int? Prop1 { get; set; }
public string? Prop2 { get; set; }
public long? Prop3 { get; set; }
...
}
public class Derived: Base
{
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public new int? Prop1 { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public new string? Prop2 { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public new long? Prop3 { get; set; }
...
}
</code></pre>
<p>and a generic model class that has a collection of Base objects:</p>
<pre><code>public class Model
{
public List<Base>? Properties { get; set; }
...
}
</code></pre>
<p>I would like to always serialize the keys of <code>Base</code> objects inside the <code>Properties</code> collection, but skip the keys where the values are <code>null</code> if I'm serializing a collection of <code>Derived</code> objects. Sample code of what I want to achieve:</p>
<pre><code> var baseModel = new Model{ Properties = new List<Base>{ new Base { Prop1 = 1 } } };
var serialized = JsonSerializer.Serialize(baseModel);
// This returns '{ "properties": { "Prop1": 1, "Prop2": null, "Prop3": null }}'
var derivedModel = new Model { Properties = new List<Derived>{ new Derived { Prop1 = 1 }}};
// This doesn't compile because of type mismatch
var derivedModel2 = new Model { Properties = new List<Base>{ (Base)new Derived { Prop1 = 1 }}};
// This works, but also returns '{ "properties": { "Prop1": 1, "Prop2": null, "Prop3": null }}'
// I need to get '{ "properties": { "Prop1": 1 } }' here
</code></pre>
<p>Any advice on where to look?</p>
<p>UPD: I've considered a generic class use, but my model is currently used in the following manner (simplified):</p>
<pre><code>public class BusinessLogic: IBusinessLogic
{
... // Constructor with DI etc.
public async Task<Model> GetStuff(...)
{
...
var model = GetModelInternal(...);
...
return model;
}
}
public interface IBusinessLogic
{
...
public Task<Model> GetStuff(...);
...
}
public class MyController: ApiController
{
protected readonly IBusinessLogic _bl;
public MyController(..., IBusinessLogic bl)
{
_bl = bl;
}
[HttpGet]
public async Task<IActionResult> GetStuff(bool baseOrDerived, ...)
{
var model = await _bl.GetModel(baseOrDerived, ...);
return Json(model);
}
}
</code></pre>
<p>The type of the return objects (Base or Derived) needs to depend upon the input parameter <code>baseOrDerived</code> that I get from the API client. This means that in order to use a generic I would need to pass the type parameter all the way through the controller. Moreover, I will have to introduce the same parameter to the <code>IBusinessLogic/BusinessLogic</code> pair and instead of simply getting <code>IBusinessLogic</code> instance from the DI, I would have to get a <code>ServiceProvider</code> instance there, create a scope inside the action and construct templated instance of <code>IBusinessLogic</code> dynamically. Given that this is NOT the only class I want this behavior from, this seems a real overkill to me.</p>
|
[
{
"answer_id": 74462030,
"author": "Reg",
"author_id": 1169349,
"author_profile": "https://Stackoverflow.com/users/1169349",
"pm_score": 4,
"selected": true,
"text": "int maxSize = 0;\nif (list1.size() >= list2.size()) {\n maxSize = list1.size(); \n} else {\n maxSize = list2.size();\n}\n\n// Now maxSize can be used as you wish :)\nfor (int i = 0; i < maxSize; i++) { ...\n"
},
{
"answer_id": 74462094,
"author": "so-random-dude",
"author_id": 6785908,
"author_profile": "https://Stackoverflow.com/users/6785908",
"pm_score": 2,
"selected": false,
"text": "maxSize"
},
{
"answer_id": 74464091,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 0,
"selected": false,
"text": "if"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/625594/"
] |
74,462,031
|
<p>I am trying to create a function which takes in 2 strings:</p>
<p>-
title: "Lorem ipsum dolor sit amet",</p>
<p>-
itle_highlighted: "ipsum amet",</p>
<p>and returns one string or array containing the all words in <code>title</code> in addition words defined in the string <code>title_highlighted</code> will have a certain property and replace their matching word in <code>title</code>.</p>
<p>End result should be something like: <code><h1>Lorem<span style={{color: "orange"}}>impsum</span>dolor sit<span style={{color: "orange"}}>amet</span>/h1></code></p>
<p><a href="https://i.stack.imgur.com/a6Y5q.png" rel="nofollow noreferrer">Output example</a></p>
<p>My approach so far:</p>
<pre><code>const highlightHeading = (title, title_highlighted) => {
const title_arr = title.trim().split(/\s+/);
const title_highlighted_arr = title_highlighted.trim().split(/\s+/);
for (const element1 of title_arr) {
console.log(element1);
for (const element2 of title_highlighted_arr) {
if (element1 === element2) {
const highlighted = `<span style={{ color: "orange" }}>${element1}</span>`;
console.log(highlighted);
}
}
}
};
highlightHeading("Lorem ipsum dolor sit amet", "ipsum amet");
</code></pre>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 74462204,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": -1,
"selected": false,
"text": "Lorem ipsum? Dolor amet!"
},
{
"answer_id": 74462392,
"author": "Mr. Polywhirl",
"author_id": 1762224,
"author_profile": "https://Stackoverflow.com/users/1762224",
"pm_score": 1,
"selected": true,
"text": "<HighlightedHeading>"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19293202/"
] |
74,462,057
|
<p>I wrote a sql query but as you noticed there are two identical records with the same name and id number. I need to show them all somehow without using Distinct. The middleware I'm using fills in values based on UserTableID. If we use DISTINCT, the query will not work while UserTableID is present. Can you help me?</p>
<pre><code>select UserTableID as [ID], Ad_Soyad AS [NAME SURNAME], Kimlik_No AS [IDENTIFICATION NUMBER]
from SA_OtelRezervasyon
ID NAME SURNAME IDENTIFICATION NUMBER
1 Ali AKYÜZ 11111111111
2 Osman 22222222222
3 Ali AKYÜZ 11111111111
4 Mustafa Batuhan 33333333333
</code></pre>
|
[
{
"answer_id": 74462364,
"author": "Nenad Zivkovic",
"author_id": 612181,
"author_profile": "https://Stackoverflow.com/users/612181",
"pm_score": 0,
"selected": false,
"text": "WITH CTE_OtelRezervasyon AS\n(\n SELECT UserTableID AS [ID]\n , Ad_Soyad AS [NAME SURNAME]\n , Kimlik_No AS [IDENTIFICATION NUMBER]\n , ROW_NUMBER() OVER (PARTITION BY Ad_Soyad, Kimlik_No ORDER by UserTableID) AS RN\n FROM SA_OtelRezervasyon\n)\nSELECT [ID], [NAME SURNAME], [IDENTIFICATION NUMBER]\nFROM CTE_OtelRezervasyon \nWHERE RN = 1;\n"
},
{
"answer_id": 74462426,
"author": "b_loy",
"author_id": 20382717,
"author_profile": "https://Stackoverflow.com/users/20382717",
"pm_score": 0,
"selected": false,
"text": "WITH row_table AS (\n SELECT ROW_NUMBER() OVER(PARTITION BY ut.ID_Num ORDER BY ut.ID) AS new_row_number\n ,ut.UserTableID\n ,ut.Ad_Soyad\n ,ut.Kimlik_No\n FROM dbo.UserTable ut\n )\nselect * \nFROM row_table rt where rt.new_row_number = 1 order by rt.ID\n"
},
{
"answer_id": 74462576,
"author": "Arvo",
"author_id": 35777,
"author_profile": "https://Stackoverflow.com/users/35777",
"pm_score": 2,
"selected": true,
"text": "select min(UserTableID) as [ID], Ad_Soyad AS [NAME SURNAME], Kimlik_No AS [IDENTIFICATION NUMBER]\nfrom SA_OtelRezervasyon\ngroup by Ad_Soyad, Kimlik_No\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20519851/"
] |
74,462,061
|
<p>I have a list of tuples with the pattern "id", "text", "language" like this:</p>
<pre><code>a = [('1', 'hello', 'en'), ...]
</code></pre>
<p>I would like to increase number of tuple members to "id", "text", "language", "color":</p>
<pre><code>b = [('1', 'hello', 'en', 'red'), ...]
</code></pre>
<p>What is the correct way of doing this?</p>
<p>Thank you.</p>
|
[
{
"answer_id": 74462129,
"author": "Matthias",
"author_id": 1209921,
"author_profile": "https://Stackoverflow.com/users/1209921",
"pm_score": 3,
"selected": true,
"text": "a = [('1', 'hello', 'en'), ('2', 'hi', 'en')]\ncolor = 'red'\n\na = [(x + (color,)) for x in a]\nprint(a)\n"
},
{
"answer_id": 74462222,
"author": "Thales",
"author_id": 20401787,
"author_profile": "https://Stackoverflow.com/users/20401787",
"pm_score": 1,
"selected": false,
"text": "a[0] = list(a[0])\na[0].append(\"red\")\na[0] = tuple(a[0])\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3449908/"
] |
74,462,066
|
<p>my Python code has a circle which moves from the right of the screen to the left but it stops. I would like it to bounce off the left edge and continue moving to the right and then bounce off the right edge to the left and so on. I think I'm missing a line. I have tried several things but it doesn't seem to be working. Please see code below. Any advice would be very grateful.</p>
<pre><code>import pygame
pygame.init()
size = width, height = 400, 300
screen = pygame.display.set_mode(size)
x_pos = 380
y_pos = 280
r = 20
running = True
while running: # game cycle
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.draw.circle(screen, (0, 255, 0), (x_pos, y_pos), r)
if x_pos > 20: # do not let the ball roll out of the screen
x_pos -= 1
pygame.time.delay(5) # delay in milliseconds
pygame.display.flip()
pygame.quit()
</code></pre>
<p>I think I am expecting another IF statement which allows it to bounce off the edge. I would like to continue using the code that I have, and I'm looking for just one or two lines that can hopefully solve my problems. I don't want the code to be completely revamped.</p>
|
[
{
"answer_id": 74462129,
"author": "Matthias",
"author_id": 1209921,
"author_profile": "https://Stackoverflow.com/users/1209921",
"pm_score": 3,
"selected": true,
"text": "a = [('1', 'hello', 'en'), ('2', 'hi', 'en')]\ncolor = 'red'\n\na = [(x + (color,)) for x in a]\nprint(a)\n"
},
{
"answer_id": 74462222,
"author": "Thales",
"author_id": 20401787,
"author_profile": "https://Stackoverflow.com/users/20401787",
"pm_score": 1,
"selected": false,
"text": "a[0] = list(a[0])\na[0].append(\"red\")\na[0] = tuple(a[0])\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20520793/"
] |
74,462,076
|
<p>im currently having trouble to split a column in pentaho that has the item ID at the begining. The main idea is to split the current column into "ItemID" and "ItemName" by "space" delimiter. I split the column with the space delimiter and get the "ItemID" correctly, but i can't get the "ItemName" completly.</p>
<p><a href="https://i.stack.imgur.com/qF4XC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qF4XC.png" alt="Original column and the way that must be splited" /></a></p>
<p>In the resulting columns, "ItemID" is fine, but "ItemName" only gets the first part of the name. I have tried to change the lenght or Trim type, but i see no changes.</p>
<p><a href="https://i.stack.imgur.com/2Wzru.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2Wzru.png" alt="Result" /></a></p>
<p>I would really appreciate some help, many thanks in advance!</p>
|
[
{
"answer_id": 74515785,
"author": "nsousa",
"author_id": 3593498,
"author_profile": "https://Stackoverflow.com/users/3593498",
"pm_score": 1,
"selected": false,
"text": "([^ ]*) (.*)"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12538763/"
] |
74,462,116
|
<p>Is it possible to make all interface fields required but only array type? The Required operator makes all fields mandatory, but I only need those fields that are an array ???</p>
<p>`</p>
<pre><code>interface IExample {
a: number,
b?: string,
c?: number[]
}
function getTest(data: IExample): Required<IExample> {
return {
...data,
c: data.c ?? []
}
}
//Error because the 'c' field is also checked, but it is not an array. How to check for arrays only?
</code></pre>
<p>`</p>
<p>Thanks in advance</p>
<p>I assume that the problem can be solved with tuples, however, no matter how I tried, it did not work out</p>
|
[
{
"answer_id": 74462305,
"author": "acrazing",
"author_id": 4380247,
"author_profile": "https://Stackoverflow.com/users/4380247",
"pm_score": 2,
"selected": false,
"text": "type ArrayKeyof<T> = {\n [P in keyof T]-?: any[] extends T[P] ? P : never;\n}[keyof T];\n\nexport type ArrayRequired<T> = Omit<T, ArrayKeyof<T>> & Required<Pick<T, ArrayKeyof<T>>>;\n\n// demo\n\ninterface IExample {\n a: number,\n b?: string,\n c?: number[]\n}\n\nconst d: ArrayRequired<IExample> = {\n a: 1,\n c: [1],\n}\n"
},
{
"answer_id": 74463087,
"author": "Woohaik",
"author_id": 17200950,
"author_profile": "https://Stackoverflow.com/users/17200950",
"pm_score": 1,
"selected": false,
"text": "KeepAllSameButArraysRequired"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15253473/"
] |
74,462,148
|
<p>I'm trying to process the json data I get from a server but when I try to do a .forEach, on it it says that the data I'm trying to work with is undefined while the console.log displays the correct values.</p>
<p>What could be the problem, am I missing an async/await from somewhere? Am I calling the data processing function too early? If yes how could it be solved?</p>
<p>Relevant parts of the component.ts:</p>
<pre><code>all: any;
constructor(private feedService: FeedService) { }
ngOnInit(): void {
this.fetchPosts();
console.log(this.all);
}
ngAfterContentInit() {
this.feedService.getTags(this.all.posts[0]);
}
async fetchPosts() {
(await this.feedService.getJSON(this.url)).subscribe((data) => {
console.log(data);
this.all = data;
console.log(this.all);
});
}
</code></pre>
<p>Relevant parts of the service:</p>
<pre><code>constructor(private http: HttpClient) {
}
public async getJSON(url: string) {
return this.http.get<any>(url);
}
public async getTags(postData: any) {
let tags = [];
await postData['tags'].array.forEach(tag => { //This throws the error
tags.push(tag); //Uncomplete processign code, for now it
});
return tags;
}
</code></pre>
<p>And here is a screenshot of the console output: <a href="https://i.stack.imgur.com/v57R8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v57R8.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74462305,
"author": "acrazing",
"author_id": 4380247,
"author_profile": "https://Stackoverflow.com/users/4380247",
"pm_score": 2,
"selected": false,
"text": "type ArrayKeyof<T> = {\n [P in keyof T]-?: any[] extends T[P] ? P : never;\n}[keyof T];\n\nexport type ArrayRequired<T> = Omit<T, ArrayKeyof<T>> & Required<Pick<T, ArrayKeyof<T>>>;\n\n// demo\n\ninterface IExample {\n a: number,\n b?: string,\n c?: number[]\n}\n\nconst d: ArrayRequired<IExample> = {\n a: 1,\n c: [1],\n}\n"
},
{
"answer_id": 74463087,
"author": "Woohaik",
"author_id": 17200950,
"author_profile": "https://Stackoverflow.com/users/17200950",
"pm_score": 1,
"selected": false,
"text": "KeepAllSameButArraysRequired"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11605800/"
] |
74,462,186
|
<p>It takes m iterations to transform the array according to the rule: a[i]=(a[i-1]+a[i+1])/2 Also, according to the assignment, I must use Thread and Phaser. Using of Thread and Phaser is mandatory, and there is no way I can refuse to use them.</p>
<p>For transforming I use this code:</p>
<pre><code>package lab3;
import java.util.concurrent.Phaser;
public class Program {
public static void main(String[] args)
{
int n = 100;
int m = 100;
int [] arr;
arr = new int [n];
int [] arr2;
arr2 = new int [n];
for (int i = 0; i<n; i++)
{
int r = (int)(Math.random()*50);
arr [i] = r;
arr2 [i] = r;
System.out.print(arr[i]+" ");
}
int [] arr3 = arr2.clone();
System.out.println(" ");
for (int p = 0; p<m; p++)
for (int i = 1; i<n-1; i++)
{
arr [i] = (arr [i-1]+arr [i+1])/2;
}
for (int i = 0; i<n; i++)
{
System.out.print(arr[i]+" ");
}
System.out.println();
Sum.arr = arr2;
Sum.m=m;
Phaser p = new Phaser();
for (int i = 1; i<n-1; i++)
{
var x = new Sum (p, i);
x.start();
}
for (int i = 0; i<n; i++)
{
System.out.print(Sum.arr[i]+" ");
}
System.out.println();
for (int i = 0; i<n; i++)
{
if (arr[i]!=Sum.arr[i])
System.out.println("Error! Value is incorrect at position: "+i+". Original val is: "+arr[i]+" Thead val is: "+Sum.arr[i]+" Before transform is: " +arr3[i]);
}
}
}
class Sum extends Thread
{
static int [] arr;
static int m;
Phaser ph;
int i;
public Sum(Phaser p, int i)
{
this.ph = p;
this.i = i;
}
public static synchronized void trans (int i)
{
arr [i]= (arr [i-1]+arr [i+1])/2;
}
@Override
public void run ()
{
ph.register();
for (int j = 0; j<m; j++)
{
trans(i);
ph.arriveAndAwaitAdvance();
}
ph.arriveAndDeregister();
}
}
</code></pre>
<p>However, the results of serial and parallel algorithms are not the same. Please tell me what am I doing wrong?</p>
|
[
{
"answer_id": 74462305,
"author": "acrazing",
"author_id": 4380247,
"author_profile": "https://Stackoverflow.com/users/4380247",
"pm_score": 2,
"selected": false,
"text": "type ArrayKeyof<T> = {\n [P in keyof T]-?: any[] extends T[P] ? P : never;\n}[keyof T];\n\nexport type ArrayRequired<T> = Omit<T, ArrayKeyof<T>> & Required<Pick<T, ArrayKeyof<T>>>;\n\n// demo\n\ninterface IExample {\n a: number,\n b?: string,\n c?: number[]\n}\n\nconst d: ArrayRequired<IExample> = {\n a: 1,\n c: [1],\n}\n"
},
{
"answer_id": 74463087,
"author": "Woohaik",
"author_id": 17200950,
"author_profile": "https://Stackoverflow.com/users/17200950",
"pm_score": 1,
"selected": false,
"text": "KeepAllSameButArraysRequired"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13589297/"
] |
74,462,187
|
<p>I'm sure I'm missing something, but I can't find a clear anwser here. I'm trying to minimize re-renderings, at least avoid useless renderings like in this case.</p>
<ol>
<li>The <code>state</code> is an object, because I'd like to set both <code>loading</code> and <code>products</code> properties with a <strong>single <code>setState</code> call</strong></li>
<li>Initially, <code>loading</code> is <code>true</code> because I'm sure that <code>useEffect</code> is called at least once</li>
<li>Calling <code>setState</code> inside <code>useEffect</code> will trigger an <strong>useless immediate re-render</strong>, because I think how object are compared (<strong>shallow vs deep</strong>)</li>
</ol>
<p>Actual code:</p>
<pre><code>export const ProductsIndex = () => {
console.log('[ProductsIndex] Rendering');
const [state, setState] = useState({ loading: true, products: [], pages: 1 });
useEffect(() => {
console.log('[ProductsIndex] useEffect');
setState(prev => ({ ...prev, loading: true });
axios.get('/api/products', params)
.then(res => {
setState(prev => ({ ...prev, loading: false, products: res.data });
});
// fetch
}, [params]);
};
</code></pre>
<p>I can think at this solution, but I really don't know if there is a better way to handle this use cases:</p>
<pre><code>useEffect(() => {
console.log('[ProductsIndex] useEffect');
setState(prev => prev.loading ? prev : { ...prev, loading: true });
}, []);
</code></pre>
|
[
{
"answer_id": 74462382,
"author": "CertainPerformance",
"author_id": 9515207,
"author_profile": "https://Stackoverflow.com/users/9515207",
"pm_score": 3,
"selected": true,
"text": "useEffect(() => {\n console.log('[ProductsIndex] useEffect');\n if (!state.loading) {\n setState(prev => ({ ...prev, loading: true });\n }\n"
},
{
"answer_id": 74462385,
"author": "Daniel Smith",
"author_id": 14930500,
"author_profile": "https://Stackoverflow.com/users/14930500",
"pm_score": 0,
"selected": false,
"text": "import { useEffect, useState } from \"react\"\nimport axios from \"axios\"\n\n\nexport default function useFetch(url){\n\n const [data,setData] = useState(null)\n const [error,setError] = useState(null)\n const [loading,setLoading] = useState(false)\n\n useEffect(() => {\n (\n async function(){\n try{\n setLoading(true)\n const response = await axios.get(url)\n setData(response.data)\n }catch(err){\n setError(err)\n }finally{\n setLoading(false)\n }\n }\n )()\n }, [url])\n\n return { data, error, loading }\n\n}\n"
},
{
"answer_id": 74462485,
"author": "albjerto",
"author_id": 11999748,
"author_profile": "https://Stackoverflow.com/users/11999748",
"pm_score": 0,
"selected": false,
"text": "setState"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/220180/"
] |
74,462,191
|
<p>Hello I have a query in plsql.
What I am looking for is that when input comes from the server as a parameter in the insert_date_time, I just want to take YYYYMMDD parts.
For example: input 20221116105703603 what I look for is 20221116</p>
<p>I tried this query but couldnt succed I hope you can correct me, thank you.</p>
<p>Note: I defined insert_date_time as NUMBER(17) and in the java code it is defined as String.</p>
<pre><code>SELECT insert_date_time FROM oc_vpos.payment_with_link a where a.insert_date_time = substr(:insert_date_time,1,8);
</code></pre>
|
[
{
"answer_id": 74462382,
"author": "CertainPerformance",
"author_id": 9515207,
"author_profile": "https://Stackoverflow.com/users/9515207",
"pm_score": 3,
"selected": true,
"text": "useEffect(() => {\n console.log('[ProductsIndex] useEffect');\n if (!state.loading) {\n setState(prev => ({ ...prev, loading: true });\n }\n"
},
{
"answer_id": 74462385,
"author": "Daniel Smith",
"author_id": 14930500,
"author_profile": "https://Stackoverflow.com/users/14930500",
"pm_score": 0,
"selected": false,
"text": "import { useEffect, useState } from \"react\"\nimport axios from \"axios\"\n\n\nexport default function useFetch(url){\n\n const [data,setData] = useState(null)\n const [error,setError] = useState(null)\n const [loading,setLoading] = useState(false)\n\n useEffect(() => {\n (\n async function(){\n try{\n setLoading(true)\n const response = await axios.get(url)\n setData(response.data)\n }catch(err){\n setError(err)\n }finally{\n setLoading(false)\n }\n }\n )()\n }, [url])\n\n return { data, error, loading }\n\n}\n"
},
{
"answer_id": 74462485,
"author": "albjerto",
"author_id": 11999748,
"author_profile": "https://Stackoverflow.com/users/11999748",
"pm_score": 0,
"selected": false,
"text": "setState"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19336013/"
] |
74,462,238
|
<p>How can I remove existing and future pycahce files from git repository in Windows? The commands I found online are not working for example when I send the command "<code>git rm -r --cached __pycache__</code>" I get the command "<code>pathspec '__pycache__' did not match any files</code>".</p>
|
[
{
"answer_id": 74462382,
"author": "CertainPerformance",
"author_id": 9515207,
"author_profile": "https://Stackoverflow.com/users/9515207",
"pm_score": 3,
"selected": true,
"text": "useEffect(() => {\n console.log('[ProductsIndex] useEffect');\n if (!state.loading) {\n setState(prev => ({ ...prev, loading: true });\n }\n"
},
{
"answer_id": 74462385,
"author": "Daniel Smith",
"author_id": 14930500,
"author_profile": "https://Stackoverflow.com/users/14930500",
"pm_score": 0,
"selected": false,
"text": "import { useEffect, useState } from \"react\"\nimport axios from \"axios\"\n\n\nexport default function useFetch(url){\n\n const [data,setData] = useState(null)\n const [error,setError] = useState(null)\n const [loading,setLoading] = useState(false)\n\n useEffect(() => {\n (\n async function(){\n try{\n setLoading(true)\n const response = await axios.get(url)\n setData(response.data)\n }catch(err){\n setError(err)\n }finally{\n setLoading(false)\n }\n }\n )()\n }, [url])\n\n return { data, error, loading }\n\n}\n"
},
{
"answer_id": 74462485,
"author": "albjerto",
"author_id": 11999748,
"author_profile": "https://Stackoverflow.com/users/11999748",
"pm_score": 0,
"selected": false,
"text": "setState"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17517402/"
] |
74,462,343
|
<p>I am trying to make a constructor that creates an array of empty homework scores (6 per student) and an array of empty exam scores (3 per student).</p>
<p>The getHomeworkAverage() method returns the average score on the student’s homework. The getFinalScore() method returns the final grade for each student using the grading as follows: (15% for exam1, 25% for exam2, 30% for exam3, and 30% for the homework average).</p>
<p><a href="https://i.stack.imgur.com/1d49A.png" rel="nofollow noreferrer">UML Diagram Here</a></p>
<pre><code>public class Student {
private String name;
private int[] homeworks;
private int[] exams;
private int[] homeworkScores;
private int[] examScores;
private double homeworkAvergae;
private int finalScore;
public Student(String name, int[] homeworks, int[] exams, int[] homeworkScores, int[] examScores, double homeworkAvergae, int finalScore) {
this.name = name;
this.homeworks = homeworks;
this.exams = exams;
this.homeworkScores = homeworkScores;
this.examScores = examScores;
this.homeworkAvergae = homeworkAvergae;
this.finalScore = finalScore;
}
public int[] getHomeworkScores() {
return homeworkScores;
}
public void setHomeworkScores(int[] homeworkScores) {
this.homeworkScores = homeworkScores;
}
public double getHomeworkAvergae() {
return homeworkAvergae;
}
public int[] getExamScores() {
return examScores;
}
public void setExamScores(int[] examScores) {
this.examScores = examScores;
}
public int getFinalScore() {
return finalScore;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int[] getHomeworks() {
return homeworks;
}
public void setHomeworks(int[] homeworks) {
this.homeworks = homeworks;
}
public int[] getExams() {
return exams;
}
public void setExams(int[] exams) {
this.exams = exams;
}
}
</code></pre>
|
[
{
"answer_id": 74462650,
"author": "Eduardo Neres",
"author_id": 20521080,
"author_profile": "https://Stackoverflow.com/users/20521080",
"pm_score": -1,
"selected": false,
"text": " int[] homeworks = new int[]{ 1,2,3,4,5,6,7,8,9,10 };\n int[] exams = new int[]{ 1,2,3,4,5,6,7,8,9,10 };\n int[] homeworkScores = new int[]{ 1,2,3,4,5,6,7,8,9,10 };\n int[] examScores = new int[]{ 1,2,3,4,5,6,7,8,9,10 };\n Student student = new Student(\n \"Name\",\n homeworks,\n exams,\n homeworkScores,\n examScores,\n 6.0,\n 6\n );\n"
},
{
"answer_id": 74466645,
"author": "Christophe",
"author_id": 3723423,
"author_profile": "https://Stackoverflow.com/users/3723423",
"pm_score": 1,
"selected": false,
"text": "«Create»"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12428572/"
] |
74,462,360
|
<p>Consider this generic function:</p>
<pre><code> public getData<T>(url: string): Observable<T> {
return this.httpClient.get<T>(url);
}
</code></pre>
<p>How can I return a <strong>hardcoded mock object array</strong> in order to test the function (for example because the remote API has not been implemented yet)?</p>
<p>I would like to return this:</p>
<pre><code>return of([{id: 1, value: 'test1'}, {id: 2, value: 'test2'}]);
</code></pre>
<p>but I am getting this error:</p>
<blockquote>
<p>TS2322: Type 'Observable<{ id: number; value: string; }[]>' is not assignable to type 'Observable'. Type '{ id: number; value: string; }[]' is not assignable to type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to '{ id: number; value: string; }[]'.</p>
</blockquote>
<p>Is there a way to achieve this?</p>
|
[
{
"answer_id": 74462650,
"author": "Eduardo Neres",
"author_id": 20521080,
"author_profile": "https://Stackoverflow.com/users/20521080",
"pm_score": -1,
"selected": false,
"text": " int[] homeworks = new int[]{ 1,2,3,4,5,6,7,8,9,10 };\n int[] exams = new int[]{ 1,2,3,4,5,6,7,8,9,10 };\n int[] homeworkScores = new int[]{ 1,2,3,4,5,6,7,8,9,10 };\n int[] examScores = new int[]{ 1,2,3,4,5,6,7,8,9,10 };\n Student student = new Student(\n \"Name\",\n homeworks,\n exams,\n homeworkScores,\n examScores,\n 6.0,\n 6\n );\n"
},
{
"answer_id": 74466645,
"author": "Christophe",
"author_id": 3723423,
"author_profile": "https://Stackoverflow.com/users/3723423",
"pm_score": 1,
"selected": false,
"text": "«Create»"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884319/"
] |
74,462,398
|
<p>I have a dataframe <strong>df</strong> structured as well:</p>
<pre><code>Name Surname Nationality
Joe Tippy Italian
Adam Wesker American
</code></pre>
<p>I would like to create a new record based on a dictionary whose keys corresponds to the column names:</p>
<pre><code>new_record = {'Name': 'Jimmy', 'Surname': 'Turner', 'Nationality': 'Australian'}
</code></pre>
<p>How can I do that? I tried with a simple:</p>
<pre><code>df = df.append(new_record, ignore_index=True)
</code></pre>
<p>but if I have a missing value in my record the dataframe doesn't get filled with a space, instead it leaves me the last column empty.</p>
|
[
{
"answer_id": 74462477,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "new_record = {'Surname': 'Turner', 'Nationality': 'Australian'}\ndf = pd.concat([df, pd.DataFrame([new_record])], ignore_index=True).fillna('')\n\nprint (df)\n Name Surname Nationality\n0 Joe Tippy Italian\n1 Adam Wesker American\n2 Turner Australian\n"
},
{
"answer_id": 74462528,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "df.loc[len(df)] = new_record\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10886071/"
] |
74,462,420
|
<p>I'm setting up a GitHub App for ArgoCD authentication. The GitHub App setup is completed. But in ArgoCD it asks for GitHub App ID and GitHub App Installation ID. I could find the App ID from the GitHub App section itself. But I couldn't find the GitHub App Installation ID.</p>
<p>Is there a way to directly find GitHub App Installation ID from the GitHub website settings section? Or do we need to use GitHub API or something?</p>
|
[
{
"answer_id": 74462496,
"author": "HeadinCloud",
"author_id": 7450826,
"author_profile": "https://Stackoverflow.com/users/7450826",
"pm_score": 1,
"selected": true,
"text": "InstallationID"
},
{
"answer_id": 74474953,
"author": "Neron Joseph",
"author_id": 4082114,
"author_profile": "https://Stackoverflow.com/users/4082114",
"pm_score": 1,
"selected": false,
"text": "https://github.com/organizations/<Organization-name>/settings/installations/<ID>\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4082114/"
] |
74,462,442
|
<p>I want to print the value between 2 to 5 from 1first columns.</p>
<pre><code>df5 = pd.DataFrame({
'colA': ['C4GSP3JOIHJ2', 'CAGPS3JOIHJ2','CALCG3EST2','CLCCV3JOIHJ2','CLCNF3JOIHJ2','CLCQU3JOIHJ2','CLSMS3JOIHJ2','CMICO3JOIHJ2'],
})
</code></pre>
<p><strong>output look like this</strong></p>
<p><a href="https://i.stack.imgur.com/sO7Qo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sO7Qo.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74462496,
"author": "HeadinCloud",
"author_id": 7450826,
"author_profile": "https://Stackoverflow.com/users/7450826",
"pm_score": 1,
"selected": true,
"text": "InstallationID"
},
{
"answer_id": 74474953,
"author": "Neron Joseph",
"author_id": 4082114,
"author_profile": "https://Stackoverflow.com/users/4082114",
"pm_score": 1,
"selected": false,
"text": "https://github.com/organizations/<Organization-name>/settings/installations/<ID>\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16609351/"
] |
74,462,445
|
<p>I've tried several ways to do this including through javascript but I cannot figure it out.
I have a table, and the header contains a "select all" checkbox with a checkbox attached to each entry.</p>
<p>applicable html:</p>
<pre><code><table>
<thread>
<tr>
<th class="border-top-0"><input type="checkbox" id="selectAll" value="selectAll"></th>
</tr>
</thread>
<tbody>
<td>
<%= check_box_tag "contacts[]", contact.id %>
</td>
</code></pre>
<p><a href="https://i.stack.imgur.com/KFxA3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KFxA3.png" alt="enter image description here" /></a></p>
<p>Ideally, what I would like to happen is for a hidden div to display when any checkbox is checked. I was partially able to accomplish this through Javascript with:</p>
<pre><code> var checkboxes = document.querySelectorAll('input#contacts_');
//var selectAll = document.querySelector('input#selectAll');
var checkCount = 0;
checkboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', function() {
checkbox.checked ? checkCount++ : checkCount--;
checkCount > 0 ? actionsContainer.style.opacity = '1': actionsContainer.style.opacity = '0';
console.log(checkCount)
});
});
</code></pre>
<p><a href="https://i.stack.imgur.com/50mEB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/50mEB.png" alt="enter image description here" /></a></p>
<p>However, when the "select all" checkbox is checked, the other checkboxes are not registered as being checked and I cannot get the hidden div to show unless a contact is unselected and then reselected. I've also tried adding a separate event listener to the <code>selectAll</code> variable with messy results.</p>
<p>So I'm trying a CSS solution along the lines of:</p>
<pre><code> input[type='checkbox']:checked.mobile-actions {
opacity: 1;
}
</code></pre>
<p>figuring that if every checkbox is an <code>input[type="checkbox"]</code> they would all be touched and the mobile-actions div would display. But this doesn't seem to work either. How can I get this done?</p>
|
[
{
"answer_id": 74463445,
"author": "Ruby Newb",
"author_id": 15054139,
"author_profile": "https://Stackoverflow.com/users/15054139",
"pm_score": 0,
"selected": false,
"text": " document.addEventListener('change', function() {\n arr = [];\n checkboxes = document.querySelectorAll('input[type=\"checkbox\"]');\n\n for (i = checkboxes.length -1; i >= 0; i--) {\n if (checkboxes[i].checked) {\n arr.push(checkboxes[i].value);\n }\n }\n\n arr.length > 0 ? actionsContainer.style.opacity = '1' : actionsContainer.style.opacity = '0' \n });\n"
},
{
"answer_id": 74463551,
"author": "Medis Redzic",
"author_id": 5810098,
"author_profile": "https://Stackoverflow.com/users/5810098",
"pm_score": 2,
"selected": true,
"text": "<table class='items'>"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15054139/"
] |
74,462,480
|
<p>I'm trying to create a Unit Test for a RestController in Spring Boot.</p>
<p>The Controller looks something like this:</p>
<pre><code>@RestController()
@RequestMapping("/endpoint")
public class MyRestController {
@Autowired
private MyService service;
@GetMapping(value = "/{id}", produces = "application/json")
public ResponseEntity<String> findSomethingById(@PathVariable("id") String id, @RequestParam("param1")String param1) throws MyServiceException {
return ResponseEntity.ok(service.findSomethingById(id,param1));
}
</code></pre>
<p>And the Unit Test Class looks as follows:</p>
<pre><code>import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.isA;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@ExtendWith(SpringExtension.class)
@WebMvcTest(MyRestController.class)
public class MyRestControllerUnitTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private MyService service;
@Test
public void testGetSomethingId() throws Exception {
when(service.findSomethingById("1", "something")).thenReturn("found");
mockMvc.perform(get("/endpoint/1").param("param1","something"))
.andDo(print())
.andExpect(status().isOk());
// some more Expects
}
}
</code></pre>
<p>The issue is that both the <code>service</code> and the <code>mockMvc</code> Variables are null during the execution of the Test, but shouldn't be as they should get intantiated by Spring according to their Annotations according to my Understanding.</p>
<p>Looking for similair issues I found mostly issues where Junit4 and Junit5 got mixed togehter, which seems not to be my problem.
Sample question I found <a href="https://stackoverflow.com/questions/70256493/nullpointerexception-on-controller-when-testing-in-springboot-api-mocking">NullPointerException on controller when testing in SpringBoot API - Mocking</a></p>
<p>I'm using Spring Boot 2.7.4 as well as Java 11 and I added the <code>spring-boot-starter-test</code> dependency to my pom.xml for the Test dependencies</p>
<p>Below is the StackTrace I get when executing the Test with my IDEA:</p>
<pre><code>java.lang.NullPointerException
at MyRestControllerUnitTest.findSomethingById(Line of when() as service is null and so is mockMvc)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:42)
at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:80)
at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:72)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Process finished with exit code -1
</code></pre>
<p>MainClass:</p>
<pre><code>@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
</code></pre>
<p>pom.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.myGroup</groupId>
<artifactId>myArtifact</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>MyApplication</name>
<properties>
<java.version>11</java.version>
<spring-cloud.version>2020.0.3</spring-cloud.version>
<start-class>org.main.MyApplication</start-class>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.12</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>org.main.MyApplication</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</code></pre>
|
[
{
"answer_id": 74479936,
"author": "Rohit Agarwal",
"author_id": 7871511,
"author_profile": "https://Stackoverflow.com/users/7871511",
"pm_score": 2,
"selected": true,
"text": "@Test"
},
{
"answer_id": 74482857,
"author": "Nullish Byte",
"author_id": 6176087,
"author_profile": "https://Stackoverflow.com/users/6176087",
"pm_score": 0,
"selected": false,
"text": "./mvw dependency:tree\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4334953/"
] |
74,462,512
|
<p>I am currently trying to get a List with unique values.</p>
<p>Technically, it should be really simple, and the obvious choice would be a HashSet.
However, I want the properties of my "points" to be the uniqueness criteria and not their "IDs".</p>
<p>After that, I wanted to use the stream().distinct() method. Hoping that that one is using the overridden equals method. Sadly, this won't work either.</p>
<p>Any solution/Idea that works for double[] is welcome as well.</p>
<p><strong>PointType Class</strong></p>
<pre><code>public class PointType{
private double x;
private double y;
public PointType(x,y){
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object other){
if(other instanceof PointType && this.x == other.x && this.y==other.y){
return true;
}
return false;
}
}
</code></pre>
<p>I am aware of the flaw of double == double. For a minimum sample, it is sufficient.</p>
<p>Now to the issue:</p>
<pre><code>@Test
public void testUniquness(){
Set<PointType>setA = new HashSet<>();
Set<PointType>setB = new HashSet<>();
ArrayList<PointType> listA= new ArrayList<>();
ArrayList<PointType> listB= new ArrayList<>();
PointType p1 = new PointType(1.0,2.0);
PointType p2 = new PointType(1.0,2.0);
PointType p3 = new PointType(2.0,2.0);
PointType p4 = new PointType(2.0,2.0);
// Trying to use the unique properties of a HashSet
setA.add(p1);
setA.add(p2);
setA.add(p1);
setA.add(p2);
setB.add(p1);
setB.add(p2);
setB.add(p3);
setB.add(p4);
//Now with array lists and streams.
listA.add(p1);
listA.add(p2);
listA.add(p1);
listA.add(p2);
listA = (ArraList<PointType>) listA.stream().distinct().collect(Collectors.toList());
listB.add(p1);
listB.add(p2);
listB.add(p3);
listB.add(p4);
listB = (ArraList<PointType>) listB.stream().distinct().collect(Collectors.toList());
assertTrue(p1.equals(p2)); // Test passes
assertTrue(p3.equals(p4)); // Test passes
assertTrue(setA.size() == 2); // Test passes (obviously)
assertTrue(setB.size() == 2); // Test failes. How can I use my custom equality condition?
assertTrue(listA.size() == 2); // Test passes (obviously)
assertTrue(listb.size() == 2); // Test failes. How can I use my custom equality condition?
}
</code></pre>
<p>Any help is appreciated.</p>
<p>For sure, a for loop would solve this too. But there has to be a more elegant way.</p>
|
[
{
"answer_id": 74462635,
"author": "Matteo NNZ",
"author_id": 3111149,
"author_profile": "https://Stackoverflow.com/users/3111149",
"pm_score": 3,
"selected": true,
"text": "equals"
},
{
"answer_id": 74462807,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 1,
"selected": false,
"text": "equals()"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9469666/"
] |
74,462,526
|
<p>Here is my structure:</p>
<pre><code><div class="list">
<div class="list-item">
<span class="item-title">St</span>
<button class="item-button">click</button>
</div>
<div class="list-item">
<span class="item-title">Middletext</span>
<button class="item-button">click</button>
</div>
<div class="list-item">
<span class="item-title">This line contains a long text.</span>
<button class="item-button">click</button>
</div>
</div>
</code></pre>
<p>So, this code creates three lines of text, short, middle and long.</p>
<p>Naturally, width of each <code>item-title</code> element is equal to the length of text, so, first <code>item-title</code> element will have the smallest width, second one will have larger and the last one the largest width.</p>
<p>What I need to do in CSS is to set the width of all <code>item-title</code> elements to the width of the longest <code>item-title</code> element. I need this so that I can align all <code>item-button</code> elements to the same horizontal position.</p>
<p>Sure, I can hardcode the <code>width</code> property of all <code>item-title</code> elements, but I really need this width to be dynamic since in reality I do not have such static list of items. I use Vue to generate those list items based on the variable values that can change.</p>
<p>So, how can I say to HTML: "Align all buttons next to the end of the longest line of text, please"?</p>
|
[
{
"answer_id": 74462635,
"author": "Matteo NNZ",
"author_id": 3111149,
"author_profile": "https://Stackoverflow.com/users/3111149",
"pm_score": 3,
"selected": true,
"text": "equals"
},
{
"answer_id": 74462807,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 1,
"selected": false,
"text": "equals()"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16974979/"
] |
74,462,555
|
<p>I'm trying to scrape some titles of the videos and to do so I'm using Selenium, but I've encountered a problem. <code>driver.find_element().text</code> returns empty string, but title is for sure located in given XPATH. Here is the fragment of the page source returned by driver.page_source:</p>
<pre><code><div class="title"><a href="/f/4n3x7e31hpwxm8"target="_blank">Big.Sky.S03E01.ITA.WEBDL.1080p</a></div>
</code></pre>
<p>To find the title I am trying to use:</p>
<pre><code>hoverable = driver.find_element(By.XPATH, '//*[@id="videojs"]/div[1]')
ActionChains(driver).move_to_element(hoverable).perform()
wait = WebDriverWait(driver, 20)
title_from_url = wait.until(EC.visibility_of_element_located((By.XPATH, '/html/body/div[1]/a'))).text
title_from_url = driver.find_element(
By.XPATH, '/html/body/div[1]/a'
).text.casefold()
</code></pre>
<p>From what I've read it could be caused by the fact that the page might not be fully loaded (I wasn't using any wait condition here). After that I've tried to add a wait condition and even time.sleep(), but it didn't change anything. <mini question: how would proper wait staitment look like here?></p>
<p>Edit:
I think the problem is caused, because title is showing up only when mouse is in the player area. I think some mouse movement will be needed here, but I have tried to move mouse into the player area and for some time it is working but after a while there is a moment when title will disappear too fast. Is there a way to use find_element() while also moving mouse?</p>
<p>Any help will be appreciated.
Best regards,
Ed.</p>
<p>Example site: <a href="https://mixdrop.to/e/4n3x7e31hpwxm8" rel="nofollow noreferrer">https://mixdrop.to/e/4n3x7e31hpwxm8</a>.</p>
|
[
{
"answer_id": 74462682,
"author": "Prophet",
"author_id": 3485434,
"author_profile": "https://Stackoverflow.com/users/3485434",
"pm_score": 2,
"selected": true,
"text": "WebDriverWait"
},
{
"answer_id": 74463040,
"author": "suman maiti",
"author_id": 7909936,
"author_profile": "https://Stackoverflow.com/users/7909936",
"pm_score": 0,
"selected": false,
"text": "from selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12606999/"
] |
74,462,613
|
<p>Checkmarx complains that "the file utilizes <strong>"format"</strong> that is accessed by other concurrent functionality in a way that is not thread-safe, which may result in a Race Condition over this resource. It highlights the format method. How do we resolve this?</p>
<pre><code> String endDate =
configProperties.getDateFormatter().format(Date.from(date.plusMonths(-1L * auditTimeMonthLimit).atStartOfDay()
.atZone(ZoneId.systemDefault())
.toInstant()));
</code></pre>
<p>Other part of code</p>
<pre><code> private final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
public SimpleDateFormat getDateFormatter() {
return dateFormatter;
}
</code></pre>
|
[
{
"answer_id": 74462682,
"author": "Prophet",
"author_id": 3485434,
"author_profile": "https://Stackoverflow.com/users/3485434",
"pm_score": 2,
"selected": true,
"text": "WebDriverWait"
},
{
"answer_id": 74463040,
"author": "suman maiti",
"author_id": 7909936,
"author_profile": "https://Stackoverflow.com/users/7909936",
"pm_score": 0,
"selected": false,
"text": "from selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19673046/"
] |
74,462,622
|
<p>I have used time.sleep(5) to see if the changes are reflected in the window.
The window opens in blue color. After I click on the 'Go' button it changes to yellow. But why does it not change to green when it enters the function 'func2'?</p>
<pre><code>import time
import tkinter
global win
def func1():
global win
win = tkinter.Tk()
win.geometry("300x200")
win.configure(bg='blue')
time.sleep(5)
button_win = tkinter.Button(win,text='Go',command=func2)
button_win.pack()
print('mainloop')
win.mainloop()
def func2():
print("func2")
global win
win.configure(bg = 'green')
time.sleep(5)
print("in func1")
time.sleep(5)
print("func3 call")
func3()
def func3():
global win
time.sleep(5)
win.configure(bg = 'yellow')
func1()
</code></pre>
<p><strong>OUTPUT in console</strong></p>
<pre><code>mainloop
(I click on 'Go' button)
func2
in func1
func3 call
</code></pre>
|
[
{
"answer_id": 74462682,
"author": "Prophet",
"author_id": 3485434,
"author_profile": "https://Stackoverflow.com/users/3485434",
"pm_score": 2,
"selected": true,
"text": "WebDriverWait"
},
{
"answer_id": 74463040,
"author": "suman maiti",
"author_id": 7909936,
"author_profile": "https://Stackoverflow.com/users/7909936",
"pm_score": 0,
"selected": false,
"text": "from selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13993793/"
] |
74,462,623
|
<p>What is the easiest/most optimal way of finding the exponential of a number, say <code>x</code>, in Python? i.e. how can I implement <code>e^x</code>?</p>
|
[
{
"answer_id": 74462624,
"author": "Marioanzas",
"author_id": 14367279,
"author_profile": "https://Stackoverflow.com/users/14367279",
"pm_score": 0,
"selected": false,
"text": "math.exp()"
},
{
"answer_id": 74462727,
"author": "Khaled DELLAL",
"author_id": 15852600,
"author_profile": "https://Stackoverflow.com/users/15852600",
"pm_score": 1,
"selected": false,
"text": "e^x"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14367279/"
] |
74,462,629
|
<p>I get this error when trying to boot right after create-next-app. Im choosing typescript with eslint.</p>
<p>Tried without typescript, tried updating create-next-app, trying reinstalling dependencies - still not helping
<a href="https://i.stack.imgur.com/ZlFQf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZlFQf.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74462624,
"author": "Marioanzas",
"author_id": 14367279,
"author_profile": "https://Stackoverflow.com/users/14367279",
"pm_score": 0,
"selected": false,
"text": "math.exp()"
},
{
"answer_id": 74462727,
"author": "Khaled DELLAL",
"author_id": 15852600,
"author_profile": "https://Stackoverflow.com/users/15852600",
"pm_score": 1,
"selected": false,
"text": "e^x"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20480318/"
] |
74,462,641
|
<p>I am trying to write a useEffect hook which will update the DOM once when the page loads. For some reason that I cannot fathom, the useEffect runs but the function does not get called. The <code>console.log()</code> on the other hand does get called.</p>
<p>There is no problem with the function itself, it works when I run it from the console or trigger it in some other way. I have also tried using different syntax for writing and/or calling the function, placing inside or outside the useEffect. The result is always the same—the DOM does not update but the <code>console.log()</code> logs.</p>
<p>Please help me, what am I doing wrong/ misunderstanding? Thank you in advance.</p>
<pre><code> // Add ids to h2 elements inside markdown
useEffect(() => {
function setID() {
const H2List = document.getElementsByTagName("h2");
const H2Array = [...H2List];
H2Array.map((a) => (
a.setAttribute('id',
`${H2Array[H2Array.indexOf(a)].childNodes[0].nodeValue
.split(" ").join("-").toLowerCase()}`)
))
}
console.log("useeffect ran once");
setID();
}, [])
</code></pre>
|
[
{
"answer_id": 74657770,
"author": "Freja",
"author_id": 12237904,
"author_profile": "https://Stackoverflow.com/users/12237904",
"pm_score": 1,
"selected": true,
"text": " window.onload = function() {\n setID()\n }\n\n function setID() {\n const H2List = document.getElementsByTagName(\"h2\");\n const H2Array = [...H2List];\n H2Array.map((a) => (\n a.setAttribute('id',\n `${H2Array[H2Array.indexOf(a)].childNodes[0].nodeValue\n .split(\" \").join(\"-\").toLowerCase()}`)\n ))\n }\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12237904/"
] |
74,462,661
|
<p>I have a pipeline that uses variables from Library. For the IN, QA, and STAGE environments, I use a variable from shared variables. But now I need to create a PROD environment and deploy to PROD. And only for the PROD environment I have to use the same variable, but with a different value. How to do it?</p>
<p>Because if I add a special variable for PROD, I will have to change it in CI, in the build. Then the wrong variable will be used for INT, QA and STAGE.
And I plan to make the deployment on PROD dependent on the build and the deployment on STAGE as in the picture:</p>
<p><a href="https://i.stack.imgur.com/9ZXCt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9ZXCt.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74657770,
"author": "Freja",
"author_id": 12237904,
"author_profile": "https://Stackoverflow.com/users/12237904",
"pm_score": 1,
"selected": true,
"text": " window.onload = function() {\n setID()\n }\n\n function setID() {\n const H2List = document.getElementsByTagName(\"h2\");\n const H2Array = [...H2List];\n H2Array.map((a) => (\n a.setAttribute('id',\n `${H2Array[H2Array.indexOf(a)].childNodes[0].nodeValue\n .split(\" \").join(\"-\").toLowerCase()}`)\n ))\n }\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14751570/"
] |
74,462,666
|
<p>I already checked many questions and I don't seem to find the suitable answer.</p>
<p>I have this df</p>
<pre><code>df = data.frame(x = 1:10,y=11:20)
</code></pre>
<p>the output</p>
<pre><code> x y
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
6 6 16
7 7 17
8 8 18
9 9 19
10 10 20
</code></pre>
<p>I just wish the output to be:</p>
<pre><code> 1 2 3 4 5 6 7 8 9 10
x 1 2 3 4 5 6 7 8 9 10
y 11 12 13 14 15 16 17 18 19 20
</code></pre>
<p>thanks</p>
|
[
{
"answer_id": 74462761,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 3,
"selected": true,
"text": "t()"
},
{
"answer_id": 74462763,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 2,
"selected": false,
"text": "setNames(data.frame(t(df)), df[,\"x\"])\n 1 2 3 4 5 6 7 8 9 10\nx 1 2 3 4 5 6 7 8 9 10\ny 11 12 13 14 15 16 17 18 19 20\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19720935/"
] |
74,462,683
|
<p>I have two <code>torch</code> tensors <code>a</code> and <code>b</code>:</p>
<pre><code>import torch
torch.manual_seed(0) # for reproducibility
a = torch.rand(size = (5, 10, 1))
b = torch.tensor([3, 3, 1, 5, 3, 1, 0, 2, 1, 2])
</code></pre>
<p>I want to split the 2nd dimension of <code>a</code> (which is dim = 1 in the <code>Python</code> language) based on the unique values in <code>b</code>.</p>
<p>What I have tried so far:</p>
<pre><code># find the unique values and unique indices of b
unique_values, unique_indices = torch.unique(b, return_inverse = True)
# split a in where dim = 1, based on unique indices
l = torch.tensor_split(a, unique_indices, dim = 1)
</code></pre>
<p>I was expecting <code>l</code> to be a list of <strong>n</strong> number of tensors where <strong>n</strong> is the number of unique values in <code>b</code>. I was also expecting the tensors to have the shape (5, <strong>number of elements corresponding to unique_values</strong>, 1).</p>
<p>However, I get the following:</p>
<pre><code>print(l)
(tensor([[[0.8198],
[0.9971],
[0.6984]],
[[0.7262],
[0.7011],
[0.2038]],
[[0.1147],
[0.3168],
[0.6965]],
[[0.0340],
[0.9442],
[0.8802]],
[[0.6833],
[0.7529],
[0.8579]]]), tensor([], size=(5, 0, 1)), tensor([], size=(5, 0, 1)), tensor([[[0.9971],
[0.6984],
[0.5675]],
[[0.7011],
[0.2038],
[0.6511]],
[[0.3168],
[0.6965],
[0.9143]],
[[0.9442],
[0.8802],
[0.0012]],
[[0.7529],
[0.8579],
[0.6870]]]), tensor([], size=(5, 0, 1)), tensor([], size=(5, 0, 1)), tensor([], size=(5, 0, 1)), tensor([[[0.8198],
[0.9971]],
[[0.7262],
[0.7011]],
[[0.1147],
[0.3168]],
[[0.0340],
[0.9442]],
[[0.6833],
[0.7529]]]), tensor([], size=(5, 0, 1)), tensor([[[0.9971]],
[[0.7011]],
[[0.3168]],
[[0.9442]],
[[0.7529]]]), tensor([[[0.6984],
[0.5675],
[0.8352],
[0.2056],
[0.5932],
[0.1123],
[0.1535],
[0.2417]],
[[0.2038],
[0.6511],
[0.7745],
[0.4369],
[0.5191],
[0.6159],
[0.8102],
[0.9801]],
[[0.6965],
[0.9143],
[0.9351],
[0.9412],
[0.5995],
[0.0652],
[0.5460],
[0.1872]],
[[0.8802],
[0.0012],
[0.5936],
[0.4158],
[0.4177],
[0.2711],
[0.6923],
[0.2038]],
[[0.8579],
[0.6870],
[0.0051],
[0.1757],
[0.7497],
[0.6047],
[0.1100],
[0.2121]]]))
</code></pre>
<p>Why do I get empty tensors like <code>tensor([], size=(5, 0, 1))</code> and how would I achieve what I want to achieve?</p>
|
[
{
"answer_id": 74463624,
"author": "guibs35",
"author_id": 10680282,
"author_profile": "https://Stackoverflow.com/users/10680282",
"pm_score": 1,
"selected": false,
"text": "index_select"
},
{
"answer_id": 74463667,
"author": "Ivan",
"author_id": 6331369,
"author_profile": "https://Stackoverflow.com/users/6331369",
"pm_score": 3,
"selected": true,
"text": "(5, number of elements corresponding to unique_values, 1)"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14802285/"
] |
74,462,708
|
<p><a href="https://i.stack.imgur.com/M5MNi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/M5MNi.png" alt="enter image description here" /></a></p>
<p>I want to move the icons to the top right just EXACTLY EXACTLY to the right of textbox. I have added float and also tried with top:30% but this is not postioning the correcty</p>
<p>Mu code is here</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><head>
<style>
.accordion {
margin: 30px;
}
.accordion-button.collapsed {
border-bottom: #ccc 1px solid
}
.accordion-body {
border-left: #673ab744 1px solid;
border-bottom: #673ab744 1px solid;
border-right: #673ab744 1px solid
}
.accordion-button{
display:inline!important
}
.wactions
{
float:right!important
}
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0">
<div class="accordion accordion-flush" id="accordionFlushExample">
<div class="accordion-item">
<h2 class="accordion-header" id="flush-headingOne">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseOne" aria-expanded="false" aria-controls="flush-collapseOne">
<input type="textbox" value="Accordion Item #1"/><br><Span>Desc goes here</span><br><Span>Desc goes here</span>
<div class="wactions">
<span class="wcopy material-symbols-outlined text-primary">content_copy</span>&nbsp;&nbsp;
<span class="wdelete material-symbols-outlined text-primary">delete</span>
</div>
</button>
</h2>
<div id="flush-collapseOne" class="accordion-collapse collapse" aria-labelledby="flush-headingOne" data-bs-parent="#accordionFlushExample">
<div class="accordion-body">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> class. This is the first item's accordion body.</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="flush-headingTwo">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseTwo" aria-expanded="false" aria-controls="flush-collapseTwo">
Accordion Item #2
</button>
</h2>
<div id="flush-collapseTwo" class="accordion-collapse collapse" aria-labelledby="flush-headingTwo" data-bs-parent="#accordionFlushExample">
<div class="accordion-body">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> class. This is the second item's accordion body. Let's imagine this being filled with some actual content.</div>
</div>
</div>
</div>
<script type="text/javascript">
$(".wdelete").off().on('click', function(event) {
if (confirm(`Are you sure to delete the workflow ${$(this).prev().parent().prev().val()}?`) == true) {
$(this).closest('.accordion-item').remove();
}
event.preventDefault();
event.stopPropagation();
});
</script>
<div class="as-console-wrapper"><div class="as-console"></div></div></body></html></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74462904,
"author": "DreamTeK",
"author_id": 2120261,
"author_profile": "https://Stackoverflow.com/users/2120261",
"pm_score": 3,
"selected": true,
"text": "flex"
},
{
"answer_id": 74464476,
"author": "reza hrkeng",
"author_id": 20517507,
"author_profile": "https://Stackoverflow.com/users/20517507",
"pm_score": 1,
"selected": false,
"text": "<div class='container'>\n <div class='left-your-options'>\n input and foo options ...\n </div>\n <div class='right-icons-top'>\n icons here\n </div>\n</div>\n\n<style>\n.container{\ndisplay:flex;\n}\n.right-icons-top{\nflex:20%;\n}\n.left-your-options{\nflex:80%;\n}\n</style>\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5549354/"
] |
74,462,724
|
<p>I created the following dictionary below (<code>mean_task_dict</code>). This dictionary includes three keys associated with three lists. Each lists includes 48 numeric values.</p>
<pre><code>mean_task_dict = {
"Interoception": task_mean_intero,
"Exteroception": task_mean_extero,
"Cognitive": task_mean_cognit,
}
</code></pre>
<p>I would like to plot the values contained in each list inside a scatterplot where the x-axis comprises three categories (<code>ROI_positions = np.array([1, 2, 3])</code>).
Each of the respective lists in the dictionary has to be linked to one of the categories from <code>ROI_positions</code> above.</p>
<p>Here is my current attempt or code for this task:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
task_mean_intero = [-0.28282956438352846, -0.33826908282117457, -0.23669673649758388]
task_mean_extero = [-0.3306686353702893, -0.4675910056474869, -0.2708033871055369]
task_mean_cognit = [-0.3053766849270014, -0.41698707094527254, -0.35655464189810543]
mean_task_dict = {
"Interoception": task_mean_intero,
"Exteroception": task_mean_extero,
"Cognitive": task_mean_cognit,
}
for value in mean_task_dict.values():
ROI_positions = np.array([1, 2, 3])
data_ROIs = np.array([
mean_task_dict["Interoception"][1],
mean_task_dict["Exteroception"][1],
mean_task_dict["Cognitive"][1]
])
plt.scatter(ROI_positions, data_ROIs)
</code></pre>
<p>My problem is that I am only able to compute and plot the data for one value by paradigmatically selecting the second index value of each list <code>[1]</code>.</p>
<p>How can I loop through all values inside the three lists nested in the dictionary, so that I can plot them all together in one plot?</p>
|
[
{
"answer_id": 74463060,
"author": "Trooper Z",
"author_id": 9190768,
"author_profile": "https://Stackoverflow.com/users/9190768",
"pm_score": 0,
"selected": false,
"text": "for value in mean_task_dict.values():\n for item in value:\n #do stuff here\n"
},
{
"answer_id": 74463127,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 3,
"selected": true,
"text": "ROI_positions = np.array([1, 2, 3])\nfor i in range(len(mean_task_dict)):\n data_ROIs = np.array([\n mean_task_dict[\"Interoception\"][i],\n mean_task_dict[\"Exteroception\"][i],\n mean_task_dict[\"Cognitive\"][i]\n ])\n plt.scatter(ROI_positions, data_ROIs)\nplt.show()\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17530552/"
] |
74,462,735
|
<p>In the sidebar, I have 4 rubrics (Administration, Marché, Portefeuille, Déconnexion ).</p>
<p><a href="https://i.stack.imgur.com/O8zpH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O8zpH.png" alt="enter image description here" /></a></p>
<p>When the user logs in, I would like the <code>Portefeuille</code> rubric to be hidden.</p>
<p>I created a method:</p>
<pre><code>canAccess(id: string): boolean {
if (id === "Portefeuille") {
if (this.store.selectSnapshot(ProfileState.currentPortfolio)) {
return true;
} else {
return false;
}
}
return true;
}
</code></pre>
<p>TypeScript file</p>
<pre><code>export class OnlineComponent implements OnInit {
private unsubscribe$ = new Subject<void>();
@Select(AuthState.user) user$!: Observable<string>;
@Select(AuthState.lastConnexionMoment) lastConnexionMoment$!: Observable<ApiConnectionMoment>;
@Select(ProfileState.currentPortfolio) currentPortfolio$!: Observable<Portfolio>;
activeItem: any;
openSidebar: boolean = true;
menuSidebar: MenuSidebar[] = [
{
link_name: 'Administration',
id: 'administration',
link: null,
icon: 'bx bx-collection',
active: false,
sub_menu: [
{
link_name: 'Sélection d\'un protefeuille',
link: '/administrations/select-portfolio',
},
],
},
{
link_name: 'Marchés',
id: 'market',
link: null,
icon: 'bx bx-line-chart',
active: false,
sub_menu: [
{
link_name: 'Valeurs',
link: '/markets/stocks',
},
{
link_name: 'Devise',
link: '/markets/currencies',
},
],
},
{
link_name: 'Portefeuille',
id: 'portefeuille',
link: null,
icon: 'bx bx-line-chart',
active: false,
sub_menu: [
{
link_name: 'Titre en portefeuille',
link: '/portfolio/stocks',
},
],
},
];
constructor(
private store: Store,
private sandbox: OnlineSandbox) { }
ngOnInit() {
}
showSubmenu(item: any) {
if (item.link_name == this.activeItem) {
this.activeItem = undefined;
} else {
this.activeItem = item.link_name;
}
}
selectMenu(parentMenu: { link_name: string }): void {
this.menuSidebar.forEach((menu) => {
if (menu.link_name !== parentMenu.link_name) {
menu.active = false;
} else {
menu.active = !menu.active;
}
});
}
signOut(): void {
this.unsubscribe$.next();
this.sandbox.signOut()
.pipe(
takeUntil(this.unsubscribe$)
).subscribe( res => { } );
}
canAccess(id: string): boolean {
if (id === "Portefeuille") {
if (this.store.selectSnapshot(ProfileState.currentPortfolio)) {
return true;
} else {
return false;
}
}
return true;
}
}
</code></pre>
<p>I don't know where/how I should embed the <code>canAccess</code> method in html?</p>
<p>html</p>
<pre><code><ul class="nav-links" id="nav-links">
<li *ngFor="let item of menuSidebar" [class.showMenu]="activeItem == item.link_name" #itemEl>
<div *ngIf="item.sub_menu.length > 0" class="dropdown-title" (click)="showSubmenu(item)">
<a (click)="selectMenu(item)">
<i [class]="item.icon"></i>
<span class="link_name">{{ item.link_name }}</span>
</a>
<i class="bx bxs-chevron-down arrow"></i>
</div>
<ul class="sub-menu" [class.blank]="item.sub_menu.length == 0">
<li>
<a class="link_name">{{ item.link_name }}</a>
</li>
<li *ngFor="let item_sub of item.sub_menu" routerLinkActive="active">
<a [routerLink]="[item_sub.link]">{{ item_sub.link_name }}</a>
</li>
</ul>
</li>
<li class="dropdown-title">
<a href="#" (click)="signOut()">
<i class="bx bx-log-out"></i>
<!-- Déconnexion -->
<span class="link_logout ">Déconnexion</span>
</a>
</li>
</ul>
</code></pre>
<p>MenuSidebar</p>
<pre><code>export type MenuSidebar = {
link_name: string;
id: string,
link: null;
icon: string;
active: boolean;
sub_menu: {
link_name: string;
link: string;
}[]
}
</code></pre>
|
[
{
"answer_id": 74463060,
"author": "Trooper Z",
"author_id": 9190768,
"author_profile": "https://Stackoverflow.com/users/9190768",
"pm_score": 0,
"selected": false,
"text": "for value in mean_task_dict.values():\n for item in value:\n #do stuff here\n"
},
{
"answer_id": 74463127,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 3,
"selected": true,
"text": "ROI_positions = np.array([1, 2, 3])\nfor i in range(len(mean_task_dict)):\n data_ROIs = np.array([\n mean_task_dict[\"Interoception\"][i],\n mean_task_dict[\"Exteroception\"][i],\n mean_task_dict[\"Cognitive\"][i]\n ])\n plt.scatter(ROI_positions, data_ROIs)\nplt.show()\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18427717/"
] |
74,462,750
|
<p>I am using swift version 5.7.1 and Xcode 14.1 . I am creating Map Application with user location and it working fine .. But here is the problem , it giving warning ..
<strong>This method can cause UI unresponsiveness if invoked on the main thread. Instead, consider waiting for the <code>-locationManagerDidChangeAuthorization:</code> callback and checking <code>authorizationStatus</code> first.</strong>.</p>
<p>On this line .. <code>if CLLocationManager.locationServicesEnabled() {</code></p>
<p>I already added into main thread. but still same warning .. Here is the code ..</p>
<pre><code>class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
let mapView = MKMapView()
let manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
mapView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(mapView)
mapView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
manager.requestAlwaysAuthorization()
manager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
DispatchQueue.main.async {
self.manager.delegate = self
self.manager.desiredAccuracy = kCLLocationAccuracyBest
self.manager.startUpdatingLocation()
self.mapView.delegate = self
self.mapView.mapType = .standard
self.mapView.isZoomEnabled = true
self.mapView.isScrollEnabled = true
self.mapView.showsUserLocation = false
}
}
if let coor = mapView.userLocation.location?.coordinate{
mapView.setCenter(coor, animated: true)
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations
locations: [CLLocation]) {
guard let mylocation = manager.location else { return }
let myCoordinates: CLLocationCoordinate2D = mylocation.coordinate
mapView.mapType = MKMapType.standard
let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
let region = MKCoordinateRegion(center: myCoordinates, span: span)
mapView.setRegion(region, animated: true)
// comment pin object if showsUserLocation = true
let pin = MKPointAnnotation()
pin.coordinate = myCoordinates
pin.title = "You are here"
mapView.addAnnotation(pin)
}
}
</code></pre>
<p>Here is the screenshot ..</p>
<p><a href="https://i.stack.imgur.com/QAedS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QAedS.png" alt="Warning " /></a></p>
|
[
{
"answer_id": 74462874,
"author": "DarkDust",
"author_id": 400056,
"author_profile": "https://Stackoverflow.com/users/400056",
"pm_score": 2,
"selected": false,
"text": "CLLocationManager.locationServicesEnabled()"
},
{
"answer_id": 74463378,
"author": "Fabio",
"author_id": 5575955,
"author_profile": "https://Stackoverflow.com/users/5575955",
"pm_score": 2,
"selected": true,
"text": "class Prova: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {\n\nlet mapView = MKMapView()\nlet manager = CLLocationManager()\n\noverride func viewDidLoad() {\n super.viewDidLoad()\n mapView.translatesAutoresizingMaskIntoConstraints = false\n view.addSubview(mapView)\n mapView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true\n mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true\n mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true\n mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true\n \n locationAuthorization()\n}\n\nfunc locationAuthorization(){\n switch manager.authorizationStatus {\n case .authorizedWhenInUse:\n print(\"Authorized\")\n determineMyCurrentLocation()\n case .denied:\n break\n case .authorizedAlways:\n determineMyCurrentLocation()\n case.notDetermined:\n manager.requestAlwaysAuthorization()\n manager.requestWhenInUseAuthorization()\n sleep(2)\n locationAuthorization()\n default:\n break\n }\n}\n\nfunc determineMyCurrentLocation() {\n print(\"determine current location\")\n if CLLocationManager.locationServicesEnabled() {\n DispatchQueue.main.async {\n self.manager.delegate = self\n self.manager.desiredAccuracy = kCLLocationAccuracyBest\n self.manager.startUpdatingLocation()\n self.mapView.delegate = self\n self.mapView.mapType = .standard\n self.mapView.isZoomEnabled = true\n self.mapView.isScrollEnabled = true\n self.mapView.showsUserLocation = false // if you want to show default pin\n }\n }\n \n if let coor = mapView.userLocation.location?.coordinate {\n mapView.setCenter(coor, animated: true)\n }\n}\n\noverride func viewDidAppear(_ animated: Bool) {\n super.viewDidAppear(animated)\n}\n\nfunc locationManager(_ manager: CLLocationManager, didUpdateLocations\n locations: [CLLocation]) {\n \n guard let mylocation = manager.location else { return }\n \n let myCoordinates: CLLocationCoordinate2D = mylocation.coordinate\n\n mapView.mapType = MKMapType.standard\n\n let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)\n let region = MKCoordinateRegion(center: myCoordinates, span: span)\n mapView.setRegion(region, animated: true)\n \n let pin = MKPointAnnotation()\n pin.coordinate = myCoordinates\n pin.title = \"You are here\"\n mapView.addAnnotation(pin)\n }\n}\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8705895/"
] |
74,462,757
|
<p>Can anyone help me with formula to compare two strings in excel using excel formulae or vba macros</p>
<p>Example :-</p>
<pre><code>str 1 : abcd def
str 2 : def abcd
</code></pre>
<p>If we compare str 1 and str 2 then it should return true</p>
<p>Thanks in advance</p>
<pre><code>str 1 : abcd def
str 2 : def abcd
=str1 = str2
</code></pre>
|
[
{
"answer_id": 74462874,
"author": "DarkDust",
"author_id": 400056,
"author_profile": "https://Stackoverflow.com/users/400056",
"pm_score": 2,
"selected": false,
"text": "CLLocationManager.locationServicesEnabled()"
},
{
"answer_id": 74463378,
"author": "Fabio",
"author_id": 5575955,
"author_profile": "https://Stackoverflow.com/users/5575955",
"pm_score": 2,
"selected": true,
"text": "class Prova: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {\n\nlet mapView = MKMapView()\nlet manager = CLLocationManager()\n\noverride func viewDidLoad() {\n super.viewDidLoad()\n mapView.translatesAutoresizingMaskIntoConstraints = false\n view.addSubview(mapView)\n mapView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true\n mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true\n mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true\n mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true\n \n locationAuthorization()\n}\n\nfunc locationAuthorization(){\n switch manager.authorizationStatus {\n case .authorizedWhenInUse:\n print(\"Authorized\")\n determineMyCurrentLocation()\n case .denied:\n break\n case .authorizedAlways:\n determineMyCurrentLocation()\n case.notDetermined:\n manager.requestAlwaysAuthorization()\n manager.requestWhenInUseAuthorization()\n sleep(2)\n locationAuthorization()\n default:\n break\n }\n}\n\nfunc determineMyCurrentLocation() {\n print(\"determine current location\")\n if CLLocationManager.locationServicesEnabled() {\n DispatchQueue.main.async {\n self.manager.delegate = self\n self.manager.desiredAccuracy = kCLLocationAccuracyBest\n self.manager.startUpdatingLocation()\n self.mapView.delegate = self\n self.mapView.mapType = .standard\n self.mapView.isZoomEnabled = true\n self.mapView.isScrollEnabled = true\n self.mapView.showsUserLocation = false // if you want to show default pin\n }\n }\n \n if let coor = mapView.userLocation.location?.coordinate {\n mapView.setCenter(coor, animated: true)\n }\n}\n\noverride func viewDidAppear(_ animated: Bool) {\n super.viewDidAppear(animated)\n}\n\nfunc locationManager(_ manager: CLLocationManager, didUpdateLocations\n locations: [CLLocation]) {\n \n guard let mylocation = manager.location else { return }\n \n let myCoordinates: CLLocationCoordinate2D = mylocation.coordinate\n\n mapView.mapType = MKMapType.standard\n\n let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)\n let region = MKCoordinateRegion(center: myCoordinates, span: span)\n mapView.setRegion(region, animated: true)\n \n let pin = MKPointAnnotation()\n pin.coordinate = myCoordinates\n pin.title = \"You are here\"\n mapView.addAnnotation(pin)\n }\n}\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20521242/"
] |
74,462,771
|
<h3>Problem</h3>
<p>I'm trying to get the command inside the docker-compose.yml to use the internal environment variables of the container, rather than the ones of the host system. However, docker compose tries to substitute environment variables in the command with the ones of my own shell, outside the container.</p>
<p>E.g. with the following compose-file:</p>
<pre><code>version: "3.9"
services:
service1:
image: alpine
command: "echo $PATH"
network_mode: bridge
</code></pre>
<p>The output contains the PATH of my own shell, not the one inside the container (The variable is getting substituted by Docker).</p>
<h3>What I've tried</h3>
<p>Using a double dollar character as described <a href="https://stackoverflow.com/a/40472001/7690374">here</a>. This gives me the following behavior:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">YAML syntax</th>
<th style="text-align: left;">Console Output</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;"><code>command: "echo ${PATH}"</code></td>
<td style="text-align: left;">(Still my own shell PATH variable)</td>
</tr>
<tr>
<td style="text-align: left;"><code>command: "echo $$PATH"</code></td>
<td style="text-align: left;"><code>$PATH</code></td>
</tr>
<tr>
<td style="text-align: left;"><code>command: "echo $${PATH}"</code></td>
<td style="text-align: left;"><code>${PATH}</code></td>
</tr>
</tbody>
</table>
</div>
<p>As noted above I want the console output to read the value of the actual PATH variable in the container (For the alpine container, the output should be <code>/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin</code>)</p>
<p>I've also tried <code>command: "printenv"</code>, which as expected shows the above internal value of the PATH variable, and not the one from my shell.</p>
<p><strong>Update1</strong><br />
I've also tried the exec format as proposed in the comments, with the following forms:</p>
<ul>
<li><code>command: ["echo", "${PATH}"]</code></li>
<li><code>command: ["echo", "$$PATH"]</code></li>
<li><code>command: ["echo", "$${PATH}"]</code>
These still give the same results as above.</li>
</ul>
<h3>Additional Context</h3>
<p>OS: Ubuntu 22.04<br />
Compose version: v2.12.2</p>
<h3>Question</h3>
<p>How can I use internal environment variables inside the command, so that the output of my command will give me the value of the internal PATH variable?</p>
|
[
{
"answer_id": 74462874,
"author": "DarkDust",
"author_id": 400056,
"author_profile": "https://Stackoverflow.com/users/400056",
"pm_score": 2,
"selected": false,
"text": "CLLocationManager.locationServicesEnabled()"
},
{
"answer_id": 74463378,
"author": "Fabio",
"author_id": 5575955,
"author_profile": "https://Stackoverflow.com/users/5575955",
"pm_score": 2,
"selected": true,
"text": "class Prova: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {\n\nlet mapView = MKMapView()\nlet manager = CLLocationManager()\n\noverride func viewDidLoad() {\n super.viewDidLoad()\n mapView.translatesAutoresizingMaskIntoConstraints = false\n view.addSubview(mapView)\n mapView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true\n mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true\n mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true\n mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true\n \n locationAuthorization()\n}\n\nfunc locationAuthorization(){\n switch manager.authorizationStatus {\n case .authorizedWhenInUse:\n print(\"Authorized\")\n determineMyCurrentLocation()\n case .denied:\n break\n case .authorizedAlways:\n determineMyCurrentLocation()\n case.notDetermined:\n manager.requestAlwaysAuthorization()\n manager.requestWhenInUseAuthorization()\n sleep(2)\n locationAuthorization()\n default:\n break\n }\n}\n\nfunc determineMyCurrentLocation() {\n print(\"determine current location\")\n if CLLocationManager.locationServicesEnabled() {\n DispatchQueue.main.async {\n self.manager.delegate = self\n self.manager.desiredAccuracy = kCLLocationAccuracyBest\n self.manager.startUpdatingLocation()\n self.mapView.delegate = self\n self.mapView.mapType = .standard\n self.mapView.isZoomEnabled = true\n self.mapView.isScrollEnabled = true\n self.mapView.showsUserLocation = false // if you want to show default pin\n }\n }\n \n if let coor = mapView.userLocation.location?.coordinate {\n mapView.setCenter(coor, animated: true)\n }\n}\n\noverride func viewDidAppear(_ animated: Bool) {\n super.viewDidAppear(animated)\n}\n\nfunc locationManager(_ manager: CLLocationManager, didUpdateLocations\n locations: [CLLocation]) {\n \n guard let mylocation = manager.location else { return }\n \n let myCoordinates: CLLocationCoordinate2D = mylocation.coordinate\n\n mapView.mapType = MKMapType.standard\n\n let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)\n let region = MKCoordinateRegion(center: myCoordinates, span: span)\n mapView.setRegion(region, animated: true)\n \n let pin = MKPointAnnotation()\n pin.coordinate = myCoordinates\n pin.title = \"You are here\"\n mapView.addAnnotation(pin)\n }\n}\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7690374/"
] |
74,462,791
|
<p>I am new in jupyter notebook and python. Recently I'm working in this code but I can't find out the problem. I want to rename <code>"Tesla Quarterly Revenue(Millions of US $)" and "Tesla Quarterly Revenue(Millions of US $).1"</code> into <code>"Data" and "Revenue"</code> but it not changed. Here is my code:</p>
<pre><code>!pip install pandas
!pip install requests
!pip install bs4
!pip install -U yfinance pandas
!pip install plotly
!pip install html5lib
!pip install lxml
</code></pre>
<pre><code>import yfinance as yf
import pandas as pd
import requests
from bs4 import BeautifulSoup
import plotly.graph_objects as go
from plotly.subplots import make_subplots
</code></pre>
<pre><code>url = "https://www.macrotrends.net/stocks/charts/TSLA/tesla/revenue?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0220ENSkillsNetwork23455606-2022-01-01"
html_data = requests.get(url).text
</code></pre>
<pre><code>soup = BeautifulSoup(html_data, 'html5lib')
tesla_revenue = pd.read_html(url, match = "Tesla Quarterly Revenue")[0]
tesla_revenue = tesla_revenue.rename(columns={"Tesla Quarterly Revenue(Millions of US $)":"Date","Tesla Quarterly Revenue(Millions of US $).1":"Revenue"})
tesla_revenue.head()
</code></pre>
<p>Here is the Output:</p>
<p><a href="https://i.stack.imgur.com/cDhIm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cDhIm.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74462874,
"author": "DarkDust",
"author_id": 400056,
"author_profile": "https://Stackoverflow.com/users/400056",
"pm_score": 2,
"selected": false,
"text": "CLLocationManager.locationServicesEnabled()"
},
{
"answer_id": 74463378,
"author": "Fabio",
"author_id": 5575955,
"author_profile": "https://Stackoverflow.com/users/5575955",
"pm_score": 2,
"selected": true,
"text": "class Prova: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {\n\nlet mapView = MKMapView()\nlet manager = CLLocationManager()\n\noverride func viewDidLoad() {\n super.viewDidLoad()\n mapView.translatesAutoresizingMaskIntoConstraints = false\n view.addSubview(mapView)\n mapView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true\n mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true\n mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true\n mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true\n \n locationAuthorization()\n}\n\nfunc locationAuthorization(){\n switch manager.authorizationStatus {\n case .authorizedWhenInUse:\n print(\"Authorized\")\n determineMyCurrentLocation()\n case .denied:\n break\n case .authorizedAlways:\n determineMyCurrentLocation()\n case.notDetermined:\n manager.requestAlwaysAuthorization()\n manager.requestWhenInUseAuthorization()\n sleep(2)\n locationAuthorization()\n default:\n break\n }\n}\n\nfunc determineMyCurrentLocation() {\n print(\"determine current location\")\n if CLLocationManager.locationServicesEnabled() {\n DispatchQueue.main.async {\n self.manager.delegate = self\n self.manager.desiredAccuracy = kCLLocationAccuracyBest\n self.manager.startUpdatingLocation()\n self.mapView.delegate = self\n self.mapView.mapType = .standard\n self.mapView.isZoomEnabled = true\n self.mapView.isScrollEnabled = true\n self.mapView.showsUserLocation = false // if you want to show default pin\n }\n }\n \n if let coor = mapView.userLocation.location?.coordinate {\n mapView.setCenter(coor, animated: true)\n }\n}\n\noverride func viewDidAppear(_ animated: Bool) {\n super.viewDidAppear(animated)\n}\n\nfunc locationManager(_ manager: CLLocationManager, didUpdateLocations\n locations: [CLLocation]) {\n \n guard let mylocation = manager.location else { return }\n \n let myCoordinates: CLLocationCoordinate2D = mylocation.coordinate\n\n mapView.mapType = MKMapType.standard\n\n let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)\n let region = MKCoordinateRegion(center: myCoordinates, span: span)\n mapView.setRegion(region, animated: true)\n \n let pin = MKPointAnnotation()\n pin.coordinate = myCoordinates\n pin.title = \"You are here\"\n mapView.addAnnotation(pin)\n }\n}\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12904389/"
] |
74,462,797
|
<p>I created a datatable from primevue, but I only get empty rows.</p>
<p>I looked where it could come from and I think it comes from my Json, whose fields have no key. What corrections should be made so that this Json becomes standard again and my data can be displayed? Thanks in advance.</p>
<p><strong>A short exemple of the Json I get:</strong></p>
<pre><code>[
[
32,
"DE BELLOUET Jag",
"1.3.13.3.",
"Cid polseruti sau"
],
[
15,
"NOURAUD Benjamin",
"1.3.13.3.",
"Cid polseruti sau"
]
]
</code></pre>
<p><strong>A short exemple of the jSon I need:</strong></p>
<pre><code>[
[
"id":32,
"fullName":"DE BELLOUET Jag",
"acs":"1.3.13.3.",
"nom_service":"Cid polseruti sau"
],
[
"id":15,
"fullName":"NOURAUD Benjamin",
"acs":"1.3.13.3.",
"nom_service":"Cid polseruti sau"
]
]
</code></pre>
<p><strong>The main program: gererPersonnes.vue</strong></p>
<pre><code><template>
<div class="principal_personnes">
<div class="bandeau">
<div>{{titre}}</div>
</div>
<div>
<h2>Liste des agents actifs</h2>
<DataTable :value="agents" :paginator="true" :rows="10" class="tableau">
<template #empty>
Pas d'agent trouvé.
</template>
<Column field="id" :sortable="true" header="Id" headerStyle="width: 3em" bodyStyle="text-align: center"></Column>
<Column field="fullName" :sortable="true" header="Nom - Prénom" headerStyle="width: 250px"></Column>
<Column field="service.acs" :sortable="true" header="A.C.S." headerStyle="width: 150px"></Column>
<Column field="service.nom_service" :sortable="true" header="Service" headerStyle="width: 250px; text-aling: left;"></Column>
<Column headerStyle="width: 8em">
<template #body >
<Button type="button" icon="pi pi-user" class="p-button-text" title="Détails"></Button>
<Button type="button" icon="pi pi-pencil" class="p-button-text" title="Modifier"></Button>
<Button type="button" icon="pi pi-trash" class="p-button-text" title="Supprimer"></Button>
</template>
</Column>
</DataTable>
</div>
<div class="button_gerer">
<button type="submit" class="boutton coin_vert" @click="cAjouter()">Ajouter un agent</button>
<button type="button" class="boutton coin_rouge" @click="cQuitter()">Abandon</button>
</div>
</div>
</template>
<style>
:root {
--gaucheP: 660px;
}
.principal_personnes {
height: var(--haut);
width: var(--large);
background-color:cornsilk;
}
.tableau {
width: 1000px;
margin: 0 auto;
}
.pi-user {
color:blue;
font-size: 1em;
}
.pi-pencil {
color:green;
font-size: 1em;
}
.pi-trash {
color:red;
font-size: 1em;
}
.p-datatable .p-datatable-tbody > tr > td {
text-align: left;
border: 1px solid #e9ecef;
border-width: 0 0 1px 0;
padding: 0rem 0rem;
}
h2 {
text-align:center;
}
.button_gerer {
display: grid;
grid-template: 30px / 130px 130px;
column-gap: 220px; /* Firefox 63+ Chrome 84+ */
justify-content: stretch;
align-content: stretch;
padding-left: var(--gaucheP);
padding-top: 40px;
}
</style>
<script>
import DataTable from 'primevue/datatable';
import Column from 'primevue/column';
import Button from 'primevue/button';
import ('primeicons/primeicons.css');
import AgentService from '../../services/AgentService'
export default {
name: 'gererPersonnes',
beforeCreate() {
window.self.document.title = "gererPersonnes"; // modification du titre de l'onglet
document.getElementById('menuU').style.setProperty('display', 'none'); //menu non affiché
},
components : {
DataTable,
Column,
Button
},
data() {
return {
agents : null,
titre: 'Gérer les personnes',
}
},
methods : {
cQuitter() {
let a = confirm("Voulez quitter la gestion des personnes ?");
if (a == true) {
this.$router.push("/");
}
},
cAjouter() {
let routeUrl = this.$router.resolve({
path : "/agents/add_agent",
});
window.open(routeUrl.href, '_blank');
}
},
created() {
this.AgentService = new AgentService;
},
mounted () {
this.AgentService.getAgentServices().then(data => this.agents = data);
},
AgentService : null
}
//Centrage du formulaire de la page
var inHeight = window.innerHeight - 140;
var inWidth = window.innerWidth;
if (inWidth > 1680) {
inWidth = 1680;
}
var l = Math.floor((inWidth - 460 - 20)/2);
var padLeft = l + 'px';
var hauteur = inHeight + 'px';
var r = document.querySelector(':root');
r.style.setProperty('--gaucheP', padLeft);
r.style.setProperty('--haut', hauteur);
</script>
</code></pre>
<p><strong>The service called by gererPersonnes.vue : AgentService.js</strong></p>
<pre><code>import axios from "axios";
const URL = "/cote-s-rest/rest/agent";
const URL2 = "/cote-s-rest/rest/password/";
const URL3 = "/cote-s-rest/rest/agent/patronyme";
const URL4 = "/cote-s-rest/rest/agent/agentServ";
export default class AgentService {
insertAgent(agent) {
return axios.post(URL, agent).then(resp => {
return Promise.resolve(resp.data);
});
}
passNewAgent(agent) {
return axios.post(URL2, agent).then(resp => {
return Promise.resolve(resp.data);
});
}
getAgents() {
return axios.get(URL3).then(resp => {
return Promise.resolve(resp.data);
});
}
getAgentServices() {
return axios.get(URL4).then(resp => {
return Promise.resolve(resp.data);
});
}
}
</code></pre>
<p><strong>The class AgentServ use in Java</strong></p>
<pre><code>
package fr.gouv.finances.douane.cotes.dao.agent;
/**
* Classe de requete pour la liste "AgentServ"
*
* @author Jean Paul Vandekerkhove
* @version 0.0.2.SNAPSHOT
*/
public class AgentServ {
//------------------------
// Attributs
//------------------------
private long id;
private String fullName;
private String acs;
private String nom_service;
//------------------------
// Constructeurs
//------------------------
/**
* Constructeur vide
*/
public AgentServ() {
super();
}
/**
* Constructeur complet
*
* @param id
* @param fullName
* @param acs
* @param nom_service
*/
public AgentServ(long id, String fullName, String acs, String nom_service) {
super();
this.id = id;
this.fullName = fullName;
this.acs = acs;
this.nom_service = nom_service;
}
//------------------------
// Getters et Setters
//------------------------
/**
* Retourne l'identifiant de l'Agent
* @return id - identifiant de l'Agent
*/
public long getId() {
return id;
}
/**
* MaJ de l'Identifiant de l'Agent
* @param id - Identifiant de l'agent
*/
public void setId(long id) {
this.id = id;
}
/**
* Retourne l'identité complete de l'Agent
* @return fullName - nom-prénom de l'Agent
*/
public String getFullName() {
return fullName;
}
/**
* MaJ de l'identité complete de l'Agent
* @param fullName - nom-prénom de l'Agent
*/
public void setFullName(String fullName) {
this.fullName = fullName;
}
/**
* Retourne l'acs du service de l'Agent
* @return acs - acs du service de l'Agent
*/
public String getAcs() {
return acs;
}
/**
* MaJ de l'acs du service de l'Agent
* @param acs - acs du service de l'Agent
*/
public void setAcs(String acs) {
this.acs = acs;
}
/**
* Retourne le libellé du service de l'Agent
* @return nom_service - libellé du service de l'Agent
*/
public String getNom_service() {
return nom_service;
}
/**
* MaJ le libellé du service de l'Agent
* @param nom_service - libellé du service de l'Agent
*/
public void setNom_service(String nom_service) {
this.nom_service = nom_service;
}
}
</code></pre>
<p><strong>The List Method use in AgentDaoImpl.java</strong></p>
<pre><code>
@SuppressWarnings("unchecked")
public List<AgentServ> listAgentService() {
String buf = null;
buf = "SELECT a.id AS id,(btrim(a.nom) || ' ' || btrim(a.prenom)) AS fullName, s.acs AS acs, s.libelle AS nom_service ";
buf += "FROM Agent a INNER JOIN Service s ON a.service = s ";
buf += "WHERE ((a.actif = true) OR ((a.actif = false) AND (a.dateSuppression >= CURRENT_DATE)))";
List<AgentServ> agents= em.createQuery(buf.toString()).getResultList();
return agents;
}
</code></pre>
<p><strong>The REST method</strong></p>
<pre><code>package fr.gouv.finances.douane.cotes.rest.agent;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.persistence.NoResultException;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import fr.gouv.finances.douane.cotes.dao.agent.Agent;
import fr.gouv.finances.douane.cotes.dao.agent.AgentDAO;
import fr.gouv.finances.douane.cotes.dao.agent.AgentServ;
import fr.gouv.finances.douane.cotes.dao.agent.ListAgent;
/**
* Classe de ressources REST de la classe ejb Agent
*
* @author VANDEKERKHOVE
* @version 0.0.1.SNAPSHOT
*/
@Path("/agent")
@RequestScoped
public class AgentResourceRESTService {
@Inject
private Logger log;
@Inject
private Validator validator;
@Inject
private AgentDAO repository;
@GET
@Path("/agentServ")
@Produces("application/json; charset=UTF-8")
public List<AgentServ> ListAgentService() {
return (List<AgentServ>) repository.listAgentService();
}
</code></pre>
<p><strong>The pom of the rest project</strong></p>
<pre><code>project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>fr.gouv.finances.douane.cote-s</groupId>
<artifactId>cote-s</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>cote-s-rest</artifactId>
<version>${project.parent.version}</version>
<packaging>war</packaging>
<description>Modules Rest de Cote-S</description>
<dependencies>
<dependency>
<groupId>fr.gouv.finances.douane.cote-s</groupId>
<artifactId>cote-s-ejb</artifactId>
<version>${project.parent.version}</version>
<type>ejb</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.ws.rs</groupId>
<artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.servlet</groupId>
<artifactId>jboss-servlet-api_4.0_spec</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson2-provider</artifactId>
<version>3.11.2.Final</version> <!-- $NO-MVN-MAN-VER$ -->
<scope>provided</scope>
</dependency>
<!-- Tests -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
</code></pre>
|
[
{
"answer_id": 74462874,
"author": "DarkDust",
"author_id": 400056,
"author_profile": "https://Stackoverflow.com/users/400056",
"pm_score": 2,
"selected": false,
"text": "CLLocationManager.locationServicesEnabled()"
},
{
"answer_id": 74463378,
"author": "Fabio",
"author_id": 5575955,
"author_profile": "https://Stackoverflow.com/users/5575955",
"pm_score": 2,
"selected": true,
"text": "class Prova: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {\n\nlet mapView = MKMapView()\nlet manager = CLLocationManager()\n\noverride func viewDidLoad() {\n super.viewDidLoad()\n mapView.translatesAutoresizingMaskIntoConstraints = false\n view.addSubview(mapView)\n mapView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true\n mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true\n mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true\n mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true\n \n locationAuthorization()\n}\n\nfunc locationAuthorization(){\n switch manager.authorizationStatus {\n case .authorizedWhenInUse:\n print(\"Authorized\")\n determineMyCurrentLocation()\n case .denied:\n break\n case .authorizedAlways:\n determineMyCurrentLocation()\n case.notDetermined:\n manager.requestAlwaysAuthorization()\n manager.requestWhenInUseAuthorization()\n sleep(2)\n locationAuthorization()\n default:\n break\n }\n}\n\nfunc determineMyCurrentLocation() {\n print(\"determine current location\")\n if CLLocationManager.locationServicesEnabled() {\n DispatchQueue.main.async {\n self.manager.delegate = self\n self.manager.desiredAccuracy = kCLLocationAccuracyBest\n self.manager.startUpdatingLocation()\n self.mapView.delegate = self\n self.mapView.mapType = .standard\n self.mapView.isZoomEnabled = true\n self.mapView.isScrollEnabled = true\n self.mapView.showsUserLocation = false // if you want to show default pin\n }\n }\n \n if let coor = mapView.userLocation.location?.coordinate {\n mapView.setCenter(coor, animated: true)\n }\n}\n\noverride func viewDidAppear(_ animated: Bool) {\n super.viewDidAppear(animated)\n}\n\nfunc locationManager(_ manager: CLLocationManager, didUpdateLocations\n locations: [CLLocation]) {\n \n guard let mylocation = manager.location else { return }\n \n let myCoordinates: CLLocationCoordinate2D = mylocation.coordinate\n\n mapView.mapType = MKMapType.standard\n\n let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)\n let region = MKCoordinateRegion(center: myCoordinates, span: span)\n mapView.setRegion(region, animated: true)\n \n let pin = MKPointAnnotation()\n pin.coordinate = myCoordinates\n pin.title = \"You are here\"\n mapView.addAnnotation(pin)\n }\n}\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14756852/"
] |
74,462,805
|
<p>I have a set of normalized tables with one-to-many and many-to-many relationships.</p>
<p>For most queries I am really interested in a highly denormalized view which shows:</p>
<ol>
<li>Entity-per-row for one specific table</li>
<li>Aggregated information about related entities from other tables</li>
</ol>
<p>Here is a <a href="https://www.db-fiddle.com/f/dTQWiqVD9xRxPov4v6Qxom/2" rel="nofollow noreferrer">DB fiddle</a>, or consider the following DDL:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE people(
name TEXT PRIMARY KEY
);
CREATE TABLE fruit(
name TEXT PRIMARY KEY
);
CREATE TABLE likes(
person TEXT REFERENCES people (name),
fruit TEXT REFERENCES fruit (name),
PRIMARY KEY (person, fruit)
);
INSERT INTO people VALUES ('Joe'), ('Brandon'), ('Miranda');
INSERT INTO fruit VALUES ('Banana'), ('Apple'), ('Orange'), ('Strawberry');
INSERT INTO likes VALUES ('Joe', 'Banana'), ('Joe', 'Apple'), ('Joe', 'Orange');
INSERT INTO likes VALUES ('Brandon', 'Apple');
INSERT INTO likes VALUES ('Miranda', 'Apple'), ('Miranda', 'Banana'), ('Miranda', 'Orange'), ('Miranda', 'Strawberry');
</code></pre>
<p>I want to show my users a filtered list of who likes which fruit so I construct the following query:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT person, string_agg(DISTINCT fruit, ', ' ORDER BY fruit) AS fruit
FROM likes
GROUP BY person;
</code></pre>
<p>This shows me a table with each person's name and a list of fruit they like. So far, so good. But now if I filter the list:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT person, string_agg(DISTINCT fruit, ', ' ORDER BY fruit) AS fruit
FROM likes
WHERE fruit='Orange'
GROUP BY person;
</code></pre>
<p>I get a list of people who like oranges, without the information about what <em>other</em> fruit those same people like.</p>
<p>Now, I understand why this happens: <code>WHERE</code> takes precedence over <code>SELECT</code>. What I would like to know is, is there a better way? How can I subset by <code>fruit='Orange'</code>, but still get a list of all fruit that a person likes in one row?</p>
<p>Do I <em>have</em> to use a CTE or an <code>INTERSECT</code>? The below gets me what I want, but I am afraid that it can get costly with multiple tables and multiple joins in each subquery because my real problem is obviously much larger, and with more tables like that:</p>
<pre><code>WITH select_people AS (
SELECT person
FROM likes
WHERE fruit = 'Orange'
)
SELECT person, string_agg(DISTINCT fruit, ', ' ORDER BY fruit) AS fruit
FROM likes
WHERE person in (select person from select_people)
GROUP BY person;
</code></pre>
<p>Thanks!</p>
|
[
{
"answer_id": 74462939,
"author": "Austin",
"author_id": 12571241,
"author_profile": "https://Stackoverflow.com/users/12571241",
"pm_score": 1,
"selected": false,
"text": "likes"
},
{
"answer_id": 74463707,
"author": "jjanes",
"author_id": 1721239,
"author_profile": "https://Stackoverflow.com/users/1721239",
"pm_score": 2,
"selected": false,
"text": "@>"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19357965/"
] |
74,462,832
|
<p>I have an array of objects which bassically are sidebar items. Every object has a MUI 5 icon. In a sidebar component I render it in a map function. I'd like to have a selected item to be highlighted...I managed to change the font color but don't know how to change icon color.</p>
<p>So the question is how to change icon color in Sidebar.tsx?</p>
<p><strong>routes.tsx</strong></p>
<pre><code>export const SIDEBAR_PATHS = [
{
id: 1,
path: PATHS.projects,
name: 'Projects',
icon: <AccountTreeIcon />,
},
{
id: 2,
path: PATHS.faces,
name: 'Faces',
icon: <FaceRetouchingNaturalIcon />,
},
];
</code></pre>
<p><strong>Sidebart.tsx</strong></p>
<pre><code> {SIDEBAR_PATHS.map(({ id, path, name, icon }) => (
<ListItem key={id} disablePadding>
<ListItemButton disableRipple onClick={() => navigate(path)} selected={path === pathname}>
{icon}
<ListItemText primary={name} primaryTypographyProps={{ fontWeight: 500 }} />
</ListItemButton>
</ListItem>
))}
</code></pre>
|
[
{
"answer_id": 74462909,
"author": "kind user",
"author_id": 6695924,
"author_profile": "https://Stackoverflow.com/users/6695924",
"pm_score": 3,
"selected": true,
"text": "icon"
},
{
"answer_id": 74463115,
"author": "arp",
"author_id": 10841628,
"author_profile": "https://Stackoverflow.com/users/10841628",
"pm_score": 0,
"selected": false,
"text": "import { SvgIcon } from \"@mui/material\";\n\n....\n\n{SIDEBAR_PATHS.map(({ id, path, name, icon }) => {\n return (\n <ListItem key={id} disablePadding>\n <ListItemButton disableRipple onClick={() => navigate(path)} selected={path === pathname}>\n <SvgIcon style={{ color: path === pathname ? 'green' : 'blue' }}{icon}</SvgIcon>\n <ListItemText primary={name} primaryTypographyProps={{ fontWeight: 500 }} />\n </ListItemButton>\n </ListItem>\n );\n})}\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16555202/"
] |
74,462,836
|
<p>I have a json file that has some parmeters with a nested object in it. And I'm trying to save this json file to the database. Altough I keep reciving this error:</p>
<p>" query did not return a unique result: 2; nested exception is javax.persistence.NonUniqueResultException: query did not return a unique result: 2"</p>
<p>`</p>
<pre><code>{
"personId" : "1xxxxxxx",
"invoiceDate" : "2020-10-12",
"invoices":[
{
"invoiceAmount" :"300",
"invoiceNumber" :"x123"
},
{
"invoiceAmount" :"100",
"invoiceNumber" :"x122"
}
],
}
</code></pre>
<p>`</p>
<p>So to insert an object in my DTO that has an array of (Invoices) I created an Object name invoices of type InvoicesDTO, then I tried to itirate through these Object everytime a request will be reviced using this API. But Still I get this error.</p>
<p>the dto's for Invoice and invoices:</p>
<p>`</p>
<pre><code>@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class InvoiceDTO {
@NotNull(message = "PersonId can't be null")
@PersonId
private String personId;
@NotNull(message = "invoiceDate can't be null")
// @DateTimeFormat(iso = DateTimeFormatter.ofPattern("yyyy-MM-dd"))
@PastOrPresent
@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate invoiceDate;
private InvoicesDTO invoices;
</code></pre>
<p>`</p>
<p>`</p>
<pre><code>@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class InvoicesDTO implements List<InvoicesDTO> {
@NotNull(message = "invoice Number can't be null")
private String invoiceNumber;
@NotNull(message = "invoiceAmount can't be null")
private Double invoiceAmount;
</code></pre>
<p>`</p>
<pre><code> try {
//Add the new amount of the invoice to an existing debts
Optional<Debts> debts = debtsRepository.findDebtsByPersonIdAndOrganization_id(invoiceDTO.getPersonId(),organization.get().getId());
Optional<Madeen> madeenOptional = madeenRepository.findByPersonId(invoiceDTO.getPersonId());
List<InvoicesDTO> invoicesDTO = invoiceDTO.getInvoices();
for (InvoicesDTO invoices : invoicesDTO) {
Debts newDebt = new Debts(); //Only debts
newDebt.setPersonId(invoiceDTO.getPersonId());
newDebt.setCreatedDate(LocalDate.now());
newDebt.setUpdatedDate(invoiceDTO.getInvoiceDate());
newDebt.setDebtAmount(invoices.getInvoiceAmount());
newDebt.setInvoiceNumber(invoices.getInvoiceNumber());
newDebt.setOrganization(organization.get());
debtsRepository.save(newDebt);
}
</code></pre>
|
[
{
"answer_id": 74462909,
"author": "kind user",
"author_id": 6695924,
"author_profile": "https://Stackoverflow.com/users/6695924",
"pm_score": 3,
"selected": true,
"text": "icon"
},
{
"answer_id": 74463115,
"author": "arp",
"author_id": 10841628,
"author_profile": "https://Stackoverflow.com/users/10841628",
"pm_score": 0,
"selected": false,
"text": "import { SvgIcon } from \"@mui/material\";\n\n....\n\n{SIDEBAR_PATHS.map(({ id, path, name, icon }) => {\n return (\n <ListItem key={id} disablePadding>\n <ListItemButton disableRipple onClick={() => navigate(path)} selected={path === pathname}>\n <SvgIcon style={{ color: path === pathname ? 'green' : 'blue' }}{icon}</SvgIcon>\n <ListItemText primary={name} primaryTypographyProps={{ fontWeight: 500 }} />\n </ListItemButton>\n </ListItem>\n );\n})}\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20521229/"
] |
74,462,846
|
<p>I'm trying to make it seem like the scroll bar is on the outside of a div that has rounded corners.</p>
<p>My approach was to place a div within the div where the inner div contains the content but the outer div has the overflow set to scroll.</p>
<p>This gets me pretty close to my desired result, except that...</p>
<ol>
<li>As you can see the content spills out of the inner div (for obvious reasons).</li>
<li>when you scroll, the div itself (not just the content) scrolls as well (see second image)</li>
</ol>
<p>Does anyone have any suggestions how to go about creating this effect?</p>
<p>I found <a href="https://stackoverflow.com/questions/16306322/put-scroll-bar-outside-div-with-auto-overflow">this question</a> which seems to be addressing the same issue but I found that this solution didn't work well for a div with rounded corners.</p>
<pre class="lang-js prettyprint-override"><code> <div style={{ width: 330, overflow: 'scroll' }}>
<div style={{ width: 300, height: 100, backgroundColor: 'lightgray', borderRadius: 30 }}>
abcdefghijklmnopqrstuvwxyz<br />
abcdefghijklmnopqrstuvwxyz<br />
abcdefghijklmnopqrstuvwxyz<br />
abcdefghijklmnopqrstuvwxyz<br />
abcdefghijklmnopqrstuvwxyz<br />
abcdefghijklmnopqrstuvwxyz<br />
abcdefghijklmnopqrstuvwxyz<br />
</div>
</div>
</code></pre>
<p><a href="https://i.stack.imgur.com/AOSv1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AOSv1.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/w1mfa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w1mfa.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74462909,
"author": "kind user",
"author_id": 6695924,
"author_profile": "https://Stackoverflow.com/users/6695924",
"pm_score": 3,
"selected": true,
"text": "icon"
},
{
"answer_id": 74463115,
"author": "arp",
"author_id": 10841628,
"author_profile": "https://Stackoverflow.com/users/10841628",
"pm_score": 0,
"selected": false,
"text": "import { SvgIcon } from \"@mui/material\";\n\n....\n\n{SIDEBAR_PATHS.map(({ id, path, name, icon }) => {\n return (\n <ListItem key={id} disablePadding>\n <ListItemButton disableRipple onClick={() => navigate(path)} selected={path === pathname}>\n <SvgIcon style={{ color: path === pathname ? 'green' : 'blue' }}{icon}</SvgIcon>\n <ListItemText primary={name} primaryTypographyProps={{ fontWeight: 500 }} />\n </ListItemButton>\n </ListItem>\n );\n})}\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14789957/"
] |
74,462,848
|
<p>my predicament is that I have to deserialize some JSON files provided by my company's software eng department, for me to use in a production environment, however some revisions of the JSON files have objects or keys where the name had been modified (E.g. <strong>"EngineTemp"</strong>:400 to <strong>"EngTemp"</strong>:400).</p>
<p>I can easily deserialize everything in C# when the names don't change, but I find myself having to modify my class property names or class names themselves, to match the JSON revisions (because I know they need to be the same). However, manually reading through each JSON file when it gets revised to check for name changes is very time-consuming, and some of these files have hundreds of objects.</p>
<p>Currently I have no way to ensure the software eng team keeps the same names from revision to revision, so I really hope there is a way to handle this in a less manual fashion.</p>
<p>I can't provide any snippets of the JSON unfortunately because it's proprietary information, but the above example is basically what I want to account for.</p>
<p>I appreciate all suggestions!</p>
<p>As mentioned previously, I haven't come up with any good way of handling this in code yet, since it deals with changing the actual class and property names in my C#, to match the revisions in the JSON if they are altered.</p>
|
[
{
"answer_id": 74463105,
"author": "Cosmin Sontu",
"author_id": 2841855,
"author_profile": "https://Stackoverflow.com/users/2841855",
"pm_score": -1,
"selected": false,
"text": "Newtonsoft"
},
{
"answer_id": 74463494,
"author": "Poul Bak",
"author_id": 5741643,
"author_profile": "https://Stackoverflow.com/users/5741643",
"pm_score": 1,
"selected": true,
"text": "(?<=\")(EngineTemp|EngTemp|OtherName)(?=\":)\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20521198/"
] |
74,462,860
|
<p>I have created a roll-up Master Project using a VBA macro that grabs all MS project files in a given directory and adds them to my Master Project file. Everything works well but the title these subtasks get added as uses the Project Title (found in File->Info->Project Information->Advanced Properties->Title) instead of the Filename.</p>
<p>I will not be the only person creating these files so I can't guarantee the Title is accurate. What I would like to do is, using a macro, every time a MS Project file is opened it checks if the Title is different than the Filename and if so sets the Title to whatever the Filename is. My issue is, I cannot find a property of the Project object or a method that allows me to access the Project Title. Can anyone help out with how I might accomplish this.</p>
<p>An alternative solution would also be to add the Projects to my Master Project using the Filename instead of the Title but I also haven't figured out how I can accomplish that. To add the projects as subtasks I loop through all .mpp files in a given direction using the following line:</p>
<pre><code>ConsolidateProjects Filenames:=projPath & projFile, NewWindow:=False, HideSubtasks:=True, AttachToSources:=False
</code></pre>
<p>Any help would be greatly appreciated.</p>
|
[
{
"answer_id": 74463105,
"author": "Cosmin Sontu",
"author_id": 2841855,
"author_profile": "https://Stackoverflow.com/users/2841855",
"pm_score": -1,
"selected": false,
"text": "Newtonsoft"
},
{
"answer_id": 74463494,
"author": "Poul Bak",
"author_id": 5741643,
"author_profile": "https://Stackoverflow.com/users/5741643",
"pm_score": 1,
"selected": true,
"text": "(?<=\")(EngineTemp|EngTemp|OtherName)(?=\":)\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1788496/"
] |
74,462,861
|
<p>I have a dataframe with various numbers. What I want, is to subset rows using all column values.</p>
<p>One could use dplyr to write the following code:</p>
<pre><code>library(dplyr)
set.seed(1)
df <- data.frame (matrix (round (runif(500, 0, 1), digits = 1), 10, 5))
dfn <- df |> dplyr::filter_all (dplyr::any_vars (grepl (0.5,.)))
</code></pre>
<p>Does anyone know what the base R version of this code would be? Any help is very much appreciated.</p>
|
[
{
"answer_id": 74462944,
"author": "Ben Bolker",
"author_id": 190277,
"author_profile": "https://Stackoverflow.com/users/190277",
"pm_score": 3,
"selected": true,
"text": "has_0.5 <- apply(df, 1, function(x) any(grepl(0.5, x)))\ndf[has_0.5, ]\n"
},
{
"answer_id": 74462985,
"author": "G. Grothendieck",
"author_id": 516548,
"author_profile": "https://Stackoverflow.com/users/516548",
"pm_score": 2,
"selected": false,
"text": "df[rowSums(sapply(df, grepl, pattern = 0.5)) > 0, ]\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17984720/"
] |
74,462,882
|
<p>I have this problem, I want to change the value of column Q based on what word is in Column U. But here comes the tricky part, in column U I could have different words which actually will mean the same, here is the index: (left side are the words of column U and right side their meaning)</p>
<pre class="lang-none prettyprint-override"><code>REOK: CONCLUSIVE RESOLVED
INIC: IN PROCESS
PLAN: IN PROCESS
VERI: IN PROCESS
OPER: IN PROCESS
FISC: IN PROCESS
OTRA: IN PROCESS
TERC: IN PROCESS
SERV: IN PROCESS
PROG: IN PROCESS
FREN: CONCLUSIVE DENIED
INFO: CONCLUSIVE DENIED
INEX: CONCLUSIVE DENIED
IM01: CONCLUSIVE DENIED
IM02: CONCLUSIVE DENIED
IM03: CONCLUSIVE DENIED
IM04: CONCLUSIVE DENIED
IM05: CONCLUSIVE DENIED
CANC: CONCLUSIVE DENIED
</code></pre>
<p>So, for example if in (column U - Row 1) I have "REOK", I would like column Q to automatically change to "CONCLUSIVE RESOLVED".</p>
<p>That would be the first part, but I have another issue. Column U is imported from another app every 3 days, so I could actually have more recent information than the report has so in some cases I would need to manually change column Q to the states of right side of index (probably until I receive the next report in 3 days) without changing the formula of the cell in case the report which comes in 3 days updates the state of the case.</p>
<p>I have tried an attempt of inserting an array formula but I encountered the problem of not being able to manually change column Q because that would delete the array formula itself.</p>
|
[
{
"answer_id": 74479184,
"author": "Martín",
"author_id": 20363318,
"author_profile": "https://Stackoverflow.com/users/20363318",
"pm_score": 0,
"selected": false,
"text": "=ArrayFormula(IF(V2:V<>\"\",V2:V,IF(U2:U=\"\",\"\",ifs(REGEXMATCH(U2:U,\"(?i)REOK\"),\"CONCLUSIVE RESOLVED\",REGEXMATCH(U2:U,\"(?i)INIC|PLAN|VERI|OPER|FISC|ORA|TERC|SERV|PROGR\"),\"IN PROCESS\",REGEXMATCH(U2:U,\"(?i)FREN|INFO|INEX|IM01|IM02|IM03|IM04|IM05|CANC\"),\"CONCLUSIVE DENIED\"))))\n"
},
{
"answer_id": 74573160,
"author": "Juan Ignacio Portilla Kitroser",
"author_id": 16799853,
"author_profile": "https://Stackoverflow.com/users/16799853",
"pm_score": -1,
"selected": false,
"text": "\"=QUERY(sap!A:B;\"SELECT B WHERE A = '\"&A2&\"')\"\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20521157/"
] |
74,462,926
|
<p>Having this node.js app which is going to be quite huge.
First I created a file named</p>
<pre><code>user.account.test.js
</code></pre>
<p>In that I begun putting all the possible tests (positive and negative tests) for the usuale flow: signup, singin, activation, restore password etc.</p>
<p>At the end I have this file that is over 600 rows. Now, Im going to create a lot of more tests. And having everything in the same file sounds silly to me.</p>
<p>I could not really find resources that explain how to split the test in severals test files.
Im having a nightmare when I created a new test file where to put other tests. I mostly got timeout issues.
And a lot of things look strange. For example:</p>
<p>In the user.account.test.js I had this line:</p>
<pre><code>beforeAll(async () => {
await mongoose.connect(process.env.MONGODB_TEST_URI);
});
</code></pre>
<p>In the second test file, named user.step2.test.js, I was unsure if I had to also put the same function.
At the end I did it, and incredibly that file did not know anything about "process.env.MONGODB_TEST_URI".</p>
<p>What is the best practice when you want to split tests into multiple files?</p>
|
[
{
"answer_id": 74479184,
"author": "Martín",
"author_id": 20363318,
"author_profile": "https://Stackoverflow.com/users/20363318",
"pm_score": 0,
"selected": false,
"text": "=ArrayFormula(IF(V2:V<>\"\",V2:V,IF(U2:U=\"\",\"\",ifs(REGEXMATCH(U2:U,\"(?i)REOK\"),\"CONCLUSIVE RESOLVED\",REGEXMATCH(U2:U,\"(?i)INIC|PLAN|VERI|OPER|FISC|ORA|TERC|SERV|PROGR\"),\"IN PROCESS\",REGEXMATCH(U2:U,\"(?i)FREN|INFO|INEX|IM01|IM02|IM03|IM04|IM05|CANC\"),\"CONCLUSIVE DENIED\"))))\n"
},
{
"answer_id": 74573160,
"author": "Juan Ignacio Portilla Kitroser",
"author_id": 16799853,
"author_profile": "https://Stackoverflow.com/users/16799853",
"pm_score": -1,
"selected": false,
"text": "\"=QUERY(sap!A:B;\"SELECT B WHERE A = '\"&A2&\"')\"\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5668102/"
] |
74,462,937
|
<p>I am pretty new to React, and the only CRUD functionality I have done has been in MVC.net, so I am pretty lost here and none of the tutorials I am finding seem to be the situation I have going on...or maybe I am just misunderstanding them. The tips I got with my initial question helped, but I am still no getting it to work, so hopefully now I have supplies enough info to help other help me. I did no include all of the input fields because their are like 15 and it was just redundant.</p>
<p>I am pulling up the modal using this onClick event:</p>
<pre><code>onClick={()=> {handleEditModal(item)}}
</code></pre>
<p><strong>modalFunctions.js</strong></p>
<pre><code>// Modal Functionality
export function ModalFunctions() {
const [selectedRecord, setSelectedRecord] = useState([]);
const [openModal, setOpenModal] = useState(false);
const handleEditModal = item =>{
setOpenModal(true)
setSelectedRecord(item)
}
return {
selectedRecord,
setSelectedRecord,
openModal,
setOpenModal,
handleEditModal,
handleDetailModal
}
}
// Form Functionality
export function FormFunctions(validateOnChange = false, validate) {
const [values, setValues] = useState('');
const [errors, setErrors] = useState({});
const handleInputChange = e => {
const { name, value } = e.target
setValues({
...values,
[name]: value
})
if (validateOnChange)
validate({ [name]: value })
}
return {errors, handleInputChange, setErrors, setValues, values}
}
</code></pre>
<p><strong>DataTable.js</strong></p>
<pre><code>// Imported Modal Functions
const {
selectedRecord,
openModal,
setOpenModal,
handleEditModal,
handleDetailModal
} = ModalFunctions();
const baseURL = 'http://localhost:8080/api/tanks';
// Fetch Data
useEffect(() => {
const fetchData = async () =>{
setLoading(true);
try {
const {data: response} = await axios.get(baseURL);
setTableData(response);
} catch (error) {
console.error(error.message);
}
setLoading(false);
};
fetchData();
}, [baseURL, setTableData, setLoading]);
// The Modal
return(
<Modal
title={ "Editing: " + (selectedRecord.tankName) }
openModal={openModal}
setOpenModal={setOpenModal}
>
<TankEdit
selectedRecord={selectedRecord}
setOpenModal={setOpenModal}
openModal={openModal}
/>
</Modal>
)
</code></pre>
<p><strong>TankEdit.js</strong></p>
<pre><code>export function TankEdit(props) {
const { baseURL, openModal, selectedRecord, setOpenModal, setTableData } = props;
const validate = (fieldValues = item) => {
let temp = { ...errors }
if ('tankName' in fieldValues)
temp.tankName = fieldValues.tankName ? "" : "This field is required."
setErrors({
...temp
})
if (fieldValues === values)
return Object.values(temp).every(x => x === " ")
}
const {
values,
setValues,
errors,
setErrors,
handleInputChange,
} = FormFunctions(true, validate);
useEffect(() => {
if (selectedRecord !== null)
setValues({
...selectedRecord
})
}, [selectedRecord, setValues])
function editRecord() {
axios.put(`${baseURL}`, {
title: "Success",
body: "The record had been successfully updated"
}).then ((response) => {setTableData(response.data);})
}
const handleSubmit = e => {
e.preventDefault()
if (validate()) {
editRecord(values);
}
setOpenModal(false)
}
const item = values; // used for easier referencing (matches table item)
return (
<Form onSubmit={handleSubmit} open={openModal}>
<Grid>
<Controls.Input
name="tankName"
label="Tank Name"
value={item.tankName}
onChange={handleInputChange}
error={errors.tankName}
/>
</Grid>
<Grid>
<Controls.Button
type="submit"
text="Submit"
/>
<Controls.Button
text="Cancel"
color="default"
onClick={()=>{setOpenModal(false)}}
/>
</Grid>
</Form>
)
}
</code></pre>
<p><strong>Input.js</strong></p>
<pre><code>export default function Input(props) {
const { error=null, label, name, onChange, value, ...other } = props;
return (
<TextField
variant="outlined"
label={label}
name={name}
value={value}
defaultValue=''
onChange={onChange}
{...other}
{...(error && {error:true,helperText:error})}
/>
)
}
</code></pre>
<p>My company is only wanting a Read and an Update function, since Creating and Deletion will be handled another ways, so this is my final hangup. I think I am close, but I am missing something.</p>
<p>Can anyone point me in the right direction?</p>
<p>THANKS!!!!</p>
|
[
{
"answer_id": 74479184,
"author": "Martín",
"author_id": 20363318,
"author_profile": "https://Stackoverflow.com/users/20363318",
"pm_score": 0,
"selected": false,
"text": "=ArrayFormula(IF(V2:V<>\"\",V2:V,IF(U2:U=\"\",\"\",ifs(REGEXMATCH(U2:U,\"(?i)REOK\"),\"CONCLUSIVE RESOLVED\",REGEXMATCH(U2:U,\"(?i)INIC|PLAN|VERI|OPER|FISC|ORA|TERC|SERV|PROGR\"),\"IN PROCESS\",REGEXMATCH(U2:U,\"(?i)FREN|INFO|INEX|IM01|IM02|IM03|IM04|IM05|CANC\"),\"CONCLUSIVE DENIED\"))))\n"
},
{
"answer_id": 74573160,
"author": "Juan Ignacio Portilla Kitroser",
"author_id": 16799853,
"author_profile": "https://Stackoverflow.com/users/16799853",
"pm_score": -1,
"selected": false,
"text": "\"=QUERY(sap!A:B;\"SELECT B WHERE A = '\"&A2&\"')\"\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10982789/"
] |
74,462,966
|
<p>I have a table below , I will like to group and concatenate into a new field based on the siteid using pandas/python</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><!DOCTYPE html>
<html>
<style>
table, th, td {
border:1px solid black;
}
</style>
<body>
<table style="width:100%">
<tr>
<th>SiteID</th>
<th>Name</th>
<th>Count</th>
</tr>
<tr>
<td>A</td>
<td>Conserve</td>
<td>3</td>
</tr>
<tr>
<td>A</td>
<td>Listed</td>
<td>5</td>
</tr>
<tr>
<td>B</td>
<td>Listed</td>
<td>5</td>
</tr>
</table>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>I will like the new table to look like this</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<style>
table, th, td {
border:1px solid black;
}
</style>
<body>
<table style="width:100%">
<tr>
<th>SiteID</th>
<th>Output</th>
</tr>
<tr>
<td>A</td>
<td>There are Conserve : 3, Listed : 5 </td>
</tr>
<tr>
<td>B</td>
<td>There are Listed : 5</td>
</tr>
</table>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>not sure what code to use, I have used group by. I tried this</p>
<p><code>df = df.groupby("SiteID")["Name"].agg(";".join).reset_index()</code></p>
<p>but I would like to put the result in a new field with a concatenate string as above</p>
|
[
{
"answer_id": 74479184,
"author": "Martín",
"author_id": 20363318,
"author_profile": "https://Stackoverflow.com/users/20363318",
"pm_score": 0,
"selected": false,
"text": "=ArrayFormula(IF(V2:V<>\"\",V2:V,IF(U2:U=\"\",\"\",ifs(REGEXMATCH(U2:U,\"(?i)REOK\"),\"CONCLUSIVE RESOLVED\",REGEXMATCH(U2:U,\"(?i)INIC|PLAN|VERI|OPER|FISC|ORA|TERC|SERV|PROGR\"),\"IN PROCESS\",REGEXMATCH(U2:U,\"(?i)FREN|INFO|INEX|IM01|IM02|IM03|IM04|IM05|CANC\"),\"CONCLUSIVE DENIED\"))))\n"
},
{
"answer_id": 74573160,
"author": "Juan Ignacio Portilla Kitroser",
"author_id": 16799853,
"author_profile": "https://Stackoverflow.com/users/16799853",
"pm_score": -1,
"selected": false,
"text": "\"=QUERY(sap!A:B;\"SELECT B WHERE A = '\"&A2&\"')\"\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74462966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6768849/"
] |
74,463,028
|
<p>I have an input image where I have drawn the green boundaries which I need to mask.
I am able to identify the boundary, but my mask is all black with baground is black. how can I fill the boundary region with different color. May be keep the background white and mask region as black</p>
<p>Input image
<a href="https://i.stack.imgur.com/Q1JMG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q1JMG.png" alt="enter image description here" /></a></p>
<pre><code>im = cv2.imread(imagePath)
plt.imshow(im)
#color boundaries [B, G, R]
lower = np.array([0,120,0])
upper = np.array([200,255,100])
# threshold on green color
thresh = cv2.inRange(im, lower, upper)
plt.imshow(thresh)
# get largest contour
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)
x,y,w,h = cv2.boundingRect(big_contour)
# draw filled contour on black background
mask = np.zeros_like(im)
cv2.drawContours(mask, [big_contour], 0, (255,255,255), cv2.FILLED)
plt.imshow(mask)
# apply mask to input image
new_image = cv2.bitwise_and(im, mask)
</code></pre>
<p>Generated Output
<a href="https://i.stack.imgur.com/AWeTF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AWeTF.png" alt="enter image description here" /></a></p>
<p>I am expecting the green countor will be filled with some different color. May be white background with black countour. or transparent background</p>
|
[
{
"answer_id": 74479184,
"author": "Martín",
"author_id": 20363318,
"author_profile": "https://Stackoverflow.com/users/20363318",
"pm_score": 0,
"selected": false,
"text": "=ArrayFormula(IF(V2:V<>\"\",V2:V,IF(U2:U=\"\",\"\",ifs(REGEXMATCH(U2:U,\"(?i)REOK\"),\"CONCLUSIVE RESOLVED\",REGEXMATCH(U2:U,\"(?i)INIC|PLAN|VERI|OPER|FISC|ORA|TERC|SERV|PROGR\"),\"IN PROCESS\",REGEXMATCH(U2:U,\"(?i)FREN|INFO|INEX|IM01|IM02|IM03|IM04|IM05|CANC\"),\"CONCLUSIVE DENIED\"))))\n"
},
{
"answer_id": 74573160,
"author": "Juan Ignacio Portilla Kitroser",
"author_id": 16799853,
"author_profile": "https://Stackoverflow.com/users/16799853",
"pm_score": -1,
"selected": false,
"text": "\"=QUERY(sap!A:B;\"SELECT B WHERE A = '\"&A2&\"')\"\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1631306/"
] |
74,463,032
|
<p>I have a simple socket server, how do I shut it down when I enter "shutdown" in the terminal on the server side?</p>
<pre><code>import socket
SERVER = "xxxx"
PORT = 1234
ADDR = (SERVER, PORT)
FORMAT = "utf-8"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_connection(conn, addr):
...
server.listen()
while True:
conn, addr = server.accept()
handle_connection(conn, addr)
</code></pre>
|
[
{
"answer_id": 74479184,
"author": "Martín",
"author_id": 20363318,
"author_profile": "https://Stackoverflow.com/users/20363318",
"pm_score": 0,
"selected": false,
"text": "=ArrayFormula(IF(V2:V<>\"\",V2:V,IF(U2:U=\"\",\"\",ifs(REGEXMATCH(U2:U,\"(?i)REOK\"),\"CONCLUSIVE RESOLVED\",REGEXMATCH(U2:U,\"(?i)INIC|PLAN|VERI|OPER|FISC|ORA|TERC|SERV|PROGR\"),\"IN PROCESS\",REGEXMATCH(U2:U,\"(?i)FREN|INFO|INEX|IM01|IM02|IM03|IM04|IM05|CANC\"),\"CONCLUSIVE DENIED\"))))\n"
},
{
"answer_id": 74573160,
"author": "Juan Ignacio Portilla Kitroser",
"author_id": 16799853,
"author_profile": "https://Stackoverflow.com/users/16799853",
"pm_score": -1,
"selected": false,
"text": "\"=QUERY(sap!A:B;\"SELECT B WHERE A = '\"&A2&\"')\"\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19366064/"
] |
74,463,108
|
<p><a href="https://i.stack.imgur.com/VBIiT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VBIiT.png" alt="enter image description here" /></a>I am working on a price sheet that has products with variations to that product underneath.
It has 15,000 rows and I would like to sort in alphabetical order.</p>
<p>However doing so breaks the product/variations, so you wont know what variations are with what product.
I have color coded all the products as well as the variations.</p>
<p><strong>What I need is the Products to be sorted A-Z, along with keeping the variations underneath it.</strong></p>
<p>Sorting breaks the product/variation setup.</p>
|
[
{
"answer_id": 74463549,
"author": "Notus_Panda",
"author_id": 19353309,
"author_profile": "https://Stackoverflow.com/users/19353309",
"pm_score": 0,
"selected": false,
"text": "=If(B2 = \"Product\"; C2; A1+1)\n"
},
{
"answer_id": 74464133,
"author": "David Leal",
"author_id": 6237093,
"author_profile": "https://Stackoverflow.com/users/6237093",
"pm_score": 2,
"selected": true,
"text": "D2"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9688187/"
] |
74,463,151
|
<p>You are given an array of integers nums and a sliding window of size <code>k</code> which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. You have to compute the maximum inside the window.</p>
<pre><code>Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
</code></pre>
<pre><code>class Solution {
public:
vector<int> maxSlidingWindow(vector<int> &nums, int k) {
int n=nums.size();
vector<int> answer;
for(int i=0; i<n; i++){
int mx = INT_MIN;
for(int j=1; j<i+k; j++){
mx = max(mx, nums[j]);
}
answer.push_back(mx);
}
while(answer.size()>n-k+1){
answer.pop_back();
}
return answer;
}
};
</code></pre>
<p>But throws an error</p>
<pre><code>=================================================================
==31==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x603000000090 at pc 0x000000345e1e bp 0x7ffef610bff0 sp 0x7ffef610bfe8
READ of size 4 at 0x603000000090 thread T0
#2 0x7fb1bb36d0b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
0x603000000090 is located 0 bytes to the right of 32-byte region [0x603000000070,0x603000000090)
allocated by thread T0 here:
#6 0x7fb1bb36d0b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
Shadow bytes around the buggy address:
0x0c067fff7fc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7fd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7fe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7ff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff8000: fa fa 00 00 00 07 fa fa fd fd fd fa fa fa 00 00
=>0x0c067fff8010: 00 00[fa]fa 00 00 00 00 fa fa fa fa fa fa fa fa
0x0c067fff8020: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8030: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8040: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8050: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8060: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
Container overflow: fc
Array cookie: ac
Intra object redzone: bb
ASan internal: fe
Left alloca redzone: ca
Right alloca redzone: cb
Shadow gap: cc
==31==ABORTING
</code></pre>
|
[
{
"answer_id": 74463549,
"author": "Notus_Panda",
"author_id": 19353309,
"author_profile": "https://Stackoverflow.com/users/19353309",
"pm_score": 0,
"selected": false,
"text": "=If(B2 = \"Product\"; C2; A1+1)\n"
},
{
"answer_id": 74464133,
"author": "David Leal",
"author_id": 6237093,
"author_profile": "https://Stackoverflow.com/users/6237093",
"pm_score": 2,
"selected": true,
"text": "D2"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20333579/"
] |
74,463,189
|
<p>I am trying the following code to drop a table in Azure Synapse</p>
<p>drop dbo.tablename</p>
<p>drop tablename</p>
<p><a href="https://i.stack.imgur.com/Q27w8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q27w8.png" alt="enter image description here" /></a></p>
<p>But I keep on getting errors such as:</p>
<pre><code>Unknown object type 'ts_originationopportunity' used in a CREATE, DROP, or ALTER statement.
</code></pre>
<p>Or</p>
<pre><code>Unknown object type 'dbo' used in a CREATE, DROP, or ALTER statement.
</code></pre>
<p><a href="https://i.stack.imgur.com/SeOve.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SeOve.png" alt="enter image description here" /></a></p>
<p>Can someone let me know what is the correct syntax to drop a table in Azure Synapse Serverless Builtin Pool please</p>
|
[
{
"answer_id": 74467716,
"author": "HimanshuSinha-msft",
"author_id": 11137679,
"author_profile": "https://Stackoverflow.com/users/11137679",
"pm_score": 0,
"selected": false,
"text": "use [your DatabaseName] \nGO \ndrop EXTERNAL table schemaname.tablename\n"
},
{
"answer_id": 74528726,
"author": "ShaikMaheer-MSFT",
"author_id": 16161919,
"author_profile": "https://Stackoverflow.com/users/16161919",
"pm_score": 2,
"selected": true,
"text": "DROP TABLE table_name"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15520615/"
] |
74,463,208
|
<p>I've set up a service and some pods in an AWS Elastic Kubernetes Service (EKS) cluster which access a RabbitMQ message service and PostgreSQL database hosted externally to the cluster. At the moment, I've opened up via AWS security groups access from all IPs (0.0.0.0/0) to these services as kubernetes assigns an IP for each node when it is created.</p>
<p>Ideally, I'd like to route traffic from Kubernetes to these services via one consistent "external Kubernetes IP" so I can add it in to each external services security group. Currently, from Googling around I haven't found a way to do this, is it possible?</p>
<p>For RabbitMQ I have the current Service and Endpoint set up, but I believe this is only for routing traffic through the Kubernetes cluster and not related to the external facing side of my cluster?</p>
<pre><code>kind: Service
metadata:
name: rabbitmq-service
spec:
selector:
app: job-wq-1
ports:
- port: 15672
targetPort: 15672
name: management-port
- port: 5672
targetPort: 5672
name: data-port
type: LoadBalancer
---
kind: Endpoints
apiVersion: v1
metadata:
name: rabbitmq
subsets:
- addresses:
- ip: 'rabbitmq.server.public.ip'
ports:
- port: 15672
name: 'management-port'
- port: 5672
name: 'data-port'
</code></pre>
|
[
{
"answer_id": 74467716,
"author": "HimanshuSinha-msft",
"author_id": 11137679,
"author_profile": "https://Stackoverflow.com/users/11137679",
"pm_score": 0,
"selected": false,
"text": "use [your DatabaseName] \nGO \ndrop EXTERNAL table schemaname.tablename\n"
},
{
"answer_id": 74528726,
"author": "ShaikMaheer-MSFT",
"author_id": 16161919,
"author_profile": "https://Stackoverflow.com/users/16161919",
"pm_score": 2,
"selected": true,
"text": "DROP TABLE table_name"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8200410/"
] |
74,463,220
|
<pre><code>import time
from multiprocessing import Process
def possible_error_causer(a, b):
time.sleep(5)
c = a / b
print(c)
time.sleep(100)
for i in range(3):
p = Process(target=possible_error_causer, args=(i, i))
p.start()
</code></pre>
<p>The code above will execute after an exception occured in process that received 0, 0 as arguments (will run 100 seconds after that). But I want script to stop when there is error in any process. Try except is not an option (sys.exit() in except), because it doesn't catch all external errors (eg it doesn't catch some OpenCV errors)</p>
|
[
{
"answer_id": 74467716,
"author": "HimanshuSinha-msft",
"author_id": 11137679,
"author_profile": "https://Stackoverflow.com/users/11137679",
"pm_score": 0,
"selected": false,
"text": "use [your DatabaseName] \nGO \ndrop EXTERNAL table schemaname.tablename\n"
},
{
"answer_id": 74528726,
"author": "ShaikMaheer-MSFT",
"author_id": 16161919,
"author_profile": "https://Stackoverflow.com/users/16161919",
"pm_score": 2,
"selected": true,
"text": "DROP TABLE table_name"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9016861/"
] |
74,463,255
|
<p>I'm learning about unit test for Flutter. I have a Sign In with Google functionality in my app as a package and I want to unit test it.</p>
<p>I'm half way there but I kinda stuck about what to do with this error.</p>
<pre><code>'package:firebase_auth_platform_interface/src/providers/google_auth.dart': Failed assertion: line 43 pos 12: 'accessToken != null || idToken != null': At least one of ID token and access token is required
dart:core _AssertionError._throwNew
package:firebase_auth_platform_interface/src/providers/google_auth.dart 43:12 GoogleAuthProvider.credential
package:firebase_auth_client/src/firebase_auth_client.dart 107:45 FirebaseAuthClient.signInWithGoogle
===== asynchronous gap ===========================
dart:async _CustomZone.registerUnaryCallback
package:firebase_auth_client/src/firebase_auth_client.dart 97:26 FirebaseAuthClient.signInWithGoogle
test/src/firebase_auth_client_test.dart 101:30 main.<fn>.<fn>.<fn>
</code></pre>
<p>My test script look like this</p>
<pre class="lang-dart prettyprint-override"><code>class FakeUserCredential extends Fake implements UserCredential {}
class MockFirebaseAuth extends Mock implements FirebaseAuth {}
class MockGoogleSignIn extends Mock implements GoogleSignIn {}
class MockGoogleSignInAccount extends Mock implements GoogleSignInAccount {}
class MockGoogleSignInAuthentication extends Mock
implements GoogleSignInAuthentication {}
class MockOAuthCredential extends Mock implements OAuthCredential {}
void main() {
late FirebaseAuth firebaseAuth;
late UserCredential userCredential;
late FirebaseAuthClient firebaseAuthClient;
late GoogleSignIn googleSignIn;
late GoogleSignInAccount googleSignInAccount;
late GoogleSignInAuthentication googleSignInAuthentication;
late OAuthCredential oAuthCredential;
setUp(() {
firebaseAuth = MockFirebaseAuth();
userCredential = FakeUserCredential();
googleSignIn = MockGoogleSignIn();
googleSignInAccount = MockGoogleSignInAccount();
oAuthCredential = MockOAuthCredential();
googleSignInAuthentication = MockGoogleSignInAuthentication();
firebaseAuthClient = FirebaseAuthClient(
auth: firebaseAuth,
googleSignIn: googleSignIn,
);
});
group('FirebaseAuthClient', () {
// passing tests omitted...
group('SignIn', () {
// passing tests omitted...
test('with google completes', () async {
when(() => googleSignIn.signIn()).thenAnswer(
(_) async => googleSignInAccount,
);
when(() => googleSignInAccount.authentication).thenAnswer(
(_) async => googleSignInAuthentication,
);
when(
() => firebaseAuth.signInWithCredential(oAuthCredential),
).thenAnswer((_) async => userCredential);
expect(
firebaseAuthClient.signInWithGoogle(),
completes,
);
});
// passing tests omitted...
});
// passing tests omitted...
});
}
</code></pre>
<p>And this is the package I wrote.</p>
<pre class="lang-dart prettyprint-override"><code>import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
/// {@template firebase_auth_client_exception}
/// Abstract class to handle the firebase auth client exceptions.
/// {@endtemplate}
abstract class FirebaseAuthClientException implements Exception {
/// {@macro firebase_auth_client_exception}
const FirebaseAuthClientException(this.error);
/// The error which was caught.
final Object error;
}
/// {@template firebase_sign_in_failure}
/// Thrown during the sign in process if a failure occurs.
/// {@endtemplate}
class FirebaseSignInFailure extends FirebaseAuthClientException {
/// {@macro firebase_sign_in_failure}
const FirebaseSignInFailure(super.error);
/// Construct error messages from the given code.
factory FirebaseSignInFailure.fromCode(String code) {
switch (code) {
case 'invalid-email':
return const FirebaseSignInFailure(
'Email address is invalid.',
);
case 'user-disabled':
return const FirebaseSignInFailure(
'Your account is disabled.',
);
case 'user-not-found':
return const FirebaseSignInFailure(
'Unable to find your account.',
);
case 'wrong-password':
return const FirebaseSignInFailure(
'You have entered the wrong password.',
);
default:
return const FirebaseSignInFailure(
'An unknown error occurred.',
);
}
}
@override
String toString() => error.toString();
}
/// {@template firebase_sign_out_failure}
/// Thrown during the sign out process if a failure occurs.
/// {@endtemplate}
class FirebaseSignOutFailure extends FirebaseAuthClientException {
/// {@macro firebase_sign_out_failure}
const FirebaseSignOutFailure(super.error);
}
/// {@template firebase_auth_client}
/// Firebase auth client
/// {@endtemplate}
class FirebaseAuthClient {
/// {@macro firebase_auth_client}
const FirebaseAuthClient({
required FirebaseAuth auth,
required GoogleSignIn googleSignIn,
}) : _auth = auth,
_googleSignIn = googleSignIn;
final FirebaseAuth _auth;
final GoogleSignIn _googleSignIn;
// unrelated methods omitted...
/// Sign the user in using Google auth provider.
Future<UserCredential> signInWithGoogle() async {
try {
final googleUser = await _googleSignIn.signIn();
final googleAuth = await googleUser?.authentication;
if (googleAuth == null) {
Error.throwWithStackTrace(
const FirebaseSignInFailure('Sign In Cancelled.'),
StackTrace.current,
);
}
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
return await _auth.signInWithCredential(credential);
} on FirebaseException catch (error, stackTrace) {
Error.throwWithStackTrace(
FirebaseSignInFailure.fromCode(error.code),
stackTrace,
);
} catch (error, stackTrace) {
Error.throwWithStackTrace(FirebaseSignInFailure(error), stackTrace);
}
}
// unrelated methods omitted...
}
</code></pre>
<p>I once tried to override the properties of the <code>MockGoogleSignInAuthentication</code> like this, but it doesn't work.</p>
<pre class="lang-dart prettyprint-override"><code>class MockGoogleSignInAuthentication extends Mock
implements GoogleSignInAuthentication {
@override
String? get idToken => 'fakeId';
@override
String? get accessToken => 'fakeToken';
}
</code></pre>
<p>Can somebody please point me to the right direction for this?
Thanks in advance!</p>
|
[
{
"answer_id": 74467716,
"author": "HimanshuSinha-msft",
"author_id": 11137679,
"author_profile": "https://Stackoverflow.com/users/11137679",
"pm_score": 0,
"selected": false,
"text": "use [your DatabaseName] \nGO \ndrop EXTERNAL table schemaname.tablename\n"
},
{
"answer_id": 74528726,
"author": "ShaikMaheer-MSFT",
"author_id": 16161919,
"author_profile": "https://Stackoverflow.com/users/16161919",
"pm_score": 2,
"selected": true,
"text": "DROP TABLE table_name"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11080170/"
] |
74,463,259
|
<p>I am making a file manager app in android studio, everything seems to work but when I open the app in the emulator it closes and says: "App keeps stopping".
The logcat is giving an error like this:</p>
<pre><code>Caused by: java.lang.NullPointerException
at java.io.File.<init>(File.java:283)
at com.roboproffa.filemanager.FileListActivity.onCreate(FileListActivity.java:33)
at android.app.Activity.performCreate(Activity.java:8290)
at android.app.Activity.performCreate(Activity.java:8269)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1384)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3657)
</code></pre>
<p>I think the error is on line 32 or 33 of this code:</p>
<pre class="lang-java prettyprint-override"><code>package com.roboproffa.filemanager;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
public class FileListActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_list);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
TextView noFiles = (TextView) findViewById(R.id.noFiles);
String FilePath = getIntent().getStringExtra("path");
File root;
root = new File(FilePath);
File[] filesAndFolders = root.listFiles();
if (filesAndFolders == null || filesAndFolders.length == 0) {
noFiles.setVisibility(View.VISIBLE);
return;
}
noFiles.setVisibility(View.INVISIBLE);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new MyAdapter(getApplicationContext(), filesAndFolders));
if(checkPermission()) {
//permission allowed
Intent intent = new Intent(FileListActivity.this, FileListActivity.class);
String path = Environment.getExternalStorageDirectory().getPath();
intent.putExtra("path", path);
startActivity(intent);
}else {
//permission not allowed
requestPermission();
}
}
//permission to access
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(FileListActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(result == PackageManager.PERMISSION_GRANTED){
return true;
}else{
return false;
}
}
private void requestPermission() {
if(ActivityCompat.shouldShowRequestPermissionRationale(FileListActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(FileListActivity.this, "Storage permission is required, please allow in settings", Toast.LENGTH_SHORT).show();
}
ActivityCompat.requestPermissions(FileListActivity.this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 111);
}
}
</code></pre>
<p>can someone please help, I googled it but I haven't found the solution.</p>
|
[
{
"answer_id": 74467716,
"author": "HimanshuSinha-msft",
"author_id": 11137679,
"author_profile": "https://Stackoverflow.com/users/11137679",
"pm_score": 0,
"selected": false,
"text": "use [your DatabaseName] \nGO \ndrop EXTERNAL table schemaname.tablename\n"
},
{
"answer_id": 74528726,
"author": "ShaikMaheer-MSFT",
"author_id": 16161919,
"author_profile": "https://Stackoverflow.com/users/16161919",
"pm_score": 2,
"selected": true,
"text": "DROP TABLE table_name"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20512332/"
] |
74,463,322
|
<p>Why output of below C code gives number when int datatype value is assigned as character</p>
<pre><code>#include<stdio.h>
int main()
{
int i= '5';
printf("%d",i);
return 0;
}
</code></pre>
<p>How its output is 53</p>
|
[
{
"answer_id": 74463409,
"author": "abelenky",
"author_id": 34824,
"author_profile": "https://Stackoverflow.com/users/34824",
"pm_score": 1,
"selected": false,
"text": "i = '5';\n"
},
{
"answer_id": 74463437,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 2,
"selected": false,
"text": "char"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20521563/"
] |
74,463,342
|
<p>Please I would like to have unique black lines for my 2D contour.</p>
<pre><code>
set terminal png size 800,800 font 'Times New Roman, 12'
set output 'TH1.png'
set view map
set pm3d map
unset surface
set cont base
set cntrparam levels 50
set isosamples 10
unset key
set xrange[0:180]
set yrange[0:180]
set xlabel '{/Symbol q}'
set ylabel '{/Symbol q}''
set palette rgb 33,13,10
splot 'TH1TH2.dat' w ima, 'TH1TH2.dat' w l lt -4 lw 1.6
</code></pre>
<p>For values great than 2000 I want a red contour.
Can someone help me?
Here is my 2D cut<a href="https://i.stack.imgur.com/Z9tiY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z9tiY.png" alt="enter image description here" /></a> But I would like to have only the black lines.
<a href="https://files.fm/u/apsq8ejmb" rel="nofollow noreferrer">link for the data</a></p>
|
[
{
"answer_id": 74463409,
"author": "abelenky",
"author_id": 34824,
"author_profile": "https://Stackoverflow.com/users/34824",
"pm_score": 1,
"selected": false,
"text": "i = '5';\n"
},
{
"answer_id": 74463437,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 2,
"selected": false,
"text": "char"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14008907/"
] |
74,463,353
|
<p>Is it possible to emplace some void* pointer into variant with a runtime generated index.</p>
<p>Can this nice solution (from here <a href="https://stackoverflow.com/a/69674233">link</a>), be updated to get index and pointer to emplace?</p>
<pre><code>#include <variant>
template <typename... Ts, std::size_t... Is>
void next(std::variant<Ts...>& v, std::index_sequence<Is...>)
{
using Func = void (*)(std::variant<Ts...>&);
Func funcs[] = {
+[](std::variant<Ts...>& v){ v.template emplace<(Is + 1) % sizeof...(Is)>(); }...
};
funcs[v.index()](v);
}
template <typename... Ts>
void next(std::variant<Ts...>& v)
{
next(v, std::make_index_sequence<sizeof...(Ts)>());
}
</code></pre>
<p>It is possible to get the required data type, but don't think it helps anyway</p>
<pre><code> Func funcs[] = {
[](MessageTypesVariant& v) {
auto y = std::get<(Is)>(v);
auto z = std::forward<decltype(y)>(y);
v.template emplace<(Is)>(); }...
};
</code></pre>
|
[
{
"answer_id": 74463409,
"author": "abelenky",
"author_id": 34824,
"author_profile": "https://Stackoverflow.com/users/34824",
"pm_score": 1,
"selected": false,
"text": "i = '5';\n"
},
{
"answer_id": 74463437,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 2,
"selected": false,
"text": "char"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20521411/"
] |
74,463,388
|
<p>I have created a custom function to create custom username in a class Inheriting DefaultSocialAccountAdapter. The code is as follows.</p>
<pre><code>def _build_username(self,data):
from allauth.utils import generate_unique_username
if(not data.get('username')):
first_name=data.get('first_name','').lower()
last_name=data.get('last_name','').lower()
suggested_username = (f"{first_name}{last_name}",)
username = generate_unique_username(suggested_username)
return username
</code></pre>
<p>But it throws lower() was called on None</p>
<p>I was trying to convert the name to lowercase because that is how our database supports usernames. This happens when i try to perform google login authentication method.</p>
|
[
{
"answer_id": 74463435,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 2,
"selected": false,
"text": "'first_name'"
},
{
"answer_id": 74463609,
"author": "josu_marty",
"author_id": 10265854,
"author_profile": "https://Stackoverflow.com/users/10265854",
"pm_score": 3,
"selected": true,
"text": "def _build_username(self,data):\n from allauth.utils import generate_unique_username\n if(not data.get('username')):\n first_name=data.get('first_name','')\n last_name=data.get('last_name','')\n l=[]\n if(first_name):\n l.append(first_name.lower().strip())\n else:\n l.append('')\n if(last_name):\n l.append(last_name.lower().strip())\n else:\n l.append('')\n suggested_username = (f\"{l[0]}{l[1]}\",)\n username = generate_unique_username(suggested_username)\n return username\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14612843/"
] |
74,463,475
|
<p>This seems like a really basic question but I can't find a solution that will do what I want for all columns of a dataframe.</p>
<p>I have a dataframe:</p>
<pre><code>df = data.frame(cats = c("A", "B", "C", NA, NA), dogs = c(-99, "F", NA, -99, "H"))
</code></pre>
<p>Where I want to count the number of times NA occurs within each column. I also want to count the number of times -99 occurs within each column. I am able to use summarise_all to count the number of NAs per column.</p>
<pre><code>df %>% summarise_all(~ sum(is.na(.)))
</code></pre>
<p>Which produces the desired result:</p>
<pre><code> cats dogs
2 1
</code></pre>
<p>But I can't figure out how to adapt this to count the number of times -99 appears per column. I've tried the following:</p>
<pre><code>df %>% summarise_all(~ sum(-99))
</code></pre>
<p>Which produces this result:</p>
<pre><code> cats dogs
-99 -99
</code></pre>
<p>This result shows -99 for each column, even though it never occurs within cats, and it doesn't produce the number of times -99 occurs. There must be an easy way to do this? Thanks for any help!</p>
|
[
{
"answer_id": 74463435,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 2,
"selected": false,
"text": "'first_name'"
},
{
"answer_id": 74463609,
"author": "josu_marty",
"author_id": 10265854,
"author_profile": "https://Stackoverflow.com/users/10265854",
"pm_score": 3,
"selected": true,
"text": "def _build_username(self,data):\n from allauth.utils import generate_unique_username\n if(not data.get('username')):\n first_name=data.get('first_name','')\n last_name=data.get('last_name','')\n l=[]\n if(first_name):\n l.append(first_name.lower().strip())\n else:\n l.append('')\n if(last_name):\n l.append(last_name.lower().strip())\n else:\n l.append('')\n suggested_username = (f\"{l[0]}{l[1]}\",)\n username = generate_unique_username(suggested_username)\n return username\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7128414/"
] |
74,463,479
|
<p>I want to change the label color in my interface when the input is disabled with Typescript or CSS</p>
<p>Here is my interface :</p>
<p><a href="https://i.stack.imgur.com/KybCP.png" rel="nofollow noreferrer">my interface</a></p>
<p>Here is my code :</p>
<pre><code><tr>
<td className="name">Critère d'agrégation</td>
<td className="value column-2">
{aggregationDomain.map(codedValue =>
<label >
<input type="radio" name="AggregationSelection"
value={codedValue.code} checked={props.reportConfig.aggregation ===
codedValue.code} onChange={updateAggregation} disabled=
{!config?.aggregationEnabled.includes(codedValue.code)}
/>
{codedValue.name}
</label>
)}
</td>
</tr>
</code></pre>
<p>I'm working with React (typescript), if someone has the answer I'd appreciate it! thnks</p>
|
[
{
"answer_id": 74463435,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 2,
"selected": false,
"text": "'first_name'"
},
{
"answer_id": 74463609,
"author": "josu_marty",
"author_id": 10265854,
"author_profile": "https://Stackoverflow.com/users/10265854",
"pm_score": 3,
"selected": true,
"text": "def _build_username(self,data):\n from allauth.utils import generate_unique_username\n if(not data.get('username')):\n first_name=data.get('first_name','')\n last_name=data.get('last_name','')\n l=[]\n if(first_name):\n l.append(first_name.lower().strip())\n else:\n l.append('')\n if(last_name):\n l.append(last_name.lower().strip())\n else:\n l.append('')\n suggested_username = (f\"{l[0]}{l[1]}\",)\n username = generate_unique_username(suggested_username)\n return username\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16230569/"
] |
74,463,480
|
<p>What is the best way to apply condition on each element in a series, and store the result on a new [0, 1]^n series?</p>
<p>For example:</p>
<p>Apply condition : >= 10 on series : [4, 10, 100, 5]</p>
<p>will return:
[0, 1, 1, 0]</p>
|
[
{
"answer_id": 74463435,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 2,
"selected": false,
"text": "'first_name'"
},
{
"answer_id": 74463609,
"author": "josu_marty",
"author_id": 10265854,
"author_profile": "https://Stackoverflow.com/users/10265854",
"pm_score": 3,
"selected": true,
"text": "def _build_username(self,data):\n from allauth.utils import generate_unique_username\n if(not data.get('username')):\n first_name=data.get('first_name','')\n last_name=data.get('last_name','')\n l=[]\n if(first_name):\n l.append(first_name.lower().strip())\n else:\n l.append('')\n if(last_name):\n l.append(last_name.lower().strip())\n else:\n l.append('')\n suggested_username = (f\"{l[0]}{l[1]}\",)\n username = generate_unique_username(suggested_username)\n return username\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9652134/"
] |
74,463,487
|
<p>I have a dataframe <code>df</code> such that <code>df.columns</code> returns</p>
<pre><code> MultiIndex([( 'a', 's1', 'm/s'),
( 'a', 's2', '%'),
( 'a', 's3', '°C'),
('b', 'z3', '°C'),
('b', 'z4', 'kPa')],
names=['kind', 'names', 'units'])
</code></pre>
<p>How to change ONLY the column name <code>('b', 'z3', '°C')</code> into <code>('b', 'z3', 'degC')</code>?</p>
<p>At the moment I am trying the following</p>
<pre><code> old_cols_name = ('b', 'z3', '°C')
new_cols_name = list(old_cols_name)
new_cols_name[2] = "degC"
df = df_temp.rename(
columns={old_cols_name: new_cols_name},
)
</code></pre>
<p>But it does not work in the sense that the columns names of <code>df</code> are left unchanged.</p>
<p>EDIT: Question slightly changed to add more generality.</p>
|
[
{
"answer_id": 74463435,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 2,
"selected": false,
"text": "'first_name'"
},
{
"answer_id": 74463609,
"author": "josu_marty",
"author_id": 10265854,
"author_profile": "https://Stackoverflow.com/users/10265854",
"pm_score": 3,
"selected": true,
"text": "def _build_username(self,data):\n from allauth.utils import generate_unique_username\n if(not data.get('username')):\n first_name=data.get('first_name','')\n last_name=data.get('last_name','')\n l=[]\n if(first_name):\n l.append(first_name.lower().strip())\n else:\n l.append('')\n if(last_name):\n l.append(last_name.lower().strip())\n else:\n l.append('')\n suggested_username = (f\"{l[0]}{l[1]}\",)\n username = generate_unique_username(suggested_username)\n return username\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2562058/"
] |
74,463,517
|
<p>I am trying to create a trigger that reads from table 2 and updates a column in table 1.
I tried with this method but an exception occurred: ORA-04091:table table1 is mutating .</p>
<pre><code>CREATE OR REPLACE TRIGGER "TRG1"
AFTER INSERT OR UPDATE ON table1
FOR EACH ROW
BEGIN
UPDATE table1 SET name =(SELECT name FROM table2
WHERE table1.id = table2.id);
END;
</code></pre>
|
[
{
"answer_id": 74463435,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 2,
"selected": false,
"text": "'first_name'"
},
{
"answer_id": 74463609,
"author": "josu_marty",
"author_id": 10265854,
"author_profile": "https://Stackoverflow.com/users/10265854",
"pm_score": 3,
"selected": true,
"text": "def _build_username(self,data):\n from allauth.utils import generate_unique_username\n if(not data.get('username')):\n first_name=data.get('first_name','')\n last_name=data.get('last_name','')\n l=[]\n if(first_name):\n l.append(first_name.lower().strip())\n else:\n l.append('')\n if(last_name):\n l.append(last_name.lower().strip())\n else:\n l.append('')\n suggested_username = (f\"{l[0]}{l[1]}\",)\n username = generate_unique_username(suggested_username)\n return username\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5773661/"
] |
74,463,522
|
<p><a href="https://i.stack.imgur.com/mKmIW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mKmIW.png" alt="Here is what my website looks like:" /></a>
As you can see, there is a white background covering the background image. I tried adding <code>background-color: transparent;</code> to the text, but nothing happened. How can I get rid of the white background, but still have the text over the background image?</p>
<p>I am using Bootstrap 5.</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-css lang-css prettyprint-override"><code>* {
padding: 0;
margin: 0;
font-family: "Roboto", sans-serif;
}
html {
background: url(http://ndquiz.epizy.com/img/worldPersonalProject.png) no-repeat center fixed;
background-size: cover;
}
.btn-select {
background-color: #008cba;
border-radius: 10px;
text-align: center;
}
.main {
margin-top: 100px;
background-color: transparent !important;
}
.big {
font-size: 60px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<main class="text-justify text-center main">
<h1 class="big">Flag Quiz Game</h1>
<div>
<h2>Select Gamemode</h2>
<a href="">Learn</a>
<a href="">All (254)</a><br />
<a href="">All Sovereign (195)</a><br />
<a href="">Easy (15)</a><br />
<a href="">Medium (30)</a><br />
<a href="">Hard (60)</a><br />
<a href="">Africa (55)</a><br />
<a href="">Americas (35)</a><br />
<a href="">Asia (51)</a><br />
<a href="">Europe (50)</a><br />
<a href="">Oceania (14)</a><br />
</div>
</main>
<footer>
Flags from <a href="https://flagpedia.net/" target="_blank">Flagpedia</a>
</footer></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74463435,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 2,
"selected": false,
"text": "'first_name'"
},
{
"answer_id": 74463609,
"author": "josu_marty",
"author_id": 10265854,
"author_profile": "https://Stackoverflow.com/users/10265854",
"pm_score": 3,
"selected": true,
"text": "def _build_username(self,data):\n from allauth.utils import generate_unique_username\n if(not data.get('username')):\n first_name=data.get('first_name','')\n last_name=data.get('last_name','')\n l=[]\n if(first_name):\n l.append(first_name.lower().strip())\n else:\n l.append('')\n if(last_name):\n l.append(last_name.lower().strip())\n else:\n l.append('')\n suggested_username = (f\"{l[0]}{l[1]}\",)\n username = generate_unique_username(suggested_username)\n return username\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18884489/"
] |
74,463,597
|
<p>The terra package has the aggregate function that allows to create a new SpatRaster with a lower resolution (larger cells) but needs the fact parameter.</p>
<p>When converting many rasters, fact needs to be calculated each time, is there a way to pass the fact parameter based on the target resolution of another raster? Other functions take an existing raster as input, such as function(r1,r2)</p>
<pre><code>library(terra)
r1 <- rast(ncol=10,nrow=10)
r2 <- rast(ncol=4,nrow=4)
values(r1) <- runif(ncell(r1))
values(r2) <- runif(ncell(r2))
</code></pre>
<p>I have tried</p>
<pre><code>r3 = aggregate(r1,fact=res(r1)/res(r2))
</code></pre>
<blockquote>
<p>Error: [aggregate] values in argument 'fact' should be > 0</p>
</blockquote>
|
[
{
"answer_id": 74463435,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 2,
"selected": false,
"text": "'first_name'"
},
{
"answer_id": 74463609,
"author": "josu_marty",
"author_id": 10265854,
"author_profile": "https://Stackoverflow.com/users/10265854",
"pm_score": 3,
"selected": true,
"text": "def _build_username(self,data):\n from allauth.utils import generate_unique_username\n if(not data.get('username')):\n first_name=data.get('first_name','')\n last_name=data.get('last_name','')\n l=[]\n if(first_name):\n l.append(first_name.lower().strip())\n else:\n l.append('')\n if(last_name):\n l.append(last_name.lower().strip())\n else:\n l.append('')\n suggested_username = (f\"{l[0]}{l[1]}\",)\n username = generate_unique_username(suggested_username)\n return username\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2319308/"
] |
74,463,599
|
<p>I was asked to implement a queue using a linked list without a header node. My teacher gave us this snippet for referring to the enqueue function. I'm familiar with how to use queue operations. But I keep getting confused when double-pointers are used along with functions. I'm not sure which variable the double-pointer points to in most cases. I would like to know what Node ** list means.</p>
<p>Any help or explanation is appreciated</p>
<p>Here is the snippet that I referred</p>
<pre class="lang-c prettyprint-override"><code>void insertNode(Node * prev,int x) {
Node * new = (Node *) malloc(sizeof(Node));
new->val = x;
new->next = prev->next;
prev->next = new;
}
void enqueue(Node ** list, int x) {
Node * new = (Node *) malloc(sizeof(Node));
if (isEmpty(*list)) {
*list = new;
(*list)->val = x;
(*list)->next = NULL;
}
else {
new = *list;
while (new->next != NULL)
new = new->next;
insertNode(new,x);
}
}
</code></pre>
|
[
{
"answer_id": 74463435,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 2,
"selected": false,
"text": "'first_name'"
},
{
"answer_id": 74463609,
"author": "josu_marty",
"author_id": 10265854,
"author_profile": "https://Stackoverflow.com/users/10265854",
"pm_score": 3,
"selected": true,
"text": "def _build_username(self,data):\n from allauth.utils import generate_unique_username\n if(not data.get('username')):\n first_name=data.get('first_name','')\n last_name=data.get('last_name','')\n l=[]\n if(first_name):\n l.append(first_name.lower().strip())\n else:\n l.append('')\n if(last_name):\n l.append(last_name.lower().strip())\n else:\n l.append('')\n suggested_username = (f\"{l[0]}{l[1]}\",)\n username = generate_unique_username(suggested_username)\n return username\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16918445/"
] |
74,463,618
|
<p>I have this json file and i have tried to filter the data keep only the user:'11111', but its not working.</p>
<pre><code>var data= [
{
id: {
server: 'xxxxx',
user: '123456',
_serialized: '64566'
},
name: 'Doe',
isCalled: false,
isReceived: false,
unreadCount: 1,
},
{
id: {
server: 'xxxxx',
user: '123456',
_serialized: '64566'
},
name: 'Doe',
isCalled: false,
isReceived: false,
unreadCount: 1,
},
{
id: {
server: 'xxxxx',
user: '123456',
_serialized: '64566'
},
name: 'Doe',
isCalled: false,
isReceived: false,
unreadCount: 1,
}
]
</code></pre>
<p>i tried</p>
<pre><code> const seun = sex.map(({ id, ...rest }) => rest);
</code></pre>
<p>but did not work</p>
<p><strong>desired result:</strong></p>
<pre><code>var data= [
{
user: '123456'
},
{
user: '123456',
},
{
user: '123456',
},
}
]
</code></pre>
|
[
{
"answer_id": 74463689,
"author": "Elie",
"author_id": 17987026,
"author_profile": "https://Stackoverflow.com/users/17987026",
"pm_score": 1,
"selected": false,
"text": "array.map( x => f(x) )"
},
{
"answer_id": 74463789,
"author": "Yosvel Quintero",
"author_id": 1932552,
"author_profile": "https://Stackoverflow.com/users/1932552",
"pm_score": 1,
"selected": false,
"text": "const data = [{id: {server: 'xxxxx',user: '123456',_serialized: '64566',},name: 'Doe',isCalled: false,isReceived: false,unreadCount: 1,},{id: {server: 'xxxxx',user: '123456',_serialized: '64566',},name: 'Doe',isCalled: false,isReceived: false,unreadCount: 1,},{id: {server: 'xxxxx',user: '123456',_serialized: '64566',},name: 'Doe',isCalled: false,isReceived: false,unreadCount: 1}]\n\nconst result = data.map(({ id: { user } }) => ({ user }))\n\nconsole.log(result)"
},
{
"answer_id": 74464122,
"author": "PeterKA",
"author_id": 3558931,
"author_profile": "https://Stackoverflow.com/users/3558931",
"pm_score": 0,
"selected": false,
"text": "Array#map"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13657813/"
] |
74,463,644
|
<p>I have a method for handling an update on this object. In this method I want to accept any field value that the object has, such as name, age, weight, eyeColor etc. If that field exists within that object, I'd like to be able to update the object dynamically for any field they pass in.</p>
<p>I am currently doing it incorrectly I believe with the spread operator while trying to update one field in the object. There is an error that fieldName does not exist within myObject. Does anyone know how to do this dynamically without need for a long switch statement checking each of the fields against fieldName passed in? In previous attempts tweaking with this I have successfully added a new field to the object named "fieldName" which is also not what I wanted.</p>
<p>If anyone has any ideas, that would be so helpful, thank you!</p>
<pre><code>let myObject = {
name: 'John',
lastName: 'Smith',
age: 26,
weight: 200,
eyeColor: 'blue',
hairColor: 'blonde'
};
const handleUpdate = (fieldName: string, fieldValue: string | number) => {
if (fieldName in myObject) {
myObject = {...myObject, fieldName: fieldValue};
}
}
handleUpdate('name', 'Jack'); // Want this call to update the name of 'John' to 'Jack'
</code></pre>
|
[
{
"answer_id": 74463689,
"author": "Elie",
"author_id": 17987026,
"author_profile": "https://Stackoverflow.com/users/17987026",
"pm_score": 1,
"selected": false,
"text": "array.map( x => f(x) )"
},
{
"answer_id": 74463789,
"author": "Yosvel Quintero",
"author_id": 1932552,
"author_profile": "https://Stackoverflow.com/users/1932552",
"pm_score": 1,
"selected": false,
"text": "const data = [{id: {server: 'xxxxx',user: '123456',_serialized: '64566',},name: 'Doe',isCalled: false,isReceived: false,unreadCount: 1,},{id: {server: 'xxxxx',user: '123456',_serialized: '64566',},name: 'Doe',isCalled: false,isReceived: false,unreadCount: 1,},{id: {server: 'xxxxx',user: '123456',_serialized: '64566',},name: 'Doe',isCalled: false,isReceived: false,unreadCount: 1}]\n\nconst result = data.map(({ id: { user } }) => ({ user }))\n\nconsole.log(result)"
},
{
"answer_id": 74464122,
"author": "PeterKA",
"author_id": 3558931,
"author_profile": "https://Stackoverflow.com/users/3558931",
"pm_score": 0,
"selected": false,
"text": "Array#map"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20514758/"
] |
74,463,657
|
<p>The thing is have a lot of these TextEditingControllers in many screens, Login, Forms, etc.
Do I have to implement a dispose method to each of these controllers do to memory leak or it doesn't matter?</p>
<p>Thank you!!</p>
<p>I tried in some screens but I don't know if is recommended.</p>
|
[
{
"answer_id": 74463689,
"author": "Elie",
"author_id": 17987026,
"author_profile": "https://Stackoverflow.com/users/17987026",
"pm_score": 1,
"selected": false,
"text": "array.map( x => f(x) )"
},
{
"answer_id": 74463789,
"author": "Yosvel Quintero",
"author_id": 1932552,
"author_profile": "https://Stackoverflow.com/users/1932552",
"pm_score": 1,
"selected": false,
"text": "const data = [{id: {server: 'xxxxx',user: '123456',_serialized: '64566',},name: 'Doe',isCalled: false,isReceived: false,unreadCount: 1,},{id: {server: 'xxxxx',user: '123456',_serialized: '64566',},name: 'Doe',isCalled: false,isReceived: false,unreadCount: 1,},{id: {server: 'xxxxx',user: '123456',_serialized: '64566',},name: 'Doe',isCalled: false,isReceived: false,unreadCount: 1}]\n\nconst result = data.map(({ id: { user } }) => ({ user }))\n\nconsole.log(result)"
},
{
"answer_id": 74464122,
"author": "PeterKA",
"author_id": 3558931,
"author_profile": "https://Stackoverflow.com/users/3558931",
"pm_score": 0,
"selected": false,
"text": "Array#map"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19997747/"
] |
74,463,690
|
<p>There's a ton of threads there already I know but I still can't get it to work. I'm building an embed with a button. The embed appears using command $test. The error happens when I trigger the embed for the second time (2nd $test) and click the button after clicking the button on the first trigger.</p>
<p>This flow should work but the error "Interaction has already been acknowledged" triggers.</p>
<p><strong>Steps:</strong></p>
<ol>
<li>Type $test to show the embed.</li>
<li>User clicks "Click me." button on the embed.</li>
<li>The embed updates to embed2 confirming the click on the button.</li>
<li>Type $test again to show the embed.</li>
<li>User clicks "Click me." button on the embed.</li>
</ol>
<p><strong>Result:</strong> Interaction has already been acknowledged.</p>
<p><strong>Expected Result:</strong> The 2nd embed should be totally new. It should not remember my first interaction on the 1st embed.</p>
<p>Should I use .reply() instead of .update()? Does that matter?</p>
<p>I read a post saying this:</p>
<blockquote>
<p>Interaction has already been acknowledged happens when you try to
reply to the interaction that you already replied, and you can fix it
by using .editReply() after you .reply() the interaction.</p>
</blockquote>
<p>Here's the code:</p>
<pre><code>client.on("messageCreate", (message) => {
if (command === "test") {
const button = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId("button1")
.setLabel("Click me.")
.setStyle(ButtonStyle.Secondary)
);
const embed = new EmbedBuilder()
.setColor("#5A5A5A")
.setTitle("Embed")
.setDescription("Did you receive this message? Click button if you did.")
const embed2 = new EmbedBuilder()
.setColor("#5A5A5A")
.setTitle("Confirmation Embed")
.setDescription("Thanks for confirming!")
message.channel.send({embeds:[embed], components:[button]});
const collector = message.channel.createMessageComponentCollector();
collector.on("collect", (i) => {
if(i.customId === "button1") {
i.update({embeds: [embed2], components:[]});
}
})
});
</code></pre>
|
[
{
"answer_id": 74463689,
"author": "Elie",
"author_id": 17987026,
"author_profile": "https://Stackoverflow.com/users/17987026",
"pm_score": 1,
"selected": false,
"text": "array.map( x => f(x) )"
},
{
"answer_id": 74463789,
"author": "Yosvel Quintero",
"author_id": 1932552,
"author_profile": "https://Stackoverflow.com/users/1932552",
"pm_score": 1,
"selected": false,
"text": "const data = [{id: {server: 'xxxxx',user: '123456',_serialized: '64566',},name: 'Doe',isCalled: false,isReceived: false,unreadCount: 1,},{id: {server: 'xxxxx',user: '123456',_serialized: '64566',},name: 'Doe',isCalled: false,isReceived: false,unreadCount: 1,},{id: {server: 'xxxxx',user: '123456',_serialized: '64566',},name: 'Doe',isCalled: false,isReceived: false,unreadCount: 1}]\n\nconst result = data.map(({ id: { user } }) => ({ user }))\n\nconsole.log(result)"
},
{
"answer_id": 74464122,
"author": "PeterKA",
"author_id": 3558931,
"author_profile": "https://Stackoverflow.com/users/3558931",
"pm_score": 0,
"selected": false,
"text": "Array#map"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/874737/"
] |
74,463,713
|
<p>I'm trying to learn to react online and I understood everything except this line code</p>
<pre><code>const removeItem = (id) => {
let newPeople = people.filter((person) => person.id !== id);
setPeople(newPeople);
};
</code></pre>
<p>especially how <code>person.id !== id</code>removes the item from list and add to new list</p>
<p>here is the full code</p>
<pre><code>import React from 'react';
import { data } from '../../../data';
const UseStateArray = () => {
const [people, setPeople] = React.useState(data);
const removeItem = (id) => {
let newPeople = people.filter((person) => person.id !== id);
setPeople(newPeople);
};
return (
<>
{people.map((person) => {
const { id, name } = person;
return (
<div key={id} className='item'>
<h4>{name}</h4>
<button onClick={() => removeItem(id)}>remove</button>
</div>
);
})}
<button className='btn' onClick={() => setPeople([])}>
clear items
</button>
</>
);
};
export default UseStateArray;
</code></pre>
|
[
{
"answer_id": 74463817,
"author": "Kamran Davar",
"author_id": 12510464,
"author_profile": "https://Stackoverflow.com/users/12510464",
"pm_score": 1,
"selected": false,
"text": "person.id !== id"
},
{
"answer_id": 74463912,
"author": "Oscar Daniel Pérez Otero",
"author_id": 6204804,
"author_profile": "https://Stackoverflow.com/users/6204804",
"pm_score": 0,
"selected": false,
"text": "newPeople"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12146779/"
] |
74,463,717
|
<p>I'm currently working with:</p>
<ul>
<li>Micronaut 3.7.3</li>
<li>RabbitMQ 3.11.2</li>
<li>Spock</li>
<li>Groovy / Java 17</li>
</ul>
<p>I'm implementing a rabbitmq consumer for a simple demo project following the guidelines from micronaut project (<a href="https://micronaut-projects.github.io/micronaut-rabbitmq/3.1.0/guide/index.html" rel="nofollow noreferrer">https://micronaut-projects.github.io/micronaut-rabbitmq/3.1.0/guide/index.html</a>)</p>
<p>I'm trying to mock a service that is a dependency of my rabbitmq consumer.</p>
<p>I've tried this approach that does not seem to work:</p>
<pre><code>@MicronautTest
@Subject(SampleRequestConsumer)
class SampleRequestConsumerSpec extends Specification {
@Inject
ExternalWorkflowProducer externalWorkflowProducer
@Inject
SampleRequestConsumer sampleRequestConsumer
@Inject
SimpleService simpleService
@MockBean(SimpleService)
SimpleService simpleService() {
Mock(SimpleService)
}
def "It receives a sampleRequest message in the simple.request queue"() {
when:
externalWorkflowProducer.send(new SampleRequest(message: "Request1"))
then:
sleep(100)
1 * simpleService.handleSimpleRequest(_ as SampleRequest) >> { SampleRequest request ->
assert request.message != null
}
}
}
</code></pre>
<p>I get this error when running the integration test:</p>
<pre><code>Too few invocations for:
1 * simpleService.handleSimpleRequest(_ as SampleRequest) >> { SampleRequest request ->
assert request.message != null
} (0 invocations)
Unmatched invocations (ordered by similarity):
None
</code></pre>
<p>See full source code on GitHub: <a href="https://github.com/art-dambrine/micronaut-rabbitmq-spock-mocking/blob/test-with-mq/src/test/groovy/com/company/microproject/amqp/consumer/SampleRequestConsumerSpec.groovy" rel="nofollow noreferrer">https://github.com/art-dambrine/micronaut-rabbitmq-spock-mocking/blob/test-with-mq/src/test/groovy/com/company/microproject/amqp/consumer/SampleRequestConsumerSpec.groovy</a></p>
<p>Also notice that when I'm not reading from the queue and directly calling the method <code>sampleRequestConsumer.receive([message: "Request1"])</code>
mocking for the <code>simpleService</code> is working : <a href="https://github.com/art-dambrine/micronaut-rabbitmq-spock-mocking/blob/test-without-mq/src/test/groovy/com/company/microproject/amqp/consumer/SampleRequestConsumerSpec.groovy" rel="nofollow noreferrer">https://github.com/art-dambrine/micronaut-rabbitmq-spock-mocking/blob/test-without-mq/src/test/groovy/com/company/microproject/amqp/consumer/SampleRequestConsumerSpec.groovy</a></p>
<p>Thanks in advance for your insight</p>
<h2>IMPORTANT</h2>
<p>Please use the branch <code>test-with-mq</code>. The branch <code>test-without-mq</code>'s tests will succeed because it's not using rabbitMQ. This is an attempt to demonstrate that the issue lies in testing RabbitMQ consumers.</p>
|
[
{
"answer_id": 74463817,
"author": "Kamran Davar",
"author_id": 12510464,
"author_profile": "https://Stackoverflow.com/users/12510464",
"pm_score": 1,
"selected": false,
"text": "person.id !== id"
},
{
"answer_id": 74463912,
"author": "Oscar Daniel Pérez Otero",
"author_id": 6204804,
"author_profile": "https://Stackoverflow.com/users/6204804",
"pm_score": 0,
"selected": false,
"text": "newPeople"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20521129/"
] |
74,463,792
|
<p>I have a select option like this:</p>
<pre><code><label>Choose One:</label>
<select id="choose1">
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
<option value="val3">Value 3</option>
</select>
</code></pre>
<p>Then, in my project I can select the necessary option, in the case below, I selected the <code>val2</code> value.</p>
<pre><code>await page.select('#choose1', 'val2');
</code></pre>
<p>So, I'm trying to get the text of <code>val2</code> but in all the attempts the return is wrong.</p>
<p>I've tryed this, and it returned the textContent of the first option:</p>
<pre><code>const element = await page.$('#choose1 option');
const selected = await (await element.getProperty('textContent')).jsonValue();
</code></pre>
<p>If I use <code>await page.$('#choose1 option:selected')</code>, I get an error that is not a valid selector.</p>
<p>Can anyone help me?</p>
|
[
{
"answer_id": 74464162,
"author": "yeya",
"author_id": 3107689,
"author_profile": "https://Stackoverflow.com/users/3107689",
"pm_score": 0,
"selected": false,
"text": "val2"
},
{
"answer_id": 74465481,
"author": "ggorlen",
"author_id": 6243352,
"author_profile": "https://Stackoverflow.com/users/6243352",
"pm_score": 2,
"selected": true,
"text": ".find"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3990953/"
] |
74,463,813
|
<p>I'll divide this into three parts:</p>
<p>What I have:</p>
<p>I have two tables <code>Table1</code> and <code>Table2</code>.</p>
<p><strong>Table1</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ObjectName</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>Active</td>
</tr>
<tr>
<td>C</td>
<td>Active</td>
</tr>
</tbody>
</table>
</div>
<p><strong>Table2</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ParentObjectType</th>
<th>ChildObjectType</th>
</tr>
</thead>
<tbody>
<tr>
<td>X</td>
<td>A</td>
</tr>
<tr>
<td>Y</td>
<td>C</td>
</tr>
<tr>
<td>Z</td>
<td>A</td>
</tr>
<tr>
<td>M</td>
<td>C</td>
</tr>
</tbody>
</table>
</div>
<p>What I want:</p>
<p>I want to write a stored procedure that gives a result that looks something like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ObjectName</th>
<th>Status</th>
<th>ParentObjectName</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>Active</td>
<td>X, Z</td>
</tr>
<tr>
<td>C</td>
<td>Active</td>
<td>Y, M</td>
</tr>
</tbody>
</table>
</div>
<p>What I have tried: I tried using the <code>STUFF</code> function and I'm getting a weird result.</p>
<p>Here's the query:</p>
<pre><code>SELECT
ObjectName,
Status,
STUFF((SELECT '; ' + table2.ParentObjectType
FROM table1
INNER JOIN table2 ON table1.[ObjectName] = table2.[ChildObjectType]
FOR XML PATH('')), 1, 1, '') [ParentObjectName]
FROM
table1
</code></pre>
<p><strong>Output</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ObjectName</th>
<th>Status</th>
<th>ParentObjectName</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>Active</td>
<td>X, Z, Y, M</td>
</tr>
<tr>
<td>C</td>
<td>Active</td>
<td>X, Z, Y, M</td>
</tr>
</tbody>
</table>
</div>
<p>Any help here is highly appreciated as I'm light handed on SQL and this is driving me nuts!</p>
|
[
{
"answer_id": 74465236,
"author": "Anel Hodžić",
"author_id": 4018834,
"author_profile": "https://Stackoverflow.com/users/4018834",
"pm_score": 2,
"selected": true,
"text": "WHERE"
},
{
"answer_id": 74465393,
"author": "Sean Bloch",
"author_id": 20187370,
"author_profile": "https://Stackoverflow.com/users/20187370",
"pm_score": 0,
"selected": false,
"text": "FOR XML PATH"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2508346/"
] |
74,463,822
|
<p>I have a couple of tables that are joined:
Table A ([Id], [Name], [Active])
Table B ([Id], [Name], [A_Id])</p>
<p>I would like to insert into Table A first, then use the Id of the new row to insert into Table B.</p>
<pre><code>DECLARE @NEWID table(NewID Numeric(19, 0));
INSERT [dbo].[TableA] ([Name], [Active])
OUTPUT INSERTED.Id INTO @NEWID (NewID)
VALUES ('testtesttest', 1);
INSERT [dbo].[TableB] ([Name], [A_Id])
VALUES ('name for b', ??? @NEWID.NewID ???)
</code></pre>
<p>I can OUTPUT the id into a temporary table but how do I use this in the next insert statement?</p>
|
[
{
"answer_id": 74465236,
"author": "Anel Hodžić",
"author_id": 4018834,
"author_profile": "https://Stackoverflow.com/users/4018834",
"pm_score": 2,
"selected": true,
"text": "WHERE"
},
{
"answer_id": 74465393,
"author": "Sean Bloch",
"author_id": 20187370,
"author_profile": "https://Stackoverflow.com/users/20187370",
"pm_score": 0,
"selected": false,
"text": "FOR XML PATH"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1094553/"
] |
74,463,833
|
<p>I need to rotate table by 90,180,270 degrees and reset it to start at last option I must do it in switch but i have no idea how to do that because table must be in char. I found a lot of question about table in int but no one in char. I had this at this moment and no idea how to rotate it in char</p>
<pre><code>using System;
namespace Table.ConsoleApp
{
class Table
{
static void Main()
{
char[,] a = new char[6, 6]
{
{'#', '#', '#', '%', '%', '%'},
{'#', '#', '#', '%', '%', '%'},
{'#', '#', '#', '%', '%', '%'},
{'*', '*', '*', '+', '+', '+'},
{'*', '*', '*', '+', '+', '+'},
{'*', '*', '*', '+', '+', '+'},
};
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
{
Console.WriteLine("a[{0}, {1}] = {2}", i, j, a[i, j]);
}
}
}
}
}
</code></pre>
|
[
{
"answer_id": 74464228,
"author": "hossein sabziani",
"author_id": 4301195,
"author_profile": "https://Stackoverflow.com/users/4301195",
"pm_score": 2,
"selected": false,
"text": "char[,] a = new char[6, 6]\n {\n {'#', '#', '#', '%', '%', '%'},\n {'#', '#', '#', '%', '%', '%'},\n {'#', '#', '#', '%', '%', '%'},\n {'*', '*', '*', '+', '+', '+'},\n {'*', '*', '*', '+', '+', '+'},\n {'*', '*', '*', '+', '+', '+'},\n };\n Console.WriteLine(\"Rotate 90\");\n for (int i = 0; i < 6; i++)\n {\n for (int j = 0; j < 6; j++)\n {\n Console.Write(\" \" + a[5 - j, i]);\n }\n Console.WriteLine();\n }\n Console.WriteLine();\n Console.WriteLine(\"Rotate 180\");\n\n for (int i = 0; i < 6; i++)\n {\n for (int j = 0; j < 6; j++)\n {\n Console.Write(\" \"+ a[5-i, 5-j]);\n }\n Console.WriteLine();\n }\n Console.WriteLine();\n Console.WriteLine(\"Rotate 270\");\n for (int i = 0; i < 6; i++)\n {\n for (int j = 0; j < 6; j++)\n {\n Console.Write(\" \" + a[j, 5-i ]);\n }\n Console.WriteLine();\n }\n"
},
{
"answer_id": 74483815,
"author": "Flydog57",
"author_id": 4739488,
"author_profile": "https://Stackoverflow.com/users/4739488",
"pm_score": 0,
"selected": false,
"text": "char"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20512350/"
] |
74,463,840
|
<p>im trying to array.push in a for loop in my Typescript code:</p>
<pre><code>var rows = [
{
id: '1',
category: 'Snow',
value: 'Jon',
cheapSource: '35',
cheapPrice: '35',
amazonSource: '233'
}
];
var newRow = {
id: productName,
category: category,
value: _value.toString(),
cheapSource: merchantName,
cheapPrice: lowPrice,
amazonSource: suppData[k][2]
};
rows.push(...newRow);
export default function DataTable() {
const { user } = useUser();
return (
<div>
{user ? (
<div
style={{
height: 400,
width: '75%',
backgroundColor: 'white',
marginLeft: 'auto',
marginRight: 'auto',
marginTop: '50px',
marginBottom: '50px'
}}
>
<DataGrid
rows={rows}
columns={columns}
pageSize={5}
rowsPerPageOptions={[5]}
checkboxSelection
onRowClick={get5CatDataNoStockCheck}
/>
</div>
) : (
<div>
<SignIn />
</div>
)}
</div>
);
}
</code></pre>
<p>The problem im facing is that it always pushes the same row even if im changing is value just before?</p>
<p>PS: A simple array.push is not usable since the array is not "extensible"</p>
|
[
{
"answer_id": 74464228,
"author": "hossein sabziani",
"author_id": 4301195,
"author_profile": "https://Stackoverflow.com/users/4301195",
"pm_score": 2,
"selected": false,
"text": "char[,] a = new char[6, 6]\n {\n {'#', '#', '#', '%', '%', '%'},\n {'#', '#', '#', '%', '%', '%'},\n {'#', '#', '#', '%', '%', '%'},\n {'*', '*', '*', '+', '+', '+'},\n {'*', '*', '*', '+', '+', '+'},\n {'*', '*', '*', '+', '+', '+'},\n };\n Console.WriteLine(\"Rotate 90\");\n for (int i = 0; i < 6; i++)\n {\n for (int j = 0; j < 6; j++)\n {\n Console.Write(\" \" + a[5 - j, i]);\n }\n Console.WriteLine();\n }\n Console.WriteLine();\n Console.WriteLine(\"Rotate 180\");\n\n for (int i = 0; i < 6; i++)\n {\n for (int j = 0; j < 6; j++)\n {\n Console.Write(\" \"+ a[5-i, 5-j]);\n }\n Console.WriteLine();\n }\n Console.WriteLine();\n Console.WriteLine(\"Rotate 270\");\n for (int i = 0; i < 6; i++)\n {\n for (int j = 0; j < 6; j++)\n {\n Console.Write(\" \" + a[j, 5-i ]);\n }\n Console.WriteLine();\n }\n"
},
{
"answer_id": 74483815,
"author": "Flydog57",
"author_id": 4739488,
"author_profile": "https://Stackoverflow.com/users/4739488",
"pm_score": 0,
"selected": false,
"text": "char"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15828620/"
] |
74,463,847
|
<p>I have a very simple method that receives a number and returns a text based on the range.
This is it:</p>
<pre><code>getBoardLocation(num) {
switch (num) {
case (6 >= num >= 1):
return 'bl';
case (12 >= num >= 7):
return 'br';
case (18 >= num >= 13):
return 'tl'
case (24 >= num >= 19):
return 'tr';
default:
break;
}
}
</code></pre>
<p>For some reason, despite being sure via breakpoints that the parameter being passed is indeed a number, and indeed in the range of one of the cases, it just goes to the default case, as seen in devtools, like here:</p>
<p><a href="https://i.stack.imgur.com/sugyq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sugyq.png" alt="why" /></a></p>
<p>I feel like I missed something incredibly stupid, but I can't figure out what.</p>
|
[
{
"answer_id": 74463927,
"author": "spender",
"author_id": 14357,
"author_profile": "https://Stackoverflow.com/users/14357",
"pm_score": 0,
"selected": false,
"text": "case"
},
{
"answer_id": 74463932,
"author": "Daniel",
"author_id": 11952668,
"author_profile": "https://Stackoverflow.com/users/11952668",
"pm_score": 0,
"selected": false,
"text": "num"
},
{
"answer_id": 74463934,
"author": "R4ncid",
"author_id": 14326899,
"author_profile": "https://Stackoverflow.com/users/14326899",
"pm_score": 3,
"selected": true,
"text": "const isBetween = (n, start, stop) => n >= start && n <= stop \n\nfunction getBoardLocation (num) {\n switch (true) {\n case isBetween(num, 1, 6):\n return 'bl'; \n case isBetween(num, 7, 12):\n return 'br';\n case isBetween(num, 13, 18):\n return 'tl'\n case isBetween(num, 19, 24):\n return 'tr';\n default:\n throw new Error(num + 'is not valid')\n }\n}\n[1, 9, 14, 21].forEach(n => console.log(n, getBoardLocation(n)))"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14794409/"
] |
74,463,863
|
<p>I am attempting to combine two regex operators when querying my MongoDB, the second of which (id) being a number field, hence the weird conversions.</p>
<p>Both of these work individually, and if I replace the <code>$where</code> regex with a more traditional one, it also works, however when run as is, it only looks for records that match the <code>$where</code> regex</p>
<pre class="lang-js prettyprint-override"><code>this.Asset
.find(query)
.or([
{
name: { $regex: searchQuery, $options: "i" }
},
{
$where: `function() { return this.id.toString().match(${searchQuery}) != null; }`
}
])
</code></pre>
|
[
{
"answer_id": 74463927,
"author": "spender",
"author_id": 14357,
"author_profile": "https://Stackoverflow.com/users/14357",
"pm_score": 0,
"selected": false,
"text": "case"
},
{
"answer_id": 74463932,
"author": "Daniel",
"author_id": 11952668,
"author_profile": "https://Stackoverflow.com/users/11952668",
"pm_score": 0,
"selected": false,
"text": "num"
},
{
"answer_id": 74463934,
"author": "R4ncid",
"author_id": 14326899,
"author_profile": "https://Stackoverflow.com/users/14326899",
"pm_score": 3,
"selected": true,
"text": "const isBetween = (n, start, stop) => n >= start && n <= stop \n\nfunction getBoardLocation (num) {\n switch (true) {\n case isBetween(num, 1, 6):\n return 'bl'; \n case isBetween(num, 7, 12):\n return 'br';\n case isBetween(num, 13, 18):\n return 'tl'\n case isBetween(num, 19, 24):\n return 'tr';\n default:\n throw new Error(num + 'is not valid')\n }\n}\n[1, 9, 14, 21].forEach(n => console.log(n, getBoardLocation(n)))"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10755384/"
] |
74,463,875
|
<p>How can I continuously copy one S3 bucket to another? I want to copy the files every time a new file has been added.</p>
<p>I've tried using the boto3 copy_object however I require the key each time which won't work if I'm getting a new file each time.</p>
|
[
{
"answer_id": 74467644,
"author": "John Rotenstein",
"author_id": 174777,
"author_profile": "https://Stackoverflow.com/users/174777",
"pm_score": 1,
"selected": false,
"text": "CopyObject()"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20281720/"
] |
74,463,894
|
<pre><code>mytype = "int"
myvalue = "35"
my_int_val = mytype(myvalue)
</code></pre>
<p>This throws up -</p>
<p><code>TypeError: 'str' object is not callable</code></p>
<p>I can't seem to remember the way to do so. Any ideas?</p>
<p>Please note that I have to use "str", "int" instead of str or int (without quotes), because I am getting this value from somewhere else where it's being passed on as a string.</p>
|
[
{
"answer_id": 74463986,
"author": "Priyatham",
"author_id": 2542516,
"author_profile": "https://Stackoverflow.com/users/2542516",
"pm_score": 0,
"selected": false,
"text": "my_int_val = int(myvalue)\nmy_str_val = str(myvalue)\n"
},
{
"answer_id": 74464018,
"author": "Harez",
"author_id": 20352132,
"author_profile": "https://Stackoverflow.com/users/20352132",
"pm_score": 0,
"selected": false,
"text": "mytype"
},
{
"answer_id": 74464061,
"author": "Matthias",
"author_id": 1209921,
"author_profile": "https://Stackoverflow.com/users/1209921",
"pm_score": 2,
"selected": false,
"text": "__builtins__"
},
{
"answer_id": 74465269,
"author": "pippo1980",
"author_id": 9877065,
"author_profile": "https://Stackoverflow.com/users/9877065",
"pm_score": 0,
"selected": false,
"text": "mytype = \"int\"\nmyvalue = \"35\"\n#my_int_val = myvalue.type(mytype)\n\n\nmy_int_val = eval(mytype)(myvalue) \n\n\nprint(my_int_val, type(my_int_val))\n\nmytype = \"str\"\nmyvalue = 35\n\nprint(myvalue, type(myvalue))\n\nmy_int_val = eval(mytype)(myvalue)\n\nprint(my_int_val, type(my_int_val))\n\n"
},
{
"answer_id": 74465373,
"author": "treuss",
"author_id": 19838568,
"author_profile": "https://Stackoverflow.com/users/19838568",
"pm_score": 0,
"selected": false,
"text": "mytype = \"str\""
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20470583/"
] |
74,463,899
|
<p>How can I change the value of a variable using dictionary? Right now I have to check every key of the dictionary and then change the corresponding variable's value.</p>
<p>`</p>
<pre><code>list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
dictionary = {
"dog": list1,
"cat": list2,
"mouse": list3
}
animal = input("Type dog, cat or mouse: ")
numbers_list = dictionary[animal]
# Adds 1 to all elements of the list
numbers_list = [x+1 for x in numbers_list]
# Is there an easier way to do this?
# Is there a way to change the value of the original list without
# using large amount of if-statements, since we know that
# dictionary[animal] is the list that we want to change?
# Using dictionary[animal] = numbers_list.copy(), obviously wont help because it
# only changes the list in the dictionary
if animal == "dog":
list1 = numbers_list.copy()
if animal == "cat":
list2 = numbers_list.copy()
if animal == "mouse":
list3 = numbers_list.copy()
print(list1, list2, list3)
</code></pre>
<p>`</p>
<p>I've tried using
<code>dictionary[animal] = numbers_list.copy()</code>
but that just changes the value in the dictionary, but not the actual list.
Those if-statements work, but if there is a large dictionary, it is quite a lot of work.</p>
|
[
{
"answer_id": 74463986,
"author": "Priyatham",
"author_id": 2542516,
"author_profile": "https://Stackoverflow.com/users/2542516",
"pm_score": 0,
"selected": false,
"text": "my_int_val = int(myvalue)\nmy_str_val = str(myvalue)\n"
},
{
"answer_id": 74464018,
"author": "Harez",
"author_id": 20352132,
"author_profile": "https://Stackoverflow.com/users/20352132",
"pm_score": 0,
"selected": false,
"text": "mytype"
},
{
"answer_id": 74464061,
"author": "Matthias",
"author_id": 1209921,
"author_profile": "https://Stackoverflow.com/users/1209921",
"pm_score": 2,
"selected": false,
"text": "__builtins__"
},
{
"answer_id": 74465269,
"author": "pippo1980",
"author_id": 9877065,
"author_profile": "https://Stackoverflow.com/users/9877065",
"pm_score": 0,
"selected": false,
"text": "mytype = \"int\"\nmyvalue = \"35\"\n#my_int_val = myvalue.type(mytype)\n\n\nmy_int_val = eval(mytype)(myvalue) \n\n\nprint(my_int_val, type(my_int_val))\n\nmytype = \"str\"\nmyvalue = 35\n\nprint(myvalue, type(myvalue))\n\nmy_int_val = eval(mytype)(myvalue)\n\nprint(my_int_val, type(my_int_val))\n\n"
},
{
"answer_id": 74465373,
"author": "treuss",
"author_id": 19838568,
"author_profile": "https://Stackoverflow.com/users/19838568",
"pm_score": 0,
"selected": false,
"text": "mytype = \"str\""
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74463899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20521653/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.