qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,602,459
|
<p>I don't understand why programmers use %s, when they can simply just add the variable name to the print statement. I mean its less work to type in the variable name instead of " ...%s" % name) "</p>
<p>Example:</p>
<pre><code># declaring a string variable
name = "David"
# append a string within a string
print("Hey, %s!" % name)`
</code></pre>
<p>Why do Programmers not type in instead:</p>
<pre><code># declaring a string variable
name = "David"
# printing a salutation without having to append a string within a string:
print("Hey," + " " + name + "!")`
```
</code></pre>
|
[
{
"answer_id": 74602493,
"author": "Bas van der Linden",
"author_id": 11119684,
"author_profile": "https://Stackoverflow.com/users/11119684",
"pm_score": 1,
"selected": false,
"text": "# declaring a string variable\nname = \"David\"\n\n# format print using f-string\nprint(f\"Hey, {name}!\")\n"
},
{
"answer_id": 74602589,
"author": "Zameel Hassan",
"author_id": 18693614,
"author_profile": "https://Stackoverflow.com/users/18693614",
"pm_score": 0,
"selected": false,
"text": "// suppose x='John Doe'\n// to print my name along with another string\nprintf(\"My name is %s\", x); // Output: My name is John Doe\n name=\"John Doe\"\nprint(f\"My name is {name}\") # output: My name is John Doe\n name=\"John Doe\"\nprint(\"My name is {}\".format(name)) # output: My name is John Doe\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20622932/"
] |
74,602,502
|
<p>I was wondering if it is possible to include a configmap with its own values.yml file with a helm chart repository that I am not managing locally. This way, I can uninstall the resource with the name of the chart.</p>
<p>Example:</p>
<p>I am using New Relics Helm chart repository and installing the helm charts using their repo name. I want to include a configmap used for infrastructure settings with the same helm deployment without having to use a kubectl apply to add it independently.</p>
<p>I also want to avoid having to manage the repo locally as I am pinning the version and other values separately from the help upgrade install set triggers.</p>
|
[
{
"answer_id": 74602493,
"author": "Bas van der Linden",
"author_id": 11119684,
"author_profile": "https://Stackoverflow.com/users/11119684",
"pm_score": 1,
"selected": false,
"text": "# declaring a string variable\nname = \"David\"\n\n# format print using f-string\nprint(f\"Hey, {name}!\")\n"
},
{
"answer_id": 74602589,
"author": "Zameel Hassan",
"author_id": 18693614,
"author_profile": "https://Stackoverflow.com/users/18693614",
"pm_score": 0,
"selected": false,
"text": "// suppose x='John Doe'\n// to print my name along with another string\nprintf(\"My name is %s\", x); // Output: My name is John Doe\n name=\"John Doe\"\nprint(f\"My name is {name}\") # output: My name is John Doe\n name=\"John Doe\"\nprint(\"My name is {}\".format(name)) # output: My name is John Doe\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3489481/"
] |
74,602,506
|
<p>To pass a list/array of ids from C# into Oracle PL/SQL procedure, <a href="https://blogs.oracle.com/connect/post/using-plsql-associative-arrays" rel="nofollow noreferrer">you have to define an associative array type</a> e.g. a table with integer indexing:</p>
<pre><code>TYPE Ids_t_a is table of Number index by binary_integer;
</code></pre>
<p>I want to write a stored proc which wraps a query like the following:</p>
<pre><code>SELECT Id, Name from Person where Id in Ids;
</code></pre>
<p>I know basic SQL but am not a PL/SQL expert at all and table-valued types are beyond me. I tried:</p>
<pre><code>PROCEDURE GetData(Ids in Ids_t_a, results out sys_refcursor) IS
BEGIN
Open Results for
SELECT Id, Name from Person p where p.Id in Ids;
END;
</code></pre>
<p>But this gives an error "expression is of wrong type" and that seems to be because you cannot use an associative array this way.</p>
<p>What additional steps do I need to run my desired query against my input arguments?</p>
|
[
{
"answer_id": 74605952,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 0,
"selected": false,
"text": "sys.odcinumberlist emp SQL> create or replace procedure getdata\n 2 (ids in sys.odcinumberlist, results out sys_refcursor)\n 3 is\n 4 begin\n 5 open results for\n 6 select empno, ename from emp\n 7 where deptno in (select * from table(ids)); --> this is what you're looking for\n 8 end;\n 9 /\n\nProcedure created.\n SQL> set serveroutput on\nSQL> declare\n 2 l_ids sys.odcinumberlist; -- it'll contain list of departments\n 3 l_rc sys_refcursor; -- refcursor will be returned into this variable\n 4 l_empno number; -- employee number\n 5 l_ename varchar2(20); -- their name\n 6 begin\n 7 getdata(sys.odcinumberlist(10, 20), l_rc); -- this is how you call the procedure\n 8\n 9 loop -- you'll be using the result differently; I'm just\n 10 fetch l_rc into l_empno, l_ename; -- displaying contents\n 11 exit when l_rc%notfound;\n 12 dbms_output.put_line(l_empno ||' - '|| l_ename);\n 13 end loop;\n 14 end;\n 15 /\n7782 - CLARK\n7839 - KING\n7934 - MILLER\n7369 - SMITH\n7566 - JONES\n7788 - SCOTT\n7876 - ADAMS\n7902 - FORD\n\nPL/SQL procedure successfully completed.\n\nSQL>\n SQL> create or replace TYPE Ids_t_a is table of Number index by binary_integer;\n 2 /\n\nWarning: Type created with compilation errors.\n\nSQL> show err\nErrors for TYPE IDS_T_A:\n\nLINE/COL ERROR\n-------- -----------------------------------------------------------------\n0/0 PL/SQL: Compilation unit analysis terminated\n1/17 PLS-00355: use of pl/sql table not allowed in this context\nSQL>\n"
},
{
"answer_id": 74608092,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 2,
"selected": true,
"text": "SYS.ODCINUMBERTYPE CREATE TYPE number_list IS TABLE OF NUMBER;\n CREATE PACKAGE your_package IS\n TYPE Ids_t_a is table of Number index by binary_integer;\n\n FUNCTION map_ids(\n Ids in Ids_t_a\n ) RETURN number_list PIPELINED;\n\n PROCEDURE GetData(\n Ids in Ids_t_a,\n results out sys_refcursor\n );\nEND;\n/\n CREATE PACKAGE BODY your_package IS\n FUNCTION map_ids(\n Ids in Ids_t_a\n ) RETURN number_list PIPELINED\n IS\n v_idx BINARY_INTEGER;\n BEGIN\n IF ids IS NULL THEN\n RETURN;\n END IF;\n v_idx := ids.FIRST;\n WHILE v_idx IS NOT NULL LOOP\n PIPE ROW(ids(v_idx));\n v_idx := ids.NEXT(v_idx);\n END LOOP;\n END;\n\n PROCEDURE GetData(\n Ids in Ids_t_a,\n results out sys_refcursor\n )\n IS\n BEGIN\n Open Results for\n SELECT Id, Name\n FROM Person\n WHERE Id MEMBER OF map_ids(ids);\n END;\nEND;\n/\n VARRAY SYS.ODCINUMBERLIST MEMBER OF Open Results for SELECT p.Id, p.Name FROM Person p INNER JOIN TABLE(map_ids(ids)) i ON p.id = i.COLUMN_VALUE; CREATE TABLE person (id, name) AS\nSELECT 1, 'Alice' FROM DUAL UNION ALL\nSELECT 2, 'Beryl' FROM DUAL UNION ALL\nSELECT 3, 'Carol' FROM DUAL UNION ALL\nSELECT 4, 'Debra' FROM DUAL;\n DECLARE\n v_cur SYS_REFCURSOR;\n v_ids YOUR_PACKAGE.IDS_T_A;\n v_id PERSON.ID%TYPE;\n v_name PERSON.NAME%TYPE;\nBEGIN\n v_ids(1) := 3; -- Note: These are deliberately not sequential index values.\n v_ids(3) := 1; -- Indexes generated by C# probably would be, but it \n v_ids(42) := 7; -- is not guaranteed to always be true.\n YOUR_PACKAGE.GetData(v_ids, v_cur);\n LOOP\n FETCH v_cur INTO v_id, v_name;\n EXIT WHEN v_cur%NOTFOUND;\n DBMS_OUTPUT.PUT_LINE(v_id || ': ' || v_name);\n END LOOP;\nEND;\n/\n 1: Alice\n3: Carol\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197229/"
] |
74,602,571
|
<p>I am trying to change long names in rows starting with <code>></code>, so that I only keep the part till <code>Stage_V_sporulation_protein...</code>:</p>
<pre><code>>tr_A0A024P1W8_A0A024P1W8_9BACI_Stage_V_sporulation_protein_AE_OS=Halobacillus_karajensis_OX=195088_GN=BN983_00096_PE=4_SV=1
MTFLWAFLVGGGICVIGQILLDVFKLTPAHVMSSFVVAGAVLDAFDLYDNLIRFAGGGATVPITSFGHSLLHGAMEQADEHGVIGVAIGIFELTSAGIASAILFGFIVAVIFKPKG
>tr_A0A060LWV2_A0A060LWV2_9BACI_SpoIVAD_sporulation_protein_AEB_OS=Alkalihalobacillus_lehensis_G1_OX=1246626_GN=BleG1_2089_PE=4_SV=1
MIFLWAFLVGGVICVIGQLLMDVVKLTPAHTMSTLVVSGAVLAGFGLYEPLVDFAGAGATVPITSFGNSLVQGAMEEANQVGLIGIITGIFEITSAGISAAIIFGFIAALIFKPKG
</code></pre>
<p>I am doing a loop:</p>
<pre><code>cat file.txt | while read line; do
if [[ $line = \>* ]] ; then
cut -d_ -f1-4 $line;
fi;
done
</code></pre>
<p>but in addresses files but not rows in the file (I get <code>cut: >>tr_A0A024P1W8_A0A024P1W8_9BACI_Stage_V_sporulation_protein_AE_OS=Halobacillus_karajensis_OX=195088_GN=BN983_00096_PE=4_SV=1: No such file or directory</code>).</p>
<p>My desired output is:</p>
<pre><code>>tr_A0A024P1W8_A0A024P1W8_9BACI
MTFLWAFLVGGGICVIGQILLDVFKLTPAHVMSSFVVAGAVLDAFDLYDNLIRFAGGGATVPITSFGHSLLHGAMEQADEHGVIGVAIGIFELTSAGIASAILFGFIVAVIFKPKG
>tr_A0A060LWV2_A0A060LWV2_9BACI
MIFLWAFLVGGVICVIGQLLMDVVKLTPAHTMSTLVVSGAVLAGFGLYEPLVDFAGAGATVPITSFGNSLVQGAMEEANQVGLIGIITGIFEITSAGISAAIIFGFIAALIFKPKG
</code></pre>
<p>How do I change actual rows?</p>
|
[
{
"answer_id": 74605952,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 0,
"selected": false,
"text": "sys.odcinumberlist emp SQL> create or replace procedure getdata\n 2 (ids in sys.odcinumberlist, results out sys_refcursor)\n 3 is\n 4 begin\n 5 open results for\n 6 select empno, ename from emp\n 7 where deptno in (select * from table(ids)); --> this is what you're looking for\n 8 end;\n 9 /\n\nProcedure created.\n SQL> set serveroutput on\nSQL> declare\n 2 l_ids sys.odcinumberlist; -- it'll contain list of departments\n 3 l_rc sys_refcursor; -- refcursor will be returned into this variable\n 4 l_empno number; -- employee number\n 5 l_ename varchar2(20); -- their name\n 6 begin\n 7 getdata(sys.odcinumberlist(10, 20), l_rc); -- this is how you call the procedure\n 8\n 9 loop -- you'll be using the result differently; I'm just\n 10 fetch l_rc into l_empno, l_ename; -- displaying contents\n 11 exit when l_rc%notfound;\n 12 dbms_output.put_line(l_empno ||' - '|| l_ename);\n 13 end loop;\n 14 end;\n 15 /\n7782 - CLARK\n7839 - KING\n7934 - MILLER\n7369 - SMITH\n7566 - JONES\n7788 - SCOTT\n7876 - ADAMS\n7902 - FORD\n\nPL/SQL procedure successfully completed.\n\nSQL>\n SQL> create or replace TYPE Ids_t_a is table of Number index by binary_integer;\n 2 /\n\nWarning: Type created with compilation errors.\n\nSQL> show err\nErrors for TYPE IDS_T_A:\n\nLINE/COL ERROR\n-------- -----------------------------------------------------------------\n0/0 PL/SQL: Compilation unit analysis terminated\n1/17 PLS-00355: use of pl/sql table not allowed in this context\nSQL>\n"
},
{
"answer_id": 74608092,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 2,
"selected": true,
"text": "SYS.ODCINUMBERTYPE CREATE TYPE number_list IS TABLE OF NUMBER;\n CREATE PACKAGE your_package IS\n TYPE Ids_t_a is table of Number index by binary_integer;\n\n FUNCTION map_ids(\n Ids in Ids_t_a\n ) RETURN number_list PIPELINED;\n\n PROCEDURE GetData(\n Ids in Ids_t_a,\n results out sys_refcursor\n );\nEND;\n/\n CREATE PACKAGE BODY your_package IS\n FUNCTION map_ids(\n Ids in Ids_t_a\n ) RETURN number_list PIPELINED\n IS\n v_idx BINARY_INTEGER;\n BEGIN\n IF ids IS NULL THEN\n RETURN;\n END IF;\n v_idx := ids.FIRST;\n WHILE v_idx IS NOT NULL LOOP\n PIPE ROW(ids(v_idx));\n v_idx := ids.NEXT(v_idx);\n END LOOP;\n END;\n\n PROCEDURE GetData(\n Ids in Ids_t_a,\n results out sys_refcursor\n )\n IS\n BEGIN\n Open Results for\n SELECT Id, Name\n FROM Person\n WHERE Id MEMBER OF map_ids(ids);\n END;\nEND;\n/\n VARRAY SYS.ODCINUMBERLIST MEMBER OF Open Results for SELECT p.Id, p.Name FROM Person p INNER JOIN TABLE(map_ids(ids)) i ON p.id = i.COLUMN_VALUE; CREATE TABLE person (id, name) AS\nSELECT 1, 'Alice' FROM DUAL UNION ALL\nSELECT 2, 'Beryl' FROM DUAL UNION ALL\nSELECT 3, 'Carol' FROM DUAL UNION ALL\nSELECT 4, 'Debra' FROM DUAL;\n DECLARE\n v_cur SYS_REFCURSOR;\n v_ids YOUR_PACKAGE.IDS_T_A;\n v_id PERSON.ID%TYPE;\n v_name PERSON.NAME%TYPE;\nBEGIN\n v_ids(1) := 3; -- Note: These are deliberately not sequential index values.\n v_ids(3) := 1; -- Indexes generated by C# probably would be, but it \n v_ids(42) := 7; -- is not guaranteed to always be true.\n YOUR_PACKAGE.GetData(v_ids, v_cur);\n LOOP\n FETCH v_cur INTO v_id, v_name;\n EXIT WHEN v_cur%NOTFOUND;\n DBMS_OUTPUT.PUT_LINE(v_id || ': ' || v_name);\n END LOOP;\nEND;\n/\n 1: Alice\n3: Carol\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8655035/"
] |
74,602,579
|
<pre><code>temp = "75.1,77.7,83.2,82.5,81.0,79.5,85.7"
</code></pre>
<p>I am stuck in this assignment and unable to find a relevant answer to help.</p>
<p>I’ve used <code>.split(",")</code> and <code>float()</code>
and I am still stuck here.</p>
|
[
{
"answer_id": 74605952,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 0,
"selected": false,
"text": "sys.odcinumberlist emp SQL> create or replace procedure getdata\n 2 (ids in sys.odcinumberlist, results out sys_refcursor)\n 3 is\n 4 begin\n 5 open results for\n 6 select empno, ename from emp\n 7 where deptno in (select * from table(ids)); --> this is what you're looking for\n 8 end;\n 9 /\n\nProcedure created.\n SQL> set serveroutput on\nSQL> declare\n 2 l_ids sys.odcinumberlist; -- it'll contain list of departments\n 3 l_rc sys_refcursor; -- refcursor will be returned into this variable\n 4 l_empno number; -- employee number\n 5 l_ename varchar2(20); -- their name\n 6 begin\n 7 getdata(sys.odcinumberlist(10, 20), l_rc); -- this is how you call the procedure\n 8\n 9 loop -- you'll be using the result differently; I'm just\n 10 fetch l_rc into l_empno, l_ename; -- displaying contents\n 11 exit when l_rc%notfound;\n 12 dbms_output.put_line(l_empno ||' - '|| l_ename);\n 13 end loop;\n 14 end;\n 15 /\n7782 - CLARK\n7839 - KING\n7934 - MILLER\n7369 - SMITH\n7566 - JONES\n7788 - SCOTT\n7876 - ADAMS\n7902 - FORD\n\nPL/SQL procedure successfully completed.\n\nSQL>\n SQL> create or replace TYPE Ids_t_a is table of Number index by binary_integer;\n 2 /\n\nWarning: Type created with compilation errors.\n\nSQL> show err\nErrors for TYPE IDS_T_A:\n\nLINE/COL ERROR\n-------- -----------------------------------------------------------------\n0/0 PL/SQL: Compilation unit analysis terminated\n1/17 PLS-00355: use of pl/sql table not allowed in this context\nSQL>\n"
},
{
"answer_id": 74608092,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 2,
"selected": true,
"text": "SYS.ODCINUMBERTYPE CREATE TYPE number_list IS TABLE OF NUMBER;\n CREATE PACKAGE your_package IS\n TYPE Ids_t_a is table of Number index by binary_integer;\n\n FUNCTION map_ids(\n Ids in Ids_t_a\n ) RETURN number_list PIPELINED;\n\n PROCEDURE GetData(\n Ids in Ids_t_a,\n results out sys_refcursor\n );\nEND;\n/\n CREATE PACKAGE BODY your_package IS\n FUNCTION map_ids(\n Ids in Ids_t_a\n ) RETURN number_list PIPELINED\n IS\n v_idx BINARY_INTEGER;\n BEGIN\n IF ids IS NULL THEN\n RETURN;\n END IF;\n v_idx := ids.FIRST;\n WHILE v_idx IS NOT NULL LOOP\n PIPE ROW(ids(v_idx));\n v_idx := ids.NEXT(v_idx);\n END LOOP;\n END;\n\n PROCEDURE GetData(\n Ids in Ids_t_a,\n results out sys_refcursor\n )\n IS\n BEGIN\n Open Results for\n SELECT Id, Name\n FROM Person\n WHERE Id MEMBER OF map_ids(ids);\n END;\nEND;\n/\n VARRAY SYS.ODCINUMBERLIST MEMBER OF Open Results for SELECT p.Id, p.Name FROM Person p INNER JOIN TABLE(map_ids(ids)) i ON p.id = i.COLUMN_VALUE; CREATE TABLE person (id, name) AS\nSELECT 1, 'Alice' FROM DUAL UNION ALL\nSELECT 2, 'Beryl' FROM DUAL UNION ALL\nSELECT 3, 'Carol' FROM DUAL UNION ALL\nSELECT 4, 'Debra' FROM DUAL;\n DECLARE\n v_cur SYS_REFCURSOR;\n v_ids YOUR_PACKAGE.IDS_T_A;\n v_id PERSON.ID%TYPE;\n v_name PERSON.NAME%TYPE;\nBEGIN\n v_ids(1) := 3; -- Note: These are deliberately not sequential index values.\n v_ids(3) := 1; -- Indexes generated by C# probably would be, but it \n v_ids(42) := 7; -- is not guaranteed to always be true.\n YOUR_PACKAGE.GetData(v_ids, v_cur);\n LOOP\n FETCH v_cur INTO v_id, v_name;\n EXIT WHEN v_cur%NOTFOUND;\n DBMS_OUTPUT.PUT_LINE(v_id || ': ' || v_name);\n END LOOP;\nEND;\n/\n 1: Alice\n3: Carol\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20624813/"
] |
74,602,608
|
<p>I am using the Accordion from bootstrap to show and hide information. In here, information is stored. The information is different depending on each accordion but the setup is the same.</p>
<p>Because I have multiple accordions I have turned this in a reusable component using Razor (Blazor).</p>
<p>My issue right now is that I want to be able to have every accordion act independently, meaning when I open one accordion, the other ones stay closed and when I close one accordion, the other ones stay open etc.</p>
<p>The current situation is, because it is a reusable component, when I open/close one component, all the other ones do the same.</p>
<p>Here is my current code:</p>
<pre><code> <div class=@FormListClass>
@foreach (var trackingFormShareable in TrackingFormShareables)
{
<div class="accordion" id="accordion">
<div class="accordion-item">
<h2 class="accordion-header" id="panelsStayOpen-headingOne">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseOne" aria-expanded="true" aria-controls="panelsStayOpen-collapseOne">
@trackingFormShareable.TrackingFormName
</button>
</h2>
<div id="panelsStayOpen-collapseOne" class="accordion-collapse collapse show" aria-labelledby="panelsStayOpen-headingOne" data-bs-parent="#accordion">
<div class="accordion-body">
@foreach (var courseItem in trackingFormShareable.CourseItems)
{
<CourseItemTrackingDetails ClickedCourseItem='_clickedCourseItem' IsFolded='@(CurrentCourseItemId != null)' TrackingCourseItemShareable=courseItem></CourseItemTrackingDetails>
}
</div>
</div>
</div>
</div>
}
</div>
</code></pre>
<p>Does anyone know how to do this (better)?</p>
|
[
{
"answer_id": 74605952,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 0,
"selected": false,
"text": "sys.odcinumberlist emp SQL> create or replace procedure getdata\n 2 (ids in sys.odcinumberlist, results out sys_refcursor)\n 3 is\n 4 begin\n 5 open results for\n 6 select empno, ename from emp\n 7 where deptno in (select * from table(ids)); --> this is what you're looking for\n 8 end;\n 9 /\n\nProcedure created.\n SQL> set serveroutput on\nSQL> declare\n 2 l_ids sys.odcinumberlist; -- it'll contain list of departments\n 3 l_rc sys_refcursor; -- refcursor will be returned into this variable\n 4 l_empno number; -- employee number\n 5 l_ename varchar2(20); -- their name\n 6 begin\n 7 getdata(sys.odcinumberlist(10, 20), l_rc); -- this is how you call the procedure\n 8\n 9 loop -- you'll be using the result differently; I'm just\n 10 fetch l_rc into l_empno, l_ename; -- displaying contents\n 11 exit when l_rc%notfound;\n 12 dbms_output.put_line(l_empno ||' - '|| l_ename);\n 13 end loop;\n 14 end;\n 15 /\n7782 - CLARK\n7839 - KING\n7934 - MILLER\n7369 - SMITH\n7566 - JONES\n7788 - SCOTT\n7876 - ADAMS\n7902 - FORD\n\nPL/SQL procedure successfully completed.\n\nSQL>\n SQL> create or replace TYPE Ids_t_a is table of Number index by binary_integer;\n 2 /\n\nWarning: Type created with compilation errors.\n\nSQL> show err\nErrors for TYPE IDS_T_A:\n\nLINE/COL ERROR\n-------- -----------------------------------------------------------------\n0/0 PL/SQL: Compilation unit analysis terminated\n1/17 PLS-00355: use of pl/sql table not allowed in this context\nSQL>\n"
},
{
"answer_id": 74608092,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 2,
"selected": true,
"text": "SYS.ODCINUMBERTYPE CREATE TYPE number_list IS TABLE OF NUMBER;\n CREATE PACKAGE your_package IS\n TYPE Ids_t_a is table of Number index by binary_integer;\n\n FUNCTION map_ids(\n Ids in Ids_t_a\n ) RETURN number_list PIPELINED;\n\n PROCEDURE GetData(\n Ids in Ids_t_a,\n results out sys_refcursor\n );\nEND;\n/\n CREATE PACKAGE BODY your_package IS\n FUNCTION map_ids(\n Ids in Ids_t_a\n ) RETURN number_list PIPELINED\n IS\n v_idx BINARY_INTEGER;\n BEGIN\n IF ids IS NULL THEN\n RETURN;\n END IF;\n v_idx := ids.FIRST;\n WHILE v_idx IS NOT NULL LOOP\n PIPE ROW(ids(v_idx));\n v_idx := ids.NEXT(v_idx);\n END LOOP;\n END;\n\n PROCEDURE GetData(\n Ids in Ids_t_a,\n results out sys_refcursor\n )\n IS\n BEGIN\n Open Results for\n SELECT Id, Name\n FROM Person\n WHERE Id MEMBER OF map_ids(ids);\n END;\nEND;\n/\n VARRAY SYS.ODCINUMBERLIST MEMBER OF Open Results for SELECT p.Id, p.Name FROM Person p INNER JOIN TABLE(map_ids(ids)) i ON p.id = i.COLUMN_VALUE; CREATE TABLE person (id, name) AS\nSELECT 1, 'Alice' FROM DUAL UNION ALL\nSELECT 2, 'Beryl' FROM DUAL UNION ALL\nSELECT 3, 'Carol' FROM DUAL UNION ALL\nSELECT 4, 'Debra' FROM DUAL;\n DECLARE\n v_cur SYS_REFCURSOR;\n v_ids YOUR_PACKAGE.IDS_T_A;\n v_id PERSON.ID%TYPE;\n v_name PERSON.NAME%TYPE;\nBEGIN\n v_ids(1) := 3; -- Note: These are deliberately not sequential index values.\n v_ids(3) := 1; -- Indexes generated by C# probably would be, but it \n v_ids(42) := 7; -- is not guaranteed to always be true.\n YOUR_PACKAGE.GetData(v_ids, v_cur);\n LOOP\n FETCH v_cur INTO v_id, v_name;\n EXIT WHEN v_cur%NOTFOUND;\n DBMS_OUTPUT.PUT_LINE(v_id || ': ' || v_name);\n END LOOP;\nEND;\n/\n 1: Alice\n3: Carol\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12707644/"
] |
74,602,611
|
<p>I would like a program that does something like this: <a href="https://www.colortools.net/color_matcher.html" rel="nofollow noreferrer">https://www.colortools.net/color_matcher.html</a></p>
<p>Anyone know how to do in flutter?</p>
<p>I expect a function that compares two colors.</p>
|
[
{
"answer_id": 74605952,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 0,
"selected": false,
"text": "sys.odcinumberlist emp SQL> create or replace procedure getdata\n 2 (ids in sys.odcinumberlist, results out sys_refcursor)\n 3 is\n 4 begin\n 5 open results for\n 6 select empno, ename from emp\n 7 where deptno in (select * from table(ids)); --> this is what you're looking for\n 8 end;\n 9 /\n\nProcedure created.\n SQL> set serveroutput on\nSQL> declare\n 2 l_ids sys.odcinumberlist; -- it'll contain list of departments\n 3 l_rc sys_refcursor; -- refcursor will be returned into this variable\n 4 l_empno number; -- employee number\n 5 l_ename varchar2(20); -- their name\n 6 begin\n 7 getdata(sys.odcinumberlist(10, 20), l_rc); -- this is how you call the procedure\n 8\n 9 loop -- you'll be using the result differently; I'm just\n 10 fetch l_rc into l_empno, l_ename; -- displaying contents\n 11 exit when l_rc%notfound;\n 12 dbms_output.put_line(l_empno ||' - '|| l_ename);\n 13 end loop;\n 14 end;\n 15 /\n7782 - CLARK\n7839 - KING\n7934 - MILLER\n7369 - SMITH\n7566 - JONES\n7788 - SCOTT\n7876 - ADAMS\n7902 - FORD\n\nPL/SQL procedure successfully completed.\n\nSQL>\n SQL> create or replace TYPE Ids_t_a is table of Number index by binary_integer;\n 2 /\n\nWarning: Type created with compilation errors.\n\nSQL> show err\nErrors for TYPE IDS_T_A:\n\nLINE/COL ERROR\n-------- -----------------------------------------------------------------\n0/0 PL/SQL: Compilation unit analysis terminated\n1/17 PLS-00355: use of pl/sql table not allowed in this context\nSQL>\n"
},
{
"answer_id": 74608092,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 2,
"selected": true,
"text": "SYS.ODCINUMBERTYPE CREATE TYPE number_list IS TABLE OF NUMBER;\n CREATE PACKAGE your_package IS\n TYPE Ids_t_a is table of Number index by binary_integer;\n\n FUNCTION map_ids(\n Ids in Ids_t_a\n ) RETURN number_list PIPELINED;\n\n PROCEDURE GetData(\n Ids in Ids_t_a,\n results out sys_refcursor\n );\nEND;\n/\n CREATE PACKAGE BODY your_package IS\n FUNCTION map_ids(\n Ids in Ids_t_a\n ) RETURN number_list PIPELINED\n IS\n v_idx BINARY_INTEGER;\n BEGIN\n IF ids IS NULL THEN\n RETURN;\n END IF;\n v_idx := ids.FIRST;\n WHILE v_idx IS NOT NULL LOOP\n PIPE ROW(ids(v_idx));\n v_idx := ids.NEXT(v_idx);\n END LOOP;\n END;\n\n PROCEDURE GetData(\n Ids in Ids_t_a,\n results out sys_refcursor\n )\n IS\n BEGIN\n Open Results for\n SELECT Id, Name\n FROM Person\n WHERE Id MEMBER OF map_ids(ids);\n END;\nEND;\n/\n VARRAY SYS.ODCINUMBERLIST MEMBER OF Open Results for SELECT p.Id, p.Name FROM Person p INNER JOIN TABLE(map_ids(ids)) i ON p.id = i.COLUMN_VALUE; CREATE TABLE person (id, name) AS\nSELECT 1, 'Alice' FROM DUAL UNION ALL\nSELECT 2, 'Beryl' FROM DUAL UNION ALL\nSELECT 3, 'Carol' FROM DUAL UNION ALL\nSELECT 4, 'Debra' FROM DUAL;\n DECLARE\n v_cur SYS_REFCURSOR;\n v_ids YOUR_PACKAGE.IDS_T_A;\n v_id PERSON.ID%TYPE;\n v_name PERSON.NAME%TYPE;\nBEGIN\n v_ids(1) := 3; -- Note: These are deliberately not sequential index values.\n v_ids(3) := 1; -- Indexes generated by C# probably would be, but it \n v_ids(42) := 7; -- is not guaranteed to always be true.\n YOUR_PACKAGE.GetData(v_ids, v_cur);\n LOOP\n FETCH v_cur INTO v_id, v_name;\n EXIT WHEN v_cur%NOTFOUND;\n DBMS_OUTPUT.PUT_LINE(v_id || ': ' || v_name);\n END LOOP;\nEND;\n/\n 1: Alice\n3: Carol\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20175621/"
] |
74,602,618
|
<p>so I want to create a filter that returns data based upon the link, if the link contains /rome/ it will list all the pages that contains /rome/ which I've managed to do. But I'm also trying to create a filter based on the market within the cities, for example if the link contains /rome/supermarket/ I want to filter out the pages to return only the pages that contain the city and the market meaning id 1 and 2 in my last link example.</p>
<p>First I'm thinking that I need to loop all over the pages, which are 3 in my example and then loop over again for each city to check if it contains that city and the supermarket and based upon that return the filtered data. I've tried a couple of things but I'm scratching my head here.</p>
<pre><code> pages: [
{
id: 1,
name: 'Meals',
startDate: '2022-11-09 10:32:00',
endDate: '2022-11-16 10:32:00',
cities: {
rome: ['supermarket'],
},
},
{
id: 2,
name: 'Deals',
startDate: '2022-11-24 11:01:00',
endDate: '2022-12-01 11:01:00',
cities: {
napoli: ['supermarket', 'minimarket'],
rome: ['supermarket'],
},
},
{
id: 3,
name: 'Toys',
startDate: '2022-11-24 11:01:00',
endDate: '2022-12-01 11:01:00',
cities: {
rome: ['minimarket'],
venice: ['supermarket', 'minimarket'],
},
}
]
</code></pre>
<p>The filter for the city -></p>
<pre><code> const pagesFilterCity = pages.filter((item) => {
return item.cities.hasOwnProperty(city); // where city is 'rome'
});
</code></pre>
<p>What I've tried -></p>
<pre><code> const pagesFilterMarket = pages.filter((item) => {
return Object.values(item.cities)
.flat()
.some((item) => item === market); // where market is 'supermarket'
});
</code></pre>
<p>But this will only loop through the first instance from each cities, meaning 3 times</p>
<p>Wanted result: after having /rome/supermarket in the link I want to create a filter that should return the following data from the pages example from above ->
<strong>Note that extracting the data from the link I've already done and that's not my question</strong></p>
<pre><code> pages: [
{
id: 1,
name: 'Meals',
startDate: '2022-11-09 10:32:00',
endDate: '2022-11-16 10:32:00',
cities: {
rome: ['supermarket'],
},
},
{
id: 2,
name: 'Deals',
startDate: '2022-11-24 11:01:00',
endDate: '2022-12-01 11:01:00',
cities: {
napoli: ['supermarket', 'minimarket'],
rome: ['supermarket'],
},
}
] // wanted result
</code></pre>
|
[
{
"answer_id": 74602724,
"author": "Salketer",
"author_id": 1620194,
"author_profile": "https://Stackoverflow.com/users/1620194",
"pm_score": 0,
"selected": false,
"text": "const pages = [{\n id: 1,\n name: 'Meals',\n startDate: '2022-11-09 10:32:00',\n endDate: '2022-11-16 10:32:00',\n cities: {\n rome: ['supermarket'],\n },\n },\n {\n id: 2,\n name: 'Deals',\n startDate: '2022-11-24 11:01:00',\n endDate: '2022-12-01 11:01:00',\n cities: {\n napoli: ['supermarket', 'minimarket'],\n rome: ['supermarket'],\n },\n },\n {\n id: 3,\n name: 'Toys',\n startDate: '2022-11-24 11:01:00',\n endDate: '2022-12-01 11:01:00',\n cities: {\n rome: ['minimarket'],\n venice: ['supermarket', 'minimarket'],\n },\n }\n]\n\nfunction filter(search) {\n const [city, service] = search.split('/');\n return pagesFilterCity = pages.filter((item) => {\n return item.cities.hasOwnProperty(city) && (service === '' || item.cities[city].includes(service)); // where city is rome for example\n });\n}\nconsole.log(filter('rome/supermarket'))"
},
{
"answer_id": 74603471,
"author": "Svetoslav Petrov",
"author_id": 4370164,
"author_profile": "https://Stackoverflow.com/users/4370164",
"pm_score": 2,
"selected": true,
"text": "const pages = [{\n id: 1,\n name: 'Meals',\n startDate: '2022-11-09 10:32:00',\n endDate: '2022-11-16 10:32:00',\n cities: {\n rome: ['supermarket'],\n },\n},\n{\n id: 2,\n name: 'Deals',\n startDate: '2022-11-24 11:01:00',\n endDate: '2022-12-01 11:01:00',\n cities: {\n napoli: ['supermarket', 'minimarket'],\n rome: ['supermarket'],\n },\n},\n{\n id: 3,\n name: 'Toys',\n startDate: '2022-11-24 11:01:00',\n endDate: '2022-12-01 11:01:00',\n cities: {\n rome: ['minimarket'],\n venice: ['supermarket', 'minimarket'],\n },\n},\n];\n\nconst search = (location, market) => {\n return pages.filter((record) => \n // Check if the cities property has a value\n record.cities[location] && \n // Check if the specific city has the given market\n record.cities[location].some((type) => type === market)\n );\n};\n\nconsole.log(search('rome', 'supermarket')); return pages.filter((record) => \n record.cities[location] && \n record.cities[location].length &&\n record.cities[location].some((type) => type === market)\n);\n"
},
{
"answer_id": 74603968,
"author": "Yosvel Quintero",
"author_id": 1932552,
"author_profile": "https://Stackoverflow.com/users/1932552",
"pm_score": 0,
"selected": false,
"text": "const pages = [{id: 1,name: 'Meals',startDate: '2022-11-09 10:32:00',endDate: '2022-11-16 10:32:00',cities: {rome: ['supermarket'],},},{id: 2,name: 'Deals',startDate: '2022-11-24 11:01:00',endDate: '2022-12-01 11:01:00',cities: {napoli: ['supermarket', 'minimarket'],rome: ['supermarket'],},},{id: 3,name: 'Toys',startDate: '2022-11-24 11:01:00',endDate: '2022-12-01 11:01:00',cities: {rome: ['minimarket'],venice: ['supermarket', 'minimarket']}}]\n\nconst result = pages.filter(o => o.cities['rome']?.includes('supermarket'))\n\nconsole.log(result)"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10423361/"
] |
74,602,649
|
<p>If I want to have two tables with many-to-many relationship, how do I create models and seed the database?</p>
<p>For example classic tables Actors and Movies. I tried it like this</p>
<pre><code>public class Actor
{
public Actor()
{
this.Movies = new HashSet<Movies>;
}
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set;}
public virtual ICollection<Movie> Movies { get; set; }
}
</code></pre>
<pre><code>public class Movie
{
public Movie()
{
this.Actors = new HashSet<Actors>;
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Actor> Actors { get; set; }
}
</code></pre>
<p>As I understood Entity Framework creates automatically new table ActorMovies with two columns with IDs of Actor and Movie.</p>
<p>How I seed it:</p>
<pre><code>Actor actor = new Actor { Name="John", Surname="Doe" };
Movie movie = new Movie { Name="John Doe and his garden hoe" };
actor.Movies.Add(movie);
dbContext.Add(movie); ( call from separate repository )
</code></pre>
<p>This automatically seeds Actor table as well and pretty much duplicates all data in both tables. Every time I add new Actor with same Movie, it creates new row in Movie table with same Name but just different ID, which is completely wrong.</p>
<p>My ApplicationDbContext is standard :</p>
<pre><code>public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
public DbSet<Actor> Actors { get; set; }
public DbSet<Movie> Movies { get; set; }
}
</code></pre>
<p>So what is the proper way of creating, initializing and seeding many-to-many relationship?</p>
<pre><code></code></pre>
|
[
{
"answer_id": 74602724,
"author": "Salketer",
"author_id": 1620194,
"author_profile": "https://Stackoverflow.com/users/1620194",
"pm_score": 0,
"selected": false,
"text": "const pages = [{\n id: 1,\n name: 'Meals',\n startDate: '2022-11-09 10:32:00',\n endDate: '2022-11-16 10:32:00',\n cities: {\n rome: ['supermarket'],\n },\n },\n {\n id: 2,\n name: 'Deals',\n startDate: '2022-11-24 11:01:00',\n endDate: '2022-12-01 11:01:00',\n cities: {\n napoli: ['supermarket', 'minimarket'],\n rome: ['supermarket'],\n },\n },\n {\n id: 3,\n name: 'Toys',\n startDate: '2022-11-24 11:01:00',\n endDate: '2022-12-01 11:01:00',\n cities: {\n rome: ['minimarket'],\n venice: ['supermarket', 'minimarket'],\n },\n }\n]\n\nfunction filter(search) {\n const [city, service] = search.split('/');\n return pagesFilterCity = pages.filter((item) => {\n return item.cities.hasOwnProperty(city) && (service === '' || item.cities[city].includes(service)); // where city is rome for example\n });\n}\nconsole.log(filter('rome/supermarket'))"
},
{
"answer_id": 74603471,
"author": "Svetoslav Petrov",
"author_id": 4370164,
"author_profile": "https://Stackoverflow.com/users/4370164",
"pm_score": 2,
"selected": true,
"text": "const pages = [{\n id: 1,\n name: 'Meals',\n startDate: '2022-11-09 10:32:00',\n endDate: '2022-11-16 10:32:00',\n cities: {\n rome: ['supermarket'],\n },\n},\n{\n id: 2,\n name: 'Deals',\n startDate: '2022-11-24 11:01:00',\n endDate: '2022-12-01 11:01:00',\n cities: {\n napoli: ['supermarket', 'minimarket'],\n rome: ['supermarket'],\n },\n},\n{\n id: 3,\n name: 'Toys',\n startDate: '2022-11-24 11:01:00',\n endDate: '2022-12-01 11:01:00',\n cities: {\n rome: ['minimarket'],\n venice: ['supermarket', 'minimarket'],\n },\n},\n];\n\nconst search = (location, market) => {\n return pages.filter((record) => \n // Check if the cities property has a value\n record.cities[location] && \n // Check if the specific city has the given market\n record.cities[location].some((type) => type === market)\n );\n};\n\nconsole.log(search('rome', 'supermarket')); return pages.filter((record) => \n record.cities[location] && \n record.cities[location].length &&\n record.cities[location].some((type) => type === market)\n);\n"
},
{
"answer_id": 74603968,
"author": "Yosvel Quintero",
"author_id": 1932552,
"author_profile": "https://Stackoverflow.com/users/1932552",
"pm_score": 0,
"selected": false,
"text": "const pages = [{id: 1,name: 'Meals',startDate: '2022-11-09 10:32:00',endDate: '2022-11-16 10:32:00',cities: {rome: ['supermarket'],},},{id: 2,name: 'Deals',startDate: '2022-11-24 11:01:00',endDate: '2022-12-01 11:01:00',cities: {napoli: ['supermarket', 'minimarket'],rome: ['supermarket'],},},{id: 3,name: 'Toys',startDate: '2022-11-24 11:01:00',endDate: '2022-12-01 11:01:00',cities: {rome: ['minimarket'],venice: ['supermarket', 'minimarket']}}]\n\nconst result = pages.filter(o => o.cities['rome']?.includes('supermarket'))\n\nconsole.log(result)"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14928702/"
] |
74,602,685
|
<p>I receive a axios api response in following manner,</p>
<pre><code> res.data = {
material:['plate','bag','bottle'],
customer:['cust1','cust2','cust3'],
prod_id: [1122,3344,4445]
}
</code></pre>
<p>now I want to rearrange this object to the display data in the table in below manner,</p>
<pre><code> rowdata = [
{
materail:'plate',
customer:'cust1',
prod_id:'1122',
},
{
materail:'bag',
customer:'cust2',
prod_id:'3344',
},
{
materail:'bottle',
customer:'cust3',
prod_id:'4445',
},
]
</code></pre>
<p>I am noob at javascript, many things still new to me, your opinions and help will be useful.</p>
<p>I tried object.entries(), foreach() and map() but I cannot achieve the rowdata format.</p>
|
[
{
"answer_id": 74602746,
"author": "Axnyff",
"author_id": 4949918,
"author_profile": "https://Stackoverflow.com/users/4949918",
"pm_score": 2,
"selected": false,
"text": "const rowdata = res_data.material.map((material, index) => ({\n material,\n customer: res_data.customer[index],\n prod_id: res_data.prod_id[index],\n});\n"
},
{
"answer_id": 74602748,
"author": "Jared Smith",
"author_id": 3757232,
"author_profile": "https://Stackoverflow.com/users/3757232",
"pm_score": 0,
"selected": false,
"text": "const rowData = res.data.prod_id.map((prod_id, i) => {\n const material = res.data.material[i];\n const customer = res.data.customer[i];\n return {\n prod_id,\n material,\n customer,\n };\n});\n"
},
{
"answer_id": 74602755,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 0,
"selected": false,
"text": "const\n data = { material: ['plate', 'bag', 'bottle'], customer: ['cust1', 'cust2', 'cust3'], prod_id: [1122, 3344, 4445] },\n result = Object\n .entries(data)\n .reduce(\n (r, [k, values]) => values.map((v, i) => ({ ...r[i], [k]: v })),\n []\n );\n\nconsole.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 74603098,
"author": "Ha Tai",
"author_id": 14036048,
"author_profile": "https://Stackoverflow.com/users/14036048",
"pm_score": 0,
"selected": false,
"text": "const raw = Object.keys(data).reduce((pre, current) => {\n return data[current].map((value, index) => ({\n [current]: value,\n ...pre[index],\n }));\n}, []);\n"
},
{
"answer_id": 74603177,
"author": "Hedi Zitouni",
"author_id": 12285347,
"author_profile": "https://Stackoverflow.com/users/12285347",
"pm_score": 0,
"selected": false,
"text": " const properties=Object.keys(data)\n const result = data[properties[0]].map((elem, i) => {\n return properties.reduce((acc, curr) => {\n acc[curr] = data[curr][i]\n return acc\n }, {})\n })\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20624706/"
] |
74,602,699
|
<p>Suppose I have items in a table that resemble the following:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Item</th>
<th>FamilyCode</th>
</tr>
</thead>
<tbody>
<tr>
<td>ABR123</td>
<td>ABR</td>
</tr>
<tr>
<td>ABR456</td>
<td>ABR</td>
</tr>
<tr>
<td>BCL369</td>
<td>BCL</td>
</tr>
<tr>
<td>BCL987</td>
<td>BCL</td>
</tr>
<tr>
<td>AEL877</td>
<td>AEL</td>
</tr>
</tbody>
</table>
</div>
<p>I would like to notate whether an item is part of a family based on the whether there are other items that exist with this same family code. I would like to add an output column such as "Is Part of a Family", Yes/No.</p>
<p>The output would be as follows:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Item</th>
<th>FamilyCode</th>
<th>Is Part of a Family?</th>
</tr>
</thead>
<tbody>
<tr>
<td>ABR123</td>
<td>ABR</td>
<td>Yes</td>
</tr>
<tr>
<td>ABR456</td>
<td>ABR</td>
<td>Yes</td>
</tr>
<tr>
<td>BCL369</td>
<td>BCL</td>
<td>Yes</td>
</tr>
<tr>
<td>BCL987</td>
<td>BCL</td>
<td>Yes</td>
</tr>
<tr>
<td>AEL877</td>
<td>AEL</td>
<td>No</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74602746,
"author": "Axnyff",
"author_id": 4949918,
"author_profile": "https://Stackoverflow.com/users/4949918",
"pm_score": 2,
"selected": false,
"text": "const rowdata = res_data.material.map((material, index) => ({\n material,\n customer: res_data.customer[index],\n prod_id: res_data.prod_id[index],\n});\n"
},
{
"answer_id": 74602748,
"author": "Jared Smith",
"author_id": 3757232,
"author_profile": "https://Stackoverflow.com/users/3757232",
"pm_score": 0,
"selected": false,
"text": "const rowData = res.data.prod_id.map((prod_id, i) => {\n const material = res.data.material[i];\n const customer = res.data.customer[i];\n return {\n prod_id,\n material,\n customer,\n };\n});\n"
},
{
"answer_id": 74602755,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 0,
"selected": false,
"text": "const\n data = { material: ['plate', 'bag', 'bottle'], customer: ['cust1', 'cust2', 'cust3'], prod_id: [1122, 3344, 4445] },\n result = Object\n .entries(data)\n .reduce(\n (r, [k, values]) => values.map((v, i) => ({ ...r[i], [k]: v })),\n []\n );\n\nconsole.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 74603098,
"author": "Ha Tai",
"author_id": 14036048,
"author_profile": "https://Stackoverflow.com/users/14036048",
"pm_score": 0,
"selected": false,
"text": "const raw = Object.keys(data).reduce((pre, current) => {\n return data[current].map((value, index) => ({\n [current]: value,\n ...pre[index],\n }));\n}, []);\n"
},
{
"answer_id": 74603177,
"author": "Hedi Zitouni",
"author_id": 12285347,
"author_profile": "https://Stackoverflow.com/users/12285347",
"pm_score": 0,
"selected": false,
"text": " const properties=Object.keys(data)\n const result = data[properties[0]].map((elem, i) => {\n return properties.reduce((acc, curr) => {\n acc[curr] = data[curr][i]\n return acc\n }, {})\n })\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11208669/"
] |
74,602,700
|
<p>I should somehow convert data type to easily insert into table with datetime format.
From</p>
<pre><code>2022-11-28T12:18:46.534919023Z
</code></pre>
<p>To
2022-11-28 12:18:46</p>
<p>BTW using PostgreSQL.
Any ideas how to do it?</p>
|
[
{
"answer_id": 74602746,
"author": "Axnyff",
"author_id": 4949918,
"author_profile": "https://Stackoverflow.com/users/4949918",
"pm_score": 2,
"selected": false,
"text": "const rowdata = res_data.material.map((material, index) => ({\n material,\n customer: res_data.customer[index],\n prod_id: res_data.prod_id[index],\n});\n"
},
{
"answer_id": 74602748,
"author": "Jared Smith",
"author_id": 3757232,
"author_profile": "https://Stackoverflow.com/users/3757232",
"pm_score": 0,
"selected": false,
"text": "const rowData = res.data.prod_id.map((prod_id, i) => {\n const material = res.data.material[i];\n const customer = res.data.customer[i];\n return {\n prod_id,\n material,\n customer,\n };\n});\n"
},
{
"answer_id": 74602755,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 0,
"selected": false,
"text": "const\n data = { material: ['plate', 'bag', 'bottle'], customer: ['cust1', 'cust2', 'cust3'], prod_id: [1122, 3344, 4445] },\n result = Object\n .entries(data)\n .reduce(\n (r, [k, values]) => values.map((v, i) => ({ ...r[i], [k]: v })),\n []\n );\n\nconsole.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 74603098,
"author": "Ha Tai",
"author_id": 14036048,
"author_profile": "https://Stackoverflow.com/users/14036048",
"pm_score": 0,
"selected": false,
"text": "const raw = Object.keys(data).reduce((pre, current) => {\n return data[current].map((value, index) => ({\n [current]: value,\n ...pre[index],\n }));\n}, []);\n"
},
{
"answer_id": 74603177,
"author": "Hedi Zitouni",
"author_id": 12285347,
"author_profile": "https://Stackoverflow.com/users/12285347",
"pm_score": 0,
"selected": false,
"text": " const properties=Object.keys(data)\n const result = data[properties[0]].map((elem, i) => {\n return properties.reduce((acc, curr) => {\n acc[curr] = data[curr][i]\n return acc\n }, {})\n })\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20624851/"
] |
74,602,709
|
<p>Im trying to scrape the information of all the player names and player rating from this website:
<a href="https://www.fifaindex.com/players/?gender=0&league=1&order=desc" rel="nofollow noreferrer">https://www.fifaindex.com/players/?gender=0&league=1&order=desc</a></p>
<p>But i only get the information from the first player on the page.</p>
<p>The code im using:</p>
<pre><code>
from bs4 import BeautifulSoup
import requests
url = "https://www.fifaindex.com/players/?gender=0&league=1&order=desc"
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
results = soup.find_all('div', class_="responsive-table table-rounded")
for result in results:
rating = result.find("span", class_="badge badge-dark rating r3").text
name = result.find("a", class_="link-player")
info = [rating, name]
print(info)
</code></pre>
<p>The HTML parsed is attached in the <a href="https://i.stack.imgur.com/51hBQ.png" rel="nofollow noreferrer">picture</a></p>
|
[
{
"answer_id": 74602746,
"author": "Axnyff",
"author_id": 4949918,
"author_profile": "https://Stackoverflow.com/users/4949918",
"pm_score": 2,
"selected": false,
"text": "const rowdata = res_data.material.map((material, index) => ({\n material,\n customer: res_data.customer[index],\n prod_id: res_data.prod_id[index],\n});\n"
},
{
"answer_id": 74602748,
"author": "Jared Smith",
"author_id": 3757232,
"author_profile": "https://Stackoverflow.com/users/3757232",
"pm_score": 0,
"selected": false,
"text": "const rowData = res.data.prod_id.map((prod_id, i) => {\n const material = res.data.material[i];\n const customer = res.data.customer[i];\n return {\n prod_id,\n material,\n customer,\n };\n});\n"
},
{
"answer_id": 74602755,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 0,
"selected": false,
"text": "const\n data = { material: ['plate', 'bag', 'bottle'], customer: ['cust1', 'cust2', 'cust3'], prod_id: [1122, 3344, 4445] },\n result = Object\n .entries(data)\n .reduce(\n (r, [k, values]) => values.map((v, i) => ({ ...r[i], [k]: v })),\n []\n );\n\nconsole.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 74603098,
"author": "Ha Tai",
"author_id": 14036048,
"author_profile": "https://Stackoverflow.com/users/14036048",
"pm_score": 0,
"selected": false,
"text": "const raw = Object.keys(data).reduce((pre, current) => {\n return data[current].map((value, index) => ({\n [current]: value,\n ...pre[index],\n }));\n}, []);\n"
},
{
"answer_id": 74603177,
"author": "Hedi Zitouni",
"author_id": 12285347,
"author_profile": "https://Stackoverflow.com/users/12285347",
"pm_score": 0,
"selected": false,
"text": " const properties=Object.keys(data)\n const result = data[properties[0]].map((elem, i) => {\n return properties.reduce((acc, curr) => {\n acc[curr] = data[curr][i]\n return acc\n }, {})\n })\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20590519/"
] |
74,602,731
|
<p>I'm trying to get a dynamic date from a span with the id datetime and use that date for a countdown timer. But I see Nan all the time</p>
<pre><code><span id="datetime">30.11.2022 08:50:00</span>
<p id="demo"></p>
<script>
var enddateTime = document.getElementById('datetime').textContent;
// Set the date we're counting down to
var countDownDate = new Date(enddateTime).getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
</code></pre>
<p>I tried using .textContent to get the field value<br />
<code>var enddateTime = document.getElementById('datetime').textContent;</code></p>
<p>Everything is fine in the console, but when I use in the timer script, I get NaN</p>
|
[
{
"answer_id": 74602746,
"author": "Axnyff",
"author_id": 4949918,
"author_profile": "https://Stackoverflow.com/users/4949918",
"pm_score": 2,
"selected": false,
"text": "const rowdata = res_data.material.map((material, index) => ({\n material,\n customer: res_data.customer[index],\n prod_id: res_data.prod_id[index],\n});\n"
},
{
"answer_id": 74602748,
"author": "Jared Smith",
"author_id": 3757232,
"author_profile": "https://Stackoverflow.com/users/3757232",
"pm_score": 0,
"selected": false,
"text": "const rowData = res.data.prod_id.map((prod_id, i) => {\n const material = res.data.material[i];\n const customer = res.data.customer[i];\n return {\n prod_id,\n material,\n customer,\n };\n});\n"
},
{
"answer_id": 74602755,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 0,
"selected": false,
"text": "const\n data = { material: ['plate', 'bag', 'bottle'], customer: ['cust1', 'cust2', 'cust3'], prod_id: [1122, 3344, 4445] },\n result = Object\n .entries(data)\n .reduce(\n (r, [k, values]) => values.map((v, i) => ({ ...r[i], [k]: v })),\n []\n );\n\nconsole.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 74603098,
"author": "Ha Tai",
"author_id": 14036048,
"author_profile": "https://Stackoverflow.com/users/14036048",
"pm_score": 0,
"selected": false,
"text": "const raw = Object.keys(data).reduce((pre, current) => {\n return data[current].map((value, index) => ({\n [current]: value,\n ...pre[index],\n }));\n}, []);\n"
},
{
"answer_id": 74603177,
"author": "Hedi Zitouni",
"author_id": 12285347,
"author_profile": "https://Stackoverflow.com/users/12285347",
"pm_score": 0,
"selected": false,
"text": " const properties=Object.keys(data)\n const result = data[properties[0]].map((elem, i) => {\n return properties.reduce((acc, curr) => {\n acc[curr] = data[curr][i]\n return acc\n }, {})\n })\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14369366/"
] |
74,602,732
|
<p>im looking to solve the problem mentioned in the title without any specific functions that may or may not exist for this[<img src="https://i.stack.imgur.com/TZdnY.png" alt="Example" />]. Something along the lines of using mostly loops.</p>
<p>I tought about reversing each individual row using list.reverse() and then moving the rows around but im not sure how to implement it.</p>
|
[
{
"answer_id": 74602746,
"author": "Axnyff",
"author_id": 4949918,
"author_profile": "https://Stackoverflow.com/users/4949918",
"pm_score": 2,
"selected": false,
"text": "const rowdata = res_data.material.map((material, index) => ({\n material,\n customer: res_data.customer[index],\n prod_id: res_data.prod_id[index],\n});\n"
},
{
"answer_id": 74602748,
"author": "Jared Smith",
"author_id": 3757232,
"author_profile": "https://Stackoverflow.com/users/3757232",
"pm_score": 0,
"selected": false,
"text": "const rowData = res.data.prod_id.map((prod_id, i) => {\n const material = res.data.material[i];\n const customer = res.data.customer[i];\n return {\n prod_id,\n material,\n customer,\n };\n});\n"
},
{
"answer_id": 74602755,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 0,
"selected": false,
"text": "const\n data = { material: ['plate', 'bag', 'bottle'], customer: ['cust1', 'cust2', 'cust3'], prod_id: [1122, 3344, 4445] },\n result = Object\n .entries(data)\n .reduce(\n (r, [k, values]) => values.map((v, i) => ({ ...r[i], [k]: v })),\n []\n );\n\nconsole.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 74603098,
"author": "Ha Tai",
"author_id": 14036048,
"author_profile": "https://Stackoverflow.com/users/14036048",
"pm_score": 0,
"selected": false,
"text": "const raw = Object.keys(data).reduce((pre, current) => {\n return data[current].map((value, index) => ({\n [current]: value,\n ...pre[index],\n }));\n}, []);\n"
},
{
"answer_id": 74603177,
"author": "Hedi Zitouni",
"author_id": 12285347,
"author_profile": "https://Stackoverflow.com/users/12285347",
"pm_score": 0,
"selected": false,
"text": " const properties=Object.keys(data)\n const result = data[properties[0]].map((elem, i) => {\n return properties.reduce((acc, curr) => {\n acc[curr] = data[curr][i]\n return acc\n }, {})\n })\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17387521/"
] |
74,602,743
|
<p>I have hundreds of .wav files and imported them using list.files. Something like above:</p>
<pre><code> [1] "10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Balsam-poplar-English-0701.wav"
[2] "10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Birch-English-0700.wav"
[3] "10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Blueberry-English-0703.wav"
.......
[73] "3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Capercaillie-English-0069.wav"
[74] "3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fat-tail-scorpion-English-0082.wav"
[75] "3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fire-salamander-English-0067.wav"
</code></pre>
<p>I use the following code to reorder the file paths of which I want number in each subpath follows numberic order. I have tried the following</p>
<pre><code>filename<- file_list[order(as.numeric(stringr::str_extract(file_list,"[0-9]+(.*?)")) )]
</code></pre>
<p>The result is something like:</p>
<pre><code> [1] "3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Capercaillie-English-0069.wav"
[2] "3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fat-tail-scorpion-English-0082.wav"
[3] "3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fire-salamander-English-0067.wav"
.......
[73] "10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Balsam-poplar-English-0701.wav"
[74] "10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Birch-English-0700.wav"
[75] "10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Blueberry-English-0703.wav"
</code></pre>
<p>I also want the last subpath follows in numberic order, e.g. English-0067;English-0069. I tried to repeat the matching for the last subpath, but it will disorder the previous order followed by 3...10. How could I let all the numbers in the subpaths follows numberic order?</p>
|
[
{
"answer_id": 74602831,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 1,
"selected": false,
"text": "vec <- c( \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Balsam-poplar-English-0701.wav\",\n\"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Birch-English-0700.wav\",\n\"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Blueberry-English-0703.wav\",\n\"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Capercaillie-English-0069.wav\",\n\"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fat-tail-scorpion-English-0082.wav\",\n\"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fire-salamander-English-0067.wav\")\nnums <- strcapture(\"^([0-9]+).*\\\\b([0-9]+)\\\\.[a-z]+$\", vec, proto=list(a=0L,b=0L))\nnums\n# a b\n# 1 10 701\n# 2 10 700\n# 3 10 703\n# 4 3 69\n# 5 3 82\n# 6 3 67\ndo.call(order, nums)\n# [1] 6 4 5 2 1 3\nvec[do.call(order, nums)]\n# [1] \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fire-salamander-English-0067.wav\" \n# [2] \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Capercaillie-English-0069.wav\" \n# [3] \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fat-tail-scorpion-English-0082.wav\" \n# [4] \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Birch-English-0700.wav\" \n# [5] \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Balsam-poplar-English-0701.wav\"\n# [6] \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Blueberry-English-0703.wav\" \n BL-0001 proto= do.call(order, nums) NA NA nums"
},
{
"answer_id": 74602869,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "ord <- order(as.numeric(sub(\"(^\\\\d+)/.*$\",\"\\\\1\",files)), as.numeric(sub(\"^.*-(\\\\d+)\\\\.wav\",\"\\\\1\",files)))\n\n\nfiles[ord]\n#> [1] \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fire-salamander-English-0067.wav\" \n#> [2] \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Capercaillie-English-0069.wav\" \n#> [3] \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fat-tail-scorpion-English-0082.wav\" \n#> [4] \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Birch-English-0700.wav\" \n#> [5] \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Balsam-poplar-English-0701.wav\"\n#> [6] \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Blueberry-English-0703.wav\"\n"
},
{
"answer_id": 74603139,
"author": "Captain Hat",
"author_id": 4676560,
"author_profile": "https://Stackoverflow.com/users/4676560",
"pm_score": 0,
"selected": false,
"text": "stringr::str_detect() vec <- c( \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Balsam-poplar-English-0701.wav\",\n \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Birch-English-0700.wav\",\n \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Blueberry-English-0703.wav\",\n \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Capercaillie-English-0069.wav\",\n \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fat-tail-scorpion-English-0082.wav\",\n \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fire-salamander-English-0067.wav\")\n\nlibrary(dplyr)\nlibrary(stringr)\n\n\nvec_tib <- tibble(filename = vec)\n\nvec_tib <- mutate(vec_tib,\n num_1 = str_extract(filename, \"\\\\d+\"),\n num_2 = str_extract(filename, \"\\\\d+(?=(\\\\.wav))\"))\n\nhead(vec_tib, 3)\n#> # A tibble: 3 × 3\n#> filename num_1 num_2\n#> <chr> <chr> <chr>\n#> 1 10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Balsa… 10 0701 \n#> 2 10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Birch… 10 0700 \n#> 3 10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Blueb… 10 0703\n\nvec_tib <- mutate(vec_tib, across(starts_with(\"num\"), as.numeric))\n\nvec_tib |> \n arrange(num_1, num_2) |> \n pull(filename)\n#> [1] \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fire-salamander-English-0067.wav\" \n#> [2] \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Capercaillie-English-0069.wav\" \n#> [3] \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fat-tail-scorpion-English-0082.wav\" \n#> [4] \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Birch-English-0700.wav\" \n#> [5] \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Balsam-poplar-English-0701.wav\"\n#> [6] \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Blueberry-English-0703.wav\"\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20624712/"
] |
74,602,757
|
<p>I Have some problem with some value on array at php, here is the array</p>
<pre><code>array:4 [
0 => array:7 [
"id" => 76
"id_sender" => 1
"id_receiver" => 2
"message" => "2 Miliar"
"is_read" => 0
"created_at" => "2022-11-28T13:57:17.000000Z"
"updated_at" => "2022-11-28T13:57:17.000000Z"
]
1 => array:7 [
"id" => 75
"id_sender" => 1
"id_receiver" => 3
"message" => "1 Miliar"
"is_read" => 0
"created_at" => "2022-11-28T13:57:10.000000Z"
"updated_at" => "2022-11-28T13:57:10.000000Z"
]
2 => array:7 [
"id" => 74
"id_sender" => 3
"id_receiver" => 1
"message" => "Property ini berapa harganya?"
"is_read" => 1
"created_at" => "2022-11-28T13:52:57.000000Z"
"updated_at" => "2022-11-28T13:55:37.000000Z"
]
3 => array:7 [
"id" => 73
"id_sender" => 2
"id_receiver" => 1
"message" => "Untuk yang ini berapa harganya?"
"is_read" => 1
"created_at" => "2022-11-28T13:07:34.000000Z"
"updated_at" => "2022-11-28T13:55:33.000000Z"
]
]
</code></pre>
<p>That's my array, I want to skip the the value on index 2 and 3 because I've already the value</p>
<p>for example</p>
<pre><code>id_sender = 1 && id_receiver = 3,
</code></pre>
<p>because on index 2 i already have value, even it is reverse</p>
<pre><code>id_sender = 3 && id_receiver = 1,
</code></pre>
<p>that's put on check of id_receiver of index 2, and another conditions and so one,</p>
<p>the result i want are like this</p>
<pre><code>array:2 [
0 => array:7 [
"id" => 76
"id_sender" => 1
"id_receiver" => 2
"message" => "2 Miliar"
"is_read" => 0
"created_at" => "2022-11-28T13:57:17.000000Z"
"updated_at" => "2022-11-28T13:57:17.000000Z"
]
1 => array:7 [
"id" => 75
"id_sender" => 1
"id_receiver" => 3
"message" => "1 Miliar"
"is_read" => 0
"created_at" => "2022-11-28T13:57:10.000000Z"
"updated_at" => "2022-11-28T13:57:10.000000Z"
]
]
</code></pre>
<p>How can I solve that in php?</p>
<p>** EDIT **</p>
<p>I tried using array_filter, but it didn't change anything:</p>
<pre><code>$member1 = 1;
$member2 = 3;
array_filter($items_message, function($v, $k) use ($member1, $member2) {
return (($k == 'id_sender' && $v == $member1) && ($k == 'id_receiver' && $v == $member2 )) || (($k == 'id_sender' && $v == $member2) && ($k == 'id_receiver' && $v == $member1 ));
}, ARRAY_FILTER_USE_BOTH);
</code></pre>
|
[
{
"answer_id": 74602831,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 1,
"selected": false,
"text": "vec <- c( \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Balsam-poplar-English-0701.wav\",\n\"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Birch-English-0700.wav\",\n\"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Blueberry-English-0703.wav\",\n\"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Capercaillie-English-0069.wav\",\n\"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fat-tail-scorpion-English-0082.wav\",\n\"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fire-salamander-English-0067.wav\")\nnums <- strcapture(\"^([0-9]+).*\\\\b([0-9]+)\\\\.[a-z]+$\", vec, proto=list(a=0L,b=0L))\nnums\n# a b\n# 1 10 701\n# 2 10 700\n# 3 10 703\n# 4 3 69\n# 5 3 82\n# 6 3 67\ndo.call(order, nums)\n# [1] 6 4 5 2 1 3\nvec[do.call(order, nums)]\n# [1] \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fire-salamander-English-0067.wav\" \n# [2] \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Capercaillie-English-0069.wav\" \n# [3] \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fat-tail-scorpion-English-0082.wav\" \n# [4] \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Birch-English-0700.wav\" \n# [5] \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Balsam-poplar-English-0701.wav\"\n# [6] \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Blueberry-English-0703.wav\" \n BL-0001 proto= do.call(order, nums) NA NA nums"
},
{
"answer_id": 74602869,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "ord <- order(as.numeric(sub(\"(^\\\\d+)/.*$\",\"\\\\1\",files)), as.numeric(sub(\"^.*-(\\\\d+)\\\\.wav\",\"\\\\1\",files)))\n\n\nfiles[ord]\n#> [1] \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fire-salamander-English-0067.wav\" \n#> [2] \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Capercaillie-English-0069.wav\" \n#> [3] \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fat-tail-scorpion-English-0082.wav\" \n#> [4] \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Birch-English-0700.wav\" \n#> [5] \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Balsam-poplar-English-0701.wav\"\n#> [6] \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Blueberry-English-0703.wav\"\n"
},
{
"answer_id": 74603139,
"author": "Captain Hat",
"author_id": 4676560,
"author_profile": "https://Stackoverflow.com/users/4676560",
"pm_score": 0,
"selected": false,
"text": "stringr::str_detect() vec <- c( \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Balsam-poplar-English-0701.wav\",\n \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Birch-English-0700.wav\",\n \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Blueberry-English-0703.wav\",\n \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Capercaillie-English-0069.wav\",\n \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fat-tail-scorpion-English-0082.wav\",\n \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fire-salamander-English-0067.wav\")\n\nlibrary(dplyr)\nlibrary(stringr)\n\n\nvec_tib <- tibble(filename = vec)\n\nvec_tib <- mutate(vec_tib,\n num_1 = str_extract(filename, \"\\\\d+\"),\n num_2 = str_extract(filename, \"\\\\d+(?=(\\\\.wav))\"))\n\nhead(vec_tib, 3)\n#> # A tibble: 3 × 3\n#> filename num_1 num_2\n#> <chr> <chr> <chr>\n#> 1 10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Balsa… 10 0701 \n#> 2 10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Birch… 10 0700 \n#> 3 10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Blueb… 10 0703\n\nvec_tib <- mutate(vec_tib, across(starts_with(\"num\"), as.numeric))\n\nvec_tib |> \n arrange(num_1, num_2) |> \n pull(filename)\n#> [1] \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fire-salamander-English-0067.wav\" \n#> [2] \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Capercaillie-English-0069.wav\" \n#> [3] \"3/Project_English-3/BL-0002_Lesser-horseshoe-bat/Fat-tail-scorpion-English-0082.wav\" \n#> [4] \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Birch-English-0700.wav\" \n#> [5] \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Balsam-poplar-English-0701.wav\"\n#> [6] \"10/Project_English-10/BL-0001_A-conifer-cone-contains-seeds/Blueberry-English-0703.wav\"\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6462825/"
] |
74,602,779
|
<p>Let's say I have an abstract class, called Logger:</p>
<pre><code>public abstract class AbstractLogger {
public enum Levels {
DEBUG, INFO, WARNING, ERROR
}
public void debug(String message) {
Levels level = Levels.DEBUG;
log(level, message);
}
public void info(String message) {
Levels level = Levels.INFO;
log(level, message);
}
public void warning(String message) {
Levels level = Levels.WARNING;
log(level, message); }
public void error(String message) {
Levels level = Levels.ERROR;
log(level, message); }
public void log(Levels level, String message) {}
</code></pre>
<p>}</p>
<p>And I also have classes that inherit this class, such as FileAppenderLogger:</p>
<pre><code>public class FileAppenderLogger extends AbstractLogger {
private final Path logPath;
public FileAppender(Path logPath) {
this.logPath = logPath;
createLogFile();
}
private void createLogFile() {
try {
File logFile = new File(logPath.toString());
if (logFile.createNewFile()) {
System.out.println("File created: " + logFile.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
@Override
public void log(Levels level, String message) {
try {
FileWriter myWriter = new FileWriter(this.logPath.toString());
myWriter.write(message+"\n");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
@Override
public void debug(String message) {
super.info(message);
}
@Override
public void info(String message) {
super.info(message);
}
@Override
public void warning(String message) {
super.warning(message);
}
@Override
public void error(String message) {
super.error(message);
}
</code></pre>
<p>}</p>
<p>Now, let's say I need to extend Logger to support new Log level, such as "FATAL", and also extend its children, such as FileAppenderLogger to support it, without modify any of those classes, only extend them.
what could be the best practice for that (if I still want to preserve non generic methods such as ".info(String s)" or ".debug(String s))?
What design pattern may I use here?
I'm open for changes regard this problem.
Thank you!</p>
|
[
{
"answer_id": 74602863,
"author": "rzwitserloot",
"author_id": 768644,
"author_profile": "https://Stackoverflow.com/users/768644",
"pm_score": 1,
"selected": false,
"text": "AbstractLogger public abstract class AbstractLogger {\n public enum Levels {\n DEBUG, INFO, WARNING, ERROR, /* added */ FATAL,\n }\n\n public void fatal(String message) {\n log(Levels.FATAL, message);\n }\n}\n AbstractLogger log FileAppenderLogger .error(x) log Level Levels String Strings java.lang.String Strings Levels Level Levels"
},
{
"answer_id": 74603182,
"author": "TheEntropyShard",
"author_id": 19857533,
"author_profile": "https://Stackoverflow.com/users/19857533",
"pm_score": 1,
"selected": false,
"text": "enum LogLevel LogLevelError, LogLevelFatal this.logLevel.log(message);"
},
{
"answer_id": 74603325,
"author": "Chaosfire",
"author_id": 17795888,
"author_profile": "https://Stackoverflow.com/users/17795888",
"pm_score": 1,
"selected": false,
"text": "String Level public class Level {\n\n private final String levelName;\n\n //getter, etc.\n}\n AbstractLogger fatal() public class ExtendedLogger extends AbstractLogger {\n\n private final AbstractLogger abstractLogger;\n\n public ExtendedLogger(AbstractLogger abstractLogger) {\n this.abstractLogger = abstractLogger;\n }\n\n @Override\n public void debug(String message) {\n abstractLogger.debug(message);\n }\n\n //info, warning and rest of methods\n\n @Override\n public void log(Levels level, String message) {\n abstractLogger.log(level, message);\n }\n\n public void fatal(String message) {\n //implement\n }\n}\n"
},
{
"answer_id": 74603353,
"author": "Joop Eggen",
"author_id": 984823,
"author_profile": "https://Stackoverflow.com/users/984823",
"pm_score": 0,
"selected": false,
"text": "java.util.Logger System.Logger FileHandler Handler *Exception FileWriter Handler"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7953882/"
] |
74,602,801
|
<p>Anybody knows how to tell jsreport about the custom fonts when loading it in .net core?</p>
<p>jsreport does not seem to load the font, no matter what and there is no clear documentation on how to do it in .net.</p>
<p>Program.cs:
`</p>
<pre><code>AddJsReport(new LocalReporting().UseBinary(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
jsreport.Binary.JsReportBinary.GetBinary() :
jsreport.Binary.Linux.JsReportBinary.GetBinary())
.KillRunningJsReportProcesses()
.AsUtility()
.Create());
</code></pre>
<p>`</p>
<p>Controller.cs:
`</p>
<pre><code>HttpContext.JsReportFeature().Recipe(Recipe.ChromePdf)
.DebugLogsToResponse()
.Configure((r) =>
{
r.Options.Base = $"http://127.0.0.1:{HttpContext.Request.Host.Port??80}";
r.Template.Chrome = new Chrome
{
MarginTop = "0mm",
MarginLeft = "0mm",
MarginBottom = "0mm",
MarginRight = "0mm",
Format = "A4",
WaitForNetworkIddle = true,
};
});
</code></pre>
<p>`</p>
<p>css:
`</p>
<pre><code>@font-face {
font-family: Athletics Regular;
src: url('fonts/Athletics/Athletics-Regular.otf');
}
</code></pre>
<p>`</p>
<pre><code></code></pre>
|
[
{
"answer_id": 74602863,
"author": "rzwitserloot",
"author_id": 768644,
"author_profile": "https://Stackoverflow.com/users/768644",
"pm_score": 1,
"selected": false,
"text": "AbstractLogger public abstract class AbstractLogger {\n public enum Levels {\n DEBUG, INFO, WARNING, ERROR, /* added */ FATAL,\n }\n\n public void fatal(String message) {\n log(Levels.FATAL, message);\n }\n}\n AbstractLogger log FileAppenderLogger .error(x) log Level Levels String Strings java.lang.String Strings Levels Level Levels"
},
{
"answer_id": 74603182,
"author": "TheEntropyShard",
"author_id": 19857533,
"author_profile": "https://Stackoverflow.com/users/19857533",
"pm_score": 1,
"selected": false,
"text": "enum LogLevel LogLevelError, LogLevelFatal this.logLevel.log(message);"
},
{
"answer_id": 74603325,
"author": "Chaosfire",
"author_id": 17795888,
"author_profile": "https://Stackoverflow.com/users/17795888",
"pm_score": 1,
"selected": false,
"text": "String Level public class Level {\n\n private final String levelName;\n\n //getter, etc.\n}\n AbstractLogger fatal() public class ExtendedLogger extends AbstractLogger {\n\n private final AbstractLogger abstractLogger;\n\n public ExtendedLogger(AbstractLogger abstractLogger) {\n this.abstractLogger = abstractLogger;\n }\n\n @Override\n public void debug(String message) {\n abstractLogger.debug(message);\n }\n\n //info, warning and rest of methods\n\n @Override\n public void log(Levels level, String message) {\n abstractLogger.log(level, message);\n }\n\n public void fatal(String message) {\n //implement\n }\n}\n"
},
{
"answer_id": 74603353,
"author": "Joop Eggen",
"author_id": 984823,
"author_profile": "https://Stackoverflow.com/users/984823",
"pm_score": 0,
"selected": false,
"text": "java.util.Logger System.Logger FileHandler Handler *Exception FileWriter Handler"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11785611/"
] |
74,602,813
|
<p>Sorry if its a very basic question but I dont understand the following:</p>
<p>When I format the Date object (no matter what library I used), I get a string.</p>
<pre><code>from this: 2022-11-28T16:55:44.000Z (new Date object)
I get this: 2022-11-28 16:55:44 (or other formats obviously depending how I format it)
</code></pre>
<p>Even if I turn it back into an object it, the T and 000Z will never be there anymore. Do I just ignore that (seems like it as any library or date methods are ignoring the T and the string ending when formatting) or do I add it 'back' Isnt it a problem if dates stored in my db are different (for later queries etc.)?</p>
|
[
{
"answer_id": 74603127,
"author": "Heiko Theißen",
"author_id": 16462950,
"author_profile": "https://Stackoverflow.com/users/16462950",
"pm_score": 2,
"selected": false,
"text": "Z Date > utc = '2022-11-28T16:55:44.000Z'\n'2022-11-28T16:55:44.000Z'\n> d = new Date(utc)\nMon Nov 28 2022 17:55:44 GMT+0100 (Central European Standard Time)\n> d.toISOString()\n'2022-11-28T16:55:44.000Z'\n Date > formatted = '2022-11-28 17:55:44'\n'2022-11-28 17:55:44'\n> d = new Date(formatted)\nMon Nov 28 2022 17:55:44 GMT+0100 (Central European Standard Time)\n> d.toLocaleString()\n'11/28/2022, 5:55:44 PM'\n Date Date Date 9/11/2022 Date"
},
{
"answer_id": 74604702,
"author": "Wernfried Domscheit",
"author_id": 3027266,
"author_profile": "https://Stackoverflow.com/users/3027266",
"pm_score": 3,
"selected": true,
"text": "Date Date new Date(<string>)"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6377312/"
] |
74,602,815
|
<p>I started c++ a few days ago and when ever I write an else if statement I always get the error <code>‘else’ without a previous ‘if’</code>. Here is my code (I'm trying to make rock paper scissors between users btw. I want to eventually add lizard and spock too from the big bang show.):</p>
<pre><code>/*
This program will play rock paper scissors with the user
*/
#include <iostream>
#include <stdlib.h>
int main() {
srand(time(NULL));
int computer = rand() % 3 + 1;
int user = 0;
std::cout << "===========================\nrock paper scissors!\n===========================\n";
std::cout << "1) ROCK\n";
std::cout << "2) PAPER\n";
std::cout << "3) SCISSORS\n";
std::cout << "shoot! \n";
std::cin >> user;
/*
if (user == 1) {
std::cout << "You pick rock!\n";
}
else if (user == 2) {
std::cout << "You pick paper!\n";
}
else if (user == 3) {
std::cout << "You picked scissors!\n";
}
else {
std::cout << "Invalid input, please select a number between 1 and 3\n";
*/
if (computer == 1)
std::cout << "CPU picks Rock!";
else if (computer == 2)
std::cout << "CPU picks Paper!";
else
std::cout << "CPU picks Scissors!";
if (user == 1)
std::cout << "You pick rock!\n";
if (computer == 1)
std::cout << "You both tie!\n";
else if (computer == 2)
std::cout << "You lose. You really just aren't good at rock paper scissors lizard spock\n";
else
std::cout << "You win!\n";
else if (user == 2)
std::cout << "You pick paper!\n";
if (computer == 2)
std::cout << "You both tie!\n";
else if (computer == 3)
std::cout << "You lose. You really just aren't good at rock paper scissors lizard spock\n";
else
std::cout << "You win!\n";
else if (user == 3)
std::cout << "You picked scissors!\n";
if (computer == 3)
std::cout << "You both tie!\n";
else if (computer == 1)
std::cout << "You lose. You really just aren't good at rock paper scissors lizard spock\n";
else
std::cout << "You win!\n";
else
std::cout << "Invalid input, please select a number between 1 and 3 (No Spaces please!)\n";
}
</code></pre>
<p>I tried adding and removing curly brackets. (I heard they were optional though) I tried switching else if to if else because I always forget which one to use. I also tried checking to make sure I didn't use any semi colons because it seems that's always a big issue. I'm still learn though and I'm very new to c++, so go easy on me.</p>
|
[
{
"answer_id": 74602910,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 3,
"selected": true,
"text": "if (user == 1)\n std::cout << \"You pick rock!\\n\";\n if (computer == 1)\n std::cout << \"You both tie!\\n\";\n else if (computer == 2)\n std::cout << \"You lose. You really just aren't good at rock paper scissors lizard spock\\n\";\n else\n std::cout << \"You win!\\n\";\nelse if (user == 2)\n std::cout << \"You pick paper!\\n\";\n if (computer == 2)\n std::cout << \"You both tie!\\n\";\n else if (computer == 3)\n std::cout << \"You lose. You really just aren't good at rock paper scissors lizard spock\\n\";\n else\n std::cout << \"You win!\\n\";\nelse if (user == 3)\n std::cout << \"You picked scissors!\\n\";\n if (computer == 3)\n std::cout << \"You both tie!\\n\";\n else if (computer == 1)\n std::cout << \"You lose. You really just aren't good at rock paper scissors lizard spock\\n\";\n else\n std::cout << \"You win!\\n\";\nelse\n std::cout << \"Invalid input, please select a number between 1 and 3 (No Spaces please!)\\n\";\n else if (user == 2)\n if (computer == 1)\n std::cout << \"You both tie!\\n\";\n else if (computer == 2)\n std::cout << \"You lose. You really just aren't good at rock paper scissors lizard spock\\n\";\n else\n std::cout << \"You win!\\n\";\n if (user == 1)\n{\n std::cout << \"You pick rock!\\n\";\n if (computer == 1)\n std::cout << \"You both tie!\\n\";\n else if (computer == 2)\n std::cout << \"You lose. You really just aren't good at rock paper scissors lizard spock\\n\";\n else\n std::cout << \"You win!\\n\";\n}\nelse if (user == 2)\n{\n std::cout << \"You pick paper!\\n\";\n if (computer == 2)\n std::cout << \"You both tie!\\n\";\n else if (computer == 3)\n std::cout << \"You lose. You really just aren't good at rock paper scissors lizard spock\\n\";\n else\n std::cout << \"You win!\\n\";\n}\nelse if (user == 3)\n{\n std::cout << \"You picked scissors!\\n\";\n if (computer == 3)\n std::cout << \"You both tie!\\n\";\n else if (computer == 1)\n std::cout << \"You lose. You really just aren't good at rock paper scissors lizard spock\\n\";\n else\n std::cout << \"You win!\\n\";\n}\nelse\n{\n std::cout << \"Invalid input, please select a number between 1 and 3 (No Spaces please!)\\n\";\n}\n switch switch (user)\n{\ncase 1:\n std::cout << \"You pick rock!\\n\";\n if (computer == 1)\n std::cout << \"You both tie!\\n\";\n else if (computer == 2)\n std::cout << \"You lose. You really just aren't good at rock paper scissors lizard spock\\n\";\n else\n std::cout << \"You win!\\n\";\n break;\n\ncase 2:\n std::cout << \"You pick paper!\\n\";\n if (computer == 2)\n std::cout << \"You both tie!\\n\";\n else if (computer == 3)\n std::cout << \"You lose. You really just aren't good at rock paper scissors lizard spock\\n\";\n else\n std::cout << \"You win!\\n\";\n break;\n\ncase 3:\n std::cout << \"You picked scissors!\\n\";\n if (computer == 3)\n std::cout << \"You both tie!\\n\";\n else if (computer == 1)\n std::cout << \"You lose. You really just aren't good at rock paper scissors lizard spock\\n\";\n else\n std::cout << \"You win!\\n\";\n break;\n\ndefault:\n std::cout << \"Invalid input, please select a number between 1 and 3 (No Spaces please!)\\n\";\n break;\n}\n enum { Rock = 1, Paper = 2, Scissors = 3 };\n\n//...\n\nswitch (user)\n{\ncase Rock:\n std::cout << \"You pick rock!\\n\";\n if (computer == 1)\n std::cout << \"You both tie!\\n\";\n else if (computer == 2)\n std::cout << \"You lose. You really just aren't good at rock paper scissors lizard spock\\n\";\n else\n std::cout << \"You win!\\n\";\n break;\n\ncase Paper:\n std::cout << \"You pick paper!\\n\";\n if (computer == 2)\n std::cout << \"You both tie!\\n\";\n else if (computer == 3)\n std::cout << \"You lose. You really just aren't good at rock paper scissors lizard spock\\n\";\n else\n std::cout << \"You win!\\n\";\n break;\n\ncase Scissors:\n std::cout << \"You picked scissors!\\n\";\n if (computer == 3)\n std::cout << \"You both tie!\\n\";\n else if (computer == 1)\n std::cout << \"You lose. You really just aren't good at rock paper scissors lizard spock\\n\";\n else\n std::cout << \"You win!\\n\";\n break;\n\ndefault:\n std::cout << \"Invalid input, please select a number between \" << Rock << \" and \" << Scissors << \" (No Spaces please!)\\n\";\n break;\n}\n"
},
{
"answer_id": 74602926,
"author": "463035818_is_not_a_number",
"author_id": 4117728,
"author_profile": "https://Stackoverflow.com/users/4117728",
"pm_score": 3,
"selected": false,
"text": "if (user == 1)\n std::cout << \"You pick rock!\\n\";\n if (computer == 1)\n std::cout << \"You both tie!\\n\";\n else if (computer == 2)\n std::cout << \"You lose. You really just aren't good at rock paper scissors lizard spock\\n\";\n else\n std::cout << \"You win!\\n\";\nelse if (user == 2)\n if (user == 1)\n std::cout << \"You pick rock!\\n\";\nif (computer == 1)\n std::cout << \"You both tie!\\n\";\nelse if (computer == 2)\n std::cout << \"You lose. You really just aren't good at rock paper scissors lizard spock\\n\";\nelse\n std::cout << \"You win!\\n\";\nelse if (user == 2) // <-------------------------\n if (foo) {\n std::cout << blabla;\n}\n\n// same as \n\nif (foo) std::cout << blabla;\n if (foo) \n std::cout << blabla;\n std::cout << whoops;\n\n// is the same as \n\nif (foo) { \n std::cout << blabla; \n}\nstd::cout << whoops;\n"
},
{
"answer_id": 74603018,
"author": "SimonC",
"author_id": 2921426,
"author_profile": "https://Stackoverflow.com/users/2921426",
"pm_score": 0,
"selected": false,
"text": "/*\nThis program will play rock paper scissors with the user\n*/\n\n\n#include <iostream>\n#include <stdlib.h>\n\nint main() {\n\n srand(time(NULL));\n int computer = rand() % 3 + 1;\n int user = 0;\n\n std::cout << \"===========================\\nrock paper scissors!\\n===========================\\n\";\n std::cout << \"1) ROCK\\n\";\n std::cout << \"2) PAPER\\n\";\n std::cout << \"3) SCISSORS\\n\";\n\n std::cout << \"shoot! \\n\";\n std::cin >> user;\n\n if (computer == 1) {\n std::cout << \"CPU picks Rock!\";\n } else if (computer == 2) {\n std::cout << \"CPU picks Paper!\";\n } else {\n std::cout << \"CPU picks Scissors!\";\n }\n\n if (user == 1) {\n std::cout << \"You pick rock!\\n\";\n if (computer == 1) {\n std::cout << \"You both tie!\\n\";\n } else if (computer == 2) {\n std::cout << \"You lose. You really just aren't good at rock paper scissors lizard spock\\n\";\n } else {\n std::cout << \"You win!\\n\";\n } else if (user == 2) {\n std::cout << \"You pick paper!\\n\";\n if (computer == 2) {\n std::cout << \"You both tie!\\n\";\n } else if (computer == 3) {\n std::cout << \"You lose. You really just aren't good at rock paper scissors lizard spock\\n\";\n } else {\n std::cout << \"You win!\\n\";\n }\n } else if (user == 3) {\n std::cout << \"You picked scissors!\\n\";\n if (computer == 3) {\n std::cout << \"You both tie!\\n\";\n } else if (computer == 1) {\n std::cout << \"You lose. You really just aren't good at rock paper scissors lizard spock\\n\";\n } else {\n std::cout << \"You win!\\n\";\n }\n } else {\n std::cout << \"Invalid input, please select a number between 1 and 3 (No Spaces please!)\\n\";\n }\n }\n}\n"
},
{
"answer_id": 74603944,
"author": "sweenish",
"author_id": 6119582,
"author_profile": "https://Stackoverflow.com/users/6119582",
"pm_score": 0,
"selected": false,
"text": " if (choice == cpuChoice) {\n std::cout << \"You tied.\\n\";\n } else if ((choice == ROCK && cpuChoice == SCISSORS) ||\n (choice == PAPER && cpuChoice == ROCK) ||\n (choice == SCISSORS && cpuChoice == PAPER)) {\n std::cout << \"You won!\\n\";\n } else {\n std::cout << \"You lost...\\n\";\n }\n enum enum enum enum enum class"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17762920/"
] |
74,602,817
|
<p>I have hamburger menu and added click to open a sub menu and after that struggling to close the sub-menu, please check the detailed code below. Thanks...!!</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function myFunction() {
document.getElementById("mob").style.display = "inline-flex";
document.getElementById("mob").style.position = "absolute";
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hamburger {
width: 35px;
height: 5px;
background-color: #f7941e;
margin: 6px 0;
}
.mobile-menu {
display: none;
}
.hamburger-container {
cursor: pointer;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="mobile-navbar">
<div class="hamburger-container" onclick="myFunction()">
<div class="hamburger"></div>
<div class="hamburger"></div>
<div class="hamburger"></div>
<div class="mobile-menu" id="mob">
<ul class="mobile-menu-container">
<li class="mobile-menu-items">Home</li>
<li class="mobile-menu-items">Types Tours
<div class="mobile-types-sub-menu">
<ul class="mobile-types-sub-menu-items">
<li>test-1</li>
<li>test-2</li>
<li>test-3</li>
</ul>
</div>
</li>
<li class="mobile-menu-items">The regions</li>
<li class="mobile-menu-items">Instructors</li>
<li class="mobile-menu-items">Questions / Answers</li>
<li class="mobile-menu-items">Contacts</li>
</ul>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74602860,
"author": "FUZIION",
"author_id": 13050564,
"author_profile": "https://Stackoverflow.com/users/13050564",
"pm_score": 1,
"selected": false,
"text": "active #mob function myFunction() {\n const toggle_btn = document.getElementById('mob');\n toggle_btn.classList.toggle('active');\n} .hamburger {\n width: 35px;\n height: 5px;\n background-color: #f7941e;\n margin: 6px 0;\n}\n\n.mobile-menu {\n display: none;\n}\n\n.hamburger-container {\n cursor: pointer;\n}\n\n#mob.active {\n display: inline-flex;\n position: absolute;\n} <div class=\"mobile-navbar\">\n <div class=\"hamburger-container\" onclick=\"myFunction()\">\n <div class=\"hamburger\"></div>\n <div class=\"hamburger\"></div>\n <div class=\"hamburger\"></div>\n <div class=\"mobile-menu\" id=\"mob\">\n <ul class=\"mobile-menu-container\">\n <li class=\"mobile-menu-items\">Home</li>\n <li class=\"mobile-menu-items\">Types Tours\n <div class=\"mobile-types-sub-menu\">\n <ul class=\"mobile-types-sub-menu-items\">\n <li>test-1</li>\n <li>test-2</li>\n <li>test-3</li>\n </ul>\n </div>\n </li>\n <li class=\"mobile-menu-items\">The regions</li>\n <li class=\"mobile-menu-items\">Instructors</li>\n <li class=\"mobile-menu-items\">Questions / Answers</li>\n <li class=\"mobile-menu-items\">Contacts</li>\n </ul>\n </div>\n </div>\n</div>"
},
{
"answer_id": 74602895,
"author": "Agustin G.",
"author_id": 12160496,
"author_profile": "https://Stackoverflow.com/users/12160496",
"pm_score": 1,
"selected": true,
"text": "hidden toggle const myFunction = () => document.getElementById(\"mob\").classList.toggle(\"hidden\"); .hamburger {\n width: 35px;\n height: 5px;\n background-color: #f7941e;\n margin: 6px 0;\n}\n\n.mobile-menu {\n display: inline-flex;\n position: absolute;\n}\n\n.mobile-menu.hidden {\n display: none;\n}\n\n.hamburger-container {\n cursor: pointer;\n} <div class=\"mobile-navbar\">\n <div class=\"hamburger-container\" onclick=\"myFunction()\">\n <div class=\"hamburger\"></div>\n <div class=\"hamburger\"></div>\n <div class=\"hamburger\"></div>\n <div class=\"mobile-menu hidden\" id=\"mob\">\n <ul class=\"mobile-menu-container\">\n <li class=\"mobile-menu-items\">Home</li>\n <li class=\"mobile-menu-items\">Types Tours\n <div class=\"mobile-types-sub-menu\">\n <ul class=\"mobile-types-sub-menu-items\">\n <li>test-1</li>\n <li>test-2</li>\n <li>test-3</li>\n </ul>\n </div>\n </li>\n <li class=\"mobile-menu-items\">The regions</li>\n <li class=\"mobile-menu-items\">Instructors</li>\n <li class=\"mobile-menu-items\">Questions / Answers</li>\n <li class=\"mobile-menu-items\">Contacts</li>\n </ul>\n </div>\n </div>\n</div>"
},
{
"answer_id": 74608980,
"author": "dumb_coder",
"author_id": 20625008,
"author_profile": "https://Stackoverflow.com/users/20625008",
"pm_score": 0,
"selected": false,
"text": "active-mobile-menu classList.toggle() function myFunction() {\n let mobileMenu = document.getElementById('mob');\n mobileMenu.classList.toggle('active-mobile-menu');\n} .hamburger {\n width: 35px;\n height: 5px;\n background-color: #f7941e;\n margin: 6px 0;\n }\n\n .mobile-menu {\n display: none;\n }\n\n .active-mobile-menu{\n display: block;\n position: absolute;\n }\n\n .hamburger-container {\n cursor: pointer;\n } <div class=\"mobile-navbar\">\n <div class=\"hamburger-container\" onclick=\"myFunction()\">\n <div class=\"hamburger\"></div>\n <div class=\"hamburger\"></div>\n <div class=\"hamburger\"></div>\n <div class=\"mobile-menu\" id=\"mob\">\n <ul class=\"mobile-menu-container\">\n <li class=\"mobile-menu-items\">Home</li>\n <li class=\"mobile-menu-items\">Types Tours\n <div class=\"mobile-types-sub-menu\">\n <ul class=\"mobile-types-sub-menu-items\">\n <li>test-1</li>\n <li>test-2</li>\n <li>test-3</li>\n </ul>\n </div>\n </li>\n <li class=\"mobile-menu-items\">The regions</li>\n <li class=\"mobile-menu-items\">Instructors</li>\n <li class=\"mobile-menu-items\">Questions / Answers</li>\n <li class=\"mobile-menu-items\">Contacts</li>\n </ul>\n </div>\n </div>\n </div>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13701644/"
] |
74,602,834
|
<p>I want to call a function where drawableprofile is binding as a profile icon. I want to call it when "imageUrl" child doesn't exist.</p>
<pre><code>val uid = firebaseAuth.currentUser?.uid
if (uid != null) {
database.child(uid).get().addOnSuccessListener {
if (it.exists()) {
val fetchimg = it.child("imageUrl").value
Glide.with(this).load(fetchimg).into(binding.profileIcon)
} else if {
database.child(uid).child("imageUrl")
val drawableprofile = resources.getDrawable(R.drawable.ic_person)
Glide.with(this).load(drawableprofile).into(binding.profileIcon)
}
}
}
</code></pre>
<p>I can't find any .isNull function etc. Thanks for help</p>
|
[
{
"answer_id": 74602860,
"author": "FUZIION",
"author_id": 13050564,
"author_profile": "https://Stackoverflow.com/users/13050564",
"pm_score": 1,
"selected": false,
"text": "active #mob function myFunction() {\n const toggle_btn = document.getElementById('mob');\n toggle_btn.classList.toggle('active');\n} .hamburger {\n width: 35px;\n height: 5px;\n background-color: #f7941e;\n margin: 6px 0;\n}\n\n.mobile-menu {\n display: none;\n}\n\n.hamburger-container {\n cursor: pointer;\n}\n\n#mob.active {\n display: inline-flex;\n position: absolute;\n} <div class=\"mobile-navbar\">\n <div class=\"hamburger-container\" onclick=\"myFunction()\">\n <div class=\"hamburger\"></div>\n <div class=\"hamburger\"></div>\n <div class=\"hamburger\"></div>\n <div class=\"mobile-menu\" id=\"mob\">\n <ul class=\"mobile-menu-container\">\n <li class=\"mobile-menu-items\">Home</li>\n <li class=\"mobile-menu-items\">Types Tours\n <div class=\"mobile-types-sub-menu\">\n <ul class=\"mobile-types-sub-menu-items\">\n <li>test-1</li>\n <li>test-2</li>\n <li>test-3</li>\n </ul>\n </div>\n </li>\n <li class=\"mobile-menu-items\">The regions</li>\n <li class=\"mobile-menu-items\">Instructors</li>\n <li class=\"mobile-menu-items\">Questions / Answers</li>\n <li class=\"mobile-menu-items\">Contacts</li>\n </ul>\n </div>\n </div>\n</div>"
},
{
"answer_id": 74602895,
"author": "Agustin G.",
"author_id": 12160496,
"author_profile": "https://Stackoverflow.com/users/12160496",
"pm_score": 1,
"selected": true,
"text": "hidden toggle const myFunction = () => document.getElementById(\"mob\").classList.toggle(\"hidden\"); .hamburger {\n width: 35px;\n height: 5px;\n background-color: #f7941e;\n margin: 6px 0;\n}\n\n.mobile-menu {\n display: inline-flex;\n position: absolute;\n}\n\n.mobile-menu.hidden {\n display: none;\n}\n\n.hamburger-container {\n cursor: pointer;\n} <div class=\"mobile-navbar\">\n <div class=\"hamburger-container\" onclick=\"myFunction()\">\n <div class=\"hamburger\"></div>\n <div class=\"hamburger\"></div>\n <div class=\"hamburger\"></div>\n <div class=\"mobile-menu hidden\" id=\"mob\">\n <ul class=\"mobile-menu-container\">\n <li class=\"mobile-menu-items\">Home</li>\n <li class=\"mobile-menu-items\">Types Tours\n <div class=\"mobile-types-sub-menu\">\n <ul class=\"mobile-types-sub-menu-items\">\n <li>test-1</li>\n <li>test-2</li>\n <li>test-3</li>\n </ul>\n </div>\n </li>\n <li class=\"mobile-menu-items\">The regions</li>\n <li class=\"mobile-menu-items\">Instructors</li>\n <li class=\"mobile-menu-items\">Questions / Answers</li>\n <li class=\"mobile-menu-items\">Contacts</li>\n </ul>\n </div>\n </div>\n</div>"
},
{
"answer_id": 74608980,
"author": "dumb_coder",
"author_id": 20625008,
"author_profile": "https://Stackoverflow.com/users/20625008",
"pm_score": 0,
"selected": false,
"text": "active-mobile-menu classList.toggle() function myFunction() {\n let mobileMenu = document.getElementById('mob');\n mobileMenu.classList.toggle('active-mobile-menu');\n} .hamburger {\n width: 35px;\n height: 5px;\n background-color: #f7941e;\n margin: 6px 0;\n }\n\n .mobile-menu {\n display: none;\n }\n\n .active-mobile-menu{\n display: block;\n position: absolute;\n }\n\n .hamburger-container {\n cursor: pointer;\n } <div class=\"mobile-navbar\">\n <div class=\"hamburger-container\" onclick=\"myFunction()\">\n <div class=\"hamburger\"></div>\n <div class=\"hamburger\"></div>\n <div class=\"hamburger\"></div>\n <div class=\"mobile-menu\" id=\"mob\">\n <ul class=\"mobile-menu-container\">\n <li class=\"mobile-menu-items\">Home</li>\n <li class=\"mobile-menu-items\">Types Tours\n <div class=\"mobile-types-sub-menu\">\n <ul class=\"mobile-types-sub-menu-items\">\n <li>test-1</li>\n <li>test-2</li>\n <li>test-3</li>\n </ul>\n </div>\n </li>\n <li class=\"mobile-menu-items\">The regions</li>\n <li class=\"mobile-menu-items\">Instructors</li>\n <li class=\"mobile-menu-items\">Questions / Answers</li>\n <li class=\"mobile-menu-items\">Contacts</li>\n </ul>\n </div>\n </div>\n </div>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20407324/"
] |
74,602,929
|
<p>I found for bash, using <code>$'string'</code> allows for escape characters. I also want to use a variable in the string like <code>$'string ${var}'</code>. However, the variable is not expanded and the output is <code>string ${var}</code>. Is there a way to use a variable in this type of string?</p>
<p>The reason I am using the string method with the dollar sign in front is to use the hexcode for a custom font to get a symbol. The desired goal is shown below.</p>
<pre><code>sybmol='\uF107'
echo $'\uF101 ${symbol}'
</code></pre>
|
[
{
"answer_id": 74602988,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 2,
"selected": false,
"text": "symbol='\\uF107'\necho -e \"\\uF101 ${symbol}\"\n printf '%b\\n' \"\\uF101 ${symbol}\"\n"
},
{
"answer_id": 74603144,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 2,
"selected": true,
"text": "\\u symbol symbol=$'\\uF107'\n echo echo $'\\uF101'\"${symbol}\"\n $'...' echo -e symbol='\\uF107'\necho -e '\\uF101'\"$symobl\"\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13231537/"
] |
74,602,934
|
<p>How did compiler decide to call bar function without knowing the type of template parameter <code>T</code> of foo function?</p>
<p>Usually when we call <code>foo(2)</code>, <code>T</code> is deduced as <code>int</code> based on argument <code>2</code>.</p>
<p>Here <code>T</code> is deduced based on parameters of function <code>bar</code> to which <code>foo</code> is passed.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
template<typename T>
void foo(const T& a_) {
std::cout << a_<< std::endl;
}
void bar(void (*ptr) (const int&)) {
std::cout << "bar called" << std::endl;
}
int main() {
bar(foo);
}
</code></pre>
<p><strong>compiler</strong>: gcc</p>
|
[
{
"answer_id": 74603861,
"author": "Karen Baghdasaryan",
"author_id": 15262489,
"author_profile": "https://Stackoverflow.com/users/15262489",
"pm_score": 0,
"selected": false,
"text": "T bar const int& T int"
},
{
"answer_id": 74603981,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 3,
"selected": true,
"text": "foo foo void(*)(const int&) foo void(const int&) void(*)(const int&) void(const T&) void(*)(const T&) void(*)(const int&)\n void(*)(const T&)\n T T int T = int"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5750805/"
] |
74,602,965
|
<p>So I am working on a project and want to get an image from my server to the application.
I use an imagesource to get the image I need and it works fine on UWP but when I test it on Android it does not work. I tried everything I could find on the internet and it is still not working.</p>
<p>If you could help that would be great,
Thank you.</p>
<pre><code>ImageSource fotoopad = ImageSource.FromFile("uploadplaceholder.png");
if (x.FotoPath != "") fotoopad = ImageSource.FromUri(new Uri(XamerinAPP.LoginApp.apiUrl + @"/api/media/image/" + x.Id));
</code></pre>
<p>and the xamarin.</p>
<pre><code><Image x:Name="StackMediaIMAGE" IsVisible="{Binding isFoto}" Source="{Binding fotoPad}"/>
</code></pre>
|
[
{
"answer_id": 74603861,
"author": "Karen Baghdasaryan",
"author_id": 15262489,
"author_profile": "https://Stackoverflow.com/users/15262489",
"pm_score": 0,
"selected": false,
"text": "T bar const int& T int"
},
{
"answer_id": 74603981,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 3,
"selected": true,
"text": "foo foo void(*)(const int&) foo void(const int&) void(*)(const int&) void(const T&) void(*)(const T&) void(*)(const int&)\n void(*)(const T&)\n T T int T = int"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74602965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14219597/"
] |
74,603,005
|
<p>Is there a reliable way to use MLFlow in a functional style? As it is not possible to pass the run ID for example to the function which logs a parameter, I wonder whether it is possible to seperate code executed in my MLFLow run into multiple pure fuctions. Have I overlooked something, or is it simply not possible?</p>
<p>So far I have looked up the documentation and did not find a way to pass the run id to a MLFlow log function, neither for parameters, nor metrics or anything else.</p>
|
[
{
"answer_id": 74603861,
"author": "Karen Baghdasaryan",
"author_id": 15262489,
"author_profile": "https://Stackoverflow.com/users/15262489",
"pm_score": 0,
"selected": false,
"text": "T bar const int& T int"
},
{
"answer_id": 74603981,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 3,
"selected": true,
"text": "foo foo void(*)(const int&) foo void(const int&) void(*)(const int&) void(const T&) void(*)(const T&) void(*)(const int&)\n void(*)(const T&)\n T T int T = int"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16766083/"
] |
74,603,020
|
<p>I have a list:</p>
<pre><code>list = [['X', 'Y'], 'A', 1, 2, 3]
</code></pre>
<p>That I want to split into:</p>
<pre><code>new_list = [['X','A', 1, 2, 3] , ['Y', 'A', 1, 2, 3]]
</code></pre>
<p>Is this possible?</p>
|
[
{
"answer_id": 74603150,
"author": "ShadowCrafter_01",
"author_id": 15174310,
"author_profile": "https://Stackoverflow.com/users/15174310",
"pm_score": 0,
"selected": false,
"text": "l = [['X', 'Y'], 'A', 1, 2, 3]\n\nnew_list = []\nto_append = []\nfor item in l:\n if isinstance(item, list):\n new_list.append(item)\n continue\n\n to_append.append(item)\n\nnew_list.append(to_append)\nprint(new_list)\n"
},
{
"answer_id": 74603153,
"author": "C.Nivs",
"author_id": 7867968,
"author_profile": "https://Stackoverflow.com/users/7867968",
"pm_score": 2,
"selected": false,
"text": "lst = [['X', 'Y'], 'A', 1, 2, 3]\n\nnew_list = []\n\nfor item in lst[0]:\n sub = [item]\n for sub_item in lst[1:]:\n sub.append(sub_item)\n new_list.append(sub)\n new_list = [[item, *lst[1:]] for item in lst[0]]\n *lst[1:] new_list = []\n\nfor item in lst[0]:\n sub = [item, *lst[1:]]\n new_list.append(sub)\n"
},
{
"answer_id": 74603171,
"author": "Danna",
"author_id": 19595981,
"author_profile": "https://Stackoverflow.com/users/19595981",
"pm_score": 0,
"selected": false,
"text": "list = [['X', 'Y'], 'A', 1, 2, 3]\nnew_list = []\n\nfor i, item in enumerate(list[0]):\n new_list.append([item] + list[1:])\n\nprint(new_list)\n"
},
{
"answer_id": 74603215,
"author": "BrokenBenchmark",
"author_id": 17769815,
"author_profile": "https://Stackoverflow.com/users/17769815",
"pm_score": 3,
"selected": true,
"text": "lst lst lst = [['X', 'Y'], 'A', 1, 2, 3]\nfst, *rest = lst\n\n[[elem, *rest] for elem in fst]\n [['X', 'A', 1, 2, 3], ['Y', 'A', 1, 2, 3]]\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20471057/"
] |
74,603,066
|
<p>i kinda new in react native. i want to make function that show cards with just feeding them list. for testing, i use usestate.it meant to be json. but somehow i cant access the property on the object.</p>
<pre class="lang-js prettyprint-override"><code> const [data,setData]= useState([
{ob1:[ {key:'1b',value:true,text:'data'},
{key:'2b',value:true,text:'data'},
{key:'3b',value:true,text:'data'},
{key:'4b',value:true,text:'data'},
]},
{ob3:[ {key:'1b',value:true,text:'data'},
{key:'2b',value:true,text:'data'},
{key:'3b',value:true,text:'data'},
{key:'4b',value:true,text:'data'},
]}
])
const Show =()=>{
return(
<View style={{flex:1, flexDirection:'row'}}>
{Object.entries(data).map(([key,value])=>(
<Grid_ver color={'yellow'}>
<Grid_hor id={value.ob1.key} color={'yellow'}>
//some <Text>
</Grid_hor>
</Grid_ver>
))}
</View>
)
}
</code></pre>
<p>on the function Show(), Object.entries(data) just doing fine. but i cant access value to use in <Grid_hor>.
somehow i got snipset like this.</p>
<pre class="lang-js prettyprint-override"><code>const data: ({
ob1: {
key: string;
value: boolean;
text: string;
}[];
ob3?: undefined;
} | {
ob3: {
key: string;
value: boolean;
text: string;
}[];
ob1?: undefined;
})[]
</code></pre>
<p>i tried Object.entries(data.ob1), Object.entries(data[0]), but still cant access the property.</p>
<p>i really glad if anyone give me some tips. hehe... thanks...</p>
|
[
{
"answer_id": 74603150,
"author": "ShadowCrafter_01",
"author_id": 15174310,
"author_profile": "https://Stackoverflow.com/users/15174310",
"pm_score": 0,
"selected": false,
"text": "l = [['X', 'Y'], 'A', 1, 2, 3]\n\nnew_list = []\nto_append = []\nfor item in l:\n if isinstance(item, list):\n new_list.append(item)\n continue\n\n to_append.append(item)\n\nnew_list.append(to_append)\nprint(new_list)\n"
},
{
"answer_id": 74603153,
"author": "C.Nivs",
"author_id": 7867968,
"author_profile": "https://Stackoverflow.com/users/7867968",
"pm_score": 2,
"selected": false,
"text": "lst = [['X', 'Y'], 'A', 1, 2, 3]\n\nnew_list = []\n\nfor item in lst[0]:\n sub = [item]\n for sub_item in lst[1:]:\n sub.append(sub_item)\n new_list.append(sub)\n new_list = [[item, *lst[1:]] for item in lst[0]]\n *lst[1:] new_list = []\n\nfor item in lst[0]:\n sub = [item, *lst[1:]]\n new_list.append(sub)\n"
},
{
"answer_id": 74603171,
"author": "Danna",
"author_id": 19595981,
"author_profile": "https://Stackoverflow.com/users/19595981",
"pm_score": 0,
"selected": false,
"text": "list = [['X', 'Y'], 'A', 1, 2, 3]\nnew_list = []\n\nfor i, item in enumerate(list[0]):\n new_list.append([item] + list[1:])\n\nprint(new_list)\n"
},
{
"answer_id": 74603215,
"author": "BrokenBenchmark",
"author_id": 17769815,
"author_profile": "https://Stackoverflow.com/users/17769815",
"pm_score": 3,
"selected": true,
"text": "lst lst lst = [['X', 'Y'], 'A', 1, 2, 3]\nfst, *rest = lst\n\n[[elem, *rest] for elem in fst]\n [['X', 'A', 1, 2, 3], ['Y', 'A', 1, 2, 3]]\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20624865/"
] |
74,603,104
|
<p>I would like to create an alias that works in zsh and bash, but weirdly enough zsh tries to pass on an unquoted variable as a single argument:</p>
<pre class="lang-bash prettyprint-override"><code>❯ zsh -f
grasshopper% LS_OPTIONS="-l -a" && ls $LS_OPTIONS
ls: invalid option -- ' '
Try 'ls --help' for more information.
grasshopper% bash --norc
bash-5.1$ LS_OPTIONS="-l -a" && ls $LS_OPTIONS
total 0
drwxr-xr-x 2 janekf janekf 40 28. Nov 14:02 .
drwxrwxrwt 24 root root 2400 28. Nov 16:41 ..
</code></pre>
<p>Is there a option to stop that?</p>
<p>See also <a href="https://stackoverflow.com/questions/54051116/using-variables-as-command-arguments-in-zsh">Using variables as command arguments in zsh</a>, but the answer there is zsh-specific.</p>
|
[
{
"answer_id": 74603396,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 3,
"selected": true,
"text": "zsh bash LS_OPTIONS=(-l -a) && ls \"${LS_OPTIONS[@]}\"\n SH_WORD_SPLIT zsh bash bash"
},
{
"answer_id": 74653305,
"author": "user1934428",
"author_id": 1934428,
"author_profile": "https://Stackoverflow.com/users/1934428",
"pm_score": 0,
"selected": false,
"text": "ls ls alias ls='ls ${(z)LS_OPTIONS}'\n ls"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6723250/"
] |
74,603,142
|
<pre><code>function Getir() {
var options =
{
host: 'example',
port: 443,
path: '/myUrl'
};
get(options, function (http_res) {
var data = "";
http_res.on("data", function (chunk) {
data += chunk;
});
http_res.on("end", function () {
writeFile('NewHtml.txt', `${data}`, 'utf8', (err) => {
if (err) console.log(err);
});
});
});
}
function DegistirDuzenle() {
if (existsSync("./DatabaseHtml.txt")) {
var DataBaseHtml = readFileSync("./DatabaseHtml.txt", 'utf-8', (err) => { if (err) console.log(err) });
var MyHtml = readFileSync("./NewHtml.txt", 'utf-8', (err) => {if (err) console.log(err) });
if (MyHtml == DataBaseHtml) {
unlink("./NewHtml.txt", (err)=>{ if(err) console.log(err)});
console.log("değişiklik yapılmadı");
} else {
//notification
console.log("değişiklik yapıldı");
//Change
unlink('./DatabaseHtml.txt', (err) => { if(err) console.log(err); });
writeFile('./DatabaseHtml.txt', `${MyHtml}`, 'utf-8', (err) => { if(err) console.log(err); });
unlink('./NewHtml.txt', (err) => { if(err) console.log(err); });
}
}
else {
writeFile('DatabaseHtml.txt', `NewDataBaseHtml`, 'utf8', (err) => {
if (err) console.log(err);
});
}
}
async function Mysystem() {
let mypromis = new Promise((resolve, reject)=>{
resolve(Getir());
});
await mypromis.then(DegistirDuzenle());
}
Mysystem();
</code></pre>
<p>I want to create a txt file, read it and delete it later. I have 2 function 1.(Getir()) Create txt, 2.(DegistirDuzenle()) read txt and delete but 2. function starts working first and I getting error. "Error: ENOENT: no such file or directory, open './NewHtml.txt'"</p>
|
[
{
"answer_id": 74603396,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 3,
"selected": true,
"text": "zsh bash LS_OPTIONS=(-l -a) && ls \"${LS_OPTIONS[@]}\"\n SH_WORD_SPLIT zsh bash bash"
},
{
"answer_id": 74653305,
"author": "user1934428",
"author_id": 1934428,
"author_profile": "https://Stackoverflow.com/users/1934428",
"pm_score": 0,
"selected": false,
"text": "ls ls alias ls='ls ${(z)LS_OPTIONS}'\n ls"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20426159/"
] |
74,603,143
|
<p>I am trying to write a function that calls another function multiple times in its body. I am hoping to control the number of such function calls and their respective target by using an argument, but this becomes tricky due to the structure of pipelines. Imagine this simple example of mutating columns. I am fully aware that this is not the greatest example as you wouldn't call mutate multiple times for different targets, but bear with me. This is just a standin example, so it is important that each mutate call corresponds to a string supplied via the <code>cols</code> argument.</p>
<pre class="lang-r prettyprint-override"><code>library(dplyr)
scale_cols <- function(data, cols = c("mpg", "cyl")) {
processed_data <- data |>
mutate("mpg" = scale(mpg)) |>
mutate("cyl" = scale(cyl))
return(processed_data)
}
scale_cols(mtcars)
#> mpg cyl disp hp drat wt qsec vs am
#> Mazda RX4 0.15088482 -0.1049878 160.0 110 3.90 2.620 16.46 0 1
#> Mazda RX4 Wag 0.15088482 -0.1049878 160.0 110 3.90 2.875 17.02 0 1
#> Datsun 710 0.44954345 -1.2248578 108.0 93 3.85 2.320 18.61 1 1
#> Hornet 4 Drive 0.21725341 -0.1049878 258.0 110 3.08 3.215 19.44 1 0
#> Hornet Sportabout -0.23073453 1.0148821 360.0 175 3.15 3.440 17.02 0 0
#> Valiant -0.33028740 -0.1049878 225.0 105 2.76 3.460 20.22 1 0
#> Duster 360 -0.96078893 1.0148821 360.0 245 3.21 3.570 15.84 0 0
#> Merc 240D 0.71501778 -1.2248578 146.7 62 3.69 3.190 20.00 1 0
#> Merc 230 0.44954345 -1.2248578 140.8 95 3.92 3.150 22.90 1 0
</code></pre>
<p><sup>Created on 2022-11-28 with <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex v2.0.2</a></sup></p>
<p>Currently which columns are to be transformed is hardcoded, but I would prefer being able to choose the columnsfor transformation by using the <code>cols</code> argument. Is it possible to map or apply the mutate function over the <code>cols</code> elements so that in the end a fully functional pipeline is created? Thank you for your time.</p>
|
[
{
"answer_id": 74603306,
"author": "Limey",
"author_id": 13434871,
"author_profile": "https://Stackoverflow.com/users/13434871",
"pm_score": 1,
"selected": false,
"text": "across scale_cols <- function(data, cols) {\n for (c in cols) {\n data <- data %>% mutate({{c}} := scale({{c}}))\n }\n data\n}\n\nmtcars %>% scale_cols(vars(mpg, cyl))\n mpg cyl disp hp drat wt qsec vs am gear carb\nMazda RX4 0.15088482 -0.1049878 160.0 110 3.90 2.620 16.46 0 1 4 4\nMazda RX4 Wag 0.15088482 -0.1049878 160.0 110 3.90 2.875 17.02 0 1 4 4\nDatsun 710 0.44954345 -1.2248578 108.0 93 3.85 2.320 18.61 1 1 4 1\nHornet 4 Drive 0.21725341 -0.1049878 258.0 110 3.08 3.215 19.44 1 0 3 1\nHornet Sportabout -0.23073453 1.0148821 360.0 175 3.15 3.440 17.02 0 0 3 2\nValiant -0.33028740 -0.1049878 225.0 105 2.76 3.460 20.22 1 0 3 1\n<output truncated for brevity>\n"
},
{
"answer_id": 74603484,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "mutate Reduce cols scale_cols <- function(data, cols = c(\"mpg\", \"cyl\")) {\n \n Reduce(function(x, y) { \n x[[y]] <- scale(x[[y]]) \n return(x)\n }, x = cols, init = data)\n}\n scale_cols(mtcars)\n#> mpg cyl disp hp drat wt qsec vs am\n#> Mazda RX4 0.15088482 -0.1049878 160.0 110 3.90 2.620 16.46 0 1\n#> Mazda RX4 Wag 0.15088482 -0.1049878 160.0 110 3.90 2.875 17.02 0 1\n#> Datsun 710 0.44954345 -1.2248578 108.0 93 3.85 2.320 18.61 1 1\n#> Hornet 4 Drive 0.21725341 -0.1049878 258.0 110 3.08 3.215 19.44 1 0\n#> Hornet Sportabout -0.23073453 1.0148821 360.0 175 3.15 3.440 17.02 0 0\n#> Valiant -0.33028740 -0.1049878 225.0 105 2.76 3.460 20.22 1 0\n#> Duster 360 -0.96078893 1.0148821 360.0 245 3.21 3.570 15.84 0 0\n#> Merc 240D 0.71501778 -1.2248578 146.7 62 3.69 3.190 20.00 1 0\n#> Merc 230 0.44954345 -1.2248578 140.8 95 3.92 3.150 22.90 1 0\n#> Merc 280 -0.14777380 -0.1049878 167.6 123 3.92 3.440 18.30 1 0\n#> Merc 280C -0.38006384 -0.1049878 167.6 123 3.92 3.440 18.90 1 0\n#> Merc 450SE -0.61235388 1.0148821 275.8 180 3.07 4.070 17.40 0 0\n#> Merc 450SL -0.46302456 1.0148821 275.8 180 3.07 3.730 17.60 0 0\n#> Merc 450SLC -0.81145962 1.0148821 275.8 180 3.07 3.780 18.00 0 0\n#> Cadillac Fleetwood -1.60788262 1.0148821 472.0 205 2.93 5.250 17.98 0 0\n#> Lincoln Continental -1.60788262 1.0148821 460.0 215 3.00 5.424 17.82 0 0\n#> Chrysler Imperial -0.89442035 1.0148821 440.0 230 3.23 5.345 17.42 0 0\n#> Fiat 128 2.04238943 -1.2248578 78.7 66 4.08 2.200 19.47 1 1\n#> Honda Civic 1.71054652 -1.2248578 75.7 52 4.93 1.615 18.52 1 1\n#> Toyota Corolla 2.29127162 -1.2248578 71.1 65 4.22 1.835 19.90 1 1\n#> Toyota Corona 0.23384555 -1.2248578 120.1 97 3.70 2.465 20.01 1 0\n#> Dodge Challenger -0.76168319 1.0148821 318.0 150 2.76 3.520 16.87 0 0\n#> AMC Javelin -0.81145962 1.0148821 304.0 150 3.15 3.435 17.30 0 0\n#> Camaro Z28 -1.12671039 1.0148821 350.0 245 3.73 3.840 15.41 0 0\n#> Pontiac Firebird -0.14777380 1.0148821 400.0 175 3.08 3.845 17.05 0 0\n#> Fiat X1-9 1.19619000 -1.2248578 79.0 66 4.08 1.935 18.90 1 1\n#> Porsche 914-2 0.98049211 -1.2248578 120.3 91 4.43 2.140 16.70 0 1\n#> Lotus Europa 1.71054652 -1.2248578 95.1 113 3.77 1.513 16.90 1 1\n#> Ford Pantera L -0.71190675 1.0148821 351.0 264 4.22 3.170 14.50 0 1\n#> Ferrari Dino -0.06481307 -0.1049878 145.0 175 3.62 2.770 15.50 0 1\n#> Maserati Bora -0.84464392 1.0148821 301.0 335 3.54 3.570 14.60 0 1\n#> Volvo 142E 0.21725341 -1.2248578 121.0 109 4.11 2.780 18.60 1 1\n#> gear carb\n#> Mazda RX4 4 4\n#> Mazda RX4 Wag 4 4\n#> Datsun 710 4 1\n#> Hornet 4 Drive 3 1\n#> Hornet Sportabout 3 2\n#> Valiant 3 1\n#> Duster 360 3 4\n#> Merc 240D 4 2\n#> Merc 230 4 2\n#> Merc 280 4 4\n#> Merc 280C 4 4\n#> Merc 450SE 3 3\n#> Merc 450SL 3 3\n#> Merc 450SLC 3 3\n#> Cadillac Fleetwood 3 4\n#> Lincoln Continental 3 4\n#> Chrysler Imperial 3 4\n#> Fiat 128 4 1\n#> Honda Civic 4 2\n#> Toyota Corolla 4 1\n#> Toyota Corona 3 1\n#> Dodge Challenger 3 2\n#> AMC Javelin 3 2\n#> Camaro Z28 3 4\n#> Pontiac Firebird 3 2\n#> Fiat X1-9 4 1\n#> Porsche 914-2 5 2\n#> Lotus Europa 5 2\n#> Ford Pantera L 5 4\n#> Ferrari Dino 5 6\n#> Maserati Bora 5 8\n#> Volvo 142E 4 2\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5539674/"
] |
74,603,169
|
<p>I am having a problem with the following programm.
When I try to run decorator the easier way, using @ like this</p>
<pre><code>def decorator1(fun):
def wrapper():
text = '------'
return text + '\n' + fun + '\n' + text
return wrapper()
def decorator2(fun):
def wrapper():
return fun.upper()
return wrapper()
@decorator1
@decorator2
def function():
return "Hey ya!"
print(function())
</code></pre>
<p>Following problems occurs:</p>
<pre><code>Traceback (most recent call last):
File "C:\Python_projects\main.py", line 17, in <module>
def function():
File "C:\Python_projects\main.py", line 13, in decorator2
return wrapper()
File "C:\Python_projects\main.py", line 11, in wrapper
return fun.upper()
AttributeError: 'function' object has no attribute 'upper'
</code></pre>
<p>or when I switch the order of decorators then it goes like this:</p>
<pre><code>Traceback (most recent call last):
File "C:\Python_projects\main.py", line 17, in <module>
def function():
File "C:\Python_projects\main.py", line 6, in decorator1
return wrapper()
File "C:\Python_projects\main.py", line 4, in wrapper
return text + '\n' + fun + '\n' + text
TypeError: can only concatenate str (not "function") to str
</code></pre>
<p>When I run the code in this way, then it works just fine:</p>
<pre><code>def decorator1(fun):
def wrapper():
text = '------'
return text + '\n' + fun + '\n' + text
return wrapper()
def decorator2(fun):
def wrapper():
return fun.upper()
return wrapper()
def function():
return "Hey ya!"
print(decorator(decorator2(function())))
</code></pre>
<p>But it seems like using @ with decorators is much more popular. Do you have any idea what I am doing wrong?</p>
|
[
{
"answer_id": 74603306,
"author": "Limey",
"author_id": 13434871,
"author_profile": "https://Stackoverflow.com/users/13434871",
"pm_score": 1,
"selected": false,
"text": "across scale_cols <- function(data, cols) {\n for (c in cols) {\n data <- data %>% mutate({{c}} := scale({{c}}))\n }\n data\n}\n\nmtcars %>% scale_cols(vars(mpg, cyl))\n mpg cyl disp hp drat wt qsec vs am gear carb\nMazda RX4 0.15088482 -0.1049878 160.0 110 3.90 2.620 16.46 0 1 4 4\nMazda RX4 Wag 0.15088482 -0.1049878 160.0 110 3.90 2.875 17.02 0 1 4 4\nDatsun 710 0.44954345 -1.2248578 108.0 93 3.85 2.320 18.61 1 1 4 1\nHornet 4 Drive 0.21725341 -0.1049878 258.0 110 3.08 3.215 19.44 1 0 3 1\nHornet Sportabout -0.23073453 1.0148821 360.0 175 3.15 3.440 17.02 0 0 3 2\nValiant -0.33028740 -0.1049878 225.0 105 2.76 3.460 20.22 1 0 3 1\n<output truncated for brevity>\n"
},
{
"answer_id": 74603484,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "mutate Reduce cols scale_cols <- function(data, cols = c(\"mpg\", \"cyl\")) {\n \n Reduce(function(x, y) { \n x[[y]] <- scale(x[[y]]) \n return(x)\n }, x = cols, init = data)\n}\n scale_cols(mtcars)\n#> mpg cyl disp hp drat wt qsec vs am\n#> Mazda RX4 0.15088482 -0.1049878 160.0 110 3.90 2.620 16.46 0 1\n#> Mazda RX4 Wag 0.15088482 -0.1049878 160.0 110 3.90 2.875 17.02 0 1\n#> Datsun 710 0.44954345 -1.2248578 108.0 93 3.85 2.320 18.61 1 1\n#> Hornet 4 Drive 0.21725341 -0.1049878 258.0 110 3.08 3.215 19.44 1 0\n#> Hornet Sportabout -0.23073453 1.0148821 360.0 175 3.15 3.440 17.02 0 0\n#> Valiant -0.33028740 -0.1049878 225.0 105 2.76 3.460 20.22 1 0\n#> Duster 360 -0.96078893 1.0148821 360.0 245 3.21 3.570 15.84 0 0\n#> Merc 240D 0.71501778 -1.2248578 146.7 62 3.69 3.190 20.00 1 0\n#> Merc 230 0.44954345 -1.2248578 140.8 95 3.92 3.150 22.90 1 0\n#> Merc 280 -0.14777380 -0.1049878 167.6 123 3.92 3.440 18.30 1 0\n#> Merc 280C -0.38006384 -0.1049878 167.6 123 3.92 3.440 18.90 1 0\n#> Merc 450SE -0.61235388 1.0148821 275.8 180 3.07 4.070 17.40 0 0\n#> Merc 450SL -0.46302456 1.0148821 275.8 180 3.07 3.730 17.60 0 0\n#> Merc 450SLC -0.81145962 1.0148821 275.8 180 3.07 3.780 18.00 0 0\n#> Cadillac Fleetwood -1.60788262 1.0148821 472.0 205 2.93 5.250 17.98 0 0\n#> Lincoln Continental -1.60788262 1.0148821 460.0 215 3.00 5.424 17.82 0 0\n#> Chrysler Imperial -0.89442035 1.0148821 440.0 230 3.23 5.345 17.42 0 0\n#> Fiat 128 2.04238943 -1.2248578 78.7 66 4.08 2.200 19.47 1 1\n#> Honda Civic 1.71054652 -1.2248578 75.7 52 4.93 1.615 18.52 1 1\n#> Toyota Corolla 2.29127162 -1.2248578 71.1 65 4.22 1.835 19.90 1 1\n#> Toyota Corona 0.23384555 -1.2248578 120.1 97 3.70 2.465 20.01 1 0\n#> Dodge Challenger -0.76168319 1.0148821 318.0 150 2.76 3.520 16.87 0 0\n#> AMC Javelin -0.81145962 1.0148821 304.0 150 3.15 3.435 17.30 0 0\n#> Camaro Z28 -1.12671039 1.0148821 350.0 245 3.73 3.840 15.41 0 0\n#> Pontiac Firebird -0.14777380 1.0148821 400.0 175 3.08 3.845 17.05 0 0\n#> Fiat X1-9 1.19619000 -1.2248578 79.0 66 4.08 1.935 18.90 1 1\n#> Porsche 914-2 0.98049211 -1.2248578 120.3 91 4.43 2.140 16.70 0 1\n#> Lotus Europa 1.71054652 -1.2248578 95.1 113 3.77 1.513 16.90 1 1\n#> Ford Pantera L -0.71190675 1.0148821 351.0 264 4.22 3.170 14.50 0 1\n#> Ferrari Dino -0.06481307 -0.1049878 145.0 175 3.62 2.770 15.50 0 1\n#> Maserati Bora -0.84464392 1.0148821 301.0 335 3.54 3.570 14.60 0 1\n#> Volvo 142E 0.21725341 -1.2248578 121.0 109 4.11 2.780 18.60 1 1\n#> gear carb\n#> Mazda RX4 4 4\n#> Mazda RX4 Wag 4 4\n#> Datsun 710 4 1\n#> Hornet 4 Drive 3 1\n#> Hornet Sportabout 3 2\n#> Valiant 3 1\n#> Duster 360 3 4\n#> Merc 240D 4 2\n#> Merc 230 4 2\n#> Merc 280 4 4\n#> Merc 280C 4 4\n#> Merc 450SE 3 3\n#> Merc 450SL 3 3\n#> Merc 450SLC 3 3\n#> Cadillac Fleetwood 3 4\n#> Lincoln Continental 3 4\n#> Chrysler Imperial 3 4\n#> Fiat 128 4 1\n#> Honda Civic 4 2\n#> Toyota Corolla 4 1\n#> Toyota Corona 3 1\n#> Dodge Challenger 3 2\n#> AMC Javelin 3 2\n#> Camaro Z28 3 4\n#> Pontiac Firebird 3 2\n#> Fiat X1-9 4 1\n#> Porsche 914-2 5 2\n#> Lotus Europa 5 2\n#> Ford Pantera L 5 4\n#> Ferrari Dino 5 6\n#> Maserati Bora 5 8\n#> Volvo 142E 4 2\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6758526/"
] |
74,603,216
|
<p>So I have this text:</p>
<p><a href="https://i.stack.imgur.com/6vyAE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6vyAE.jpg" alt="enter image description here" /></a></p>
<p>Using JavaScript, I am trying to develop a regex that matches the first 4 sentences, including any newline characters.</p>
<p>The closest I got to is <code>/([0-9])+.*/gm</code> but it's incomplete; It ignores the 2nd part of the sentence starting with "4." because of the <code>\n</code> character between the words <code>completed</code> and <code>tasks</code>. It only matches the part in blue on the screenshot.</p>
<p>Any ideas on how to include:</p>
<blockquote>
<p>"tasks and the last task that was submitted."</p>
</blockquote>
<p>in the match?</p>
<hr />
<p><em><strong>Edit 1:</strong> Here's the text in the screenshot:</em></p>
<ol>
<li><p>It creates a directory for the log file if it doesn't exist.</p>
</li>
<li><p>It checks that the log file is newline-terminated.</p>
</li>
<li><p>It writes a newline-terminated JSON object to the log file.</p>
</li>
<li><p>It reads the log file and returns a dictionary with the set of completed</p>
<p>tasks and the last task that was submitted.</p>
</li>
</ol>
<p>Using <code>/^\d+\.[\w\W]*?(?=\n\n|\n\d+\.)/gm</code> as suggested in the 1st comment by @Wiktor Stribizew, works. However using this sample text, it doesn't (it's skipping the last line):</p>
<ol>
<li>The extension is activated the very first time the command is executed</li>
<li>The command handler parses the user's selection and calls the explain function</li>
<li>The explain function returns a promise that resolves to the explanation</li>
<li>The command handler displays the explanation in a message box</li>
</ol>
<p><a href="https://i.stack.imgur.com/IWGHR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IWGHR.jpg" alt="enter image description here" /></a></p>
<hr />
<p><em><strong>Edit 2:</strong> To clarify, the regex needs to match any number of sentences starting with a number and a period and ending with a period. Sometimes it could be 4, and sometimes it could anything up to 20.</em></p>
<hr />
|
[
{
"answer_id": 74603306,
"author": "Limey",
"author_id": 13434871,
"author_profile": "https://Stackoverflow.com/users/13434871",
"pm_score": 1,
"selected": false,
"text": "across scale_cols <- function(data, cols) {\n for (c in cols) {\n data <- data %>% mutate({{c}} := scale({{c}}))\n }\n data\n}\n\nmtcars %>% scale_cols(vars(mpg, cyl))\n mpg cyl disp hp drat wt qsec vs am gear carb\nMazda RX4 0.15088482 -0.1049878 160.0 110 3.90 2.620 16.46 0 1 4 4\nMazda RX4 Wag 0.15088482 -0.1049878 160.0 110 3.90 2.875 17.02 0 1 4 4\nDatsun 710 0.44954345 -1.2248578 108.0 93 3.85 2.320 18.61 1 1 4 1\nHornet 4 Drive 0.21725341 -0.1049878 258.0 110 3.08 3.215 19.44 1 0 3 1\nHornet Sportabout -0.23073453 1.0148821 360.0 175 3.15 3.440 17.02 0 0 3 2\nValiant -0.33028740 -0.1049878 225.0 105 2.76 3.460 20.22 1 0 3 1\n<output truncated for brevity>\n"
},
{
"answer_id": 74603484,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "mutate Reduce cols scale_cols <- function(data, cols = c(\"mpg\", \"cyl\")) {\n \n Reduce(function(x, y) { \n x[[y]] <- scale(x[[y]]) \n return(x)\n }, x = cols, init = data)\n}\n scale_cols(mtcars)\n#> mpg cyl disp hp drat wt qsec vs am\n#> Mazda RX4 0.15088482 -0.1049878 160.0 110 3.90 2.620 16.46 0 1\n#> Mazda RX4 Wag 0.15088482 -0.1049878 160.0 110 3.90 2.875 17.02 0 1\n#> Datsun 710 0.44954345 -1.2248578 108.0 93 3.85 2.320 18.61 1 1\n#> Hornet 4 Drive 0.21725341 -0.1049878 258.0 110 3.08 3.215 19.44 1 0\n#> Hornet Sportabout -0.23073453 1.0148821 360.0 175 3.15 3.440 17.02 0 0\n#> Valiant -0.33028740 -0.1049878 225.0 105 2.76 3.460 20.22 1 0\n#> Duster 360 -0.96078893 1.0148821 360.0 245 3.21 3.570 15.84 0 0\n#> Merc 240D 0.71501778 -1.2248578 146.7 62 3.69 3.190 20.00 1 0\n#> Merc 230 0.44954345 -1.2248578 140.8 95 3.92 3.150 22.90 1 0\n#> Merc 280 -0.14777380 -0.1049878 167.6 123 3.92 3.440 18.30 1 0\n#> Merc 280C -0.38006384 -0.1049878 167.6 123 3.92 3.440 18.90 1 0\n#> Merc 450SE -0.61235388 1.0148821 275.8 180 3.07 4.070 17.40 0 0\n#> Merc 450SL -0.46302456 1.0148821 275.8 180 3.07 3.730 17.60 0 0\n#> Merc 450SLC -0.81145962 1.0148821 275.8 180 3.07 3.780 18.00 0 0\n#> Cadillac Fleetwood -1.60788262 1.0148821 472.0 205 2.93 5.250 17.98 0 0\n#> Lincoln Continental -1.60788262 1.0148821 460.0 215 3.00 5.424 17.82 0 0\n#> Chrysler Imperial -0.89442035 1.0148821 440.0 230 3.23 5.345 17.42 0 0\n#> Fiat 128 2.04238943 -1.2248578 78.7 66 4.08 2.200 19.47 1 1\n#> Honda Civic 1.71054652 -1.2248578 75.7 52 4.93 1.615 18.52 1 1\n#> Toyota Corolla 2.29127162 -1.2248578 71.1 65 4.22 1.835 19.90 1 1\n#> Toyota Corona 0.23384555 -1.2248578 120.1 97 3.70 2.465 20.01 1 0\n#> Dodge Challenger -0.76168319 1.0148821 318.0 150 2.76 3.520 16.87 0 0\n#> AMC Javelin -0.81145962 1.0148821 304.0 150 3.15 3.435 17.30 0 0\n#> Camaro Z28 -1.12671039 1.0148821 350.0 245 3.73 3.840 15.41 0 0\n#> Pontiac Firebird -0.14777380 1.0148821 400.0 175 3.08 3.845 17.05 0 0\n#> Fiat X1-9 1.19619000 -1.2248578 79.0 66 4.08 1.935 18.90 1 1\n#> Porsche 914-2 0.98049211 -1.2248578 120.3 91 4.43 2.140 16.70 0 1\n#> Lotus Europa 1.71054652 -1.2248578 95.1 113 3.77 1.513 16.90 1 1\n#> Ford Pantera L -0.71190675 1.0148821 351.0 264 4.22 3.170 14.50 0 1\n#> Ferrari Dino -0.06481307 -0.1049878 145.0 175 3.62 2.770 15.50 0 1\n#> Maserati Bora -0.84464392 1.0148821 301.0 335 3.54 3.570 14.60 0 1\n#> Volvo 142E 0.21725341 -1.2248578 121.0 109 4.11 2.780 18.60 1 1\n#> gear carb\n#> Mazda RX4 4 4\n#> Mazda RX4 Wag 4 4\n#> Datsun 710 4 1\n#> Hornet 4 Drive 3 1\n#> Hornet Sportabout 3 2\n#> Valiant 3 1\n#> Duster 360 3 4\n#> Merc 240D 4 2\n#> Merc 230 4 2\n#> Merc 280 4 4\n#> Merc 280C 4 4\n#> Merc 450SE 3 3\n#> Merc 450SL 3 3\n#> Merc 450SLC 3 3\n#> Cadillac Fleetwood 3 4\n#> Lincoln Continental 3 4\n#> Chrysler Imperial 3 4\n#> Fiat 128 4 1\n#> Honda Civic 4 2\n#> Toyota Corolla 4 1\n#> Toyota Corona 3 1\n#> Dodge Challenger 3 2\n#> AMC Javelin 3 2\n#> Camaro Z28 3 4\n#> Pontiac Firebird 3 2\n#> Fiat X1-9 4 1\n#> Porsche 914-2 5 2\n#> Lotus Europa 5 2\n#> Ford Pantera L 5 4\n#> Ferrari Dino 5 6\n#> Maserati Bora 5 8\n#> Volvo 142E 4 2\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3485759/"
] |
74,603,276
|
<p>I'm trying to write a small gpx file conversion script. The conversion part is done but I can't fix the naming of the converted file. I want the filename of the converted file like this:</p>
<pre><code>originalfilename.2.gpx
</code></pre>
<p>This is the code I have so far:</p>
<pre><code>-- begin script
-- For converting from one format to another. Preset to convert from GPX to KML. Tailor as needed. Read the documentation for your version
--Based on the script by Robert Nixon, http://www.gpsbabel.org/os/OSX_oneclick.html
-- This is set up for gpsbabel installed using DarwinPorts. See <http://www.gpsbabel.org/osnotes.html> for details
-- This script is not being actively supported, but you may get some help from the gpsbabel discussion group: <http://www.gpsbabel.org/lists.html>
--start script
-- HINT a '~/' is your home folder and of course the double hyphen is a comment. Remove to make active.
-- setting path for gpsbabel. Reset as needed
--set gpsBabelLocation to "/opt/local/var/db/dports/software/gpsbabel/1.2.7_0/opt/local/bin/" -- DarwinPorts Default for Tiger, Feb. 2006
set gpsBabelLocation to "/Applications/GPSBabelFE.app/Contents/MacOS/" -- Normal MacGPSBabel location
--set gpsBabelLocation to ""
set inputTYPE to "gpx" -- set the input file type to whatever you want
set outputTYPE to "gpx" --set the output file type to whatever you want
set strPath to POSIX file "/Users/someusername/downloads/" --set the default path for file input dialog
--set inputPATH to "~/Desktop/route.gpx" --set the path to where your input file is
-- comment out the following line if you want to use the line above
set inputPATHalias to (choose file with prompt "Select a GPX file to convert to " & outputTYPE & ":" default location strPath)
-- set inputPATH to quoted form of POSIX path of inputPATHalias -- got error, but two step below works.
set inputfilename to (inputPATHalias as text)
set inputPATH to POSIX path of inputPATHalias
set inputPATH to quoted form of inputPATH -- needed to pass to shell script
--set outputPATH to "~/Desktop/yournewfile.wpt" --set the path to where your output file will be
set outputFileName to "converted." & inputTYPE & ".2." & outputTYPE
--set outputFileName to outputFileName & ".2." & outputTYPE
set outputFolderalias to choose folder with prompt "Select a folder for converted file:"
set outputPATH to fileCheckName(outputFolderalias, outputFileName)
-- See the Documentation for normal usage. http://www.gpsbabel.org/readme.html#d0e1388
-- Using the Position filter to correct a Garmin error. When the Garmin loses sight of the sattiletes, when it reconects, it puts in poitns with a lat-long equal to the last good point, but current time and elevation (mine has a barometer). Garmin: remove extraneous points recorded when out of range that have same lat and long as last good point (altitude is ignored in this filter).
set filterSetting to "" -- use this one if you don't want any Position filtering. You can leave in uncommented and any below will override it.
-- set filterSetting to " -x position " -- Default, distance=0
-- set filterSetting to " -x position,distance=1f " -- 1 foot and leave one
-- set filterSetting to " -x position,distance=1m " -- 1 meter and leave one
-- set filterSetting to " -x position,all" -- remove all duplicates
-- set filterSetting to " -x simplify,count=1000"
-- set filterSetting to " -x simplify,error=1k" -- doesnt' work, but then it's not in the manual
-- set filterSetting to ""
tell application "System Events"
activate
do shell script gpsBabelLocation & "gpsbabel " & filterSetting & "-i " & inputTYPE & " -f " & inputPATH & " -x transform,trk=rte " & " -o " & outputTYPE & " -F " & outputPATH
end tell
--Handlers. Only used once, but I've used them elsewhere
on fileCheckName(outputFolderalias, outputFileName)
set outputFolder to POSIX path of outputFolderalias
set outputPATHnoQuote to outputFolder & "/" & outputFileName -- may need to change this if the extension isn't the same as the outputType, The Desktop is a common location
set outputPATH to quoted form of outputPATHnoQuote -- needed to pass to shell script
--check if file already exist and if we want to overwrite it
set outputFolderaliasText to outputFolderalias as text
set outputPATHcolon to outputFolderaliasText & outputFileName
tell application "Finder" -- trying to get handler to work
if file outputPATHcolon exists then display dialog "The file " & outputFileName & " already exists. Do you want to overwrite it?"
end tell
return outputPATH
end fileCheckName
--end script
</code></pre>
<p>I'm unable to find Applescript code that translates the filename from a prompt into a variable.</p>
|
[
{
"answer_id": 74603306,
"author": "Limey",
"author_id": 13434871,
"author_profile": "https://Stackoverflow.com/users/13434871",
"pm_score": 1,
"selected": false,
"text": "across scale_cols <- function(data, cols) {\n for (c in cols) {\n data <- data %>% mutate({{c}} := scale({{c}}))\n }\n data\n}\n\nmtcars %>% scale_cols(vars(mpg, cyl))\n mpg cyl disp hp drat wt qsec vs am gear carb\nMazda RX4 0.15088482 -0.1049878 160.0 110 3.90 2.620 16.46 0 1 4 4\nMazda RX4 Wag 0.15088482 -0.1049878 160.0 110 3.90 2.875 17.02 0 1 4 4\nDatsun 710 0.44954345 -1.2248578 108.0 93 3.85 2.320 18.61 1 1 4 1\nHornet 4 Drive 0.21725341 -0.1049878 258.0 110 3.08 3.215 19.44 1 0 3 1\nHornet Sportabout -0.23073453 1.0148821 360.0 175 3.15 3.440 17.02 0 0 3 2\nValiant -0.33028740 -0.1049878 225.0 105 2.76 3.460 20.22 1 0 3 1\n<output truncated for brevity>\n"
},
{
"answer_id": 74603484,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "mutate Reduce cols scale_cols <- function(data, cols = c(\"mpg\", \"cyl\")) {\n \n Reduce(function(x, y) { \n x[[y]] <- scale(x[[y]]) \n return(x)\n }, x = cols, init = data)\n}\n scale_cols(mtcars)\n#> mpg cyl disp hp drat wt qsec vs am\n#> Mazda RX4 0.15088482 -0.1049878 160.0 110 3.90 2.620 16.46 0 1\n#> Mazda RX4 Wag 0.15088482 -0.1049878 160.0 110 3.90 2.875 17.02 0 1\n#> Datsun 710 0.44954345 -1.2248578 108.0 93 3.85 2.320 18.61 1 1\n#> Hornet 4 Drive 0.21725341 -0.1049878 258.0 110 3.08 3.215 19.44 1 0\n#> Hornet Sportabout -0.23073453 1.0148821 360.0 175 3.15 3.440 17.02 0 0\n#> Valiant -0.33028740 -0.1049878 225.0 105 2.76 3.460 20.22 1 0\n#> Duster 360 -0.96078893 1.0148821 360.0 245 3.21 3.570 15.84 0 0\n#> Merc 240D 0.71501778 -1.2248578 146.7 62 3.69 3.190 20.00 1 0\n#> Merc 230 0.44954345 -1.2248578 140.8 95 3.92 3.150 22.90 1 0\n#> Merc 280 -0.14777380 -0.1049878 167.6 123 3.92 3.440 18.30 1 0\n#> Merc 280C -0.38006384 -0.1049878 167.6 123 3.92 3.440 18.90 1 0\n#> Merc 450SE -0.61235388 1.0148821 275.8 180 3.07 4.070 17.40 0 0\n#> Merc 450SL -0.46302456 1.0148821 275.8 180 3.07 3.730 17.60 0 0\n#> Merc 450SLC -0.81145962 1.0148821 275.8 180 3.07 3.780 18.00 0 0\n#> Cadillac Fleetwood -1.60788262 1.0148821 472.0 205 2.93 5.250 17.98 0 0\n#> Lincoln Continental -1.60788262 1.0148821 460.0 215 3.00 5.424 17.82 0 0\n#> Chrysler Imperial -0.89442035 1.0148821 440.0 230 3.23 5.345 17.42 0 0\n#> Fiat 128 2.04238943 -1.2248578 78.7 66 4.08 2.200 19.47 1 1\n#> Honda Civic 1.71054652 -1.2248578 75.7 52 4.93 1.615 18.52 1 1\n#> Toyota Corolla 2.29127162 -1.2248578 71.1 65 4.22 1.835 19.90 1 1\n#> Toyota Corona 0.23384555 -1.2248578 120.1 97 3.70 2.465 20.01 1 0\n#> Dodge Challenger -0.76168319 1.0148821 318.0 150 2.76 3.520 16.87 0 0\n#> AMC Javelin -0.81145962 1.0148821 304.0 150 3.15 3.435 17.30 0 0\n#> Camaro Z28 -1.12671039 1.0148821 350.0 245 3.73 3.840 15.41 0 0\n#> Pontiac Firebird -0.14777380 1.0148821 400.0 175 3.08 3.845 17.05 0 0\n#> Fiat X1-9 1.19619000 -1.2248578 79.0 66 4.08 1.935 18.90 1 1\n#> Porsche 914-2 0.98049211 -1.2248578 120.3 91 4.43 2.140 16.70 0 1\n#> Lotus Europa 1.71054652 -1.2248578 95.1 113 3.77 1.513 16.90 1 1\n#> Ford Pantera L -0.71190675 1.0148821 351.0 264 4.22 3.170 14.50 0 1\n#> Ferrari Dino -0.06481307 -0.1049878 145.0 175 3.62 2.770 15.50 0 1\n#> Maserati Bora -0.84464392 1.0148821 301.0 335 3.54 3.570 14.60 0 1\n#> Volvo 142E 0.21725341 -1.2248578 121.0 109 4.11 2.780 18.60 1 1\n#> gear carb\n#> Mazda RX4 4 4\n#> Mazda RX4 Wag 4 4\n#> Datsun 710 4 1\n#> Hornet 4 Drive 3 1\n#> Hornet Sportabout 3 2\n#> Valiant 3 1\n#> Duster 360 3 4\n#> Merc 240D 4 2\n#> Merc 230 4 2\n#> Merc 280 4 4\n#> Merc 280C 4 4\n#> Merc 450SE 3 3\n#> Merc 450SL 3 3\n#> Merc 450SLC 3 3\n#> Cadillac Fleetwood 3 4\n#> Lincoln Continental 3 4\n#> Chrysler Imperial 3 4\n#> Fiat 128 4 1\n#> Honda Civic 4 2\n#> Toyota Corolla 4 1\n#> Toyota Corona 3 1\n#> Dodge Challenger 3 2\n#> AMC Javelin 3 2\n#> Camaro Z28 3 4\n#> Pontiac Firebird 3 2\n#> Fiat X1-9 4 1\n#> Porsche 914-2 5 2\n#> Lotus Europa 5 2\n#> Ford Pantera L 5 4\n#> Ferrari Dino 5 6\n#> Maserati Bora 5 8\n#> Volvo 142E 4 2\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5376591/"
] |
74,603,282
|
<p>This navbar contains dropdown menus that don't work while converting from Bootstrap v5.2.2 to v5.2.3. It does not dropdown, instead staying still. Can someone explain what I am doing wrong?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<div id="page">
<header>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<div class="container-fluid">
<a class="navbar-brand" href="/">AT Products LLC</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#collapsibleNavbar" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="/">AT Products</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">Products</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="/paid">Paid Services</a></li>
<li><a class="dropdown-item" href="/flash">Flash Documentation</a></li>
<li><a class="dropdown-item" href="/sms">SMS Bomb</a></li>
<li><a class="dropdown-item" href="/mdickie">MDickie Projects</a></li>
<li><a class="dropdown-item" href="/bxpp">BxPP</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
</header>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74603306,
"author": "Limey",
"author_id": 13434871,
"author_profile": "https://Stackoverflow.com/users/13434871",
"pm_score": 1,
"selected": false,
"text": "across scale_cols <- function(data, cols) {\n for (c in cols) {\n data <- data %>% mutate({{c}} := scale({{c}}))\n }\n data\n}\n\nmtcars %>% scale_cols(vars(mpg, cyl))\n mpg cyl disp hp drat wt qsec vs am gear carb\nMazda RX4 0.15088482 -0.1049878 160.0 110 3.90 2.620 16.46 0 1 4 4\nMazda RX4 Wag 0.15088482 -0.1049878 160.0 110 3.90 2.875 17.02 0 1 4 4\nDatsun 710 0.44954345 -1.2248578 108.0 93 3.85 2.320 18.61 1 1 4 1\nHornet 4 Drive 0.21725341 -0.1049878 258.0 110 3.08 3.215 19.44 1 0 3 1\nHornet Sportabout -0.23073453 1.0148821 360.0 175 3.15 3.440 17.02 0 0 3 2\nValiant -0.33028740 -0.1049878 225.0 105 2.76 3.460 20.22 1 0 3 1\n<output truncated for brevity>\n"
},
{
"answer_id": 74603484,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "mutate Reduce cols scale_cols <- function(data, cols = c(\"mpg\", \"cyl\")) {\n \n Reduce(function(x, y) { \n x[[y]] <- scale(x[[y]]) \n return(x)\n }, x = cols, init = data)\n}\n scale_cols(mtcars)\n#> mpg cyl disp hp drat wt qsec vs am\n#> Mazda RX4 0.15088482 -0.1049878 160.0 110 3.90 2.620 16.46 0 1\n#> Mazda RX4 Wag 0.15088482 -0.1049878 160.0 110 3.90 2.875 17.02 0 1\n#> Datsun 710 0.44954345 -1.2248578 108.0 93 3.85 2.320 18.61 1 1\n#> Hornet 4 Drive 0.21725341 -0.1049878 258.0 110 3.08 3.215 19.44 1 0\n#> Hornet Sportabout -0.23073453 1.0148821 360.0 175 3.15 3.440 17.02 0 0\n#> Valiant -0.33028740 -0.1049878 225.0 105 2.76 3.460 20.22 1 0\n#> Duster 360 -0.96078893 1.0148821 360.0 245 3.21 3.570 15.84 0 0\n#> Merc 240D 0.71501778 -1.2248578 146.7 62 3.69 3.190 20.00 1 0\n#> Merc 230 0.44954345 -1.2248578 140.8 95 3.92 3.150 22.90 1 0\n#> Merc 280 -0.14777380 -0.1049878 167.6 123 3.92 3.440 18.30 1 0\n#> Merc 280C -0.38006384 -0.1049878 167.6 123 3.92 3.440 18.90 1 0\n#> Merc 450SE -0.61235388 1.0148821 275.8 180 3.07 4.070 17.40 0 0\n#> Merc 450SL -0.46302456 1.0148821 275.8 180 3.07 3.730 17.60 0 0\n#> Merc 450SLC -0.81145962 1.0148821 275.8 180 3.07 3.780 18.00 0 0\n#> Cadillac Fleetwood -1.60788262 1.0148821 472.0 205 2.93 5.250 17.98 0 0\n#> Lincoln Continental -1.60788262 1.0148821 460.0 215 3.00 5.424 17.82 0 0\n#> Chrysler Imperial -0.89442035 1.0148821 440.0 230 3.23 5.345 17.42 0 0\n#> Fiat 128 2.04238943 -1.2248578 78.7 66 4.08 2.200 19.47 1 1\n#> Honda Civic 1.71054652 -1.2248578 75.7 52 4.93 1.615 18.52 1 1\n#> Toyota Corolla 2.29127162 -1.2248578 71.1 65 4.22 1.835 19.90 1 1\n#> Toyota Corona 0.23384555 -1.2248578 120.1 97 3.70 2.465 20.01 1 0\n#> Dodge Challenger -0.76168319 1.0148821 318.0 150 2.76 3.520 16.87 0 0\n#> AMC Javelin -0.81145962 1.0148821 304.0 150 3.15 3.435 17.30 0 0\n#> Camaro Z28 -1.12671039 1.0148821 350.0 245 3.73 3.840 15.41 0 0\n#> Pontiac Firebird -0.14777380 1.0148821 400.0 175 3.08 3.845 17.05 0 0\n#> Fiat X1-9 1.19619000 -1.2248578 79.0 66 4.08 1.935 18.90 1 1\n#> Porsche 914-2 0.98049211 -1.2248578 120.3 91 4.43 2.140 16.70 0 1\n#> Lotus Europa 1.71054652 -1.2248578 95.1 113 3.77 1.513 16.90 1 1\n#> Ford Pantera L -0.71190675 1.0148821 351.0 264 4.22 3.170 14.50 0 1\n#> Ferrari Dino -0.06481307 -0.1049878 145.0 175 3.62 2.770 15.50 0 1\n#> Maserati Bora -0.84464392 1.0148821 301.0 335 3.54 3.570 14.60 0 1\n#> Volvo 142E 0.21725341 -1.2248578 121.0 109 4.11 2.780 18.60 1 1\n#> gear carb\n#> Mazda RX4 4 4\n#> Mazda RX4 Wag 4 4\n#> Datsun 710 4 1\n#> Hornet 4 Drive 3 1\n#> Hornet Sportabout 3 2\n#> Valiant 3 1\n#> Duster 360 3 4\n#> Merc 240D 4 2\n#> Merc 230 4 2\n#> Merc 280 4 4\n#> Merc 280C 4 4\n#> Merc 450SE 3 3\n#> Merc 450SL 3 3\n#> Merc 450SLC 3 3\n#> Cadillac Fleetwood 3 4\n#> Lincoln Continental 3 4\n#> Chrysler Imperial 3 4\n#> Fiat 128 4 1\n#> Honda Civic 4 2\n#> Toyota Corolla 4 1\n#> Toyota Corona 3 1\n#> Dodge Challenger 3 2\n#> AMC Javelin 3 2\n#> Camaro Z28 3 4\n#> Pontiac Firebird 3 2\n#> Fiat X1-9 4 1\n#> Porsche 914-2 5 2\n#> Lotus Europa 5 2\n#> Ford Pantera L 5 4\n#> Ferrari Dino 5 6\n#> Maserati Bora 5 8\n#> Volvo 142E 4 2\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20322733/"
] |
74,603,291
|
<p>I have a basic html markup, where i am trying to use minimal html wrappers to achieve the design.<br>
So my goal is without adding more html wrappers, using flex, force 3rd flex item to start from second column like here</p>
<pre><code>1 2
3
</code></pre>
<p>Of course, we can achieve adding <code>padding/margin-left</code> for the 3rd element, but I am looking for a solution with css flex and using minimal html markup.<br>
Here is the screenshot what I am trying to achieve<a href="https://i.stack.imgur.com/jbsu6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jbsu6.png" alt="enter image description here" /></a></p>
<p>Basically the title and text should start from the same column.</p>
<p>See the code snippet and <a href="https://codesandbox.io/s/affectionate-dirac-3vwsnm?file=/style.css:0-676" rel="nofollow noreferrer">sandbox link</a>, if you want to test it more</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>body {
margin: 0;
padding: 0;
}
.container {
background-color: grey;
overflow: auto;
padding: 20px;
align-items: center;
display: flex;
position: relative;
column-gap: 15px;
flex-wrap: wrap;
width: 100%;
}
.content {
display: flex;
flex-wrap: wrap;
}
.logo-image {
align-self: flex-start;
padding-top: 10px;
order: 1;
}
.headline {
color: white;
order: 2;
padding-left: 10px;
}
.text {
color: white;
font-size: 16px;
margin-bottom: 20px;
order: 3;
}
.btn {
display: flex;
width: 100%;
}
button {
align-items: center;
background-color: black;
color: white;
flex: 0 0 90%;
justify-content: center;
margin: 0;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="container">
<div class="content">
<h4 class="headline">
Block Title
</h4>
<img src="https://www.fillmurray.com/200/200" width="50px" class="logo-image" alt="img" />
<p class="text">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Sapiente
aliquid sit, cupiditate
</p>
</div>
<div class="btn">
<button>click</button>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74603763,
"author": "Michael Benjamin",
"author_id": 3597276,
"author_profile": "https://Stackoverflow.com/users/3597276",
"pm_score": 3,
"selected": true,
"text": ".container {\n display: flex;\n flex-wrap: wrap;\n background-color: grey;\n column-gap: 15px;\n padding: 20px;\n}\n\n.content {\n display: grid;\n grid-template-columns: 50px 1fr;\n}\n\n.logo-image {\n padding-top: 10px;\n order: 1;\n}\n\n.headline {\n color: white;\n order: 2;\n padding-left: 10px;\n}\n\n.text {\n grid-column: 2;\n color: white;\n font-size: 16px;\n margin-bottom: 20px;\n order: 3;\n}\n\n.btn {\n display: flex;\n width: 100%;\n}\n\nbutton {\n align-items: center;\n background-color: black;\n color: white;\n flex: 0 0 90%;\n justify-content: center;\n margin: 0;\n}\n\nbody {\n margin: 0;\n padding: 0;\n} <div class=\"container\">\n <div class=\"content\">\n <h4 class=\"headline\">\n Block Title\n </h4>\n <img src=\"https://www.fillmurray.com/200/200\" width=\"50px\" class=\"logo-image\" alt=\"img\" />\n <p class=\"text\">\n Lorem ipsum dolor sit amet consectetur adipisicing elit. Sapiente aliquid sit, cupiditate\n </p>\n </div>\n <div class=\"btn\">\n <button>click</button>\n </div> flex-direction column flex-wrap wrap .container {\n display: flex;\n flex-wrap: wrap;\n background-color: grey;\n column-gap: 15px;\n padding: 20px;\n height: 200px; /* new (for demo purposes) */\n}\n\n.content {\n display: flex;\n flex-direction: column; /* new */\n flex-wrap: wrap;\n}\n\n.logo-image {\n flex-basis: 100%; /* new */\n object-fit: contain; /* new (for proper image rendering) */\n object-position: top; /* new (for proper image rendering) */\n align-self: flex-start;\n padding-top: 10px;\n order: 1;\n}\n\n.headline {\n color: white;\n order: 2;\n padding-left: 10px;\n}\n\n.text {\n color: white;\n font-size: 16px;\n margin-bottom: 20px;\n order: 3;\n}\n\n.btn {\n display: flex;\n width: 100%;\n}\n\nbutton {\n align-items: center;\n background-color: black;\n color: white;\n flex: 0 0 90%;\n justify-content: center;\n margin: 0;\n}\n\nbody {\n margin: 0;\n padding: 0;\n} <div class=\"container\">\n <div class=\"content\">\n <h4 class=\"headline\">Block Title</h4>\n <img src=\"https://www.fillmurray.com/200/200\" width=\"50px\" class=\"logo-image\" alt=\"img\" />\n <p class=\"text\">\n Lorem ipsum dolor sit amet consectetur adipisicing elit. Sapiente\n aliquid sit, cupiditate\n </p>\n </div>\n <div class=\"btn\">\n <button>click</button>\n </div>"
},
{
"answer_id": 74603783,
"author": "mohammad khakshoor",
"author_id": 19840739,
"author_profile": "https://Stackoverflow.com/users/19840739",
"pm_score": 0,
"selected": false,
"text": "/* added this --v */\n.content {\n display: grid; /* ----- new ------- */\n grid-template-columns: auto 1fr; /* ----- new ------- */\n grid-template-rows: 1fr 1fr; /* ----- new ------- */\n column-gap: 15px; /* ----- new ------- */\n} <body>\n <div class=\"container\">\n <div class=\"content\">\n \n \n <!-- bring the img element above of h4 because we want it to be in the first item of our grid layout -->\n \n \n <img src=\"download.png\" width=\"50px\" class=\"logo-image\" alt=\"img\" />\n <h4 class=\"headline\">\n Block Title\n </h4>\n \n <p class=\"text\">\n Lorem ipsum dolor sit amet consectetur adipisicing elit. Sapiente\n aliquid sit, cupiditate\n </p>\n </div>\n <div class=\"btn\">\n <button>link</button>\n </div>\n </div>\n </body> .content { display: grid; grid-template-columns: auto 1fr; grid-template-rows: 1fr 1fr; column-gap: 15px; } <br>\n grid-column: 2/3;"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12971921/"
] |
74,603,298
|
<p>I trying to group several nodes that have the same contexts inside a existing nodes, by example my case is try to group node Desglose within Detalle, so by example one Node <strong>Detalle</strong> could have N nodes <strong>Desglose</strong>.</p>
<p>My Actual XML</p>
<pre><code> <?xml version="1.0" encoding="UTF-8"?>
<MT_Request_Respuesta_plano>
<Cabecera>
<TipoRegistro>C</TipoRegistro>
<TipoFichero>Facturas</TipoFichero>
<CCAA>12</CCAA>
<FechaFichero>20221124</FechaFichero>
<DescripProceso>DESCARGAS DEL FICHERO DE FACTURAS DEL SERMAS </DescripProceso>
<CodigoResultado/>
<DescripResultado/>
<espacios/>
</Cabecera>
<Certificacion>
<TipoRegistro>R</TipoRegistro>
<NroCertificacion>121100</NroCertificacion>
<NombreSPS>SERVICIO MADRILEÑO DE SALUD </NombreSPS>
<DireccionSPS>PLAZA DE CARLOS TRÍAS BERTRÁN, Nº 7, EDIFICIO SOLLUBE </DireccionSPS>
<LocalidadSPS>MADRID </LocalidadSPS>
<CodPostalSPS>28020 </CodPostalSPS>
<FecDesdeLiquidacion>20210316</FecDesdeLiquidacion>
<FecHastaLiquidacion>20210330</FecHastaLiquidacion>
<NroLiquidacionDesde>000000000000000</NroLiquidacionDesde>
<NroLiquidacionHasta>999999999999999</NroLiquidacionHasta>
<TotalLiquidacionesMes>0000075</TotalLiquidacionesMes>
<ImporteTotal>000000001498200</ImporteTotal>
<Observaciones/>
<Libre>914555222 </Libre>
</Certificacion>
<Detalle>
<TipoRegistro>D</TipoRegistro>
<ProvinciaOrigen>28</ProvinciaOrigen>
<CodCentroGrabacion>2803 </CodCentroGrabacion>
<CodCentroAsistencia/>
<NumeroFactura> 2110100556</NumeroFactura>
<ProvinciaDestino>28</ProvinciaDestino>
<FechaGrabacion>20210316</FechaGrabacion>
<Nombre>AURORA </Nombre>
<PrimerApellido>DE </PrimerApellido>
<SegundoApellido>BLAS GUTIERREZ </SegundoApellido>
<NSS>390050482793</NSS>
<IPF>113740356H </IPF>
<IndicadorRecaida>N</IndicadorRecaida>
<FechaAccidente>20171107</FechaAccidente>
<FechaInicioAs>20171107</FechaInicioAs>
<FechaFinAs>20171107</FechaFinAs>
<TipoContingencia>AT</TipoContingencia>
<CodigoContingencia>3</CodigoContingencia>
<espacios/>
</Detalle>
<Desglose>
<TipoRegistro>T</TipoRegistro>
<CodigoPrestaciones>0</CodigoPrestaciones>
<CodConceptoCargo>E03.1.1.2.2.1.1 </CodConceptoCargo>
<FechaTecnica>20171107</FechaTecnica>
<CodHospitalizacion>0</CodHospitalizacion>
<CodTipoTarifa/>
<Unidades>001</Unidades>
<PrecioConcepto>00017500</PrecioConcepto>
<ImporteTotal>0000000017500</ImporteTotal>
<FechaPublicacionBOCA>20170821</FechaPublicacionBOCA>
<espacios/>
</Desglose>
<Desglose>
<TipoRegistro>T</TipoRegistro>
<CodigoPrestaciones>0</CodigoPrestaciones>
<CodConceptoCargo>E03.1.1.2.1.1 </CodConceptoCargo>
<FechaTecnica>20171108</FechaTecnica>
<CodHospitalizacion>0</CodHospitalizacion>
<CodTipoTarifa/>
<Unidades>001</Unidades>
<PrecioConcepto>00011500</PrecioConcepto>
<ImporteTotal>0000000011500</ImporteTotal>
<FechaPublicacionBOCA>20170821</FechaPublicacionBOCA>
<espacios/>
</Desglose>
<Detalle>
<TipoRegistro>D</TipoRegistro>
<ProvinciaOrigen>28</ProvinciaOrigen>
<CodCentroGrabacion>2803 </CodCentroGrabacion>
<CodCentroAsistencia/>
<NumeroFactura> 2110100559</NumeroFactura>
<ProvinciaDestino>28</ProvinciaDestino>
<FechaGrabacion>20210316</FechaGrabacion>
<Nombre>CLAUDIA </Nombre>
<PrimerApellido>JIMENEZ </PrimerApellido>
<SegundoApellido>TORIJA </SegundoApellido>
<NSS>281208193843</NSS>
<IPF>111862836B </IPF>
<IndicadorRecaida>N</IndicadorRecaida>
<FechaAccidente>20171213</FechaAccidente>
<FechaInicioAs>20171213</FechaInicioAs>
<FechaFinAs>20171214</FechaFinAs>
<TipoContingencia>AT</TipoContingencia>
<CodigoContingencia>3</CodigoContingencia>
<espacios/>
</Detalle>
<Desglose>
<TipoRegistro>T</TipoRegistro>
<CodigoPrestaciones>0</CodigoPrestaciones>
<CodConceptoCargo>E03.1.1.2.2.1.1 </CodConceptoCargo>
<FechaTecnica>20171213</FechaTecnica>
<CodHospitalizacion>0</CodHospitalizacion>
<CodTipoTarifa/>
<Unidades>001</Unidades>
<PrecioConcepto>00017500</PrecioConcepto>
<ImporteTotal>0000000017500</ImporteTotal>
<FechaPublicacionBOCA>20170821</FechaPublicacionBOCA>
<espacios/>
</Desglose>
<Detalle>
<TipoRegistro>D</TipoRegistro>
<ProvinciaOrigen>28</ProvinciaOrigen>
<CodCentroGrabacion>2803 </CodCentroGrabacion>
<CodCentroAsistencia/>
<NumeroFactura> 2110100562</NumeroFactura>
<ProvinciaDestino>28</ProvinciaDestino>
<FechaGrabacion>20210316</FechaGrabacion>
<Nombre>SUSANA SARA </Nombre>
<PrimerApellido>MACHO </PrimerApellido>
<SegundoApellido>LOPEZ </SegundoApellido>
<NSS>280343142847</NSS>
<IPF>170164060F </IPF>
<IndicadorRecaida>N</IndicadorRecaida>
<FechaAccidente>20171030</FechaAccidente>
<FechaInicioAs>20171030</FechaInicioAs>
<FechaFinAs>20171031</FechaFinAs>
<TipoContingencia>AT</TipoContingencia>
<CodigoContingencia>3</CodigoContingencia>
<espacios/>
</Detalle>
<Desglose>
<TipoRegistro>T</TipoRegistro>
<CodigoPrestaciones>0</CodigoPrestaciones>
<CodConceptoCargo>E03.1.1.2.2.1.1 </CodConceptoCargo>
<FechaTecnica>20171030</FechaTecnica>
<CodHospitalizacion>0</CodHospitalizacion>
<CodTipoTarifa/>
<Unidades>001</Unidades>
<PrecioConcepto>00017500</PrecioConcepto>
<ImporteTotal>0000000017500</ImporteTotal>
<FechaPublicacionBOCA>20170821</FechaPublicacionBOCA>
<espacios/>
</Desglose>
<Desglose>
<TipoRegistro>T</TipoRegistro>
<CodigoPrestaciones>0</CodigoPrestaciones>
<CodConceptoCargo>E03.1.1.2.1.1 </CodConceptoCargo>
<FechaTecnica>20171102</FechaTecnica>
<CodHospitalizacion>0</CodHospitalizacion>
<CodTipoTarifa/>
<Unidades>001</Unidades>
<PrecioConcepto>00011500</PrecioConcepto>
<ImporteTotal>0000000011500</ImporteTotal>
<FechaPublicacionBOCA>20170821</FechaPublicacionBOCA>
<espacios/>
</Desglose>
<Totales>
<TipoRegistro>X</TipoRegistro>
<TotalRegGrabados>0000184</TotalRegGrabados>
<espacios/>
</Totales>
</MT_Request_Respuesta_plano>
</code></pre>
<pre><code></code></pre>
<p>The result I expect is to be able to group the <strong>"Desglose"</strong> nodes inside the <strong>"Detalle"</strong> nodes, assuming the sequence in which the <strong>"Desglose"</strong> nodes arrive to me, after each <strong>"Detail"</strong> node, could be N <strong>"Detalle"</strong> with M <strong>"Desglose"</strong> associated</p>
<pre><code></code></pre>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<MT_Request_Respuesta_plano>
<Cabecera>
<TipoRegistro>C</TipoRegistro>
<TipoFichero>Facturas</TipoFichero>
<CCAA>12</CCAA>
<FechaFichero>20221124</FechaFichero>
<DescripProceso>DESCARGAS DEL FICHERO DE FACTURAS DEL SERMA</DescripProceso>
<CodigoResultado/>
<DescripResultado/>
<espacios/>
</Cabecera>
<Certificacion>
<TipoRegistro>R</TipoRegistro>
<NroCertificacion>121100</NroCertificacion>
<NombreSPS>SERVICIO MADRILEÑO DE SALUD </NombreSPS>
<DireccionSPS>PLAZA DE CARLOS TRÍAS BERTRÁN, Nº 7, EDIFICIO SOLLUBE</DireccionSPS>
<LocalidadSPS>MADRID </LocalidadSPS>
<CodPostalSPS>28020 </CodPostalSPS>
<FecDesdeLiquidacion>20210316</FecDesdeLiquidacion>
<FecHastaLiquidacion>20210330</FecHastaLiquidacion>
<NroLiquidacionDesde>000000000000000</NroLiquidacionDesde>
<NroLiquidacionHasta>999999999999999</NroLiquidacionHasta>
<TotalLiquidacionesMes>0000075</TotalLiquidacionesMes>
<ImporteTotal>000000001498200</ImporteTotal>
<Observaciones/>
<Libre>914555222 </Libre>
</Certificacion>
<Detalle>
<TipoRegistro>D</TipoRegistro>
<ProvinciaOrigen>28</ProvinciaOrigen>
<CodCentroGrabacion>2803 </CodCentroGrabacion>
<CodCentroAsistencia/>
<NumeroFactura> 2110100556</NumeroFactura>
<ProvinciaDestino>28</ProvinciaDestino>
<FechaGrabacion>20210316</FechaGrabacion>
<Nombre>AURORA </Nombre>
<PrimerApellido>DE </PrimerApellido>
<SegundoApellido>BLAS GUTIERREZ </SegundoApellido>
<NSS>390050482793</NSS>
<IPF>113740356H </IPF>
<IndicadorRecaida>N</IndicadorRecaida>
<FechaAccidente>20171107</FechaAccidente>
<FechaInicioAs>20171107</FechaInicioAs>
<FechaFinAs>20171107</FechaFinAs>
<TipoContingencia>AT</TipoContingencia>
<CodigoContingencia>3</CodigoContingencia>
<espacios/>
<Desglose>
<TipoRegistro>T</TipoRegistro>
<CodigoPrestaciones>0</CodigoPrestaciones>
<CodConceptoCargo>E03.1.1.2.2.1.1 </CodConceptoCargo>
<FechaTecnica>20171107</FechaTecnica>
<CodHospitalizacion>0</CodHospitalizacion>
<CodTipoTarifa/>
<Unidades>001</Unidades>
<PrecioConcepto>00017500</PrecioConcepto>
<ImporteTotal>0000000017500</ImporteTotal>
<FechaPublicacionBOCA>20170821</FechaPublicacionBOCA>
<espacios/>
</Desglose>
<Desglose>
<TipoRegistro>T</TipoRegistro>
<CodigoPrestaciones>0</CodigoPrestaciones>
<CodConceptoCargo>E03.1.1.2.1.1 </CodConceptoCargo>
<FechaTecnica>20171108</FechaTecnica>
<CodHospitalizacion>0</CodHospitalizacion>
<CodTipoTarifa/>
<Unidades>001</Unidades>
<PrecioConcepto>00011500</PrecioConcepto>
<ImporteTotal>0000000011500</ImporteTotal>
<FechaPublicacionBOCA>20170821</FechaPublicacionBOCA>
<espacios/>
</Desglose>
</Detalle>
<Detalle>
<TipoRegistro>D</TipoRegistro>
<ProvinciaOrigen>28</ProvinciaOrigen>
<CodCentroGrabacion>2803 </CodCentroGrabacion>
<CodCentroAsistencia/>
<NumeroFactura> 2110100559</NumeroFactura>
<ProvinciaDestino>28</ProvinciaDestino>
<FechaGrabacion>20210316</FechaGrabacion>
<Nombre>CLAUDIA </Nombre>
<PrimerApellido>JIMENEZ </PrimerApellido>
<SegundoApellido>TORIJA </SegundoApellido>
<NSS>281208193843</NSS>
<IPF>111862836B </IPF>
<IndicadorRecaida>N</IndicadorRecaida>
<FechaAccidente>20171213</FechaAccidente>
<FechaInicioAs>20171213</FechaInicioAs>
<FechaFinAs>20171214</FechaFinAs>
<TipoContingencia>AT</TipoContingencia>
<CodigoContingencia>3</CodigoContingencia>
<espacios/>
<Desglose>
<TipoRegistro>T</TipoRegistro>
<CodigoPrestaciones>0</CodigoPrestaciones>
<CodConceptoCargo>E03.1.1.2.2.1.1 </CodConceptoCargo>
<FechaTecnica>20171213</FechaTecnica>
<CodHospitalizacion>0</CodHospitalizacion>
<CodTipoTarifa/>
<Unidades>001</Unidades>
<PrecioConcepto>00017500</PrecioConcepto>
<ImporteTotal>0000000017500</ImporteTotal>
<FechaPublicacionBOCA>20170821</FechaPublicacionBOCA>
<espacios/>
</Desglose>
</Detalle>
<Detalle>
<TipoRegistro>D</TipoRegistro>
<ProvinciaOrigen>28</ProvinciaOrigen>
<CodCentroGrabacion>2803 </CodCentroGrabacion>
<CodCentroAsistencia/>
<NumeroFactura> 2110100562</NumeroFactura>
<ProvinciaDestino>28</ProvinciaDestino>
<FechaGrabacion>20210316</FechaGrabacion>
<Nombre>SUSANA SARA </Nombre>
<PrimerApellido>MACHO </PrimerApellido>
<SegundoApellido>LOPEZ </SegundoApellido>
<NSS>280343142847</NSS>
<IPF>170164060F </IPF>
<IndicadorRecaida>N</IndicadorRecaida>
<FechaAccidente>20171030</FechaAccidente>
<FechaInicioAs>20171030</FechaInicioAs>
<FechaFinAs>20171031</FechaFinAs>
<TipoContingencia>AT</TipoContingencia>
<CodigoContingencia>3</CodigoContingencia>
<espacios/>
<Desglose>
<TipoRegistro>T</TipoRegistro>
<CodigoPrestaciones>0</CodigoPrestaciones>
<CodConceptoCargo>E03.1.1.2.2.1.1 </CodConceptoCargo>
<FechaTecnica>20171030</FechaTecnica>
<CodHospitalizacion>0</CodHospitalizacion>
<CodTipoTarifa/>
<Unidades>001</Unidades>
<PrecioConcepto>00017500</PrecioConcepto>
<ImporteTotal>0000000017500</ImporteTotal>
<FechaPublicacionBOCA>20170821</FechaPublicacionBOCA>
<espacios/>
</Desglose>
<Desglose>
<TipoRegistro>T</TipoRegistro>
<CodigoPrestaciones>0</CodigoPrestaciones>
<CodConceptoCargo>E03.1.1.2.1.1 </CodConceptoCargo>
<FechaTecnica>20171102</FechaTecnica>
<CodHospitalizacion>0</CodHospitalizacion>
<CodTipoTarifa/>
<Unidades>001</Unidades>
<PrecioConcepto>00011500</PrecioConcepto>
<ImporteTotal>0000000011500</ImporteTotal>
<FechaPublicacionBOCA>20170821</FechaPublicacionBOCA>
<espacios/>
</Desglose>
</Detalle>
<Totales>
<TipoRegistro>X</TipoRegistro>
<TotalRegGrabados>0000184</TotalRegGrabados>
<espacios/>
</Totales>
</MT_Request_Respuesta_plano>
</code></pre>
<pre><code></code></pre>
<p>I've tried this XSLT, one with <strong>for-each-group</strong>, but no result.</p>
<pre><code></code></pre>
<pre><code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"
version="1.0"
encoding="UTF-8"
indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Detalle">
<xsl:for-each-group select="Detalle | Desglose" group-by="@Detalle">
<Detalle>
<xsl:copy-of select="node()"/>
<xsl:for-each-group select="current-group()" group-by="@Desglose">
<Desglose>
<xsl:for-each select="current-group()">
<xsl:copy-of select="node()"/>
</xsl:for-each>
</Desglose>
</xsl:for-each-group>
</Detalle>
</xsl:for-each-group>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<pre><code></code></pre>
<p>I also have tried this another XSLT, more nice, but just result with values without label...</p>
<pre><code></code></pre>
<pre><code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:key name="Kgrupo" match="Desglose" use="generate-id(preceding-sibling::Detalle[NumeroFactura][1])" />
<xsl:template match="Detalle">
<xsl:copy>
<xsl:for-each select="Desglose">
<xsl:for-each select="key('Kgrupo', generate-id())" >
<Desglose>
<xsl:value-of select="normalize-space(main)" />
</Desglose>
</xsl:for-each>
</xsl:for-each>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<pre><code></code></pre>
<p>I would really appreciate any help to solve this transformation that seems easy, but it is not, at least for me =)</p>
<pre><code></code></pre>
|
[
{
"answer_id": 74612904,
"author": "michael.hor257k",
"author_id": 3016153,
"author_profile": "https://Stackoverflow.com/users/3016153",
"pm_score": 2,
"selected": true,
"text": "xsl:for-each-group group-starting-with <xsl:stylesheet version=\"1.0\" \nxmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n<xsl:output method=\"xml\" version=\"1.0\" encoding=\"UTF-8\" indent=\"yes\"/>\n<xsl:strip-space elements=\"*\"/>\n\n<xsl:key name=\"Kgrupo\" match=\"Desglose\" use=\"generate-id(preceding-sibling::Detalle[1])\" />\n\n<xsl:template match=\"/MT_Request_Respuesta_plano\">\n <xsl:copy>\n <xsl:copy-of select=\"Cabecera | Certificacion\"/>\n <xsl:for-each select=\"Detalle\">\n <xsl:copy>\n <xsl:copy-of select=\"*\"/>\n <xsl:copy-of select=\"key('Kgrupo', generate-id())\"/>\n </xsl:copy>\n </xsl:for-each>\n <xsl:copy-of select=\"Totales\"/>\n </xsl:copy>\n</xsl:template>\n\n</xsl:stylesheet>\n"
},
{
"answer_id": 74617386,
"author": "pgfearo",
"author_id": 63965,
"author_profile": "https://Stackoverflow.com/users/63965",
"pm_score": 0,
"selected": false,
"text": "xsl:for-each xsl:key $currentElement $targetElement Detalle $sourceElements Desglose $targetElement $targetElement fn:injectElements <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:fn=\"com.group-elements.sample\"\n exclude-result-prefixes=\"#all\"\n version=\"1.0\">\n \n <xsl:strip-space elements=\"*\"/> \n <xsl:output method=\"xml\" indent=\"yes\"/>\n \n <xsl:template match=\"/*\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*\" mode=\"#current\"/>\n <xsl:call-template name=\"iterate-elements\"/>\n </xsl:copy>\n </xsl:template>\n \n <xsl:template name=\"iterate-elements\">\n <xsl:param name=\"elements\" as=\"element()*\" select=\"*\"/>\n <xsl:param name=\"currentElement\" select=\"$elements[1]\"/>\n <xsl:param name=\"targetElement\" as=\"element()?\" select=\"()\"/>\n <xsl:param name=\"sourceElements\" as=\"element()*\"/>\n \n <xsl:choose>\n <xsl:when test=\"empty($currentElement)\">\n <!-- in case there are any source elements left over: -->\n <xsl:sequence select=\"fn:injectElements($targetElement, $sourceElements)\"/>\n </xsl:when>\n <xsl:when test=\"fn:isTarget($currentElement)\">\n <!-- on a new target element so process previous target element and set the new target element -->\n <xsl:sequence select=\"fn:injectElements($targetElement, $sourceElements)\"/>\n <xsl:call-template name=\"iterate-elements\">\n <xsl:with-param name=\"currentElement\" select=\"$currentElement/following-sibling::*[1]\"/>\n <xsl:with-param name=\"sourceElements\" select=\"()\"/>\n <xsl:with-param name=\"targetElement\" select=\"$currentElement\"/>\n </xsl:call-template>\n </xsl:when>\n <!-- on a new source element so concatanate to the sequence of source elements -->\n <xsl:when test=\"fn:isSource($currentElement)\">\n <xsl:call-template name=\"iterate-elements\">\n <xsl:with-param name=\"currentElement\" select=\"$currentElement/following-sibling::*[1]\"/>\n <xsl:with-param name=\"sourceElements\" select=\"$sourceElements, $currentElement\"/>\n <xsl:with-param name=\"targetElement\" select=\"$targetElement\"/>\n </xsl:call-template>\n </xsl:when>\n <xsl:otherwise>\n <!-- not on source/target element - process any target element then emit current element -->\n <xsl:sequence select=\"fn:injectElements($targetElement, $sourceElements), $currentElement\"/>\n <xsl:call-template name=\"iterate-elements\">\n <xsl:with-param name=\"currentElement\" select=\"$currentElement/following-sibling::*[1]\"/>\n <xsl:with-param name=\"sourceElements\" select=\"()\"/>\n <xsl:with-param name=\"targetElement\" select=\"()\"/>\n </xsl:call-template>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:template>\n \n <xsl:function name=\"fn:isTarget\" as=\"xs:boolean\">\n <xsl:param name=\"element\" as=\"element()\"/>\n <xsl:sequence select=\"exists($element[self::Detalle])\"/>\n </xsl:function>\n \n <xsl:function name=\"fn:isSource\" as=\"xs:boolean\">\n <xsl:param name=\"element\" as=\"element()\"/>\n <xsl:sequence select=\"exists($element[self::Desglose])\"/>\n </xsl:function>\n \n <xsl:function name=\"fn:injectElements\" as=\"element()?\">\n <xsl:param name=\"target\" as=\"element()?\"/>\n <xsl:param name=\"sourceElements\" as=\"element()*\"/>\n <xsl:if test=\"exists($target)\">\n <xsl:copy select=\"$target\">\n <xsl:copy-of select=\"$target/@*, $target/node()\"/>\n <xsl:copy-of select=\"$sourceElements\"/>\n </xsl:copy>\n </xsl:if>\n </xsl:function>\n \n</xsl:stylesheet>[enter link description here][1]\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8936307/"
] |
74,603,327
|
<p>Here is my code:</p>
<pre><code>return Scaffold(
appBar: AppBar(
backgroundColor: Colors.grey[900],
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => Navigator.of(context).pop(false),
),
),
backgroundColor: Colors.grey[900],
body: Visibility(
visible: questionLoaded,
child: Builder(builder: (context) {
return Wrap(
spacing: 8.0,
runSpacing: 4.0,
direction: Axis.horizontal,
children: [
Container(
width: double.infinity,
child: Text(
question!.question,
textAlign: TextAlign.center,
style: GoogleFonts.mukta(
textStyle: TextStyle(
color: Colors.amber,
fontSize: 24,
shadows: const [
Shadow(
color: Colors.white,
offset: Offset.zero,
blurRadius: 15)
]),
),
),
),
if (question?.answer1 != "")
RadioButton(
textStyle: TextStyle(color: Colors.white),
description: (question?.answer1)!,
value: "1",
groupValue: _decision,
onChanged: (value) => setState(
() => _decision = value!,
),
),
if (question?.answer2 != "")
RadioButton(
textStyle: TextStyle(color: Colors.white),
description: (question?.answer2)!,
value: "2",
groupValue: _decision,
onChanged: (value) => setState(
() => _decision = value!,
),
),
if (question?.answer3 != "")
RadioButton(
textStyle: TextStyle(color: Colors.white),
description: (question?.answer3)!,
value: "3",
groupValue: _decision,
onChanged: (value) => setState(
() => _decision = value!,
),
),
if (question?.answer4 != "")
RadioButton(
textStyle: TextStyle(color: Colors.white),
description: (question?.answer4)!,
value: "4",
groupValue: _decision,
onChanged: (value) => setState(
() => _decision = value!,
),
),
],
);
})),
);
</code></pre>
<p>This produces the following issue:</p>
<p><a href="https://i.stack.imgur.com/rh54s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rh54s.png" alt="enter image description here" /></a></p>
<p>Any idea why and how can I fix it ?</p>
|
[
{
"answer_id": 74603399,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 0,
"selected": false,
"text": "Flexible Expanded Expnaded( child: Text( question!.question,....\n"
},
{
"answer_id": 74604482,
"author": "hari kurniawan",
"author_id": 20547245,
"author_profile": "https://Stackoverflow.com/users/20547245",
"pm_score": -1,
"selected": false,
"text": "Expanded(\n child: Column(\n children: [\n Text(\n 'datadatadatadatadatadata',\n overflow: TextOverflow.ellipsis,\n )\n ],\n ),\n ),\n Row(\n children: [\n Expanded(\n child: Text(\n 'datadatadatadatadatadata',\n overflow: TextOverflow.ellipsis,\n ),\n )\n ],\n ),\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2661419/"
] |
74,603,328
|
<p>I have a div "button" that opens a popup. When you click on the popup, it runs</p>
<pre><code>function theFunctionAbout() {
var popup = document.getElementById("thePopupAbout");
popup.classList.add("show");
}
</code></pre>
<p>and it will add show, which is visibility:visible;
when you click a button in the popup, it runs</p>
<pre><code>function theFunctionAboutClose(){
var popup = document.getElementById("thePopupAbout");
popup.classList.add("hide");
}
</code></pre>
<p>and it will add hide, which runs display:none;.</p>
<p>After hitting the button, the popup closes, but never opens again. How do i fix this?</p>
<p>I have tried switching add.("hide") to remove.("show"). This works on another popup where the popup window is part of a dive form element, and that popup is reopenable, However, my popup window here has a paragraph element. When i tried to do remove.("show") on my about popup, the button would not close the window.</p>
<p>My button:</p>
<pre><code><div class="aboutPopup" onclick="theFunctionAbout()">About
<p class="aboutPopupText" id="thePopupAbout">
<span class="aboutPopupInfo">
Mathalassa is a fun and educational math game that offers students from varying ages and grades to learn and perfect their math skills.
</span>
<button class="aboutPopupClose" onclick="theFunctionAboutClose()">x</button>
</p>
</div>
</code></pre>
<p>Another button:</p>
<pre><code><div class="oldUserPopup" onclick="theFunctionOld()">Old User
<form class="oldUserPopupText" id="thePopupOld">
<label class="oldUserPopupInfo" for="name">Please Enter Your Username:</label>
<div class="form-grp">
<input class="inputNameHere" type="text" name="username" id="user" required minlength="2" maxlength="15" size="10" >
</div>
<div class="form-grp">
<input class="inputSubmit" type="Submit" name="login-btn" id="user">
</div>
<button class="oldUserPopupClose" onclick="theFunctionOldClose()">x</button>
</form>
</div>
</code></pre>
|
[
{
"answer_id": 74603476,
"author": "Grizou",
"author_id": 20068386,
"author_profile": "https://Stackoverflow.com/users/20068386",
"pm_score": 1,
"selected": false,
"text": "element.classList.toggle(\"hide\");"
},
{
"answer_id": 74603510,
"author": "Moussa Bistami",
"author_id": 15628525,
"author_profile": "https://Stackoverflow.com/users/15628525",
"pm_score": 0,
"selected": false,
"text": "class=\"...other_classes show hide show hide show hide\" function theFunctionAbout() {\n var popup = document.getElementById(\"thePopupAbout\");\n popup.classList.remove(\"hide\");\n popup.classList.add(\"show\");\n }\n function theFunctionAboutClose(){\n var popup = document.getElementById(\"thePopupAbout\"); \n popup.classList.remove(\"show\")\n popup.classList.add(\"hide\");\n }\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20542839/"
] |
74,603,338
|
<p>I am having a problem with the image src that I am trying to upload in my dApp. I have the height and width properties set but it still shows the following error:</p>
<p><code>Uncaught Error: Image with src "https://vivi-project.infura-ipfs.io/ipfs/Qmc5VkpgsRbiyxG1152WVfnHgZ4caqVLJDSrUPYhX9TdCP" must use "width" and "height" properties or "layout='fill'" property.</code></p>
<p>I have the properties set as:
`</p>
<pre><code><Image
src={fileUrl}
alt="Picture of the NFT"
className="rounded mt-4"
width={350}
height={500}
//blurDataURL="data:..." automatically provided
//placeholder="blur" // Optional blur-up while loading
/>
</code></pre>
<p>`</p>
<p>I have looked at solution:
<a href="https://stackoverflow.com/questions/66784795/nextjs-image-issue-with-src-and-default-external-image-url">NextjS Image issue with src and default external image URL</a></p>
<p>and looked at the Nextjs documentation
<a href="https://nextjs.org/docs/api-reference/next/image" rel="nofollow noreferrer">https://nextjs.org/docs/api-reference/next/image</a></p>
|
[
{
"answer_id": 74603476,
"author": "Grizou",
"author_id": 20068386,
"author_profile": "https://Stackoverflow.com/users/20068386",
"pm_score": 1,
"selected": false,
"text": "element.classList.toggle(\"hide\");"
},
{
"answer_id": 74603510,
"author": "Moussa Bistami",
"author_id": 15628525,
"author_profile": "https://Stackoverflow.com/users/15628525",
"pm_score": 0,
"selected": false,
"text": "class=\"...other_classes show hide show hide show hide\" function theFunctionAbout() {\n var popup = document.getElementById(\"thePopupAbout\");\n popup.classList.remove(\"hide\");\n popup.classList.add(\"show\");\n }\n function theFunctionAboutClose(){\n var popup = document.getElementById(\"thePopupAbout\"); \n popup.classList.remove(\"show\")\n popup.classList.add(\"hide\");\n }\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20251805/"
] |
74,603,351
|
<p>I have created a data frame which has rolling quarter mapping using the code</p>
<pre><code>abcd = pd.DataFrame()
abcd['Month'] = np.nan
abcd['Month'] = pd.date_range(start='2020-04-01', end='2022-04-01', freq = 'MS')
abcd['Time_1'] = np.arange(1, abcd.shape[0]+1)
abcd['Time_2'] = np.arange(0, abcd.shape[0])
abcd['Time_3'] = np.arange(-1, abcd.shape[0]-1)
db_nd_ad_unpivot = pd.melt(abcd, id_vars=['Month'],
value_vars=['Time_1', 'Time_2', 'Time_3',],
var_name='Time_name', value_name='Time')
abcd_map = db_nd_ad_unpivot[(db_nd_ad_unpivot['Time']>0)&(db_nd_ad_unpivot['Time']< abcd.shape[0]+1)]
abcd_map = abcd_map[['Month','Time']]
</code></pre>
<p>The output of the code looks like this:</p>
<p><a href="https://i.stack.imgur.com/tV6xV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tV6xV.png" alt="Output of the rolling quarter code" /></a></p>
<p>Now, I have created an additional column name that gives me the name of the month and year in format Mon-YY using the code</p>
<pre><code>abcd_map['Month'] = pd.to_datetime(abcd_map.Month)
# abcd_map['Month'] = abcd_map['Month'].astype(str)
abcd_map['Time_Period'] = abcd_map['Month'].apply(lambda x: x.strftime("%b'%y"))
</code></pre>
<p><a href="https://i.stack.imgur.com/yEooR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yEooR.png" alt="Same Dataframe with month name added" /></a></p>
<p>Now I want to see for a specific time, what is the minimum and maximum in the month column. For eg. for time instance 17
<a href="https://i.stack.imgur.com/7VZiF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7VZiF.png" alt="Time Instance 17" /></a></p>
<p>,The simple groupby results as:
Time Period
17 Aug'21-Sept'21</p>
<p><a href="https://i.stack.imgur.com/23Z9S.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/23Z9S.png" alt="enter image description here" /></a></p>
<p>The desired output is
Time Time_Period
17 Aug'21-Oct'21.</p>
<p>I think it is based on min and max of the column Month as by using the strftime function the column is getting converted in String/object type.</p>
|
[
{
"answer_id": 74603476,
"author": "Grizou",
"author_id": 20068386,
"author_profile": "https://Stackoverflow.com/users/20068386",
"pm_score": 1,
"selected": false,
"text": "element.classList.toggle(\"hide\");"
},
{
"answer_id": 74603510,
"author": "Moussa Bistami",
"author_id": 15628525,
"author_profile": "https://Stackoverflow.com/users/15628525",
"pm_score": 0,
"selected": false,
"text": "class=\"...other_classes show hide show hide show hide\" function theFunctionAbout() {\n var popup = document.getElementById(\"thePopupAbout\");\n popup.classList.remove(\"hide\");\n popup.classList.add(\"show\");\n }\n function theFunctionAboutClose(){\n var popup = document.getElementById(\"thePopupAbout\"); \n popup.classList.remove(\"show\")\n popup.classList.add(\"hide\");\n }\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14363224/"
] |
74,603,354
|
<p>Here is the array</p>
<pre><code> string[] Numbers = new string[5] { "1", "2", "", "3", "4" };
</code></pre>
<p>As you can see I have 1 item that has nothing in it.
What I'm trying to do is make the array smaller and move, everything after the clear space, 1 down. I'm also going to use it for a bigger array. But it will always have just 1 clear space.</p>
<pre><code>{"1", "2", "3", "4"}
</code></pre>
<p>This is what I'm trying to get.</p>
<p>Here are the variables</p>
<pre><code>int intSelected, intCounter = 1, intAmount = Numbers.length;
</code></pre>
<p>And here is the code</p>
<pre><code> while (true)
{
Numbers[intSelected + intCounter] = Numbers[intSelected + intCounter - 1];
if (intSelected + intCounter == intAmount)
{
Array.Resize(ref Numbers, Numbers.Length - 1);
MessageBox.Show("It works");
intAmount--;
break;
}
else
{
intCounter++;
}
}
</code></pre>
|
[
{
"answer_id": 74603408,
"author": "Roman Ryzhiy",
"author_id": 7592390,
"author_profile": "https://Stackoverflow.com/users/7592390",
"pm_score": 2,
"selected": false,
"text": "System.Linq string[] Numbers = new string[5] { \"1\", \"2\", \"\", \"3\", \"4\" };\nstring[] ClearNumbers = Numbers.Where(e => !string.IsNullOrEmpty(e)).ToArray();\n"
},
{
"answer_id": 74603694,
"author": "Dmitry Bychenko",
"author_id": 2319407,
"author_profile": "https://Stackoverflow.com/users/2319407",
"pm_score": 2,
"selected": false,
"text": "Array.Resize string[] Numbers = new string[5] { \"1\", \"2\", \"\", \"3\", \"4\" };\n\n...\n\nint lastIndex = 0;\n\nfor (int i = 0; i < Numbers.Length; ++i)\n if (!string.IsNullOrEmpty(Numbers[i])) // if Numbers[i] should be preserved...\n Numbers[lastIndex++] = Numbers[i]; // ... Copy it to the lastIndex place \n\nArray.Resize(ref Numbers, lastIndex);\n"
},
{
"answer_id": 74608782,
"author": "Vic F",
"author_id": 4054386,
"author_profile": "https://Stackoverflow.com/users/4054386",
"pm_score": 0,
"selected": false,
"text": "int[] x = new[] { 1, 2, 3 };\n\nx = x[..^1]; // this takes everything except the last position.\n\nConsole.WriteLine(x.Length); // 2\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17473661/"
] |
74,603,356
|
<p>I would like to bind a variable inside a LOOP macro, but only conditionally.</p>
<p>Example:</p>
<pre class="lang-lisp prettyprint-override"><code>(loop :for (num div) :in '((1 2) (4 2) (3 0) (1 4))
:when (/= 0 div)
:for res = (/ num div)
:collect num
:do (format T "~A divided by ~A = ~A~%" num div res))
</code></pre>
<p>This doesn't work as written:</p>
<pre><code>:FOR does not introduce a LOOP clause that can follow WHEN.
current LOOP context: :FOR RES.
[Condition of type SB-INT:SIMPLE-PROGRAM-ERROR]
</code></pre>
<p>Is there a way to do this inside a single loop call? Any solutions I can think of, involve breaking out of the loop somehow which has considerable drawbacks. Among others you lose access to the loop context (:collect etc).</p>
|
[
{
"answer_id": 74603408,
"author": "Roman Ryzhiy",
"author_id": 7592390,
"author_profile": "https://Stackoverflow.com/users/7592390",
"pm_score": 2,
"selected": false,
"text": "System.Linq string[] Numbers = new string[5] { \"1\", \"2\", \"\", \"3\", \"4\" };\nstring[] ClearNumbers = Numbers.Where(e => !string.IsNullOrEmpty(e)).ToArray();\n"
},
{
"answer_id": 74603694,
"author": "Dmitry Bychenko",
"author_id": 2319407,
"author_profile": "https://Stackoverflow.com/users/2319407",
"pm_score": 2,
"selected": false,
"text": "Array.Resize string[] Numbers = new string[5] { \"1\", \"2\", \"\", \"3\", \"4\" };\n\n...\n\nint lastIndex = 0;\n\nfor (int i = 0; i < Numbers.Length; ++i)\n if (!string.IsNullOrEmpty(Numbers[i])) // if Numbers[i] should be preserved...\n Numbers[lastIndex++] = Numbers[i]; // ... Copy it to the lastIndex place \n\nArray.Resize(ref Numbers, lastIndex);\n"
},
{
"answer_id": 74608782,
"author": "Vic F",
"author_id": 4054386,
"author_profile": "https://Stackoverflow.com/users/4054386",
"pm_score": 0,
"selected": false,
"text": "int[] x = new[] { 1, 2, 3 };\n\nx = x[..^1]; // this takes everything except the last position.\n\nConsole.WriteLine(x.Length); // 2\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4359699/"
] |
74,603,360
|
<p>i am new to python and i'm trying to understand the use of the 'getter'. it's use case is not obvious to me.
if i use a property decorator on a method and im able to return a certain value, what exactly would i use 'getter' for.</p>
<pre><code>class Person:
def __init__(self,name, age):
self._name = name
self._age = age
@property
def age(self):
return self._age
@age.setter
def age(self,new_age):
if isinstance(new_age,int) and 18 < new_age < 120:
self._age = new_age
</code></pre>
|
[
{
"answer_id": 74603568,
"author": "CodeMonkey",
"author_id": 543969,
"author_profile": "https://Stackoverflow.com/users/543969",
"pm_score": 3,
"selected": true,
"text": "@age.setter p = Person(\"John\", 22)\nprint(p.age)\n 22\n"
},
{
"answer_id": 74603784,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 1,
"selected": false,
"text": "property class Person:\n def __init__(self,name, age):\n self._name = name\n self._age = age\n \n def _age_getter(self):\n return self._age\n\n def _age_setter(self, new_age):\n ...\n\n age = property(_age_getter, _age_setter)\n property property # Equivalent to\n# def age(self):\n# return self._age\n# age = property(age)\n@property\ndef age(self):\n return self._age\n age.setter property age @age.setter\ndef age(self, new_age):\n ...\n age old_property = age\ndef age(self, new_age):\n ...\nage = old_property.setter(age)\n property getter class Person:\n def __init__(self, name, age):\n ...\n\n age = property()\n\n @age.getter\n def age(self):\n ...\n\n @age.setter\n def age(self, new_age):\n ...\n getter setter deleter property"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20389571/"
] |
74,603,374
|
<p>I have a very lengthy html page with multiple instances of this type of code:</p>
<pre><code><h3>Some header text
<span class="text-small">Text I want to move</span>
</h3>
</code></pre>
<p>Ideal result:</p>
<pre><code><p>Text I want to move</p>
<h3>Some header text</h3>
</code></pre>
<p>I can use regex to find all the spans, but then what? Replace doesn't help me since the content is unique each time.</p>
<p>Thanks for your help, and let me know if I left any crucial info out.</p>
<p>Edit:
Per @bloodyKnuckles's comments, adding some more information:
I'm on mac, editing an html locally in Adobe Dreamweaver that will be copied onto a remote server later. The pages already exist there and I am updating some of the code.
In terms of regex, I do not have a lot of experience with it, and I tried a couple of different processors but I can't recall exactly which ones.</p>
|
[
{
"answer_id": 74603568,
"author": "CodeMonkey",
"author_id": 543969,
"author_profile": "https://Stackoverflow.com/users/543969",
"pm_score": 3,
"selected": true,
"text": "@age.setter p = Person(\"John\", 22)\nprint(p.age)\n 22\n"
},
{
"answer_id": 74603784,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 1,
"selected": false,
"text": "property class Person:\n def __init__(self,name, age):\n self._name = name\n self._age = age\n \n def _age_getter(self):\n return self._age\n\n def _age_setter(self, new_age):\n ...\n\n age = property(_age_getter, _age_setter)\n property property # Equivalent to\n# def age(self):\n# return self._age\n# age = property(age)\n@property\ndef age(self):\n return self._age\n age.setter property age @age.setter\ndef age(self, new_age):\n ...\n age old_property = age\ndef age(self, new_age):\n ...\nage = old_property.setter(age)\n property getter class Person:\n def __init__(self, name, age):\n ...\n\n age = property()\n\n @age.getter\n def age(self):\n ...\n\n @age.setter\n def age(self, new_age):\n ...\n getter setter deleter property"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030420/"
] |
74,603,379
|
<p>I am probably overengineering this - but I was hoping some can help me understand why this isn't working. My goal was to build a class that primarily uses classmethods, except in the case where a user creates an instance of the class so that they can change the assumed internal date.</p>
<pre><code>import datetime as dt
class Example():
"""
Primary usage is via classmethods, however if historical is needed then create
an instance of the class and pass reference date
"""
@staticmethod
def _get_time_to_mat():
return dt.date.today()
def __init__(self, ref_date):
self.ref_date = ref_date
#change the date the class method uses for **this instance**
def _override_get_time_to_mat():
return self.ref_date
# I was hoping that I could overwrite the function with a new function object
self._get_time_to_mat = _override_get_time_to_mat
@classmethod
def get_date(cls):
return cls._get_time_to_mat()
</code></pre>
<p>However, when I run it</p>
<pre><code>example_instance = Example(dt.date(2021,6,1))
print(Example.get_date())
print(example_instance.get_date())
2022-08-28
2022-08-28 # I would expect this to be 2021-06-01 !
</code></pre>
<p>Any help is appreciated! Thanks</p>
<p>PS.</p>
<ol>
<li>I'd like to avoid having to pass a ref_date to the classmethod as an optional argument.</li>
<li>I'd also like to avoid just using an instance of the class where the ref_date is passed with a default of dt.date.today().</li>
</ol>
|
[
{
"answer_id": 74603646,
"author": "edd313",
"author_id": 12040751,
"author_profile": "https://Stackoverflow.com/users/12040751",
"pm_score": 2,
"selected": false,
"text": "class Example():\n ref_date = dt.date.today()\n \n def __init__(self, ref_date=None):\n if ref_date:\n self.ref_date = ref_date\n >>> Example.ref_date\ndatetime.date(2022, 11, 28)\n>>> example_instance = Example(dt.date(2021,6,1))\n>>> example_instance.ref_date\ndatetime.date(2021, 6, 1)\n"
},
{
"answer_id": 74603649,
"author": "Lucas M. Uriarte",
"author_id": 14543462,
"author_profile": "https://Stackoverflow.com/users/14543462",
"pm_score": 1,
"selected": false,
"text": "class Example():\n \"\"\" \n Primary usage is via classmethods, however if historical is needed then create \n an instance of the class and pass reference date \n \n \"\"\"\n ref_date = dt.date.today() \n \n def __init__(self, ref_date=None):\n self.ref_date = ref_date\n if ref_date:\n self._override_class_date(ref_date)\n \n #change the date the class method uses for **this instance** \n @classmethod\n def _override_class_date(cls, date): \n cls.ref_date = date\n \n @classmethod\n def get_date(cls):\n return cls.ref_date\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/558619/"
] |
74,603,385
|
<p>I cannot seem to get the serif font 'Source Serif Pro' to render in my app. I have also set up 'Roboto" which renders fine. I tried a few different ways in the tailwind config...array...string...font stack in double quotes as said on Tailwind site.<br />
Not sure what I am missing here?</p>
<p>tailwind config</p>
<pre class="lang-js prettyprint-override"><code>module.exports = {
content: [
'./components/**/*.{js,vue,ts}',
'./layouts/**/*.vue',
'./pages/**/*.vue',
'./plugins/**/*.{js,ts}',
'./nuxt.config.{js,ts}',
],
theme: {
fontFamily: {
roboto: ['Roboto', 'sans'],
source: ['Source Serif Pro', 'serif'],
},
extend: {
colors: {
gray: {
50: '#f4f4f4',
100: '#000029',
200: '#bebebe',
300: '#555555',
400: '#444444',
500: '#3e3e3e',
},
tan: {
400: '#d1b991',
500: '#caae7f',
},
green: {
400: '#008059',
500: '#006846',
},
},
},
},
};
</code></pre>
<p>nuxt config inside 'build modules'</p>
<pre class="lang-js prettyprint-override"><code>[
'@nuxtjs/google-fonts',
{
families: {
Roboto: {
wght: [400, 700],
},
'Source+Serif+Pro': {
wght: [400, 600],
},
},
subsets: ['latin'],
display: 'swap',
prefetch: false,
preconnect: false,
preload: false,
download: true,
base64: false,
},
],
</code></pre>
|
[
{
"answer_id": 74603480,
"author": "kanuos",
"author_id": 10822859,
"author_profile": "https://Stackoverflow.com/users/10822859",
"pm_score": 0,
"selected": false,
"text": "@font-face css"
},
{
"answer_id": 74603777,
"author": "kissu",
"author_id": 8816585,
"author_profile": "https://Stackoverflow.com/users/8816585",
"pm_score": 2,
"selected": true,
"text": "Nunito @font-face {\n font-display: swap;\n font-family: 'Nunito';\n font-style: normal;\n font-weight: 400;\n src: local('Nunito Regular'), local('Nunito-Regular'),\n url('~assets/fonts/Nunito-400-cyrillic-ext1.woff2') format('woff2');\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9859897/"
] |
74,603,418
|
<p>I am trying to implement <code>strcmp</code> and <code>strcpy</code> to re-arrange names in alphabetical order and there is an issue with my name array initialization.</p>
<p>The state array cannot be printed out on the console as expected.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char sort(char [], char []);
int main() {
char strStates[8] = {
'Ontario', 'Quebec', 'Manitoba', 'Alberta',
'British Colombia', 'Nova Scotia', '\0'
};
char strSorted[] = { '\0' };
int x = 0;
printf("\nThe list of states before being sorted in alphabetical order: %s", strStates);
for (x = 0; x < 7; x++) {
printf("\n%s", strStates);
}
sort(strStates[x], strSorted[x]);
printf("\nThe list of states sorted alphabetically are: ");
for (x = 0; x < 4; x++) {
printf("\n%s", strStates[x]);
}
return 0;
}
char sort(char string1[], char string2[]) {
int x, y = 0;
for (x = 0; x < 3; x++) {
for (y = 1; y < 4; y++) {
if (strcmp(string1[x], string1[y]) > 0) {
strcpy(string2[y], string1[x]);
strcpy(string1[x], string1[y]);
strcpy(string[y], string2[y]);
}
}
}
}
</code></pre>
|
[
{
"answer_id": 74603480,
"author": "kanuos",
"author_id": 10822859,
"author_profile": "https://Stackoverflow.com/users/10822859",
"pm_score": 0,
"selected": false,
"text": "@font-face css"
},
{
"answer_id": 74603777,
"author": "kissu",
"author_id": 8816585,
"author_profile": "https://Stackoverflow.com/users/8816585",
"pm_score": 2,
"selected": true,
"text": "Nunito @font-face {\n font-display: swap;\n font-family: 'Nunito';\n font-style: normal;\n font-weight: 400;\n src: local('Nunito Regular'), local('Nunito-Regular'),\n url('~assets/fonts/Nunito-400-cyrillic-ext1.woff2') format('woff2');\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488233/"
] |
74,603,443
|
<p>In the browser returns the input in the list when I placed, but in the same second disappears. Until the end of the function the array is fulfill, when refresh the response the array "does" is empty.
Something is wrong and the state is not storing.</p>
<pre><code>import React,{useState} from 'react';
import './App.css';
function App() {
const [text1,setText1] = useState('');
const [does,setDoes] = useState([]);
function addTodo(){
return setDoes([...does,text1]);
}
return (
<div>
<h1>To do List!</h1>
<form onSubmit={addTodo}>
<input type="text" name='text1' id='text1' placeholder='To do' onChange={(e)=>setText1(e.target.value)}/>
<button type="submit" className="submitButton">Add</button>
</form>
<ul className='todoo'>
{does.map(item => <li key={item.toString()}>{item}</li>)}
</ul>
</div>
);
}
export default App;
</code></pre>
<p>I expect to storage the tasks...</p>
|
[
{
"answer_id": 74603840,
"author": "Dream Bold",
"author_id": 12743692,
"author_profile": "https://Stackoverflow.com/users/12743692",
"pm_score": 1,
"selected": true,
"text": "div ...\n <h1>To do List!</h1>\n <div>\n <input\n type=\"text\"\n name=\"text1\"\n id=\"text1\"\n placeholder=\"To do\"\n onChange={(e) => setText1(e.target.value)}\n />\n <button type=\"submit\" className=\"submitButton\" onClick={addTodo}>\n Add\n </button>\n </div>\n \n...\n"
},
{
"answer_id": 74603895,
"author": "Mario",
"author_id": 11169942,
"author_profile": "https://Stackoverflow.com/users/11169942",
"pm_score": 1,
"selected": false,
"text": "e.preventDefault() function App() {\n const [text1, setText1] = useState(\"\");\n const [does, setDoes] = useState([]);\n\n const addTodo = (e) => {\n e.preventDefault(); \n return setDoes([...does, text1]);\n };\n\n return (\n <div>\n <h1>To do List!</h1>\n <form onSubmit={(e) => addTodo(e)}>\n <input\n type=\"text\"\n name=\"text1\"\n id=\"text1\"\n placeholder=\"To do\"\n onChange={(e) => setText1(e.target.value)}\n />\n <button\n type=\"submit\"\n className=\"submitButton\"\n >\n Add\n </button>\n </form>\n\n <ul className=\"todoo\">\n {does.map((item) => (\n <li key={item.toString()}>{item}</li>\n ))}\n </ul>\n </div>\n );\n}\nexport default App;\n localStorage"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20531893/"
] |
74,603,450
|
<p>I am working on an application to predict a disease from it's symptoms, I have some trouble making a dataset.
If someone has a dataset on this, please link it to drive and share it here.
Also I have a question on a good model for this(sklearn only). I am currently using decision tree classifier as my model for the project. Give suggestions if you have any.
Thank you for reading.
EDIT: Got the solution</p>
|
[
{
"answer_id": 74603840,
"author": "Dream Bold",
"author_id": 12743692,
"author_profile": "https://Stackoverflow.com/users/12743692",
"pm_score": 1,
"selected": true,
"text": "div ...\n <h1>To do List!</h1>\n <div>\n <input\n type=\"text\"\n name=\"text1\"\n id=\"text1\"\n placeholder=\"To do\"\n onChange={(e) => setText1(e.target.value)}\n />\n <button type=\"submit\" className=\"submitButton\" onClick={addTodo}>\n Add\n </button>\n </div>\n \n...\n"
},
{
"answer_id": 74603895,
"author": "Mario",
"author_id": 11169942,
"author_profile": "https://Stackoverflow.com/users/11169942",
"pm_score": 1,
"selected": false,
"text": "e.preventDefault() function App() {\n const [text1, setText1] = useState(\"\");\n const [does, setDoes] = useState([]);\n\n const addTodo = (e) => {\n e.preventDefault(); \n return setDoes([...does, text1]);\n };\n\n return (\n <div>\n <h1>To do List!</h1>\n <form onSubmit={(e) => addTodo(e)}>\n <input\n type=\"text\"\n name=\"text1\"\n id=\"text1\"\n placeholder=\"To do\"\n onChange={(e) => setText1(e.target.value)}\n />\n <button\n type=\"submit\"\n className=\"submitButton\"\n >\n Add\n </button>\n </form>\n\n <ul className=\"todoo\">\n {does.map((item) => (\n <li key={item.toString()}>{item}</li>\n ))}\n </ul>\n </div>\n );\n}\nexport default App;\n localStorage"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625247/"
] |
74,603,466
|
<p>I'm trying to make a if-else statement that if user put time which have past, it will alert the user that the time has past. And I also unable to set the timedialogpicker to the current time when the user open it. Thanks in advance.</p>
<p>The code:</p>
<pre><code>button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar timeNow = Calendar.getInstance();
timePickerDialog = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
int currHour = calendar.get(Calendar.HOUR_OF_DAY);
int currMin = calendar.get(Calendar.MINUTE);
Time currTime = new Time(currHour, currMin); //This part display error
if (currTime.getTimeInMillis() >= timeNow.getTimeInMillis()) { //This part display error
//it's after current
int hour = hourOfDay % 12;
} else {
//it's before current'
Toast.makeText(getApplicationContext(), "Invalid Time", Toast.LENGTH_LONG).show();
}
time = "";
time = hourOfDay+":"+minute;
Userbook book = new Userbook(temp, time);
db.collection("Booking").add(book).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(MainActivity.this, "Note saved", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
});
Toast.makeText(MainActivity.this, "Time is "+currHour+":"+currMin, Toast.LENGTH_SHORT).show();
}
},timeNow.get(Calendar.HOUR_OF_DAY), timeNow.get(Calendar.MINUTE),false);
timePickerDialog.show();
}
});
</code></pre>
|
[
{
"answer_id": 74604630,
"author": "Devin Sag",
"author_id": 20388932,
"author_profile": "https://Stackoverflow.com/users/20388932",
"pm_score": 1,
"selected": false,
"text": " Calendar timeNow = Calendar.getInstance();\n Date curDate = new Date();\n timeNow.setTime(curDate);\n timeNow.set(Calendar.HOUR_OF_DAY, hourOfDay);\n timeNow.set(Calendar.MINUTE, minute);\n // If you want to warn on dates being equal to current time, then \n // switch the conditional to be greater than or equal to 0, instead\n // of greater than 0. \n if (curDate.compareTo(timeNow.getTime()) > 0) {\n //it's after current\n int hour = hourOfDay % 12;\n }\n ...\n ...\n"
},
{
"answer_id": 74606418,
"author": "Arvind Kumar Avinash",
"author_id": 10819573,
"author_profile": "https://Stackoverflow.com/users/10819573",
"pm_score": 3,
"selected": true,
"text": "! LocalTime.of( 10 , 20 ).isBefore( LocalTime.now() ) LocalTime#isBefore java.time LocalTime#of(int hour, int minute) LocalTime hour minute LocalTime#now LocalTime#isBefore import java.time.LocalTime;\n\npublic class Main {\n public static void main(String[] args) {\n LocalTime now = LocalTime.now();\n\n // Sample hour and minute values\n int hour = 10;\n int minute = 20;\n\n LocalTime givenTime = LocalTime.of(hour, minute);\n\n System.out.println(!givenTime.isBefore(now));\n }\n}\n false\n !givenTime.isBefore(now) givenTime now"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19485355/"
] |
74,603,467
|
<p>I would like to add a <code>Product</code> to a <code>Shop</code>'s container but i can't and i don't understand why because my <code>Shop</code> is var and not let.
My goal is to put a <code>Product</code> into a <code>Shop</code> like this:
input Shop(name: "Apple Store", container: [])
output: Shop(name: "Apple Store", container: [Product(name: "Cheese")])</p>
<p>Here is My code:</p>
<pre><code>import SwiftUI
struct Shop: Identifiable {
let name: String
var container: [Product]
var id = UUID()
}
struct Product: Identifiable {
let name: String
var id = UUID()
}
struct ContentView: View {
@State var shops: [Shop] = [
Shop(name: "Apple Store", container: []),
Shop(name: "StopShop", container: [Product(name: "milk")])
]
var body: some View {
NavigationView {
List {
ForEach(shops) { shop in
NavigationLink(shop.name, destination: {
List {
ForEach(shop.container) { product in
Text(product.name)
}
}
.navigationBarTitle(shop.name)
.navigationBarItems(trailing: Button {
shop.container.append(Product(name: "Cheese"))
} label: {
Text("add").bold()
})
})
}
}
.navigationBarTitle("Shops")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
</code></pre>
<p>I have tried by append or insert it and i expected it to work but it didn't. :(</p>
|
[
{
"answer_id": 74603997,
"author": "Jorge Poveda",
"author_id": 18557672,
"author_profile": "https://Stackoverflow.com/users/18557672",
"pm_score": 1,
"selected": false,
"text": "@State var shops: [Shop]\n ForEach(shops) { shop in // shop here is a let\n ForEach(Array(shops.enumerated()), id: \\.offset) { index, element in\n // ...\n shops[index].container.append(Product(name: \"Cheese\"))\n}\n"
},
{
"answer_id": 74604136,
"author": "vadian",
"author_id": 5044042,
"author_profile": "https://Stackoverflow.com/users/5044042",
"pm_score": 1,
"selected": true,
"text": "Shop shops func appendProduct(_ product: Product, to shop: Shop) {\n guard let index = shops.firstIndex(where: {$0.id == shop.id}) else { return }\n shops[index].container.append(product)\n}\n .navigationBarItems(trailing: Button {\n appendProduct(Product(name: \"Cheese\"), to: shop)\n} label: {\n Text(\"add\").bold()\n})\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20558077/"
] |
74,603,493
|
<p>I have the following (atom) input component Element UI (Element Plus for vue 3) as base component.</p>
<p><code>atom/input/index.vue</code></p>
<pre><code><template>
<el-form-item :label="label">
<ElInput
:value="modelValue"
@input="$emit('update:modelValue', handleInputChange($event))"
>
<template v-if="prepend" #prepend>Http://</template>
<template v-if="append" #append>.com</template>
</ElInput>
</el-form-item>
</template>
<script setup lang="ts">
import { ElInput, ElFormItem } from "element-plus"
interface IInput {
label: string
modelValue: any
}
const { label, modelValue } = defineProps<IInput>()
const handleInputChange = (event: Event) => {
console.log(event)
return (event.target as HTMLInputElement).value
}
</script>
</code></pre>
<p>In my home component:</p>
<p><code>components/home.vue</code></p>
<pre><code><template>
<Input :label="'Book title'" v-model="title" />
<br/>
<h1>{{title}}</h1>
</template>
<script setup lang="ts">
import { ref } from "vue"
import Input from "./atom/input/index.vue"
const title = ref<string>("")
</script>
</code></pre>
<p>With the above code setup the component is displayed in correct form with its label.</p>
<p>But when I start typing in the input component I get the following error in my console.</p>
<blockquote>
<p>Uncaught (in promise) TypeError: Cannot read properties of undefined
(reading 'value')</p>
</blockquote>
<p>I've also logged the event in the console and it is returning the characters that I've typed.</p>
<p>Additionally I get error message of:</p>
<blockquote>
<p>Argument of type 'string' is not assignable to parameter of type
'Event'.</p>
</blockquote>
<p>In my code line : <code>@input="$emit('update:modelValue', handleInputChange($event))"</code></p>
<p>Which I was able to remove my typecasting: <code>handleInputChange(<Event | unknown>$event)</code></p>
<p>I also tried creating reusable input component with html input tag with same value and emit as above and it worked without any error.</p>
<p>Can anyone help me figure out what I'm missing here ?</p>
<p><strong>Update:</strong></p>
<p>As suggestion by <a href="https://stackoverflow.com/users/4254681/duannx">Duannx</a> I changed my return of the function:</p>
<pre><code> const handleInputChange = (event: any) => {
return event
}
</code></pre>
<p>But now when I type in the input field the first character is replaced by second character, second character is replaced by third and so on.</p>
<p>Here is the reproduction of the issue in element ui playground:</p>
<p><a href="https://element-plus.run/#eyJBcHAudnVlIjoiPHNjcmlwdCBzZXR1cCBsYW5nPVwidHNcIj5cbmltcG9ydCB7IHJlZiwgdmVyc2lvbiBhcyB2dWVWZXJzaW9uIH0gZnJvbSAndnVlJ1xuaW1wb3J0IHsgdmVyc2lvbiBhcyBFcFZlcnNpb24gfSBmcm9tICdlbGVtZW50LXBsdXMnXG5pbXBvcnQgeyBFbGVtZW50UGx1cyB9IGZyb20gJ0BlbGVtZW50LXBsdXMvaWNvbnMtdnVlJ1xuaW1wb3J0IEJhc2VJbnB1dCBmcm9tIFwiLi9CYXNlSW5wdXQudnVlXCJcbmltcG9ydCBOb3JtYWxJbnB1dCBmcm9tIFwiLi9Ob3JtYWxJbnB1dC52dWVcIlxuY29uc3QgbXNnID0gcmVmKCdIb3VzZSBvZiB0aGUgZHJhZ29ucyEnKVxuY29uc3QgYXV0aG9yID0gcmVmKCdHZW9yZ2UgUlIgTWFydGluJylcbjwvc2NyaXB0PlxuXG48dGVtcGxhdGU+XG4gIDxoMT57eyBtc2cgfX08L2gxPlxuICA8QmFzZUlucHV0IDpsYWJlbD1cImBCb29rIFRpdGxlYFwiIHYtbW9kZWw9XCJtc2dcIiAvPlxuICA8YnIvPlxuICA8aDE+e3thdXRob3J9fVxuICA8L2gxPlxuICA8Tm9ybWFsSW5wdXQgOmxhYmVsPVwiYEF1dGhvcmBcIiB2LW1vZGVsPVwiYXV0aG9yXCIvPlxuPC90ZW1wbGF0ZT5cbiIsImltcG9ydF9tYXAuanNvbiI6IntcbiAgXCJpbXBvcnRzXCI6IHt9XG59IiwiTm9ybWFsSW5wdXQudnVlIjoiPHRlbXBsYXRlPlxuICA8bGFiZWwgZm9yPVwiXCI+e3sgbGFiZWwgfX08L2xhYmVsPlxuICA8YnIvPlxuICA8aW5wdXRcbiAgICA6dmFsdWU9XCJtb2RlbFZhbHVlXCJcbiAgICBAaW5wdXQ9XCIkZW1pdCgndXBkYXRlOm1vZGVsVmFsdWUnLCBoYW5kbGVJbnB1dENoYW5nZSgkZXZlbnQpKVwiXG4gIC8+XG48L3RlbXBsYXRlPlxuPHNjcmlwdCBzZXR1cCBsYW5nPVwidHNcIj5cbiAgaW50ZXJmYWNlIElJbnB1dCB7XG4gICAgbGFiZWw6IHN0cmluZ1xuICAgIG1vZGVsVmFsdWU6IGFueVxuICB9XG4gIGNvbnN0IHsgbGFiZWwsIG1vZGVsVmFsdWUgfSA9IGRlZmluZVByb3BzPElJbnB1dD4oKVxuICBjb25zdCBoYW5kbGVJbnB1dENoYW5nZSA9IChldmVudDogRXZlbnQpID0+IHtcbiAgICByZXR1cm4gKGV2ZW50LnRhcmdldCBhcyBIVE1MSW5wdXRFbGVtZW50KS52YWx1ZVxuICB9XG48L3NjcmlwdD5cbiIsIkJhc2VJbnB1dC52dWUiOiI8dGVtcGxhdGU+XG4gIDxlbC1mb3JtLWl0ZW0gOmxhYmVsPVwibGFiZWxcIj5cbiAgICA8RWxJbnB1dFxuICAgICAgOmF1dG9mb2N1cz1cInRydWVcIlxuICAgICAgOnR5cGU9XCJ0eXBlXCJcbiAgICAgIDpwbGFjZWhvbGRlcj1cInBsYWNlaG9sZGVyXCJcbiAgICAgIDpzaG93LXdvcmQtbGltaXQ9XCJzaG93V29yZExpbWl0XCJcbiAgICAgIDpjbGVhcmFibGU9XCJjbGVhcmFibGVcIlxuICAgICAgOnNob3ctcGFzc3dvcmQ9XCJzaG93UGFzc3dvcmRcIlxuICAgICAgOnN1ZmZpeC1pY29uPVwic3VmZml4SWNvblwiXG4gICAgICA6cHJlZml4LWljb249XCJwcmVmaXhJY29uXCJcbiAgICAgIDpzaXplPVwic2l6ZVwiXG4gICAgICA6bWF4LWxlbmd0aD1cIm1heExlbmd0aFwiXG4gICAgICA6dmFsdWU9XCJtb2RlbFZhbHVlXCJcbiAgICAgIEBpbnB1dD1cIiRlbWl0KCd1cGRhdGU6bW9kZWxWYWx1ZScsIGhhbmRsZUlucHV0Q2hhbmdlKCRldmVudCkpXCJcbiAgICA+XG4gICAgICA8dGVtcGxhdGUgdi1pZj1cInByZXBlbmRcIiAjcHJlcGVuZD5IdHRwOi8vPC90ZW1wbGF0ZT5cbiAgICAgIDx0ZW1wbGF0ZSB2LWlmPVwiYXBwZW5kXCIgI2FwcGVuZD4uY29tPC90ZW1wbGF0ZT5cbiAgICA8L0VsSW5wdXQ+XG4gIDwvZWwtZm9ybS1pdGVtPlxuPC90ZW1wbGF0ZT5cbjxzY3JpcHQgc2V0dXAgbGFuZz1cInRzXCI+XG4gIGltcG9ydCB7IEVsSW5wdXQsIEVsRm9ybUl0ZW0gfSBmcm9tIFwiZWxlbWVudC1wbHVzXCJcbiAgaW50ZXJmYWNlIElJbnB1dCB7XG4gICAgbGFiZWw6IHN0cmluZ1xuICAgIHR5cGU/OiBzdHJpbmdcbiAgICBwbGFjZWhvbGRlcj86IHN0cmluZ1xuICAgIG1heExlbmd0aD86IG51bWJlclxuICAgIHNob3dXb3JkTGltaXQ/OiBib29sZWFuXG4gICAgY2xlYXJhYmxlPzogYm9vbGVhblxuICAgIHNob3dQYXNzd29yZD86IGJvb2xlYW5cbiAgICBzdWZmaXhJY29uPzogYW55XG4gICAgcHJlZml4SWNvbj86IGFueVxuICAgIHNpemU/OiBzdHJpbmdcbiAgICBwcmVwZW5kPzogYW55XG4gICAgYXBwZW5kPzogYW55XG4gICAgbW9kZWxWYWx1ZTogYW55XG4gIH1cbiAgY29uc3Qge1xuICAgIGxhYmVsLFxuICAgIHR5cGUsXG4gICAgcGxhY2Vob2xkZXIsXG4gICAgbWF4TGVuZ3RoLFxuICAgIHNob3dXb3JkTGltaXQsXG4gICAgY2xlYXJhYmxlLFxuICAgIHNob3dQYXNzd29yZCxcbiAgICBzdWZmaXhJY29uLFxuICAgIHByZWZpeEljb24sXG4gICAgc2l6ZSxcbiAgICBwcmVwZW5kLFxuICAgIGFwcGVuZCxcbiAgICBtb2RlbFZhbHVlLFxuICB9ID0gZGVmaW5lUHJvcHM8SUlucHV0PigpXG5cbiAgY29uc3QgaGFuZGxlSW5wdXRDaGFuZ2UgPSAodmFsdWU6IGFueSkgPT4ge1xuICAgIHJldHVybiB2YWx1ZVxuICB9XG5cbjwvc2NyaXB0PlxuIiwiX28iOnt9fQ==" rel="nofollow noreferrer">Demo url</a></p>
|
[
{
"answer_id": 74603997,
"author": "Jorge Poveda",
"author_id": 18557672,
"author_profile": "https://Stackoverflow.com/users/18557672",
"pm_score": 1,
"selected": false,
"text": "@State var shops: [Shop]\n ForEach(shops) { shop in // shop here is a let\n ForEach(Array(shops.enumerated()), id: \\.offset) { index, element in\n // ...\n shops[index].container.append(Product(name: \"Cheese\"))\n}\n"
},
{
"answer_id": 74604136,
"author": "vadian",
"author_id": 5044042,
"author_profile": "https://Stackoverflow.com/users/5044042",
"pm_score": 1,
"selected": true,
"text": "Shop shops func appendProduct(_ product: Product, to shop: Shop) {\n guard let index = shops.firstIndex(where: {$0.id == shop.id}) else { return }\n shops[index].container.append(product)\n}\n .navigationBarItems(trailing: Button {\n appendProduct(Product(name: \"Cheese\"), to: shop)\n} label: {\n Text(\"add\").bold()\n})\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7512296/"
] |
74,603,495
|
<p>I am trying to get elements from ng-content which is present in the same component, but I am unable to get them.</p>
<p>Component html</p>
<pre><code><div>
<ng-content #action></ng-content>
<app-comp2></app-comp2>
</div>
</code></pre>
<p>Component's .ts</p>
<pre><code>@ContentChildren('action') content:QueryList<ElementRef>;
</code></pre>
<p>I am always getting undefined. What could be the reason?</p>
|
[
{
"answer_id": 74603997,
"author": "Jorge Poveda",
"author_id": 18557672,
"author_profile": "https://Stackoverflow.com/users/18557672",
"pm_score": 1,
"selected": false,
"text": "@State var shops: [Shop]\n ForEach(shops) { shop in // shop here is a let\n ForEach(Array(shops.enumerated()), id: \\.offset) { index, element in\n // ...\n shops[index].container.append(Product(name: \"Cheese\"))\n}\n"
},
{
"answer_id": 74604136,
"author": "vadian",
"author_id": 5044042,
"author_profile": "https://Stackoverflow.com/users/5044042",
"pm_score": 1,
"selected": true,
"text": "Shop shops func appendProduct(_ product: Product, to shop: Shop) {\n guard let index = shops.firstIndex(where: {$0.id == shop.id}) else { return }\n shops[index].container.append(product)\n}\n .navigationBarItems(trailing: Button {\n appendProduct(Product(name: \"Cheese\"), to: shop)\n} label: {\n Text(\"add\").bold()\n})\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11423881/"
] |
74,603,507
|
<p>I'm trying to parse lyrics site and I need to collect song's lyrics. I have issues with my output</p>
<p>I need to have lyrics displayed as below <a href="https://i.stack.imgur.com/JB4zF.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I've figured out how to split text at uppercase, but there is one thing remains: the brackets are splitted unproperly, here's my code:</p>
<pre><code>import re
import requests
from bs4 import BeautifulSoup
r = requests.get('https://genius.com/Taylor-swift-lavender-haze-lyrics')
#print(r.status_code)
if r.status_code != 200:
print('Error')
soup = BeautifulSoup(r.content, 'lxml')
titles = soup.find_all('title')
titles = titles[0].text
titlist = titles.split('Lyrics | ')
titlist.pop(1)
titlist = titlist[0].replace("\xa0", " ")
print(titlist)
divs = soup.find_all('div', {'class' : 'Lyrics__Container-sc-1ynbvzw-6 YYrds'})
#print(divs[0].text)
lyrics = (divs[0].text)
res = re.findall(r'[A-Z][^A-Z]*', lyrics)
res_l = []
for el in res:
res_l.append(el + '\n')
print(el)
</code></pre>
<p>and output is snown on a screenshot. How do I fix it?<a href="https://i.stack.imgur.com/fmQhG.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>for those, who asked, added a full code</p>
|
[
{
"answer_id": 74603997,
"author": "Jorge Poveda",
"author_id": 18557672,
"author_profile": "https://Stackoverflow.com/users/18557672",
"pm_score": 1,
"selected": false,
"text": "@State var shops: [Shop]\n ForEach(shops) { shop in // shop here is a let\n ForEach(Array(shops.enumerated()), id: \\.offset) { index, element in\n // ...\n shops[index].container.append(Product(name: \"Cheese\"))\n}\n"
},
{
"answer_id": 74604136,
"author": "vadian",
"author_id": 5044042,
"author_profile": "https://Stackoverflow.com/users/5044042",
"pm_score": 1,
"selected": true,
"text": "Shop shops func appendProduct(_ product: Product, to shop: Shop) {\n guard let index = shops.firstIndex(where: {$0.id == shop.id}) else { return }\n shops[index].container.append(product)\n}\n .navigationBarItems(trailing: Button {\n appendProduct(Product(name: \"Cheese\"), to: shop)\n} label: {\n Text(\"add\").bold()\n})\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625309/"
] |
74,603,529
|
<p>I'm pulling a JSON file using js. But since I do this with a for loop, the server gives a 429 error. I looked for ways to slow the cycle. but I couldn't find a working solution.
I tried setTimeOut, I tried delay fetch. I guess it wasn't true.</p>
<pre><code> let koordinatlar = [];
for (let konumOlustur = 0; konumOlustur < 10; konumOlustur++) {
musteriAdres = encodeURIComponent(yesilListe[0][konumOlustur][5]+' '+yesilListe[0][konumOlustur][6]+' '+yesilListe[0][konumOlustur][7]+' '+yesilListe[0][konumOlustur][8]);
fetch(`https://api.tomtom.com/search/2/geocode/${musteriAdres}.json?key=APIKEY`)
.then((response) => response.json())
.then((data)=>
koordinatlar.push(
[data['results'][0]['position']['lon'],
data['results'][0]['position']['lat'],
yesilListe[0][konumOlustur][2]+' '+
yesilListe[0][konumOlustur][3],
yesilListe[0][konumOlustur][4],
yesilListe[0][konumOlustur][5]+' '+
yesilListe[0][konumOlustur][6]+' '+
yesilListe[0][konumOlustur][7]+' '+
yesilListe[0][konumOlustur][8]]))
.catch(function(){
console.log("hata")
});
}
console.log(koordinatlar);
</script>
</code></pre>
|
[
{
"answer_id": 74603997,
"author": "Jorge Poveda",
"author_id": 18557672,
"author_profile": "https://Stackoverflow.com/users/18557672",
"pm_score": 1,
"selected": false,
"text": "@State var shops: [Shop]\n ForEach(shops) { shop in // shop here is a let\n ForEach(Array(shops.enumerated()), id: \\.offset) { index, element in\n // ...\n shops[index].container.append(Product(name: \"Cheese\"))\n}\n"
},
{
"answer_id": 74604136,
"author": "vadian",
"author_id": 5044042,
"author_profile": "https://Stackoverflow.com/users/5044042",
"pm_score": 1,
"selected": true,
"text": "Shop shops func appendProduct(_ product: Product, to shop: Shop) {\n guard let index = shops.firstIndex(where: {$0.id == shop.id}) else { return }\n shops[index].container.append(product)\n}\n .navigationBarItems(trailing: Button {\n appendProduct(Product(name: \"Cheese\"), to: shop)\n} label: {\n Text(\"add\").bold()\n})\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18756115/"
] |
74,603,540
|
<p>I am transforming input XML to this output format:</p>
<pre><code><InvoiceTransmission xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="IATAFuelInvoiceStandardv2.0.2.xsd">
<InvoiceTransmissionHeader>
<InvoiceCreationDate>2020-07-23</InvoiceCreationDate>
<Version>2.0.2</Version>
</InvoiceTransmissionHeader>
.....
</InvoiceTransmission>
</code></pre>
<p>And I have problem with proper setup of root element
This is my XST but I am still receiving error.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">
<xsl:output method="xml" encoding="UTF-8" standalone="no"/>
<xsl:template match="/">
<!--<InvoiceTransmission xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="IATAFuelInvoiceStandardv2.0.2.xsd">-->
<InvoiceTransmission>
<xsl:element name="InvoiceTransmission">
<xsl:namespace name="xsi" select="'http://www.w3.org/2001/XMLSchema-instance'" />
<xsl:attribute name="xsi:noNamespaceSchemaLocation">
<xsl:value-of select="IATAFuelInvoiceStandardv2.0.2.xsd" />
</xsl:attribute>
</xsl:element>
<xsl:apply-templates select="SSC"/>
</InvoiceTransmission>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>And this is error which I receive:</p>
<pre><code>XTDE0860 Undeclared namespace prefix {xsi}
</code></pre>
|
[
{
"answer_id": 74603654,
"author": "Heiko Theißen",
"author_id": 16462950,
"author_profile": "https://Stackoverflow.com/users/16462950",
"pm_score": 2,
"selected": true,
"text": "xsl:namespace xmlns:xsi <xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n exclude-result-prefixes=\"xs xsi\" version=\"2.0\">\n <xsl:attribute name=\"xsi:noNamespaceSchemaLocation\">\n <xsl:value-of select=\"IATAFuelInvoiceStandardv2.0.2.xsd\" />\n</xsl:attribute>\n <xsl:attribute name=\"xsi:noNamespaceSchemaLocation\">IATAFuelInvoiceStandardv2.0.2.xsd</xsl:attribute>\n IATAFuelInvoiceStandardv2.0.2.xsd"
},
{
"answer_id": 74603829,
"author": "michael.hor257k",
"author_id": 3016153,
"author_profile": "https://Stackoverflow.com/users/3016153",
"pm_score": 0,
"selected": false,
"text": "<xsl:template match=\"/\"> \n <InvoiceTransmission xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"IATAFuelInvoiceStandardv2.0.2.xsd\">\n <!-- the rest of the code -->\n </InvoiceTransmission>\n</xsl:template>\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1617437/"
] |
74,603,550
|
<p>Why is this raising an AttributeError?</p>
<pre><code>class A:
def f(self):
print(super().__dict__)
A().f() # raises AttributeError: 'super' object has no attribute '__dict__'
</code></pre>
|
[
{
"answer_id": 74603994,
"author": "Paweł Rubin",
"author_id": 8091093,
"author_profile": "https://Stackoverflow.com/users/8091093",
"pm_score": 0,
"selected": false,
"text": "super() object object __dict__ object().__dict__ # raises AttributeError\n __dict__ A class Foo:\n pass\n\n\nclass A(Foo):\n def f(self):\n print(super().__dict__)\n\nA().f() # prints '{}'\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10680954/"
] |
74,603,557
|
<p>We figured out finding way to list only B2C users by using filter. We tried to filter users with their B2C domain name like</p>
<pre><code>GET https://graph.microsoft.com/v1.0/users?$filter=endswith(mail,'@b2ctenant.onmicrosoft.com')
</code></pre>
<p>But this is not working out, tried different ways but same error</p>
<pre><code>{
"error": {
"code": "Request_UnsupportedQuery",
"message": "Unsupported Query.",
"innerError": {
"date": "2022-11-28T15:47:46",
"request-id": "4171772d-05f8-4f97-97f9-f0965b3f46d3",
"client-request-id": "d8a4aee6-4ba1-4f92-a26d-2b7bbbd54520"
}
}
}
</code></pre>
<p>Along with the list of B2C users, we want to get their count. There is no proper documentation regarding this.</p>
|
[
{
"answer_id": 74609631,
"author": "Sridevi",
"author_id": 18043665,
"author_profile": "https://Stackoverflow.com/users/18043665",
"pm_score": 3,
"selected": true,
"text": "GET https://graph.microsoft.com/v1.0/users?$filter=endswith(mail,'@b2ctenant.onmicrosoft.com')\n UserPrincipalName GET https://graph.microsoft.com/v1.0/users?$select=displayName,userPrincipalName\n $count GET https://graph.microsoft.com/v1.0/users?$filter=endswith(mail,'@tenant.onmicrosoft.com')&$orderby=userPrincipalName&$count=true\nConsistencyLevel: eventual\n"
},
{
"answer_id": 74610232,
"author": "user2250152",
"author_id": 2250152,
"author_profile": "https://Stackoverflow.com/users/2250152",
"pm_score": 1,
"selected": false,
"text": "endsWith mail otherMails userPrincipalName proxyAddresses ConsistencyLevel eventual $count true ConsistencyLevel $count $count=true @odata.count GET https://graph.microsoft.com/v1.0/users?$filter=endswith(mail,'@b2ctenant.onmicrosoft.com')&$count=true\nConsistencyLevel: eventual\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20600454/"
] |
74,603,571
|
<p>I am trying to add a remote address to a branch, but when trying to fetch, or do <code>git ls-remote</code> , I get Permission denied:</p>
<pre><code>myuser@22.22.22.222: Permission denied (publickey).
fatal: Could not read from remote repository.
</code></pre>
<p>So I'm wondering how to troubleshoot this?
I tried using regular command line and Git bash.</p>
<p>It worked when I tried a different repo and server, connecting with root user in the same way:</p>
<pre><code>git remote add prod ssh://root@11.111.11.11:22/myfolder/gittest.git
</code></pre>
<p>The successful message is: <code>From ssh://root@22.222.22.22:22/myfolder/gittest.git</code></p>
<p>On the problematic server the user has access and I can ssh with no problem , I specify a key at the same time:</p>
<pre><code>ssh -i .ssh/mykey.pem myuser@22.22.22.222
</code></pre>
<p>When I try to add the remote to the server, I do this:</p>
<pre><code>git remote add prod ssh://myuser@22.222.22.22:22/myfolder/gittest.git
</code></pre>
<p>But it needs the <code>.pem</code> file , so I've specified it in <code>.ssh/config</code>:</p>
<pre><code>Host theserver
HostName 22.22.22.222
IdentityFile ~/.ssh/myfile.pem
Port 22
</code></pre>
<p>How can I verify that the <code>.pem</code> file being read? If I remove the text from <code>config</code>, there is no error about "missing key" or anything?</p>
<p>The folder exists on the server: <code>/myfolder/gittest.git</code> (myfolder is at the root).
I also tried to a differemt location for the repo, moving it into a sub directory to the user. But it's the same error.</p>
<p>So how can I pinpoint the problem?</p>
<p>If it's of any use, when I check the user on the server: <code>id myuser</code> I get:</p>
<pre><code>uid=1000(myuser) gid=1000(myuser) groups=1000(myuser),4(adm),20(dialout),24(cdrom),
25(floppy),27(sudo),
29(audio),30(dip),33(www-data),44(video),46(plugdev),119(netdev),120(lxd)
</code></pre>
<p><strong>Update:</strong></p>
<p>I updated the config , adding <code>User</code> and <code>IdentitiesOnly</code>, and changed the remote address to:</p>
<pre><code>git remote add prod theserver:/myfolder/gittest.git
</code></pre>
<p><strong>Verify that config file is read</strong></p>
<p>If I remove the config file from <code>.ssh</code> folder and then do <code>git ls-remote</code> it says <code>Could not resolve hostname theserver</code> , so that means that it is being found when it's in <code>.ssh</code>.</p>
<p><strong>Verify connection</strong></p>
<p>On my other <em>working</em> example, if I remove the key from .ssh folder and do <code>git ls-remote</code>, it says <code>The authenticity of host '11.111.11.11' can't be established.</code> (and so on) - so that seems to verify that I have established a connection but have not been authenticated.</p>
<p>But on the problem server, <code>git ls-remote</code> only gives:</p>
<pre><code>ssh: connect to host 22.22.22.222 port 22: Connection timed out
fatal: Could not read from remote repository.
</code></pre>
<p>This is the same if I change the IP in config to something completely wrong.
So that would suggest that it's not related to the key? I'm not sure it connects to the IP correctly.
But I do get access using normal ssh.</p>
<p><strong>Update: Solved</strong></p>
<p>My odd case had to do with VPN. I had to activate the VPN because that's how the SSH and the server required.
Then it worked. (using this way of connecting with config: <code>git remote add prod theserver:/myfolder/gittest.git</code> )</p>
|
[
{
"answer_id": 74604410,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 2,
"selected": true,
"text": "theserver Host theserver\n User myuser\n HostName 22.22.22.222\n IdentityFile ~/.ssh/myfile.pem\n Port 22\n git git remote add prod theserver:myfolder/gittest.git\n theserver Host ssh://myuser@22.222.22.22:22/myfolder/gittest.git Host"
},
{
"answer_id": 74604453,
"author": "Evgeny",
"author_id": 7309962,
"author_profile": "https://Stackoverflow.com/users/7309962",
"pm_score": 0,
"selected": false,
"text": "IdentitiesOnly yes .ssh/config Host theserver\n HostName 22.22.22.222\n IdentityFile ~/.ssh/myfile.pem\n Port 22\n IdentitiesOnly yes\n ~/.ssh/id_rsa"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4245985/"
] |
74,603,582
|
<p>I have a web page where I show list of strings (strings are fetched from API call). They are presented as select/option tags and I need to show ALL options (they should not be hidden). To make it possible I specify <code>size</code> attribute in select tag. Here's the code:</p>
<p>html:</p>
<pre><code><select size="2">
<option value="1">1</option>
<option value="2">2</option>
</select>
</code></pre>
<p>css:</p>
<pre><code> select {
overflow: auto;
height: auto;
background-color: #08112d;
max-height: 300px;
}
option {
font-size: 16px;
color: #fff;
padding: 1rem;
}
</code></pre>
<p><a href="https://jsfiddle.net/advzjh1m/" rel="nofollow noreferrer">example on fiddle which works</a></p>
<p><a href="https://i.stack.imgur.com/QW7pz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QW7pz.png" alt="enter image description here" /></a></p>
<p><strong>The problem</strong></p>
<p>If there's only one option in the list, then the styles are broken and select list requires a click to see options, which is something that I don't want. How to fix it?</p>
<p><a href="https://jsfiddle.net/advzjh1m/1/" rel="nofollow noreferrer">example on fiddle which has broken styles</a></p>
<p><a href="https://i.stack.imgur.com/FadKH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FadKH.png" alt="enter image description here" /></a></p>
<p><strong>P.S.</strong>
I need to use select/options tags as I need their behavior (like selectable options and possibility to choose options with arrow up button ⬆ and arrow down ⬇). So I cannot use other tags (unless you can suggest how to add such behavior then).</p>
|
[
{
"answer_id": 74603680,
"author": "Moussa Bistami",
"author_id": 15628525,
"author_profile": "https://Stackoverflow.com/users/15628525",
"pm_score": 2,
"selected": true,
"text": "<select size=\"1\">\n <option value=\"1\">1</option>\n</select>\n <select size=\"1\" multiple>\n <option value=\"1\">1</option>\n</select>\n"
},
{
"answer_id": 74603709,
"author": "Giorgi Shalamberidze",
"author_id": 20248276,
"author_profile": "https://Stackoverflow.com/users/20248276",
"pm_score": 0,
"selected": false,
"text": "<select size=\"1\" multiple>\n <option value=\"1\">1</option>\n </select>\n"
},
{
"answer_id": 74603781,
"author": "jjj",
"author_id": 13365797,
"author_profile": "https://Stackoverflow.com/users/13365797",
"pm_score": 1,
"selected": false,
"text": "size=\"1\" size=\"2\" select {\n overflow: auto;\n height: auto;\n background-color: #08112d;\n max-height: 300px;\n margin: 0;\n padding: 0;\n border: 0;\n }\nselect.single {\n overflow: hidden;\n background-color: #2d0811;\n min-width: 40px;\n max-height: 51px;\n }\noption {\n font-size: 16px;\n color: #fff;\n padding: 1rem;\n}\noption:hover {\n background-color: #6b7081;\n} <select size=\"2\" class=\"single\">\n <option value=\"1\" >1</option>\n</select>\n\n<select size=\"2\">\n <option value=\"1\">1</option>\n <option value=\"2\">2</option>\n</select>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6056624/"
] |
74,603,618
|
<p>I have one variable group in ADO library which store different paths and some other variables.</p>
<p>In my main "master" pipeline I use it as below:</p>
<pre><code>variables:
- group: myGroupName
- name: nameOfMyVariable(from variables group) or JustAnyName
- value: $[variables.nameOfMyVariable] or $[variables.JustAnyName]
</code></pre>
<p>then in job in the first Stage (for testing, there is only one stage and job for now) I'm trying to using template yaml:</p>
<pre><code>jobs:
- template: my-template.yaml
parameters:
path: $(nameOfMyVariable) or $(JustAnyName)
</code></pre>
<p>then in <strong>my-template.yaml</strong> I have this code:</p>
<pre><code>parameters:
- name: path
type: string
default: ''
jobs:
- job: BuildSomething
steps:
- task: CopyFiles@2
inputs:
Contents: |
${{ parameters.path }}
TargetFolder: '$Build.ArtifactStagingDirectory)'
....
</code></pre>
<p>Rest is not that important as it just can't find files to copy and when I try to print parameters.path with <strong>echo</strong> I get error :
<em>syntax error: invalid arithmetic operator(error token is ".nameOfMyVariable").</em></p>
<p>I do not know how to fix it so I can access variables from variable group in some of my templates. Do I need to use ##vso[task.setvariables] or something else?</p>
|
[
{
"answer_id": 74606600,
"author": "Kontekst",
"author_id": 6334351,
"author_profile": "https://Stackoverflow.com/users/6334351",
"pm_score": 1,
"selected": false,
"text": "variables:\n- group: myGroupName\n"
},
{
"answer_id": 74610283,
"author": "Ceeno Qi-MSFT",
"author_id": 18361074,
"author_profile": "https://Stackoverflow.com/users/18361074",
"pm_score": 0,
"selected": false,
"text": "trigger: \n- none \npool: \n vmImage: ubuntu-latest \n \n\nparameters: \n- name: pathmain \n displayName: Source Path \n type: string \n default: README.md \n values: \n - azure-pipelines.yml \n - README.md \njobs: \n - job: \n steps: \n - script: echo ${{ parameters.pathmain }} \n - template: test-template.yml \n parameters: \n path: ${{parameters.pathmain}}\n parameters:\n- name: path \n displayName: Source Path \n type: string \njobs: \n- job: BuildSomething \n steps: \n - task: CopyFiles@2 \n inputs: \n Contents: | \n ${{ parameters.path }} \n TargetFolder: '$Build.ArtifactStagingDirectory'\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2968396/"
] |
74,603,622
|
<p>I run two same code. But it shows different answer.</p>
<p>Code 1:</p>
<pre><code>#include<stdio.h>
int main(){
float far = 98.6;
printf("%f", (far-32)*5/9);
return 0;
}
</code></pre>
<p>Code 2:</p>
<pre><code>#include<stdio.h>
int main(){
float far = 98.6;
float cel;
cel = (far-32)*5/9;
printf("%f", cel);
return 0;
}
</code></pre>
<p>First code gives 36.99999 as output and second code gives 37.00000 as output.</p>
|
[
{
"answer_id": 74603690,
"author": "Some programmer dude",
"author_id": 440558,
"author_profile": "https://Stackoverflow.com/users/440558",
"pm_score": 1,
"selected": false,
"text": "printf printf float double double float printf double cel double"
},
{
"answer_id": 74604242,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 2,
"selected": false,
"text": "FLT_EVAL_METHOD printf(\"%d\\n\", FLT_EVAL_METHOD);\n printf(\"%f\", (far-32)*5/9); (far-32)*5/9 double float (far-32)*5/9); float double float double printf() far, cel, (far-32)*5/9 \"%a\" \"%.17g\" far float 0x1.8a6666p+6 98.599998474121094... double printf(\"%f\", (far-32)*5/9); double float cel = (far-32)*5/9; double float // float far = 98.6;\nfloat far = 98.6f;\n double float"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19630256/"
] |
74,603,624
|
<p>I've carried around a really useful JavaScript function for a while, not entirely sure of the origin (probably here on Stack Overflow) but it's certainly not something I've written as I know very little JS.</p>
<p>It basically reveals form sections based on the chosen select option. It works a charm when used once, however I'm now in a situation whereby I have a fairly complex form and need to use it multiple times. The obvious method is to copy\paste and simply rename each function thus making it unique. However, that's a lot of replicated code.</p>
<p>My issue is if I re-use it, the two select fields interfere with each other. I've tried seeing if I can lock it down or it isolate is using an ID but I'm struggling.</p>
<p>Minimum, reproducible example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var current;
function reveal(element) {
if (current !== undefined) {
var chosen = document.getElementById(current);
chosen.classList.remove("visible");
chosen.classList.add("hidden");
}
var fetchMe = element.options[element.selectedIndex].getAttribute('data-show');
if (fetchMe !== null) {
current = fetchMe;
var fetched = document.getElementById(fetchMe);
fetched.classList.remove("hidden");
fetched.classList.add("visible");
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden {
display: none;
}
.visible {
display: block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Knowledge</h2>
<select onchange="reveal(this)">
<option>Select...</option>
<option data-show="known">Known</option>
<option data-show="unknown">Unknown</option>
</select>
<div class="hidden" id="known">
<input type="text" name="known" value="Known">
</div>
<div class="hidden" id="unknown">
<input type="text" name="unknown" value="Unknown">
</div>
<h2>Superheroes</h2>
<select onchange="reveal(this)">
<option>Select...</option>
<option data-show="batman">Batman</option>
<option data-show="superman">Superman</option>
</select>
<div class="hidden" id="batman">
<input type="text" name="batman" value="Batman">
</div>
<div class="hidden" id="superman">
<input type="text" name="supermann" value="Superman">
</div></code></pre>
</div>
</div>
</p>
<p>Ideally I want to be ringfence it, or use an ID to limit it.</p>
<p>Also available as <a href="https://jsfiddle.net/morgyface/78tfuwjq/11/" rel="nofollow noreferrer">a Fiddle</a>.</p>
|
[
{
"answer_id": 74603814,
"author": "isherwood",
"author_id": 1264804,
"author_profile": "https://Stackoverflow.com/users/1264804",
"pm_score": 1,
"selected": false,
"text": "function reveal() {\n // hide all\n document.querySelectorAll('.hidden').forEach(el => {\n el.style.display = 'none';\n });\n\n // show for each select\n document.querySelectorAll('select').forEach(el => {\n const selectedVal = el.selectedOptions[0].dataset.show;\n\n if (selectedVal) {\n document.getElementById(selectedVal).style.display = 'block';\n }\n });\n}\n\ndocument.querySelectorAll('select.special').forEach(el => {\n el.addEventListener('change', reveal);\n}); .hidden {\n display: none;\n} <h2>Knowledge</h2>\n\n<select class=\"special\">\n <option>Select...</option>\n <option data-show=\"known\">Known</option>\n <option data-show=\"unknown\">Unknown</option>\n</select>\n\n<div class=\"hidden\" id=\"known\">\n <input type=\"text\" name=\"known\" value=\"Known\">\n</div>\n\n<div class=\"hidden\" id=\"unknown\">\n <input type=\"text\" name=\"unknown\" value=\"Unknown\">\n</div>\n\n<h2>Superheroes</h2>\n\n<select class=\"special\">\n <option>Select...</option>\n <option data-show=\"batman\">Batman</option>\n <option data-show=\"superman\">Superman</option>\n</select>\n\n<div class=\"hidden\" id=\"batman\">\n <input type=\"text\" name=\"batman\" value=\"Batman\">\n</div>\n\n<div class=\"hidden\" id=\"superman\">\n <input type=\"text\" name=\"supermann\" value=\"Superman\">\n</div>"
},
{
"answer_id": 74603889,
"author": "Hedi Zitouni",
"author_id": 12285347,
"author_profile": "https://Stackoverflow.com/users/12285347",
"pm_score": 3,
"selected": true,
"text": "var current = {};\n\nfunction reveal(element) {\n const idSelect = element.id\n if (current[idSelect] !== undefined) {\n var chosen = document.getElementById(current[idSelect]);\n chosen.classList.remove(\"visible\");\n chosen.classList.add(\"hidden\");\n }\n var fetchMe = element.options[element.selectedIndex].getAttribute('data-show');\n if (fetchMe !== null) {\n current[idSelect] = fetchMe;\n var fetched = document.getElementById(fetchMe);\n fetched.classList.remove(\"hidden\");\n fetched.classList.add(\"visible\");\n }\n} .hidden {\n display: none;\n}\n\n.visible {\n display: block;\n} <h2>Knowledge</h2>\n\n<select onchange=\"reveal(this)\" id=\"id1\">\n <option>Select...</option>\n <option data-show=\"known\">Known</option>\n <option data-show=\"unknown\">Unknown</option>\n</select>\n\n<div class=\"hidden\" id=\"known\">\n <input type=\"text\" name=\"known\" value=\"Known\">\n</div>\n\n<div class=\"hidden\" id=\"unknown\">\n <input type=\"text\" name=\"unknown\" value=\"Unknown\">\n</div>\n\n<h2>Superheroes</h2>\n\n<select onchange=\"reveal(this)\" id=\"id2\">\n <option>Select...</option>\n <option data-show=\"batman\">Batman</option>\n <option data-show=\"superman\">Superman</option>\n</select>\n\n<div class=\"hidden\" id=\"batman\">\n <input type=\"text\" name=\"batman\" value=\"Batman\">\n</div>\n\n<div class=\"hidden\" id=\"superman\">\n <input type=\"text\" name=\"supermann\" value=\"Superman\">\n</div>"
},
{
"answer_id": 74604046,
"author": "marzelin",
"author_id": 5664434,
"author_profile": "https://Stackoverflow.com/users/5664434",
"pm_score": 1,
"selected": false,
"text": "select function reveal(element) {\n var options = element.options;\n for (var i = 0; i < options.length; i++) {\n var option = options[i].getAttribute('data-show');\n var chosen = option && document.getElementById(option);\n if (chosen !== null) {\n if (i === element.selectedIndex) {\n chosen.classList.remove(\"hidden\");\n chosen.classList.add(\"visible\");\n } else {\n chosen.classList.remove(\"visible\");\n chosen.classList.add(\"hidden\");\n }\n }\n }\n} .hidden {\n display: none;\n}\n\n.visible {\n display: block;\n} <h2>Knowledge</h2>\n\n<select onchange=\"reveal(this)\">\n <option>Select...</option>\n <option data-show=\"known\">Known</option>\n <option data-show=\"unknown\">Unknown</option>\n</select>\n\n<div class=\"hidden\" id=\"known\">\n <input type=\"text\" name=\"known\" value=\"Known\">\n</div>\n\n<div class=\"hidden\" id=\"unknown\">\n <input type=\"text\" name=\"unknown\" value=\"Unknown\">\n</div>\n\n<h2>Superheroes</h2>\n\n<select onchange=\"reveal(this)\">\n <option>Select...</option>\n <option data-show=\"batman\">Batman</option>\n <option data-show=\"superman\">Superman</option>\n</select>\n\n<div class=\"hidden\" id=\"batman\">\n <input type=\"text\" name=\"batman\" value=\"Batman\">\n</div>\n\n<div class=\"hidden\" id=\"superman\">\n <input type=\"text\" name=\"supermann\" value=\"Superman\">\n</div>"
},
{
"answer_id": 74604345,
"author": "Moob",
"author_id": 1921385,
"author_profile": "https://Stackoverflow.com/users/1921385",
"pm_score": 1,
"selected": false,
"text": "function reveal(selectElem) {\n //for each of this selectElem's options\n for (const option of selectElem) {\n var div = document.getElementById(option.getAttribute('data-show'));//find the corresponding div\n if(div!=undefined){//if it exists\n div.classList.add(\"hidden\");//hide it\n if(option.selected){//if its selected\n div.classList.remove(\"hidden\");//show it\n }\n }\n }\n} .hidden {\n display: none;\n} <h2>Knowledge</h2>\n\n<select onchange=\"reveal(this)\">\n <option>Select...</option>\n <option data-show=\"known\">Known</option>\n <option data-show=\"unknown\">Unknown</option>\n</select>\n\n<div class=\"hidden\" id=\"known\">\n <input type=\"text\" name=\"known\" value=\"Known\">\n</div>\n\n<div class=\"hidden\" id=\"unknown\">\n <input type=\"text\" name=\"unknown\" value=\"Unknown\">\n</div>\n\n<h2>Superheroes</h2>\n\n<select onchange=\"reveal(this)\">\n <option>Select...</option>\n <option data-show=\"batman\">Batman</option>\n <option data-show=\"superman\">Superman</option>\n</select>\n\n<div class=\"hidden\" id=\"batman\">\n <input type=\"text\" name=\"batman\" value=\"Batman\">\n</div>\n\n<div class=\"hidden\" id=\"superman\">\n <input type=\"text\" name=\"supermann\" value=\"Superman\">\n</div>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1641090/"
] |
74,603,629
|
<p>what is the problem, i just changed group name here, i get could not resolve for springsecuriy extras
i can't see why</p>
<pre><code>plugins {
id 'java'
id 'org.springframework.boot' version '3.0.0'
id 'io.spring.dependency-management' version '1.1.0'
id 'org.hibernate.orm' version '6.1.5.Final'
id 'org.graalvm.buildtools.native' version '0.9.18'
}
group = '*********'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
runtimeOnly 'org.mariadb.jdbc:mariadb-java-client'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
}
tasks.named('test') {
useJUnitPlatform()
}
hibernate {
enhancement {
lazyInitialization true
dirtyTracking true
associationManagement true
}
}
</code></pre>
<p>Could not resolve all files for configuration ':compileClasspath'. > Could not resolve org.thymeleaf.extras:thymeleaf-extras-springsecurity6:3.1.0.RELEASE. Required by: project : > Could not resolve org.thymeleaf.extras:thymeleaf-extras-springsecurity6:3.1.0.RELEASE. > Could not parse POM repo.maven.apache.org/maven2/org/thymeleaf/extras/… > Could not find org.springframework.security:spring-security-bom:6.0.0-RC2</p>
<p>I tried nothing it is made by spring initializer and boot version 3.0.0</p>
|
[
{
"answer_id": 74604641,
"author": "Raya",
"author_id": 19879549,
"author_profile": "https://Stackoverflow.com/users/19879549",
"pm_score": 1,
"selected": false,
"text": "repositories {\nmaven {\n url \"https://repo1.maven.org/maven2\"\n\n\n\n}\nmaven { url \"https://repo.spring.io/milestone\"\n content {\n // Thymeleaf uses 6.0.0-RC2 of Security's bom in its dependency management\n includeModule(\"org.springframework.security\", \"spring-security-bom\")\n }\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19879549/"
] |
74,603,631
|
<p>I have looked high and low (all over google/stackoverflow) for whatever could be wrong with my code... but nothing has turned out all day, so now I turn to writing a question myself:
I have two near identical functions in my service class, that make a post request to my api/backend (which in turn contains two near identical functions to receive said requests). One works flawlessly, and the other doesn't even seem to "fire" off in the frontend before generating "status: 400."
In my backend/api:</p>
<pre><code>[HttpPost("Patients/update")] //not working
public async Task<IActionResult> UpdatePatientAsync(Patient editedPatient)
{
try
{
_logger.LogDebug("APIController.UpdatePatientAsync() was called...");
var updated = await _dbHandler.UpdatePatientAsync(editedPatient);
if (updated)
{
return Ok(updated);
}
else
{
return BadRequest("Patient not updated!");
}
}
catch
{
throw;
}
}
</code></pre>
<pre><code>[HttpPost("Patients/comment/update")] //works GREAT!
public async Task<IActionResult> UpdatePatientCommentAsync(PatientComment editedComment)
{
try
{
_logger.LogDebug("APIController.UpdatePatientComment() was called...");
var updated = await _dbHandler.UpdatePatientCommentAsync(editedComment);
if (updated)
{
return Ok(editedComment);
}
else
{
return BadRequest("Comment not updated.");
}
}
catch
{
throw;
}
}
</code></pre>
<p>and in my service:</p>
<pre><code>updatePatient(editedPatient: Patient): Observable<Patient> { //not working at all
return this.http.post<Patient>(ConfigService.Config.apiBaseUrl + "/Patients/update", editedPatient).pipe(
catchError(this.rHndlr.handleError("updatePatient", this.updatedPatient))
)
}
</code></pre>
<pre><code>updatePatientComment(editedComment: PatientComment): Observable<PatientComment>{ //works (again) GREAT!
return this.http.post<PatientComment>(ConfigService.Config.apiBaseUrl + "/Patients/comment/update", editedComment).pipe(
catchError(this.rHndlr.handleError("updatePatientComment", this.updatedComment))
)
}
</code></pre>
<p>and how they're being called:</p>
<pre><code>updatePatient(updatedPatient: Patient): Promise<Patient> {
this.loading = {
loadingText: "Updating patient",
errorText: "Comment update failed, try something else.",
errorTextVisible: false
}
const promise = new Promise<Patient>((resolve, reject) => {
this.patientSvc.updatePatient(updatedPatient).subscribe({ //NOT EVEN CLOSE TO WORKING!!!
next: (data: Patient) => {
if (JSON.stringify(updatedPatient) === JSON.stringify(data)) {
console.log("Success updating patient!")
}
},
error: (err) => {
alert("Error updating patient data!\n" + JSON.stringify(err));
},
complete: () => {
resolve(this.patient);
}
})
});
return promise;
}
</code></pre>
<pre><code>updatePatientComment(editedComment: PatientComment): Promise<PatientComment> {
this.loading = {
loadingText: "Updating comment",
errorText: "Comment update failed, try something else.",
errorTextVisible: false
}
const promise = new Promise<PatientComment>((resolve, reject) => {
this.patientSvc.updatePatientComment(editedComment).subscribe({ //WORKING!!!
next: (data: PatientComment) => {
if(JSON.stringify(editedComment) === JSON.stringify(data)){
console.log("Success updating comment!");
this.commentChanged = false;
}
},
error: (err) => {
alert("Error updating comment! \n" + JSON.stringify(err));
},
complete: () => {
resolve(this.patientComment);
}
})
});
return promise;
}
</code></pre>
<p>And the two objects at hand:</p>
<pre><code>export interface Patient {
id: number;
socialSecurityNumber: string;
firstName: string;
lastName: string;
diagnosisId: number;
riskAssessmentId: number;
deceasedDate?: number;
commentId: number;
clinicId: number;
active: boolean;
staffId: number;
}
</code></pre>
<pre><code>export interface PatientComment {
id: number,
commentText: string,
commentDate: Date,
signature: string
}
</code></pre>
<p>(The objects being posted are the same object retreived from the corresponding classes' get-functions, with slightly altered lastName (for Patient) and commentText (for PatientComment))
I guess my question is: Am I missing something obvious? Is it the size of the Patient object that is too large, maybe? Again, it seems to me that the call doesn't even begin to process before I get status: 400 when updating Patient... and the post method in backend isn't even getting triggered - for PatientComment everything works, and I can trigger a breakpoint on its method in the backend whenever I call the endpoint. I've tested the api using both Swagger and Postman and they both seem to work there (though I am not super experienced using either of them, I guess, so I could be missing something). Any ideas?</p>
<p>I've triggered both api methods using Swagger/Postman, and I have debugged the process in VS Code - google'ing every part of the error message supplied from 'catchError' in the service class:</p>
<p>{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":400,"statusText":"Bad Request","url":"https://localhost:62006/api/Patients/update","ok":false,"name":"HttpErrorResponse","message":"Http failure response for https://localhost:62006/api/Patients/update: 400 Bad Request","error":{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-f1e88aa13075736f6590b352c4afe68f-64f8c787e1bbcc8b-00","errors":{"Staff":["The Staff field is required."],"Clinic":["The Clinic field is required."],"Diagnosis":["The Diagnosis field is required."],"PatientComment":["The PatientComment field is required."],"RiskAssessment":["The RiskAssessment field is required."]}}}</p>
<p>I have then applied too many solutions to even count (most from other threads on stackoverflow), even when it mearly resembled a smiliar issue.
The address to the api (localhost:whatever) is the same for both calls, and absolutely correct, and the endpoint has been copy/pasted from the backend just in case.
I've tried supplying preflight data ( {headers: {'Content-Type':"application/json"}} ), using .put instead of .post, changing endpoint address setup, other localhost ports, JSON.stringify(editedPatient) as body... but nothing has worked (obv). The only thing I have been able to gather, since the breakpoint in the backend never fires, is that it is a frontend related issue... but at this point, I am barely sure of my own name :P</p>
|
[
{
"answer_id": 74604641,
"author": "Raya",
"author_id": 19879549,
"author_profile": "https://Stackoverflow.com/users/19879549",
"pm_score": 1,
"selected": false,
"text": "repositories {\nmaven {\n url \"https://repo1.maven.org/maven2\"\n\n\n\n}\nmaven { url \"https://repo.spring.io/milestone\"\n content {\n // Thymeleaf uses 6.0.0-RC2 of Security's bom in its dependency management\n includeModule(\"org.springframework.security\", \"spring-security-bom\")\n }\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19887473/"
] |
74,603,678
|
<p>I'm learning SQL, I'm a bit complicated with a sentence that I have to do.</p>
<p>I need to get the accounts, which have these values in the same columns (KEY)</p>
<pre><code>1133-1-1, 7095-1-1
</code></pre>
<p>Code:</p>
<pre><code>SELECT cta
FROM cargos
WHERE key = '7095-1-1' AND key = '7021-233-1';
</code></pre>
<p>Expected result:</p>
<pre><code>cta: 192568210
</code></pre>
<p>The result of this query is 0, but If I make the query to get the keys of an account, it shows them to me:</p>
<pre><code>SELECT key
FROM cargos
WHERE cta = 192568210;
</code></pre>
<p>Result:</p>
<p><a href="https://i.stack.imgur.com/CeiZv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CeiZv.png" alt="enter image description here" /></a></p>
<p>I use Oracle 11g.</p>
|
[
{
"answer_id": 74604641,
"author": "Raya",
"author_id": 19879549,
"author_profile": "https://Stackoverflow.com/users/19879549",
"pm_score": 1,
"selected": false,
"text": "repositories {\nmaven {\n url \"https://repo1.maven.org/maven2\"\n\n\n\n}\nmaven { url \"https://repo.spring.io/milestone\"\n content {\n // Thymeleaf uses 6.0.0-RC2 of Security's bom in its dependency management\n includeModule(\"org.springframework.security\", \"spring-security-bom\")\n }\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16596581/"
] |
74,603,683
|
<p>I'm doing multiple fetchs with <code>Promise.all</code>. So I receive data like this :</p>
<pre><code>[
0: {
...
},
1: {
...
}
]
</code></pre>
<p>But I would like to name my Objects. So I can do <code>data.myObject</code> istead of <code>data[0]</code>.</p>
<p>I would like the index to be a string that I chose.
For example, i'd like to get :</p>
<pre><code>[
"home": {
...
},
"product": {
...
}
]
</code></pre>
<p>Is is possible ? Thanks</p>
|
[
{
"answer_id": 74603753,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 1,
"selected": false,
"text": "Promise.all const names = ['home', 'product'];\nconst promises = [fetchHome(), fetchProduct()];\nconst results = await Promise.all(promises);\nconst resultsByName = names.reduce((prev, curr, index) => {\n return {...prev, [curr]: results[index]};\n}, {});\n fetchHome() fetchProduct()"
},
{
"answer_id": 74603759,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 2,
"selected": false,
"text": "Promise.all Promise.all const data = await Promise.all([…, …]);\nconst home = data[0], product = data[1];\n const [home, product] = await Promise.all([…, …]);\n"
},
{
"answer_id": 74603762,
"author": "Zargold",
"author_id": 4142459,
"author_profile": "https://Stackoverflow.com/users/4142459",
"pm_score": 1,
"selected": false,
"text": "const [home, product, toolbar, nav] = await Promise.all([\ngetHome(), getProduct(), getToolBar(), getNav()\n]);\n const [home, product, toolbar, nav, ...otherPromises] = await Promise.all([\ngetHome(), getProduct(), getToolBar(), getNav(), getOtherThing1()\n]);\n// otherPromises will be an array that you'll have to access\n// with numeric keys as before:\n// eg. otherPromises[0] might be the first non-named promise\n// the result of getOtherThing1()\n"
},
{
"answer_id": 74603832,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": -1,
"selected": true,
"text": "const arr = [ { id: \"home\", val: \"val1\" }, { id: \"product\", val: \"val2\" }];\nconst convert = arr.reduce((a,b) => (a[b.id] ??= b,a),{});\nconsole.log(convert);\nconsole.log(convert.home);"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17978333/"
] |
74,603,703
|
<p>I am reading about Angular Interceptors, and I don’t get one thing. Is there a need to use HTTP interceptors in Angular, if let’s say I use CORS in a backend in NodeJS to connect back and front. Do we use interceptors in case where i don’t have custom backend, or is it optional.</p>
<p>I was reading, but as I don’t a single app completely finished, and I am trying to understand the difference between those two. I couldn’t find an adequate answer on this topic.</p>
|
[
{
"answer_id": 74603753,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 1,
"selected": false,
"text": "Promise.all const names = ['home', 'product'];\nconst promises = [fetchHome(), fetchProduct()];\nconst results = await Promise.all(promises);\nconst resultsByName = names.reduce((prev, curr, index) => {\n return {...prev, [curr]: results[index]};\n}, {});\n fetchHome() fetchProduct()"
},
{
"answer_id": 74603759,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 2,
"selected": false,
"text": "Promise.all Promise.all const data = await Promise.all([…, …]);\nconst home = data[0], product = data[1];\n const [home, product] = await Promise.all([…, …]);\n"
},
{
"answer_id": 74603762,
"author": "Zargold",
"author_id": 4142459,
"author_profile": "https://Stackoverflow.com/users/4142459",
"pm_score": 1,
"selected": false,
"text": "const [home, product, toolbar, nav] = await Promise.all([\ngetHome(), getProduct(), getToolBar(), getNav()\n]);\n const [home, product, toolbar, nav, ...otherPromises] = await Promise.all([\ngetHome(), getProduct(), getToolBar(), getNav(), getOtherThing1()\n]);\n// otherPromises will be an array that you'll have to access\n// with numeric keys as before:\n// eg. otherPromises[0] might be the first non-named promise\n// the result of getOtherThing1()\n"
},
{
"answer_id": 74603832,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": -1,
"selected": true,
"text": "const arr = [ { id: \"home\", val: \"val1\" }, { id: \"product\", val: \"val2\" }];\nconst convert = arr.reduce((a,b) => (a[b.id] ??= b,a),{});\nconsole.log(convert);\nconsole.log(convert.home);"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13052552/"
] |
74,603,707
|
<p>i have a string like d333-4444-555--5---5-<br />
and want catch only two first dashes and get 333-4444-55555<br />
if it will be first two and two in a row, two becomes one like:
d333--4444-555--5---5- goes 333-4444-55555</p>
<p>any advice or ready solvation</p>
<p>i started with
<code>console.log('d-45----'.replace(/[^0-9]/g, ''))</code>
but it's very far from what i expect
two days on the same point</p>
<p>Thank you</p>
|
[
{
"answer_id": 74603753,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 1,
"selected": false,
"text": "Promise.all const names = ['home', 'product'];\nconst promises = [fetchHome(), fetchProduct()];\nconst results = await Promise.all(promises);\nconst resultsByName = names.reduce((prev, curr, index) => {\n return {...prev, [curr]: results[index]};\n}, {});\n fetchHome() fetchProduct()"
},
{
"answer_id": 74603759,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 2,
"selected": false,
"text": "Promise.all Promise.all const data = await Promise.all([…, …]);\nconst home = data[0], product = data[1];\n const [home, product] = await Promise.all([…, …]);\n"
},
{
"answer_id": 74603762,
"author": "Zargold",
"author_id": 4142459,
"author_profile": "https://Stackoverflow.com/users/4142459",
"pm_score": 1,
"selected": false,
"text": "const [home, product, toolbar, nav] = await Promise.all([\ngetHome(), getProduct(), getToolBar(), getNav()\n]);\n const [home, product, toolbar, nav, ...otherPromises] = await Promise.all([\ngetHome(), getProduct(), getToolBar(), getNav(), getOtherThing1()\n]);\n// otherPromises will be an array that you'll have to access\n// with numeric keys as before:\n// eg. otherPromises[0] might be the first non-named promise\n// the result of getOtherThing1()\n"
},
{
"answer_id": 74603832,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": -1,
"selected": true,
"text": "const arr = [ { id: \"home\", val: \"val1\" }, { id: \"product\", val: \"val2\" }];\nconst convert = arr.reduce((a,b) => (a[b.id] ??= b,a),{});\nconsole.log(convert);\nconsole.log(convert.home);"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12030982/"
] |
74,603,719
|
<p>I have a KC instance where I have some clients with the <code>Authorization</code> option enabled. All works well, but, acting as a client, I need this specific information: Given a certain resource with specific scopes I want the list of users who have accesse to this resource.</p>
<p>I've explored the available APIs multiple times without success. Is there a way to obtain this information or do I necessary need to extends KC capabilities with a dedicated SPI ?</p>
|
[
{
"answer_id": 74603753,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 1,
"selected": false,
"text": "Promise.all const names = ['home', 'product'];\nconst promises = [fetchHome(), fetchProduct()];\nconst results = await Promise.all(promises);\nconst resultsByName = names.reduce((prev, curr, index) => {\n return {...prev, [curr]: results[index]};\n}, {});\n fetchHome() fetchProduct()"
},
{
"answer_id": 74603759,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 2,
"selected": false,
"text": "Promise.all Promise.all const data = await Promise.all([…, …]);\nconst home = data[0], product = data[1];\n const [home, product] = await Promise.all([…, …]);\n"
},
{
"answer_id": 74603762,
"author": "Zargold",
"author_id": 4142459,
"author_profile": "https://Stackoverflow.com/users/4142459",
"pm_score": 1,
"selected": false,
"text": "const [home, product, toolbar, nav] = await Promise.all([\ngetHome(), getProduct(), getToolBar(), getNav()\n]);\n const [home, product, toolbar, nav, ...otherPromises] = await Promise.all([\ngetHome(), getProduct(), getToolBar(), getNav(), getOtherThing1()\n]);\n// otherPromises will be an array that you'll have to access\n// with numeric keys as before:\n// eg. otherPromises[0] might be the first non-named promise\n// the result of getOtherThing1()\n"
},
{
"answer_id": 74603832,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": -1,
"selected": true,
"text": "const arr = [ { id: \"home\", val: \"val1\" }, { id: \"product\", val: \"val2\" }];\nconst convert = arr.reduce((a,b) => (a[b.id] ??= b,a),{});\nconsole.log(convert);\nconsole.log(convert.home);"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2381099/"
] |
74,603,734
|
<p>I am configuring minio as S3 compatible storage.</p>
<p>Based on <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-bucket-policies.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-bucket-policies.html</a></p>
<p>I understood that I can limit access to the bucket using BUCKET level policy for particular user.</p>
<p>aws example from the linked document:</p>
<pre><code>{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AddCannedAcl",
"Effect": "Allow",
"Principal": {
"AWS": [
"arn:aws:iam::111122223333:root",
"arn:aws:iam::444455556666:root"
]
},
"Action": [
"s3:PutObject",
"s3:PutObjectAcl"
],
"Resource": "arn:aws:s3:::DOC-EXAMPLE-BUCKET/*",
"Condition": {
"StringEquals": {
"s3:x-amz-acl": [
"public-read"
]
}
}
}
]
}
</code></pre>
<p>Let's consider 2 lines:</p>
<pre><code> "arn:aws:iam::111122223333:root",
"arn:aws:iam::444455556666:root"
</code></pre>
<p>as I understand <code>111122223333:root</code> and <code>444455556666:root</code> are user identifiers. But I haven't found any mc command which return me any user identifier ? I also check UI console but I haven't found anything</p>
<p>Could you please help ?</p>
|
[
{
"answer_id": 74662111,
"author": "Harshavardhana",
"author_id": 4465767,
"author_profile": "https://Stackoverflow.com/users/4465767",
"pm_score": 1,
"selected": false,
"text": " \"Principal\": {\n \"AWS\": [\n \"arn:aws:iam::111122223333:root\",\n \"arn:aws:iam::444455556666:root\"\n ]\n },\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2674303/"
] |
74,603,748
|
<p>I'm new to java and trying to add a string to itself (plus other strings also) and it runs but doesn't do anything at all, as in it just outputs "test", which is what it is before
everything else seems to work</p>
<pre><code>package chucknorris;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input string:");
String input = scanner.nextLine();
int length = input.length();
String output = "test";
for (int current = 0;current <= length;current++) {
String letter = input.substring(current, current);
output = output + letter + " ";
if (current == length) {
System.out.println(output);
}
}
}
}
</code></pre>
|
[
{
"answer_id": 74604056,
"author": "Vidu Gajadeera",
"author_id": 20624511,
"author_profile": "https://Stackoverflow.com/users/20624511",
"pm_score": 0,
"selected": false,
"text": "public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n System.out.println(\"Input string:\");\n String input = scanner.nextLine();\n int length = input.length();\n String output = \"test\";\n \n output = output.concat(output).concat(input).concat(\"\");\n\n System.out.println(output); \n}\n"
},
{
"answer_id": 74604064,
"author": "MohammadN99",
"author_id": 20625618,
"author_profile": "https://Stackoverflow.com/users/20625618",
"pm_score": 1,
"selected": false,
"text": " import java.util.Scanner;\n\n public class Main {\n\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n System.out.println(\"Input string:\");\n String input = scanner.nextLine();\n int length = input.length();\n String output = \"test\";\n\n\n for (int current = 0;current <= length;current++) {\n\n if (current >= length) {\n break;\n }\n String letter = input.substring(current, current + 1);\n output = output + letter;\n\n }\n\n System.out.println(output);\n\n}\n\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10000907/"
] |
74,603,758
|
<p>I'm trying to validate that a user input int is numbers only. This has been my most recent try:</p>
<pre><code>while True:
NumCars = int(input("Enter the number of cars on the policy: "))
NumCarsStr = str(NumCars)
if NumCarsStr == "":
print("Number of cars cannot be blank. Please re-enter.")
elif NumCarsStr.isalpha == True:
print("Number of cars must be numbers only. Please re-enter.")
else:
break
</code></pre>
<p>With this, I get the following error:</p>
<pre><code>line 91, in <module>
NumCars = int(input("Enter the number of cars on the policy: "))
ValueError: invalid literal for int() with base 10: 'g'
</code></pre>
<p>(I entered a "g" to test if it was working)
Thanks in advance!</p>
|
[
{
"answer_id": 74603785,
"author": "Sembei Norimaki",
"author_id": 20396240,
"author_profile": "https://Stackoverflow.com/users/20396240",
"pm_score": 1,
"selected": false,
"text": "while True:\n try:\n NumCars = int(input(\"Enter the number of cars on the policy: \"))\n break\n except ValueError:\n print(\"You must enter an integer number\")\n"
},
{
"answer_id": 74603823,
"author": "Devin Sag",
"author_id": 20388932,
"author_profile": "https://Stackoverflow.com/users/20388932",
"pm_score": -1,
"selected": false,
"text": " NumCarsStr = str(input(\"Enter the number of cars on the policy: \"))\n ...\n ...\n elif not NumCarsStr.isnumeric():\n print(\"Number of cars must be numbers only. Please re-enter.\")\n"
},
{
"answer_id": 74603846,
"author": "user20624405",
"author_id": 20624405,
"author_profile": "https://Stackoverflow.com/users/20624405",
"pm_score": 0,
"selected": false,
"text": "if type(input) == int: do_code_if_is_numbersonly() else: print(\"Numbers Only\")"
},
{
"answer_id": 74604123,
"author": "jonahpocalypse",
"author_id": 20258403,
"author_profile": "https://Stackoverflow.com/users/20258403",
"pm_score": 1,
"selected": false,
"text": " while True:\n\n NumCars = (input(\"Enter the number of cars on the policy: \"))\n if NumCars == \"\":\n print(\"Number of cars cannot be blank. Please re-enter.\")\n elif NumCars.isdigit() == False:\n print(\"Number of cars must be numbers only. Please re-enter.\")\n else:\n break\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20258403/"
] |
74,603,772
|
<p>I own an Asustor and I want to dockerise my node js app to be able to run any time.
I followed <a href="https://nodejs.org/fr/docs/guides/nodejs-docker-webapp/" rel="nofollow noreferrer">official tutorial from nodejs</a> but it's not working as intended on my nas, while on my computer everything is fine.</p>
<p>Here is my Dockerfile :</p>
<pre><code>FROM node:latest
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 8080
CMD ["node", "app.js"]
</code></pre>
<p>And here is the error I'm getting on the nas :</p>
<pre><code>Sending build context to Docker daemon 45.57kB
Step 1/7 : FROM node:latest
---> b254e440661a
Step 2/7 : WORKDIR /app
---> Running in 4ddb713a2c92
Removing intermediate container 4ddb713a2c92
---> 7956afe6d600
Step 3/7 : COPY package*.json ./
---> 9a814bfae80d
Step 4/7 : RUN npm install
---> Running in 477d3abd6312
node:internal/fs/utils:347
throw err;
^
Error: ENOENT: no such file or directory, open '/usr/local/lib/cli.js'
at Object.openSync (node:fs:591:3)
at Object.readFileSync (node:fs:459:35)
at Module._extensions..js (node:internal/modules/cjs/loader:1222:18)
at Module.load (node:internal/modules/cjs/loader:1068:32)
at Module._load (node:internal/modules/cjs/loader:909:12)
at Module.require (node:internal/modules/cjs/loader:1092:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/usr/local/bin/npm:2:1)
at Module._compile (node:internal/modules/cjs/loader:1205:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1259:10) {
errno: -2,
syscall: 'open',
code: 'ENOENT',
path: '/usr/local/lib/cli.js'
}
Node.js v19.1.0
The command '/bin/sh -c npm install' returned a non-zero code: 1
</code></pre>
|
[
{
"answer_id": 74603785,
"author": "Sembei Norimaki",
"author_id": 20396240,
"author_profile": "https://Stackoverflow.com/users/20396240",
"pm_score": 1,
"selected": false,
"text": "while True:\n try:\n NumCars = int(input(\"Enter the number of cars on the policy: \"))\n break\n except ValueError:\n print(\"You must enter an integer number\")\n"
},
{
"answer_id": 74603823,
"author": "Devin Sag",
"author_id": 20388932,
"author_profile": "https://Stackoverflow.com/users/20388932",
"pm_score": -1,
"selected": false,
"text": " NumCarsStr = str(input(\"Enter the number of cars on the policy: \"))\n ...\n ...\n elif not NumCarsStr.isnumeric():\n print(\"Number of cars must be numbers only. Please re-enter.\")\n"
},
{
"answer_id": 74603846,
"author": "user20624405",
"author_id": 20624405,
"author_profile": "https://Stackoverflow.com/users/20624405",
"pm_score": 0,
"selected": false,
"text": "if type(input) == int: do_code_if_is_numbersonly() else: print(\"Numbers Only\")"
},
{
"answer_id": 74604123,
"author": "jonahpocalypse",
"author_id": 20258403,
"author_profile": "https://Stackoverflow.com/users/20258403",
"pm_score": 1,
"selected": false,
"text": " while True:\n\n NumCars = (input(\"Enter the number of cars on the policy: \"))\n if NumCars == \"\":\n print(\"Number of cars cannot be blank. Please re-enter.\")\n elif NumCars.isdigit() == False:\n print(\"Number of cars must be numbers only. Please re-enter.\")\n else:\n break\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625342/"
] |
74,603,789
|
<p>I am using the Pandas library on Python and was wondering if there is a way to use a list variable (or perhaps series is better?), let's say <code>uID_list</code>, in an SQL query that is also executed within the same Python code. For example:</p>
<pre><code>dict = {'a': 1, 'b': 2, 'c':3}
uID_series = pd.Series(data=dict, index=['a','b','c'])
uID_list = uID_series.toList()
</code></pre>
<p>and let's assume this <code>uID_list</code> can be changed down the road, so it does not always consist of <code>1, 2, 3</code>.</p>
<p>How can I "plug in" this <code>uID_list</code> variable in the following SQL query?</p>
<pre><code>sql =
f'''
CREATE PROCEDURE SearchForUsers(@uIDinput AS INT(11))
AS
BEGIN
SELECT username
FROM users_table
WHERE uID in @uIDinput
END
EXECUTE SearchForUsers {uID_list}
'''
</code></pre>
<p>Note that creating a new table in the database is not an option for me, as it is work related and my supervisor is strict on keeping the database clean.</p>
<p>What I'm essentially trying to do is see a selection of <code>username</code>s in <code>users_table</code> table, where the <code>uID</code>s in <code>users_table</code> match a varying collection of <code>uID</code>s stored, which is given by <code>uID_list</code>. And <code>uID_list</code> depends on the rest of the python code where it can get changed and manipulated.</p>
|
[
{
"answer_id": 74603785,
"author": "Sembei Norimaki",
"author_id": 20396240,
"author_profile": "https://Stackoverflow.com/users/20396240",
"pm_score": 1,
"selected": false,
"text": "while True:\n try:\n NumCars = int(input(\"Enter the number of cars on the policy: \"))\n break\n except ValueError:\n print(\"You must enter an integer number\")\n"
},
{
"answer_id": 74603823,
"author": "Devin Sag",
"author_id": 20388932,
"author_profile": "https://Stackoverflow.com/users/20388932",
"pm_score": -1,
"selected": false,
"text": " NumCarsStr = str(input(\"Enter the number of cars on the policy: \"))\n ...\n ...\n elif not NumCarsStr.isnumeric():\n print(\"Number of cars must be numbers only. Please re-enter.\")\n"
},
{
"answer_id": 74603846,
"author": "user20624405",
"author_id": 20624405,
"author_profile": "https://Stackoverflow.com/users/20624405",
"pm_score": 0,
"selected": false,
"text": "if type(input) == int: do_code_if_is_numbersonly() else: print(\"Numbers Only\")"
},
{
"answer_id": 74604123,
"author": "jonahpocalypse",
"author_id": 20258403,
"author_profile": "https://Stackoverflow.com/users/20258403",
"pm_score": 1,
"selected": false,
"text": " while True:\n\n NumCars = (input(\"Enter the number of cars on the policy: \"))\n if NumCars == \"\":\n print(\"Number of cars cannot be blank. Please re-enter.\")\n elif NumCars.isdigit() == False:\n print(\"Number of cars must be numbers only. Please re-enter.\")\n else:\n break\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15488220/"
] |
74,603,819
|
<p>I have the following function that makes a GET request for my user information and caches it using react query's fetchQuery so that every call after the first one does not make a GET request and instead just pulls the data from the cache.</p>
<pre><code>export const getSelf = async (): Promise<UserData> =>
await queryClient.fetchQuery(['getSelf'], async () => {
try {
const { data } = await request.get('/users/me');
// @todo: This sideloads a bunch of stuff, that we could cache
return data;
} catch (error) {
throw new Error('Failed to fetch user information');
}
});
</code></pre>
<p>The problem is that now I actually want to make a new GET request in order to check if the user data has changed, but calling <code>getSelf()</code> pulls from the cache. How can I instruct fetchQuery to make a fresh GET request and not used the cache?</p>
|
[
{
"answer_id": 74603888,
"author": "Oleg Brazhnichenko",
"author_id": 7028321,
"author_profile": "https://Stackoverflow.com/users/7028321",
"pm_score": 1,
"selected": false,
"text": "import { useQueryClient } from '@tanstack/react-query'\n\n// Get QueryClient from the context\nconst queryClient = useQueryClient()\n\nqueryClient.invalidateQueries({ queryKey: ['getSelf'] })\n"
},
{
"answer_id": 74603930,
"author": "Chad S.",
"author_id": 5274205,
"author_profile": "https://Stackoverflow.com/users/5274205",
"pm_score": 2,
"selected": true,
"text": "export const getSelf = async (skipCache = false) => {\n if(skipCache) { queryClient.invalidateQueries(['getSelf']); }\n \n return queryClient.fetchQuery(['getSelf'], async () => {\n try {\n const { data } = await request.get('/users/me');\n\n // @todo: This sideloads a bunch of stuff, that we could cache\n return data;\n } catch (error) {\n throw new Error('Failed to fetch user information');\n }\n });\n}\n"
},
{
"answer_id": 74674792,
"author": "TkDodo",
"author_id": 8405310,
"author_profile": "https://Stackoverflow.com/users/8405310",
"pm_score": 0,
"selected": false,
"text": "fetchQuery fresh staleTime staleTime 0 fetchQuery staleTime fetchQuery staleTime staleTime fetchQuery staleTime: 0 fetchQuery await queryClient.fetchQuery(\n ['getSelf'],\n async () => { ... },\n { staleTime: 0 }\n)\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8618818/"
] |
74,603,821
|
<p>I was shocked by the output of this... been coding in C for a few years now.
Could someone explain a possible use case? Seems like it should be a compiler warning.</p>
<pre><code>#include <stdio.h>
int chk(int var)
{
return var++;
}
int main (void)
{
int a = 1;
a = chk(a);
printf("var is: %d\n", a);
return 0;
}
</code></pre>
<p><code>var is: 1</code></p>
|
[
{
"answer_id": 74604142,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 2,
"selected": false,
"text": "int chk(int var)\n{\n return var++;\n}\n var return var;\n int chk(int var)\n{\n return ++var;\n}\n"
},
{
"answer_id": 74604237,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile": "https://Stackoverflow.com/users/298225",
"pm_score": 0,
"selected": false,
"text": "return var++; var var var return var a"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6534937/"
] |
74,603,839
|
<p>I need some help with this, I'm stuck in JS Arrays & Loops, I don't know why this is telling me that if the function is empty is not returning "0".</p>
<pre class="lang-js prettyprint-override"><code>function sumArray (numbers) {
// your code
var numbers = [1, 2, 3, 4];
if (numbers !== undefined) {
const sum = numbers.reduce((a,b) => a+b, 0)
return sum
}
else if ( numbers === []);{
return 0
}
}
sumArray();
</code></pre>
<p>I tried to return 0 when the array is empty, but I' don't know what I'm missig.</p>
|
[
{
"answer_id": 74604142,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 2,
"selected": false,
"text": "int chk(int var)\n{\n return var++;\n}\n var return var;\n int chk(int var)\n{\n return ++var;\n}\n"
},
{
"answer_id": 74604237,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile": "https://Stackoverflow.com/users/298225",
"pm_score": 0,
"selected": false,
"text": "return var++; var var var return var a"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625555/"
] |
74,603,849
|
<p>My input type has an attributed <code>disabled</code> but whenever i save the value in php it does say " field_name is required" why i can't insert when the input is disabled?</p>
<pre><code><input disabled type="number" name="qty[]" id="qty_1" class="form-control" min="0" placeholder="Quantity" required onclick="getTotal(1)" onkeyup="getTotal(1)">
</code></pre>
<p>also how in select?</p>
<pre><code><select class="form-control select_group product" data-row-id="row_<?php echo $x; ?>" id="product_<?php echo $x; ?>" name="product[]" style="width:100%;" onchange="getProductData(<?php echo $x; ?>)" required>
<option value=""></option>
<?php foreach ($products as $k => $v): ?>
<option value="<?php echo $v['id'] ?>" <?php if($val['product_id'] == $v['id']) { echo "selected='selected'"; } ?>><?php echo $v['name'] ?></option>
<?php endforeach ?>
</select>
</code></pre>
|
[
{
"answer_id": 74604164,
"author": "mykaf",
"author_id": 1599011,
"author_profile": "https://Stackoverflow.com/users/1599011",
"pm_score": -1,
"selected": false,
"text": "<select name=\"product[]\" disabled>\n<option value=\"1\">1</option>\n<option value=\"2\" selected>2</option>\n<option value=\"3\">3</option>\n</select>\n<input type=\"hidden\" name=\"product[]\" value=\"2\" />\n"
},
{
"answer_id": 74604224,
"author": "hanafi naufal",
"author_id": 20568912,
"author_profile": "https://Stackoverflow.com/users/20568912",
"pm_score": 0,
"selected": false,
"text": "<input readonly type=\"number\" name=\"qty[]\" id=\"qty_1\" class=\"form-control\" min=\"0\" placeholder=\"Quantity\" required onclick=\"getTotal(1)\" onkeyup=\"getTotal(1)\">\n"
},
{
"answer_id": 74635698,
"author": "Nagonus Lrak",
"author_id": 20476491,
"author_profile": "https://Stackoverflow.com/users/20476491",
"pm_score": 0,
"selected": false,
"text": "form.onsubmit = function() {\n qty_1.removeAttribute(\"required\")\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14393948/"
] |
74,603,867
|
<p>Basically I want to be able to rotate the numbers clockwise when I click the rotate button. I think I've attached all of the associated code. I created a button. It links back to the javascript function. It even runs the function. The issue is I can only get it to run the function and rotate one time.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var value1 = "1";
var value2 = "2";
var value4 = "3";
var value3 = "4";
document.getElementById("value1").innerHTML = value1;
document.getElementById("value2").innerHTML = value2;
document.getElementById("value3").innerHTML = value3;
document.getElementById("value4").innerHTML = value4;
var btn = document.querySelector('#bt1');
btn.addEventListener('click', rotate)
function rotate() {
var Value1 = value1;
var Value2 = value2;
var Value3 = value3;
var Value4 = value4;
document.getElementById("value1").innerHTML = Value4;
document.getElementById("value2").innerHTML = Value1;
document.getElementById("value3").innerHTML = Value2;
document.getElementById("value4").innerHTML = Value3;
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
font-family: sans-serif;
margin-left: auto;
margin-right: auto;
width: 20%;
}
.import {
padding-bottom: 0.3em;
}
.import input[type=text] {
width: 630px;
}
.valid {
background-color: limegreen;
}
.invalid {
background-color: red;
}
.imported_square {
background-color: lightgray;
}
.puzzle {
border: 4px solid black;
border-collapse: collapse;
}
.puzzle tr {
padding: 0;
}
.puzzle td {
padding: 0;
border: 1px solid black;
width: 2em;
font-size: 50pt;
text-align: center;
}
.puzzle .thick_right {
border-right: 4px solid black;
}
.puzzle .thick_bottom {
border-bottom: 4px solid black;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<button id="bt1">Rotate</button>
<table class="puzzle" width=250px height=250px>
<tr class="1 thick_bottom">
<td id="value1" class="1 thick_right"></td>
<td id="value2" class="2 thick_right"></td>
</tr>
<tr class="2 thick_bottom">
<td id="value3" class="1 thick_right"></td>
<td id="value4" class="2 thick_right"></td>
</tr>
</table>
</div></code></pre>
</div>
</div>
</p>
<p>I've spent a long time scouring threads on here and also trying to create my own roundabout ways but nothing seems to work. I can get it to rotate once but I just can't find a way to make it rotate more than once. I want to be able to click the rotate button as many times as I want and the numbers keep rotating in a clockwise direction.</p>
|
[
{
"answer_id": 74604012,
"author": "IT goldman",
"author_id": 3807365,
"author_profile": "https://Stackoverflow.com/users/3807365",
"pm_score": 0,
"selected": false,
"text": "var value1 = \"1\";\nvar value2 = \"2\";\nvar value4 = \"3\";\nvar value3 = \"4\";\n\ndocument.getElementById(\"value1\").innerHTML = value1;\ndocument.getElementById(\"value2\").innerHTML = value2;\ndocument.getElementById(\"value3\").innerHTML = value3;\ndocument.getElementById(\"value4\").innerHTML = value4;\n\nvar btn = document.querySelector('#bt1');\n\nbtn.addEventListener('click', rotate)\n\nfunction rotate() {\n var old_value1 = value1\n value1 = value2;\n value2 = value4;\n value4 = value3;\n value3 = old_value1;\n document.getElementById(\"value1\").innerHTML = value1;\n document.getElementById(\"value2\").innerHTML = value2;\n document.getElementById(\"value3\").innerHTML = value3;\n document.getElementById(\"value4\").innerHTML = value4;\n} body {\n font-family: sans-serif;\n margin-left: auto;\n margin-right: auto;\n width: 20%;\n}\n\n.import {\n padding-bottom: 0.3em;\n}\n\n.import input[type=text] {\n width: 630px;\n}\n\n.valid {\n background-color: limegreen;\n}\n\n.invalid {\n background-color: red;\n}\n\n.imported_square {\n background-color: lightgray;\n}\n\n.puzzle {\n border: 4px solid black;\n border-collapse: collapse;\n}\n\n.puzzle tr {\n padding: 0;\n}\n\n.puzzle td {\n padding: 0;\n border: 1px solid black;\n width: 2em;\n font-size: 50pt;\n text-align: center;\n}\n\n.puzzle .thick_right {\n border-right: 4px solid black;\n}\n\n.puzzle .thick_bottom {\n border-bottom: 4px solid black;\n} <div>\n <button id=\"bt1\">Rotate</button>\n <table class=\"puzzle\" width=250px height=250px>\n <tr class=\"1 thick_bottom\">\n <td id=\"value1\" class=\"1 thick_right\"></td>\n <td id=\"value2\" class=\"2 thick_right\"></td>\n </tr>\n <tr class=\"2 thick_bottom\">\n <td id=\"value3\" class=\"1 thick_right\"></td>\n <td id=\"value4\" class=\"2 thick_right\"></td>\n </tr>\n </table>\n</div>"
},
{
"answer_id": 74604032,
"author": "jjj",
"author_id": 13365797,
"author_profile": "https://Stackoverflow.com/users/13365797",
"pm_score": 1,
"selected": false,
"text": " var value1 = 1;\n var value2 = 2;\n var value4 = 3;\n var value3 = 4;\n \n document.getElementById(\"value1\").innerHTML = value1;\n document.getElementById(\"value2\").innerHTML = value2;\n document.getElementById(\"value3\").innerHTML = value3;\n document.getElementById(\"value4\").innerHTML = value4;\n \n var btn = document.querySelector('#bt1');\n \n btn.addEventListener('click', rotate)\n \n function nextNum(currentNum) {\n // upon each rotate, minus the current number by 1 or reset to 4\n return currentNum - 1 < 1 ? 4 : currentNum - 1\n }\n \n function rotate(){\n\n value1 = nextNum(value1)\n value2 = nextNum(value2)\n value3 = nextNum(value3)\n value4 = nextNum(value4)\n \n document.getElementById(\"value1\").innerHTML = value1;\n document.getElementById(\"value2\").innerHTML = value2;\n document.getElementById(\"value3\").innerHTML = value3;\n document.getElementById(\"value4\").innerHTML = value4;\n } body {\n font-family:sans-serif;\n margin-left: auto;\n margin-right: auto;\n width: 20%;\n }\n.import {padding-bottom:0.3em;}\n.import input[type=text] {width:630px;}\n\n.valid {background-color:limegreen;}\n.invalid {background-color:red;}\n.imported_square {background-color:lightgray;}\n\n.puzzle {border:4px solid black; border-collapse: collapse;}\n.puzzle tr {padding:0;}\n.puzzle td {padding:0; border:1px solid black; width:2em; font-size:50pt; text-align:center;}\n.puzzle .thick_right {border-right:4px solid black;}\n.puzzle .thick_bottom {border-bottom:4px solid black;} <div>\n <button id=\"bt1\">Rotate</button>\n <table class=\"puzzle\" width=250px height=250px>\n <tr class=\"1 thick_bottom\">\n <td id=\"value1\" class=\"1 thick_right\"></td>\n <td id=\"value2\" class=\"2 thick_right\"></td>\n </tr>\n <tr class=\"2 thick_bottom\">\n <td id=\"value3\" class=\"1 thick_right\"></td>\n <td id=\"value4\" class=\"2 thick_right\"></td>\n </tr>\n </table>\n </div>"
},
{
"answer_id": 74604263,
"author": "PADMANABAN GOKULA",
"author_id": 20450907,
"author_profile": "https://Stackoverflow.com/users/20450907",
"pm_score": 0,
"selected": false,
"text": "<div>\n <button id=\"bt1\">Rotate</button>\n <table class=\"puzzle\" width=250px height=250px>\n <tr class=\"1 thick_bottom\">\n <td id=\"value1\" class=\"1 thick_right\"></td>\n <td id=\"value2\" class=\"2 thick_right\"></td>\n </tr>\n <tr class=\"2 thick_bottom\">\n <td id=\"value3\" class=\"1 thick_right\"></td>\n <td id=\"value4\" class=\"2 thick_right\"></td>\n </tr>\n </table>\n <script>\n var values = [\"1\", \"2\", \"3\", \"4\"];\n \n document.getElementById(\"value1\").innerHTML = values[0];\n document.getElementById(\"value2\").innerHTML = values[1];\n document.getElementById(\"value3\").innerHTML = values[2];\n document.getElementById(\"value4\").innerHTML = values[3];\n \n var btn = document.querySelector('#bt1');\n \n btn.addEventListener('click', rotate)\n var counter = 0;\n function rotate(){\n ++counter;\n document.getElementById(\"value1\").innerHTML = values[(counter + 0)%4];\n document.getElementById(\"value2\").innerHTML = values[(counter + 1)%4];\n document.getElementById(\"value3\").innerHTML = values[(counter + 2)%4 ];\n document.getElementById(\"value4\").innerHTML = values[(counter + 3)%4 ];\n }\n </script>\n <style type=\"text/css\">\n body {\n font-family:sans-serif;\n margin-left: auto;\n margin-right: auto;\n width: 20%;\n }\n.import {padding-bottom:0.3em;}\n.import input[type=text] {width:630px;}\n\n.valid {background-color:limegreen;}\n.invalid {background-color:red;}\n.imported_square {background-color:lightgray;}\n\n.puzzle {border:4px solid black; border-collapse: collapse;}\n.puzzle tr {padding:0;}\n.puzzle td {padding:0; border:1px solid black; width:2em; font-size:50pt; text-align:center;}\n.puzzle .thick_right {border-right:4px solid black;}\n.puzzle .thick_bottom {border-bottom:4px solid black;}\n </style>\n </div>\n"
},
{
"answer_id": 74604303,
"author": "Giorgi Shalamberidze",
"author_id": 20248276,
"author_profile": "https://Stackoverflow.com/users/20248276",
"pm_score": 0,
"selected": false,
"text": " var value1 = 1;\n var value2 = 2;\n var value4 = 3;\n var value3 = 4;\n\n document.getElementById(\"value1\").innerHTML = value1;\n document.getElementById(\"value2\").innerHTML = value2;\n document.getElementById(\"value3\").innerHTML = value3;\n document.getElementById(\"value4\").innerHTML = value4;\n\n var btn = document.querySelector('#bt1');\n\n btn.addEventListener('click', rotate)\n\n function rotate() {\n if(value1 === 1) {\n value1 = 4\n }else {\n value1--\n }\n\n if(value2 === 1) {\n value2 = 4\n }else {\n value2--\n }\n\n if(value3 === 1) {\n value3 = 4\n }else {\n value3--\n }\n\n if(value4 === 1) {\n value4 = 4\n }else {\n value4--\n }\n\n document.getElementById(\"value1\").innerHTML = value1;\n document.getElementById(\"value2\").innerHTML = value2;\n document.getElementById(\"value3\").innerHTML = value3;\n document.getElementById(\"value4\").innerHTML = value4;\n \n } body {\n font-family: sans-serif;\n margin-left: auto;\n margin-right: auto;\n width: 20%;\n}\n\n.import {\n padding-bottom: 0.3em;\n}\n\n.import input[type=text] {\n width: 630px;\n}\n\n.valid {\n background-color: limegreen;\n}\n\n.invalid {\n background-color: red;\n}\n\n.imported_square {\n background-color: lightgray;\n}\n\n.puzzle {\n border: 4px solid black;\n border-collapse: collapse;\n}\n\n.puzzle tr {\n padding: 0;\n}\n\n.puzzle td {\n padding: 0;\n border: 1px solid black;\n width: 2em;\n font-size: 50pt;\n text-align: center;\n}\n\n.puzzle .thick_right {\n border-right: 4px solid black;\n}\n\n.puzzle .thick_bottom {\n border-bottom: 4px solid black;\n} <div>\n <button id=\"bt1\">Rotate</button>\n <table class=\"puzzle\" width=250px height=250px>\n <tr class=\"1 thick_bottom\">\n <td id=\"value1\" class=\"1 thick_right\"></td>\n <td id=\"value2\" class=\"2 thick_right\"></td>\n </tr>\n <tr class=\"2 thick_bottom\">\n <td id=\"value3\" class=\"1 thick_right\"></td>\n <td id=\"value4\" class=\"2 thick_right\"></td>\n </tr>\n </table>\n</div>"
},
{
"answer_id": 74604332,
"author": "Anirudh Singh",
"author_id": 20587475,
"author_profile": "https://Stackoverflow.com/users/20587475",
"pm_score": 0,
"selected": false,
"text": "function rotate() {\n \n var array = []\n\n document.querySelectorAll('td').forEach((element) => {\n array.push(element.innerText)\n })\n\n array.push(array.shift())\n\n document.querySelectorAll('td').forEach((element, index) => {\n element.innerText = array[index]\n })\n \n} table{\n border-collapse: collapse;\n}\n\ntable td{\n border: 2px solid #111;\n padding: 20px;\n}\n\nbutton{\n margin-top: 20px;\n border: none;\n outline: none;\n padding: 10px 16px;\n background: #111;\n color: #FFF;\n} <table>\n <tr>\n <td>1</td>\n <td>2</td>\n <td>3</td>\n <td>4</td>\n </tr>\n</table>\n\n<button onclick='rotate()'>Rotate</button>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625506/"
] |
74,603,929
|
<p>I have a collection of Products in a list (<code>List<Product></code> ) where product holds id, name and price.</p>
<p>If I would order the list in a descending way based on price, is there a one liner or extensionmethod that allows me to insert a new product in the correct position of the list?</p>
<pre><code>public class Product
{
public int Id {get; set;}
public string Name {get; set;}
public int Price {get; set;} // assume only whole integers for price
}
public class Main()
{
List<Product> products = new();
products.Add(new Product(id= 1, Name="Product1", Price=10 };
products.Add(new Product(id= 2, Name="Product2", Price=15 };
products.Add(new Product(id= 3, Name="Product3", Price=11 };
products.Add(new Product(id= 4, Name="Product4", Price=20 };
products = products.OrderByDescending(prd => prd.Price).ToList();
var newProduct = new({id = 5, Name="new product", Price = 17})
// Is there an short solution available that allows me to insert a new product with
// price = 17 and that will be inserted between products with price 15 and 20?
// Without repeatedly iterating over the list to find the one lower and the one higher
// than the new price and recalculate the index...
var lastIndex = products.FindLastIndex(x => x.Price >= newProduct.Price);
products.Insert(lastIndex + 1, p5);
}
</code></pre>
<p><em><strong>Edit for Solution</strong></em>: I upvoted Tim Schmelter's answer as the most correct one. It is not a single line, as it requires a custom extension method, but I think a single line solution isn't available. Adding it and do a OrderByDescending() works, and is simple, but then depends on the OrderByDescending() statement for the rest of the code...</p>
|
[
{
"answer_id": 74604141,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 4,
"selected": true,
"text": "SortedList<TKey, TValue> SortedList<int, Product> productList = new();\nvar p = new Product{ Id = 1, Name = \"Product1\", Price = 10 };\nproductList.Add(p.Price, p);\np = new Product { Id = 2, Name = \"Product2\", Price = 15 };\nproductList.Add(p.Price, p);\np = new Product { Id = 3, Name = \"Product3\", Price = 11 };\nproductList.Add(p.Price, p);\np = new Product { Id = 4, Name = \"Product4\", Price = 20 };\nproductList.Add(p.Price, p);\n\np = new Product { Id = 5, Name = \"Product5\", Price = 17 };\nproductList.Add(p.Price, p);\n\nforeach(var x in productList) \n Console.WriteLine($\"{x.Key} {x.Value.Name}\");\n 10 Product1\n11 Product3\n15 Product2\n17 Product5\n20 Product4\n SortedList<int, List<Product>> public static class CollectionExtensions\n{\n public static void AddItem<TKey, TValue>(this SortedList<TKey, List<TValue>> sortedList, TValue item, Func<TValue, TKey> getKey)\n {\n TKey key = getKey(item);\n if (sortedList.TryGetValue(key, out var list))\n {\n list.Add(item);\n }\n else\n {\n sortedList.Add(key, new List<TValue> { item });\n }\n }\n}\n SortedList<int, List<Product>> productLists = new();\nproductLists.AddItem(new Product { Id = 1, Name = \"Product1\", Price = 10 }, p => p.Price);\nproductLists.AddItem(new Product { Id = 2, Name = \"Product2\", Price = 10 }, p => p.Price);\nproductLists.AddItem(new Product { Id = 3, Name = \"Product3\", Price = 20 }, p => p.Price);\nproductLists.AddItem(new Product { Id = 4, Name = \"Product4\", Price = 20 }, p => p.Price);\nproductLists.AddItem(new Product { Id = 5, Name = \"Product5\", Price = 15 }, p => p.Price);\n\nforeach (var x in productLists) \n Console.WriteLine($\"{x.Key} {string.Join(\"|\", x.Value.Select(p => p.Name))}\");\n 10 Product1|Product2\n15 Product5\n20 Product3|Product4\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7924943/"
] |
74,603,960
|
<p>The goal -> For each word in the text except the last one, a key should appear in the resulting dictionary, and the corresponding value should be a list of every word that occurs immediately after the key word in the text. Repeated words should have multiple values:
example:</p>
<pre><code>fun(["ONE", "two", "one", "three"]) ==
{"one": ["two", "three"],"two": ["one] })
</code></pre>
<p>what I have so far:</p>
<pre><code>def build_predictions(words: list) -> dict:
dictionary = {}
for word in words:
if word.index() != words.len():
if word not in dictionary:
dictionary.update({word : words(words.index(word)+1)})
else:
dictionary[word] = dictionary[word] + [words(words.index(word)+1)]
</code></pre>
<p>Im getting an EOF error ;[ -> not sure if this is right anyways.</p>
|
[
{
"answer_id": 74604141,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 4,
"selected": true,
"text": "SortedList<TKey, TValue> SortedList<int, Product> productList = new();\nvar p = new Product{ Id = 1, Name = \"Product1\", Price = 10 };\nproductList.Add(p.Price, p);\np = new Product { Id = 2, Name = \"Product2\", Price = 15 };\nproductList.Add(p.Price, p);\np = new Product { Id = 3, Name = \"Product3\", Price = 11 };\nproductList.Add(p.Price, p);\np = new Product { Id = 4, Name = \"Product4\", Price = 20 };\nproductList.Add(p.Price, p);\n\np = new Product { Id = 5, Name = \"Product5\", Price = 17 };\nproductList.Add(p.Price, p);\n\nforeach(var x in productList) \n Console.WriteLine($\"{x.Key} {x.Value.Name}\");\n 10 Product1\n11 Product3\n15 Product2\n17 Product5\n20 Product4\n SortedList<int, List<Product>> public static class CollectionExtensions\n{\n public static void AddItem<TKey, TValue>(this SortedList<TKey, List<TValue>> sortedList, TValue item, Func<TValue, TKey> getKey)\n {\n TKey key = getKey(item);\n if (sortedList.TryGetValue(key, out var list))\n {\n list.Add(item);\n }\n else\n {\n sortedList.Add(key, new List<TValue> { item });\n }\n }\n}\n SortedList<int, List<Product>> productLists = new();\nproductLists.AddItem(new Product { Id = 1, Name = \"Product1\", Price = 10 }, p => p.Price);\nproductLists.AddItem(new Product { Id = 2, Name = \"Product2\", Price = 10 }, p => p.Price);\nproductLists.AddItem(new Product { Id = 3, Name = \"Product3\", Price = 20 }, p => p.Price);\nproductLists.AddItem(new Product { Id = 4, Name = \"Product4\", Price = 20 }, p => p.Price);\nproductLists.AddItem(new Product { Id = 5, Name = \"Product5\", Price = 15 }, p => p.Price);\n\nforeach (var x in productLists) \n Console.WriteLine($\"{x.Key} {string.Join(\"|\", x.Value.Select(p => p.Name))}\");\n 10 Product1|Product2\n15 Product5\n20 Product3|Product4\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74603960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625629/"
] |
74,604,005
|
<p>I have members, the group in which they belong and datetimes in which they were active. I want to find out which of the members had gap of more than 3 months between dates and I need to rank them.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>header 1</th>
<th>header 2</th>
<th>Create Date</th>
<th>Rank</th>
</tr>
</thead>
<tbody>
<tr>
<td>11111</td>
<td>EAM</td>
<td>2022-01-27 12:23:28.474000000</td>
<td>1</td>
</tr>
<tr>
<td>11111</td>
<td>EAM</td>
<td>2022-08-25 10:41:15.500000000</td>
<td>2</td>
</tr>
<tr>
<td>11111</td>
<td>EAM</td>
<td>2022-09-01 18:15:07.362000000</td>
<td>2</td>
</tr>
<tr>
<td>11111</td>
<td>EAM</td>
<td>2022-09-08 13:03:38.859000000</td>
<td>2</td>
</tr>
<tr>
<td>11111</td>
<td>EAM</td>
<td>2022-10-06 18:15:07.245000000</td>
<td>2</td>
</tr>
<tr>
<td>11111</td>
<td>PEM</td>
<td>2022-07-25 10:41:15.500000000</td>
<td>1</td>
</tr>
<tr>
<td>11111</td>
<td>PEM</td>
<td>2022-08-25 10:41:15.500000000</td>
<td>1</td>
</tr>
<tr>
<td>11111</td>
<td>PEM</td>
<td>2022-09-26 13:03:38.859000000</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>The desired result is above with the rank; the table contains the data without the <code>Rank</code> column.</p>
|
[
{
"answer_id": 74604141,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 4,
"selected": true,
"text": "SortedList<TKey, TValue> SortedList<int, Product> productList = new();\nvar p = new Product{ Id = 1, Name = \"Product1\", Price = 10 };\nproductList.Add(p.Price, p);\np = new Product { Id = 2, Name = \"Product2\", Price = 15 };\nproductList.Add(p.Price, p);\np = new Product { Id = 3, Name = \"Product3\", Price = 11 };\nproductList.Add(p.Price, p);\np = new Product { Id = 4, Name = \"Product4\", Price = 20 };\nproductList.Add(p.Price, p);\n\np = new Product { Id = 5, Name = \"Product5\", Price = 17 };\nproductList.Add(p.Price, p);\n\nforeach(var x in productList) \n Console.WriteLine($\"{x.Key} {x.Value.Name}\");\n 10 Product1\n11 Product3\n15 Product2\n17 Product5\n20 Product4\n SortedList<int, List<Product>> public static class CollectionExtensions\n{\n public static void AddItem<TKey, TValue>(this SortedList<TKey, List<TValue>> sortedList, TValue item, Func<TValue, TKey> getKey)\n {\n TKey key = getKey(item);\n if (sortedList.TryGetValue(key, out var list))\n {\n list.Add(item);\n }\n else\n {\n sortedList.Add(key, new List<TValue> { item });\n }\n }\n}\n SortedList<int, List<Product>> productLists = new();\nproductLists.AddItem(new Product { Id = 1, Name = \"Product1\", Price = 10 }, p => p.Price);\nproductLists.AddItem(new Product { Id = 2, Name = \"Product2\", Price = 10 }, p => p.Price);\nproductLists.AddItem(new Product { Id = 3, Name = \"Product3\", Price = 20 }, p => p.Price);\nproductLists.AddItem(new Product { Id = 4, Name = \"Product4\", Price = 20 }, p => p.Price);\nproductLists.AddItem(new Product { Id = 5, Name = \"Product5\", Price = 15 }, p => p.Price);\n\nforeach (var x in productLists) \n Console.WriteLine($\"{x.Key} {string.Join(\"|\", x.Value.Select(p => p.Name))}\");\n 10 Product1|Product2\n15 Product5\n20 Product3|Product4\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5522504/"
] |
74,604,048
|
<p>I have a type like below:</p>
<pre class="lang-js prettyprint-override"><code>type Entity =
| {
type: 'user' | 'person';
id: string;
}
| {
type: 'animal';
id: number;
};
</code></pre>
<p>Now I want to extract the types from it:</p>
<p><code>type Animal = Extract<Entity, {type: 'animal'}></code> - works perfectly (returns <code>{ type: 'animal'; id: number; }</code>);</p>
<p><code>type User = Extract<Entity, {type: 'user'}></code> - returns <code>never</code>.</p>
<p>How can I make it return <code>{ type: 'user'; id: string; }</code>
?</p>
|
[
{
"answer_id": 74604130,
"author": "Alex Wayne",
"author_id": 62076,
"author_profile": "https://Stackoverflow.com/users/62076",
"pm_score": 3,
"selected": true,
"text": "Extract<T, U> { type: 'user' | 'person', id: string } { type: 'user' } declare const entity: Entity\nconst user: { type: 'user' } = entity\n/*\nType 'Entity' is not assignable to type '{ type: \"user\"; }'.\n Type '{ type: \"user\" | \"person\"; id: string; }' is not assignable to type '{ type: \"user\"; }'.\n Types of property 'type' are incompatible.\n Type '\"user\" | \"person\"' is not assignable to type '\"user\"'.\n Type '\"person\"' is not assignable to type '\"user\"'.(2322)\n*/\n Extract & type User = Entity & { type: 'user' }\n\nconst user: User = { type: 'user', id: 'abc' }\nuser.id // type: string\n"
},
{
"answer_id": 74604225,
"author": "Tobias S.",
"author_id": 8613630,
"author_profile": "https://Stackoverflow.com/users/8613630",
"pm_score": 0,
"selected": false,
"text": "Extract 'user' | 'person' 'user' CustomExtract Partial<T> type CustomExtract<T, U> = \n T extends T \n ? U extends Partial<T> \n ? T \n : never\n : never\n\ntype Animal = CustomExtract<Entity, { type: 'animal' }>\n// type Animal = {\n// type: 'animal';\n// id: number;\n// }\n\ntype User = CustomExtract<Entity, { type: 'user' }>\n// type User = {\n// type: 'user' | 'person';\n// id: string;\n// }\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/291695/"
] |
74,604,066
|
<p>I have created a Docker image and pushed it to the AWS ECR repository</p>
<p>I'm creating a task with 3 containers included, one for Redis one for PostgreSQL and another one for the given Image which is my Node project</p>
<p>In Dockerfile, I have added a CMD to run the App with <code>node</code> command, here is the Dockerfile content:</p>
<pre><code>FROM node:16-alpine as build
WORKDIR /usr/token-manager/app
COPY package*.json .
RUN npm install
COPY . .
RUN npm run build
FROM node:16-alpine as production
ARG ENV_ARG=production
ENV NODE_ENV=${ENV_ARG}
WORKDIR /usr/token-manager/app
COPY package*.json .
RUN npm install --production
COPY --from=build /usr/token-manager/app/dist ./dist
CMD ["node", "./dist/index.js"]
</code></pre>
<p>This image is working in a docker-compose locally without any issue</p>
<p>The issue is when I run the task in ECS Cluster it's not running the Node project, it seems that it's not running the CMD command</p>
<p>I tried to override that CMD command by adding a new command to the Task definition:</p>
<p><a href="https://i.stack.imgur.com/PwSx5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PwSx5.png" alt="enter image description here" /></a></p>
<p>When I run task with this command, there is nothing in the CloudWatch log and obviously the Node App is not running, here you can see that there is no log for <code>api-container</code>:</p>
<p><a href="https://i.stack.imgur.com/FW0xs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FW0xs.png" alt="enter image description here" /></a></p>
<p>When I change the command to something else, for example "ls" it gets executed and I can see the result in CloudWatch log:</p>
<p><a href="https://i.stack.imgur.com/SkwGc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SkwGc.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/HVnS2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HVnS2.png" alt="enter image description here" /></a></p>
<p>or when I change it to a wrong command, I get an error in the log:</p>
<p><a href="https://i.stack.imgur.com/mrAIs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mrAIs.png" alt="enter image description here" /></a></p>
<p>But When I change it to the right command which should run the App, nothing happens, it's not even showing anything in the log as error</p>
<p>I have added inbound rules to allow the port number needed for connecting to the App but it seems it's not running at all!</p>
<p>What should I do? How can I check to see what is the issue?</p>
<p><strong>UPDATE</strong>: I changed the App Container configuration to make it <code>Essential</code>, it means that the whole Task will fail and stop if this container exits with any error, then I started the Task again and it gets stopped, so now I'm sure that the App Container is crashing and exiting some how but there is nothing in the log!</p>
|
[
{
"answer_id": 74604130,
"author": "Alex Wayne",
"author_id": 62076,
"author_profile": "https://Stackoverflow.com/users/62076",
"pm_score": 3,
"selected": true,
"text": "Extract<T, U> { type: 'user' | 'person', id: string } { type: 'user' } declare const entity: Entity\nconst user: { type: 'user' } = entity\n/*\nType 'Entity' is not assignable to type '{ type: \"user\"; }'.\n Type '{ type: \"user\" | \"person\"; id: string; }' is not assignable to type '{ type: \"user\"; }'.\n Types of property 'type' are incompatible.\n Type '\"user\" | \"person\"' is not assignable to type '\"user\"'.\n Type '\"person\"' is not assignable to type '\"user\"'.(2322)\n*/\n Extract & type User = Entity & { type: 'user' }\n\nconst user: User = { type: 'user', id: 'abc' }\nuser.id // type: string\n"
},
{
"answer_id": 74604225,
"author": "Tobias S.",
"author_id": 8613630,
"author_profile": "https://Stackoverflow.com/users/8613630",
"pm_score": 0,
"selected": false,
"text": "Extract 'user' | 'person' 'user' CustomExtract Partial<T> type CustomExtract<T, U> = \n T extends T \n ? U extends Partial<T> \n ? T \n : never\n : never\n\ntype Animal = CustomExtract<Entity, { type: 'animal' }>\n// type Animal = {\n// type: 'animal';\n// id: number;\n// }\n\ntype User = CustomExtract<Entity, { type: 'user' }>\n// type User = {\n// type: 'user' | 'person';\n// id: string;\n// }\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/955719/"
] |
74,604,073
|
<p>How can I get the value that I am getting with the following jQuery code with JavaScript?</p>
<p><strong>jQuery code snippet:</strong></p>
<pre><code>$('.add-to-cart-btn').on('click', function() {
qualifyingProductVariantId = $(this).closest('form').find("input[type='hidden'][name='id']").val();
});
</code></pre>
<p>As I was trying with <strong>javascript code:</strong></p>
<pre><code>function getVariant(this){
var qualifyingProductVariantId = this.querySelector('[name="related_id"]').value;
alert(qualifyingProductVariantId);
}
</code></pre>
<p>Any help would be much appreciated.</p>
|
[
{
"answer_id": 74604130,
"author": "Alex Wayne",
"author_id": 62076,
"author_profile": "https://Stackoverflow.com/users/62076",
"pm_score": 3,
"selected": true,
"text": "Extract<T, U> { type: 'user' | 'person', id: string } { type: 'user' } declare const entity: Entity\nconst user: { type: 'user' } = entity\n/*\nType 'Entity' is not assignable to type '{ type: \"user\"; }'.\n Type '{ type: \"user\" | \"person\"; id: string; }' is not assignable to type '{ type: \"user\"; }'.\n Types of property 'type' are incompatible.\n Type '\"user\" | \"person\"' is not assignable to type '\"user\"'.\n Type '\"person\"' is not assignable to type '\"user\"'.(2322)\n*/\n Extract & type User = Entity & { type: 'user' }\n\nconst user: User = { type: 'user', id: 'abc' }\nuser.id // type: string\n"
},
{
"answer_id": 74604225,
"author": "Tobias S.",
"author_id": 8613630,
"author_profile": "https://Stackoverflow.com/users/8613630",
"pm_score": 0,
"selected": false,
"text": "Extract 'user' | 'person' 'user' CustomExtract Partial<T> type CustomExtract<T, U> = \n T extends T \n ? U extends Partial<T> \n ? T \n : never\n : never\n\ntype Animal = CustomExtract<Entity, { type: 'animal' }>\n// type Animal = {\n// type: 'animal';\n// id: number;\n// }\n\ntype User = CustomExtract<Entity, { type: 'user' }>\n// type User = {\n// type: 'user' | 'person';\n// id: string;\n// }\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3574257/"
] |
74,604,121
|
<p>My dataset has a dummy variable which divides the data set into two groups. I would like to display the descriptive statistics for both next to each other, like:</p>
<p><a href="https://i.stack.imgur.com/ZLDzZ.png" rel="nofollow noreferrer">example</a></p>
<p>using stargazer. Is this possible?</p>
<p>For example, if there is the mtcars data set and the variable $am divides the dataset into two groups, how can I display the one group on the left side and the other group on the other side?</p>
<p>Thank you!</p>
<p>I was able to display the two statistics below each other (I had to make two separate datasets for each group), but never next to each other.</p>
<pre><code>treated <- mtcars[mtcars$am == 1,]
control <- mtcars[mtcars$am == 0,]
stargazer(treated, control, keep=c("mpg", "cyl", "disp", "hp"),
header=FALSE, title="Descriptive statistics", digits=1, type="text")
</code></pre>
<p><a href="https://i.stack.imgur.com/EXcbn.png" rel="nofollow noreferrer">Descriptive statistics below each other</a></p>
|
[
{
"answer_id": 74658947,
"author": "jrcalabrese",
"author_id": 14992857,
"author_profile": "https://Stackoverflow.com/users/14992857",
"pm_score": 2,
"selected": false,
"text": "stargazer modelsummary gtsummary flextable stargazer mtcars am gtsummary library(tidyverse)\ndata(mtcars)\n\n### modelsummary\n# not great since it treats `cyl` as a continuous variable\n# https://vincentarelbundock.github.io/modelsummary/articles/datasummary.html\nlibrary(modelsummary)\ndatasummary_balance(~am, data = mtcars, dinm = FALSE)\n\n### gtsummary\n# based on example 3 from here\n# https://www.danieldsjoberg.com/gtsummary/reference/add_stat_label.html\nlibrary(gtsummary)\nmtcars %>%\n select(am, mpg, cyl, disp, hp) %>%\n tbl_summary(\n by = am, \n missing = \"no\",\n type = list(mpg ~ 'continuous2',\n cyl ~ 'categorical',\n disp ~ 'continuous2',\n hp ~ 'continuous2'),\n statistic = all_continuous2() ~ c(\"{mean} ({sd})\", \"{median}\")\n ) %>%\n add_stat_label(label = c(mpg, disp, hp) ~ c(\"Mean (SD)\", \"Median\")) %>%\n modify_footnote(everything() ~ NA)\n\n### flextable\n# this function only works on continuous vars, so I removed `cyl`\n# https://davidgohel.github.io/flextable/reference/continuous_summary.html\nlibrary(flextable)\nmtcars %>%\n select(am, mpg, cyl, disp, hp) %>%\n continuous_summary(\n by = \"am\",\n hide_grouplabel = FALSE,\n digits = 3\n )\n"
},
{
"answer_id": 74659815,
"author": "Vincent",
"author_id": 342331,
"author_profile": "https://Stackoverflow.com/users/342331",
"pm_score": 0,
"selected": false,
"text": "modelsummary datasummary datasummary datasummary_balance() library(modelsummary)\ndat <- mtcars[, c(\"mpg\", \"cyl\", \"disp\", \"hp\", \"am\")]\ndatasummary(\n All(dat) ~ Factor(am) * (N + Mean + SD + Min + Max),\n data = dat)\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625239/"
] |
74,604,145
|
<p>Using <a href="https://stackoverflow.com/questions/19882085/subset-dataframe-using-a-loop">this SO question</a> as a starting point, if my data appears like this:</p>
<pre><code>index state date Amount
2 FL 2010-06-08 0
21 FL 2010-10-08 10
6 FL 2010-08-16 30
5 GA 2010-11-25 20
9 GA 2010-01-01 0
8 CA 2011-03-06 10
12 CA 2012-03-12 10
11 CA 2012-06-21 10
15 NY 2010-01-01 30
13 NY 2010-04-06 20
</code></pre>
<p>How do I use the loop example from that question's highest voted answer to create data tables for export that are named based on the state value? My goal is to export each state-specific data table to csv for separate analyses. These are large datasets so prefer using data.table package.</p>
<p>Below is the loop from the question linked above using the <code>iris</code> dataset.</p>
<pre><code>iris_split <- split(iris, iris$Species)
new_names <- c("one", "two", "three")
for (i in 1:length(iris_split)) {
assign(new_names[i], iris_split[[i]])
}
</code></pre>
|
[
{
"answer_id": 74658947,
"author": "jrcalabrese",
"author_id": 14992857,
"author_profile": "https://Stackoverflow.com/users/14992857",
"pm_score": 2,
"selected": false,
"text": "stargazer modelsummary gtsummary flextable stargazer mtcars am gtsummary library(tidyverse)\ndata(mtcars)\n\n### modelsummary\n# not great since it treats `cyl` as a continuous variable\n# https://vincentarelbundock.github.io/modelsummary/articles/datasummary.html\nlibrary(modelsummary)\ndatasummary_balance(~am, data = mtcars, dinm = FALSE)\n\n### gtsummary\n# based on example 3 from here\n# https://www.danieldsjoberg.com/gtsummary/reference/add_stat_label.html\nlibrary(gtsummary)\nmtcars %>%\n select(am, mpg, cyl, disp, hp) %>%\n tbl_summary(\n by = am, \n missing = \"no\",\n type = list(mpg ~ 'continuous2',\n cyl ~ 'categorical',\n disp ~ 'continuous2',\n hp ~ 'continuous2'),\n statistic = all_continuous2() ~ c(\"{mean} ({sd})\", \"{median}\")\n ) %>%\n add_stat_label(label = c(mpg, disp, hp) ~ c(\"Mean (SD)\", \"Median\")) %>%\n modify_footnote(everything() ~ NA)\n\n### flextable\n# this function only works on continuous vars, so I removed `cyl`\n# https://davidgohel.github.io/flextable/reference/continuous_summary.html\nlibrary(flextable)\nmtcars %>%\n select(am, mpg, cyl, disp, hp) %>%\n continuous_summary(\n by = \"am\",\n hide_grouplabel = FALSE,\n digits = 3\n )\n"
},
{
"answer_id": 74659815,
"author": "Vincent",
"author_id": 342331,
"author_profile": "https://Stackoverflow.com/users/342331",
"pm_score": 0,
"selected": false,
"text": "modelsummary datasummary datasummary datasummary_balance() library(modelsummary)\ndat <- mtcars[, c(\"mpg\", \"cyl\", \"disp\", \"hp\", \"am\")]\ndatasummary(\n All(dat) ~ Factor(am) * (N + Mean + SD + Min + Max),\n data = dat)\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2868585/"
] |
74,604,150
|
<h2>This is My text I want to change color which is in single quotes and last id, This text is dynamic Its coming from API -></h2>
<p>Your query 'THIS IS TESTING SUBJECT TRYING TO EXPLORE HAHA .' has been raised with ticket id: #0606c2a23d9e</p>
<p>I want to make like this
<a href="https://i.stack.imgur.com/DsIku.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DsIku.png" alt="enter image description here" /></a></p>
<p>How to make it like this</p>
|
[
{
"answer_id": 74604198,
"author": "Munsif Ali",
"author_id": 14466860,
"author_profile": "https://Stackoverflow.com/users/14466860",
"pm_score": 1,
"selected": false,
"text": "RichText(\n text: TextSpan(\n text: 'Hello ',\n style: DefaultTextStyle.of(context).style,\n children: const <TextSpan>[\n TextSpan(text: 'bold', style: TextStyle(fontWeight: FontWeight.bold)),\n TextSpan(text: ' world!'),\n],\n),\n)\n"
},
{
"answer_id": 74604578,
"author": "powerman23rus",
"author_id": 6163011,
"author_profile": "https://Stackoverflow.com/users/6163011",
"pm_score": 0,
"selected": false,
"text": "Your query 'THIS IS TESTING SUBJECT TRYING TO EXPLORE HAHA .' has been raised with ticket id: #0606c2a23d9e\n regex final regex = RegExp('\\'.+\\'');\n target regex final target = regex.stringMatch(string)!;\n target placeholder final placeholder = '{@}';\nfinal updatedString = string.replaceAll(regex, placeholder);\n updatedString tokens final tokens = updatedString.split(RegExp(' '));\n TextSpan token placeholder target final spans = tokens\n .map((e) => e == placeholder\n ? TextSpan(text: target + ' ', style: TextStyle(color: Colors.blue))\n : TextSpan(text: e + ' '))\n .toList();\n Text.rich(TextSpan(children: spans)))\n class Page extends StatelessWidget {\n final String string;\n\n const Page({Key? key, required this.string}) : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n final regex = RegExp('\\'.+\\'');\n const placeholder = '{@}';\n final target = regex.stringMatch(string)!;\n final updatedString = string.replaceAll(regex, placeholder);\n final tokens = updatedString.split(RegExp(' '));\n final spans = tokens\n .map((e) => e == placeholder\n ? TextSpan(text: target + ' ', style: const TextStyle(color: Colors.blue))\n : TextSpan(text: e + ' '))\n .toList();\n \n return Center(child: Text.rich(TextSpan(children: spans)));\n }\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15610685/"
] |
74,604,190
|
<p>I have a column with two types of names (embedded within a longer string).</p>
<p>names are like <code>A/HK/RATATA/Lol(2007)</code> or <code>A/chickapig/RATATA/Lol(2003)</code>.</p>
<p>I would like to filter using a regular expression based on the number of "/" within each name.</p>
<pre><code>Example:
Influenza A virus (A/chicken/Wenzhou/642/2013(H9N2))
Influenza A virus (A/chicken/Wenzhou/643/2013(H9N2))
Influenza A virus (A/chicken/Wenzhou/644/2013(H9N2))
Influenza A virus (A/Wenzhou/mamamam/2013(H9N2))
</code></pre>
<p>I would only like to filter the row containing Influenza A virus (A/Wenzhou/mamamam/2013(H9N2))</p>
<p>I tried using \ to scape /, not even sure if it makes sense.</p>
|
[
{
"answer_id": 74604239,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "/ str_count filter library(dplyr)\nn <- 3\ndf %>%\n filter(str_count(col1, fixed(\"/\")) == n)\n col1\n1 Influenza A virus (A/Wenzhou/mamamam/2013(H9N2))\n df <- structure(list(col1 = c(\"Influenza A virus (A/chicken/Wenzhou/642/2013(H9N2))\", \n\"Influenza A virus (A/chicken/Wenzhou/643/2013(H9N2))\", \"Influenza A virus (A/chicken/Wenzhou/644/2013(H9N2))\", \n\"Influenza A virus (A/Wenzhou/mamamam/2013(H9N2))\")),\n class = \"data.frame\", row.names = c(NA, \n-4L))\n"
},
{
"answer_id": 74604428,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 1,
"selected": false,
"text": "nchar gsub library(dplyr)\nlibrary(tibble)\n\n# example tibble\ndf <- tibble(x = c(\"Influenza A virus (A/chicken/Wenzhou/642/2013(H9N2))\",\n \"Influenza A virus (A/chicken/Wenzhou/643/2013(H9N2))\",\n \"Influenza A virus (A/chicken/Wenzhou/644/2013(H9N2))\",\n \"Influenza A virus (A/Wenzhou/mamamam/2013(H9N2))\"))\n\ndf %>% \n filter(nchar(x) - nchar(gsub('\\\\/', '', x)) == 3)\n x \n <chr> \n1 Influenza A virus (A/Wenzhou/mamamam/2013(H9N2))\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8877090/"
] |
74,604,193
|
<p>I am trying to randomize a number with 32 hexadecimal digits in bash with seed which depends on the date.<br />
I thought about something like: <code>RANDOM=$(date +%N | cut -b4-9)</code> , but it's not give me 32 hexadecimal digits.</p>
<p>ideas?</p>
|
[
{
"answer_id": 74604239,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "/ str_count filter library(dplyr)\nn <- 3\ndf %>%\n filter(str_count(col1, fixed(\"/\")) == n)\n col1\n1 Influenza A virus (A/Wenzhou/mamamam/2013(H9N2))\n df <- structure(list(col1 = c(\"Influenza A virus (A/chicken/Wenzhou/642/2013(H9N2))\", \n\"Influenza A virus (A/chicken/Wenzhou/643/2013(H9N2))\", \"Influenza A virus (A/chicken/Wenzhou/644/2013(H9N2))\", \n\"Influenza A virus (A/Wenzhou/mamamam/2013(H9N2))\")),\n class = \"data.frame\", row.names = c(NA, \n-4L))\n"
},
{
"answer_id": 74604428,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 1,
"selected": false,
"text": "nchar gsub library(dplyr)\nlibrary(tibble)\n\n# example tibble\ndf <- tibble(x = c(\"Influenza A virus (A/chicken/Wenzhou/642/2013(H9N2))\",\n \"Influenza A virus (A/chicken/Wenzhou/643/2013(H9N2))\",\n \"Influenza A virus (A/chicken/Wenzhou/644/2013(H9N2))\",\n \"Influenza A virus (A/Wenzhou/mamamam/2013(H9N2))\"))\n\ndf %>% \n filter(nchar(x) - nchar(gsub('\\\\/', '', x)) == 3)\n x \n <chr> \n1 Influenza A virus (A/Wenzhou/mamamam/2013(H9N2))\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9459321/"
] |
74,604,195
|
<p>I pull data with react-query and need to store it in state due to some form editing that is happening later.</p>
<p>Before the form editing, it worked well:</p>
<pre><code>import { useQuery } from '@apollo/client';
import { SINGLE_PARTICIPANT_QUERY } from 'queries/participantQueries';
import { ProfileGeneral } from './ProfileGeneral';
const ProfilePage = ({ id }) => {
const {data, loading, error} = useQuery(SINGLE_PARTICIPANT_QUERY, {
variables: {
id
}
});
if (loading) {
return <div>Loading</div>;
}
if (error) {
return (
<div>
{error.message} />
</div>
);
}
const { participant } =data;
return (
<div>
<ProfileGeneral participant={participant} />
</div>
</code></pre>
<p>But after trying to add it into state, I keep getting an error message, indicating that it renders without having the data ready.</p>
<pre><code>import { useQuery } from '@apollo/client';
import { SINGLE_PARTICIPANT_QUERY } from 'queries/participantQueries';
import { ProfileGeneral } from './ProfileGeneral';
import { useEffect, useState } from 'react';
const ProfilePage = ({ id }) => {
const [participant, setParticipant] = useState(null);
const { data, loading, error } = useQuery(SINGLE_PARTICIPANT_QUERY, {
variables: {
id
}
});
useEffect(() => {
if (data && data.participant) {
setParticipant(data.participant);
}
}, [data, participant]);
if (loading) {
return <div>Loading</div>;
}
if (error) {
return (
<div>
{error.message} />
</div>
);
}
return (
<div>
<ProfileGeneral participant={participant} />
</div>
</code></pre>
<p>I get back:</p>
<pre><code>Server Error
TypeError: Cannot read properties of null (reading 'firstName')
This error happened while generating the page. Any console logs will be displayed in the terminal window.
</code></pre>
<p>I know that I need to make it wait or re-render as soon as it has the data from the query, but I am not sure how to prevent it.</p>
<p>Thank you for taking a look!</p>
|
[
{
"answer_id": 74604239,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "/ str_count filter library(dplyr)\nn <- 3\ndf %>%\n filter(str_count(col1, fixed(\"/\")) == n)\n col1\n1 Influenza A virus (A/Wenzhou/mamamam/2013(H9N2))\n df <- structure(list(col1 = c(\"Influenza A virus (A/chicken/Wenzhou/642/2013(H9N2))\", \n\"Influenza A virus (A/chicken/Wenzhou/643/2013(H9N2))\", \"Influenza A virus (A/chicken/Wenzhou/644/2013(H9N2))\", \n\"Influenza A virus (A/Wenzhou/mamamam/2013(H9N2))\")),\n class = \"data.frame\", row.names = c(NA, \n-4L))\n"
},
{
"answer_id": 74604428,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 1,
"selected": false,
"text": "nchar gsub library(dplyr)\nlibrary(tibble)\n\n# example tibble\ndf <- tibble(x = c(\"Influenza A virus (A/chicken/Wenzhou/642/2013(H9N2))\",\n \"Influenza A virus (A/chicken/Wenzhou/643/2013(H9N2))\",\n \"Influenza A virus (A/chicken/Wenzhou/644/2013(H9N2))\",\n \"Influenza A virus (A/Wenzhou/mamamam/2013(H9N2))\"))\n\ndf %>% \n filter(nchar(x) - nchar(gsub('\\\\/', '', x)) == 3)\n x \n <chr> \n1 Influenza A virus (A/Wenzhou/mamamam/2013(H9N2))\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4551483/"
] |
74,604,202
|
<p>Sorry , please bare with me , ah I would just like to ask for the terminology and how do we implement or convert a string into something like below. I am not sure if that is string array or something but the output should look like the example.</p>
<p>Thanks for any help and ideas. Appreciated.</p>
<pre><code>let a = 'propertyAccountId';
output = "[\"propertyAccountId\"]"
let b = 'name';
output = "[\"name\"]"
</code></pre>
|
[
{
"answer_id": 74604277,
"author": "Martinez",
"author_id": 19027584,
"author_profile": "https://Stackoverflow.com/users/19027584",
"pm_score": 2,
"selected": true,
"text": "const b = 'name'\nconst output = JSON.stringify([b])\n"
},
{
"answer_id": 74604346,
"author": "jjj",
"author_id": 13365797,
"author_profile": "https://Stackoverflow.com/users/13365797",
"pm_score": -1,
"selected": false,
"text": "let a = 'propertyAccountId';\nlet b = 'name';\nconst convert = input => {\n return JSON.stringify([input])\n}\n\nconsole.log(convert(a))\nconsole.log(convert(b))"
},
{
"answer_id": 74605075,
"author": "Mr.Code77",
"author_id": 18128876,
"author_profile": "https://Stackoverflow.com/users/18128876",
"pm_score": 0,
"selected": false,
"text": "let a = \"propertyAccountId\";\n\nfunction convert(stringvar){\n var newstring = `[\"${stringvar}\"]`\n return newstring;\n}\n\nconsole.log(convert(a));\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16703570/"
] |
74,604,221
|
<p>I have a DataFrame that has a column with time data like ['25:45','12:34:34'], the initial idea is: first convert this column to a list called "time_list". Then with a for, iterate and convert it to minutes</p>
<pre><code>time_list = df7[' Chip Time'].tolist()
time_mins = []
for i in time_list:
h, m, s = i.split(':')
math = (int(h) * 3600 + int(m) * 60 + int(s))/60
time_mins.append(math)
</code></pre>
<p>But I got this error: ValueError: too many values to unpack... . It is because within the data there are values of only minutes and seconds but also others with hours, minutes and seconds.</p>
<p>My idea is to convert this column into a single format, that of 'hh:mm:ss' but I can't find the way. Thanks for your reply</p>
|
[
{
"answer_id": 74604818,
"author": "user911346",
"author_id": 20586552,
"author_profile": "https://Stackoverflow.com/users/20586552",
"pm_score": 1,
"selected": false,
"text": "h, m, s = i.split(':') t = i.split(':') i.split i = [aa:bb] t = i.split(':')\nfor i in range(len(t)):\n math += t[i] * 3600 ** (1./(60 ** i))\n # 3600 ** (1./(60 ** i)) returns 3600, 60, 1 for i = 0, 1, 2\ntime_mins.append(math)\n t = i.split(':')\nif len(t) == 2:\n time_mins.append(str(i)+\":00\")\nelse:\n time_mins.append(i)\n"
},
{
"answer_id": 74605366,
"author": "Josue V.",
"author_id": 20163459,
"author_profile": "https://Stackoverflow.com/users/20163459",
"pm_score": 0,
"selected": false,
"text": "def format_date(n):\n if len(n) == 5:\n return \"{}:{}:{}\".format('00', n[0:2], n[3:5])\n else:\n return n**\n\n df7['ChipTime'] = df7.apply(lambda x: format_date(x.ChipTime), axis=1)\ndf7\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20163459/"
] |
74,604,238
|
<p>I iterate through a nested dictionary taken from a json including one of the keys ("price") and sometimes a list sometimes a dictionary.</p>
<pre><code>Data={"main": {"sub_main": [
{"id": "995", "item": "850", "price": {"ref": "razorback", "value": "250"}},
{"id": "953", "item": "763", "price": [{"ref": "razorback", "value": "450"},{"ref": "sumatra", "value": "370"},{"ref": "ligea", "value": "320"} ]},
]}}
</code></pre>
<p>I filter the result according to the value of another key ("id").</p>
<pre><code># here, the value of "price" key is a dict
result1 = [item["price"] for item in Data["main"]["sub_main"] if item["id"]=="995"]
# here, the value of "price" key is a list of dict
result2 = [item["price"] for item in Data["main"]["sub_main"] if item["id"]=="953"]
</code></pre>
<p>then I convert the result into a dictionary</p>
<p>#here I have what I wanted, because the "price" key is a dict</p>
<pre><code>dresult={k:v for e in result1 for (k,v) in e.items()}
</code></pre>
<p>but when the "price" key has a dictionary list as its value, it doesn't work, because of course I get an error "'list' object has no attribute 'items'</p>
<p>#it cannot loop on the value and key because the "price" key is a list</p>
<pre><code>dresult={k:v for e in result2 for (k,v) in e.items()}
</code></pre>
<p>how to make it convert the result to dictionary in both cases (because I'm iterating through thousands of data). how to dynamically do a type test and change to finally have a dictionary.I would like to use the result to display in a view in Django. I need it to be a dictionary</p>
<p>thank you.</p>
|
[
{
"answer_id": 74604945,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": true,
"text": "item['price'] dict list ref value Data = {\n \"main\": {\n \"sub_main\": [\n {\n \"id\": \"995\",\n \"item\": \"850\",\n \"price\": {\"ref\": \"razorback\", \"value\": \"250\"},\n },\n {\n \"id\": \"953\",\n \"item\": \"763\",\n \"price\": [\n {\"ref\": \"razorback\", \"value\": \"450\"},\n {\"ref\": \"sumatra\", \"value\": \"370\"},\n {\"ref\": \"ligea\", \"value\": \"320\"},\n ],\n },\n ]\n }\n}\n\n\nids = \"995\", \"953\"\n\nfor id_ in ids:\n out = {\n d[\"ref\"]: d[\"value\"]\n for item in Data[\"main\"][\"sub_main\"]\n for d in (\n [item[\"price\"]]\n if isinstance(item[\"price\"], dict)\n else item[\"price\"]\n )\n if item[\"id\"] == id_\n }\n print(id_, out)\n 995 {'razorback': '250'}\n953 {'razorback': '450', 'sumatra': '370', 'ligea': '320'}\n"
},
{
"answer_id": 74605067,
"author": "Dante ",
"author_id": 16320430,
"author_profile": "https://Stackoverflow.com/users/16320430",
"pm_score": 0,
"selected": false,
"text": "id def get_result(id_):\n price= [item[\"price\"] for item in Data[\"main\"][\"sub_main\"] if item[\"id\"]==id_][0]\n match type(price).__name__:\n case 'dict':return [price]\n case 'list':return price\n string dresult=get_result('953')#[{'ref': 'razorback', 'value': '450'}, {'ref': 'sumatra', 'value': '370'}, {'ref': 'ligea', 'value': '320'}]\n dresult=get_result('995')#[{'ref': 'razorback', 'value': '250'}]\n return render(request, 'app_name/template_name.html',{'dictionaries': dresult})\n ie.{'ref': 'razorback', 'value': '450'}, {'ref': 'sumatra', 'value': '370'}, {'ref': 'ligea', 'value': '320'} {% for dictionary in dictionaries %}:\n {{ dictionary.ref}}#to get ref\n{{ dictionary.value}}#to get value\n ...\n{%endfor%}\n pk def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n \n context['dictionaries'] = get_result(self.kwargs.get('pk'))\n return context\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11230924/"
] |
74,604,248
|
<p>I'm currently making a instagram type of app in Android Studio, my app only shows the newest pic at the bottom of the grid. The Collections.reverse(arrayList) is not working</p>
<p>here's my main.java</p>
<pre><code>package com.example.mygram;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.mygram.utils.SpacingItemDecoder;
import java.util.ArrayList;
import java.util.Collections;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity {
private static final int IMAGE_PICK_CODE=1000;
private static final int PERMISSION_CODE=1001;
RecyclerView recyclerView;
TextView textView;
Button pick, gallery;
CircleImageView profpic;
ArrayList <Uri> uri = new ArrayList<>();
RecyclerAdapter adapter ;
private static final int Read_Permission = 101;
private static final int PICK_IMAGE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
profpic = findViewById(R.id.profile_image);
gallery = findViewById(R.id.select);
gallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
galleryActivityResultLauncher.launch(intent);
}
});
textView = findViewById(R.id.totalPhotos);
recyclerView = findViewById(R.id.recyclerView_Gallery_Images);
pick = findViewById(R.id.pick);
adapter = new RecyclerAdapter(uri);
recyclerView.setLayoutManager(new GridLayoutManager(MainActivity.this,3));
SpacingItemDecoder itemDecorator = new SpacingItemDecoder(10);
recyclerView.addItemDecoration(itemDecorator);
recyclerView.setAdapter(adapter);
Collections.reverse(uri);
pick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Read_Permission);
return;
}
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
//intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
});
}
private ActivityResultLauncher<Intent> galleryActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK){
Intent data = result.getData();
Uri imageUri = data.getData();
profpic.setImageURI(imageUri);
}
else{
Toast.makeText(MainActivity.this, "Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
);
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && null != data){
if(data.getClipData()!=null){
int countofImages = data.getClipData().getItemCount();
for(int i=0; i<countofImages; i++){
Uri imageuri = data.getClipData().getItemAt(i).getUri();
uri.add(imageuri);
}
adapter.notifyDataSetChanged();
textView.setText("");
}else{
Uri imageuri = data.getData();
uri.add(imageuri);
}
adapter.notifyDataSetChanged();
textView.setText("");
}else{
Toast.makeText(this, "You haven't pick any images", Toast.LENGTH_SHORT).show();
}
}
}
</code></pre>
<p>here's my adapter.java</p>
<pre><code>package com.example.mygram;
import android.media.Image;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<Uri> uriArrayList;
public RecyclerAdapter(ArrayList<Uri> uriArrayList) {
this.uriArrayList = uriArrayList;
}
@NonNull
@Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.custom_single_image,parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerAdapter.ViewHolder holder, int position) {
holder.imageView.setImageURI(uriArrayList.get(position));
}
@Override
public int getItemCount() {
return uriArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image);
}
}
}
</code></pre>
<p>I want my app to display the last selected images at the top and first grid. I dont know what code should I use and where to put it. Please help, thank you!</p>
|
[
{
"answer_id": 74604945,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": true,
"text": "item['price'] dict list ref value Data = {\n \"main\": {\n \"sub_main\": [\n {\n \"id\": \"995\",\n \"item\": \"850\",\n \"price\": {\"ref\": \"razorback\", \"value\": \"250\"},\n },\n {\n \"id\": \"953\",\n \"item\": \"763\",\n \"price\": [\n {\"ref\": \"razorback\", \"value\": \"450\"},\n {\"ref\": \"sumatra\", \"value\": \"370\"},\n {\"ref\": \"ligea\", \"value\": \"320\"},\n ],\n },\n ]\n }\n}\n\n\nids = \"995\", \"953\"\n\nfor id_ in ids:\n out = {\n d[\"ref\"]: d[\"value\"]\n for item in Data[\"main\"][\"sub_main\"]\n for d in (\n [item[\"price\"]]\n if isinstance(item[\"price\"], dict)\n else item[\"price\"]\n )\n if item[\"id\"] == id_\n }\n print(id_, out)\n 995 {'razorback': '250'}\n953 {'razorback': '450', 'sumatra': '370', 'ligea': '320'}\n"
},
{
"answer_id": 74605067,
"author": "Dante ",
"author_id": 16320430,
"author_profile": "https://Stackoverflow.com/users/16320430",
"pm_score": 0,
"selected": false,
"text": "id def get_result(id_):\n price= [item[\"price\"] for item in Data[\"main\"][\"sub_main\"] if item[\"id\"]==id_][0]\n match type(price).__name__:\n case 'dict':return [price]\n case 'list':return price\n string dresult=get_result('953')#[{'ref': 'razorback', 'value': '450'}, {'ref': 'sumatra', 'value': '370'}, {'ref': 'ligea', 'value': '320'}]\n dresult=get_result('995')#[{'ref': 'razorback', 'value': '250'}]\n return render(request, 'app_name/template_name.html',{'dictionaries': dresult})\n ie.{'ref': 'razorback', 'value': '450'}, {'ref': 'sumatra', 'value': '370'}, {'ref': 'ligea', 'value': '320'} {% for dictionary in dictionaries %}:\n {{ dictionary.ref}}#to get ref\n{{ dictionary.value}}#to get value\n ...\n{%endfor%}\n pk def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n \n context['dictionaries'] = get_result(self.kwargs.get('pk'))\n return context\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20604535/"
] |
74,604,250
|
<p>Hey I need some help with sql query
I have this data</p>
<pre><code>count Timestamp
1 10:05
2 10:06
3 10:07
1 10:08
2 10:09
3 10:10
</code></pre>
<p>I would like to obtain for each timestamp the total of count until that moment</p>
<pre><code>count Timestamp
1 10:05
3 10:06
6 10:07
7 10:08
9 10:09
12 10:10
</code></pre>
<p>I tried a lot of things
the last I have and blocked with it is :</p>
<pre><code>select sum(count), timestamp
from table
where timestamp > now() - interval 2 hour
group by date_format(timestamp, '%Y-%m-%d %h:%i')
</code></pre>
<p>But with that I dont get an increase value everytime for the sum, i guess it is because i use group by and the timestamp</p>
<p>I was thinking adding a join where I will do without the group by but how can I get the sum until the timestamp needed ? and not for all the table</p>
<pre><code>select sum(count)
from table
</code></pre>
|
[
{
"answer_id": 74604945,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": true,
"text": "item['price'] dict list ref value Data = {\n \"main\": {\n \"sub_main\": [\n {\n \"id\": \"995\",\n \"item\": \"850\",\n \"price\": {\"ref\": \"razorback\", \"value\": \"250\"},\n },\n {\n \"id\": \"953\",\n \"item\": \"763\",\n \"price\": [\n {\"ref\": \"razorback\", \"value\": \"450\"},\n {\"ref\": \"sumatra\", \"value\": \"370\"},\n {\"ref\": \"ligea\", \"value\": \"320\"},\n ],\n },\n ]\n }\n}\n\n\nids = \"995\", \"953\"\n\nfor id_ in ids:\n out = {\n d[\"ref\"]: d[\"value\"]\n for item in Data[\"main\"][\"sub_main\"]\n for d in (\n [item[\"price\"]]\n if isinstance(item[\"price\"], dict)\n else item[\"price\"]\n )\n if item[\"id\"] == id_\n }\n print(id_, out)\n 995 {'razorback': '250'}\n953 {'razorback': '450', 'sumatra': '370', 'ligea': '320'}\n"
},
{
"answer_id": 74605067,
"author": "Dante ",
"author_id": 16320430,
"author_profile": "https://Stackoverflow.com/users/16320430",
"pm_score": 0,
"selected": false,
"text": "id def get_result(id_):\n price= [item[\"price\"] for item in Data[\"main\"][\"sub_main\"] if item[\"id\"]==id_][0]\n match type(price).__name__:\n case 'dict':return [price]\n case 'list':return price\n string dresult=get_result('953')#[{'ref': 'razorback', 'value': '450'}, {'ref': 'sumatra', 'value': '370'}, {'ref': 'ligea', 'value': '320'}]\n dresult=get_result('995')#[{'ref': 'razorback', 'value': '250'}]\n return render(request, 'app_name/template_name.html',{'dictionaries': dresult})\n ie.{'ref': 'razorback', 'value': '450'}, {'ref': 'sumatra', 'value': '370'}, {'ref': 'ligea', 'value': '320'} {% for dictionary in dictionaries %}:\n {{ dictionary.ref}}#to get ref\n{{ dictionary.value}}#to get value\n ...\n{%endfor%}\n pk def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n \n context['dictionaries'] = get_result(self.kwargs.get('pk'))\n return context\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625788/"
] |
74,604,275
|
<p>I am aware of the sorted() function but I am having a little trouble using it/implementing it in my code. I have a database containing student records such as Name, address, age etc. When the user selects "4" the program runs the function to Display all records saved in the database and I desire it to be sorted alphabetically. My function works and displays the records, just not alphabetically. How could I take advantage of the sorted() function to make my code display the records alphabetically? Any help would be greatly appreciated.</p>
<pre><code>rom ShowAllRecords import show_record
from deleteRecord import delete_student
from showRecord import view_records
from createRecord import add_record
global student_info
global database
"""
Fields :- ['Student ID', 'First name', 'Last Name', 'age', 'address', 'phone number']
1. Create a new Record
2. Show a record
3. Delete a record
4. Display All Records.
5. Exit
"""
student_info = ['Student ID', 'First name', 'last name', 'age', 'address', 'phone number']
database = 'file_records.txt'
def display_menu():
print("**********************************************")
print(" RECORDS MANAGER ")
print("**********************************************")
print("1. Create a new record. ")
print("2. Show a record. ")
print("3. Delete a record. ")
print("4. Display All Records. ")
print("5. Exit")
while True:
display_menu()
choice = input("Enter your choice: ")
if choice == '1':
print('You have chosen "Create a new record."')
add_record()
elif choice == '2':
print('You have chosen "Show a record"')
show_record()
elif choice == '3':
delete_student()
elif choice == '4':
print('You have chosen "Display ALL records"')
view_records()
else:
break
print("**********************************************")
print(" RECORDS MANAGER ")
print("**********************************************")
</code></pre>
<p>ViewRecords function-</p>
<pre><code>import csv
student_info = ['Student ID', 'First name', 'last name', 'age', 'address', 'phone number']
database = 'file_records.txt'
def view_records():
global student_info
global database
print("--- Student Records ---")
with open(database, "r", encoding="utf-8") as f:
reader = csv.reader(f)
for x in student_info:
print(x, end='\t |')
print("\n-----------------------------------------------------------------")
for row in reader:
for item in row:
print(item, end="\t |")
print("\n")
input("Press any key to continue")
</code></pre>
<p>I know I should use the sorted function, just not sure where/how to properly implement it within my code</p>
<p>Sample Run:</p>
<blockquote>
<p>Blockquote</p>
</blockquote>
<hr />
<pre><code> RECORDS MANAGER
</code></pre>
<hr />
<pre><code> 1. Create a new record.
2. Show a record.
3. Delete a record.
4. Display All Records.
5. Exit.
</code></pre>
<p>Enter your option [1 - 5]: 4
You have chosen "Display ALL records in alphabetical order by last name."
Would you like the registry sorted alphabetically in Ascending or Descending order? (A or D): D</p>
<p>Last Name: Hunt
First Name: Alan
Student ID: 875653
Age: 23
Address: 345 Ocean Way
Phone number: 3334445454</p>
<p>Last Name: Farrow
First Name: Mia
Student ID: 86756475
Age: 22
Address: 34 Lotus Ct
Phone number: 9994448585</p>
<p>Done! Press enter to continue.
returning to Main Menu.</p>
|
[
{
"answer_id": 74604945,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": true,
"text": "item['price'] dict list ref value Data = {\n \"main\": {\n \"sub_main\": [\n {\n \"id\": \"995\",\n \"item\": \"850\",\n \"price\": {\"ref\": \"razorback\", \"value\": \"250\"},\n },\n {\n \"id\": \"953\",\n \"item\": \"763\",\n \"price\": [\n {\"ref\": \"razorback\", \"value\": \"450\"},\n {\"ref\": \"sumatra\", \"value\": \"370\"},\n {\"ref\": \"ligea\", \"value\": \"320\"},\n ],\n },\n ]\n }\n}\n\n\nids = \"995\", \"953\"\n\nfor id_ in ids:\n out = {\n d[\"ref\"]: d[\"value\"]\n for item in Data[\"main\"][\"sub_main\"]\n for d in (\n [item[\"price\"]]\n if isinstance(item[\"price\"], dict)\n else item[\"price\"]\n )\n if item[\"id\"] == id_\n }\n print(id_, out)\n 995 {'razorback': '250'}\n953 {'razorback': '450', 'sumatra': '370', 'ligea': '320'}\n"
},
{
"answer_id": 74605067,
"author": "Dante ",
"author_id": 16320430,
"author_profile": "https://Stackoverflow.com/users/16320430",
"pm_score": 0,
"selected": false,
"text": "id def get_result(id_):\n price= [item[\"price\"] for item in Data[\"main\"][\"sub_main\"] if item[\"id\"]==id_][0]\n match type(price).__name__:\n case 'dict':return [price]\n case 'list':return price\n string dresult=get_result('953')#[{'ref': 'razorback', 'value': '450'}, {'ref': 'sumatra', 'value': '370'}, {'ref': 'ligea', 'value': '320'}]\n dresult=get_result('995')#[{'ref': 'razorback', 'value': '250'}]\n return render(request, 'app_name/template_name.html',{'dictionaries': dresult})\n ie.{'ref': 'razorback', 'value': '450'}, {'ref': 'sumatra', 'value': '370'}, {'ref': 'ligea', 'value': '320'} {% for dictionary in dictionaries %}:\n {{ dictionary.ref}}#to get ref\n{{ dictionary.value}}#to get value\n ...\n{%endfor%}\n pk def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n \n context['dictionaries'] = get_result(self.kwargs.get('pk'))\n return context\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74604275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20524919/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.