qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,302,175
<p>I was trying to run a program using intel compilers but while compiling the program it showed error. It was was due to cmake.</p> <pre><code>cmake -G &quot;Visual Studio 17 2022&quot; -A x64 -T &quot;Intel(R) oneAPI DPC++ Compiler&quot; .. -- CMAKE_BUILD_TYPE is unset, defaulting to Release -- Selecting Windows SDK version 10.0.22000.0 to target Windows 10.0.25099. CMake Error at CMakeLists.txt:81 (project): Failed to run MSBuild command: C:/Program Files/Microsoft Visual Studio/2022/Community/MSBuild/Current/Bin/amd64/MSBuild.exe to get the value of VCTargetsPath: MSBuild version 17.3.1+2badb37d1 for .NET Framework Build started 9/2/2022 10:51:43 AM. Project &quot;C:\Users\mtc\source\repos\onednn\build\CMakeFiles\3.23.1\VCTargetsPath.vcxproj&quot; on node 1 (default targets). C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Microsoft\VC\v170\Microsoft.CppBuild.targets(460,5): error MSB8020: The build tools for Intel(R) oneAPI DPC++ Compiler (Platform Toolset = 'Intel(R) oneAPI DPC++ Compiler') cannot be found. To build using the Intel(R) oneAPI DPC++ Compiler build tools, please install Intel(R) oneAPI DPC++ Compiler build tools. Alternatively, you may upgrade to the current Visual Studio tools by selecting the Project menu or right-click the solution, and then selecting &quot;Retarget solution&quot;. [C:\Users\mtc\source\repos\onednn\build\CMakeFiles\3.23.1\VCTargetsPath.vcxproj] Done Building Project &quot;C:\Users\mtc\source\repos\onednn\build\CMakeFiles\3.23.1\VCTargetsPath.vcxproj&quot; (default targets) -- FAILED &quot;C:\Users\mtc\source\repos\onednn\build\CMakeFiles\3.23.1\VCTargetsPath.vcxproj&quot; (default target) (1) -&gt; (PrepareForBuild target) -&gt; C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Microsoft\VC\v170\Microsoft.CppBuild.targets(460,5): error MSB8020: The build tools for Intel(R) oneAPI DPC++ Compiler (Platform Toolset = 'Intel(R) oneAPI DPC++ Compiler') cannot be found. To build using the Intel(R) oneAPI DPC++ Compiler build tools, please install Intel(R) oneAPI DPC++ Compiler build tools. Alternatively, you may upgrade to the current Visual Studio tools by selecting the Project menu or right-click the solution, and then selecting &quot;Retarget solution&quot;. [C:\Users\mtc\source\repos\onednn\build\CMakeFiles\3.23.1\VCTargetsPath.vcxproj] 0 Warning(s) 1 Error(s) Time Elapsed 00:00:00.15 Exit code: 1 </code></pre>
[ { "answer_id": 74304369, "author": "Arsha Mamoozadeh", "author_id": 11808221, "author_profile": "https://Stackoverflow.com/users/11808221", "pm_score": 0, "selected": false, "text": "C:\\Program Files (x86)\\Intel\\oneAPI\\setvars.bat" }, { "answer_id": 74373918, "author": "AlekhyaV - Intel", "author_id": 15766425, "author_profile": "https://Stackoverflow.com/users/15766425", "pm_score": 2, "selected": true, "text": "cmake -G \"\"Visual Studio 17 2022\"\" -T \"\"Intel C++ Compiler 2022\"\" ...\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20211661/" ]
74,302,199
<p>I have a list of elements and I would like to print 3 of them in cards in every row.</p> <p>the <strong>problem</strong> with the following code : it prints just the first two elements and the loop stops.</p> <p>here's my code im using reactjs and mui :</p> <pre><code>const testList = [//my list] const ListInvoices = (props) =&gt; { const invoicesList = () =&gt; { for(let i = 1; i &lt;= testList?.length; 3*i){ let invList = testList?.slice(i-1, 2*i) return( &lt;Grid container alignItems=&quot;center&quot; justifyContent=&quot;center&quot;&gt; &lt;div style={{ display: &quot;flex&quot;, flexDirection: &quot;row&quot; }}&gt; {invList ?.map((elt, index) =&gt; { return( &lt;Grid item&gt; &lt;Card sx={{m: 2}} key={{index}}&gt; {/* content of card */} &lt;/Card&gt; &lt;/Grid&gt; ) }) } &lt;/div&gt; &lt;/Grid&gt; ) } } return( &lt;Box sx={{ backgroundColor: &quot;#f6f6f6&quot; }} pt={4} pb={4}&gt; &lt;Container maxWidth=&quot;lg&quot;&gt; {invoicesList()} &lt;/Container&gt; &lt;/Box&gt; ) } </code></pre> <p>EDIT : as the answers suggested, i changed this</p> <pre><code> for(let i = 1; i &lt;= testList?.length; i*3) //.. let invList= testList?.slice(i-1, 2*i) </code></pre> <p>to this</p> <pre><code>for(let i = 1; i &lt;= testList?.length; i+3) //.. let invList = testList?.slice(i-1, 3*i) </code></pre> <p>but the <strong>problem is always there</strong></p> <p>thank you in advance</p>
[ { "answer_id": 74302303, "author": "Lochyj", "author_id": 16113187, "author_profile": "https://Stackoverflow.com/users/16113187", "pm_score": 1, "selected": false, "text": "for(let i = 1; i <= testList?.length; 3*i <-- here\n" }, { "answer_id": 74302398, "author": "xifre", "author_id": 19458666, "author_profile": "https://Stackoverflow.com/users/19458666", "pm_score": 1, "selected": false, "text": "for(let i = 1; i <= testList.length; i = i + 3) {\n" }, { "answer_id": 74303932, "author": "hakima maarouf", "author_id": 14994239, "author_profile": "https://Stackoverflow.com/users/14994239", "pm_score": 0, "selected": false, "text": "const testList = [//my list]\n\nconst ListInvoices = (props) => {\n\nreturn(\n <Box sx={{ backgroundColor: \"#f6f6f6\" }} pt={4} pb={4}>\n <Container maxWidth=\"lg\">\n <Grid container spacing={2} alignItems=\"center\" justifyContent=\"center\">\n {testList?.map((elt, index) => {\n return (\n <Grid item xs={4}>\n <Card sx={{m: 2}} key={{index}}>\n {/*content*/}\n </Card>\n </Grid> \n );\n })\n }\n </Container>\n </Box>\n)\n}\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14994239/" ]
74,302,200
<p>I have recently removed jcenter() repository from the project-level build Gradle.</p> <p>Since then Koin (version: 2.2.2) started giving me the compile-time error below:</p> <p>Could not find org.koin:koin-test:2.0.1</p>
[ { "answer_id": 74302303, "author": "Lochyj", "author_id": 16113187, "author_profile": "https://Stackoverflow.com/users/16113187", "pm_score": 1, "selected": false, "text": "for(let i = 1; i <= testList?.length; 3*i <-- here\n" }, { "answer_id": 74302398, "author": "xifre", "author_id": 19458666, "author_profile": "https://Stackoverflow.com/users/19458666", "pm_score": 1, "selected": false, "text": "for(let i = 1; i <= testList.length; i = i + 3) {\n" }, { "answer_id": 74303932, "author": "hakima maarouf", "author_id": 14994239, "author_profile": "https://Stackoverflow.com/users/14994239", "pm_score": 0, "selected": false, "text": "const testList = [//my list]\n\nconst ListInvoices = (props) => {\n\nreturn(\n <Box sx={{ backgroundColor: \"#f6f6f6\" }} pt={4} pb={4}>\n <Container maxWidth=\"lg\">\n <Grid container spacing={2} alignItems=\"center\" justifyContent=\"center\">\n {testList?.map((elt, index) => {\n return (\n <Grid item xs={4}>\n <Card sx={{m: 2}} key={{index}}>\n {/*content*/}\n </Card>\n </Grid> \n );\n })\n }\n </Container>\n </Box>\n)\n}\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11044592/" ]
74,302,202
<p>My data is undefined when the app is started but after the refresh, the data comes perfectly.</p> <p>For startup It gives me [<strong>Unhandled promise rejection: TypeError: Object.entries requires that input parameter not be null or undefined]</strong></p> <p>But after the refresh, the data comes perfectly and everything working.</p> <p>This is part of my data</p> <pre><code>Object { &quot;attributes&quot;: Object { &quot;htmlName&quot;: null, &quot;id&quot;: 0, &quot;items&quot;: Array [ Object { &quot;htmlName&quot;: &quot;r_1&quot;, &quot;name&quot;: &quot;m2 (Brüt)&quot;, &quot;numeric&quot;: true, &quot;options&quot;: Object {}, &quot;order&quot;: 0, &quot;required&quot;: true, }, Object { &quot;htmlName&quot;: &quot;r_2&quot;, &quot;name&quot;: &quot;m2 (Net)&quot;, &quot;numeric&quot;: true, &quot;options&quot;: Object {}, &quot;order&quot;: 0, &quot;required&quot;: true, }, Object { &quot;htmlName&quot;: &quot;r_164&quot;, &quot;name&quot;: &quot;Arsa Alanı (m2)&quot;, &quot;numeric&quot;: true, &quot;options&quot;: Object {}, &quot;order&quot;: 0, &quot;required&quot;: true, }, Object { &quot;htmlName&quot;: &quot;a_137&quot;, &quot;name&quot;: &quot;Oda Sayısı&quot;, &quot;numeric&quot;: false, &quot;options&quot;: Object { &quot;12&quot;: &quot;1+0&quot;, &quot;13&quot;: &quot;1+1&quot;, &quot;14&quot;: &quot;1.5+1&quot;, &quot;15&quot;: &quot;2+0&quot;, &quot;16&quot;: &quot;2+1&quot;, &quot;17&quot;: &quot;2.5+1&quot;, &quot;18&quot;: &quot;2+2&quot;, &quot;19&quot;: &quot;3+1&quot;, &quot;20&quot;: &quot;3.5+1&quot;, &quot;21&quot;: &quot;3+2&quot;, &quot;22&quot;: &quot;4+1&quot;, &quot;226&quot;: &quot;0+1&quot;, &quot;23&quot;: &quot;4.5+1&quot;, &quot;24&quot;: &quot;4+2&quot;, &quot;25&quot;: &quot;4+3&quot;, &quot;26&quot;: &quot;4+4&quot;, &quot;27&quot;: &quot;5+1&quot;, &quot;28&quot;: &quot;5+2&quot;, &quot;29&quot;: &quot;5+3&quot;, &quot;30&quot;: &quot;5+4&quot;, &quot;31&quot;: &quot;6+1&quot;, &quot;32&quot;: &quot;6+2&quot;, &quot;33&quot;: &quot;6+3&quot;, &quot;34&quot;: &quot;7+1&quot;, &quot;35&quot;: &quot;7+2&quot;, &quot;36&quot;: &quot;7+3&quot;, &quot;37&quot;: &quot;8+1&quot;, &quot;38&quot;: &quot;8+2&quot;, &quot;39&quot;: &quot;8+3&quot;, &quot;40&quot;: &quot;8+4&quot;, &quot;41&quot;: &quot;9+1&quot;, &quot;42&quot;: &quot;9+2&quot;, &quot;43&quot;: &quot;9+3&quot;, &quot;44&quot;: &quot;9+4&quot;, &quot;45&quot;: &quot;9+5&quot;, &quot;46&quot;: &quot;9+6&quot;, &quot;47&quot;: &quot;10+1&quot;, &quot;48&quot;: &quot;10+2&quot;, &quot;49&quot;: &quot;10 Üzeri&quot;, }, &quot;order&quot;: 0, &quot;required&quot;: true, }, </code></pre> <p><strong>api.js</strong></p> <pre><code> export const getData = function () { return axios .get( &quot;blabla&quot;, { headers: { Authorization: `blabla`, }, } ) .then((json) =&gt; { if (json &amp;&amp; json.status === 200) { //console.log(json); return json.data; } }) .catch((e) =&gt; { console.log(e); }); }; </code></pre> <p><strong>App.js</strong></p> <pre><code>const [data, setData] = useState({}); const [roomValue, setRoomValue] = useState(null); const [roomCount, setRoomCount] = useState([]); const [isFocus, setIsFocus] = useState(false); useEffect(() =&gt; { getDataFunc(); //setDropdown(data.attributes.items[3].options); }, []); const getDataFunc = async () =&gt; { const res = await getData(); //console.log(res); setData(res); console.log(data); }; function setDropdown(query) { const response = query; try { const entries = Object.entries(response); const tempArray = []; for (let i = 0; i &lt; entries.length; i++) { var key; var value; (key = entries[i][0]), (value = entries[i][1]); tempArray.push({ key: value, value: key }); } setRoomCount(tempArray); //console.log(roomCount); } catch (error) { //console.log(error); } } </code></pre> <p>How can I fix that ?</p>
[ { "answer_id": 74302363, "author": "Serhii Chyzhyk", "author_id": 9849697, "author_profile": "https://Stackoverflow.com/users/9849697", "pm_score": 0, "selected": false, "text": "data.attributes" }, { "answer_id": 74302919, "author": "medard mandane", "author_id": 8414995, "author_profile": "https://Stackoverflow.com/users/8414995", "pm_score": 1, "selected": false, "text": "const response = data.attributes.items[3].options;\n" }, { "answer_id": 74303857, "author": "ZFloc Technologies", "author_id": 10657559, "author_profile": "https://Stackoverflow.com/users/10657559", "pm_score": 1, "selected": false, "text": "const [data, setData] = useState([]);\nconst [roomCount, setRoomCount] = useState([]);\n\nuseEffect(() => {\n getDataFunc()\n}, []);\n\nconst getDataFunc = async() => {\n await getData(setData);\n const response = data;\n console.log(response);\n const entries = Object.entries(response);\n const tempArray = [];\n for (let i = 0; i < entries.length; i++) {\n var key;\n var value;\n (key = entries[i][0]), (value = entries[i][1]);\n tempArray.push({ key: value, value: key });\n }\n\n setRoomCount(tempArray);\n console.log(roomCount);\n}\n" }, { "answer_id": 74314599, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 2, "selected": true, "text": " useEffect(() => {\n getDataFunc();\n }, []);\n\n useEffect(() => {\n if(data && data.attributes?.items[3]){\n setDropdown(data.attributes.items[3].options);\n }\n }, [data]);\n\n const getDataFunc = async () => {\n const res = await getData();\n //console.log(res);\n setData(res);\n console.log(data);\n };\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14982006/" ]
74,302,211
<p>I want to design a series of horizontal checkboxes where the checkboxes are located on the right side of the labels.</p> <p>This is what I have written where the labels are located on the left side.</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>.add-margin { margin-top: 10px !important; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;div ng-init="loaded()" ng-class="{'add-margin': descriptionsAvailable}" class="checkbox-inline" ng-repeat="opt in options track by $index"&gt; &lt;label&gt; &lt;input ng-disabled="answer['none']" type="checkbox" ng-model="answer[opt]" ng-true-value="true" ng-false-value="false" name="checkbox-answer-input" display= inline-block &gt; &lt;span&gt;{{opt}}&lt;/span&gt;&lt;br/&gt; &lt;span&gt;&lt;i&gt;{{descriptions[$index]}}&lt;/i&gt;&lt;/span&gt; &lt;/label&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>How can I fix this?</p>
[ { "answer_id": 74302363, "author": "Serhii Chyzhyk", "author_id": 9849697, "author_profile": "https://Stackoverflow.com/users/9849697", "pm_score": 0, "selected": false, "text": "data.attributes" }, { "answer_id": 74302919, "author": "medard mandane", "author_id": 8414995, "author_profile": "https://Stackoverflow.com/users/8414995", "pm_score": 1, "selected": false, "text": "const response = data.attributes.items[3].options;\n" }, { "answer_id": 74303857, "author": "ZFloc Technologies", "author_id": 10657559, "author_profile": "https://Stackoverflow.com/users/10657559", "pm_score": 1, "selected": false, "text": "const [data, setData] = useState([]);\nconst [roomCount, setRoomCount] = useState([]);\n\nuseEffect(() => {\n getDataFunc()\n}, []);\n\nconst getDataFunc = async() => {\n await getData(setData);\n const response = data;\n console.log(response);\n const entries = Object.entries(response);\n const tempArray = [];\n for (let i = 0; i < entries.length; i++) {\n var key;\n var value;\n (key = entries[i][0]), (value = entries[i][1]);\n tempArray.push({ key: value, value: key });\n }\n\n setRoomCount(tempArray);\n console.log(roomCount);\n}\n" }, { "answer_id": 74314599, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 2, "selected": true, "text": " useEffect(() => {\n getDataFunc();\n }, []);\n\n useEffect(() => {\n if(data && data.attributes?.items[3]){\n setDropdown(data.attributes.items[3].options);\n }\n }, [data]);\n\n const getDataFunc = async () => {\n const res = await getData();\n //console.log(res);\n setData(res);\n console.log(data);\n };\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18290425/" ]
74,302,236
<p>Sorry for the uncertain title, I can't think of something better. Let me explain.</p> <p>I have a complex TS type that looks like this: <code>type Foobar &lt;T extends object, K extends keyof T = keyof T&gt; = ...</code>.</p> <p>I need the <code>K</code> parameter to track the specific key type through the type definition and I suppose that the type definition itself does not play any role — because I give a minimal viable example below.</p> <p><a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAIghsOUC8UDeBYAUFXUBmA9oQFxQB2ArgLYBGEATgDTZ5S1wNkDOwDAluQDmLHHg4AvMpjFtccMrWIAbCHHKi54xSrUbWWqAGNpBw3gAep2ebkhpUM7fNSKNegyfPcAXy+GfTQCnQKdCMGAARgB+Mio6RiDccOAAJlj0f1wLEFd4jxDHLD8sbFBIKAAFBnDGUABBIyMIbm5CBgAeABUoCAtgCHIAE24oQloAKwgjYCYoAGle-sGRqABrCBBCfCge1A2tna6APhQitkW+geHR3gFhc8NoqAADABI0eZ8PrLkAOUI5D+lGUyjgtFU3QA2vMALqnK4rUbjKYzR7ePDPAAULwAdB9qrUGA0mi02p0AUCQWCIRBoXDjscfC8oAAfKAAcg5AEp0RioGQub9mb84hAAG6MbAAbmw2CMgN4UAGvAADJEyITIMSQI1mq12h14IhTqgOURCBz5YrgMqWsBValNTVtST9eSjQg4KbORwGFasAryEqVQ6AMzOolusmG43es4cyQBoMh+2qgAskddutJBs6cZ9ibgElxcGTNrtaoArFm6jn3bGvYXJLjaOXg7bQ6qAGy1nV6mP5psJltGXEWXEgXESduptUAdj70bznpNCZSkVnnbTAA4l-XB6v42aUqlx7kA9gAPRXqAAAWA3AAtH1IDMXwwap5AxWuwBOfcBxXAsEwDG970fF8LDfYAPy-a0O0rKJVUA3MPRAs0LVxMDbwfZ9X2mWDGHgn9ENDSINSqF06yA9Dh0w4hcWw69cMggj32I9oELnKInSoqMD2A+jOVxLCcIg-DoMIuCuNInjIgjfjs1oxs1wYwgjDWcS8KgmCZO-FNt14SJMyUmi0NU49OSwssWIk3TpM4gzf3tSIazM-sLKHNTfWLXEhm0tipI4z9ZMMpDIl7DzlzonyixLMcJynAB3AMgA" rel="nofollow noreferrer">I want to see it anyway.</a></p> <p>So, I have such a type and I need to check whether <code>K</code> is <code>never</code> or <code>string</code>:</p> <pre class="lang-js prettyprint-override"><code>type Foobar&lt;T extends object, K extends keyof T = keyof T&gt; = K extends never ? { __debug: 1 } : K extends string ? { __debug: 2 } : { __debug: 3 } ; let test1: Foobar&lt;{ foo: unknown, bar: unknown }&gt;; // { __debug: 2 }, as expected let test2: Foobar&lt;{}&gt;; // { __debug: 1 } expected, got never let test3: Foobar&lt;object&gt;; // { __debug: 1 } expected, got never </code></pre> <p>I expect that in the <code>test2</code> and <code>test3</code> cases the resulting type is <code>{ __debug: 1 }</code>, but it's <code>never</code>. Why <code>never</code>? Where it came from? I have no <code>never</code> in my type definition at all.</p> <p>More interesting, if I remove the <code>K</code> parameter, it works fine:</p> <pre class="lang-js prettyprint-override"><code>type Foobar&lt;T extends object&gt; = keyof T extends never ? { __debug: 1 } : keyof T extends string ? { __debug: 2 } : { __debug: 3 } ; let test1: Foobar&lt;{ foo: unknown, bar: unknown }&gt;; // { __debug: 2 } let test2: Foobar&lt;{}&gt;; // { __debug: 1 } let test3: Foobar&lt;object&gt;; // { __debug: 1 } </code></pre> <p>I'm absolutely confused about this behavior. Am I missing something or is it some kind of the compiler bug/restriction?</p>
[ { "answer_id": 74302446, "author": "Harrison", "author_id": 15291770, "author_profile": "https://Stackoverflow.com/users/15291770", "pm_score": 0, "selected": false, "text": "Foobar<T, K>" }, { "answer_id": 74302586, "author": "Tobias S.", "author_id": 8613630, "author_profile": "https://Stackoverflow.com/users/8613630", "pm_score": 3, "selected": true, "text": "K" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1833886/" ]
74,302,241
<p>I am getting a <code>java.lang.NullPointerException</code> error at the line where the program begins to retrieve data from the database, specifically starting with the code <code>recordDB.setAccountName(billing.getAccountId().getAccountName());</code>. The entity tables are joined together and at first I thought that it can't retrieve data from other other tables but I tried to run with just <code>recordDB.setAmount(billing.getAmount());</code> Can someone explain what I missed or is there something wrong with the logic?</p> <p><strong>Component</strong></p> <pre><code>@Component public class FileProcessor { @Autowired private BillingRepository billingRepository; public FileProcessor() { } public List&lt;Record&gt; retrieveRecordfromDB(List&lt;Request&gt; requests) throws BarsException{ List&lt;Record&gt; records = new ArrayList&lt;&gt;(); if (!requests.isEmpty()) { for (Request request : requests) { Billing billing = billingRepository .findByBillingCycleAndStartDateAndEndDate( request.getBillingCycle() , request.getStartDate() , request.getEndDate()); if (billing == null) { throw new BarsException(BarsException.NO_RECORDS_TO_WRITE); } Record recordDB = new Record(); recordDB.setBillingCycle(request.getBillingCycle()); recordDB.setStartDate(request.getStartDate()); recordDB.setEndDate(request.getStartDate()); recordDB.setAccountName(billing.getAccountId().getAccountName()); recordDB.setFirstName(billing.getAccountId().getCustomerId().getFirstName()); recordDB.setLastName(billing.getAccountId().getCustomerId().getLastName()); recordDB.setAmount(billing.getAmount()); records.add(recordDB); } } return records; } } </code></pre> <p><strong>Account Entity</strong></p> <pre><code>@Entity public class Account { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = &quot;account_id&quot;) private int accountId; private String accountName; private LocalDateTime dateCreated; private String isActive; private String lastEdited; public Account() { } public int getAccountId() { return accountId; } public void setAccountId(int accountId) { this.accountId = accountId; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public LocalDateTime getDateCreated() { return dateCreated; } public void setDateCreated(LocalDateTime dateCreated) { this.dateCreated = dateCreated; } public String getIsActive() { return isActive; } public void setIsActive(String isActive) { this.isActive = isActive; } public String getLastEdited() { return lastEdited; } public void setLastEdited(String lastEdited) { this.lastEdited = lastEdited; } public Customer getCustomerId() { return customerId; } public void setCustomerId(Customer customerId) { this.customerId = customerId; } public Set&lt;Billing&gt; getBilling() { return billing; } public void setBilling(Set&lt;Billing&gt; billing) { this.billing = billing; } @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = &quot;customer_id&quot;) private Customer customerId; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinColumn(name = &quot;account_id&quot;) private Set&lt;Billing&gt; billing; } </code></pre> <p><strong>Billing Entity</strong></p> <pre><code>@Entity public class Billing { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = &quot;billing_id&quot;) private int billingId; //private int billingId; private int billingCycle; private String billingMonth; private Double amount; private LocalDate startDate; private LocalDate endDate; private String lastEdited; //private Account accountId; public Billing() { } public int getBillingId() { return billingId; } public void setBillingId(int billingId) { this.billingId = billingId; } public int getBillingCycle() { return billingCycle; } public void setBillingCycle(int billingCycle) { this.billingCycle = billingCycle; } public String getBillingMonth() { return billingMonth; } public void setBillingMonth(String billingMonth) { this.billingMonth = billingMonth; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } public LocalDate getStartDate() { return startDate; } public void setStartDate(LocalDate startDate) { this.startDate = startDate; } public LocalDate getEndDate() { return endDate; } public void setEndDate(LocalDate endDate) { this.endDate = endDate; } public String getLastEdited() { return lastEdited; } public void setLastEdited(String lastEdited) { this.lastEdited = lastEdited; } public Account getAccountId() { return accountId; } public void setAccountId(Account accountId) { this.accountId = accountId; } @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = &quot;account_id&quot;) private Account accountId; } </code></pre> <p><strong>Customer Entity</strong></p> <pre><code>@Entity public class Customer { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = &quot;customer_id&quot;) private int customerId; private String firstName; private String lastName; private String address; private String status; private LocalDateTime dateCreated; private String lastEdited; public Customer() { } public int getCustomerId() { return customerId; } public void setCustomerId(int customerId) { this.customerId = customerId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public LocalDateTime getDateCreated() { return dateCreated; } public void setDateCreated(LocalDateTime dateCreated) { this.dateCreated = dateCreated; } public String getLastEdited() { return lastEdited; } public void setLastEdited(String lastEdited) { this.lastEdited = lastEdited; } @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinColumn(name = &quot;customer_id&quot;) private Set&lt;Account&gt; account; } </code></pre> <p><strong>Repository</strong></p> <pre><code>@Repository public interface BillingRepository extends JpaRepository&lt;Billing, Integer&gt; { public Billing findByBillingCycleAndStartDateAndEndDate (int billingCycle, LocalDate startDate, LocalDate endDate); } </code></pre>
[ { "answer_id": 74302446, "author": "Harrison", "author_id": 15291770, "author_profile": "https://Stackoverflow.com/users/15291770", "pm_score": 0, "selected": false, "text": "Foobar<T, K>" }, { "answer_id": 74302586, "author": "Tobias S.", "author_id": 8613630, "author_profile": "https://Stackoverflow.com/users/8613630", "pm_score": 3, "selected": true, "text": "K" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15849197/" ]
74,302,297
<p>I'm struggling to write a regex that matches the following requirements:</p> <ol> <li>up to 20 characters (English letters and numbers)</li> <li>may have one optional dash ( - ) but can't start or end with it</li> </ol> <p>I could come up with this patters: <code>^[a-zA-Z0-9-]{0,20}$</code> but this one allows for multiple dashes and one may enter the dash at the begin/end of the input string.</p>
[ { "answer_id": 74302446, "author": "Harrison", "author_id": 15291770, "author_profile": "https://Stackoverflow.com/users/15291770", "pm_score": 0, "selected": false, "text": "Foobar<T, K>" }, { "answer_id": 74302586, "author": "Tobias S.", "author_id": 8613630, "author_profile": "https://Stackoverflow.com/users/8613630", "pm_score": 3, "selected": true, "text": "K" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1056118/" ]
74,302,318
<p>After having read the <code>pandas reindex</code> docs, it is still not clear to me how to re-arrange the order of the columns in a <code>MultiIndex</code> <code>DataFrame</code> and re-assign it to the original <code>DataFrame</code>. For example, say that I have the following <code>DataFrame</code></p> <pre><code>df = kind A B names u1 u2 u3 y1 y2 Time 0.0 0.5083 0.1007 0.8001 0.7373 0.1387 0.1 0.6748 0.0354 0.0076 0.8421 0.2670 0.2 0.1753 0.1013 0.5231 0.8060 0.0040 </code></pre> <p>and I want to re-order some columns such that at the end I get the following</p> <pre><code>df = kind A B names u3 u2 u1 y1 y2 Time 0.0 0.8001 0.1007 0.5083 0.7373 0.1387 0.1 0.0076 0.0354 0.6748 0.8421 0.2670 0.2 0.5231 0.1013 0.1753 0.8060 0.0040 </code></pre> <p>If I do <code>df.reindex(level=&quot;names&quot;, columns=[&quot;u3&quot;,&quot;u1&quot;])</code>, then I got</p> <pre><code>kind A names u3 u1 Time 0.0 0.8001 0.5083 0.1 0.0076 0.6748 0.2 0.5231 0.1753 </code></pre> <p>which is encouraging, but then I cannot figure out how to re-assign it to the original <code>df</code>. I tried <code>df.loc[:,&quot;A&quot;] = df.reindex(level=&quot;names&quot;, columns=[&quot;u3&quot;,&quot;u1&quot;])</code> but what I get is the following</p> <pre><code>kind A B names u1 u2 u3 y1 y2 Time 0.0 0.5083 NaN 0.8001 0.7373 0.1387 0.1 0.6748 NaN 0.0076 0.8421 0.2670 0.2 0.1753 NaN 0.5231 0.8060 0.0040 </code></pre>
[ { "answer_id": 74302974, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 1, "selected": false, "text": "print (df)\nkind C A B\nnames d1 u2 u3 u1 y2\n0.0 0.5083 0.1007 0.8001 0.7373 0.1387\n0.1 0.6748 0.0354 0.0076 0.8421 0.2670\n0.2 0.1753 0.1013 0.5231 0.8060 0.0040\n\n#original columns\ncols = df.columns\n\n#columns after change order\nnew = df.reindex(level=\"names\", columns=[\"u3\",\"u2\", \"u1\"]).columns\n\n#filter only tuples from new\nd = dict(zip(cols[cols.isin(new)], new))\n\n#recreate Multiindex with mapping and reindex all columns\nmux = pd.MultiIndex.from_tuples([d.get(x, x) for x in cols],names=[\"kind\",\"names\"])\ndf = df.reindex(mux, axis=1)\nprint (df)\nkind C A B\nnames d1 u3 u2 u1 y2\n0.0 0.5083 0.8001 0.1007 0.7373 0.1387\n0.1 0.6748 0.0076 0.0354 0.8421 0.2670\n0.2 0.1753 0.5231 0.1013 0.8060 0.0040\n" }, { "answer_id": 74303449, "author": "user19795989", "author_id": 19795989, "author_profile": "https://Stackoverflow.com/users/19795989", "pm_score": 0, "selected": false, "text": "df2 = df.reindex(level=\"names\", columns=[\"u3\", \"u2\", \"u1\", \"y1\", \"y2\"])\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2562058/" ]
74,302,341
<p>i am having an issue with uploading avatars to my supabase bucket as its giving me &quot;new row violates row-level security policy for table &quot;objects&quot;&quot;. I tried other StackOverflow solutions and nothing. Before trying to upload I log in using supabse so my user is authenticated yet its still not letting me upload. I added this policy in storage.objects:</p> <p><code>(role() = 'authenticated'::text)</code> and clicked the insert button. Does anyone know what I am doing wrong? I assume its something to do with the policies. Thanks</p> <p>this is how I'm trying to upload my avatar:</p> <pre><code>try{ const { data, error } = await supabase .storage .from('/public/avatars') .upload(`${values.email}.png`, values.avatar, { cacheControl: '3600', upsert: true }); if(error) throw error; }catch(error){ console.log(error); } </code></pre>
[ { "answer_id": 74342787, "author": "thorwebdev", "author_id": 17622044, "author_profile": "https://Stackoverflow.com/users/17622044", "pm_score": 0, "selected": false, "text": "public" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12774586/" ]
74,302,374
<p>I have a simple Webserver that exposes the pod name on which it is located by using the <code>OUT</code> env var.</p> <p>Deployment and service look like this:</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: v1 kind: Service metadata: name: simpleweb-service spec: selector: app: simpleweb ports: - protocol: TCP port: 8080 targetPort: 8080 --- apiVersion: apps/v1 kind: Deployment metadata: name: simpleweb-deployment labels: app: simpleweb spec: replicas: 3 selector: matchLabels: app: simpleweb template: metadata: labels: app: simpleweb spec: containers: - name: simpleweb env: - name: OUT valueFrom: fieldRef: fieldPath: metadata.name imagePullPolicy: Never image: simpleweb ports: - containerPort: 8080 </code></pre> <p>I deploy this on my local <a href="https://kind.sigs.k8s.io" rel="nofollow noreferrer">kind cluster</a></p> <pre><code>default simpleweb-deployment-5465f84584-m59n5 1/1 Running 0 12m default simpleweb-deployment-5465f84584-mw8vj 1/1 Running 0 9m36s default simpleweb-deployment-5465f84584-x6n74 1/1 Running 0 12m </code></pre> <p>and access it via</p> <pre class="lang-bash prettyprint-override"><code>kubectl port-forward service/simpleweb-service 8080:8080 </code></pre> <p>When I am hitting <code>localhost:8080</code> I always get to the same pod</p> <p><strong>Questions:</strong></p> <ul> <li>Is my service not doing round robin?</li> <li>Is there some caching that I am not aware of</li> <li>Do I have to expose my service differently? Is this a kind issue?</li> </ul>
[ { "answer_id": 74342787, "author": "thorwebdev", "author_id": 17622044, "author_profile": "https://Stackoverflow.com/users/17622044", "pm_score": 0, "selected": false, "text": "public" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5345715/" ]
74,302,381
<p>I see in this topic <a href="https://stackoverflow.com/questions/1070497/c-convert-hex-string-to-signed-integer">C++ convert hex string to signed integer</a> that <code>boost::lexical_cast</code> can convert hexadecimal inside string to another type (int, long...)</p> <p>but when I tried this code:</p> <pre><code>std::string s = &quot;0x3e8&quot;; try { auto i = boost::lexical_cast&lt;int&gt;(s); std::cout &lt;&lt; i &lt;&lt; std::endl; // 1000 } catch (boost::bad_lexical_cast&amp; e) { // bad input - handle exception std::cout &lt;&lt; &quot;bad&quot; &lt;&lt; std::endl; } </code></pre> <p>It ends with a bad lexical cast exception !</p> <p>boost doesn't support this kind of cast from string hex to int ?</p>
[ { "answer_id": 74303303, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "lexical_cast<>" }, { "answer_id": 74305688, "author": "sehe", "author_id": 85371, "author_profile": "https://Stackoverflow.com/users/85371", "pm_score": 0, "selected": false, "text": "boost::cnv::cstream converter;\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11961961/" ]
74,302,382
<p>I want to suppress before two zeros and include zeros before values with two digits.</p> <p><a href="https://i.stack.imgur.com/TvR8F.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TvR8F.png" alt="enter image description here" /></a></p> <p>How to do the logic kindly help me on this.</p>
[ { "answer_id": 74303303, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "lexical_cast<>" }, { "answer_id": 74305688, "author": "sehe", "author_id": 85371, "author_profile": "https://Stackoverflow.com/users/85371", "pm_score": 0, "selected": false, "text": "boost::cnv::cstream converter;\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1492885/" ]
74,302,414
<p>I am trying to plot a tree with previously specified node labels in Newick format:</p> <pre><code>((58_Amphimedon_queenslandica:1.271048872,59_Oscarella_carmela:1.182998044)60:0.034049179,((61_Mnemiopsis_leidyi:0.322168794,62_Pleurobrachia_bachei:0.548640591)63:1.652794394,((((((1_Adineta_vaga:1.7879779,(((2_Echinococcus_multilocularis:1.046556098,3_Schistosoma_mansoni:0.91678556)4:0.616271036,5_Schmidtea_mediterranea:1.692309447)6:0.32666239,7_Macrostomum_lignano:1.568266346)8:0.378093813)9:0.130389525,(((((10_Biomphalaria_glabrata:0.618932621,11_Lottia_gigantea:0.452269273)12:0.059417719,13_Crassostrea_gigas:0.518431208)14:0.040670598,15_Octopus_bimaculata:0.646961425)16:0.101479681,(17_Notospermus_geniculatus:0.529250964,18_Phoronis_australis:0.555407465)19:0.044453771)20:0.020365466,(21_Capitella_teleta:0.570779897,22_Helobdella_robusta:1.12545896)23:0.111068195)24:0.042564036)25:0.04351873,((((((26_Apis_mellifera:0.703550258,27_Drosophila_melanogaster:1.030363662)28:0.223325196,29_Daphnia_pulex:0.896728176)30:0.178376492,((31_Ixodes_scapularis:0.772869706,(32_Limulus_polyphemus:0.410288152,33_Stegodyphus_mimosarum:0.666118706)34:0.032501467)35:0.11894679,36_Strigamia_maritima:0.721726909)37:0.049724874)38:0.083204725,(39_Hypsibius_dujardini:0.431761707,40_Ramazzottius_varieornatus:0.877374545)41:1.393205979)42:0.016782622,(((43_Caenorhabditis_elegans:0.989355479,44_Pristionchus_pacificus:0.938419613)45:0.353607734,46_Loa_loa:0.922207873)47:0.803845621,(48_Romanomermis_culicivorax:1.176159859,(49_Trichuris_muris:1.244039486,50_Trichinella_spiralis:1.095739241)51:0.623094809)52:0.13754668)53:0.514360208)54:0.04135167,55_Priapulus_caudatus:0.755052063)56:0.038898188)57:0.075727099,(((((0_Acanthaster_planci:0.075878507,110_Patiria_miniata:0.110665648)111:0.325399251,(104_Apostichopus_japonicus:0.599326865,(105_Lytechinus_variegatus:0.129683096,106_Strongylocentrotus_purpuratus:0.059356674)107:0.376377895)108:0.051862417)109:0.16901716,((98_Ptychodera_flava:0.346722111,99_Saccoglossus_kowalevskii:0.259401265)100:0.172870001,101_Rhabdopleura_recondita:0.68730129)102:0.054777546)103:0.076162868,96_Xenoturbella_bocki:0.970285664)97:0.02334384,(78_Branchiostoma_floridae:0.56505513,((((79_Callorhinchus_milii:0.254322263,((80_Gallus_gallus:0.158525779,(81_Homo_sapiens:0.044793306,82_Mus_musculus:0.061786122)83:0.134090431)84:0.086737559,85_Latimeria_chalumnae:0.190806452)86:0.02269946)87:0.030197923,88_Danio_rerio:0.286590103)89:0.112840392,90_Petromyzon_marinus:0.506518606)91:0.246748947,92_Ciona_intestinalis:1.198840655)93:0.063420667)94:0.053862064)95:0.029924804)77:0.165620347,(69_Hydra_vulgaris:1.185855052,(70_Nematostella_vectensis:0.405991429,(71_Orbicella_faveolata:0.1188383,72_Stylophora_pistillata:0.126624764)73:0.2570364)74:0.221701033)75:0.130324524)76:0.053502655,(65_Hoilungia_hongkongensis:0.130085304,66_Trichoplax_adhaerens:0.144715451)67:1.018316539)68:0.057759319)64:0.034049179); </code></pre> <p>My code looks like this:</p> <pre><code>tree &lt;- read.tree(&quot;/home/agalvez/data/sims/trees/rooted_tree_nodenames.txt&quot;) tree tree$node.label plot(tree); nodelabels(frame = &quot;n&quot;, cex=0.8, col= &quot;blue&quot;) </code></pre> <p>My tree gets printed with node labels, the problem is that they are not the specified node labels in my original tree.</p> <p>Thanks a lot for reading!</p>
[ { "answer_id": 74303303, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "lexical_cast<>" }, { "answer_id": 74305688, "author": "sehe", "author_id": 85371, "author_profile": "https://Stackoverflow.com/users/85371", "pm_score": 0, "selected": false, "text": "boost::cnv::cstream converter;\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17550734/" ]
74,302,416
<p>I'm trying to get all the files in a directory and to get the name of the newest one.</p> <pre><code>List&lt;string&gt; NewFiles = new List&lt;string&gt;(); NewFiles = Directory.GetFiles(path,, &quot;*.*&quot;, SearchOption.AllDirectories).ToList(); String lastItem = NewFiles.Last(); </code></pre> <p>The problem is that i have 354 files in this folder and the last file i get from this is the file 99.</p>
[ { "answer_id": 74302502, "author": "Klaus Gütter", "author_id": 2142950, "author_profile": "https://Stackoverflow.com/users/2142950", "pm_score": 2, "selected": false, "text": "Last()" }, { "answer_id": 74302524, "author": "Prasad Telkikar", "author_id": 6299857, "author_profile": "https://Stackoverflow.com/users/6299857", "pm_score": 2, "selected": false, "text": "LastWriteTime" }, { "answer_id": 74302746, "author": "Pradeep Kumar", "author_id": 18704952, "author_profile": "https://Stackoverflow.com/users/18704952", "pm_score": 0, "selected": false, "text": "string pattern = \"*.txt\";\nvar dirInfo = new DirectoryInfo(directory);\nvar file = (from f in dirInfo.GetFiles(pattern) orderby f.LastWriteTime descending select f).First();\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19053339/" ]
74,302,420
<p>I wish to pick a random number of elements (can be 0 too) from a list in python. The probability of choosing any element is independent of others. For example:</p> <pre><code>example_list = ['Apple', 'Orange', 'Kiwi', 'Mango'] example_probabilties = [6, 9, 1, 4] </code></pre> <p>I wish to pick out a random number of fruits, where the element 'Apple' has a probability of 6% of being chosen, 'Orange' has a 9% probability of being picked, and so on.</p> <p>As far as I understand, random.choices() uses the weights differently, essentially treating the probabilities in this manner:</p> <pre><code>Probability of choosing 'Apple': 6/sum(example_probabilities) Probability of choosing 'Orange': 9/sum(example_probabilities) </code></pre> <p>And so on...</p> <p>Is there any other way I can achieve the desired result?</p>
[ { "answer_id": 74302502, "author": "Klaus Gütter", "author_id": 2142950, "author_profile": "https://Stackoverflow.com/users/2142950", "pm_score": 2, "selected": false, "text": "Last()" }, { "answer_id": 74302524, "author": "Prasad Telkikar", "author_id": 6299857, "author_profile": "https://Stackoverflow.com/users/6299857", "pm_score": 2, "selected": false, "text": "LastWriteTime" }, { "answer_id": 74302746, "author": "Pradeep Kumar", "author_id": 18704952, "author_profile": "https://Stackoverflow.com/users/18704952", "pm_score": 0, "selected": false, "text": "string pattern = \"*.txt\";\nvar dirInfo = new DirectoryInfo(directory);\nvar file = (from f in dirInfo.GetFiles(pattern) orderby f.LastWriteTime descending select f).First();\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13663677/" ]
74,302,459
<p><a href="https://i.stack.imgur.com/g4AhF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g4AhF.png" alt="enter image description here" /></a></p> <p>I have a table onLoad that renders my data fine, it's when I interact with the inputs above each column that handle the filtering is the problem. If I enter any value nothing displays.</p> <p>I'm handling the onChange for the inputs in a single function called filterBySearch which captures the event.</p> <p>Here's my function and filtering logic - I suspect this is where I'm doing wrong:</p> <pre><code>const filterBySearch = (e) =&gt; { const { name, value } = e.target; setFilters({ ...filters, [name]: value }); //Take copy of current list let updatedList = [...data]; //Filter logic updatedList = rows.filter((document) =&gt; { return ( document.documentAuthor ?.toLowerCase() .includes(filters.documentAuthor.toLowerCase()) &amp;&amp; document.documentName ?.toLowerCase() .includes(filters.documentName.toLowerCase()) &amp;&amp; document.documentSource ?.toLowerCase() .includes(filters.documentSource.toLowerCase()) &amp;&amp; document.featureId?.includes(filters.featureId) ); }); // Trigger render with updated values setRows(updatedList); }; </code></pre> <p><a href="https://codesandbox.io/s/testing-filters-logic-r1imjd?fontsize=14&amp;hidenavigation=1&amp;theme=dark" rel="nofollow noreferrer"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit Testing filters logic" /></a></p>
[ { "answer_id": 74302732, "author": "user20386762", "author_id": 20386762, "author_profile": "https://Stackoverflow.com/users/20386762", "pm_score": -1, "selected": false, "text": "const Component = ({ rows }) => {\n const [rowState, setRowState] = useState(rows)\n const [cachedRows, setCachedRows] = useState(rows)\n // Rest of the implementation\n}\n" }, { "answer_id": 74302766, "author": "Apostolos", "author_id": 1121008, "author_profile": "https://Stackoverflow.com/users/1121008", "pm_score": 3, "selected": true, "text": "data" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665312/" ]
74,302,487
<p>I have the following dataframe:</p> <pre><code>Date Name Grade Hobby 01/01/2005 Albert 4 Drawing 08/04/1996 Martha 6 Horseback riding 03/03/2003 Jack 5 Singing 07/01/2001 Millie 5 Netflix 24/09/2000 Julie 7 Sleeping ... </code></pre> <p>I want to filter the df to only contain the rows for repeat dates, so where <code>df['Date'].value_counts()&gt;=2</code> And then groupby dates sorted in chronological order so that I can have something like:</p> <pre><code>Date Name Grade Hobby 08/08/1996 Martha 6 Horseback riding Matt 4 Sleeping Paul 5 Cooking 24/09/2000 Julie 7 Sleeping Simone 4 Sleeping ... </code></pre> <p>I have tried some code, but I get stuck on the first step. I tried something like:</p> <pre><code>same=df['Date'].value_counts() same=same.loc[lambda x:x &gt;=2] mult=same.index.to_list() for i in df['Date']: if i not in mult: df.drop(df[df['Date'==i]].index) </code></pre> <p>I also tried</p> <pre><code>new=df.loc[df['Date'].isin(mult)] plot=pd.pivot_table(new, index=['Date'],columns=['Name']) </code></pre> <p>But this only gets 1 of the rows per each repeat dates instead of all the rows with the same date</p>
[ { "answer_id": 74302523, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 2, "selected": true, "text": "Date" }, { "answer_id": 74302544, "author": "Alisher Azizov", "author_id": 19930975, "author_profile": "https://Stackoverflow.com/users/19930975", "pm_score": 2, "selected": false, "text": "df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)\n\ndf_new = df[df['Date'].duplicated(keep=False)].sort_values('Date')\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12462131/" ]
74,302,493
<p>I have a dump file (size around 5 GB) which is taken via this command:</p> <pre><code>pg_dump -U postgres -p 5440 MYPRODDB &gt; MYPRODDB_2022.dmp </code></pre> <p>The database consists multiple schemas (let's say Schema A,B,C and D) but i need to restore only one schema (schema A).</p> <p>How can i achieve that? The command below didn't work and gave error:</p> <pre><code>pg_restore -U postgres -d MYPRODDB -n A -p 5440 &lt; MYPRODDB_2022.dmp </code></pre> <blockquote> <p>pgrestore: error: input file appears to be a text format dump. please use psql.</p> </blockquote>
[ { "answer_id": 74302523, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 2, "selected": true, "text": "Date" }, { "answer_id": 74302544, "author": "Alisher Azizov", "author_id": 19930975, "author_profile": "https://Stackoverflow.com/users/19930975", "pm_score": 2, "selected": false, "text": "df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)\n\ndf_new = df[df['Date'].duplicated(keep=False)].sort_values('Date')\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2372522/" ]
74,302,521
<p>I want to allow the user to download the report, when it is approved by a supervisor. At the moment, I'm working with manager account, where he can check many reports and change their state to either verified or denied, but I don't understand why the report states enum list is not displaying, even though it is shown in the console.</p> <p><a href="https://i.stack.imgur.com/cqEWg.png" rel="nofollow noreferrer">HTML code</a></p> <p>Model:</p> <pre><code>public class Report { public int ID { get; set; } [Display(Name = &quot;Report Name&quot;)] public string reportName { get; set; } public virtual User reportManager { get; set; } [Display(Name = &quot;State&quot;)] public ReportState reportState { get; set; } public byte[] reportData { get; set; } } public enum ReportState { Accepted, Pending, Denied } </code></pre> <hr /> <p>Controller:</p> <pre><code>public async Task&lt;IActionResult&gt; Index() { ViewBag.Reports = await _context.Reports.ToListAsync(); ViewBag.ReportStates = new SelectList(Enum.GetNames(typeof(ReportState))); return View(); } </code></pre> <hr /> <pre><code>@model variable_pay_system.Models.Report @{ ViewData[&quot;Title&quot;] = &quot;Reports&quot;; } &lt;div class=&quot;container&quot;&gt; &lt;h5&gt;Reports&lt;/h5&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt; @Html.DisplayNameFor(model =&gt; model.reportName) &lt;/th&gt; &lt;th&gt; @Html.DisplayNameFor(model =&gt; model.reportState) &lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; @foreach (Report report in ViewBag.Reports) { &lt;tr&gt; &lt;td&gt; @Html.DisplayFor(modelItem =&gt; report.reportName) &lt;/td&gt; &lt;td&gt; &lt;select asp-for=&quot;@report.reportState&quot; asp-items=&quot;Html.GetEnumSelectList&lt;ReportState&gt;()&quot;&gt;&lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; } &lt;/tbody&gt; &lt;/table&gt; </code></pre>
[ { "answer_id": 74302523, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 2, "selected": true, "text": "Date" }, { "answer_id": 74302544, "author": "Alisher Azizov", "author_id": 19930975, "author_profile": "https://Stackoverflow.com/users/19930975", "pm_score": 2, "selected": false, "text": "df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)\n\ndf_new = df[df['Date'].duplicated(keep=False)].sort_values('Date')\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18738557/" ]
74,302,529
<p>This is one of my first attempts to use Java and I tried my best, but I need to shorten it so it's not so long.</p> <p>Important is that it keeps all the coins of the Euro. It's a German code so geld means money.</p> <p>This part of the code <code>System.out.println(rgeldt + &quot; mal 2 Euro&quot;);</code> just means how often the 2 euros have to be ejected.</p> <pre class="lang-java prettyprint-override"><code>public static void Rueckgaberechner(Double geld) { System.out.println(&quot;Rueckgeld: &quot;); int rgeldt = 0; while (geld &gt;= 200) { geld = geld - 200; rgeldt = rgeldt + 1; } if (rgeldt &gt;= 1) { System.out.println(rgeldt + &quot; mal 2 Euro&quot;); } int rgeldO = 0; while (geld &gt;= 100) { geld = geld - 100; rgeldO = rgeldO + 1; } if (rgeldO &gt;= 1) { System.out.println(rgeldO + &quot; mal 1 Euro&quot;); } int rgeldf = 0; while (geld &gt;= 50) { geld = geld - 50; rgeldf = rgeldf + 1; } if (rgeldf &gt;= 1) { System.out.println(rgeldf + &quot; mal 50 Cent&quot;); } int rgeldtw = 0; while (geld &gt;= 20) { geld = geld - 20; rgeldtw = rgeldtw + 1; } if (rgeldtw &gt;= 1) { System.out.println(rgeldtw + &quot; mal 20 Cent&quot;); } int rgeldten = 0; while (geld &gt;= 10) { geld = geld - 10; rgeldten = rgeldten + 1; } if (rgeldten &gt;= 1) { System.out.println(rgeldten + &quot; mal 10 Cent&quot;); } int rgeldfive = 0; while (geld &gt;= 5) { geld = geld - 5; rgeldfive = rgeldfive + 1; } if (rgeldfive &gt;= 1) { System.out.println(rgeldfive + &quot; mal 5 Cent&quot;); } int rgeldtwo = 0; while (geld &gt;= 2) { geld = geld - 2; rgeldtwo = rgeldtwo + 1; } if (rgeldtwo &gt;= 1) { System.out.println(rgeldtwo + &quot; mal 2 Cent&quot;); } int rgeldone = 0; while (geld &gt;= 1) { geld = geld - 1; rgeldone = rgeldone + 1; } if (rgeldone &gt;= 1) { System.out.println(rgeldone + &quot; mal 1 Cent&quot;); } } </code></pre>
[ { "answer_id": 74302781, "author": "Jens", "author_id": 3636601, "author_profile": "https://Stackoverflow.com/users/3636601", "pm_score": 1, "selected": true, "text": "public static void Rueckgaberechner(Double geld) {\n System.out.println(\"Rueckgeld: \");\n geld = anzahlRueckgeld(200,geld, \" mal 2 Euro\");\n geld = anzahlRueckgeld(100,geld, \" mal 1 Euro\");\n geld = anzahlRueckgeld(50,geld, \" mal 50 cent\");\n geld = anzahlRueckgeld(20,geld, \" mal 20 cent\");\n geld = anzahlRueckgeld(10,geld, \" mal 10 cent\");\n geld = anzahlRueckgeld(5,geld, \" mal 5 cent\");\n geld = anzahlRueckgeld(2,geld, \" mal 2 cent\");\n anzahlRueckgeld(1,geld, \" mal 1 cent\");\n}\n\npublic static double anzahlRueckgeld(int amount, double geld ,String text) {\n int rgeldt =0;\n \n while (geld >= amount) {\n geld = geld - amount;\n rgeldt = rgeldt + 1;\n }\n if (rgeldt >=1) {\n System.out.println(rgeldt +text);\n }\n return geld;\n}\n" }, { "answer_id": 74302833, "author": "Stephen Flavin", "author_id": 20402396, "author_profile": "https://Stackoverflow.com/users/20402396", "pm_score": 1, "selected": false, "text": " int numberOf2Euros = (int) (geld / 200);\n geld = geld % 200;\n" }, { "answer_id": 74303038, "author": "Mr. Polywhirl", "author_id": 1762224, "author_profile": "https://Stackoverflow.com/users/1762224", "pm_score": 0, "selected": false, "text": "int" }, { "answer_id": 74303166, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "static int Rueckgaberechner(int geld, int unit, String message) {\n int regld = geld / unit;\n if (regld > 0)\n System.out.println(regld + \" mal \" + message);\n return geld % unit;\n}\n\npublic static void Rueckgaberechner(int geld) {\n System.out.println(\"Rueckgeld: \");\n geld = Rueckgaberechner(geld, 200, \"2 Euro\");\n geld = Rueckgaberechner(geld, 100, \"1 Euro\");\n geld = Rueckgaberechner(geld, 50, \"50 Cent\");\n geld = Rueckgaberechner(geld, 20, \"20 Cent\");\n geld = Rueckgaberechner(geld, 10, \"10 Cent\");\n geld = Rueckgaberechner(geld, 5, \"5 Cent\");\n geld = Rueckgaberechner(geld, 2, \"2 Cent\");\n geld = Rueckgaberechner(geld, 1, \"1 Cent\");\n}\n\npublic static void main(String[] args) {\n Rueckgaberechner(1498);\n}\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20406969/" ]
74,302,532
<p>I have created the following code and everything works fine except the definition of TestDBAPI.</p> <p>When I want to create a type that conforms to the DBAPIProtocol protocol, it is always impossible to generate a type instance that satisfies the generic constraints</p> <p>Please, how can I define TestNoteFetcher to satisfy the protocol requirement of DBAPIProtocol.</p> <p>ps: I hope the flexibility of generic definitions can be maintained in DBAPIProtocol</p> <p>thanks</p> <pre class="lang-swift prettyprint-override"><code>import Combine // For Value public enum WrappedID: Equatable, Identifiable, Sendable, Hashable { case string(String) case integer(Int) public var id: Self { self } } public protocol BaseValueProtocol: Equatable, Identifiable, Sendable { var id: WrappedID { get } } public struct Note: BaseValueProtocol { public var id: WrappedID public var index: Int public init(id: WrappedID, index: Int) { self.id = id self.index = index } } // For Object public protocol ConvertibleValueObservableObject&lt;Value&gt;: ObservableObject, Equatable, Identifiable where ID == WrappedID { associatedtype Value: BaseValueProtocol func convertToValueType() -&gt; Value } public final class TestNote: ConvertibleValueObservableObject { public static func == (lhs: TestNote, rhs: TestNote) -&gt; Bool { true } public var id: WrappedID { .integer(1) } public func convertToValueType() -&gt; Note { .init(id: .integer(1), index: 0) } } // For Fetcher public protocol ObjectFetcherProtocol&lt;Object,ConvertValue&gt; { associatedtype ConvertValue: BaseValueProtocol associatedtype Object: ConvertibleValueObservableObject&lt;ConvertValue&gt; var stream: AsyncPublisher&lt;AnyPublisher&lt;[Object], Never&gt;&gt; { get } } public final class TestNoteFetcher: ObjectFetcherProtocol { public typealias ConvertValue = Note public typealias Object = TestNote public var stream: AsyncPublisher&lt;AnyPublisher&lt;[TestNote], Never&gt;&gt; { sender.eraseToAnyPublisher().values } public var sender: CurrentValueSubject&lt;[TestNote], Never&gt; public init(_ notes: [TestNote] = []) { sender = .init(notes) } } // For API public protocol DBAPIProtocol { var notesFetcher: () async -&gt; any ObjectFetcherProtocol&lt;any ConvertibleValueObservableObject&lt;Note&gt;, Note&gt; { get set } } // get error in here . Cannot convert value of type 'TestNoteFetcher.Object' (aka 'TestNote') to closure result type 'any ConvertibleValueObservableObject&lt;Note&gt;' public final class TestDBAPI: DBAPIProtocol { public var notesFetcher: () async -&gt; any ObjectFetcherProtocol&lt;any ConvertibleValueObservableObject&lt;Note&gt;, Note&gt; = { TestNoteFetcher([]) } } </code></pre> <p><a href="https://i.stack.imgur.com/NwZWF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NwZWF.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74302865, "author": "Timmy", "author_id": 13278922, "author_profile": "https://Stackoverflow.com/users/13278922", "pm_score": 3, "selected": true, "text": "any" }, { "answer_id": 74310246, "author": "Bob Xu", "author_id": 12260342, "author_profile": "https://Stackoverflow.com/users/12260342", "pm_score": 0, "selected": false, "text": "public protocol ObjectFetcherProtocol<ConvertValue> {\n associatedtype ConvertValue: BaseValueProtocol\n var stream: AsyncPublisher<AnyPublisher<[any ConvertibleValueObservableObject<ConvertValue>], Never>> { get }\n}\n\npublic final class TestNoteFetcher: ObjectFetcherProtocol {\n\n public var stream: AsyncPublisher<AnyPublisher<[any ConvertibleValueObservableObject<Note>], Never>> {\n sender.eraseToAnyPublisher().values\n }\n\n public var sender: CurrentValueSubject<[any ConvertibleValueObservableObject<Note>], Never>\n public init(_ notes: [any ConvertibleValueObservableObject<Note>] = []) {\n sender = .init(notes)\n }\n}\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12260342/" ]
74,302,534
<p>For Node app, it is often discouraged to use .env library to store api keys in production. What is the best way to store the keys in production?</p> <p>.env library is discouraged to be used in production for Node app.</p>
[ { "answer_id": 74302995, "author": "DᴀʀᴛʜVᴀᴅᴇʀ", "author_id": 1952287, "author_profile": "https://Stackoverflow.com/users/1952287", "pm_score": 1, "selected": false, "text": "production" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18850363/" ]
74,302,562
<p>I'm Using Dialogname.Show() method to show a loading dialog this is working fine however when I try to dismiss it it does not work I have used Dialogname.hide(), Dialogname.cancel(), Dialogname.dismiss()</p> <p><strong>Dialog is an acitivity</strong></p> <pre><code>public class RecipeLoading extends Dialog { public RecipeLoading(@NonNull Context context){ super(context); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(com.meetvishalkumar.myapplication.R.layout.activity_recipe_loading); } </code></pre> <p>}</p> <p><strong>Dialog Dismiss Code</strong> `</p> <pre><code>RecipeLoading recipeLoading = new RecipeLoading(RecipeDetailsActivity.this); recipeLoading.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND); recipeLoading.hide(); recipeLoading.cancel(); recipeLoading.dismiss(); </code></pre> <p>`</p> <p><strong>Dialog Show Code</strong></p> <p>`</p> <pre><code>RecipeLoading recipeLoading = new RecipeLoading(RecipeDetailsActivity.this); recipeLoading.setCancelable(false); recipeLoading.getWindow().setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.transparent))); recipeLoading.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND); recipeLoading.show(); </code></pre> <p>`</p> <p>i'm Using Dialogname.Show() method to show a loading dialog this is working fine however when i try to dismiss it it does not work i have used Dialogname.hide(), Dialogname.cancel(), Dialogname.dismiss()</p>
[ { "answer_id": 74302995, "author": "DᴀʀᴛʜVᴀᴅᴇʀ", "author_id": 1952287, "author_profile": "https://Stackoverflow.com/users/1952287", "pm_score": 1, "selected": false, "text": "production" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12626929/" ]
74,302,569
<pre><code>arr_list = [] arr = ['5', '6', '2', '4', '+'] arr_list.append([''.join(arr[0:4])]) print(arr_list) </code></pre> <p>Ouput: <code>[['5624']]</code></p> <p>Why does the output have 2 sets of square brackets? I only want one.</p> <p>Thanks in advnace.</p>
[ { "answer_id": 74302599, "author": "brenodacosta", "author_id": 18091040, "author_profile": "https://Stackoverflow.com/users/18091040", "pm_score": 0, "selected": false, "text": "arr_list.append(''.join(arr[0:4]))\n" }, { "answer_id": 74302618, "author": "helloworld", "author_id": 9817642, "author_profile": "https://Stackoverflow.com/users/9817642", "pm_score": 0, "selected": false, "text": "arr_list.append(''.join(arr[0:4]))\n" }, { "answer_id": 74302628, "author": "Tr3ate", "author_id": 14793476, "author_profile": "https://Stackoverflow.com/users/14793476", "pm_score": 3, "selected": true, "text": "arr_list = []\narr = ['5', '6', '2', '4', '+']\narr_list.append(''.join(arr[0:4]))\nprint(arr_list)\n" }, { "answer_id": 74302641, "author": "Sash Sinha", "author_id": 6328256, "author_profile": "https://Stackoverflow.com/users/6328256", "pm_score": 0, "selected": false, "text": ">>> arr_list = []\n>>> arr = ['5', '6', '2', '4', '+']\n>>> arr_list.append(''.join(arr[0:4]))\n>>> arr_list\n['5624']\n" }, { "answer_id": 74302770, "author": "OneLastBug", "author_id": 19782437, "author_profile": "https://Stackoverflow.com/users/19782437", "pm_score": 0, "selected": false, "text": "arr_list.append(''.join(arr[0:4]))\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11774730/" ]
74,302,609
<p>I used the fromJson method to recover a Struct with a List from Json decode http request and receiver it on my class, but now i want to do a reverse, i want to pass the data on my class to my toJson method and send him to a Json encode http POST. Please, i new on Dart/Flutter, someone know how to do this?</p> <pre><code>import 'dart:convert'; List&lt;Itens&gt; userFromJson(String str) =&gt; List&lt;Itens&gt;.from(jsonDecode(str).map((x) =&gt; Itens.fromJson(x))); class Coletas { final int codigo; final String dataIni; late String? dataFin; late String? status; final List&lt;Itens&gt; itemList; Coletas( { required this.dataIni, this.dataFin, this.status, required this.codigo, required this.itemList } ); factory Coletas.fromJson(Map&lt;String, dynamic&gt; json) { return Coletas( dataIni: json['dtData'], codigo: json['iCodigo'], itemList: List&lt;Itens&gt;.from(json['stItens'].map((x) =&gt; Itens.fromJson(x))), ); } Map&lt;String, dynamic&gt; toMap() { return { 'codigo': codigo, 'dataIni': dataIni, 'dataFin': dataFin, 'status': status }; } } class Itens { final int? id; final int codigo; late int quantidade; late String? status; final String codigoEAN; Itens({ this.id, this.status, required this.codigo, required this.codigoEAN, required this.quantidade, }); Map&lt;String, dynamic&gt; toJson(){ return { 'icodigo' : codigo, 'sCodigoBarras': codigoEAN, 'iQtd': quantidade }; } factory Itens.fromJson(Map&lt;String, dynamic&gt; json) { return Itens( codigo: json['iCodigo'], codigoEAN: json['sCodigoBarras'], quantidade: json['iQtd'], ); } Map&lt;String, dynamic&gt; toMap() { return { 'id': id, 'status': status, 'codigo': codigo, 'codigoEAN': codigoEAN, 'quantidade': quantidade, }; } } </code></pre> <p>I tried to pass ever item on List separeted so, but not happen i expected.</p> <pre><code> Map&lt;String, dynamic&gt; toJSon(Coletas value) =&gt; { 'dtData' : dataIni, 'iCodigo': codigo, 'stItens': [], }; </code></pre>
[ { "answer_id": 74302599, "author": "brenodacosta", "author_id": 18091040, "author_profile": "https://Stackoverflow.com/users/18091040", "pm_score": 0, "selected": false, "text": "arr_list.append(''.join(arr[0:4]))\n" }, { "answer_id": 74302618, "author": "helloworld", "author_id": 9817642, "author_profile": "https://Stackoverflow.com/users/9817642", "pm_score": 0, "selected": false, "text": "arr_list.append(''.join(arr[0:4]))\n" }, { "answer_id": 74302628, "author": "Tr3ate", "author_id": 14793476, "author_profile": "https://Stackoverflow.com/users/14793476", "pm_score": 3, "selected": true, "text": "arr_list = []\narr = ['5', '6', '2', '4', '+']\narr_list.append(''.join(arr[0:4]))\nprint(arr_list)\n" }, { "answer_id": 74302641, "author": "Sash Sinha", "author_id": 6328256, "author_profile": "https://Stackoverflow.com/users/6328256", "pm_score": 0, "selected": false, "text": ">>> arr_list = []\n>>> arr = ['5', '6', '2', '4', '+']\n>>> arr_list.append(''.join(arr[0:4]))\n>>> arr_list\n['5624']\n" }, { "answer_id": 74302770, "author": "OneLastBug", "author_id": 19782437, "author_profile": "https://Stackoverflow.com/users/19782437", "pm_score": 0, "selected": false, "text": "arr_list.append(''.join(arr[0:4]))\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20266118/" ]
74,302,688
<p>I want create alert with extraction query. Query should fetch last 10 sec data and find the matching phrase</p> <p>I have tried below getting the matching phrase but it is taking from all the logs which are present. i want this phrase should search in last 10 sec logs. in kibana i have tried its working fine because there are options to set the time here in open search I did not found such options</p> <pre class="lang-json prettyprint-override"><code>{ &quot;query&quot;: { &quot;match_phrase&quot;: { &quot;log&quot;: { &quot;query&quot;: &quot;happy world&quot;, &quot;slop&quot;: 3, &quot;analyzer&quot;: &quot;standard&quot;, &quot;zero_terms_query&quot;: &quot;none&quot; } } } } </code></pre>
[ { "answer_id": 74302599, "author": "brenodacosta", "author_id": 18091040, "author_profile": "https://Stackoverflow.com/users/18091040", "pm_score": 0, "selected": false, "text": "arr_list.append(''.join(arr[0:4]))\n" }, { "answer_id": 74302618, "author": "helloworld", "author_id": 9817642, "author_profile": "https://Stackoverflow.com/users/9817642", "pm_score": 0, "selected": false, "text": "arr_list.append(''.join(arr[0:4]))\n" }, { "answer_id": 74302628, "author": "Tr3ate", "author_id": 14793476, "author_profile": "https://Stackoverflow.com/users/14793476", "pm_score": 3, "selected": true, "text": "arr_list = []\narr = ['5', '6', '2', '4', '+']\narr_list.append(''.join(arr[0:4]))\nprint(arr_list)\n" }, { "answer_id": 74302641, "author": "Sash Sinha", "author_id": 6328256, "author_profile": "https://Stackoverflow.com/users/6328256", "pm_score": 0, "selected": false, "text": ">>> arr_list = []\n>>> arr = ['5', '6', '2', '4', '+']\n>>> arr_list.append(''.join(arr[0:4]))\n>>> arr_list\n['5624']\n" }, { "answer_id": 74302770, "author": "OneLastBug", "author_id": 19782437, "author_profile": "https://Stackoverflow.com/users/19782437", "pm_score": 0, "selected": false, "text": "arr_list.append(''.join(arr[0:4]))\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18510198/" ]
74,302,807
<p>I am trying to write a function that checks the current day (In the format of Thursday, Friday, Monday), and then displays that day with the last 6 days behind it. For example:</p> <blockquote> <p>Friday, Saturday, Sunday, Monday, Tuesday, Wednesday, <strong>Thursday</strong></p> </blockquote> <blockquote> <p>Thursday, Friday, Saturday, Sunday, Monday, Tuesday, <strong>Wednesday</strong></p> </blockquote> <p>The last day being the current day. Hope I explained it more or less clear.</p> <p>I am using <em>MomentJs</em> to get the current day but I haven't managed to get much further than that. I am thinking of maybe using an Array with numbers that equal to the days of the week, but I don't know how to &quot;generate&quot; the other days. I have also thought of using a <em>for</em> loop to iterate through the <em>daysOfWeek</em> array and log each element until it reaches <em>currentDay</em> but then I don't know how to show the days of the week before, as it would only show the days of the current week, for example in the case of Thursday:</p> <blockquote> <p>Monday, Tuesday, Wednesday, Thursday</p> </blockquote> <p><em>So Sunday, Saturday, Friday would be missing</em></p> <pre><code>function dynamicLabels() { let daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] let currentDay = moment().format('dddd') if (daysOfWeek.includes(currentDay)) { } console.log() } </code></pre> <p>I know the code is pretty bare bones but I am completely stuck with this, even with the ideas I have mentioned above. Thanks in advance! :)</p>
[ { "answer_id": 74303061, "author": "gavgrif", "author_id": 5867572, "author_profile": "https://Stackoverflow.com/users/5867572", "pm_score": 3, "selected": true, "text": "function dynamicLabels(day) {\n let daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\n const dayIndex = daysOfWeek.indexOf(day) + 1;\n const preDays = daysOfWeek.slice(dayIndex);\n const postDays = daysOfWeek.slice(0,dayIndex);\n return preDays.concat(postDays);\n \n} \n\nconsole.log(dynamicLabels('Thursday'));\n//[\"Friday\",\"Saturday\", \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\"];\n\nconsole.log(dynamicLabels('Monday'));\n//[\"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\", \"Monday\"];\n\nconsole.log(dynamicLabels('Wednesday'));\n//[ \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\"];" }, { "answer_id": 74303313, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 0, "selected": false, "text": "const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nconsole.log(days.map((e,i,a)=>a[(new Date().getDay()+i+1)%7]));" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15415630/" ]
74,302,856
<p>I have a hypothetical api that returns color values based on user selection.</p> <p>Take an array with string values:</p> <pre><code>const Input1 = ['red', 'blue', 'purple']; const Input2 = ['blue', 'white']; </code></pre> <p>And the api returns objects:</p> <pre><code>const Response1 = { red: &quot;#ff0000&quot;, blue: &quot;#0000ff&quot;, purple: &quot;#aa22ff&quot; } const Response2 = { blue: &quot;#0000ff&quot;, white: &quot;#ffffff&quot; } </code></pre> <p>I can manually create the types:</p> <pre><code>type TResponse1 = { red: string; blue: string; purple: string; } type TResponse2 = { blue: string; white: string; } </code></pre> <p>But is it possible to derive the type? Something along the lines of this:</p> <pre><code>type TGenerated1 = {[any-value-from-Input1: string]: string}; type TGenerated2 = {[any-value-from-Input2: string]: string}; </code></pre>
[ { "answer_id": 74303061, "author": "gavgrif", "author_id": 5867572, "author_profile": "https://Stackoverflow.com/users/5867572", "pm_score": 3, "selected": true, "text": "function dynamicLabels(day) {\n let daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\n const dayIndex = daysOfWeek.indexOf(day) + 1;\n const preDays = daysOfWeek.slice(dayIndex);\n const postDays = daysOfWeek.slice(0,dayIndex);\n return preDays.concat(postDays);\n \n} \n\nconsole.log(dynamicLabels('Thursday'));\n//[\"Friday\",\"Saturday\", \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\"];\n\nconsole.log(dynamicLabels('Monday'));\n//[\"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\", \"Monday\"];\n\nconsole.log(dynamicLabels('Wednesday'));\n//[ \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\"];" }, { "answer_id": 74303313, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 0, "selected": false, "text": "const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nconsole.log(days.map((e,i,a)=>a[(new Date().getDay()+i+1)%7]));" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12348782/" ]
74,302,861
<p>I cannot get my spring-boot server to run against my database using docker.</p> <p>If I start up my mysql database (called <strong>shape-shop-db-container</strong>) and intialize the database like so :</p> <pre><code>docker run -d -p 3306:3306 --name=shape-shop-db-container --env=&quot;MYSQL_ROOT_PASSWORD=root&quot; --env=&quot;MYSQL_PASSWORD=root&quot; --env=&quot;MYSQL_DATABASE=shapeshop&quot; mysql docker exec -i shape-shop-db-container mysql -uroot -proot shapeshop &lt; SCHEMA.sql docker exec -i shape-shop-db-container mysql -uroot -proot shapeshop &lt; TEST_DATA.sql </code></pre> <p>and then run my application server <em>within</em> my IDE with the following <strong>application.properties</strong> :</p> <pre><code>spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/shapeshop?useSSL=false&amp;allowPublicKeyRetrieval=true&amp;serverTimezone=UTC&amp;useLegacyDatetimeCode=false spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect spring.datasource.username=root spring.datasource.password=root spring.datasource.platform=mysql spring.datasource.initialization-mode=always server.port=8080 </code></pre> <p>everything works <em>fine</em>.</p> <p>Now</p> <p>.... instead of running my application server through my IDE, I instead have it running on a docker <em>container</em>, and I try the following :</p> <p>(1) create network 'shape-shop-network'</p> <pre><code>docker network create shape-shop-network </code></pre> <p>(2) run db container as before, but this time specifying the <em>network</em> as well.</p> <pre><code>docker run -d -p 3306:3306 --name=shape-shop-db-container --network shape-shop-network --env=&quot;MYSQL_ROOT_PASSWORD=root&quot; --env=&quot;MYSQL_PASSWORD=root&quot; --env=&quot;MYSQL_DATABASE=shapeshop&quot; mysql docker exec -i shape-shop-db-container mysql -uroot -proot shapeshop &lt; SCHEMA.sql docker exec -i shape-shop-db-container mysql -uroot -proot shapeshop &lt; TEST_DATA.sql </code></pre> <p>(3) now i build my app server and run it on a container called 'shape-shop-server'.</p> <pre><code>docker build -t shapeshop:1.0 . docker run --name shape-shop-server -p 8080:8080 shapeshop:1.0 --name shape-shop-server --network shape-shop-network </code></pre> <p>But when I run it in the container, I get &quot;unable to acquire JDBC Connection&quot; error.</p> <pre><code>Caused by: org.springframework.dao.DataAccessResourceFailureException: Unable to acquire JDBC Connection; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection 2022-11-03T11:34:10.043594500Z at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:275) ~[spring-orm-5.1.8.RELEASE.jar:5.1.8.RELEASE] 2022-11-03T11:34:10.043602700Z at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:253) ~[spring-orm-5.1.8.RELEASE.jar:5.1.8.RELEASE] 2022-11-03T11:34:10.043610900Z Caused by: java.net.ConnectException: Connection refused (Connection refused) at java.base/java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:na] at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:412) ~[na:na] at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:255) ~[na:na] at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:237) ~[na:na] at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:na] </code></pre> <p>Why is this happening? Is something 'off' with my ports? Why would it work in my IDE but not as a container? I would assume that the settings are the same.</p> <p><strong>UPDATE:</strong></p> <p>I tried to rename &quot;localhost&quot; in my <strong>application.properties</strong> to shape-shop-db-conatiner. Eg :</p> <pre><code>spring.datasource.url=jdbc:mysql://shape-shop-db-container:3306/shapeshop?useSSL=false&amp;allowPublicKeyRetrieval=true&amp;serverTimezone=UTC&amp;useLegacyDatetimeCode=false </code></pre> <p>But I get &quot;Caused by: java.net.UnknownHostException: shape-shop-db-container&quot; , even though <strong>shape-shop-db-container</strong> is running.</p>
[ { "answer_id": 74328422, "author": "birca123", "author_id": 10231374, "author_profile": "https://Stackoverflow.com/users/10231374", "pm_score": 2, "selected": true, "text": "--hostname" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022330/" ]
74,302,879
<p>I have a data like below:</p> <pre><code>V1 V2 1 orange, apple 2 orange, lemon 3 lemon, apple 4 orange, lemon, apple 5 lemon 6 apple 7 orange 8 lemon, apple </code></pre> <p>I want to split the V2 variable like this:</p> <ul> <li>I have three categories of the V2 column: &quot;orange&quot;, &quot;lemon&quot;, &quot;apple&quot;</li> <li>for each of the categories I want to create a new column (variable) that will inform about whether such a name appeared in V2 (0,1)</li> </ul> <p>I tried this</p> <p><code>df %&gt;% separate(V2, into = c(&quot;orange&quot;, &quot;lemon&quot;, &quot;apple&quot;))</code></p> <p>.. and I got this result, but it's not what I expect.</p> <pre><code> V1 orange lemon apple 1 1 orange apple &lt;NA&gt; 2 2 orange lemon &lt;NA&gt; 3 3 lemon apple &lt;NA&gt; 4 4 orange lemon apple 5 5 lemon &lt;NA&gt; &lt;NA&gt; 6 6 apple &lt;NA&gt; &lt;NA&gt; 7 7 orange &lt;NA&gt; &lt;NA&gt; 8 8 lemon apple &lt;NA&gt; </code></pre> <p>The result I mean is below.</p> <pre><code>V1 orange lemon apple 1 1 0 1 2 1 1 0 3 0 1 1 4 1 1 0 5 0 1 0 6 0 0 1 7 1 0 0 8 0 1 1 </code></pre>
[ { "answer_id": 74303000, "author": "Stephan", "author_id": 8598377, "author_profile": "https://Stackoverflow.com/users/8598377", "pm_score": 3, "selected": true, "text": "library(dplyr)\nlibrary(tidyr)\ndf |> \n separate_rows(V2, sep = \", \") |> \n mutate(ind = 1) |> \n pivot_wider(names_from = V2,\n values_from = ind,\n values_fill = 0)\n\n" }, { "answer_id": 74305215, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "dummy_cols" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18002254/" ]
74,302,884
<p>Consider a simple clock display and an input which I bound one-way to keep control over old/new state:</p> <pre class="lang-html prettyprint-override"><code>&lt;div&gt;{{ time }}&lt;/div&gt; &lt;input ref=&quot;text&quot; type=&quot;text&quot; :value=&quot;text&quot; style=&quot;width:95%&quot;&gt; &lt;button type=&quot;button&quot; @click=&quot;saveOnDiff&quot;&gt;Save&lt;/button&gt; </code></pre> <pre class="lang-js prettyprint-override"><code>createApp({ ..., methods: { saveOnDiff() { const current = this.$refs.text.value; // Compare current with old text + update if it changed. ... } }, mounted() { const instance = this; setInterval(() =&gt; instance.time = new Date(), 1000); } }).mount('#app'); </code></pre> <p>The clock is updated each second. Unfortunately, this update spoils the input. Try it here: <a href="https://jsfiddle.net/dL78tsh9" rel="nofollow noreferrer">https://jsfiddle.net/dL78tsh9</a></p> <p><strong>How can I reduce binding updates to the absolute necessary ones?</strong> Some extra switch on one-way bindings like <code>:value.lazy=&quot;text&quot;</code> would be helpful...</p>
[ { "answer_id": 74303793, "author": "Tolbxela", "author_id": 2487565, "author_profile": "https://Stackoverflow.com/users/2487565", "pm_score": 0, "selected": false, "text": ":value" }, { "answer_id": 74303863, "author": "Facundo Gallardo", "author_id": 20375146, "author_profile": "https://Stackoverflow.com/users/20375146", "pm_score": 1, "selected": false, "text": "const {\n createApp\n} = Vue\n\nconst characterWiseDiff = (left, right) => right\n .split(\"\")\n .filter(function(character, index) {\n return character != left.charAt(index);\n })\n .join(\"\");\n\n\ncreateApp({\n data() {\n return {\n result: \"\",\n text: \"Try to change me here\",\n previousText: \"Try to change me here\",\n time: new Date(),\n }\n },\n methods: {\n saveOnDiff() {\n if (this.text === this.previousText) {\n this.result = \"No changes have been made!\";\n } else {\n this.result = `Saved! Your changes were: \"${characterWiseDiff(this.previousText, this.text)}\"`;\n this.previousText = this.text;\n }\n }\n },\n mounted() {\n const instance = this;\n setInterval(() => instance.time = new Date(), 1000);\n }\n}).mount('#app');" }, { "answer_id": 74303890, "author": "Rohìt Jíndal", "author_id": 4116300, "author_profile": "https://Stackoverflow.com/users/4116300", "pm_score": 1, "selected": false, "text": "time" }, { "answer_id": 74379167, "author": "Marcel", "author_id": 692753, "author_profile": "https://Stackoverflow.com/users/692753", "pm_score": 1, "selected": true, "text": "v-memo=\"[text]\"" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/692753/" ]
74,302,888
<p>I have : (dateTime is in string format)</p> <pre><code>df dateTime level 2020-10-31T23:18:00.000 slow 2020-10-31T23:25:00.000 moderate </code></pre> <p>I want to convert this to time series in 1min level by replicating the 'level' for every minute until the next instance where there is a change:</p> <pre><code>df dateTime level 2020-10-31 23:18:00 slow 2020-10-31 23:19:00 slow 2022-10-31 23:20:00 slow ...... 2020-10-31 23:25:00 moderate 2022-10-31 23:26:00 moderate </code></pre> <p>How do I, first convert the string dateTime format into datetime dtype, and convert the dataframe into time series?</p>
[ { "answer_id": 74303793, "author": "Tolbxela", "author_id": 2487565, "author_profile": "https://Stackoverflow.com/users/2487565", "pm_score": 0, "selected": false, "text": ":value" }, { "answer_id": 74303863, "author": "Facundo Gallardo", "author_id": 20375146, "author_profile": "https://Stackoverflow.com/users/20375146", "pm_score": 1, "selected": false, "text": "const {\n createApp\n} = Vue\n\nconst characterWiseDiff = (left, right) => right\n .split(\"\")\n .filter(function(character, index) {\n return character != left.charAt(index);\n })\n .join(\"\");\n\n\ncreateApp({\n data() {\n return {\n result: \"\",\n text: \"Try to change me here\",\n previousText: \"Try to change me here\",\n time: new Date(),\n }\n },\n methods: {\n saveOnDiff() {\n if (this.text === this.previousText) {\n this.result = \"No changes have been made!\";\n } else {\n this.result = `Saved! Your changes were: \"${characterWiseDiff(this.previousText, this.text)}\"`;\n this.previousText = this.text;\n }\n }\n },\n mounted() {\n const instance = this;\n setInterval(() => instance.time = new Date(), 1000);\n }\n}).mount('#app');" }, { "answer_id": 74303890, "author": "Rohìt Jíndal", "author_id": 4116300, "author_profile": "https://Stackoverflow.com/users/4116300", "pm_score": 1, "selected": false, "text": "time" }, { "answer_id": 74379167, "author": "Marcel", "author_id": 692753, "author_profile": "https://Stackoverflow.com/users/692753", "pm_score": 1, "selected": true, "text": "v-memo=\"[text]\"" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15299852/" ]
74,302,922
<p>I have gone through stack over flow and found these questions</p> <p><a href="https://stackoverflow.com/questions/38972736/how-to-print-lines-between-two-patterns-inclusive-or-exclusive-in-sed-awk-or">How to print lines between two patterns, inclusive or exclusive (in sed, AWK or Perl)?</a></p> <p><a href="https://stackoverflow.com/questions/66737726/combine-multiple-lines-between-flags-in-one-line-in-awk">Combine multiple lines between flags in one line in AWK</a></p> <p>The problem with my question is that there can be another TAG1 without the matching TAG2 like this</p> <p>file.txt:</p> <pre><code>aa TAG1 some right text TAG2 some text2 TAG1 some text3 TAG1 some text4 TAG1 some right text 2 TAG2 some text4 TAG1 some text5 some text6 </code></pre> <p>expected output:</p> <pre><code>TAG1 some right text TAG2 TAG1 some right text 2 TAG2 </code></pre>
[ { "answer_id": 74303029, "author": "Sundeep", "author_id": 4082052, "author_profile": "https://Stackoverflow.com/users/4082052", "pm_score": 2, "selected": true, "text": "TAG2" }, { "answer_id": 74304125, "author": "Thor", "author_id": 1331399, "author_profile": "https://Stackoverflow.com/users/1331399", "pm_score": 0, "selected": false, "text": "sed -nE ':a; /TAG1$/ s/.*(TAG1)/\\1/; N; /TAG2$/ { /^TAG1/ { G; p; }; z; }; ba'\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/799325/" ]
74,302,932
<p>I have a viewModel containing a list and another class like so :</p> <pre><code>public class MyViewModel { public List&lt;Guids&gt; Ids{ get; set; } public History HistoryRecord{ get; set; } } public class History { public string UserName{ get; set; } public string Email{ get; set; } } </code></pre> <p>and a controller action that I need to send the above data to:</p> <pre><code>public async Task&lt;IActionResult&gt; myAction([Bind(&quot;Ids&quot;,&quot;UserName&quot;,&quot;Email&quot;)] MyViewModel viewModel) { ... } </code></pre> <p>i'm getting the values for userName and Email via inputs</p> <pre><code> &lt;input type=&quot;text&quot; class=&quot;form-control child &quot; name=&quot;name&quot; id=&quot;nameTextbox&quot; placeholder=&quot;name&quot; required /&gt; &lt;input type=&quot;text&quot; class=&quot;form-control child &quot; name=&quot;email&quot; id=&quot;emailTextbox&quot; placeholder=&quot;email&quot; required /&gt; </code></pre> <p>how can I send this from a razor page?</p> <p>i've tried using url.Action but this doesnt seem to work and not sure how to put multiple values in</p> <pre><code>&lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot; id=&quot;confirm&quot; onclick=&quot;location.href='@Url.Action(&quot;myAction&quot;,&quot;myController&quot;, values: new {Ids= @Model.Ids.ToList(), Name = ? , Emil = ? })'&quot;&gt;confrim&lt;/button&gt; </code></pre>
[ { "answer_id": 74303029, "author": "Sundeep", "author_id": 4082052, "author_profile": "https://Stackoverflow.com/users/4082052", "pm_score": 2, "selected": true, "text": "TAG2" }, { "answer_id": 74304125, "author": "Thor", "author_id": 1331399, "author_profile": "https://Stackoverflow.com/users/1331399", "pm_score": 0, "selected": false, "text": "sed -nE ':a; /TAG1$/ s/.*(TAG1)/\\1/; N; /TAG2$/ { /^TAG1/ { G; p; }; z; }; ba'\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9931604/" ]
74,302,940
<p>I want to update the listBox items after doubleClick and modifying the selectedItem in a texbox. It doesn't work.</p> <p>XAML</p> <pre><code>&lt;Window x:Class=&quot;MainWindow&quot; xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; Title=&quot;MainWindow&quot; Height=&quot;450&quot; Width=&quot;800&quot;&gt; &lt;Grid&gt; &lt;ListBox x:Name=&quot;lstTextes&quot; SelectedItem=&quot;{Binding SelectedText,Mode=TwoWay}&quot; ItemsSource=&quot;{Binding ListTexts,UpdateSourceTrigger=PropertyChanged}&quot; Grid.Column=&quot;0&quot; Margin=&quot;52,54,117,85&quot; MouseDoubleClick=&quot;lstTextes_DblClick&quot;/&gt; &lt;Popup x:Name=&quot;popLigText&quot; StaysOpen=&quot;False&quot; Grid.ColumnSpan=&quot;1&quot; Width=&quot;300&quot; IsOpen=&quot;false&quot;&gt; &lt;ScrollViewer VerticalScrollBarVisibility=&quot;Auto&quot; MaxHeight=&quot;500&quot; Background=&quot;#F9F9F9&quot; FontSize=&quot;11&quot; Foreground=&quot;#0E1D31&quot;&gt; &lt;StackPanel&gt; &lt;TextBox x:Name=&quot;TB_LigneText&quot; HorizontalAlignment=&quot;Center&quot; Text=&quot;{Binding Path=SelectedItem, ElementName=lstTextes, Mode=TwoWay}&quot; Width=&quot;300&quot; Height=&quot;30&quot; KeyDown=&quot;UpdateSelectedItem&quot;/&gt; &lt;/StackPanel&gt; &lt;/ScrollViewer&gt; &lt;/Popup&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>Code vb.net</p> <pre><code> Imports System.ComponentModel Class MainWindow Private Property datasGravures As New Gravures Sub New() InitializeComponent() Me.DataContext = datasGravures End Sub Private Sub UpdateSelectedItem(sender As Object, e As KeyEventArgs) Dim c As TextBox = sender If e.Key = Key.Return Then Me.popLigText.IsOpen = False End If End Sub Private Sub lstTextes_DblClick(sender As Object, e As MouseButtonEventArgs) Dim c As ListBox = sender Me.popLigText.PlacementTarget = c Me.popLigText.IsOpen = True End Sub End Class </code></pre> <pre><code> Class Gravures Implements INotifyPropertyChanged Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged Private Property _ListTexts As New List(Of String) Private Property _selectedText As String Sub New() ListTexts.Add(&quot;toto&quot;) ListTexts.Add(&quot;titi&quot;) End Sub Public Sub OnPropertyChanged(ByVal e As PropertyChangedEventArgs) If Not PropertyChangedEvent Is Nothing Then RaiseEvent PropertyChanged(Me, e) End If End Sub Public Property ListTexts As List(Of String) Get Return _ListTexts End Get Set(value As List(Of String)) _ListTexts = value OnPropertyChanged(New PropertyChangedEventArgs(&quot;ListTexts&quot;)) End Set End Property Public Property SelectedText As String Get Return _selectedText End Get Set(value As String) _SelectedText = value OnPropertyChanged(New PropertyChangedEventArgs(&quot;SelectedText&quot;)) End Set End Property End Class </code></pre> <p>Where is the error? Thank you for your help.</p> <p>the textbox is displayed with the text of the selected item. I modify it, the list(of string) ListText is modified but the textBox does not update.</p>
[ { "answer_id": 74303029, "author": "Sundeep", "author_id": 4082052, "author_profile": "https://Stackoverflow.com/users/4082052", "pm_score": 2, "selected": true, "text": "TAG2" }, { "answer_id": 74304125, "author": "Thor", "author_id": 1331399, "author_profile": "https://Stackoverflow.com/users/1331399", "pm_score": 0, "selected": false, "text": "sed -nE ':a; /TAG1$/ s/.*(TAG1)/\\1/; N; /TAG2$/ { /^TAG1/ { G; p; }; z; }; ba'\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7261294/" ]
74,302,953
<p>here is the code i done. and it works perfectly fine. i tried debugging and the post method is posting everything properly. but the notification is not receiving. here is the whole code</p> <pre><code>import 'dart:convert'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'firebase_options.dart'; import 'package:http/http.dart' as http; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState(); } class _MyHomePageState extends State&lt;MyHomePage&gt; { int _counter = 0; Future&lt;bool&gt; callOnFcmApiSendPushNotifications( {required String title, required String body}) async { const postUrl = 'https://fcm.googleapis.com/fcm/send'; final data = { &quot;to&quot;: &quot;/topics/myTopic&quot;, &quot;notification&quot;: { &quot;title&quot;: title, &quot;body&quot;: body, }, &quot;data&quot;: { &quot;type&quot;: '0rder', &quot;id&quot;: '28', &quot;click_action&quot;: 'FLUTTER_NOTIFICATION_CLICK', } }; final headers = { 'content-type': 'application/json', 'Authorization': 'key=AAAAMKtOtwQ:APA91bFCCEwWKU75EVeyc912ghzS0Yon8dlfjiFEiw9nfdtfrq0BCBWS3x_ioTqX1l2MUDO_Wb-c2PbRl66Z_2mvFEsPRbDEAPTSCEb7SVFykecC_BWGR5P2La8T47eIfCiMvU9oJDJd' }; final response = await http.post(Uri.parse(postUrl), body: json.encode(data), encoding: Encoding.getByName('utf-8'), headers: headers); if (response.statusCode == 200) { print('test ok push CFM'); return true; } else { print(' CFM error'); return false; } } void _incrementCounter() { setState(() { callOnFcmApiSendPushNotifications( title: 'fcm by api2', body: 'its working fine2'); _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: &lt;Widget&gt;[ const Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } } </code></pre> <p>is there anything i need to fix from firebase or any problem with the code. i can't figure it out please help me</p> <p>i tried debugging and printing everywhere in the code file. and everything work fine. and i enabled everything ive to do from firebase. still not getting a notification</p> <p>also I'm testing this in android</p>
[ { "answer_id": 74303029, "author": "Sundeep", "author_id": 4082052, "author_profile": "https://Stackoverflow.com/users/4082052", "pm_score": 2, "selected": true, "text": "TAG2" }, { "answer_id": 74304125, "author": "Thor", "author_id": 1331399, "author_profile": "https://Stackoverflow.com/users/1331399", "pm_score": 0, "selected": false, "text": "sed -nE ':a; /TAG1$/ s/.*(TAG1)/\\1/; N; /TAG2$/ { /^TAG1/ { G; p; }; z; }; ba'\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20278822/" ]
74,302,956
<p>I fairly new to programming in python and using the pandas library and I am having problems with comparing 2 dataframes with different quantities i want to see if the quantity in data_1 is less than the quantity in data_2 for each item</p> <pre><code>import pandas as pd data_1 = [['banana',10],['orange',2],['strawberry',3]] data_2 = [['banana',1],['orange',2],['strawberry',5],['melon',8]] df_1 = pd.Dataframe(data_1,columns = ['item','quantity']) df_2 = pd.Dataframe(data_2,columns = ['item','quantity']) </code></pre> <p><a href="https://i.stack.imgur.com/PcRI3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PcRI3.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/WO45M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WO45M.png" alt="enter image description here" /></a></p> <p>i was trying to use pd.merge() the 2 dataframes to compare but it's not quite what i was looking for..... i needed a 3° dataframe with the differences only</p>
[ { "answer_id": 74303029, "author": "Sundeep", "author_id": 4082052, "author_profile": "https://Stackoverflow.com/users/4082052", "pm_score": 2, "selected": true, "text": "TAG2" }, { "answer_id": 74304125, "author": "Thor", "author_id": 1331399, "author_profile": "https://Stackoverflow.com/users/1331399", "pm_score": 0, "selected": false, "text": "sed -nE ':a; /TAG1$/ s/.*(TAG1)/\\1/; N; /TAG2$/ { /^TAG1/ { G; p; }; z; }; ba'\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17443294/" ]
74,302,969
<p>I have multiple csv files (which I've moved into pandas dataframes) in a folder, each of which holds monthly website data</p> <pre><code>January.csv: URL Value page1 10 page2 52 page3 17 February.csv: URL Value page1 20 page2 7 page3 15 March.csv: URL Value page1 7 page2 15 page3 23 </code></pre> <p>and need to combine them by copying the Value column from each to make a new dataframe (which will ultimately be exported to another csv)</p> <pre><code>URL January February March page1 10 20 7 page2 52 7 15 page3 17 15 23 </code></pre> <p>A new csv file will be added to the folder each month, so I need to keep it as dynamic as possible. I'm currently using <code>all_filenames = [i for i in glob.glob('*.{}'.format('csv'))]</code> to get the files with the hope that I can then use something like <code>pd.read_csv(f)['URL'] for f in all_filenames</code>, but that may be totally the wrong approach?</p> <p>Can anyone point me in the right direction?</p> <p>Thanks</p>
[ { "answer_id": 74303064, "author": "robinood", "author_id": 8814229, "author_profile": "https://Stackoverflow.com/users/8814229", "pm_score": 1, "selected": false, "text": "all_filenames = [i for i in glob.glob('*.{}'.format('csv'))]\nall_df = [pd.read_csv(f) for f in all_filenames]\n" }, { "answer_id": 74303290, "author": "SultanOrazbayev", "author_id": 10693596, "author_profile": "https://Stackoverflow.com/users/10693596", "pm_score": 3, "selected": true, "text": "all_filenames = [i for i in glob.glob('*.{}'.format('csv'))]\nresult = pd.concat((pd.read_csv(f, index_col='URL', usecols=['URL', 'Value']) for f in all_filenames), axis=1)\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4737883/" ]
74,302,979
<p>I have found that one can add Closing property inside Window tag in .xaml file and then define closing behaviour in the c# file.</p> <pre><code>&lt;Window ... Closing=&quot;DataWindow_Closing&quot;&gt; </code></pre> <p>Which works fine.</p> <p>In my case I have an instance of a window that is defined in c# like this:</p> <pre><code> public bool ShowDial() { var window = new Window { Content = this, ResizeMode = ResizeMode.NoResize }; ... } </code></pre> <p>How to define closing behaviour of this window that is instantiated in c# and not in xaml file?</p> <p>P.S. I have a UserControl defined in .xaml file</p>
[ { "answer_id": 74303335, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 3, "selected": true, "text": "Closing" }, { "answer_id": 74303345, "author": "EldHasp", "author_id": 13349759, "author_profile": "https://Stackoverflow.com/users/13349759", "pm_score": 2, "selected": false, "text": "Closing" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74302979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19902555/" ]
74,303,003
<p>I'm trying to push my local git project into github remote repo. I added node_modules into one commit I made but this exceeds GitHub's file size limit of 100.00 MB when I try</p> <pre><code>git push -u origin main </code></pre> <p>then</p> <pre><code>remote: error: Trace: d8e81b49d1b7e109e7b4585cf6b84d574b3888e15cb1b4f858c87c5a0147bc57 remote: error: File node_modules/node-sass/build/Release/libsass.lib is 160.60 MB; this exceeds GitHub's file size limit of 100.00 MB </code></pre> <p>Then I added .gitignore but that doesn't work because the commit was already made</p> <p>I tried to remove that node_modules from being tracked and commited using</p> <pre><code>git rm -r cached node_modules </code></pre> <p>but it keeps trying to push that when I do git push.</p> <p>I don't know how to remove node_modules from being pushed</p>
[ { "answer_id": 74303138, "author": "Tirth", "author_id": 11717445, "author_profile": "https://Stackoverflow.com/users/11717445", "pm_score": 1, "selected": false, "text": "git reset HEAD~N\n" }, { "answer_id": 74304488, "author": "Torge Rosendahl", "author_id": 10875738, "author_profile": "https://Stackoverflow.com/users/10875738", "pm_score": 3, "selected": true, "text": "master" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12924124/" ]
74,303,006
<p>I want to be able to get a list with a range of numbers 3 or higher, and turn it into a list of numbers of range 1 to 3 only. The code only removes some numbers above 3 and leaves others. I want all numbers above 3 removed from the list.</p> <pre><code>thelist= [1,8,9,2,3] for element in thelist: if int(element) &gt;= 4: thelist.remove(element) elif int(element) &lt;= 3: continue print(thelist) # prints [1, 9, 2, 3]. Number 8 was removed but not number 9 </code></pre>
[ { "answer_id": 74303138, "author": "Tirth", "author_id": 11717445, "author_profile": "https://Stackoverflow.com/users/11717445", "pm_score": 1, "selected": false, "text": "git reset HEAD~N\n" }, { "answer_id": 74304488, "author": "Torge Rosendahl", "author_id": 10875738, "author_profile": "https://Stackoverflow.com/users/10875738", "pm_score": 3, "selected": true, "text": "master" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19608349/" ]
74,303,023
<p>0</p> <p>I write two inputs by same change function in vue.js but when inputs changed T method works just on one input. what should i do tp resolve this problem?</p> <pre><code>&lt;select v-model=&quot;client.day&quot; @change=&quot;birthday_changed&quot; id=&quot;birthday_day&quot;&gt; &lt;option v-for=&quot;day in 31&quot; :key=day :value=&quot;('0' + day).slice(-2)&quot;&gt;{{ (&quot;0&quot; + day).slice(-2) }}&lt;/option&gt; &lt;/select&gt; &lt;select v-model=&quot;client.year&quot; @change=&quot;birthday_changed&quot; id=&quot;birthday_year&quot;&gt; &lt;option v-for=&quot;year in 81&quot; :key=year :value=&quot;1320 + year&quot;&gt; {{ 1320 + year }} &lt;/option&gt; &lt;/select&gt; birthday_changed: function () { alert('changed'); }, </code></pre>
[ { "answer_id": 74303138, "author": "Tirth", "author_id": 11717445, "author_profile": "https://Stackoverflow.com/users/11717445", "pm_score": 1, "selected": false, "text": "git reset HEAD~N\n" }, { "answer_id": 74304488, "author": "Torge Rosendahl", "author_id": 10875738, "author_profile": "https://Stackoverflow.com/users/10875738", "pm_score": 3, "selected": true, "text": "master" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8327515/" ]
74,303,026
<p>I'm trying to code an optimization problem in Julia using <code>JuMP</code>. The objective function has two matrix multiplications.<br /> <strong>First</strong>, multiply the vector of <code>w</code> with size (10) by the matrix of <code>arr_C</code> with size (20, 10). So the <code>w</code> should be transposed to size (1, 10) to perform matrix multiplication.<br /> <strong>Second</strong>, multiply the vector of <code>w_each_sim</code> with size (20) by the result of the first multiplication, which is also a vector of size (20). So the multiplication should be like (1x20) x (20x1) to achieve a scalar. Please read until the last line of the question because I applied updates according to suggestions. My first try is as follows:</p> <pre><code>julia&gt; using JuMP, Ipopt julia&gt; a = rand(20, 10); julia&gt; b = rand(20); b = b./sum(b) julia&gt; function port_opt( n_assets::Int8, arr_C::Matrix{Float64}, w_each_sim::Vector{Float64}) &quot;&quot;&quot; Calculate weight of each asset through optimization Parameters ---------- n_assets::Int8 - number of assets arr_C::Matrix{Float64} - array of C w_each_sim::Vector{Float64} - weights of each similar TW Returns ------- w_opt::Vector{Float64} - weights of each asset &quot;&quot;&quot; model = Model(Ipopt.Optimizer) @variable(model, 0&lt;= w[1:n_assets] &lt;=1) @NLconstraint(model, sum([w[i] for i in 1:n_assets]) == 1) @NLobjective(model, Max, w_each_sim * log10.([w[i]*arr_C[i] for i in 1:n_assets])) optimize!(model) @show value.(w) return value.(w) end julia&gt; port_opt(Int8(10), a, b) ERROR: UndefVarError: i not defined Stacktrace: [1] macro expansion @ C:\Users\JL\.julia\packages\JuMP\Z1pVn\src\macros.jl:1834 [inlined] [2] port_opt(n_assets::Int8, arr_C::Matrix{Float64}, w_each_sim::Vector{Float64}) @ Main e:\MyWork\paperbase.jl:237 [3] top-level scope @ REPL[4]:1 </code></pre> <p>The problem is with the <code>@NLconstraint</code> line. How can I make this code work and get the optimization done?</p> <h2>Aditional tests</h2> <p>As @Shayan suggested, I rectified the objective function as follows:</p> <pre><code>function Obj(w, arr_C, w_each_sim) first_expr = w'*arr_C' second_expr = map(first_expr) do x log10(x) end return w_each_sim * second_expr end function port_opt( n_assets::Int8, arr_C::Matrix{Float64}, w_each_sim::Vector{Float64}) .... .... @NLconstraint(model, sum(w[i] for i in 1:n_assets) == 1) @NLobjective(model, Max, Obj(w, arr_C, w_each_sim)) optimize!(model) @show value.(w) return value.(w) end a, b = rand(20, 10), rand(20); b = b./sum(b); port_opt(Int8(10), a, b) # Threw this: ERROR: Unexpected array VariableRef[w[1], w[2], w[3], w[4], w[5], w[6], w[7], w[8], w[9], w[10]] in nonlinear expression. Nonlinear expressions may contain only scalar expressions. </code></pre> <p>Now, based on @PrzemyslawSzufel's suggestions, I tried this:</p> <pre><code>function Obj(w, arr_C::Matrix{T}, w_each_sim::Vector{T}) where {T&lt;:Real} first_expr = zeros(T, length(w_each_sim)) for i∈size(w_each_sim, 1), j∈eachindex(w) first_expr[i] += w[j]*arr_C[i, j] end second_expr = map(first_expr) do x log(x) end res = 0 for idx∈eachindex(w_each_sim) res += w_each_sim[idx]*second_expr[idx] end return res end function port_opt( n_assets::Int8, arr_C::Matrix{Float64}, w_each_sim::Vector{Float64}) model = Model() @variable(model, 0&lt;= w[1:n_assets] &lt;=1) @NLconstraint(model, +(w...) == 1) register(model, :Obj, Int64(n_assets), Obj, autodiff=true) @NLobjective(model, Max, Obj(w, arr_C, w_each_sim)) optimize!(model) @show value.(w) return value.(w) end a, b = rand(20, 10), rand(20); b = b./sum(b); port_opt(Int8(10), a, b) # threw this ERROR: Unable to register the function :Obj because it does not support differentiation via ForwardDiff. Common reasons for this include: * the function assumes `Float64` will be passed as input, it must work for any generic `Real` type. * the function allocates temporary storage using `zeros(3)` or similar. This defaults to `Float64`, so use `zeros(T, 3)` instead. </code></pre>
[ { "answer_id": 74303963, "author": "Przemyslaw Szufel", "author_id": 9957710, "author_profile": "https://Stackoverflow.com/users/9957710", "pm_score": 1, "selected": false, "text": "@constraint(model, sum([w[i] for i in 1:n_assets]) == 1)\n" }, { "answer_id": 74309548, "author": "Oscar Dowson", "author_id": 13591160, "author_profile": "https://Stackoverflow.com/users/13591160", "pm_score": 3, "selected": true, "text": "using JuMP, Ipopt\na = rand(20, 10)\nb = rand(20); b = b./sum(b)\n\n\"\"\"\nCalculate weight of each asset through optimization\n\nParameters\n----------\n n_assets::Int8 - number of assets\n arr_C::Matrix{Float64} - array of C\n w_each_sim::Vector{Float64} - weights of each similar TW\n\nReturns\n-------\n w_opt::Vector{Float64} - weights of each asset\n\"\"\"\nfunction port_opt(\n n_assets::Int8,\n arr_C::Matrix{Float64},\n w_each_sim::Vector{Float64},\n)\n model = Model(Ipopt.Optimizer)\n @variable(model, 0<= w[1:n_assets] <=1)\n @NLconstraint(model, sum(w[i] for i in 1:n_assets) == 1)\n @NLobjective(\n model,\n Max, \n sum(\n w_each_sim[i] * log10(sum(w[j] * arr_C[i, j] for j in 1:size(arr_C, 2)))\n for i in 1:length(w_each_sim)\n )\n )\n optimize!(model)\n return value.(w)\nend\n\nport_opt(Int8(10), a, b)\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20407495/" ]
74,303,028
<p>I have the following problem, in my VBA code it comes to Runtime Error 5 Invalid Procedure call or argument when I want to save a range as PDF. The code looks like this:</p> <pre><code>Worksheets(2).Range(&quot;A1:G103&quot;).ExportAsFixedFormat Type:=xlTypePDF, Filename:=path1_1 &amp; &quot;\Idea&quot; &amp; Worksheets(3).Range(&quot;B12&quot;).Value &amp; &quot;.pdf&quot;, OpenAfterPublish:=False </code></pre> <p>The sheet that is being accessed is hidden. The error message does not occur if <code>Worksheets(2).Visible = True</code>. How can I write the code so that the error message no longer comes up and I don't have to show the sheets? It would also be good to know why the error occurs. I really appreciate your help.</p> <pre><code>Worksheets(2).Visible = True Worksheets(2).Range(&quot;A1:G103&quot;).ExportAsFixedFormat Type:=xlTypePDF, Filename:=path1_1 &amp; &quot;\Idea&quot; &amp; Worksheets(3).Range(&quot;B12&quot;).Value &amp; &quot;.pdf&quot;, OpenAfterPublish:=False Worksheets(2).Visible = xlVeryHidden </code></pre> <p>This is how the VBA code would work but unfortunately this is not an option.</p>
[ { "answer_id": 74303963, "author": "Przemyslaw Szufel", "author_id": 9957710, "author_profile": "https://Stackoverflow.com/users/9957710", "pm_score": 1, "selected": false, "text": "@constraint(model, sum([w[i] for i in 1:n_assets]) == 1)\n" }, { "answer_id": 74309548, "author": "Oscar Dowson", "author_id": 13591160, "author_profile": "https://Stackoverflow.com/users/13591160", "pm_score": 3, "selected": true, "text": "using JuMP, Ipopt\na = rand(20, 10)\nb = rand(20); b = b./sum(b)\n\n\"\"\"\nCalculate weight of each asset through optimization\n\nParameters\n----------\n n_assets::Int8 - number of assets\n arr_C::Matrix{Float64} - array of C\n w_each_sim::Vector{Float64} - weights of each similar TW\n\nReturns\n-------\n w_opt::Vector{Float64} - weights of each asset\n\"\"\"\nfunction port_opt(\n n_assets::Int8,\n arr_C::Matrix{Float64},\n w_each_sim::Vector{Float64},\n)\n model = Model(Ipopt.Optimizer)\n @variable(model, 0<= w[1:n_assets] <=1)\n @NLconstraint(model, sum(w[i] for i in 1:n_assets) == 1)\n @NLobjective(\n model,\n Max, \n sum(\n w_each_sim[i] * log10(sum(w[j] * arr_C[i, j] for j in 1:size(arr_C, 2)))\n for i in 1:length(w_each_sim)\n )\n )\n optimize!(model)\n return value.(w)\nend\n\nport_opt(Int8(10), a, b)\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19983642/" ]
74,303,081
<p>I'm trying to write a code for serial and parallel algorithm of LDLT decomposition in C++ using MPI. Here's a code</p> <pre><code>#include &lt;iostream&gt; #include &lt;mpi.h&gt; #include &lt;cassert&gt; #include &lt;chrono&gt; #include &lt;cmath&gt; namespace para { double solveSym(int n, double* a, double* b) { int nproc, myid; MPI_Comm_size(MPI_COMM_WORLD, &amp;nproc); MPI_Comm_rank(MPI_COMM_WORLD, &amp;myid); int i = myid; if (myid != 0) { double data; MPI_Request rreq; MPI_Irecv((void*)&amp;data, 1, MPI_DOUBLE, myid - 1, 0, MPI_COMM_WORLD, &amp;rreq); MPI_Status st; MPI_Wait(&amp;rreq, &amp;st); a[i * n + i] = data; } double invp = 1.0 / a[i * n + i]; int send_size = 0; int recv_size = 1; for (int j = i + 1; j &lt; n; j++) { send_size++; recv_size++; if (myid != 0) { double* data = new double[j]; MPI_Request rreq; MPI_Irecv((void*)data, recv_size, MPI_DOUBLE, myid - 1, 0, MPI_COMM_WORLD, &amp;rreq); MPI_Status st; MPI_Wait(&amp;rreq, &amp;st); for (int k = 0; k &lt; recv_size; k++) a[j * n + (myid + k)] = data[k]; } double aji = a[j * n + i]; a[j * n + i] *= invp; for (int k = i + 1; k &lt;= j; k++) a[j * n + k] -= aji * a[k * n + i]; if (myid != nproc - 1) { MPI_Request sreq; double* send_data = new double[send_size]; for (int k = 0; k &lt; send_size; k++) send_data[k] = a[j * n + (i + 1 + k)]; MPI_Isend((void*)send_data, send_size, MPI_DOUBLE, myid + 1, 0, MPI_COMM_WORLD, &amp;sreq); MPI_Status st; MPI_Wait(&amp;sreq, &amp;st); } } return 0; } } namespace seq { void symMatVec(int n, double* a, double* x, double* y) { int i, j; for (i = 0; i &lt; n; i++) { double t = 0.0; for (j = 0; j &lt;= i; j++) t += a[i * n + j] * x[j]; for (j = i + 1; j &lt; n; j++) t += a[j * n + i] * x[j]; y[i] = t; } } void solveSym(int n, double* a, double* x, double* b) { for (int i = 0; i &lt; n; i++) { double invp = 1.0 / a[i * n + i]; for (int j = i + 1; j &lt; n; j++) { double aji = a[j * n + i]; a[j * n + i] *= invp; for (int k = i + 1; k &lt;= j; k++) a[j * n + k] -= aji * a[k * n + i]; } } for (int i = 0; i &lt; n; i++) { double t = b[i]; for (int j = 0; j &lt; i; j++) t -= a[i * n + j] * x[j]; x[i] = t; } for (int i = n - 1; i &gt;= 0; i--) { double t = x[i] / a[i * n + i]; for (int j = i + 1; j &lt; n; j++) t -= a[j * n + i] * x[j]; x[i] = t; } } } int main(int argc, char** argv) { srand((unsigned)time(NULL)); MPI_Init(&amp;argc, &amp;argv); int nproc, myid; MPI_Comm_size(MPI_COMM_WORLD, &amp;nproc); MPI_Comm_rank(MPI_COMM_WORLD, &amp;myid); int n = nproc; double* a = new double[n * n]; assert(a != NULL); for (int i = 0; i &lt; n; i++) for (int j = 0; j &lt; i; j++) a[i * n + j] = rand() / (RAND_MAX + 1.0); for (int i = 0; i &lt; n; i++) { double s = 0.0; for (int j = 0; j &lt; i; j++) s += a[i * n + j]; for (int j = i + 1; j &lt; n; j++) s += a[j * n + i]; a[i * n + i] = s + 1.0; } double start, end; double* xx = new double[n]; assert(xx != NULL); for (int i = 0; i &lt; n; i++) xx[i] = 1.0; double* b = new double[n]; assert(b != NULL); seq::symMatVec(n, a, xx, b); MPI_Barrier(MPI_COMM_WORLD); start = MPI_Wtime(); double x = para::solveSym(n, a, b); MPI_Barrier(MPI_COMM_WORLD); end = MPI_Wtime(); double* output = new double[n]; MPI_Gather((void*)&amp;x, 1, MPI_DOUBLE, (void*)output, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); if (myid == 0) { std::cout &lt;&lt; &quot;processors num = &quot; &lt;&lt; nproc &lt;&lt; &quot; execution time = &quot; &lt;&lt; (end-start)/1000.0 &lt;&lt; &quot; seconds&quot; &lt;&lt; std::endl; } MPI_Finalize(); return 0; } </code></pre> <p>While I execute this code (4 processors, matrix 100x100) using:</p> <pre><code>mpiexec -np 4 LDLT 100 </code></pre> <p>I get strange results. For example, with matrix of 100x100 using 1 processor, the execution time is 1,2e-9 seconds; using 2 processors, the execution time is 5,48e-9 seconds; using 4 processors, the execution time is 5,55e-9 seconds.</p> <p>Why do I get such results? What's wrong with this code? Help me to correct it. Thanks!</p> <p>EDIT: I made some changes according to y'all suggestions, it has some improvements in execution time (now it's not so little), but still the same problem: I changed the matrix size to 1000x1000, and with 1 processor the execution time = 0,0016 seconds; with 2 processors it takes 0,014 seconds. Here's a code of main() function:</p> <pre><code>int main(int argc, char** argv) { srand((unsigned)time(NULL)); MPI_Init(&amp;argc, &amp;argv); int nproc, myid; MPI_Comm_size(MPI_COMM_WORLD, &amp;nproc); MPI_Comm_rank(MPI_COMM_WORLD, &amp;myid); int n = atoi(argv[1]); double* a = new double[n * n]; assert(a != NULL); for (int i = 0; i &lt; n; i++) for (int j = 0; j &lt; i; j++) a[i * n + j] = rand() / (RAND_MAX + 1.0); for (int i = 0; i &lt; n; i++) { double s = 0.0; for (int j = 0; j &lt; i; j++) s += a[i * n + j]; for (int j = i + 1; j &lt; n; j++) s += a[j * n + i]; a[i * n + i] = s + 1.0; } double start, end; double* xx = new double[n]; assert(xx != NULL); for (int i = 0; i &lt; n; i++) xx[i] = 1.0; double* b = new double[n]; assert(b != NULL); start = MPI_Wtime(); if (nproc == 1) { seq::symMatVec(n, a, xx, b); end = MPI_Wtime(); std::cout &lt;&lt; &quot;processors num = &quot; &lt;&lt; nproc &lt;&lt; &quot; execution time = &quot; &lt;&lt; (end - start) &lt;&lt; &quot; seconds&quot; &lt;&lt; std::endl; MPI_Barrier(MPI_COMM_WORLD); MPI_Finalize(); } else { double x = para::solveSym(n, a, b); double* output = new double[n]; MPI_Gather((void*)&amp;x, 1, MPI_DOUBLE, (void*)output, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); if (myid == 0) { end = MPI_Wtime(); std::cout &lt;&lt; &quot;processors num = &quot; &lt;&lt; nproc &lt;&lt; &quot; execution time = &quot; &lt;&lt; (end - start) &lt;&lt; &quot; seconds&quot; &lt;&lt; std::endl; } MPI_Barrier(MPI_COMM_WORLD); MPI_Finalize(); } return 0; } </code></pre>
[ { "answer_id": 74303985, "author": "j23", "author_id": 10911932, "author_profile": "https://Stackoverflow.com/users/10911932", "pm_score": 1, "selected": false, "text": "MPI_Isend" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14432525/" ]
74,303,085
<p>When I run this c snippet, it outputs something really random every time, and then segfaults... Code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int parse(void) { int i = 0; int system(const char *command); char line[1024]; scanf(&quot;%[^\n]&quot;, line); system(line); do { line[i] = &quot;\0&quot;; i++; } while (i != 1024); parse(); } int main(void) { parse(); return 0; } </code></pre> <p>What I expected was a prompt, and when any shell command is entered (I used pwd for my testing), the output of the command prints and the prompt returns. And this is what actually happened:</p> <p>Output:</p> <pre><code>&gt; pwd /home/runner/c-test sh: 1: �: not found sh: 1: : not found sh: 1: ׀: not found signal: segmentation fault (core dumped) </code></pre>
[ { "answer_id": 74303545, "author": "Support Ukraine", "author_id": 4386427, "author_profile": "https://Stackoverflow.com/users/4386427", "pm_score": 0, "selected": false, "text": "scanf(\"%[^\\n]\", line);\n" }, { "answer_id": 74303659, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 2, "selected": true, "text": "#include <stdio.h>\n#include <stdlib.h>\n\n\nint parse(void) \n{\n static char line[1024];\n while(1)\n {\n printf(\">>>\");\n if(!fgets(line, 1024, stdin)) return 1;\n system(line);\n }\n}\n\nint main(void) {\n parse();\n}\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20407499/" ]
74,303,125
<p>may I know if there is more efficient way of constructing below variant?</p> <pre><code>#include &lt;variant&gt; #include &lt;string&gt; class Person{ public: Person(std::string name, int age, std::string school) :name_(name), age_(age){} private: std::string name_; int age_; }; class Dummy1{}; class Dummy2{}; using PersonVariant = std::variant&lt;Person, Dummy2, Dummy1&gt;; int main() { Person person(&quot;jack&quot;, 10, &quot;school&quot;); PersonVariant pv(person); // does this involve an uneccessary copy? } </code></pre> <p>The construct seems involve an unnecessary copy.</p>
[ { "answer_id": 74303545, "author": "Support Ukraine", "author_id": 4386427, "author_profile": "https://Stackoverflow.com/users/4386427", "pm_score": 0, "selected": false, "text": "scanf(\"%[^\\n]\", line);\n" }, { "answer_id": 74303659, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 2, "selected": true, "text": "#include <stdio.h>\n#include <stdlib.h>\n\n\nint parse(void) \n{\n static char line[1024];\n while(1)\n {\n printf(\">>>\");\n if(!fgets(line, 1024, stdin)) return 1;\n system(line);\n }\n}\n\nint main(void) {\n parse();\n}\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1569058/" ]
74,303,133
<p>Hi i'm new into vscode and when i run a program there is some text that i want to get rid of.</p> <p><a href="https://i.stack.imgur.com/GyJxM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GyJxM.png" alt="enter image description here" /></a></p> <p>i mainly want to remove the first two paragraphs, but also removing the path would be ideal</p> <p>i tried code runner but thats not the solution i'm looking for i also tried changing the color to black but i reckon there is a way to remove it</p>
[ { "answer_id": 74303253, "author": "Yogesh Thambidurai", "author_id": 18944758, "author_profile": "https://Stackoverflow.com/users/18944758", "pm_score": 3, "selected": true, "text": "// should go in the main JSON object with the other keys\n\"terminal.integrated.profiles.windows\": {\n // it might generate some more profiles automatically, but powershell is what matters\n \"PowerShell\": {\n \"source\": \"PowerShell\",\n \"icon\": \"terminal-powershell\",\n \"args\": [\"-NoLogo\"]\n }\n}\n" }, { "answer_id": 74303288, "author": "Alex Turner", "author_id": 15899193, "author_profile": "https://Stackoverflow.com/users/15899193", "pm_score": 0, "selected": false, "text": "cls" }, { "answer_id": 74303459, "author": "Rohith Nambiar", "author_id": 15747757, "author_profile": "https://Stackoverflow.com/users/15747757", "pm_score": 0, "selected": false, "text": "-nologo" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20407301/" ]
74,303,148
<p>I want to clean up this date column inside of a csv file using python pandas.</p> <p>Let's say my code is:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'name': ['alice','bob','charlie'], 'date_of_birth': ['10/25/2005 R','10/29/2002','01/01/2001 BD'] }) </code></pre> <p><strong>How can I clean up this mess for thousands of rows?</strong></p> <p>I thought of using:</p> <pre><code>df['date of birth'] = df['new date'].str[0,10] </code></pre> <p>but it does not work.</p>
[ { "answer_id": 74303253, "author": "Yogesh Thambidurai", "author_id": 18944758, "author_profile": "https://Stackoverflow.com/users/18944758", "pm_score": 3, "selected": true, "text": "// should go in the main JSON object with the other keys\n\"terminal.integrated.profiles.windows\": {\n // it might generate some more profiles automatically, but powershell is what matters\n \"PowerShell\": {\n \"source\": \"PowerShell\",\n \"icon\": \"terminal-powershell\",\n \"args\": [\"-NoLogo\"]\n }\n}\n" }, { "answer_id": 74303288, "author": "Alex Turner", "author_id": 15899193, "author_profile": "https://Stackoverflow.com/users/15899193", "pm_score": 0, "selected": false, "text": "cls" }, { "answer_id": 74303459, "author": "Rohith Nambiar", "author_id": 15747757, "author_profile": "https://Stackoverflow.com/users/15747757", "pm_score": 0, "selected": false, "text": "-nologo" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20407589/" ]
74,303,156
<p>I have this data in a spreadsheet</p> <pre><code>Country Sales Spain 1 1000 Spain 2 200 France 300 Nigeria 1 500 Nigeria 2 700 </code></pre> <p>I want the sum of this country's sales stored a seperate dataframe.</p> <p>I tried using the dplyr function but the result is not what i want</p> <p>Here is the output I want please</p> <pre><code>Country Sum_of_sales Spain 1200 France 300 Nigeria 1200 </code></pre> <p>Is there a way I can run this on R that will give me this above output stored in a separate dataframe please.</p>
[ { "answer_id": 74303250, "author": "Gregor Thomas", "author_id": 903061, "author_profile": "https://Stackoverflow.com/users/903061", "pm_score": 2, "selected": false, "text": "library(dplyr)\ndf %>%\n mutate(Country= gsub(pattern = \" *[0-9]+\", replacement = \"\", x = Country)) %>%\n group_by(Country) %>%\n summarize(Sum_of_Sales = sum(Sales))\n# # A tibble: 3 × 2\n# Country Sum_of_Sales\n# <chr> <int>\n# 1 France 300\n# 2 Nigeria 1200\n# 3 Spain 1200\n" }, { "answer_id": 74303411, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 1, "selected": true, "text": "tidyverse" }, { "answer_id": 74305174, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 0, "selected": false, "text": "str_remove" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20407565/" ]
74,303,182
<p>I have a database with Products and each product has an Id, Name, ManufacturerId, CategoryId and UserScore.</p> <p>I want to retrieve all Products by a given Category sorted by UserScore, but avoiding many products of same Manufacturer listed together.</p> <p>With the following query they all stuck together:</p> <pre><code>SELECT P.ProductId, P.Name, P.ManufacturerId, P.UserScore FROM Products P WHERE P.CategoryId = 1 ORDER BY P.UserScore </code></pre> <p>This is the result in T-SQL</p> <p><a href="https://i.stack.imgur.com/nfCcs.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nfCcs.jpg" alt="This is the result ordered by UserScore but in yellow are different products same manufacturer" /></a></p> <p>In T-SQL I came up with a solution like the following, where Products are grouped in no more than 2 elements by Manufacturer, and it suits perfectly my needs:</p> <pre><code>SELECT T.* FROM ( SELECT P.ProductId, P.Name, P.ManufacturerId, P.UserScore, ROW_NUMBER() OVER (PARTITION BY P.ManufacturerId ORDER BY P.UserScore DESC) RN FROM Products P WHERE P.CategoryId = 1 ) T ORDER BY T.UserScore / CEILING(RN/2.0) DESC </code></pre> <p><a href="https://i.stack.imgur.com/B6eFH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B6eFH.jpg" alt="This is the result expected in T-SQL" /></a></p> <p>How could I implement a ElasticSearch Query to mimic this behaviour?</p> <p>Any ideas?</p> <p>The index in elasticsearch would be like this, this is just an abstract example:</p> <pre><code>{&quot;ProductId&quot;: &quot;157072&quot;, &quot;Name&quot;: &quot;Product 157072&quot;, &quot;ManufacturerId&quot;: &quot;7790&quot;, &quot;UserScore&quot;: &quot;100000&quot;, &quot;CategoryId&quot;: &quot;1&quot;}, {&quot;ProductId&quot;: &quot;296881&quot;, &quot;Name&quot;: &quot;Product 296881&quot;, &quot;ManufacturerId&quot;: &quot;6921&quot;, &quot;UserScore&quot;: &quot;35400&quot;, &quot;CategoryId&quot;: &quot;1&quot;}, {&quot;ProductId&quot;: &quot;353924&quot;, &quot;Name&quot;: &quot;Product 353924&quot;, &quot;ManufacturerId&quot;: &quot;54616&quot;, &quot;UserScore&quot;: &quot;25000&quot;, &quot;CategoryId&quot;: &quot;1&quot;}, ... </code></pre>
[ { "answer_id": 74303250, "author": "Gregor Thomas", "author_id": 903061, "author_profile": "https://Stackoverflow.com/users/903061", "pm_score": 2, "selected": false, "text": "library(dplyr)\ndf %>%\n mutate(Country= gsub(pattern = \" *[0-9]+\", replacement = \"\", x = Country)) %>%\n group_by(Country) %>%\n summarize(Sum_of_Sales = sum(Sales))\n# # A tibble: 3 × 2\n# Country Sum_of_Sales\n# <chr> <int>\n# 1 France 300\n# 2 Nigeria 1200\n# 3 Spain 1200\n" }, { "answer_id": 74303411, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 1, "selected": true, "text": "tidyverse" }, { "answer_id": 74305174, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 0, "selected": false, "text": "str_remove" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2385368/" ]
74,303,205
<p>Suppose I want to make a new variable based on conditions within multiple other variables, and the condition is the same across each of these variables. I know I could use case_when(), but I'm curious to see if this can be simplified if my conditional phrase is the same for each conditional variable. I also want to know if this can be easily replicated to create multiple variables.</p> <p>Example: A teacher has 3 students who have received grades for 3 tests and 3 quizzes. He wants to create a variable that says whether or not a student ever had a score of &lt;70 on any test or quiz. So he will create two new variables as so:</p> <pre><code> ID &lt;- c(&quot;Dave&quot;, &quot;Joe&quot;, &quot;Steve&quot;) exam1 &lt;- c(80, 100, 90) exam2 &lt;- c(30, 90, 88) exam3 &lt;- c(90, 65, 95) quiz1 &lt;- c(90, 90, 20) quiz2 &lt;- c(33, 100, 100) quiz3 &lt;- c(90, 90, 50) data &lt;- tibble(ID, exam1, exam2, exam3, quiz1, quiz2, quiz3) data &lt;- data %&gt;% mutate( fail_exam = case_when( exam1 &lt; 70 ~ 1, exam2 &lt; 70 ~ 1, exam3 &lt; 70 ~ 1, T ~ 0 ), fail_quiz = case_when( quiz1 &lt; 70 ~ 1, quiz2 &lt; 70 ~ 1, quiz3 &lt; 70 ~ 1, T ~ 0 ) ) </code></pre> <p>He ends up with the following output with his two new variables:</p> <pre><code># A tibble: 3 × 9 ID exam1 exam2 exam3 quiz1 quiz2 quiz3 fail_exam fail_quiz &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; 1 Dave 80 30 90 90 33 90 1 1 2 Joe 100 90 65 90 100 90 1 0 3 Steve 90 88 95 20 100 50 0 1 </code></pre> <p>Now for the sake of this example, suppose you have 100 examination categories (e.g., mid-term, final exam, homework, etc.) for which students received grades, and you want create a new variable for each one of them indicating whether or not they ever had a failing score on it. One could iteratively go through each examination category as I did above with exam and quiz using case_when(), but I'd like to know if there is a simpler way to apply a single condition (i.e., if numeric score &lt;70) to a list of examination categories (example: c(&quot;exam&quot;, &quot;quiz&quot;, &quot;homework&quot;, &quot;midterm&quot;) that follow the numbering convention I have above in order to create unique output variables such as &quot;fail_exam&quot; and &quot;fail_quiz&quot; for each one of them.</p> <p>This isn't mission critical, but looking to simplify things a bit.</p> <p>Thx, C</p>
[ { "answer_id": 74303293, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 3, "selected": false, "text": "dplyr::if_any()" }, { "answer_id": 74303956, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 2, "selected": true, "text": "map_dfc" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11536205/" ]
74,303,232
<p>I wrote simple program on C++</p> <pre class="lang-cpp prettyprint-override"><code>#include&lt;iostream&gt; using namespace std; int main() { int number19 , number20 ; const int number = 10 ; number20 = number + 10 ; number19 = number20--; cout &lt;&lt; number &lt;&lt; endl; cout &lt;&lt; number20 &lt;&lt; endl; cout &lt;&lt; number19 &lt;&lt; endl; return 0; } </code></pre> <p>I think that output should be: 10 20 19 But output is 10 19 20</p> <p>Why I get such output ?</p>
[ { "answer_id": 74303410, "author": "Some programmer dude", "author_id": 440558, "author_profile": "https://Stackoverflow.com/users/440558", "pm_score": 2, "selected": false, "text": "number19 = number20--;\n" }, { "answer_id": 74303451, "author": "jwezorek", "author_id": 1413244, "author_profile": "https://Stackoverflow.com/users/1413244", "pm_score": 2, "selected": false, "text": "number19 = number20--;\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11707382/" ]
74,303,234
<p>First off I know using regular expression is not the best email validation but this is a preliminary step, a better validation comes later.</p> <p>I want to create a function that validates whether or not an email address is valid but i am not sure how to reference only one column in a data frame.</p> <pre><code>import pandas as pd d=[['Automotive','testgmail.com','bob','smith']] df=pd.DataFrame(d,columns=['industry','email','first',last]) filename='temp' </code></pre> <p><strong>I want to keep the code in a def function like the one below</strong></p> <pre><code>def Prospect(colname,errors): wrong=[] if #reference to column.str.match(r&quot;^.+@.+\..{2,}$&quot;): return else: error='this is an invalid email' wrong.append(error) return wrong print(Prospect(errors,colname)) </code></pre> <p>How do I create a function to only reference a specific column in a data frame and only run that column name through the function and create a print statement saying that the email is invalid?</p> <p>P.S: speed of the operation is not a huge concern since the datasets are not massive.</p> <p>desired output:</p> <pre><code>This is an invalid email </code></pre>
[ { "answer_id": 74303368, "author": "Noah", "author_id": 14028308, "author_profile": "https://Stackoverflow.com/users/14028308", "pm_score": 0, "selected": false, "text": "import pandas as pd\nimport re\n\nd=[['Automotive','testgmail.com','bob','smith'],\n ['Automotive','test@gmail.com','bob','smith']]\ndf=pd.DataFrame(d,columns=['industry','email','first','last'])\n\nemail_regex = regex = '^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$'\n\ndf[\"email\"].apply(lambda email: print(\"This is a valid email: \" + email if re.search(email_regex,email) else \"This is an invalid email: \" + email))\n" }, { "answer_id": 74303644, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "def Prospect(colname, errors, df=df):\n \n m = df[colname].str.match(r\"^.+@.+\\..{2,}$\")\n \n if m.all():\n pass\n else:\n error='this is an invalid email'\n errors.append(error)\n \nerrors = []\nProspect('email', errors, df=df)\n\nprint(errors)\n" }, { "answer_id": 74303772, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 0, "selected": false, "text": "import pandas as pd\nimport re\n\nd=[['Automotive','testgmail.com','bob','smith'],\n ['Automotive','test@gmail.com','bob','smith']]\ndf=pd.DataFrame(d,columns=['industry','email','first','last'])\n\ndef Prospect(colname):\n email_regex = r\"^.+@.+\\..{2,}$\"\n wrong=[]\n for i in range(len(df)):\n this_email = df[colname][i]\n if re.search(email_regex,this_email):\n continue\n else:\n error=f'{this_email} is an invalid email'\n wrong.append(error)\n return wrong\n\nprint(Prospect('email'))\n# ['testgmail.com is an invalid email']\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20398270/" ]
74,303,238
<p>I want to create a wrapper function for an existing function in TypeScript.</p> <p>The wrapper function could start some other process and clean it up after finishing the main (&quot;callback&quot;) function passed to the wrapper.</p> <p>This can be done using approaches like <a href="https://stackoverflow.com/questions/38598280/is-it-possible-to-wrap-a-function-and-retain-its-types">shown here</a>. However, these solutions do not allow me to specify additional options that can be passed to the wrapper itself.</p> <p>How would I go about doing that?</p> <p>My starting point was:</p> <pre class="lang-js prettyprint-override"><code>export const wrap = async &lt;T&gt;( callback: () =&gt; T | Promise&lt;T&gt;, options?: { foo?: string | undefined }, ): Promise&lt;T&gt; =&gt; { let ret; // begin if (options.foo) { // do something } try { ret = await callback(); } catch (e) { throw e; } finally { // cleanup } return ret; }; </code></pre> <p>This would not let me add arguments to <code>callback()</code>. I can use <code>...args</code>, but how would I specify both <code>...args</code> <em>and</em> <code>options</code>?</p>
[ { "answer_id": 74303239, "author": "slhck", "author_id": 435093, "author_profile": "https://Stackoverflow.com/users/435093", "pm_score": 1, "selected": false, "text": "F" }, { "answer_id": 74303386, "author": "Guerric P", "author_id": 3738171, "author_profile": "https://Stackoverflow.com/users/3738171", "pm_score": 3, "selected": true, "text": "function wrap<T extends (...args: any[]) => any>(callback: T, options?: { foo?: string | undefined }): (...args: Parameters<T>) => ReturnType<T> extends Promise<infer U> ? Promise<U> : Promise<ReturnType<T>>\nfunction wrap(callback: (...args: any[]) => any, options?: { foo?: string | undefined }): (...args: any[]) => Promise<any> {\n\n return async function (...args: any[]) {\n let ret;\n\n // begin\n if (options && options.foo) {\n // do something\n }\n\n try {\n ret = await callback(...args);\n } catch (e) {\n throw e;\n } finally {\n // cleanup\n }\n\n return ret;\n }\n};\n\nasync function asyncExtractFirstParameter(str: string, num: number, bool: boolean) {\n return str;\n}\n\nfunction extractFirstParameter(str: string, num: number, bool: boolean) {\n return str;\n}\n\nconst wrappedAsyncExtractFirstParameter = wrap(asyncExtractFirstParameter);\nconst wrappedExtractFirstParameter = wrap(extractFirstParameter);\n\nwrappedAsyncExtractFirstParameter('test', 23, true).then(console.log);\nwrappedExtractFirstParameter('test', 23, true).then(console.log);\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/435093/" ]
74,303,295
<p>I'm trying to understand how to properly delete a many to one relationship.</p> <p>Let's suppose I have the following entities:</p> <pre><code>@Entity @Table(name = &quot;user&quot;) public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; private String lastname; } </code></pre> <pre><code>@Entity @Table(name = &quot;badge&quot;) public class Badge { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String code; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = &quot;badge_id&quot;) private User user; } </code></pre> <p>Now these two entites have different controllers and services. I can delete a badge in the BadgeService and delete a user in its service.</p> <pre><code>@Service public class BadgeService { @Autowired BadgeRepository badgeRepository; public void delete(int id) { badgeRepository.deleteById(id); } } </code></pre> <pre><code>@Service public class UserService { @Autowired UserRepository userRepository; public void delete(int id) { userRepository.deleteById(id); } } </code></pre> <p>The problem is that if I delete a badge everthing works but If I delete a User a got an error due to the FK.</p> <p>To solve the problem I came up with 2 ways but I was wondering if there is a better way to handle this kind of problem:</p> <h2>First Way</h2> <p>I simply create a method in the badge repository to delete all badges related to the specific user.</p> <pre><code>public interface BadgeRepository extends CrudRepository&lt;Badge, Integer&gt; { @Modifying @Query(value = &quot;DELETE Badge b WHERE b.user.id = :userId&quot;) public void deleteByUserId(@Param(&quot;userId&quot;) int userId); } </code></pre> <p>Then I create a method in the badge service.</p> <pre><code>@Service public class BadgeService { @Autowired BadgeRepository badgeRepository; public void delete(int id) { badgeRepository.deleteById(id); } @Transactional public void deleteByUserId(int userId) { badgeRepository.deleteByUserId(userId); } } </code></pre> <p>And last I simply autowire badge service in user service and call the method in the user delete.</p> <pre><code>@Service public class UserService { @Autowired UserRepository userRepository; @Autowired BadgeService badgeService; @Transactional public void delete(int id) { badgeService.deleteByUserId(id); userRepository.deleteById(id); } } </code></pre> <h3>Cons:</h3> <p>If I have multiple relationships with the User entity, I will end up autowiring a lot of services in the user service and that is bad.</p> <h2>Second Way</h2> <p>Instead of having an unidirectional relationship I create a bidirectional relationship between User and Badge.</p> <pre><code>@Entity @Table(name = &quot;user&quot;) public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; private String lastname; @OneToMany(mappedBy = &quot;user&quot;, cascade = CascadeType.REMOVE, orphanRemoval = true) private List&lt;Badge&gt; badges = new ArrayList&lt;Badge&gt;(); } </code></pre> <p>And when I delete a user, the cascade or simplying removing the badge from the colletion will delete all the related badges.</p> <h3>Cons:</h3> <ol> <li><p>Extra Query</p> </li> <li><p>If the collection is too big the app performances will decrease</p> </li> </ol> <p>That being said, what would you suggest? first or second approach? Maybe there is a better approach to handle this problem?</p> <p>Thank you all.</p>
[ { "answer_id": 74303239, "author": "slhck", "author_id": 435093, "author_profile": "https://Stackoverflow.com/users/435093", "pm_score": 1, "selected": false, "text": "F" }, { "answer_id": 74303386, "author": "Guerric P", "author_id": 3738171, "author_profile": "https://Stackoverflow.com/users/3738171", "pm_score": 3, "selected": true, "text": "function wrap<T extends (...args: any[]) => any>(callback: T, options?: { foo?: string | undefined }): (...args: Parameters<T>) => ReturnType<T> extends Promise<infer U> ? Promise<U> : Promise<ReturnType<T>>\nfunction wrap(callback: (...args: any[]) => any, options?: { foo?: string | undefined }): (...args: any[]) => Promise<any> {\n\n return async function (...args: any[]) {\n let ret;\n\n // begin\n if (options && options.foo) {\n // do something\n }\n\n try {\n ret = await callback(...args);\n } catch (e) {\n throw e;\n } finally {\n // cleanup\n }\n\n return ret;\n }\n};\n\nasync function asyncExtractFirstParameter(str: string, num: number, bool: boolean) {\n return str;\n}\n\nfunction extractFirstParameter(str: string, num: number, bool: boolean) {\n return str;\n}\n\nconst wrappedAsyncExtractFirstParameter = wrap(asyncExtractFirstParameter);\nconst wrappedExtractFirstParameter = wrap(extractFirstParameter);\n\nwrappedAsyncExtractFirstParameter('test', 23, true).then(console.log);\nwrappedExtractFirstParameter('test', 23, true).then(console.log);\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11191394/" ]
74,303,304
<p>Suppose i have the following model:</p> <pre><code>from django.db import models from django.contrib.gis.db import models as gis_models class Place(models.Model): location = gis_models.PointField(geography=True, srid=4326) </code></pre> <p>Later i am performing the search on those Places; my query is &quot;fetch all places no further N meters from me&quot;:</p> <pre><code>from django.contrib.gis.db.models.functions import Distance from django.contrib.gis.geos import Point location = Point(1.0, 2.0) distance = 20.0 queryset = queryset.annotate(distance=Distance(&quot;location&quot;, location)).filter( distance__lte=distance ) </code></pre> <p>Is there any way using PostGIS to optimize those queries? For example, using indexes or something related.</p>
[ { "answer_id": 74303766, "author": "Laurenz Albe", "author_id": 6464308, "author_profile": "https://Stackoverflow.com/users/6464308", "pm_score": 1, "selected": false, "text": "geometry" }, { "answer_id": 74303801, "author": "fresser", "author_id": 17466122, "author_profile": "https://Stackoverflow.com/users/17466122", "pm_score": 1, "selected": false, "text": "CREATE INDEX unique_index_name ON table_name USING gist (geometry_column);\n" }, { "answer_id": 74304659, "author": "marqueewinq", "author_id": 2409446, "author_profile": "https://Stackoverflow.com/users/2409446", "pm_score": 2, "selected": true, "text": "from django.contrib.postgres.indexes import GistIndex\n\nclass Place:\n ...\n\n class Meta:\n indexes = [\n GistIndex(fields=[\"location\"]),\n ]\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2409446/" ]
74,303,325
<p>There are Error Messagge, Error Code and some HomePageCode. What is matter??</p> <p>I did that error message said to do. But I CAN'T SOLVE PLOBLEM.</p> <p>[Error Message]</p> <pre><code>lib/create_page.dart:194:63: Error: Too few positional arguments: 1 required, 0 given. context, MaterialPageRoute(builder:(context) =&gt; HomePage()), ^ lib/home_page.dart:10:3: Context: Found this candidate, but the arguments don't match. HomePage(this.user); ^^^^^^^^ </code></pre> <p>[Error Code]</p> <pre><code>Navigator.push( context, MaterialPageRoute(builder:(context) =&gt; HomePage()), ); </code></pre> <p>[HomePage]</p> <pre><code>class HomePage extends StatelessWidget { final FirebaseUser user; HomePage(this.user); </code></pre>
[ { "answer_id": 74303381, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 1, "selected": false, "text": "HomePage" }, { "answer_id": 74303384, "author": "Najedo", "author_id": 19880301, "author_profile": "https://Stackoverflow.com/users/19880301", "pm_score": 0, "selected": false, "text": "HomePage" }, { "answer_id": 74303399, "author": "IonicFireBaseApp", "author_id": 19303836, "author_profile": "https://Stackoverflow.com/users/19303836", "pm_score": 0, "selected": false, "text": "final FirebaseUser user;\n" }, { "answer_id": 74305258, "author": "ahmed", "author_id": 20033412, "author_profile": "https://Stackoverflow.com/users/20033412", "pm_score": 0, "selected": false, "text": "HomePage" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19711930/" ]
74,303,332
<p>I've a flat dict with entities. Each entity can have a parent. I'd like to recursively build each entity, considering the parent values.</p> <p>Logic:</p> <ol> <li>Each entity <strong>inherits</strong> defaults from its parent (e.g. <code>is_mammal</code>)</li> <li>Each entity can <strong>overwrite</strong> the defaults of its parent (e.g. <code>age</code>)</li> <li>Each entity can <strong>add</strong> new attributes (e.g. <code>hobby</code>)</li> </ol> <p>I'm struggling to get it done. Help is appreciated, thanks!</p> <pre><code>entities = { 'human': { 'is_mammal': True, 'age': None, }, 'man': { 'parent': 'human', 'gender': 'male', }, 'john': { 'parent': 'man', 'age': 20, 'hobby': 'football', } }; def get_character(key): # ... recursive magic with entities ... return entity john = get_character('john') print(john) </code></pre> <p>Expected output:</p> <pre><code>{ 'is_mammal': True, # inherited from human 'gender': 'male' # inherited from man 'parent': 'man', 'age': 20, # overwritten 'hobby': 'football', # added } </code></pre>
[ { "answer_id": 74303454, "author": "matszwecja", "author_id": 9296093, "author_profile": "https://Stackoverflow.com/users/9296093", "pm_score": 3, "selected": true, "text": "def get_character(entities, key):\n try:\n entity = get_character(entities, entities[key]['parent'])\n except KeyError:\n entity = {}\n entity.update(entities[key])\n return entity\n" }, { "answer_id": 74303788, "author": "Nathan Furnal", "author_id": 9479128, "author_profile": "https://Stackoverflow.com/users/9479128", "pm_score": 1, "selected": false, "text": "{}" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1792858/" ]
74,303,378
<p>I have a table History with the columns date, person and status and I need to know what is the total amount of time spent since it started until it reaches the finished status ( Finished status can occur multiples times). I need to get the datediff from the first time it's created until the first time it's with status finished, afterwards I need to get the next date were it's not finished and get again the datediff using the date it was again finished and so on. Another condition is to do this calculation only if Person who changed the status is not null. After that I need to sum all times and get the total.</p> <p><a href="https://i.stack.imgur.com/ScFmu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ScFmu.png" alt="enter image description here" /></a></p> <p>I tried with Lead and Lag function but was not getting the results that I need.</p>
[ { "answer_id": 74305147, "author": "DannySlor", "author_id": 19174570, "author_profile": "https://Stackoverflow.com/users/19174570", "pm_score": 1, "selected": false, "text": "select min(date) as start\n ,max(date) as finish\n ,datediff(millisecond, min(date), max(date)) as diff_in_millisecond\n ,sum(datediff(millisecond, min(date), max(date))) over() as total_diff_in_millisecond\nfrom\n(\nselect *\n ,count(case when Status = 'Finished' then 1 end) over(order by date desc, status desc) as grp\n ,case when person is null then 0 else 1 end as flg\nfrom t\n) t\ngroup by grp\nhaving min(flg) = 1\norder by start\n" }, { "answer_id": 74305656, "author": "Patrick Hurst", "author_id": 18522514, "author_profile": "https://Stackoverflow.com/users/18522514", "pm_score": 3, "selected": true, "text": "DECLARE @statusTable TABLE (Date DATETIME, Person INT, Status NVARCHAR(10), KeyID NVARCHAR(7))\nINSERT INTO @statusTable (Date, Person, Status, KeyID) VALUES\n('2022-10-07 07:01:17.463', 1, 'Start', 'AAA-111'),\n('2022-10-07 07:01:17.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-11 14:01:44.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-14 10:04:17.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-14 10:04:17.463', 1, 'Finished','AAA-111'),\n('2022-10-14 10:04:17.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-17 17:01:17.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-21 11:03:17.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-21 11:03:17.463', 1, 'Finished','AAA-111'),\n('2022-10-21 11:03:17.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-21 11:04:17.463', NULL, 'Waiting', 'AAA-111'),\n('2022-10-21 11:05:17.463', 1, 'Finished','AAA-111')\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6727198/" ]
74,303,394
<p>I'm looping through two lists &quot;rows&quot; and &quot;columns&quot; to create a dictionary &quot;fields&quot;, which should look like that:</p> <pre><code>fields = { &quot;A0&quot;: &quot; &quot;, &quot;A1&quot;: &quot; &quot;, &quot;A2&quot;: &quot; &quot;, ... &quot;A7&quot;: &quot; &quot;, &quot;B0&quot;: &quot; &quot;, &quot;B1&quot;: &quot; &quot;, ... ... &quot;H6&quot;: &quot; &quot;, &quot;H7&quot;: &quot; &quot; } </code></pre> <p>After each of the items is created, I want to check whether the current item's key matches a certain variable, e.g. apple=&quot;A1&quot;. If that's the case, the value of the key &quot;A1&quot; shall be changed to &quot;O&quot;. I tried the following, note that &quot;current_field_key&quot; is just a placeholder for the right expression I'm not able to find:</p> <pre><code>apple = &quot;A1&quot; rows = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;H&quot;] columns = [&quot;0&quot;, &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;] fields = {} for r in rows: for c in columns: fields[r+c] = &quot; &quot; if current_field_key == apple: fields[&quot;A1&quot;] = &quot;O&quot; </code></pre> <p>I already thought about accessing the item's key name via creating a list of all key names and check for the index, but I don't know how to find the right index without making it too complicated:</p> <pre><code>if list(fields.keys())[index] == apple: fields[&quot;A1&quot;] = &quot;O&quot; </code></pre> <p>Thanks in advance!</p>
[ { "answer_id": 74305147, "author": "DannySlor", "author_id": 19174570, "author_profile": "https://Stackoverflow.com/users/19174570", "pm_score": 1, "selected": false, "text": "select min(date) as start\n ,max(date) as finish\n ,datediff(millisecond, min(date), max(date)) as diff_in_millisecond\n ,sum(datediff(millisecond, min(date), max(date))) over() as total_diff_in_millisecond\nfrom\n(\nselect *\n ,count(case when Status = 'Finished' then 1 end) over(order by date desc, status desc) as grp\n ,case when person is null then 0 else 1 end as flg\nfrom t\n) t\ngroup by grp\nhaving min(flg) = 1\norder by start\n" }, { "answer_id": 74305656, "author": "Patrick Hurst", "author_id": 18522514, "author_profile": "https://Stackoverflow.com/users/18522514", "pm_score": 3, "selected": true, "text": "DECLARE @statusTable TABLE (Date DATETIME, Person INT, Status NVARCHAR(10), KeyID NVARCHAR(7))\nINSERT INTO @statusTable (Date, Person, Status, KeyID) VALUES\n('2022-10-07 07:01:17.463', 1, 'Start', 'AAA-111'),\n('2022-10-07 07:01:17.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-11 14:01:44.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-14 10:04:17.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-14 10:04:17.463', 1, 'Finished','AAA-111'),\n('2022-10-14 10:04:17.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-17 17:01:17.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-21 11:03:17.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-21 11:03:17.463', 1, 'Finished','AAA-111'),\n('2022-10-21 11:03:17.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-21 11:04:17.463', NULL, 'Waiting', 'AAA-111'),\n('2022-10-21 11:05:17.463', 1, 'Finished','AAA-111')\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11907641/" ]
74,303,396
<p>I am using laravel framework to develop api’s ,it’s an existing application .there is a requirement if more than 5users registered from 6th user onwards i have to restrict them to use application until they approved by manager or they paid for registration fee then only the user will allow to use the application.</p> <p>Can anyone give me the idea how to acheive this scenario or suggest me any package in laravel</p>
[ { "answer_id": 74305147, "author": "DannySlor", "author_id": 19174570, "author_profile": "https://Stackoverflow.com/users/19174570", "pm_score": 1, "selected": false, "text": "select min(date) as start\n ,max(date) as finish\n ,datediff(millisecond, min(date), max(date)) as diff_in_millisecond\n ,sum(datediff(millisecond, min(date), max(date))) over() as total_diff_in_millisecond\nfrom\n(\nselect *\n ,count(case when Status = 'Finished' then 1 end) over(order by date desc, status desc) as grp\n ,case when person is null then 0 else 1 end as flg\nfrom t\n) t\ngroup by grp\nhaving min(flg) = 1\norder by start\n" }, { "answer_id": 74305656, "author": "Patrick Hurst", "author_id": 18522514, "author_profile": "https://Stackoverflow.com/users/18522514", "pm_score": 3, "selected": true, "text": "DECLARE @statusTable TABLE (Date DATETIME, Person INT, Status NVARCHAR(10), KeyID NVARCHAR(7))\nINSERT INTO @statusTable (Date, Person, Status, KeyID) VALUES\n('2022-10-07 07:01:17.463', 1, 'Start', 'AAA-111'),\n('2022-10-07 07:01:17.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-11 14:01:44.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-14 10:04:17.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-14 10:04:17.463', 1, 'Finished','AAA-111'),\n('2022-10-14 10:04:17.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-17 17:01:17.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-21 11:03:17.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-21 11:03:17.463', 1, 'Finished','AAA-111'),\n('2022-10-21 11:03:17.463', 1, 'Waiting', 'AAA-111'),\n('2022-10-21 11:04:17.463', NULL, 'Waiting', 'AAA-111'),\n('2022-10-21 11:05:17.463', 1, 'Finished','AAA-111')\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20336151/" ]
74,303,431
<pre><code>const data = [{ &quot;hello&quot;:'thameem', &quot;age&quot;:24 }, { &quot;hello&quot;:'thameem', &quot;age&quot;:25 }]; console.log(data); </code></pre> <p>I need all age values</p>
[ { "answer_id": 74303464, "author": "sidhant manchanda", "author_id": 9590893, "author_profile": "https://Stackoverflow.com/users/9590893", "pm_score": 3, "selected": true, "text": "\nlet data = [{ \"hello\":'thameem', \"age\":24 }, { \"hello\":'thameem', \"age\":25 }];\n\n// will give you an array to ages\ndata = data?.map(item => item.age)\n\n" }, { "answer_id": 74303477, "author": "MrBens", "author_id": 11666446, "author_profile": "https://Stackoverflow.com/users/11666446", "pm_score": 0, "selected": false, "text": "map" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19279366/" ]
74,303,439
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>GET_DRUG</th> <th>HOSP</th> <th>DATE</th> <th>QTY</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>H111</td> <td>H111</td> <td>2021/12/31</td> <td>3</td> </tr> <tr> <td>A</td> <td>H112</td> <td>H112</td> <td>2022/1/10</td> <td>4</td> </tr> <tr> <td>A</td> <td>H110</td> <td>H110</td> <td>2022/1/13</td> <td>5</td> </tr> <tr> <td>A</td> <td>D110</td> <td>H110</td> <td>2022/1/14</td> <td>6</td> </tr> <tr> <td>A</td> <td>D111</td> <td>H110</td> <td>2022/1/16</td> <td>3</td> </tr> <tr> <td>A</td> <td>H112</td> <td>H112</td> <td>2022/1/23</td> <td>4</td> </tr> <tr> <td>A</td> <td>D113</td> <td>H110</td> <td>2022/1/30</td> <td>5</td> </tr> <tr> <td>A</td> <td>D114</td> <td>H110</td> <td>2022/2/13</td> <td>5</td> </tr> </tbody> </table> </div> <p><a href="https://i.stack.imgur.com/xKqwP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xKqwP.png" alt="Data is order by Date." /></a></p> <p>[![ Step(1).Trying to do calculation like this, the initial character of variable &quot;GET_DRUG&quot; is &quot;D&quot; then calculating days with above each row but only keeping DATE_DIFFERENCE&lt;=15 days records.</p> <p>Step(2).Count distinct variable &quot;HOSP&quot; value and sum variable &quot;QTY&quot; OF Step(1) result.</p> <p>Step(3).Count frequency of Step(2) result if HOSP NUM&gt;=2 AND QTY_SUM&gt;=10. ](<a href="https://i.stack.imgur.com/029Xl.png" rel="nofollow noreferrer">https://i.stack.imgur.com/029Xl.png</a>)](<a href="https://i.stack.imgur.com/029Xl.png" rel="nofollow noreferrer">https://i.stack.imgur.com/029Xl.png</a>)</p> <p>Final answer is &quot;2&quot; including &quot;2021/12/31~2022/1/13&quot; and &quot;2022/1/10~2022/1/14&quot; two combinations. How to use SAS to calculate like this? Many thanks.</p> <p><a href="https://i.stack.imgur.com/Fndfa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Fndfa.png" alt="Sorry that just learn SAS. So, I only know how to use Excel do the calculation with small data sets. I need to do the calculation with a large data set ,but Excel can't perform it." /></a></p>
[ { "answer_id": 74303464, "author": "sidhant manchanda", "author_id": 9590893, "author_profile": "https://Stackoverflow.com/users/9590893", "pm_score": 3, "selected": true, "text": "\nlet data = [{ \"hello\":'thameem', \"age\":24 }, { \"hello\":'thameem', \"age\":25 }];\n\n// will give you an array to ages\ndata = data?.map(item => item.age)\n\n" }, { "answer_id": 74303477, "author": "MrBens", "author_id": 11666446, "author_profile": "https://Stackoverflow.com/users/11666446", "pm_score": 0, "selected": false, "text": "map" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20407645/" ]
74,303,448
<p>We'd like to make use of the <code>@MainActor</code> Annotation for our ViewModels in an existing SwiftUI project, so we can get rid of <code>DispatchQueue.main.async</code> and <code>.receive(on: RunLoop.main)</code>.</p> <pre><code>@MainActor class MyViewModel: ObservableObject { private var counter: Int init(counter: Int) { self.counter = counter } } </code></pre> <p>This works fine when initializing the annotated class from a SwiftUI View. However, when using a SwiftUI Previews or XCTest we also need to initialize the class from outside of the <code>@MainActor</code> context:</p> <pre><code>class MyViewModelTests: XCTestCase { private var myViewModel: MyViewModel! override func setUp() { myViewModel = MyViewModel(counter: 0) } </code></pre> <p>Which obviously doesn't compile:</p> <blockquote> <p>Main actor-isolated property 'init(counter:Int)' can not be mutated from a non-isolated context</p> </blockquote> <p>Now, obviously we could also annotate <code>MyViewModelTests</code> with <code>@MainActor</code> as suggested <a href="https://stackoverflow.com/questions/68139689/how-do-i-construct-a-swiftui-class-annotated-mainactor-in-preview">here</a>.</p> <p>But we don't want all our UnitTests to run on the main thread. So what is the recommended practice in this situation?</p> <p>Annotating the <code>init</code> function with <code>nonisolated</code> as also suggested in the conversation above only works, if we don't want to set the value of variables inside the initializer.</p>
[ { "answer_id": 74303464, "author": "sidhant manchanda", "author_id": 9590893, "author_profile": "https://Stackoverflow.com/users/9590893", "pm_score": 3, "selected": true, "text": "\nlet data = [{ \"hello\":'thameem', \"age\":24 }, { \"hello\":'thameem', \"age\":25 }];\n\n// will give you an array to ages\ndata = data?.map(item => item.age)\n\n" }, { "answer_id": 74303477, "author": "MrBens", "author_id": 11666446, "author_profile": "https://Stackoverflow.com/users/11666446", "pm_score": 0, "selected": false, "text": "map" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20407691/" ]
74,303,456
<p>I receive input that is in a float format. I've broken it up into individual int numbers and am trying to encode them as the same ascii characters. Ie: int 1 to ascii character 1.</p> <p>I have tried different variations of this:</p> <pre><code>x = 1 y = chr(x) print (y) </code></pre> <p>which results in ascii character SOH instead of ascii character 1.</p>
[ { "answer_id": 74303759, "author": "Bryan Amaguaña", "author_id": 18532370, "author_profile": "https://Stackoverflow.com/users/18532370", "pm_score": 2, "selected": false, "text": "x=1\nprint(chr(ord(str(x))))\n" }, { "answer_id": 74305216, "author": "Sean Mckay", "author_id": 19331978, "author_profile": "https://Stackoverflow.com/users/19331978", "pm_score": 0, "selected": false, "text": "y = f'0x{ord(str(1)):x}'\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19331978/" ]
74,303,547
<p>I'm trying to read a old file of snow data from <a href="https://nsidc.org/data/nsidc-0271/versions/1" rel="nofollow noreferrer">here</a>, but I'm having a ton of trouble just opening a single file and getting data out. In the user guide, it says &quot;Each monthly binary data file with the file extension &quot;.NSIDC8&quot; contains a flat, binary array of 16-bit signed, little-endian (LSB) integers, 721 columns by 721 rows (row-major order, i.e. the top row of the array comprises the first 721 values in the file, etc.).&quot; The data is 20 to 50 years old so there's not much coding documentation</p> <p>If I just open the file and run readlines, with this code:</p> <pre><code>with open(os.path.join(folder,file), 'rb') as f: # contents = f.read() lines = f.readlines() </code></pre> <p>I get something looking like this: <code>\x00P\x00@\x00\x19\x00\x13\x00C\x00F\x00\x11\x00\r\x00:\x00.\x00\x02</code></p> <p>If I use np.load(), the results are number like: <code>-6.85682214e+304</code></p> <p>I imagine I need to use the struct package and the unstruct function, but I have no idea what format to use, and my attempts are not getting reasonable answers. For instance, I've tried just reading the first four bytes and using '&lt;i' as the format, as shown in the code below</p> <pre><code>with open(os.path.join(folder,file), 'rb') as f: print(struct.unpack('&lt;i', f.read(4))) </code></pre> <p>And the print statement showed (-13041864,), which doesn't make sense. Any insights would be greatly appreciated</p>
[ { "answer_id": 74303702, "author": "oskros", "author_id": 9490769, "author_profile": "https://Stackoverflow.com/users/9490769", "pm_score": 0, "selected": false, "text": ".encode()" }, { "answer_id": 74303842, "author": "davidlowryduda", "author_id": 1141805, "author_profile": "https://Stackoverflow.com/users/1141805", "pm_score": 2, "selected": true, "text": "unpack" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9367533/" ]
74,303,555
<p>I want to add a border to header when accordion is expanded, when its close all is good as its working now.</p> <p>The border is missing for this as shown (when expanded) <a href="https://i.stack.imgur.com/rEuo1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rEuo1.png" alt="enter image description here" /></a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous"&gt; &lt;script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;style&gt; .accordion{ margin:30px; } .accordion-button.collapsed { border-bottom: #ccc 1px solid } .accordion-body { border-left: #673ab744 1px solid; border-bottom: #673ab744 1px solid; border-right: #673ab744 1px solid } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="accordion accordion-flush" id="accordionFlushExample"&gt; &lt;div class="accordion-item"&gt; &lt;h2 class="accordion-header" id="flush-headingOne"&gt; &lt;button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseOne" aria-expanded="false" aria-controls="flush-collapseOne"&gt; Accordion Item #1 &lt;/button&gt; &lt;/h2&gt; &lt;div id="flush-collapseOne" class="accordion-collapse collapse" aria-labelledby="flush-headingOne" data-bs-parent="#accordionFlushExample"&gt; &lt;div class="accordion-body"&gt;Placeholder content for this accordion, which is intended to demonstrate the &lt;code&gt;.accordion-flush&lt;/code&gt; class. This is the first item's accordion body.&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="accordion-item"&gt; &lt;h2 class="accordion-header" id="flush-headingTwo"&gt; &lt;button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseTwo" aria-expanded="false" aria-controls="flush-collapseTwo"&gt; Accordion Item #2 &lt;/button&gt; &lt;/h2&gt; &lt;div id="flush-collapseTwo" class="accordion-collapse collapse" aria-labelledby="flush-headingTwo" data-bs-parent="#accordionFlushExample"&gt; &lt;div class="accordion-body"&gt;Placeholder content for this accordion, which is intended to demonstrate the &lt;code&gt;.accordion-flush&lt;/code&gt; class. This is the second item's accordion body. Let's imagine this being filled with some actual content.&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="accordion-item"&gt; &lt;h2 class="accordion-header" id="flush-headingThree"&gt; &lt;button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseThree" aria-expanded="false" aria-controls="flush-collapseThree"&gt; Accordion Item #3 &lt;/button&gt; &lt;/h2&gt; &lt;div id="flush-collapseThree" class="accordion-collapse collapse" aria-labelledby="flush-headingThree" data-bs-parent="#accordionFlushExample"&gt; &lt;div class="accordion-body"&gt;Placeholder content for this accordion, which is intended to demonstrate the &lt;code&gt;.accordion-flush&lt;/code&gt; class. This is the third item's accordion body. Nothing more exciting happening here in terms of content, but just filling up the space to make it look, at least at first glance, a bit more representative of how this would look in a real-world application.&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74303816, "author": "Teobis", "author_id": 9944461, "author_profile": "https://Stackoverflow.com/users/9944461", "pm_score": 2, "selected": true, "text": "<!doctype html>\n<html lang=\"en\">\n\n<head>\n <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi\" crossorigin=\"anonymous\">\n <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3\" crossorigin=\"anonymous\"></script>\n<style>\n\n.accordion{\nmargin:30px;\n}\n\n\n.accordion-button.collapsed {\n border-bottom: #ccc 1px solid\n}\n\n.accordion-body {\n border-left: #673ab744 1px solid;\n border-bottom: #673ab744 1px solid;\n border-right: #673ab744 1px solid\n}\n.accordion-item h2:has(~ .show){ border:1px solid red !important; }\n</style>\n \n</head>\n\n<body>\n <div class=\"accordion accordion-flush\" id=\"accordionFlushExample\">\n <div class=\"accordion-item\">\n <h2 class=\"accordion-header\" id=\"flush-headingOne\">\n <button class=\"accordion-button collapsed\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#flush-collapseOne\" aria-expanded=\"false\" aria-controls=\"flush-collapseOne\">\n Accordion Item #1\n </button>\n </h2>\n <div id=\"flush-collapseOne\" class=\"accordion-collapse collapse\" aria-labelledby=\"flush-headingOne\" data-bs-parent=\"#accordionFlushExample\">\n <div class=\"accordion-body\">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> class. This is the first item's accordion body.</div>\n </div>\n </div>\n <div class=\"accordion-item\">\n <h2 class=\"accordion-header\" id=\"flush-headingTwo\">\n <button class=\"accordion-button collapsed\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#flush-collapseTwo\" aria-expanded=\"false\" aria-controls=\"flush-collapseTwo\">\n Accordion Item #2\n </button>\n </h2>\n <div id=\"flush-collapseTwo\" class=\"accordion-collapse collapse\" aria-labelledby=\"flush-headingTwo\" data-bs-parent=\"#accordionFlushExample\">\n <div class=\"accordion-body\">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> class. This is the second item's accordion body. Let's imagine this being filled with some actual content.</div>\n </div>\n </div>\n <div class=\"accordion-item\">\n <h2 class=\"accordion-header\" id=\"flush-headingThree\">\n <button class=\"accordion-button collapsed\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#flush-collapseThree\" aria-expanded=\"false\" aria-controls=\"flush-collapseThree\">\n Accordion Item #3\n </button>\n </h2>\n <div id=\"flush-collapseThree\" class=\"accordion-collapse collapse\" aria-labelledby=\"flush-headingThree\" data-bs-parent=\"#accordionFlushExample\">\n <div class=\"accordion-body\">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> class. This is the third item's accordion body. Nothing more exciting happening here in terms of content, but just filling up the space to make it look, at least at first glance, a bit more representative of how this would look in a real-world application.</div>\n </div>\n </div>\n</div>\n\n</body>\n\n</html>" }, { "answer_id": 74304093, "author": "Selcuk xD", "author_id": 18893404, "author_profile": "https://Stackoverflow.com/users/18893404", "pm_score": 0, "selected": false, "text": ".accordion-button:not(.collapsed) {\n border: 4px solid red;\n transition: ease 0.25s;\n}\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5549354/" ]
74,303,559
<p>I have created a userform with some comboboxes, based on combobox2 I would like to populate combobox1.</p> <p>In combobox2 there are 6 items to choose from 17, 19, 21, 23, 25, 25+</p> <p>Based on the selected item in Combobox1 I would like to populate combobox2 as following:</p> <p>If ItemA is selected, Combobox1 should be populated from range in Sheet ”supply_to_production” range (T6:T1000)</p> <p>If ItemB is selected, Combobox1 should be populated from range in Sheet ”supply_to_production” range (V6:V1000)</p> <p>If ItemC is selected, Combobox1 should be populated from range in Sheet ”supply_to_production” range (X6:X1000)</p> <p>If ItemD is selected, Combobox1 should be populated from range in Sheet ”supply_to_production” range (Z6:Z1000)</p> <p>If ItemE is selected, Combobox1 should be populated from range in Sheet ”supply_to_production” range (AB6:AB1000)</p> <p>If ItemF is selected, Combobox1 should be populated from range in Sheet ”supply_to_production” range (AD 6:AD1000)</p> <p>I have tried the code bellow, it is not giving me any error but is also does not give me any list in combobox1.</p> <p>`</p> <pre><code> Private Sub UserForm_Initialize() With ComboBox2 .AddItem &quot;17&quot; .AddItem &quot;19&quot; .AddItem &quot;21&quot; .AddItem &quot;23&quot; .AddItem &quot;25&quot; .AddItem &quot;25+&quot; End With End Sub Private Sub ComboBox1_Update() Dim index As Integer index = ComboBox2.ListIndex ComboBox1.Clear Select Case index Case &quot;17&quot;: ComboBox1.List = [SUPPLY_TO_PRODUCTION!T6:T1000] Case &quot;19&quot;: ComboBox1.List = [SUPPLY_TO_PRODUCTION!V6:V1000] Case &quot;21&quot;: ComboBox1.List = [SUPPLY_TO_PRODUCTION!X6:X1000] Case &quot;23&quot;: ComboBox1.List = [SUPPLY_TO_PRODUCTION!Z6:Z1000] Case &quot;25&quot;: ComboBox1.List = [SUPPLY_TO_PRODUCTION!AB6:AB1000] Case &quot;25+&quot;: ComboBox1.List = [SUPPLY_TO_PRODUCTION!AD6:AD1000] End Select End Sub </code></pre> <p>`</p>
[ { "answer_id": 74303816, "author": "Teobis", "author_id": 9944461, "author_profile": "https://Stackoverflow.com/users/9944461", "pm_score": 2, "selected": true, "text": "<!doctype html>\n<html lang=\"en\">\n\n<head>\n <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi\" crossorigin=\"anonymous\">\n <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3\" crossorigin=\"anonymous\"></script>\n<style>\n\n.accordion{\nmargin:30px;\n}\n\n\n.accordion-button.collapsed {\n border-bottom: #ccc 1px solid\n}\n\n.accordion-body {\n border-left: #673ab744 1px solid;\n border-bottom: #673ab744 1px solid;\n border-right: #673ab744 1px solid\n}\n.accordion-item h2:has(~ .show){ border:1px solid red !important; }\n</style>\n \n</head>\n\n<body>\n <div class=\"accordion accordion-flush\" id=\"accordionFlushExample\">\n <div class=\"accordion-item\">\n <h2 class=\"accordion-header\" id=\"flush-headingOne\">\n <button class=\"accordion-button collapsed\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#flush-collapseOne\" aria-expanded=\"false\" aria-controls=\"flush-collapseOne\">\n Accordion Item #1\n </button>\n </h2>\n <div id=\"flush-collapseOne\" class=\"accordion-collapse collapse\" aria-labelledby=\"flush-headingOne\" data-bs-parent=\"#accordionFlushExample\">\n <div class=\"accordion-body\">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> class. This is the first item's accordion body.</div>\n </div>\n </div>\n <div class=\"accordion-item\">\n <h2 class=\"accordion-header\" id=\"flush-headingTwo\">\n <button class=\"accordion-button collapsed\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#flush-collapseTwo\" aria-expanded=\"false\" aria-controls=\"flush-collapseTwo\">\n Accordion Item #2\n </button>\n </h2>\n <div id=\"flush-collapseTwo\" class=\"accordion-collapse collapse\" aria-labelledby=\"flush-headingTwo\" data-bs-parent=\"#accordionFlushExample\">\n <div class=\"accordion-body\">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> class. This is the second item's accordion body. Let's imagine this being filled with some actual content.</div>\n </div>\n </div>\n <div class=\"accordion-item\">\n <h2 class=\"accordion-header\" id=\"flush-headingThree\">\n <button class=\"accordion-button collapsed\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#flush-collapseThree\" aria-expanded=\"false\" aria-controls=\"flush-collapseThree\">\n Accordion Item #3\n </button>\n </h2>\n <div id=\"flush-collapseThree\" class=\"accordion-collapse collapse\" aria-labelledby=\"flush-headingThree\" data-bs-parent=\"#accordionFlushExample\">\n <div class=\"accordion-body\">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> class. This is the third item's accordion body. Nothing more exciting happening here in terms of content, but just filling up the space to make it look, at least at first glance, a bit more representative of how this would look in a real-world application.</div>\n </div>\n </div>\n</div>\n\n</body>\n\n</html>" }, { "answer_id": 74304093, "author": "Selcuk xD", "author_id": 18893404, "author_profile": "https://Stackoverflow.com/users/18893404", "pm_score": 0, "selected": false, "text": ".accordion-button:not(.collapsed) {\n border: 4px solid red;\n transition: ease 0.25s;\n}\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20378135/" ]
74,303,562
<p>I'm trying to write a JavaScript that makes an id change its id on click. Basically, I would like to create a dark mode toggle button. Not sure what I'm doing wrong though.</p> <p>HTML</p> <pre><code>&lt;button id=&quot;nottebottone&quot; class=&quot;notte&quot;&gt;Attiva modalità notturna&lt;/button&gt; </code></pre> <p>CSS</p> <pre><code>#Sito { max-width: 1024px; margin: auto; text-align: center; background-color: rgb(221, 241, 235); border: black ridge; border-width: 0.03cm; } </code></pre> <p>Which I'm trying to change to:</p> <pre><code>#Nightmode { max-width: 1024px; margin: auto; text-align: center; background-color: rgb(0, 0, 0); border: rgb(255, 255, 255) ridge; border-width: 0.03cm; color: white; } </code></pre> <p>JavaScript:</p> <pre><code>let bottonedarkmode = document.getElementById(&quot;nottebottone&quot;); function attivadarkmode() { if (document.div.id == &quot;Sito&quot;) { document.div.id = &quot;Nightmode&quot;; } else { documento.div.id = &quot;Sito&quot;; } } bottonedarkmode.addEventListener('click', attivadarkmode); </code></pre> <p>Click the button nottebottone to enable the id switch, but nothing happens.</p>
[ { "answer_id": 74303642, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "let darkModeBtn = document.querySelector(\".notte\");\n\nfunction attivadarkmode() {\n darkModeBtn.classList.toggle('light');\n darkModeBtn.classList.toggle('dark');\n}\n\ndarkModeBtn.addEventListener('click', attivadarkmode);" }, { "answer_id": 74303664, "author": "Shoaib Amin", "author_id": 19580087, "author_profile": "https://Stackoverflow.com/users/19580087", "pm_score": 0, "selected": false, "text": "document.getElementById('nottebottone').id = 'Nightmode';\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13707732/" ]
74,303,577
<p>I have a data file like this :</p> <pre class="lang-none prettyprint-override"><code>0000 0f 13 45 54 23 24 ae e1 f6 0001 f8 31 35 23 24 e7 e6 e1 f5 0002 0f 13 45 54 23 24 ae e1 f6 0003 0f 13 45 54 23 24 ae e1 f6 0004 f8 31 35 23 24 e7 e6 e1 f5 0005 0f 13 45 54 23 24 ae e1 f6 0006 0f 13 45 54 23 24 ae e1 f6 </code></pre> <p>So let's say i would like to remove every 2nd 3rd row starting from top and leaving 2 rows each after which the output should be:</p> <pre class="lang-none prettyprint-override"><code>0000 0f 13 45 54 23 24 ae e1 f6 0003 0f 13 45 54 23 24 ae e1 f6 0004 f8 31 35 23 24 e7 e6 e1 f5 </code></pre>
[ { "answer_id": 74303707, "author": "choroba", "author_id": 1030675, "author_profile": "https://Stackoverflow.com/users/1030675", "pm_score": 0, "selected": false, "text": "perl -ne 'print if $. % 4 < 2' file\n" }, { "answer_id": 74304817, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 0, "selected": false, "text": "AWK" }, { "answer_id": 74305377, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 1, "selected": false, "text": "sed '2~4,+1d' file\n" }, { "answer_id": 74314978, "author": "M. Nejat Aydin", "author_id": 13809001, "author_profile": "https://Stackoverflow.com/users/13809001", "pm_score": 0, "selected": false, "text": "sed" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14726199/" ]
74,303,578
<p>I'm trying to build a sort of multi step form with React Hook Form, but it is not the classic multi step form. In my case I need to persist in the database on every submit.</p> <p>To me that was an indication that I should split the form into small forms, and validate each one of them individually.</p> <p>The only problem - but not simple - with this approach is that now I'm running into situations where <strong>one step needs data from another step</strong>. Since each individual form has its own <code>FormProvider</code>, I can only use <code>useContext</code> to access data from their correspondent context. I don't want to build another context just to store all data from all steps.</p> <p>This is an ilustration of the structure I currently have</p> <pre><code>interface IForm1 { id?: number; } interface IForm2 { name?: string; } const GenericForm = &lt;T extends FieldValues, &gt;(props: PropsWithChildren&lt;T&gt;) =&gt; { const form = useForm&lt;T&gt;(); return &lt;FormProvider {...form}&gt; &lt;form&gt; {props.children} &lt;/form&gt; &lt;/FormProvider&gt;; }; const MyForms = () =&gt; &lt;&gt; &lt;GenericForm&lt;IForm1&gt;&gt; &lt;Component1 /&gt; &lt;/GenericForm&gt; &lt;GenericForm&lt;IForm2&gt;&gt; &lt;Component1 /&gt; &lt;/GenericForm&gt; &lt;/&gt;; </code></pre> <p>Now I want the children components to be able to access data from both contexts, something like this:</p> <pre><code>const Component1 = () =&gt; { const { watch } = useFormContext&lt;IForm1&gt;(); const form2Context = useFormContext&lt;IForm2&gt;(); const id = watch('id'); const name = form2Context.watch('name'); return &lt;div&gt; {id} and {name} &lt;/div&gt;; }; </code></pre> <p>This won't work since each FormProvider is in a different level, so I thought of doing something like this:</p> <pre><code>const MyForms = () =&gt; &lt;&gt; &lt;FormProvider {...form1}&gt; &lt;FormProvider {...form2}&gt; &lt;GenericForm&lt;IForm1&gt;&gt; &lt;Component1 /&gt; &lt;/GenericForm&gt; &lt;GenericForm&lt;IForm2&gt;&gt; &lt;Component1 /&gt; &lt;/GenericForm&gt; &lt;/FormProvider&gt; &lt;/&gt;; </code></pre> <p>This also didn't work, the deepest FormProvider seems to override all parents.</p> <p>Has anyone ever had this kind of problem? Any ideas?</p> <p>Another idea that I'm investigating would be to try to expose the form methods - <code>watch</code> <code>setValue</code> to the parent and register them somehow in an Record. This way any child could use them. The problem is that it is really hard to keep these methods in sync.</p> <p><strong>Update</strong></p> <p>I found a way to combine the instances of useForm()</p> <pre><code>It is something like this: const form1 = useForm(); const form2 = useForm(); &lt;FormProvider {...{ ...form1, ...form2}}&gt; &lt;form&gt;Form 1&lt;/form&gt; &lt;form&gt;Form 2&lt;/form&gt; &lt;/FormProvider&gt; </code></pre> <p>The problem is that when I try to use <code>useFormContext</code> I can see that the context contains a large object with all the properties of the two forms as if like they were simply combined.</p> <p>I thought the contexts would be separated from each other and that I could do something like:</p> <pre><code>const form1 = useFormContext&lt;IForm1&gt;(); </code></pre> <p>This does not work =/</p>
[ { "answer_id": 74303707, "author": "choroba", "author_id": 1030675, "author_profile": "https://Stackoverflow.com/users/1030675", "pm_score": 0, "selected": false, "text": "perl -ne 'print if $. % 4 < 2' file\n" }, { "answer_id": 74304817, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 0, "selected": false, "text": "AWK" }, { "answer_id": 74305377, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 1, "selected": false, "text": "sed '2~4,+1d' file\n" }, { "answer_id": 74314978, "author": "M. Nejat Aydin", "author_id": 13809001, "author_profile": "https://Stackoverflow.com/users/13809001", "pm_score": 0, "selected": false, "text": "sed" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6640681/" ]
74,303,602
<p>I want to add the report question text on the right side I tried the position widget but it doesn't work what I do?</p> <p>I try to achieve-</p> <p><a href="https://i.stack.imgur.com/SIgSa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SIgSa.png" alt="enter image description here" /></a></p> <p>code-</p> <pre><code>Positioned( right: 0, child: Row( children: [ Icon(Icons.report, color: Color(0xff0E5487),), TextButton(onPressed: () =&gt; {}, child: Text(&quot;Report Question&quot;, style: cstmTextStyle(fs: 18, fc:Color(0xff0E5487) ),)), ], ),), </code></pre>
[ { "answer_id": 74303914, "author": "powerman23rus", "author_id": 6163011, "author_profile": "https://Stackoverflow.com/users/6163011", "pm_score": 2, "selected": true, "text": "Column" }, { "answer_id": 74315160, "author": "MrShakila", "author_id": 19292778, "author_profile": "https://Stackoverflow.com/users/19292778", "pm_score": 0, "selected": false, "text": "Align(alignment: Alignment.topRight,\n child: const Row(\n \n ),\n ),\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19845719/" ]
74,303,615
<p>I am prompted the following: &quot;In PyCharm, write a program that prompts the user for their name and age. Your program should then tell the user the year they were born. Here is a sample execution of the program with the user input in bold:</p> <p>What is your name? Amanda How old are you? 15</p> <p>Hello Amanda! You were born in 2005.</p> <p>Write the program. Format your code using best practices. Refer to the zyBooks style guide, if needed, to use proper naming conventions for variables and methods. Use the most appropriate statements with minimal extraneous elements, steps, or procedures. Run the program. Debug the program. Be sure your code produces the correct results. Save and submit your file.&quot;</p> <p>Why is user_age = int(input()) returning a ValueError? &quot;</p> <pre><code> user_age = int(input()) ^^^^^^^^^^^^ ValueError: invalid literal for int() with base 10: '' </code></pre> <p>&quot; and how would I fix it? I've tried a few different things but I'm not too sure what exactly is wrong. Also not sure if that's the correct way to bold the user inputs or not.</p> <p>Program:</p> <pre><code>user_name = input('What is your name?') user_age = int(input()) birth_year = (2022 - user_age) print('How old are you? &lt;b&gt;{}&lt;/b&gt;'.format(user_age)) print('Hello &lt;b&gt;{}&lt;/b&gt;! You were born in &lt;b&gt;{}&lt;/b&gt;.'.format(user_name, birth_year)) </code></pre>
[ { "answer_id": 74303914, "author": "powerman23rus", "author_id": 6163011, "author_profile": "https://Stackoverflow.com/users/6163011", "pm_score": 2, "selected": true, "text": "Column" }, { "answer_id": 74315160, "author": "MrShakila", "author_id": 19292778, "author_profile": "https://Stackoverflow.com/users/19292778", "pm_score": 0, "selected": false, "text": "Align(alignment: Alignment.topRight,\n child: const Row(\n \n ),\n ),\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20399377/" ]
74,303,646
<p>Hello so i have two columns that im using <code>describe()</code> and im getting their stats. I have something like this</p> <pre><code>x=pd.Series([1,3,4,6,7]) y=pd.Series([75,324,234,42]) desk1=x.describe() desk2=y.describe() </code></pre> <p>I want to print <code>desk1</code> and <code>desk2</code> below of each category.I am doing this:</p> <pre><code>print(&quot;desk1 stats&quot;,end=&quot;\t\t&quot;) print(&quot;desk1 stats&quot;) print(desk1,end=&quot;\t\t&quot;) print(desk2) </code></pre> <p>I get this :</p> <pre><code>desk1 stats desk1 stats count 5.000000 mean 4.200000 std 2.387467 min 1.000000 25% 3.000000 50% 4.000000 75% 6.000000 max 7.000000 dtype: float64 count 4.000000 mean 168.750000 std 133.185022 min 42.000000 25% 66.750000 50% 154.500000 75% 256.500000 max 324.000000 dtype: float64 </code></pre> <p>And i my desired output is this:</p> <pre><code>desk1 stats desk1 stats count 5.000000 count 4.000000 mean 4.200000 mean 168.750000 std 2.387467 std 133.185022 min 1.000000 min 42.000000 25% 3.000000 25% 66.750000 50% 4.000000 50% 154.500000 75% 6.000000 75% 256.500000 max 7.000000 max 324.000000 dtype: float64 dtype: float64 </code></pre> <p>I would like to not create a dataframe.Any solutions? Thanks in advance</p>
[ { "answer_id": 74303679, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "print(pd.concat([desk1, desk2],\n keys=['desk1 description', 'desk2 description'],\n axis=1))\n" }, { "answer_id": 74303927, "author": "Khaled DELLAL", "author_id": 15852600, "author_profile": "https://Stackoverflow.com/users/15852600", "pm_score": 0, "selected": false, "text": "\ndesk1=pd.DataFrame(desk1)\n\ndesk_mid=pd.DataFrame(desk1.index)\n\ndesk_mid.index=desk1.index\n\ndesk2=pd.DataFrame(desk2)\n\ndf=pd.concat([desk1, desk_mid, desk2], axis=1)\n\ndf.columns=[\"desk1 description\", \" desk2 description\", \"\"]\n\ndf\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17700692/" ]
74,303,653
<p>I have table like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>value</th> </tr> </thead> <tbody> <tr> <td>{&quot;Date&quot;:&quot;2022-10-31&quot;,&quot;Delta&quot;:5,&quot;Comment&quot;:null}</td> </tr> <tr> <td>{&quot;Date&quot;:&quot;2022-11-01&quot;,&quot;Delta&quot;:5,&quot;Comment&quot;:null}</td> </tr> </tbody> </table> </div> <p>How can I get a table like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Delta</th> <th>Comment</th> </tr> </thead> <tbody> <tr> <td>2022-10-31</td> <td>5</td> <td>null</td> </tr> <tr> <td>2022-11-01</td> <td>5</td> <td>null</td> </tr> </tbody> </table> </div> <p>Data:</p> <pre><code>DECLARE @r TABLE ( value VARCHAR(255) ) INSERT INTO @r VALUES (N'{&quot;Date&quot;:&quot;2022-10-31&quot;,&quot;Delta&quot;:5,&quot;Comment&quot;:null}'), (N'{&quot;Date&quot;:&quot;2022-11-01&quot;,&quot;Delta&quot;:5,&quot;Comment&quot;:null}'); </code></pre>
[ { "answer_id": 74303741, "author": "marc_s", "author_id": 13302, "author_profile": "https://Stackoverflow.com/users/13302", "pm_score": 3, "selected": true, "text": "SELECT j.* \nFROM @r\nCROSS APPLY OPENJSON(value)\n WITH \n (\n Date DATE,\n Delta INT,\n Comment VARCHAR(50)\n ) j;\n" }, { "answer_id": 74303987, "author": "John Cappelletti", "author_id": 1570000, "author_profile": "https://Stackoverflow.com/users/1570000", "pm_score": 2, "selected": false, "text": "JSON_VALUE()" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14448434/" ]
74,303,662
<p>I have the following initial json:</p> <pre><code>let options = {cf: { image: {} } } </code></pre> <p>I need to add new elements inside the images key as per the checks below:</p> <pre><code> if (url.searchParams.has(&quot;fit&quot;)) options.cf.image.fit = url.searchParams.get(&quot;fit&quot;) if (url.searchParams.has(&quot;width&quot;)) options.cf.image.width = url.searchParams.get(&quot;width&quot;) if (url.searchParams.has(&quot;height&quot;)) options.cf.image.height = url.searchParams.get(&quot;height&quot;) if (url.searchParams.has(&quot;quality&quot;)) options.cf.image.quality = url.searchParams.get(&quot;quality&quot;) </code></pre> <p>The problem is that it returns that the type <strong>&quot;fit&quot;, &quot;width&quot;, &quot;height&quot;, &quot;quality&quot;</strong> does not exist in the <strong>options.cf.image</strong> element (example below):</p> <pre><code>Property 'fit' does not exist on type '{}'.ts (2339) </code></pre> <p>I tried to create an interface for <strong>cf.image</strong> with the elements being optional but it didn't work because it returns that the element can be null and it can't because it's a string.</p> <p>In the end, I need the options to be sent to the <strong>fetch(URL, options)</strong> function, where options is of type RequestInit | Request</p> <p>My complete code is at <a href="https://pastebin.com/fvvBpf1e" rel="nofollow noreferrer">https://pastebin.com/fvvBpf1e</a>. It is <strong>Cloudflare's</strong> open source for resizing images <a href="https://developers.cloudflare.com/images/image-resizing/resize-with-workers/#an-example-worker" rel="nofollow noreferrer">https://developers.cloudflare.com/images/image-resizing/resize-with-workers/#an-example-worker</a></p>
[ { "answer_id": 74304098, "author": "Lesiak", "author_id": 1570854, "author_profile": "https://Stackoverflow.com/users/1570854", "pm_score": 0, "selected": false, "text": "// Disable ScrapeShield for this request.\nfetch(event.request, { cf: { scrapeShield: false } })\n" }, { "answer_id": 74304132, "author": "Tyler Aldrich", "author_id": 1580425, "author_profile": "https://Stackoverflow.com/users/1580425", "pm_score": 1, "selected": false, "text": "let options = {cf: { image: {} } }" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3732676/" ]
74,303,686
<p>I've been looking around here for an example drop down nav menu that does three things:</p> <ol> <li>When the user CLICK on the menu drop it shows the drop down (this works)</li> <li>When the user CLICKS outside of the nav area or anywhere else on the page is closes an open drops (this works too)</li> <li>When a user CLICKS on another drop down if one is already open, it closes the previously open drop and opens the new drop menu. &lt;-(I'm stuck here).</li> </ol> <p>Currently if you click on one drop menu, then click on another, the first stays open. I want any other menus that are open to close if you click on another drop down. But i want to retain the behavior that when the user clicks outside of the menu anywhere in the document it closes too.</p> <p>I've found several SO posts that solve some of this. However sometimes they nav bar only has 1 drop down as an example. Other times for some reason the solution causes other issues in my nav. So i decided to create a new post.</p> <p>Please note that i'm learning JS and jquery now.</p> <p>Here is my code:</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>$(document).ready(function() { $('.dropdown').click(function(e) { e.stopPropagation(); // hide all dropdown that may be visible - // this works but it breaks the functionality of toggling open and closed // when you click on the menu item e.preventDefault(); // close when click outside $(this).find('.dropdown-content').toggleClass('open') }); // Close dropdown when u click outside of the nav ul $(document).click(function(e) { if (!e.target.closest("ul") &amp;&amp; $(".dropdown-content").hasClass("open")) { $(".dropdown-content").removeClass("open"); } }) });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.nav__topbar { position: relative; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-align: center; -ms-flex-align: center; align-items: center; min-height: 2em; background: #fff; } .nav__links { overflow: hidden; display: flex; align-items: center; margin-left: auto!important; a { float: left; display: block; text-align: center; padding: 14px 16px; text-decoration: none; &amp;:hover { color: #ccc; } } .icon { display: none; } } .nav__links .dropdown .dropdown-content { position: absolute; max-width: 25%; } .dropdown .dropbtn, .nav__links a { font-size: 1.5em!important; color: #222; } /* Upon click the menu should turn into a vertical stacked menu with a soft drop shadow */ .nav__links.vertical { position: absolute; display: flex; flex-direction: column; align-items: flex-start; padding-top: 2em; top: 50%; left: 70%; background-color: #fff; z-index: 1; border: 1px solid #f2f3f3; border-radius: 4px; background: #fff; -webkit-box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12); box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12); } .dropdown { float: left; overflow: hidden; } /* Codepen doesn't like when i nest styles */ .dropdown .dropbtn { border: none; outline: none; padding: 14px 16px; background-color: inherit; font-family: inherit; margin: 0; } .dropdown { cursor: pointer; display: block; &amp;:hover { background-color: #444; } } /* Style the dropdown content (hidden by default) */ .dropdown-content { display: none; background-color: #fff; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2); z-index: 1; width: 100%; transition: all 0.25s ease-in; transform: translateY(-10px); } /* Style the links inside the dropdown codepen doesn't like my nesting */ .dropdown-content a { float: none; text-decoration: none; display: block; text-align: left; } .dropdown-content li, .nav__links li, .nav__links li a { list-style-type: none; text-decoration: none; } .dropdown li { padding: 20px } .dropdown .dropdown-content.open { display: block; padding: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;nav class="nav__topbar"&gt; &lt;ul class="nav__links"&gt; &lt;li class="dropdown" data-hover="title"&gt; &lt;button class="dropbtn"&gt;community &lt;span class="downBtn"&gt;&amp;#x25BC;&lt;/span&gt; &lt;/button&gt; &lt;ul class="dropdown-content"&gt; &lt;li&gt;&lt;a href="#" class="masthead__menu-item hover-underline"&gt;item 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="masthead__menu-item hover-underline"&gt;item 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="masthead__menu-item hover-underline"&gt;item 3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Menu item 2&lt;/a&gt;&lt;/li&gt; &lt;li class="dropdown" data-hover="title"&gt; &lt;button class="dropbtn"&gt;menu &lt;span class="downBtn"&gt;&amp;#x25BC;&lt;/span&gt; &lt;/button&gt; &lt;ul class="dropdown-content"&gt; &lt;li&gt;&lt;a href="#" class="masthead__menu-item hover-underline"&gt;item 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="masthead__menu-item hover-underline"&gt;item 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="masthead__menu-item hover-underline"&gt;item 3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="dropdown" data-hover="title"&gt; &lt;button class="dropbtn"&gt;menu &lt;span class="downBtn"&gt;&amp;#x25BC;&lt;/span&gt; &lt;/button&gt; &lt;ul class="dropdown-content"&gt; &lt;li&gt;&lt;a href="#" class="masthead__menu-item hover-underline"&gt;item 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="masthead__menu-item hover-underline"&gt;item 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="masthead__menu-item hover-underline"&gt;item 3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt;</code></pre> </div> </div> </p> <p>And here [is a codepen](<a href="https://codepen.io/lwasser/pen/BaVKYNX" rel="nofollow noreferrer">https://codepen.io/lwasser/pen/BaVKYNX</a> as well with the same code in case you want to play with the code.</p> <p>UPDATE: the code above works with the fixes provided in the accepted answer below! The code had another bug which was drop down links didn't work. but i was able to remove / fix that by removing:</p> <pre><code>e.stopPropagation(); e.preventDefault(); </code></pre> <p>Many thanks for the folks who helped below!! And i'll try to fully update my codepen with the hamburger as well as soon as I can in case that helps people.</p>
[ { "answer_id": 74303757, "author": "Nitha", "author_id": 1983045, "author_profile": "https://Stackoverflow.com/users/1983045", "pm_score": 1, "selected": false, "text": "$(document).ready(function () {\n $(\".dropdown\").click(function (e) {\n e.stopPropagation();\n e.preventDefault();\n // close when click outside\n $(this).find(\".dropdown-content\").toggleClass(\"open\");\n $(this).siblings('.dropdown').find('.dropdown-content').removeClass('open');\n });\n\n // Close dropdown when u click outside of the nav ul\n $(document).click(function (e) {\n if (!e.target.closest(\"ul\") && $(\".dropdown-content\").hasClass(\"open\")) {\n $(\".dropdown-content\").removeClass(\"open\");\n }\n });\n});" }, { "answer_id": 74303791, "author": "Valeriu Ciuca", "author_id": 4527645, "author_profile": "https://Stackoverflow.com/users/4527645", "pm_score": 3, "selected": true, "text": "open" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3908816/" ]
74,303,699
<p>I'm using this code to parse a json file and change some items in de app I build:</p> <pre><code> fun fetchJson() { if (isNetworkAvailable()) { val request = Request.Builder().url(stationAPPJsonURL).build() client.newCall(request).enqueue(object : Callback { override fun onResponse(call: Call, response: Response) { val body = response.body?.string() val gson = GsonBuilder().create() try { val stationAPP = gson.fromJson(body, StationAPP::class.java) //ACTIE actie_zichtbaar = stationAPP.actie_zichtbaar actie_img = stationAPP.actie_img actie_url = stationAPP.actie_url ... I left out some code catch (error: JsonParseException) { runOnUiThread { val toast = Toast.makeText(applicationContext, &quot;Problem loading JSON.\nFunctionality may be limited for a while.&quot;, Toast.LENGTH_SHORT) val view = toast.view!!.findViewById&lt;TextView&gt;(android.R.id.message) toast?.let { view.gravity = Gravity.CENTER } toast.setGravity(Gravity.CENTER, 0, 0) toast.show() } } } override fun onFailure(call: Call, e: IOException) { runOnUiThread { val toast = Toast.makeText(applicationContext, &quot;Problem loading JSON.\nFunctionality may be limited for a while.&quot;, Toast.LENGTH_SHORT) val view = toast.view!!.findViewById&lt;TextView&gt;(android.R.id.message) view?.let { view.gravity = Gravity.CENTER } toast.setGravity(Gravity.CENTER, 0, 0) toast.show() --&gt; line 1390!! } } } } </code></pre> <p>I see in the logs in Google Play Console that sometime this part of the code crashes (4%). I've no clue why? I tested it on several devices and no errors at all.</p> <p>Who can help me out here?</p> <p>Is it possible That: val stationAPP = gson.fromJson(body, StationAPP::class.java) throws no exception but that somehow the json file is loaded with some errors in it? And therefor some items are null?</p> <p>Thanks for you help ;)</p> <p>Update: this is the error it produces:</p> <pre><code>Exception java.lang.NullPointerException: at com.familiekoning.grolloo.MainActivity$fetchJson$1.onFailure$lambda-10 (MainActivity.kt:1390) at com.familiekoning.grolloo.MainActivity$fetchJson$1.$r8$lambda$lczurdfMtnZdFDn9iwHvPqw9_Pg at com.familiekoning.grolloo.MainActivity$fetchJson$1$$ExternalSyntheticLambda8.run at android.os.Handler.handleCallback (Handler.java:938) at android.os.Handler.dispatchMessage (Handler.java:99) at android.os.Looper.loop (Looper.java:250) at android.app.ActivityThread.main (ActivityThread.java:7806) at java.lang.reflect.Method.invoke at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:592) at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:958) </code></pre>
[ { "answer_id": 74304565, "author": "TheLibrarian", "author_id": 3434763, "author_profile": "https://Stackoverflow.com/users/3434763", "pm_score": 2, "selected": true, "text": "!!" }, { "answer_id": 74304701, "author": "Patrick Koning", "author_id": 12620176, "author_profile": "https://Stackoverflow.com/users/12620176", "pm_score": 0, "selected": false, "text": "val toast = Toast.makeText(applicationContext, \"Problem loading JSON.\\nFunctionality may be limited for a while.\", Toast.LENGTH_SHORT)\n\n val view = toast.view!!.findViewById<TextView>(android.R.id.message)\n view?.let { view.gravity = Gravity.CENTER }\n toast.setGravity(Gravity.CENTER, 0, 0)\n toast.show()\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12620176/" ]
74,303,745
<p>I am trying to get data by Id records saved in mssql database. for eg. I am forming a get request in postman like this: <em>localhost:3200/api/v1/players</em> Problem is I am getting error displayed as follows:</p> <pre><code>node:_http_outgoing:576 throw new ERR_HTTP_HEADERS_SENT('set'); ^ Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client </code></pre> <p>Why is it so? Is it because some other query is also running when I am visiting that endpoint?</p> <p>My code for querying by data:</p> <pre><code>const getPlayerById=async(req, res, next)=&gt; { try { const id = req.params.id; sql.connect(config, function(err) { if(err) { console.log(err); } else { var req=new sql.Request(); var player=req.input('input_parameter', sql.BigInt, id) .query(&quot;select distinct * from players WHERE Id=@input_parameter&quot;, function(err, recordset) { if(err) { console.log(&quot;Error while querying for Id!: &quot;+err) } else { res.send(recordset); } }); } return res.send(&quot;Record fetched for selected player!&quot;); }); } catch(error) { res.status(400).send(error.message); } } </code></pre> <p>In my main server.js I have wired up</p> <pre><code>app.use('/api/v1', playerRoutes.routes); </code></pre> <p>In router file:</p> <pre><code>router.get('/players/:id', playerControll.getPlayerById) </code></pre> <p>The record being displayed in my postman response window is like:</p> <p><em><strong>Could not send request Error: connect ECONNREFUSED 127.0.0.1:3200</strong></em></p> <p><em><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong>EDIT</strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></em>********** Now the query is working, but I am getting the fetched record being displayed twice in a nested format!!</p> <p>Like this-&gt;</p> <pre><code>{ &quot;recordsets&quot;: [ [ { &quot;Id&quot;: 6, &quot;player_code&quot;: &quot;P006&quot;, &quot;player_name&quot;: &quot;Petr Cech&quot;, &quot;player_club&quot;: &quot;Chelsea&quot;, &quot;player_position&quot;: &quot;Goalkeeper&quot; } ] ], &quot;recordset&quot;: [ { &quot;Id&quot;: 6, &quot;player_code&quot;: &quot;P006&quot;, &quot;player_name&quot;: &quot;Petr Cech&quot;, &quot;player_club&quot;: &quot;Chelsea&quot;, &quot;player_position&quot;: &quot;Goalkeeper&quot; } ], &quot;output&quot;: {}, &quot;rowsAffected&quot;: [] } </code></pre> <p>What's the glitch now?? Why is it showing like this?</p>
[ { "answer_id": 74303823, "author": "Paul", "author_id": 8193101, "author_profile": "https://Stackoverflow.com/users/8193101", "pm_score": 1, "selected": false, "text": "res.send(recordset)\n" }, { "answer_id": 74303835, "author": "Sebastien H.", "author_id": 1667822, "author_profile": "https://Stackoverflow.com/users/1667822", "pm_score": 3, "selected": true, "text": "res.send(recordset);" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9193561/" ]
74,303,753
<p>I need to be able to pull the same report but from Different Databases on the same server. ie different backups at certain points in time. The Stored procedures All Reside in a Reporting Database on said server. On the Report I would like to have a drop down of the Databases(ie Genesis_1, Genesis_2 etc then run the reports with their other parameters. Is this possible or am i looking at it from the wrong perspective.</p>
[ { "answer_id": 74303823, "author": "Paul", "author_id": 8193101, "author_profile": "https://Stackoverflow.com/users/8193101", "pm_score": 1, "selected": false, "text": "res.send(recordset)\n" }, { "answer_id": 74303835, "author": "Sebastien H.", "author_id": 1667822, "author_profile": "https://Stackoverflow.com/users/1667822", "pm_score": 3, "selected": true, "text": "res.send(recordset);" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19238060/" ]
74,303,781
<p><a href="https://i.stack.imgur.com/uqbeo.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uqbeo.jpg" alt="i want to auto click the search button" /></a></p> <p>Search button &gt;&gt;&gt;</p> <p>i want the button to auto click after entering the school ID of textbox</p>
[ { "answer_id": 74303823, "author": "Paul", "author_id": 8193101, "author_profile": "https://Stackoverflow.com/users/8193101", "pm_score": 1, "selected": false, "text": "res.send(recordset)\n" }, { "answer_id": 74303835, "author": "Sebastien H.", "author_id": 1667822, "author_profile": "https://Stackoverflow.com/users/1667822", "pm_score": 3, "selected": true, "text": "res.send(recordset);" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20408097/" ]
74,303,804
<p>i'm using beautiful soup <code>Data = soup.find_all('td')</code> which returns to me everything with the tag. is there a way for me to add an exception to not include the tag if <code>colspan=7</code>? cause that's the only indicator all the td tags are classless :)</p> <p>Thank you!</p>
[ { "answer_id": 74303823, "author": "Paul", "author_id": 8193101, "author_profile": "https://Stackoverflow.com/users/8193101", "pm_score": 1, "selected": false, "text": "res.send(recordset)\n" }, { "answer_id": 74303835, "author": "Sebastien H.", "author_id": 1667822, "author_profile": "https://Stackoverflow.com/users/1667822", "pm_score": 3, "selected": true, "text": "res.send(recordset);" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17555222/" ]
74,303,807
<p>I'm trying to make some unit tests for a pyqt5 application. The problem is that I cannot run multiple tests in a test suite because I'm not clearning up the application properly and the end of every test.</p> <pre><code> class MainWindowTest(QMainWindow): def __init__(self, widgetTypeUnderTest=None, model=None): super().__init__() self.widgetTypeUnderTest = widgetTypeUnderTest self.model = model # setting title self.setWindowTitle(&quot;AccosTest&quot;) self.setGeometry(100, 100, 500, 600) self.mainWindowLayout = QHBoxLayout() # container widget for everything else widget = QWidget() widget.setLayout(self.mainWindowLayout) self.setCentralWidget(widget) self.show() class Tests(unittest.TestCase): def setUp(self) -&gt; None: self.app = QApplication(sys.argv) def tearDown(self) -&gt; None: self.app.exit() def test(self): mainWindow = MainWindowTest() def test2(self): mainWindow = MainWindowTest() </code></pre> <p>Runing <code>Tests.test1</code> or <code>Tests.test2</code> individually does what is required, although this is likely because a second <code>QApplication</code> has not been started. When running both tests together I get a segfault.</p> <p>Would anybody know the correct commands to properly dismantle the <code>QApplication</code> after every test, since <code>self.app.exit()</code> doesn't seem to be doing the trick. Thanks!</p> <h1>edit</h1> <p>Do you think a better strategy would be to have two threads. One would start the main loop <code>sys.exit(self.app.exec())</code> and the other would wait for a while and then call exit?</p>
[ { "answer_id": 74308668, "author": "musicamante", "author_id": 2001654, "author_profile": "https://Stackoverflow.com/users/2001654", "pm_score": 3, "selected": true, "text": "instance()" }, { "answer_id": 74314324, "author": "CiaranWelsh", "author_id": 3059024, "author_profile": "https://Stackoverflow.com/users/3059024", "pm_score": 0, "selected": false, "text": "del" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3059024/" ]
74,303,815
<p>I'm trying to transform one 2d array:</p> <pre><code>{4: 6, 6: 2, 1: 2, 3: 7, 5: 4, 9: 1, 2: 3, 7: 2, 8: 1} </code></pre> <p>in to 2 different 1d arrays, like this:</p> <pre><code>arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] arr2 = [2, 3, 7, 6, 4, 2, 2, 1, 1] </code></pre> <p>To plot, using matplotlib, arr1 as y and arr2 as x.</p> <p>How can I do this?</p> <p>PS: Sorry for the bad English. (;</p>
[ { "answer_id": 74308668, "author": "musicamante", "author_id": 2001654, "author_profile": "https://Stackoverflow.com/users/2001654", "pm_score": 3, "selected": true, "text": "instance()" }, { "answer_id": 74314324, "author": "CiaranWelsh", "author_id": 3059024, "author_profile": "https://Stackoverflow.com/users/3059024", "pm_score": 0, "selected": false, "text": "del" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15764695/" ]
74,303,843
<p>Java 8 introduced <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html" rel="nofollow noreferrer"><code>Arrays.stream()</code></a> to convert a (primitive) array to a <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html" rel="nofollow noreferrer">Stream</a>.</p> <p>How can this method be used to get a stream for a <code>byte[]</code>?</p> <hr /> <p>It looks like the method only exists for <code>double[]</code>, <code>int[]</code> and <code>long[]</code>, but not for <code>byte[]</code>.</p> <p><a href="https://i.stack.imgur.com/BPRG8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BPRG8.png" alt="Arrays.stream() methods" /></a></p> <p>I guess the reason is that <code>Arrays.stream()</code> internally utilizes <code>StreamSupport</code> which does not provide a method for <code>byte[]</code> ...</p>
[ { "answer_id": 74303844, "author": "Stefan", "author_id": 1518225, "author_profile": "https://Stackoverflow.com/users/1518225", "pm_score": 1, "selected": false, "text": "byte[]" }, { "answer_id": 74304062, "author": "MikeFHay", "author_id": 839128, "author_profile": "https://Stackoverflow.com/users/839128", "pm_score": 1, "selected": false, "text": "map" }, { "answer_id": 74304089, "author": "WJS", "author_id": 1552534, "author_profile": "https://Stackoverflow.com/users/1552534", "pm_score": 2, "selected": false, "text": "IntStream" }, { "answer_id": 74304094, "author": "Morph21", "author_id": 7406338, "author_profile": "https://Stackoverflow.com/users/7406338", "pm_score": 0, "selected": false, "text": "byte[] byteArray = new byte[100];\nByte[] byteObjectArray = ArrayUtils.toObject(byteArray);\nStream<Byte> byteObjectStream = Arrays.stream(byteObjectArray);\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1518225/" ]
74,303,862
<p>I have a table and want to replace the column value with value from other column value based on some condition.</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> +---------------------+ | Cntry | Code | Value | +---------------------+ | US | C11 | A | | US | C12 | B | | US | C13 | C | | US | C14 | D | | US | C15 | E | | UK | C11 | A | | UK | C12 | B | | UK | C13 | C | | UK | C14 | D | | UK | C15 | E | +---------------------+</code></pre> </div> </div> </p> <p>I want to replace the value of C14 based on the value of C11 based on Cntry</p> <p>So my output should be like this.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>+---------------------+ | Cntry | Code | Value | +---------------------+ | US | C11 | A | | US | C12 | B | | US | C13 | C | | US | C14 | A |&lt;====Repalce with C11 for US | US | C15 | E | | UK | C11 | G | | UK | C12 | B | | UK | C13 | C | | UK | C14 | G |&lt;====Repalce with C11 for UK | UK | C15 | E | +---------------------+</code></pre> </div> </div> </p> <p>Is there anyway to do this in postgresql?</p> <p>Thanks</p>
[ { "answer_id": 74303844, "author": "Stefan", "author_id": 1518225, "author_profile": "https://Stackoverflow.com/users/1518225", "pm_score": 1, "selected": false, "text": "byte[]" }, { "answer_id": 74304062, "author": "MikeFHay", "author_id": 839128, "author_profile": "https://Stackoverflow.com/users/839128", "pm_score": 1, "selected": false, "text": "map" }, { "answer_id": 74304089, "author": "WJS", "author_id": 1552534, "author_profile": "https://Stackoverflow.com/users/1552534", "pm_score": 2, "selected": false, "text": "IntStream" }, { "answer_id": 74304094, "author": "Morph21", "author_id": 7406338, "author_profile": "https://Stackoverflow.com/users/7406338", "pm_score": 0, "selected": false, "text": "byte[] byteArray = new byte[100];\nByte[] byteObjectArray = ArrayUtils.toObject(byteArray);\nStream<Byte> byteObjectStream = Arrays.stream(byteObjectArray);\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20408108/" ]
74,303,866
<ol> <li>I am receiving the below error message after the implementation return service.</li> </ol> <blockquote> <p>Failure: Invalid merchandise description of package (120623)</p> </blockquote> <p>Code what we used.</p> <pre><code>if (isset($return_order) &amp;&amp; $return_order==1) { $returnService = new \Ups\Entity\ReturnService; $returnService-&gt;setCode(\Ups\Entity\ReturnService::PRINT_RETURN_LABEL_PRL); $shipment-&gt;setReturnService($returnService); } </code></pre> <ol start="2"> <li>If I also use the below code then it gives as mention error</li> </ol> <blockquote> <p>Failure: Shipment/ReferenceNumber is not allowed for this shipment (120541)</p> </blockquote> <p>Code what we used.</p> <pre><code>if (isset($return_order) &amp;&amp; $return_order==1) { $referenceNumber-&gt;setCode(\Ups\Entity\ReferenceNumber::CODE_RETURN_AUTHORIZATION_NUMBER); $referenceNumber-&gt;setValue($shipping_reference_number); } else { $referenceNumber-&gt;setCode(\Ups\Entity\ReferenceNumber::CODE_INVOICE_NUMBER); $referenceNumber-&gt;setValue($shipping_reference_number); } $shipment-&gt;setReferenceNumber($referenceNumber); </code></pre> <ol start="3"> <li>If I also use the below code then it gives as mention error</li> </ol> <blockquote> <p>Failure: Invalid merchandise description of package (120623)</p> </blockquote> <p>Code what we used.</p> <pre><code>if (isset($return_order) &amp;&amp; $return_order==1) { $referenceNumber-&gt;setCode(\Ups\Entity\ReferenceNumber::CODE_RETURN_AUTHORIZATION_NUMBER); $referenceNumber-&gt;setValue($shipping_reference_number); } else { $referenceNumber-&gt;setCode(\Ups\Entity\ReferenceNumber::CODE_INVOICE_NUMBER); $referenceNumber-&gt;setValue($shipping_reference_number); } $shipment-&gt;getPackages()[0]-&gt;setReferenceNumber($referenceNumber); </code></pre> <p>I'm using the following package, <a href="https://github.com/gabrielbull/php-ups-api" rel="nofollow noreferrer">https://github.com/gabrielbull/php-ups-api</a></p>
[ { "answer_id": 74580138, "author": "Top-Master", "author_id": 8740349, "author_profile": "https://Stackoverflow.com/users/8740349", "pm_score": 2, "selected": false, "text": "$referenceNumber" }, { "answer_id": 74610024, "author": "Joy Zalte", "author_id": 11872534, "author_profile": "https://Stackoverflow.com/users/11872534", "pm_score": 2, "selected": true, "text": "$package->setDescription(\"box type : \".$box_type)" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11872534/" ]
74,303,888
<p>I have a struct <code>Context</code> that as a type takes an association list from string to a custom type <code>process</code>. I'm trying to pattern match to see if my struct is empty (this seems to work fine) however checking whether my struct contains elements is giving me the following error.</p> <pre class="lang-none prettyprint-override"><code>File &quot;src/main.ml&quot;, line 131, characters 13-30: 131 | | Context.((ext_ref,prc)::tl) -&gt; ^^^^^^^^^^^^^^^^^ Error: This pattern matches values of type 'a list but a pattern was expected which matches values of type t </code></pre> <p>Here is the code that won't compile:</p> <pre><code>(* Finds a recv corresponding to a send stmt *) let rec find_recv (ctx: Context.t) (external_ref:variable) = match ctx with | Context.(empty) -&gt; None | Context.((ext_ref,prc)::tl) -&gt; begin match prc with | Prc(_, _,Recv(_,_,chn,_)) -&gt; if chn = external_ref then Some prc else find_recv tl external_ref |_ -&gt; find_recv tl external_ref end </code></pre> <p>Here is the signature for the 'Context' struct.</p> <pre><code>module type Context = sig type t val empty : t val lookup : t -&gt; string -&gt; process val extend : t-&gt;string -&gt;process -&gt; t val filter : t-&gt;string -&gt;t end </code></pre> <p>Here is the instantiation of my <code>Context</code> module:</p> <pre><code>(** Instantiating a Process Table *) module Context : Context = struct type t = (string * process) list let empty = [] let lookup (ctx:t) (x:string): process= let chck = List.assoc_opt x ctx in match chck with |Some i -&gt; i |None -&gt; Null(&quot;&quot;) let extend (ctx:t) (x:string) (ty:process) = (x, ty) :: ctx let filter ctx x = List.remove_assoc x ctx end </code></pre> <p>I got this code from the Real World Ocaml book.</p>
[ { "answer_id": 74580138, "author": "Top-Master", "author_id": 8740349, "author_profile": "https://Stackoverflow.com/users/8740349", "pm_score": 2, "selected": false, "text": "$referenceNumber" }, { "answer_id": 74610024, "author": "Joy Zalte", "author_id": 11872534, "author_profile": "https://Stackoverflow.com/users/11872534", "pm_score": 2, "selected": true, "text": "$package->setDescription(\"box type : \".$box_type)" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20321674/" ]
74,303,900
<p>I don't understand how Haskell can destructure the array to a tuple</p> <p>e.g., why this works</p> <pre><code>head :: [a] -&gt; a head (x:xs) = x </code></pre> <p>But this does not work</p> <pre><code>head :: [a] -&gt; a head [x:xs] = x </code></pre> <p>it's unintuitive to me</p>
[ { "answer_id": 74303997, "author": "Willem Van Onsem", "author_id": 67579, "author_profile": "https://Stackoverflow.com/users/67579", "pm_score": 2, "selected": false, "text": "(x:xs)" }, { "answer_id": 74324700, "author": "Jon Purdy", "author_id": 246886, "author_profile": "https://Stackoverflow.com/users/246886", "pm_score": 3, "selected": true, "text": "head :: [a] -> a \nhead (x:xs) = x \n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3422861/" ]
74,303,934
<p>I've been trying to loop through the incoming data from a json serializer for a couple of weeks now. Tried a few different approaches, but i can't seem to loop through the json and return a list with all facility_id's for example. Ultimately i want to create one leadfacility object for each json item using it's facility_id and it's datetime. But I can't even seem to access the facility_id when using a for loop. The facilities that are being assigned are already inside the database.</p> <p>Does anyone know what I'm missing here? How can i loop though &quot;assigned_facilities&quot;? The only thing I am able to return is the entire json data all at once with print(). Or is my json data structured in the wrong way?</p> <pre><code>class LeadUpdateSerializer(serializers.ModelSerializer): assigned_facilities = serializers.JSONField(required=False, allow_null=True, write_only=True) def create(self, validated_data): assigned_facilities = validated_data.pop(&quot;assigned_facilities&quot;) instance = Lead.objects.create(**validated_data) for item in assigned_facilities: instance.leadfacility.create(assigned_facilities_id=assigned_facilities.get('facility_id'), datetime=assigned_facilities.get('datetime')) return instance </code></pre> <p>json</p> <pre><code>{ &quot;assigned_facilities&quot;: [{ &quot;facility_id&quot;: &quot;1&quot;, &quot;datetime&quot;: &quot;2018-12-19 09:26:03.478039&quot; }, { &quot;facility_id&quot;: &quot;1&quot;, &quot;datetime&quot;: &quot;2019-12-19 08:26:03.478039&quot; } ] } </code></pre> <p>models.py</p> <pre><code>class LeadFacilityAssign(models.Model): assigned_facilities = models.ForeignKey(Facility, on_delete=models.CASCADE, related_name='leadfacility') lead = models.ForeignKey(Lead, on_delete=models.CASCADE, related_name='leadfacility') datetime = models.DateTimeField(null=True, blank=True) class Facility(models.Model): name = models.CharField(max_length=150, null=True, blank=False) def __str__(self): return self.name class Lead(models.Model): first_name = models.CharField(max_length=40, null=True, blank=True) last_name = models.CharField(max_length=40, null=True, blank=True) def __str__(self): return f&quot;{self.first_name} {self.last_name}&quot; </code></pre>
[ { "answer_id": 74338498, "author": "Dimanshu Parihar", "author_id": 8459014, "author_profile": "https://Stackoverflow.com/users/8459014", "pm_score": 0, "selected": false, "text": "for item in assigned_facilities:\n instance.leadfacility.create(assigned_facilities_id=assigned_facilities.get('facility_id'), datetime=assigned_facilities.get('datetime'))\n" }, { "answer_id": 74352025, "author": "Ben L", "author_id": 16344708, "author_profile": "https://Stackoverflow.com/users/16344708", "pm_score": 0, "selected": false, "text": "for item in assigned_facilities:\n instance.leadfacility.create(assigned_facilities_id=item['facility_id'], datetime=item['datetime'])\n \n" }, { "answer_id": 74356482, "author": "Maz", "author_id": 20356680, "author_profile": "https://Stackoverflow.com/users/20356680", "pm_score": 0, "selected": false, "text": "pop()" }, { "answer_id": 74358946, "author": "Jovan Vuchkov", "author_id": 13774703, "author_profile": "https://Stackoverflow.com/users/13774703", "pm_score": 2, "selected": true, "text": "JSONField" }, { "answer_id": 74359527, "author": "gripep", "author_id": 8757925, "author_profile": "https://Stackoverflow.com/users/8757925", "pm_score": 0, "selected": false, "text": "LeadFacilityAssign" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3530084/" ]
74,303,953
<p>I am looking for a solution to run a sql script via the BigQueryInsertJobOperator operator. There are very few examples to be found online for that and the ones I tried have failed so far. Mainly I am getting <strong>jinja2.exceptions.TemplateNotFound</strong>: error.</p> <p>I have the following folder where I would like to save all my SQL scripts:</p> <p><strong>my_bucket/dags/my_other_folder/sql_scripts</strong></p> <p>I have used the <strong>template_searchpath</strong> attribute in the DAG's configuration:</p> <pre><code>with DAG( 'DE_test', schedule_interval=None, default_args=default_dag_args, catchup=False, template_searchpath='/home/airflow/dags' ) as dag: </code></pre> <p>and I have specified the filename in the BigQueryInsertJobOperator:</p> <pre><code>Transform = BigQueryInsertJobOperator( task_id='insert_data', configuration={ 'query': { 'query': &quot;{% include 'my_other_folder/test.sql' %}&quot;, 'useLegacySql': False } }, location='EU', ) </code></pre> <p>No matter what I do I keep getting jinja2.exceptions.TemplateNotFound: my_other_folder/test.sql error. What am I doing wrong?</p>
[ { "answer_id": 74338498, "author": "Dimanshu Parihar", "author_id": 8459014, "author_profile": "https://Stackoverflow.com/users/8459014", "pm_score": 0, "selected": false, "text": "for item in assigned_facilities:\n instance.leadfacility.create(assigned_facilities_id=assigned_facilities.get('facility_id'), datetime=assigned_facilities.get('datetime'))\n" }, { "answer_id": 74352025, "author": "Ben L", "author_id": 16344708, "author_profile": "https://Stackoverflow.com/users/16344708", "pm_score": 0, "selected": false, "text": "for item in assigned_facilities:\n instance.leadfacility.create(assigned_facilities_id=item['facility_id'], datetime=item['datetime'])\n \n" }, { "answer_id": 74356482, "author": "Maz", "author_id": 20356680, "author_profile": "https://Stackoverflow.com/users/20356680", "pm_score": 0, "selected": false, "text": "pop()" }, { "answer_id": 74358946, "author": "Jovan Vuchkov", "author_id": 13774703, "author_profile": "https://Stackoverflow.com/users/13774703", "pm_score": 2, "selected": true, "text": "JSONField" }, { "answer_id": 74359527, "author": "gripep", "author_id": 8757925, "author_profile": "https://Stackoverflow.com/users/8757925", "pm_score": 0, "selected": false, "text": "LeadFacilityAssign" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8543148/" ]
74,303,955
<p>I am new on React and I have the following use case: I have a JSON that I mapped out in a dynamically generated table I had no problem with that but now I want a popup to show up below the row in the table whenever I hover over a that row. This popup has to show additional information about the summarized info in the row.</p> <p>I generated to table in a component as follow:</p> <pre><code>function ScheduleComponent(props) { // Required hooks useEffect(() =&gt; { setSchedule(props.schedule); }, [props.schedule]); const handleMouseOver = () =&gt; { // I dont know what to do here }; const handleMouseOut = () =&gt; { //neither here }; const showAppointments = schedule.map((appointment, i) =&gt; { return ( &lt;tr&gt; &lt;td&gt;{appointment.hourOfService}&lt;/td&gt; { appointment.appointmentDto != null ? &lt;div&gt; &lt;td onMouseOver={handleMouseOver} onMouseOut={handleMouseOut} &gt;{appointment.appointmentDto.name}&lt;/td&gt; &lt;/div&gt; : &lt;td&gt;No hay citas programadas&lt;/td&gt; } &lt;/tr&gt; ); }); return ( &lt;div&gt; &lt;div&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th &gt; Hora &lt;/th&gt; &lt;th &gt; Descripcion &lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; {showAppointments} &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; ); } export default ScheduleComponent; </code></pre> <p>I get the JSON via props but this is not the problem. I automatically generate the table with the funtion <strong>showAppointments</strong></p> <p>The result in HTML is:</p> <p><a href="https://i.stack.imgur.com/o5LJi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o5LJi.png" alt="enter image description here" /></a></p> <p>Whenever I hover over an appointment I want to show additional info in a popup but just for that appointment row and set that popup below the row element. I had some ideas but whenever I hover over one name, a popup shows for every name ( the 4 names in this case, i mean 4 popups). Hence, is there a way to generate the table automatically and in some way condition the appearance of a popup just for one row.<br /> Thanks in advance!!! I really appreciate your time folks!</p>
[ { "answer_id": 74338498, "author": "Dimanshu Parihar", "author_id": 8459014, "author_profile": "https://Stackoverflow.com/users/8459014", "pm_score": 0, "selected": false, "text": "for item in assigned_facilities:\n instance.leadfacility.create(assigned_facilities_id=assigned_facilities.get('facility_id'), datetime=assigned_facilities.get('datetime'))\n" }, { "answer_id": 74352025, "author": "Ben L", "author_id": 16344708, "author_profile": "https://Stackoverflow.com/users/16344708", "pm_score": 0, "selected": false, "text": "for item in assigned_facilities:\n instance.leadfacility.create(assigned_facilities_id=item['facility_id'], datetime=item['datetime'])\n \n" }, { "answer_id": 74356482, "author": "Maz", "author_id": 20356680, "author_profile": "https://Stackoverflow.com/users/20356680", "pm_score": 0, "selected": false, "text": "pop()" }, { "answer_id": 74358946, "author": "Jovan Vuchkov", "author_id": 13774703, "author_profile": "https://Stackoverflow.com/users/13774703", "pm_score": 2, "selected": true, "text": "JSONField" }, { "answer_id": 74359527, "author": "gripep", "author_id": 8757925, "author_profile": "https://Stackoverflow.com/users/8757925", "pm_score": 0, "selected": false, "text": "LeadFacilityAssign" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13273596/" ]
74,303,959
<p><a href="https://i.stack.imgur.com/GyuZh.png" rel="nofollow noreferrer">This is what my dataframe looks like</a></p> <p>I have a dataframe of several columns and several rows per Participant_ID. I want to sum data for all lines of Participant_ID, to obtain one value per Participant_ID. The problem is that some columns are empty (all NAs), and for these columns I want to keep NA as a result. But when I sum with na.rm = T, it transforms the sum of NAs to 0.</p> <p>I am using :</p> <pre><code> df = df %&gt;% group_by(Participant_ID) %&gt;% summarise(across(where(is.numeric), ~ sum(.x, na.rm = T))) </code></pre> <p>How can I exclude columns (after group_by) with only NAs ? Or filter columns (after group_by) that contain at least one numeric value ?</p> <p>Thanks a lot for your help !!</p>
[ { "answer_id": 74304121, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 3, "selected": true, "text": "across" }, { "answer_id": 74305119, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 0, "selected": false, "text": "fsum" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20408112/" ]
74,303,974
<p>I am new to coding, and just started learning Python last week. I made this Powerball number generator to practice:</p> <pre><code>import random print(random.randrange(1, 70)) import random print(random.randrange(1,70)) import random print(random.randrange(1, 70)) import random print(random.randrange(1,70)) import random print(random.randrange(1, 70)) import random print(random.randrange(1,27)) </code></pre> <p><strong>I am wondering, how can I shorten this, since the first 5 &quot;import random prints&quot; are exactly identical?</strong></p> <p>Thanks ahead for helping a noob!</p>
[ { "answer_id": 74304027, "author": "yem", "author_id": 14789957, "author_profile": "https://Stackoverflow.com/users/14789957", "pm_score": 1, "selected": false, "text": "import random\n\nprint(random.randrange(1, 70))\n\nprint(random.randrange(1,70))\n\nprint(random.randrange(1, 70))\n\nprint(random.randrange(1,70))\n\nprint(random.randrange(1, 70))\n\nprint(random.randrange(1,27))\n" }, { "answer_id": 74304031, "author": "mikeb", "author_id": 1022260, "author_profile": "https://Stackoverflow.com/users/1022260", "pm_score": 0, "selected": false, "text": "import random" }, { "answer_id": 74304054, "author": "Michiel Janssen", "author_id": 20169332, "author_profile": "https://Stackoverflow.com/users/20169332", "pm_score": 0, "selected": false, "text": "import random\n\nfor x in range(0, 5):\n print(random.randrange(1, 70))\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20408195/" ]
74,303,978
<p>I have two columns and i wanted to display all the combinations of a single columns</p> <p>Table 1</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>column1</th> <th>column2</th> </tr> </thead> <tbody> <tr> <td>value</td> <td>145</td> </tr> <tr> <td>value</td> <td>146</td> </tr> <tr> <td>value2</td> <td>13</td> </tr> <tr> <td>value2</td> <td>56</td> </tr> <tr> <td>value2</td> <td>364</td> </tr> </tbody> </table> </div> <p><a href="https://i.stack.imgur.com/tm5T6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tm5T6.png" alt="enter image description here" /></a></p> <p>I have used selfjoin, but that doesnot workout.</p> <pre><code>SELECT a.column1 FROM table1 a CROSS JOIN table1 b where column1=&quot;value&quot; </code></pre> <p>Any suggestions would be appreciated</p>
[ { "answer_id": 74304999, "author": "Ozan Sen", "author_id": 19469088, "author_profile": "https://Stackoverflow.com/users/19469088", "pm_score": 1, "selected": true, "text": "CREATE TABLE Combination (Column1 VARCHAR(20), Column2 INT);\n\nINSERT INTO Combination VALUES ('value', 145), ('value', 146),('value2', 13), ('value2', 56), ('value2', 364);\n\n+---------+---------+\n| Column1 | Column2 |\n+---------+---------+\n| value | 145 |\n| value | 146 |\n| value2 | 13 |\n| value2 | 56 |\n| value2 | 364 |\n+---------+---------+\n5 rows in set (0.00 sec)\n" }, { "answer_id": 74309315, "author": "Lucky", "author_id": 20411709, "author_profile": "https://Stackoverflow.com/users/20411709", "pm_score": -1, "selected": false, "text": "CASE COLUMN2 ..\nTHEN\nEND...\nSELECT CONCAT(cte1.Column2, cte2.Column2) AS Result FROM cte1 CROSS\n JOIN cte2;\n\n| Result | \n| -------- | \n| 001- | \n| 123- |\n| 456- |\n| 789- |\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9629107/" ]
74,303,979
<pre class="lang-cs prettyprint-override"><code>Console.WriteLine(&quot;Here you can write the name as many as you want, and if u wanna end up just write No!&quot;); Console.WriteLine(&quot;\n&quot;); Console.WriteLine(&quot;Start writing a name:&quot;); string[] namnArray = new string[200]; for (int i = 0; i &lt; namnArray.Length; i++) { Console.ForegroundColor = ConsoleColor.Yellow; namnArray[i] = Console.ReadLine(); Console.ForegroundColor = ConsoleColor.White; Console.Write(&quot;Do u wanna write another one? &quot;); if (namnArray[i] == &quot;No&quot;) { Console.WriteLine(&quot;\n&quot;); Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine(&quot;write a name of your choice:&quot;); //Here i wanna know how many times a names used as the user wrote up there! //but dont know how to do it, if you wanna help me will be thankful! } } </code></pre> <p>I tried to make a new string variable as</p> <pre><code>string youChoice = Console.ReadLine(); </code></pre> <p>and then I don't know how to go further!</p>
[ { "answer_id": 74304082, "author": "Dmyto Holota", "author_id": 6895130, "author_profile": "https://Stackoverflow.com/users/6895130", "pm_score": -1, "selected": false, "text": "var number = Array.FindAll(namnArray, x => x == name ).Count();\n" }, { "answer_id": 74304302, "author": "phuzi", "author_id": 592958, "author_profile": "https://Stackoverflow.com/users/592958", "pm_score": 1, "selected": false, "text": "List<string>" }, { "answer_id": 74304580, "author": "Partha Thakura", "author_id": 5054850, "author_profile": "https://Stackoverflow.com/users/5054850", "pm_score": 0, "selected": false, "text": " Console.WriteLine(\"\\n\");\n Console.WriteLine(\"Start writing a name:\");\n string[] namnArray = new string[200];\n \n for (int i = 0; i < namnArray.Length; i++)\n {\n Console.ForegroundColor = ConsoleColor.Yellow;\n namnArray[i] = Console.ReadLine();\n Console.ForegroundColor = ConsoleColor.White;\n Console.Write(\"Do u wanna write another one? \");\n\n if (namnArray[i] == \"No\")\n {\n Console.WriteLine(\"\\n\");\n Console.ForegroundColor = ConsoleColor.Magenta;\n Console.WriteLine(\"write a name of your choice:\");\n var names = string.Join(\"\", namnArray);\n var input = Console.ReadLine();\n var count = Regex.Matches(names, input).Count;\n Console.WriteLine(\"The number of ocurance is \" + count);\n\n }\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74303979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18783323/" ]
74,304,006
<p>This is my first question so sorry if it's dumb. I'm trying to do the classic FizzBuzz exercise in the console using javascrypt, putting the changes into an array for 1 to 100. So far:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let nums = []; for (let i = 1; i &lt;= 100; i++) { nums.push(i); } for (num of nums) { if (nums[num] % 5 === 0) { nums[num] = "Buzz"; console.log("Buzz"); } else if (nums[num] % 3 === 0) { nums[num] = "Fizz"; console.log("Fizz"); } else if (nums[num] % 3 === 0 &amp;&amp; nums[num] % 5 === 0) { nums[num] = "FizzBuzz"; console.log("FizzBuzz"); } else { console.log(nums[num]); } }</code></pre> </div> </div> </p> <p>I'm expecting each FizzBuzz to be put into the array instead of the number, and all the array to be printed on the console. But for some specific numbers it doesn't work. When two vales need to be changed consequently, the second one gives some kind of error. What am i missing?</p> <p>Thanks for your help!</p>
[ { "answer_id": 74304082, "author": "Dmyto Holota", "author_id": 6895130, "author_profile": "https://Stackoverflow.com/users/6895130", "pm_score": -1, "selected": false, "text": "var number = Array.FindAll(namnArray, x => x == name ).Count();\n" }, { "answer_id": 74304302, "author": "phuzi", "author_id": 592958, "author_profile": "https://Stackoverflow.com/users/592958", "pm_score": 1, "selected": false, "text": "List<string>" }, { "answer_id": 74304580, "author": "Partha Thakura", "author_id": 5054850, "author_profile": "https://Stackoverflow.com/users/5054850", "pm_score": 0, "selected": false, "text": " Console.WriteLine(\"\\n\");\n Console.WriteLine(\"Start writing a name:\");\n string[] namnArray = new string[200];\n \n for (int i = 0; i < namnArray.Length; i++)\n {\n Console.ForegroundColor = ConsoleColor.Yellow;\n namnArray[i] = Console.ReadLine();\n Console.ForegroundColor = ConsoleColor.White;\n Console.Write(\"Do u wanna write another one? \");\n\n if (namnArray[i] == \"No\")\n {\n Console.WriteLine(\"\\n\");\n Console.ForegroundColor = ConsoleColor.Magenta;\n Console.WriteLine(\"write a name of your choice:\");\n var names = string.Join(\"\", namnArray);\n var input = Console.ReadLine();\n var count = Regex.Matches(names, input).Count;\n Console.WriteLine(\"The number of ocurance is \" + count);\n\n }\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74304006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20408218/" ]
74,304,012
<p>I am trying to create a sorted map using <code>TreeMap&lt;String, Integer&gt;</code> from an existing map in java.</p> <p>Entries should be sorted based on value, so I created a custom <code>Comparator</code>.</p> <pre><code>class ValueComparator implements Comparator&lt;String&gt; { Map&lt;String, Integer&gt; base; ValueComparator(Map&lt;String, Integer&gt; base) { this.base = base; } @Override public int compare(String o1, String o2) { return base.get(o2).compareTo(base.get(o1)); } } class Test { public static void main(String[] args) { Map&lt;String, Integer&gt; map = new HashMap&lt;&gt;(); map.put(&quot;a&quot;, 100); map.put(&quot;b&quot;, 100); map.put(&quot;c&quot;, 200); map.put(&quot;d&quot;, 300); map.put(&quot;e&quot;, 400); SortedMap&lt;String, Integer&gt; sortedMap = new TreeMap&lt;&gt;(new ValueComparator(map)); sortedMap.putAll(map); System.out.println(map); System.out.println(sortedMap); } } </code></pre> <p><em>Output</em></p> <pre><code>{a=100, b=100, c=200, d=300, e=400} {e=400, d=300, c=200, a=100} </code></pre> <p>As you can see, my <code>sortedMap</code> has removed one key having the same value. Can someone explain this? And how can we fix this?</p>
[ { "answer_id": 74304136, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 1, "selected": false, "text": "Comparator" }, { "answer_id": 74304307, "author": "Murat Karagöz", "author_id": 4467208, "author_profile": "https://Stackoverflow.com/users/4467208", "pm_score": -1, "selected": false, "text": "public int compare(String o1, String o2) {\n int val = base.get(o2).compareTo(base.get(o1));\n return val == 0 ? o1.compareTo(o2) : val;\n}\n" } ]
2022/11/03
[ "https://Stackoverflow.com/questions/74304012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4063455/" ]