qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,615,546
|
<p>I have a table with strings in one column, which are actually storing other SQL Queries written before and stored to be ran at later times. They contain parameters such as '@organisationId' or '@enterDateHere'. I want to be able to extract these.</p>
<p>Example:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Query</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>SELECT * FROM table WHERE id = @organisationId</td>
</tr>
<tr>
<td>2</td>
<td>SELECT * FROM topic WHERE creation_time <=@startDate AND creation_time >= @endDate AND id = @enterOrgHere</td>
</tr>
<tr>
<td>3</td>
<td>SELECT name + '@' + domain FROM user</td>
</tr>
</tbody>
</table>
</div>
<p>I want the following:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Parameters</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>@organisationId</td>
</tr>
<tr>
<td>2</td>
<td>@startDate, @endDate, @enterOrgHere</td>
</tr>
<tr>
<td>3</td>
<td>NULL</td>
</tr>
</tbody>
</table>
</div>
<p>No need to worry about how to separate/list them, as long as they are clearly visible and as long as the query lists all of them, which I don't know the number of. Please note that sometimes the queries contain just @ for example when email binding is being done, but it's not a parameter. I want just strings which start with @ and have at least one letter after it, ending with a non-letter character (space, enter, comma, semi-colon). If this causes problems, then return all strings starting with @ and I will simply identify the parameters manually.</p>
<p>It can include usage of Excel/Python/C# if needed, but SQL is preferable.</p>
|
[
{
"answer_id": 74616176,
"author": "Arzanis",
"author_id": 20517352,
"author_profile": "https://Stackoverflow.com/users/20517352",
"pm_score": 0,
"selected": false,
"text": "DECLARE @sql TABLE\n(\n id INT PRIMARY KEY IDENTITY\n, sql_query NVARCHAR(MAX)\n);\n\nINSERT INTO @sql (sql_query)\nVALUES (N'SELECT * FROM table WHERE id = @organisationId')\n , (N'SELECT * FROM topic WHERE creation_time <=@startDate AND creation_time >= @endDate AND id = @enterOrgHere')\n , (N' SELECT name + ''@'' + domain FROM user')\n ;\n\n\nWITH prepared AS\n(\n SELECT id\n , IIF(sql_query LIKE '%@%'\n , SUBSTRING(sql_query, CHARINDEX('@', sql_query) + 1, LEN(sql_query))\n , CHAR(32)\n ) prep_string\n FROM @sql\n),\nparsed AS\n(\nSELECT id\n , IIF(CHARINDEX(CHAR(32), value) = 0\n , SUBSTRING(value, 1, LEN(VALUE))\n , SUBSTRING(value, 1, CHARINDEX(CHAR(32), value) -1)\n ) parsed_value\n FROM prepared p\n CROSS APPLY STRING_SPLIT(p.prep_string, '@')\n)\nSELECT id, '@' + STRING_AGG(IIF(parsed_value LIKE '[a-zA-Z]%', parsed_value, NULL) , ', @')\n FROM parsed\nGROUP BY id\n"
},
{
"answer_id": 74616211,
"author": "Dordi",
"author_id": 4266936,
"author_profile": "https://Stackoverflow.com/users/4266936",
"pm_score": 0,
"selected": false,
"text": "DROP TABLE IF EXISTS #TEMP\n\nSELECT 1 AS ID ,'SELECT * FROM table WHERE id = @organisationId' AS Query\nINTO #TEMP\nUNION ALL SELECT 2, 'SELECT * FROM topic WHERE creation_time <=@startDate AND creation_time >= @endDate AND id = @enterOrgHere'\nUNION ALL SELECT 3, 'SELECT name + ''@'' + domain FROM user'\n\n;WITH cte as\n(\n SELECT ID,\n Query,\n STRING_AGG(REPLACE(REPLACE(REPLACE(value,'<',''),'>',''),'=',''),', ') AS Parameters\n FROM #TEMP\n CROSS APPLY string_split(Query,' ')\n WHERE value LIKE '%@[a-z]%'\n GROUP BY ID,\n Query\n)\nSELECT #TEMP.*,cte.Parameters\nFROM #TEMP\nLEFT JOIN cte on #TEMP.ID = cte.ID\n"
},
{
"answer_id": 74616451,
"author": "Yitzhak Khabinsky",
"author_id": 1932311,
"author_profile": "https://Stackoverflow.com/users/1932311",
"pm_score": 2,
"selected": false,
"text": "CROSS APPLY CROSS APPLY -- DDL and sample data population, start\nDECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, Query VARCHAR(2048));\nINSERT INTO @tbl (Query) VALUES\n('SELECT * FROM table WHERE id = @organisationId'),\n('SELECT * FROM topic WHERE creation_time <=@startDate AND creation_time >= @endDate AND id = @enterOrgHere'),\n('SELECT name + ''@'' + domain FROM user');\n-- DDL and sample data population, end\n\nDECLARE @separator CHAR(1) = SPACE(1);\n\nSELECT t.ID\n , Parameters = IIF(t2.Par LIKE '@[a-z]%', t2.Par, NULL)\nFROM @tbl AS t\nCROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' + \n REPLACE(Query, @separator, ']]></r><r><![CDATA[') + \n ']]></r></root>' AS XML)) AS t1(c)\nCROSS APPLY (SELECT TRIM('><=' FROM c.query('data(/root/r[contains(text()[1],\"@\")])').value('text()[1]','VARCHAR(1024)'))) AS t2(Par)\n SELECT t.*\n , Parameters = IIF(t2.Par LIKE '@[a-z]%', t2.Par, NULL)\nFROM @tbl AS t\nCROSS APPLY (SELECT TRY_CAST('<r><![CDATA[' + Query + ']]></r>' AS XML).value('(/r/text())[1] cast as xs:token?','VARCHAR(MAX)')) AS t0(pure)\nCROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' + \n REPLACE(Pure, @separator, ']]></r><r><![CDATA[') + \n ']]></r></root>' AS XML)) AS t1(c)\nCROSS APPLY (SELECT TRIM('><=' FROM c.query('data(/root/r[contains(text()[1],\"@\")])')\n .value('text()[1]','VARCHAR(1024)'))) AS t2(Par);\n"
},
{
"answer_id": 74616535,
"author": "David Browne - Microsoft",
"author_id": 7297700,
"author_profile": "https://Stackoverflow.com/users/7297700",
"pm_score": 2,
"selected": false,
"text": "exec sp_describe_undeclared_parameters @tsql = N'SELECT * FROM topic WHERE creation_time <=@startDate AND creation_time >= @endDate AND id = @enterOrgHere' \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10325913/"
] |
74,615,578
|
<p>I have a list for example of type <code>People</code>. My list can contain only elements of type <code>Student</code> or only elements of type <code>Worker</code>:</p>
<pre><code> interface People {
val name: String
val age: Int
}
data class Student(
override val name: String,
override val age: Int,
val course: Int
) : People
data class Worker(
override val name: String,
override val age: Int,
val position: String
) : People
</code></pre>
<p>At some point I need to know the exact type of the list (student or worker).
Can I safely find out the exact type? So far I've written this code, but it doesn't look very good:</p>
<pre><code>fun someLogic(items: List<People>): List<People> {
return (items as? List<Student>) ?: (items as? List<Worker>)
?.filter {}
....
}
</code></pre>
<p>Also, I get a warning:</p>
<blockquote>
<p>Unchecked cast</p>
</blockquote>
<p>Can you please tell me how to perform such transformations correctly?</p>
|
[
{
"answer_id": 74615689,
"author": "MoCoding",
"author_id": 11617754,
"author_profile": "https://Stackoverflow.com/users/11617754",
"pm_score": 2,
"selected": false,
"text": "List<People> List<Student> fun List<People>.isStudentList(): Boolean {\n // returns true if no element is not Student, so all elements are Student\n return all { it is Student } \n}\n List<People> List<Student> People Student Student as? mapNotNull Student fun List<People>.toStudentList(): List<Student> {\n // This is going to loop through the list and cast each People to Student\n return mapNotNull { it as? Student }\n}\n filterIsInstance<Student> toStudentList list.filterIsInstance<Student>()\n Worker"
},
{
"answer_id": 74615783,
"author": "Simon Jacobs",
"author_id": 10928439,
"author_profile": "https://Stackoverflow.com/users/10928439",
"pm_score": 1,
"selected": false,
"text": "interface PeopleList<P : People> : List<P>\n\nclass StudentList : PeopleList<Student> {\n // add implementation\n}\n\nclass WorkerList : PeopleList<Worker> {\n // add implementation\n}\n Student Worker List List<People> PeopleList interface PeopleList<P : People> : List<P> {\n fun doSomethingGood()\n}\n PeopleList"
},
{
"answer_id": 74616151,
"author": "Sweeper",
"author_id": 5133585,
"author_profile": "https://Stackoverflow.com/users/5133585",
"pm_score": 3,
"selected": true,
"text": "val students: List<People> = listOf<Student>(student1, student2)\nval people: List<People> = listOf<People>(student1, student2)\n when (items.firstOrNull()) {\n null -> { /* cannot determine the type */ }\n is Student -> { /* is a list of students */ }\n is Worker -> { /* is a list of worker */ }\n\n // you can remove this branch by making the interface sealed\n else -> { /* someone made another class implementing People! */ }\n}\n List<Student> List<Worker> filterIsInstance val students = items.filterIsInstance<Student>()\nval worker = items.filterIsInstance<Worker>()\n items"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15742980/"
] |
74,615,585
|
<p>I have a CSV that's few thousand rows long. It contains data sent from various devices. They should transmit frequently (every 10 minutes) however sometimes there is a lag. I'm trying to write a program that will highlight all instances where the delay between two readings is greater than 15 minutes</p>
<p>I've made a functional code that works, but with this code I first have to manually edit the CSV to change the "eventTime" variable from time format (e.g. 03:22:00) to a float value based on 1/24 (e.g. 03:22:00 becomes 0.14027). Similarly, the 15 minute interval becomes 0.01042 (15/(60*24))</p>
<pre><code>import pandas as pd
df = pd.read_csv('file.csv')
df2 = pd.DataFrame()
deviceID = df["deviceId"].unique().tolist()
threshold = 0.01042
for id_no in range(0, len(deviceID)):
subset = df[df.deviceId == deviceID[id_no]]
for row in range(len(subset)-1):
difference = subset.iloc[row, 1] - subset.iloc[row+1, 1]
if difference > threshold:
df2 = df2.append(subset.iloc[row])
df2 = df2.append(subset.iloc[row+1])
df2.to_csv('file2.csv)
</code></pre>
<p>This works, and I can open the CSV in excel and manually change the float values back to time format, but when I might be dealing with a few hundred CSV files, this becomes impractical,</p>
<p>I've tried this below</p>
<pre><code>import pandas as pd
from datetime import datetime
df = pd.read_csv('file.csv')
df2 = pd.DataFrame()
deviceID = df["deviceId"].unique().tolist()
df['eventTime'].apply(lambda x: datetime.strptime(x, "%H:%M:%S"))
threshold = datetime.strptime("00:15:00", '%H:%M:%S')
for id_no in range(0, len(deviceID)):
subset = df[df.deviceId == deviceID[id_no]]
for row in range(len(subset)-1):
difference = datetime.strptime(subset.iloc[row, 1],'%H:%M:%S') - datetime.strptime(subset.iloc[row+1, 1], '%H:%M:%S')
if difference > threshold:
df2 = df2.append(subset.iloc[row])
df2 = df2.append(subset.iloc[row+1])
df2.to_csv('file2.csv')
</code></pre>
<p>but I get the following error:</p>
<pre><code>if difference > threshold:
TypeError: '>' not supported between instances of 'datetime.timedelta' and 'datetime.datetime'
</code></pre>
<p>The data looks like this:</p>
<pre><code>| eventTime| deviceId|
| -------- | -------- |
| 15:30:00 | 11234889|
| 15:45:00 | 11234889|
| 16:00:00 | 11234889|
</code></pre>
<p>and for different IDs</p>
<pre><code>| eventTime| deviceId|
| -------- | -------- |
| 15:30:00 | 11234890|
| 15:45:00 | 11234890|
| 16:00:00 | 11234890|
</code></pre>
|
[
{
"answer_id": 74615689,
"author": "MoCoding",
"author_id": 11617754,
"author_profile": "https://Stackoverflow.com/users/11617754",
"pm_score": 2,
"selected": false,
"text": "List<People> List<Student> fun List<People>.isStudentList(): Boolean {\n // returns true if no element is not Student, so all elements are Student\n return all { it is Student } \n}\n List<People> List<Student> People Student Student as? mapNotNull Student fun List<People>.toStudentList(): List<Student> {\n // This is going to loop through the list and cast each People to Student\n return mapNotNull { it as? Student }\n}\n filterIsInstance<Student> toStudentList list.filterIsInstance<Student>()\n Worker"
},
{
"answer_id": 74615783,
"author": "Simon Jacobs",
"author_id": 10928439,
"author_profile": "https://Stackoverflow.com/users/10928439",
"pm_score": 1,
"selected": false,
"text": "interface PeopleList<P : People> : List<P>\n\nclass StudentList : PeopleList<Student> {\n // add implementation\n}\n\nclass WorkerList : PeopleList<Worker> {\n // add implementation\n}\n Student Worker List List<People> PeopleList interface PeopleList<P : People> : List<P> {\n fun doSomethingGood()\n}\n PeopleList"
},
{
"answer_id": 74616151,
"author": "Sweeper",
"author_id": 5133585,
"author_profile": "https://Stackoverflow.com/users/5133585",
"pm_score": 3,
"selected": true,
"text": "val students: List<People> = listOf<Student>(student1, student2)\nval people: List<People> = listOf<People>(student1, student2)\n when (items.firstOrNull()) {\n null -> { /* cannot determine the type */ }\n is Student -> { /* is a list of students */ }\n is Worker -> { /* is a list of worker */ }\n\n // you can remove this branch by making the interface sealed\n else -> { /* someone made another class implementing People! */ }\n}\n List<Student> List<Worker> filterIsInstance val students = items.filterIsInstance<Student>()\nval worker = items.filterIsInstance<Worker>()\n items"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20223579/"
] |
74,615,588
|
<p>I'm trying to spawn enemies just outside the bounds of a rectangle. Here's a picture:</p>
<p><a href="https://i.stack.imgur.com/0kjRE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0kjRE.png" alt="enter image description here" /></a></p>
<p>That is, the grey area is the playing area that the user can see, and the green is outside the rendering bounds. I'm looking for a way to calculate a spawn position in this green area.</p>
<p>I have a tentative solution, but it's pretty long and involves a bunch of if statements. Is there a more efficient or elegant way of calculating this?</p>
<pre><code>function calcEnemySpawnPos(r) {
const roll = Math.random();
const left = -r;
const right = canvas.width + r;
const top = -r;
const bottom = canvas.height + r;
if (roll <= 0.25) {
return { x: left, y: getRandomInt(top, bottom) };
} else if (roll <= 0.5) {
return { x: right, y: getRandomInt(top, bottom) };
} else if (roll < 0.75) {
return { x: getRandomInt(left, right), y: top };
} else {
return { x: getRandomInt(left, right), y: bottom };
}
}
</code></pre>
|
[
{
"answer_id": 74615785,
"author": "faraday703",
"author_id": 2113474,
"author_profile": "https://Stackoverflow.com/users/2113474",
"pm_score": 2,
"selected": false,
"text": "const rollLeft = Math.random() - 0.5;\nconst rollTop = Math.random() - 0.5;\n\nif (rollLeft > 0){\n x = getRandomInt(-r, 0)\n} else {\n x = getRandomInt(canvas.width, canvas.width + r)\n}\n \nif (rollRight > 0){\n y = getRandomInt(-r, 0)\n} else {\n y = getRandomInt(canvas.height, canvas.height + r)\n}\n\nreturn {x, y}\n"
},
{
"answer_id": 74626691,
"author": "Trevor Dixon",
"author_id": 711902,
"author_profile": "https://Stackoverflow.com/users/711902",
"pm_score": 1,
"selected": false,
"text": "function startPos(ranges, totalSize) {\n let n = Math.trunc(Math.random() * totalSize);\n const {x: j, y: k, w} = ranges.find(r => n < r.size || void(n -= r.size));\n const x = n % w, y = (n - x) / w; // remainder/quotient of dividing by width\n return [x + j, y + k]; // translate to start of range\n}\n\n[x, y] = startPos([\n {x: -100, y: -100, w: 600, h: 100, size: 600 * 100},\n {x: 500, y: -100, w: 100, h: 400, size: 100 * 400},\n {x: 0, y: 300, w: 600, h: 100, size: 600 * 100},\n {x: -100, y: 0, w: 100, h: 400, size: 100 * 400},\n], 200_000);\n ranges.find(...) ranges.find(({size}) => {\n if (n < size) return true;\n else n -= size;\n});\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/962155/"
] |
74,615,612
|
<p>Im new to coding and am currently in a HS class. I have been trying extremely hard to get some :hover tags to work, using the knowledge I have gained from this class. The issue is that no matter what the form is, my hover tag will not work.</p>
<p>Here is my bare bones code:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title></title>
<style>
two {
display: none;
}
one {
display: block;
}
one:hover two {
display: block;
}
</style>
</head>
<body>
<one>Hello</one>
<two>Hello</two>
</body>
</html>
</code></pre>
<p>Its a highly simplified version of my actual project, and in the past, this seems to have worked. It now refuses to work no matter what I change. What am I missing in this, and what are my mistakes?</p>
|
[
{
"answer_id": 74615664,
"author": "Luís P. A.",
"author_id": 3613208,
"author_profile": "https://Stackoverflow.com/users/3613208",
"pm_score": 2,
"selected": false,
"text": "one:hover ~ two {\n display: block;\n }\n"
},
{
"answer_id": 74615889,
"author": "Pankaj Shrivastava",
"author_id": 16605279,
"author_profile": "https://Stackoverflow.com/users/16605279",
"pm_score": 0,
"selected": false,
"text": " h2{\n display: block;\n background-color: green;\n color: red;\n }\n h2:hover{\n background-color: black;\n }\n\n\n <h2>any</h2>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20634418/"
] |
74,615,638
|
<p>How can I group my database by month of the year and get the value of that grouping for each column I have ? in R</p>
<p>Here is a pic of my dataframe:</p>
<p><img src="https://i.stack.imgur.com/6Zu7a.png" alt="enter image description here" /></p>
<p>I tried to do that but it is not working:</p>
<pre><code>df_publications <- df_publications %>% group_by(publication_date)
%>% count()
</code></pre>
|
[
{
"answer_id": 74615848,
"author": "Sumant Yadav",
"author_id": 20634190,
"author_profile": "https://Stackoverflow.com/users/20634190",
"pm_score": -1,
"selected": false,
"text": "SQL SELECT Year_, Month_, SUM(Counts)\nFROM (\n SELECT YEAR(DATEADD(MM,DATEDIFF(MM,0,StartTime),0))'Year_'\n ,DATENAME(MONTH,DATEADD(MM,DATEDIFF(MM,0,StartTime),0))'Month_'\n ,TestName\n ,CASE WHEN Testname = 'POE Business Rules' THEN (count(TestName)*36) \n WHEN TestName = 'Submit' THEN (COUNT(TestName)*6) \n ELSE 0 \n END 'Counts'\n FROM VExecutionGlobalHistory\n GROUP BY YEAR(DATEADD(MM,DATEDIFF(MM,0,StartTime),0))\n ,DATENAME(MONTH,DATEADD(MM,DATEDIFF(MM,0,StartTime),0))\n ,TestName\n )sub\nGROUP BY Year_, Month_\nORDER BY CAST(CAST(Year_ AS CHAR(4)) + Month_ + '01' AS DATETIME) \n ORDER BY"
},
{
"answer_id": 74619267,
"author": "M.Viking",
"author_id": 10276092,
"author_profile": "https://Stackoverflow.com/users/10276092",
"pm_score": 1,
"selected": true,
"text": "Dplyr summarize across everything df<-data.frame(publication_date=c(\"2015 Jul\",\"2015 Jul\",\"2015 Aug\",\"2015 Aug\"),\n Asym=c(3,5,1,2),\n Auth=c(5,7,2,3),\n Cert=c(1,2,3,4))\n\nlibrary(tidyverse)\n\ndf %>% \n group_by(publication_date) %>% \n summarize(across(everything(), sum))\n\n# publication_date Asym Auth Cert\n#1 2015 Aug 3 5 7\n#2 2015 Jul 8 12 3\n base::xtabs() xtabs(cbind(Auth, Asym, Cert)~., data=df)\n#publication_date Auth Asym Cert\n# 2015 Aug 5 3 7\n# 2015 Jul 12 8 3\n xtabs(sprintf(\"cbind(%s)~.\", toString(names(df)[-1])), data = df)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19291009/"
] |
74,615,642
|
<p>I'm making a like button for a post in django. What I need is that when the like button is clicked, the function is executed, but I need the page not to be reloaded (To later use javascript). To do that I return a jsonresponse() instead of a return render. But the real problem is that it redirects me to the page that I show in the photo. The page is not reloaded. as I want it. but I don't want it to show me the blank page with the jsonresponse data (like this photo).I want to stay in the same page without reload.</p>
<p><a href="https://i.stack.imgur.com/joyCf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/joyCf.png" alt="What I get" /></a></p>
<p>My view function:</p>
<p>def liking (request, pk):</p>
<pre><code>posts = get_object_or_404(Post, id = pk)
if request.user in posts.likes.all():
posts.likes.remove(request.user)
else:
posts.likes.add(request.user.id)
likes_count = posts.likes.all().count()
print(f'likes_count = {likes_count}')
data= {
'likes_count': likes_count,
}
#return redirect ('index')# This is commented
return JsonResponse(data, safe=False, status=200 )
</code></pre>
|
[
{
"answer_id": 74615848,
"author": "Sumant Yadav",
"author_id": 20634190,
"author_profile": "https://Stackoverflow.com/users/20634190",
"pm_score": -1,
"selected": false,
"text": "SQL SELECT Year_, Month_, SUM(Counts)\nFROM (\n SELECT YEAR(DATEADD(MM,DATEDIFF(MM,0,StartTime),0))'Year_'\n ,DATENAME(MONTH,DATEADD(MM,DATEDIFF(MM,0,StartTime),0))'Month_'\n ,TestName\n ,CASE WHEN Testname = 'POE Business Rules' THEN (count(TestName)*36) \n WHEN TestName = 'Submit' THEN (COUNT(TestName)*6) \n ELSE 0 \n END 'Counts'\n FROM VExecutionGlobalHistory\n GROUP BY YEAR(DATEADD(MM,DATEDIFF(MM,0,StartTime),0))\n ,DATENAME(MONTH,DATEADD(MM,DATEDIFF(MM,0,StartTime),0))\n ,TestName\n )sub\nGROUP BY Year_, Month_\nORDER BY CAST(CAST(Year_ AS CHAR(4)) + Month_ + '01' AS DATETIME) \n ORDER BY"
},
{
"answer_id": 74619267,
"author": "M.Viking",
"author_id": 10276092,
"author_profile": "https://Stackoverflow.com/users/10276092",
"pm_score": 1,
"selected": true,
"text": "Dplyr summarize across everything df<-data.frame(publication_date=c(\"2015 Jul\",\"2015 Jul\",\"2015 Aug\",\"2015 Aug\"),\n Asym=c(3,5,1,2),\n Auth=c(5,7,2,3),\n Cert=c(1,2,3,4))\n\nlibrary(tidyverse)\n\ndf %>% \n group_by(publication_date) %>% \n summarize(across(everything(), sum))\n\n# publication_date Asym Auth Cert\n#1 2015 Aug 3 5 7\n#2 2015 Jul 8 12 3\n base::xtabs() xtabs(cbind(Auth, Asym, Cert)~., data=df)\n#publication_date Auth Asym Cert\n# 2015 Aug 5 3 7\n# 2015 Jul 12 8 3\n xtabs(sprintf(\"cbind(%s)~.\", toString(names(df)[-1])), data = df)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17357385/"
] |
74,615,651
|
<p>For this question, consider I have a repository with one asset:</p>
<pre class="lang-py prettyprint-override"><code>@asset
def my_int():
return 1
@repository
def my_repo():
return [my_int]
</code></pre>
<p>I want to execute it in process (with mem_io_manager), but I would like to retrieve the value returned by my_int from memory later. I can do that with fs_io_manager, for example, using <code>my_repo.load_asset_value('my_int')</code>, after it ran. But the same method with mem_io_manager raises <code>dagster._core.errors.DagsterInvariantViolationError: Attempting to access step_key, but it was not provided when constructing the OutputContext</code>.</p>
<p>Ideally, I would execute it in process and tell the executor to return me one (or more) of the assets, something like:</p>
<pre class="lang-py prettyprint-override"><code>my_assets = my_repo.get_job('__ASSET_JOB').execute_in_process(return_assets=[my_int, ...])
</code></pre>
|
[
{
"answer_id": 74616303,
"author": "Kay",
"author_id": 4351039,
"author_profile": "https://Stackoverflow.com/users/4351039",
"pm_score": 2,
"selected": false,
"text": "mem_io_manager fs_io_manager my_int @asset\ndef my_int(context):\n return Output(my_int_value, metadata={'my_int_value': my_int_value})\n @asset\ndef retrieve_my_int(context):\n asset_key = 'my_int'\n latest_materialization_event = (\n self.init_context.instance.get_latest_materialization_events(\n [asset_key]\n ).get(asset_key)\n )\n if latest_materialization_event:\n materialization = (\n latest_materialization_event.dagster_event.event_specific_data.materialization\n )\n metadata = {\n entry.label: entry.entry_data\n for entry in materialization.metadata_entries\n }\n retrieved_int = metadata['my_int_value'].value if 'my_int_value' in metadata.keys() else None\n .......\n execute_in_process materialize @asset\ndef my_int(context):\n ....\n\n\n@asset\ndef asset_other(context):\n ....\n\n\nif __name__ == '__main__':\n asset_results = materialize(\n load_assets_from_current_module()\n )\n my_int_value = asset_results.output_for_node('my_int')\n"
},
{
"answer_id": 74617329,
"author": "zyd",
"author_id": 6297800,
"author_profile": "https://Stackoverflow.com/users/6297800",
"pm_score": 0,
"selected": false,
"text": "mem_io_manager from dagster import materialize\nasset_result = materialize([my_int])\n"
},
{
"answer_id": 74633001,
"author": "pedrovgp",
"author_id": 1708819,
"author_profile": "https://Stackoverflow.com/users/1708819",
"pm_score": 0,
"selected": false,
"text": "output_for_node execute_in_process my_int from dagster import asset, repository\n\n@asset\ndef my_int():\n return 1\n\n@repository\ndef my_repo():\n return [my_int]\n\nmy_assets = my_repo.get_job('__ASSET_JOB').execute_in_process()\nmy_assets.output_for_node(\"my_int\")\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1708819/"
] |
74,615,683
|
<p>lets say I have a <code>Table1</code> as follow:</p>
<pre><code>ID | Value
________________
1 | 0
2 | 0
1 | 1
3 | 1
1 | 0
2 | 0
1 | 0
2 | 0
3 | 0
4 | 1
1 | 0
5 | 0
</code></pre>
<p>and I have a second table that contains unique <code>IDs</code> from <code>Table1</code>.
In <code>Table1</code> <code>ID</code> may repeat, but each <code>ID</code> can have at most one <code>1</code> in <code>Value</code> column, the rest is <code>0</code>.
How can I write <code>VLOOKUP</code> like formula that will tell me if given <code>ID</code> has <code>1</code> in any occurence?</p>
<p>I would like to get smth like</p>
<pre><code>ID | Value
________________
1 | 1
2 | 0
3 | 1
4 | 1
5 | 0
</code></pre>
<p>with SQL I would write smth as <code> SELECT ID, max(Value) from Table1 group by ID</code>, or even instead of <code>max</code> would use <code>sum</code>.
Also to mention: <code>Table1</code> will be in separate file from my output table and the <code>Value</code> will be just one of many columns, therefore I cannot use Pivot Tables</p>
|
[
{
"answer_id": 74615917,
"author": "Dominique",
"author_id": 4279155,
"author_profile": "https://Stackoverflow.com/users/4279155",
"pm_score": 2,
"selected": false,
"text": "=SUMIFS(B$2:B$13,A$2:A$13,1)\n =IF(E2,1,0)\n"
},
{
"answer_id": 74616577,
"author": "Harun24hr",
"author_id": 5514747,
"author_profile": "https://Stackoverflow.com/users/5514747",
"pm_score": 0,
"selected": false,
"text": "=HSTACK(UNIQUE(A2:A13),MAXIFS(B2:B13,A2:A13,UNIQUE(A2:A13)))\n SQL"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19035289/"
] |
74,615,694
|
<p>We are working with a <code>function</code> which could draw a plot or not.<br />
I am looking for a solution to check if the function has a side effect of drawing.<br />
I hope there is some <code>dev.*</code> solution to check it out.<br />
The <code>inherits</code> could be used only for solutions which return reusable objects like <code>ggplot2</code>. On the other hand <code>boxplot</code> return a <code>list</code> and <code>plot</code> a NULL class.<br />
I expect to check the <code>dev</code> precisely.<br />
The extensive list of different graphics and non-graphics is provided.</p>
<pre class="lang-r prettyprint-override"><code>input_plots <- list(
function() print(ggplot2::qplot(1)),
function() lattice::densityplot(1),
function() grid::grid.draw(ggplotify::as.grob(lattice::densityplot(1))),
function() plot(1),
function() boxplot(2),
function() hist(1)
)
input_noplots <- list(
function() list(),
function() NULL,
function() 2,
function() NA
)
# We are working with a function which could draw a plot or not
all(vapply(input_plots, is.function, FUN.VALUE = logical(1)))
#> [1] TRUE
all(vapply(input_noplots, is.function, FUN.VALUE = logical(1)))
#> [1] TRUE
# all input_plots should be TRUE for is_draw
# all input_noplots should be FALSE for is_draw
is_draw <- function(fun){
# inherits works only for functions returning proper instances
# you can call a function fun()
...
# return logical if the fun draw a plot
}
# all(vapply(input_plots, is_draw, FUN.VALUE = logical(1)))
# TRUE
# all(vapply(input_noplots, Negate(is_draw), FUN.VALUE = logical(1)))
# TRUE
</code></pre>
<p><sup>Created on 2022-11-29 with <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex v2.0.2</a></sup></p>
<p>VALIDATE SOLUTION:</p>
<pre class="lang-r prettyprint-override"><code># all input_plots should be TRUE for is_draw
# all input_noplots should be FALSE for is_draw
# this function will clear your device
is_draw <- function(f) {
try(dev.off(), silent = TRUE)
# graphics.off() # close any current graphics devices
cdev <- dev.cur()
f()
if (cdev != dev.cur()) {
on.exit(dev.off())
return(TRUE)
}
return(FALSE)
}
all(vapply(input_plots, is_draw, FUN.VALUE = logical(1)))
#> Warning: `qplot()` was deprecated in ggplot2 3.4.0.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> [1] TRUE
# TRUE
all(vapply(input_noplots, Negate(is_draw), FUN.VALUE = logical(1)))
#> [1] TRUE
# TRUE
plot(1)
all(vapply(input_plots, is_draw, FUN.VALUE = logical(1)))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> [1] TRUE
# TRUE
all(vapply(input_noplots, Negate(is_draw), FUN.VALUE = logical(1)))
#> [1] TRUE
# TRUE
</code></pre>
<p><sup>Created on 2022-11-29 with <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex v2.0.2</a></sup></p>
|
[
{
"answer_id": 74615917,
"author": "Dominique",
"author_id": 4279155,
"author_profile": "https://Stackoverflow.com/users/4279155",
"pm_score": 2,
"selected": false,
"text": "=SUMIFS(B$2:B$13,A$2:A$13,1)\n =IF(E2,1,0)\n"
},
{
"answer_id": 74616577,
"author": "Harun24hr",
"author_id": 5514747,
"author_profile": "https://Stackoverflow.com/users/5514747",
"pm_score": 0,
"selected": false,
"text": "=HSTACK(UNIQUE(A2:A13),MAXIFS(B2:B13,A2:A13,UNIQUE(A2:A13)))\n SQL"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5442527/"
] |
74,615,696
|
<p>So i updated the values of a dictionary into percentage by multiplying by 100. Now i want to replace the initial decimal with the updated results, but instead, i am getting each value replaced by the whole new values.</p>
<pre><code>job_role_overtime_att_rate = {'Healthcare Representative Overtime Rate' : 2/37, ' Human Resources Overtime Rate': 5/13,
'Laboratory Technician Total' : 31/62, 'Manager Total': 4/27, 'Manufacturing Director Total': 4/39,
'Research Director Total' : 1/23, 'Research Scientist Total' : 33/97,
'Sales Executive Total' : 31/94, 'Sales Representative Total' : 16/24}
job_role_overtime_att_rate()
</code></pre>
<pre><code>{'Healthcare Representative Overtime Rate': 0.05405405405405406,
' Human Resources Overtime Rate': 0.38461538461538464,
'Laboratory Technician Total': 0.5,
'Manager Total': 0.14814814814814814,
'Manufacturing Director Total': 0.10256410256410256,
'Research Director Total': 0.043478260869565216,
'Research Scientist Total': 0.3402061855670103,
'Sales Executive Total': 0.32978723404255317,
'Sales Representative Total': 0.6666666666666666}
</code></pre>
<p>this the result of the above code.</p>
<pre><code>for i in job_role_overtime_att_rate.values():
a = i * 100
print('{0:.2f}'.format(a))
</code></pre>
<p>this multiplies the initial result by 100. now</p>
<pre><code>5.41
38.46
50.00
14.81
10.26
4.35
34.02
32.98
66.67
</code></pre>
<p>here is the result.</p>
<pre><code>for i in job_role_overtime_att_rate.values():
a = i * 100
print('{0:.2f}'.format(a))
for values in job_role_overtime_att_rate.values():
values = a
print(values)
</code></pre>
<p>this is to replace the intial values with the new one. at least that's what i thought it will do.</p>
<pre><code>5.41
5.405405405405405
5.405405405405405
5.405405405405405
5.405405405405405
5.405405405405405
5.405405405405405
5.405405405405405
5.405405405405405
5.405405405405405
38.46
38.46153846153847
38.46153846153847
38.46153846153847
38.46153846153847
38.46153846153847
38.46153846153847
38.46153846153847
38.46153846153847
38.46153846153847
50.00
50.0
50.0
50.0
50.0
50.0
50.0
50.0
50.0
50.0
14.81
14.814814814814813
14.814814814814813
14.814814814814813
14.814814814814813
14.814814814814813
14.814814814814813
14.814814814814813
14.814814814814813
14.814814814814813
10.26
10.256410256410255
10.256410256410255
10.256410256410255
10.256410256410255
10.256410256410255
10.256410256410255
10.256410256410255
10.256410256410255
10.256410256410255
4.35
4.3478260869565215
4.3478260869565215
4.3478260869565215
4.3478260869565215
4.3478260869565215
4.3478260869565215
4.3478260869565215
4.3478260869565215
4.3478260869565215
34.02
34.02061855670103
34.02061855670103
34.02061855670103
34.02061855670103
34.02061855670103
34.02061855670103
34.02061855670103
34.02061855670103
34.02061855670103
32.98
32.97872340425532
32.97872340425532
32.97872340425532
32.97872340425532
32.97872340425532
32.97872340425532
32.97872340425532
32.97872340425532
32.97872340425532
66.67
66.66666666666666
66.66666666666666
66.66666666666666
66.66666666666666
66.66666666666666
66.66666666666666
66.66666666666666
66.66666666666666
66.66666666666666
</code></pre>
<p>here is what it's returning. Kindly help. Thanks</p>
|
[
{
"answer_id": 74615862,
"author": "Gameplay",
"author_id": 15923186,
"author_profile": "https://Stackoverflow.com/users/15923186",
"pm_score": 0,
"selected": false,
"text": "for key, value in job_role_overtime_att_rate.items():\n job_role_overtime_att_rate[key]= value*100\n"
},
{
"answer_id": 74616032,
"author": "JesterIsHere",
"author_id": 18872613,
"author_profile": "https://Stackoverflow.com/users/18872613",
"pm_score": 2,
"selected": false,
"text": "dict.items() job_role_overtime_att_rate = {\n 'Healthcare Representative Overtime Rate': 0.05405405405405406,\n 'Human Resources Overtime Rate': 0.38461538461538464,\n 'Laboratory Technician Total': 0.5,\n 'Manager Total': 0.14814814814814814,\n 'Manufacturing Director Total': 0.10256410256410256,\n 'Research Director Total': 0.043478260869565216,\n 'Research Scientist Total': 0.3402061855670103,\n 'Sales Executive Total': 0.32978723404255317,\n 'Sales Representative Total': 0.6666666666666666\n}\n\nfor name, value in job_role_overtime_att_rate.items():\n a = round(value*100, 2)\n job_role_overtime_att_rate[name] = a\n\nprint(job_role_overtime_att_rate)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10289706/"
] |
74,615,700
|
<p>I'm trying to import data from a CSV file, unfortunately there is no primary key that would allow me to uniquely identify a given row. So I created a dictionary in which the key is the value that GetHashCode returns to me. I use the dictionary because its search is much faster than searching with linq and where with conditions for several properties.</p>
<p>My GetHashCode override looks like this:</p>
<pre><code> public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = hash * 23 + this.Id.GetHashCode();
hash = hash * 23 + this.Author?.GetHashCode() ?? 0.GetHashCode();
hash = hash * 23 + this.Activity?.GetHashCode() ?? 0.GetHashCode();
hash = hash * 23 + this.DateTime?.GetHashCode() ?? 0.GetHashCode();
return hash;
}
}
</code></pre>
<p>After fetching data from DB I do:</p>
<pre><code>.ToDictionary(d => d.GetHashCode());
</code></pre>
<p>And here comes the problem, I checked the database and I don't have any duplicates when it comes to these four parameters. But when running the import I often get an error that the given key already exists in the dictionary, but if I run the import again for the same data the next time everything runs fine.</p>
<p>How can I fix this error?
The import application is written in .net 5</p>
<blockquote>
<p>Id - long</p>
<p>Author, Activity - string</p>
<p>DateTime - DateTime?</p>
</blockquote>
<p>Unfortunately, this ID is more like FK is not unique, there may be many rows with the same id, author, activity, but e.g. a different datetime</p>
|
[
{
"answer_id": 74615832,
"author": "Batesias",
"author_id": 10975965,
"author_profile": "https://Stackoverflow.com/users/10975965",
"pm_score": 0,
"selected": false,
"text": "GetHashCode Guid"
},
{
"answer_id": 74616005,
"author": "Panagiotis Kanavos",
"author_id": 134204,
"author_profile": "https://Stackoverflow.com/users/134204",
"pm_score": 1,
"selected": false,
"text": "ValueTuple record .ToDictionary(d=>(d.Id,d.Author,d.Activity,d.DateTime));\n ValueTuple record record struct public record ActivityKey( int Id, \n string Author, \n string Activity, \n DateTime DateTime);\n...\n.ToDictionary(d=>new ActivityKey(d.Id,d.Author,d.Activity,d.DateTime));\n"
},
{
"answer_id": 74616064,
"author": "Matthew Watson",
"author_id": 106159,
"author_profile": "https://Stackoverflow.com/users/106159",
"pm_score": 3,
"selected": true,
"text": "GetHashCode() GetHashCode() IEquatable<T> x y GetHashCode() x.Equals(y) true public sealed class DataKey : IEquatable<DataKey>\n{\n public long Id { get; }\n public string? Author { get; }\n public string? Activity { get; }\n public DateTime? DateTime { get; }\n\n public DataKey(long id, string? author, string? activity, DateTime? dateTime)\n {\n Id = id;\n Author = author;\n Activity = activity;\n DateTime = dateTime;\n }\n\n public bool Equals(DataKey? other)\n {\n if (other is null)\n return false;\n\n if (ReferenceEquals(this, other))\n return true;\n\n return Id == other.Id && Author == other.Author && Activity == other.Activity && Nullable.Equals(DateTime, other.DateTime);\n }\n\n public override bool Equals(object? obj)\n {\n return ReferenceEquals(this, obj) || obj is DataKey other && Equals(other);\n }\n\n public override int GetHashCode()\n {\n unchecked\n {\n var hashCode = Id.GetHashCode();\n hashCode = (hashCode * 397) ^ (Author?.GetHashCode() ?? 0);\n hashCode = (hashCode * 397) ^ (Activity?.GetHashCode() ?? 0);\n hashCode = (hashCode * 397) ^ (DateTime?.GetHashCode() ?? 0);\n return hashCode;\n }\n }\n}\n record public sealed record DataKey(\n long Id,\n string? Author,\n string? Activity,\n DateTime? DateTime);\n record IEquatable<T> GetHashCode() long string? DateTime? GetHashCode() Equals()"
},
{
"answer_id": 74616243,
"author": "Stephan Samuel",
"author_id": 20564392,
"author_profile": "https://Stackoverflow.com/users/20564392",
"pm_score": 1,
"selected": false,
"text": "int GetHashCode() public class Record {\n public int ID;\n public string Author;\n public string Activity;\n public DateTime? DateTime;\n \n public string GetRowHash() {\n var builder = new System.Text.StringBuilder();\n builder.Append(this.ID.ToString());\n builder.Append(this.Author ?? \"\");\n builder.Append(this.Activity ?? \"\");\n builder.Append(this.DateTime?.ToString() ?? \"\");\n \n using (var md5 = System.Security.Cryptography.MD5.Create()) {\n byte[] buffer = System.Text.Encoding.ASCII.GetBytes(builder.ToString());\n byte[] hash = md5.ComputeHash(buffer);\n return Convert.ToBase64String(hash);\n }\n }\n}\n GetRowHash() int Convert.ToBase64String(...)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14952105/"
] |
74,615,708
|
<p>Good day</p>
<p>I am very very new two paginated reports so forgive me if this is a silly question</p>
<p>I have a report that displays values for Mondays to Fridays based on the date selected from a date picker.
So basically
You select a date (Example 24 Nov) and the following table is displayed based on values pulled from SQL.</p>
<p><a href="https://i.stack.imgur.com/KtWAf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KtWAf.png" alt="enter image description here" /></a></p>
<p>Now my question is how do I display the dates of the weekdays too?
So if the date selected is Thursday 24 Nov, in the column headers under the week day names it should give the corresponding date i.e Monday-21/11/2022, Tuesday - 22/11/2022, etc.</p>
<p>Below is a little snippet of the data</p>
<p><a href="https://i.stack.imgur.com/cQlcR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cQlcR.png" alt="enter image description here" /></a></p>
<p>So the date picker is based on the ReportingDate column. The rows of the matrix consist of Region and Country and the values are the sum of Monday-Friday.</p>
<p>Any guidance would be greatly appreciated.</p>
<p>Edit: The day names are not obtained via an expression in SSRS. They carry over from the column headers in the data set.</p>
|
[
{
"answer_id": 74615832,
"author": "Batesias",
"author_id": 10975965,
"author_profile": "https://Stackoverflow.com/users/10975965",
"pm_score": 0,
"selected": false,
"text": "GetHashCode Guid"
},
{
"answer_id": 74616005,
"author": "Panagiotis Kanavos",
"author_id": 134204,
"author_profile": "https://Stackoverflow.com/users/134204",
"pm_score": 1,
"selected": false,
"text": "ValueTuple record .ToDictionary(d=>(d.Id,d.Author,d.Activity,d.DateTime));\n ValueTuple record record struct public record ActivityKey( int Id, \n string Author, \n string Activity, \n DateTime DateTime);\n...\n.ToDictionary(d=>new ActivityKey(d.Id,d.Author,d.Activity,d.DateTime));\n"
},
{
"answer_id": 74616064,
"author": "Matthew Watson",
"author_id": 106159,
"author_profile": "https://Stackoverflow.com/users/106159",
"pm_score": 3,
"selected": true,
"text": "GetHashCode() GetHashCode() IEquatable<T> x y GetHashCode() x.Equals(y) true public sealed class DataKey : IEquatable<DataKey>\n{\n public long Id { get; }\n public string? Author { get; }\n public string? Activity { get; }\n public DateTime? DateTime { get; }\n\n public DataKey(long id, string? author, string? activity, DateTime? dateTime)\n {\n Id = id;\n Author = author;\n Activity = activity;\n DateTime = dateTime;\n }\n\n public bool Equals(DataKey? other)\n {\n if (other is null)\n return false;\n\n if (ReferenceEquals(this, other))\n return true;\n\n return Id == other.Id && Author == other.Author && Activity == other.Activity && Nullable.Equals(DateTime, other.DateTime);\n }\n\n public override bool Equals(object? obj)\n {\n return ReferenceEquals(this, obj) || obj is DataKey other && Equals(other);\n }\n\n public override int GetHashCode()\n {\n unchecked\n {\n var hashCode = Id.GetHashCode();\n hashCode = (hashCode * 397) ^ (Author?.GetHashCode() ?? 0);\n hashCode = (hashCode * 397) ^ (Activity?.GetHashCode() ?? 0);\n hashCode = (hashCode * 397) ^ (DateTime?.GetHashCode() ?? 0);\n return hashCode;\n }\n }\n}\n record public sealed record DataKey(\n long Id,\n string? Author,\n string? Activity,\n DateTime? DateTime);\n record IEquatable<T> GetHashCode() long string? DateTime? GetHashCode() Equals()"
},
{
"answer_id": 74616243,
"author": "Stephan Samuel",
"author_id": 20564392,
"author_profile": "https://Stackoverflow.com/users/20564392",
"pm_score": 1,
"selected": false,
"text": "int GetHashCode() public class Record {\n public int ID;\n public string Author;\n public string Activity;\n public DateTime? DateTime;\n \n public string GetRowHash() {\n var builder = new System.Text.StringBuilder();\n builder.Append(this.ID.ToString());\n builder.Append(this.Author ?? \"\");\n builder.Append(this.Activity ?? \"\");\n builder.Append(this.DateTime?.ToString() ?? \"\");\n \n using (var md5 = System.Security.Cryptography.MD5.Create()) {\n byte[] buffer = System.Text.Encoding.ASCII.GetBytes(builder.ToString());\n byte[] hash = md5.ComputeHash(buffer);\n return Convert.ToBase64String(hash);\n }\n }\n}\n GetRowHash() int Convert.ToBase64String(...)"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6302043/"
] |
74,615,760
|
<p>I want to put this for loop into a comprehension. Is this even possible?</p>
<pre><code>for i in range(1, 11):
result = len({tuple(walk) for (walk, distance) in dic[i] if distance == 0})
print(f'There are {result} different unique walks with length {i}')
</code></pre>
<p>I tried stuff like</p>
<pre><code>print({tuple(walk) for i in range(1, 11) for (walk, distance) in dic[i] if distance == 0})
</code></pre>
<p>but this prints all walks for all i together, but i want 10 different print statements.</p>
|
[
{
"answer_id": 74616011,
"author": "Gameplay",
"author_id": 15923186,
"author_profile": "https://Stackoverflow.com/users/15923186",
"pm_score": 3,
"selected": true,
"text": "[print(f'There are {len({tuple(walk) for (walk, distance) in dic[i] if distance == 0})} different unique walks with length {i}') for i in range(1,11)]\n"
},
{
"answer_id": 74616059,
"author": "Lone Lunatic",
"author_id": 7694279,
"author_profile": "https://Stackoverflow.com/users/7694279",
"pm_score": 1,
"selected": false,
"text": "print None None >>> res = [print(i) for i in range(1, 11)]\n1\n2\n...\n>>> res\n[None, None, ...]\n str.join print >>> print('\\n'.join(str(i) for i in range(1, 11)))\n1\n2\n...\n >>> res = [i for i in range(1, 11)]\n>>> res\n[1, 2, ...]\n>>> print(*res, sep='\\n')\n1\n2\n...\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20627928/"
] |
74,615,763
|
<p>When trying to install ruby gems to enable libvirt management for vagrant, the installation fails with a undocumented message « it depends on a library which is not currently installed : libvirt ».</p>
<p>Libvirt is working, I am able to compile manually « vagrant-libvirt », and even starting and configuring qemu VMs using virsh.</p>
<p>The host is a VMWare one, but the nested virtualization is enabled.
The Virtualization « VT-x » is visible thru lscpu and « vmx / svm » capabilities are presents in /proc/cpuinfo.</p>
<pre><code>Vagrant failed to install the requested plugin because it depends
on a library which is not currently installed on this system. The
following library is required by the 'vagrant-libvirt' plugin:
libvirt
Please install the library and then run the command again.
</code></pre>
<p>I have installed all packages / gems <a href="https://computingforgeeks.com/use-vagrant-with-libvirt-kvm-on-centos/" rel="nofollow noreferrer">https://computingforgeeks.com/use-vagrant-with-libvirt-kvm-on-centos/</a> and cannot figure how ruby is trying to talk to libvirt, with which library that may be missing.</p>
<p>Tried both with RHEL, Centos8 (alma), Debian sid.</p>
|
[
{
"answer_id": 74616011,
"author": "Gameplay",
"author_id": 15923186,
"author_profile": "https://Stackoverflow.com/users/15923186",
"pm_score": 3,
"selected": true,
"text": "[print(f'There are {len({tuple(walk) for (walk, distance) in dic[i] if distance == 0})} different unique walks with length {i}') for i in range(1,11)]\n"
},
{
"answer_id": 74616059,
"author": "Lone Lunatic",
"author_id": 7694279,
"author_profile": "https://Stackoverflow.com/users/7694279",
"pm_score": 1,
"selected": false,
"text": "print None None >>> res = [print(i) for i in range(1, 11)]\n1\n2\n...\n>>> res\n[None, None, ...]\n str.join print >>> print('\\n'.join(str(i) for i in range(1, 11)))\n1\n2\n...\n >>> res = [i for i in range(1, 11)]\n>>> res\n[1, 2, ...]\n>>> print(*res, sep='\\n')\n1\n2\n...\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8639606/"
] |
74,615,766
|
<p><strong>Edit: I'm starting to suspect the problems arising below are due to the metadata, because even after correcting the issues raised regarding units mpcalc.geostrophic_wind(z) still issues warnings about the coordinates and ordering. Maybe the function is unable to identify the coordinates from the file? Perhaps this is because WRF output data is non-CF compliant?</strong></p>
<p>I would like to compute geostrophic and ageostrophic winds from WRF-ARW data using the MetPy function mpcalc.geostrophic_wind.</p>
<p>My attempt results in a bunch of errors and I don't know what I'm doing wrong. Can someone tell me how to modify my code to get rid of these errors?</p>
<p>Here is my attempt so far:</p>
<pre><code>#
import numpy as np
from netCDF4 import Dataset
import metpy.calc as mpcalc
from wrf import getvar
# Open the NetCDF file
filename = "wrfout_d01_2016-10-04_12:00:00"
ncfile = Dataset(filename)
# Extract the geopotential height and wind variables
z = getvar(ncfile, "z", units="m")
ua = getvar(ncfile, "ua", units="m s-1")
va = getvar(ncfile, "va", units="m s-1")
# Smooth height data
z = mpcalc.smooth_gaussian(z, 3)
# Compute the geostrophic wind
geo_wind_u, geo_wind_v = mpcalc.geostrophic_wind(z)
# Calculate ageostrophic wind components
ageo_wind_u = ua - geo_wind_u
ageo_wind_v = va - geo_wind_v
#
</code></pre>
<p>The computation of the geostrophic wind throws several warnings:</p>
<pre><code>>>> # Compute the geostrophic wind
>>> geo_wind_u, geo_wind_v = mpcalc.geostrophic_wind(z)
/mnt/.../.../metpy_en/lib/python3.9/site-packages/metpy/xarray.py:355: UserWarning: More than one time coordinate present for variable.
warnings.warn('More than one ' + axis + ' coordinate present for variable'
/mnt/.../.../lib/python3.9/site-packages/metpy/xarray.py:1459: UserWarning: Horizontal dimension numbers not found. Defaulting to (..., Y, X) order.
warnings.warn('Horizontal dimension numbers not found. Defaulting to '
/mnt/.../.../lib/python3.9/site-packages/metpy/xarray.py:355: UserWarning: More than one time coordinate present for variable "XLAT".
warnings.warn('More than one ' + axis + ' coordinate present for variable'
/mnt/.../.../lib/python3.9/site-packages/metpy/xarray.py:1393: UserWarning: y and x dimensions unable to be identified. Assuming [..., y, x] dimension order.
warnings.warn('y and x dimensions unable to be identified. Assuming [..., y, x] '
/mnt/.../.../lib/python3.9/site-packages/metpy/calc/basic.py:1274: UserWarning: Input over 1.5707963267948966 radians. Ensure proper units are given.
warnings.warn('Input over {} radians. '
</code></pre>
<p>Can anyone tell me why I'm getting these warnings?</p>
<p>And then trying to compute an ageostrophic wind component results in a bunch of errors:</p>
<pre><code>>>> # Calculate ageostrophic wind components
>>> ageo_wind_u = ua - geo_wind_u
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/mnt/.../lib/python3.9/site-packages/xarray/core/_typed_ops.py", line 209, in __sub__
return self._binary_op(other, operator.sub)
File "/mnt/.../lib/python3.9/site-packages/xarray/core/dataarray.py", line 4357, in _binary_op f(self.variable, other_variable)
File "/mnt/.../lib/python3.9/site-packages/xarray/core/_typed_ops.py", line 399, in __sub__
return self._binary_op(other, operator.sub)
File "/mnt/.../lib/python3.9/site-packages/xarray/core/variable.py", line 2639, in _binary_op
f(self_data, other_data) if not reflexive else f(other_data, self_data)
File "/mnt/iusers01/fatpou01/sees01/w34926hb/.conda/envs/metpy_env/lib/python3.9/site-packages/pint/facets/numpy/quantity.py", line 61, in __array_ufunc__
return numpy_wrap("ufunc", ufunc, inputs, kwargs, types)
File "/mnt/.../lib/python3.9/site-packages/pint/facets/numpy/numpy_func.py", line 953, in numpy_wrap return handled[name](*args, **kwargs)
File "/mnt/.../lib/python3.9/site-packages/pint/facets/numpy/numpy_func.py", line 513, in _subtract (x1, x2), output_wrap = unwrap_and_wrap_consistent_units(x1, x2)
File "/mnt/.../lib/python3.9/site-packages/pint/facets/numpy/numpy_func.py", line 130, in unwrap_and_wrap_consistent_units args, _ = convert_to_consistent_units(*args, pre_calc_units=first_input_units)
File "/mnt/.../lib/python3.9/site-packages/pint/facets/numpy/numpy_func.py", line 111, in convert_to_consistent_units tuple(convert_arg(arg, pre_calc_units=pre_calc_units) for arg in args),
File "/mnt/.../lib/python3.9/site-packages/pint/facets/numpy/numpy_func.py", line 111, in <genexpr> tuple(convert_arg(arg, pre_calc_units=pre_calc_units) for arg in args),
File "/mnt/.../lib/python3.9/site-packages/pint/facets/numpy/numpy_func.py", line 93, in convert_arg raise DimensionalityError("dimensionless", pre_calc_units)
pint.errors.DimensionalityError: Cannot convert from 'dimensionless' to 'meter / second'
</code></pre>
<p>Any help would be appreciated.</p>
<p>(By the way, I looked at the script at <a href="https://github.com/Unidata/python-training/blob/master/pages/gallery/Ageostrophic_Wind_Example.ipynb" rel="nofollow noreferrer">https://github.com/Unidata/python-training/blob/master/pages/gallery/Ageostrophic_Wind_Example.ipynb</a> and did not find it helpful because I'm not sure which of the data manipulations near the top I need to do for the WRF data.)</p>
|
[
{
"answer_id": 74617085,
"author": "DopplerShift",
"author_id": 119314,
"author_profile": "https://Stackoverflow.com/users/119314",
"pm_score": 2,
"selected": false,
"text": "getvar from metpy.units import units\n\ndef metpy_getvar(file, name, units_str):\n return getvar(file, name, units=units_str) * units(units_str)\n\nz = metpy_getvar(ncfile, \"z\", units=\"m\")\nua = metpy_getvar(ncfile, \"ua\", units=\"m s-1\")\nva = metpy_getvar(ncfile, \"va\", units=\"m s-1\")\n"
},
{
"answer_id": 74632434,
"author": "n0rthern.dancer",
"author_id": 5100241,
"author_profile": "https://Stackoverflow.com/users/5100241",
"pm_score": 0,
"selected": false,
"text": "import numpy as np\nfrom netCDF4 import Dataset\nimport metpy.calc as mpcalc\nfrom metpy.units import units\nimport matplotlib.pyplot as plt\nfrom matplotlib.cm import get_cmap\n\nfrom wrf import getvar, interplevel, to_np, get_basemap, latlon_coords\n\n# Open the NetCDF file\nfilename = \"wrfout_d01_2016-10-04_12:00:00\"\nncfile = Dataset(filename)\n\nz = getvar(ncfile, \"z\", units=\"m\") * units.meter\n\n# Smooth height data\nz = mpcalc.smooth_gaussian(z, 3)\n\ndx = 4000.0 * units.meter\ndy = 4000.0 * units.meter\n\nlat = getvar(ncfile, \"lat\") * units.degrees\n\ngeo_wind_u, geo_wind_v = mpcalc.geostrophic_wind(z,dx,dy,lat,x_dim=-2,y_dim=-1)\n\n#####\n\np = getvar(ncfile, \"pressure\")\nz = getvar(ncfile, \"z\", units=\"m\")\n\nht_300 = interplevel(z, p, 300)\n\n#geostrophic wind components on 300 mb level\ngeo_wind_u_300 = interplevel(geo_wind_u, p, 300)\ngeo_wind_v_300 = interplevel(geo_wind_v, p, 300)\n\n# Get the lat/lon coordinates\nlats, lons = latlon_coords(ht_300)\n\n# Get the basemap object\nbm = get_basemap(ht_300)\n\n# Create the figure\nfig = plt.figure(figsize=(12,12))\nax = plt.axes()\n\n# Convert the lat/lon coordinates to x/y coordinates in the projection space\nx, y = bm(to_np(lons), to_np(lats))\n\n# Add the 300 mb height contours\nlevels = np.arange(8640., 9690., 40.)\ncontours = bm.contour(x, y, to_np(ht_300), levels=levels, colors=\"black\")\nplt.clabel(contours, inline=1, fontsize=10, fmt=\"%i\")\n\n# Add the wind contours\nlevels = np.arange(10, 70, 5)\ngeo_u_contours = bm.contourf(x, y, to_np(geo_wind_u_300), levels=levels, cmap=get_cmap(\"YlGnBu\"))\nplt.colorbar(geo_u_contours, ax=ax, orientation=\"horizontal\", pad=.05, shrink=0.75)\n\n# Add the geographic boundaries\nbm.drawcoastlines(linewidth=0.25)\nbm.drawstates(linewidth=0.25)\nbm.drawcountries(linewidth=0.25)\n\nplt.title(\"300 mb height (m) and u-component of geostrophic wind (m s-1) at 1200 UTC on 04-10-2016\", fontsize=12)\n\nplt.savefig('geo_u_300mb_04-10-2016_1200_smoothed.png', bbox_inches='tight')\n"
},
{
"answer_id": 74648232,
"author": "Jon Thielen",
"author_id": 10714117,
"author_profile": "https://Stackoverflow.com/users/10714117",
"pm_score": 0,
"selected": false,
"text": "wrf-python xwrf xwrf import metpy.calc as mpcalc\nimport xarray as xr\nimport xwrf\n\n# Open the NetCDF file\nfilename = \"wrfout_d01_2016-10-04_12:00:00\"\nds = xr.open_dataset(filename).xwrf.postprocess()\n\n# Extract the geopotential height and wind variables\nz = ds['geopotential_height']\nua = ds['wind_east']\nva = ds['wind_north']\n\n# Smooth height data\nz = mpcalc.smooth_gaussian(z, 3)\n\n# Compute the geostrophic wind\ngeo_wind_u, geo_wind_v = mpcalc.geostrophic_wind(z)\n\n# Calculate ageostrophic wind components\nageo_wind_u = ua - geo_wind_u\nageo_wind_v = va - geo_wind_v\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5100241/"
] |
74,615,781
|
<p>Excel coding gurus, can someone help me count in Excel? :) I need a count, based on multiple, dictionaty depandant, conditions.</p>
<p><strong>What I have</strong>:
I have an Excel 2019. Not the 365 edition.
I have an Excel sheet called, say <strong>Dicts</strong> with a table of 2 columns. I is a dictionary. Column <code>I</code> contains list of people. And each person in the <code>I</code> column has the country of his/her origin denoted in the correspondent cell of <code>H</code> column.</p>
<p>For a better view check this picture, plz.</p>
<p><a href="https://i.stack.imgur.com/cSTSd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cSTSd.png" alt="Dictionary of persons with their Country of Origin" /></a></p>
<p>And I have a DataSheet, that contains records of various persons from the dictionary table along wiht some data on each record.
For a better view check this picture, plz.</p>
<p><a href="https://i.stack.imgur.com/K2V61.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K2V61.png" alt="enter image description here" /></a></p>
<p><strong>Now, the question is</strong>:
How can I count the number of all the citizens of USA and Iitaly in the column <code>A</code> that have either <strong>Y</strong> or <strong>M</strong> in the correspondent cell of Column <code>B</code>?</p>
|
[
{
"answer_id": 74629941,
"author": "P.b",
"author_id": 12634230,
"author_profile": "https://Stackoverflow.com/users/12634230",
"pm_score": 1,
"selected": false,
"text": "=LET(condition1,FILTER(A2:A25,MMULT(--({\"Y\",\"M\"}=B2:B25),SEQUENCE(2,,1,0))),\n condition2,FILTER(Table1[C2],MMULT(--({\"USA\",\"Irtaly\"}=Table1[C1]),SEQUENCE(2,,1,0))),\nSUM(--(TRANSPOSE(condition1)=condition2)))\n =SUM(\n --(TRANSPOSE(INDEX(Table1[C2],\n AGGREGATE(15,6,ROW(Table1[C1])-1/(MMULT((--(Table1[C1]={\"USA\",\"Irtaly\"})),ROW(1:2)^0)),\n ROW(A1:INDEX(A:A,SUMPRODUCT(--({\"USA\",\"Irtaly\"}=Table1[C1])))))))\n =INDEX(A2:A25,\n AGGREGATE(15,6,ROW(A2:A25)-1/(MMULT((--(B2:B25={\"Y\",\"M\"})),ROW(1:2)^0)),\n ROW(A1:INDEX(A:A,SUMPRODUCT(--({\"Y\",\"M\"}=B2:B25))))))))\n ctrl+shift+enter"
},
{
"answer_id": 74630249,
"author": "Dominique",
"author_id": 4279155,
"author_profile": "https://Stackoverflow.com/users/4279155",
"pm_score": 0,
"selected": false,
"text": "COUNTIFS() =COUNT_Multiple_Criteria(range,country=\"USA\", done=\"Y\") + \n COUNT_Multiple_Criteria(range,country=\"USA\", done=\"M\") + \n COUNT_Multiple_Criteria(range,country=\"Italy\", done=\"Y\") +\n COUNT_Multiple_Criteria(range,country=\"Italy\", done=\"M\")\n"
},
{
"answer_id": 74633859,
"author": "David Leal",
"author_id": 6237093,
"author_profile": "https://Stackoverflow.com/users/6237093",
"pm_score": 0,
"selected": false,
"text": "H4 =SUMPRODUCT(\n N(ISNUMBER(MATCH(INDEX(A3:A8, MATCH(D3:D7, B3:B8,0)), H2:I2,0))),\n N(ISNUMBER(MATCH(E3:E7,H3:I3,0)))\n)\n MMULT SUMPRODUCT LET =LET(lkUpC, H2:I2, lkupD, H3:J3, countries, INDEX(A3:A8, MATCH(D3:D7, B3:B8,0)),\n cCnts, N(ISNUMBER(MATCH(countries, lkUpC,0))),\n dCnts, N(ISNUMBER(MATCH(E3:E7,lkupD,0))),\n SUMPRODUCT(cCnts, dCnts)\n)\n countries cCnts countries 1 LkUpC 0 dCnts lkUpD SUMPRODUCT D E"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11764603/"
] |
74,615,795
|
<p>My code is :</p>
<pre><code>#!/bin/bash
strversion=`apache2ctl -v | awk '{print $3}' | sed 's/(Debian)//g;s/Server//g;s/built//g;s/2022-06-09T04:26:43//g'`
echo ${strversion%}
exit 0
</code></pre>
<p>i get this:</p>
<pre><code>Apache/2.4.54
</code></pre>
<p>but i will have to look</p>
<pre><code>Apache version 2.4.54
</code></pre>
|
[
{
"answer_id": 74615922,
"author": "glenn jackman",
"author_id": 7552,
"author_profile": "https://Stackoverflow.com/users/7552",
"pm_score": 1,
"selected": false,
"text": "echo \"Apache2 - ${strversion%')'}\"\n# ...^...........................^\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20634538/"
] |
74,615,797
|
<p>Let's say I have the following <code>pd.DataFrame</code></p>
<pre><code>>>> df = pd.DataFrame({
'col_1': ['Elon', 'Jeff', 'Warren', 'Mark'],
'col_2': ['nan', 'Bezos', 'Buffet', 'nan'],
'col_3': ['nan', 'Amazon', 'Berkshire', 'Meta'],
})
</code></pre>
<p>which gets me</p>
<pre><code> col_1 col_2 col_3
0 Elon nan nan
1 Jeff Bezos Amazon
2 Warren Buffet Berkshire
3 Mark nan Meta
</code></pre>
<p>All column types are strings. I would like a way to obtain the number of rows per column where the cell value is <code>'nan'</code>.</p>
<p>Where I simply run the following I get always zeros as missing count since it doesnt check for string which contain nan.</p>
<pre><code>>>> df.isna().sum()
col_1 0
col_2 0
col_3 0
dtype: int64
</code></pre>
<p>However, what I want is to get</p>
<pre><code>col_1 0
col_2 2
col_3 1
</code></pre>
<p>How can I do that?</p>
|
[
{
"answer_id": 74615909,
"author": "eshirvana",
"author_id": 1367454,
"author_profile": "https://Stackoverflow.com/users/1367454",
"pm_score": 3,
"selected": true,
"text": "nan df.eq(\"nan\").sum()\n col_1 0\ncol_2 2\ncol_3 1\ndtype: int64\n"
},
{
"answer_id": 74616009,
"author": "DarknessPlusPlus",
"author_id": 8972207,
"author_profile": "https://Stackoverflow.com/users/8972207",
"pm_score": 0,
"selected": false,
"text": "'nan' mask = np.column_stack([df[col].str.contains(\"nan\", na = False) for col in df])\ndf_new = df.loc[mask.any(axis = 1)]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12052180/"
] |
74,615,812
|
<p>I have the following lines of code:</p>
<pre><code>ROUND((((SUM(VALOR_2)) - SQLTMP.VALOR_1) / SQLTMP.VALOR_1) * 100, 2)
</code></pre>
<p>I was hoping it would return a percentage, but it returns an ERROR instead... Any ideas on what's wrong?</p>
|
[
{
"answer_id": 74615909,
"author": "eshirvana",
"author_id": 1367454,
"author_profile": "https://Stackoverflow.com/users/1367454",
"pm_score": 3,
"selected": true,
"text": "nan df.eq(\"nan\").sum()\n col_1 0\ncol_2 2\ncol_3 1\ndtype: int64\n"
},
{
"answer_id": 74616009,
"author": "DarknessPlusPlus",
"author_id": 8972207,
"author_profile": "https://Stackoverflow.com/users/8972207",
"pm_score": 0,
"selected": false,
"text": "'nan' mask = np.column_stack([df[col].str.contains(\"nan\", na = False) for col in df])\ndf_new = df.loc[mask.any(axis = 1)]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5887716/"
] |
74,615,819
|
<p>I have a simple .NET 6 class library <code>FooBarService.Contracts</code> that contains only one DTO class <code>FooBarRequest</code>. I want that to be available to my team in our Azure Artifacts Feed as a NuGet package.</p>
<pre><code>namespace FooBarService.Contracts.Requests;
public class FooBarRequest
{
public string Id { get; set; }
public FooBarRequest(string id)
{
Id= id;
}
}
</code></pre>
<p>The <code>azure-pipeline.yml</code> has a stage for packing and pushing the aforementioned class library as a nuget package. I removed the irrelevant parts of the file. Update: it is the nuget push task that fails, the nuget pack task works.</p>
<pre><code>pool:
vmImage: ubuntu-latest
name: 1.0.0.0
- stage: nuget_stage
jobs:
- job: 'build_push_job'
steps:
- task: UseDotNet@2
displayName: Use .NET 6.0
inputs:
packageType: 'sdk'
version: '6.0.x'
- task: DotNetCoreCLI@2
inputs:
command: 'pack'
packagesToPack: '**/FooBarService.Contracts.csproj'
versioningScheme: 'byBuildNumber'
- task: DotNetCoreCLI@2
inputs:
command: 'push'
packagesToPush: '$(Build.ArtifactStagingDirectory)/*.nupkg'
nuGetFeedType: 'internal'
publishVstsFeed: 'REDACTED_FOR_PRIVACY_REASONS/REDACTED_FOR_PRIVACY_REASONS'
</code></pre>
<p>All other stages are executing as planned, but this <code>nuget_stage</code> fails with the following error:</p>
<pre><code>##[error]Error: The process '/usr/bin/dotnet' failed with exit code 1
##[error]Packages failed to publish
Info: Azure Pipelines hosted agents have been updated and now contain .Net 5.x SDK/Runtime along with the older .Net Core version which are currently lts. Unless you have locked down a SDK version for your project(s), 5.x SDK might be picked up which might have breaking behavior as compared to previous versions. You can learn more about the breaking changes here: https://docs.microsoft.com/en-us/dotnet/core/tools/ and https://docs.microsoft.com/en-us/dotnet/core/compatibility/ . To learn about more such changes and troubleshoot, refer here: https://docs.microsoft.com/en-us/azure/devops/pipelines/tasks/build/dotnet-core-cli?view=azure-devops#troubleshooting
</code></pre>
<p><strong>EDIT</strong></p>
<p>I added the the task with <code>Use .NET 6.0</code> as suggested by @Maytham Fahmi and I'm still getting the same error.</p>
<p>The <code>FooBarService.Contracts.csproj</code> file says</p>
<pre><code><Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Title>FooBarService.Contracts</Title>
<Authors />
<LangVersion>10</LangVersion>
</PropertyGroup>
</Project>
</code></pre>
|
[
{
"answer_id": 74615909,
"author": "eshirvana",
"author_id": 1367454,
"author_profile": "https://Stackoverflow.com/users/1367454",
"pm_score": 3,
"selected": true,
"text": "nan df.eq(\"nan\").sum()\n col_1 0\ncol_2 2\ncol_3 1\ndtype: int64\n"
},
{
"answer_id": 74616009,
"author": "DarknessPlusPlus",
"author_id": 8972207,
"author_profile": "https://Stackoverflow.com/users/8972207",
"pm_score": 0,
"selected": false,
"text": "'nan' mask = np.column_stack([df[col].str.contains(\"nan\", na = False) for col in df])\ndf_new = df.loc[mask.any(axis = 1)]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3561837/"
] |
74,615,875
|
<p>I want the redirect back to home if the params are not passed with the url.
How can I achieve this?
I tried something like this, but it`s not working:</p>
<pre><code>export default function Summary() {
const { id } = useParams();
const navigate = useNavigate();
if (!id) {
navigate("/home");
}
</code></pre>
<p>Thanks in advance</p>
|
[
{
"answer_id": 74615909,
"author": "eshirvana",
"author_id": 1367454,
"author_profile": "https://Stackoverflow.com/users/1367454",
"pm_score": 3,
"selected": true,
"text": "nan df.eq(\"nan\").sum()\n col_1 0\ncol_2 2\ncol_3 1\ndtype: int64\n"
},
{
"answer_id": 74616009,
"author": "DarknessPlusPlus",
"author_id": 8972207,
"author_profile": "https://Stackoverflow.com/users/8972207",
"pm_score": 0,
"selected": false,
"text": "'nan' mask = np.column_stack([df[col].str.contains(\"nan\", na = False) for col in df])\ndf_new = df.loc[mask.any(axis = 1)]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18151453/"
] |
74,615,882
|
<p>I want to create multiple <code>aws_iam_policy_document</code> resources with <code>for_each</code>, to be later assumed by several roles, as follows:</p>
<pre><code># Policy to allow services to assume the role
data "aws_iam_policy_document" "this" {
for_each = var.lambda_configuration
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = [
"lambda.amazonaws.com",
"apigateway.amazonaws.com",
]
}
}
}
# IAM role for executing the Lambda function
resource "aws_iam_role" "this" {
for_each = var.lambda_configuration
name = "my_lambda_${each.key}_Executor_Role"
description = "Role for executing my_lambda-${each.key} function"
assume_role_policy = data.aws_iam_policy_document.assume_role_policy_[each.key].json
}
</code></pre>
<p>How should I interpolate this</p>
<pre><code>assume_role_policy = data.aws_iam_policy_document.assume_role_policy_[each.key].json
</code></pre>
<p>to make the correct matching with the roles?</p>
|
[
{
"answer_id": 74615975,
"author": "Mark B",
"author_id": 13070,
"author_profile": "https://Stackoverflow.com/users/13070",
"pm_score": 2,
"selected": true,
"text": "data.aws_iam_policy_document.this[each.key].json\n assume_role_policy_"
},
{
"answer_id": 74633903,
"author": "Martin Atkins",
"author_id": 281848,
"author_profile": "https://Stackoverflow.com/users/281848",
"pm_score": 0,
"selected": false,
"text": "for_each data \"aws_iam_policy_document\" \"this\" {\n for_each = var.lambda_configuration\n\n statement {\n actions = [\"sts:AssumeRole\"]\n\n principals {\n type = \"Service\"\n\n identifiers = [\n \"lambda.amazonaws.com\",\n \"apigateway.amazonaws.com\",\n ]\n }\n }\n}\n\n# IAM role for executing the Lambda function\nresource \"aws_iam_role\" \"this\" {\n for_each = data.aws_iam_policy_document.this\n\n name = \"my_lambda_${each.key}_Executor_Role\"\n description = \"Role for executing my_lambda-${each.key} function\"\n assume_role_policy = each.value.json\n}\n for_each for_each for_each each.value data.aws_iam_policy_document.this each.key"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2409793/"
] |
74,615,885
|
<p>I'm trying to learn OOP but my pygame window wont update with the background I'm trying to put in. The gameObject class is in another file. Filling it with white color also isn't working and I don't know why. I was able to display a background on another project I did but I cant now and I have no idea what's different. I have compared the code and they seem like they should be doing the same thing.</p>
<p>gameObject.py</p>
<pre><code>import pygame
class GameObject:
def __init__(self, x, y, width, height, image_path):
self.background= pygame.image.load(image_path)
self.background = pygame.transform.scale(self.background, (width, height))
self.x = x
self.y = y
self.width = width
self.height = height
</code></pre>
<p>main.py</p>
<pre><code>import pygame
from gameObject import GameObject
pygame.init()
class Player(GameObject):
def __init__(self, x, y, width, height, image_path, speed):
super().__init__(x, y, width, height, image_path)
self.speed = speed
def move(self, direction, max_height):
if (self.y >= max_height - self.height and direction > 0) or (self.y <= 0 and direction < 0):
return
self.y += (direction * self.speed)
class Game:
def __init__(self):
self.width = 800
self.height = 800
self.color = (255, 255, 255)
self.game_window = pygame.display.set_mode((self.width, self.height))
self.clock = pygame.time.Clock()
self.background = GameObject(0, 0, self.width, self.height, 'assets/background.png')
self.player1 = Player(375, 700, 50, 50, 'assets/player.png', 10)
self.level = 1.0
def draw_objects(self):
self.game_window.fill(self.white_color)
self.game_window.blit(self.background.image, (self.background.x, self.background.y))
pygame.display.update()
def run_game_loop(self):
gameRunning = True
while gameRunning:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameRunning = False
if gameRunning == False:
pygame.quit()
self.draw_objects()
self.clock.tick(60)
game = Game()
game.run_game_loop()
quit()
</code></pre>
<p>I have tried basic research on it and looking at other code that uses a custom background with pygame</p>
|
[
{
"answer_id": 74616340,
"author": "Rabbid76",
"author_id": 5577765,
"author_profile": "https://Stackoverflow.com/users/5577765",
"pm_score": 2,
"selected": true,
"text": "self.draw_objects() class Game:\n # [...]\n\n def run_game_loop(self):\n\n gameRunning = True\n while gameRunning:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n gameRunning = False\n if gameRunning == False:\n pygame.quit()\n\n # INDENTATION\n #-->|\n \n self.draw_objects()\n self.clock.tick(60)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20634555/"
] |
74,615,900
|
<p>I am learning spring boot but in the part of creating the models for the creation in mysql, but I need the id field to be auto-incremental, does anyone know how I can do it?</p>
<p>`</p>
<pre><code>package com.pruebas.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Persona {
@Id
private Integer id;
@Column
private String title;
@Column
private String description;
//Getter and setter
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
</code></pre>
<p>`</p>
<p>I was looking for some property and I even put in the part of id AUTO_INCREMENT how the query would be done in MySql</p>
|
[
{
"answer_id": 74616340,
"author": "Rabbid76",
"author_id": 5577765,
"author_profile": "https://Stackoverflow.com/users/5577765",
"pm_score": 2,
"selected": true,
"text": "self.draw_objects() class Game:\n # [...]\n\n def run_game_loop(self):\n\n gameRunning = True\n while gameRunning:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n gameRunning = False\n if gameRunning == False:\n pygame.quit()\n\n # INDENTATION\n #-->|\n \n self.draw_objects()\n self.clock.tick(60)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19940897/"
] |
74,615,905
|
<p>I'm a Python beginner and would like to learn how to use it for operations on text files. I have an input txt file of 4 columns separated by TAB, and I want to search whether, row by row, the cell pairs in columns 1 and 4 simultaneously contain the pattern "BBB" or "CCC". If true, send the whole line to output1. If false, send the whole line to output2.</p>
<p>This is the input.txt:</p>
<pre><code>
more input.txt
AABBBAA 2 5 AACCCAA
AAAAAAA 4 10 AAAAAAA
AABBBAA 6 15 AABBBAA
AAAAAAA 8 20 AAAAAAA
AACCCAA 10 25 AACCCAA
AAAAAAA 12 30 AAAAAAA
</code></pre>
<p>This is the Python code I wrote:</p>
<pre><code>more main.py
</code></pre>
<pre><code>import sys
input = open(sys.argv[1], "r")
output1 = open(sys.argv[2], "w")
output2 = open(sys.argv[3], "w")
list = ["BBB", "CCC"]
for line in input:
for item in list:
if item in line.split("\t")[0] and item in line.split("\t")[3]:
output1.write(line)
else:
output2.write(line)
input.close()
output1.close()
output2.close()
</code></pre>
<p>Command:</p>
<pre><code>python main.py input.txt output1.txt output2.txt
</code></pre>
<p>output1.txt is correct</p>
<pre><code>more output1.txt
</code></pre>
<pre><code>AABBBAA 6 15 AABBBAA
AACCCAA 10 25 AACCCAA
</code></pre>
<p>output2 is incorrect. I'm trying to understand why it takes both the lines of output1.txt and the double copy of the other lines.</p>
<pre><code>more output2.txt
</code></pre>
<pre><code>AABBBAA 2 5 AACCCAA
AABBBAA 2 5 AACCCAA
AAAAAAA 4 10 AAAAAAA
AAAAAAA 4 10 AAAAAAA
AABBBAA 6 15 AABBBAA
AAAAAAA 8 20 AAAAAAA
AAAAAAA 8 20 AAAAAAA
AACCCAA 10 25 AACCCAA
AAAAAAA 12 30 AAAAAAA
AAAAAAA 12 30 AAAAAAA
</code></pre>
<p>output2.txt should be:</p>
<pre><code>AABBBAA 2 5 AACCCAA
AAAAAAA 4 10 AAAAAAA
AAAAAAA 8 20 AAAAAAA
AAAAAAA 12 30 AAAAAAA
</code></pre>
<p>Thank you for your help!</p>
|
[
{
"answer_id": 74616081,
"author": "Pranav Hosangadi",
"author_id": 843953,
"author_profile": "https://Stackoverflow.com/users/843953",
"pm_score": 3,
"selected": true,
"text": "output2 item output1 output2 item list list output2 output2 any list for item in lst item in cols[0] and item in cols[3] lst = [\"BBB\", \"CCC\"]\nfor line in input_file:\n cols = line.split(\"\\t\")\n if any(item in cols[0] and item in cols[3] for item in lst):\n output1.write(line)\n else:\n output2.write(line)\n list lst input input_file"
},
{
"answer_id": 74616445,
"author": "SgtSafety",
"author_id": 5075574,
"author_profile": "https://Stackoverflow.com/users/5075574",
"pm_score": 0,
"selected": false,
"text": "else if if True"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8049502/"
] |
74,615,925
|
<p>I done <code>npm update</code> and broke start project. Using <code>npm run start</code> returns an error:</p>
<pre><code>10% building 0/1 entries 0/0 dependencies 0/0 modulesnode:internal/errors:484
ErrorCaptureStackTrace(err);
^
Error: EMFILE: too many open files, watch
at FSWatcher._handle.onchange (node:internal/fs/watchers:204:21)
Emitted 'error' event on FSWatcher instance at:
at FSWatcher._handleError (/Users/199/WebstormProjects/isu_frontend_common/node_modules/chokidar/index.js:647:10)
at NodeFsHandler._boundHandleError (/Users/199/WebstormProjects/isu_frontend_common/node_modules/chokidar/lib/nodefs-handler.js:303:43)
at /Users/199/WebstormProjects/isu_frontend_common/node_modules/chokidar/lib/nodefs-handler.js:137:5
at foreach (/Users/199/WebstormProjects/isu_frontend_common/node_modules/chokidar/lib/nodefs-handler.js:41:5)
at fsWatchBroadcast (/Users/199/WebstormProjects/isu_frontend_common/node_modules/chokidar/lib/nodefs-handler.js:136:3)
at FSWatcher.<anonymous> (/Users/199/WebstormProjects/isu_frontend_common/node_modules/chokidar/lib/nodefs-handler.js:185:9)
at FSWatcher.emit (node:events:513:28)
at FSWatcher._handle.onchange (node:internal/fs/watchers:210:12) {
errno: -24,
syscall: 'watch',
code: 'EMFILE',
filename: null
}
Node.js v18.12.1
node:internal/process/promises:288
triggerUncaughtException(err, true /* fromPromise */);
^
RpcIpcMessagePortClosedError: Cannot send the message - the message port has been closed for the process 17332.
</code></pre>
<p>I've already tried:</p>
<ul>
<li>Removing <code>node_modules</code> and <code>package-lock.json</code>, <code>clean cache</code> and <code>npm install</code></li>
<li>Switch Node.js and NPM versions to lastest stable</li>
<li>Installing the project again in another folder</li>
</ul>
<p>But it didn't help me. What else can I do?</p>
|
[
{
"answer_id": 74616081,
"author": "Pranav Hosangadi",
"author_id": 843953,
"author_profile": "https://Stackoverflow.com/users/843953",
"pm_score": 3,
"selected": true,
"text": "output2 item output1 output2 item list list output2 output2 any list for item in lst item in cols[0] and item in cols[3] lst = [\"BBB\", \"CCC\"]\nfor line in input_file:\n cols = line.split(\"\\t\")\n if any(item in cols[0] and item in cols[3] for item in lst):\n output1.write(line)\n else:\n output2.write(line)\n list lst input input_file"
},
{
"answer_id": 74616445,
"author": "SgtSafety",
"author_id": 5075574,
"author_profile": "https://Stackoverflow.com/users/5075574",
"pm_score": 0,
"selected": false,
"text": "else if if True"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13626719/"
] |
74,615,952
|
<p>I want to sort a character variable into two categories in a new variable based on conditions, in conditions are not met i want it to return "other".</p>
<p>If variable x cointains 4 character values "A", "B", "C" & "D" I want to sort them into a 2 categories, 1 and 0, in a new variable y, creating a dummy variable</p>
<p>Ideally I want it to look like this</p>
<pre><code>df <- data.frame(x = c("A", "B", "C" & "D")
y <- if x == "A" | "D" then assign 1 in y
if x == "B" | "C" then assign 0 in y
if x == other then assign NA in y
x y
1 "A" 1
2 "B" 0
3 "C" 0
4 "D" 1
library(dplyr)
df <- df %>% mutate ( y =case_when(
(x %in% df == "A" | "D") ~ 1 ,
(x %in% df == "B" | "C") ~ 1,
x %in% df == ~ NA
))
</code></pre>
<p>I got this error message</p>
<pre><code>Error: replacement has 3 rows, data has 2
</code></pre>
|
[
{
"answer_id": 74616128,
"author": "Aron Strandberg",
"author_id": 4885169,
"author_profile": "https://Stackoverflow.com/users/4885169",
"pm_score": 3,
"selected": true,
"text": "case_when df <- data.frame(x = c(\"A\", \"B\", \"C\", \"D\"))\n \nlibrary(dplyr)\n\ndf <- df %>%\n mutate(y = case_when(x %in% c(\"A\", \"D\") ~ 1,\n x %in% c(\"B\", \"C\") ~ 0,\n TRUE ~ NA_real_))\ndf\n#> x y\n#> 1 A 1\n#> 2 B 0\n#> 3 C 0\n#> 4 D 1\n"
},
{
"answer_id": 74616155,
"author": "Gregor Thomas",
"author_id": 903061,
"author_profile": "https://Stackoverflow.com/users/903061",
"pm_score": 1,
"selected": false,
"text": "foo == \"G\" | \"H\" foo == \"G\" | foo == \"H\" foo %in% c(\"G\", \"H\") x %in% df == \"A\" x %in% df df == \"A\" x %in% df == ... x %in% df result result == \"A\" dplyr mutate df df x x %in% df x df x %in% c(\"A\", \"D\")"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20454178/"
] |
74,615,981
|
<p>Tallying which color has a greater value in each array element for data. Then push the higher valued color into an empty object, and/or increment that color by 1. Lastly sort the totals object highest to lowest in terms of the totals property values and return highest valued color</p>
<p>Struggling with how to map over this structure array since property keys are not uniform. Should I destructure it?</p>
<p>*I can redesign data structure as needed, and if it's easier to solve with a different design, please let me know!</p>
<pre><code>data = [
{ orange: 4, green: 4},
{ green: 0, yellow: 0},
{ yellow: 1, orange: 4 },
{ blue: 2, green: 1 },
{ blue: 2, yellow: 1 },
{ green: 3, yellow: 2 },
{ green: 1, blue: 3},
{ green: 5, yellow: 2 },
]
```
```
totals = {
blue: 3,
green: 2,
orange: 1,
}
```
solution:
```
highValueColor = blue
```
// PSEUDOCODE
//map over the array => data.map()
//identify highest value between two elements => propA - propB
//check to see if the color's (key) in the element has already been added to totals object
//IF the key does not yet exist, create a property in the tally object with the color(key) and set its value to 1
//IF the key is already listed in tally object, increment its property value by 1 => ++
//sort totals object => Math.max()
//return highest value color
`
</code></pre>
|
[
{
"answer_id": 74616128,
"author": "Aron Strandberg",
"author_id": 4885169,
"author_profile": "https://Stackoverflow.com/users/4885169",
"pm_score": 3,
"selected": true,
"text": "case_when df <- data.frame(x = c(\"A\", \"B\", \"C\", \"D\"))\n \nlibrary(dplyr)\n\ndf <- df %>%\n mutate(y = case_when(x %in% c(\"A\", \"D\") ~ 1,\n x %in% c(\"B\", \"C\") ~ 0,\n TRUE ~ NA_real_))\ndf\n#> x y\n#> 1 A 1\n#> 2 B 0\n#> 3 C 0\n#> 4 D 1\n"
},
{
"answer_id": 74616155,
"author": "Gregor Thomas",
"author_id": 903061,
"author_profile": "https://Stackoverflow.com/users/903061",
"pm_score": 1,
"selected": false,
"text": "foo == \"G\" | \"H\" foo == \"G\" | foo == \"H\" foo %in% c(\"G\", \"H\") x %in% df == \"A\" x %in% df df == \"A\" x %in% df == ... x %in% df result result == \"A\" dplyr mutate df df x x %in% df x df x %in% c(\"A\", \"D\")"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20606743/"
] |
74,615,995
|
<p>Struggling with a large dataset in my mariaDB database. I have two tables, where table A contains 57 million rows and table B contains around 500. Table B is a subset of ids related to a column in table A. I want to delete all rows from A which do not have a corresponding ID in table B.</p>
<p>Example table A:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>classification_id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>20</td>
<td>Mercedes</td>
</tr>
<tr>
<td>30</td>
<td>Kawasaki</td>
</tr>
<tr>
<td>80</td>
<td>Leitz</td>
</tr>
<tr>
<td>70</td>
<td>HP</td>
</tr>
</tbody>
</table>
</div>
<p>Example table B:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>classification_id</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>20</td>
<td>car</td>
</tr>
<tr>
<td>30</td>
<td>bike</td>
</tr>
<tr>
<td>40</td>
<td>bus</td>
</tr>
<tr>
<td>50</td>
<td>boat</td>
</tr>
</tbody>
</table>
</div>
<p>So in this example the last two rows from table A would be deleted (or a mirror table would be made containing only the first two rows, thats also fine).</p>
<p>I tried to do the second one using an inner join but this query took a few minutes before giving an out of memory exception.</p>
<p>Any suggestions on how to tackle this?</p>
|
[
{
"answer_id": 74616128,
"author": "Aron Strandberg",
"author_id": 4885169,
"author_profile": "https://Stackoverflow.com/users/4885169",
"pm_score": 3,
"selected": true,
"text": "case_when df <- data.frame(x = c(\"A\", \"B\", \"C\", \"D\"))\n \nlibrary(dplyr)\n\ndf <- df %>%\n mutate(y = case_when(x %in% c(\"A\", \"D\") ~ 1,\n x %in% c(\"B\", \"C\") ~ 0,\n TRUE ~ NA_real_))\ndf\n#> x y\n#> 1 A 1\n#> 2 B 0\n#> 3 C 0\n#> 4 D 1\n"
},
{
"answer_id": 74616155,
"author": "Gregor Thomas",
"author_id": 903061,
"author_profile": "https://Stackoverflow.com/users/903061",
"pm_score": 1,
"selected": false,
"text": "foo == \"G\" | \"H\" foo == \"G\" | foo == \"H\" foo %in% c(\"G\", \"H\") x %in% df == \"A\" x %in% df df == \"A\" x %in% df == ... x %in% df result result == \"A\" dplyr mutate df df x x %in% df x df x %in% c(\"A\", \"D\")"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74615995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11775623/"
] |
74,616,016
|
<p>How do I add a string/integer into an existing text file at a specific location?<br />
My sample text looks like below:</p>
<pre class="lang-txt prettyprint-override"><code>No, Color, Height, age
1, blue,70,
2, white,65,
3, brown,49,
4, purple,71,
5, grey,60,
</code></pre>
<p>My text file has 4 columns, three columns have text, how do I write to any row in the fourth column?<br />
If I want to write 12 to the second row, the updated file (sample.txt) should look like this:</p>
<pre class="lang-txt prettyprint-override"><code>No, Color, Height, age
1, blue,70,12
2, white,65,
3, brown,49,
4, purple,71,
5, grey,60,
</code></pre>
<p>I have tried this:</p>
<pre class="lang-py prettyprint-override"><code>with open("sample.txt",'r') as file:
data =file.readlines()
data[1]. split(",") [3] = 1
with open ('sample.txt', 'w') as file:
file.writelines(data)
with open ('sample.txt', 'r') as file:
print (file. Read())
</code></pre>
<p>But it does not work. Your help is needed.</p>
|
[
{
"answer_id": 74616128,
"author": "Aron Strandberg",
"author_id": 4885169,
"author_profile": "https://Stackoverflow.com/users/4885169",
"pm_score": 3,
"selected": true,
"text": "case_when df <- data.frame(x = c(\"A\", \"B\", \"C\", \"D\"))\n \nlibrary(dplyr)\n\ndf <- df %>%\n mutate(y = case_when(x %in% c(\"A\", \"D\") ~ 1,\n x %in% c(\"B\", \"C\") ~ 0,\n TRUE ~ NA_real_))\ndf\n#> x y\n#> 1 A 1\n#> 2 B 0\n#> 3 C 0\n#> 4 D 1\n"
},
{
"answer_id": 74616155,
"author": "Gregor Thomas",
"author_id": 903061,
"author_profile": "https://Stackoverflow.com/users/903061",
"pm_score": 1,
"selected": false,
"text": "foo == \"G\" | \"H\" foo == \"G\" | foo == \"H\" foo %in% c(\"G\", \"H\") x %in% df == \"A\" x %in% df df == \"A\" x %in% df == ... x %in% df result result == \"A\" dplyr mutate df df x x %in% df x df x %in% c(\"A\", \"D\")"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5255512/"
] |
74,616,025
|
<p>I'm trying to improve the following method:</p>
<pre class="lang-rust prettyprint-override"><code>let output: Vec<i32> = stream::iter(vec![1, 2, 3])
.then(|val| {
future::ok::<_, ()>(vec![val * 10, val * 10 + 1])
})
.try_collect::<Vec<Vec<_>>>()
.await?
.into_iter()
.flatten() // How to flatten directly from the stream?
.collect();
assert_eq!(output, vec![10, 11, 20, 21, 30, 31]);
</code></pre>
<p>This method works but I think this could be improved because, as you can see, I need to collect two times in order to have the output I want.</p>
<p>This issue comes from the fact that I'm trying to flatten <code>Result</code>s that contain a list. I tried to use <code>try_flatten()</code> however I absolutely can't make it work. Does anybody have an idea on how to achieve this?</p>
|
[
{
"answer_id": 74616128,
"author": "Aron Strandberg",
"author_id": 4885169,
"author_profile": "https://Stackoverflow.com/users/4885169",
"pm_score": 3,
"selected": true,
"text": "case_when df <- data.frame(x = c(\"A\", \"B\", \"C\", \"D\"))\n \nlibrary(dplyr)\n\ndf <- df %>%\n mutate(y = case_when(x %in% c(\"A\", \"D\") ~ 1,\n x %in% c(\"B\", \"C\") ~ 0,\n TRUE ~ NA_real_))\ndf\n#> x y\n#> 1 A 1\n#> 2 B 0\n#> 3 C 0\n#> 4 D 1\n"
},
{
"answer_id": 74616155,
"author": "Gregor Thomas",
"author_id": 903061,
"author_profile": "https://Stackoverflow.com/users/903061",
"pm_score": 1,
"selected": false,
"text": "foo == \"G\" | \"H\" foo == \"G\" | foo == \"H\" foo %in% c(\"G\", \"H\") x %in% df == \"A\" x %in% df df == \"A\" x %in% df == ... x %in% df result result == \"A\" dplyr mutate df df x x %in% df x df x %in% c(\"A\", \"D\")"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/553488/"
] |
74,616,055
|
<p>Compiling this C code:</p>
<pre><code>#include <stdio.h>
const char code[] __attribute__((section(".mySection"))) = "\xb8\x0d\x00\x00\x00\xc3";
int main(int argc, char **argv)
{
int val = ((int(*)(void))code)();
printf("val %d\n", val);
}
</code></pre>
<p>together with this ld script:</p>
<pre><code>MEMORY
{
my_region (RWX) : ORIGIN = 0x405340, LENGTH = 4K
}
SECTIONS
{
.mySegment 0x405340 : {KEEP(*(.mySection))} > my_region
}
</code></pre>
<p>as:</p>
<pre><code>gcc link.ld t79.c
</code></pre>
<p>leads to:</p>
<pre><code>/usr/bin/ld: warning: link.ld contains output sections; did you forget -T?
/usr/bin/ld: internal error ../../ld/ldlang.c 6101
collect2: error: ld returned 1 exit status
</code></pre>
<p>Why? How to fix?</p>
<pre><code>ld version: 2.34
gcc version: 9.4.0
uname -a:
Linux xxx 5.15.0-25-generic #25~20.04.2-Ubuntu SMP Mon Apr 11 08:31:42 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
</code></pre>
<p>UPD: the <code>internal error ../../ld/ldlang.c 6101</code> comes from here (function <code>lang_size_relro_segment_1</code>):</p>
<pre><code>ASSERT (desired_end >= seg->base);
</code></pre>
|
[
{
"answer_id": 74616128,
"author": "Aron Strandberg",
"author_id": 4885169,
"author_profile": "https://Stackoverflow.com/users/4885169",
"pm_score": 3,
"selected": true,
"text": "case_when df <- data.frame(x = c(\"A\", \"B\", \"C\", \"D\"))\n \nlibrary(dplyr)\n\ndf <- df %>%\n mutate(y = case_when(x %in% c(\"A\", \"D\") ~ 1,\n x %in% c(\"B\", \"C\") ~ 0,\n TRUE ~ NA_real_))\ndf\n#> x y\n#> 1 A 1\n#> 2 B 0\n#> 3 C 0\n#> 4 D 1\n"
},
{
"answer_id": 74616155,
"author": "Gregor Thomas",
"author_id": 903061,
"author_profile": "https://Stackoverflow.com/users/903061",
"pm_score": 1,
"selected": false,
"text": "foo == \"G\" | \"H\" foo == \"G\" | foo == \"H\" foo %in% c(\"G\", \"H\") x %in% df == \"A\" x %in% df df == \"A\" x %in% df == ... x %in% df result result == \"A\" dplyr mutate df df x x %in% df x df x %in% c(\"A\", \"D\")"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1778275/"
] |
74,616,062
|
<p>I have a decorator that is supposed to use a parameter that's passed in from the commandline e.g</p>
<pre><code>@deco(name)
def handle(self, *_args, **options):
name = options["name"]
</code></pre>
<pre><code>def deco(name):
// The name should come from commandline
pass
</code></pre>
<pre><code>class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--name",
type=str,
required=True,
)
@deco(//How can I pass the name here?)
def handle(self, *_args, **options):
name = options["name"]
</code></pre>
<p>any suggestions on this?</p>
|
[
{
"answer_id": 74616131,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 3,
"selected": true,
"text": "from functool import wraps\n\ndef metadeco(function):\n @wraps(function)\n def func(*args, **kwargs):\n name = kwargs['name']\n return deco(name)(function)(*args, **kwargs)\n return func\n class Command(BaseCommand):\n def add_arguments(self, parser):\n parser.add_argument(\n \"--name\",\n type=str,\n required=True,\n )\n \n @metadeco\n def handle(self, *_args, **options):\n name = options['name']\n # …"
},
{
"answer_id": 74616219,
"author": "Martijn Pieters",
"author_id": 100297,
"author_profile": "https://Stackoverflow.com/users/100297",
"pm_score": 2,
"selected": false,
"text": "@deco @decorator def functionname deco from functools import wraps\n\ndef apply_deco_from_name(f):\n @wraps(f)\n def wrapper(self, *args, **options):\n # this code is called instead of the decorated method\n # and *now* we have access to the options mapping.\n name = options[\"name\"] # or use options.pop(\"name\") to remove it\n decorated = deco(name)(f) # the same thing as @deco(name) for the function\n return decorated(self, *args, **options)\n \n return wrapper\n class Command(BaseCommand):\n def add_arguments(self, parser):\n parser.add_argument(\n \"--name\",\n type=str,\n required=True,\n )\n\n @apply_deco_from_name\n def handle(self, *_args, **options):\n name = options[\"name\"]\n @apply_deco_from_name def handle(...) handle apply_deco_from_name(handle) wrapper wrapper(command, [other arguments], name=\"command-line-value-for-name\", [other options]) decorated = deco(\"command-line-value-for-name\")(f) @deco(\"command-line-value-for-name\") deco(\"command-line-value-for-name\") deco(\"command-line-value-for-name\")(f)"
},
{
"answer_id": 74616473,
"author": "Abdul Aziz Barkat",
"author_id": 14991864,
"author_profile": "https://Stackoverflow.com/users/14991864",
"pm_score": 2,
"selected": false,
"text": "class YourMixin:\n def handle(self, name):\n # Code that was previously in deco\n\n\nclass Command(YourMixin, BaseCommand):\n def add_arguments(self, parser):\n parser.add_argument(\n \"--name\",\n type=str,\n required=True,\n )\n\n def handle(self, *_args, **options):\n # Code before calling YourMixin.handle\n name = options[\"name\"]\n super().handle(name)\n # Code after calling YourMixin.handle\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5562041/"
] |
74,616,068
|
<p>If we create a 2d/3d list by this way:</p>
<pre><code> List recipes = List.generate(
999,
(i) => List.generate(
999,
(i) => List<Ingredient>.filled(
0,
Ingredient(
name: '',
carbohydrates: 0,
proteins: 0,
lipids: 0,
fibers: 0),
growable: true)));
</code></pre>
<p>Please assume that Ingredient is a simple Class.</p>
<p>When we try to access it:</p>
<p><code>print(recipes[0][0][0].name);</code></p>
<p>Arriving at this point:</p>
<p><code>print(recipes[0][0][0].</code></p>
<p>We need to see (access) the Class properties (like kcal, name, carbohydrates...); exactly as in a one dimension list.</p>
<p>However, at least in VS Code, the code editor display this only: hashCode, runtimeType, toString(), noSuchMethod(...)</p>
<p>When I try to create the list by this way:</p>
<pre><code>List<List<List<Ingredient>>> ingredient =
List.generate(999, (index) => [[]], growable: true);
</code></pre>
<p>This bug does not exists, but I have no idea on how to fill (give a dimension and class) the first and the second list...</p>
<p>My first goal is not to lose the autocomplete function (by the editor) because it's too hard to remember every List.properties/funcions by mind.</p>
<p>The Ingredient Class:</p>
<pre><code>class Ingredient {
String? name;
int? kcal;
int? carbohydrates;
int? proteins;
int? lipids;
int? fibers;
Ingredient(
{this.name,
this.kcal,
this.carbohydrates,
this.proteins,
this.lipids,
this.fibers});
}
</code></pre>
|
[
{
"answer_id": 74616232,
"author": "Emc2Theory",
"author_id": 4651768,
"author_profile": "https://Stackoverflow.com/users/4651768",
"pm_score": 0,
"selected": false,
"text": " List<List<List<Ingredient>>> ingredient = (List.generate(\n 999,\n (i) => List.generate(\n 999,\n (i) => List<Ingredient>.filled(\n 0,\n Ingredient(\n name: '',\n carbohydrates: 0,\n proteins: 0,\n lipids: 0,\n fibers: 0),\n growable: true))));\n"
},
{
"answer_id": 74616424,
"author": "Su Mit",
"author_id": 18523016,
"author_profile": "https://Stackoverflow.com/users/18523016",
"pm_score": 2,
"selected": false,
"text": "var final var ingredient = (List.generate( \n 999,\n (i) => List.generate(\n 999,\n (i) => List<Ingredient>.filled(\n 1, // -> put 1 if you want to populate your list or else it will be empty list\n Ingredient(\n name: '',\n carbohydrates: 0,\n proteins: 0,\n lipids: 0,\n fibers: 0),\n growable: true))));\n\n print(ingredient[0][0][0]);\n print(ingredient[0][0][0].carbohydrates);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4651768/"
] |
74,616,074
|
<p>I am trying to create a docker-compose.yml file from 0 following this <a href="https://www.smarthomebeginner.com/docker-media-server-2022/#4_Docker_and_Docker_Compose_Usage" rel="nofollow noreferrer">guide.</a></p>
<p>When I try to run the container I get the following error: <code>yaml: line 29: could not find expected ':'</code></p>
<p>I've read everywhere and I find indentation problems, but I haven't been able to tell why my file won't run, any help would be Highly apreciated. My docker-compose.yml file contains the following:</p>
<pre><code>version: "3.9"
########################### NETWORKS
# You may customize the network subnet (192.168.89.0/24) below as you please.
# Docker Compose version 3.5 or higher required to define networks this way.
networks:
default:
driver: bridge
npm_proxy:
name: npm_proxy
driver: bridge
ipam:
config:
- subnet: 192.168.89.0/24
########################### EXTENSION FIELDS
# Helps eliminate repetition of sections
# More Info on how to use this: https://github.com/htpcBeginner/docker-traefik/pull/228
# Common environment values
x-environment: &default-tz-puid-pgid
TZ: $TZ
PUID: $PUID
PGID: $PGID
# Keys common to some of the core services that we always to automatically restart on failure
x-common-keys-core: &common-keys-core
networks:
- npm_proxy
security_opt:
- no-new-privileges:true
restart: always
# Keys common to some of the dependent services/apps
x-common-keys-apps: &common-keys-apps
networks:
- npm_proxy
security_opt:
- no-new-privileges:true
restart: unless-stopped
# Keys common to some of the services in media-services.txt
x-common-keys-media: &common-keys-media
networks:
- npm_proxy
security_opt:
- no-new-privileges:true
restart: "no"
########################### SERVICES
services:
################ FRONTENDS
# Nginx Proxy Manager - Reverse Proxy with LetsEncrypt
npm:
<<: *common-keys-core # See EXTENSION FIELDS at the top
container_name: nginx-proxy-manager
image: 'jc21/nginx-proxy-manager:latest'
# For Static IP
networks:
# For Static IP
npm_proxy:
ipv4_address: 192.168.89.254 # You can specify a static IP
# For Dynamic IP
# networks:
# - npm_proxy
ports:
- '80:80' # Public HTTP Port. Port Forwarding on Router is ON.
- '443:443' # Public HTTPS Port. Port Forwarding on Router is ON.
- '81:81' # Admin Web Port. Port Forwarding on Router is OFF. Internal Home Network Access only - 192.168.89.254:81.
volumes:
- $DOCKERDIR/appdata/npm/config:/config
- $DOCKERDIR/appdata/npm/letsencrypt:/etc/letsencrypt
- $DOCKERDIR/appdata/npm/data:/data
environment:
DB_SQLITE_FILE: "/config/database.sqlite"
DISABLE_IPV6: 'true'
</code></pre>
<p>I've tried reviewing the indentation, and changing some environment variables definitions ex:
<code>TZ: $TZ</code> to <code>- TZ=$TZ</code></p>
|
[
{
"answer_id": 74616232,
"author": "Emc2Theory",
"author_id": 4651768,
"author_profile": "https://Stackoverflow.com/users/4651768",
"pm_score": 0,
"selected": false,
"text": " List<List<List<Ingredient>>> ingredient = (List.generate(\n 999,\n (i) => List.generate(\n 999,\n (i) => List<Ingredient>.filled(\n 0,\n Ingredient(\n name: '',\n carbohydrates: 0,\n proteins: 0,\n lipids: 0,\n fibers: 0),\n growable: true))));\n"
},
{
"answer_id": 74616424,
"author": "Su Mit",
"author_id": 18523016,
"author_profile": "https://Stackoverflow.com/users/18523016",
"pm_score": 2,
"selected": false,
"text": "var final var ingredient = (List.generate( \n 999,\n (i) => List.generate(\n 999,\n (i) => List<Ingredient>.filled(\n 1, // -> put 1 if you want to populate your list or else it will be empty list\n Ingredient(\n name: '',\n carbohydrates: 0,\n proteins: 0,\n lipids: 0,\n fibers: 0),\n growable: true))));\n\n print(ingredient[0][0][0]);\n print(ingredient[0][0][0].carbohydrates);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20469761/"
] |
74,616,076
|
<p>when I open the app, white screen appears with icon. Then only the splash screen appears.
I have already tried changing the background colour.</p>
|
[
{
"answer_id": 74616134,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 0,
"selected": false,
"text": "flutter_native_splash:\n # This package generates native code to customize Flutter's default white native splash screen\n # with background color and splash image.\n # Customize the parameters below, and run the following command in the terminal:\n # flutter pub run flutter_native_splash:create\n # To restore Flutter's default white splash screen, run the following command in the terminal:\n # flutter pub run flutter_native_splash:remove\n\n # color or background_image is the only required parameter. Use color to set the background\n # of your splash screen to a solid color. Use background_image to set the background of your\n # splash screen to a png image. This is useful for gradients. The image will be stretch to the\n # size of the app. Only one parameter can be used, color and background_image cannot both be set.\n color: \"#42a5f5\" #here the color \n flutter pub run flutter_native_splash:create\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19588129/"
] |
74,616,112
|
<p>Web page have element with structure like:</p>
<pre><code><label>
<input type="checkbox" name="storage_locations" value="3" style="vertical-align: middle;">
<span style="padding-left: 6px;">example.domain.com: [Text] Text_1 (Sometext)</span>
</label>
<label>
<input type="checkbox" name="storage_locations" value="3" style="vertical-align: middle;">
<span style="padding-left: 6px;">example.domain.com: [Text] Text_2 (Sometext)</span>
</label>
<label>
<input type="checkbox" name="storage_locations" value="3" style="vertical-align: middle;">
<span style="padding-left: 6px;">example.domain.com: [Text] Text_3 (Sometext)</span>
</label>
</code></pre>
<p>How i can select input-element located in label with span-element which contains 'Text 2' (for example)?</p>
<p>I know that i could find span-element using this code:</p>
<pre><code>example = driver.find_element(By.XPATH,'//*/label/span[contains(text(),"Text_2")')
</code></pre>
<p>But i'm new in selenium-python and haven't ideas what to do next</p>
|
[
{
"answer_id": 74616134,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 0,
"selected": false,
"text": "flutter_native_splash:\n # This package generates native code to customize Flutter's default white native splash screen\n # with background color and splash image.\n # Customize the parameters below, and run the following command in the terminal:\n # flutter pub run flutter_native_splash:create\n # To restore Flutter's default white splash screen, run the following command in the terminal:\n # flutter pub run flutter_native_splash:remove\n\n # color or background_image is the only required parameter. Use color to set the background\n # of your splash screen to a solid color. Use background_image to set the background of your\n # splash screen to a png image. This is useful for gradients. The image will be stretch to the\n # size of the app. Only one parameter can be used, color and background_image cannot both be set.\n color: \"#42a5f5\" #here the color \n flutter pub run flutter_native_splash:create\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20634622/"
] |
74,616,138
|
<p>I am a C++ noob.</p>
<p>What I am trying to do is sum the values of a vector of doubles (let's call it <code>x</code>) and ignore any values that are NaN. I tried to look this up, but I couldn't find anything specifically referencing what would happen if a vector contains any NaN values.</p>
<p>E.g.:</p>
<pre class="lang-cpp prettyprint-override"><code>// let's say x = [1.0, 2.0, 3.0, nan, 4.0]
y = sum(x) // y should be equal to 10.0
</code></pre>
<p>Would the <code>accumulate</code> function work here? Or would it return <code>NaN</code> if <code>x</code> contains a <code>NaN</code>? Would a for loop work here with a condition to check for if the value is <code>NaN</code> (if yes, how do I check if <code>NaN</code>? In Python, the language I know best, this kind of check is not always straightforward).</p>
|
[
{
"answer_id": 74616418,
"author": "Stack Danny",
"author_id": 6039995,
"author_profile": "https://Stackoverflow.com/users/6039995",
"pm_score": 2,
"selected": false,
"text": "std::isnan true sum constexpr auto sum(auto list) {\n typename decltype(list)::value_type result = 0;\n\n for (const auto& i : list) {\n if (!std::isnan(i)) { // < - crucial check here\n result += i;\n }\n }\n return result;\n}\n int main() {\n auto list = std::array{ 1.0f, 2.0f, 3.0f, NAN };\n std::cout << sum(list); //prints out 6\n}\n"
},
{
"answer_id": 74616449,
"author": "Willi",
"author_id": 20635039,
"author_profile": "https://Stackoverflow.com/users/20635039",
"pm_score": 1,
"selected": false,
"text": "const std::vector<double> myVector{1.0, 2.0, 3.0, std::nan(\"42\"), 4.0};\n\nauto nansum = [](const double a, const double b)\n{\n return a + (std::isnan(b) ? 0 : b);\n}\n\nauto mySum = std::accumulate(myVector.begin(), myVector.end(), 0.0, nansum);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9123489/"
] |
74,616,165
|
<p>I have data that arrives as so in a sheet from a google form. It's to manage pieces of our product that we send to a painter.</p>
<pre><code>in/out model_1 model_2
-------------------------
in 10 0
out 5 0
in 10 10
in 2 5
out 2 12
</code></pre>
<p>I want something like so</p>
<pre><code>model IN OUT
-------------------------
model_1 22 7
model_2 15 12
</code></pre>
<p>I managed to get the first column with a query with something along those lines</p>
<pre><code>SELECT SUM(B), SUM(C) WHERE A="in"
</code></pre>
<p>Then I added a <code>TRANSPOSE</code>.</p>
<p>How to add to the query a second column <code>where A="out"</code> ?</p>
<p>This is the real query :</p>
<pre><code>=TRANSPOSE(QUERY('Réponses au formulaire 2'!A1:W; "SELECT SUM(E), SUM(F), SUM(G), SUM(H), SUM(I), SUM(J), SUM(K), SUM(L), SUM(M), SUM(N), SUM(O), SUM(P), SUM(Q), SUM(R), SUM(S), SUM(T), SUM(U), SUM(V), SUM(W) WHERE D = 'DEPOT'";1))
</code></pre>
<p>Hope you understand what I mean. Maybe another approach is best?</p>
<p>But for now I'm kinda stuck but not really happy with my solution of adding a second query as it add a column of labels sum_a sum_b....</p>
|
[
{
"answer_id": 74616418,
"author": "Stack Danny",
"author_id": 6039995,
"author_profile": "https://Stackoverflow.com/users/6039995",
"pm_score": 2,
"selected": false,
"text": "std::isnan true sum constexpr auto sum(auto list) {\n typename decltype(list)::value_type result = 0;\n\n for (const auto& i : list) {\n if (!std::isnan(i)) { // < - crucial check here\n result += i;\n }\n }\n return result;\n}\n int main() {\n auto list = std::array{ 1.0f, 2.0f, 3.0f, NAN };\n std::cout << sum(list); //prints out 6\n}\n"
},
{
"answer_id": 74616449,
"author": "Willi",
"author_id": 20635039,
"author_profile": "https://Stackoverflow.com/users/20635039",
"pm_score": 1,
"selected": false,
"text": "const std::vector<double> myVector{1.0, 2.0, 3.0, std::nan(\"42\"), 4.0};\n\nauto nansum = [](const double a, const double b)\n{\n return a + (std::isnan(b) ? 0 : b);\n}\n\nauto mySum = std::accumulate(myVector.begin(), myVector.end(), 0.0, nansum);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10729553/"
] |
74,616,185
|
<p>Suppose you create a Spark DataFrame with a precise schema:</p>
<pre><code>import pyspark.sql.functions as sf
from pyspark.sql.types import *
dfschema = StructType([
StructField("_1", ArrayType(IntegerType())),
StructField("_2", ArrayType(IntegerType())),
])
df = spark.createDataFrame([[[1, 2, 5], [13, 74, 1]],
[[1, 2, 3], [77, 23, 15]]
], schema=dfschema)
df = df.select(sf.map_from_arrays("_1", "_2").alias("omap"))
df = df.withColumn("id", sf.lit(1))
</code></pre>
<p>The above DataFrame looks like this:</p>
<pre><code>+---------------------------+---+
|omap |id |
+---------------------------+---+
|{1 -> 13, 2 -> 74, 5 -> 1} |1 |
|{1 -> 77, 2 -> 23, 3 -> 15}|1 |
+---------------------------+---+
</code></pre>
<p>I would like to perform the following operation:</p>
<pre><code>df.groupby("id").agg(sum_counter("omap")).show(truncate=False)
</code></pre>
<p>Could you please help me in defining a <code>sum_counter</code> function which uses only SQL functions from <code>pyspark.sql.functions</code> (so no UDFs) that allows me to obtain in output such a DataFrame:</p>
<pre><code>+---+-----------------------------------+
|id |mapsum |
+---+-----------------------------------+
|1 |{1 -> 90, 2 -> 97, 5 -> 1, 3 -> 15}|
+---+-----------------------------------+
</code></pre>
<p>I could solve this using applyInPandas:</p>
<pre><code>from pyspark.sql.types import *
from collections import Counter
import pandas as pd
reschema = StructType([
StructField("id", LongType()),
StructField("mapsum", MapType(IntegerType(), IntegerType()))
])
def sum_counter(key: int, pdf: pd.DataFrame) -> pd.DataFrame:
return pd.DataFrame([
key
+ (sum([Counter(x) for x in pdf["omap"]], Counter()), )
])
df.groupby("id").applyInPandas(sum_counter, reschema).show(truncate=False)
+---+-----------------------------------+
|id |mapsum |
+---+-----------------------------------+
|1 |{1 -> 90, 2 -> 97, 5 -> 1, 3 -> 15}|
+---+-----------------------------------+
</code></pre>
<p>However, for performance reasons, I would like to avoid using <code>applyInPandas</code> or <code>UDFs</code>. Any ideas?</p>
|
[
{
"answer_id": 74619099,
"author": "Bartosz Gajda",
"author_id": 6870955,
"author_profile": "https://Stackoverflow.com/users/6870955",
"pm_score": 1,
"selected": false,
"text": "omap exploded_df = df.select(\"*\", sf.explode(\"omap\"))\nagg_df = exploded_df.groupBy(\"id\", \"key\").sum(\"value\")\nagg_df.groupBy(\"id\").agg(sf.map_from_entries(sf.collect_list(sf.struct(\"key\",\"sum(value)\"))).alias(\"mapsum\")).show(truncate=False)\n\n+---+-----------------------------------+\n|id |mapsum |\n+---+-----------------------------------+\n|1 |{2 -> 97, 1 -> 90, 5 -> 1, 3 -> 15}|\n+---+-----------------------------------+\n\n"
},
{
"answer_id": 74624732,
"author": "mik1904",
"author_id": 5617858,
"author_profile": "https://Stackoverflow.com/users/5617858",
"pm_score": 1,
"selected": true,
"text": "import pyspark.sql.functions as sf\n\ndef sum_counter(mapcoln: str):\n dkeys = sf.array_distinct(sf.flatten(sf.collect_list(sf.map_keys(mapcoln))))\n dkeyscount = sf.transform(\n dkeys,\n lambda ukey: sf.aggregate(\n sf.collect_list(mapcoln),\n sf.lit(0),\n lambda acc, mapentry: sf.when(\n ~sf.isnull(sf.element_at(mapentry, ukey)),\n acc + sf.element_at(mapentry, ukey),\n ).otherwise(acc),\n ),\n )\n return sf.map_from_arrays(dkeys, dkeyscount).alias(\"mapsum\")\n\ndf.groupby(\"id\").agg(sum_counter(\"omap\")).show(truncate=False)\n\n\n+---+-----------------------------------+\n|id |mapsum |\n+---+-----------------------------------+\n|1 |{1 -> 90, 2 -> 97, 5 -> 1, 3 -> 15}|\n+---+-----------------------------------+\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5617858/"
] |
74,616,207
|
<p>I made a login form and I put an icon next to each input. But those icons are overlapping the text zone. How can I make the input start next to the icon.</p>
<p><a href="https://i.stack.imgur.com/tERq3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tERq3.png" alt="enter image description here" /></a></p>
<p>I tried in CSS with a text-align: center; but it's not what I was expecting. The text align is a text format not a text placement.</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>.fa-solid.fa-user {
position: relative;
color: rgb(177, 177, 177);
right: 250px;
top: 2px;
}
.fa-solid.fa-lock {
position: relative;
color: rgb(177, 177, 177);
right: 250px;
top: 2px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="centered">
<div id="form">
<h2>Connexion</h2>
<form>
<p>Nom d'utilisateur</p>
<p><input type="text" name="username" id="username" placeholder="Username" required /><span><i class="fa-solid fa-user"></i></span></p>
<p>Mot de passe</p>
<p><input type="password" name="password" id="pw" placeholder="Mot de passe" required /><i class="fa-solid fa-lock"></i></p>
<p><input type="submit" name="login" value="S'enregistrer" required /></p>
</form>
</div>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74616328,
"author": "Jack",
"author_id": 20633571,
"author_profile": "https://Stackoverflow.com/users/20633571",
"pm_score": 1,
"selected": false,
"text": "input {\n padding-left: 20px;\n} <div id=\"centered\">\n <div id=\"form\">\n <h2>Connexion</h2>\n <form>\n <p>Nom d'utilisateur</p>\n <p><input type=\"text\" name=\"username\" id=\"username\" placeholder=\"Username\" required /><span><i class=\"fa-solid fa-user\"></i></span></p>\n <p>Mot de passe</p>\n <p><input type=\"password\" name=\"password\" id=\"pw\" placeholder=\"Mot de passe\" required /><i class=\"fa-solid fa-lock\"></i></p>\n <p><input type=\"submit\" name=\"login\" value=\"S'enregistrer\" required /></p>\n </form>\n </div>\n</div>"
},
{
"answer_id": 74616375,
"author": "manjiro sano",
"author_id": 19160227,
"author_profile": "https://Stackoverflow.com/users/19160227",
"pm_score": 0,
"selected": false,
"text": "padding padding-left .fa-solid.fa-user {\n position: relative;\n color: rgb(177, 177, 177);\n right: 250px;\n top: 2px;\n}\n\n.fa-solid.fa-lock {\n position: relative;\n color: rgb(177, 177, 177);\n right: 250px;\n top: 2px;\n}\n\n#username,\n#pw {\n padding-left: 15px;\n} <div id=\"centered\">\n <div id=\"form\">\n <h2>Connexion</h2>\n <form>\n <p>Nom d'utilisateur</p>\n <p><input type=\"text\" name=\"username\" id=\"username\" placeholder=\"Username\" required /><span><i class=\"fa-solid fa-user\"></i></span></p>\n <p>Mot de passe</p>\n <p><input type=\"password\" name=\"password\" id=\"pw\" placeholder=\"Mot de passe\" required /><i class=\"fa-solid fa-lock\"></i></p>\n <p><input type=\"submit\" name=\"login\" value=\"S'enregistrer\" required /></p>\n </form>\n </div>\n</div>"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20152199/"
] |
74,616,213
|
<p>I need to write a function named older_people(people: list, year: int), which selects all those people on the list who were born before the year given as an argument. The function should return the names of these people in a new list.</p>
<p>An example of its use:</p>
<pre><code>p1 = ("Adam", 1977)
p2 = ("Ellen", 1985)
p3 = ("Mary", 1953)
p4 = ("Ernest", 1997)
people = [p1, p2, p3, p4]
older = older_people(people, 1979)
print(older)
</code></pre>
<p>Sample output:
[ 'Adam', 'Mary' ]</p>
<p>So far I got:</p>
<pre><code> def older_people(people: list, year: int):
for person in plist:
if person[1] < year:
return person[0]
p1 = ("Adam", 1977)
p2 = ("Ellen", 1985)
p3 = ("Mary", 1953)
p4 = ("Ernest", 1997)
plist = [p1, p2, p3, p4]
older = older_people(plist, 1979)
print(older)
</code></pre>
<p>At the moment this just prints the first person (Adam) who is born before 1979.
Any help for this one?</p>
|
[
{
"answer_id": 74616323,
"author": "robinood",
"author_id": 8814229,
"author_profile": "https://Stackoverflow.com/users/8814229",
"pm_score": 3,
"selected": true,
"text": "def older_people(people: list, year: int):\n result = []\n for person in people:\n if person[1] < year:\n result.append(person[0])\n return result\n\n\n\n\np1 = (\"Adam\", 1977)\np2 = (\"Ellen\", 1985)\np3 = (\"Mary\", 1953)\np4 = (\"Ernest\", 1997)\nplist = [p1, p2, p3, p4]\n\nolder = older_people(plist, 1979)\nprint(older)\n"
},
{
"answer_id": 74617522,
"author": "Amos Baker",
"author_id": 4603318,
"author_profile": "https://Stackoverflow.com/users/4603318",
"pm_score": 0,
"selected": false,
"text": "def older_people(people: list, year: int):\n return [person for person, birth_year in people if birth_year <= year]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20633646/"
] |
74,616,247
|
<p>I have a table with a column having timestamp as it's value. I need to add a new column & calculate the time difference between 2 rows.
How to do this?</p>
<p><img src="https://i.stack.imgur.com/5P4HJ.jpg" alt="enter image description here" /></p>
<p>I'm new to this & want to know how to do it please</p>
|
[
{
"answer_id": 74616368,
"author": "horseyride",
"author_id": 9264230,
"author_profile": "https://Stackoverflow.com/users/9264230",
"pm_score": 2,
"selected": false,
"text": "= try [Timestamp] - #\"Added Index\"{[Index]-1}[Timestamp] otherwise null\n #\"Added Index\" = Table.AddIndexColumn(#\"PriorStepNameHere\", \"Index\", 0, 1, Int64.Type),\n#\"Added Custom\" = Table.AddColumn(#\"Added Index\", \"Custom\", each try [Timestamp] - #\"Added Index\"{[Index]-1}[Timestamp] otherwise null, type duration)\nin #\"Added Custom\"\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20634815/"
] |
74,616,276
|
<p>I'm trying to access to a nested object property.</p>
<pre><code><th data-toggle="tooltip" data-placement="bottom" v-for="schedule in employee.daily_schedules">{{schedule.start}}-{{schedule.end}}-{{schedule.employee_function.name}}</th>
</code></pre>
<p>When I try to get the schedule.employee_function.name I get an error</p>
<blockquote>
<p>(TypeError: u.employee_function is null)</p>
</blockquote>
<p>but if I render schedule.employee_function I have the whole object:</p>
<p><a href="https://i.stack.imgur.com/cfmy1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cfmy1.png" alt="enter image description here" /></a></p>
<p>This is the object that I get from the api:</p>
<p><a href="https://i.stack.imgur.com/jMjoC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jMjoC.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74616368,
"author": "horseyride",
"author_id": 9264230,
"author_profile": "https://Stackoverflow.com/users/9264230",
"pm_score": 2,
"selected": false,
"text": "= try [Timestamp] - #\"Added Index\"{[Index]-1}[Timestamp] otherwise null\n #\"Added Index\" = Table.AddIndexColumn(#\"PriorStepNameHere\", \"Index\", 0, 1, Int64.Type),\n#\"Added Custom\" = Table.AddColumn(#\"Added Index\", \"Custom\", each try [Timestamp] - #\"Added Index\"{[Index]-1}[Timestamp] otherwise null, type duration)\nin #\"Added Custom\"\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1295853/"
] |
74,616,281
|
<p>very simple, android kotlin.
i have a file in the project assest folder with sentence in each line.
what i wants, is when i open dialog, it will select random line and put it as the dialog message.
i couldn't find any proper solution.
dialog's code:</p>
<pre><code>class JokeFragment : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
val sentence: String = //random line from the file
// Use the Builder class for convenient dialog construction
val builder = Builder(it)
builder.setMessage(sentence)
.setNegativeButton(R.string.cancel){ _, _->}
// Create the AlertDialog object and return it
builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
}
</code></pre>
|
[
{
"answer_id": 74618407,
"author": "bylazy",
"author_id": 17787605,
"author_profile": "https://Stackoverflow.com/users/17787605",
"pm_score": 1,
"selected": false,
"text": "fun readRandomLineFromAsset(context: Context, fileName: String): String =\n context\n .assets\n .open(fileName)\n .bufferedReader()\n .use(BufferedReader::readText)\n .lines()\n .shuffled()\n .first()\n"
},
{
"answer_id": 74653425,
"author": "nope",
"author_id": 20568970,
"author_profile": "https://Stackoverflow.com/users/20568970",
"pm_score": 1,
"selected": true,
"text": "val sharedPreference = getSharedPreferences(\"PREFERENCE_NAME\", Context.MODE_PRIVATE)\nval editor = sharedPreference.edit()\n...\n btn.setOnClickListener{\n val file = assets.open(\"jokes.txt\")\n val joke :String =file.bufferedReader().use(BufferedReader::readText).lines().shuffled().first()\n editor.putString(\"joke\", joke)\n editor.apply()\n JokeFragment().show(supportFragmentManager, \"NoticeDialogFragment\")\n }\n val sharedPreference = requireActivity().getSharedPreferences(\"PREFERENCE_NAME\", Context.MODE_PRIVATE)\nval joke = sharedPreference.getString(\"joke\" , \"error\")\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20568970/"
] |
74,616,363
|
<p>I have the data in the following format:
<a href="https://i.stack.imgur.com/9mTBR.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I want to convert the year column to intervals (decade), so that I have the decade column in the format 1950-1959, 1960-1969 and so on (without removing the company name).
So that I can find companies with the highest revenue for the decade and then plot the top 5 companies along with revenues (for all intervals) using seaborn.</p>
<p>I tried the following script.</p>
<pre class="lang-py prettyprint-override"><code>df_Fortune.groupby(['Year', 'Company']).sum().sort_values(['Year', 'Revenue (in millions)'], ascending=[1, 0])
</code></pre>
<p>The result is a multi-index (I guess) and I don't know how to convert Year into decades.
<a href="https://i.stack.imgur.com/V5l7N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V5l7N.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74617317,
"author": "Baron Legendre",
"author_id": 14527886,
"author_profile": "https://Stackoverflow.com/users/14527886",
"pm_score": 2,
"selected": true,
"text": "\nimport pandas as pd\nimport numpy as np\n# create a dataframe with 100 rows random with column year random between 1950-2019\ndf = pd.DataFrame({'year': np.random.randint(1950, 2020, 100)})\ndf['revenue'] = np.random.randint(1000, 10000, 100)\ndf.sort_values(by='year', inplace=True)\ndf.reset_index(drop=True, inplace=True)\ndf['year_interval'] = pd.cut(df['year'], bins=range(1950, 2025, 5), labels=range(1950, 2020, 5), include_lowest=True)\ndf['year_interval'] = df['year_interval'].astype(str) + '-' + (df['year_interval'].astype(int) + 4).astype(str)\ndf['company'] =['Walmart', 'Amazon', 'Apple', 'CVS Health', 'UnitedHealth Group', 'Exxon Mobil', 'Berkshire Hathaway', 'Alphabet', 'McKesson', 'AmerisourceBergen', 'Costco Wholesale', 'Cigna', 'AT&T', 'Microsoft', 'Cardinal Health', 'Chevron', 'Home Depot', 'Walgreens Boots Alliance', 'Marathon Petroleum', 'Elevance Health', 'Kroger', 'Ford Motor', 'Verizon Communications', 'JPMorgan Chase', 'General Motors', 'Centene', 'Meta Platforms', 'Comcast', 'Phillips 66', 'Valero Energy', 'Dell Technologies', 'Target', 'Fannie Mae', 'United Parcel Service', 'Lowe\\'s', 'Bank of America', 'Johnson & Johnson', 'Archer Daniels Midland', 'FedEx', 'Humana', 'Wells Fargo', 'State Farm Insurance', 'Pfizer', 'Citigroup', 'PepsiCo', 'Intel', 'Procter & Gamble', 'General Electric', 'IBM', 'MetLife', 'Prudential Financial', 'Albertsons', 'Walt Disney', 'Energy Transfer', 'Lockheed Martin', 'Freddie Mac', 'Goldman Sachs Group', 'Raytheon Technologies', 'HP', 'Boeing', 'Morgan Stanley', 'HCA Healthcare', 'AbbVie', 'Dow', 'Tesla', 'Allstate', 'American International Group', 'Best Buy', 'Charter Communications', 'Sysco', 'Merck', 'New York Life Insurance', 'Caterpillar', 'Cisco Systems', 'TJX', 'Publix Super Markets', 'ConocoPhillips', 'Liberty Mutual Insurance Group', 'Progressive', 'Nationwide', 'Tyson Foods', 'Bristol-Myers Squibb', 'Nike', 'Deere', 'American Express', 'Abbott Laboratories', 'StoneX Group', 'Plains GP Holdings', 'Enterprise Products Partners', 'TIAA', 'Oracle', 'Thermo Fisher Scientific', 'Coca-Cola', 'General Dynamics', 'CHS', 'USAA', 'Northwestern Mutual', 'Nucor', 'Exelon', 'Massachusetts Mutual Life Insurance']\ndf\n###\n year revenue year_interval company\n0 1951 8951 1950-1954 Walmart\n1 1954 7270 1950-1954 Amazon\n2 1955 7148 1950-1954 Apple\n3 1955 5661 1950-1954 CVS Health\n4 1955 5179 1950-1954 UnitedHealth Group\n.. ... ... ... ...\n95 2016 4945 2015-2019 USAA\n96 2016 6860 2015-2019 Northwestern Mutual\n97 2017 6535 2015-2019 Nucor\n98 2018 6235 2015-2019 Exelon\n99 2019 8624 2015-2019 Massachusetts Mutual Life Insurance\n\n[100 rows x 4 columns]\n year_interval df_max = df.groupby('year_interval')['revenue'].max().reset_index()\ndf_result = df_max.merge(df, on=['year_interval', 'revenue'], how='left')\ndf_result\n###\n year_interval revenue year company\n0 1950-1954 8951 1951 Walmart\n1 1955-1959 8891 1959 McKesson\n2 1960-1964 9643 1962 Cigna\n3 1965-1969 9723 1970 Elevance Health\n4 1970-1974 9396 1973 General Motors\n5 1975-1979 7048 1978 Comcast\n6 1980-1984 9776 1982 United Parcel Service\n7 1985-1989 9216 1986 State Farm Insurance\n8 1990-1994 8788 1994 Morgan Stanley\n9 1995-1999 7339 1997 Best Buy\n10 2000-2004 9750 2003 Liberty Mutual Insurance Group\n11 2005-2009 9986 2008 Deere\n12 2010-2014 9438 2014 Coca-Cola\n13 2015-2019 8624 2019 Massachusetts Mutual Life Insurance\n import matplotlib.pyplot as plt\nimport seaborn as sns\n\nsns.set_theme(style=\"whitegrid\")\nplt.gcf().set_size_inches(15, 6)\nax = sns.barplot(x=\"year_interval\", y=\"revenue\", hue=\"company\", data=df_result, dodge=False)\nax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha=\"right\")\nplt.legend(bbox_to_anchor=(1.15, 1), loc=2, borderaxespad=0.)\n\nfor p in ax.patches:\n ax.annotate(format(p.get_height(), '.0f'), (p.get_x() + p.get_width() / 2., p.get_height()), ha = 'center', va = 'center', xytext = (0, 10), textcoords = 'offset points')\nplt.tight_layout()\nplt.show()\n"
},
{
"answer_id": 74618189,
"author": "Akash Parmar",
"author_id": 17917312,
"author_profile": "https://Stackoverflow.com/users/17917312",
"pm_score": 0,
"selected": false,
"text": "df['decade1'] = df['year'] - df['year'] % 10\ndf['decade2'] = df['year'] + (10 - df['year'] % 10)\n df['decade'] = df['decade1'].astype(str).str.cat(df['decade1'].values.astype(str), sep='-')\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11970261/"
] |
74,616,402
|
<p>I've seen some Jetpack Compose projects and I've seen two types of managing states, not realizing which one is better.</p>
<p>For example, let's assume: the input state. I've seen people manage this state in the UI, using remember to save the state of the value.</p>
<p>Another way I've seen is to create this mutableState in the ViewModel and store/use it from there. What's the best way to do this?</p>
|
[
{
"answer_id": 74616609,
"author": "Thracian",
"author_id": 5457853,
"author_profile": "https://Stackoverflow.com/users/5457853",
"pm_score": 2,
"selected": false,
"text": "@Composable\nfun rememberScrollState(initial: Int = 0): ScrollState {\n return rememberSaveable(saver = ScrollState.Saver) {\n ScrollState(initial = initial)\n }\n} \n\n\n@Stable\nclass ScrollState(initial: Int) : ScrollableState {\n\n/**\n * current scroll position value in pixels\n */\nvar value: Int by mutableStateOf(initial, structuralEqualityPolicy())\n private set\n @Suppress(\"NotCloseable\")\nclass Animatable<T, V : AnimationVector>(\n initialValue: T,\n val typeConverter: TwoWayConverter<T, V>,\n private val visibilityThreshold: T? = null\n) {\n\ninternal val internalState = AnimationState(\n typeConverter = typeConverter,\n initialValue = initialValue\n)\n\n/**\n * Current value of the animation.\n */\nval value: T\n get() = internalState.value\n\n/**\n * Velocity vector of the animation (in the form of [AnimationVector].\n */\nval velocityVector: V\n get() = internalState.velocityVector\n\n/**\n * Returns the velocity, converted from [velocityVector].\n */\nval velocity: T\n get() = typeConverter.convertFromVector(velocityVector)\n\n/**\n * Indicates whether the animation is running.\n */\nvar isRunning: Boolean by mutableStateOf(false)\n private set\n\n/**\n * The target of the current animation. If the animation finishes un-interrupted, it will\n * reach this target value.\n */\nvar targetValue: T by mutableStateOf(initialValue)\n private set\n\n}\n"
},
{
"answer_id": 74616884,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 3,
"selected": true,
"text": "@Composable\nfun LoginScreen() {\n \n val userName by remember { <mutable string state username> }\n val password by remember { <mutable string state password> }\n\n Column {\n Text(text = username)\n Text(text = password)\n\n Button(\"Login\")\n }\n}\n class LoginState {\n\n var event;\n var mutableUserNameState;\n var mutablePasswordState;\n\n fun onUserNameInput() {...}\n fun onPasswordInput() {...}\n\n fun onValidate() {\n if (not valid) {\n event.emit(ShowToast(\"Not Valid\"))\n } else {\n event.emit(ShowToast(\"Valid\"))\n }\n }\n}\n\n@Composable\nfun LoginScreen() {\n\n val loginState by remember { LoginState }\n\n LaunchedEffect() {\n event.observe {\n it.ShowToast()\n }\n }\n Column {\n Text(text = loginState.mutableUserNameState, onInput = { loginState.onUserNameInput()} )\n Text(text = loginState.mutablePasswordState, onInput = { loginState.onPasswordInput()} )\n\n Button(loginState.onValidate)\n }\n}\n class LoginViewModel(\n val userRepository: UserRepository // injected by your D.I framework\n): ViewModel {\n\n var event;\n var mutableUserNameState;\n var mutablePasswordState;\n\n fun onUserNameInput() {...}\n fun onPasswordInput() {...}\n\n fun onValidateViaNetwork() {\n // do a non-blocking call to a server\n viewModelScope.launch {\n var isUserValid = userRepository.validate(username, password)\n if (isUserValid) {\n event.emit(ShowToast(\"Valid\"))\n } else {\n event.emit(ShowToast(\"Not Valid\"))\n }\n }\n }\n}\n\n@Composable\nfun LoginScreen() {\n\n val userNameState by viewModel.mutableUserNameState\n val passwordState by viewModel.mutablePasswordState\n \n LaunchedEffect() {\n event.observe {\n it.ShowToast()\n }\n }\n\n Column {\n Text(text = userNameState, onInput = { viewModel.onUserNameInput()} )\n Text(text = passwordState, onInput = { viewModel.onPasswordInput()} )\n\n Button(viewModel.onValidateViaNetwork)\n }\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18215416/"
] |
74,616,410
|
<p>In my react component, once the component loads, I am trying to repeat a task every 100ms and after 3 repetitions pause for 1 second. Then repeat this pattern indefinitely.</p>
<p>I want to achieve this output:</p>
<pre><code>1 // pause 100ms
2 // pause 100ms
3 // pause 100ms
// pause 1second
... repeat
</code></pre>
<p>I tried something like this</p>
<pre><code>useEffect(() => {
let i = 0
function increment() {
if (i === 3) {
// i = 0
// restart timer?
// return?
}
i++
console.log(i)
}
const incrementTimer = setInterval(increment, 100)
setInterval(() => {
clearInterval(incrementTimer)
}, 1000)
}, [])
</code></pre>
|
[
{
"answer_id": 74616771,
"author": "Oktay Yuzcan",
"author_id": 13311273,
"author_profile": "https://Stackoverflow.com/users/13311273",
"pm_score": 0,
"selected": false,
"text": "useEffect(() => {\n let i = 0\n let incrementTimer\n function increment() {\n if (i === 3) {\n // i = 0\n // restart timer?\n // return?\n }\n i++\n console.log(i)\n incrementTimer = setTimeout(increment, 100)\n }\n\n increment()\n\n setInterval(() => {\n clearInterval(incrementTimer)\n }, 1000)\n}, [])\n"
},
{
"answer_id": 74617301,
"author": "mahooresorkh",
"author_id": 15235482,
"author_profile": "https://Stackoverflow.com/users/15235482",
"pm_score": 0,
"selected": false,
"text": "const [levelIndex, setLevelIndex] = useState(0);\n const intevalExecutionTime = [100,100,100,1000];\n useEffect useEffect(() => {\n const timer = setInterval(() => {\n //**write the task that you want to be done.**\n if(levelIndex === 3){\n setLevelIndex(0);\n console.log(`one second paused`);\n }\n else{\n setLevelIndex(levelIndex+1);\n console.log('task is done.');\n }\n clearInterval(timer);\n }, intevalExecutionTime[levelIndex])\n}, [levelIndex]);\n setInterval levelIndex useEffect"
},
{
"answer_id": 74620414,
"author": "lissettdm",
"author_id": 14349808,
"author_profile": "https://Stackoverflow.com/users/14349808",
"pm_score": 2,
"selected": true,
"text": "recursive useEffect useEffect(() => {\n function start(i = 1) {\n const reset = i > 3;\n const time = reset ? 1000 : 100;\n\n const timeout = setTimeout(() => {\n task(i, time); // -> run your task\n start(reset ? 1 : i + 1); recursive call to schedule next task\n clearTimeout(timeout); // -> clear \n }, time);\n }\n\n start();\n}, []);\n\nfunction task(i, time) {\n console.log('task is running: ', i, time);\n}\n\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2135210/"
] |
74,616,420
|
<p>I have a simple data set. The row names are a meaningful index and column 1 has a list of values. What I eventually want is the average of that list for each row name.</p>
<p>What it looks like now:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>row name</th>
<th>years</th>
</tr>
</thead>
<tbody>
<tr>
<td>108457</td>
<td>[1200, 1200, 1540, 1890]</td>
</tr>
<tr>
<td>237021</td>
<td>[1600, 1270, 1270]</td>
</tr>
</tbody>
</table>
</div>
<p>What I eventually want it to look like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>row name</th>
<th>years</th>
</tr>
</thead>
<tbody>
<tr>
<td>108457</td>
<td>mean of list</td>
</tr>
<tr>
<td>237021</td>
<td>mean of list</td>
</tr>
</tbody>
</table>
</div>
<p>Currently, I'm trying to use <code>unnest_wider(years)</code>. My plan is to then afterwards use <code>rowMeans()</code> to find the mean of the unnested row. I can then merge the row name and average value with my main data set, so I'm not too concerned with deleting the new columns.</p>
<p>However, this whole process is taking a while and I'm having some issues with <code>unnest_wider</code>. Currently, when I try:</p>
<pre><code>unnest_wider(dataset, colname)
</code></pre>
<p>I get the following error:</p>
<blockquote>
<p>Error in <code>as_indices_impl()</code>:
! Must subset columns with a valid subscript vector.
✖ Subscript has the wrong type <code>data.frame<years:list></code>.
ℹ It must be numeric or character.</p>
</blockquote>
<p>When I try:</p>
<p><code>unnest_wider(colname)</code></p>
<p>My computer just runs endlessly and it looks like it's counting... it doesn't stop and I have to quit the application to terminate processing.</p>
<p>I had previously tried to directly apply <code>rowMeans</code>, use <code>mean(df$ColName)</code>, and use <code>apply(ColName, mean)</code>.</p>
<p>I wonder if there's a more efficient way?</p>
<p>It may be that I shouldn't have created the list in the first place. It looks like it does now because I converted it from this format:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
</tr>
</thead>
<tbody>
<tr>
<td>108457</td>
<td>1200</td>
</tr>
<tr>
<td>108457</td>
<td>1200</td>
</tr>
<tr>
<td>108457</td>
<td>1540</td>
</tr>
<tr>
<td>237021</td>
<td>1600</td>
</tr>
<tr>
<td>108457</td>
<td>1890</td>
</tr>
<tr>
<td>237021</td>
<td>1270</td>
</tr>
</tbody>
</table>
</div>
<p>I converted it using <code>pivot_wide</code>r and then <code>as.data.frame.(t(dataset))</code></p>
<p>Should I have tried to get the averages directly from this format? If so, how would I do that?</p>
|
[
{
"answer_id": 74616508,
"author": "jpsmith",
"author_id": 12109788,
"author_profile": "https://Stackoverflow.com/users/12109788",
"pm_score": 1,
"selected": true,
"text": "ColumnA df <- read.table(text = \"ColumnA ColumnB\n108457 1200\n108457 1200\n108457 1540\n237021 1600\n108457 1890\n237021 1270\", header = TRUE)\n aggregate(df$ColumnB, list(df$ColumnA), FUN=mean) \n\n# Group.1 x\n# 1 108457 1457.5\n# 2 237021 1435.0\n library(dplyr)\ndf %>% \n group_by(ColumnA) %>%\n summarise(mean_years = mean(ColumnB))\n\n# ColumnA mean_years\n# <int> <dbl>\n#1 108457 1458.\n#2 237021 1435 \n"
},
{
"answer_id": 74616591,
"author": "AndrewGB",
"author_id": 15293191,
"author_profile": "https://Stackoverflow.com/users/15293191",
"pm_score": 2,
"selected": false,
"text": "sapply df$years <- sapply(df$years, mean, na.rm = TRUE)\n years\n108457 1457.5\n237021 1380.0\n df <- structure(list(years = structure(list(c(1200, 1200, 1540, 1890\n), c(1600, 1270, 1270)), class = \"AsIs\")), row.names = c(\"108457\", \n\"237021\"), class = \"data.frame\")\n data.table library(data.table)\n\nas.data.table(df2)[, list(ColumnB = mean(ColumnB)), by = ColumnA]\n ColumnA ColumnB\n1: 108457 1457.5\n2: 237021 1435.0\n df2 <- structure(list(ColumnA = c(108457L, 108457L, 108457L, 237021L, \n108457L, 237021L), ColumnB = c(1200L, 1200L, 1540L, 1600L, 1890L, \n1270L)), class = \"data.frame\", row.names = c(NA, -6L))\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20628348/"
] |
74,616,421
|
<p>When we have multiple terms to locate an element we can use a single predicate with logical <strong>and</strong> operator inside it or to use multiple predicates with single term inside each predicate.<br />
For example on <a href="https://stackoverflow.com/questions/tagged/selenium%2Bor%2Bwebdriver%2Bor%2Bxpath%2Bor%2Bselenium-webdriver%2Bor%2Bselenium-chromedriver?tab=Newest">this page</a> we can locate links to questions containing <code>selenium</code> in their links with this XPath:</p>
<pre><code>"//a[@class='s-link'][contains(@href,'selenium')]"
</code></pre>
<p>and with this</p>
<pre><code>"//a[@class='s-link' and contains(@href,'selenium')]"
</code></pre>
<p>I'm wondering if there are any differences between these 2 approaches?</p>
|
[
{
"answer_id": 74616837,
"author": "Heiko Theißen",
"author_id": 16462950,
"author_profile": "https://Stackoverflow.com/users/16462950",
"pm_score": 1,
"selected": false,
"text": "position() last() //a[@class='s-link'][position() > 1] s-link position() //a[@class='s-link'] //a[@class='s-link' and position() > 1] s-link position() //a s-link //a[@class='s-link'][1] //a[@class='s-link' and 1]"
},
{
"answer_id": 74618412,
"author": "Michael Kay",
"author_id": 415448,
"author_profile": "https://Stackoverflow.com/users/415448",
"pm_score": 3,
"selected": true,
"text": "position() A[X][Y] position() Y X X Y position()=X position()=Y and A[@code][1] A[@code and 1]"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3485434/"
] |
74,616,528
|
<p>The following is the given html code and I am not allowed to alter it by any means</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>#exceriseHead {
font-family: Arial, Helvetica, sans-serif;
font-size: 50px;
font-weight: bold;
border: 1px solid black;
background-color: greenyellow;
text-align: center;
color: black;
}
body {
color: gainsboro;
text-align: center;
}
p {
color: black
}
.exEnumeration {
color: green;
}
#exceriseFooter {
font-family: Arial, Helvetica, sans-serif;
font-size: 10px;
font-weight: bold;
border: 1px solid black;
background-color: greenyellow;
text-align: center;
color: black;
}
.contentcolumnContent {
display: flex;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Abgabeseite 3</title>
<link rel="stylesheet" href="cssaufgabe2.css">
<!-- TODO: Import der CSS Datei -->
</head>
<body>
<h1>Übungsblatt 4</h1>
<div id="exceriseHead">
Aufgabe 3
</div>
<div class="contentcolumnContent">
<div class="exercisePart">
<div class="exEnumeration">
<h1>a.)</h1>
</div>
<div>
<!-- TODO: Beispieltext durch Aufgabentext ersetzen -->
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Aenean pellentesque aliquet imperdiet. Nam ut lacinia elit.<br> Fusce dictum lorem purus, a ullamcorper dolor dictum eu.<br> Proin a sapien ut mauris egestas fringilla eu eu magna. Ut<br> eu imperdiet leo, vel ultrices quam.</p>
</div>
</div>
<div class="exercisePart">
<div class="exEnumeration">
<h1>b.)</h1>
</div>
<div>
<!-- TODO: Beispieltext durch Aufgabentext ersetzen -->
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Aenean pellentesque aliquet imperdiet. <span class="code">Nam ut lacinia<br> elit. </span> Fusce dictum lorem purus, a ullamcorper dolor<br> dictum eu. Proin a sapien ut mauris egestas
fringilla eu eu<br> magna. Ut eu imperdiet leo, vel ultrices quam.</p>
</div>
</div>
<div class="exercisePart">
<div class="exEnumeration">
<h1>c.)</h1>
</div>
<div>
<!-- TODO: Beispieltext durch Aufgabentext ersetzen -->
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Aenean pellentesque aliquet imperdiet. Nam ut lacinia elit.<br> Fusce dictum lorem purus, a ullamcorper dolor dictum eu.<br> Proin a sapien ut mauris egestas fringilla eu eu magna. Ut<br> eu imperdiet leo, vel ultrices quam.</p>
</div>
</div>
</div>
<div id="exceriseFooter">
[Gruppenbezeichnung]
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p><a href="https://i.stack.imgur.com/AiUn4.png" rel="nofollow noreferrer">This is how it looks</a></p>
<p><a href="https://i.stack.imgur.com/dAsuC.jpg" rel="nofollow noreferrer">This is how it should look like</a></p>
<p>Hi, I got an assignment to write a css sheet in order to make a given html page look like the image below. However I can't figure out, how to put the enumerations ( a.), b.)and c.)) in front of the text. I hope you can help me :(</p>
|
[
{
"answer_id": 74616625,
"author": "Wolfeur",
"author_id": 6201111,
"author_profile": "https://Stackoverflow.com/users/6201111",
"pm_score": 0,
"selected": false,
"text": ".exercisePart <div> display: block .exercisePart .exercisePart {\n display: flex;\n}\n"
},
{
"answer_id": 74616659,
"author": "Fabrizio Calderan",
"author_id": 1098851,
"author_profile": "https://Stackoverflow.com/users/1098851",
"pm_score": 1,
"selected": false,
"text": ".exercisePart flex-grow flex-shrink display: flex items: center #exceriseHead {\n font-family: Arial, Helvetica, sans-serif;\n font-size: 50px;\n font-weight: bold;\n border: 1px solid black;\n background-color: greenyellow;\n text-align: center;\n color: black;\n}\n\nbody {\n color: gainsboro;\n text-align: center;\n}\n\np {\n color: black\n}\n\n.exEnumeration {\n color: green;\n}\n\n#exceriseFooter {\n font-family: Arial, Helvetica, sans-serif;\n font-size: 10px;\n font-weight: bold;\n border: 1px solid black;\n background-color: greenyellow;\n text-align: center;\n color: black;\n}\n\n.contentcolumnContent {\n display: flex;\n gap: 1rem;\n justify-content: space-between;\n}\n\n.exercisePart {\n flex: 1 1 auto;\n display: flex;\n gap: .25rem;\n align-items: center;\n } <!DOCTYPE html>\n\n<head>\n <meta charset=\"utf-8\">\n <title>Abgabeseite 3</title>\n <link rel=\"stylesheet\" href=\"cssaufgabe2.css\">\n <!-- TODO: Import der CSS Datei -->\n\n</head>\n\n<body>\n\n <h1>Übungsblatt 4</h1>\n\n <div id=\"exceriseHead\">\n Aufgabe 3\n </div>\n\n\n\n\n\n <div class=\"contentcolumnContent\">\n <div class=\"exercisePart\">\n\n <div class=\"exEnumeration\">\n <h1>a.)</h1>\n </div>\n <div>\n <!-- TODO: Beispieltext durch Aufgabentext ersetzen -->\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Aenean pellentesque aliquet imperdiet. Nam ut lacinia elit.<br> Fusce dictum lorem purus, a ullamcorper dolor dictum eu.<br> Proin a sapien ut mauris egestas fringilla eu eu magna. Ut<br> eu imperdiet leo, vel ultrices quam.</p>\n </div>\n\n </div>\n\n <div class=\"exercisePart\">\n\n <div class=\"exEnumeration\">\n <h1>b.)</h1>\n </div>\n <div>\n <!-- TODO: Beispieltext durch Aufgabentext ersetzen -->\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Aenean pellentesque aliquet imperdiet. <span class=\"code\">Nam ut lacinia<br> elit. </span> Fusce dictum lorem purus, a ullamcorper dolor<br> dictum eu. Proin a sapien ut mauris egestas\n fringilla eu eu<br> magna. Ut eu imperdiet leo, vel ultrices quam.</p>\n </div>\n </div>\n\n <div class=\"exercisePart\">\n <div class=\"exEnumeration\">\n <h1>c.)</h1>\n </div>\n <div>\n <!-- TODO: Beispieltext durch Aufgabentext ersetzen -->\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Aenean pellentesque aliquet imperdiet. Nam ut lacinia elit.<br> Fusce dictum lorem purus, a ullamcorper dolor dictum eu.<br> Proin a sapien ut mauris egestas fringilla eu eu magna. Ut<br> eu imperdiet leo, vel ultrices quam.</p>\n </div>\n </div>\n </div>\n\n\n\n\n\n\n\n <div id=\"exceriseFooter\">\n [Gruppenbezeichnung]\n </div>\n\n</body>\n\n</html>"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20635021/"
] |
74,616,555
|
<p>I am trying to create a proper relationship on Hibernate and I have the following relationship between Recipe and Ingredients entities:</p>
<p><a href="https://i.stack.imgur.com/2ZZud.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2ZZud.png" alt="enter image description here" /></a></p>
<p>I thought that:</p>
<ul>
<li>One recipe can have multiple ingredients</li>
<li>One ingredient can also be part of different recipes</li>
</ul>
<p>In this situation, I would create <strong>many to many</strong> relationship.</p>
<p><strong>However</strong>, by considering the <code>unit</code> and <code>amount</code> fields in the <code>Ingredient</code> entity, I think the amount of ingredient for a specific recipe may be changed later. In this situation, each ingredient should be belonging to a specific recipe. As a result, I create <strong>one to many</strong> relationship as shown on the image.</p>
<p><strong>1.</strong> Is the approach (<strong>one to many</strong>) explained above true?</p>
<p><strong>2.</strong> I also think that for a Category entity (that describes recipe categories e.g. vegetarian, diabetic, ...), I should use <strong>many to many</strong> relationship as the category is not identical for a specific recipe and when updating any category, all the related recipes should be affected. Is this true?</p>
|
[
{
"answer_id": 74616625,
"author": "Wolfeur",
"author_id": 6201111,
"author_profile": "https://Stackoverflow.com/users/6201111",
"pm_score": 0,
"selected": false,
"text": ".exercisePart <div> display: block .exercisePart .exercisePart {\n display: flex;\n}\n"
},
{
"answer_id": 74616659,
"author": "Fabrizio Calderan",
"author_id": 1098851,
"author_profile": "https://Stackoverflow.com/users/1098851",
"pm_score": 1,
"selected": false,
"text": ".exercisePart flex-grow flex-shrink display: flex items: center #exceriseHead {\n font-family: Arial, Helvetica, sans-serif;\n font-size: 50px;\n font-weight: bold;\n border: 1px solid black;\n background-color: greenyellow;\n text-align: center;\n color: black;\n}\n\nbody {\n color: gainsboro;\n text-align: center;\n}\n\np {\n color: black\n}\n\n.exEnumeration {\n color: green;\n}\n\n#exceriseFooter {\n font-family: Arial, Helvetica, sans-serif;\n font-size: 10px;\n font-weight: bold;\n border: 1px solid black;\n background-color: greenyellow;\n text-align: center;\n color: black;\n}\n\n.contentcolumnContent {\n display: flex;\n gap: 1rem;\n justify-content: space-between;\n}\n\n.exercisePart {\n flex: 1 1 auto;\n display: flex;\n gap: .25rem;\n align-items: center;\n } <!DOCTYPE html>\n\n<head>\n <meta charset=\"utf-8\">\n <title>Abgabeseite 3</title>\n <link rel=\"stylesheet\" href=\"cssaufgabe2.css\">\n <!-- TODO: Import der CSS Datei -->\n\n</head>\n\n<body>\n\n <h1>Übungsblatt 4</h1>\n\n <div id=\"exceriseHead\">\n Aufgabe 3\n </div>\n\n\n\n\n\n <div class=\"contentcolumnContent\">\n <div class=\"exercisePart\">\n\n <div class=\"exEnumeration\">\n <h1>a.)</h1>\n </div>\n <div>\n <!-- TODO: Beispieltext durch Aufgabentext ersetzen -->\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Aenean pellentesque aliquet imperdiet. Nam ut lacinia elit.<br> Fusce dictum lorem purus, a ullamcorper dolor dictum eu.<br> Proin a sapien ut mauris egestas fringilla eu eu magna. Ut<br> eu imperdiet leo, vel ultrices quam.</p>\n </div>\n\n </div>\n\n <div class=\"exercisePart\">\n\n <div class=\"exEnumeration\">\n <h1>b.)</h1>\n </div>\n <div>\n <!-- TODO: Beispieltext durch Aufgabentext ersetzen -->\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Aenean pellentesque aliquet imperdiet. <span class=\"code\">Nam ut lacinia<br> elit. </span> Fusce dictum lorem purus, a ullamcorper dolor<br> dictum eu. Proin a sapien ut mauris egestas\n fringilla eu eu<br> magna. Ut eu imperdiet leo, vel ultrices quam.</p>\n </div>\n </div>\n\n <div class=\"exercisePart\">\n <div class=\"exEnumeration\">\n <h1>c.)</h1>\n </div>\n <div>\n <!-- TODO: Beispieltext durch Aufgabentext ersetzen -->\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Aenean pellentesque aliquet imperdiet. Nam ut lacinia elit.<br> Fusce dictum lorem purus, a ullamcorper dolor dictum eu.<br> Proin a sapien ut mauris egestas fringilla eu eu magna. Ut<br> eu imperdiet leo, vel ultrices quam.</p>\n </div>\n </div>\n </div>\n\n\n\n\n\n\n\n <div id=\"exceriseFooter\">\n [Gruppenbezeichnung]\n </div>\n\n</body>\n\n</html>"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20609042/"
] |
74,616,597
|
<pre><code>var navbody: some View {
NavigationView {
ZStack {
somedarkcolorhere
List(searchModel.suggestions ?? [], rowContent: { text in
NavigationLink(destination: MediaSearchResultsView(searchText: text)) {
Text(text)
}
})
.overlay(SearchMediaHintsResultsScreen(searchModel: searchModel))
.searchable(text: $searchModel.searchText
// https://stackoverflow.com/questions/69668266/searchable-modifier-not-displaying-search-bar-below-navigation-bar-title
/* uncomment for search field to be shown initially and ever.
On iPad running 16.1 search field does show initially.
On iphone running 15.6.1 navigationTitle shows and search field
initially does not
*/
// , placement: .navigationBarDrawer(displayMode: .always)
)
.navigationTitle("v1_what_are_we_searching_for".localized)
}
.onChange(of: searchModel.searchText) { _ in
searchModel.processChangeOfSearchText()
}
.preference(key: ErrorPreferenceKey.self, value: observableError)
.sheet(isPresented: $observableError.showingError) {
ErrorView(error: observableError)
}
}
}
</code></pre>
<p>How to show .overlay with search results full width of the window?
currently it has gaps on the left and right</p>
<p><a href="https://i.stack.imgur.com/sOPnF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sOPnF.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74616625,
"author": "Wolfeur",
"author_id": 6201111,
"author_profile": "https://Stackoverflow.com/users/6201111",
"pm_score": 0,
"selected": false,
"text": ".exercisePart <div> display: block .exercisePart .exercisePart {\n display: flex;\n}\n"
},
{
"answer_id": 74616659,
"author": "Fabrizio Calderan",
"author_id": 1098851,
"author_profile": "https://Stackoverflow.com/users/1098851",
"pm_score": 1,
"selected": false,
"text": ".exercisePart flex-grow flex-shrink display: flex items: center #exceriseHead {\n font-family: Arial, Helvetica, sans-serif;\n font-size: 50px;\n font-weight: bold;\n border: 1px solid black;\n background-color: greenyellow;\n text-align: center;\n color: black;\n}\n\nbody {\n color: gainsboro;\n text-align: center;\n}\n\np {\n color: black\n}\n\n.exEnumeration {\n color: green;\n}\n\n#exceriseFooter {\n font-family: Arial, Helvetica, sans-serif;\n font-size: 10px;\n font-weight: bold;\n border: 1px solid black;\n background-color: greenyellow;\n text-align: center;\n color: black;\n}\n\n.contentcolumnContent {\n display: flex;\n gap: 1rem;\n justify-content: space-between;\n}\n\n.exercisePart {\n flex: 1 1 auto;\n display: flex;\n gap: .25rem;\n align-items: center;\n } <!DOCTYPE html>\n\n<head>\n <meta charset=\"utf-8\">\n <title>Abgabeseite 3</title>\n <link rel=\"stylesheet\" href=\"cssaufgabe2.css\">\n <!-- TODO: Import der CSS Datei -->\n\n</head>\n\n<body>\n\n <h1>Übungsblatt 4</h1>\n\n <div id=\"exceriseHead\">\n Aufgabe 3\n </div>\n\n\n\n\n\n <div class=\"contentcolumnContent\">\n <div class=\"exercisePart\">\n\n <div class=\"exEnumeration\">\n <h1>a.)</h1>\n </div>\n <div>\n <!-- TODO: Beispieltext durch Aufgabentext ersetzen -->\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Aenean pellentesque aliquet imperdiet. Nam ut lacinia elit.<br> Fusce dictum lorem purus, a ullamcorper dolor dictum eu.<br> Proin a sapien ut mauris egestas fringilla eu eu magna. Ut<br> eu imperdiet leo, vel ultrices quam.</p>\n </div>\n\n </div>\n\n <div class=\"exercisePart\">\n\n <div class=\"exEnumeration\">\n <h1>b.)</h1>\n </div>\n <div>\n <!-- TODO: Beispieltext durch Aufgabentext ersetzen -->\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Aenean pellentesque aliquet imperdiet. <span class=\"code\">Nam ut lacinia<br> elit. </span> Fusce dictum lorem purus, a ullamcorper dolor<br> dictum eu. Proin a sapien ut mauris egestas\n fringilla eu eu<br> magna. Ut eu imperdiet leo, vel ultrices quam.</p>\n </div>\n </div>\n\n <div class=\"exercisePart\">\n <div class=\"exEnumeration\">\n <h1>c.)</h1>\n </div>\n <div>\n <!-- TODO: Beispieltext durch Aufgabentext ersetzen -->\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Aenean pellentesque aliquet imperdiet. Nam ut lacinia elit.<br> Fusce dictum lorem purus, a ullamcorper dolor dictum eu.<br> Proin a sapien ut mauris egestas fringilla eu eu magna. Ut<br> eu imperdiet leo, vel ultrices quam.</p>\n </div>\n </div>\n </div>\n\n\n\n\n\n\n\n <div id=\"exceriseFooter\">\n [Gruppenbezeichnung]\n </div>\n\n</body>\n\n</html>"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3544438/"
] |
74,616,599
|
<pre><code>import random
#yes or no
yrn = input("R u going to play black jack? (Y/N): ").upper()
if yrn == "Y":
player1 = random.randint(1,19)
player2 = random.randint(1,19)
print(player1,player2)
while True:
player1_yrn = input("Player 1, Do you want more numbers? (Y/N): ").upper()
if player1_yrn == "Y":
player1 = player1 + random.randint(1,19)
print(f"Player 1's number is {player1}")
else:
print(f"Player 1's number is {player1}")
quit()
player2_yrn = input("Player 2, Do you want more numbers? (Y/N) : ").upper()
if player2_yrn == "Y":
player2 = player2 + random.randint(1,19)
print(f"Player 2's number is {player2}")
else:
print(f"Player 2's number is {player2}")
</code></pre>
<p>What I want is when I press 'n', the asking loop needs to end only for that player.<br />
For example: When I press 'n' for the question: "Player 2, Do you want more numbers? (Y/N) : ", then the asking loop ends only for player 2 and the program only asks for player 1 for more numbers.</p>
|
[
{
"answer_id": 74616625,
"author": "Wolfeur",
"author_id": 6201111,
"author_profile": "https://Stackoverflow.com/users/6201111",
"pm_score": 0,
"selected": false,
"text": ".exercisePart <div> display: block .exercisePart .exercisePart {\n display: flex;\n}\n"
},
{
"answer_id": 74616659,
"author": "Fabrizio Calderan",
"author_id": 1098851,
"author_profile": "https://Stackoverflow.com/users/1098851",
"pm_score": 1,
"selected": false,
"text": ".exercisePart flex-grow flex-shrink display: flex items: center #exceriseHead {\n font-family: Arial, Helvetica, sans-serif;\n font-size: 50px;\n font-weight: bold;\n border: 1px solid black;\n background-color: greenyellow;\n text-align: center;\n color: black;\n}\n\nbody {\n color: gainsboro;\n text-align: center;\n}\n\np {\n color: black\n}\n\n.exEnumeration {\n color: green;\n}\n\n#exceriseFooter {\n font-family: Arial, Helvetica, sans-serif;\n font-size: 10px;\n font-weight: bold;\n border: 1px solid black;\n background-color: greenyellow;\n text-align: center;\n color: black;\n}\n\n.contentcolumnContent {\n display: flex;\n gap: 1rem;\n justify-content: space-between;\n}\n\n.exercisePart {\n flex: 1 1 auto;\n display: flex;\n gap: .25rem;\n align-items: center;\n } <!DOCTYPE html>\n\n<head>\n <meta charset=\"utf-8\">\n <title>Abgabeseite 3</title>\n <link rel=\"stylesheet\" href=\"cssaufgabe2.css\">\n <!-- TODO: Import der CSS Datei -->\n\n</head>\n\n<body>\n\n <h1>Übungsblatt 4</h1>\n\n <div id=\"exceriseHead\">\n Aufgabe 3\n </div>\n\n\n\n\n\n <div class=\"contentcolumnContent\">\n <div class=\"exercisePart\">\n\n <div class=\"exEnumeration\">\n <h1>a.)</h1>\n </div>\n <div>\n <!-- TODO: Beispieltext durch Aufgabentext ersetzen -->\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Aenean pellentesque aliquet imperdiet. Nam ut lacinia elit.<br> Fusce dictum lorem purus, a ullamcorper dolor dictum eu.<br> Proin a sapien ut mauris egestas fringilla eu eu magna. Ut<br> eu imperdiet leo, vel ultrices quam.</p>\n </div>\n\n </div>\n\n <div class=\"exercisePart\">\n\n <div class=\"exEnumeration\">\n <h1>b.)</h1>\n </div>\n <div>\n <!-- TODO: Beispieltext durch Aufgabentext ersetzen -->\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Aenean pellentesque aliquet imperdiet. <span class=\"code\">Nam ut lacinia<br> elit. </span> Fusce dictum lorem purus, a ullamcorper dolor<br> dictum eu. Proin a sapien ut mauris egestas\n fringilla eu eu<br> magna. Ut eu imperdiet leo, vel ultrices quam.</p>\n </div>\n </div>\n\n <div class=\"exercisePart\">\n <div class=\"exEnumeration\">\n <h1>c.)</h1>\n </div>\n <div>\n <!-- TODO: Beispieltext durch Aufgabentext ersetzen -->\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Aenean pellentesque aliquet imperdiet. Nam ut lacinia elit.<br> Fusce dictum lorem purus, a ullamcorper dolor dictum eu.<br> Proin a sapien ut mauris egestas fringilla eu eu magna. Ut<br> eu imperdiet leo, vel ultrices quam.</p>\n </div>\n </div>\n </div>\n\n\n\n\n\n\n\n <div id=\"exceriseFooter\">\n [Gruppenbezeichnung]\n </div>\n\n</body>\n\n</html>"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20634715/"
] |
74,616,600
|
<p>I'm playing with drawing on html canvas and I'm little confused of how different coordinate systems actually works. What I have learned so far is that there are more coordinate systems:</p>
<ul>
<li>canvas coordinate system</li>
<li>css coordinate system</li>
<li>physical (display) coordinate system</li>
</ul>
<p>So when I draw a line using <code>CanvasRenderingContext2D</code></p>
<pre><code>ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(3, 1);
ctx.lineTo(3, 5);
ctx.stroke();
</code></pre>
<p>before drawing pixels to the display, the path needs to be</p>
<ol>
<li>scaled according to the ctx transformation matrix (if any)</li>
<li>scaled according to the ratio between css canvas element dimensions (<code>canvas.style.width</code> and <code>canvas.style.height</code>) and canvas drawing dimensions (<code>canvas.width</code> and <code>canvas.height</code>)</li>
<li>scaled according to the <code>window.devicePixelRatio</code> (hi-res displays)</li>
</ol>
<p>Now when I want to draw a crisp line, I found that there are two things to fight with. The first one is that canvas uses antialiasing. So when I draw a line of thikness <code>1</code> at integer coordinates, it will be blurred.</p>
<p><a href="https://i.stack.imgur.com/ZNiDs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZNiDs.png" alt="enter image description here" /></a></p>
<p>To fix this, it needs to be shifted by 0.5 pixels</p>
<pre><code>ctx.moveTo(3.5, 1);
ctx.lineTo(3.5, 5);
</code></pre>
<p>The second thing to consider is <code>window.devicePixelRatio</code>. It is used to map logical css pixels to physical pixels. The snadard way how to adapt canvas to hi-res devices is to scale to the ratio</p>
<pre><code>const ratio = window.devicePixelRatio || 1;
const clientBoundingRectangle = canvas.getBoundingClientRect();
canvas.width = clientBoundingRectangle.width * ratio;
canvas.height = clientBoundingRectangle.height * ratio;
const ctx = canvas.getContext('2d');
ctx.scale(ratio, ratio);
</code></pre>
<p>My question is, how is the solution of the antialiasing problem related to the scaling for the hi-res displays?</p>
<p>Let's say my display is hi-res and <code>window.devicePixelRatio</code> is <code>2.0</code>. When I apply context scaling to adapt canvas to the hi-res display and want to draw the line with thickness of <code>1</code>, can I just ignore the context scale and draw</p>
<pre><code>ctx.moveTo(3.5, 1);
ctx.lineTo(3.5, 5);
</code></pre>
<p>which is in this case effectively</p>
<pre><code>ctx.moveTo(7, 2);
ctx.lineTo(7, 10);
</code></pre>
<p>or do I have to consider the scaling ratio and use something like</p>
<pre><code>ctx.moveTo(3.75, 1);
ctx.lineTo(3.75, 5);
</code></pre>
<p>to get the crisp line?</p>
|
[
{
"answer_id": 74616625,
"author": "Wolfeur",
"author_id": 6201111,
"author_profile": "https://Stackoverflow.com/users/6201111",
"pm_score": 0,
"selected": false,
"text": ".exercisePart <div> display: block .exercisePart .exercisePart {\n display: flex;\n}\n"
},
{
"answer_id": 74616659,
"author": "Fabrizio Calderan",
"author_id": 1098851,
"author_profile": "https://Stackoverflow.com/users/1098851",
"pm_score": 1,
"selected": false,
"text": ".exercisePart flex-grow flex-shrink display: flex items: center #exceriseHead {\n font-family: Arial, Helvetica, sans-serif;\n font-size: 50px;\n font-weight: bold;\n border: 1px solid black;\n background-color: greenyellow;\n text-align: center;\n color: black;\n}\n\nbody {\n color: gainsboro;\n text-align: center;\n}\n\np {\n color: black\n}\n\n.exEnumeration {\n color: green;\n}\n\n#exceriseFooter {\n font-family: Arial, Helvetica, sans-serif;\n font-size: 10px;\n font-weight: bold;\n border: 1px solid black;\n background-color: greenyellow;\n text-align: center;\n color: black;\n}\n\n.contentcolumnContent {\n display: flex;\n gap: 1rem;\n justify-content: space-between;\n}\n\n.exercisePart {\n flex: 1 1 auto;\n display: flex;\n gap: .25rem;\n align-items: center;\n } <!DOCTYPE html>\n\n<head>\n <meta charset=\"utf-8\">\n <title>Abgabeseite 3</title>\n <link rel=\"stylesheet\" href=\"cssaufgabe2.css\">\n <!-- TODO: Import der CSS Datei -->\n\n</head>\n\n<body>\n\n <h1>Übungsblatt 4</h1>\n\n <div id=\"exceriseHead\">\n Aufgabe 3\n </div>\n\n\n\n\n\n <div class=\"contentcolumnContent\">\n <div class=\"exercisePart\">\n\n <div class=\"exEnumeration\">\n <h1>a.)</h1>\n </div>\n <div>\n <!-- TODO: Beispieltext durch Aufgabentext ersetzen -->\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Aenean pellentesque aliquet imperdiet. Nam ut lacinia elit.<br> Fusce dictum lorem purus, a ullamcorper dolor dictum eu.<br> Proin a sapien ut mauris egestas fringilla eu eu magna. Ut<br> eu imperdiet leo, vel ultrices quam.</p>\n </div>\n\n </div>\n\n <div class=\"exercisePart\">\n\n <div class=\"exEnumeration\">\n <h1>b.)</h1>\n </div>\n <div>\n <!-- TODO: Beispieltext durch Aufgabentext ersetzen -->\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Aenean pellentesque aliquet imperdiet. <span class=\"code\">Nam ut lacinia<br> elit. </span> Fusce dictum lorem purus, a ullamcorper dolor<br> dictum eu. Proin a sapien ut mauris egestas\n fringilla eu eu<br> magna. Ut eu imperdiet leo, vel ultrices quam.</p>\n </div>\n </div>\n\n <div class=\"exercisePart\">\n <div class=\"exEnumeration\">\n <h1>c.)</h1>\n </div>\n <div>\n <!-- TODO: Beispieltext durch Aufgabentext ersetzen -->\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Aenean pellentesque aliquet imperdiet. Nam ut lacinia elit.<br> Fusce dictum lorem purus, a ullamcorper dolor dictum eu.<br> Proin a sapien ut mauris egestas fringilla eu eu magna. Ut<br> eu imperdiet leo, vel ultrices quam.</p>\n </div>\n </div>\n </div>\n\n\n\n\n\n\n\n <div id=\"exceriseFooter\">\n [Gruppenbezeichnung]\n </div>\n\n</body>\n\n</html>"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1894204/"
] |
74,616,602
|
<p>I want to get the rownumber of each row from a MySQL Table. I already read this <a href="https://stackoverflow.com/questions/8509996/is-there-a-way-to-get-the-row-number-in-mysql-like-the-rownum-in-oracle">article</a> and tried the suggested select statement as below,</p>
<pre><code>SELECT @rownum:=@rownum + 1 as row_number,
t.*
FROM (
select * from myTable
) t,
(SELECT @rownum := 0) r
</code></pre>
<p>But I am getting in syntax error as below when I ran in <code>Dbeaver</code>,</p>
<pre><code>SQL Error [1064] [42000]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'row_number,
t.*
FROM (
select * from myTable
) t,
(SELECT @r' at line 1
</code></pre>
<p>Can someone please help? I am new to MySQL. I am using version <code>8.0</code>. Once it's tested I would basically want to use this select in my <code>Apache Spark Code</code></p>
|
[
{
"answer_id": 74616684,
"author": "drdalle",
"author_id": 20207622,
"author_profile": "https://Stackoverflow.com/users/20207622",
"pm_score": 0,
"selected": false,
"text": " SELECT *, \n ROW_NUMBER() OVER(PARTITION BY 'some column' ) AS row_num \n FROM my_table\n"
},
{
"answer_id": 74616812,
"author": "Divya Prakash",
"author_id": 11983208,
"author_profile": "https://Stackoverflow.com/users/11983208",
"pm_score": 1,
"selected": false,
"text": "SELECT @rownum:=@rownum + 1 as row_num, \n t.*\nFROM ( \n select * from myTable\n) t,\n(SELECT @rownum := 0) r;\n row_number"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9008023/"
] |
74,616,617
|
<p>I'm trying to come up with a system where visual components like <code>foo</code> or <code>faa</code> would be stored in the <code>/components</code> folder, and each component would be in its folder with that components files, say <code>/foo</code>, and the component files <code>foo.component.css</code> and <code>foo.component.php</code> inside it.</p>
<p>The <code>name.component.php</code> has some <code>HTML</code> and a style <code><link></code> inside, referring to the <code>name.component.css.</code> which styles that component. Components are included in page files, such as <code>index.php</code>, which gets its <code><head></code> tag from <code>head.php</code>, which is outside the <code>root</code>.</p>
<p>The file hierarchy would look like this:</p>
<pre><code>├──* head.php
└──* /root
├──* index.php
└──* /components
├──* /foo
│ ├── foo.component.css
│ └── foo.component.php
└──* /faa
├── faa.component.css
└── faa.component.php
</code></pre>
<p>When <code>index.php</code> includes a component, its <code>CSS</code> will be added outside the <code><head></code>, which I would like to avoid. Is there a way to move the <code>CSS</code> link to the document <code><head></code> during the <code>PHP</code> execution, for example, with a custom function? The <code>CSS</code> needs to be moved from the <code>name.component.php</code> specifically, so manually adding the <code>CSS</code> to the <code>head.php</code> won't do.</p>
<p><strong>File: head.php</strong></p>
<pre class="lang-php prettyprint-override"><code><head>
<!-- Other non-component stylesheets here; -->
<!-- Component stylesheets would be moved here during PHP execution; -->
</head>
<body>
</code></pre>
<p><strong>File: index.php</strong></p>
<pre class="lang-php prettyprint-override"><code>require_once("../head.php");
require_once("coponents/foo.component.php");
</code></pre>
<p><strong>File: foo.component.php</strong></p>
<pre class="lang-php prettyprint-override"><code>// Can this be moved to the head during execution from this folder?
echo('<link href="/components/foo/foo.component.css" rel="stylesheet">');
// Some HTML elements here...
// Trigger something here that moves the CSS link to the head.php
</code></pre>
<p>Could buffering be an option here? Any pointers would be appreciated.</p>
|
[
{
"answer_id": 74617204,
"author": "Salketer",
"author_id": 1620194,
"author_profile": "https://Stackoverflow.com/users/1620194",
"pm_score": 2,
"selected": true,
"text": "// File foo.manifest.php\nclass FooComponent implements Component{\n public $stylesheets = ['foo.component.css'];\n public $javascripts= ['foo.component.js'];\n public $dependsOn = []; // You could set dependencies here so other components are loaded if needed.\n public $template = 'foo.component.php';\n}\n $components = [new Foo(),new Faa()];\nforeach($components as $component){\n foreach($component->stylesheet as $stylesheet){\n echo ('<link href=\"'.$stylesheet.'\" rel=\"stylesheet\">');\n }\n}\nrequire_once(\"../head.php\");\n\nforeach($components as $component){\n require_once($component->template); \n}\n"
},
{
"answer_id": 74617680,
"author": "user3425506",
"author_id": 3425506,
"author_profile": "https://Stackoverflow.com/users/3425506",
"pm_score": 0,
"selected": false,
"text": "<?= $headEls ?> $headEls $headEls $headEls $headEls = isset($headEls) ? $headEls : ''; $headEls"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18703252/"
] |
74,616,668
|
<p>I saw following hibernate validator code</p>
<pre><code>package org.hibernate.validator.constraints;
...
public @interface CreditCardNumber {
String message() default "{org.hibernate.validator.constraints.CreditCardNumber.message}";
...
}
</code></pre>
<p>and in the properties files has key value the credit card error message like</p>
<pre><code>org.hibernate.validator.constraints.CreditCardNumber.message = invalid credit card number
</code></pre>
<p>how do hibernate validator do such things<br />
i mean load properties on @interface?</p>
|
[
{
"answer_id": 74617204,
"author": "Salketer",
"author_id": 1620194,
"author_profile": "https://Stackoverflow.com/users/1620194",
"pm_score": 2,
"selected": true,
"text": "// File foo.manifest.php\nclass FooComponent implements Component{\n public $stylesheets = ['foo.component.css'];\n public $javascripts= ['foo.component.js'];\n public $dependsOn = []; // You could set dependencies here so other components are loaded if needed.\n public $template = 'foo.component.php';\n}\n $components = [new Foo(),new Faa()];\nforeach($components as $component){\n foreach($component->stylesheet as $stylesheet){\n echo ('<link href=\"'.$stylesheet.'\" rel=\"stylesheet\">');\n }\n}\nrequire_once(\"../head.php\");\n\nforeach($components as $component){\n require_once($component->template); \n}\n"
},
{
"answer_id": 74617680,
"author": "user3425506",
"author_id": 3425506,
"author_profile": "https://Stackoverflow.com/users/3425506",
"pm_score": 0,
"selected": false,
"text": "<?= $headEls ?> $headEls $headEls $headEls $headEls = isset($headEls) ? $headEls : ''; $headEls"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4478578/"
] |
74,616,671
|
<p>I have join table between t_table and s_table.<br />
there are many to many relationships between them.</p>
<p>s_table</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>s_value</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>3</td>
</tr>
</tbody>
</table>
</div>
<p>t_table</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>t_value</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>100</td>
</tr>
<tr>
<td>2</td>
<td>200</td>
</tr>
<tr>
<td>3</td>
<td>300</td>
</tr>
</tbody>
</table>
</div>
<p>t_id_s_id_table</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>s_id</th>
<th>t_id</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>3</td>
</tr>
</tbody>
</table>
</div>
<p>First, I aggregated t_value group by s_table id by this query</p>
<pre><code>SELECT
t_id_s_id_table.s_id,
JSON_AGG(t_value) AS json_agg
FROM
t_id_s_id_table
LEFT JOIN
t_table
ON
t_table.id = t_id_s_id_table.t_id
GROUP BY
t_id_s_id_table.s_id
</code></pre>
<p>And I got this result.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>s_id</th>
<th>json_agg</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>100, 200</td>
</tr>
<tr>
<td>2</td>
<td>200, 300</td>
</tr>
<tr>
<td>3</td>
<td>100, 300</td>
</tr>
</tbody>
</table>
</div><h2>What I would like to do</h2>
<p>I want to obtain all s_ids whose associated json_agg value includes 100.
(It means s_id = 1 and 3)</p>
<p>I tried the following query</p>
<pre><code> SELECT *
FROM (
SELECT
t_id_s_id_table.s_id,
JSON_AGG(t_value) AS json_agg
FROM
t_id_s_id_table
LEFT JOIN
t_table
ON
t_table.id = t_id_s_id_table.t_id
GROUP BY
t_id_s_id_table.s_id
)
WHERE COUNT(json_agg = 100) > 0
</code></pre>
<p>but it doesn't work for me.
I got error <code>operator does not exist: json = integer</code>.</p>
<p>How can I make SQL in order to obtain get this result?
I am using PostgreSQL 11.2.
Thank you in advance.</p>
|
[
{
"answer_id": 74617204,
"author": "Salketer",
"author_id": 1620194,
"author_profile": "https://Stackoverflow.com/users/1620194",
"pm_score": 2,
"selected": true,
"text": "// File foo.manifest.php\nclass FooComponent implements Component{\n public $stylesheets = ['foo.component.css'];\n public $javascripts= ['foo.component.js'];\n public $dependsOn = []; // You could set dependencies here so other components are loaded if needed.\n public $template = 'foo.component.php';\n}\n $components = [new Foo(),new Faa()];\nforeach($components as $component){\n foreach($component->stylesheet as $stylesheet){\n echo ('<link href=\"'.$stylesheet.'\" rel=\"stylesheet\">');\n }\n}\nrequire_once(\"../head.php\");\n\nforeach($components as $component){\n require_once($component->template); \n}\n"
},
{
"answer_id": 74617680,
"author": "user3425506",
"author_id": 3425506,
"author_profile": "https://Stackoverflow.com/users/3425506",
"pm_score": 0,
"selected": false,
"text": "<?= $headEls ?> $headEls $headEls $headEls $headEls = isset($headEls) ? $headEls : ''; $headEls"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11768681/"
] |
74,616,754
|
<p>I've recently discovered that redis has a <a href="https://github.com/opencypher/openCypher/blob/master/docs/property-graph-model.adoc" rel="nofollow noreferrer">property graph model</a> implementation called <a href="https://github.com/RedisGraph/RedisGraph#loading-redisgraph-into-redis" rel="nofollow noreferrer">redis graph</a> and it's amazing.</p>
<p>One thing that I really miss for my use-case though, is the ability to "watch" the data. In typical redis data structures I can enable <a href="https://redis.io/docs/manual/keyspace-notifications/" rel="nofollow noreferrer">Keyspace notifications</a> or <a href="https://redis.io/docs/manual/client-side-caching/" rel="nofollow noreferrer">client tracking</a> and be notified on the data mutations I'm interested in, pull data from the server or mark my local cache as "dirty".</p>
<p>I don't know how that would work for a property graph since relations are much more complex (and the key feature for that matter), but <strong>is there a way to watch or synchronize with data stored in redis graph?</strong></p>
|
[
{
"answer_id": 74617204,
"author": "Salketer",
"author_id": 1620194,
"author_profile": "https://Stackoverflow.com/users/1620194",
"pm_score": 2,
"selected": true,
"text": "// File foo.manifest.php\nclass FooComponent implements Component{\n public $stylesheets = ['foo.component.css'];\n public $javascripts= ['foo.component.js'];\n public $dependsOn = []; // You could set dependencies here so other components are loaded if needed.\n public $template = 'foo.component.php';\n}\n $components = [new Foo(),new Faa()];\nforeach($components as $component){\n foreach($component->stylesheet as $stylesheet){\n echo ('<link href=\"'.$stylesheet.'\" rel=\"stylesheet\">');\n }\n}\nrequire_once(\"../head.php\");\n\nforeach($components as $component){\n require_once($component->template); \n}\n"
},
{
"answer_id": 74617680,
"author": "user3425506",
"author_id": 3425506,
"author_profile": "https://Stackoverflow.com/users/3425506",
"pm_score": 0,
"selected": false,
"text": "<?= $headEls ?> $headEls $headEls $headEls $headEls = isset($headEls) ? $headEls : ''; $headEls"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4224575/"
] |
74,616,758
|
<p>I have the following in Call.xlsm, A2 contains the path to a second Workbook, Data.xlsm. A3 holds the sheetname I'm trying to copy from Data.xlsm to Call.xlsm.</p>
<p><a href="https://i.stack.imgur.com/z53DN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z53DN.png" alt="enter image description here" /></a></p>
<p>I understand the first step to copying a sheet from another workbook, is to open it the other workbook (this is in Call.xlsm):</p>
<pre><code>Sub GetData()
Dim filenameIS As String
filenameIS = Worksheets("Sheet1").Range("a2")
Workbooks.Open (filenameIS)
Workbooks(filenameis).WorkSheets("Data 2018").CopyBefore:=ThisWorkbook.Sheets(1))
End Sub
</code></pre>
<p>This returns:</p>
<blockquote>
<p>Compile error: Synatax error</p>
</blockquote>
<p>It doesn't like the :=</p>
|
[
{
"answer_id": 74616906,
"author": "Tim Williams",
"author_id": 478884,
"author_profile": "https://Stackoverflow.com/users/478884",
"pm_score": 2,
"selected": true,
"text": "Sub GetData()\n Dim filenameIS As String, wb As Workbook, wsInfo As Worksheet\n \n Set wsInfo = ThisWorkbook.Worksheets(\"Sheet1\")\n filenameIS = wsInfo.Range(\"a2\")\n \n Set wb = Workbooks.Open(filenameIS) 'get a reference to the opened workbook\n 'Copy the worksheet named in A3 over to `wb`\n wb.Worksheets(wsInfo.Range(\"A3\").Value).Copy _\n Before:=ThisWorkbook.Worksheets(1) \n\nEnd Sub\n"
},
{
"answer_id": 74617385,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 0,
"selected": false,
"text": "Sub ImportSheet()\n \n Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code\n Dim dws As Worksheet: Set dws = dwb.Sheets(\"Sheet1\")\n \n Dim sFilePath As String: sFilePath = CStr(dws.Range(\"A2\").Value)\n Dim sSheetName As String: sSheetName = CStr(dws.Range(\"A3\").Value)\n \n Dim IsFound As Boolean\n IsFound = CreateObject(\"Scripting.FileSystemObject\").FileExists(sFilePath)\n \n If Not IsFound Then\n MsgBox \"The file '\" & sFilePath & \"' doesn't exist.\", vbExclamation\n Exit Sub\n End If\n \n Dim swb As Workbook: Set swb = Workbooks.Open(sFilePath)\n \n Dim sws As Object ' if it's a worksheet, use 'Dim sws As Worksheet'\n On Error Resume Next\n Set sws = swb.Sheets(sSheetName)\n On Error GoTo 0\n \n If Not sws Is Nothing Then sws.Copy Before:=dwb.Sheets(1)\n \n swb.Close SaveChanges:=False\n \n If sws Is Nothing Then\n MsgBox \"Sheet '\" & sSheetName & \"' doesn't exist.\", vbExclamation\n Else\n MsgBox \"Sheet '\" & sSheetName & \"' imported.\", vbInformation\n End If\n \nEnd Sub\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15316309/"
] |
74,616,782
|
<p>In the <code>.git/objects/</code> folder there are many folders with files within such as <code>ab/cde...</code>. I understand that these are actually blobs <code>abcde...</code></p>
<p>Is there a way to obtain a flat file listing of all blobs under <code>.git/objects/</code> with no <code>/</code> being used a delimitor between <code>ab</code> and <code>cde</code> in the example above? For e.g.</p>
<pre><code>abcde....
ab812....
74axs...
</code></pre>
<p>I tried</p>
<pre><code>/.git/objects$ du -a .
</code></pre>
<p>This does list recursively all folders and files within the <code>/objects/</code> folder but the blobs are not listed since the command lists the folder followed by the filename (as the OS recognizes them, as opposed to git). Furthermore, the <code>du</code> command does not provide a flat listing in a single column -- it provides the output in two columns with a numeric entry (disk usage) in the first column.</p>
|
[
{
"answer_id": 74616906,
"author": "Tim Williams",
"author_id": 478884,
"author_profile": "https://Stackoverflow.com/users/478884",
"pm_score": 2,
"selected": true,
"text": "Sub GetData()\n Dim filenameIS As String, wb As Workbook, wsInfo As Worksheet\n \n Set wsInfo = ThisWorkbook.Worksheets(\"Sheet1\")\n filenameIS = wsInfo.Range(\"a2\")\n \n Set wb = Workbooks.Open(filenameIS) 'get a reference to the opened workbook\n 'Copy the worksheet named in A3 over to `wb`\n wb.Worksheets(wsInfo.Range(\"A3\").Value).Copy _\n Before:=ThisWorkbook.Worksheets(1) \n\nEnd Sub\n"
},
{
"answer_id": 74617385,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 0,
"selected": false,
"text": "Sub ImportSheet()\n \n Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code\n Dim dws As Worksheet: Set dws = dwb.Sheets(\"Sheet1\")\n \n Dim sFilePath As String: sFilePath = CStr(dws.Range(\"A2\").Value)\n Dim sSheetName As String: sSheetName = CStr(dws.Range(\"A3\").Value)\n \n Dim IsFound As Boolean\n IsFound = CreateObject(\"Scripting.FileSystemObject\").FileExists(sFilePath)\n \n If Not IsFound Then\n MsgBox \"The file '\" & sFilePath & \"' doesn't exist.\", vbExclamation\n Exit Sub\n End If\n \n Dim swb As Workbook: Set swb = Workbooks.Open(sFilePath)\n \n Dim sws As Object ' if it's a worksheet, use 'Dim sws As Worksheet'\n On Error Resume Next\n Set sws = swb.Sheets(sSheetName)\n On Error GoTo 0\n \n If Not sws Is Nothing Then sws.Copy Before:=dwb.Sheets(1)\n \n swb.Close SaveChanges:=False\n \n If sws Is Nothing Then\n MsgBox \"Sheet '\" & sSheetName & \"' doesn't exist.\", vbExclamation\n Else\n MsgBox \"Sheet '\" & sSheetName & \"' imported.\", vbInformation\n End If\n \nEnd Sub\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492307/"
] |
74,616,805
|
<p>Is it possible to set type of <code>filterIsInstance</code> extension at runtime.
For example I have list of <code>Item</code> and I nee to cast my list by specific condition:</p>
<pre><code>fun (items: List<Item>) {
items.filterIsInstance<if(someCondition) OldItem else NewItem>()
}
</code></pre>
<p>I understand that such code cannot work, but is it possible to do something like this in runtime, please help me.</p>
|
[
{
"answer_id": 74616906,
"author": "Tim Williams",
"author_id": 478884,
"author_profile": "https://Stackoverflow.com/users/478884",
"pm_score": 2,
"selected": true,
"text": "Sub GetData()\n Dim filenameIS As String, wb As Workbook, wsInfo As Worksheet\n \n Set wsInfo = ThisWorkbook.Worksheets(\"Sheet1\")\n filenameIS = wsInfo.Range(\"a2\")\n \n Set wb = Workbooks.Open(filenameIS) 'get a reference to the opened workbook\n 'Copy the worksheet named in A3 over to `wb`\n wb.Worksheets(wsInfo.Range(\"A3\").Value).Copy _\n Before:=ThisWorkbook.Worksheets(1) \n\nEnd Sub\n"
},
{
"answer_id": 74617385,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 0,
"selected": false,
"text": "Sub ImportSheet()\n \n Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code\n Dim dws As Worksheet: Set dws = dwb.Sheets(\"Sheet1\")\n \n Dim sFilePath As String: sFilePath = CStr(dws.Range(\"A2\").Value)\n Dim sSheetName As String: sSheetName = CStr(dws.Range(\"A3\").Value)\n \n Dim IsFound As Boolean\n IsFound = CreateObject(\"Scripting.FileSystemObject\").FileExists(sFilePath)\n \n If Not IsFound Then\n MsgBox \"The file '\" & sFilePath & \"' doesn't exist.\", vbExclamation\n Exit Sub\n End If\n \n Dim swb As Workbook: Set swb = Workbooks.Open(sFilePath)\n \n Dim sws As Object ' if it's a worksheet, use 'Dim sws As Worksheet'\n On Error Resume Next\n Set sws = swb.Sheets(sSheetName)\n On Error GoTo 0\n \n If Not sws Is Nothing Then sws.Copy Before:=dwb.Sheets(1)\n \n swb.Close SaveChanges:=False\n \n If sws Is Nothing Then\n MsgBox \"Sheet '\" & sSheetName & \"' doesn't exist.\", vbExclamation\n Else\n MsgBox \"Sheet '\" & sSheetName & \"' imported.\", vbInformation\n End If\n \nEnd Sub\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15742980/"
] |
74,616,824
|
<p>In ms doc <a href="https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding</a>, in <strong>Listing of encodings</strong> section, in the encodings table, at the <strong>gb2312</strong> row, there is a mark in <strong>.NET Framework support</strong> column, that means gb2312 is natively supported by .NET Framework.</p>
<p>But when I call</p>
<pre><code>System.Text.Encoding.GetEncoding("gb2312")
</code></pre>
<p>in my program, it gives me a Exception in a Win11 machine and another Windows Server 2008 machine, with message:</p>
<pre><code>'GB2312' is not a supported encoding name
</code></pre>
<p>But it gets that gb2312 Encoding correctly in my Win10 machine in which I build the program.</p>
<p>My program is built with .NET Framework 4.6.2, so I think gb2312 is natively supported, so what is wrong?</p>
<p>I did some search, which suggest</p>
<pre><code>Encoding.RegisterProvider(new CodePagesEncodingProvider())
</code></pre>
<p>but it's a solution for .NET Core. I think it doesn't address the root cause and isn't a good fix for .NET Framework.</p>
<p>UPDATE: the code which call <em>GetEncoding</em> is inside a dll</p>
|
[
{
"answer_id": 74616906,
"author": "Tim Williams",
"author_id": 478884,
"author_profile": "https://Stackoverflow.com/users/478884",
"pm_score": 2,
"selected": true,
"text": "Sub GetData()\n Dim filenameIS As String, wb As Workbook, wsInfo As Worksheet\n \n Set wsInfo = ThisWorkbook.Worksheets(\"Sheet1\")\n filenameIS = wsInfo.Range(\"a2\")\n \n Set wb = Workbooks.Open(filenameIS) 'get a reference to the opened workbook\n 'Copy the worksheet named in A3 over to `wb`\n wb.Worksheets(wsInfo.Range(\"A3\").Value).Copy _\n Before:=ThisWorkbook.Worksheets(1) \n\nEnd Sub\n"
},
{
"answer_id": 74617385,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 0,
"selected": false,
"text": "Sub ImportSheet()\n \n Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code\n Dim dws As Worksheet: Set dws = dwb.Sheets(\"Sheet1\")\n \n Dim sFilePath As String: sFilePath = CStr(dws.Range(\"A2\").Value)\n Dim sSheetName As String: sSheetName = CStr(dws.Range(\"A3\").Value)\n \n Dim IsFound As Boolean\n IsFound = CreateObject(\"Scripting.FileSystemObject\").FileExists(sFilePath)\n \n If Not IsFound Then\n MsgBox \"The file '\" & sFilePath & \"' doesn't exist.\", vbExclamation\n Exit Sub\n End If\n \n Dim swb As Workbook: Set swb = Workbooks.Open(sFilePath)\n \n Dim sws As Object ' if it's a worksheet, use 'Dim sws As Worksheet'\n On Error Resume Next\n Set sws = swb.Sheets(sSheetName)\n On Error GoTo 0\n \n If Not sws Is Nothing Then sws.Copy Before:=dwb.Sheets(1)\n \n swb.Close SaveChanges:=False\n \n If sws Is Nothing Then\n MsgBox \"Sheet '\" & sSheetName & \"' doesn't exist.\", vbExclamation\n Else\n MsgBox \"Sheet '\" & sSheetName & \"' imported.\", vbInformation\n End If\n \nEnd Sub\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2319206/"
] |
74,616,829
|
<p>I want to print below code.</p>
<p>!!!!**
!!!****
!!******
!********</p>
<p>So I use while loop with i, j. But, in some parts, the output of ! becomes weird.
I tried some case, there is no problem if the i and j are in ascending order, but there is a problem if they are in descending order. Below my code, print(i, j) means there was no problem with the value of i and j.</p>
<pre><code>i = 0
j = 6
s1 = ""
s2 = ""
while True:
i += 1
j -= 1
if i > 5: break
s1 = f"{s1:!<{j}}"
s2 = f"{s2:*^{i*2}}"
print(i, j)
print(s1+s2)
</code></pre>
<pre><code>1 5
!!!!!**
2 4
!!!!!****
3 3
!!!!!******
4 2
!!!!!********
5 1
!!!!!**********
</code></pre>
|
[
{
"answer_id": 74617037,
"author": "Gameplay",
"author_id": 15923186,
"author_profile": "https://Stackoverflow.com/users/15923186",
"pm_score": 0,
"selected": false,
"text": "def print_pattern(bangs: int, stars: int)->None:\n output = f\"{'!'*bangs}{'*'*stars}\"\n print(output)\n i, j = 0, 6\ntotal = i+1\nwhile i+j == total:\n if i>5:\n break\n print_pattern(bangs=i, stars=j)\n i+=1\n j-=1\n"
},
{
"answer_id": 74617101,
"author": "NobleX7",
"author_id": 20635205,
"author_profile": "https://Stackoverflow.com/users/20635205",
"pm_score": -1,
"selected": false,
"text": "s1 = f\"{s1:!<{j}}\" s1 = \"\""
},
{
"answer_id": 74617134,
"author": "AntonioRB",
"author_id": 3645050,
"author_profile": "https://Stackoverflow.com/users/3645050",
"pm_score": 0,
"selected": false,
"text": "i = 0\nj = 6\ns1 = \"\"\ns2 = \"\"\nwhile True:\n i += 1\n j -= 1\n if i >= 5:\n break\n s1 = f\"{'!'*(j-1)}\"\n s2 = f\"{s2:*^{i*2}}\"\n print(s1 + s2, end=\" \")\n !!!!** !!!**** !!****** !******** \n"
},
{
"answer_id": 74617250,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 0,
"selected": false,
"text": "M = 4\nN = 2\n\nfor m in range(M, 0, -1):\n print(f\"{'!' * m}{'*' * N} \", end='')\n N += 2\n\nprint('\\b')\n !!!!** !!!**** !!****** !********\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20635205/"
] |
74,616,852
|
<p>so i have to make an snakecase program</p>
<pre><code>camelcase = input("camelCase: ")
snakecase = camelcase.lower()
for c in camelcase:
if c.isupper():
snakecase += "_"
snakecase += c.lower()
print(snakecase)
</code></pre>
<p>with the for im going through each letter, the if is for finding the uppercase right? but im failing on the last part, i dont really understand how to not add the "_" and c.lower() at the end of the word but just replace it.</p>
|
[
{
"answer_id": 74616952,
"author": "Loïc Robert",
"author_id": 19033618,
"author_profile": "https://Stackoverflow.com/users/19033618",
"pm_score": -1,
"selected": false,
"text": "snakecase snakecase = str()"
},
{
"answer_id": 74617004,
"author": "Cpt.Hook",
"author_id": 20599896,
"author_profile": "https://Stackoverflow.com/users/20599896",
"pm_score": 2,
"selected": true,
"text": "+= _ snakecase myteststring_t_s myTestString camel_case = 'myTestString'\nsnake_case = \"\"\n\nfor c in camel_case:\n if c.isupper():\n snake_case += f'_{c.lower()}'\n else:\n snake_case += c\n\nprint(snake_case)\n"
},
{
"answer_id": 74617023,
"author": "Timur Shtatland",
"author_id": 967621,
"author_profile": "https://Stackoverflow.com/users/967621",
"pm_score": 2,
"selected": false,
"text": "camelcase = input(\"camelCase: \")\nsnakecase = ''.join(c if c.lower() == c else '_' + c.lower() for c in camelcase)\nprint(snakecase)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20574466/"
] |
74,616,896
|
<p>I think this is a basic question, but it seems to be frustrating me...</p>
<p>I am using R and have data in long format; a data.frame with each value a string. I want to produce a summary table of the counts of each value. So for the data:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Location</th>
<th>Colour</th>
</tr>
</thead>
<tbody>
<tr>
<td>North</td>
<td>red</td>
</tr>
<tr>
<td>North</td>
<td>blue</td>
</tr>
<tr>
<td>North</td>
<td>red</td>
</tr>
<tr>
<td>South</td>
<td>red</td>
</tr>
<tr>
<td>South</td>
<td>red</td>
</tr>
<tr>
<td>North</td>
<td>red</td>
</tr>
<tr>
<td>South</td>
<td>blue</td>
</tr>
<tr>
<td>North</td>
<td>blue</td>
</tr>
<tr>
<td>South</td>
<td>red</td>
</tr>
<tr>
<td>South</td>
<td>red</td>
</tr>
</tbody>
</table>
</div>
<p>I would like to produce the summary table:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Location</th>
<th>red</th>
<th>blue</th>
</tr>
</thead>
<tbody>
<tr>
<td>North</td>
<td>3</td>
<td>2</td>
</tr>
<tr>
<td>South</td>
<td>4</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>I've tried numerous attempts of reshape and cast. I'm drawing a blank as there are no numeric 'values' in the table.</p>
|
[
{
"answer_id": 74616973,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "dplyr::count() library(dplyr)\nlibrary(tidyr)\n\ndat %>% \n count(Location, Colour) %>% \n pivot_wider(names_from = Colour, values_from = n)\n# # A tibble: 2 × 3\n# Location blue red\n# <chr> <int> <int>\n# 1 North 2 3\n# 2 South 1 4\n table() table(Location = dat$Location, dat$Colour)\n# Location blue red\n# North 2 3\n# South 1 4\n table()"
},
{
"answer_id": 74617027,
"author": "sindri_baldur",
"author_id": 4552295,
"author_profile": "https://Stackoverflow.com/users/4552295",
"pm_score": 2,
"selected": false,
"text": "table() df |>\n with(table(Location, Colour)) |>\n rbind() |>\n as_tibble(rownames = \"Location\")\n\n Location blue red\n <chr> <int> <int>\n1 North 2 3\n2 South 1 4\n df = data.frame(\n Location = c(\"North\", \"North\", \"North\", \"South\", \"South\", \"North\", \"South\", \"North\", \"South\", \"South\"), \n Colour = c(\"red\", \"blue\", \"red\", \"red\", \"red\", \"red\", \"blue\", \"blue\", \"red\", \"red\" )\n)\n"
},
{
"answer_id": 74618338,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "tabyl janitor library(janitor)\ntabyl(df1, Location, Colour)\n Location blue red\n North 2 3\n South 1 4\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14327060/"
] |
74,616,911
|
<p>I have the following plot made with some data points,<a href="https://i.stack.imgur.com/dsAbn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dsAbn.png" alt="Plot" /></a>. What is the best Pythonic way to find the point through which the curve intersects the X-axis? Thanks for any help.</p>
<pre><code>-2.0 -2.22537043
-1.9 -2.22609532
-1.8 -2.22075396
-1.7 -2.22729678
-1.6 -2.22353721
-1.5 -2.22341588
-1.4 -2.2180032
-1.3 -2.22850037
-1.2 -2.22553919
-1.1 -2.22866368
-1.0 -2.22400234
-0.9 -2.22865694
-0.8 -2.22058969
-0.7 -2.22399086
-0.6 -2.20372207
-0.5 -2.22639477
-0.4 -2.10633351
-0.3 -2.03573848
-0.2 -1.52582935
-0.1 -0.344812049
0.0 1.61330696
0.1 2.21013059
0.2 2.22698993
0.3 2.22698993
0.4 2.22698993
0.5 2.22698993
0.6 2.22698993
0.7 2.21522144
0.8 2.22699297
0.9 2.22361681
1.0 2.22055266
1.1 2.22299154
1.2 2.21155482
1.3 2.22212628
1.4 2.22437687
1.5 2.22365865
1.6 2.21749658
1.7 2.22603657
1.8 2.22736
1.9 2.22471317
2.0 2.22724296
</code></pre>
<p>Update: Here is the data point.
How I'm finding it now? I take my mouse to the plot window and find the point manually, why it is not working? It is slow.</p>
|
[
{
"answer_id": 74617410,
"author": "sandcountyfrank",
"author_id": 9541277,
"author_profile": "https://Stackoverflow.com/users/9541277",
"pm_score": 4,
"selected": true,
"text": "from intersect import intersection\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx1 = np.linspace(-1, 1, 100)\ny1 = 1 / (1 + np.exp(-x1 * 25))\n\nx2 = np.linspace(-1, 1, 100)\ny2 = np.sin(x2 * 2.25) + 0.5\n\nx, y = intersection(x1, y1, x2, y2)\n\nplt.plot(x1, y1, c=\"r\")\nplt.plot(x2, y2, c=\"g\")\nplt.plot(x, y, \"*k\")\nplt.show()\n x1 from intersect import intersection\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndata = np.array(\n [\n [-2.0, -2.22537043],\n [-1.9, -2.22609532],\n [-1.8, -2.22075396],\n [-1.7, -2.22729678],\n [-1.6, -2.22353721],\n [-1.5, -2.22341588],\n [-1.4, -2.2180032],\n [-1.3, -2.22850037],\n [-1.2, -2.22553919],\n [-1.1, -2.22866368],\n [-1.0, -2.22400234],\n [-0.9, -2.22865694],\n [-0.8, -2.22058969],\n [-0.7, -2.22399086],\n [-0.6, -2.20372207],\n [-0.5, -2.22639477],\n [-0.4, -2.10633351],\n [-0.3, -2.03573848],\n [-0.2, -1.52582935],\n [-0.1, -0.344812049],\n [0.0, 1.61330696],\n [0.1, 2.21013059],\n [0.2, 2.22698993],\n [0.3, 2.22698993],\n [0.4, 2.22698993],\n [0.5, 2.22698993],\n [0.6, 2.22698993],\n [0.7, 2.21522144],\n [0.8, 2.22699297],\n [0.9, 2.22361681],\n [1.0, 2.22055266],\n [1.1, 2.22299154],\n [1.2, 2.21155482],\n [1.3, 2.22212628],\n [1.4, 2.22437687],\n [1.5, 2.22365865],\n [1.6, 2.21749658],\n [1.7, 2.22603657],\n [1.8, 2.22736],\n [1.9, 2.22471317],\n [2.0, 2.227242961]\n ]\n)\nx1, y1 = data[:, 0], data[:, 1]\n\nx2 = [np.min(x1), np.max(x1)]\ny2 = [0, 0]\n\nx, y = intersection(x1, y1, x2, y2)\n\nplt.plot(x1, y1, c=\"r\")\nplt.plot(x2, y2, c=\"g\")\nplt.plot(x, y, \"*k\")\nplt.show()\n"
},
{
"answer_id": 74617873,
"author": "Shmack",
"author_id": 3155240,
"author_profile": "https://Stackoverflow.com/users/3155240",
"pm_score": 0,
"selected": false,
"text": "import numpy as np\nvalues = np.loadtxt(r\"test.txt\", delimiter=\" \")\nx_intercepts = []\nfor i, v in enumerate(values):\n if i > 0:\n # if y > 0\n if v[1] > 0:\n previous_v = values[i - 1]\n # if the previous y == 0\n if previous_v[1] == 0:\n x_intercepts.append(previous_v[0])\n elif previous_v[1] < 0:\n # slope = y2 - y1 / x2 - x1\n # formula of linear equation -> y = mx + b\n # intercept -> b = y - m(x)\n slope = (v[1] - previous_v[1]) / (v[0] - previous_v[0])\n # if the slope is changing and not a constant\n if slope != 0:\n intercept = v[1] - (slope * v[0])\n # equation -> y = (slope * x) + intercept\n # equation -> y - intercept = (slope * x)\n # equation -> (y - intercept) / slope = x\n x_intercept = (0 - intercept) / slope\n x_intercepts.append(x_intercept)\n else:\n # if the if doesn't make it, we still need to check if the previous value was 0\n if values[i - 1][1] == 0:\n x_intercepts.append(values[i - 1][0])\nprint(x_intercepts)\n i v if i > 0: else == =="
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10755782/"
] |
74,616,972
|
<p>I found this script that creates dependent drop down lists on a sheet (mainWsName = "Sheet1") based on a reference table that's on another sheet (optionsWsName = "ReferenceData") where firstLevelColumn is the first drop down list on Sheet1, secondLevelColumn drop down list is created when the value is selected on firstLevelColumn on Sheet1, and finally thirdLevelColumn drop down list is created when the value is selected on secondLevelColumn on Sheet1</p>
<p>This script works on one sheet but doesn't work on multiple sheets.</p>
<pre><code>function onEdit(e)
{
var activeCell = e.range;
var val = activeCell.getValue();
var r = activeCell.getRow();
var c = activeCell.getColumn();
var wsName = activeCell.getSheet().getName();
if(wsName === mainWsName && c === firstLevelColumn && r > 1)
{
applyFirstLevelValidation(val,r);
}
else if(wsName === mainWsName && c === secondLevelColumn && r > 1)
{
applySecondLevelValidation(val,r);
}
}
var mainWsName = "Sheet1";
var optionsWsName = "ReferenceData";
var firstLevelColumn = 3;
var secondLevelColumn = 4;
var thirdLevelColumn = 5;
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(mainWsName);
var wsOptions = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(optionsWsName);
var options = wsOptions.getRange(2, 1,wsOptions.getLastRow()-1,3).getValues();
function applyFirstLevelValidation(val,r)
{
if(val === "")
{
ws.getRange(r, secondLevelColumn).clearContent();
ws.getRange(r, secondLevelColumn).clearDataValidations();
ws.getRange(r, thirdLevelColumn).clearContent();
ws.getRange(r, thirdLevelColumn).clearDataValidations();
} else
{
ws.getRange(r, secondLevelColumn).clearContent();
ws.getRange(r, secondLevelColumn).clearDataValidations();
ws.getRange(r, thirdLevelColumn).clearContent();
ws.getRange(r, thirdLevelColumn).clearDataValidations();
var filteredOptions = options.filter(function(o)
{
return o[0] === val
});
var listToApply = filteredOptions.map(function(o){ return o[1] });
var cell = ws.getRange(r, secondLevelColumn);
applyValidationToCell(listToApply,cell);
}
}
function applySecondLevelValidation(val,r)
{
if(val === "")
{
ws.getRange(r, thirdLevelColumn).clearContent();
ws.getRange(r, thirdLevelColumn).clearDataValidations();
} else
{
ws.getRange(r, thirdLevelColumn).clearContent();
var firstLevelColValue= ws.getRange(r,firstLevelColumn).getValue();
var filteredOptions = options.filter(function(o)
{
return o[0] === firstLevelColValue && o[1] === val
});
var listToApply = filteredOptions.map(function(o)
{
return o[2]
});
var cell = ws.getRange(r,thirdLevelColumn);
applyValidationToCell(listToApply,cell);
}
}
function applyValidationToCell(list,cell)
{
var rule = SpreadsheetApp
.newDataValidation()
.requireValueInList(list)
.setAllowInvalid(false)
.build();
cell.setDataValidation(rule);
}
</code></pre>
<p>I tried getting rid of mainWsName, moving it to a separate function and calling it inside onEdit but to no avail. I want this function to work on Sheet2, Sheet3, Sheet4, etc. as well.</p>
|
[
{
"answer_id": 74617410,
"author": "sandcountyfrank",
"author_id": 9541277,
"author_profile": "https://Stackoverflow.com/users/9541277",
"pm_score": 4,
"selected": true,
"text": "from intersect import intersection\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx1 = np.linspace(-1, 1, 100)\ny1 = 1 / (1 + np.exp(-x1 * 25))\n\nx2 = np.linspace(-1, 1, 100)\ny2 = np.sin(x2 * 2.25) + 0.5\n\nx, y = intersection(x1, y1, x2, y2)\n\nplt.plot(x1, y1, c=\"r\")\nplt.plot(x2, y2, c=\"g\")\nplt.plot(x, y, \"*k\")\nplt.show()\n x1 from intersect import intersection\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndata = np.array(\n [\n [-2.0, -2.22537043],\n [-1.9, -2.22609532],\n [-1.8, -2.22075396],\n [-1.7, -2.22729678],\n [-1.6, -2.22353721],\n [-1.5, -2.22341588],\n [-1.4, -2.2180032],\n [-1.3, -2.22850037],\n [-1.2, -2.22553919],\n [-1.1, -2.22866368],\n [-1.0, -2.22400234],\n [-0.9, -2.22865694],\n [-0.8, -2.22058969],\n [-0.7, -2.22399086],\n [-0.6, -2.20372207],\n [-0.5, -2.22639477],\n [-0.4, -2.10633351],\n [-0.3, -2.03573848],\n [-0.2, -1.52582935],\n [-0.1, -0.344812049],\n [0.0, 1.61330696],\n [0.1, 2.21013059],\n [0.2, 2.22698993],\n [0.3, 2.22698993],\n [0.4, 2.22698993],\n [0.5, 2.22698993],\n [0.6, 2.22698993],\n [0.7, 2.21522144],\n [0.8, 2.22699297],\n [0.9, 2.22361681],\n [1.0, 2.22055266],\n [1.1, 2.22299154],\n [1.2, 2.21155482],\n [1.3, 2.22212628],\n [1.4, 2.22437687],\n [1.5, 2.22365865],\n [1.6, 2.21749658],\n [1.7, 2.22603657],\n [1.8, 2.22736],\n [1.9, 2.22471317],\n [2.0, 2.227242961]\n ]\n)\nx1, y1 = data[:, 0], data[:, 1]\n\nx2 = [np.min(x1), np.max(x1)]\ny2 = [0, 0]\n\nx, y = intersection(x1, y1, x2, y2)\n\nplt.plot(x1, y1, c=\"r\")\nplt.plot(x2, y2, c=\"g\")\nplt.plot(x, y, \"*k\")\nplt.show()\n"
},
{
"answer_id": 74617873,
"author": "Shmack",
"author_id": 3155240,
"author_profile": "https://Stackoverflow.com/users/3155240",
"pm_score": 0,
"selected": false,
"text": "import numpy as np\nvalues = np.loadtxt(r\"test.txt\", delimiter=\" \")\nx_intercepts = []\nfor i, v in enumerate(values):\n if i > 0:\n # if y > 0\n if v[1] > 0:\n previous_v = values[i - 1]\n # if the previous y == 0\n if previous_v[1] == 0:\n x_intercepts.append(previous_v[0])\n elif previous_v[1] < 0:\n # slope = y2 - y1 / x2 - x1\n # formula of linear equation -> y = mx + b\n # intercept -> b = y - m(x)\n slope = (v[1] - previous_v[1]) / (v[0] - previous_v[0])\n # if the slope is changing and not a constant\n if slope != 0:\n intercept = v[1] - (slope * v[0])\n # equation -> y = (slope * x) + intercept\n # equation -> y - intercept = (slope * x)\n # equation -> (y - intercept) / slope = x\n x_intercept = (0 - intercept) / slope\n x_intercepts.append(x_intercept)\n else:\n # if the if doesn't make it, we still need to check if the previous value was 0\n if values[i - 1][1] == 0:\n x_intercepts.append(values[i - 1][0])\nprint(x_intercepts)\n i v if i > 0: else == =="
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20635175/"
] |
74,616,997
|
<p>I want to return my nested array in a foreach loop. In this foreach loop I need to add a foreach, because it is variable how many accordions exist.</p>
<p>But I can't get it to load the data from the "accordion" array into the frontend.
There is always an error somewhere.</p>
<p>I can't describe it any better right now.</p>
<p>Save</p>
<p>This is my treatments.php file:</p>
<pre><code>'treatments' => [
[ /* */
'img' => asset('img/logos/Dermatologie_Dr_med_Aresu_Naderi_Nienstedten_Logo.png'),
'title' => 'Klassische Dermatologie',
'teaser' => 'Ein wesentlicher Bestandteil im Behandlungskonzept meiner Hautarztpraxis ist die ästhetische Dermatologie und Lasermedizin.',
'pop-up' => 'derma',
'accordion' => [
[
'title' => 'test',
'content' => 'test2',
],
[
'title' => 'test',
'content' => 'test2',
],
],
],
]
</code></pre>
<p>And this is my Frontend Blade Code:</p>
<pre><code><div class="row">
@foreach( $treatments as $key => $value)
<?php print_r($value) ?>
<div class="col-md-4 py-5">
<img class="w-100" src="{!! __($value['img']) !!}" alt="{!! __($value['title']) !!}">
</div>
<div class="col-md-8 py-5">
<span class="treatmentsHeadline">{!! __($value['title']) !!}</span>
<p class="pt-3">{!! __($value['teaser']) !!}</p>
<div class="pt-3">
<button class="button-naderi" href="#{!! __($value['pop-up']) !!}">Mehr erfahren</button>
<button class="button-naderi" href="#{!! __($value['pop-up']) !!}">Termin vereinbaren</button>
</div>
</div>
@foreach($value as $acc)
<p>{!! __($acc['title']) !!}</p>
@endforeach
@endforeach
<p class="footer-vh"></p>
</div>
</code></pre>
<p>And this is the Array printed out:
<a href="https://i.stack.imgur.com/vSwCm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vSwCm.jpg" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74617410,
"author": "sandcountyfrank",
"author_id": 9541277,
"author_profile": "https://Stackoverflow.com/users/9541277",
"pm_score": 4,
"selected": true,
"text": "from intersect import intersection\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx1 = np.linspace(-1, 1, 100)\ny1 = 1 / (1 + np.exp(-x1 * 25))\n\nx2 = np.linspace(-1, 1, 100)\ny2 = np.sin(x2 * 2.25) + 0.5\n\nx, y = intersection(x1, y1, x2, y2)\n\nplt.plot(x1, y1, c=\"r\")\nplt.plot(x2, y2, c=\"g\")\nplt.plot(x, y, \"*k\")\nplt.show()\n x1 from intersect import intersection\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndata = np.array(\n [\n [-2.0, -2.22537043],\n [-1.9, -2.22609532],\n [-1.8, -2.22075396],\n [-1.7, -2.22729678],\n [-1.6, -2.22353721],\n [-1.5, -2.22341588],\n [-1.4, -2.2180032],\n [-1.3, -2.22850037],\n [-1.2, -2.22553919],\n [-1.1, -2.22866368],\n [-1.0, -2.22400234],\n [-0.9, -2.22865694],\n [-0.8, -2.22058969],\n [-0.7, -2.22399086],\n [-0.6, -2.20372207],\n [-0.5, -2.22639477],\n [-0.4, -2.10633351],\n [-0.3, -2.03573848],\n [-0.2, -1.52582935],\n [-0.1, -0.344812049],\n [0.0, 1.61330696],\n [0.1, 2.21013059],\n [0.2, 2.22698993],\n [0.3, 2.22698993],\n [0.4, 2.22698993],\n [0.5, 2.22698993],\n [0.6, 2.22698993],\n [0.7, 2.21522144],\n [0.8, 2.22699297],\n [0.9, 2.22361681],\n [1.0, 2.22055266],\n [1.1, 2.22299154],\n [1.2, 2.21155482],\n [1.3, 2.22212628],\n [1.4, 2.22437687],\n [1.5, 2.22365865],\n [1.6, 2.21749658],\n [1.7, 2.22603657],\n [1.8, 2.22736],\n [1.9, 2.22471317],\n [2.0, 2.227242961]\n ]\n)\nx1, y1 = data[:, 0], data[:, 1]\n\nx2 = [np.min(x1), np.max(x1)]\ny2 = [0, 0]\n\nx, y = intersection(x1, y1, x2, y2)\n\nplt.plot(x1, y1, c=\"r\")\nplt.plot(x2, y2, c=\"g\")\nplt.plot(x, y, \"*k\")\nplt.show()\n"
},
{
"answer_id": 74617873,
"author": "Shmack",
"author_id": 3155240,
"author_profile": "https://Stackoverflow.com/users/3155240",
"pm_score": 0,
"selected": false,
"text": "import numpy as np\nvalues = np.loadtxt(r\"test.txt\", delimiter=\" \")\nx_intercepts = []\nfor i, v in enumerate(values):\n if i > 0:\n # if y > 0\n if v[1] > 0:\n previous_v = values[i - 1]\n # if the previous y == 0\n if previous_v[1] == 0:\n x_intercepts.append(previous_v[0])\n elif previous_v[1] < 0:\n # slope = y2 - y1 / x2 - x1\n # formula of linear equation -> y = mx + b\n # intercept -> b = y - m(x)\n slope = (v[1] - previous_v[1]) / (v[0] - previous_v[0])\n # if the slope is changing and not a constant\n if slope != 0:\n intercept = v[1] - (slope * v[0])\n # equation -> y = (slope * x) + intercept\n # equation -> y - intercept = (slope * x)\n # equation -> (y - intercept) / slope = x\n x_intercept = (0 - intercept) / slope\n x_intercepts.append(x_intercept)\n else:\n # if the if doesn't make it, we still need to check if the previous value was 0\n if values[i - 1][1] == 0:\n x_intercepts.append(values[i - 1][0])\nprint(x_intercepts)\n i v if i > 0: else == =="
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74616997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18712347/"
] |
74,617,013
|
<p>I am working on an angular project that needs to load up pages and then display them one by one / two by two.</p>
<p>As per <a href="https://indepth.dev/posts/1279/rxjs-in-angular-when-to-subscribe-rarely#:%7E:text=So%20far%20as%20I%20can%20tell%2C%20you%20never%20have%20to%20subscribe%20to%20Observables%20inside%20services." rel="nofollow noreferrer">this article</a> and some other sources, subscribing in services is almost never necessary. So is there a way to rewrite this in pure reactive style using RxJS operators?</p>
<p>Here's what I have (simplified) :</p>
<pre><code>export class NavigationService {
private pages: Page[] = [];
private mode = Mode.SinglePage;
private index = 0;
private currentPages = new BehaviorSubject<Page[]>([]);
constructor(
private pageService: PageService,
private view: ViewService,
) {
this.pageService.pages$.subscribe(pages => {
this.setPages(pages);
});
this.view.mode$.subscribe(mode => {
this.setMode(mode);
});
}
private setPages(pages: Page[]) {
this.pages = pages;
this.updateCurrentPages();
}
private setMode(mode: Mode) {
this.mode = mode;
this.updateCurrentPages();
}
private updateCurrentPages() {
// get an array of current pages depending on pages array, mode & index
this.currentPages.next(...);
}
public goToNextPage() {
this.index += 1;
this.updateCurrentPages();
}
public get currentPages$() {
return this.currentPages.asObservable();
}
}
</code></pre>
<p>I've tried multiple solutions and didn't manage to get it right. The closest I got was using <code>scan()</code>, but it always reset my accumulated value when the outer observables (pages, mode) got updated.</p>
<p>Any help is appreciated, thanks !</p>
|
[
{
"answer_id": 74617410,
"author": "sandcountyfrank",
"author_id": 9541277,
"author_profile": "https://Stackoverflow.com/users/9541277",
"pm_score": 4,
"selected": true,
"text": "from intersect import intersection\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx1 = np.linspace(-1, 1, 100)\ny1 = 1 / (1 + np.exp(-x1 * 25))\n\nx2 = np.linspace(-1, 1, 100)\ny2 = np.sin(x2 * 2.25) + 0.5\n\nx, y = intersection(x1, y1, x2, y2)\n\nplt.plot(x1, y1, c=\"r\")\nplt.plot(x2, y2, c=\"g\")\nplt.plot(x, y, \"*k\")\nplt.show()\n x1 from intersect import intersection\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndata = np.array(\n [\n [-2.0, -2.22537043],\n [-1.9, -2.22609532],\n [-1.8, -2.22075396],\n [-1.7, -2.22729678],\n [-1.6, -2.22353721],\n [-1.5, -2.22341588],\n [-1.4, -2.2180032],\n [-1.3, -2.22850037],\n [-1.2, -2.22553919],\n [-1.1, -2.22866368],\n [-1.0, -2.22400234],\n [-0.9, -2.22865694],\n [-0.8, -2.22058969],\n [-0.7, -2.22399086],\n [-0.6, -2.20372207],\n [-0.5, -2.22639477],\n [-0.4, -2.10633351],\n [-0.3, -2.03573848],\n [-0.2, -1.52582935],\n [-0.1, -0.344812049],\n [0.0, 1.61330696],\n [0.1, 2.21013059],\n [0.2, 2.22698993],\n [0.3, 2.22698993],\n [0.4, 2.22698993],\n [0.5, 2.22698993],\n [0.6, 2.22698993],\n [0.7, 2.21522144],\n [0.8, 2.22699297],\n [0.9, 2.22361681],\n [1.0, 2.22055266],\n [1.1, 2.22299154],\n [1.2, 2.21155482],\n [1.3, 2.22212628],\n [1.4, 2.22437687],\n [1.5, 2.22365865],\n [1.6, 2.21749658],\n [1.7, 2.22603657],\n [1.8, 2.22736],\n [1.9, 2.22471317],\n [2.0, 2.227242961]\n ]\n)\nx1, y1 = data[:, 0], data[:, 1]\n\nx2 = [np.min(x1), np.max(x1)]\ny2 = [0, 0]\n\nx, y = intersection(x1, y1, x2, y2)\n\nplt.plot(x1, y1, c=\"r\")\nplt.plot(x2, y2, c=\"g\")\nplt.plot(x, y, \"*k\")\nplt.show()\n"
},
{
"answer_id": 74617873,
"author": "Shmack",
"author_id": 3155240,
"author_profile": "https://Stackoverflow.com/users/3155240",
"pm_score": 0,
"selected": false,
"text": "import numpy as np\nvalues = np.loadtxt(r\"test.txt\", delimiter=\" \")\nx_intercepts = []\nfor i, v in enumerate(values):\n if i > 0:\n # if y > 0\n if v[1] > 0:\n previous_v = values[i - 1]\n # if the previous y == 0\n if previous_v[1] == 0:\n x_intercepts.append(previous_v[0])\n elif previous_v[1] < 0:\n # slope = y2 - y1 / x2 - x1\n # formula of linear equation -> y = mx + b\n # intercept -> b = y - m(x)\n slope = (v[1] - previous_v[1]) / (v[0] - previous_v[0])\n # if the slope is changing and not a constant\n if slope != 0:\n intercept = v[1] - (slope * v[0])\n # equation -> y = (slope * x) + intercept\n # equation -> y - intercept = (slope * x)\n # equation -> (y - intercept) / slope = x\n x_intercept = (0 - intercept) / slope\n x_intercepts.append(x_intercept)\n else:\n # if the if doesn't make it, we still need to check if the previous value was 0\n if values[i - 1][1] == 0:\n x_intercepts.append(values[i - 1][0])\nprint(x_intercepts)\n i v if i > 0: else == =="
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9397419/"
] |
74,617,038
|
<p>I have a console application built into an .exe, and a WriteLog module built into a .dll. The WriteLog module is referenced within the console app project.
The module is using Directory.GetCurrentDirectory() for creating a Log folder and writing .log files in the same folder next to the executable. This all works as expected when debugging on my dev machine, and also when the .exe is manually executed on the server. However, when the executable is called by Windows Task Scheduler the logs are written to the C:\Windows\SysWOW64 folder. It seems that my Directory.GetCurrentDirectory() is returning the path of the parent process (taskeng.exe or taskmgr.exe) and not the path of the running executable.
I have tried a couple of different ways of getting the path like Environment.CurrentDirectory() with no success. How can I get my program to create the log files in the desired location in the same folder as the executable?</p>
<p>Notes: Both the console app and the WriteLog module are written in VB.Net 4.7.2 and the
Server is Windows Server 2012 R2 Standard</p>
|
[
{
"answer_id": 74651194,
"author": "Lundt",
"author_id": 19564057,
"author_profile": "https://Stackoverflow.com/users/19564057",
"pm_score": 0,
"selected": false,
"text": "Imports System\nImports System.Runtime.InteropServices\nPublic Module AnythingYouWantToCallIt\n\n\n Sub Main\n Console.writeline(System.Windows.Forms.Application.StartupPath)\n End Sub \nEnd Module\n \"C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\vbc.exe\" /target:exe /out:\"%~dp0\\Tee.exe\" \"%~dp0\\Tee.vb\"\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4186464/"
] |
74,617,132
|
<p>I'm self-learning SML and am currently am stuck with the concept of recursion between two lists of varying sizes.</p>
<p>Suppose you have two int lists of varying size, and a function that multiplies two numbers, like so:</p>
<pre><code>val mul = fn(a, b) => a * b;
</code></pre>
<p>I want to use this function to be passed as a parameter into another function, which multiplies the numbers in the same index recursively until at least one of the lists is empty. So</p>
<pre><code>val list1 = [1, 3, 5, 7];
val list2 = [2, 6, 3];
</code></pre>
<p>would be passed through that same function with <code>mul</code> and <code>35</code> would be returned, as <code>1*2 + 3*6 + 5*3</code> would be calculated.</p>
<p>My knowledge of how SML works is a bit limited, as I'm not exactly sure how to carry the result of the sum forward during the recursion, nor how to handle the base case when one of either lists terminates early. Could someone point me in the right direction in thinking of this problem?</p>
|
[
{
"answer_id": 74617827,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 2,
"selected": true,
"text": "fun mulAndSum acc ([], []) = ...\n | mulAndSum acc ([], _) = ...\n | mulAndSum acc (_, []) = ...\n | mulAndSum acc ((x::xs), (y::ys)) = mulAndSum (...) (xs, ys)\n mulAndSum 0 ([1, 3, 5, 7], [2, 4, 6])\n"
},
{
"answer_id": 74664840,
"author": "sshine",
"author_id": 235908,
"author_profile": "https://Stackoverflow.com/users/235908",
"pm_score": 0,
"selected": false,
"text": "map zip fun add (x, y) = x + y\nfun mul (x, y) = x * y\nfun sum xs = foldl add 0 xs\nval zip = ListPair.zip\n\nfun mulAndSum xs ys = sum (map mul (zip xs ys))\n zip"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14587195/"
] |
74,617,154
|
<p>I can't seem to get my delete, edit and add review functionality working. The errors come as soon as I try to navigate to the urls I have set up. When I try and add a new review using my link on the reviews page I get the below message:</p>
<p>TemplateDoesNotExist at /reviews/add</p>
<p>I don't understand why because I have linked the url above to the template, which I have created.</p>
<p>The issue I have with my edit/delete views is that the url it searches for when I click the button is just <strong>/edit/</strong> or <strong>/delete/</strong> rather than <strong>reviews/edit/int:pk</strong> or <strong>reviews/delete/int:pk</strong> as per my urls.</p>
<p>I have pasted my code below, any help would be much appreciated! I have the feeling I am going to kick myself when I realise!</p>
<p>reviews.html:</p>
<pre><code>{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid home-container">
<div class="row align-items-center">
<div class="col-sm-12 text-center mt-4">
<h2><strong>Reviews</strong></h2>
</div>
</div>
{% for review in reviews %}
<hr class="hr-1">
<div class="row featurette">
<div class="col-sm-12">
<h2 class="featurette-heading">{{ review.title }}</h2>
<p class="lead">{{ review.content }}</p>
<div class="row justify-content-between mx-1">
<p>By: {{ review.user }}</p>
<p>Created on: {{ review.created }}</p>
<p>Last Updated: {{ review.updated }}</p>
</div>
<!-- Add user authentication if -->
<div class="text-center">
<a href="edit/{{ review.id }}" class="mx-2">
<button class="positive-button mb-2">Edit</button></a>
<a href="delete/{{ review.id }}" class="mx-2 mb-2">
<button class="negative-button">Delete</button></a>
</div>
</div>
</div>
{% endfor %}
<div class="row">
<div class="col-sm-12 text-center py-4">
{% if user.is_authenticated %}
<a href="{% url 'home:add_review' %}">
<button class="positive-button-lg">Add a review</button>
</a>
{% else %}
<p>If you would like to add your own review, please login or sign up if you haven't already!</p>
{% endif %}
</div>
</div>
</div>
{% endblock %}
</code></pre>
<p>add_review.html:</p>
<pre><code>{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-auto text-center p-3">
<form method="post" style="margin-top: 1.3em;">
{{ review_form }}
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</form>
</div>
</div>
{% endblock %}
</code></pre>
<p>views.py:</p>
<pre><code>from django.shortcuts import render
from django.views import View
from django.urls import reverse_lazy
from django.views.generic import UpdateView, DeleteView
from .models import Reviews
from .forms import ReviewForm
def home(request):
''' Returns the home page.'''
return render(request, 'home/index.html')
def reviews(request):
''' Returns the reviews page.'''
serialized_reviews = []
reviews = Reviews.objects.all()
for review in reviews:
serialized_reviews.append({
"title": review.title,
"content": review.content,
"user": review.user,
"created": review.created,
"updated": review.updated,
})
context = {
"reviews": serialized_reviews
}
print(serialized_reviews)
return render(request, 'home/reviews.html', context)
class AddReview(View):
'''View which allows the user to add a new review.'''
def get(self, request, *args, **kwargs):
review = Reviews
review_form = ReviewForm
context = {
'review': review,
'review_form': review_form,
'user': review.user,
'title': review.title,
'content': review.content,
}
return render(request, 'add_review.html', context)
def post(self, request, *args, **kwargs):
review_form = ReviewForm(data=request.POST)
if review_form.is_valid():
obj = review_form.save(commit=False)
obj.user = request.user
obj.save()
return redirect("home:reviews")
class DeleteReview(DeleteView):
'''View which allows the user to delete the selected review.'''
model = Reviews
template_name = 'delete_review.html'
success_url = reverse_lazy('reviews')
class EditReview(UpdateView):
'''View which allows the user to edit the selected review.'''
model = Reviews
template_name = 'edit_review.html'
fields = ['title', 'content']
</code></pre>
<p>urls.py:</p>
<pre><code>from django.urls import path
from . import views
app_name = 'home'
urlpatterns = [
path('', views.home, name='home'),
path('reviews', views.reviews, name='reviews'),
path('reviews/add', views.AddReview.as_view(), name='add_review'),
path('reviews/delete/<int:pk>', views.DeleteReview.as_view(), name='delete_review'),
path('reviews/edit/<int:pk>', views.EditReview.as_view(), name='edit_review'),
]
</code></pre>
|
[
{
"answer_id": 74617827,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 2,
"selected": true,
"text": "fun mulAndSum acc ([], []) = ...\n | mulAndSum acc ([], _) = ...\n | mulAndSum acc (_, []) = ...\n | mulAndSum acc ((x::xs), (y::ys)) = mulAndSum (...) (xs, ys)\n mulAndSum 0 ([1, 3, 5, 7], [2, 4, 6])\n"
},
{
"answer_id": 74664840,
"author": "sshine",
"author_id": 235908,
"author_profile": "https://Stackoverflow.com/users/235908",
"pm_score": 0,
"selected": false,
"text": "map zip fun add (x, y) = x + y\nfun mul (x, y) = x * y\nfun sum xs = foldl add 0 xs\nval zip = ListPair.zip\n\nfun mulAndSum xs ys = sum (map mul (zip xs ys))\n zip"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19053957/"
] |
74,617,156
|
<p>I'm trying to write a script that will check if the first line of a text file has changed and print the value once. It needs to be an infinite loop so It will always keep checking for a change. The problem I'm having is when the value is changed it will keep constantly printing and it does not detect the new change.
What I need to is the script to constantly check the first line and print the value once if it changes and do nothing if it does not change.
This is what I tried so far:</p>
<pre class="lang-py prettyprint-override"><code>def getvar():
with open('readme.txt') as f:
first_line = f.readline().strip('\n')
result = first_line
return result
def checkvar():
initial = getvar()
print("Initial var: {}".format(initial))
while True:
current = getvar()
if initial == current:
pass
else:
print("var has changed!")
pass
checkvar()
</code></pre>
|
[
{
"answer_id": 74617827,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 2,
"selected": true,
"text": "fun mulAndSum acc ([], []) = ...\n | mulAndSum acc ([], _) = ...\n | mulAndSum acc (_, []) = ...\n | mulAndSum acc ((x::xs), (y::ys)) = mulAndSum (...) (xs, ys)\n mulAndSum 0 ([1, 3, 5, 7], [2, 4, 6])\n"
},
{
"answer_id": 74664840,
"author": "sshine",
"author_id": 235908,
"author_profile": "https://Stackoverflow.com/users/235908",
"pm_score": 0,
"selected": false,
"text": "map zip fun add (x, y) = x + y\nfun mul (x, y) = x * y\nfun sum xs = foldl add 0 xs\nval zip = ListPair.zip\n\nfun mulAndSum xs ys = sum (map mul (zip xs ys))\n zip"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18368599/"
] |
74,617,179
|
<p>I want to select the value of the "data" attribute where the "key" attribute matches a specific search.</p>
<p>The XML file will look like this.</p>
<pre><code><connections>
<production>
<connection key="KEY1" data="value1" />
<connection key="KEY2" data="value2" />
<connection key="KEY3" data="value3" />
</production>
</connections>
</code></pre>
<p>So is there a way to return the value of the data attribute by searching for key = key1 for example?</p>
|
[
{
"answer_id": 74617535,
"author": "Ethan Shannon",
"author_id": 18621413,
"author_profile": "https://Stackoverflow.com/users/18621413",
"pm_score": 2,
"selected": true,
"text": "using System.Xml.Linq;\n\nvar xmlStr = File.ReadAllText(\"Testfile.xml\");\nXElement root = XElement.Parse(xmlStr);\nvar data = root.Element(\"production\")\n .Elements().Where(x => x.Attribute(\"key\").Value == \"KEY1\")\n .Select(x=>x.Attribute(\"data\").Value)\n .First();\nConsole.WriteLine(data);\n"
},
{
"answer_id": 74617654,
"author": "st4ticv0id",
"author_id": 13028455,
"author_profile": "https://Stackoverflow.com/users/13028455",
"pm_score": 0,
"selected": false,
"text": "private void YOUR_METHOD_NAME()\n{\n // Call GetXml method which returns the result in the form of string\n string result = GetXml(\"xmlfile.xml\", \"KEY2\");\n Debug.WriteLine(result);\n}\n\nprivate string GetXml(string filePath, string searchKey)\n{\n XmlDocument doc = new XmlDocument();\n doc.Load(filePath);\n\n XmlNodeList nodes = doc.SelectSingleNode(\"//connections/production\").ChildNodes;\n\n string output = string.Empty;\n foreach (XmlNode node in nodes)\n {\n if (node.Attributes[\"key\"].Value == searchKey)\n {\n output = node.Attributes[\"data\"].Value;\n }\n else\n {\n continue;\n }\n }\n\n return output;\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18337808/"
] |
74,617,192
|
<p>I have a website that I am making with bootstrap, firebase and JQuery. I have a button that when clicked is supposed to display a modal so the user can enter data. The data will be saved in my firebase database and then displayed on a table on the website. However, no matter what I do nothing happens when I click the button. The modal does not display.
This is what the modal looks like:</p>
<p><a href="https://i.stack.imgur.com/Dnlo8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dnlo8.png" alt="Modal that is meant to appear" /></a></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>import { getDatabase } from "https://www.gstatic.com/firebasejs/7.15.0/firebase-database.js";
import { initializeApp } from "https://www.gstatic.com/firebasejs/7.15.0/firebase-app.js";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "xxxxxxxxxx",
authDomain: "xxxxxx",
databaseURL: "xxxxxxx",
projectId: "xxxxx",
storageBucket: "xxxxxxxxxxx",
messagingSenderId: "xxxxxx",
appId: "xxxxxxxxx"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = firebase.database(app);
coleccionProductos = db.ref().child('productos');
bodyProductos = $('#bodyProductos').val();
console.log(bodyProductos);
$('form').submit(function(e){
e.preventDefault();
let id = $('#id').val();
let codigo = $('#codigo').val();
let descripcion = $('#descripcion').val();
let cantidad = $('#cantidad').val();
let idFirebase = id;
if(idFirebase == ''){
idFirebase = coleccionProductos.push().key;
}
data = {codigo:codigo, descripcion: descripcion, cantidad: cantidad};
actualizacionData = {};
actualizacionData[`/${idFirebase}`] = data;
coleccionProductos.update(actualizacionData);
id = '';
$('form').trigger('reset');
$('#modalAltaEdicion').modal('hide');
});
const iconoEditar = '';
const iconoBorrar = '';
function mostrarProductos({codigo, descripcion, cantidad}){
return `
<td>${codigo}</td>
<td>${descripcion}</td>
<td>${cantidad}</td>
<td><button class="btnEditar btn btn-secondary" data-toggle="tooltip" title="Editar">${iconoEditar}</button><button class="btnBorrar btn btn-danger" data-toggle="tooltip" title="Borrar">${iconoBorrar}</button></td>
`
}
//Buttons programming
$('#btnNuevo').click(function(){
$('#id').val('');
$('#codigo').val('');
$('#descripcion').val('');
$('#cantidad').val('');
$('form').trigger('reset');
$('#modalAltaEdicion').modal('show');
});
</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="es">
<head>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<title>Firebase CRUD</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<button id="btnNuevo" class="btn btn-primary" data-toggle="tooltip" title="Nuevo Producto"><svg class="bi bi-plus-circle-fill" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM8.5 4a.5.5 0 0 0-1 0v3.5H4a.5.5 0 0 0 0 1h3.5V12a.5.5 0 0 0 1 0V8.5H12a.5.5 0 0 0 0-1H8.5V4z"/></svg></button>
<!--Modal-->
<div id="modalAltaEdicion" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header bg-primary text-light">
<h5 class="modal-title" id="exampleModalLabel">High / edition</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
</button>
</div>
<form>
<div class="modal-body">
<input id="id" type="hidden"> <!-- ID we are going to receive from Firebase -->
<div class="form-group">
<label>Code</label>
<input id="codigo" type="text" class="form-control" required>
</div>
<div class="form-group">
<label>Description</label>
<input id="descripcion" type="text" class="form-control" required>
</div>
<div class="form-group">
<label>Quantity</label>
<input id="cantidad" type="number" class="form-control" required>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal" tabindex="2">Cancelar</button>
<button type="submit" id="btnGuardar" class="btn btn-primary" translate="1">Guardar</button>
</div>
</form>
</div>
</div>
</div>
<table id="tablaProductos" class="table table-bordered">
<thead>
<tr class="bg-dark text-light">
<th scope="col">CODE</th>
<th scope="col">DESCRIPTION</th>
<th scope="col">Quantity </th>
<th scope="col">ACTIONS</th>
</tr>
</thead>
<tbody id="bodyProductos">
</tbody>
</table>
</div>
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9.14.4/dist/sweetalert2.all.min.js"></script>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.15.0/firebase-app.js"></script>
<script type = "module" src = "firestore.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74617535,
"author": "Ethan Shannon",
"author_id": 18621413,
"author_profile": "https://Stackoverflow.com/users/18621413",
"pm_score": 2,
"selected": true,
"text": "using System.Xml.Linq;\n\nvar xmlStr = File.ReadAllText(\"Testfile.xml\");\nXElement root = XElement.Parse(xmlStr);\nvar data = root.Element(\"production\")\n .Elements().Where(x => x.Attribute(\"key\").Value == \"KEY1\")\n .Select(x=>x.Attribute(\"data\").Value)\n .First();\nConsole.WriteLine(data);\n"
},
{
"answer_id": 74617654,
"author": "st4ticv0id",
"author_id": 13028455,
"author_profile": "https://Stackoverflow.com/users/13028455",
"pm_score": 0,
"selected": false,
"text": "private void YOUR_METHOD_NAME()\n{\n // Call GetXml method which returns the result in the form of string\n string result = GetXml(\"xmlfile.xml\", \"KEY2\");\n Debug.WriteLine(result);\n}\n\nprivate string GetXml(string filePath, string searchKey)\n{\n XmlDocument doc = new XmlDocument();\n doc.Load(filePath);\n\n XmlNodeList nodes = doc.SelectSingleNode(\"//connections/production\").ChildNodes;\n\n string output = string.Empty;\n foreach (XmlNode node in nodes)\n {\n if (node.Attributes[\"key\"].Value == searchKey)\n {\n output = node.Attributes[\"data\"].Value;\n }\n else\n {\n continue;\n }\n }\n\n return output;\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13911746/"
] |
74,617,210
|
<p>Say I have multiple lists of lists. Something like this:</p>
<pre><code>list1 = [[1,2],[56,32],[34,244]]
list2 = [[43,21],[30,1],[19,3]]
list3 = [[1,3],[8,21],[9,57]]
</code></pre>
<p>I want to create two new lists:</p>
<pre><code>right_side = [2,32,244,21,1,3,3,21,57]
left_side = [1,56,34,43,30,19,1,8,9]
</code></pre>
<p>All sub-lists have only two values. And all big lists (list1,list2,list3) have the same number of values as well.</p>
<p>How do I do that?</p>
|
[
{
"answer_id": 74617308,
"author": "Jonathan Dauwe",
"author_id": 17229877,
"author_profile": "https://Stackoverflow.com/users/17229877",
"pm_score": 3,
"selected": true,
"text": "left_side, right_side = zip(*list1, *list2, *list3)\n left_side, right_side = map(list, zip(*list1, *list2, *list3))\n"
},
{
"answer_id": 74617316,
"author": "balderman",
"author_id": 415016,
"author_profile": "https://Stackoverflow.com/users/415016",
"pm_score": 2,
"selected": false,
"text": "list1 = [[1, 2], [56, 32], [34, 244]]\nlist2 = [[43, 21], [30, 1], [19, 3]]\nlist3 = [[1, 3], [8, 21], [9, 57]]\n\nleft = []\nright = []\nlst = [list1, list2, list3]\nfor l in lst:\n for ll in l:\n left.append(ll[0])\n right.append(ll[1])\nprint(f'Left: {left}')\nprint(f'Right: {right}')\n"
},
{
"answer_id": 74617322,
"author": "alphamu",
"author_id": 10215873,
"author_profile": "https://Stackoverflow.com/users/10215873",
"pm_score": 2,
"selected": false,
"text": "import itertools\nfrom operator import itemgetter\n\nright_side = list(map(itemgetter(1), itertools.chain(list1, list2, list3)))\nleft_side = list(map(itemgetter(0), itertools.chain(list1, list2, list3)))\n print [2, 32, 244, 21, 1, 3, 3, 21, 57]\n[1, 56, 34, 43, 30, 19, 1, 8, 9]\n"
},
{
"answer_id": 74617334,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\nAll = list1+list2+list3\nAll = np.array(All)\nprint(All[:,1].tolist())\n [2, 32, 244, 21, 1, 3, 3, 21, 57]\n print(All[:,0].tolist())\n [1, 56, 34, 43, 30, 19, 1, 8, 9]\n>>> \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17945841/"
] |
74,617,219
|
<p>I have this list in R:</p>
<pre><code>my_list = list("word",c("word", "word"), "word", c("word", "word","word"), "word")
[[1]]
[1] "word"
[[2]]
[1] "word" "word"
[[3]]
[1] "word"
[[4]]
[1] "word" "word" "word"
[[5]]
[1] "word"
</code></pre>
<p>I would like to convert this list into a data frame that looks something like this:</p>
<pre><code> col1 col2 col3
1 word
2 word word
3 word
4 word word word
5 word
# source code of the desired output
structure(list(col1 = c("word", "word", "word", "word", "word"
), col2 = c("", "word", "", "word", ""), col3 = c("", "", "",
"word", "")), class = "data.frame", row.names = c(NA, -5L))
</code></pre>
<p>I tried to use the answer provided here (<a href="https://stackoverflow.com/questions/25014886/how-to-split-a-column-of-list-into-several-columns-using-r">How to split a column of list into several columns using R</a>) for my question:</p>
<pre><code>z = my_list
x <- do.call(rbind, z)
colnames(x) <- LETTERS[1:ncol(x)]
h = data.frame(cbind(z[c("sg", "time")], x))
</code></pre>
<p>But this is not giving me the desired output.</p>
<p>Can someone please show me how to do this?</p>
<p>Thank you!</p>
|
[
{
"answer_id": 74617324,
"author": "jpsmith",
"author_id": 12109788,
"author_profile": "https://Stackoverflow.com/users/12109788",
"pm_score": 3,
"selected": true,
"text": "lapply do.call rbind do.call(rbind, lapply(my_list, `length<-`, max(lengths(my_list))))\n # [,1] [,2] [,3] \n# [1,] \"word\" NA NA \n# [2,] \"word\" \"word\" NA \n# [3,] \"word\" NA NA \n# [4,] \"word\" \"word\" \"word\"\n# [5,] \"word\" NA NA \n NA new_df <- do.call(rbind, lapply(my_list, `length<-`, max(lengths(my_list))))\nnew_df[is.na(new_df)] <- \"\"\n # [,1] [,2] [,3] \n# [1,] \"word\" \"\" \"\" \n# [2,] \"word\" \"word\" \"\" \n# [3,] \"word\" \"\" \"\" \n# [4,] \"word\" \"word\" \"word\"\n# [5,] \"word\" \"\" \"\" \n"
},
{
"answer_id": 74617396,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 2,
"selected": false,
"text": "stringi::stri_list2matrix library(stringi)\ndata.frame(stri_list2matrix(my_list, byrow = TRUE))\n# X1 X2 X3\n# 1 word <NA> <NA>\n# 2 word word <NA>\n# 3 word <NA> <NA>\n# 4 word word word\n# 5 word <NA> <NA>\n sapply t(sapply(my_list, \"length<-\", max(lengths(my_list))))\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13203841/"
] |
74,617,304
|
<p>Good afternoon Powershell wizards!</p>
<p>I am hoping someone can explain to me how I can fix this issue, and more importantly what the issue actually is!</p>
<p>I'm attempting to fix an old script I wrote years ago that searches for several dates on a files properties and picks one to use for renaming that file.</p>
<p>The issue I'm having is that when I use parseExact it fails for the date strings read from the files... but it works if I manually type the same string into powershell!</p>
<p>Please note that this script is only going to be ran on my PC and only needs to work with dates from my files formats so I'm not too worried about use of $null unless it's related.</p>
<p>See example below:</p>
<pre><code>Write-Host "TEST 1"
$DateTime = [DateTime]::ParseExact("240720211515","ddMMyyyyHHmm",$null)
Write-Host $DateTime # WORKS!
Write-Host "TEST 2"
$DateTime2 = [DateTime]::ParseExact("240720211515","ddMMyyyyHHmm",$null)
Write-Host $DateTime2 # FAILS!
</code></pre>
<p>Looks the same right?</p>
<p>Here is a more real world example of what I'm up to that fails</p>
<pre><code>$file = Get-Item "C:\SomeFolder\somefile.jpg"
$shellObject = New-Object -ComObject Shell.Application
$directoryObject = $shellObject.NameSpace( $file.Directory.FullName )
$fileObject = $directoryObject.ParseName( $file.Name )
$property = 'Date taken'
for(
$index = 5;
$directoryObject.GetDetailsOf( $directoryObject.Items, $index ) -ne $property;
++$index) { }
$photoDate = $directoryObject.GetDetailsOf($fileObject, $index)
Write-Host $photoDate # <-- This reads 03/08/2021 09:15
$output = [DateTime]::ParseExact($photoDate,"dd/MM/yyyy HH:mm",$null) # <-- This fails
Write-Host $output
# If i manually type in here it works.... If I copy and paste from the Write-Host it fails...
$someInput = "03/08/2021 09:15"
$workingOutput = [DateTime]::ParseExact($someInput,"dd/MM/yyyy HH:mm",$null)
Write-Host $workingOutput
</code></pre>
|
[
{
"answer_id": 74617791,
"author": "Ravendarksky",
"author_id": 1021864,
"author_profile": "https://Stackoverflow.com/users/1021864",
"pm_score": 1,
"selected": false,
"text": "$photoDate = $directoryObject.GetDetailsOf($fileObject, $index)\n$utfFree = $photoDate -replace \"\\u200e|\\u200f\", \"\"\n"
},
{
"answer_id": 74666535,
"author": "Keith Miller",
"author_id": 9406738,
"author_profile": "https://Stackoverflow.com/users/9406738",
"pm_score": 1,
"selected": false,
"text": "PS Pictures> $FileInfo = Get-Item \"C:\\Users\\keith\\Pictures\\Leland\\2009\\Leland 191.JPG\"\nPS Pictures> $Shell = New-Object -ComObject shell.application\nPS Pictures> $comFolder = $Shell.NameSpace($FileInfo.DirectoryName)\nPS Pictures> $comFile = $comFolder.ParseName($FileInfo.Name)\nPS Pictures>\nPS Pictures> $comFolder.GetDetailsOf($null,12)\nDate taken\nPS Pictures> $comFolder.GetDetailsOf($comFile,12)\n9/5/2009 2:06 PM\nPS Pictures> $comFolder.GetDetailsOf($comFile,12).GetType()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True String System.Object\n\n\nPS Pictures> $comFile.ExtendedProperty(\"DateTaken\")\nPS Pictures> $comFile.ExtendedProperty(\"System.Photo.DateTaken\")\n\nSaturday, September 5, 2009 07:06:41 PM\n\n\nPS Pictures> $comFile.ExtendedProperty(\"System.Photo.DateTaken\").GetType()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True DateTime System.ValueType\n PS Pictures> $comFolder.GetDetailsOf($null,18)\nTags\nPS Pictures> $comFolder.GetDetailsOf($comFile,18)\nLeland; Tim; Jorge\nPS Pictures> $comFolder.GetDetailsOf($comFile,18).GetTYpe()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True String System.Object\n\n\nPS Pictures> $comFile.ExtendedProperty(\"System.KeyWords\")\nPS Pictures> $comFile.ExtendedProperty(\"System.Keywords\")\nLeland\nTim\nJorge\nPS Pictures> $comFile.ExtendedProperty(\"System.Keywords\").GetType()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True String[] System.Array\n\n GetDetailsOf() PS Pictures> $comFolder.GetDetailsOf($null,261)\nFlash mode\nPS Pictures> $comFolder.GetDetailsOf($comFile,261)\nNo flash, auto\nPS Pictures> $comFile.ExtendedProperty(\"System.Photo.Flash\")\n24\n"
},
{
"answer_id": 74672353,
"author": "js2010",
"author_id": 6654942,
"author_profile": "https://Stackoverflow.com/users/6654942",
"pm_score": 0,
"selected": false,
"text": "$string = '# <-- This reads 03/08/2021 09:15' \nfunction chardump {\n param($string)\n [char[]]$string | \n % { [pscustomobject]@{Char = $_; Code = [int]$_ | % tostring x} }\n}\nchardump $string\n\n\nChar Code\n---- ----\n # 23\n 20\n < 3c\n - 2d\n - 2d\n 20\n T 54\n h 68\n i 69\n s 73\n 20\n r 72\n e 65\n a 61\n d 64\n s 73\n 20\n 200e\n 0 30\n 3 33\n / 2f\n 200e\n 0 30\n 8 38\n / 2f\n 200e\n 2 32\n 0 30\n 2 32\n 1 31\n 20\n 200f\n 200e\n 0 30\n 9 39\n : 3a\n 1 31\n 5 35\n\n\nchardump $string | ? {[int]('0x' + $_.code) -gt 0x7f}\n\nChar Code\n---- ----\n 200e\n 200e\n 200e\n 200f\n 200e\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1021864/"
] |
74,617,339
|
<p>I need help with creating a trial balance report for a specific tenure, from beginning of fiscal year to a selected period. I need this in Crystal Reports.</p>
<p>I am unable to formulate how can I get debit and credit amounts totalling from beginning of the fiscal year till the end of selected period (not YTD).</p>
<p>For example, I want to get a trial balance report till period 6 (June), I am able to get the balance at the end of period 6, but unable to formulate total credits and total debits for selected number of periods/months. Instead, it is either debit/credit amounts for June or it's for total debit/credits till date.</p>
<p>Can anyone help me please?</p>
|
[
{
"answer_id": 74617791,
"author": "Ravendarksky",
"author_id": 1021864,
"author_profile": "https://Stackoverflow.com/users/1021864",
"pm_score": 1,
"selected": false,
"text": "$photoDate = $directoryObject.GetDetailsOf($fileObject, $index)\n$utfFree = $photoDate -replace \"\\u200e|\\u200f\", \"\"\n"
},
{
"answer_id": 74666535,
"author": "Keith Miller",
"author_id": 9406738,
"author_profile": "https://Stackoverflow.com/users/9406738",
"pm_score": 1,
"selected": false,
"text": "PS Pictures> $FileInfo = Get-Item \"C:\\Users\\keith\\Pictures\\Leland\\2009\\Leland 191.JPG\"\nPS Pictures> $Shell = New-Object -ComObject shell.application\nPS Pictures> $comFolder = $Shell.NameSpace($FileInfo.DirectoryName)\nPS Pictures> $comFile = $comFolder.ParseName($FileInfo.Name)\nPS Pictures>\nPS Pictures> $comFolder.GetDetailsOf($null,12)\nDate taken\nPS Pictures> $comFolder.GetDetailsOf($comFile,12)\n9/5/2009 2:06 PM\nPS Pictures> $comFolder.GetDetailsOf($comFile,12).GetType()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True String System.Object\n\n\nPS Pictures> $comFile.ExtendedProperty(\"DateTaken\")\nPS Pictures> $comFile.ExtendedProperty(\"System.Photo.DateTaken\")\n\nSaturday, September 5, 2009 07:06:41 PM\n\n\nPS Pictures> $comFile.ExtendedProperty(\"System.Photo.DateTaken\").GetType()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True DateTime System.ValueType\n PS Pictures> $comFolder.GetDetailsOf($null,18)\nTags\nPS Pictures> $comFolder.GetDetailsOf($comFile,18)\nLeland; Tim; Jorge\nPS Pictures> $comFolder.GetDetailsOf($comFile,18).GetTYpe()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True String System.Object\n\n\nPS Pictures> $comFile.ExtendedProperty(\"System.KeyWords\")\nPS Pictures> $comFile.ExtendedProperty(\"System.Keywords\")\nLeland\nTim\nJorge\nPS Pictures> $comFile.ExtendedProperty(\"System.Keywords\").GetType()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True String[] System.Array\n\n GetDetailsOf() PS Pictures> $comFolder.GetDetailsOf($null,261)\nFlash mode\nPS Pictures> $comFolder.GetDetailsOf($comFile,261)\nNo flash, auto\nPS Pictures> $comFile.ExtendedProperty(\"System.Photo.Flash\")\n24\n"
},
{
"answer_id": 74672353,
"author": "js2010",
"author_id": 6654942,
"author_profile": "https://Stackoverflow.com/users/6654942",
"pm_score": 0,
"selected": false,
"text": "$string = '# <-- This reads 03/08/2021 09:15' \nfunction chardump {\n param($string)\n [char[]]$string | \n % { [pscustomobject]@{Char = $_; Code = [int]$_ | % tostring x} }\n}\nchardump $string\n\n\nChar Code\n---- ----\n # 23\n 20\n < 3c\n - 2d\n - 2d\n 20\n T 54\n h 68\n i 69\n s 73\n 20\n r 72\n e 65\n a 61\n d 64\n s 73\n 20\n 200e\n 0 30\n 3 33\n / 2f\n 200e\n 0 30\n 8 38\n / 2f\n 200e\n 2 32\n 0 30\n 2 32\n 1 31\n 20\n 200f\n 200e\n 0 30\n 9 39\n : 3a\n 1 31\n 5 35\n\n\nchardump $string | ? {[int]('0x' + $_.code) -gt 0x7f}\n\nChar Code\n---- ----\n 200e\n 200e\n 200e\n 200f\n 200e\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20635574/"
] |
74,617,343
|
<p>The out put of the script after initial parsing data is like this at this point</p>
<pre><code> - hostname: lfpm9001
- id: 700
addr: 100.241.50.118/28
- id: 800
addr: 10.241.50.161/28
- hostname: lfpm9002
- id: 355
addr: 100.243.52.129/25
- id: 228
addr: 100.241.51.161/25
- id: 190
addr: 100.245.25.1/24
- hostname: lfpm9003
- id: 400
addr: 100.250.55.121/24
- id: 600
addr: 100.242.56.168/28
- id: 185
addr: 100.240.26.10/24
</code></pre>
<p>trying to convert this file to have like this in output :</p>
<pre><code>
lfpm9001 700 100.241.50.118 28
lfpm9001 800 10.241.50.161 28
lfpm9002 355 100.243.52.129 25
lfpm9002 288 100.241.51.161 25
lfpm9002 190 100.245.25.1 24
lfpm9003 400 100.250.55.121 24
lfpm9003 600 100.242.56.168 28
lfpm9003 185 100.240.26.10 24
</code></pre>
<p>Tried this, and partially solved the issue but can't capture hostname as desired.</p>
<pre><code>sed -E '/-/{N;s~[^0-9]*([0-9]+)\n[^0-9]*([0-9.]+)/([0-9]+)~\1,\2,\3~}'
</code></pre>
|
[
{
"answer_id": 74617791,
"author": "Ravendarksky",
"author_id": 1021864,
"author_profile": "https://Stackoverflow.com/users/1021864",
"pm_score": 1,
"selected": false,
"text": "$photoDate = $directoryObject.GetDetailsOf($fileObject, $index)\n$utfFree = $photoDate -replace \"\\u200e|\\u200f\", \"\"\n"
},
{
"answer_id": 74666535,
"author": "Keith Miller",
"author_id": 9406738,
"author_profile": "https://Stackoverflow.com/users/9406738",
"pm_score": 1,
"selected": false,
"text": "PS Pictures> $FileInfo = Get-Item \"C:\\Users\\keith\\Pictures\\Leland\\2009\\Leland 191.JPG\"\nPS Pictures> $Shell = New-Object -ComObject shell.application\nPS Pictures> $comFolder = $Shell.NameSpace($FileInfo.DirectoryName)\nPS Pictures> $comFile = $comFolder.ParseName($FileInfo.Name)\nPS Pictures>\nPS Pictures> $comFolder.GetDetailsOf($null,12)\nDate taken\nPS Pictures> $comFolder.GetDetailsOf($comFile,12)\n9/5/2009 2:06 PM\nPS Pictures> $comFolder.GetDetailsOf($comFile,12).GetType()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True String System.Object\n\n\nPS Pictures> $comFile.ExtendedProperty(\"DateTaken\")\nPS Pictures> $comFile.ExtendedProperty(\"System.Photo.DateTaken\")\n\nSaturday, September 5, 2009 07:06:41 PM\n\n\nPS Pictures> $comFile.ExtendedProperty(\"System.Photo.DateTaken\").GetType()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True DateTime System.ValueType\n PS Pictures> $comFolder.GetDetailsOf($null,18)\nTags\nPS Pictures> $comFolder.GetDetailsOf($comFile,18)\nLeland; Tim; Jorge\nPS Pictures> $comFolder.GetDetailsOf($comFile,18).GetTYpe()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True String System.Object\n\n\nPS Pictures> $comFile.ExtendedProperty(\"System.KeyWords\")\nPS Pictures> $comFile.ExtendedProperty(\"System.Keywords\")\nLeland\nTim\nJorge\nPS Pictures> $comFile.ExtendedProperty(\"System.Keywords\").GetType()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True String[] System.Array\n\n GetDetailsOf() PS Pictures> $comFolder.GetDetailsOf($null,261)\nFlash mode\nPS Pictures> $comFolder.GetDetailsOf($comFile,261)\nNo flash, auto\nPS Pictures> $comFile.ExtendedProperty(\"System.Photo.Flash\")\n24\n"
},
{
"answer_id": 74672353,
"author": "js2010",
"author_id": 6654942,
"author_profile": "https://Stackoverflow.com/users/6654942",
"pm_score": 0,
"selected": false,
"text": "$string = '# <-- This reads 03/08/2021 09:15' \nfunction chardump {\n param($string)\n [char[]]$string | \n % { [pscustomobject]@{Char = $_; Code = [int]$_ | % tostring x} }\n}\nchardump $string\n\n\nChar Code\n---- ----\n # 23\n 20\n < 3c\n - 2d\n - 2d\n 20\n T 54\n h 68\n i 69\n s 73\n 20\n r 72\n e 65\n a 61\n d 64\n s 73\n 20\n 200e\n 0 30\n 3 33\n / 2f\n 200e\n 0 30\n 8 38\n / 2f\n 200e\n 2 32\n 0 30\n 2 32\n 1 31\n 20\n 200f\n 200e\n 0 30\n 9 39\n : 3a\n 1 31\n 5 35\n\n\nchardump $string | ? {[int]('0x' + $_.code) -gt 0x7f}\n\nChar Code\n---- ----\n 200e\n 200e\n 200e\n 200f\n 200e\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20626676/"
] |
74,617,358
|
<p>I'm trying to use an extension of UIImage to convert image download URLs to UIImage, but I'm getting this error: <code>'self.init' isn't called on all paths before returning from initializer</code></p>
<p>Here is my whole extension:</p>
<p>(<a href="https://i.stack.imgur.com/oZGJu.png" rel="nofollow noreferrer">https://i.stack.imgur.com/oZGJu.png</a>)</p>
<pre><code>extension UIImage {
convenience init?(url: URL?) {
let session = URLSession(configuration: .default)
let downloadPicTask = session.dataTask(with: url!) { (data, response, error) in
if let e = error {
print("Error downloading picture: \(e)")
} else {
if let res = response as? HTTPURLResponse {
print("Downloaded picture with response code \(res.statusCode)")
if let imageData = data {
let image = UIImage(data: imageData)
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
downloadPicTask.resume()
}
}
</code></pre>
<p>I don't know what I'm missing or if I should try a new way to convert URL to UIImage. I tried a different way, but it throws an error saying I need to do it asynchronously.</p>
|
[
{
"answer_id": 74618316,
"author": "Rob",
"author_id": 1271826,
"author_profile": "https://Stackoverflow.com/users/1271826",
"pm_score": 2,
"selected": false,
"text": "async await static extension UIImage {\n enum ImageError: Error {\n case notImage\n case unknownError\n }\n\n @discardableResult\n static func fetchImage(from url: URL, queue: DispatchQueue = .main, completion: @escaping (Result<UIImage, Error>) -> Void) -> URLSessionDataTask? {\n let session = URLSession.shared\n let task = session.dataTask(with: url) { data, response, error in\n guard\n let data = data,\n error == nil,\n let response = response as? HTTPURLResponse\n else {\n queue.async { completion(.failure(error ?? ImageError.unknownError)) }\n return\n }\n\n print(\"Downloaded picture with response code \\(response.statusCode)\")\n\n guard let image = UIImage(data: data) else {\n queue.async { completion(.failure(ImageError.notImage)) }\n return\n }\n\n queue.async { completion(.success(image)) }\n }\n task.resume()\n\n return task\n }\n}\n static func updateImageView() {\n let url = ...\n\n UIImage.fetchImage(from: url) { [weak self] result in\n switch result {\n case .failure(let error): print(error)\n case .success(let image): self?.imageView.image = image\n }\n }\n}\n async await async extension UIImage {\n convenience init?(from url: URL) async throws {\n let (data, _) = try await URLSession.shared.data(from: url)\n self.init(data: data)\n }\n}\n func updateImageView() async throws {\n let url = ...\n imageView.image = try await UIImage(from: url)\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20215370/"
] |
74,617,360
|
<p>i have python 3.11 downloaded, and i installed pip with it.
however, i can't install discord py with</p>
<pre><code>py -3 -m pip install -U discord.py
</code></pre>
<p>i've tried a few other ways, still didn't work.</p>
<p>in the end it says:</p>
<pre><code> note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for yarl
Failed to build multidict yarl
ERROR: Could not build wheels for multidict, yarl, which is required to install pyproject.toml-based projects
</code></pre>
<p>there are a few other errors throughout the process.</p>
|
[
{
"answer_id": 74617492,
"author": "M.K",
"author_id": 7396613,
"author_profile": "https://Stackoverflow.com/users/7396613",
"pm_score": 1,
"selected": false,
"text": "pip3 install --upgrade pip\n"
},
{
"answer_id": 74617527,
"author": "JesterIsHere",
"author_id": 18872613,
"author_profile": "https://Stackoverflow.com/users/18872613",
"pm_score": 0,
"selected": false,
"text": "pip install discord.py"
},
{
"answer_id": 74650715,
"author": "J Muzhen",
"author_id": 12341397,
"author_profile": "https://Stackoverflow.com/users/12341397",
"pm_score": 1,
"selected": false,
"text": "$ pip install git+https://github.com/Rapptz/discord.py\n"
},
{
"answer_id": 74678424,
"author": "Miro Pletscher",
"author_id": 19282100,
"author_profile": "https://Stackoverflow.com/users/19282100",
"pm_score": 0,
"selected": false,
"text": "pip install discord"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20635667/"
] |
74,617,416
|
<p>I use Google App Engine standard environemment with Flask Python3 for a current project.
This project use as cache the App Engine Memcache (google.appengine.api.memcache).</p>
<p>Currently the cache doesn't work and I think that it's probably because of the dependency on App Engine APIs that need to be enable because when I try to deploy my app (gcloud app deploy) I have this warning: <code>WARNING: There is a dependency on App Engine APIs, but they are not enabled in your app.yaml. Set the app_engine_apis property.</code></p>
<p>My issue is that when I try to set the dependancy in my app.yaml and deploy, I have then this error: <code>Unexpected attribute 'app_engine_apis' for object of type AppInfoExternal.</code></p>
<p>I also tried with the exact same yaml file than the Google example: <a href="https://github.com/googlecodelabs/migrate-python2-appengine/blob/master/mod12b-memcache/app.yaml" rel="nofollow noreferrer">https://github.com/googlecodelabs/migrate-python2-appengine/blob/master/mod12b-memcache/app.yaml</a>, it doesn't work.</p>
<p>Here the current app.yaml that I'm trying to use:</p>
<pre><code>runtime: python39
env: standard
app_engine_apis: true
resources:
cpu: 2
memory_gb: 4
disk_size_gb: 15
manual_scaling:
instances: 2
</code></pre>
<p>This issue is almost the same as this question but I couldn't use it to solve my problem: <a href="https://stackoverflow.com/questions/68893661/how-to-deal-with-app-engine-apis-warning-when-updating-app-yaml-from-go114-to">How to deal with `app_engine_apis` warning when updating app.yaml from go114 to go115</a></p>
<p>Thank you for your help.</p>
|
[
{
"answer_id": 74617492,
"author": "M.K",
"author_id": 7396613,
"author_profile": "https://Stackoverflow.com/users/7396613",
"pm_score": 1,
"selected": false,
"text": "pip3 install --upgrade pip\n"
},
{
"answer_id": 74617527,
"author": "JesterIsHere",
"author_id": 18872613,
"author_profile": "https://Stackoverflow.com/users/18872613",
"pm_score": 0,
"selected": false,
"text": "pip install discord.py"
},
{
"answer_id": 74650715,
"author": "J Muzhen",
"author_id": 12341397,
"author_profile": "https://Stackoverflow.com/users/12341397",
"pm_score": 1,
"selected": false,
"text": "$ pip install git+https://github.com/Rapptz/discord.py\n"
},
{
"answer_id": 74678424,
"author": "Miro Pletscher",
"author_id": 19282100,
"author_profile": "https://Stackoverflow.com/users/19282100",
"pm_score": 0,
"selected": false,
"text": "pip install discord"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20635585/"
] |
74,617,447
|
<p>Let's say I have MySQL database records with this structure</p>
<pre><code>{
"id": 44207,
"actors": [
{
"id": "9c88bd9c-f41b-59fa-bfb6-427b1755ea64",
"name": "APT41",
"scope": "confirmed"
},
{
"id": "6f82bd9c-f31b-59fa-bf26-427b1355ea64",
"name": "APT67",
"scope": "confirmed"
}
],
},
{
"id": 44208,
"actors": [
{
"id": "427b1355ea64-bfb6-59fa-bfb6-427b1755ea64",
"name": "APT21",
"scope": "confirmed"
},
{
"id": "9c88bd9c-f31b-59fa-bf26-427b1355ea64",
"name": "APT22",
"scope": "confirmed"
}
],
},
...
</code></pre>
<p>"actors" is a JSONField</p>
<p>Any way I can filter all of the objects whose actors name contains '67', for example?</p>
<p>Closest variant I have is that I got it working like that:</p>
<pre><code>queryset.filter(actors__contains=[{"name":"APT67"}])
</code></pre>
<p>But this query matches by exact actor.name value, while I want to to accept 'contains' operator.</p>
<p>I also have it working by quering with strict array index, like this:</p>
<pre><code>queryset.filter(actors__0__name__icontains='67')
</code></pre>
<p>But it only matches if first element in array matches my request. And I need that object shall be returned in any of his actors matches my query, so I was expecting something like <code>queryset.filter(actors__name__icontains='67')</code> to work, but it's not working :(</p>
<p>So far I have to use models.Q and multiple <code>OR</code>s to support my needs, like this -</p>
<pre><code>search_query = models.Q(actors__0__name__icontains='67') | models.Q(actors__1__name__icontains='67') | models.Q(actors__2__name__icontains='67') | models.Q(actors__3__name__icontains='67')
queryset.filter(search_query)
</code></pre>
<p>but this looks horrible and supports only 4 elements lookup(or I have to include more OR's)</p>
<p>Any clues if thats possible to be solved normal way overall?</p>
|
[
{
"answer_id": 74617492,
"author": "M.K",
"author_id": 7396613,
"author_profile": "https://Stackoverflow.com/users/7396613",
"pm_score": 1,
"selected": false,
"text": "pip3 install --upgrade pip\n"
},
{
"answer_id": 74617527,
"author": "JesterIsHere",
"author_id": 18872613,
"author_profile": "https://Stackoverflow.com/users/18872613",
"pm_score": 0,
"selected": false,
"text": "pip install discord.py"
},
{
"answer_id": 74650715,
"author": "J Muzhen",
"author_id": 12341397,
"author_profile": "https://Stackoverflow.com/users/12341397",
"pm_score": 1,
"selected": false,
"text": "$ pip install git+https://github.com/Rapptz/discord.py\n"
},
{
"answer_id": 74678424,
"author": "Miro Pletscher",
"author_id": 19282100,
"author_profile": "https://Stackoverflow.com/users/19282100",
"pm_score": 0,
"selected": false,
"text": "pip install discord"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4943446/"
] |
74,617,449
|
<p>I need to fill missing date values in orders table.
DDL:</p>
<pre><code>create table orders(order_date date, order_value int)
insert into orders values('2022-11-01',100),('2022-11-04 ',200),('2022-11-08',300)
</code></pre>
<p>Expected output is as:</p>
<pre><code>order_date | order_value
-----------------------
2022-11-01 | 100
2022-11-02 | 100
2022-11-03 | 100
2022-11-04 | 200
2022-11-05 | 200
2022-11-06 | 200
2022-11-07 | 200
2022-11-08 | 300
</code></pre>
<p>I have solved the problem in ms sql using recursive query listed below.</p>
<pre><code>with cte as (
select min(order_date) [min_date], MAX(order_date) [max_date]
FROM orders
), cte2 AS(
SELECT min_date [date]
FROM cte
UNION ALL
SELECT dateadd(day,1,date) [date]
FROM cte2
WHERE date < (SELECT max_date FROM cte)
), cte3 as(
select date [order_date], order_value
FROM cte2
LEFT JOIN orders on date = order_date
)
SELECT order_date,
FIRST_VALUE(order_value) IGNORE NULLS
OVER(ORDER BY order_date desc ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) [order_value]
FROM cte3
</code></pre>
<p>Is there any alternate approach to solve this problem or any way to optimize the recursive query?</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 74617492,
"author": "M.K",
"author_id": 7396613,
"author_profile": "https://Stackoverflow.com/users/7396613",
"pm_score": 1,
"selected": false,
"text": "pip3 install --upgrade pip\n"
},
{
"answer_id": 74617527,
"author": "JesterIsHere",
"author_id": 18872613,
"author_profile": "https://Stackoverflow.com/users/18872613",
"pm_score": 0,
"selected": false,
"text": "pip install discord.py"
},
{
"answer_id": 74650715,
"author": "J Muzhen",
"author_id": 12341397,
"author_profile": "https://Stackoverflow.com/users/12341397",
"pm_score": 1,
"selected": false,
"text": "$ pip install git+https://github.com/Rapptz/discord.py\n"
},
{
"answer_id": 74678424,
"author": "Miro Pletscher",
"author_id": 19282100,
"author_profile": "https://Stackoverflow.com/users/19282100",
"pm_score": 0,
"selected": false,
"text": "pip install discord"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16640543/"
] |
74,617,493
|
<p>I want to redirect to route with name doug-test, but I want to preserve the url parameter. I saw a webpage that says use $request->query('url') to get the url parameter, but that doesn't seem to work. I want to know the value of the <em>get</em> parameter "url".</p>
<p>For example, if someone goes /login?url=/xyz</p>
<p>I want them redirected to /dougs-page?url=/xyz where /dougs-page is a route named "doug-test"</p>
<p>Here's what I have so far:</p>
<pre><code>Route::get('/login', function (Request $request) {return redirect()->route('doug-test', ['url'=> $request->query('url')]);})->middleware('not-auth')->name('login');
</code></pre>
<p>The error I'm getting is "Call to undefined method Illuminate\Support\Facades\Request::query()"</p>
|
[
{
"answer_id": 74617591,
"author": "msmahon",
"author_id": 3704398,
"author_profile": "https://Stackoverflow.com/users/3704398",
"pm_score": -1,
"selected": false,
"text": "url()->previous();"
},
{
"answer_id": 74617694,
"author": "dougd_in_nc",
"author_id": 1228463,
"author_profile": "https://Stackoverflow.com/users/1228463",
"pm_score": 1,
"selected": true,
"text": "Route::get('/login', function (Request $request) {return redirect()->route('doug-test', ['url'=> $request::query('url')]);})->middleware('not-auth')->name('login');\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1228463/"
] |
74,617,510
|
<p>how can i change the button color(for highlight it) after i press my keyboard keys?
like the label said "Type some text using your keyboard.The keys you press will be <strong>highlighted</strong> and text will be displayed."</p>
<p>here is my code, what should i add in the code so when i press key on my keyboard, the button on the JFrame will change color? thanks
like example, on my keyboard i press A, and on the JFrame button A will change color from gray to red(example) after i release it, the color(red) changing back to default color(gray) i set</p>
<pre><code>import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
/**
*
* @author frint6
*/
public class GUITyping extends JFrame implements KeyListener {
private final JLabel lFp = new JLabel("Type some text using your keyboard. The keys you press will be highlighted and the text will be displayed.");
private final JLabel lSp = new JLabel("Note: Clicking the buttons with your mouse will not perform any action.");
private final JTextArea taL = new JTextArea();
private final String firstRow[] = {"~","1","2","3","4","5","6","7","8","9","0","-","+","Backspace"};
private final String secondRow[] = {"Tab","Q","W","E","R","T","Y","U","I","O","P","[","]","\\"};
private final String thirdRow[] = {"Caps","A","S","D","F","G","H","J","K","L",":","\"","Enter"};
private final String fourthRow[] = {"Shift","Z","X","C","V","B","N","M",",",".","?","^"};
private final String fifthRow[] = {" ","<","\\/",">"};
private JButton first[];
private JButton second[];
private JButton third[];
private JButton fourth[];
private JButton fifth[];
private final Container cont = getContentPane();
GUITyping(){
super("Typing Application");
initWidget();
}
private void initWidget(){
cont.setLayout(null);
lFp.setBounds(10, 0, 600, 30);
lSp.setBounds(10, 20, 400, 30);
taL.setBounds(10,50,765,230);
taL.setBorder(BorderFactory.createLoweredBevelBorder());
cont.add(lFp);
cont.add(lSp);
cont.add(taL);
first = new JButton[firstRow.length];
for(int i = 0; i < firstRow.length; ++i){
JButton a = new JButton(firstRow[i]);
first[i] = a;
first[i].addKeyListener(this);
first[i].setBorder(BorderFactory.createRaisedBevelBorder());
first[i].setBackground(Color.LIGHT_GRAY);
cont.add(first[i]);
}
second = new JButton[secondRow.length];
for(int i = 0; i < secondRow.length; ++i){
JButton b = new JButton(secondRow[i]);
second[i] = b;
second[i].addKeyListener(this);
second[i].setBorder(BorderFactory.createRaisedBevelBorder());
second[i].setBackground(Color.LIGHT_GRAY);
cont.add(second[i]);
}
third = new JButton[thirdRow.length];
for(int i = 0; i < thirdRow.length; ++i){
JButton c = new JButton(thirdRow[i]);
third[i] = c;
third[i].addKeyListener(this);
third[i].setBorder(BorderFactory.createRaisedBevelBorder());
third[i].setBackground(Color.LIGHT_GRAY);
cont.add(third[i]);
}
fourth = new JButton[fourthRow.length];
for(int i = 0; i < fourthRow.length; ++i){
JButton d = new JButton(fourthRow[i]);
fourth[i] = d;
fourth[i].addKeyListener(this);
fourth[i].setBorder(BorderFactory.createRaisedBevelBorder());
fourth[i].setBackground(Color.LIGHT_GRAY);
cont.add(fourth[i]);
}
fifth = new JButton[fifthRow.length];
for(int i = 0; i < fifthRow.length; ++i){
JButton e = new JButton(fifthRow[i]);
fifth[i] = e;
fifth[i].addKeyListener(this);
fifth[i].setBorder(BorderFactory.createRaisedBevelBorder());
fifth[i].setBackground(Color.LIGHT_GRAY);
cont.add(fifth[i]);
}
first[0].setBounds(10, 300, 45, 45);
first[1].setBounds(60, 300, 45, 45);
first[2].setBounds(110, 300, 45, 45);
first[3].setBounds(160, 300, 45, 45);
first[4].setBounds(210, 300, 45, 45);
first[5].setBounds(260, 300, 45, 45);
first[6].setBounds(310, 300, 45, 45);
first[7].setBounds(360, 300, 45, 45);
first[8].setBounds(410, 300, 45, 45);
first[9].setBounds(460, 300, 45, 45);
first[10].setBounds(510, 300, 45, 45);
first[11].setBounds(560, 300, 45, 45);
first[12].setBounds(610, 300, 45, 45);
first[13].setBounds(660, 300, 115, 45);
second[0].setBounds(10, 350, 75, 45);
second[1].setBounds(90, 350, 45, 45);
second[2].setBounds(140, 350, 46, 45);
second[3].setBounds(190, 350, 45, 45);
second[4].setBounds(240, 350, 45, 45);
second[5].setBounds(290, 350, 45, 45);
second[6].setBounds(340, 350, 45, 45);
second[7].setBounds(390, 350, 45, 45);
second[8].setBounds(440, 350, 45, 45);
second[9].setBounds(490, 350, 45, 45);
second[10].setBounds(540, 350, 45, 45);
second[11].setBounds(590, 350, 45, 45);
second[12].setBounds(640, 350, 45, 45);
second[13].setBounds(690, 350, 85, 45);
third[0].setBounds(10, 400, 75, 45);
third[1].setBounds(90, 400, 45, 45);
third[2].setBounds(140, 400, 46, 45);
third[3].setBounds(190, 400, 45, 45);
third[4].setBounds(240, 400, 45, 45);
third[5].setBounds(290, 400, 45, 45);
third[6].setBounds(340, 400, 45, 45);
third[7].setBounds(390, 400, 45, 45);
third[8].setBounds(440, 400, 45, 45);
third[9].setBounds(490, 400, 45, 45);
third[10].setBounds(540, 400, 45, 45);
third[11].setBounds(590, 400, 45, 45);
third[12].setBounds(640, 400, 135, 45);
fourth[0].setBounds(10, 450, 105, 45);
fourth[1].setBounds(120, 450, 45, 45);
fourth[2].setBounds(170, 450, 45, 45);
fourth[3].setBounds(220, 450, 45, 45);
fourth[4].setBounds(270, 450, 45, 45);
fourth[5].setBounds(320, 450, 45, 45);
fourth[6].setBounds(370, 450, 45, 45);
fourth[7].setBounds(420, 450, 45, 45);
fourth[8].setBounds(470, 450, 45, 45);
fourth[9].setBounds(520, 450, 45, 45);
fourth[10].setBounds(570, 450, 45, 45);
fourth[11].setBounds(680, 450, 45, 45);
fifth[0].setBounds(215, 500, 305, 45);
fifth[1].setBounds(630, 500, 45, 45);
fifth[2].setBounds(680, 500, 45, 45);
fifth[3].setBounds(730, 500, 45, 45);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
private class Actions implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
}
}
}
</code></pre>
|
[
{
"answer_id": 74617591,
"author": "msmahon",
"author_id": 3704398,
"author_profile": "https://Stackoverflow.com/users/3704398",
"pm_score": -1,
"selected": false,
"text": "url()->previous();"
},
{
"answer_id": 74617694,
"author": "dougd_in_nc",
"author_id": 1228463,
"author_profile": "https://Stackoverflow.com/users/1228463",
"pm_score": 1,
"selected": true,
"text": "Route::get('/login', function (Request $request) {return redirect()->route('doug-test', ['url'=> $request::query('url')]);})->middleware('not-auth')->name('login');\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20635511/"
] |
74,617,559
|
<p>This is the code where I'm trying to use the insert query:</p>
<pre><code>int insertItems(String name,double amt,String exp)throws Exception{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("insert into itemsList (null,name,amt,expire) values (?,?,?,?);");//when I use the 4?s it displays [Exception in thread "main" java.sql.SQLException: No value specified for parameter 1] and if I use 3?s it shows out of range.
//ps.setInt(1,id);//I declared the id as auto-Increment and primary key
ps.setString(2,name);
ps.setDouble(3,amt);
ps.setString(4,exp);
int n=ps.executeUpdate();
return n;
}
</code></pre>
<p>I don't understand that where I'm going wrong please help me to understand it.</p>
<p>getConnection() is where I created the JDBC driver, driver manager till connection and it is returning the connection object to other methods</p>
<p>I can read data easily but when it comes to exp line its shows exception</p>
<pre class="lang-none prettyprint-override"><code>Choose Option :
1.Add Item 2.View all Items
3.Place Order 4.NA
5.View Orders 6.Exit
-------------------------------------------------------------------------------------------
1
Choose type of Item :
1.Normal item 2.Food
2
Enter Item name :
dragon
Enter the Price :
70
Enter the Expire date :
12/11
Exception in thread "main" java.sql.SQLException: No value specified for parameter 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1084)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1009)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1320)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:994)
at com.fixitytech.isodb.ItemDAO.insertItems(ItemDAO.java:37)
at com.fixitytech.isodb.ShopdbUI.main(ShopdbUI.java:90)
</code></pre>
|
[
{
"answer_id": 74618246,
"author": "Ajay J",
"author_id": 14520572,
"author_profile": "https://Stackoverflow.com/users/14520572",
"pm_score": 0,
"selected": false,
"text": "PreparedStatement ps=con.prepareStatement(\"insert into itemsList (name,amt,expire) values (?,?,?);\")\n\nps.setString(1,name);\nps.setDouble(2,amt);\nps.setString(3,exp);\n"
},
{
"answer_id": 74618294,
"author": "Christoph Dahlen",
"author_id": 20370596,
"author_profile": "https://Stackoverflow.com/users/20370596",
"pm_score": 1,
"selected": false,
"text": "null PreparedStatement ps=con\n .prepareStatement(\"insert into itemsList (name,amt,expire) values (?,?,?)\");\n\nps.setString(1,name);\nps.setDouble(2,amt);\nps.setString(3,exp);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17282548/"
] |
74,617,563
|
<p>I am trying to get the last alphabet from an input and then gives a particular response from that.
like input "morning" have G at end and i want output as "G-Text".
so any input letter having last letter at end gives the output as "_ - TEXT". I tried with REGEX_LIKE but nothing.
Also in same function i need code for below examples-</p>
<p>I can check the function with this input data, for example, " fdsfdsfdd23" - > the result of the function will be "3 - ODD"
or jsdhfjsdhjfhdksf -> the result will be "f - TEXT"</p>
<p>please help.</p>
<p><a href="https://i.stack.imgur.com/uRHII.png" rel="nofollow noreferrer">code</a></p>
<p>error-
number or argument called for =</p>
<p>i tried everything. Syntax error maybe</p>
|
[
{
"answer_id": 74618295,
"author": "d r",
"author_id": 19023353,
"author_profile": "https://Stackoverflow.com/users/19023353",
"pm_score": 3,
"selected": true,
"text": "create or replace Function Last_Char(p_input_char VarChar2) RETURN VarChar2 Is\nBEGIN\n Declare\n mChar VarChar2(1) := '';\n mSfx VarChar2(20) := '';\n Begin\n If p_input_char Is Null Then \n RETURN 'NO_PARAM_ERR'; \n End If;\n --\n mChar := SubStr(p_input_char, Length(p_input_char), 1);\n If mChar = '0' Then \n mSfx := '-ZERO';\n ElsIf InStr('1,3,5,7,9', mChar) > 0 Then\n mSfx := '-ODD';\n ElsIf InStr('2,4,6,8', mChar) > 0 Then\n mSfx := '-EVEN';\n Else\n mSfx := '-TEXT';\n End If;\n RETURN Upper(mChar) || mSfx;\n End;\nEND Last_Char\n SET SERVEROUTPUT ON\nBegin\n DBMS_OUTPUT.PUT_LINE('jhkjd087');\n DBMS_OUTPUT.PUT_LINE('jhkjd08');\n DBMS_OUTPUT.PUT_LINE('jhkjd0');\n DBMS_OUTPUT.PUT_LINE('jhkjd');\nEnd;\n-- Results\n-- \n-- anonymous block completed\n-- 7-ODD\n-- 8-EVEN\n-- 0-ZERO\n-- D-TEXT\n"
},
{
"answer_id": 74620025,
"author": "Gary_W",
"author_id": 2543416,
"author_profile": "https://Stackoverflow.com/users/2543416",
"pm_score": 2,
"selected": false,
"text": "WITH tbl(ID, str) AS (\n SELECT 1, 'abcd' FROM dual UNION ALL\n SELECT 2, 'abc1' FROM dual UNION ALL\n SELECT 3, 'abc2' FROM dual UNION ALL\n SELECT 4, 'abc0' FROM dual UNION ALL\n SELECT 5, NULL FROM dual UNION ALL\n SELECT 6, 'abc'||CHR(09) FROM dual -- a tab\n)\nSELECT ID, str, \n CASE \n WHEN str IS NULL THEN\n 'NULL'\n -- If last character is a zero\n WHEN SUBSTR(str, '-1', '1') = '0' THEN \n '0 - Zero'\n -- If last character is an alpha character\n WHEN REGEXP_LIKE(str, '.*[[:alpha:]]$') THEN\n SUBSTR(str, '-1', '1') || ' - Text'\n -- If last character is a number, test for even/odd by seeing if it's\n -- evenly divisible by 2\n WHEN REGEXP_LIKE(str, '.*[[:digit:]]$') THEN\n CASE MOD(SUBSTR(str, '-1', '1'), 2) \n WHEN 0 THEN SUBSTR(str, '-1', '1') || ' - Even'\n WHEN 1 THEN SUBSTR(str, '-1', '1') || ' - Odd'\n ELSE 'Something went horribly wrong'\n END\n -- Something not already caught. Non-printable character, show yourself!\n ELSE 'Hex value - '|| RAWTOHEX(UTL_RAW.CAST_TO_RAW(SUBSTR(str, '-1', '1'))) \n END as last_char\nFROM tbl;\n\n ID STR LAST_CHAR \n---- ---- ---------------\n 1 abcd d - Text \n 2 abc1 1 - Odd \n 3 abc2 2 - Even \n 4 abc0 0 - Zero \n 5 NULL \n 6 abc Hex value - 09 \n\n6 rows selected.\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20633834/"
] |
74,617,610
|
<p>I have a dictionary dt which consists of cost price, selling price and the inventory. The purpose of the code is to calculate the Profit. Profit and can be calculated by
<strong>Profit = Total selling price - Total Cost price.</strong> For example following is the input
<strong>profit({
"cost_price": 32.67,
"sell_price": 45.00,
"inventory": 1200
})</strong>
And it's output is <strong>14796</strong>. To calculate individual Total cost the formula is <strong>Total cost price = inventory * cost_price</strong> and <strong>Total Selling Price = inventory * sell_price</strong>. Below is my code and the error.</p>
<pre><code> class Solution(object):
def total_profit(self, di):
global total_selling_price
global total_cost_price
for k, v in enumerate(di):
if k == 'cost_price':
cp = di[v]
elif k == 'inventory':
inventory = di[v]
total_cost_price = cp * inventory
else:
sp = di[v]
total_selling_price = sp * inventory
profit = total_selling_price - total_cost_price
return profit
if __name__ == '__main__':
p = Solution()
dt = {"cost_price": 2.77,
"sell_price": 7.95,
"inventory": 8500}
print(p.total_profit(dt))
</code></pre>
<p>Error shown is as follows</p>
<pre><code> Traceback (most recent call last):
File "/Users/tejas/PycharmProjects/LeetcodeinPython/EdbatsQuestions/Profit.py", line 27, in <module>
print(p.total_profit(dt))
File "/Users/tejas/PycharmProjects/LeetcodeinPython/EdbatsQuestions/Profit.py", line 15, in total_profit
total_selling_price = sp * inventory
UnboundLocalError: local variable 'inventory' referenced before assignment
</code></pre>
|
[
{
"answer_id": 74618295,
"author": "d r",
"author_id": 19023353,
"author_profile": "https://Stackoverflow.com/users/19023353",
"pm_score": 3,
"selected": true,
"text": "create or replace Function Last_Char(p_input_char VarChar2) RETURN VarChar2 Is\nBEGIN\n Declare\n mChar VarChar2(1) := '';\n mSfx VarChar2(20) := '';\n Begin\n If p_input_char Is Null Then \n RETURN 'NO_PARAM_ERR'; \n End If;\n --\n mChar := SubStr(p_input_char, Length(p_input_char), 1);\n If mChar = '0' Then \n mSfx := '-ZERO';\n ElsIf InStr('1,3,5,7,9', mChar) > 0 Then\n mSfx := '-ODD';\n ElsIf InStr('2,4,6,8', mChar) > 0 Then\n mSfx := '-EVEN';\n Else\n mSfx := '-TEXT';\n End If;\n RETURN Upper(mChar) || mSfx;\n End;\nEND Last_Char\n SET SERVEROUTPUT ON\nBegin\n DBMS_OUTPUT.PUT_LINE('jhkjd087');\n DBMS_OUTPUT.PUT_LINE('jhkjd08');\n DBMS_OUTPUT.PUT_LINE('jhkjd0');\n DBMS_OUTPUT.PUT_LINE('jhkjd');\nEnd;\n-- Results\n-- \n-- anonymous block completed\n-- 7-ODD\n-- 8-EVEN\n-- 0-ZERO\n-- D-TEXT\n"
},
{
"answer_id": 74620025,
"author": "Gary_W",
"author_id": 2543416,
"author_profile": "https://Stackoverflow.com/users/2543416",
"pm_score": 2,
"selected": false,
"text": "WITH tbl(ID, str) AS (\n SELECT 1, 'abcd' FROM dual UNION ALL\n SELECT 2, 'abc1' FROM dual UNION ALL\n SELECT 3, 'abc2' FROM dual UNION ALL\n SELECT 4, 'abc0' FROM dual UNION ALL\n SELECT 5, NULL FROM dual UNION ALL\n SELECT 6, 'abc'||CHR(09) FROM dual -- a tab\n)\nSELECT ID, str, \n CASE \n WHEN str IS NULL THEN\n 'NULL'\n -- If last character is a zero\n WHEN SUBSTR(str, '-1', '1') = '0' THEN \n '0 - Zero'\n -- If last character is an alpha character\n WHEN REGEXP_LIKE(str, '.*[[:alpha:]]$') THEN\n SUBSTR(str, '-1', '1') || ' - Text'\n -- If last character is a number, test for even/odd by seeing if it's\n -- evenly divisible by 2\n WHEN REGEXP_LIKE(str, '.*[[:digit:]]$') THEN\n CASE MOD(SUBSTR(str, '-1', '1'), 2) \n WHEN 0 THEN SUBSTR(str, '-1', '1') || ' - Even'\n WHEN 1 THEN SUBSTR(str, '-1', '1') || ' - Odd'\n ELSE 'Something went horribly wrong'\n END\n -- Something not already caught. Non-printable character, show yourself!\n ELSE 'Hex value - '|| RAWTOHEX(UTL_RAW.CAST_TO_RAW(SUBSTR(str, '-1', '1'))) \n END as last_char\nFROM tbl;\n\n ID STR LAST_CHAR \n---- ---- ---------------\n 1 abcd d - Text \n 2 abc1 1 - Odd \n 3 abc2 2 - Even \n 4 abc0 0 - Zero \n 5 NULL \n 6 abc Hex value - 09 \n\n6 rows selected.\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20502753/"
] |
74,617,627
|
<p><a href="https://i.stack.imgur.com/dNOYm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dNOYm.jpg" alt="anyone help me.how to design like below image. any sample. i am new for flutter developement" /></a></p>
<p><strong>how to create design look like below image. any sample please send</strong></p>
|
[
{
"answer_id": 74618295,
"author": "d r",
"author_id": 19023353,
"author_profile": "https://Stackoverflow.com/users/19023353",
"pm_score": 3,
"selected": true,
"text": "create or replace Function Last_Char(p_input_char VarChar2) RETURN VarChar2 Is\nBEGIN\n Declare\n mChar VarChar2(1) := '';\n mSfx VarChar2(20) := '';\n Begin\n If p_input_char Is Null Then \n RETURN 'NO_PARAM_ERR'; \n End If;\n --\n mChar := SubStr(p_input_char, Length(p_input_char), 1);\n If mChar = '0' Then \n mSfx := '-ZERO';\n ElsIf InStr('1,3,5,7,9', mChar) > 0 Then\n mSfx := '-ODD';\n ElsIf InStr('2,4,6,8', mChar) > 0 Then\n mSfx := '-EVEN';\n Else\n mSfx := '-TEXT';\n End If;\n RETURN Upper(mChar) || mSfx;\n End;\nEND Last_Char\n SET SERVEROUTPUT ON\nBegin\n DBMS_OUTPUT.PUT_LINE('jhkjd087');\n DBMS_OUTPUT.PUT_LINE('jhkjd08');\n DBMS_OUTPUT.PUT_LINE('jhkjd0');\n DBMS_OUTPUT.PUT_LINE('jhkjd');\nEnd;\n-- Results\n-- \n-- anonymous block completed\n-- 7-ODD\n-- 8-EVEN\n-- 0-ZERO\n-- D-TEXT\n"
},
{
"answer_id": 74620025,
"author": "Gary_W",
"author_id": 2543416,
"author_profile": "https://Stackoverflow.com/users/2543416",
"pm_score": 2,
"selected": false,
"text": "WITH tbl(ID, str) AS (\n SELECT 1, 'abcd' FROM dual UNION ALL\n SELECT 2, 'abc1' FROM dual UNION ALL\n SELECT 3, 'abc2' FROM dual UNION ALL\n SELECT 4, 'abc0' FROM dual UNION ALL\n SELECT 5, NULL FROM dual UNION ALL\n SELECT 6, 'abc'||CHR(09) FROM dual -- a tab\n)\nSELECT ID, str, \n CASE \n WHEN str IS NULL THEN\n 'NULL'\n -- If last character is a zero\n WHEN SUBSTR(str, '-1', '1') = '0' THEN \n '0 - Zero'\n -- If last character is an alpha character\n WHEN REGEXP_LIKE(str, '.*[[:alpha:]]$') THEN\n SUBSTR(str, '-1', '1') || ' - Text'\n -- If last character is a number, test for even/odd by seeing if it's\n -- evenly divisible by 2\n WHEN REGEXP_LIKE(str, '.*[[:digit:]]$') THEN\n CASE MOD(SUBSTR(str, '-1', '1'), 2) \n WHEN 0 THEN SUBSTR(str, '-1', '1') || ' - Even'\n WHEN 1 THEN SUBSTR(str, '-1', '1') || ' - Odd'\n ELSE 'Something went horribly wrong'\n END\n -- Something not already caught. Non-printable character, show yourself!\n ELSE 'Hex value - '|| RAWTOHEX(UTL_RAW.CAST_TO_RAW(SUBSTR(str, '-1', '1'))) \n END as last_char\nFROM tbl;\n\n ID STR LAST_CHAR \n---- ---- ---------------\n 1 abcd d - Text \n 2 abc1 1 - Odd \n 3 abc2 2 - Even \n 4 abc0 0 - Zero \n 5 NULL \n 6 abc Hex value - 09 \n\n6 rows selected.\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2270200/"
] |
74,617,632
|
<p>I have a class called person and a dictionary of people. I want to loop through each person in the People dictionary and check for errors. Is there a way of referencing the item in the library using similar to the below example. e.g. looping through the errors array and appending it to the item name instead of having to write a check for each individual error in the array?</p>
<p>Example code:</p>
<pre><code>errors = array("A", "B", "C")
for each theError in errors
for each person in people
if person.error & theError > 0 then
debug.print theError 'e.g. A, B or C
end if
next person
next theError
</code></pre>
|
[
{
"answer_id": 74618295,
"author": "d r",
"author_id": 19023353,
"author_profile": "https://Stackoverflow.com/users/19023353",
"pm_score": 3,
"selected": true,
"text": "create or replace Function Last_Char(p_input_char VarChar2) RETURN VarChar2 Is\nBEGIN\n Declare\n mChar VarChar2(1) := '';\n mSfx VarChar2(20) := '';\n Begin\n If p_input_char Is Null Then \n RETURN 'NO_PARAM_ERR'; \n End If;\n --\n mChar := SubStr(p_input_char, Length(p_input_char), 1);\n If mChar = '0' Then \n mSfx := '-ZERO';\n ElsIf InStr('1,3,5,7,9', mChar) > 0 Then\n mSfx := '-ODD';\n ElsIf InStr('2,4,6,8', mChar) > 0 Then\n mSfx := '-EVEN';\n Else\n mSfx := '-TEXT';\n End If;\n RETURN Upper(mChar) || mSfx;\n End;\nEND Last_Char\n SET SERVEROUTPUT ON\nBegin\n DBMS_OUTPUT.PUT_LINE('jhkjd087');\n DBMS_OUTPUT.PUT_LINE('jhkjd08');\n DBMS_OUTPUT.PUT_LINE('jhkjd0');\n DBMS_OUTPUT.PUT_LINE('jhkjd');\nEnd;\n-- Results\n-- \n-- anonymous block completed\n-- 7-ODD\n-- 8-EVEN\n-- 0-ZERO\n-- D-TEXT\n"
},
{
"answer_id": 74620025,
"author": "Gary_W",
"author_id": 2543416,
"author_profile": "https://Stackoverflow.com/users/2543416",
"pm_score": 2,
"selected": false,
"text": "WITH tbl(ID, str) AS (\n SELECT 1, 'abcd' FROM dual UNION ALL\n SELECT 2, 'abc1' FROM dual UNION ALL\n SELECT 3, 'abc2' FROM dual UNION ALL\n SELECT 4, 'abc0' FROM dual UNION ALL\n SELECT 5, NULL FROM dual UNION ALL\n SELECT 6, 'abc'||CHR(09) FROM dual -- a tab\n)\nSELECT ID, str, \n CASE \n WHEN str IS NULL THEN\n 'NULL'\n -- If last character is a zero\n WHEN SUBSTR(str, '-1', '1') = '0' THEN \n '0 - Zero'\n -- If last character is an alpha character\n WHEN REGEXP_LIKE(str, '.*[[:alpha:]]$') THEN\n SUBSTR(str, '-1', '1') || ' - Text'\n -- If last character is a number, test for even/odd by seeing if it's\n -- evenly divisible by 2\n WHEN REGEXP_LIKE(str, '.*[[:digit:]]$') THEN\n CASE MOD(SUBSTR(str, '-1', '1'), 2) \n WHEN 0 THEN SUBSTR(str, '-1', '1') || ' - Even'\n WHEN 1 THEN SUBSTR(str, '-1', '1') || ' - Odd'\n ELSE 'Something went horribly wrong'\n END\n -- Something not already caught. Non-printable character, show yourself!\n ELSE 'Hex value - '|| RAWTOHEX(UTL_RAW.CAST_TO_RAW(SUBSTR(str, '-1', '1'))) \n END as last_char\nFROM tbl;\n\n ID STR LAST_CHAR \n---- ---- ---------------\n 1 abcd d - Text \n 2 abc1 1 - Odd \n 3 abc2 2 - Even \n 4 abc0 0 - Zero \n 5 NULL \n 6 abc Hex value - 09 \n\n6 rows selected.\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10358185/"
] |
74,617,689
|
<p>I have 6 data in database record but I want to get last 3 data</p>
<p>this is my data :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>criteria_id</th>
<th>criteria_name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>A</td>
</tr>
<tr>
<td>2</td>
<td>B</td>
</tr>
<tr>
<td>3</td>
<td>C</td>
</tr>
<tr>
<td>4</td>
<td>D</td>
</tr>
<tr>
<td>5</td>
<td>E</td>
</tr>
<tr>
<td>6</td>
<td>F</td>
</tr>
</tbody>
</table>
</div>
<p>i have tried with this code :</p>
<pre><code> $criteria= criteria::latest()->take(3)->get();
</code></pre>
<p>but i got data like this :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>criteria_id</th>
<th>criteria_name</th>
</tr>
</thead>
<tbody>
<tr>
<td>6</td>
<td>F</td>
</tr>
<tr>
<td>1</td>
<td>A</td>
</tr>
<tr>
<td>2</td>
<td>B</td>
</tr>
</tbody>
</table>
</div>
<p>and I also tried with orderby the result is like this :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>criteria_id</th>
<th>criteria_name</th>
</tr>
</thead>
<tbody>
<tr>
<td>6</td>
<td>F</td>
</tr>
<tr>
<td>5</td>
<td>E</td>
</tr>
<tr>
<td>4</td>
<td>D</td>
</tr>
</tbody>
</table>
</div>
<p>the result should be like this, i want this result :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>criteria_id</th>
<th>criteria_name</th>
</tr>
</thead>
<tbody>
<tr>
<td>4</td>
<td>D</td>
</tr>
<tr>
<td>5</td>
<td>E</td>
</tr>
<tr>
<td>6</td>
<td>F</td>
</tr>
</tbody>
</table>
</div>
<p>how can i get data like last result ?</p>
|
[
{
"answer_id": 74617748,
"author": "msmahon",
"author_id": 3704398,
"author_profile": "https://Stackoverflow.com/users/3704398",
"pm_score": 3,
"selected": true,
"text": "created_at latest() criteria_id Criteria::orderBy('criteria_id', 'desc')->take(3)->get();\n Criteria::orderBy('criteria_id', 'desc')->take(3)->get()->sortBy('criteria_id');\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20365171/"
] |
74,617,711
|
<p>I am using Kibana to view an Opensearch index with objects like:</p>
<pre><code>timestamp:"November 3rd 2022, 23:50:51.253" client_id:"61c9aebdd01d" event:"login"
</code></pre>
<pre><code>timestamp:"November 3rd 2022, 23:51:11.553" client_id:"61c9aebdd01d" event:"error"
</code></pre>
<pre><code>timestamp:"November 3rd 2022, 23:52:19.982" client_id:"287a5ef458db" event:"login"
</code></pre>
<pre><code>timestamp:"November 3rd 2022, 23:59:35.840" client_id:"61c9aebdd01d" event:"login"
</code></pre>
<p>I'd like to count unique client_ids with event "login"; so, using the data above, the count would be 2.</p>
<p>I'm able to count events matching "login" using AWS's Kibana interface, with the query DSL:</p>
<pre><code>{
"query": {
"match": {
"event": "login"
}
}
}
</code></pre>
<p>...that works fine, and produces the count 3.</p>
<p>But when I try to construct an aggregation per various documentation, like:</p>
<pre><code>{
"size": 0,
"aggs": {
"client_count": {
"cardinality": {
"field": "client_id"
}
}
}
}
</code></pre>
<p>...I get a <code>SearchError: Internal Server Error</code>.</p>
<p>I've tried various variations on this. For instance, this works without an error:</p>
<pre><code>{
"size": 0,
"query": {
"match": {
"event": "login"
}
},
"aggs": {
"client_count": {
"cardinality": {
"field": "client_id",
"size": 0
}
}
}
}
</code></pre>
<p>...but, it doesn't seem to actually report the count of unique client_ids, it just produces the same exact results as the first query above (that matches all "login" events).</p>
<p>Aggregation types "cardinality", "terms" and "global" all seem to produce the same error.</p>
<p>Any ideas what syntax I should be using?</p>
<hr />
<p>P.S.: I looked at about 30 other Elasticsearch query questions, but none seemed to answer this question</p>
<p>P.P.S: I can't use syntax like</p>
<pre><code>GET /my_index_here/_search
{
...
</code></pre>
<p>because it's not allowed in the Kibana interface:
<a href="https://i.stack.imgur.com/SbIBM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SbIBM.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74617748,
"author": "msmahon",
"author_id": 3704398,
"author_profile": "https://Stackoverflow.com/users/3704398",
"pm_score": 3,
"selected": true,
"text": "created_at latest() criteria_id Criteria::orderBy('criteria_id', 'desc')->take(3)->get();\n Criteria::orderBy('criteria_id', 'desc')->take(3)->get()->sortBy('criteria_id');\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2308190/"
] |
74,617,717
|
<p>I have a list of dictionaries and a separate dictionary having the same keys and only the values are different. For example the list of dictionaries look like this:</p>
<pre><code>[{'A': 0.102, 'B': 0.568, 'C': 0.33}, {'A': 0.026, 'B': 0.590, 'C': 0.382}, {'A': 0.005, 'B': 0.857, 'C': 0.137}, {'A': 0.0, 'B': 0.962, 'C': 0.036}, {'A': 0.0, 'B': 0.991, 'C': 0.008}]
</code></pre>
<p>and the separate dictionary looks like this:</p>
<pre><code>{'A': 0.005, 'B': 0.956, 'C': 0.038}
</code></pre>
<p>I want to compare the separate dictionary with the list of dictionaries and return the index from the list which has higher value than the separate dictionary. In this example, the indices would be 3, 4 as the dictionary in indices 3 and 4 has a higher value for key <code>'B'</code> since <code>'B'</code> has the highest value in the separate dictionary.</p>
<p>Any ideas on how I should I proceed the problem?</p>
|
[
{
"answer_id": 74617748,
"author": "msmahon",
"author_id": 3704398,
"author_profile": "https://Stackoverflow.com/users/3704398",
"pm_score": 3,
"selected": true,
"text": "created_at latest() criteria_id Criteria::orderBy('criteria_id', 'desc')->take(3)->get();\n Criteria::orderBy('criteria_id', 'desc')->take(3)->get()->sortBy('criteria_id');\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13469713/"
] |
74,617,766
|
<p>Consider I have dataframe which the first column is the datetime, and the other columns are data in the specified datetime (Data is collected hourly, so first column of every row is one hour after the previous row). In this dateframe data for some datetimes are missed.
I want to make a new dataframe in which missing rows are replaced with the related datetime and NaNs for other columns.</p>
<p>I tried to read the dataframe from a csv as first DF, and created an empty DF in a loop to create datetime for every hour chronologically, then I take the data from first DF and put it in the second DF and if there is no data from first DF for the specified datetime I put NaN in the row.</p>
<p>This works for me, but it's very slow and takes 3 days to run for 70000 rows and I guess there is an efficient and pythonic way to do this.</p>
<p>I guess there is a better way like <a href="https://stackoverflow.com/questions/51437954/whats-the-best-way-to-find-missing-values-in-a-dataframe">this one</a> but I need it for datetime.</p>
<p>I'm looking for an answer like <a href="https://stackoverflow.com/questions/74525405/replacing-one-data-frame-value-from-another-based-on-timestamp-criterion">Replacing one data frame value from another based on timestamp Criterion</a> but just with datetime.</p>
|
[
{
"answer_id": 74618088,
"author": "Matt",
"author_id": 5125264,
"author_profile": "https://Stackoverflow.com/users/5125264",
"pm_score": 3,
"selected": true,
"text": "pd.date_range Index.difference NaN import pandas as pd\nimport numpy as np\n\n# name of your datetime column\ndatetime_col = 'datetime'\n \n# mock up some data\ndata = {\n datetime_col: [\n '2021-01-18 00:00:00', '2021-01-18 01:00:00',\n '2021-01-18 03:00:00', '2021-01-18 06:00:00'],\n 'extra_col1': ['b', 'c', 'd', 'e'],\n 'extra_col2': ['g', 'h', 'i', 'j'],\n}\n\ndf = pd.DataFrame(data)\n \n# Setting the Date values as index\ndf = df.set_index(datetime_col)\n \n# to_datetime() method converts string\n# format to a DateTime object\ndf.index = pd.to_datetime(df.index)\n \n# create df of missing dates from the sequence\n# starting from min dateitme, to max, with hourly intervals\nnew_df = pd.DataFrame(\n pd.date_range(\n start=df.index.min(), \n end=df.index.max(),\n freq='H'\n ).difference(df.index)\n)\n\n# you will need to add these columns to your df\nmissing_columns = [col for col in df.columns if col!=datetime_col]\n\n# add null data\nnew_df[missing_columns] = np.nan\n\n# fix column names\nnew_df.columns = [datetime_col] + missing_columns\n\nnew_df\n"
},
{
"answer_id": 74618106,
"author": "Adrien P.",
"author_id": 9806066,
"author_profile": "https://Stackoverflow.com/users/9806066",
"pm_score": 1,
"selected": false,
"text": "pd.date_range(start_date, end_date, freq='H') pd.merge(initial_df, complete_df, how='outer') import pandas as pd\nimport numpy as np\n \n# mock up some data\ndata = {\n 'date': [\n '2021-01-18 00:00:00', '2021-01-18 01:00:00',\n '2021-01-18 03:00:00', '2021-01-18 06:00:00'],\n 'extra_col1': ['b', 'c', 'd', 'e'],\n 'extra_col2': ['g', 'h', 'i', 'j'],\n}\n\ndf = pd.DataFrame(data)\n \n# Use to_datetime() method to convert string\n# format to a DateTime object\ndf['date'] = pd.to_datetime(df['date'])\n \n# Create df with missing dates from the sequence\n# starting from min dateitme, to max, with hourly intervals\nnew_df = pd.DataFrame(\n {'date': pd.date_range(\n start=df['date'].min(), \n end=df['date'].max(),\n freq='H'\n )}\n)\n\n# Use the merge function to perform an outer merge\n# and reorder the date column\nresult_df = pd.merge(df,new_df,how='outer')\nresult_df.sort_values(by='date',ascending=True, inplace=True)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13812421/"
] |
74,617,804
|
<p>I have followed a few different tutorials on how to get <code>Signup by invite</code> working and I am very close to getting it working in blazor server side but I am having issues with the final returned token.</p>
<p>I have 2 authentications setup, one which is the default Microsoft Identity and my custom one which is used for sign ups via an email link.</p>
<p>Everything seems to work until the final step.
When you click the link, it takes you to Azure signup pages asking for Name, email etc and then it returns back to my site with the returned "id_token".</p>
<p>When this happens I get the following error.</p>
<blockquote>
<p>InvalidOperationException: The authentication handler registered for scheme 'OpenIdConnect' is 'OpenIdConnectHandler' which cannot be used for SignInAsync. The registered sign-in schemes are: Cookies.</p>
</blockquote>
<p>I set breakpoints in the <code>OpenIdConnectEvents</code> on event <code>TicketReceived</code> and I can see that the <code>TicketReceivedContext</code> object has a valid <code>ClaimsPrinciple</code> with correct claims and <code>IsAuthenticated</code> is true.</p>
<p>My return page never gets hit because of the error.</p>
<p>Any ideas on how to fix this?</p>
<p>Edit
My startup registration for the 2 authentications.</p>
<pre><code>builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options =>{
builder.Configuration.Bind("AzureAd", options);
options.ResponseType = OpenIdConnectResponseType.IdToken;
options.Events = new CustomOpenIdConnectEvents();
options.DataProtectionProvider = protector;
}, subscribeToOpenIdConnectMiddlewareDiagnosticsEvents: true);
</code></pre>
<p>and</p>
<pre><code>string invite_policy = builder.Configuration.GetSection("AzureAdB2C")["SignUpSignInPolicyId"]; builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddOpenIdConnect(invite_policy, GetOpenIdSignUpOptions(invite_policy, builder.Configuration));
Action<OpenIdConnectOptions> GetOpenIdSignUpOptions(string policy, Microsoft.Extensions.Configuration.ConfigurationManager Configuration)
=> options =>
{
builder.Configuration.Bind("AzureAdB2C", options);
options.ResponseType = OpenIdConnectResponseType.IdToken;
string B2CDomain = Configuration.GetSection("AzureAdB2C")["B2CDomain"];
string Domain = Configuration.GetSection("AzureAdB2C")["Domain"];
options.MetadataAddress = $"https://{B2CDomain}/{Domain}/{policy}/v2.0/.well-known/openid-configuration";
options.ResponseMode = OpenIdConnectResponseMode.FormPost;
options.CallbackPath = "/LoginRedirect";
options.Events = new CustomOpenIdConnectEvents();
options.DataProtectionProvider = protector;
};
</code></pre>
<p>Update:<br />
So thanks to Wolfspirit's answer I am now closer to solving the issue.
My start up registration has now changed to this.</p>
<pre><code>string invite_policy = builder.Configuration.GetSection("AzureAdB2C")["SignUpSignInPolicyId"];
builder.Services.AddAuthentication(options => {
options.DefaultScheme =
CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddOpenIdConnect(invite_policy, GetOpenIdSignUpOptions(invite_policy, builder.Configuration))
.AddMicrosoftIdentityWebApp(options =>{
builder.Configuration.Bind("AzureAd", options);
options.ResponseType = OpenIdConnectResponseType.IdToken;
options.Events = new CustomOpenIdConnectEvents();
options.DataProtectionProvider = protector;
}, subscribeToOpenIdConnectMiddlewareDiagnosticsEvents: true);
</code></pre>
<p>My issue now is that <code>User.Identity.Name</code> is returning a null if you login through the signup method. If you login the normal default way then everything is fine. I checked the claims and they are correct so not sure why <code>Name</code> is no being populated.</p>
|
[
{
"answer_id": 74629506,
"author": "Gaz83",
"author_id": 1255136,
"author_profile": "https://Stackoverflow.com/users/1255136",
"pm_score": 0,
"selected": false,
"text": "string invite_policy = builder.Configuration.GetSection(\"AzureAdB2C\")[\"SignUpSignInPolicyId\"];\nbuilder.Services.AddAuthentication(options => {\n options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;\n options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;\n})\n.AddOpenIdConnect(invite_policy, GetOpenIdSignUpOptions(invite_policy, builder.Configuration))\n.AddMicrosoftIdentityWebApp(options =>{ \n\nbuilder.Configuration.Bind(\"AzureAd\", options);\n\noptions.ResponseType = OpenIdConnectResponseType.IdToken;\n\noptions.Events = new CustomOpenIdConnectEvents();\noptions.DataProtectionProvider = protector;\n\n// Thanks to Nan Yu for the folowing to fix the null name after login\n//https://stackoverflow.com/questions/54444747/user-identity-name-is-null-after-federated-azure-ad-login-with-aspnetcore-2-2\noptions.TokenValidationParameters = new TokenValidationParameters() { NameClaimType = \"name\" };\n\n}, subscribeToOpenIdConnectMiddlewareDiagnosticsEvents: true); // don't need this, for debugging.\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74617804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1255136/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.