qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,564,064
<p>I want to jump from def number1 to def number2. I tried this:</p> <pre><code>def number1(): print(&quot;from here to &quot;) number2() number1() def blablabla(): print(&quot;blablabla&quot;) blablabla() def number2(): print(&quot;here&quot;) number2() </code></pre> <p>but I received this error:</p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\i5 9400f\Documents\projetos python\test.py&quot;, line 4, in &lt;module&gt; number1() File &quot;C:\Users\i5 9400f\Documents\projetos python\test.py&quot;, line 3, in number1 number2() ^^^^^^^ NameError: name 'number2' is not defined. Did you mean: 'number1'? from here to Process finished with exit code 1 </code></pre> <p>I tried using the number2() it did not work</p>
[ { "answer_id": 74564142, "author": "Xiidref", "author_id": 11260467, "author_profile": "https://Stackoverflow.com/users/11260467", "pm_score": 2, "selected": true, "text": "def number1():\n print(\"from here to \")\n number2()\n\ndef blablabla():\n print(\"blablabla\")\n\ndef number2():\n print(\"here\")\n\nnumber1()\nblablabla()\nnumber2()\n" }, { "answer_id": 74564193, "author": "zyroxxx", "author_id": 20592878, "author_profile": "https://Stackoverflow.com/users/20592878", "pm_score": 0, "selected": false, "text": "def number1():\n print(\"from here to \")\n number2()\n\ndef number2():\n print(\"here\")\n\ndef blablabla():\n print(\"blablabla\")\n\nnumber1()\nblablabla()\nnumber2()\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20592582/" ]
74,564,068
<p>I was trying to create a blog app by following an online Django tutorial and while I was testing the sign-up page, I ran into a Value Error saying that the view did not return a HTTP response object. i tried everything but i could not find the answer as i am not a Django expert</p> <p>in the users app's views.py file was the code that threw the error</p> <pre><code>from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') messages.success(request, f'Account Created for {username}') return redirect('blog-home') else: form = UserCreationForm() return render(request, 'users/register.html', {'form': form}) </code></pre> <p>and this is the register template</p> <pre><code>{% extends &quot;myblog/base.html&quot; %} {% block content %} &lt;div class=&quot;content-section&quot;&gt; &lt;form method=&quot;POST&quot;&gt; {% csrf_token %} &lt;fieldset class=&quot;form-group&quot;&gt; &lt;legend class=&quot;border-bottom mb-4&quot;&gt; Join Today! &lt;/legend&gt; {{ form.as_p }} &lt;/fieldset&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;button class=&quot;btn btn-outline-info&quot; type=&quot;submit&quot;&gt; Sign Up! &lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;div class=&quot;border-top pt-3&quot;&gt; &lt;small class=&quot;text-muted&quot;&gt; Already Have an account? &lt;a href=&quot;#&quot; class=&quot;ml-2&quot;&gt;Sign In!&lt;/a&gt; &lt;/small&gt; &lt;/div&gt; &lt;/div&gt; {% endblock content%} </code></pre> <p>And this is the file structure of the project <a href="https://i.stack.imgur.com/olYOh.png" rel="nofollow noreferrer">File Structure</a></p>
[ { "answer_id": 74564142, "author": "Xiidref", "author_id": 11260467, "author_profile": "https://Stackoverflow.com/users/11260467", "pm_score": 2, "selected": true, "text": "def number1():\n print(\"from here to \")\n number2()\n\ndef blablabla():\n print(\"blablabla\")\n\ndef number2():\n print(\"here\")\n\nnumber1()\nblablabla()\nnumber2()\n" }, { "answer_id": 74564193, "author": "zyroxxx", "author_id": 20592878, "author_profile": "https://Stackoverflow.com/users/20592878", "pm_score": 0, "selected": false, "text": "def number1():\n print(\"from here to \")\n number2()\n\ndef number2():\n print(\"here\")\n\ndef blablabla():\n print(\"blablabla\")\n\nnumber1()\nblablabla()\nnumber2()\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20592802/" ]
74,564,096
<p>I have a function which groups anagrams together</p> <pre class="lang-js prettyprint-override"><code>function groupAnagrams(strs) { let result = {}; for (let word of strs) { let cleansed = word.split(&quot;&quot;).sort().join(&quot;&quot;); if (result[cleansed]) { result[cleansed].push(word); } else { result[cleansed] = [word]; } } console.log(Object.values(result)); return Object.values(result); } </code></pre> <p>it prints the results in the following format</p> <pre class="lang-js prettyprint-override"><code>[ [ 'abc', 'bac', 'cba' ], [ 'fun', 'fun', 'unf' ], [ 'hello' ] ] </code></pre> <p>However I would like the output to look like the following</p> <pre><code>abc, bac, cba fun, fun, unf hello </code></pre> <p>How can I achieve this?</p>
[ { "answer_id": 74564166, "author": "R4ncid", "author_id": 14326899, "author_profile": "https://Stackoverflow.com/users/14326899", "pm_score": 3, "selected": true, "text": "const data = [ [ 'abc', 'bac', 'cba' ], [ 'fun', 'fun', 'unf' ], [ 'hello' ] ]\n\ndata.forEach(row => console.log(row.join(', ')))\n//or\n\nconsole.log(data.map(row => row.join(', ')).join('\\n'))" }, { "answer_id": 74564249, "author": "Teneff", "author_id": 637367, "author_profile": "https://Stackoverflow.com/users/637367", "pm_score": 1, "selected": false, "text": "os.EOL const { EOL } = require('os');\nconst lines = [ [ 'abc', 'bac', 'cba' ], [ 'fun', 'fun', 'unf' ], [ 'hello' ] ];\n\nconst output = lines.map((words) => words.join(', ')).join(EOL);\n\nprocess.stdout.write(output);\n\n" }, { "answer_id": 74564335, "author": "Relcode", "author_id": 8500718, "author_profile": "https://Stackoverflow.com/users/8500718", "pm_score": 0, "selected": false, "text": "function groupAnagram(arr){\n let res = '';\n arr.map(function(item){\n res += `${item.join(', ')} \\n\\n`\n })\n console.log(res)\n}\n\ngroupAnagram([ [ 'abc', 'bac', 'cba' ], [ 'fun', 'fun', 'unf' ], [ 'hello' ] ]\n);" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19940752/" ]
74,564,118
<p><code>std::reference_wrapper</code> cannot be bound to rvalue reference to prevent dangling pointer. However, with combination of <code>std::optional</code>, it seems that rvalue could be bound.</p> <p>That is, <code>std::is_constructible_v&lt;std::reference_wrapper&lt;const int&gt;, int&amp;&amp;&gt;)</code> is <code>false</code> but <code>std::is_constructible_v&lt;std::optional&lt;std::reference_wrapper&lt;const int&gt;&gt;, std::optional&lt;int&gt;&amp;&amp;&gt;</code> is <code>true</code>.</p> <p>Here's an example:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;optional&gt; auto make() -&gt; std::optional&lt;int&gt; { return 3; } int main() { std::optional&lt;std::reference_wrapper&lt;const int&gt;&gt; opt = make(); if (opt) std::cout &lt;&lt; opt-&gt;get() &lt;&lt; std::endl; return 0; } </code></pre> <p>I expected this code will be rejected by compiler, but it compiles well and <code>opt</code> contains dangling pointer.</p> <p>Is this a bug of standard library? Or, is it just not possible to prevent dangling pointer here because of some kind of limitaion of C++ language specification?</p> <p>If it is a bug of standard library, how can I fix it when I implement my own <code>optional</code> type?</p> <p>It it's a limitation of current C++ specification, could you tell me where this problem comes from?</p>
[ { "answer_id": 74567461, "author": "Ranoiaetep", "author_id": 12861639, "author_profile": "https://Stackoverflow.com/users/12861639", "pm_score": 2, "selected": false, "text": "optional const& auto ref = std::cref(static_cast<const int&>(1));\n" }, { "answer_id": 74567981, "author": "Brian Bi", "author_id": 481267, "author_profile": "https://Stackoverflow.com/users/481267", "pm_score": 3, "selected": true, "text": "std::optional<T> template <class U>\nconstexpr optional(const optional<U>& other)\nrequires std::is_constructible_v<T, const U&>; // 1\n\ntemplate <class U>\nconstexpr optional(optional<U>&& other);\nrequires std::is_constructible_v<T, U>; // 2\n std::is_constructible_v std::reference_wrapper<const int> int int std::reference_wrapper<const int> const int& const int U std::optional<int> const optional<U>& optional template <class V>\nconstexpr optional(V&& other)\nrequires (is_derived_from_optional_v<std::remove_cvref_t<V>> && see_below) // 3\n is_derived_from_optional optional optional V U optional V const_cast<std::remove_cv_t<V>&&>(other) const const reference_wrapper" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2580815/" ]
74,564,148
<p>I want to be able to run my Cypress scripts on any URL by modifying the value of <code>baseUrl</code> but the command doesn't change it.</p> <pre><code>&quot;cypress open --env version=development --config baseUrl=https://google.com&quot; </code></pre> <p>I have tried env variable too but that also doesn't work:</p> <pre><code>&quot;cypress:open:dev&quot;: &quot;cypress open --env version=development,baseUrl=https://google.com&quot; </code></pre> <p>Config file:</p> <pre><code>export default defineConfig({ e2e: { async setupNodeEvents(on, config) { const version = config.env.version || 'development' const configFile = await import(path.join( config.projectRoot, 'cypress/config', `${version}.json` )); const credentialsFile = await import(path.join( config.projectRoot, 'cypress/config', 'credentials.json' )); config = { ...config, // take config defined in this file ...configFile // merge/override from the external file } config.env = { ...config.env, // 2nd level merge ...credentialsFile[version] // from git-ignored file } config.baseUrl = configFile.baseUrl return config }, reporter: 'mochawesome' }, }); </code></pre> <p>development.json:</p> <pre><code>{ &quot;env&quot;: { &quot;baseUrl&quot;: &quot;https://test.com&quot;, } } </code></pre>
[ { "answer_id": 74564842, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 0, "selected": false, "text": "\"cypress:open:dev\": \"CYPRESS_BASE_URL=https://google.com cypress open --env version=development\"\n" }, { "answer_id": 74565621, "author": "Fody", "author_id": 16997707, "author_profile": "https://Stackoverflow.com/users/16997707", "pm_score": 2, "selected": false, "text": "setupNodeEvents() config.baseUrl = configFile.baseUrl config.baseUrl = config.baseUrl || configFile.baseUrl\n export default defineConfig({\n e2e: {\n baseUrl: \"some-hard-coded-url\",\n undefined configFile.baseUrl --env config configFile config.env development.json config = {\n ...config, // env from command-line overrides are on .env property \n ...configFile // env from external file replaces that property entirely\n}\n config.env || const env = {...config.env}\nconfig = {...config,...configFile}\nconfig.env = {...env,...credentialsFile[version]}\n\nconfig.baseUrl = config.env.baseUrl || configFile.env.baseUrl \n baseUrl: 'https://google.com' \"cypress:open:dev\": \"cypress open --env version=development,baseUrl=https://google.com\"\n baseUrl: 'https://test.com' \"cypress:open\": \"cypress open\"\n development.json env baseUrl configFile.baseUrl configFile.env.baseUrl" }, { "answer_id": 74594154, "author": "Chloe", "author_id": 20617867, "author_profile": "https://Stackoverflow.com/users/20617867", "pm_score": 2, "selected": false, "text": "config.env export default defineConfig({\n e2e: {\n async setupNodeEvents(on, config) {\n ...\n config = {\n ...config, // take config defined in this file\n ...configFile, // merge/override from the external file\n env: {...config.env} // don't merge env\n }\n ...\n return config\n },\n reporter: 'mochawesome',\n // baseUrl: 'http://example.com', // cannot use this with above merge!!\n },\n})\n baseUrl development.json env.baseUrl development.json {\n \"baseUrl\": \"https://test.com\",\n}\n" }, { "answer_id": 74616466, "author": "George", "author_id": 4405472, "author_profile": "https://Stackoverflow.com/users/4405472", "pm_score": 1, "selected": true, "text": "development.json \"cypress:open:dev\": \"CYPRESS_BASE_URL=$URL cypress open --env version=development\"\n config.baseUrl = config.baseUrl || configFile.env.baseUrl\n cy.visit(Cypress.env('baseUrl'))\n cy.visit('')\n baseUrl URL=\"https://google.com/ npm run cypress:open:dev baseUrl" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4405472/" ]
74,564,164
<p>I have a scenario where i will be getting a datatable with multiple rows of data (sometimes in thousands) and i need to process the data row by row. While processing the data row by row, initially i need to call an ONprem sql DB where in i will call a stored procedure with input and output parameters and once the SP is executed i need to fetch the output data and update another table which is in another Azure sql DB as per the output parameter.</p> <p>The issue is, when i use USING, i feel like it opens and closes the connection once for each row for each of the two databases and if there are 1000 rows of data then it might open and close DB1 10000 each and DB2 1000 each which takes much time and server hits.</p> <p>How can i minimize this and may be keep the connection open until it does everything in the foreach loop.</p> <p>Below is the sample code snippet-</p> <pre><code>public void Main() { //Declare Variables int InputID; string OutputProcessedMsg; string SqlConn = &quot;Data Source=xyx.com;Initial Catalog=ddddd;Provider=SQLNCLI11.1;Integrated Security=SSPI&quot;; string AzureSqlConn = &quot;Data Source=vvvv.dev.com;Initial Catalog=yyyy;Provider=SQLNCLI11.1;Integrated Security=SSPI&quot;; Object AllData = Dts.Variables[&quot;User::VarAllPowerAppData&quot;].Value; // this gets the data object and sets it to a data table OleDbDataAdapter A = new OleDbDataAdapter(); System.Data.DataTable dt = new System.Data.DataTable(); A.Fill(dt, AllData); //DataTable sourceTable = dt; foreach (DataRow dr in dt.Rows) { InputID = Convert.ToInt32(dr[0]); using (SqlConnection conn = new SqlConnection(SqlConn)) { using (SqlCommand cmd = new SqlCommand(&quot;UpdateDataOnpremSQL&quot;, conn)) { cmd.CommandType = CommandType.StoredProcedure; // set up the parameters and it's values cmd.Parameters.Add(&quot;@ID&quot;, SqlDbType.VarChar,15).Value = InputDealerID; cmd.Parameters.Add(&quot;@ProcessedMsg&quot;, SqlDbType.VarChar,-1).Direction = ParameterDirection.Output; conn.Open(); cmd.ExecuteNonQuery(); OutputProcessedMsg = Convert.ToString(cmd.Parameters[&quot;@ProcessedMsg&quot;].Value); conn.Close(); } } using (OleDbConnection Oconn = new OleDbConnection(AzureSqlConn)) { using (OleDbCommand cmd = new OleDbCommand(&quot;UpdateDataAzureSQL&quot;, Oconn)) { cmd.CommandType = CommandType.StoredProcedure; // set up the parameters and it's values cmd.Parameters.AddWithValue(&quot;@ID&quot;, SqlDbType.VarChar).Value = InputDealerID; cmd.Parameters.AddWithValue(&quot;@ProcessedMsg&quot;, SqlDbType.VarChar).Value = OutputProcessedMsg; Oconn.Open(); cmd.ExecuteNonQuery(); Oconn.Close(); } } } } </code></pre> <p>I have tried this connection pooling but it seems like for every row it would hit the db , open and close connections which would affect DB server performance and hence wanted something where the connection will be open and the process is faster while switching to DB's until end of foreach loop of Databtable</p>
[ { "answer_id": 74564267, "author": "SNBS", "author_id": 20426120, "author_profile": "https://Stackoverflow.com/users/20426120", "pm_score": 3, "selected": true, "text": "foreach Declare Variables" }, { "answer_id": 74564378, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 1, "selected": false, "text": "public void Main()\n{\n\n //Declare Variables\n int InputID;\n string OutputProcessedMsg;\n string SqlConn = \"Data Source=xyx.com;Initial Catalog=ddddd;Provider=SQLNCLI11.1;Integrated Security=SSPI\";\n SqlConnection conn = new SqlConnection(SqlConn);\n \n string AzureSqlConn = \"Data Source=vvvv.dev.com;Initial Catalog=yyyy;Provider=SQLNCLI11.1;Integrated Security=SSPI\";\n OleDbConnection Oconn = new OleDbConnection(AzureSqlConn);\n \n Object AllData = Dts.Variables[\"User::VarAllPowerAppData\"].Value;\n // open all connections only once\n conn.Open();\n Oconn.Open();\n // this gets the data object and sets it to a data table\n OleDbDataAdapter A = new OleDbDataAdapter();\n System.Data.DataTable dt = new System.Data.DataTable();\n A.Fill(dt, AllData);\n //DataTable sourceTable = dt;\n\n foreach (DataRow dr in dt.Rows)\n {\n InputID = Convert.ToInt32(dr[0]);\n\n using (SqlCommand cmd = new SqlCommand(\"UpdateDataOnpremSQL\", conn))\n {\n cmd.CommandType = CommandType.StoredProcedure;\n // set up the parameters and it's values\n cmd.Parameters.Add(\"@ID\", SqlDbType.VarChar, 15).Value = InputID;\n cmd.Parameters.Add(\"@ProcessedMsg\", SqlDbType.VarChar, -1).Direction = ParameterDirection.Output;\n \n cmd.ExecuteNonQuery();\n OutputProcessedMsg = (string)cmd.Parameters[\"@ProcessedMsg\"].Value;\n\n\n }\n\n\n using (OleDbCommand cmd = new OleDbCommand(\"UpdateDataAzureSQL\", Oconn))\n {\n cmd.CommandType = CommandType.StoredProcedure;\n // set up the parameters and it's values\n cmd.Parameters.AddWithValue(\"@ID\", SqlDbType.VarChar).Value = InputID;\n cmd.Parameters.AddWithValue(\"@ProcessedMsg\", SqlDbType.VarChar).Value = OutputProcessedMsg;\n \n cmd.ExecuteNonQuery();\n \n }\n }\n conn.Close();\n Oconn.Close();\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10838358/" ]
74,564,176
<p>I wonder if I can catch up with custom event (EventEmiter). I have a child component that emit event with @Output('myCustomEvent).</p> <p>Can I catch it in my parent component with @HostListener('myCustomEvent') ?</p> <p>I try to di this so I get rid of the (myCustomEvent)=&quot;myMethod&quot; in my html, which I think my be better (cleaner html code).</p> <p>Can I do that ?</p> <p>Thank you ahead for your help :)</p>
[ { "answer_id": 74564267, "author": "SNBS", "author_id": 20426120, "author_profile": "https://Stackoverflow.com/users/20426120", "pm_score": 3, "selected": true, "text": "foreach Declare Variables" }, { "answer_id": 74564378, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 1, "selected": false, "text": "public void Main()\n{\n\n //Declare Variables\n int InputID;\n string OutputProcessedMsg;\n string SqlConn = \"Data Source=xyx.com;Initial Catalog=ddddd;Provider=SQLNCLI11.1;Integrated Security=SSPI\";\n SqlConnection conn = new SqlConnection(SqlConn);\n \n string AzureSqlConn = \"Data Source=vvvv.dev.com;Initial Catalog=yyyy;Provider=SQLNCLI11.1;Integrated Security=SSPI\";\n OleDbConnection Oconn = new OleDbConnection(AzureSqlConn);\n \n Object AllData = Dts.Variables[\"User::VarAllPowerAppData\"].Value;\n // open all connections only once\n conn.Open();\n Oconn.Open();\n // this gets the data object and sets it to a data table\n OleDbDataAdapter A = new OleDbDataAdapter();\n System.Data.DataTable dt = new System.Data.DataTable();\n A.Fill(dt, AllData);\n //DataTable sourceTable = dt;\n\n foreach (DataRow dr in dt.Rows)\n {\n InputID = Convert.ToInt32(dr[0]);\n\n using (SqlCommand cmd = new SqlCommand(\"UpdateDataOnpremSQL\", conn))\n {\n cmd.CommandType = CommandType.StoredProcedure;\n // set up the parameters and it's values\n cmd.Parameters.Add(\"@ID\", SqlDbType.VarChar, 15).Value = InputID;\n cmd.Parameters.Add(\"@ProcessedMsg\", SqlDbType.VarChar, -1).Direction = ParameterDirection.Output;\n \n cmd.ExecuteNonQuery();\n OutputProcessedMsg = (string)cmd.Parameters[\"@ProcessedMsg\"].Value;\n\n\n }\n\n\n using (OleDbCommand cmd = new OleDbCommand(\"UpdateDataAzureSQL\", Oconn))\n {\n cmd.CommandType = CommandType.StoredProcedure;\n // set up the parameters and it's values\n cmd.Parameters.AddWithValue(\"@ID\", SqlDbType.VarChar).Value = InputID;\n cmd.Parameters.AddWithValue(\"@ProcessedMsg\", SqlDbType.VarChar).Value = OutputProcessedMsg;\n \n cmd.ExecuteNonQuery();\n \n }\n }\n conn.Close();\n Oconn.Close();\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7698722/" ]
74,564,182
<p>By running the procedure through the command line, pointing it to the input file like this</p> <pre><code>_progres -b -p test.p &lt; test.txt </code></pre> <p>I can read the contents of test.txt into test.p with a simple</p> <pre><code>def var cline as c no-undo. _tt: do while true on endkey undo _tt,leave _tt: import unformatted cline. end. </code></pre> <p>However, if i don't pass a file to test.p, then without an explicitly open input, the error will be ** Attempt to read with no current source of input. (513). How to determine that a procedure was passed a file as input.</p>
[ { "answer_id": 74574675, "author": "Tom Bascom", "author_id": 123238, "author_profile": "https://Stackoverflow.com/users/123238", "pm_score": 3, "selected": true, "text": "/* isatty.i\n */\n \nfunction isatty returns logical () in super.\n /* isatty.p\n * \n * to use this:\n *\n * run isatty.p persistent\n *\n * {isatty.i}\n * message isatty().\n *\n */\n\n&IF \"{&PROCESS-ARCHITECTURE}\" = \"64\" &THEN\n &global-define XINT int64\n &global-define LONGINT int64\n &global-define PUTLONGINT PUT-INT64\n &global-define GETLONGINT GET-INT64\n &ELSE\n &global-define XINT integer\n &global-define LONGINT long\n &global-define PUTLONGINT PUT-LONG\n &global-define GETLONGINT GET-LONG\n&ENDIF\n\ndefine stream inStrm.\n\nsession:add-super-procedure( this-procedure ).\n\nreturn.\n\n\nprocedure GetFileType external \"kernel32.dll\":\n define input parameter fileHandle as {&LONGINT}.\n define return parameter result as {&LONGINT}.\nend.\n\nprocedure GetStdHandle external \"kernel32.dll\":\n define input parameter fileHandle as {&LONGINT}.\n define return parameter result as {&LONGINT}.\nend.\n\n\n/* determine if we are running with user input or redirected input\n *\n */\n\nfunction isatty returns logical ():\n\n define variable result as logical no-undo.\n define variable tty as character no-undo.\n define variable fileHandle as int64 no-undo.\n define variable fileType as int64 no-undo.\n\n result = false.\n\n if opsys = \"unix\" then\n do:\n\n input stream inStrm through value( \"tty\" ).\n import stream inStrm unformatted tty.\n input stream inStrm close.\n if tty begins \"/dev/\" then\n result = true.\n\n end.\n else\n do:\n\n /* Windows stdin = -10 */\n\n run getStdHandle( -10, output fileHandle ).\n\n run getFileType( fileHandle, output fileType ).\n\n /* 0x0000 = unknown\n * 0x0001 = disk\n * 0x0002 = character (CON or LPT etc)\n * 0x0003 = pipe\n * 0x8000 = remote (unused?)\n */\n\n if fileType = 2 then\n result = true.\n\n end.\n\n return result.\n\nend.\n /* testtty.p\n */\n\nrun isatty.p persistent.\n \n{isatty.i}\nmessage isatty().\n \nquit.\n $ pro -p testtty.p\nyes\n $ cat /dev/null | pro -b -p testtty.p > tty.out\n$ cat tty.out\nno\n $ pro -b -p testtty.p > tty.out\n$ cat tty.out\nyes\n" }, { "answer_id": 74612740, "author": "Александр Овчинников", "author_id": 4846049, "author_profile": "https://Stackoverflow.com/users/4846049", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <string>\nusing namespace std;\nint main()\n{\n int i,l;\n string str;\n fseek(stdin, 0, SEEK_END);\n i = ftell(stdin);\n if (i == 0)\n return 0;\n fseek(stdin, 0, SEEK_SET);\n for (std::string line; std::getline(std::cin, line);) {\n std::cout << line << std::endl;\n }\n return 0;\n}\n DEFINE VARIABLE c AS C. \ndefine stream sin.\ninput stream sin through VALUE('[ ! -t 0 ] && echo $(</dev/stdin) || echo \"\"').\nDO WHILE TRUE ON ENDKEY UNDO,LEAVE:\n import stream sin unformatted c.\n MESSAGE c. PAUSE 0.\n END.\ninput stream sin close.\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4846049/" ]
74,564,241
<p>I've a 5x5 2D array filled like this :</p> <pre><code> ----- ----- ----- ----- </code></pre> <p>I'm trying to fill this array by percentage, for example <strong>40%</strong> :</p> <pre><code>-e--e ---f- -i-h- -ghh- ---ii </code></pre> <p>As you can see 40 % of 25 is 10 so 10 characters have been added to the array, my code is :</p> <pre><code> private static char[][] fillArrayWithThisPercentage(int percentage, char[][] arrayOfChars, char startChar, char endChar) { int size = 5; int arraySize = size * size; float percentageOfSize = (percentage / 100f * arraySize); int filled = 0; while (filled &lt;= percentageOfSize) { int i = getRandomNumber(size); int j = getRandomNumber(size); arrayOfChars[i][j] = getRandomChar(startChar, endChar); filled++; } } </code></pre> <p>Get a random character in range of two characters :</p> <pre><code>private static char getRandomChar(char startChar, char endChar) { String alphabet = &quot;a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z&quot;; List&lt;String&gt; alphabetList = Arrays.asList(alphabet.split(&quot;,&quot;)); int max = alphabetList.indexOf(startChar + &quot;&quot;); int min = alphabetList.indexOf(endChar + &quot;&quot;); int randomNumber = (int) ((Math.random() * (max - min)) + min); return alphabetList.get(randomNumber).charAt(0); } </code></pre> <p>Output :</p> <pre><code>b---- --db- --a-- ----- a---- </code></pre>
[ { "answer_id": 74574675, "author": "Tom Bascom", "author_id": 123238, "author_profile": "https://Stackoverflow.com/users/123238", "pm_score": 3, "selected": true, "text": "/* isatty.i\n */\n \nfunction isatty returns logical () in super.\n /* isatty.p\n * \n * to use this:\n *\n * run isatty.p persistent\n *\n * {isatty.i}\n * message isatty().\n *\n */\n\n&IF \"{&PROCESS-ARCHITECTURE}\" = \"64\" &THEN\n &global-define XINT int64\n &global-define LONGINT int64\n &global-define PUTLONGINT PUT-INT64\n &global-define GETLONGINT GET-INT64\n &ELSE\n &global-define XINT integer\n &global-define LONGINT long\n &global-define PUTLONGINT PUT-LONG\n &global-define GETLONGINT GET-LONG\n&ENDIF\n\ndefine stream inStrm.\n\nsession:add-super-procedure( this-procedure ).\n\nreturn.\n\n\nprocedure GetFileType external \"kernel32.dll\":\n define input parameter fileHandle as {&LONGINT}.\n define return parameter result as {&LONGINT}.\nend.\n\nprocedure GetStdHandle external \"kernel32.dll\":\n define input parameter fileHandle as {&LONGINT}.\n define return parameter result as {&LONGINT}.\nend.\n\n\n/* determine if we are running with user input or redirected input\n *\n */\n\nfunction isatty returns logical ():\n\n define variable result as logical no-undo.\n define variable tty as character no-undo.\n define variable fileHandle as int64 no-undo.\n define variable fileType as int64 no-undo.\n\n result = false.\n\n if opsys = \"unix\" then\n do:\n\n input stream inStrm through value( \"tty\" ).\n import stream inStrm unformatted tty.\n input stream inStrm close.\n if tty begins \"/dev/\" then\n result = true.\n\n end.\n else\n do:\n\n /* Windows stdin = -10 */\n\n run getStdHandle( -10, output fileHandle ).\n\n run getFileType( fileHandle, output fileType ).\n\n /* 0x0000 = unknown\n * 0x0001 = disk\n * 0x0002 = character (CON or LPT etc)\n * 0x0003 = pipe\n * 0x8000 = remote (unused?)\n */\n\n if fileType = 2 then\n result = true.\n\n end.\n\n return result.\n\nend.\n /* testtty.p\n */\n\nrun isatty.p persistent.\n \n{isatty.i}\nmessage isatty().\n \nquit.\n $ pro -p testtty.p\nyes\n $ cat /dev/null | pro -b -p testtty.p > tty.out\n$ cat tty.out\nno\n $ pro -b -p testtty.p > tty.out\n$ cat tty.out\nyes\n" }, { "answer_id": 74612740, "author": "Александр Овчинников", "author_id": 4846049, "author_profile": "https://Stackoverflow.com/users/4846049", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <string>\nusing namespace std;\nint main()\n{\n int i,l;\n string str;\n fseek(stdin, 0, SEEK_END);\n i = ftell(stdin);\n if (i == 0)\n return 0;\n fseek(stdin, 0, SEEK_SET);\n for (std::string line; std::getline(std::cin, line);) {\n std::cout << line << std::endl;\n }\n return 0;\n}\n DEFINE VARIABLE c AS C. \ndefine stream sin.\ninput stream sin through VALUE('[ ! -t 0 ] && echo $(</dev/stdin) || echo \"\"').\nDO WHILE TRUE ON ENDKEY UNDO,LEAVE:\n import stream sin unformatted c.\n MESSAGE c. PAUSE 0.\n END.\ninput stream sin close.\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13739336/" ]
74,564,245
<p>I have the following code.</p> <p>I am trying to loop through columns of a dataframe <strong>(newerdf)</strong> and plot a <strong>histogram</strong> for each one.</p> <p>I am then saving each plot as a .png file on my desktop.</p> <p>However, the following code gives me the error: <strong>'numpy.ndarray' object has no attribute 'tick_params'.</strong></p> <p>I would be so grateful for a helping hand!</p> <pre><code>listedvariables = ['distance','age'] for i in range(0,len(listedvariables)): x = newerdf[[listedvariables[i]]].hist(figsize=(50,50)) x.tick_params(axis='x',labelsize=60) x.tick_params(axis='y',labelsize=60) x.set_xlabel(var,fontsize=70,labelpad=30,weight='bold') x.set_ylabel('Number of participants',fontsize=70,labelpad=30,weight='bold') x.set_title(var,fontsize=70,pad=30,weight='bold') dir_name = &quot;/Users/macbook/Desktop/UCL PhD Work/&quot; plt.rcParams[&quot;savefig.directory&quot;] = os.chdir(os.path.dirname(dir_name)) plt.savefig(var+' '+'histogram') plt.show() </code></pre> <p>The first 10 rows of newerdf['age'] look like this:</p> <pre><code>0 21.0 1 24.0 2 47.0 3 32.0 5 29.0 6 29.0 7 22.0 8 23.0 9 32.0 10 22.0 </code></pre>
[ { "answer_id": 74574675, "author": "Tom Bascom", "author_id": 123238, "author_profile": "https://Stackoverflow.com/users/123238", "pm_score": 3, "selected": true, "text": "/* isatty.i\n */\n \nfunction isatty returns logical () in super.\n /* isatty.p\n * \n * to use this:\n *\n * run isatty.p persistent\n *\n * {isatty.i}\n * message isatty().\n *\n */\n\n&IF \"{&PROCESS-ARCHITECTURE}\" = \"64\" &THEN\n &global-define XINT int64\n &global-define LONGINT int64\n &global-define PUTLONGINT PUT-INT64\n &global-define GETLONGINT GET-INT64\n &ELSE\n &global-define XINT integer\n &global-define LONGINT long\n &global-define PUTLONGINT PUT-LONG\n &global-define GETLONGINT GET-LONG\n&ENDIF\n\ndefine stream inStrm.\n\nsession:add-super-procedure( this-procedure ).\n\nreturn.\n\n\nprocedure GetFileType external \"kernel32.dll\":\n define input parameter fileHandle as {&LONGINT}.\n define return parameter result as {&LONGINT}.\nend.\n\nprocedure GetStdHandle external \"kernel32.dll\":\n define input parameter fileHandle as {&LONGINT}.\n define return parameter result as {&LONGINT}.\nend.\n\n\n/* determine if we are running with user input or redirected input\n *\n */\n\nfunction isatty returns logical ():\n\n define variable result as logical no-undo.\n define variable tty as character no-undo.\n define variable fileHandle as int64 no-undo.\n define variable fileType as int64 no-undo.\n\n result = false.\n\n if opsys = \"unix\" then\n do:\n\n input stream inStrm through value( \"tty\" ).\n import stream inStrm unformatted tty.\n input stream inStrm close.\n if tty begins \"/dev/\" then\n result = true.\n\n end.\n else\n do:\n\n /* Windows stdin = -10 */\n\n run getStdHandle( -10, output fileHandle ).\n\n run getFileType( fileHandle, output fileType ).\n\n /* 0x0000 = unknown\n * 0x0001 = disk\n * 0x0002 = character (CON or LPT etc)\n * 0x0003 = pipe\n * 0x8000 = remote (unused?)\n */\n\n if fileType = 2 then\n result = true.\n\n end.\n\n return result.\n\nend.\n /* testtty.p\n */\n\nrun isatty.p persistent.\n \n{isatty.i}\nmessage isatty().\n \nquit.\n $ pro -p testtty.p\nyes\n $ cat /dev/null | pro -b -p testtty.p > tty.out\n$ cat tty.out\nno\n $ pro -b -p testtty.p > tty.out\n$ cat tty.out\nyes\n" }, { "answer_id": 74612740, "author": "Александр Овчинников", "author_id": 4846049, "author_profile": "https://Stackoverflow.com/users/4846049", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <string>\nusing namespace std;\nint main()\n{\n int i,l;\n string str;\n fseek(stdin, 0, SEEK_END);\n i = ftell(stdin);\n if (i == 0)\n return 0;\n fseek(stdin, 0, SEEK_SET);\n for (std::string line; std::getline(std::cin, line);) {\n std::cout << line << std::endl;\n }\n return 0;\n}\n DEFINE VARIABLE c AS C. \ndefine stream sin.\ninput stream sin through VALUE('[ ! -t 0 ] && echo $(</dev/stdin) || echo \"\"').\nDO WHILE TRUE ON ENDKEY UNDO,LEAVE:\n import stream sin unformatted c.\n MESSAGE c. PAUSE 0.\n END.\ninput stream sin close.\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12985497/" ]
74,564,252
<p>Starting with the following dictionary:</p> <pre><code>test_dict = {'header1_1': {'header2_1': {'header3_1': {'header4_1': ['322.5', 330.0, -0.28], 'header4_2': ['322.5', 332.5, -0.26]}, 'header3_2': {'header4_1': ['285.0', 277.5, -0.09], 'header4_2': ['287.5', 277.5, -0.12]}}, 'header2_2': {'header3_1': {'header4_1': ['345.0', 357.5, -0.14], 'header4_2': ['345.0', 362.5, -0.14]}, 'header3_2': {'header4_1': ['257.5', 245.0, -0.1], 'header4_2': ['257.5', 240.0, -0.08]}}}} </code></pre> <p>I want the headers in the index, so I reform the dictionary:</p> <pre><code>reformed_dict = {} for outerKey, innerDict in test_dict.items(): for innerKey, innerDict2 in innerDict.items(): for innerKey2, innerDict3 in innerDict2.items(): for innerKey3, values in innerDict3.items(): reformed_dict[(outerKey, innerKey, innerKey2, innerKey3)] = values </code></pre> <p>And assign column names to the headers:</p> <pre><code>keys = reformed_dict.keys() values = reformed_dict.values() index = pd.MultiIndex.from_tuples(keys, names=[&quot;H1&quot;, &quot;H2&quot;, &quot;H3&quot;, &quot;H4&quot;]) df = pd.DataFrame(data=values, index=index) </code></pre> <p>That gets to a dataframe that looks like this: <a href="https://i.stack.imgur.com/vDQ5R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vDQ5R.png" alt="enter image description here" /></a></p> <p><strong>Issue #1</strong> [*** this has been answered by @AzharKhan, so feel free to skip ahead to Issue #2 ***]: To assign names to the data columns, I tried:</p> <pre><code>df.columns = ['col 1', 'col 2' 'col 3'] </code></pre> <p>and got error: &quot;ValueError: Length mismatch: Expected axis has 3 elements, new values have 2 elements&quot;</p> <p>Then per a suggestion, I tried:</p> <pre><code>df = df.rename(columns={'0': 'Col1', '1': 'Col2', '2': 'Col3'}) </code></pre> <p>This does not generate an error, but the dataframe looks exactly the same as before, with 0, 1, 2 as the data column headers.</p> <p>How can I assign names to these data columns? I assume 0, 1, 2 are column indices, not column names.</p> <p><strong>Issue #2</strong>: When I write this dataframe to Google Sheets using <a href="https://gspread-pandas.readthedocs.io/en/latest/index.html" rel="nofollow noreferrer">gspread-pandas</a>:</p> <pre><code>s.open_sheet('test') Spread.df_to_sheet(s, df, index=True, headers=True, start='A8', replace=False) </code></pre> <p>The result is this: <a href="https://i.stack.imgur.com/y5rvk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y5rvk.png" alt="enter image description here" /></a></p> <p>What I would like is this: <a href="https://i.stack.imgur.com/VcikS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VcikS.png" alt="enter image description here" /></a></p> <p>This is how the dataframe appears in Jupyter notebook screenshot earlier, so it seems the process of writing to spreadsheet is filling in the empty row headers, which makes the table harder to read at a glance.</p> <p>How can I get the output to spreadsheet to omit the row headers until they have changed, and thus get the second spreadsheet output?</p>
[ { "answer_id": 74568499, "author": "Azhar Khan", "author_id": 2847330, "author_profile": "https://Stackoverflow.com/users/2847330", "pm_score": 1, "selected": false, "text": "print(df.columns)\n\n[Out]:\nRangeIndex(start=0, stop=3, step=1)\n df.rename() df = df.rename(columns={0: 'Col1', 1: 'Col2', 2: 'Col3'})\nprint(df.columns)\nprint(df)\n\n[Out]:\nIndex(['Col1', 'Col2', 'Col3'], dtype='object')\n\n Col1 Col2 Col3\nH1 H2 H3 H4 \nheader1_1 header2_1 header3_1 header4_1 322.5 330.0 -0.28\n header4_2 322.5 332.5 -0.26\n header3_2 header4_1 285.0 277.5 -0.09\n header4_2 287.5 277.5 -0.12\n header2_2 header3_1 header4_1 345.0 357.5 -0.14\n header4_2 345.0 362.5 -0.14\n header3_2 header4_1 257.5 245.0 -0.10\n header4_2 257.5 240.0 -0.08\n df = df.rename(columns={i:f\"Col{i+1}\" for i in df.columns})\n" }, { "answer_id": 74590704, "author": "rhug123", "author_id": 13802115, "author_profile": "https://Stackoverflow.com/users/13802115", "pm_score": 0, "selected": false, "text": "pd.json_normalize() df = pd.json_normalize(test_dict,max_level=3).stack().droplevel(0)\nidx = df.index.map(lambda x: tuple(x.split('.'))).rename(['H1','H2','H3','H4'])\ndf = pd.DataFrame(df.tolist(),index = idx,columns = ['col1','col2','col3'])\n col1 col2 col3\nH1 H2 H3 H4 \nheader1_1 header2_1 header3_1 header4_1 322.5 330.0 -0.28\n header4_2 322.5 332.5 -0.26\n header3_2 header4_1 285.0 277.5 -0.09\n header4_2 287.5 277.5 -0.12\n header2_2 header3_1 header4_1 345.0 357.5 -0.14\n header4_2 345.0 362.5 -0.14\n header3_2 header4_1 257.5 245.0 -0.10\n header4_2 257.5 240.0 -0.08\n df.index idx_df = df.index.to_frame().reset_index(drop=True)\n\ndf = idx_df.where(idx_df.ne(idx_df.shift())).join(df.reset_index(drop=True))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6467736/" ]
74,564,253
<p>I have a object like this,</p> <pre><code>const obj = { &quot;One&quot;: &quot;1&quot;, &quot;Two&quot;: &quot;2&quot;, &quot;Three&quot;: &quot;3&quot; } </code></pre> <p>I want to convert this object in to an array, in this format,</p> <pre><code>const options = [ { value: &quot;1&quot;, label: &quot;One&quot; }, { value: &quot;2&quot;, label: &quot;Two&quot; }, { value: &quot;3&quot;, label: &quot;Three&quot; }, ]; </code></pre> <p>Can anybody help me how to do it in Javascript?</p>
[ { "answer_id": 74568499, "author": "Azhar Khan", "author_id": 2847330, "author_profile": "https://Stackoverflow.com/users/2847330", "pm_score": 1, "selected": false, "text": "print(df.columns)\n\n[Out]:\nRangeIndex(start=0, stop=3, step=1)\n df.rename() df = df.rename(columns={0: 'Col1', 1: 'Col2', 2: 'Col3'})\nprint(df.columns)\nprint(df)\n\n[Out]:\nIndex(['Col1', 'Col2', 'Col3'], dtype='object')\n\n Col1 Col2 Col3\nH1 H2 H3 H4 \nheader1_1 header2_1 header3_1 header4_1 322.5 330.0 -0.28\n header4_2 322.5 332.5 -0.26\n header3_2 header4_1 285.0 277.5 -0.09\n header4_2 287.5 277.5 -0.12\n header2_2 header3_1 header4_1 345.0 357.5 -0.14\n header4_2 345.0 362.5 -0.14\n header3_2 header4_1 257.5 245.0 -0.10\n header4_2 257.5 240.0 -0.08\n df = df.rename(columns={i:f\"Col{i+1}\" for i in df.columns})\n" }, { "answer_id": 74590704, "author": "rhug123", "author_id": 13802115, "author_profile": "https://Stackoverflow.com/users/13802115", "pm_score": 0, "selected": false, "text": "pd.json_normalize() df = pd.json_normalize(test_dict,max_level=3).stack().droplevel(0)\nidx = df.index.map(lambda x: tuple(x.split('.'))).rename(['H1','H2','H3','H4'])\ndf = pd.DataFrame(df.tolist(),index = idx,columns = ['col1','col2','col3'])\n col1 col2 col3\nH1 H2 H3 H4 \nheader1_1 header2_1 header3_1 header4_1 322.5 330.0 -0.28\n header4_2 322.5 332.5 -0.26\n header3_2 header4_1 285.0 277.5 -0.09\n header4_2 287.5 277.5 -0.12\n header2_2 header3_1 header4_1 345.0 357.5 -0.14\n header4_2 345.0 362.5 -0.14\n header3_2 header4_1 257.5 245.0 -0.10\n header4_2 257.5 240.0 -0.08\n df.index idx_df = df.index.to_frame().reset_index(drop=True)\n\ndf = idx_df.where(idx_df.ne(idx_df.shift())).join(df.reset_index(drop=True))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18972177/" ]
74,564,292
<p>I have some high dimensional boolean data, in this example an array with 4 dimensions, but this is arbitrary:</p> <pre><code>X.shape (3, 2, 66, 241) </code></pre> <p>I want to group the dataset into connected regions of True values, which can be done with <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.label.html" rel="nofollow noreferrer">scipy.ndimage.label</a>, with the aid of a connectivity structure which says which points in the array should be considered to touch. The default 2-D structure is a cross:</p> <pre><code>[[0,1,0], [1,1,1], [0,1,0]] </code></pre> <p>Which can be easily extended to high dimensions <em>if all those dimensions are connected</em>. However I want to programmatically generate such a structure where I have a list of which dims are connected to which:</p> <pre><code>#We want to find connections across dims 2 and 3 across each slice of dims 0 and 1: dim_connections=[[0],[1],[2,3]] #Now we want two separate connected subspaces in our data: dim_connections=[[0,1],[2,3]] </code></pre> <p>For individual cases I can work out with hard-thinking how to generate the correct structuring element, but I am struggling to work out the general rule! For clarity I want something like:</p> <pre><code>mystructure=construct_arbitrary_structure(ndim, dim_connections) the_correct_result=scipy.ndimage.label(X,structure=my_structure) </code></pre>
[ { "answer_id": 74568499, "author": "Azhar Khan", "author_id": 2847330, "author_profile": "https://Stackoverflow.com/users/2847330", "pm_score": 1, "selected": false, "text": "print(df.columns)\n\n[Out]:\nRangeIndex(start=0, stop=3, step=1)\n df.rename() df = df.rename(columns={0: 'Col1', 1: 'Col2', 2: 'Col3'})\nprint(df.columns)\nprint(df)\n\n[Out]:\nIndex(['Col1', 'Col2', 'Col3'], dtype='object')\n\n Col1 Col2 Col3\nH1 H2 H3 H4 \nheader1_1 header2_1 header3_1 header4_1 322.5 330.0 -0.28\n header4_2 322.5 332.5 -0.26\n header3_2 header4_1 285.0 277.5 -0.09\n header4_2 287.5 277.5 -0.12\n header2_2 header3_1 header4_1 345.0 357.5 -0.14\n header4_2 345.0 362.5 -0.14\n header3_2 header4_1 257.5 245.0 -0.10\n header4_2 257.5 240.0 -0.08\n df = df.rename(columns={i:f\"Col{i+1}\" for i in df.columns})\n" }, { "answer_id": 74590704, "author": "rhug123", "author_id": 13802115, "author_profile": "https://Stackoverflow.com/users/13802115", "pm_score": 0, "selected": false, "text": "pd.json_normalize() df = pd.json_normalize(test_dict,max_level=3).stack().droplevel(0)\nidx = df.index.map(lambda x: tuple(x.split('.'))).rename(['H1','H2','H3','H4'])\ndf = pd.DataFrame(df.tolist(),index = idx,columns = ['col1','col2','col3'])\n col1 col2 col3\nH1 H2 H3 H4 \nheader1_1 header2_1 header3_1 header4_1 322.5 330.0 -0.28\n header4_2 322.5 332.5 -0.26\n header3_2 header4_1 285.0 277.5 -0.09\n header4_2 287.5 277.5 -0.12\n header2_2 header3_1 header4_1 345.0 357.5 -0.14\n header4_2 345.0 362.5 -0.14\n header3_2 header4_1 257.5 245.0 -0.10\n header4_2 257.5 240.0 -0.08\n df.index idx_df = df.index.to_frame().reset_index(drop=True)\n\ndf = idx_df.where(idx_df.ne(idx_df.shift())).join(df.reset_index(drop=True))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6555561/" ]
74,564,294
<p>I am trying to plot a raster in a projected in a coordinated system which follows the curvature of the earth like most projections that are not WGS84. The problem is that the places were the globe wraps around the data should not be plotted outside the globe. I realize that ggplot cannot do a rounded/elliptical plot but how do I mask or remove automatically the data outside the globe? I have to plot more than 100 maps and I can't do this manually especially if I want to change to a different projection.</p> <p>There's <a href="https://stackoverflow.com/questions/43612903/how-to-properly-plot-projected-gridded-data-in-ggplot2">an answer here</a> but it's hackish and doesn't seem to apply to every case, is there function or package that deals with this problem? I don't think R users only plot maps in WGS84? I am attaching a file and code to quickly plot the map. I cannot use xlim because it would cut some parts of the map since the borders are not straight.</p> <pre><code>#netcdf file https://ufile.io/fy08x33d library(terra);library(tidyterra) r=rast('Beck_KG_V1_present_0p5.tif') #background map r[r==0]=NA ggplot() +geom_spatraster(data=r)+scale_fill_viridis_c(na.value='transparent') +coord_sf(crs=st_crs(&quot;+proj=hatano&quot;),expand=FALSE) </code></pre> <p><a href="https://i.stack.imgur.com/WGxRK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WGxRK.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74568499, "author": "Azhar Khan", "author_id": 2847330, "author_profile": "https://Stackoverflow.com/users/2847330", "pm_score": 1, "selected": false, "text": "print(df.columns)\n\n[Out]:\nRangeIndex(start=0, stop=3, step=1)\n df.rename() df = df.rename(columns={0: 'Col1', 1: 'Col2', 2: 'Col3'})\nprint(df.columns)\nprint(df)\n\n[Out]:\nIndex(['Col1', 'Col2', 'Col3'], dtype='object')\n\n Col1 Col2 Col3\nH1 H2 H3 H4 \nheader1_1 header2_1 header3_1 header4_1 322.5 330.0 -0.28\n header4_2 322.5 332.5 -0.26\n header3_2 header4_1 285.0 277.5 -0.09\n header4_2 287.5 277.5 -0.12\n header2_2 header3_1 header4_1 345.0 357.5 -0.14\n header4_2 345.0 362.5 -0.14\n header3_2 header4_1 257.5 245.0 -0.10\n header4_2 257.5 240.0 -0.08\n df = df.rename(columns={i:f\"Col{i+1}\" for i in df.columns})\n" }, { "answer_id": 74590704, "author": "rhug123", "author_id": 13802115, "author_profile": "https://Stackoverflow.com/users/13802115", "pm_score": 0, "selected": false, "text": "pd.json_normalize() df = pd.json_normalize(test_dict,max_level=3).stack().droplevel(0)\nidx = df.index.map(lambda x: tuple(x.split('.'))).rename(['H1','H2','H3','H4'])\ndf = pd.DataFrame(df.tolist(),index = idx,columns = ['col1','col2','col3'])\n col1 col2 col3\nH1 H2 H3 H4 \nheader1_1 header2_1 header3_1 header4_1 322.5 330.0 -0.28\n header4_2 322.5 332.5 -0.26\n header3_2 header4_1 285.0 277.5 -0.09\n header4_2 287.5 277.5 -0.12\n header2_2 header3_1 header4_1 345.0 357.5 -0.14\n header4_2 345.0 362.5 -0.14\n header3_2 header4_1 257.5 245.0 -0.10\n header4_2 257.5 240.0 -0.08\n df.index idx_df = df.index.to_frame().reset_index(drop=True)\n\ndf = idx_df.where(idx_df.ne(idx_df.shift())).join(df.reset_index(drop=True))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2319308/" ]
74,564,387
<p>I am trying to remove whitespace from the titles of columns on a dataframe.</p> <pre><code>my_df=pd.DataFrame({' name_1':[1, 2],' name_2':[3, 4],}) </code></pre> <p>After some research, i've tried:</p> <pre><code>my_df.columns.map(lstrip()) df.columns.to_series().map(lstrip) </code></pre> <p>these both give:</p> <p>NameError: name 'lstrip' is not defined</p> <p>even though mystr.lstrip() works fine.</p> <p>how can I do this without getting the name error? and why am I getting it?</p>
[ { "answer_id": 74568499, "author": "Azhar Khan", "author_id": 2847330, "author_profile": "https://Stackoverflow.com/users/2847330", "pm_score": 1, "selected": false, "text": "print(df.columns)\n\n[Out]:\nRangeIndex(start=0, stop=3, step=1)\n df.rename() df = df.rename(columns={0: 'Col1', 1: 'Col2', 2: 'Col3'})\nprint(df.columns)\nprint(df)\n\n[Out]:\nIndex(['Col1', 'Col2', 'Col3'], dtype='object')\n\n Col1 Col2 Col3\nH1 H2 H3 H4 \nheader1_1 header2_1 header3_1 header4_1 322.5 330.0 -0.28\n header4_2 322.5 332.5 -0.26\n header3_2 header4_1 285.0 277.5 -0.09\n header4_2 287.5 277.5 -0.12\n header2_2 header3_1 header4_1 345.0 357.5 -0.14\n header4_2 345.0 362.5 -0.14\n header3_2 header4_1 257.5 245.0 -0.10\n header4_2 257.5 240.0 -0.08\n df = df.rename(columns={i:f\"Col{i+1}\" for i in df.columns})\n" }, { "answer_id": 74590704, "author": "rhug123", "author_id": 13802115, "author_profile": "https://Stackoverflow.com/users/13802115", "pm_score": 0, "selected": false, "text": "pd.json_normalize() df = pd.json_normalize(test_dict,max_level=3).stack().droplevel(0)\nidx = df.index.map(lambda x: tuple(x.split('.'))).rename(['H1','H2','H3','H4'])\ndf = pd.DataFrame(df.tolist(),index = idx,columns = ['col1','col2','col3'])\n col1 col2 col3\nH1 H2 H3 H4 \nheader1_1 header2_1 header3_1 header4_1 322.5 330.0 -0.28\n header4_2 322.5 332.5 -0.26\n header3_2 header4_1 285.0 277.5 -0.09\n header4_2 287.5 277.5 -0.12\n header2_2 header3_1 header4_1 345.0 357.5 -0.14\n header4_2 345.0 362.5 -0.14\n header3_2 header4_1 257.5 245.0 -0.10\n header4_2 257.5 240.0 -0.08\n df.index idx_df = df.index.to_frame().reset_index(drop=True)\n\ndf = idx_df.where(idx_df.ne(idx_df.shift())).join(df.reset_index(drop=True))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792022/" ]
74,564,401
<p>When I try to define a constructor taking a universal reference with a defaulted value as a parameter like this:</p> <pre class="lang-cpp prettyprint-override"><code>struct S { int x; // I know that universal ref is useless for int, but it's here for simplicity template&lt;class T&gt; S(const T&amp;&amp; arg = 123) : x(std::forward(arg)) { } // S(const auto&amp;&amp; arg = 123) : x(std::forward(arg)) { } // The auto-syntax fails as well, yields similar error }; int main() { S s; } </code></pre> <p>I get an error:</p> <pre><code>&lt;source&gt;:18:7: error: no matching constructor for initialization of 'S' S s; ^ &lt;source&gt;:10:5: note: candidate template ignored: couldn't infer template argument 'T' S(const T&amp;&amp; arg = 123) : x(std::forward(arg)) { } ^ &lt;source&gt;:3:8: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided struct S { ^ &lt;source&gt;:3:8: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 0 were provided </code></pre> <p>Is there a way to do it with a universal reference or do I have to do it in a different way?</p>
[ { "answer_id": 74564555, "author": "Jarod42", "author_id": 2684539, "author_profile": "https://Stackoverflow.com/users/2684539", "pm_score": 1, "selected": false, "text": "T template<class T = int>\nS(T&& arg = 123) : x(std::forward<T>(arg)) {}\n" }, { "answer_id": 74564559, "author": "user17732522", "author_id": 17732522, "author_profile": "https://Stackoverflow.com/users/17732522", "pm_score": 3, "selected": true, "text": "template<class T = int>\n std::forward x(std::forward<T>(arg))\n const const S(T&& arg = 123)\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19087625/" ]
74,564,445
<p>The code to render a TabList:</p> <pre><code>import React, { Children, useEffect } from 'react'; import { LayoutChangeEvent, View } from 'react-native'; import { ScrollView, TouchableWithoutFeedback, } from 'react-native-gesture-handler'; import Animated, { Easing, useAnimatedStyle, useSharedValue, withTiming, } from 'react-native-reanimated'; import { isValidChild } from '@utils'; import { useTabIndex } from '../tab-context'; import { useStyle } from './tab-list.styles'; import { TabListProps } from './tab-list.type'; const animConfig = { duration: 200, easing: Easing.bezier(0.25, 0.1, 0.25, 1), }; const TabList: React.FC&lt;TabListProps&gt; = props =&gt; { const styles = useStyle(); const { children, onChange } = props; const selectedTabIndex = useTabIndex(); const animatedTabIndicatorPosition = useSharedValue(0); // Save layout of the container const [containerLayout, setContainerLayout] = React.useState({ x: 0, y: 0, width: 0, height: 0, }); const onContainerLayout = (event: LayoutChangeEvent) =&gt; { const { x, y, width, height } = event.nativeEvent.layout; setContainerLayout({ x, y, width, height }); }; // get children length const childrenLength = Children.count(children); const tabWidth = childrenLength &gt; 3 ? containerLayout.width / 3 : containerLayout.width / childrenLength; const renderChildren = () =&gt; { // Render only children of component type TabList return Children.map(children, child =&gt; { // Check if child is a valid React element and has type TabList if (isValidChild(child, 'Tab')) { return ( &lt;TouchableWithoutFeedback containerStyle={{ width: tabWidth }} onPress={() =&gt; onChange((child as JSX.Element)?.props.tabIndex)} &gt; {child} &lt;/TouchableWithoutFeedback&gt; ); } // Throw error if child is not a TabList throw new Error('TabList component can only have children of type Tab'); }); }; useEffect(() =&gt; { animatedTabIndicatorPosition.value = selectedTabIndex * tabWidth; }, [selectedTabIndex]); const indicatorAnimatedStyle = useAnimatedStyle(() =&gt; { return { width: tabWidth, transform: [ { translateX: withTiming( animatedTabIndicatorPosition.value, animConfig, ), }, ], }; }, []); return ( &lt;View onLayout={onContainerLayout} style={styles.container}&gt; &lt;ScrollView horizontal showsHorizontalScrollIndicator={false} testID=&quot;TestID__component-TabList&quot; &gt; &lt;Animated.View style={[styles.indicatorContainer, indicatorAnimatedStyle]} &gt; &lt;View style={[ styles.indicator, { width: tabWidth - 4, }, ]} /&gt; &lt;/Animated.View&gt; {renderChildren()} &lt;/ScrollView&gt; &lt;/View&gt; ); }; export default TabList; </code></pre> <p>The styles for the component elements:</p> <pre><code>import { createUseStyle } from '@theme'; // createUseStyle basically returns (fn) =&gt; useStyle(fn) export const useStyle = createUseStyle(theme =&gt; ({ container: { position: 'relative', flexGrow: 1, backgroundColor: theme.palette.accents.color8, height: 32, borderRadius: theme.shape.borderRadius(4.5), }, indicatorContainer: { position: 'absolute', height: 32, justifyContent: 'center', alignItems: 'center', }, indicator: { height: 28, backgroundColor: theme.palette.background.main, borderRadius: theme.shape.borderRadius(4), }, })); </code></pre> <p>I am using react-native-reanimated to animate the tab indicator. What I noticed is, on app reload, the initial tab indicator position keeps on changing as seen in the GIF I have attached. At times, it is positioned where it should be and at times, half the box is hidden behind the scrollview container. When I remove the <code>alignItems: center</code> from the <code>Animated.View</code>, things work as expected.</p> <p>I am perplexed as to why the position keeps changing because of <code>align-items</code>?</p> <p><a href="https://i.stack.imgur.com/WcjeQ.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WcjeQ.gif" alt="Initial tab indicator position gets jumped" /></a></p>
[ { "answer_id": 74577130, "author": "shet_tayyy", "author_id": 2338858, "author_profile": "https://Stackoverflow.com/users/2338858", "pm_score": 1, "selected": false, "text": "flexWrap: 'wrap' import { createUseStyle } from '@theme';\n\n// createUseStyle basically returns (fn) => useStyle(fn)\nexport const useStyle = createUseStyle(theme => ({\n container: {\n position: 'relative',\n flexGrow: 1,\n backgroundColor: theme.palette.accents.color8,\n height: 32,\n borderRadius: theme.shape.borderRadius(4.5),\n },\n\n indicatorContainer: {\n position: 'absolute',\n height: 32,\n justifyContent: 'center',\n alignItems: 'center',\n flexWrap: 'wrap'\n },\n\n indicator: {\n height: 28,\n backgroundColor: theme.palette.background.main,\n borderRadius: theme.shape.borderRadius(4),\n },\n}));\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2338858/" ]
74,564,479
<p>I have the following linq query:</p> <pre><code>private List&lt;Port&gt; DoCountriesSearch(string search) { return Countries.Where(x =&gt; x.CountrySearch.ToLower().Contains(search.ToLower())).ToList(); } </code></pre> <p>I have an object called <code>Countries</code> which is a list of Port objects with various properties. Each Port object contains a property called <code>CountrySearch</code> which you can see here:</p> <p><a href="https://i.stack.imgur.com/olbMz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/olbMz.png" alt="enter image description here" /></a></p> <p>But as soon as I try to run the linq query on <code>Countries</code>, suddenly the <code>CountrySearch</code> property is null which throws a null reference exception:</p> <p><a href="https://i.stack.imgur.com/LPITl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LPITl.png" alt="enter image description here" /></a></p> <p>I've never had this issue with linq before. What am I missing?</p>
[ { "answer_id": 74577130, "author": "shet_tayyy", "author_id": 2338858, "author_profile": "https://Stackoverflow.com/users/2338858", "pm_score": 1, "selected": false, "text": "flexWrap: 'wrap' import { createUseStyle } from '@theme';\n\n// createUseStyle basically returns (fn) => useStyle(fn)\nexport const useStyle = createUseStyle(theme => ({\n container: {\n position: 'relative',\n flexGrow: 1,\n backgroundColor: theme.palette.accents.color8,\n height: 32,\n borderRadius: theme.shape.borderRadius(4.5),\n },\n\n indicatorContainer: {\n position: 'absolute',\n height: 32,\n justifyContent: 'center',\n alignItems: 'center',\n flexWrap: 'wrap'\n },\n\n indicator: {\n height: 28,\n backgroundColor: theme.palette.background.main,\n borderRadius: theme.shape.borderRadius(4),\n },\n}));\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4388132/" ]
74,564,509
<p>I have a list of tuples and the tuples look like this (2, 11) which means exam 2 must be taken by student 11. The exams are numbered from 0 to however many exams there are and the same with students. I need to produce a 2D list where the first list is the exams the 0th student is taking and the second list is the exams student number 1 is taking etc. I have this code:</p> <pre><code>examsEachStudentsIsDoing = [] exams = [] number_of_students = 14 exams_to_students = [(0, 1), (0, 4), (0, 5), (0, 3), (0, 10), (0, 13), (0, 9), (0, 11), (0, 12), (0, 2), (0, 7), (0, 6), (1, 7), (2, 7), (2, 5), (2, 0), (2, 11), (2, 13), (3, 4), (4, 6), (4, 8)] for i in range(0,number_of_students): exams.clear() for j in range(0,len(exams_to_students)): if (exams_to_students[j][1]==i): exams.append(exams_to_students[j][0]) examsEachStudentsIsDoing.append(exams) print(examsEachStudentsIsDoing) </code></pre> <p>if i add a print line just before <code>examsEachStudentsIsDoing.append(exams)</code> then i get the result:</p> <pre><code>[2] [0] [0] [0] [0, 3] [0, 2] [0, 4] [0, 1, 2] [4] [0] [0] [0, 2] [0] [0, 2] [[0, 2], [0, 2], [0, 2], [0, 2], [0, 2], [0, 2], [0, 2], [0, 2], [0, 2], [0, 2], [0, 2], [0, 2], [0, 2], [0, 2]] </code></pre> <p>why is it repeatedly appending on the last students exams and not each one individually</p>
[ { "answer_id": 74564613, "author": "Jay", "author_id": 8677071, "author_profile": "https://Stackoverflow.com/users/8677071", "pm_score": 2, "selected": true, "text": "exams exams examsEachStudentsIsDoing exams examsEachStudentsIsDoing exams [0,2] examsEachStudentsIsDoing exams examsEachStudentsIsDoing list.copy() list[:] examsEachStudentsIsDoing = []\nexams = []\nnumber_of_students = 14\nexams_to_students = [(0, 1), (0, 4), (0, 5), (0, 3), (0, 10), (0, 13), (0, 9), (0, 11), (0, 12), (0, 2), (0, 7), (0, 6), (1, 7), (2, 7), (2, 5), (2, 0), (2, 11), (2, 13), (3, 4), (4, 6), (4, 8)]\n \nfor i in range(0,number_of_students):\n exams.clear()\n for j in range(0,len(exams_to_students)):\n if (exams_to_students[j][1]==i):\n exams.append(exams_to_students[j][0])\n examsEachStudentsIsDoing.append(exams.copy()) #updated\n\nprint(examsEachStudentsIsDoing)\n [[2], [0], [0], [0], [0, 3], [0, 2], [0, 4], [0, 1, 2], [4], [0], [0], [0, 2], [0], [0, 2]]\n exams examsEachStudentsIsDoing = []\nnumber_of_students = 14\nexams_to_students = [(0, 1), (0, 4), (0, 5), (0, 3), (0, 10), (0, 13), (0, 9), (0, 11), (0, 12), (0, 2), (0, 7), (0, 6), (1, 7), (2, 7), (2, 5), (2, 0), (2, 11), (2, 13), (3, 4), (4, 6), (4, 8)]\n \nfor i in range(0,number_of_students):\n exams = []\n for j in range(0,len(exams_to_students)):\n if (exams_to_students[j][1]==i):\n exams.append(exams_to_students[j][0])\n examsEachStudentsIsDoing.append(exams)\n\nprint(examsEachStudentsIsDoing)\n" }, { "answer_id": 74564711, "author": "Niko", "author_id": 7100120, "author_profile": "https://Stackoverflow.com/users/7100120", "pm_score": 0, "selected": false, "text": "import json\n\nnumber_of_students = 14\nexams_to_students = [(0, 1), (0, 4), (0, 5), (0, 3), (0, 10), (0, 13), (0, 9), (0, 11), (0, 12), (0, 2), (0, 7), (0, 6), (1, 7), (2, 7), (2, 5), (2, 0), (2, 11), (2, 13), (3, 4), (4, 6), (4, 8)]\n\"\"\"\n(2, 11) which means exam 2 must be taken by student 11\n\"\"\"\ndisposal = {}\n# Create a key for every student\nfor i in range(0, number_of_students):\n disposal[i] = { 'exams': []}\n\n\n# loop through tuples\n# add exam to the designated student\nfor value in exams_to_students:\n disposal[value[1]]['exams'].append(value[0])\n\njson_object = json.dumps(disposal, indent=4)\nprint(json_object)\n\n#Output\n{\n \"0\": { \n \"exams\": [\n 2 \n ]\n },\n \"1\": { \n \"exams\": [\n 0 \n ]\n },\n \"2\": { \n \"exams\": [\n 0 \n ]\n },\n \"3\": { \n \"exams\": [\n 0\n ]\n },\n \"4\": {\n \"exams\": [\n 0,\n 3\n ]\n },\n \"5\": {\n \"exams\": [\n 0,\n 2\n ]\n },\n \"6\": {\n \"exams\": [\n 0,\n 4\n ]\n },\n \"7\": {\n \"exams\": [\n 0,\n 1,\n 2\n ]\n },\n ...\n}\n # loop through your tuples\nfor value in exams_to_students:\n if value[0] not in disposal[value[1]]['exams']:\n disposal[value[1]]['exams'].append(value[0])\n" }, { "answer_id": 74564976, "author": "Frank", "author_id": 3913120, "author_profile": "https://Stackoverflow.com/users/3913120", "pm_score": 0, "selected": false, "text": "from collections import defaultdict\n\nexams_to_students = [(0, 1), (0, 4), (0, 5), (0, 3),\n (0, 10), (0, 13), (0, 9), (0, 11),\n (0, 12), (0, 2), (0, 7), (0, 6),\n (1, 7), (2, 7), (2, 5), (2, 0),\n (2, 11), (2, 13), (3, 4), (4, 6), (4, 8)]\n\ntracker = defaultdict(list)\nfor (exam, student) in exams_to_students:\n tracker[student].append(exam)\n\nprint(\"Exams by student using a defaultdict\")\nfor student in sorted(tracker.keys()):\n print(student, tracker[student])\n\nprint(\"Exams by student using a list\")\nexams_by_student_as_list = [tracker[student] for student in sorted(tracker.keys())]\nfor exams in exams_by_student_as_list:\n print(exams)\n" }, { "answer_id": 74565158, "author": "BSimjoo", "author_id": 7421566, "author_profile": "https://Stackoverflow.com/users/7421566", "pm_score": 0, "selected": false, "text": "l l a=l a l exam.clear() exam = [] examsEachStudentsIsDoing = []\n# no need to write exams = [] here\nnumber_of_students = 14\nexams_to_students = [(0, 1), (0, 4), (0, 5), (0, 3), (0, 10), (0, 13), (0, 9), (0, 11), (0, 12), (0, 2), (0, 7), (0, 6), (1, 7), (2, 7), (2, 5), (2, 0), (2, 11), (2, 13), (3, 4), (4, 6), (4, 8)]\n \nfor i in range(0,number_of_students):\n print(f'{i=}')\n exams = [] # replaced exams.clear()\n for j in range(0,len(exams_to_students)):\n if (exams_to_students[j][1]==i):\n print(f'index ({j})={exams_to_students[j]}')\n exams.append(exams_to_students[j][0])\n print(f'{exams=}')\n examsEachStudentsIsDoing.append(exams)\n\nprint(examsEachStudentsIsDoing)\n exams_to_students = [(0, 1), (0, 4), (0, 5), (0, 3), (0, 10), (0, 13), (0, 9), (0, 11), (0, 12), (0, 2), (0, 7), (0, 6), (1, 7), (2, 7), (2, 5), (2, 0), (2, 11), (2, 13), (3, 4), (4, 6), (4, 8)]\nexamsEachStudentsIsDoing = [list() for _ in exams_to_students]\nfor exam, student in exams_to_students:\n examsEachStudentsIsDoing[student].append(exam)\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20585322/" ]
74,564,510
<p>Tried to keep this relatively simple but let me know if you need more information.</p> <p>I have 2 dictionaries made up of three dataframes each, these have been produced through loops then added into a dictionary. They have the keys ['XAUUSD', 'EURUSD', 'GBPUSD'] in common:</p> <p>trades_dict</p> <pre><code>{'XAUUSD': df_trades_1 'EURUSD': df_trades_2 'GBPUSD': df_trades_3} </code></pre> <p>prices_dict</p> <pre><code>{'XAUUSD': df_prices_1 'EURUSD': df_prices_2 'GBPUSD': df_prices_3} </code></pre> <p>I would like to merge the tables on the closest timestamps to produce 3 new dataframes such that the XAUUSD trades dataframe is merged with the corresponding XAUUSD prices dataframe and so on</p> <p>I have been able to join the dataframes in a loop using:</p> <pre><code>df_merge_list = [] for trades in trades_dict.values(): for prices in prices_dict.values(): df_merge = pd.merge_asof(trades, prices, left_on='transact_time', right_on='time', direction='backward') df_merge_list.append(df_merge) </code></pre> <p>However this produces a list of 9 dataframes, XAUUSD trades + XAUUSD price, XAUUSD trades + EURUSD price and XAUUSD trades + GBPUSD price etc.</p> <p>Is there a way for me to join only the dataframes where the keys are identical? I'm assuming it will need to be something like this: <code>if trades_dict.keys() == prices_dict.keys():</code></p> <pre><code>df_merge_list = [] for trades in trades_dict.values(): for prices in prices_dict.values(): if trades_dict.keys() == prices_dict.keys(): df_merge = pd.merge_asof(trades, prices, left_on='transact_time', right_on='time', direction='backward') df_merge_list.append(df_merge) </code></pre> <p>but I'm getting the same result as above</p> <p>Am I close? How can I do this for all instruments and only produce the 3 outputs I need? Any help is appreciated</p> <p>Thanks in advance</p>
[ { "answer_id": 74564872, "author": "R Walser", "author_id": 17889492, "author_profile": "https://Stackoverflow.com/users/17889492", "pm_score": 0, "selected": false, "text": "import numpy as np\nimport pandas as pd\n\nnp.random.seed(42)\ndf_trades_1 = df_trades_2 = df_trades_3 = pd.DataFrame(np.random.rand(10, 2), columns = ['ID1', 'Val1'])\ndf_prices_1 = df_prices_2 = df_prices_3 = pd.DataFrame(np.random.rand(10, 2), columns = ['ID2', 'Val2'])\ntrades_dict = {'XAUUSD':df_trades_1, 'EURUSD':df_trades_2, 'GBPUSD':df_trades_3}\nprices_dict = {'XAUUSD':df_prices_1, 'EURUSD':df_prices_2, 'GBPUSD':df_prices_3}\n\nframes ={}\nfor t in trades_dict.keys():\n frames[t] = (pd.concat([trades_dict[t], prices_dict[t]], axis = 1))\nframes['XAUUSD']\n ID1 Val1 ID2 Val2\n0 0.374540 0.950714 0.611853 0.139494\n1 0.731994 0.598658 0.292145 0.366362\n2 0.156019 0.155995 0.456070 0.785176\n3 0.058084 0.866176 0.199674 0.514234\n4 0.601115 0.708073 0.592415 0.046450\n5 0.020584 0.969910 0.607545 0.170524\n6 0.832443 0.212339 0.065052 0.948886\n7 0.181825 0.183405 0.965632 0.808397\n8 0.304242 0.524756 0.304614 0.097672\n9 0.431945 0.291229 0.684233 0.440152\n" }, { "answer_id": 74564950, "author": "p-krishna", "author_id": 14480565, "author_profile": "https://Stackoverflow.com/users/14480565", "pm_score": 2, "selected": true, "text": "\"\"\"\nPseudocode :\nFor each key in the list of keys in trades_dict :\n Pick that key's value (trades df) from trades_dict\n Using the same key, pick corresponding value (prices df) from prices_dict\n Merge both values (trades & prices dataframes)\n\"\"\"\n\ndf_merge_list = []\n\nfor key in trades_dict.keys():\n trades = trades_dict[key]\n prices = prices_dict[key] # using the same key to get corresponding prices\n\n df_merge = pd.merge_asof(trades, prices, left_on='transact_time', right_on='time', direction='backward')\n df_merge_list.append(df_merge)\n trades_dict.keys() == prices_dict.keys() True dict_a_all_keys == dict_b_all_keys dict_a_key_1 == dict_b_key_1 df_merge_list = []\n\nfor trades_key in trades_dict.keys():\n for prices_key in prices_dict.keys():\n if trades_key == prices_key:\n trades = trades_dict[trades_key]\n prices = prices_dict[trades_key] # since trades_key is same as prices_key, they are interchangeable\n df_merge = pd.merge_asof(trades, prices, left_on='transact_time', right_on='time', direction='backward')\n df_merge_list.append(df_merge)\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16342202/" ]
74,564,521
<p>I need to &quot;subtract&quot; from the distance a line has and doing so maintaining the same direction it initially had.</p> <p>Note: If we try to simply subtract a given value (example 10) the direction will change.</p> <p>I guess it's a mathematical problem? I need to be able to change coordinates to cause the distance to shorten by percentage. Be it from the initial position (x1, y1) or from the end position (x2, y2) all the while keeping the line in the same direction.</p> <p>Note: See attached image for illustration.</p> <pre><code>// Gray line (100% distance) &lt;line x1=&quot;x1&quot; y1=&quot;y1&quot; x2=&quot;x2&quot; y2=&quot;y2&quot; /&gt; // Purple line (90% distance) &lt;line x1=&quot;x1&quot; y1=&quot;y1&quot; x2=&quot;subtractByPercentage(x2, '10%')&quot; y2=&quot;subtractByPercentage(y2, '10%')&quot; /&gt; </code></pre> <p><a href="https://i.stack.imgur.com/qBMS7.png" rel="nofollow noreferrer">Full distance vs percentage</a></p> <p>I tried subtracting a given value e.g. 10, or a percentage of x and y value, but that would always change the direction of line.</p>
[ { "answer_id": 74564551, "author": "Bill Lynch", "author_id": 47453, "author_profile": "https://Stackoverflow.com/users/47453", "pm_score": 2, "selected": false, "text": "<line\n x1=\"x1\"\n y1=\"y1\"\n x2=\"x1 + (x2 - x1) * .9\"\n y2=\"y1 + (y2 - y1) * .9\">\n" }, { "answer_id": 74564574, "author": "Yves Daoust", "author_id": 1196549, "author_profile": "https://Stackoverflow.com/users/1196549", "pm_score": 2, "selected": false, "text": "X = X0 + t.(X1 - X0)\nY = Y0 + t.(X1 - X0)\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5857719/" ]
74,564,532
<p>I am trying to lay down all these square divs horizontally but when I set <code>display:inline-block</code> on the parent div, everything shrinks down and collapses into a pellet. If I use <code>flex</code>, I feel like I need to tweak <code>flex</code> property to my need. Is there a simple way to fix it?(I want them to always occupy two lines evenly with the gap in between in response to the changing viewport width)</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>.square { position: relative; margin: 0; max-width: 60px; border: 1px dotted black; border-radius: 4px; } .square:after { content: ""; display: block; padding-bottom: 100%; } .square .content { position: absolute; width: 100%; height: 100%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="number-of-round"&gt; &lt;div class="square"&gt; &lt;div class="content flex flex-center"&gt;1&lt;/div&gt; &lt;/div&gt; &lt;div class="square"&gt; &lt;div class="content flex flex-center"&gt;2&lt;/div&gt; &lt;/div&gt; &lt;div class="square"&gt; &lt;div class="content flex flex-center"&gt;3&lt;/div&gt; &lt;/div&gt; &lt;div class="square"&gt; &lt;div class="content flex flex-center"&gt;4&lt;/div&gt; &lt;/div&gt; &lt;div class="square"&gt; &lt;div class="content flex flex-center"&gt;5&lt;/div&gt; &lt;/div&gt; &lt;div class="square"&gt; &lt;div class="content flex flex-center"&gt;6&lt;/div&gt; &lt;/div&gt; &lt;div class="square"&gt; &lt;div class="content flex flex-center"&gt;7&lt;/div&gt; &lt;/div&gt; &lt;div class="square"&gt; &lt;div class="content flex flex-center"&gt;8&lt;/div&gt; &lt;/div&gt; &lt;div class="square"&gt; &lt;div class="content flex flex-center"&gt;9&lt;/div&gt; &lt;/div&gt; &lt;div class="square"&gt; &lt;div class="content flex flex-center"&gt;10&lt;/div&gt; &lt;/div&gt; &lt;div class="square"&gt; &lt;div class="content flex flex-center"&gt;11&lt;/div&gt; &lt;/div&gt; &lt;div class="square"&gt; &lt;div class="content flex flex-center"&gt;12&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74564664, "author": "DCR", "author_id": 4398966, "author_profile": "https://Stackoverflow.com/users/4398966", "pm_score": -1, "selected": false, "text": ".square {\nwidth:10vw;\nmax-width:60px;aspect-ratio:1;\n \n \n margin-bottom:3vw;\n border: 1px dotted black;\n border-radius: 4px;\n \n}\n.number-of-round{\ndisplay:flex;\njustify-content: space-between;} <div class=\"number-of-round\">\n <div class=\"square\">\n <div class=\"content flex flex-center\">1</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">2</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">3</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">4</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">5</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">6</div>\n </div>\n </div>\n <div class=\"number-of-round\">\n <div class=\"square\">\n <div class=\"content flex flex-center\">7</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">8</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">9</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">10</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">11</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">12</div>\n </div>\n </div>" }, { "answer_id": 74564991, "author": "Edgar MC", "author_id": 7824783, "author_profile": "https://Stackoverflow.com/users/7824783", "pm_score": -1, "selected": false, "text": ".square {\n display: inline-block;\n position: relative;\n margin: 0;\n width: 60px;\n border: 1px dotted black;\n border-radius: 4px;\n}\n.square:after {\n content: \"\";\n display: block;\n padding-bottom: 100%;\n}\n.square .content {\n position: absolute;\n width: 100%;\n height: 100%;\n} <div class=\"number-of-round\">\n <div class=\"square\">\n <div class=\"content flex flex-center\">1</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">2</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">3</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">4</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">5</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">6</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">7</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">8</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">9</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">10</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">11</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">12</div>\n </div>\n </div>" }, { "answer_id": 74577312, "author": "Temani Afif", "author_id": 8620333, "author_profile": "https://Stackoverflow.com/users/8620333", "pm_score": 0, "selected": false, "text": "width max-width inline-block max-width .square {\n display: inline-block;\n position: relative;\n margin: 0;\n width: 60px;\n border: 1px dotted black;\n border-radius: 4px;\n}\n.square:after {\n content: \"\";\n display: block;\n padding-bottom: 100%;\n}\n.square .content {\n position: absolute;\n width: 100%;\n height: 100%;\n} <div class=\"number-of-round\">\n <div class=\"square\">\n <div class=\"content flex flex-center\">1</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">2</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">3</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">4</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">5</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">6</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">7</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">8</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">9</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">10</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">11</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">12</div>\n </div>\n </div>" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15173572/" ]
74,564,548
<p>How do use a structure variables value inside a structure member without calling on the structure variables name but only using the member of that structure and a global variable (string)? the idea is that i set the global variables value to the structure variables name and then just doing <code>.structM</code> after that variable kinda like this: <code>global.structM</code> with <code>global</code> being the global variable.</p> <p>i tried this:</p> <pre><code>#include &lt;iostream&gt; using namespace std; string global = &quot;structV&quot;; struct{ int structM; }structV; int main() { structV.structM = 100; cout &lt;&lt; structV.structM &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; global.structM &lt;&lt; endl &lt;&lt; endl; } </code></pre> <p>but of course the solution won't be that simple. <code>cout &lt;&lt; global.value &lt;&lt; endl &lt;&lt; endl;</code> appered as a error. i inatialy thought that maybe, just maybe, it would work. My hopes were low and sure enough, it didn't work. it just said that there were, <code>no member named &quot;structM&quot; in std::basic_string&lt;char&gt;</code>. So, is there a way to solve this?</p>
[ { "answer_id": 74564664, "author": "DCR", "author_id": 4398966, "author_profile": "https://Stackoverflow.com/users/4398966", "pm_score": -1, "selected": false, "text": ".square {\nwidth:10vw;\nmax-width:60px;aspect-ratio:1;\n \n \n margin-bottom:3vw;\n border: 1px dotted black;\n border-radius: 4px;\n \n}\n.number-of-round{\ndisplay:flex;\njustify-content: space-between;} <div class=\"number-of-round\">\n <div class=\"square\">\n <div class=\"content flex flex-center\">1</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">2</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">3</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">4</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">5</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">6</div>\n </div>\n </div>\n <div class=\"number-of-round\">\n <div class=\"square\">\n <div class=\"content flex flex-center\">7</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">8</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">9</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">10</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">11</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">12</div>\n </div>\n </div>" }, { "answer_id": 74564991, "author": "Edgar MC", "author_id": 7824783, "author_profile": "https://Stackoverflow.com/users/7824783", "pm_score": -1, "selected": false, "text": ".square {\n display: inline-block;\n position: relative;\n margin: 0;\n width: 60px;\n border: 1px dotted black;\n border-radius: 4px;\n}\n.square:after {\n content: \"\";\n display: block;\n padding-bottom: 100%;\n}\n.square .content {\n position: absolute;\n width: 100%;\n height: 100%;\n} <div class=\"number-of-round\">\n <div class=\"square\">\n <div class=\"content flex flex-center\">1</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">2</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">3</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">4</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">5</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">6</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">7</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">8</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">9</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">10</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">11</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">12</div>\n </div>\n </div>" }, { "answer_id": 74577312, "author": "Temani Afif", "author_id": 8620333, "author_profile": "https://Stackoverflow.com/users/8620333", "pm_score": 0, "selected": false, "text": "width max-width inline-block max-width .square {\n display: inline-block;\n position: relative;\n margin: 0;\n width: 60px;\n border: 1px dotted black;\n border-radius: 4px;\n}\n.square:after {\n content: \"\";\n display: block;\n padding-bottom: 100%;\n}\n.square .content {\n position: absolute;\n width: 100%;\n height: 100%;\n} <div class=\"number-of-round\">\n <div class=\"square\">\n <div class=\"content flex flex-center\">1</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">2</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">3</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">4</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">5</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">6</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">7</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">8</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">9</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">10</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">11</div>\n </div>\n <div class=\"square\">\n <div class=\"content flex flex-center\">12</div>\n </div>\n </div>" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19873242/" ]
74,564,564
<p>The function below needs the values of some <code>user</code> properties. Parameter <code>scores</code> is dependent on <code>user</code> and is provided by <code>this.form.get('scores').valueChanges.subscribe((value)</code>. The <code>console.log</code> correctly shows <code>scores</code> as an array and <code>this.user</code> as an Observable.</p> <p>How do I access the property values of <code>user</code> needed to return a value.</p> <p><a href="https://stackblitz.com/edit/using-angular-forms-with-async-data-qzxpxr?file=src%2Fapp%2Fuser.service.ts,src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.module.ts" rel="nofollow noreferrer">Full StackBlitz here</a>. When I change a value of scores, I want stp =&gt; Score to Post1 to contain new values.</p> <p>Thanks to Cory Rylan for the template.</p> <pre><code> ESA(scores) { let stp = []; console.log('ESA', scores, this.user); scores.map((item: number, index) =&gt; { stp[index] = this.user.pipe( tap((user) =&gt; user.scores[index] + 100) ); console.log('stp', stp, item, this.user); }); return stp; } </code></pre>
[ { "answer_id": 74572587, "author": "Dimanoid", "author_id": 1122806, "author_profile": "https://Stackoverflow.com/users/1122806", "pm_score": 1, "selected": false, "text": "this.user.pipe(...) user BehaviorSubject<User> this.userService.user.getValue() userService.loadUser() constructor(...) {\n this.userService.loadUser().subscribe(user => this.user = user);\n...\n}\n" }, { "answer_id": 74649983, "author": "Clifford Eby", "author_id": 3998720, "author_profile": "https://Stackoverflow.com/users/3998720", "pm_score": 0, "selected": false, "text": "this.user async pipe shareReplay this.user this.user = this.userService.loadUser().pipe(\n tap((user) => this.form.patchValue(user)),\n shareReplay()\n );\n this.user userProp() userProp() {\n let parsArray = [];\n let hCapsArray = [];\n let ci\n this.user.subscribe((user) => {\n parsArray = user.pars;\n hCapsArray = user.hCaps;\n ci = user.ci;\n });\n return [parsArray, hCapsArray, ci] as const;\n }\n ESA(value) {\n const data = this.userProp(); //First Subcription to User\n const pars = data[0];\n const hCaps = data[1];\n const ci = data[2];\n const value1 = [];\n value\n .forEach((x, index) =>\n x - pars[index] > 3\n ? (value1[index] = pars[index] + 3)\n : x - pars[index] > 2 && hCaps[index] >= ci\n ? (value1[index] = pars[index] + 2)\n : (value1[index] = x)\n );\n console.log('values', value1, value, pars, ci);\n return value1;\n }\n this.user async pipe and shareReplay this.user loadScoreControls(item)" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3998720/" ]
74,564,586
<p>I want to get the records based on the row value. Please refer to the attached image for a table overview with records.</p> <p>If there is no <code>Execution Project</code> in the column <code>projecttype</code> for a specific <code>ESAProjectID</code> then take the row with values <code>projecttype='Group Project'</code> .</p> <p>otherwise</p> <p>if both <code>Execution Project</code> and <code>Group Project</code> are found for a specific <code>ESAProjectID</code> then take only <code>projecttype='Execution Project'</code></p> <p>In the attached image I have marked in green color records are the expected result. <a href="https://i.stack.imgur.com/XM29k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XM29k.png" alt="enter image description here" /></a></p> <p>I tried this SQL but no luck</p> <pre><code>SELECT DISTINCT a.ESAProjectID, a.projecttype FROM test1 a INNER JOIN test1 b ON a.ESAProjectID = b.ESAProjectID WHERE a.projecttype = 'Group Project' </code></pre>
[ { "answer_id": 74572587, "author": "Dimanoid", "author_id": 1122806, "author_profile": "https://Stackoverflow.com/users/1122806", "pm_score": 1, "selected": false, "text": "this.user.pipe(...) user BehaviorSubject<User> this.userService.user.getValue() userService.loadUser() constructor(...) {\n this.userService.loadUser().subscribe(user => this.user = user);\n...\n}\n" }, { "answer_id": 74649983, "author": "Clifford Eby", "author_id": 3998720, "author_profile": "https://Stackoverflow.com/users/3998720", "pm_score": 0, "selected": false, "text": "this.user async pipe shareReplay this.user this.user = this.userService.loadUser().pipe(\n tap((user) => this.form.patchValue(user)),\n shareReplay()\n );\n this.user userProp() userProp() {\n let parsArray = [];\n let hCapsArray = [];\n let ci\n this.user.subscribe((user) => {\n parsArray = user.pars;\n hCapsArray = user.hCaps;\n ci = user.ci;\n });\n return [parsArray, hCapsArray, ci] as const;\n }\n ESA(value) {\n const data = this.userProp(); //First Subcription to User\n const pars = data[0];\n const hCaps = data[1];\n const ci = data[2];\n const value1 = [];\n value\n .forEach((x, index) =>\n x - pars[index] > 3\n ? (value1[index] = pars[index] + 3)\n : x - pars[index] > 2 && hCaps[index] >= ci\n ? (value1[index] = pars[index] + 2)\n : (value1[index] = x)\n );\n console.log('values', value1, value, pars, ci);\n return value1;\n }\n this.user async pipe and shareReplay this.user loadScoreControls(item)" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2681855/" ]
74,564,588
<p>I want my app in SwiftUI for macOS get shown or available to user with some sec delay like 5 sec delay, how can I do this? Just given more info, <strong>I want nothing shown to user in 5 sec</strong>, and after that Window get available to user. Also I know the use case of timer or DispatchQueue, but I have no idea how can I use them for making this delay.</p> <pre><code> @main struct test58App: App { var body: some Scene { WindowGroup { // Here, I want Window get shown to user with some delay like 5 sec delay! ContentView() } } } </code></pre>
[ { "answer_id": 74565701, "author": "Frederik Mrozek", "author_id": 17997003, "author_profile": "https://Stackoverflow.com/users/17997003", "pm_score": 1, "selected": false, "text": "@main\nstruct test2App: App {\n @State private var visible: Bool = false\n var body: some Scene {\n WindowGroup {\n Group {\n if visible {\n ContentView()\n }\n }\n .onAppear(perform: {\n DispatchQueue.main.asyncAfter(deadline: .now() + 5) {\n visible = true\n }\n })\n }\n }\n}\n" }, { "answer_id": 74565712, "author": "user1046037", "author_id": 1046037, "author_profile": "https://Stackoverflow.com/users/1046037", "pm_score": 0, "selected": false, "text": "ContentView struct ContentView: View {\n @State private var isReady = false\n var body: some View {\n Group {\n if isReady {\n Text(\"Ready\")\n } else {\n// Text(\"Not Ready\")\n EmptyView()\n }\n }\n .task {\n try? await Task.sleep(nanoseconds: 5_000_000_000)\n isReady = true\n }\n }\n}\n" }, { "answer_id": 74566400, "author": "Frederik Mrozek", "author_id": 17997003, "author_profile": "https://Stackoverflow.com/users/17997003", "pm_score": 0, "selected": false, "text": "@main\nstruct test2App: App {\n \n init() {\n NSApplication.shared.hide(nil)\n DispatchQueue.main.asyncAfter(deadline: .now() + 5) {\n NSApplication.shared.unhide(nil)\n NSApplication.shared.activate(ignoringOtherApps: true)\n }\n }\n \n var body: some Scene {\n WindowGroup {\n ContentView()\n }\n }\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20027993/" ]
74,564,595
<pre><code>class_day &lt;- c(1:10) control_group &lt;- c(67,72,69,81,73,66,71,72,77,71) A_treatment_group &lt;- c(NA,72,77,81,73,85,69,73,74,77) B_treatment_group &lt;- c(NA,66,68,69,67,72,73,75,79,77) class.df&lt;-data.frame(class_day, control_group, A_treatment_group, B_treatment_group) </code></pre> <p>I tried to convert vecotrs to a table but I am not sure how to include three categories in one plot.</p> <p>How can I get a scatter plot with three different colors? I would like to set x-axis as class_day above and y axis as scores.</p>
[ { "answer_id": 74564650, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 2, "selected": false, "text": "class.df<-data.frame(class_day = c(1:10),\n control_group = c(67,72,69,81,73,66,71,72,77,71), \n A_treatment_group = c(NA,72,77,81,73,85,69,73,74,77),\n B_treatment_group = c(NA,66,68,69,67,72,73,75,79,77) )\nlibrary(tidyverse)\nclass.df %>% \n pivot_longer(!class_day) %>% \n ggplot(aes(x=class_day, y=value, color=name))+\n geom_point()\n" }, { "answer_id": 74564963, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 0, "selected": false, "text": "ggscatter ggpubr library(ggpubr)\nlibrary(tidyverse)\n\nclass.df %>% \n pivot_longer(-class_day,\n names_to= \"group\", \n values_to = \"score\") %>% \n ggscatter(x = \"class_day\", y = \"score\", color = \"group\",\n palette = c(\"#00AFBB\", \"#E7B800\", \"#FC4E07\"))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20379598/" ]
74,564,598
<p>The script I'm working on is a ticket reserving bot for student events, it waits in the specified loop until sales start, and the write-progress is supposed to let you know when they do start. I'm fairly new to PowerShell and I'm sorry if the code is a sore for the eyes. I'm just baffled since this part did work earlier today, even though nothing about the loop changed iirc.</p> <p>Here is the relevant part of the script:</p> <pre><code>While ($currentDate -lt $purchaseTime){ $currentDate = Get-Date $waitTime = (New-TimeSpan -End $purchaseTime).TotalSeconds Write-Progress -Activity &quot;Waiting until sales start&quot; -SecondsRemaining $waitTime Start-Sleep -Milliseconds 10 If ($currentDate -ge $purchaseTime){continue} } </code></pre> <p>I also tried this:</p> <pre><code>Do { $currentDate = Get-Date $waitTime = (New-TimeSpan -End $purchaseTime).TotalSeconds Write-Progress -Activity &quot;Waiting until sales start&quot; -SecondsRemaining $waitTime Start-Sleep -Milliseconds 201 } until ($currentDate -gt $purchaseTime) </code></pre> <p>I tried changing the loop from While to Do and even If statements but nothing changed. Can anyone solve this? I'm not getting any errors either, it just won't render.</p> <p>EDIT 1 This is how the value is fetched, $jsonObject is made out of a GET request, and below is its value.</p> <pre><code> $purchaseTime = $jsonObject.model.product.dateSalesFrom &quot;2022-11-25T11:00:00+02:00&quot; </code></pre> <p>The format shouldn't be the issue, since they've been the same throughout the process of me writing this script. And it used to with that formatting too.</p> <p>I tried inserting the code suggested by Mathias before that declaration, but it didn't change the end result. Did he mean I should insert it within the loop? Would that screw it up since I really need it to be this static place in time in order for the script to work as intended. My PSVersion is 5.1. Should I post the entire script for clarity?</p> <p>EDIT 2.</p> <p>I have implemented the code that Santiago suggested as the answer, but nothing has changed. The progress still won't render. Could the issue be with how the date from the jsonobject is formatted? The code Santiago posted runs and works on its own in a powershell instance, so I doubt my settings or anything like that is not working as intended.</p> <p>Here is what the loop currently looks like:</p> <pre><code>$nowDate = Get-Date $targetDate = Get-Date $jsonObject.model.product.dateSalesFrom $timeSpan = $targetDate - $nowDate $stopWatch = [System.Diagnostics.Stopwatch]::StartNew() Do { $progess = @{ Activity = 'Waiting until sales start' SecondsRemaining = ($timeSpan - $stopWatch.Elapsed).TotalSeconds } Write-Progress @progess Start-Sleep -Milliseconds 200 } until($stopWatch.Elapsed -ge $timeSpan) </code></pre>
[ { "answer_id": 74564650, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 2, "selected": false, "text": "class.df<-data.frame(class_day = c(1:10),\n control_group = c(67,72,69,81,73,66,71,72,77,71), \n A_treatment_group = c(NA,72,77,81,73,85,69,73,74,77),\n B_treatment_group = c(NA,66,68,69,67,72,73,75,79,77) )\nlibrary(tidyverse)\nclass.df %>% \n pivot_longer(!class_day) %>% \n ggplot(aes(x=class_day, y=value, color=name))+\n geom_point()\n" }, { "answer_id": 74564963, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 0, "selected": false, "text": "ggscatter ggpubr library(ggpubr)\nlibrary(tidyverse)\n\nclass.df %>% \n pivot_longer(-class_day,\n names_to= \"group\", \n values_to = \"score\") %>% \n ggscatter(x = \"class_day\", y = \"score\", color = \"group\",\n palette = c(\"#00AFBB\", \"#E7B800\", \"#FC4E07\"))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20593176/" ]
74,564,607
<p>I am struggling with Text binding in my WPF app.</p> <ol> <li>Lets imagine that I have another working app (ex. windows service) with some data in it.</li> <li>In my WPF app I would like to have folder &quot;DATA&quot; with class where data are introduced and in same folder another class which would include a void which will query my windows service</li> <li>I would like to show this data in my WPF window.</li> </ol> <p>To make it simpler - one class with data, one class with data changing and WPF window with showing this data.</p> <p>Unfortunately I can not achieve this... When I am executing below code, my window is showing 0 instead 123.</p> <p>I would like to achive that my window will show value 123.</p> <ol> <li>file &quot;Database.cs&quot; in folder &quot;Data&quot; in project &quot;example&quot;</li> </ol> <pre><code>namespace example.Data { public class Database { private int _testInt = 0; public int testInt { get { return _testInt; } set { _testInt = value; } } } } </code></pre> <ol start="2"> <li>file &quot;Query.cs&quot; in folder &quot;Data&quot; in project &quot;example&quot;</li> </ol> <pre><code>namespace example.Data { public class Query { public Database _database; public void execute() { _database = new Database(); _database.testInt = 123; } } } </code></pre> <ol start="3"> <li>file &quot;MainWindow.xaml.cs&quot; in project &quot;example&quot;</li> </ol> <pre><code>namespace example { public partial class MainWindow : Window { public Data.Database _database; public Data.Query _query; public int testInt { get { return _database.testInt; } set { _database.testInt = value; OnPropertyChanged(); } } public MainWindow() { InitializeComponent(); DataContext = this; _database = new Data.Database(); _query = new Data.Query(); _query.execute(); } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } } #endregion } } </code></pre> <ol start="4"> <li>File MainWindow.xaml</li> </ol> <pre><code>&lt;Window&gt; &lt;TextBlock Text=&quot;{Binding testInt}&quot; Foreground=&quot;White&quot; FontSize=&quot;15&quot; VerticalAlignment=&quot;Top&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;20,10,10,0&quot; /&gt; &lt;/Window&gt; </code></pre> <p>P.S. If I will put</p> <pre><code>_database.testInt = 987; </code></pre> <p>to MainWindow.xaml.cs it is working properly - window is showing value 987 in textblock.</p>
[ { "answer_id": 74564679, "author": "Jason", "author_id": 1338, "author_profile": "https://Stackoverflow.com/users/1338", "pm_score": 0, "selected": false, "text": "INotifyPropertyChanged public partial class MainWindow : Window, INotifyPropertyChanged\n" }, { "answer_id": 74564990, "author": "Orace", "author_id": 361177, "author_profile": "https://Stackoverflow.com/users/361177", "pm_score": 1, "selected": true, "text": "Database Query.execute MainWindow Query _query = new Data.Query(_database);\n\n// ...\n\npublic class Query\n{\n private readonly Database _database;\n\n public Query(Database database)\n {\n _database = database;\n }\n\n public void Execute()\n {\n _database.testInt = 123;\n }\n}\n Database INotifyPropertyChanged" }, { "answer_id": 74565441, "author": "mrsopel", "author_id": 20592936, "author_profile": "https://Stackoverflow.com/users/20592936", "pm_score": -1, "selected": false, "text": "private Database _database; \npublic Query(Database database)\n{\n _database = database;\n} \n" }, { "answer_id": 74565574, "author": "deafjeff", "author_id": 1758906, "author_profile": "https://Stackoverflow.com/users/1758906", "pm_score": 0, "selected": false, "text": " public void execute(int value)\n {\n //_database = new Database();\n // inject _database like in the answer above\n _database.testInt = value;\n }\n testInt _query `public int testInt\n {get { return _database.testInt; } \n `set { _query.execute(value); OnPropertyChanged(); }`\n }\n public MainWindow()\n {\n InitializeComponent();\n DataContext = this;\n _database = new Data.Database();\n // the property change will change both the view and the model\n testInt = 987;\n }\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20592936/" ]
74,564,616
<p>Good afternoon! We're looking to get a javascript variable from a webpage, that we are usually able to retrieve typing <code>app</code> in the Chrome DevTools.</p> <p>However, we're looking to realize this headlessly as it has to be performed on numerous apps.</p> <p><strong>Our ideas :</strong></p> <ul> <li><p>Using a Puppeteer instance to go on the page, type the command and return the variable, which works, but it's very ressource consuming.</p> </li> <li><p>Using a GET/POST request to the page trying to inject the JS command, but we didn't succeed.</p> </li> </ul> <p>We're then wondering if there will be an easier solution, as a special API that could extract the variable? The goal would be to automate this process with no human interaction.</p> <p>Thanks for your help!</p>
[ { "answer_id": 74564679, "author": "Jason", "author_id": 1338, "author_profile": "https://Stackoverflow.com/users/1338", "pm_score": 0, "selected": false, "text": "INotifyPropertyChanged public partial class MainWindow : Window, INotifyPropertyChanged\n" }, { "answer_id": 74564990, "author": "Orace", "author_id": 361177, "author_profile": "https://Stackoverflow.com/users/361177", "pm_score": 1, "selected": true, "text": "Database Query.execute MainWindow Query _query = new Data.Query(_database);\n\n// ...\n\npublic class Query\n{\n private readonly Database _database;\n\n public Query(Database database)\n {\n _database = database;\n }\n\n public void Execute()\n {\n _database.testInt = 123;\n }\n}\n Database INotifyPropertyChanged" }, { "answer_id": 74565441, "author": "mrsopel", "author_id": 20592936, "author_profile": "https://Stackoverflow.com/users/20592936", "pm_score": -1, "selected": false, "text": "private Database _database; \npublic Query(Database database)\n{\n _database = database;\n} \n" }, { "answer_id": 74565574, "author": "deafjeff", "author_id": 1758906, "author_profile": "https://Stackoverflow.com/users/1758906", "pm_score": 0, "selected": false, "text": " public void execute(int value)\n {\n //_database = new Database();\n // inject _database like in the answer above\n _database.testInt = value;\n }\n testInt _query `public int testInt\n {get { return _database.testInt; } \n `set { _query.execute(value); OnPropertyChanged(); }`\n }\n public MainWindow()\n {\n InitializeComponent();\n DataContext = this;\n _database = new Data.Database();\n // the property change will change both the view and the model\n testInt = 987;\n }\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19762598/" ]
74,564,625
<p>I work inside a research environment and I can't copy paste the code I used there, but I have <a href="https://stackoverflow.com/questions/73961307/how-to-label-plot-with-value-of-bars">previously generated this plot</a>, and have been helped by various people in labelling it with the count number. The problem arises when I screenshot the plot from inside the research environment, and the legends are illegible. I am hoping I can address this by making the labels (including the X-axis label) all bold.</p> <p>I used some mock-data outside the environment and this is what I have so far.</p> <pre><code>library(ggplot2) library(reshape2) md.df = melt(df, id.vars = c('Group.1')) tmp = c(&quot;virginica&quot;,&quot;setosa&quot;,&quot;versicolor&quot;) md.df2 = md.df[order(match(md.df$Group.1, tmp)),] md.df2$Group.1 = factor(as.character(md.df2$Group.1), levels = unique(md.df2$Group.1)) ggplot(md.df2, aes(x = Group.1, y = value, group = variable, fill = variable)) + geom_bar(stat=&quot;identity&quot;,color='black', position = &quot;dodge&quot;) + xlab('Species') + ylab('Values') + theme_bw()+ ylim(0,8)+ theme(text = element_text(size=16), axis.text.x = element_text(angle=0, hjust=.5), plot.title = element_text(hjust = 0.5), plot.subtitle = element_text(hjust = 0.5))+ ggtitle(&quot;Order variables in barplot&quot;)+ geom_text(aes(label=value), vjust=-0.3, size=4, # adding values position = position_dodge(0.9))+ element_text(face=&quot;bold&quot;) </code></pre> <p>I need to make the labels onto bold, and the element_text isn't working mainly because I am probably using it in the wrong way. I'd appreciate any help with this.</p> <p>An example of this plot which I haven't been able to find mock data to re-create outside the environment, <a href="https://stackoverflow.com/questions/73953472/sorting-ggplot-columns">have asked a question about in the past</a>, is the one where the axis ticks also need to be made bold. This is because the plot is illegible from the outside.</p> <p>I've tried addressing the illegibility by saving all my plots using ggsave in 300 resolution but it is very illegible.</p> <p>I'd appreciate any help with this, and thank you for taking the time to help with this. <a href="https://i.stack.imgur.com/cJBGz.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cJBGz.jpg" alt="enter image description here" /></a></p>
[ { "answer_id": 74564820, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 3, "selected": true, "text": "geom_text(..., fontface = \"bold\") axis.text.x = element_text(angle=0, hjust=.5, face = \"bold\") ggplot2::mpg library(ggplot2)\nlibrary(dplyr)\n\n# Create exmaple data\nmd.df2 <- mpg |>\n count(Group.1 = manufacturer, name = \"value\") |>\n mutate(\n variable = value >= max(value),\n Group.1 = reorder(Group.1, -value)\n )\n\nggplot(md.df2, aes(x = Group.1, y = value, group = variable, fill = variable)) +\n geom_col(color = \"black\", position = \"dodge\") +\n geom_text(aes(label = value), vjust = -0.3, size = 4, position = position_dodge(0.9), fontface = \"bold\") +\n labs(x = \"Species\", y = \"Values\", title = \"Order variables in barplot\") +\n theme_bw() +\n theme(\n text = element_text(size = 16),\n axis.text.x = element_text(angle = 90, vjust = .5, face = \"bold\"),\n plot.title = element_text(hjust = 0.5),\n plot.subtitle = element_text(hjust = 0.5)\n )\n" }, { "answer_id": 74566242, "author": "I_O ", "author_id": 20513099, "author_profile": "https://Stackoverflow.com/users/20513099", "pm_score": 0, "selected": false, "text": "## ... plot code +\n theme(## other settings ...,\n axis.ticks = element_line(linewidth = 5),\n axis.ticks.length = unit(10, 'pt'))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7825736/" ]
74,564,633
<p>I’m looking for something like <code>Record.Do</code> with <code>Record.bind</code> so I can do something like this</p> <pre><code>function getB: (a:A) =&gt; B function getC: (b: B) =&gt; C function getD: (c: C) =&gt; D type Z = { a: A, b: B, c: C, d: D, } const getZ = (a: A): Z =&gt; pipe( R.Do, R.bind('a', () =&gt; a), R.bind('b', () =&gt; getB(a)), R.bind('c', (bindings) =&gt; getC(bindings.b)), R.bind('d', (bindings) =&gt; getD(bindings.c)), ) </code></pre> <p>I basically want to construct an object of different types while retaining all the inner objects of different types before applying some transformations on them</p> <p>Not sure how to go about achieving this. I don’t want to take my types to other domains like <code>Option</code>, <code>Either</code>, <code>IO</code>; I feel like that just adds more code using <code>O.some</code>(s) or <code>E.right</code>(s) or <code>IO.of</code>(s) for transformations that don’t error.</p> <p>This is the closes I could get</p> <pre><code>const getZ = (a: A): Z =&gt; pipe( IO.Do, IO.bind('a', () =&gt; () =&gt; a), IO.bind('b', () =&gt; () =&gt; getB(a)), IO.bind('c', (bindings) =&gt; () =&gt; getC(bindings.b)), IO.bind('d', (bindings) =&gt; () =&gt; getD(bindings.c)), )() </code></pre>
[ { "answer_id": 74564769, "author": "Manav Chawla", "author_id": 5895968, "author_profile": "https://Stackoverflow.com/users/5895968", "pm_score": 0, "selected": false, "text": "const getZ = (a:A): Z => {\n const b = getB(a)\n const c = getC(b)\n const d = getD(c)\n return ({a, b, c, d})\n}\n\n const getZ = (a: A): Z => pipe(\n a,\n (a) => ({ b: getB(a), a}),\n (bindings) => ({ c: getC(bindings.b), ...bindings })\n (bindings) => ({ d: getD(bindings.c), ...bindings })\n)\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5895968/" ]
74,564,636
<pre><code>[{ &quot;resource&quot;: &quot;/d:/Users/Home/Desktop/Python/estudos/pratices.py&quot;, &quot;owner&quot;: &quot;_generated_diagnostic_collection_name_#0&quot;, &quot;code&quot;: { &quot;value&quot;: &quot;reportMissingModuleSource&quot;, &quot;target&quot;: { &quot;$mid&quot;: 1, &quot;external&quot;: &quot;https://github.com/microsoft/pyright/blob/main/docs/configuration.md#reportMissingModuleSource&quot;, &quot;path&quot;: &quot;/microsoft/pyright/blob/main/docs/configuration.md&quot;, &quot;scheme&quot;: &quot;https&quot;, &quot;authority&quot;: &quot;github.com&quot;, &quot;fragment&quot;: &quot;reportMissingModuleSource&quot; } }, &quot;severity&quot;: 4, &quot;message&quot;: &quot;Import \&quot;pandas\&quot; could not be resolved from source&quot;, &quot;source&quot;: &quot;Pylance&quot;, &quot;startLineNumber&quot;: 1, &quot;startColumn&quot;: 8, &quot;endLineNumber&quot;: 1, &quot;endColumn&quot;: 14 }] </code></pre> <p>is the message given the cmd shell tells me i have all the libraries i want installed and they're in the project folder, i'm running a virtual environment but whenever i try to run something in a .py file, it says that it's not defined, i have installed anaconda but don't mean to use it right now, if i open a jupyter file it'll import no problem, but trying to run pip doesn't work at all</p> <p>reinstalling vscode, making sure python's installed, making sure pip is installed</p>
[ { "answer_id": 74564769, "author": "Manav Chawla", "author_id": 5895968, "author_profile": "https://Stackoverflow.com/users/5895968", "pm_score": 0, "selected": false, "text": "const getZ = (a:A): Z => {\n const b = getB(a)\n const c = getC(b)\n const d = getD(c)\n return ({a, b, c, d})\n}\n\n const getZ = (a: A): Z => pipe(\n a,\n (a) => ({ b: getB(a), a}),\n (bindings) => ({ c: getC(bindings.b), ...bindings })\n (bindings) => ({ d: getD(bindings.c), ...bindings })\n)\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20460171/" ]
74,564,654
<p>I have a question on using regular expressions in Python. This is a part of the text I am analysing.</p> <pre><code>Amit Jawaharlaz Daryanani, Evercore ISI Institutional Equities, Research Division - Senior MD &amp; Fundamental Research Analyst [19]\n I have 2 as well. I guess, first off, on the channel inventory, I was hoping if you could talk about how did channel inventory look like in the March quarter because it sounds like it may be below the historical ranges. And then the discussion you had for June quarter performance of iPhones, what are you embedding from a channel building back inventory levels in that expectation?\n </code></pre> <p>My Goal is to extract this part of the text by matching the name of the analyst which is Amit Jawaharlaz Daryanani: \n I have 2 as well. I guess, first off, on the channel inventory, I was hoping if you could talk about how did channel inventory look like in the March quarter because it sounds like it may be below the historical ranges. And then the discussion you had for June quarter performance of iPhones, what are you embedding from a channel building back inventory levels in that expectation?\n</p> <p>I cannot just do from \n to \n because the text is much longer and I specifically need the line of text which comes after his name.</p> <p>I tried: re.findall(r'(?&lt;=Amit Jawaharlaz Daryanani).*?(?=\n)', text)</p> <p>But the Output here is</p> <pre><code>[', Evercore ISI Institutional Equities, Research Division - Senior MD &amp; Fundamental Research Analyst [19]' </code></pre> <p>So how can I start after the first \n that comes after his name until the second \n after his name?</p>
[ { "answer_id": 74564676, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 3, "selected": true, "text": "\\bAmit Jawaharlaz Daryanani\\b.*\\n\\s*(.*)\\n\n \\bAmit Jawaharlaz Daryanani\\b .*\\n \\s*(.*)\\n import re\n\npattern = r\"\\bAmit Jawaharlaz Daryanani\\b.*\\n\\s*(.*)\\n\"\n\ns = (\"Amit Jawaharlaz Daryanani, Evercore ISI Institutional Equities, Research Division - Senior MD & Fundamental Research Analyst [19]\\n\"\n \" I have 2 as well. I guess, first off, on the channel inventory, I was hoping if you could talk about how did channel inventory look like in the March quarter because it sounds like it may be below the historical ranges. And then the discussion you had for June quarter performance of iPhones, what are you embedding from a channel building back inventory levels in that expectation?\\n\"\n \" \\n\")\n\nm = re.search(pattern, s)\nif m:\n print(m.group(1))\n I have 2 as well. I guess, first off, on the channel inventory, I was hoping if you could talk about how did channel inventory look like in the March quarter because it sounds like it may be below the historical ranges. And then the discussion you had for June quarter performance of iPhones, what are you embedding from a channel building back inventory levels in that expectation?\n" }, { "answer_id": 74564689, "author": "Cam", "author_id": 2045611, "author_profile": "https://Stackoverflow.com/users/2045611", "pm_score": 1, "selected": false, "text": "\\n \\n re.findall(r'(?:Amit Jawaharlaz Daryanani).*?\\n(.*?)\\n', text)\n .*? \\n [' I have 2 as well. I guess, first off, on the channel inventory, I was hoping if you could talk about how did channel inventory look like in the March quarter because it sounds like it may be below the historical ranges. And then the discussion you had for June quarter performance of iPhones, what are you embedding from a channel building back inventory levels in that expectation?']\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15788507/" ]
74,564,659
<p>I want to make imagecircleview and textview lie side by side in xml kotlin android. I have tried this but the textview lies above the imageview. The button is also above the image which I want at the bottom.</p> <p>I also would appreciate a brief description of the main android layout attributes.<a href="https://i.stack.imgur.com/8aIFd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8aIFd.png" alt="user profile ui" /></a></p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; xmlns:tools=&quot;http://schemas.android.com/tools&quot; android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;fill_parent&quot; tools:context=&quot;.FirstFragment&quot;&gt; &lt;LinearLayout android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:orientation=&quot;horizontal&quot;&gt; &lt;de.hdodenhof.circleimageview.CircleImageView android:id=&quot;@+id/imageview_profile&quot; android:layout_width=&quot;120dp&quot; android:layout_height=&quot;120dp&quot; android:src=&quot;@drawable/kaleab_profile&quot; android:layout_marginTop=&quot;60dp&quot;/&gt; &lt;TextView android:id=&quot;@+id/textview_first&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;match_parent&quot; android:text=&quot;Kaleab Woldemariam&quot; android:textColor=&quot;#000&quot; android:textStyle=&quot;bold&quot; android:layout_marginTop=&quot;5dp&quot;/&gt; &lt;/LinearLayout&gt; &lt;Button android:id=&quot;@+id/button_first&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:text=&quot;@string/previous&quot; android:layout_centerHorizontal=&quot;true&quot; app:layout_constraintBottom_toBottomOf=&quot;parent&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@id/textview_first&quot; /&gt; &lt;/RelativeLayout&gt; </code></pre>
[ { "answer_id": 74564676, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 3, "selected": true, "text": "\\bAmit Jawaharlaz Daryanani\\b.*\\n\\s*(.*)\\n\n \\bAmit Jawaharlaz Daryanani\\b .*\\n \\s*(.*)\\n import re\n\npattern = r\"\\bAmit Jawaharlaz Daryanani\\b.*\\n\\s*(.*)\\n\"\n\ns = (\"Amit Jawaharlaz Daryanani, Evercore ISI Institutional Equities, Research Division - Senior MD & Fundamental Research Analyst [19]\\n\"\n \" I have 2 as well. I guess, first off, on the channel inventory, I was hoping if you could talk about how did channel inventory look like in the March quarter because it sounds like it may be below the historical ranges. And then the discussion you had for June quarter performance of iPhones, what are you embedding from a channel building back inventory levels in that expectation?\\n\"\n \" \\n\")\n\nm = re.search(pattern, s)\nif m:\n print(m.group(1))\n I have 2 as well. I guess, first off, on the channel inventory, I was hoping if you could talk about how did channel inventory look like in the March quarter because it sounds like it may be below the historical ranges. And then the discussion you had for June quarter performance of iPhones, what are you embedding from a channel building back inventory levels in that expectation?\n" }, { "answer_id": 74564689, "author": "Cam", "author_id": 2045611, "author_profile": "https://Stackoverflow.com/users/2045611", "pm_score": 1, "selected": false, "text": "\\n \\n re.findall(r'(?:Amit Jawaharlaz Daryanani).*?\\n(.*?)\\n', text)\n .*? \\n [' I have 2 as well. I guess, first off, on the channel inventory, I was hoping if you could talk about how did channel inventory look like in the March quarter because it sounds like it may be below the historical ranges. And then the discussion you had for June quarter performance of iPhones, what are you embedding from a channel building back inventory levels in that expectation?']\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4317594/" ]
74,564,671
<p>What I'm trying to do is this:</p> <pre><code>interface A { a: number b: number } function f&lt;T extends A&gt;() { const x: Partial&lt;Record&lt;keyof T, string&gt;&gt; = {a: 'generz'} console.log(x) } </code></pre> <p>But, when compiling (using <code>tsc v4.9.3</code>) I get this error message:</p> <pre><code>error TS2322: Type '{ a: &quot;generz&quot;; }' is not assignable to type 'Partial&lt;Record&lt;keyof T, string&gt;&gt;'. </code></pre> <p>I don't understand why and <strong>I would like to have an explanation on this error.</strong> If <code>T extends A</code> then <code>keyof T</code> is a superset of <code>keyof A</code> (containing at least <code>'a'|'b'</code>), so the <code>{a: 'generz'}</code> would be legal independently of <code>T</code>? Am i missing something?</p> <hr /> <p>I've found out, that creating a custom <code>PartialRecord</code> type (described <a href="https://stackoverflow.com/questions/53276792/define-a-list-of-optional-keys-for-typescript-record">here</a>) like this:</p> <pre><code>type PartialRecord&lt;K extends keyof any, T&gt; = { [P in K]?: T } </code></pre> <p>And then changing the type of variable <code>x</code> to <code>PartialRecord&lt;keyof T, string&gt;</code> , like this:</p> <pre><code>const x: PartialRecord&lt;keyof T, string&gt; = {a: 'generz'} </code></pre> <p>Compiles the code without complaining.</p> <hr /> <h2>Update 2022-11-25</h2> <p>This would be equivalent code and it compiles too:</p> <pre><code>const x: Partial&lt;Record&lt;keyof T, string&gt;&gt; = {} x.a = 'generz' </code></pre> <p>Although is not what i'll like to do.</p> <hr /> <h2>Update 2022-11-29</h2> <p><strong>What I'm asking is NOT &quot;how to make it work in alternative ways&quot;, but is &quot;why it doesn't work that way&quot;</strong>, since I expect it to work. Otherwise I'd just do <code>{a: 'generz'} as Partial&lt;Record&lt;keyof T, string&gt;&gt;</code> (or worse <code>as any</code>).</p> <p>And if it wasn't clear: the code is nothing more than the minimum necessary to reproduce the error. So its purpose is not to make sense or do anything useful.</p>
[ { "answer_id": 74601661, "author": "dubble", "author_id": 17867284, "author_profile": "https://Stackoverflow.com/users/17867284", "pm_score": -1, "selected": false, "text": "function f<T extends A>() {\n const x: Partial<Record<keyof T, string>> = { a: 'generz' }\n // Type `{ a: \"generz\"; }` is not assignable to...\n return x\n}\n\nconst a = f<\n {\n a: number\n b: number\n } & {\n c: () => number\n }\n>()\n if (a.c) doWithString(a.c)\n doWithString a.c x x c x x c c keyof T keyof T keyof x x extends equal satisfies function fn<T extends A>() {\n const x = {a: 'generz'} satisfies {[K in keyof T]?: string }\n return x\n}\n\nconst x = fn()\n/* {\n a: string;\n} */\n\n interface A {\n a: number\n b: number\n}\n x Record<keyof T, ...> T Partial<Record<keyof A, ...> T function fn<T extends A>( /* normally we use the parameter here */ ) {}\n Partial<A> A Partial<Record<Keyof A, ...>> function createA() {\n const a: Partial<Record<keyof A, string>> = {a: 'generz'}\n return a\n}\n t T A x T A string function createB<T extends A>(t?: T) {\n const x: { [K in keyof T]?: string } = { a: 'generz' }\n return x\n}\n\nconst b = createB({\n a: 1,\n b: 2,\n c: 3,\n}) \n// the input object's values were numbers.\n// now they are strings | undefined.\n/* { \n a?: string | undefined; \n b?: string | undefined; \n c?: string | undefined \n} */\n\n\nconst b2 = createB()\n// t was not given.\n// b2 does not include any additional properties,\n// only the known properties of A.\n/* {\n a?: string | undefined;\n b?: string | undefined;\n} */\n t interface C {\n a: () => void\n}\n\nfunction createC<T extends A>(t: T) {\n const x: {\n [K in keyof C]?: C[K]\n } & {\n [K in Exclude<keyof T, keyof C>]?: string\n } = {\n ...Object.entries(t)\n .map(([k, v]) => {\n return [k, 'generz'] as [keyof T, string]\n })\n .reduce((acc, [key, str]) => {\n acc[key] = str\n return acc\n }, {} as { [K in keyof T]?: string }),\n a: () => console.log('rotunda')\n }\n\n // consolidate the intersection into a more readable type.\n return x as typeof x extends infer U ? { [K in keyof U]: U[K] } : never\n}\n\nconst c = createC({\n a: 1,\n b: 2\n})\n// c \"maybe\" has all property keys of `T`,\n// but all property values are type `string`,\n// and if `T` had a property,`K`, of `C`, it has been replaced by `C[K]`\n/* {\n a?: (() => void) | undefined;\n b?: string | undefined;\n} */\n\nc.a?.() // rotunda\n" }, { "answer_id": 74621415, "author": "Tobias S.", "author_id": 8613630, "author_profile": "https://Stackoverflow.com/users/8613630", "pm_score": 2, "selected": true, "text": "Record<keyof T, string> Partial Record Partial Record<keyof T, string> Partial Partial Omit Pick<T, Exclude<keyof T, K>> & Pick<T, Extract<keyof T, K>> T" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2394898/" ]
74,564,685
<p>R noob here, working in <code>tidyverse</code> / RStudio.</p> <p>I have a categorical / factor variable that I'd like to retain in a <code>group_by</code>/<code>summarize</code> workflow. I'd like to <code>summarize</code> it using a summary function that returns the most common value of that factor within each group.</p> <p>Is there a summary function I can use for this?</p> <p><code>mean</code> returns <code>NA</code>, <code>median</code> only works with numeric data, and <code>summary</code> gives me separate rows with counts of each factor level instead of the most common level.</p> <p>Edit: example using subset of <code>mtcars</code> dataset:</p> <pre><code>mpg cyl disp hp drat wt qsec vs am gear carb &lt;dbl&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; &lt;dbl&gt; &lt;fct&gt; 21 6 160 110 3.9 2.62 16.5 0 1 4 4 21 6 160 110 3.9 2.88 17.0 0 1 4 4 22.8 4 108 93 3.85 2.32 18.6 1 1 4 1 21.4 6 258 110 3.08 3.22 19.4 1 0 3 1 18.7 8 360 175 3.15 3.44 17.0 0 0 3 2 18.1 6 225 105 2.76 3.46 20.2 1 0 3 1 14.3 8 360 245 3.21 3.57 15.8 0 0 3 4 24.4 4 147. 62 3.69 3.19 20 1 0 4 2 22.8 4 141. 95 3.92 3.15 22.9 1 0 4 2 19.2 6 168. 123 3.92 3.44 18.3 1 0 4 4 </code></pre> <p>Here I have converted <code>carb</code> into a factor variable. In this subset of the data, you can see that among 6-cylinder cars there are 3 with <code>carb=4</code> and 1 with <code>carb=1</code>; similarly among 4-cylinder cars there are 2 with <code>carb=2</code> and 1 with <code>carb=1</code>.</p> <p>So if I do:</p> <pre><code>data %&gt;% group_by(cyl) %&gt;% summarise(modalcarb = FUNC(carb)) </code></pre> <p>where <code>FUNC</code> is the function I'm looking for, I should get:</p> <pre><code>cyl carb &lt;dbl&gt; &lt;fct&gt; 4 2 6 4 8 2 # there are multiple potential ways of handling multi-modal situations, but that's secondary here </code></pre> <p>Hope that makes sense!</p>
[ { "answer_id": 74565029, "author": "Quinten", "author_id": 14282714, "author_profile": "https://Stackoverflow.com/users/14282714", "pm_score": 3, "selected": true, "text": "fmode collapse mtcars cyl library(dplyr)\nlibrary(collapse)\n\nmtcars %>%\n mutate(cyl = as.factor(cyl)) %>%\n group_by(cyl) %>%\n summarise(mode = fmode(am))\n#> # A tibble: 3 × 2\n#> cyl mode\n#> <fct> <dbl>\n#> 1 4 1\n#> 2 6 0\n#> 3 8 0\n" }, { "answer_id": 74565048, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 1, "selected": false, "text": "which.max count library(dplyr)\n\n# fake dataset\nx <- mtcars %>% \n mutate(cyl = factor(cyl)) %>% \n select(cyl) \n\nx %>% \n count(cyl) %>% \n slice(which.max(n))\n cyl n\n <fct> <int>\n1 8 14\n" }, { "answer_id": 74566572, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 0, "selected": false, "text": "which.max table library(tidyverse)\n\nmtcars |>\n group_by(cyl) |>\n summarise(modalcarb = carb[which.max(table(carb))])\n#> # A tibble: 3 x 2\n#> cyl modalcarb\n#> <dbl> <dbl>\n#> 1 4 2\n#> 2 6 4\n#> 3 8 3\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12305295/" ]
74,564,691
<p>When using <code>@Secured</code> on a REST-Controller, implementing an interface, the Controller is not found in a <code>@WebMvcTest</code>. Either removing the @Secured annotation or removing the implements on the class will make it run in the test.</p> <pre><code>@Controller @RequestMapping(path=&quot;/failing&quot;) public class FailingTestController implements MyPasswordApi { @RequestMapping(method = GET, produces = MediaType.APPLICATION_JSON_VALUE, path = &quot;/test&quot;) @Secured(&quot;ROLE_USER&quot;) public ResponseEntity&lt;GetEntity&gt; getMethod() </code></pre> <p>and</p> <pre><code>@Controller @RequestMapping(path = &quot;/running&quot;) public class RunningTestController { @RequestMapping(method = GET, produces = MediaType.APPLICATION_JSON_VALUE, path = &quot;/test&quot;) @Secured(&quot;ROLE_USER&quot;) public ResponseEntity&lt;GetEntity&gt; getMethod() { </code></pre> <p>are both used in different jUnit-5 Tests. The &quot;RunningTest&quot; will succeed (i.e. the GET-Request will have status 200), whereas the &quot;FailingTest&quot; will end up with a status 404. Using the injected <code>RequestMapppingHanderMapping</code> one can see, that the controller with the inheritance is not bound.</p> <p>In fact, in the application, both controllers are found.</p> <p>My question is, how to test an controller implementing security <em>and</em> an interface.</p> <p>A testcase is found on github: <a href="https://github.com/sanddorn/Spring-Boot-Security-Rest-Showcase" rel="nofollow noreferrer">https://github.com/sanddorn/Spring-Boot-Security-Rest-Showcase</a></p>
[ { "answer_id": 74564778, "author": "viking", "author_id": 19741639, "author_profile": "https://Stackoverflow.com/users/19741639", "pm_score": -1, "selected": false, "text": "@RestController\n@RequestMapping(path = \"/running\")\npublic class RunningTestController {\n}\n" }, { "answer_id": 74570026, "author": "Nils Bokermann", "author_id": 5545821, "author_profile": "https://Stackoverflow.com/users/5545821", "pm_score": 0, "selected": false, "text": "@SpringBootApplication @EnableGlobalMethodSecurity @SpringBootApplication\n@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)\npublic class TestApplication {\n public static void main(String []argv) {\n SpringApplication.run(TestApplication.class);\n }\n}\n @Configuration\n@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)\npublic class TestConfiguration {\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5545821/" ]
74,564,700
<p>I am trying to get a total by using the <code>forEach</code> in javascript but failing somehow... It just lists the values rather than giving me the total figure</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>const finances = [ ["Jan", 867884], ["Feb", 984655], ["Mar", 322013], ["Apr", -69417], ["May", 310503], ]; let sum2 = 0; for (let i = 0; i &lt; finances.length - 1; i++) { let monthDiff = finances[i][1] - finances[i + 1][1]; // console.log(monthDiff) // console.log(typeof(monthDiff)) const newArray = [monthDiff]; // console.log(newArray) newArray.forEach((item) =&gt; { sum2 += item; console.log(sum2); //listing values not giving me a total why? }); }</code></pre> </div> </div> </p>
[ { "answer_id": 74564810, "author": "Daniel Benisti", "author_id": 10022794, "author_profile": "https://Stackoverflow.com/users/10022794", "pm_score": 0, "selected": false, "text": "const array1 = [1, 2, 3, 4];\n// 0 + 1 + 2 + 3 + 4\nconst initialValue = 0;\nconst sumWithInitial = array1.reduce(\n (accumulator, currentValue) => accumulator + currentValue,\n initialValue\n);\n\nconsole.log(sumWithInitial);\n// expected output: 10\n" }, { "answer_id": 74564812, "author": "Sundara Moorthy Anandh", "author_id": 6477821, "author_profile": "https://Stackoverflow.com/users/6477821", "pm_score": 1, "selected": false, "text": " const finances = [[\"Jan\", 867884], [\"Feb\", 984655], [\"Mar\", 322013], [\"Apr\", -69417], [\"May\", 310503]];\n \n const total = finances.reduce(\n (currentSum, currentValue) => currentValue[1] + currentSum\n , 0); // initial sum is zero\n \n console.log(total) const finances = [[\"Jan\", 867884], [\"Feb\", 984655], [\"Mar\", 322013], [\"Apr\", -69417], [\"May\", 310503]];\n \n let total = 0;\n finances.forEach(item => total = item[1] + total);\n console.log(total)" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20581800/" ]
74,564,728
<p>I'm trying to use Kafka ByteArrayDeserializer to read avro records from a Kafka topic. But getting below exception.</p> <pre><code>Caused by: java.lang.ClassCastException: [B cannot be cast to java.lang.String </code></pre> <p>My Code:</p> <pre><code>val ssc = new StreamingContext(spark.sparkContext, Seconds(1)) val kafkaParams: Map[String, Object] = Map( &quot;bootstrap.servers&quot; -&gt; &quot;kafka-server:9092&quot;, &quot;key.serializer&quot; -&gt; classOf[StringSerializer], &quot;value.serializer&quot; -&gt; classOf[StringSerializer], &quot;key.deserializer&quot; -&gt; classOf[StringDeserializer], &quot;value.deserializer&quot; -&gt; classOf[ByteArrayDeserializer], &quot;auto.offset.reset&quot; -&gt; &quot;earliest&quot;, &quot;enable.auto.commit&quot; -&gt; (false: java.lang.Boolean), &quot;security.protocol&quot; -&gt; &quot;SSL&quot;, &quot;ssl.truststore.location&quot; -&gt; &quot;truststore&quot;, &quot;ssl.truststore.password&quot; -&gt; &quot;pass&quot;, &quot;ssl.keystore.location&quot; -&gt; &quot;keystore.jks&quot;, &quot;ssl.keystore.password&quot; -&gt; &quot;pass&quot;, &quot;group.id&quot; -&gt; &quot;group1&quot; ) val topics: Array[String] = Array(&quot;topics&quot;) val kafkaDstream = KafkaUtils.createDirectStream( ssc, LocationStrategies.PreferConsistent, ConsumerStrategies.Subscribe[String, String](topics, kafkaParams) ) val schema = parser.parse(new String(Files.readAllBytes(Paths.get(&quot;avro2.avsc&quot;)))) val datumReader = new SpecificDatumReader[GenericRecord](schema) val processedStream = kafkaDstream.map(record =&gt; { val x = new ByteArrayInputStream(record.value().getBytes()) // throwing exception here val binaryDecoder = DecoderFactory.get.binaryDecoder(x, null) datumReader.read(null, binaryDecoder) }) processedStream.map(rec =&gt; rec.get(&quot;taskId&quot;)).print </code></pre> <p>Any help is appretiated.</p> <p>Thank you.</p>
[ { "answer_id": 74566310, "author": "OneCricketeer", "author_id": 2308683, "author_profile": "https://Stackoverflow.com/users/2308683", "pm_score": 3, "selected": true, "text": "Subscribe[String, String] Subscribe[String, Array[Byte]] record.value()" }, { "answer_id": 74571707, "author": "Jacek Laskowski", "author_id": 1305344, "author_profile": "https://Stackoverflow.com/users/1305344", "pm_score": 1, "selected": false, "text": "[B java.lang.String [B Array[Byte] jshell> byte[] bytes = new byte[10]\nbytes ==> byte[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }\n\njshell> bytes.toString()\n$2 ==> \"[B@6e8cf4c6\"\n String val x = new ByteArrayInputStream(record.value().getBytes()) // throwing exception here\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15982497/" ]
74,564,730
<p>I'm trying to make an countdown timer set to 1 hour , when the hour is done , the timer should redirect people to a specific page.</p> <p>My current code is not working as intended since its not storing in localstorage the countdown after a refresh of the page.</p> <pre><code>&lt;div id='stored'&gt;&lt;/div&gt; &lt;script&gt; function countdown(minutes, seconds ) { var endTime, hours, mins, msLeft, time; function twoDigits( n ) { return (n &lt;= 9 ? '0' + n : n); } function updateTimer() { msLeft = endTime - (+new Date); if ( msLeft &lt; 1000 ) { window.location.replace('done'); } else { time = new Date( msLeft ); hours = time.getUTCHours(); mins = time.getUTCMinutes(); localStorage.setItem('timelol', (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() )); document.getElementById('stored').innerHTML = localStorage.getItem('timelol'); setTimeout( updateTimer, time.getUTCMilliseconds() + 500 ); } } endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500; updateTimer(); } countdown( 60,0 ); </code></pre>
[ { "answer_id": 74566310, "author": "OneCricketeer", "author_id": 2308683, "author_profile": "https://Stackoverflow.com/users/2308683", "pm_score": 3, "selected": true, "text": "Subscribe[String, String] Subscribe[String, Array[Byte]] record.value()" }, { "answer_id": 74571707, "author": "Jacek Laskowski", "author_id": 1305344, "author_profile": "https://Stackoverflow.com/users/1305344", "pm_score": 1, "selected": false, "text": "[B java.lang.String [B Array[Byte] jshell> byte[] bytes = new byte[10]\nbytes ==> byte[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }\n\njshell> bytes.toString()\n$2 ==> \"[B@6e8cf4c6\"\n String val x = new ByteArrayInputStream(record.value().getBytes()) // throwing exception here\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20084394/" ]
74,564,755
<p><img src="https://i.stack.imgur.com/7dp33.png" alt="Problem outline" /></p> <p>This is the solution I have come up with but I'm unsure whether this is the best possible solution as far as Big (O) notation is concerned...</p> <pre><code>def solution(A): B = [0, 0, 0, 0, 0] for i in range (len(A)): if A[i] == &quot;Cardiology&quot;: B[0] += 1 elif A[i] == &quot;Neurology&quot;: B[1] += 1 elif A[i] == &quot;Orthopaedics&quot;: B[2] += 1 elif A[i] == &quot;Gynaecology&quot;: B[3] += 1 elif A[i] == &quot;Oncology&quot;: B[4] += 1 max_patients = max(B) return max_patients </code></pre>
[ { "answer_id": 74566310, "author": "OneCricketeer", "author_id": 2308683, "author_profile": "https://Stackoverflow.com/users/2308683", "pm_score": 3, "selected": true, "text": "Subscribe[String, String] Subscribe[String, Array[Byte]] record.value()" }, { "answer_id": 74571707, "author": "Jacek Laskowski", "author_id": 1305344, "author_profile": "https://Stackoverflow.com/users/1305344", "pm_score": 1, "selected": false, "text": "[B java.lang.String [B Array[Byte] jshell> byte[] bytes = new byte[10]\nbytes ==> byte[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }\n\njshell> bytes.toString()\n$2 ==> \"[B@6e8cf4c6\"\n String val x = new ByteArrayInputStream(record.value().getBytes()) // throwing exception here\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14683805/" ]
74,564,760
<p>I've seen this question a lot, and I feel like I've tried most suggestions, but I can't get it to work. For now, I'm just logging the messageCreate event, but it just won't work. Help would be very much appreciated.</p> <p>This is my code:</p> <p>as you can see I've tried a couple things^^</p> <pre><code> const { GatewayIntentBits, Partials, Guilds, Events } = require('discord.js'); const Discord = require('discord.js'); const Client = new Discord.Client({ intents: [ /* GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.DirectMessages, GatewayIntentBits.DirectMessageTyping, GatewayIntentBits.MessageContent, */ 'Guilds', 'GuildMessages', 'DirectMessages', 'MessageContent' ], partials: [ /* Partials.Channel, Partials.GuildMember, Partials.Message, Partials.MessageReaction, Partials.User, Partials.GuildMessages, Discord.PartialGroupDMChannel */ &quot;CHANNEL&quot;, &quot;GUILD_MEMBER&quot;, &quot;MESSAGES&quot;, &quot;MESSAGE_REACTION&quot;, &quot;USER&quot;, &quot;DMCHANNEL&quot; ] }); Client.on('messageCreate', async message =&gt; { console.log('messageCreate event'); }; </code></pre> <p>I've tried different ways of enabling the right intents and partials, but I'm about to lose my sanity.</p>
[ { "answer_id": 74566310, "author": "OneCricketeer", "author_id": 2308683, "author_profile": "https://Stackoverflow.com/users/2308683", "pm_score": 3, "selected": true, "text": "Subscribe[String, String] Subscribe[String, Array[Byte]] record.value()" }, { "answer_id": 74571707, "author": "Jacek Laskowski", "author_id": 1305344, "author_profile": "https://Stackoverflow.com/users/1305344", "pm_score": 1, "selected": false, "text": "[B java.lang.String [B Array[Byte] jshell> byte[] bytes = new byte[10]\nbytes ==> byte[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }\n\njshell> bytes.toString()\n$2 ==> \"[B@6e8cf4c6\"\n String val x = new ByteArrayInputStream(record.value().getBytes()) // throwing exception here\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19476464/" ]
74,564,791
<p>So I have next situation. I need to check if entity with <em>ManyToMany</em> relationship exists by list of this entities. Example:</p> <pre><code>@Entity @NoArgsConstructor @Builder(setterPrefix = &quot;with&quot;) @AllArgsConstructor @Getter @Setter @Table(name = &quot;ingredient&quot;) public class Ingredient { @Id @Column(name = &quot;id&quot;) @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = &quot;ingredient_generator&quot;) @SequenceGenerator(name = &quot;ingredient_generator&quot;, sequenceName = &quot;ingredient_id_seq&quot;, allocationSize = 100,initialValue = 1000) private Long id; @Column(name = &quot;name&quot;,unique = true,nullable = false) private String name; @Column(name = &quot;price&quot;,nullable = false) private Integer price; @Column(name = &quot;loss_probability&quot;,nullable = false) private Short lossProbability; @ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY) @JoinTable( name = &quot;recipe&quot;, joinColumns = { @JoinColumn(name = &quot;recipe_ingredient_id&quot;,referencedColumnName = &quot;id&quot;,nullable = false) }, inverseJoinColumns = { @JoinColumn(name = &quot;ingredient_id&quot;,nullable = false) } ) private List&lt;Ingredient&gt; ingredients; } </code></pre> <p>This is my entity, and I need to check if Ingredient with same ingredients already exists. Like this: Ingredient made from ingredients with ids [1,2], and I want to get true if ingredient from ids [1,2] exists, and if I have no Ingredient with [1,3], I want go get false. But in my example:</p> <pre><code>@Query(value = &quot;SELECT CASE WHEN r.ingredient_id IN(?1) THEN TRUE ELSE FALSE END &quot; + &quot;FROM ingredient i JOIN recipe r ON i.id = r.recipe_ingredient_id &quot; + &quot;WHERE r.ingredient_id IN (?1) &quot; + &quot;GROUP BY r.ingredient_id &quot;,nativeQuery = true) List&lt;Boolean&gt; existIngredientsByIngredients(List&lt;Ingredient&gt; ingredients); </code></pre> <p>I got true, even with one coincidence, example: I have Ingredient from ingredients [1,3], and checking by ingredient ids [1,4], and it's return me true, cuz in my ingredient I got id -&gt; 1, but it's should return false cause their no Ingredient created from ingredients [1,4] but only from [1,3]. P.S. method generated from data jpa <em>existsByIngredientsIn</em> dont work as I want, cuz it's too return true even with one coincidence. I really don't understand how I can write this query.</p>
[ { "answer_id": 74566310, "author": "OneCricketeer", "author_id": 2308683, "author_profile": "https://Stackoverflow.com/users/2308683", "pm_score": 3, "selected": true, "text": "Subscribe[String, String] Subscribe[String, Array[Byte]] record.value()" }, { "answer_id": 74571707, "author": "Jacek Laskowski", "author_id": 1305344, "author_profile": "https://Stackoverflow.com/users/1305344", "pm_score": 1, "selected": false, "text": "[B java.lang.String [B Array[Byte] jshell> byte[] bytes = new byte[10]\nbytes ==> byte[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }\n\njshell> bytes.toString()\n$2 ==> \"[B@6e8cf4c6\"\n String val x = new ByteArrayInputStream(record.value().getBytes()) // throwing exception here\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17683553/" ]
74,564,792
<p>I have the following curl command which I can use to retrieve a list of users from a specific group in PagerDuty:</p> <pre><code>curl -H &quot;Accept: application/vnd.pagerduty+json;version=2&quot; -H &quot;Authorization: Token token=xxx&quot; -X GET --data-urlencode &quot;team_ids[]=abc&quot; 'https://api.pagerduty.com/users' </code></pre> <p>How can I translate this exact command to run in a python get.requests() command? I can't seem to get it to work. This is what I'm currently trying but it doesn't filter on the group:</p> <pre><code>response = requests.get( 'https://api.pagerduty.com/users', params = {&quot;data-urlencode&quot;: &quot;team_ids[]=abc&quot;}, headers={'Accept': 'application/vnd.pagerduty+json;version=2','Authorization': 'Token token=xxx'} ) ) </code></pre> <p>Thanks!</p>
[ { "answer_id": 74564931, "author": "Lord Elrond", "author_id": 10746224, "author_profile": "https://Stackoverflow.com/users/10746224", "pm_score": 2, "selected": true, "text": "--data-urlencode import requests\n\nparams = {\n 'team_ids[]':\"abc\",\n \"offset\": '0',\n}\nheaders = {\n 'Accept': 'application/vnd.pagerduty+json;version=2',\n 'Authorization': 'Token token=xxx',\n}\n\nresponse = requests.get('https://api.pagerduty.com/users', params=params, headers=headers)\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20536016/" ]
74,564,802
<p>I have a modal where I want to display a certain amount of picture in a window, but show the full picture (the overlay) in the background.</p> <p>Basically if the amount of picture to be shown (the window) is 100px wide, but the picture itself is 150px wide, you'd see the picture as is in the window (<code>opacity: 1;</code>) but the overflow of the picture would be faded slightly, to give the effect that it would not be seen if the photo was cropped as is.</p> <p>Right now my modal looks like this:</p> <p><a href="https://i.stack.imgur.com/3BfYX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3BfYX.png" alt="enter image description here" /></a></p> <p>Its code:</p> <pre><code>&lt;div&gt; &lt;div className=&quot;d-grid&quot;&gt; &lt;h4&gt;Crop&lt;/h4&gt; &lt;Button variant=&quot;primary&quot; onClick={() =&gt; setModalShow(true)}&gt; Thumbnail &lt;/Button&gt; &lt;Modal show={modalShow} onHide={() =&gt; setModalShow(false)} size=&quot;lg&quot; aria-labelledby=&quot;contained-modal-title-vcenter&quot; centered animation={false} &gt; &lt;Modal.Header closeButton&gt; &lt;Modal.Title id=&quot;contained-modal-title-vcenter&quot;&gt;Crop&lt;/Modal.Title&gt; &lt;/Modal.Header&gt; {selectedThumb ? ( &lt;div&gt; &lt;Modal.Body className=&quot;crop-container&quot;&gt; &lt;div className=&quot;visible&quot;&gt; {&quot; &quot;} &lt;img className=&quot;pic&quot; src={previewThumb} alt=&quot;&quot; /&gt; &lt;/div&gt; &lt;/Modal.Body&gt; &lt;Modal.Footer&gt; &lt;Button&gt;Crop&lt;/Button&gt; &lt;/Modal.Footer&gt; &lt;/div&gt; ) : ( &lt;Modal.Body&gt; &lt;div&gt; You cannot crop or adjust an image that does not exist. Go back and upload a file, dummy. &lt;/div&gt; &lt;/Modal.Body&gt; )} &lt;/Modal&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <pre><code>$width: 254.98px; $height: 143.42px; $channel-pic-width: 38px; $channel-pic-height: 38px; $title-font: 14px; $desc-font: 12.5px; .crop-container { min-height: 400px; // overflow: hidden; .visible { border: 5px solid red; aspect-ratio: $width / $height; width: 200px; height: 200px; } .pic { width: 100%; } } </code></pre> <p>The functionality behind actually cropping the photo is not what I'm worried about right now, although I probably should. What I need now are three things:</p> <ol> <li>A modal that will fit all content (including the overflowing picture) inside it.</li> <li>A window (<code>width: 200px; height: 100px;</code> -- the actual size doesn't matter as long as it's smaller than the picture)</li> <li>Some kind of overlay to make the part of the picture that's overflowing (outside of the window dimensions) have a lower opacity than the window.</li> </ol>
[ { "answer_id": 74588258, "author": "Rokit", "author_id": 996314, "author_profile": "https://Stackoverflow.com/users/996314", "pm_score": 0, "selected": false, "text": "let imageContainer = document.getElementById(\"image-container\");\nimageContainer.onmousemove = function(e) {\n let overlay = document.getElementById(\"overlay\");\n overlay.style.left = e.offsetX + \"px\";\n overlay.style.top = e.offsetY + \"px\";\n}; div {\n position: relative;\n width: 500px;\n height: 300px;\n background-image: url(\"https://images.pexels.com/photos/533769/pexels-photo-533769.jpeg\");\n background-color: rgba(0, 0, 0, 0.5);\n background-blend-mode: multiply;\n background-attachment: fixed;\n overflow: hidden;\n}\n\n#overlay {\n position:absolute;\n width: 200px;\n height: 100px;\n background-blend-mode: normal;\n pointer-events: none;\n} <div id=\"image-container\">\n <div id=\"overlay\"></div>\n</div>" }, { "answer_id": 74638907, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 3, "selected": true, "text": "::before ::after ::before .window::before {\n content: \"\";\n position: absolute;\n inset: 0;\n opacity: 0.8;\n outline: 250px solid white;\n z-index: 50;\n}\n ::after .window::after {\n content: \"\";\n position: absolute;\n inset: 0;\n outline: 5px solid tomato;\n z-index: 75;\n}\n function Crop({ image, boxSizeX, boxSizeY, step }) {\n const [imgX, setImgX] = React.useState(0);\n const [imgY, setImgY] = React.useState(0);\n\n const imgRef = React.useRef(null);\n const [imgNatural, setImgNatural] = React.useState({ width: 0, height: 0 });\n\n const handleImageLoad = () =>\n setImgNatural({\n width: imgRef.current.naturalWidth,\n height: imgRef.current.naturalHeight,\n });\n\n const rangeX = imgNatural.width\n ? Math.abs((boxSizeX - imgNatural.width) / 2)\n : 100;\n\n const rangeY = imgNatural.height\n ? Math.abs((boxSizeY - imgNatural.height) / 2)\n : 100;\n\n return (\n <div className=\"modal\">\n <div\n className=\"window\"\n style={{ width: `${boxSizeX}px`, height: `${boxSizeY}px` }}\n >\n <img\n src={image}\n alt=\"\"\n ref={imgRef}\n onLoad={handleImageLoad}\n style={{\n transform: `translate(${imgX}px, ${imgY}px)`,\n }}\n />\n </div>\n <button\n onClick={() => {\n setImgY((prev) => (prev -= step));\n }}\n disabled={imgY <= -rangeY ? true : false}\n >\n \n </button>\n <button\n onClick={() => {\n setImgY((prev) => (prev += step));\n }}\n disabled={imgY >= rangeY ? true : false}\n >\n \n </button>\n <button\n onClick={() => {\n setImgX((prev) => (prev -= step));\n }}\n disabled={imgX <= -rangeX ? true : false}\n >\n \n </button>\n <button\n onClick={() => {\n setImgX((prev) => (prev += step));\n }}\n disabled={imgX >= rangeX ? true : false}\n >\n \n </button>\n </div>\n );\n}\n\nconst App = () => {\n return (\n <div className=\"app\">\n <Crop\n image={\"https://picsum.photos/400/300\"}\n boxSizeX={200}\n boxSizeY={200}\n step={10}\n />\n </div>\n );\n};\n\nReactDOM.render(<App />, document.querySelector(\"#root\")); body {\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n}\n\n.modal {\n width: 450px;\n height: 350px;\n border-radius: 10px;\n overflow: hidden;\n display: flex;\n justify-content: center;\n align-items: center;\n position: relative;\n outline: 5px solid darkseagreen;\n}\n\n.window {\n background-color: pink;\n display: flex;\n justify-content: center;\n align-items: center;\n position: relative;\n}\n\n.window > img {\n z-index: 25;\n}\n\n.window::before {\n content: \"\";\n position: absolute;\n inset: 0;\n opacity: 0.8;\n outline: 250px solid white;\n z-index: 50;\n}\n\n.window::after {\n content: \"\";\n position: absolute;\n inset: 0;\n outline: 5px solid tomato;\n z-index: 75;\n}\n\nbutton {\n position: absolute;\n padding: 6px;\n z-index: 100;\n}\n\nbutton:disabled {\n opacity: 0.3;\n}\n\nbutton:nth-of-type(1) {\n top: 25px;\n}\n\nbutton:nth-of-type(2) {\n bottom: 25px;\n}\n\nbutton:nth-of-type(3) {\n left: 70px;\n}\n\nbutton:nth-of-type(4) {\n right: 70px;\n} <div id=\"root\"></div>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.production.min.js\"></script>" }, { "answer_id": 74669727, "author": "palash gupta", "author_id": 12719634, "author_profile": "https://Stackoverflow.com/users/12719634", "pm_score": 0, "selected": false, "text": "<div>\n <div className=\"d-grid\">\n <h4>Crop</h4>\n <Button variant=\"primary\" onClick={() => setModalShow(true)}>\n Thumbnail\n </Button>\n <Modal\n show={modalShow}\n onHide={() => setModalShow(false)}\n size=\"lg\"\n aria-labelledby=\"contained-modal-title-vcenter\"\n centered\n animation={false}\n >\n <Modal.Header closeButton>\n <Modal.Title id=\"contained-modal-title-vcenter\">Crop</Modal.Title>\n </Modal.Header>\n {selectedThumb ? (\n <div>\n <Modal.Body className=\"crop-container\">\n <div className=\"visible\">\n <div class=\"window\">\n <img className=\"pic\" src={previewThumb} alt=\"\" />\n </div>\n </div>\n </Modal.Body>\n <Modal.Footer>\n <Button>Crop</Button>\n </Modal.Footer>\n </div>\n ) : (\n <Modal.Body>\n <div>\n You cannot crop or adjust an image that does not exist. Go back\n and upload a file, dummy.\n </div>\n </Modal.Body>\n )}\n </Modal>\n </div>\n</div>\n ::before rgba(255, 255, 255, 0.5)" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18060222/" ]
74,564,804
<p>I'm trying to modify a nested property of a useState, but I'm struggling to do it in this case:</p> <ol> <li><p>The component receives a prop &quot;order&quot; which has many items (line_items), which are the products within that order</p> </li> <li><p>A useEffect iterates through the line_items and generates an array which is stored in an &quot;editOrders&quot; state</p> <p>useEffect(() =&gt; { if (order.line_items &amp;&amp; order.line_items.length) { setEditOrders([]);</p> <pre><code> order.line_items.forEach(item =&gt; { setEditOrders(prevState =&gt; [ ...prevState, { name: item.name, price: item.total, quantity: item.quantity, weight: '' } ]) }) } }, []) </code></pre> </li> <li><p>The items in the array state &quot;editOrders&quot; is displayed in a form</p> <pre><code> &lt;form onSubmit={(e) =&gt; handleSubmitChanges(e)}&gt; { (editOrders.map((item, index) =&gt; ( &lt;div style={{ display: &quot;flex&quot;, flexDirection: &quot;row&quot;, padding: &quot;10px 30px&quot;, alignItems: &quot;center&quot; }}&gt; &lt;h5 style={{flex: 8}}&gt;{item.name}&lt;/h5&gt; &lt;MDBox pt={2} pb={1} px={1} sx={{flex: 3}}&gt; &lt;MDInput type=&quot;text&quot; variant=&quot;standard&quot; label=&quot;Gewicht&quot; disabled={loading &amp;&amp; true} onChange={(e) =&gt; setEditOrders(e.target.value)} value={item.weight} /&gt; &lt;/MDBox&gt; /////// THIS IS WHERE THE PROBLEM IS &lt;MDBox pt={2} pb={1} px={1} sx={{flex: 1}}&gt; &lt;FormControl variant=&quot;standard&quot;&gt; &lt;Select value=&quot;kg&quot; style={{height: 44}} label=&quot;Einheit&quot; endAdornment={ &lt;InputAdornment position=&quot;end&quot;&gt; &lt;ArrowDropDown fontSize=&quot;medium&quot; color=&quot;standard&quot;/&gt; &lt;/InputAdornment&gt; } onChange={(e) =&gt; setEditOrders(prevState =&gt; ({ ...prevState, editOrders[index].weight: e.target.value }))} disabled={loading &amp;&amp; true} &gt; &lt;MenuItem value=&quot;g&quot;&gt;g&lt;/MenuItem&gt; &lt;MenuItem value=&quot;kg&quot;&gt;kg&lt;/MenuItem&gt; &lt;MenuItem value=&quot;ml&quot;&gt;ml&lt;/MenuItem&gt; &lt;MenuItem value=&quot;cl&quot;&gt;cl&lt;/MenuItem&gt; &lt;MenuItem value=&quot;l&quot;&gt;l&lt;/MenuItem&gt; &lt;MenuItem value=&quot;Stück&quot;&gt;Stück&lt;/MenuItem&gt; &lt;/Select&gt; &lt;/FormControl&gt; &lt;/MDBox&gt; &lt;/div&gt; ))) } &lt;MDBox pt={2} pb={3} px={3}&gt; &lt;MDButton type=&quot;submit&quot; variant=&quot;gradient&quot; color=&quot;info&quot; disabled={disabled}&gt; &quot;Create&quot; &lt;/MDButton&gt; &lt;/MDBox&gt; &lt;/form&gt; </code></pre> </li> </ol> <p>Since it's a dynamically generated list, depending on the {order} prop, my goal is to change the state of that particular item in the list.</p> <p>Thank you!</p>
[ { "answer_id": 74588258, "author": "Rokit", "author_id": 996314, "author_profile": "https://Stackoverflow.com/users/996314", "pm_score": 0, "selected": false, "text": "let imageContainer = document.getElementById(\"image-container\");\nimageContainer.onmousemove = function(e) {\n let overlay = document.getElementById(\"overlay\");\n overlay.style.left = e.offsetX + \"px\";\n overlay.style.top = e.offsetY + \"px\";\n}; div {\n position: relative;\n width: 500px;\n height: 300px;\n background-image: url(\"https://images.pexels.com/photos/533769/pexels-photo-533769.jpeg\");\n background-color: rgba(0, 0, 0, 0.5);\n background-blend-mode: multiply;\n background-attachment: fixed;\n overflow: hidden;\n}\n\n#overlay {\n position:absolute;\n width: 200px;\n height: 100px;\n background-blend-mode: normal;\n pointer-events: none;\n} <div id=\"image-container\">\n <div id=\"overlay\"></div>\n</div>" }, { "answer_id": 74638907, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 3, "selected": true, "text": "::before ::after ::before .window::before {\n content: \"\";\n position: absolute;\n inset: 0;\n opacity: 0.8;\n outline: 250px solid white;\n z-index: 50;\n}\n ::after .window::after {\n content: \"\";\n position: absolute;\n inset: 0;\n outline: 5px solid tomato;\n z-index: 75;\n}\n function Crop({ image, boxSizeX, boxSizeY, step }) {\n const [imgX, setImgX] = React.useState(0);\n const [imgY, setImgY] = React.useState(0);\n\n const imgRef = React.useRef(null);\n const [imgNatural, setImgNatural] = React.useState({ width: 0, height: 0 });\n\n const handleImageLoad = () =>\n setImgNatural({\n width: imgRef.current.naturalWidth,\n height: imgRef.current.naturalHeight,\n });\n\n const rangeX = imgNatural.width\n ? Math.abs((boxSizeX - imgNatural.width) / 2)\n : 100;\n\n const rangeY = imgNatural.height\n ? Math.abs((boxSizeY - imgNatural.height) / 2)\n : 100;\n\n return (\n <div className=\"modal\">\n <div\n className=\"window\"\n style={{ width: `${boxSizeX}px`, height: `${boxSizeY}px` }}\n >\n <img\n src={image}\n alt=\"\"\n ref={imgRef}\n onLoad={handleImageLoad}\n style={{\n transform: `translate(${imgX}px, ${imgY}px)`,\n }}\n />\n </div>\n <button\n onClick={() => {\n setImgY((prev) => (prev -= step));\n }}\n disabled={imgY <= -rangeY ? true : false}\n >\n \n </button>\n <button\n onClick={() => {\n setImgY((prev) => (prev += step));\n }}\n disabled={imgY >= rangeY ? true : false}\n >\n \n </button>\n <button\n onClick={() => {\n setImgX((prev) => (prev -= step));\n }}\n disabled={imgX <= -rangeX ? true : false}\n >\n \n </button>\n <button\n onClick={() => {\n setImgX((prev) => (prev += step));\n }}\n disabled={imgX >= rangeX ? true : false}\n >\n \n </button>\n </div>\n );\n}\n\nconst App = () => {\n return (\n <div className=\"app\">\n <Crop\n image={\"https://picsum.photos/400/300\"}\n boxSizeX={200}\n boxSizeY={200}\n step={10}\n />\n </div>\n );\n};\n\nReactDOM.render(<App />, document.querySelector(\"#root\")); body {\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n}\n\n.modal {\n width: 450px;\n height: 350px;\n border-radius: 10px;\n overflow: hidden;\n display: flex;\n justify-content: center;\n align-items: center;\n position: relative;\n outline: 5px solid darkseagreen;\n}\n\n.window {\n background-color: pink;\n display: flex;\n justify-content: center;\n align-items: center;\n position: relative;\n}\n\n.window > img {\n z-index: 25;\n}\n\n.window::before {\n content: \"\";\n position: absolute;\n inset: 0;\n opacity: 0.8;\n outline: 250px solid white;\n z-index: 50;\n}\n\n.window::after {\n content: \"\";\n position: absolute;\n inset: 0;\n outline: 5px solid tomato;\n z-index: 75;\n}\n\nbutton {\n position: absolute;\n padding: 6px;\n z-index: 100;\n}\n\nbutton:disabled {\n opacity: 0.3;\n}\n\nbutton:nth-of-type(1) {\n top: 25px;\n}\n\nbutton:nth-of-type(2) {\n bottom: 25px;\n}\n\nbutton:nth-of-type(3) {\n left: 70px;\n}\n\nbutton:nth-of-type(4) {\n right: 70px;\n} <div id=\"root\"></div>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.production.min.js\"></script>" }, { "answer_id": 74669727, "author": "palash gupta", "author_id": 12719634, "author_profile": "https://Stackoverflow.com/users/12719634", "pm_score": 0, "selected": false, "text": "<div>\n <div className=\"d-grid\">\n <h4>Crop</h4>\n <Button variant=\"primary\" onClick={() => setModalShow(true)}>\n Thumbnail\n </Button>\n <Modal\n show={modalShow}\n onHide={() => setModalShow(false)}\n size=\"lg\"\n aria-labelledby=\"contained-modal-title-vcenter\"\n centered\n animation={false}\n >\n <Modal.Header closeButton>\n <Modal.Title id=\"contained-modal-title-vcenter\">Crop</Modal.Title>\n </Modal.Header>\n {selectedThumb ? (\n <div>\n <Modal.Body className=\"crop-container\">\n <div className=\"visible\">\n <div class=\"window\">\n <img className=\"pic\" src={previewThumb} alt=\"\" />\n </div>\n </div>\n </Modal.Body>\n <Modal.Footer>\n <Button>Crop</Button>\n </Modal.Footer>\n </div>\n ) : (\n <Modal.Body>\n <div>\n You cannot crop or adjust an image that does not exist. Go back\n and upload a file, dummy.\n </div>\n </Modal.Body>\n )}\n </Modal>\n </div>\n</div>\n ::before rgba(255, 255, 255, 0.5)" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8726315/" ]
74,564,823
<p>I want to get the maximum values in a row and print the value and the name of the appropriate column.</p> <pre><code>s1 = pd.Series([5, 6, 7, 10, 12, 6, 8, 55, 9]) s2 = pd.Series([7, 8, 9, 16, 13, 8, 2, 11, 7]) df = pd.DataFrame([list(s1), list(s2)], columns = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;H&quot;, &quot;I&quot;]) A B C D E F G H I 0 5 6 7 10 12 6 8 55 9 1 7 8 9 16 13 8 2 11 7 </code></pre> <p>I want to choose for example &quot;index 0&quot; and get something like this:</p> <pre><code>55 H 12 E 10 D 9 I </code></pre>
[ { "answer_id": 74565155, "author": "msailor", "author_id": 10155119, "author_profile": "https://Stackoverflow.com/users/10155119", "pm_score": 0, "selected": false, "text": ">>> df.loc[0].sort_values(ascending=False).iloc[:4]\nH 55\nE 12\nD 10\nI 9\nName: 0, dtype: int64\n def top_n(idx, n):\n return df.loc[idx].sort_values(ascending=False).iloc[:n]\n" }, { "answer_id": 74565904, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "O(n*log(n)) nlargest out = df.loc[0].nlargest(4)\n H 55\nE 12\nD 10\nI 9\nName: 0, dtype: int64\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19668762/" ]
74,564,846
<p>Suppose there is a dataset. Let's say that the dataset has a column A which contains city names like &quot;New York&quot;, &quot;California&quot;, or &quot;Florida&quot; now we have a dictionary like</p> <pre><code>my_dict = {&quot;New York&quot;:1, &quot;California&quot;:2, &quot;Florida&quot;:3} </code></pre> <p>So I need to generate a column B such that if column A has a row value &quot;New York&quot;, then column B has the value 1 as in the dictionary.</p> <p>I used the lambda function and it worked but is it possible without the use of the lambda function?</p>
[ { "answer_id": 74565155, "author": "msailor", "author_id": 10155119, "author_profile": "https://Stackoverflow.com/users/10155119", "pm_score": 0, "selected": false, "text": ">>> df.loc[0].sort_values(ascending=False).iloc[:4]\nH 55\nE 12\nD 10\nI 9\nName: 0, dtype: int64\n def top_n(idx, n):\n return df.loc[idx].sort_values(ascending=False).iloc[:n]\n" }, { "answer_id": 74565904, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "O(n*log(n)) nlargest out = df.loc[0].nlargest(4)\n H 55\nE 12\nD 10\nI 9\nName: 0, dtype: int64\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20593253/" ]
74,564,868
<p>I am processing binary images, and was previously using this code to find the largest area in the binary image:</p> <pre><code># Use the hue value to convert to binary thresh = 20 thresh, thresh_img = cv2.threshold(h, thresh, 255, cv2.THRESH_BINARY) cv2.imshow('thresh', thresh_img) cv2.waitKey(0) cv2.destroyAllWindows() # Finding Contours # Use a copy of the image since findContours alters the image contours, _ = cv2.findContours(thresh_img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) #Extract the largest area c = max(contours, key=cv2.contourArea) </code></pre> <p>This code isn't really doing what I need it to do, now I think it would better to extract the most central area in the binary image.</p> <p><a href="https://i.stack.imgur.com/fkljm.png" rel="nofollow noreferrer">Binary Image</a> <a href="https://i.stack.imgur.com/0BSih.png" rel="nofollow noreferrer">Largest Image</a></p> <p>This is currently what the code is extracting, but I am hoping to get the central circle in the first binary image extracted.</p>
[ { "answer_id": 74566139, "author": "Nick ODell", "author_id": 530160, "author_profile": "https://Stackoverflow.com/users/530160", "pm_score": 1, "selected": false, "text": "np.argwhere() import cv2\nimport numpy as np\n\nimg = cv2.imread('test197_img.png')\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n_, thresh_img = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)\nn_groups, comp_grouped = cv2.connectedComponents(thresh_img)\ncomponents = []\nsearch_point = [600, 150]\nfor i in range(1, n_groups):\n mask = (comp_grouped == i)\n component_coords = np.argwhere(mask)[:, ::-1]\n min_distance = np.sqrt(((component_coords - search_point) ** 2).sum(axis=1)).min()\n components.append({\n 'mask': mask,\n 'min_distance': min_distance,\n })\nclosest = min(components, key=lambda x: x['min_distance'])['mask']\n" }, { "answer_id": 74566502, "author": "Christoph Rackwitz", "author_id": 2602877, "author_profile": "https://Stackoverflow.com/users/2602877", "pm_score": 2, "selected": false, "text": "mask = cv.imread(\"fkljm.png\", cv.IMREAD_GRAYSCALE)\n(height, width) = mask.shape\nret, mask = cv.threshold(mask, 128, 255, cv.THRESH_BINARY) # required because the sample picture isn't exactly clean\n # get contours\ncontours, hierarchy = cv.findContours(mask, cv.RETR_LIST | cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)\n center = (np.array([width, height]) - 1) / 2\n\n# find contour closest to center of picture\ndistances = [\n cv.pointPolygonTest(contour, center, True) # looking for most positive (inside); negative is outside\n for contour in contours\n]\niclosest = np.argmax(distances)\nprint(\"closest contour is\", iclosest, \"with distance\", distances[iclosest])\n\n# draw closest contour\ncanvas = cv.cvtColor(mask, cv.COLOR_GRAY2BGR)\ncv.drawContours(image=canvas, contours=[contours[iclosest]], contourIdx=-1, color=(0, 255, 0), thickness=5)\n closest contour is 45 with distance 65.19202405202648\n cv.floodFill() (cx, cy) = center.astype(int)\nassert mask[cy,cx], \"floodFill not applicable\"\n\n# trying cv.floodFill on the image center\nmask2 = mask >> 1 # turns everything else gray\ncv.floodFill(image=mask2, mask=None, seedPoint=center.astype(int), newVal=255)\n\n# use (mask2 == 255) to identify that blob\n sqrt(2) * blocksize" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13451885/" ]
74,564,878
<p>I am building a React-based SPA that communicates with a spring-boot backend via a REST API. I need the user to be able to log into their Microsoft account on the browser client (the SPA) and I need the backend service (spring-boot app) to be able to query Microsoft's Graph API on behalf of that user.</p> <p>After reading up on the Oauth2 flows, the authorization code flow (not the PKCE flow, just the regular authorization code flow) seems the most appropriate. The browser client could let the user log into their Microsoft account, retrieve an authorization code, and send the authorization code to our backend service via HTTP request. The backend service (which is trusted and can safely store a client secret) can then request an access token, make requests to the Graph API directly (meaning that the SPA would never need to make any requests to the Graph API), and silently refresh the token as needed.</p> <p>However, I cannot see any examples of anyone using this flow to access Microsoft's Graph API.</p> <p>Looking at Microsoft's documentation, it seems like they recommend using the <a href="https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow" rel="nofollow noreferrer">on-behalf-of flow</a>. But this flow requires the browser client to request an access token and then use that to communicate with the backend service (which in turn can communicate with the Graph API). It doesn't make sense to me why the access token cannot be requested on the backend using a client secret. Wouldn't this be a more secure and preferred method than having the client retrieve the access token, as is done in the on-behalf-of flow?</p> <p>The <a href="https://auth0.com/docs/get-started/authentication-and-authorization-flow/which-oauth-2-0-flow-should-i-use" rel="nofollow noreferrer">Oauth2.0 site</a>, recommends that SPAs should either use the authorization code with PKE or the implicit flow, but I do not see an option to use the standard authentication code flow for SPAs. Should I take this as an indication that SPAs should not be using the standard authorization code flow as I described earlier?</p> <p>Despite not finding a clear-cut example of the standard authorization code flow in Microsoft's documentation for a react frontend + java backend, I tried to go about doing this myself. However, using the <code>@microsoft/mgt-react</code> and <code>@microsoft/mgt-element</code> libraries to do this are not straight forward. For example, the <code>@microsoft/mgt-element</code> notion of a <code>Provider</code> supports a call to retrieve an access token, but doesn't clearly expose the authorization code. If I wanted to do the authorization code flow described earlier, it seems like I would need to use raw HTTP requests, which I know is not a recommended way of accomplishing this.</p> <p><strong>Summarizing my questions:</strong></p> <ul> <li><p><strong>What OAuth2.0 flow should I be using: 1) authorization code (access token is retrieved by backend service using client secret), 2) authorization code with PKE (access token is retrieved by client), or 3) on-behalf-of flow (access token is retrieved by client, seems to be an extension of PKE flow)?</strong></p> </li> <li><p><strong>If using the on-behalf-of flow, does the SPA just include the access token in the header (marked as 'bearer') and the backend service just includes that same header to query the Graph API, or does the backend service need to request another token before querying the Graph API?</strong></p> </li> </ul>
[ { "answer_id": 74568623, "author": "Tiny Wang", "author_id": 14574199, "author_profile": "https://Stackoverflow.com/users/14574199", "pm_score": 2, "selected": true, "text": "on-behalf-flow client credential flow User.ReadWrite.All, Mail.ReadWrite.All" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2779450/" ]
74,564,884
<p>I've been through the array documentation in Big Query and found that I can use UNNEST and DISTINCT to remove duplicates in an array content, but I want to remove the duplicates <strong>only if</strong> they are adjacent in the array (as it's an ordered list).</p> <p>For example, for this input:</p> <p><code>[a, a, b, a, a, c, b, b]</code></p> <p>Expected output would be:</p> <p><code>[a, b, a, c, b]</code></p> <p>Any ideas appreciated.</p>
[ { "answer_id": 74565148, "author": "Mikhail Berlyant", "author_id": 5221944, "author_profile": "https://Stackoverflow.com/users/5221944", "pm_score": 0, "selected": false, "text": "select *, array( \n select any_value(el)\n from (\n select as struct *, countif(flag) over(order by offset) grp\n from (\n select offset, el, ifnull(el != lag(el) over(order by offset), true) flag\n from t.arr as el with offset\n )\n )\n group by grp\n order by min(offset)\n )\nfrom your_table t \n" }, { "answer_id": 74566208, "author": "Jaytiger", "author_id": 19039920, "author_profile": "https://Stackoverflow.com/users/19039920", "pm_score": 1, "selected": false, "text": "WITH sample_data AS (\n SELECT ['a', 'a', 'b', 'a', 'a', 'c', 'b', 'b'] arr\n)\nSELECT *,\n ARRAY(\n SELECT e FROM (\n SELECT e, o FROM t.arr e WITH offset o\n EXCEPT DISTINCT\n SELECT e, o + 1 FROM t.arr e WITH offset o\n ) ORDER BY o\n ) AS distinct_arr\n FROM sample_data t;\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20593365/" ]
74,564,889
<p>I run into a compiler error that I am not sure how to resolve it.</p> <p>Basically, I have a few enum classes described below.</p> <p>I created abstract classes myTool and myTools deriving from myTool. The compiler for some reason does not like the way I structured the constructor for MyTools and threw error</p> <blockquote> <p>CS0030: Can not convert type int to type T.</p> </blockquote> <p>Please advice me how to resolve this.</p> <pre><code>public enum TOOLS { HAMMER =1, DRILL = 2, SCREWDRIVER =3, VACUUM=4 } public enum EQUIPMENTS { MOWER=1, TRIMMER=2, SNOWBLOWER=3 } public abstract class MyTool { protected T _myStuff int quantity double price public MyTool(T t) { _myStuff =t; } ... properties... } public abstract class MyTools&lt;T&gt;:myTool&lt;T&gt; where T:System.Enum { protected MyTool&lt;T&gt;[] _myTools; public MyTool&lt;T&gt; this[int i]=&gt; this._myTools[i]; public MyTools(int count, T t):base(t) { _myTools = new MyTools&lt;T&gt;[count]; for (int i=0; i&lt;count;i++) { _myTools[i]=(T)(i+1); } } } </code></pre>
[ { "answer_id": 74565115, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 2, "selected": true, "text": "int System.Enum T enumValue = (T)Enum.ToObject(typeof(T), intValue);\n T enumValue = (T)(object)intValue;\n" }, { "answer_id": 74565193, "author": "d00lar", "author_id": 11305308, "author_profile": "https://Stackoverflow.com/users/11305308", "pm_score": 0, "selected": false, "text": "public static class TConverter\n{\n public static T ChangeType<T>(object value)\n {\n return (T)ChangeType(typeof(T), value);\n }\n\n public static object ChangeType(Type t, object value)\n {\n TypeConverter tc = TypeDescriptor.GetConverter(t);\n return tc.ConvertFrom(value);\n }\n\n public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter\n {\n\n TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));\n }\n}\n TConverter.ChangeType<T>(intValue); \n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1205746/" ]
74,564,919
<p>I'm trying to make a program which concatenates two strings. The max length of the strings should be 50 characters and I'm making a string with that size. I'm getting the strings using <code>argv</code>. How can I detect if the strings are over 50 characters? Can I do it without playing around with memory since I haven't learned this yet. The function for concatenation is stored in a mystrings.h file Here's my current code:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &quot;mystrings.h&quot; int main(int argc, char *argv[]) { if (argc == 3) { char str1[50]; char str2[50]; strcpy(str1, argv[1]); strcpy(str2, argv[2]); strConcat(str1, str2); printf(&quot;Concatenated string: %s\n&quot;, str1); } else { printf(&quot;Invalid number of arguments passed. Format required:\n &lt;STRING1&gt; &lt;STRING2&gt;\n&quot;); } } </code></pre>
[ { "answer_id": 74565104, "author": "Oka", "author_id": 2505965, "author_profile": "https://Stackoverflow.com/users/2505965", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n#include <string.h>\n\n#define LIMIT 50\n\nint main(int argc, char **argv)\n{\n if (argc < 3) {\n fprintf(stderr, \"usage: %s STRING1 STRING2\\n\", argv[0]);\n return 1;\n }\n\n if (strlen(argv[1]) + strlen(argv[2]) >= LIMIT) {\n fprintf(stderr, \"Combined string length is too long.\\n\");\n return 1;\n }\n\n char result[LIMIT];\n strcpy(result, argv[1]);\n strcat(result, argv[2]);\n puts(result);\n}\n" }, { "answer_id": 74565323, "author": "h00die", "author_id": 20082256, "author_profile": "https://Stackoverflow.com/users/20082256", "pm_score": 1, "selected": true, "text": "#include <stdio.h>\n#include <string.h>\nint main(int argc, char *argv[]) \n{\n if (argc == 3) \n {\n char str1[50];\n char str2[50];\n\n if (strlen(argv[1]) > 50 || strlen(argv[2]) > 50)\n {\n printf(\"Max string length is 50\");\n return 1;\n }\n\n strcpy(str1, argv[1]);\n strcpy(str2, argv[2]);\n \n strConcat(str1, str2);\n\n printf(\"Concatenated string: %s\\n\", str1);\n } \n\n else\n {\n printf(\"Invalid number of arguments passed. Format required:\\n <STRING1> \"\n \"<STRING2>\\n\");\n }\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16748931/" ]
74,564,937
<p>What happens with this simple workflow:</p> <pre><code>x@PC MINGW64 /c/Temp/tests/git/branches/changes $ git init Initialized empty Git repository in C:/Temp/tests/git/branches/changes/.git/ x@PC MINGW64 /c/Temp/tests/git/branches/changes (master) $ echo &quot;CHANGE #1&quot; &gt;&gt; test.txt x@PC MINGW64 /c/Temp/tests/git/branches/changes (master) $ git add test.txt x@PC MINGW64 /c/Temp/tests/git/branches/changes (master) $ git commit -m &quot;.&quot; [master (root-commit) 439c0f8] . 1 file changed, 1 insertion(+) create mode 100644 test.txt x@PC MINGW64 /c/Temp/tests/git/branches/changes (master) $ git branch branch-1 x@PC MINGW64 /c/Temp/tests/git/branches/changes (master) $ echo &quot;CHANGE #2&quot; &gt;&gt; test.txt x@PC MINGW64 /c/Temp/tests/git/branches/changes (master) $ cat test.txt CHANGE #1 CHANGE #2 x@PC MINGW64 /c/Temp/tests/git/branches/changes (master) $ git switch branch-1 Switched to branch 'branch-1' M test.txt x@PC MINGW64 /c/Temp/tests/git/branches/changes (branch-1) $ git add test.txt x@PC MINGW64 /c/Temp/tests/git/branches/changes (branch-1) $ git commit -m &quot;.&quot; [branch-1 4c62bc9] . 1 file changed, 1 insertion(+) x@PC MINGW64 /c/Temp/tests/git/branches/changes (branch-1) $ git switch master Switched to branch 'master' x@PC MINGW64 /c/Temp/tests/git/branches/changes (master) $ cat test.txt CHANGE #1 </code></pre> <p>With words:</p> <ul> <li>when working in <code>master</code> create a file with &quot;CHANGE #1&quot;</li> <li>add and commit it</li> <li>create another branch <code>branch-1</code></li> <li>make another change adding &quot;CHANGE #2&quot;</li> <li>switch to <code>branch-1</code></li> <li>add and commit the file</li> <li>switch back to <code>master</code></li> </ul> <p>(the order of creating the branch and making the second change does not seem to have any importance)</p> <p>I was surprised by:</p> <ul> <li>seeing local changes made &quot;in the context of <code>master</code>&quot; in <code>branch-1</code></li> <li>not seeing the changes anymore when switching back to <code>master</code></li> </ul> <p>So I have 2 questions:</p> <ol> <li>When switching to <code>branch-1</code> the local changes have been left untouched, so they are not associated with <code>master</code>, but seem merely ignored by Git, where is this behaviour documented?</li> <li>After committing the changes from <code>branch-1</code>, and switching back to <code>master</code> the second change is no more visible from <code>master</code>: in gross terms, the change has been captured on <code>branch-1</code>, what is the exact terminology (snapshot)?</li> </ol>
[ { "answer_id": 74565535, "author": "eftshift0", "author_id": 2437508, "author_profile": "https://Stackoverflow.com/users/2437508", "pm_score": 1, "selected": false, "text": "HEAD -f" }, { "answer_id": 74572335, "author": "torek", "author_id": 1256452, "author_profile": "https://Stackoverflow.com/users/1256452", "pm_score": 2, "selected": false, "text": ".git .git .git the_repository the_index git worktree add git switch git checkout git switch git checkout git switch git switch branch-1\n git switch master\n 63bba4fdd86d80ef061c449daa97a981a9be0792 master branch-1 git switch xyzzy\n xyzzy $ git branch branch-1 # while you were on \"master\"\n...\n$ git switch branch-1\n master branch-1 439c0f8 git rm --cached git add git commit git add 4c62bc9 branch-1 git switch master\n master 439c0f8 4c62bc9 439c0f8 4c62bc9 branch-1 439c0f8 M test.txt\n git switch -q git stash git stash git stash git status git status" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145757/" ]
74,564,952
<p>I want to accept a input with java.time.Duration data type in java using net.sourceforge.argparse4j.ArgumentParsers . However since Duration is a non-primitive data type, it is not directly supported to be passed as one of the argument. Is there any better or direct way to accept Duration as paramter in java other than specifying it as String in ISO-8601 format and using Duration.parse() (<a href="https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html#parse-java.lang.CharSequence-" rel="nofollow noreferrer">https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html#parse-java.lang.CharSequence-</a>) to convert it to Duration type.?</p>
[ { "answer_id": 74565221, "author": "hc_dev", "author_id": 5730279, "author_profile": "https://Stackoverflow.com/users/5730279", "pm_score": 2, "selected": false, "text": "valueOf T valueOf(String text) T T valueOf(String) java.time java.time.Duration final Duration valueOf Duration.parse(CharSequence text) private static class IsoDuration {\n\n public static Duration valueOf(String isoFormat) throws ArgumentParserException {\n try {\n return Duration.parse(isoFormat); // the method you found\n } catch (DateTimeParseException e) {\n throw new ArgumentParserException(e, parser);\n }\n }\n}\n\npublic static void main(String[] args) {\n ArgumentParser parser = ArgumentParsers.newFor(\"prog\").build();\n parser.addArgument(\"duration\").type(IsoDuration.class);\n try {\n System.out.println(parser.parseArgs(args));\n } catch (ArgumentParserException e) {\n parser.handleError(e);\n }\n}\n convert ArgumentType<Duration> Duration.parse(CharSequence text) private static class IsoDurationArgument implements ArgumentType<Duration> {\n\n @Override\n public Duration convert(ArgumentParser parser, Argument arg, String value) throws ArgumentParserException {\n try {\n return Duration.parse(value); // the method you found\n } catch (DateTimeParseException e) {\n throw new ArgumentParserException(e, parser);\n }\n }\n}\n\npublic static void main(String[] args) {\n ArgumentParser parser = ArgumentParsers.newFor(\"prog\").build();\n parser.addArgument(\"duration\").type(new IsoDurationArgument());\n try {\n System.out.println(parser.parseArgs(args));\n } catch (ArgumentParserException e) {\n parser.handleError(e);\n }\n}\n Argument.type() PerfectSquare Argument.type() ArgumentType" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74564952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10074233/" ]
74,565,012
<p>If I run this query:</p> <pre><code>select date, sum(orders) as &quot;Total orders&quot; from tbl where date &gt;=1 and date &lt;= 4 group by date </code></pre> <p>How can I get the expected output as shown in the screenshot?</p> <p><a href="https://i.stack.imgur.com/Qe1Z4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qe1Z4.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74565272, "author": "Jiří Kopřiva", "author_id": 15018327, "author_profile": "https://Stackoverflow.com/users/15018327", "pm_score": -1, "selected": false, "text": "WITH cte as (\n\nSELECT date, orders\nFROM dbo.Orders\n\n),\n\ncte2 as (\n\nselect top (SELECT MAX(date) FROM cte) ROW_NUMBER() over(order by a.name) \nas date\nfrom sys.all_objects a\n\n) \n\nSELECT cte2.date, SUM(ISNULL(orders, 0))\nFROM cte2 LEFT JOIN cte ON cte2.date = cte.date\nGROUP BY cte2.date\n" }, { "answer_id": 74565867, "author": "a_horse_with_no_name", "author_id": 330315, "author_profile": "https://Stackoverflow.com/users/330315", "pm_score": 2, "selected": true, "text": "select g.date, \n sum(tbl.orders) as \"Total orders\" \nfrom generate_series(1,4) as g(date)\n left join tbl on tbl.date = g.date \ngroup by g.date\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15079214/" ]
74,565,057
<p>I try do split a dataframe by two variables, year and sectors. I did split them with group_split but everytime I need them, I have to call them with $ operator. I want to give them a name automatically so I do not need to use $ for every usage. I know I can assign them to new names by hand but I have more than 70 values so it's a bit time consuming</p> <pre><code>dummy &lt;- data.frame(year = rep(2014:2020, 12), sector = rep(c(&quot;auto&quot;,&quot;retail&quot;,&quot;sales&quot;,&quot;medical&quot;),3), emp = sample(1:2000, size = 84)) dummy%&gt;% group_by(year)%&gt;% group_split(year)%&gt;% set_names(nm = unique(dummy$year)) -&gt; dummy_year head(dummy_year$2014) year sector emp &lt;int&gt; &lt;chr&gt; &lt;int&gt; 2014 auto 171 2014 medical 1156 2014 sales 1838 2014 retail 1386 2014 auto 1360 2014 medical 1403 </code></pre> <p>I want to call them like</p> <pre><code>some_kind_of_function(dummy_year, assign new variable by date) head(year_2014) year sector emp &lt;int&gt; &lt;chr&gt; &lt;int&gt; 2014 auto 171 2014 medical 1156 2014 sales 1838 2014 retail 1386 2014 auto 1360 2014 medical 1403 </code></pre> <p>maybe a for loop?</p>
[ { "answer_id": 74565096, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 3, "selected": true, "text": "group_split list split base R lst1 <- split(dummy, dummy$year)\nnames(lst1) <- paste0('year_', names(lst1))\n list2env list2env(lst1, .GlobalEnv)\n > year_2014\n year sector emp\n1 2014 auto 740\n8 2014 medical 123\n15 2014 sales 700\n22 2014 retail 166\n29 2014 auto 323\n36 2014 medical 653\n43 2014 sales 986\n50 2014 retail 1814\n57 2014 auto 1381\n64 2014 medical 661\n71 2014 sales 1362\n78 2014 retail 641\n" }, { "answer_id": 74565254, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 2, "selected": false, "text": "library(dplyr)\ndummy %>% \n split(f = paste0(\"year_\", as.factor(.$year)))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20193096/" ]
74,565,063
<p>i'm trying to make a program that calculates simple interest and the function i made to calculate the interest returns 0 when i run it and i don't know what the problem is</p> <pre><code> </code></pre> <pre><code>`year = int(input(&quot;Enter years: &quot;)) month = int(input(&quot;Enter months: &quot;)) days = int(input(&quot;Enter days: &quot;)) totalYears = float() interest = float() def get_time(): totalYears = round(year + (month * 31 + days)/365,1) print(&quot;total time in years is&quot;,totalYears,&quot;years&quot;) principal = float(input(&quot;Enter principal: &quot;)) rate = float(input(&quot;Enter rate (in %): &quot;)) def simple_interest(): interest = round(principal * rate/100 * totalYears,2) print(&quot;Total interest earned is $&quot;,interest) get_time() simple_interest()` </code></pre> <pre><code> </code></pre> <p>i tried intializing the principal and rate at the start even though i know it's unnecessary since it's intialized when i ask for the input, i assume the problem is with the variables but i can't find it if it is.</p>
[ { "answer_id": 74565172, "author": "michael perkins", "author_id": 19620151, "author_profile": "https://Stackoverflow.com/users/19620151", "pm_score": 1, "selected": false, "text": "TotalYears get_time TotalYears year = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\n\ntotalYears = float()\ninterest = float()\n\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\ndef get_time():\n global totalYears\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n\ndef simple_interest():\n interest = round(principal * (rate/100) * totalYears,2)\n print(\"Total interest earned is $\",interest)\n\nget_time()\nsimple_interest()\n" }, { "answer_id": 74565318, "author": "Vin", "author_id": 7955271, "author_profile": "https://Stackoverflow.com/users/7955271", "pm_score": 1, "selected": false, "text": "totalYears float() totalYears get_time() totalYears get_time() totalYears totalYears simple_interest 0.0 get_time() get_time() simple_interest() year = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\n\ntotalYears = float()\ninterest = float()\n\ndef get_time():\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n return totalYears\n\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\ndef simple_interest(totalYears):\n interest = principal * rate/100 * totalYears\n\n print(f'Total interest earned is ${round(interest, 2)}')\n\ntotalYears = get_time()\nsimple_interest(totalYears)\n Enter years: 5\n\nEnter months: 3\n\nEnter days: 2\n\nEnter principal: 1000\n\nEnter rate (in %): 2\ntotal time in years is 5.3 years\nTotal interest earned is $106.0\n totalYears = float() interest = float() def get_inputs():\n\n year = int(input(\"Enter years: \"))\n month = int(input(\"Enter months: \"))\n days = int(input(\"Enter days: \"))\n principal = float(input(\"Enter principal: \"))\n rate = float(input(\"Enter rate (in %): \"))\n\n return year, month, days, principal, rate\n get_inputs def get_time(year, month, days):\n\n totalYears = round(year + (month * 31 + days)/365,1)\n\n return totalYears\n\ndef simple_interest(principal, rate, totalYears):\n\n interest = principal * rate/100 * totalYears\n\n return interest\n get_time simple_interest def print_outputs(totalYears, interest):\n\n print(f'total time in years is {totalYears} years')\n print(f'Total interest earned is ${round(interest, 2)}')\n \n print_outputs get_inputs year, month, days, principal, rate = get_inputs()\ntotalYears = get_time(year, month, days)\ninterest = simple_interest(principal, rate, totalYears)\nprint_outputs(totalYears, interest)\n" }, { "answer_id": 74565413, "author": "MrChicano", "author_id": 17366168, "author_profile": "https://Stackoverflow.com/users/17366168", "pm_score": 0, "selected": false, "text": "get_time() totalYears simple_interest() interest totalYears simple_interest() def simple_interest():\n interest = round(principal * rate/100 * totalYears,2)\n \n #This should return 0:\n print(totalYears)\n print(\"Total interest earned is $\",interest)\n totalYears interest def get_time():\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n return totalYears\n\ndef simple_interest():\n interest = round(principal * rate/100 * totalYears,2)\n print(\"Total interest earned is $\",interest)\n return interest\n\nyear = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\n\ntotalYears = get_time()\ninterest = simple_interest()\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20160436/" ]
74,565,085
<p>I have a text file containing random strings. I want to use specific criterias to extract the strings that match these criterias.</p> <p>Example text :</p> <p>B311-SG-1700-ASJND83-ANSDN762 BAKSJD873-JAN-1293</p> <p>Example criteria :</p> <p>All the strings that contains characters seperated by hyphens this way : XXX-XX-XXXX</p> <p>Output : 'B311-SG-1700'</p> <p>I tried creating a function but I can't seem to know how to use criterias for string specifically and how to apply them.</p>
[ { "answer_id": 74565172, "author": "michael perkins", "author_id": 19620151, "author_profile": "https://Stackoverflow.com/users/19620151", "pm_score": 1, "selected": false, "text": "TotalYears get_time TotalYears year = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\n\ntotalYears = float()\ninterest = float()\n\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\ndef get_time():\n global totalYears\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n\ndef simple_interest():\n interest = round(principal * (rate/100) * totalYears,2)\n print(\"Total interest earned is $\",interest)\n\nget_time()\nsimple_interest()\n" }, { "answer_id": 74565318, "author": "Vin", "author_id": 7955271, "author_profile": "https://Stackoverflow.com/users/7955271", "pm_score": 1, "selected": false, "text": "totalYears float() totalYears get_time() totalYears get_time() totalYears totalYears simple_interest 0.0 get_time() get_time() simple_interest() year = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\n\ntotalYears = float()\ninterest = float()\n\ndef get_time():\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n return totalYears\n\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\ndef simple_interest(totalYears):\n interest = principal * rate/100 * totalYears\n\n print(f'Total interest earned is ${round(interest, 2)}')\n\ntotalYears = get_time()\nsimple_interest(totalYears)\n Enter years: 5\n\nEnter months: 3\n\nEnter days: 2\n\nEnter principal: 1000\n\nEnter rate (in %): 2\ntotal time in years is 5.3 years\nTotal interest earned is $106.0\n totalYears = float() interest = float() def get_inputs():\n\n year = int(input(\"Enter years: \"))\n month = int(input(\"Enter months: \"))\n days = int(input(\"Enter days: \"))\n principal = float(input(\"Enter principal: \"))\n rate = float(input(\"Enter rate (in %): \"))\n\n return year, month, days, principal, rate\n get_inputs def get_time(year, month, days):\n\n totalYears = round(year + (month * 31 + days)/365,1)\n\n return totalYears\n\ndef simple_interest(principal, rate, totalYears):\n\n interest = principal * rate/100 * totalYears\n\n return interest\n get_time simple_interest def print_outputs(totalYears, interest):\n\n print(f'total time in years is {totalYears} years')\n print(f'Total interest earned is ${round(interest, 2)}')\n \n print_outputs get_inputs year, month, days, principal, rate = get_inputs()\ntotalYears = get_time(year, month, days)\ninterest = simple_interest(principal, rate, totalYears)\nprint_outputs(totalYears, interest)\n" }, { "answer_id": 74565413, "author": "MrChicano", "author_id": 17366168, "author_profile": "https://Stackoverflow.com/users/17366168", "pm_score": 0, "selected": false, "text": "get_time() totalYears simple_interest() interest totalYears simple_interest() def simple_interest():\n interest = round(principal * rate/100 * totalYears,2)\n \n #This should return 0:\n print(totalYears)\n print(\"Total interest earned is $\",interest)\n totalYears interest def get_time():\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n return totalYears\n\ndef simple_interest():\n interest = round(principal * rate/100 * totalYears,2)\n print(\"Total interest earned is $\",interest)\n return interest\n\nyear = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\n\ntotalYears = get_time()\ninterest = simple_interest()\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20593393/" ]
74,565,105
<p>I want to change the background of the elements in a list from dark to light.</p> <p>The number of items in the list is variable. It could be 5, it could be 50.</p> <p>I can set the default color of the first item.</p> <p>for example; <a href="https://i.stack.imgur.com/dqSnY.png" rel="nofollow noreferrer">for example</a></p> <p><a href="https://jsfiddle.net/tL25ngrq/1/" rel="nofollow noreferrer">https://jsfiddle.net/tL25ngrq/1/</a></p> <pre><code>class TodoApp extends React.Component { constructor(props) { super(props) this.state = { } } render() { const min = 1; const max = 255; const rand = min + Math.random() * (max - min); const minColor = 1; const maxColor = 255; const randColor = minColor + Math.random() * (maxColor - minColor); console.log(randColor) let rows = []; for (let i = 0; i &lt; rand; i++) { rows.push(&lt;tr style={{ backgroundColor: `rgb(10, ${randColor * i}, 100)` }} &gt;&lt;td&gt;Test {i}&lt;/td&gt;&lt;/tr&gt;)} return ( &lt;div&gt; &lt;table&gt; &lt;tr&gt; &lt;th&gt;Title&lt;/th&gt; &lt;/tr&gt; {rows} &lt;/table&gt; &lt;/div&gt; ) } } ReactDOM.render(&lt;TodoApp /&gt;, document.querySelector(&quot;#app&quot;)) </code></pre>
[ { "answer_id": 74565172, "author": "michael perkins", "author_id": 19620151, "author_profile": "https://Stackoverflow.com/users/19620151", "pm_score": 1, "selected": false, "text": "TotalYears get_time TotalYears year = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\n\ntotalYears = float()\ninterest = float()\n\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\ndef get_time():\n global totalYears\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n\ndef simple_interest():\n interest = round(principal * (rate/100) * totalYears,2)\n print(\"Total interest earned is $\",interest)\n\nget_time()\nsimple_interest()\n" }, { "answer_id": 74565318, "author": "Vin", "author_id": 7955271, "author_profile": "https://Stackoverflow.com/users/7955271", "pm_score": 1, "selected": false, "text": "totalYears float() totalYears get_time() totalYears get_time() totalYears totalYears simple_interest 0.0 get_time() get_time() simple_interest() year = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\n\ntotalYears = float()\ninterest = float()\n\ndef get_time():\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n return totalYears\n\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\ndef simple_interest(totalYears):\n interest = principal * rate/100 * totalYears\n\n print(f'Total interest earned is ${round(interest, 2)}')\n\ntotalYears = get_time()\nsimple_interest(totalYears)\n Enter years: 5\n\nEnter months: 3\n\nEnter days: 2\n\nEnter principal: 1000\n\nEnter rate (in %): 2\ntotal time in years is 5.3 years\nTotal interest earned is $106.0\n totalYears = float() interest = float() def get_inputs():\n\n year = int(input(\"Enter years: \"))\n month = int(input(\"Enter months: \"))\n days = int(input(\"Enter days: \"))\n principal = float(input(\"Enter principal: \"))\n rate = float(input(\"Enter rate (in %): \"))\n\n return year, month, days, principal, rate\n get_inputs def get_time(year, month, days):\n\n totalYears = round(year + (month * 31 + days)/365,1)\n\n return totalYears\n\ndef simple_interest(principal, rate, totalYears):\n\n interest = principal * rate/100 * totalYears\n\n return interest\n get_time simple_interest def print_outputs(totalYears, interest):\n\n print(f'total time in years is {totalYears} years')\n print(f'Total interest earned is ${round(interest, 2)}')\n \n print_outputs get_inputs year, month, days, principal, rate = get_inputs()\ntotalYears = get_time(year, month, days)\ninterest = simple_interest(principal, rate, totalYears)\nprint_outputs(totalYears, interest)\n" }, { "answer_id": 74565413, "author": "MrChicano", "author_id": 17366168, "author_profile": "https://Stackoverflow.com/users/17366168", "pm_score": 0, "selected": false, "text": "get_time() totalYears simple_interest() interest totalYears simple_interest() def simple_interest():\n interest = round(principal * rate/100 * totalYears,2)\n \n #This should return 0:\n print(totalYears)\n print(\"Total interest earned is $\",interest)\n totalYears interest def get_time():\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n return totalYears\n\ndef simple_interest():\n interest = round(principal * rate/100 * totalYears,2)\n print(\"Total interest earned is $\",interest)\n return interest\n\nyear = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\n\ntotalYears = get_time()\ninterest = simple_interest()\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20592836/" ]
74,565,121
<p>After defining a variable (&quot;xyz&quot; at screenshot), I fetched some data on my firestore database, then changed that variable value to data i fetched from firestore. When I print the changed variable with &quot;print()&quot; it appears at &quot;Run&quot; the value I fetched, which is what I want. But when I run the app, the text I assigned as changed variable appears on the screen with old value like I never changed it after defining. <a href="https://i.stack.imgur.com/HwH2w.png" rel="nofollow noreferrer">the code</a></p> <p>When I print(xyz); it appears as the data from firestore, so there is no problem at database connection. I just want to update the value appears at screen too.</p>
[ { "answer_id": 74565172, "author": "michael perkins", "author_id": 19620151, "author_profile": "https://Stackoverflow.com/users/19620151", "pm_score": 1, "selected": false, "text": "TotalYears get_time TotalYears year = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\n\ntotalYears = float()\ninterest = float()\n\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\ndef get_time():\n global totalYears\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n\ndef simple_interest():\n interest = round(principal * (rate/100) * totalYears,2)\n print(\"Total interest earned is $\",interest)\n\nget_time()\nsimple_interest()\n" }, { "answer_id": 74565318, "author": "Vin", "author_id": 7955271, "author_profile": "https://Stackoverflow.com/users/7955271", "pm_score": 1, "selected": false, "text": "totalYears float() totalYears get_time() totalYears get_time() totalYears totalYears simple_interest 0.0 get_time() get_time() simple_interest() year = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\n\ntotalYears = float()\ninterest = float()\n\ndef get_time():\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n return totalYears\n\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\ndef simple_interest(totalYears):\n interest = principal * rate/100 * totalYears\n\n print(f'Total interest earned is ${round(interest, 2)}')\n\ntotalYears = get_time()\nsimple_interest(totalYears)\n Enter years: 5\n\nEnter months: 3\n\nEnter days: 2\n\nEnter principal: 1000\n\nEnter rate (in %): 2\ntotal time in years is 5.3 years\nTotal interest earned is $106.0\n totalYears = float() interest = float() def get_inputs():\n\n year = int(input(\"Enter years: \"))\n month = int(input(\"Enter months: \"))\n days = int(input(\"Enter days: \"))\n principal = float(input(\"Enter principal: \"))\n rate = float(input(\"Enter rate (in %): \"))\n\n return year, month, days, principal, rate\n get_inputs def get_time(year, month, days):\n\n totalYears = round(year + (month * 31 + days)/365,1)\n\n return totalYears\n\ndef simple_interest(principal, rate, totalYears):\n\n interest = principal * rate/100 * totalYears\n\n return interest\n get_time simple_interest def print_outputs(totalYears, interest):\n\n print(f'total time in years is {totalYears} years')\n print(f'Total interest earned is ${round(interest, 2)}')\n \n print_outputs get_inputs year, month, days, principal, rate = get_inputs()\ntotalYears = get_time(year, month, days)\ninterest = simple_interest(principal, rate, totalYears)\nprint_outputs(totalYears, interest)\n" }, { "answer_id": 74565413, "author": "MrChicano", "author_id": 17366168, "author_profile": "https://Stackoverflow.com/users/17366168", "pm_score": 0, "selected": false, "text": "get_time() totalYears simple_interest() interest totalYears simple_interest() def simple_interest():\n interest = round(principal * rate/100 * totalYears,2)\n \n #This should return 0:\n print(totalYears)\n print(\"Total interest earned is $\",interest)\n totalYears interest def get_time():\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n return totalYears\n\ndef simple_interest():\n interest = round(principal * rate/100 * totalYears,2)\n print(\"Total interest earned is $\",interest)\n return interest\n\nyear = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\n\ntotalYears = get_time()\ninterest = simple_interest()\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20267587/" ]
74,565,122
<pre><code>String s = &quot;vttqexwqgdc&quot;; char[] ch = s.toCharArray(); int[] indices = {9, 5, 8, 0, 4, 3, 6, 10, 1, 2, 7}; ArrayList&lt;String&gt; list = new ArrayList&lt;&gt;(); for (int i = 0, j = 0; i &lt; ch.length; i++, j++) { list.add((indices[j] + &quot;&quot; + ch[i])); } Collections.sort(list); System.out.println(list); // **[0q, 10q, 1g, 2d, 3x, 4e, 5t, 6w, 7c, 8t, 9v], Here the 10q should be after 9 **String str = &quot;&quot;; for (String value : list) { str = str + value; } str = str.replaceAll(&quot;\\d&quot;, &quot;&quot;); System.out.println(str); </code></pre> <p>please help me how can i sort it, where i can place 10q after 9v.</p> <p>Thank you Everyone</p> <p>sorting the answer ,</p>
[ { "answer_id": 74565172, "author": "michael perkins", "author_id": 19620151, "author_profile": "https://Stackoverflow.com/users/19620151", "pm_score": 1, "selected": false, "text": "TotalYears get_time TotalYears year = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\n\ntotalYears = float()\ninterest = float()\n\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\ndef get_time():\n global totalYears\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n\ndef simple_interest():\n interest = round(principal * (rate/100) * totalYears,2)\n print(\"Total interest earned is $\",interest)\n\nget_time()\nsimple_interest()\n" }, { "answer_id": 74565318, "author": "Vin", "author_id": 7955271, "author_profile": "https://Stackoverflow.com/users/7955271", "pm_score": 1, "selected": false, "text": "totalYears float() totalYears get_time() totalYears get_time() totalYears totalYears simple_interest 0.0 get_time() get_time() simple_interest() year = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\n\ntotalYears = float()\ninterest = float()\n\ndef get_time():\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n return totalYears\n\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\ndef simple_interest(totalYears):\n interest = principal * rate/100 * totalYears\n\n print(f'Total interest earned is ${round(interest, 2)}')\n\ntotalYears = get_time()\nsimple_interest(totalYears)\n Enter years: 5\n\nEnter months: 3\n\nEnter days: 2\n\nEnter principal: 1000\n\nEnter rate (in %): 2\ntotal time in years is 5.3 years\nTotal interest earned is $106.0\n totalYears = float() interest = float() def get_inputs():\n\n year = int(input(\"Enter years: \"))\n month = int(input(\"Enter months: \"))\n days = int(input(\"Enter days: \"))\n principal = float(input(\"Enter principal: \"))\n rate = float(input(\"Enter rate (in %): \"))\n\n return year, month, days, principal, rate\n get_inputs def get_time(year, month, days):\n\n totalYears = round(year + (month * 31 + days)/365,1)\n\n return totalYears\n\ndef simple_interest(principal, rate, totalYears):\n\n interest = principal * rate/100 * totalYears\n\n return interest\n get_time simple_interest def print_outputs(totalYears, interest):\n\n print(f'total time in years is {totalYears} years')\n print(f'Total interest earned is ${round(interest, 2)}')\n \n print_outputs get_inputs year, month, days, principal, rate = get_inputs()\ntotalYears = get_time(year, month, days)\ninterest = simple_interest(principal, rate, totalYears)\nprint_outputs(totalYears, interest)\n" }, { "answer_id": 74565413, "author": "MrChicano", "author_id": 17366168, "author_profile": "https://Stackoverflow.com/users/17366168", "pm_score": 0, "selected": false, "text": "get_time() totalYears simple_interest() interest totalYears simple_interest() def simple_interest():\n interest = round(principal * rate/100 * totalYears,2)\n \n #This should return 0:\n print(totalYears)\n print(\"Total interest earned is $\",interest)\n totalYears interest def get_time():\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n return totalYears\n\ndef simple_interest():\n interest = round(principal * rate/100 * totalYears,2)\n print(\"Total interest earned is $\",interest)\n return interest\n\nyear = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\n\ntotalYears = get_time()\ninterest = simple_interest()\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20593457/" ]
74,565,134
<p>What is the proper way for storing LocalDate instances in h2 db?</p> <p>I am using data type <code>TIMESTAMP</code> but getting a strange behaviour depending on the <code>user.timezone</code> java process started with.</p> <p>When I insert a <code>TIMESTAMP</code> with timeZone America/Toronto - and read it back with timeZone UTC - there will be a 1 hour difference for <code>2021-05-01</code> but not for <code>2021-01-01</code>.</p> <p><strong>Steps to Reproduce</strong></p> <p>Make sure you have <code>h2-1.4.196.jar</code> in the current folder. Start h2 console with:</p> <pre><code>java -Duser.timezone=America/Toronto -cp h2*.jar org.h2.tools.Console </code></pre> <p>For JDBC URL I am using, not all are relevant I assume but <code>MV_STORE=FALSE</code> and <code>MVCC=FALSE</code> should be important.</p> <pre><code>jdbc:h2:~/mydb;DATABASE_TO_UPPER=FALSE;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=60000;CACHE_SIZE=16384;AUTO_SERVER=TRUE;MV_STORE=FALSE;MVCC=FALSE </code></pre> <p>Run the following query to create a new table:</p> <pre><code>CREATE TABLE foo ( time TIMESTAMP NULL, ); </code></pre> <p>Insert two rows:</p> <pre><code>INSERT INTO foo VALUES (TIMESTAMP '2021-05-01 00:00:00.0') INSERT INTO foo VALUES (TIMESTAMP '2021-01-01 00:00:00.0') </code></pre> <p>Verify you inserted data successfully, which returns:</p> <pre><code>SELECT * FROM foo; time 2021-05-01 00:00:00.0 2021-01-01 00:00:00.0 </code></pre> <p>Now stop the java process you started and this time run it with the following, note the <code>user.timezone</code> is different:</p> <pre><code>java -Duser.timezone=UTC -cp h2*.jar org.h2.tools.Console </code></pre> <p>Connect using the same URL above and run the same SELECT query above. Observe the hour difference in the result <strong>only for the first entry.</strong></p> <pre><code>SELECT * FROM foo; time 2021-04-30 23:00:00.0 2021-01-01 00:00:00.0 </code></pre>
[ { "answer_id": 74565172, "author": "michael perkins", "author_id": 19620151, "author_profile": "https://Stackoverflow.com/users/19620151", "pm_score": 1, "selected": false, "text": "TotalYears get_time TotalYears year = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\n\ntotalYears = float()\ninterest = float()\n\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\ndef get_time():\n global totalYears\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n\ndef simple_interest():\n interest = round(principal * (rate/100) * totalYears,2)\n print(\"Total interest earned is $\",interest)\n\nget_time()\nsimple_interest()\n" }, { "answer_id": 74565318, "author": "Vin", "author_id": 7955271, "author_profile": "https://Stackoverflow.com/users/7955271", "pm_score": 1, "selected": false, "text": "totalYears float() totalYears get_time() totalYears get_time() totalYears totalYears simple_interest 0.0 get_time() get_time() simple_interest() year = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\n\ntotalYears = float()\ninterest = float()\n\ndef get_time():\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n return totalYears\n\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\ndef simple_interest(totalYears):\n interest = principal * rate/100 * totalYears\n\n print(f'Total interest earned is ${round(interest, 2)}')\n\ntotalYears = get_time()\nsimple_interest(totalYears)\n Enter years: 5\n\nEnter months: 3\n\nEnter days: 2\n\nEnter principal: 1000\n\nEnter rate (in %): 2\ntotal time in years is 5.3 years\nTotal interest earned is $106.0\n totalYears = float() interest = float() def get_inputs():\n\n year = int(input(\"Enter years: \"))\n month = int(input(\"Enter months: \"))\n days = int(input(\"Enter days: \"))\n principal = float(input(\"Enter principal: \"))\n rate = float(input(\"Enter rate (in %): \"))\n\n return year, month, days, principal, rate\n get_inputs def get_time(year, month, days):\n\n totalYears = round(year + (month * 31 + days)/365,1)\n\n return totalYears\n\ndef simple_interest(principal, rate, totalYears):\n\n interest = principal * rate/100 * totalYears\n\n return interest\n get_time simple_interest def print_outputs(totalYears, interest):\n\n print(f'total time in years is {totalYears} years')\n print(f'Total interest earned is ${round(interest, 2)}')\n \n print_outputs get_inputs year, month, days, principal, rate = get_inputs()\ntotalYears = get_time(year, month, days)\ninterest = simple_interest(principal, rate, totalYears)\nprint_outputs(totalYears, interest)\n" }, { "answer_id": 74565413, "author": "MrChicano", "author_id": 17366168, "author_profile": "https://Stackoverflow.com/users/17366168", "pm_score": 0, "selected": false, "text": "get_time() totalYears simple_interest() interest totalYears simple_interest() def simple_interest():\n interest = round(principal * rate/100 * totalYears,2)\n \n #This should return 0:\n print(totalYears)\n print(\"Total interest earned is $\",interest)\n totalYears interest def get_time():\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n return totalYears\n\ndef simple_interest():\n interest = round(principal * rate/100 * totalYears,2)\n print(\"Total interest earned is $\",interest)\n return interest\n\nyear = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\n\ntotalYears = get_time()\ninterest = simple_interest()\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1173112/" ]
74,565,159
<p>I would like to call a function that is inside another function, that function will clear the timeout.</p> <p>I have tried the following code, but without success:</p> <pre class="lang-js prettyprint-override"><code>async function Blast2() { const delayTime = 1000; const timer = (ms) =&gt; new Promise((res) =&gt; setTimeout(res, ms)); function ClearDelayTime() { return clearTimeout(blast); } const blast = setTimeout(function () { let blast = &quot;SELECT * FROM admin_contacts,temporary WHERE blast_status = 'sended'&quot;; db.query(blast, async function (err, result, field) { if (err) throw err; loop: { for (var i = 0; i &lt; result.length; i++) { console.log(result[i].telefone); await timer(delayTime); // then the created Promise can be awaited } } }); }, delayTime); } // I Want Call the function ClearDelayTime() inside Blast2() Blast2().ClearDelayTime(); </code></pre>
[ { "answer_id": 74565172, "author": "michael perkins", "author_id": 19620151, "author_profile": "https://Stackoverflow.com/users/19620151", "pm_score": 1, "selected": false, "text": "TotalYears get_time TotalYears year = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\n\ntotalYears = float()\ninterest = float()\n\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\ndef get_time():\n global totalYears\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n\ndef simple_interest():\n interest = round(principal * (rate/100) * totalYears,2)\n print(\"Total interest earned is $\",interest)\n\nget_time()\nsimple_interest()\n" }, { "answer_id": 74565318, "author": "Vin", "author_id": 7955271, "author_profile": "https://Stackoverflow.com/users/7955271", "pm_score": 1, "selected": false, "text": "totalYears float() totalYears get_time() totalYears get_time() totalYears totalYears simple_interest 0.0 get_time() get_time() simple_interest() year = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\n\ntotalYears = float()\ninterest = float()\n\ndef get_time():\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n return totalYears\n\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\ndef simple_interest(totalYears):\n interest = principal * rate/100 * totalYears\n\n print(f'Total interest earned is ${round(interest, 2)}')\n\ntotalYears = get_time()\nsimple_interest(totalYears)\n Enter years: 5\n\nEnter months: 3\n\nEnter days: 2\n\nEnter principal: 1000\n\nEnter rate (in %): 2\ntotal time in years is 5.3 years\nTotal interest earned is $106.0\n totalYears = float() interest = float() def get_inputs():\n\n year = int(input(\"Enter years: \"))\n month = int(input(\"Enter months: \"))\n days = int(input(\"Enter days: \"))\n principal = float(input(\"Enter principal: \"))\n rate = float(input(\"Enter rate (in %): \"))\n\n return year, month, days, principal, rate\n get_inputs def get_time(year, month, days):\n\n totalYears = round(year + (month * 31 + days)/365,1)\n\n return totalYears\n\ndef simple_interest(principal, rate, totalYears):\n\n interest = principal * rate/100 * totalYears\n\n return interest\n get_time simple_interest def print_outputs(totalYears, interest):\n\n print(f'total time in years is {totalYears} years')\n print(f'Total interest earned is ${round(interest, 2)}')\n \n print_outputs get_inputs year, month, days, principal, rate = get_inputs()\ntotalYears = get_time(year, month, days)\ninterest = simple_interest(principal, rate, totalYears)\nprint_outputs(totalYears, interest)\n" }, { "answer_id": 74565413, "author": "MrChicano", "author_id": 17366168, "author_profile": "https://Stackoverflow.com/users/17366168", "pm_score": 0, "selected": false, "text": "get_time() totalYears simple_interest() interest totalYears simple_interest() def simple_interest():\n interest = round(principal * rate/100 * totalYears,2)\n \n #This should return 0:\n print(totalYears)\n print(\"Total interest earned is $\",interest)\n totalYears interest def get_time():\n totalYears = round(year + (month * 31 + days)/365,1)\n print(\"total time in years is\",totalYears,\"years\")\n return totalYears\n\ndef simple_interest():\n interest = round(principal * rate/100 * totalYears,2)\n print(\"Total interest earned is $\",interest)\n return interest\n\nyear = int(input(\"Enter years: \"))\nmonth = int(input(\"Enter months: \"))\ndays = int(input(\"Enter days: \"))\nprincipal = float(input(\"Enter principal: \"))\nrate = float(input(\"Enter rate (in %): \"))\n\n\ntotalYears = get_time()\ninterest = simple_interest()\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17909031/" ]
74,565,175
<p>Suppose I have something like this:</p> <pre><code>CREATE TABLE &quot;PIPPO&quot; (&quot;COLUMN1&quot; number); INSERT INTO PIPPO (COLUMN1) VALUES (1); INSERT INTO PIPPO (COLUMN1) VALUES (2); INSERT INTO PIPPO (COLUMN1) VALUES (3); INSERT INTO PIPPO (COLUMN1) VALUES (4); INSERT INTO PIPPO (COLUMN1) VALUES (5); INSERT INTO PIPPO (COLUMN1) VALUES (6); INSERT INTO PIPPO (COLUMN1) VALUES (7); INSERT INTO PIPPO (COLUMN1) VALUES (8); </code></pre> <p>Is there an &quot;easy&quot; way to run a <code>SELECT</code> query on the table to get the last N rows, where N is the rest of divide by 3?</p> <p>For example for this case I would like o retrieve:</p> <pre><code>7 8 </code></pre> <p>Imagine to insert another record</p> <pre><code> INSERT INTO PIPPO (COLUMN1) VALUES (9); </code></pre> <p>In this case, I would like to retrieve:</p> <pre><code>7 8 9 </code></pre> <p>Imagine inserting yet another record:</p> <pre><code> INSERT INTO PIPPO (COLUMN1) VALUES (10); </code></pre> <p>Now in this case I would like to retrieve just:</p> <pre><code>10 </code></pre> <p>Any ideas?</p>
[ { "answer_id": 74565259, "author": "jarlh", "author_id": 3706016, "author_profile": "https://Stackoverflow.com/users/3706016", "pm_score": 3, "selected": true, "text": "FETCH FIRST select * from\n(\n select * from PIPPO \n order by COLUMN1 desc\n fetch first (select mod(count(*)-1, 3) + 1 from PIPPO) rows only\n) dt\norder by COLUMN1 \n" }, { "answer_id": 74565362, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 2, "selected": false, "text": "FETCH FIRST n ROWS ONLY n SELECT *\nFROM pippo\nORDER BY column1 DESC\nFETCH FIRST (SELECT DECODE(MOD(COUNT(*), 3), 0, 3, 1, 1, 2, 2) FROM pippo) ROWS ONLY\n SELECT column1\nFROM (\n SELECT column1,\n ROW_NUMBER() OVER (ORDER BY column1 DESC) AS rn,\n MOD(COUNT(*) OVER (), 3) AS rem\n FROM pippo p\n)\nWHERE rn <= DECODE(rem, 0, 3, rem);\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3359469/" ]
74,565,179
<p>I have a boxplot with four groups and I want to add a name to each group that consists <strong>of two lines</strong> and <strong>includes subscripts</strong>. Therefore I tried using <code>bquote()</code>:</p> <pre><code>#sample data groups = matrix(1:40,ncol=4) #create group names names = as.expression(sapply(1:4, function(x){ letter = LETTERS[x] name = bquote(atop(.(letter),num[.(x)] == .(x))) return(name) })) boxplot(groups, names = names) </code></pre> <p>Which gives me the following result: <a href="https://i.stack.imgur.com/Mc8mb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mc8mb.png" alt="enter image description here" /></a></p> <p>I'm almost pleased with the result. However, <code>atop()</code> has some weird spacing so that the top line (with letters A-D) lies on top of the outer boundary. I couldn't find any solution working for me to solve this problem.</p> <p>I also tried the following:</p> <pre><code>#Alternative Approach (not working) names = parse(text=paste(LETTERS[1:4],&quot;\n&quot;,&quot;num[&quot;, 1:4, &quot;]&quot;, sep=&quot;&quot;)) </code></pre> <p>In this case, the addition of &quot;\n&quot; (new line) simply breaks the <code>names</code> variable from length 4 into length 8.</p> <p>I have absolutely no idea how to solve this seemingly simple problem. Help is much appreciated!</p>
[ { "answer_id": 74565259, "author": "jarlh", "author_id": 3706016, "author_profile": "https://Stackoverflow.com/users/3706016", "pm_score": 3, "selected": true, "text": "FETCH FIRST select * from\n(\n select * from PIPPO \n order by COLUMN1 desc\n fetch first (select mod(count(*)-1, 3) + 1 from PIPPO) rows only\n) dt\norder by COLUMN1 \n" }, { "answer_id": 74565362, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 2, "selected": false, "text": "FETCH FIRST n ROWS ONLY n SELECT *\nFROM pippo\nORDER BY column1 DESC\nFETCH FIRST (SELECT DECODE(MOD(COUNT(*), 3), 0, 3, 1, 1, 2, 2) FROM pippo) ROWS ONLY\n SELECT column1\nFROM (\n SELECT column1,\n ROW_NUMBER() OVER (ORDER BY column1 DESC) AS rn,\n MOD(COUNT(*) OVER (), 3) AS rem\n FROM pippo p\n)\nWHERE rn <= DECODE(rem, 0, 3, rem);\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11738400/" ]
74,565,181
<pre><code> Container( decoration: BoxDecoration( color: (page == _currentPage) ? Colors.blue.shade800 : Colors.green.shade600 ), </code></pre> <p>I am trying to add another option to the tenerary operator since i have three pages that will change color. How can i add a third option</p>
[ { "answer_id": 74565295, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 2, "selected": false, "text": "color: page == _currentPage\n ? anotherCheck == _currentPage? \n Colors.blue.shade500: Colors.blue.shade800 \n : Colors.green.shade600 \n" }, { "answer_id": 74565333, "author": "Mohamed Amine F", "author_id": 18391837, "author_profile": "https://Stackoverflow.com/users/18391837", "pm_score": 2, "selected": true, "text": "List<Color> colors = [Colors.blue, Colors.amber, Colors.pink];\n...\n\n\nContainer(\n decoration: BoxDecoration(\n color: colors[ _currentPage],\n" }, { "answer_id": 74565888, "author": "Amit Bahadur", "author_id": 14562817, "author_profile": "https://Stackoverflow.com/users/14562817", "pm_score": 0, "selected": false, "text": "(foo==1)? something1():(foo==2)? something2():(foo==3)?something3():something4();\n if(foo == 1){\n something1();\n}\nelse if(foo == 2){\n something2();\n}\nelse if (foo == 3){\n something3();\n}\nelse{\n something4();}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17302941/" ]
74,565,192
<p>I have a third party closed source c library that interfaces with hardware. The library has some api functions that accept <code>void *</code> arguments to read/write and configure some io, like so:</p> <pre><code>int iocall(int cmd, void * args); int iorw(int cmd, void * buff, size_t buff_size); </code></pre> <p>I want to wrap these in a c++ class to be able to inject that class, be able to mock it using gtest and introduce exceptions and get rid of all the return value checks inside the upper service classes. So far so good. Here comes my question: What would be the best way of designing an interface for that class when it comes to the <code>void *</code> arguments?</p> <p>interface.h</p> <pre><code>class wrap: { virtual void wrap_iocall(int cmd, ??) = 0; } </code></pre> <p>interface_impl.h</p> <pre><code>class wrap: { void wrap_iocall(int cmd, ??) override { int ret{iocall(cmd, ??)}; // do some more stuff, e.g. exceptions and so on } } </code></pre> <p>My first take was to just overload the calls with dedicated types - but since there are a lot of them, this might be a pain to maintain and I will need to change the interface when another call is needed (e.g. other hardware call) + the library might get updates which forces me to update types.</p> <p>The second thing I thought about is using <code>std::any</code> which would fit my use case but I am unsure how I would pass a pointer to the <code>std::any</code> container to the underlying c-function? I thought about pushing it into a <code>std::vector&lt;std::any&gt;</code> and use the <code>.data()</code> function to pass a pointer, but then I am left with a guess on the size of that container I think? And this sounds like a very bad attempt to achieve what I am looking for.</p> <p>The third thing I came across was a solution using templates, but if my understanding is correct, these things cannot be virtual and hence break with my intention to mock the interface, requiring it to be virtual. So I think this might not work either.</p> <p>The last thing I can currently think of is sticking to just <code>void *</code> in the wrapping function and have the upper service layer handle the type casts, e.g. allocate the struct for the specific device call and pass the pointer to the <code>void *</code> argument of the wrapper. This is by far my least favorite option.</p> <p>I want to stick to the principle of type safe function arguments but I am not sure of how to proceed from here. Any help/feedback is appreciated!</p>
[ { "answer_id": 74565295, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 2, "selected": false, "text": "color: page == _currentPage\n ? anotherCheck == _currentPage? \n Colors.blue.shade500: Colors.blue.shade800 \n : Colors.green.shade600 \n" }, { "answer_id": 74565333, "author": "Mohamed Amine F", "author_id": 18391837, "author_profile": "https://Stackoverflow.com/users/18391837", "pm_score": 2, "selected": true, "text": "List<Color> colors = [Colors.blue, Colors.amber, Colors.pink];\n...\n\n\nContainer(\n decoration: BoxDecoration(\n color: colors[ _currentPage],\n" }, { "answer_id": 74565888, "author": "Amit Bahadur", "author_id": 14562817, "author_profile": "https://Stackoverflow.com/users/14562817", "pm_score": 0, "selected": false, "text": "(foo==1)? something1():(foo==2)? something2():(foo==3)?something3():something4();\n if(foo == 1){\n something1();\n}\nelse if(foo == 2){\n something2();\n}\nelse if (foo == 3){\n something3();\n}\nelse{\n something4();}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20593119/" ]
74,565,207
<p>I have a table tx_bla_domain_model_offer</p> <p>in the title field I store several titles from tx_bla_domain_model_blubtitle with tx_bla_blub_title_mm</p> <p>The first time I save everything is correct, I can sort the titles as I want and it keeps everything sorted.</p> <p>Only, if I want to sort the same titles differently, it keeps the old sorting when saving...</p> <p>Sorting in $_POST['tx_bla']['offer']['offerTitle'] is correct. Sorting in $this-&gt;arguments-&gt;getArgument('offer')-&gt;getValue()-&gt;getOfferTitle() is not correct.</p> <p>In tx_bla_blub_title_mm the sorting does not change...</p> <p>In the TCA is set foreign_sortby, but it haves no effect...</p>
[ { "answer_id": 74568919, "author": "Bernd Wilke πφ", "author_id": 6796354, "author_profile": "https://Stackoverflow.com/users/6796354", "pm_score": 1, "selected": false, "text": "attention" }, { "answer_id": 74575750, "author": "Gero Langheim", "author_id": 20593382, "author_profile": "https://Stackoverflow.com/users/20593382", "pm_score": 0, "selected": false, "text": " $offer->setOfferTitle(new \\TYPO3\\CMS\\Extbase\\Persistence\\ObjectStorage);\n foreach ($_POST['tx_bla_jobs']['offer']['offerTitle'] as $titleUid) {\n $offer->addOfferTitle($this->offertitleRepository->findByUid($titleUid));\n }\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20593382/" ]
74,565,229
<p>I am using below formula to find the last matching value<br /> but how can i expand it with ArrayFormula<br /> =index(filter(A:A,B:B=F3),SUMPRODUCT(B:B=F3))</p> <p>I expect to have a arrayformula to work with index and filter but couldnt</p>
[ { "answer_id": 74568919, "author": "Bernd Wilke πφ", "author_id": 6796354, "author_profile": "https://Stackoverflow.com/users/6796354", "pm_score": 1, "selected": false, "text": "attention" }, { "answer_id": 74575750, "author": "Gero Langheim", "author_id": 20593382, "author_profile": "https://Stackoverflow.com/users/20593382", "pm_score": 0, "selected": false, "text": " $offer->setOfferTitle(new \\TYPO3\\CMS\\Extbase\\Persistence\\ObjectStorage);\n foreach ($_POST['tx_bla_jobs']['offer']['offerTitle'] as $titleUid) {\n $offer->addOfferTitle($this->offertitleRepository->findByUid($titleUid));\n }\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20590728/" ]
74,565,244
<p>Im making portfolio website, and I want my fixed texts change its color on some sections, how can I do that ?I can't post my code,because its too big and long, but if you will give example with codes will be really pleased,here is how it must look like (<a href="https://olaolu.dev" rel="nofollow noreferrer">https://olaolu.dev</a>),you see how button and name is changing color while scrollings want to do as well:)</p> <p>P.s please do it with js,thanks!</p> <p>I tried to find info but I haven't find anything:(</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;/b/cs.css&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css&quot;&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;section class=&quot;section-top active&quot; id=&quot;s1&quot;&gt; &lt;div class=&quot;details&quot;&gt; &lt;div class=&quot;top&quot;&gt; &lt;h2&gt;Faxraddin&lt;/h2&gt; &lt;div class=&quot;lists&quot;&gt; &lt;div class=&quot;nav-btn&quot; id=&quot;nav-icon1&quot; onclick=&quot;document.getElementById('nav-icon1').classList.toggle('open')&quot;&gt; &lt;span&gt;&lt;/span&gt; &lt;span&gt;&lt;/span&gt; &lt;span&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;hide-it&quot;&gt; &lt;div class=&quot;hide1&quot;&gt; &lt;div class=&quot;p1&quot;&gt; &lt;a class=&quot;hide1-btn&quot;&gt;My Work&lt;/a&gt; &lt;a class=&quot;hide1-btn&quot;&gt;My Shelf&lt;/a&gt; &lt;a class=&quot;hide1-btn&quot;&gt;My Resume&lt;/a&gt; &lt;/div&gt; &lt;div class=&quot;p2&quot;&gt; &lt;a class=&quot;hide-span&quot;&gt;SAY HELLO&lt;/a&gt; &lt;a class=&quot;hide-span&quot;&gt;jncoicih@gmail.com&lt;/a&gt; &lt;a class=&quot;hide-span&quot;&gt;t/me.com&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;first-info&quot;&gt; &lt;div class=&quot;first-sec&quot;&gt; &lt;h1&gt;Frontend&lt;/br&gt; Developer.&lt;/h1&gt; &lt;h3 class=&quot;profession-info&quot;&gt;I like to craft solid and scalable frontend products with great user experiences.&lt;/h3&gt; &lt;/div&gt; &lt;img class=&quot;my-img&quot; src=&quot;/b/images/Screenshot 2022-11-04 at 19.35.20.png&quot;&gt; &lt;/div&gt; &lt;div class=&quot;some-info&quot;&gt; &lt;div class=&quot;a1&quot;&gt; &lt;span&gt;Highly skilled at progressive enhancement, design systems &amp; UI Engineering. &lt;/span&gt; &lt;span&gt;Over a decade of experience building products for clients across several countries. &lt;/span&gt; &lt;/div&gt; &lt;div class=&quot;btn-container&quot;&gt; &lt;ul&gt; &lt;a class=&quot;a&quot; href=&quot;#s1&quot;&gt;&lt;div class=&quot;btn&quot;&gt;&lt;/div&gt;&lt;/a&gt; &lt;a class=&quot;a&quot; href=&quot;#s2&quot;&gt;&lt;div class=&quot;btn&quot;&gt;&lt;/div&gt;&lt;/a&gt; &lt;a class=&quot;a&quot; href=&quot;#s3&quot;&gt;&lt;div class=&quot;btn&quot;&gt;&lt;/div&gt;&lt;/a&gt; &lt;a class=&quot;a&quot; href=&quot;#s4&quot;&gt;&lt;div class=&quot;btn&quot;&gt;&lt;/div&gt;&lt;/a&gt; &lt;a class=&quot;a&quot; href=&quot;#s5&quot;&gt;&lt;div class=&quot;btn&quot;&gt;&lt;/div&gt;&lt;/a&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;section class=&quot;what-do&quot; id=&quot;s2&quot;&gt; &lt;div class=&quot;my-info&quot;&gt; &lt;div class=&quot;what-doing&quot; id=&quot;i1&quot;&gt; &lt;h1&gt;Design&lt;/h1&gt; &lt;p&gt; I'm probably not the typical designer positioned behind an Illustrator artboard adjusting pixels, but I design. Immersed in stylesheets tweaking font sizes and contemplating layouts is where you'll find me (~_^). I'm committed to creating fluent user experiences while staying fashionable. &lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;what-doing&quot; id=&quot;i2&quot;&gt; &lt;h1&gt;Engineering&lt;/h1&gt; &lt;p&gt; In building JavaScript applications, I'm equipped with just the right tools, and can absolutely function independently of them to deliver fast, resilient solutions optimized for scale — performance and scalabilty are priorities on my radar &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;section class=&quot;exp&quot; id=&quot;s3&quot;&gt; &lt;div class=&quot;e1&quot;&gt; &lt;div class=&quot;exp-info&quot;&gt; &lt;h2&gt;Over the&lt;/br&gt; past 3 years,&lt;/h2&gt; &lt;p&gt;I've built products for companies and businesses around the globe ranging from marketing websites to complex solutions and enterprise apps with focus on fast, elegant and accessible user experiences.&lt;/p&gt; &lt;p&gt;Currently, I work at Shopify as a Senior UX Developer and Accessibility advocate crafting thoughtful and inclusive experiences that adhere to web standards for over a million merchants across the world.&lt;/p&gt; &lt;p&gt;Before now, I was Principal Frontend Engineer at hellotax, where I worked on a suite of tools and services tailored at providing fast, automated VAT Registration / filings &amp; Returns solutions for multi-channel sellers across Europe.&lt;/p&gt; &lt;p&gt;Prior to hellotax, I was Senior frontend engineering contractor with Pixel2HTML, building JavaScript applications and interfaces for orgs and individuals.&lt;/p&gt; &lt;p&gt;I once also led the frontend team at a Russian startup, Conectar through building multiple React applications into a single robust learning platform.&lt;/p&gt; &lt;/div&gt; &lt;img class=&quot;exp-img&quot; src=&quot;/b/images/2634454 copy.pdf&quot;&gt; &lt;/div&gt; &lt;/section&gt; &lt;section class=&quot;done&quot; id=&quot;s4&quot;&gt; &lt;div class=&quot;grid&quot;&gt; &lt;div class=&quot;what-done&quot;&gt; &lt;div class=&quot;w1&quot;&gt; &lt;h1&gt;I buld &amp; &lt;/br&gt; deign stuff&lt;/h1&gt; &lt;p&gt;Open source projects, web apps and experimentals. &lt;/p&gt; &lt;button class=&quot;done-btn&quot;&gt;see my work ---&gt;&lt;/button&gt; &lt;/div&gt; &lt;div class=&quot;w2&quot;&gt; &lt;h1&gt;I write,&lt;/br&gt;sometimes&lt;/h1&gt; &lt;p&gt;About design, frontend dev, learning and life. &lt;/p&gt; &lt;button class=&quot;done-btn&quot;&gt;read my article ---&gt;&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;section id=&quot;s5&quot; class=&quot;send-me&quot;&gt; &lt;div class=&quot;send-container&quot;&gt; &lt;div class=&quot;send-top&quot;&gt; &lt;h1&gt;Send me a message!&lt;/h1&gt; &lt;p&gt;Got a question or proposal, or just want&lt;/br&gt; to say hello? Go ahead.&lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;send-inputs&quot;&gt; &lt;div class=&quot;l&quot;&gt; &lt;label&gt;Your Name&lt;/label&gt; &lt;input type=&quot;text&quot; placeholder=&quot;Enter your name&quot;&gt; &lt;/div&gt; &lt;div class=&quot;l&quot;&gt; &lt;label&gt;Email Address&lt;/label&gt; &lt;input type=&quot;text&quot; placeholder=&quot;Enter your address&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;send-final&quot;&gt; &lt;input type=&quot;text&quot; placeholder=&quot;Hi,i think we have to work together&quot;&gt; &lt;button class=&quot;shoot&quot;&gt;SHOOT ---&gt;&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;section class=&quot;end-1&quot; id=&quot;s6&quot;&gt; &lt;div class=&quot;end-container&quot;&gt; &lt;div class=&quot;end-info&quot;&gt; &lt;div class=&quot;e2&quot; id=&quot;ll&quot;&gt; &lt;span&gt;SAY HELLO&lt;/span&gt; &lt;span&gt;hello@olaolu.dev&lt;/span&gt; &lt;span&gt;t.me/mrolaolu&lt;/span&gt; &lt;/div&gt; &lt;div class=&quot;e2&quot;&gt; &lt;span&gt;My Work&lt;/span&gt; &lt;span&gt;My Shelf&lt;/span&gt; &lt;span&gt;My Resume&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;h2 class=&quot;end-link&quot;&gt;© Faxraddin Olawuyi 2022&lt;/h2&gt; &lt;/div&gt; &lt;/section&gt; &lt;script src=&quot;/b/js.js&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; body { margin: 0; padding: 0; scroll-snap-type: y mandatory; } html{ scroll-behavior: smooth; } .bar1, .bar2, .bar3 { width: 2.5vw; height: .35vw; background-color: #333; margin: 6px 0; transition: 0.2s; } .change .bar1 { transform: translate(0, 11px) rotate(-45deg); } .change .bar2 {opacity: 0;} .change .bar3 { transform: translate(0, -11px) rotate(45deg); } section{ scroll-snap-align: start; } .section-top{ height: 47vw; padding-bottom: 10vw; } .details{ background-color:#0b2361; background-repeat: no-repeat; background-size: 100vw 100%; } .top { display: flex; justify-content: space-between; padding: 1vw; padding-bottom: 6vw; } .top h2{ font-size: 2.2vw; margin: 0; margin-top: 30px; margin-left: 60px; color:#e9ecf4; position: fixed; z-index: 3; } .nav-btn { background: none; border: none; font-size: 3vw; cursor: pointer; position: fixed; right: 4.5vw; top:4vw; z-index: 3; padding-bottom: 2vw; } #l1{ width: 3vw; } #l2{ width: 2vw; } .first-info{ display: flex; justify-content: space-between; width: 70vw; margin-left: 10vw ; padding-top: 30px; } .first-sec h1{ font-size: 4.4vw; color: #f1554c; } .first-sec h3{ width: 35vw; margin-top: -2vw; font-size: 1.5vw; color:#e9ecf4; } .my-img{ width: 24vw; margin-top: 10px; } .a1{ display: flex; justify-content: space-between; width: 35vw; margin-left: 10vw ; padding-top: 30px; color:#f1554c; margin-top: 20px; padding-bottom: 6.5vw; font-size: 1.3vw; } .a1 span{ width: 45%; font-size: 1vw; } .some-info { display: flex; justify-content: space-between; width: 93vw; } .btn-container{ position: fixed; z-index: 1; right: 0; padding-right: 5.5vw; margin-top: -3vw; } .btn-container ul{ display: flex; flex-direction: column; align-items: center; } .btn{ margin:.7vw; cursor: pointer; z-index: 1; width: .2vw; height: .2vw; background-color: black; transform: rotate(45deg); border-style:solid; transition: 0.3s; } .what-do{ background-repeat: no-repeat; background-size: 100vw 100%; height: 840px; background-color: #e9ecf4; } .my-info{ display: flex; margin-left: 7vw ; position: relative; top: 50%; left: 50%; transform: translate(-50%, -50%); } .what-doing{ width: 50%; } .what-doing h1{ font-size: 4vw; color: #f1554c; } .what-doing p{ font-size: 1.2vw; width: 30vw; margin-top: -2vw; color:#0b2361; } #i2{ margin-top: 17vw; margin-left: 1vw; } .exp{ height: 840px; background-color:#0b2361 } .e1{ display: flex; justify-content: space-between; width: 85vw; padding-top: 1vw; margin-left: -8vw; padding-bottom: 2vw; position: relative; top: 50%; left: 50%; transform: translate(-50%, -50%); } .exp-info{ display: flex; flex-direction: column; margin-left: 10vw; color: #e9ecf4; } .exp-info h2{ font-size: 4.5vw; margin-bottom: 0; } .exp-info p{ width: 25vw; font-size: 1.1vw; } .exp-img{ height: 40vw; margin-top: 6vw; } .done{ height: 840px; background-color:#e9ecf4; } .grid{ position: relative; top: 50%; left: 50%; transform: translate(-50%, -50%); } .what-done{ display: flex; margin: auto; width: 90vw; height: 40vw; background-color: whitesmoke; } .w1{ width: 50%; text-align: left; padding: 5vw; } .w2{ width: 50%; text-align: left; padding: 5vw; border-left-style: solid; border-width: thin; } .w1 h1{ font-size: 3.3vw; color: #f1554c; } .w1 p{ font-size: 2vw; color:#0b2361; } .w2 h1{ font-size: 3.3vw; color: #f1554c; } .w2 p{ font-size: 2vw; color: #0b2361; } .done-btn{ background: none; cursor: pointer; font-size: 1.3vw; padding: 1.3vw 5vw 1.3vw 5vw; margin-top: 3vw; color: #f1554c; } .hide-it{ position: absolute; transition: 0.2s; background-color: white; height: 0; width: 25vw; position: fixed; right: 3vw; top:3vw; color: white; } .hide1{ display: flex; flex-direction: column; } .p1{ display: flex; flex-direction: column; padding-top: 6vw; padding-left: 2.7vw; transition: 0.1s; visibility: hidden; transition: 0.1; } .hide1-btn{ border: none; background: none; font-size: 1.4vw; text-align: left; padding: 10px; } .p2{ display: flex; flex-direction: column; padding-top: 6vw; padding-left: 2.7vw; transition: 0.1s; visibility: hidden; transition: 0.9; } .hode-1{ font-size: 1.4vw; text-align: left; padding: 10px; } .hide-span{ font-size: 1.4vw; text-align: left; padding: 10px; } .active{ visibility: visible; height: 34vw; z-index: 2; color: black; } .active2{ visibility: visible; } .btn.active1{ background-color: white; width: .7vw; height: .7vw; transform: rotate(0deg); border-radius: 4px; } #nav-icon1 { width: 4vw; height: 3vw; -webkit-transform: rotate(0deg); -moz-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); -webkit-transition: .5s ease-in-out; -moz-transition: .5s ease-in-out; -o-transition: .5s ease-in-out; transition: .5s ease-in-out; cursor: pointer; } #nav-icon1 span { display: block; position: absolute; height: 3px; width: 3.5vw; background: black; border-radius: 9px; opacity: 1; left: 0; -webkit-transform: rotate(0deg); -moz-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); -webkit-transition: .25s ease-in-out; -moz-transition: .25s ease-in-out; -o-transition: .25s ease-in-out; transition: .25s ease-in-out; } #nav-icon1 span:nth-child(1) { top: 0px; } #nav-icon1 span:nth-child(2) { top: 18px; } #nav-icon1 span:nth-child(3) { top: 36px; } #nav-icon1.open span:nth-child(1) { top: 18px; -webkit-transform: rotate(135deg); -moz-transform: rotate(135deg); -o-transform: rotate(135deg); transform: rotate(135deg); } #nav-icon1.open span:nth-child(2) { opacity: 0; left: -60px; } #nav-icon1.open span:nth-child(3) { top: 18px; -webkit-transform: rotate(-135deg); -moz-transform: rotate(-135deg); -o-transform: rotate(-135deg); transform: rotate(-135deg); } .send-me{ height: 840px; background-color: #e9ecf4; display: flex; justify-content: center; align-items: center; } .send-top h1{ font-size: 3.3vw; text-align: center; color: #f1554c; } .send-top p{ font-size: 1.7vw; color:#0b2361; text-align: center; margin-top: -2vw; padding-bottom: 5vw; } .send-inputs{ display: flex; justify-content: space-between; width: 50vw; } .send-inputs input{ outline: none; padding: 1vw 0vw 1vw 0vw; width: 21vw; height: 2vw; font-size: 1.3vw; border-bottom: 5px solid black; border-width: thin; background: none; border-top: none; border-left: none; border-right: none; } .send-inputs label{ font-size: 1vw; } .l{ display: flex; flex-direction: column; } .send-final{ padding-top: 4vw; width: 50.5vw; display: flex; justify-content: center; align-items: center; flex-direction: column; } .send-final input{ background: none; font-size: 1.3vw; width: 100%; outline: none; padding: 1vw 0vw 1vw 0vw; height: 2vw; border-width: thin; border-bottom: 5px solid black; background: none; border-width: thin; border-top: none; border-left: none; border-right: none; } .shoot{ border-width: thin; font-size: 1.3vw; border-color: black; margin-top: 4vw; width: 20vw; height: 4vw; background: none; cursor: pointer; font-size: 1.3vw; padding: 1.3vw 5vw 1.3vw 5vw; } .end-1{ background-color: #0b2361; height: 830px; display: flex; justify-content: center; align-items: center; } .end-container{ display: flex; flex-direction: column; width: 80vw; } .end-info{ border-width: thin; border-bottom: 5px solid #e9ecf4; background: none; border-width: thin; border-top: none; border-left: none; border-right: none; display: flex; } .e2{ display: flex; flex-direction: column; font-size: 1.5vw; color: #e9ecf4; padding: 4vw 0vw 8vw 0vw; } .e2 span{ padding-top: 1.5vw; } #ll{ margin-top:-3vw; padding-right: 19vw; } .end-link{ color: #e9ecf4; padding-top: 3vw; } </code></pre>
[ { "answer_id": 74568919, "author": "Bernd Wilke πφ", "author_id": 6796354, "author_profile": "https://Stackoverflow.com/users/6796354", "pm_score": 1, "selected": false, "text": "attention" }, { "answer_id": 74575750, "author": "Gero Langheim", "author_id": 20593382, "author_profile": "https://Stackoverflow.com/users/20593382", "pm_score": 0, "selected": false, "text": " $offer->setOfferTitle(new \\TYPO3\\CMS\\Extbase\\Persistence\\ObjectStorage);\n foreach ($_POST['tx_bla_jobs']['offer']['offerTitle'] as $titleUid) {\n $offer->addOfferTitle($this->offertitleRepository->findByUid($titleUid));\n }\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19269749/" ]
74,565,245
<p>i get the error Unhandled Exception: &quot;dynamic&quot; not found. You need to call &quot;Get.put(dynamic())&quot; or &quot;Get.lazyPut(()=&gt;dynamic())&quot; when i call the authController, below is my code.</p> <pre><code>if (Get.find&lt;AuthController&gt;().isLoggedIn()) { //statements } </code></pre> <p>my init function</p> <pre><code>Future init() async { // Core final sharedPreferences = await SharedPreferences.getInstance(); Get.lazyPut(() =&gt; sharedPreferences); Get.lazyPut(() =&gt; ApiClient( appBaseUrl: AppConstants.BASE_URL, )); // Repository Get.lazyPut(() =&gt; AuthRepo(apiClient:Get.find(), sharedPreferences: Get.find())); // controller Get.lazyPut(() =&gt; AuthController(authRepo: Get.find())); </code></pre> <p>}</p> <p>main method</p> <pre><code> void main() async{ await di.init(); runApp( child: MyApp(), ), ); } </code></pre>
[ { "answer_id": 74565644, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 2, "selected": false, "text": "Getx Get.find() sharedPreferences AuthController Get.find();\nGet.find();\n Getx Type Getx Type dynamic Get.find(); // Getx: how I would know what should I return?\nGet.find(); // Getx: how I would know what should I return?\n Type Get.find<AuthController>(); // return AuthController dependency \nGet.find<SharedPreferences>(); // return SharedPreferences dependency\n Type Get.find() Type Get.put() Get.lazyPut() Type" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7987255/" ]
74,565,298
<p>I have a list of values and want to create a new dictionary from an existing dictionary using the key/value pairs that correspond to the values in the list. I can't find a Stackoverflow answer that covers this.</p> <pre><code>example_list = [1, 2, 3, 4, 5] original_dict = {&quot;a&quot;: 1, &quot;b&quot;: 2, &quot;c&quot;: 9, &quot;d&quot;: 2, &quot;e&quot;: 6, &quot;f&quot;: 1} desired_dict = {&quot;a&quot;: 1, &quot;b&quot;: 2, &quot;d&quot;: 2, &quot;f&quot;: 1} </code></pre> <p>Note that there are some values that are assigned to multiple keys in <code>original_dict</code> (as in the example).</p> <p>Any help would be appreciated.</p> <p>Thanks</p>
[ { "answer_id": 74565321, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 3, "selected": true, "text": "dict comprehension filter example_list = [1, 2, 3, 4, 5]\n\noriginal_dict = {\"a\": 1, \"b\": 2, \"c\": 9, \"d\": 2, \"e\": 6, \"f\": 1}\n\ndesired_dict = {key: value for key, value in original_dict.items() if value in example_list}\n\n# Option_2\ndesired_dict = dict(filter(lambda x: x[1] in example_list, original_dict.items()))\n# -------------------------------^^^ x[0] is key, x[1] is value of 'dict'\n\nprint(desired_dict)\n {'a': 1, 'b': 2, 'd': 2, 'f': 1}\n" }, { "answer_id": 74565464, "author": "OneMadGypsy", "author_id": 10292330, "author_profile": "https://Stackoverflow.com/users/10292330", "pm_score": 1, "selected": false, "text": "original_dict.items() filter filter dict el = [1, 2, 3, 4, 5]\n\nod = {\"a\": 1, \"b\": 2, \"c\": 9, \"d\": 2, \"e\": 6, \"f\": 1}\n\n# `i` will be (key,value)\ndd = dict(filter(lambda i: i[1] in el, od.items()))\n\nprint(dd) #{\"a\": 1, \"b\": 2, \"d\": 2, \"f\": 1}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16027663/" ]
74,565,303
<p>I have an exported csv file that contains extracted climate data from netCDF file, however the Date column has exported as below list, I would like to change this column to normal datetime. Is there any solution please! Thanks!</p> <pre><code>(cftime.Datetime360Day(2006, 1, 1, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 2, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 3, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 4, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 5, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 6, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 7, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 8, 12, 0, 0, 0, has_year_zero=True),) </code></pre> <p>I would like to change this column to normal datetime. Is there any solution please! Thanks!</p>
[ { "answer_id": 74565321, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 3, "selected": true, "text": "dict comprehension filter example_list = [1, 2, 3, 4, 5]\n\noriginal_dict = {\"a\": 1, \"b\": 2, \"c\": 9, \"d\": 2, \"e\": 6, \"f\": 1}\n\ndesired_dict = {key: value for key, value in original_dict.items() if value in example_list}\n\n# Option_2\ndesired_dict = dict(filter(lambda x: x[1] in example_list, original_dict.items()))\n# -------------------------------^^^ x[0] is key, x[1] is value of 'dict'\n\nprint(desired_dict)\n {'a': 1, 'b': 2, 'd': 2, 'f': 1}\n" }, { "answer_id": 74565464, "author": "OneMadGypsy", "author_id": 10292330, "author_profile": "https://Stackoverflow.com/users/10292330", "pm_score": 1, "selected": false, "text": "original_dict.items() filter filter dict el = [1, 2, 3, 4, 5]\n\nod = {\"a\": 1, \"b\": 2, \"c\": 9, \"d\": 2, \"e\": 6, \"f\": 1}\n\n# `i` will be (key,value)\ndd = dict(filter(lambda i: i[1] in el, od.items()))\n\nprint(dd) #{\"a\": 1, \"b\": 2, \"d\": 2, \"f\": 1}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20593581/" ]
74,565,320
<p>I just joined a new company and I'm trying to learn Airflow as I used it. So far I've got the basics of most things down except External Task Sensors. I have two DAGs, DAG A that has a schedule interval of <code>&quot;0 6 * * *&quot;</code> and DAG B with schedule interval of <code>&quot;0 7 * * *&quot;</code> DAG A waits for DAG B to Complete before it Continues. However DAG B sometimes takes 3 hours to Complete and at other times 10+ hours.</p> <p>I created an ExternalTask Sensor as show Below but it never triggers and timesout even when DAG B is complete.</p> <pre><code>ExternalTaskSensor( task_id = &quot;wait_sensor&quot;, external_dag_id=&quot;dag_b&quot;, external_task_id = &quot;end&quot;, poke_interval = 60*30, timeout=60*60, retries = 10, execution_delta= timedelta(hours=2), dag=dag ) </code></pre> <p>Any help on properly setting up the sensor is greatly appreciated. Also, Happy Thanksgiving!</p>
[ { "answer_id": 74597849, "author": "Jabbar", "author_id": 16930239, "author_profile": "https://Stackoverflow.com/users/16930239", "pm_score": 0, "selected": false, "text": "timeout reschedule poke ExternalTaskSensor(\n task_id = \"wait_sensor\",\n external_dag_id=\"dag_b\",\n external_task_id = \"end\",\n mode=\"reschedule\",\n timeout=60*60*23,\n retries = 10,\n execution_delta= timedelta(hours=2),\n dag=dag \n)\n" }, { "answer_id": 74634914, "author": "regex", "author_id": 9470979, "author_profile": "https://Stackoverflow.com/users/9470979", "pm_score": 0, "selected": false, "text": "external_dag_id external_task_id external_dag_id external_task_id poke_interval timeout execution_delta retries from airflow.sensors.external_task_sensor import ExternalTaskSensor\nfrom datetime import timedelta\n\nwait_sensor = ExternalTaskSensor(\n task_id = \"wait_sensor\",\n external_dag_id=\"dag_b\",\n external_task_id = \"end\",\n poke_interval = 60*30, # Check for task completion every 30 minutes\n timeout=60*60, # Timeout after 1 hour\n retries = 10, # Retry up to 10 times\n execution_delta= timedelta(hours=2), # Task must complete within 2 hours\n dag=dag \n)\n\n timeout execution_delta" }, { "answer_id": 74644573, "author": "Michal Volešíni", "author_id": 20646982, "author_profile": "https://Stackoverflow.com/users/20646982", "pm_score": 0, "selected": false, "text": "get_context def wait_for_another_task(dag_name, task_name, table_name):\n task = ExternalTaskSensor(\n task_id=f\"{table_name}{WAITING_TASK_TEXT_SEPARATOR}{dag_name}.{task_name}\",\n external_dag_id=dag_name,\n external_task_id=task_name,\n timeout=60 * 60, # timeout is in sec, so *60 and we have timeout in minutes\n allowed_states=['success'],\n failed_states=['failed', 'skipped'],\n execution_date_fn = get_context,\n mode = 'reschedule'\n )\n return task\n WAITING_TASK_TEXT_SEPARATOR = '_wait_for_' get_context def get_context(dt, **kwargs):\n task_instance_str = str(kwargs[\"task_instance\"])\n # look for \"_wait_for_\" string as it is separator for external_dag\n starting_loc_of_wait_for = task_instance_str.find(WAITING_TASK_TEXT_SEPARATOR)\n len_of_wait_for = len(WAITING_TASK_TEXT_SEPARATOR)\n ending_loc_of_wait_for = starting_loc_of_wait_for + len_of_wait_for\n\n beggiging_of_dag_task = task_instance_str[ending_loc_of_wait_for:]\n ending_of_dag_task_loc = beggiging_of_dag_task.find(\" \")\n dag_task = beggiging_of_dag_task[:ending_of_dag_task_loc]\n dag_task_lst = dag_task.split('.')\n dag_name = dag_task_lst[0]\n task_name = dag_task_lst[1]\n\n dag_runs = DagRun.find(dag_id=dag_name)\n dag_runs.sort(key=lambda x: x.execution_date, reverse=True)\n if dag_runs:\n last_exec_date = dag_runs[0].execution_date\n return last_exec_date\n else:\n return dt\n timeout ExternalTaskSensor" }, { "answer_id": 74653175, "author": "Chen Meyouhas", "author_id": 9167958, "author_profile": "https://Stackoverflow.com/users/9167958", "pm_score": 3, "selected": true, "text": "check_existence=True [2022-12-02, 08:21:36 UTC] {external_task.py:206} INFO - Poking for tasks ['test_task'] in dag test_dag on 2022-12-02T08:25:00+00:00 ... execution_delta=timedelta(hours=-1)" }, { "answer_id": 74661073, "author": "hakkikonu", "author_id": 1848929, "author_profile": "https://Stackoverflow.com/users/1848929", "pm_score": 0, "selected": false, "text": "ExternalTaskSensor from airflow.sensors.external_task_sensor import ExternalTaskSensor\nfrom datetime import timedelta\n\n# Set up the ExternalTaskSensor in DAG A\nexternal_task_sensor = ExternalTaskSensor(\n task_id = \"wait_sensor\",\n external_dag_id=\"dag_b\",\n external_task_id = \"end\",\n poke_interval = 60*30,\n timeout=60*60,\n retries = 10,\n execution_delta= timedelta(hours=1), # Set the execution_delta to account for the 1-hour difference in the execution times of the two DAGs\n dag=dag \n)\n" }, { "answer_id": 74663200, "author": "Benjamin Woolston", "author_id": 20188398, "author_profile": "https://Stackoverflow.com/users/20188398", "pm_score": -1, "selected": false, "text": "ExternalTaskSensor(\n task_id=\"wait_sensor\",\n external_dag_id=\"dag_b\",\n external_task_id=\"end\",\n poke_interval=60 * 10, # Check for the completion of the external task every 10 minutes\n timeout=60 * 60,\n retries=10,\n execution_delta=timedelta(hours=10), # Allow up to 10 hours for the external task to complete\n dag=dag\n)\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2250263/" ]
74,565,364
<p>I have a dataframe like this:</p> <pre><code>INDEX_COL col1 A Random Text B Some more random text C more stuff A Blah B Blah, Blah C Yet more stuff A erm B yup C whatever </code></pre> <p>What I need is it reformed into new columns and stacked/grouped by values in col_1. So something like this:</p> <pre><code>A B C Random Text Some more random text more stuff Blah Blah, Blah Yet more stuff erm yup whatever </code></pre> <p>I've reviewed <a href="https://stackoverflow.com/questions/47152691/how-can-i-pivot-a-dataframe">How can I pivot a dataframe?</a> but all of the examples work with numerical data and this is a use case that involves textual data, so aggregation appears to be not an option (but it was - see accepted answer below)</p> <p>I've tried the following:</p> <p>Pivot - but all the examples I've seen involve numerical values with aggregate functions. This is reshaping non-numerical data</p> <p>I get that index=INDEX COL, and columns= 'col1', but values? add a numerical column, pivot and then drop the numberical columns created? Feels like trying for forced pivot to do something it was never meant to do.</p> <p>Unstack - but this seems to convert the df into a new df with a single value index of 'b'</p> <p><code>unstack(level=0)</code></p> <p>I've even considered slicing the data frame by index into separate dataframes and the concatinating them, but the mismatched indexes result in NaN appearing like a checkerboard. Also this feels like an fugly solution.</p> <p>I've tried dropping the index_col, with Col1=['A,B,C'] and col2= the random text, but the new integer index comes along and spoils the fun.</p> <p>Any suggestions or thoughts in which direction I should go with this?</p>
[ { "answer_id": 74565448, "author": "Nuri Taş", "author_id": 19255749, "author_profile": "https://Stackoverflow.com/users/19255749", "pm_score": 3, "selected": true, "text": "agg(list) explode output = df.groupby('INDEX_COL').agg(list).T.apply(pd.Series.explode)\n INDEX_COL A B C\ncol1 Random Text Some more random text more stuff\ncol1 Blah Blah, Blah Yet more stuff\ncol1 erm yup whatever\n" }, { "answer_id": 74565655, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 0, "selected": false, "text": "pandas.pivot_table (df.pivot_table(columns='INDEX_COL', values='col1', aggfunc=list)\n .pipe(lambda d: d.explode(d.columns.tolist()))\n .reset_index(drop=True))\n INDEX_COL A B C\n0 Random Text Some more random text more stuff\n1 Blah Blah, Blah Yet more stuff\n2 erm yup whatever\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8818760/" ]
74,565,368
<p>I've been on this for a while now, trying to find something similar. And I bet there is - I just can't seem to find it.</p> <p>Basically what I am trying to do is getting the name of a term located in a custom taxonomy by ID.</p> <p>The taxonomy is called <code>pwb-brand</code></p> <p>The term ID is generated from an Advanced Custom Field <code>the_sub_field('varumarke')</code></p> <p>All I get in return is the ID of the term but I don't get the name as wished for.</p> <pre><code>&lt;?php $brands = get_term_by('id', the_sub_field('varumarke'), 'pwb-brand'); ?&gt; &lt;?php foreach( $brands as $brand ): echo '&lt;h2&gt;' . $brand-&gt;name . '&lt;/h2&gt;'; endforeach; ?&gt; </code></pre>
[ { "answer_id": 74566031, "author": "Web Assembler", "author_id": 15500541, "author_profile": "https://Stackoverflow.com/users/15500541", "pm_score": 0, "selected": false, "text": "get_term_by $brands = get_terms( array(\n 'taxonomy' => 'pwb-brand',\n));\n the_sub_field echo '<pre>';\nvar_dump( $brands );\necho '</pre>';\ndie();\n" }, { "answer_id": 74569636, "author": "CBroe", "author_id": 1427878, "author_profile": "https://Stackoverflow.com/users/1427878", "pm_score": 2, "selected": true, "text": "the_something get_something get_term_by('id', the_sub_field('varumarke'), 'pwb-brand');\n the_sub_field get_sub_field" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4026698/" ]
74,565,378
<p>I am trying to understand the order of events in the code. I hypothesized that after a click event, when Promise 2 (//2) is awaited, the for loop would proceed, after Promise 1 is awaited, and break because <code>stop</code> had been set to true prior to Promise 2 being awaited. However, it isn't predictable. What is the correct way to think about how these events are ordered in the event loop?</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 zeros = new Array(10000).fill(0); (async () =&gt; { let stop = false; document.addEventListener('click', async ()=&gt;{ console.log('click'); stop = true; await new Promise((r)=&gt;setTimeout(r)); //2 stop = false; }); for (let zero of zeros) { await new Promise((r)=&gt;setTimeout(r)); //1 if (stop) { break; } console.log(zero); } })();</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>click here</code></pre> </div> </div> </p>
[ { "answer_id": 74566031, "author": "Web Assembler", "author_id": 15500541, "author_profile": "https://Stackoverflow.com/users/15500541", "pm_score": 0, "selected": false, "text": "get_term_by $brands = get_terms( array(\n 'taxonomy' => 'pwb-brand',\n));\n the_sub_field echo '<pre>';\nvar_dump( $brands );\necho '</pre>';\ndie();\n" }, { "answer_id": 74569636, "author": "CBroe", "author_id": 1427878, "author_profile": "https://Stackoverflow.com/users/1427878", "pm_score": 2, "selected": true, "text": "the_something get_something get_term_by('id', the_sub_field('varumarke'), 'pwb-brand');\n the_sub_field get_sub_field" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12465038/" ]
74,565,412
<p>In my nav bar I want my logo text to be centered vertically with the logo. Here's <a href="https://i.stack.imgur.com/YI6N9.png" rel="nofollow noreferrer">what it looks like right now</a>.</p> <p>HTML:</p> <pre><code>&lt;header&gt; &lt;ul class = &quot;logo&quot;&gt; &lt;img class = &quot;logo-image&quot; src = &quot;images/logo.png&quot; alt = &quot;logo&quot;&gt; &lt;a href=&quot;../index.html&quot;&gt;Ultimate Tennis Team&lt;/a&gt; &lt;/ul&gt; &lt;nav&gt; &lt;ul class = &quot;nav-links&quot;&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Leaderboard&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Scoring&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Sign in&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; </code></pre> <p>CSS:</p> <pre><code> .logo { margin-right: auto; list-style: none; display: inline-block; } .logo li { padding: 0px 20px; } .logo-image { cursor: pointer; height: 50px; } </code></pre> <p>I'm new to web development. I've tried a variety of things like spans and table but I couldn't figure out this issue.</p>
[ { "answer_id": 74565502, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 1, "selected": false, "text": "flex align-items: center .logo Flex .logo {\n margin-right: auto;\n list-style: none;\n /* Add these */\n display: flex;\n align-items: center;\n /* (Optional) set a gap between the two */\n gap: 1em;\n}\n\n" }, { "answer_id": 74565510, "author": "Professor Abronsius", "author_id": 3603681, "author_profile": "https://Stackoverflow.com/users/3603681", "pm_score": 2, "selected": true, "text": ".logo align-items .logo {\n margin-right: auto;\n list-style: none;\n /* position things within flex container */\n display: inline-flex;\n flex-direction:row;\n align-items:center;\n}\n\n.logo li {\n padding: 0px 20px;\n}\n\n.logo-image {\n cursor: pointer;\n height: 50px;\n border:1px solid red\n}\n.logo a{\n margin:0 0 0 2rem;\n} <header>\n <ul class=\"logo\">\n <img class=\"logo-image\" src=\"//img.freepik.com/free-vector/branding-identity-corporate-vector-logo-design_460848-8717.jpg?w=300\" alt=\"logo\">\n <a href=\"../index.html\">Ultimate Tennis Team</a>\n </ul>\n <nav>\n <ul class=\"nav-links\">\n <li><a href=\"#\">Leaderboard</a></li>\n <li><a href=\"#\">Scoring</a></li>\n <li><a href=\"#\">Sign in</a></li>\n </ul>\n </nav>\n</header>" }, { "answer_id": 74565543, "author": "Nils Kähler", "author_id": 1112631, "author_profile": "https://Stackoverflow.com/users/1112631", "pm_score": 0, "selected": false, "text": " display: flex;\n align-items: center;\n .logo {\n display: flex;\n align-items: center;\n}\n\n.logo li {\n padding: 0px 20px;\n}\n\n.logo-image {\n cursor: pointer;\n height: 50px;\n}\n\nheader {\n display: flex;\n align-items: center;\n}\n\n.nav-links {\n display: flex;\n list-style: none;\n}\n\n.nav-links li {\n padding: 0px 5px;\n} <header>\n <ul class=\"logo\">\n <img class=\"logo-image\" src=\"https://png.pngtree.com/png-clipart/20190524/ourmid/pngtree-tennis-ball-clipart-png-png-image_1079029.jpg\" alt=\"logo\">\n <a href=\"../index.html\">Ultimate Tennis Team</a>\n </ul>\n <nav>\n <ul class=\"nav-links\">\n <li><a href=\"#\">Leaderboard</a></li>\n <li><a href=\"#\">Scoring</a></li>\n <li><a href=\"#\">Sign in</a></li>\n </ul>\n </nav>\n</header>" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16529833/" ]
74,565,429
<p>I want to connect to the <code>twelevedata</code> server through its provided socket connection to receive information.</p> <pre class="lang-js prettyprint-override"><code> import * as dotenv from 'dotenv' import WebSocket from 'ws'; import express from 'express' const app = express(); //setting up env dotenv.config() // setting up the websocket const ws = new WebSocket(`wss://ws.twelvedata.com/v1/quotes/price?apikey=${process.env.API_KEY_TWELVEDATA}`); const payload = { &quot;action&quot;: &quot;subscribe&quot;, &quot;params&quot;: { &quot;symbols&quot;: &quot;AAPL,INFY,TRP,QQQ,IXIC,EUR/USD,USD/JPY,BTC/USD,ETH/BTC&quot; }, } ws.on('connection',function (steam) { ws.on('open', (data) =&gt; { console.log(&quot;data ==&gt;&quot;,data); ws.emit('subscribe',payload) }) ws.on('subscribe', (data) =&gt; { console.log(&quot;data ==&gt;&quot;,data); }) }) const port = process.env.PORT || 5000; app.listen(port, () =&gt; { console.log(`I am listening at ${port}`); }); </code></pre> <p>I created a websocket with my websocket connection on an express application but I am unable to receive any information from the twelvedata server regarding the <code>subscribe</code> event that I have emitted !</p> <p>This is how the websocket should work as shown by the <code>twelvedata</code> website (look into the screen shots)</p> <p><a href="https://i.stack.imgur.com/4Vivl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4Vivl.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/sW7x6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sW7x6.png" alt="enter image description here" /></a></p> <p>I am unable to connect and emit the <code>subscribe</code> event given by the <a href="https://twelvedata.com/docs#websocket" rel="nofollow noreferrer">twelvedata's documentation</a></p>
[ { "answer_id": 74565722, "author": "Christian Fritz", "author_id": 1087119, "author_profile": "https://Stackoverflow.com/users/1087119", "pm_score": 1, "selected": false, "text": "emit send ws.emit('subscribe',payload)\n ws.send(payload)\n" }, { "answer_id": 74577712, "author": "Abdullah Ch", "author_id": 13708712, "author_profile": "https://Stackoverflow.com/users/13708712", "pm_score": 1, "selected": true, "text": "\n// sending the parameters\n ws.on('open', function open() {\n ws.send(JSON.stringify(payload));\n });\n \n ws.on('message', function message(data) {\n // receiving data\n console.log('data ===>: ', JSON.parse(data));\n });\n ws.send" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13708712/" ]
74,565,432
<p>I am new at using the angular form, and I was told to use reactive forms and I am following the angular material tutorial, but when I tried to use the input that has the form control it says that is not part of the input, and I believe that I already have all the imports, here is the error my code.</p> <p><code> Can't bind to 'formControl' since it isn't a known property of 'input'.</code></p> <p>Html:</p> <pre><code>&lt;label for=&quot;naame&quot;&gt;Name: &lt;/label&gt; &lt;input id=&quot;name&quot; type=&quot;text&quot; [formControl]=&quot;name&quot;&gt; </code></pre> <p>Ts of the form component</p> <pre><code>import { Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.scss'] }) export class FormComponent implements OnInit { name = new FormControl(''); constructor() { } ngOnInit(): void { } } </code></pre> <p>and also I have a module called material, where I have imported all the angular material stuff</p> <pre><code>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; // Material Form Controls import { MatAutocompleteModule } from '@angular/material/autocomplete'; import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatDatepickerModule } from '@angular/material/datepicker'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatRadioModule } from '@angular/material/radio'; import { MatSelectModule } from '@angular/material/select'; import { MatSliderModule } from '@angular/material/slider'; import { MatSlideToggleModule } from '@angular/material/slide-toggle'; // Material Navigation import { MatMenuModule } from '@angular/material/menu'; import { MatSidenavModule } from '@angular/material/sidenav'; import { MatToolbarModule } from '@angular/material/toolbar'; // Material Layout import { MatCardModule } from '@angular/material/card'; import { MatDividerModule } from '@angular/material/divider'; import { MatExpansionModule } from '@angular/material/expansion'; import { MatGridListModule } from '@angular/material/grid-list'; import { MatListModule } from '@angular/material/list'; import { MatStepperModule } from '@angular/material/stepper'; import { MatTabsModule } from '@angular/material/tabs'; import { MatTreeModule } from '@angular/material/tree'; // Material Buttons &amp; Indicators import { MatButtonModule } from '@angular/material/button'; import { MatButtonToggleModule } from '@angular/material/button-toggle'; import { MatBadgeModule } from '@angular/material/badge'; import { MatChipsModule } from '@angular/material/chips'; import { MatIconModule } from '@angular/material/icon'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { MatRippleModule } from '@angular/material/core'; // Material Popups &amp; Modals import { MatBottomSheetModule } from '@angular/material/bottom-sheet'; import { MatDialogModule } from '@angular/material/dialog'; import { MatSnackBarModule } from '@angular/material/snack-bar'; import { MatTooltipModule } from '@angular/material/tooltip'; // Material Data tables import { MatPaginatorModule } from '@angular/material/paginator'; import { MatSortModule } from '@angular/material/sort'; import { MatTableModule } from '@angular/material/table'; // import { ReactiveFormsModule } from '@angular/forms'; // import { FormsModule } from '@angular/forms'; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatNativeDateModule } from '@angular/material/core'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; @NgModule({ declarations: [], imports: [ CommonModule, BrowserModule, BrowserAnimationsModule, MatNativeDateModule, MatAutocompleteModule, MatCheckboxModule, MatDatepickerModule, MatFormFieldModule, MatInputModule, MatRadioModule, MatSelectModule, MatSliderModule, MatSlideToggleModule, MatMenuModule, MatSidenavModule, MatToolbarModule, MatCardModule, MatDividerModule, MatExpansionModule, MatGridListModule, MatListModule, MatStepperModule, MatTabsModule, MatTreeModule, MatButtonModule, MatButtonToggleModule, MatBadgeModule, MatChipsModule, MatIconModule, MatProgressSpinnerModule, MatProgressBarModule, MatRippleModule, MatBottomSheetModule, MatDialogModule, MatSnackBarModule, MatTooltipModule, MatPaginatorModule, MatSortModule, MatTableModule, BrowserModule, FormsModule, ReactiveFormsModule, MaterialModule, ], exports: [ MatAutocompleteModule, MatCheckboxModule, MatDatepickerModule, MatFormFieldModule, MatInputModule, MatRadioModule, MatSelectModule, MatSliderModule, MatSlideToggleModule, MatMenuModule, MatSidenavModule, MatToolbarModule, MatCardModule, MatDividerModule, MatExpansionModule, MatGridListModule, MatListModule, MatStepperModule, MatTabsModule, MatTreeModule, MatButtonModule, MatButtonToggleModule, MatBadgeModule, MatChipsModule, MatIconModule, MatProgressSpinnerModule, MatProgressBarModule, MatRippleModule, MatBottomSheetModule, MatDialogModule, MatSnackBarModule, MatTooltipModule, MatPaginatorModule, MatSortModule, MatTableModule, BrowserModule, FormsModule, ReactiveFormsModule, MaterialModule, ] }) export class MaterialModule { } </code></pre>
[ { "answer_id": 74565498, "author": "Andrés Blanco", "author_id": 14017883, "author_profile": "https://Stackoverflow.com/users/14017883", "pm_score": -1, "selected": false, "text": "<label for=\"name\">Name: </label>\n<input id=\"name\" type=\"text\" matInput [formControl]=\"name\">\n" }, { "answer_id": 74565921, "author": "Fernando Lugo", "author_id": 12454272, "author_profile": "https://Stackoverflow.com/users/12454272", "pm_score": 1, "selected": true, "text": "`import {FormsModule, ReactiveFormsModule} from '@angular/forms';\n import {FormComponent} from './FormComponent';\n\n @NgModule({\n declarations: [FormComponent],\n imports: [\n BrowserModule,\n FormsModule,\n ReactiveFormsModule,\n MaterialModule,\n ],\n })\n export class AppModule {}`\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20531528/" ]
74,565,437
<p>When I was working on a Django project (blog), I had an error(s) while working on the site. Here are the errors I have appeared: 1: When I entered the python command manage.py makemigrations blog(via the console) in the directory C:\mysite\site\miniproject , then there is this:</p> <pre><code>Traceback (most recent call last): File &quot;manage.py&quot;, line 23, in &lt;module&gt; main() File &quot;manage.py&quot;, line 19, in main execute_from_command_line(sys.argv) File &quot;C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py&quot;, line 419, in execute_from_command_line utility.execute() File &quot;C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py&quot;, line 395, in execute django.setup() File &quot;C:\Program Files\Python36\lib\site-packages\django\__init__.py&quot;, line 24, in setup apps.populate(settings.INSTALLED_APPS) File &quot;C:\Program Files\Python36\lib\site-packages\django\apps\registry.py&quot;, line 114, in populate app_config.import_models() File &quot;C:\Program Files\Python36\lib\site-packages\django\apps\config.py&quot;, line 301, in import_models self.models_module = import_module(models_module_name) File &quot;C:\Program Files\Python36\lib\importlib\__init__.py&quot;, line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 978, in _gcd_import File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 961, in _find_and_load File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 950, in _find_and_load_unlocked File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 655, in _load_unlocked File &quot;&lt;frozen importlib._bootstrap_external&gt;&quot;, line 678, in exec_module File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 205, in _call_with_frames_removed File &quot;C:\mysite\site\miniproject\blog\models.py&quot;, line 5, in &lt;module&gt; class Post(models.Model): File &quot;C:\mysite\site\miniproject\blog\models.py&quot;, line 12, in Post author = models.ForeignKey(User, related_name='blog_posts') TypeError: __init__() missing 1 required positional argument: 'on_delete' </code></pre> <p>Although I did everything according to the instructions on the website https://pocoz .gitbooks.io/django-v-primerah/content/sozdanie-i-primenenie-migracij.html. I did everything according to plan, I did everything in order and there was such a mistake. And I do not know how to fix it</p> <p>Updated all the necessary libraries, entered them in manage.ру (which is located in the directory C:\mysite\site\miniproject ) import django, it didn't help</p>
[ { "answer_id": 74565495, "author": "Swift", "author_id": 8874154, "author_profile": "https://Stackoverflow.com/users/8874154", "pm_score": 1, "selected": false, "text": "ForeignKey on_delete BlogPost models.ForeignKey(..., on_delete=models.CASCADE)\n BlogPost blog/models.py" }, { "answer_id": 74570744, "author": "haduki", "author_id": 18229792, "author_profile": "https://Stackoverflow.com/users/18229792", "pm_score": 0, "selected": false, "text": " File \"C:\\mysite\\site\\miniproject\\blog\\models.py\", line 12, in Post Post author = models.ForeignKey(User, related_name='blog_posts')\n author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19350769/" ]
74,565,450
<p>Hi I have problem i dont knbwo how to add numbers order 1 to 8 on the left side and right side of this function. And another problem is there is always showing none when I print it I dont know why I thouth it was beacouse my function was empty but that din't help . So what can I do with this thank you very much.</p>
[ { "answer_id": 74565495, "author": "Swift", "author_id": 8874154, "author_profile": "https://Stackoverflow.com/users/8874154", "pm_score": 1, "selected": false, "text": "ForeignKey on_delete BlogPost models.ForeignKey(..., on_delete=models.CASCADE)\n BlogPost blog/models.py" }, { "answer_id": 74570744, "author": "haduki", "author_id": 18229792, "author_profile": "https://Stackoverflow.com/users/18229792", "pm_score": 0, "selected": false, "text": " File \"C:\\mysite\\site\\miniproject\\blog\\models.py\", line 12, in Post Post author = models.ForeignKey(User, related_name='blog_posts')\n author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20583119/" ]
74,565,468
<p>I am trying to install an exe created using Inno Setup. When I try to install it using PowerShell with</p> <pre class="lang-none prettyprint-override"><code>Start-Process -wait C:\updatefile.exe /VERYSILENT </code></pre> <p>all folders are created at proper places, registry values are created, but console hangs and does not return unless <kbd>Ctrl+C</kbd> is pressed.</p> <p>But if I install exe using command prompt with</p> <pre><code>start /wait C:\updatefile.exe /VERYSILENT </code></pre> <p>everything goes properly and command prompt returns.</p> <p>What could be cause of this anomaly?</p> <p>I need this exe to install through Dockerfile, but as PowerShell install is hanging, container does not install exe. Even with <code>cmd</code> version in Dockerfile, container does not create install folders.</p> <hr /> <p>After checking logs I found that exe service is being started by installer in end. If that is reason for hanging, is there some argument I can use to exit PowerShell?</p>
[ { "answer_id": 74565710, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 4, "selected": true, "text": "-Wait Start-Process cmd.exe start Start-Process cmd /c C:\\updatefile.exe /VERYSILENT\n cmd /c cmd.exe start /wait -PassThru Start-Process -Wait Wait-Process Start-Process -PassThru C:\\updatefile.exe /VERYSILENT | Wait-Process\n Wait-Process Start-Process -Wait" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1126021/" ]
74,565,479
<p>I have a fairly simple terraform setup setting up:</p> <ul> <li>An AWS VPC</li> <li>Its default route table, with an endpoint to S3</li> <li>A couple of security groups</li> <li>Some EC2 instances</li> <li>An internal Route53 DNS zone</li> </ul> <p>Now, if I execute <code>terraform plan</code> immediately after <code>terraform apply</code> from scratch, a bunch of spurious changes are detected. These fall into two categories:</p> <ul> <li>Empty attributes (tags and <code>aws_default_route_table.propagating_vgws</code>), even though they are set explicitly empty in the code</li> <li>Two Route53 records that are marked as changed, but show no changes to be applied</li> <li>ingress and egress rules in security groups</li> </ul> <p>The first two groups are annoying, but no big deal even if they'd be nice to get rid of.</p> <p>The last one I'd rather like to get rid of. I think it's related to the fact that I have the rules as separate <code>aws_security_group_rule</code> resources rather than inline in the security group resources (because some of them refer to each other mutually). I had a couple of inline rules, but rereading the docs I think that's not allowed, but even removing them doesn't remove this issue.</p> <p>(Running <code>terraform apply -refresh-only</code> makes everything good, but it's really annoying that an apply from a blank slate needs this kind of fixup)</p>
[ { "answer_id": 74565710, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 4, "selected": true, "text": "-Wait Start-Process cmd.exe start Start-Process cmd /c C:\\updatefile.exe /VERYSILENT\n cmd /c cmd.exe start /wait -PassThru Start-Process -Wait Wait-Process Start-Process -PassThru C:\\updatefile.exe /VERYSILENT | Wait-Process\n Wait-Process Start-Process -Wait" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62143/" ]
74,565,490
<p>I am wondering how it is possible to combine the following functions into one. The functions remove the entire word if &quot;_&quot; respectively &quot;/&quot; occur in a text.</p> <p>I have tried the following, and the code fulfils it purpose. It his however cumbersome and I am wondering how to simplify it.</p> <pre><code>text = &quot;This is _a default/ text&quot; def filter_string1(string): a = [] for i in string.split(): if &quot;_&quot; not in i: a.append(i) return ' '.join(a) def filter_string2(string): a = [] for i in string.split(): if &quot;/&quot; not in i: a.append(i) return ' '.join(a) text_no_underscore = filter_string1(text) text_no_underscore_no_slash = filter_string2(text_no_underscore) print(text_no_underscore_no_slash) </code></pre> <p>The output is (as desired):</p> <p>&quot;This is text&quot;</p>
[ { "answer_id": 74565710, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 4, "selected": true, "text": "-Wait Start-Process cmd.exe start Start-Process cmd /c C:\\updatefile.exe /VERYSILENT\n cmd /c cmd.exe start /wait -PassThru Start-Process -Wait Wait-Process Start-Process -PassThru C:\\updatefile.exe /VERYSILENT | Wait-Process\n Wait-Process Start-Process -Wait" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20556046/" ]
74,565,515
<p>I am new to DynamoDB and working on a dynamo project. I am trying to update the item amount in a transaction with condition <strong>if_not_exists()</strong> with <strong>TransactionWriteRequest</strong> in DynamoDB Mapper.</p> <p>As per the Doc, <strong>transactionWriteRequest.updateItem()</strong> takes <strong>DynamoDBTransactionWriteExpression</strong> which doesn't have any UpdateExpression. Class definition is attached bellow., <a href="https://i.stack.imgur.com/mSDOk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mSDOk.png" alt="" /></a></p> <p>Wanted to know How can i provide the <strong>if_not_exists()</strong> in <strong>DynamoDBTransactionWriteExpression</strong> to update the item in a transaction. Or there is no way to do this in a transactionWrite.</p> <p>Please help here.</p> <p>Thanks in advance</p>
[ { "answer_id": 74565710, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 4, "selected": true, "text": "-Wait Start-Process cmd.exe start Start-Process cmd /c C:\\updatefile.exe /VERYSILENT\n cmd /c cmd.exe start /wait -PassThru Start-Process -Wait Wait-Process Start-Process -PassThru C:\\updatefile.exe /VERYSILENT | Wait-Process\n Wait-Process Start-Process -Wait" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5124753/" ]
74,565,537
<p>I have a node express server running on Machine 1 as (0.0.0.0) and some client applications running on Machine 2, 3, and so on... All machines are connected to the same Wi-Fi</p> <p>How can I get the private IP of Machine 1 (which is running the express server), so that I can directly start calling the server APIs from client applications?</p> <p>Note : I am using electron js in both server and client</p>
[ { "answer_id": 74565710, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 4, "selected": true, "text": "-Wait Start-Process cmd.exe start Start-Process cmd /c C:\\updatefile.exe /VERYSILENT\n cmd /c cmd.exe start /wait -PassThru Start-Process -Wait Wait-Process Start-Process -PassThru C:\\updatefile.exe /VERYSILENT | Wait-Process\n Wait-Process Start-Process -Wait" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7771944/" ]
74,565,551
<p>I'm trying to make the code repeat the line &quot;player name invalid&quot; and ask for the input repetively until the input is &quot;player 1&quot;. How do i do that?</p> <pre><code>correct_n=&quot;player 1&quot; while True: Name1 = input (&quot;Enter Your Name: &quot;) if Name1 == correct_n: cp = 'password' while True: password= input(&quot;enter the password &quot;) if password == cp: print (&quot;yes you are in&quot;) break print(&quot;please try again&quot;) else: print(&quot;Player name not valid&quot;) break print(&quot;player name invalid&quot;) </code></pre> <p>The code just prints &quot;player name invalid&quot; and goes on to do the rest of the code. I don't want the rest of the code to be outputted until the user inputs the correct name and password.</p>
[ { "answer_id": 74565582, "author": "walker", "author_id": 19708567, "author_profile": "https://Stackoverflow.com/users/19708567", "pm_score": -1, "selected": false, "text": "while input('Enter your name: ') != 'player 1': print('Player name invalid')\n" }, { "answer_id": 74565611, "author": "Dash", "author_id": 11542834, "author_profile": "https://Stackoverflow.com/users/11542834", "pm_score": 0, "selected": false, "text": "while break correct_n=\"player 1\"\nwhile True:\n Name1 = input(\"Enter Your Name: \")\n if Name1 == correct_n:\n break\n else:\n print(\"Player name not valid\")\n\ncp = 'password'\nwhile True:\n password= input(\"enter the password \")\n if password == cp:\n print (\"yes you are in\")\n break\n else:\n print(\"please try again\")\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20593781/" ]
74,565,594
<p>I am using cypress to test that a textfield displays the entered text correctly.</p> <pre><code>cy.get('.creation-name').should('not.have.text'); const testName = 'Test name'; cy.get('.creation-name').type(`${testName}`); </code></pre> <p>TextField is a MUI component and this is a React project.</p> <pre><code>&lt;div className=&quot;create-name&quot;&gt; &lt;TextField id=&quot;Name&quot; label=&quot;Create name&quot; onChange={(event) =&gt; setName(event.target.value)} /&gt; &lt;/div&gt; </code></pre> <p>I can see from the video that the text types in fine, but when I try to check that it's there it fails. I have tried multiple different lines to get the test text value, including these:</p> <pre><code>//got AssertionError for all of these cy.get('.creation-name').invoke('val').should('equal', 'Test name');//expected '' to equal Test name cy.contains(`${testName}`).should('have.text', `${testName}`);//expected '' to equal Test name cy.get('[id=&quot;Name&quot;]').should('have.text', `${testName}`);//expected '' to equal Test name cy.get('.creation-name').invoke('text').should('equal', 'Test');//expected Create name to equal Test name cy.get('.creation-name').should('have.text', `${testName}`);//expected Create name to equal Test name </code></pre> <p>Seems I am not getting anything or I am targeting the label. This is my first time using cypress so I hope I didn't miss anything obvious.</p>
[ { "answer_id": 74565679, "author": "Fody", "author_id": 16997707, "author_profile": "https://Stackoverflow.com/users/16997707", "pm_score": 3, "selected": true, "text": "<input> cy.get('.creation-name') // or .create-name, maybe a typo in the question\n .find('input')\n .invoke('val')\n .should('equal', 'Test name')\n contains() <div>Test text</div>" }, { "answer_id": 74565699, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 0, "selected": false, "text": "cy.get('input[id=\"Name\"]').invoke('val').then(value => assert.equal(value, testName));\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12474420/" ]
74,565,596
<p>Clean Architecture recommends to implement &quot;enterprise wide rules&quot; in the entity / domain level.</p> <p>I'm struggling to understand how to deal with the following scenario: Take a warehouse where you need to make sure that safety rules are followed. For example, acid must not be stored above alkaline (lye) and vice versa. Or fresh meet must not be stored in an area without properly functioning air condition.</p> <p>Because these are safety or hygiene rules which apply worldwide, the domain level seems the appropriate place to implement them. That could be a class called &quot;WarehouseBoxUnit&quot; with a method &quot;AddProduct&quot; that includes validation of environmental conditions.</p> <p>However, in a typical scenario, you have to access an external state to check if there are any acid products are stored above or below a certain storage box where you want to put alkaline. Or you have even to access sensor data to check if the air conditioning is working. In any case, this state is dynamic and external. Accessing external data should be part of the infrastructure.</p> <p>The conflict is that in Clear Architecture, the domain model should not have a reference to the infrastructure project. And that might be a circular reference anyway.</p> <p>I could move the validation to the application layer where I would have interfaces to infrastructure classes. However, this would be risky as someone could forget to do all necessary validation when adding new features / use cases.</p> <p>Is there an established way to deal with this?</p>
[ { "answer_id": 74565679, "author": "Fody", "author_id": 16997707, "author_profile": "https://Stackoverflow.com/users/16997707", "pm_score": 3, "selected": true, "text": "<input> cy.get('.creation-name') // or .create-name, maybe a typo in the question\n .find('input')\n .invoke('val')\n .should('equal', 'Test name')\n contains() <div>Test text</div>" }, { "answer_id": 74565699, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 0, "selected": false, "text": "cy.get('input[id=\"Name\"]').invoke('val').then(value => assert.equal(value, testName));\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10035674/" ]
74,565,625
<p>I'm kinda new to JS so I kinda got stuck with this what it seemed simple problem. I have to convert payload from:</p> <pre><code>const payload = {left: ['name', 'phone'], right: ['address']} </code></pre> <p>to:</p> <pre><code>const payload = columns: { name: { pinned: 'left', }, phone: { pinned: 'left', }, address: { pinned: 'right' } }, </code></pre> <p>So far i came up with something like this:</p> <pre><code></code></pre> <pre><code>const left = pinnedColumns.left.map((col) =&gt; ({ [col]: { pinned: 'left' } })); </code></pre> <pre><code></code></pre> <p>But it creates an array with index as a key.</p>
[ { "answer_id": 74565679, "author": "Fody", "author_id": 16997707, "author_profile": "https://Stackoverflow.com/users/16997707", "pm_score": 3, "selected": true, "text": "<input> cy.get('.creation-name') // or .create-name, maybe a typo in the question\n .find('input')\n .invoke('val')\n .should('equal', 'Test name')\n contains() <div>Test text</div>" }, { "answer_id": 74565699, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 0, "selected": false, "text": "cy.get('input[id=\"Name\"]').invoke('val').then(value => assert.equal(value, testName));\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17361030/" ]
74,565,663
<p>I have a library (dll). For some reason, when I compile, file .runtimeconfig.json is generated:</p> <pre><code>{ &quot;runtimeOptions&quot;: { &quot;tfm&quot;: &quot;net6.0&quot;, &quot;frameworks&quot;: [ { &quot;name&quot;: &quot;Microsoft.NETCore.App&quot;, &quot;version&quot;: &quot;6.0.0&quot; }, { &quot;name&quot;: &quot;Microsoft.WindowsDesktop.App&quot;, &quot;version&quot;: &quot;6.0.0&quot; } ], &quot;configProperties&quot;: { &quot;System.Reflection.Metadata.MetadataUpdater.IsSupported&quot;: false } } } </code></pre> <p>Why is this file generated and why does it contain &quot;System.Reflection.Metadata.MetadataUpdater.IsSupported&quot;: false? This is a non runable library, so why is a .runtimeconfig.json generated?</p>
[ { "answer_id": 74565679, "author": "Fody", "author_id": 16997707, "author_profile": "https://Stackoverflow.com/users/16997707", "pm_score": 3, "selected": true, "text": "<input> cy.get('.creation-name') // or .create-name, maybe a typo in the question\n .find('input')\n .invoke('val')\n .should('equal', 'Test name')\n contains() <div>Test text</div>" }, { "answer_id": 74565699, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 0, "selected": false, "text": "cy.get('input[id=\"Name\"]').invoke('val').then(value => assert.equal(value, testName));\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2671330/" ]
74,565,668
<p>I'm trying to make a program that accepts the number of students enrolled to an exam, and how many points each of them got. I try to loop the inputs but it gives seemingly random numbers in output</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main () { int studenti; scanf(&quot;%d&quot;, &amp;studenti); printf(&quot;%d &quot;, studenti); int niza[studenti]; for (int i = 1; i &lt;= studenti; i++){ scanf(&quot;%d&quot;, &amp;niza[i]); i++; printf(&quot;%d &quot;,niza[i]); } } </code></pre> <p>What am I doing wrong? Is there another way to add array elements without knowing how big the array will be beforehand because I don't know how big they are when I pass the checks on my uni website.</p>
[ { "answer_id": 74565781, "author": "Dash", "author_id": 11542834, "author_profile": "https://Stackoverflow.com/users/11542834", "pm_score": 0, "selected": false, "text": "malloc" }, { "answer_id": 74566046, "author": "user3121023", "author_id": 3121023, "author_profile": "https://Stackoverflow.com/users/3121023", "pm_score": 2, "selected": true, "text": "for 1 i <= studenti studenti - 1 for i i++; i scanf #include <stdio.h>\n#include <stdlib.h>\n\nint main ()\n{\n int studenti = 0; // initialize\n if ( 1 == scanf(\"%d\", &studenti)) { // successful scan\n printf(\"%d \", studenti);\n int niza[studenti]; // variable length array\n for (int i = 0; i < studenti; i++) { // start from index 0\n if ( 1 == scanf(\"%d\", &niza[i])) {\n printf(\"%d \",niza[i]);\n }\n else { // scanf returned 0 or EOF\n fprintf ( stderr, \"problem scanning array element\\n\");\n return 2;\n }\n }\n }\n else { // scanf returned 0 or EOF\n fprintf ( stderr, \"problem scanning\\n\");\n return 1;\n }\n printf(\"\\n\");\n return 0;\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17594677/" ]
74,565,689
<p>i have a problem with this python code for inverting a Number <strong>like Nb = 358 ---&gt; inv = 853</strong> but in the end <strong>i got 'inf' msg</strong> from the prog , and its runs normally in C language</p> <pre><code>def envers(Nb): inv = 0 cond = True while cond: s = Nb % 10 inv = (inv*10)+ s Nb = Nb/10 if Nb == 0: cond = False return inv data = int(input(&quot;give num&quot;)) res = envers(data) print(res) </code></pre>
[ { "answer_id": 74565717, "author": "ti7", "author_id": 4541045, "author_profile": "https://Stackoverflow.com/users/4541045", "pm_score": 2, "selected": false, "text": ">>> int(input(\"enter a number to reverse: \")[::-1])\nenter a number to reverse: 1234\n4321\n input() [::-1] int" }, { "answer_id": 74565788, "author": "yanjunk", "author_id": 15061414, "author_profile": "https://Stackoverflow.com/users/15061414", "pm_score": 1, "selected": false, "text": "Nb = Nb / 10 Nb = Nb // 10" }, { "answer_id": 74565850, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "def envers(Nb):\n out = 0\n while Nb>0:\n Nb, r = divmod(Nb, 10)\n out = 10*out + r\n return out\n\n\nenvers(1234)\n# 4321\n\nenvers(358)\n# 853\n\nenvers(1020)\n# 201\n divmod def envers(Nb):\n out = 0\n while Nb>0:\n r = Nb % 10\n Nb //= 10\n out = 10*out + r\n return out\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18900688/" ]
74,565,704
<p>I am learning SQL and using Oracle SQL Developer. I have a table that contains the following columns</p> <ol> <li>FlightDate</li> <li>DepartureTime</li> <li>ArrivalTime</li> </ol> <p>I have inserted values using either</p> <pre><code>TO_DATE('10:45', 'hh24:mi') </code></pre> <p>or</p> <pre><code>TO_DATE('20/10/2000', 'DD/MM/YYYY') </code></pre> <p>When I do a SELECT * FROM TABLE_NAME, the DepartureTime and ArrivalTime display a date (which I have not entered). How do I display the date in the first column and time in the other 2 columns?</p> <p>I have tried `</p> <pre><code>SELECT to_char(DepartureTime, 'HH24:MI' ) AS Departure to_char( ArrivalTime, 'HH24:MI' ) AS Arrival FROM FLIGHT; </code></pre> <p>` Although the above statement displays the right values, I want to write a statement to output all the columns (because the actual table has more than 3 columns), but in the format explained above - a date for FlightDate and time for DepartureTime and ArrivalTime.</p>
[ { "answer_id": 74565870, "author": "Littlefoot", "author_id": 9097906, "author_profile": "https://Stackoverflow.com/users/9097906", "pm_score": 1, "selected": false, "text": "DATE SQL> create table flight\n 2 (id number,\n 3 flight_date date,\n 4 departure_time date,\n 5 arrival_time date);\n\nTable created.\n\nSQL> insert into flight values (1, to_date('10:45', 'hh24:mi'), to_date('20/10/2000', 'dd/mm/yyyy'), sysdate);\n\n1 row created.\n SQL> select * From flight;\n\n ID FLIGHT_DA DEPARTURE ARRIVAL_T\n---------- --------- --------- ---------\n 1 01-NOV-22 20-OCT-00 24-NOV-22\n SQL> alter session set nls_date_Format = 'dd.mm.yyyy hh24:Mi';\n\nSession altered.\n SQL> select * From flight;\n\n ID FLIGHT_DATE DEPARTURE_TIME ARRIVAL_TIME\n---------- ---------------- ---------------- ----------------\n 1 01.11.2022 10:45 20.10.2000 00:00 24.11.2022 21:17\n\nSQL>\n" }, { "answer_id": 74566169, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 3, "selected": true, "text": "DATE DATE DATE INTERVAL DAY TO SECOND CREATE TABLE table_name (\n FlightDate DATE\n CONSTRAINT table_name__flightdate__chk CHECK (flightdate = TRUNC(flightdate)),\n DepartureTime INTERVAL DAY(0) TO SECOND(0) NOT NULL,\n ArrivalTime INTERVAL DAY(1) TO SECOND(0) NOT NULL\n);\n CREATE TABLE table_name (\n Departure DATE NOT NULL,\n Arrival DATE NOT NULL\n);\n" }, { "answer_id": 74574813, "author": "d r", "author_id": 19023353, "author_profile": "https://Stackoverflow.com/users/19023353", "pm_score": 0, "selected": false, "text": "WITH\n flights (FLIGHT_OPERATOR, FLIGHT_FROM, FLIGHT_TO, DEPARTURE, ARRIVAL, SOME_OTHER_COL) AS\n (\n Select 'Vueling', 'Barcelona', 'Paris', To_Date('01.11.2022 10:45', 'dd.mm.yyyy hh24:mi'), To_Date('01.11.2022 12:30', 'dd.mm.yyyy hh24:mi'), 'Some other stuff' From Dual Union All\n Select 'RyanAir', 'Barcelona', 'Dublin', To_Date('01.11.2022 11:10', 'dd.mm.yyyy hh24:mi'), To_Date('01.11.2022 13:00', 'dd.mm.yyyy hh24:mi'), 'Some other stuff' From Dual Union All\n Select 'KLM', 'Barcelona', 'Amsterdam', To_Date('01.11.2022 20:10', 'dd.mm.yyyy hh24:mi'), To_Date('01.11.2022 23:00', 'dd.mm.yyyy hh24:mi'), 'Some other stuff' From Dual Union All\n Select 'Lufthansa', 'Barcelona', 'Frankfurt', To_Date('01.11.2022 23:25', 'dd.mm.yyyy hh24:mi'), To_Date('02.11.2022 02:20', 'dd.mm.yyyy hh24:mi'), 'Some other stuff' From Dual \n )\n Select \n FLIGHT_OPERATOR, FLIGHT_FROM, FLIGHT_TO, \n DEPARTURE, To_Char(DEPARTURE, 'hh24:mi') \"DEPARTURE_TIME\", \n ARRIVAL, To_Char(ARRIVAL, 'hh24:mi') \"ARRIVAL_TIME\", \n SOME_OTHER_COL\nFrom\n flights\nOrder By \n DEPARTURE, FLIGHT_OPERATOR\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20239849/" ]
74,565,707
<p>I have an excel file and I accumulate thre values for each fruit sort with each other.</p> <p>So I do it like this:</p> <pre><code>def calulate_total_fruit_NorthMidSouth(): import openpyxl import tabula excelWorkbook = openpyxl.load_workbook(path, data_only=True) sheet_factuur = excelWorkbook['Facturen '] new_list =[] fruit_sums = { 'ananas': 0, 'apple': 0, 'waspeen': 0, } fruit_name_rows = { 'ananas': [6, 7, 8], 'apple': [9, 10, 11], 'waspeen': [12, 13, 14], } array = [row for row in sheet_factuur.values] # type: ignore # excel does not have a row 0 for row_num, row_values in enumerate(array, 1): for fruit in ['ananas', 'apple', 'waspeen']: # loop through specific fruits if row_num in fruit_name_rows[fruit]: # index 4 is column 5 in excel fruit_sums[fruit] += row_values[4] # type: ignore return list(fruit_sums.items()) </code></pre> <p>But the output is this:</p> <pre><code>[('ananas', 3962), ('apple', 3304.08), ('waspeen', 3767.3999999999996)] </code></pre> <p>But the output has to look like this:</p> <pre><code>ananas 3962 apple 3304.08 waspeen 3767.39 </code></pre> <p>How to archive this with return statement?</p>
[ { "answer_id": 74565891, "author": "Cole Bechtel", "author_id": 20593892, "author_profile": "https://Stackoverflow.com/users/20593892", "pm_score": 0, "selected": false, "text": "mylist = list(fruit_sums.items())\nfor i in mylist:\n newlist = list(i)\n for x in range(len(newlist)):\n newlist[x] = str(newlist[x])\nprint(\" \".join(newlist))\n" }, { "answer_id": 74565950, "author": "Adrian Kurzeja", "author_id": 8571154, "author_profile": "https://Stackoverflow.com/users/8571154", "pm_score": 2, "selected": true, "text": "def f():\n x = {'a': 1, 'b': 2, 'c': 3}\n return '\\n'.join(f'{a} {b}' for a, b in x.items())\n\nprint(f())\n# a 1\n# b 2\n# c 3\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7713770/" ]
74,565,735
<p>let's say a generic code of validate function of shiny R :</p> <pre><code>## Only run examples in interactive R sessions if (interactive()) { ui &lt;- fluidPage( checkboxGroupInput('in1', 'Check some letters', choices = head(LETTERS)), selectizeInput('in2', 'Select a state', choices = state.name), plotOutput('plot') ) server &lt;- function(input, output) { output$plot &lt;- renderPlot({ validate( need(input$in1, 'Check at least one letter!'), need(input$in2 != '', 'Please choose a state.') ) plot(1:10, main = paste(c(input$in1, input$in2), collapse = ', ')) }) } shinyApp(ui, server) } </code></pre> <p>Could you think it's possible to replace mesage error in character ('Check at least one letter!') by an image (png, jpeg format) ? I tried with renderImage function or , with the help of package <code>imager</code>, and don't manage to do it.</p> <p>many thanks to you, echoes</p> <p>Thanks you for your quick answer, it could be a great solution for my shiny application, and it works !</p> <p>in :</p> <pre><code>tags$style(HTML(&quot; .shiny-output-error-validation { background-image: URL(https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.svg); background-repeat: no-repeat; } &quot;)) </code></pre> <p>It would be nice to display a random or personalized image, who depends on user action. shinipsum package offer a random_image function, which could be quoted, something as :</p> <pre><code>tags$style(HTML(&quot; .shiny-output-error-validation { background-image: plotOutput(&quot;random_image&quot;); background-repeat: no-repeat; } &quot;)) </code></pre> <p>and in server part :</p> <pre><code>output$random_image &lt;- renderImage({ random_image() },deleteFile=FALSE) </code></pre> <p>Do you think it's possible to use output of ui part in tags$style or tagsList parts ?</p> <p>many thanks, echoes</p>
[ { "answer_id": 74566411, "author": "Johan Rosa", "author_id": 10266675, "author_profile": "https://Stackoverflow.com/users/10266675", "pm_score": 0, "selected": false, "text": ".shiny-output-error-validation library(shiny)\n\nui <- fluidPage(\n tags$head(\n tags$style(HTML(\"\n .shiny-output-error-validation {\n background-image: URL(https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.svg);\n background-repeat: no-repeat;\n }\n \"))\n ),\n checkboxGroupInput('in1', 'Check some letters', choices = head(LETTERS)),\n selectizeInput('in2', 'Select a state', choices = state.name),\n plotOutput('plot')\n)\n\nserver <- function(input, output) {\n output$plot <- renderPlot({\n validate(\n need(input$in1, \" \")\n )\n plot(1:10, main = paste(c(input$in1, input$in2), collapse = ', '))\n })\n}\n\nshinyApp(ui, server)\n" }, { "answer_id": 74585908, "author": "Ochees", "author_id": 8811744, "author_profile": "https://Stackoverflow.com/users/8811744", "pm_score": 0, "selected": false, "text": "css_content1 <- \"\n.shiny-output-error-validation {\n background-image:\"\nwriteLines(text = css_content1, con = \"styles1.css\")\ncss1 <- readLines(con = \"styles1.css\") %>% paste(collapse = \"\\n\")\n css_content2 <- \"\nbackground-repeat: no-repeat;\n }\n\"\nwriteLines(text = css_content2, con = \"styles2.css\")\ncss2 <- readLines(con = \"styles2.css\") %>% paste(collapse = \"\\n\")\n server <- function(input, output) {\n output$plot <- renderPlot({\n validate(\n need(input$in1, \" \")\n )\n plot(1:10, main = paste(c(input$in1, input$in2), collapse = ', '))\n })\n \n output$css_style <- renderUI({\n tags$head( tags$style(HTML(paste0(css1,\"URL(test\",sample(1:4,1),\".png);\",css2,collapse=\"\\n\"))\n ))\n })\n \n \n output$css_style_text <- renderText({\n HTML(paste0(css1,\"test\",sample(1:4,1),\".png\",\");\",css2,collapse=\"\\n\")) \n })\n \n \n} \n www ui <- fluidPage(\n uiOutput(\"css_style\"),\n checkboxGroupInput('in1', 'Check some letters', choices = head(LETTERS)),\n selectizeInput('in2', 'Select a state', choices = state.name),\n plotOutput('plot') \n)\n" }, { "answer_id": 74589791, "author": "Stéphane Laurent", "author_id": 1100107, "author_profile": "https://Stackoverflow.com/users/1100107", "pm_score": 2, "selected": true, "text": "ggplot library(shiny)\nlibrary(shinipsum)\n\nui <- fluidPage(\n checkboxGroupInput('in1', 'Check some letters', choices = head(LETTERS)),\n plotOutput('plot')\n)\n\nserver <- function(input, output) {\n output$plot <- renderPlot({\n test <- need(input$in1, \"\")\n if(!is.null(test)) {\n random_ggplot()\n } else {\n plot(1:10, main = input$in1)\n }\n })\n}\n\nshinyApp(ui, server)\n library(shiny)\nlibrary(shinipsum)\nlibrary(imager)\n\nui <- fluidPage(\n checkboxGroupInput('in1', 'Check some letters', choices = head(LETTERS)),\n plotOutput('plot')\n)\n\nserver <- function(input, output) {\n output$plot <- renderPlot({\n test <- need(input$in1, \"\")\n if(!is.null(test)) {\n img <- load.image(random_image()$src)\n plot(img)\n } else {\n plot(1:10, main = input$in1)\n }\n })\n}\n\nshinyApp(ui, server)\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8811744/" ]
74,565,811
<p>I have a class called Bullet which is essentially a div on a space invader webpage. When this bullet gets 'fired' I call a method which gradually moves the 'bullet' up the screen.</p> <p>When the bullet gets to the edge of the screen I want to remove the whole bullet object from memory. However, the <code>setTimeout</code> loop continues to run even after I've deleted it (I think).</p> <p>I'm sure there is a better way to do this! Perhaps it's foolish to run the loop like this?</p> <p>TIA</p> <pre><code>this.bulletmove = new CustomEvent(&quot;bulletmove&quot;,{detail:this.name}); ... /** * moves the bullet up the screen gradually */ fire(){ var that = this; setTimeout(function(){ that.moveUp(); window.dispatchEvent(that.bulletmove); that.fire(); },50); } </code></pre> <p>The event is picked up in a controller script which checks if the bullet has reached the edge of the screen at which point it is deleted:</p> <pre><code> window.addEventListener('bulletmove', function(evt) { checkCollision(evt); },false); ... /** *Check if the bullet has gone off screen and deletes it **/ function checkCollision(e){ var bulletName = e.detail; var bullet = bullets[bulletName]; //check if the bullet has gone off screen if (bullet.bottom &lt; 0){ bullet.destroy; delete bullets[e.detail]; bullet=null; } } </code></pre>
[ { "answer_id": 74565880, "author": "Amanda Woods", "author_id": 19771135, "author_profile": "https://Stackoverflow.com/users/19771135", "pm_score": 2, "selected": false, "text": "const fireBullet = setTimeout(function(){\n that.moveUp();\n window.dispatchEvent(that.bulletmove);\n that.fire();\n\n},50);\n\nclearTimeout(fireBullet)\n" }, { "answer_id": 74566037, "author": "muka.gergely", "author_id": 2316540, "author_profile": "https://Stackoverflow.com/users/2316540", "pm_score": 1, "selected": false, "text": "setInterval fire() setTimeout object obj.halt() setInterval const obj = {\n name: \"objName\",\n bulletmove() {\n return new CustomEvent(\"bulletmove\", {\n detail: this.name\n })\n },\n halt() {\n clearInterval(this.intervalHandler)\n },\n intervalHandler: null,\n fire() {\n const handler = setInterval(() => {\n // this.moveUp()\n // console.log(\"move up\")\n window.dispatchEvent(this.bulletmove())\n // this.fire()\n }, 500)\n this.intervalHandler = handler\n },\n}\n\nlet i = 0\n\nwindow.addEventListener('bulletmove', function(e) {\n\n // this if-else if mocks the collision detection\n // expected: log obj.name 5 times, then clear the interval,\n // then event should not be called anymore\n if (i < 5) {\n console.log(i, e.detail)\n } else if (i < 8) {\n obj.halt()\n console.log(i)\n } else if (i < 100) {\n console.log(i, e.detail)\n }\n i++\n})\n\nobj.fire() fire const obj = {\n name: \"objName\",\n bulletmove() {\n return new CustomEvent(\"bulletmove\", {\n detail: this.name\n })\n },\n fire() {\n const handler = setInterval(() => {\n // this.moveUp()\n // console.log(\"move up\")\n window.dispatchEvent(this.bulletmove())\n // this.fire()\n }, 500)\n return () => clearInterval(handler)\n },\n}\n\nlet i = 0\n\nconst fireHandler = obj.fire()\nconst eventHandler = (clearFn) => (e) => {\n\n // this if-else if mocks the collision detection\n // expected: log obj.name 5 times, then clear the interval,\n // then event should not be called anymore\n if (i < 5) {\n console.log(i, e.detail)\n } else if (i < 8) {\n clearFn()\n console.log(i)\n } else if (i < 100) {\n console.log(i, e.detail)\n }\n i++\n}\n\nconst eventHandlerWithRemoveFn = eventHandler(fireHandler)\n\nwindow.addEventListener('bulletmove', eventHandlerWithRemoveFn) window window const eventHandler = (e) => {\n const i = e.detail.eventCounter\n if (i < 3) {\n console.log(i, e.detail.name)\n } else if (i < 4) {\n window.bulletIntervals[e.detail.name]()\n console.log(i, e.detail.name + \" is halted\")\n } else if (i < 100) {\n console.log(i, e.detail.name)\n }\n}\n\nconst getBullet = (i) => ({\n eventCounter: i, // only for mocking!\n name: `objName-${i}`,\n bulletmove() {\n return new CustomEvent(\"bulletmove\", {\n detail: {\n name: this.name,\n eventCounter: this.eventCounter,\n }\n })\n },\n fire() {\n const handler = setInterval(() => {\n window.dispatchEvent(this.bulletmove())\n this.eventCounter++\n }, 500)\n if (!window.bulletIntervals) window.bulletIntervals = {}\n window.bulletIntervals[this.name] = () => clearInterval(handler)\n },\n})\n\nconst bullets = [\n getBullet(0),\n getBullet(1),\n getBullet(2),\n]\n\nconst fireAll = (bullets) => {\n window.addEventListener(\"bulletmove\", eventHandler)\n bullets.forEach((bullet) => {\n bullet.fire()\n })\n}\nfireAll(bullets)" }, { "answer_id": 74566898, "author": "customcommander", "author_id": 1244884, "author_profile": "https://Stackoverflow.com/users/1244884", "pm_score": 1, "selected": false, "text": "requestAnimationFrame const rightPos = el => el.getBoundingClientRect().right;\n \nconst moveBullet = (sel, pos) =>\n document.querySelector(sel)\n .style.left = `${pos}px`;\n\nconst fire = (bullet) => {\n const el = document.querySelector(bullet);\n const parentPos = rightPos(el.parentNode);\n return animationFrames().pipe(\n map(() => rightPos(el)),\n takeWhile(pos => pos < parentPos)\n );\n}\n\nconst bullet1$ = fire('#bullet1');\nconst bullet2$ = fire('#bullet2');\nconst bullet3$ = fire('#bullet3');\n\nconst fire$ = fromEvent(document.querySelector('button'),'click');\n\nfire$.subscribe(() => {\n bullet1$.subscribe(pos => moveBullet('#bullet1', pos+1));\n bullet2$.subscribe(pos => moveBullet('#bullet2', pos+1));\n bullet3$.subscribe(pos => moveBullet('#bullet3', pos+1));\n}); div {\n height: 30px;\n border: 1px solid black;\n margin: 5px;\n position: relative;\n}\n\nspan { position: absolute; } <script src=\"https://unpkg.com/rxjs@7.5.7/dist/bundles/rxjs.umd.min.js\"></script>\n\n<script>\nconst {animationFrames, fromEvent} = rxjs;\nconst {map, takeWhile} = rxjs.operators;\n</script>\n\n\n<div style=\"width:150px\"><span id=\"bullet1\"></span></div>\n<div style=\"width:300px\"><span id=\"bullet2\"></span></div>\n<div style=\"width:450px\"><span id=\"bullet3\">⚽️</span></div>\n\n<button>Fire!</button>" }, { "answer_id": 74575137, "author": "Ben Aston", "author_id": 38522, "author_profile": "https://Stackoverflow.com/users/38522", "pm_score": 0, "selected": false, "text": "div div requestAnimationFrame const elem = ({ kind = 'div', classN = '' }) => {\n const el = document.createElement(kind)\n el.classList.add(classN)\n return el\n}\n\nconst applyStyle = (el, style) => \n (Object.entries(style)\n .forEach(([k, v]) => el.style[k] = v), el)\n \nconst cssPixels = (str) => +(str.slice(0, -2))\n\nconst isVisible = (left) => \n cssPixels(left) < cssPixels(playfield.style.width)\n\nconst createPlayfield = () =>\n applyStyle(elem({ classN: 'playfield' }), { width: '300px' })\n\nconst createShip = (startLeft, width) => \n [{ classN: 'ship', style: { left: startLeft, width } }, null]\n\nconst createBullet = (startLeft) => {\n const b = {\n classN: 'bullet',\n style: { left: startLeft },\n firingTime: +new Date(),\n velocity: 0.5,\n velocitySeed: Number('1.' + ~~(Math.random() * 9)),\n startLeft\n }\n const g = bulletStateGen(b) \n return [ b, () => g.next() ]\n} \n\nconst bulletPos = ({ firingTime, \n startLeft,\n velocity,\n velocitySeed }, now = +new Date()) => \n `${~~(velocity * (now - firingTime) * velocitySeed + cssPixels(startLeft))}px`\n\nconst bulletStateGen = function*(b) {\n while (1) {\n const left = bulletPos(b)\n \n if (!isVisible(left))\n break\n\n b.style = { left }\n yield(b)\n }\n}\n\nconst fire = (startLeft) => \n state.unshift(createBullet(startLeft))\n\nconst tick = () => \n state = state.reduce((acc, [o, next]) => {\n if (!next)\n return acc.push([o, next]), acc\n \n const { value, done } = next()\n \n if (done)\n return acc\n \n return acc.push([value, next]), acc\n }, [])\n\nconst blank = () => playfield.innerHTML = ''\n \nconst render = () => {\n blank()\n state.forEach(([{ classN, style = {} }]) => \n playfield.appendChild(applyStyle(elem({ classN }), style)))\n}\n\nlet ship = createShip('10px', '50px')\nlet state = [ship]\nlet playfield = createPlayfield()\n\nconst gameLoop = () => \n (render(), tick(), requestAnimationFrame(gameLoop))\n\nconst init = () => { \n document.body.appendChild(playfield)\n document.body.onkeyup = (e) =>\n e.key === \" \" \n && fire(`${cssPixels(ship[0].style.left) + cssPixels(ship[0].style.width)}px`)\n}\n\ninit()\ngameLoop(state, playfield) .playfield {\n height: 300px;\n background-color: black;\n position: relative;\n}\n\n.ship {\n top: 138px;\n height: 50px;\n background-color: gold;\n position: absolute;\n border-radius: 7px 22px 22px 7px;\n}\n\n.bullet {\n top: 163px;\n width: 10px;\n height: 2px;\n background-color: silver;\n position: absolute;\n} Click on the game to focus it, and then press spacebar to fire!" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74565811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4150443/" ]