qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,667,887
<p>I find myself doing this a lot, and I assume there is a short hand way to make this faster. Yet in my research about shorthand and ternary operations, I can't quite seem to wrap my head around how to do it.</p> <pre><code>// below variable only be impactful if it's SET, not Null, and === important value. $verbose_instructively_named_variable = $other_variable. &quot;_modifier&quot;; if(isset($verbose_instructively_named_variable) &amp;&amp; $verbose_instructively_named_variable !== null &amp;&amp; $verbose_instructively_named_variable === &quot;key_text_modifier&quot;): // Now do important thing here; endif; </code></pre> <p>I am a beginning programmer obviously, but find myself attracted to longer variable names so when I revisit things later it flows linearly for me. So I find myself wanting to do the below all the time, and am frustrated I can't.</p> <pre><code>if(isset($verbose_instructively_named_variable) &amp;&amp; !==null &amp;&amp; === &quot;key_text_modifier&quot;): // Now do important stuff; endif; </code></pre> <p>I know this is a PHP question, but I find myself wanting this form of chained logic in javascript also. Am I missing a basic step of some kind?</p> <p>Is there an altogether different way to test ONE variable for multiple conditions quickly and efficiently?</p> <p>I have tried combinations of things found in similar questions. Like the in_array solution provided in this answer: <a href="https://stackoverflow.com/questions/16345833/in-php-is-there-a-short-way-to-compare-a-variable-to-multiple-values">In PHP, is there a short way to compare a variable to multiple values?</a></p> <p>As well as things like the below standard shortcut/shorthand.</p> <pre><code>$result = $initial ?: 'default'; </code></pre> <p>But what I want often is something more like this.</p> <pre><code>$result = ($initial !==null &amp;&amp; !==&quot;bad&quot; &amp;&amp; !in_array($initial,$record_set_from_mysql_query) ? $initial : 'default'); </code></pre> <p>And keep in mind the main reason I don't like and don't want to do this:</p> <pre><code>$result = ($initial !==null &amp;&amp; $initial !==&quot;bad&quot; $initial !==&quot;even_worse&quot; ? $initial : 'default'); </code></pre> <p>Is because &quot;$initial&quot; maybe named something like $always_make_this_value_green_when_blue_present or something otherwise cumbersome to type repeatedly and it makes the code hard to read later with multi-line parameters in the functions etc.</p> <p>Presently my best work around for this is to do this.</p> <pre><code>$a = $long_verbose_instructively_named_variable; $result = $a !== null &amp;&amp; $a !== &quot;bad&quot; &amp;&amp; $a !== &quot;even_worse&quot; ? $a : 'default'; </code></pre> <p>But this means in a function with a half dozen little small if/else checks I end up with a, aa, aaa, a_4, a_5 variables all over the place and it just gets cumbersome.</p>
[ { "answer_id": 74667879, "author": "N.braha", "author_id": 6121138, "author_profile": "https://Stackoverflow.com/users/6121138", "pm_score": 0, "selected": false, "text": "function erstellenEintrag() {\n var li = document.createElement(\"li\");\n // Set the content of the <li> element to the value of the input element\n li.innerHTML = input.value;\n ul.appendChild(li);\n // Reset the value of the input element\n input.value = \"\";\n}\n" }, { "answer_id": 74668009, "author": "gautam thakur", "author_id": 20633741, "author_profile": "https://Stackoverflow.com/users/20633741", "pm_score": -1, "selected": false, "text": " window.onload = function() {\n var enterButton = document.getElementById(\"enter\");\n \n function erstellenEintrag() {\n var ul = document.querySelector(\"ul\");\n var input = document.getElementById(\"benutzerInput\").value;\n var li = document.createElement(\"li\");\n li.append(input);\n ul.appendChild(li);\n }\n } \n\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74667887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13757852/" ]
74,667,899
<p>I have simple class like that;</p> <pre><code>class Foo { constructor() { this.datas = {} } set(key, data) { return this.datas[key] = data } get(key) { return this.datas[key] } } module.exports = Foo </code></pre> <p>I am adding some data to <code>datas</code> veriable first. But when I call same class in the next time, veriable is not saving like that;</p> <pre><code>const foo1 = Foo() foo1.set('a',[1,2,3]) const foo2 = Foo() var aData = foo2.get('a') console.log(aData) </code></pre> <p>But data not getting. How can I fix it?</p>
[ { "answer_id": 74667879, "author": "N.braha", "author_id": 6121138, "author_profile": "https://Stackoverflow.com/users/6121138", "pm_score": 0, "selected": false, "text": "function erstellenEintrag() {\n var li = document.createElement(\"li\");\n // Set the content of the <li> element to the value of the input element\n li.innerHTML = input.value;\n ul.appendChild(li);\n // Reset the value of the input element\n input.value = \"\";\n}\n" }, { "answer_id": 74668009, "author": "gautam thakur", "author_id": 20633741, "author_profile": "https://Stackoverflow.com/users/20633741", "pm_score": -1, "selected": false, "text": " window.onload = function() {\n var enterButton = document.getElementById(\"enter\");\n \n function erstellenEintrag() {\n var ul = document.querySelector(\"ul\");\n var input = document.getElementById(\"benutzerInput\").value;\n var li = document.createElement(\"li\");\n li.append(input);\n ul.appendChild(li);\n }\n } \n\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74667899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18220526/" ]
74,667,900
<p>I'm trying to decode a JSON string in swift but having some weird issues accessing the properties once decoded.</p> <p>This is the contents of the JSON file that I retrieve from a locally stored JSON file</p> <pre class="lang-json prettyprint-override"><code>[ { &quot;word&quot;: &quot;a&quot;, &quot;usage&quot;: [ { &quot;partOfSpeech&quot;: &quot;determiner&quot; } ] } ] </code></pre> <p>And this is the code to access the properties of the JSON file</p> <pre class="lang-swift prettyprint-override"><code>struct WordDictionary : Codable { var word: String var usage: [Usage] } struct Usage: Codable { var partOfSpeech: String } if let url = Bundle.main.url(forResource: FILE_NAME, withExtension: &quot;json&quot;) { do { let data = try Data(contentsOf: url) let decoder = JSONDecoder() let jsonData = try decoder.decode([WordDictionary].self, from: data) print(jsonData[0].word) //Outputs &quot;a&quot; print(jsonData[0].usage) //Outputs &quot;[MyApp.AppDelegate.(unknown context at $102a37f00).(unknown context at $102a38038).Usage(partOfSpeech: &quot;determiner&quot;)]&quot; } catch { print(&quot;error:\(error)&quot;) } } </code></pre> <p>As you can see, when I try to <code>print(jsonData[0].usage)</code> I get a series of unknown data messages before I get the “Usage” property. When I print this line I just want to see <code>determiner</code>, I’m not sure what the preamble about the “unknown context” is all about.</p> <p>I’m also running this code in <code>didFinishLaunchingWithOptions</code> function of the <code>AppDelegate</code>.</p> <p>I’m not sure what I’m missing. I've been trying to find a solution for a few days now and trying different approaches but still can’t get the desired output, any help would be appreciated.</p>
[ { "answer_id": 74667879, "author": "N.braha", "author_id": 6121138, "author_profile": "https://Stackoverflow.com/users/6121138", "pm_score": 0, "selected": false, "text": "function erstellenEintrag() {\n var li = document.createElement(\"li\");\n // Set the content of the <li> element to the value of the input element\n li.innerHTML = input.value;\n ul.appendChild(li);\n // Reset the value of the input element\n input.value = \"\";\n}\n" }, { "answer_id": 74668009, "author": "gautam thakur", "author_id": 20633741, "author_profile": "https://Stackoverflow.com/users/20633741", "pm_score": -1, "selected": false, "text": " window.onload = function() {\n var enterButton = document.getElementById(\"enter\");\n \n function erstellenEintrag() {\n var ul = document.querySelector(\"ul\");\n var input = document.getElementById(\"benutzerInput\").value;\n var li = document.createElement(\"li\");\n li.append(input);\n ul.appendChild(li);\n }\n } \n\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74667900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20675069/" ]
74,667,901
<p>I am trying to have 9 columns per row using <code>row-cols-*</code>, but it doesn't work with more than 6:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"&gt;&lt;/script&gt; &lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"/&gt; &lt;div class="row row-cols-lg-9 row-cols-md-9 row-cols-sm-9 row-cols-9 text-center"&gt; &lt;div&gt;Item1&lt;/div&gt; &lt;div&gt;Item2&lt;/div&gt; &lt;div&gt;Item3&lt;/div&gt; &lt;div&gt;Item4&lt;/div&gt; &lt;div&gt;Item5&lt;/div&gt; &lt;div&gt;Item6&lt;/div&gt; &lt;div&gt;Item7&lt;/div&gt; &lt;div&gt;Item8&lt;/div&gt; &lt;div&gt;Item9&lt;/div&gt; &lt;div&gt;Item10&lt;/div&gt; &lt;div&gt;Item11&lt;/div&gt; &lt;div&gt;Item12&lt;/div&gt; &lt;div&gt;Item13&lt;/div&gt; &lt;div&gt;Item14&lt;/div&gt; &lt;div&gt;Item15&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>How can I use more than 6? I need 9 in my case. I thought I could have up to 12.</p>
[ { "answer_id": 74667879, "author": "N.braha", "author_id": 6121138, "author_profile": "https://Stackoverflow.com/users/6121138", "pm_score": 0, "selected": false, "text": "function erstellenEintrag() {\n var li = document.createElement(\"li\");\n // Set the content of the <li> element to the value of the input element\n li.innerHTML = input.value;\n ul.appendChild(li);\n // Reset the value of the input element\n input.value = \"\";\n}\n" }, { "answer_id": 74668009, "author": "gautam thakur", "author_id": 20633741, "author_profile": "https://Stackoverflow.com/users/20633741", "pm_score": -1, "selected": false, "text": " window.onload = function() {\n var enterButton = document.getElementById(\"enter\");\n \n function erstellenEintrag() {\n var ul = document.querySelector(\"ul\");\n var input = document.getElementById(\"benutzerInput\").value;\n var li = document.createElement(\"li\");\n li.append(input);\n ul.appendChild(li);\n }\n } \n\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74667901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17746636/" ]
74,667,952
<p>I am in the process of creating a web application for a genealogy project. I want each person I add onto the database to have a unique id, based on the first 3 characters of their surname (let's call it, for the purpose of explaining, 'surname-string'), concatenated with an autoincrement (which starts from 00001 for each unique 'surname-string').</p> <p>For example - a person's surname is &quot;Smith&quot;. The surname-string will be SMI and due to the fact that they are the first surname-string &quot;SMI&quot; the full reference will be SMI00001. Another person's surname is Black, making their surname-string BLA, and because they are the first one with the surname-string BLA, their reference will be BLA00001. A third person's surname is also Smith - they are the second person with the SMI surname-string, so their reference should be SMI00002.</p> <p>This unique id will be used in the persons URL, to be searched by and create relationships between people in the database.</p> <p>I have no clue how to approach this logically.</p> <p>I have not tried anything yet. It goes way over my head!</p>
[ { "answer_id": 74668396, "author": "Ergest Basha", "author_id": 16461952, "author_profile": "https://Stackoverflow.com/users/16461952", "pm_score": 1, "selected": false, "text": "uniqu_identifier CREATE TABLE test(\nid bigint NOT NULL AUTO_INCREMENT,\nsurname varchar(20),\nuniqu_identifier varchar(30) ,\n PRIMARY KEY (id)\n ) ;\n CREATE TRIGGER test_BEFORE_INSERT\n BEFORE INSERT ON test \n FOR EACH ROW\n BEGIN\n IF EXISTS (SELECT 1 FROM test WHERE left(surname,3) = left(new.surname,3)) THEN\n SET new.uniqu_identifier = (select concat(upper(left(new.surname,3)),'0000' ,max(right(uniqu_identifier,1)) +1) from test );\n ELSE \n SET new.uniqu_identifier = concat(upper(left(new.surname,3)),'00001');\n END IF ;\n END\n insert into test (surname) values ('SMITH');\ninsert into test (surname) values ('SMITH1');\ninsert into test (surname) values ('JOHN');\n\nselect * \nfrom test;\n id surname uniqu_identifier\n1 SMITH SMI00001\n2 SMITH1 SMI00002\n3 JOHN JOH00001\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74667952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13355162/" ]
74,667,965
<p>I am trying to write a multi-threaded program to produce a vector of <code>N*NumPerThread</code> uniform random integers, where <code>N</code> is the return value of <code>std::thread::hardware_concurrency()</code> and <code>NumPerThread</code> is the amount of random numbers I want each thread to generate.</p> <p>I created a multi-threaded version:</p> <pre><code>#include &lt;iostream&gt; #include &lt;thread&gt; #include &lt;vector&gt; #include &lt;random&gt; #include &lt;chrono&gt; using Clock = std::chrono::high_resolution_clock; namespace Vars { const unsigned int N = std::thread::hardware_concurrency(); //number of threads on device const unsigned int NumPerThread = 5e5; //number of random numbers to generate per thread std::vector&lt;int&gt; RandNums(NumPerThread*N); std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution&lt;&gt; dis(1, 1000); int sz = 0; } using namespace Vars; void AddN(int start) { static std::mutex mtx; std::lock_guard&lt;std::mutex&gt; lock(mtx); for (unsigned int i=start; i&lt;start+NumPerThread; i++) { RandNums[i] = dis(gen); ++sz; } } int main() { auto start_time = Clock::now(); std::vector&lt;std::thread&gt; threads; threads.reserve(N); for (unsigned int i=0; i&lt;N; i++) { threads.emplace_back(std::move(std::thread(AddN, i*NumPerThread))); } for (auto &amp;i: threads) { i.join(); } auto end_time = Clock::now(); std::cout &lt;&lt; &quot;\nTime difference = &quot; &lt;&lt; std::chrono::duration&lt;double, std::nano&gt;(end_time - start_time).count() &lt;&lt; &quot; nanoseconds\n&quot;; std::cout &lt;&lt; &quot;size = &quot; &lt;&lt; sz &lt;&lt; '\n'; } </code></pre> <p>and a single-threaded version</p> <pre><code>#include &lt;iostream&gt; #include &lt;thread&gt; #include &lt;vector&gt; #include &lt;random&gt; #include &lt;chrono&gt; using Clock = std::chrono::high_resolution_clock; namespace Vars { const unsigned int N = std::thread::hardware_concurrency(); //number of threads on device const unsigned int NumPerThread = 5e5; //number of random numbers to generate per thread std::vector&lt;int&gt; RandNums(NumPerThread*N); std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution&lt;&gt; dis(1, 1000); int sz = 0; } using namespace Vars; void AddN() { for (unsigned int i=0; i&lt;NumPerThread*N; i++) { RandNums[i] = dis(gen); ++sz; } } int main() { auto start_time = Clock::now(); AddN(); auto end_time = Clock::now(); std::cout &lt;&lt; &quot;\nTime difference = &quot; &lt;&lt; std::chrono::duration&lt;double, std::nano&gt;(end_time - start_time).count() &lt;&lt; &quot; nanoseconds\n&quot;; std::cout &lt;&lt; &quot;size = &quot; &lt;&lt; sz &lt;&lt; '\n'; } </code></pre> <p>The execution times are more or less the same. I am assuming there is a problem with the multi-threaded version?</p> <p>P.S. I looked at all of the other similar questions here, I don't see how they directly apply to this task...</p>
[ { "answer_id": 74668092, "author": "Nicol Bolas", "author_id": 734069, "author_profile": "https://Stackoverflow.com/users/734069", "pm_score": 2, "selected": false, "text": "std::vector<int>" }, { "answer_id": 74668131, "author": "lewis", "author_id": 6814658, "author_profile": "https://Stackoverflow.com/users/6814658", "pm_score": 1, "selected": true, "text": " std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_int_distribution<> dis(1, 1000);\n using Clock = std::chrono::high_resolution_clock;\n\nnamespace SharedVars\n{\n const unsigned int N = std::thread::hardware_concurrency(); //number of threads on device\n const unsigned int NumPerThread = 5e5; //number of random numbers to generate per thread\n std::vector<int> RandNums(NumPerThread*N);\n std::mutex mtx;\n}\n\nvoid PerThread_AddN(int threadNumber)\n{\n using namespace SharedVars;\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_int_distribution<> dis(1, 1000);\n int sz = 0;\n\n vector<int>::iterator from;\n vector<int>::iterator to;\n {\n std::lock_guard<std::mutex> lock(mtx); // hold the lock only while accessing shared vector, not while accessing its contents\n from = RandNums.begin () + threadNumber*NumPerThread;\n to = from + NumPerThread;\n }\n for (auto i = from; i < to; ++i)\n {\n *i = dis(gen);\n }\n}\n\nint main()\n{\n auto start_time = Clock::now();\n std::vector<std::thread> threads;\n threads.reserve(N);\n \n for (unsigned int i=0; i<N; i++)\n {\n threads.emplace_back(std::move(std::thread(PerThread_AddN, i)));\n }\n for (auto &i: threads)\n {\n i.join();\n }\n auto end_time = Clock::now();\n std::cout << \"\\nTime difference = \"\n << std::chrono::duration<double, std::nano>(end_time - start_time).count() << \" nanoseconds\\n\";\n std::cout << \"size = \" << sz << '\\n';\n}\n" }, { "answer_id": 74671345, "author": "Edward Finkelstein", "author_id": 18255427, "author_profile": "https://Stackoverflow.com/users/18255427", "pm_score": 0, "selected": false, "text": "std::packaged_task #include <iostream>\n#include <vector>\n#include <random>\n#include <future>\n#include <chrono>\n\nusing Clock = std::chrono::high_resolution_clock;\n\nconst unsigned int N = std::thread::hardware_concurrency(); //number of threads on device\nconst unsigned int NumPerThread = 5e5; //number of random numbers to generate per thread\n\nstd::vector<int> createVec()\n{\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_int_distribution<> dis(1, 1000);\n std::vector<int> x;\n x.reserve(NumPerThread);\n for (unsigned int i = 0; i < NumPerThread; i++)\n {\n x.push_back(dis(gen));\n }\n return x;\n}\n\nint main()\n{\n auto start_time = Clock::now();\n\n std::vector<int> RandNums;\n RandNums.reserve(N*NumPerThread);\n \n std::vector<std::future<std::vector<int>>> results;\n results.reserve(N);\n std::vector<int> crap;\n crap.reserve(NumPerThread);\n \n for (unsigned int i=0; i<N; i++)\n {\n std::packaged_task<std::vector<int>()> temp(createVec);\n results[i] = temp.get_future();\n temp();\n crap = std::move(results[i].get());\n RandNums.insert(RandNums.begin()+(0*NumPerThread),crap.begin(),crap.end());\n }\n\n auto end_time = Clock::now();\n std::cout << \"Time difference = \"\n << std::chrono::duration<double, std::nano>(end_time - start_time).count() << \" nanoseconds\\n\";\n}\n\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74667965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18255427/" ]
74,667,970
<p>I have a lot of movie files and I want to get their production year from their file names. as below:</p> <p>Input: <code>Kingdom.of.Heaven.2005.720p.Dubbed.Film2media</code></p> <p>Output: <code>2005</code></p> <p>This code just splits <strong>all</strong> the numbers:</p> <pre class="lang-cs prettyprint-override"><code>string[] result = Regex.Split(str, @&quot;(\d+:)&quot;); </code></pre>
[ { "answer_id": 74668067, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 3, "selected": true, "text": "\\b(19\\d\\d)|(20\\d\\d)\\b\n 19\\d\\d 20\\d\\d \\b | 2001 string productionYear =\n Regex.Match(str, @\"\\b(19\\d\\d)|(20\\d\\d)\\b\", RegexOptions.RightToLeft);\n 720p 2048p \\b string[] parts = str.Split('.');\nstring productionYear = parts[^4]; // C# 8.0+, .NET Core\n// or\nstring productionYear = parts[parts.Length - 4]; // C# < 8 or .NET Framework\n" }, { "answer_id": 74668366, "author": "Ibrahim Timimi", "author_id": 8316900, "author_profile": "https://Stackoverflow.com/users/8316900", "pm_score": 0, "selected": false, "text": "var regex = new Regex(@\"\\b\\d{4}\\b\");\nvar myInput = \"Kingdom.of.Heaven.2005.720p.Dubbed.Film2media\";\nvar productionYear = regex.Matches(myInput).Single().Value;\n\nConsole.WriteLine($\"Production year: {productionYear}\");\n Production year: 2005\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74667970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16478672/" ]
74,667,993
<p>If I have a dataframe `</p> <pre><code>A Variant&amp;Price Qty AAC 7:124|25: 443 1 AAD 35:|35: 1 AAS 32:98|3:40 1 AAG 2: |25: 1 AAC 25:443|26:344 1 </code></pre> <p>and I want to get variant which has one of its values is below 7</p> <pre><code>A Variant&amp;Price Qty AAC 7:124|25: 443 1 AAS 32:9|3:40 1 AAG 2: |25: 1 </code></pre> <p>Note that first digit is the variant, as well as the third digit (variant always before <code>:</code>) I can apply this code,</p> <pre><code>split_df = df['Variant&amp;Price'].str.split(':|\|', expand=True) print(df[split_df.iloc[:, [0,2]].astype(int).min(axis=1) &lt;= 7]) </code></pre> <p>But what if I want to get, instead of 7, it is now range from 2 to 7. I ve tried <code>&gt;=2 &amp; &lt;=7</code> but not working</p>
[ { "answer_id": 74668029, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "extractall : any between m = (df['Variant&Price'].str.extractall('(\\d+):')[0]\n .astype(int).between(2,7).groupby(level=0).any()\n )\n\nout = df[m]\n A Variant&Price Qty\n0 AAC 7:124|25: 443 1\n2 AAS 32:98|3:40 1\n3 AAG 2: |25: 1\n" }, { "answer_id": 74668128, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 1, "selected": false, "text": "cond1 = (df['Variant&Price'].str.split('|').explode()\n .str.split(':').str[0]\n .astype('int')\n .between(2, 7).max(level=0))\n\ndf[cond1]\n Am Variant&Price Qty\n0 AAC 7:124|25: 443 1\n2 AAS 32:98|3:40 1\n3 AAG 2: |25: 1\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74667993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20434497/" ]
74,668,015
<p>Inside one JS file I saw:</p> <pre><code>Math.round(timeEngine.timeLeft, 10) </code></pre> <p>I've checked many documentations (some are mentioned here) and all mention that this function takes one argument, so what the second argument (10) is referring to?</p> <p><a href="https://www.w3schools.com/jsref/jsref_round.asp" rel="nofollow noreferrer">https://www.w3schools.com/jsref/jsref_round.asp</a></p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round</a></p>
[ { "answer_id": 74668029, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "extractall : any between m = (df['Variant&Price'].str.extractall('(\\d+):')[0]\n .astype(int).between(2,7).groupby(level=0).any()\n )\n\nout = df[m]\n A Variant&Price Qty\n0 AAC 7:124|25: 443 1\n2 AAS 32:98|3:40 1\n3 AAG 2: |25: 1\n" }, { "answer_id": 74668128, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 1, "selected": false, "text": "cond1 = (df['Variant&Price'].str.split('|').explode()\n .str.split(':').str[0]\n .astype('int')\n .between(2, 7).max(level=0))\n\ndf[cond1]\n Am Variant&Price Qty\n0 AAC 7:124|25: 443 1\n2 AAS 32:98|3:40 1\n3 AAG 2: |25: 1\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20675451/" ]
74,668,064
<p>Here's the code that I attempted</p> <pre><code>public String isPalindrome(String s) { String trimmed = s.replaceAll(&quot;[^A-Za-z0-9]&quot;, &quot;&quot;); String reversed = &quot;&quot;; int len = trimmed.length(); for (int i = len - 1; i &gt;= 0; i--) { char[] allChars = trimmed.toCharArray(); reversed += allChars[i]; } if (trimmed.equalsIgnoreCase(reversed)) { return &quot;true&quot;; } else { return &quot;false&quot;; } } </code></pre> <p>Sample Input 1 A man, a plan, a canal: Panama</p> <p>Sample Output 1 true</p> <p>Explanation 1 The given string is palindrome when considering only alphanumeric characters.</p> <p>Sample Input 2 race a car</p> <p>Sample Output 2 false</p> <p>Explanation 2 The given string is not a palindrome when considering alphanumeric characters.</p>
[ { "answer_id": 74668029, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "extractall : any between m = (df['Variant&Price'].str.extractall('(\\d+):')[0]\n .astype(int).between(2,7).groupby(level=0).any()\n )\n\nout = df[m]\n A Variant&Price Qty\n0 AAC 7:124|25: 443 1\n2 AAS 32:98|3:40 1\n3 AAG 2: |25: 1\n" }, { "answer_id": 74668128, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 1, "selected": false, "text": "cond1 = (df['Variant&Price'].str.split('|').explode()\n .str.split(':').str[0]\n .astype('int')\n .between(2, 7).max(level=0))\n\ndf[cond1]\n Am Variant&Price Qty\n0 AAC 7:124|25: 443 1\n2 AAS 32:98|3:40 1\n3 AAG 2: |25: 1\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17934589/" ]
74,668,103
<p>I want to merge two arrays. I want to get arr1 data based on arr2 structure, how should I do it?</p> <p>I tried using 3 forEach, but it doesn't work.</p> <pre><code>const arr1 = [{id:'1', List:[{name:'a', title:'a title'}, {name:'b', title:'b title'}]}, {id:'2', List:[{name:'c', title:'c title'}, {name:'d', title:'d title'}]}]; const arr2 = [{id:'1', name:'a'}, {id:'1', name:'b'}, {id:'2', name:'c'}]; </code></pre> <p>I want the result below</p> <pre><code>newArr = [{id:'1', List:[{name:'a', title:'a title'}, {name:'b', title:'b title'}]}, {id:'2', List:[{name:'c', title:'c title'}]}] </code></pre>
[ { "answer_id": 74668214, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 2, "selected": true, "text": "const arr1 = [{id:'1', List:[{name:'a', title:'a title'}, {name:'b', title:'b title'}]}, {id:'2', List:[{name:'c', title:'c title'}, {name:'d', title:'d title'}]}]\nconst arr2 = [{id:'1', name:'a'}, {id:'1', name:'b'}, {id:'2', name:'c'}]\n\nconst r = [...new Set(arr2.map(i=>i.id))].map(id=>(({id, List})=>({id, List:List.filter(({name})=>arr2.some(i=>i.id===id && i.name===name))}))(arr1.find(i=>i.id===id)))\n\nconsole.log(r) const arr1 = [{id:'1', List:[{name:'a', title:'a title'}, {name:'b', title:'b title'}]}, {id:'2', List:[{name:'c', title:'c title'}, {name:'d', title:'d title'}]}]\nconst arr2 = [{id:'1', name:'a'}, {id:'1', name:'b'}, {id:'2', name:'c'}]\n\nconst r = [...new Set(arr2.map(i=>i.id))].map((id,c)=>(({List})=>({id, List:List.filter(({name})=>arr2.some(({id:x, name:y})=>x===id && y===name)).map((i,d)=>({...i, index: `${c}-${d}`}))}))(arr1.find(({id:x})=>x===id)))\n\nconsole.log(r)" }, { "answer_id": 74668238, "author": "Alen.Toma", "author_id": 4828524, "author_profile": "https://Stackoverflow.com/users/4828524", "pm_score": 0, "selected": false, "text": "const arr1 = [{id:'1', List:[{name:'a', title:'a title'}, {name:'b', title:'b title'}]}, {id:'2', List:[{name:'c', title:'c title'}, {name:'d', title:'d title'}]}];\nconst arr2 = [{id:'1', name:'a'}, {id:'1', name:'b'}, {id:'2', name:'c'}];\n\n\nconst res = arr2.reduce((a,v)=> {\n const item = arr1.find(x=> x.id === v.id);\n const tItem =a.find(x=> x.id == v.id) || {id: v.id, List:[]};\n tItem.List = [...tItem.List,...item.List.filter(x=> x.name == v.name)]\n \n a.push({...tItem});\n return a;\n \n},[])\n\nconsole.log(res)" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12066654/" ]
74,668,114
<p>The calculator should take inputs like (23&gt;3) or (a&gt;9) and prints if it's true or false. My main difficulty is doing it for letters. I only managed to do it for numbers. I don't know how to define the <code>scanf</code> to accept a letter. When a letter is compared to a number, I need to compare the letters' ASCII values. So, if I do <code>a&gt;9</code> it actually checks if <code>97&gt;9</code> (97 is the ASCII value of 'a').</p> <pre><code>#include &lt;stdio.h&gt; int main() { int num1, num2; char operator; printf(&quot;Please write your logical statement:&quot;); scanf(&quot;%d %c %d&quot;, &amp;num1, &amp;operator, &amp;num2); if (operator=='&gt;') { if (num1&gt;num2) { printf(&quot;True&quot;); } else { printf(&quot;false&quot;); } } else if (operator =='&lt;') { if (num1&lt;num2) { printf(&quot;True&quot;); } else { printf(&quot;false&quot;); } } else if (operator == '=') { if (num1==num2) { printf(&quot;True&quot;); } else { printf(&quot;False&quot;); } } } </code></pre> <p>How do I modify it to also accept characters?</p>
[ { "answer_id": 74668214, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 2, "selected": true, "text": "const arr1 = [{id:'1', List:[{name:'a', title:'a title'}, {name:'b', title:'b title'}]}, {id:'2', List:[{name:'c', title:'c title'}, {name:'d', title:'d title'}]}]\nconst arr2 = [{id:'1', name:'a'}, {id:'1', name:'b'}, {id:'2', name:'c'}]\n\nconst r = [...new Set(arr2.map(i=>i.id))].map(id=>(({id, List})=>({id, List:List.filter(({name})=>arr2.some(i=>i.id===id && i.name===name))}))(arr1.find(i=>i.id===id)))\n\nconsole.log(r) const arr1 = [{id:'1', List:[{name:'a', title:'a title'}, {name:'b', title:'b title'}]}, {id:'2', List:[{name:'c', title:'c title'}, {name:'d', title:'d title'}]}]\nconst arr2 = [{id:'1', name:'a'}, {id:'1', name:'b'}, {id:'2', name:'c'}]\n\nconst r = [...new Set(arr2.map(i=>i.id))].map((id,c)=>(({List})=>({id, List:List.filter(({name})=>arr2.some(({id:x, name:y})=>x===id && y===name)).map((i,d)=>({...i, index: `${c}-${d}`}))}))(arr1.find(({id:x})=>x===id)))\n\nconsole.log(r)" }, { "answer_id": 74668238, "author": "Alen.Toma", "author_id": 4828524, "author_profile": "https://Stackoverflow.com/users/4828524", "pm_score": 0, "selected": false, "text": "const arr1 = [{id:'1', List:[{name:'a', title:'a title'}, {name:'b', title:'b title'}]}, {id:'2', List:[{name:'c', title:'c title'}, {name:'d', title:'d title'}]}];\nconst arr2 = [{id:'1', name:'a'}, {id:'1', name:'b'}, {id:'2', name:'c'}];\n\n\nconst res = arr2.reduce((a,v)=> {\n const item = arr1.find(x=> x.id === v.id);\n const tItem =a.find(x=> x.id == v.id) || {id: v.id, List:[]};\n tItem.List = [...tItem.List,...item.List.filter(x=> x.name == v.name)]\n \n a.push({...tItem});\n return a;\n \n},[])\n\nconsole.log(res)" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20522584/" ]
74,668,149
<p>Need to scrape the full table from this site with &quot;Load more&quot; option.</p> <p>As of now when I`m scraping , I only get the one that shows up by default on when loading the page.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import requests from six.moves import urllib URL2 = &quot;https://www.mykhel.com/football/indian-super-league-player-stats-l750/&quot; header = {'Accept-Language': &quot;en-US,en;q=0.9&quot;, 'User-Agent': &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 &quot; &quot;(KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36&quot; } resp2 = requests.get(url=URL2, headers=header).text tables2 = pd.read_html(resp2) overview_table2= tables2[0] overview_table2 </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;"></th> <th style="text-align: right;">Player Name</th> <th style="text-align: right;">Team</th> <th style="text-align: right;">Matches</th> <th style="text-align: right;">Goals</th> <th style="text-align: right;">Time Played</th> <th style="text-align: right;">Unnamed: 5</th> </tr> </thead> <tbody> <tr> <td style="text-align: right;">0</td> <td style="text-align: right;">Jorge Pereyra Diaz</td> <td style="text-align: right;">Mumbai City</td> <td style="text-align: right;">9</td> <td style="text-align: right;">6</td> <td style="text-align: right;">538 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">1</td> <td style="text-align: right;">Cleiton Silva</td> <td style="text-align: right;">SC East Bengal</td> <td style="text-align: right;">8</td> <td style="text-align: right;">5</td> <td style="text-align: right;">707 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">2</td> <td style="text-align: right;">Abdenasser El Khayati</td> <td style="text-align: right;">Chennaiyin FC</td> <td style="text-align: right;">5</td> <td style="text-align: right;">4</td> <td style="text-align: right;">231 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">3</td> <td style="text-align: right;">Lallianzuala Chhangte</td> <td style="text-align: right;">Mumbai City</td> <td style="text-align: right;">9</td> <td style="text-align: right;">4</td> <td style="text-align: right;">737 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">4</td> <td style="text-align: right;">Nandhakumar Sekar</td> <td style="text-align: right;">Odisha</td> <td style="text-align: right;">8</td> <td style="text-align: right;">4</td> <td style="text-align: right;">673 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">5</td> <td style="text-align: right;">Ivan Kalyuzhnyi</td> <td style="text-align: right;">Kerala Blasters</td> <td style="text-align: right;">7</td> <td style="text-align: right;">4</td> <td style="text-align: right;">428 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">6</td> <td style="text-align: right;">Bipin Singh</td> <td style="text-align: right;">Mumbai City</td> <td style="text-align: right;">9</td> <td style="text-align: right;">4</td> <td style="text-align: right;">806 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">7</td> <td style="text-align: right;">Noah Sadaoui</td> <td style="text-align: right;">Goa</td> <td style="text-align: right;">8</td> <td style="text-align: right;">4</td> <td style="text-align: right;">489 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">8</td> <td style="text-align: right;">Diego Mauricio</td> <td style="text-align: right;">Odisha</td> <td style="text-align: right;">8</td> <td style="text-align: right;">3</td> <td style="text-align: right;">526 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">9</td> <td style="text-align: right;">Pedro Martin</td> <td style="text-align: right;">Odisha</td> <td style="text-align: right;">8</td> <td style="text-align: right;">3</td> <td style="text-align: right;">263 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">10</td> <td style="text-align: right;">Dimitri Petratos</td> <td style="text-align: right;">ATK Mohun Bagan</td> <td style="text-align: right;">6</td> <td style="text-align: right;">3</td> <td style="text-align: right;">517 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">11</td> <td style="text-align: right;">Petar Sliskovic</td> <td style="text-align: right;">Chennaiyin FC</td> <td style="text-align: right;">8</td> <td style="text-align: right;">3</td> <td style="text-align: right;">662 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">12</td> <td style="text-align: right;">Holicharan Narzary</td> <td style="text-align: right;">Hyderabad</td> <td style="text-align: right;">9</td> <td style="text-align: right;">3</td> <td style="text-align: right;">705 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">13</td> <td style="text-align: right;">Dimitrios Diamantakos</td> <td style="text-align: right;">Kerala Blasters</td> <td style="text-align: right;">7</td> <td style="text-align: right;">3</td> <td style="text-align: right;">529 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">14</td> <td style="text-align: right;">Alberto Noguera</td> <td style="text-align: right;">Mumbai City</td> <td style="text-align: right;">9</td> <td style="text-align: right;">3</td> <td style="text-align: right;">371 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">15</td> <td style="text-align: right;">Jerry Mawihmingthanga</td> <td style="text-align: right;">Odisha</td> <td style="text-align: right;">8</td> <td style="text-align: right;">3</td> <td style="text-align: right;">611 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">16</td> <td style="text-align: right;">Hugo Boumous</td> <td style="text-align: right;">ATK Mohun Bagan</td> <td style="text-align: right;">7</td> <td style="text-align: right;">2</td> <td style="text-align: right;">580 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">17</td> <td style="text-align: right;">Javi Hernandez</td> <td style="text-align: right;">Bengaluru</td> <td style="text-align: right;">6</td> <td style="text-align: right;">2</td> <td style="text-align: right;">397 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">18</td> <td style="text-align: right;">Borja Herrera</td> <td style="text-align: right;">Hyderabad</td> <td style="text-align: right;">9</td> <td style="text-align: right;">2</td> <td style="text-align: right;">314 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">19</td> <td style="text-align: right;">Mohammad Yasir</td> <td style="text-align: right;">Hyderabad</td> <td style="text-align: right;">9</td> <td style="text-align: right;">2</td> <td style="text-align: right;">777 Mins</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: right;">20</td> <td style="text-align: right;">Load More....</td> <td style="text-align: right;">Load More....</td> <td style="text-align: right;">Load More....</td> <td style="text-align: right;">Load More....</td> <td style="text-align: right;">Load More....</td> <td style="text-align: right;">Load More....</td> </tr> </tbody> </table> </div> <p>But I need the full table , including the data under &quot;Load more&quot;, please help.</p>
[ { "answer_id": 74669245, "author": "αԋɱҽԃ αмєяιcαη", "author_id": 7658985, "author_profile": "https://Stackoverflow.com/users/7658985", "pm_score": 2, "selected": false, "text": "import requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0'\n}\n\n\ndef main(url):\n params = {\n \"action\": \"stats\",\n \"league_id\": \"750\",\n \"limit\": \"300\",\n \"offset\": \"0\",\n \"part\": \"leagues\",\n \"season_id\": \"2022\",\n \"section\": \"football\",\n \"stats_type\": \"player\",\n \"tab\": \"overview\"\n }\n r = requests.get(url, headers=headers, params=params)\n soup = BeautifulSoup(r.text, 'lxml')\n goal = [(x['title'], *[i.get_text(strip=True) for i in x.find_all_next('td', limit=4)])\n for x in soup.select('a.player_link')]\n df = pd.DataFrame(\n goal, columns=['Name', 'Team', 'Matches', 'Goals', 'Time Played'])\n print(df)\n\n\nmain('https://www.mykhel.com/src/index.php')\n Name Team Matches Goals Time Played\n0 Jorge Pereyra Diaz Mumbai City 9 6 538 Mins\n1 Cleiton Silva SC East Bengal 8 5 707 Mins\n2 Abdenasser El Khayati Chennaiyin FC 5 4 231 Mins\n3 Lallianzuala Chhangte Mumbai City 9 4 737 Mins\n4 Nandhakumar Sekar Odisha 8 4 673 Mins\n.. ... ... ... ... ...\n268 Sarthak Golui SC East Bengal 6 0 402 Mins\n269 Ivan Gonzalez SC East Bengal 8 0 683 Mins\n270 Michael Jakobsen NorthEast United 8 0 676 Mins\n271 Pratik Chowdhary Jamshedpur FC 6 0 495 Mins\n272 Chungnunga Lal SC East Bengal 8 0 720 Mins\n\n[273 rows x 5 columns]\n" }, { "answer_id": 74669291, "author": "DiMithras", "author_id": 8489602, "author_profile": "https://Stackoverflow.com/users/8489602", "pm_score": 0, "selected": false, "text": "pip install selenium\n html5lib pip install html5lib BeautifulSoup4\n PATH import pandas as pd\nfrom selenium import webdriver\n\nURL2 = \"https://www.mykhel.com/football/indian-super-league-player-stats-l750/\"\n\ndriver = webdriver.Firefox()\ndriver.get(URL2)\n\nelement = driver.find_element_by_xpath(\"//a[text()=' Load More.... ']\")\nwhile(element.is_displayed()):\n driver.execute_script(\"arguments[0].click();\", element)\n\ntable = driver.find_element_by_css_selector('table')\ntables2 = pd.read_html(table.get_attribute('outerHTML'))\ndriver.close()\n\noverview_table2 = tables2[0].dropna(how='all').dropna(axis='columns', how='all')\noverview_table2.drop_duplicates().reset_index(drop=True)\noverview_table2\n pandas selenium URL2 driver = webdriver.Firefox() PATH webdriver.Firefox(r\"C:\\WebDriver\\bin\") webdriver.Chrome(service=Service(executable_path=\"/path/to/chromedriver\")) driver.get(URL2) element = driver.find_element_by_xpath(\"//a[text()=' Load More.... ']\") element element.click() table tables2 <table> .close() list overview_table2" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20041271/" ]
74,668,152
<p>I am using a Stanford STANZA pipeline on some (italian) text.</p> <p>Problem I'm grappling with is that I need data from BOTH the Token and Word objects.</p> <p>While I'm able to access one or the other separately I'm not wrapping my head on how to get data from both in a single loop over the Document -&gt; Sentence</p> <p>Specifically I need both some Word data (such as lemma, upos and head) but I also need to know the corresponding start and end position, which in my understanding I can find in the token.start_char and token.end_char.</p> <p>Here's my code to test what I've achieved:</p> <pre><code>import stanza IN_TXT = '''Il paziente Rossi e' stato ricoverato presso il nostro reparto a seguito di accesso al pronto soccorso con diagnosi sospetta di aneurisma aorta addominale sottorenale. In data 12/11/2022 e' stato sottoposto ad asportazione dell'aneurisma con anastomosi aorto aortica con protesi in dacron da 20mm. Paziente dimesso in data odierna in condizioni stabili.''' stanza.download('it', verbose=False) it_nlp = stanza.Pipeline('it', processors='tokenize,lemma,pos,depparse,ner', verbose=False, use_gpu=False) it_doc = it_nlp(IN_TXT) # iterate through the Token objects T = 0 for token in it_doc.iter_tokens(): T += 1 token_id = 'T' + str((T)) token_start = token.start_char token_end = token.end_char token_text = token.text print(f&quot;{token_id}\t{token_start} {token_end} {token_text}&quot;) # iterate through Word objects print(*[f'word: {word.text}\t\t\tupos: {word.upos}\txpos: {word.xpos}\tfeats: {word.feats if word.feats else &quot;_&quot;}' for sent in it_doc.sentences for word in sent.words], sep='\n') </code></pre> <p>Here is the documentation of these objects: <a href="https://stanfordnlp.github.io/stanza/data_objects.html" rel="nofollow noreferrer">https://stanfordnlp.github.io/stanza/data_objects.html</a></p>
[ { "answer_id": 74669245, "author": "αԋɱҽԃ αмєяιcαη", "author_id": 7658985, "author_profile": "https://Stackoverflow.com/users/7658985", "pm_score": 2, "selected": false, "text": "import requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0'\n}\n\n\ndef main(url):\n params = {\n \"action\": \"stats\",\n \"league_id\": \"750\",\n \"limit\": \"300\",\n \"offset\": \"0\",\n \"part\": \"leagues\",\n \"season_id\": \"2022\",\n \"section\": \"football\",\n \"stats_type\": \"player\",\n \"tab\": \"overview\"\n }\n r = requests.get(url, headers=headers, params=params)\n soup = BeautifulSoup(r.text, 'lxml')\n goal = [(x['title'], *[i.get_text(strip=True) for i in x.find_all_next('td', limit=4)])\n for x in soup.select('a.player_link')]\n df = pd.DataFrame(\n goal, columns=['Name', 'Team', 'Matches', 'Goals', 'Time Played'])\n print(df)\n\n\nmain('https://www.mykhel.com/src/index.php')\n Name Team Matches Goals Time Played\n0 Jorge Pereyra Diaz Mumbai City 9 6 538 Mins\n1 Cleiton Silva SC East Bengal 8 5 707 Mins\n2 Abdenasser El Khayati Chennaiyin FC 5 4 231 Mins\n3 Lallianzuala Chhangte Mumbai City 9 4 737 Mins\n4 Nandhakumar Sekar Odisha 8 4 673 Mins\n.. ... ... ... ... ...\n268 Sarthak Golui SC East Bengal 6 0 402 Mins\n269 Ivan Gonzalez SC East Bengal 8 0 683 Mins\n270 Michael Jakobsen NorthEast United 8 0 676 Mins\n271 Pratik Chowdhary Jamshedpur FC 6 0 495 Mins\n272 Chungnunga Lal SC East Bengal 8 0 720 Mins\n\n[273 rows x 5 columns]\n" }, { "answer_id": 74669291, "author": "DiMithras", "author_id": 8489602, "author_profile": "https://Stackoverflow.com/users/8489602", "pm_score": 0, "selected": false, "text": "pip install selenium\n html5lib pip install html5lib BeautifulSoup4\n PATH import pandas as pd\nfrom selenium import webdriver\n\nURL2 = \"https://www.mykhel.com/football/indian-super-league-player-stats-l750/\"\n\ndriver = webdriver.Firefox()\ndriver.get(URL2)\n\nelement = driver.find_element_by_xpath(\"//a[text()=' Load More.... ']\")\nwhile(element.is_displayed()):\n driver.execute_script(\"arguments[0].click();\", element)\n\ntable = driver.find_element_by_css_selector('table')\ntables2 = pd.read_html(table.get_attribute('outerHTML'))\ndriver.close()\n\noverview_table2 = tables2[0].dropna(how='all').dropna(axis='columns', how='all')\noverview_table2.drop_duplicates().reset_index(drop=True)\noverview_table2\n pandas selenium URL2 driver = webdriver.Firefox() PATH webdriver.Firefox(r\"C:\\WebDriver\\bin\") webdriver.Chrome(service=Service(executable_path=\"/path/to/chromedriver\")) driver.get(URL2) element = driver.find_element_by_xpath(\"//a[text()=' Load More.... ']\") element element.click() table tables2 <table> .close() list overview_table2" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7800760/" ]
74,668,183
<p>I'm trying to clear values in the sheets that are present in a workbook. I have a list of all possible (valid) sheets, but I won't know which sheet is currently present in the workbook. So, I need to get the worksheets' name, see if it's valid and then clear its contents. Here's what I have so far:</p> <pre><code>Sub testclear() Dim validsheets() As Variant, sheetstoclear() As Variant Dim i as Integer, j As Integer, k As Integer, m as Integer validsheets() = Array (&quot;Sheet1&quot;, &quot;Sheet2&quot;, &quot;Sheet3&quot;, &quot;Sheet4&quot;, &quot;Sheet5&quot;) For i = 1 To Worksheets.count For j = LBound(validsheets) to UBound(validsheets) If Worksheets(i).Name = validsheets(J) Then sheetstoclear(k) = Worksheets(i).Name k = k +1 End If Next j Next i For m = LBound(sheetstoclear) to UBound(sheetstoclear) Sheets(sheetstoclear(m+1)).Cells.clear Next m End Sub </code></pre> <p>If I execute the above code, I get the following error -</p> <pre><code>Run-time error'9': Subscript out of range </code></pre>
[ { "answer_id": 74669245, "author": "αԋɱҽԃ αмєяιcαη", "author_id": 7658985, "author_profile": "https://Stackoverflow.com/users/7658985", "pm_score": 2, "selected": false, "text": "import requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0'\n}\n\n\ndef main(url):\n params = {\n \"action\": \"stats\",\n \"league_id\": \"750\",\n \"limit\": \"300\",\n \"offset\": \"0\",\n \"part\": \"leagues\",\n \"season_id\": \"2022\",\n \"section\": \"football\",\n \"stats_type\": \"player\",\n \"tab\": \"overview\"\n }\n r = requests.get(url, headers=headers, params=params)\n soup = BeautifulSoup(r.text, 'lxml')\n goal = [(x['title'], *[i.get_text(strip=True) for i in x.find_all_next('td', limit=4)])\n for x in soup.select('a.player_link')]\n df = pd.DataFrame(\n goal, columns=['Name', 'Team', 'Matches', 'Goals', 'Time Played'])\n print(df)\n\n\nmain('https://www.mykhel.com/src/index.php')\n Name Team Matches Goals Time Played\n0 Jorge Pereyra Diaz Mumbai City 9 6 538 Mins\n1 Cleiton Silva SC East Bengal 8 5 707 Mins\n2 Abdenasser El Khayati Chennaiyin FC 5 4 231 Mins\n3 Lallianzuala Chhangte Mumbai City 9 4 737 Mins\n4 Nandhakumar Sekar Odisha 8 4 673 Mins\n.. ... ... ... ... ...\n268 Sarthak Golui SC East Bengal 6 0 402 Mins\n269 Ivan Gonzalez SC East Bengal 8 0 683 Mins\n270 Michael Jakobsen NorthEast United 8 0 676 Mins\n271 Pratik Chowdhary Jamshedpur FC 6 0 495 Mins\n272 Chungnunga Lal SC East Bengal 8 0 720 Mins\n\n[273 rows x 5 columns]\n" }, { "answer_id": 74669291, "author": "DiMithras", "author_id": 8489602, "author_profile": "https://Stackoverflow.com/users/8489602", "pm_score": 0, "selected": false, "text": "pip install selenium\n html5lib pip install html5lib BeautifulSoup4\n PATH import pandas as pd\nfrom selenium import webdriver\n\nURL2 = \"https://www.mykhel.com/football/indian-super-league-player-stats-l750/\"\n\ndriver = webdriver.Firefox()\ndriver.get(URL2)\n\nelement = driver.find_element_by_xpath(\"//a[text()=' Load More.... ']\")\nwhile(element.is_displayed()):\n driver.execute_script(\"arguments[0].click();\", element)\n\ntable = driver.find_element_by_css_selector('table')\ntables2 = pd.read_html(table.get_attribute('outerHTML'))\ndriver.close()\n\noverview_table2 = tables2[0].dropna(how='all').dropna(axis='columns', how='all')\noverview_table2.drop_duplicates().reset_index(drop=True)\noverview_table2\n pandas selenium URL2 driver = webdriver.Firefox() PATH webdriver.Firefox(r\"C:\\WebDriver\\bin\") webdriver.Chrome(service=Service(executable_path=\"/path/to/chromedriver\")) driver.get(URL2) element = driver.find_element_by_xpath(\"//a[text()=' Load More.... ']\") element element.click() table tables2 <table> .close() list overview_table2" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5118106/" ]
74,668,211
<p>I want to call a component and render it once on button click. So if I pressed the button again it would render however does not constantly try and re render itself.</p> <p>At the moment, I am passing a function to the component and calling at the end of the useEffect. However this seems to not render anything.</p> <p>Here is what I have in my App.js</p> <pre><code>function App() { const [open, setOpen] = React.useState(false); const [dataFormat, setDataFormat] = React.useState(&quot;&quot;); const openData = () =&gt; { setOpen(true); }; const closeData = () =&gt;{ setOpen(false); } const changeDataFormat = (selectedOption) =&gt; { console.log(selectedOption); setDataFormat(selectedOption); }; return ( &lt;main className=&quot;App&quot;&gt; &lt;h1&gt;Film Management&lt;/h1&gt; &lt;SelectDataFormat changeDataFormat={changeDataFormat} /&gt; &lt;button onClick={openData}&gt;Show Films&lt;/button&gt; &lt;table border=&quot;1&quot;&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Title&lt;/th&gt; &lt;th&gt;Year&lt;/th&gt; &lt;th&gt;Director&lt;/th&gt; &lt;th&gt;Stars&lt;/th&gt; &lt;th&gt;Review&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt;{open &amp;&amp; &lt;FilmTableRows closeData={closeData} dataFormat={dataFormat} /&gt;}&lt;/tbody&gt; &lt;/table&gt; &lt;/main&gt; ); } </code></pre> <p>And this is the component I want to render</p> <pre><code> function FilmTableRows(props) { const convert = require(&quot;xml-js&quot;); const dataFormat = props.dataFormat; const [filmList, setFilmList] = useState([]); const baseURL = &quot;http://localhost:8080/FilmRestful/filmapi&quot;; const getJson = () =&gt; { let config = { headers: { &quot;data-type&quot;: &quot;json&quot;, &quot;Content-type&quot;: &quot;application/json&quot;, }, }; axios .get(baseURL, config) .then((res) =&gt; { const resData = res.data; setFilmList(resData); }) .catch((err) =&gt; {}); }; const getXML = () =&gt; { let config = { headers: { &quot;data-type&quot;: &quot;xml&quot;, &quot;Content-type&quot;: &quot;application/xml&quot;, // accept: &quot;application/xml&quot;, }, }; axios .get(baseURL, config) .then((res) =&gt; { let newList = []; const resData = JSON.parse( convert.xml2json(res.data, { compact: true, spaces: 2 }) ); resData.films.film.forEach((f) =&gt; { const film = new Film( f.id, f.title, f.year, f.director, f.stars, f.review ); newList = newList.concat(film); }); setFilmList(newList); }) .catch((err) =&gt; {}); }; const getString = () =&gt; { let config = { headers: { &quot;data-type&quot;: &quot;string&quot;, &quot;Content-type&quot;: &quot;application/html&quot;, // accept: &quot;application/xml&quot;, }, }; axios .get(baseURL, config) .then((res) =&gt; { setFilmList(res.data); }) .catch((err) =&gt; {}); }; useEffect(() =&gt; { switch (dataFormat.value) { case &quot;json&quot;: getJson(); break; case &quot;xml&quot;: getXML(); break; default: getString(); } }); const child = filmList.map((el, index) =&gt; { return ( &lt;tr key={index}&gt; &lt;td&gt;{el.title}&lt;/td&gt; &lt;td&gt;{el.year}&lt;/td&gt; &lt;td&gt;{el.director}&lt;/td&gt; &lt;td&gt;{el.stars}&lt;/td&gt; &lt;td&gt;{el.review}&lt;/td&gt; &lt;/tr&gt; ); }); return &lt;&gt;{filmList &amp;&amp; child}&lt;/&gt;; } </code></pre>
[ { "answer_id": 74669245, "author": "αԋɱҽԃ αмєяιcαη", "author_id": 7658985, "author_profile": "https://Stackoverflow.com/users/7658985", "pm_score": 2, "selected": false, "text": "import requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0'\n}\n\n\ndef main(url):\n params = {\n \"action\": \"stats\",\n \"league_id\": \"750\",\n \"limit\": \"300\",\n \"offset\": \"0\",\n \"part\": \"leagues\",\n \"season_id\": \"2022\",\n \"section\": \"football\",\n \"stats_type\": \"player\",\n \"tab\": \"overview\"\n }\n r = requests.get(url, headers=headers, params=params)\n soup = BeautifulSoup(r.text, 'lxml')\n goal = [(x['title'], *[i.get_text(strip=True) for i in x.find_all_next('td', limit=4)])\n for x in soup.select('a.player_link')]\n df = pd.DataFrame(\n goal, columns=['Name', 'Team', 'Matches', 'Goals', 'Time Played'])\n print(df)\n\n\nmain('https://www.mykhel.com/src/index.php')\n Name Team Matches Goals Time Played\n0 Jorge Pereyra Diaz Mumbai City 9 6 538 Mins\n1 Cleiton Silva SC East Bengal 8 5 707 Mins\n2 Abdenasser El Khayati Chennaiyin FC 5 4 231 Mins\n3 Lallianzuala Chhangte Mumbai City 9 4 737 Mins\n4 Nandhakumar Sekar Odisha 8 4 673 Mins\n.. ... ... ... ... ...\n268 Sarthak Golui SC East Bengal 6 0 402 Mins\n269 Ivan Gonzalez SC East Bengal 8 0 683 Mins\n270 Michael Jakobsen NorthEast United 8 0 676 Mins\n271 Pratik Chowdhary Jamshedpur FC 6 0 495 Mins\n272 Chungnunga Lal SC East Bengal 8 0 720 Mins\n\n[273 rows x 5 columns]\n" }, { "answer_id": 74669291, "author": "DiMithras", "author_id": 8489602, "author_profile": "https://Stackoverflow.com/users/8489602", "pm_score": 0, "selected": false, "text": "pip install selenium\n html5lib pip install html5lib BeautifulSoup4\n PATH import pandas as pd\nfrom selenium import webdriver\n\nURL2 = \"https://www.mykhel.com/football/indian-super-league-player-stats-l750/\"\n\ndriver = webdriver.Firefox()\ndriver.get(URL2)\n\nelement = driver.find_element_by_xpath(\"//a[text()=' Load More.... ']\")\nwhile(element.is_displayed()):\n driver.execute_script(\"arguments[0].click();\", element)\n\ntable = driver.find_element_by_css_selector('table')\ntables2 = pd.read_html(table.get_attribute('outerHTML'))\ndriver.close()\n\noverview_table2 = tables2[0].dropna(how='all').dropna(axis='columns', how='all')\noverview_table2.drop_duplicates().reset_index(drop=True)\noverview_table2\n pandas selenium URL2 driver = webdriver.Firefox() PATH webdriver.Firefox(r\"C:\\WebDriver\\bin\") webdriver.Chrome(service=Service(executable_path=\"/path/to/chromedriver\")) driver.get(URL2) element = driver.find_element_by_xpath(\"//a[text()=' Load More.... ']\") element element.click() table tables2 <table> .close() list overview_table2" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19213617/" ]
74,668,286
<p>I want to send image in <code>Socket</code>. How can I do that with <code>Ktor</code>?</p>
[ { "answer_id": 74668762, "author": "hassan bazai", "author_id": 14279755, "author_profile": "https://Stackoverflow.com/users/14279755", "pm_score": 0, "selected": false, "text": "val multipart = MultipartFormDataContent()\nval filePart = FileDataPart(\"filename\", \"image.jpg\")\nmultipart.addPart(filePart)\nval request = HttpRequestBuilder().apply {\n url(\"http://your-server-url\")\n method = HttpMethod.Post\n body = multipart\n}.build()\nval response = client.submitFormWithBinaryData(request, multipart)\n" }, { "answer_id": 74670112, "author": "Gowtham K K", "author_id": 9248098, "author_profile": "https://Stackoverflow.com/users/9248098", "pm_score": 2, "selected": true, "text": "var arr = File(path).inputStream().use { it.readBytes() }\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20626088/" ]
74,668,291
<p>I would like to be able to call class prototype methods using bracket notation, so that the method name can be decided at run time:</p> <pre class="lang-js prettyprint-override"><code>classInstance['methodName'](arg); </code></pre> <p>I am failing to do this properly with TypeScript:</p> <pre class="lang-js prettyprint-override"><code>class Foo { readonly ro: string = ''; constructor() {} fn(s: number) { console.log(s); } } const foo = new Foo(); const methods = ['fn']; foo['fn'](0) // Type 'undefined' cannot be used as an index type. foo[methods[0]](1); // This expression is not callable. // Not all constituents of type 'string | ((s: number) =&gt; void)' are callable. // Type 'string' has no call signatures. foo[methods[0] as keyof Foo](1); </code></pre> <p>The above example is in the <a href="https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&amp;noPropertyAccessFromIndexSignature=false#code/MYGwhgzhAEBiD29oG8BQ1oCcCmYAm8AdiAJ5bwBc0EALpgJaEDm0AvNAOQcDc60wRWpgCuwGvEwAKAJQoAvnwBmhSRCqFhAWwBG2TLOT9B8ENgB0IeE1XTu0BQtQDCtaIsRtohbAHc4iGV5nV01sGgALeDwYdgBtDmUOAF1eVHd4eMSkyQAGaVRUAHpC6AAVEgAHbE5hQjxsRUZsPA5+MEJCeBpoXWhhCGboSCHCaEZ6gA9oGkrzNMRY0IioiFicpOyARlsC4rLw+hhsCYqcKHoiMZhO7uAwEHBtUzMikoA5LqGHoxcaehphNhCDQYPBFNNZpwhIwWAAfaCSVTqLS6fRsAB80AAbvB6HhpK0wDg2g8wE85ntylUoXQYa1wsNOiSQNR6ExCGAAWcXulFmFItE1kkhjAANbYEhg-zwLa2IA" rel="nofollow noreferrer">TS Playground</a>.</p> <p>I think that I have a reasonable understanding of what the errors mean and why the string literal in <code>foo['fn'](0)</code> does not produce an error. However, I don't understand how to prevent the errors. I thought that I might be able to use <a href="https://www.typescriptlang.org/docs/handbook/utility-types.html#extracttype-union" rel="nofollow noreferrer">Extract</a> to build a type comprising of Function, but I've failed to do that.</p> <p>How can I produce a list of typed method names over which my code can iterate? And better, is it possible for the class to export such a list so that users of the class can easily access them?</p> <p><strong>Background Information</strong></p> <p>I have a <a href="https://playwright.dev/" rel="nofollow noreferrer">Playwright</a> test that needs to iterate over a list of methods from a <a href="https://playwright.dev/docs/pom" rel="nofollow noreferrer">Page Object Model</a>, producing a screenshot for each.</p>
[ { "answer_id": 74668762, "author": "hassan bazai", "author_id": 14279755, "author_profile": "https://Stackoverflow.com/users/14279755", "pm_score": 0, "selected": false, "text": "val multipart = MultipartFormDataContent()\nval filePart = FileDataPart(\"filename\", \"image.jpg\")\nmultipart.addPart(filePart)\nval request = HttpRequestBuilder().apply {\n url(\"http://your-server-url\")\n method = HttpMethod.Post\n body = multipart\n}.build()\nval response = client.submitFormWithBinaryData(request, multipart)\n" }, { "answer_id": 74670112, "author": "Gowtham K K", "author_id": 9248098, "author_profile": "https://Stackoverflow.com/users/9248098", "pm_score": 2, "selected": true, "text": "var arr = File(path).inputStream().use { it.readBytes() }\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/340355/" ]
74,668,300
<p>Julia REPL tells me that the output of</p> <pre><code>'c'+2 </code></pre> <p>is <code>'e': ASCII/Unicode U+0065 (category Ll: Letter, lowercase)</code> but that the output of</p> <pre><code>'c'+2-'a' </code></pre> <p>is <code>4</code>.</p> <p>I'm fine with the fact that Chars are identified as numbers via their ASCII code. But I'm confused about the type inference here: why is the first output a char and the second an integer?</p>
[ { "answer_id": 74668529, "author": "Bogumił Kamiński", "author_id": 1269567, "author_profile": "https://Stackoverflow.com/users/1269567", "pm_score": 4, "selected": true, "text": "julia> @which 'a' - 1\n-(x::T, y::Integer) where T<:AbstractChar in Base at char.jl:227\n\njulia> @which 'a' - 'b'\n-(x::AbstractChar, y::AbstractChar) in Base at char.jl:226\n Char Char 'a' - 1 Char 'a' - 'b' Char Char julia> 'a' + 'a'\nERROR: MethodError: no method matching +(::Char, ::Char)\n julia> 'a' + ('a' - 'a')\n'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)\n\njulia> 'a' + 'a' - 'a'\nERROR: MethodError: no method matching +(::Char, ::Char)\n Char Char julia> 2 - 'a'\nERROR: MethodError: no method matching -(::Int64, ::Char)\n c - '0' '0' + d" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3525251/" ]
74,668,309
<p>hello im trying to change a class name dynamiclly in react</p> <p>hello im trying to change a class name dynamiclly in react</p> <p>i am importing the classes from a realted css file like this</p> <pre><code>import classes from &quot;./Board.module.css&quot;; </code></pre> <p>and in my Board componnet i want to return a classname based on somthing i genarate it can be &quot;card&quot; &quot;card activate &quot; &quot;card disable&quot; and i have 3 class in my css file</p> <pre><code>.card{ do card somthing } .card.activate{ do card activate somthing } .card.disable{ do card disable somthing } </code></pre> <p>how can i do it becuase concateing dosent seem to be working</p> <p>edit: I am trying to to this:</p> <pre><code> import &quot;./Board.module.css&quot; const Card = (props) =&gt; { const itemClass = &quot;card&quot; + (props.item.stat ? &quot; active &quot; + props.item.stat : &quot;&quot;); return ( &lt;div className={itemClass} onClick={() =&gt; props.clickHandler(props.id)}&gt; &lt;label&gt;{props.item.content}&lt;/label&gt; &lt;/div&gt; ); }; export default Card; </code></pre> <p>and the CSS is :</p> <pre><code>.card.wrong{ background-color: red; } .card.correct{ background-color: green; } .card.active{ transform: rotateY(0); } </code></pre> <p>i am doing so that every time i click a card i change its class name to active and somthing and base on that i do a color but the class is undifined so i dont know what to do</p>
[ { "answer_id": 74668529, "author": "Bogumił Kamiński", "author_id": 1269567, "author_profile": "https://Stackoverflow.com/users/1269567", "pm_score": 4, "selected": true, "text": "julia> @which 'a' - 1\n-(x::T, y::Integer) where T<:AbstractChar in Base at char.jl:227\n\njulia> @which 'a' - 'b'\n-(x::AbstractChar, y::AbstractChar) in Base at char.jl:226\n Char Char 'a' - 1 Char 'a' - 'b' Char Char julia> 'a' + 'a'\nERROR: MethodError: no method matching +(::Char, ::Char)\n julia> 'a' + ('a' - 'a')\n'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)\n\njulia> 'a' + 'a' - 'a'\nERROR: MethodError: no method matching +(::Char, ::Char)\n Char Char julia> 2 - 'a'\nERROR: MethodError: no method matching -(::Int64, ::Char)\n c - '0' '0' + d" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15784054/" ]
74,668,311
<p>I have sales data that gives me dates in a bad format. Every new sale gets automatically added to the sheet. Looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> <th>Column B</th> <th>Column C</th> </tr> </thead> <tbody> <tr> <td>Order 1</td> <td>2022-12-02T02:09:37Z</td> <td>$1025.19</td> </tr> <tr> <td>Order 2</td> <td>2022-12-02T01:25:15Z</td> <td>$873.65</td> </tr> </tbody> </table> </div> <p>This will continue on for all sales. Now the date format is UTC for whatever reason and I can't adjust that, so within this formula I have to subtract 6 hours to get it to central time. I'm trying to create an auto-updating chart that shows an average day for 7 days, so I'm trying to do a sumif formula.</p> <p>Here's what I have on Sheet2:</p> <pre><code>=sumif(Sheet1!C:C,index(split((index(split(Sheet1!B:B,&quot;T&quot;),1)+index(split(left(Sheet1!B:B,19),&quot;T&quot;),2))-0.25,&quot;.&quot;),1),A1) </code></pre> <p>Where A1 is a single date. Testing this with one date and not the range shows that it does match. When I do the range, the total comes to 0, even though multiple different dates should match. What am I doing wrong?</p>
[ { "answer_id": 74668529, "author": "Bogumił Kamiński", "author_id": 1269567, "author_profile": "https://Stackoverflow.com/users/1269567", "pm_score": 4, "selected": true, "text": "julia> @which 'a' - 1\n-(x::T, y::Integer) where T<:AbstractChar in Base at char.jl:227\n\njulia> @which 'a' - 'b'\n-(x::AbstractChar, y::AbstractChar) in Base at char.jl:226\n Char Char 'a' - 1 Char 'a' - 'b' Char Char julia> 'a' + 'a'\nERROR: MethodError: no method matching +(::Char, ::Char)\n julia> 'a' + ('a' - 'a')\n'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)\n\njulia> 'a' + 'a' - 'a'\nERROR: MethodError: no method matching +(::Char, ::Char)\n Char Char julia> 2 - 'a'\nERROR: MethodError: no method matching -(::Int64, ::Char)\n c - '0' '0' + d" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11995921/" ]
74,668,354
<p>Have this so far, and essentially want to get there is something wrong with the position of <code>last_odd</code> as the compiler says the pop index is out of range?</p> <pre><code>def remove_last_odd(numbers): has_odd = False last_odd = 0 for num in range(len(numbers)): if numbers[num] % 2 == 1: has_odd = True last_odd = numbers[num] if has_odd: numbers.pop(last_odd) numbers = [1, 7, 2, 34, 8, 7, 2, 5, 14, 22, 93, 48, 76, 15, 6] </code></pre>
[ { "answer_id": 74668529, "author": "Bogumił Kamiński", "author_id": 1269567, "author_profile": "https://Stackoverflow.com/users/1269567", "pm_score": 4, "selected": true, "text": "julia> @which 'a' - 1\n-(x::T, y::Integer) where T<:AbstractChar in Base at char.jl:227\n\njulia> @which 'a' - 'b'\n-(x::AbstractChar, y::AbstractChar) in Base at char.jl:226\n Char Char 'a' - 1 Char 'a' - 'b' Char Char julia> 'a' + 'a'\nERROR: MethodError: no method matching +(::Char, ::Char)\n julia> 'a' + ('a' - 'a')\n'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)\n\njulia> 'a' + 'a' - 'a'\nERROR: MethodError: no method matching +(::Char, ::Char)\n Char Char julia> 2 - 'a'\nERROR: MethodError: no method matching -(::Int64, ::Char)\n c - '0' '0' + d" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11725381/" ]
74,668,364
<p>I need to write a JavaScript program where it validates input.</p> <p>Requirement:</p> <ul> <li>Input will have a specific prefix. (eg: --NAME--)</li> <li>After this prefix, there can be any characters. (eg: --NAME--any-name_wit#-any*_special_char@#$%)</li> <li>Minimum length of total input (or length of suffix) should be 50 (for example)</li> </ul> <p>I was able to write regex for the first two points, but I couldn't include the final point. here is what I have tried for the first two points.</p> <pre><code>input.match(^--NAME--(.*)$) </code></pre>
[ { "answer_id": 74668388, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 3, "selected": true, "text": "/^--NAME--.{42,}$/ .{42,} --NAME-- const regex = /^--NAME--.{42,}$/\n\nconsole.log(regex.test(\"--NAME--C$#V\"))\nconsole.log(regex.test(\"--NAME--C$#Vf34F#$f3ftbalc93h34vs#$3gfsddn;yu67u4g3dfvrv34f3f3ff\"))" }, { "answer_id": 74668525, "author": "Amadan", "author_id": 240443, "author_profile": "https://Stackoverflow.com/users/240443", "pm_score": 1, "selected": false, "text": "/^(?=.{50})--NAME--.*$/\n --NAME--" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13427720/" ]
74,668,410
<pre><code> &lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; package=&quot;com.example.flutterbluetooth&quot;&gt; &lt;uses-permission android:name=&quot;android.permission.BLUETOOTH&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.BLUETOOTH_ADMIN&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.ACCESS_COARSE_LOCATION&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.ACCESS_FINE_LOCATION&quot; /&gt; &lt;application android:label=&quot;flutterbluetooth&quot; android:name=&quot;${applicationName}&quot; android:icon=&quot;@mipmap/ic_launcher&quot;&gt; &lt;activity ... &lt;/activity&gt; &lt;meta-data android:name=&quot;flutterEmbedding&quot; android:value=&quot;2&quot; /&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>I am trying to get bluetooth permission in flutter. But I am getting the error in the title.</p>
[ { "answer_id": 74668388, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 3, "selected": true, "text": "/^--NAME--.{42,}$/ .{42,} --NAME-- const regex = /^--NAME--.{42,}$/\n\nconsole.log(regex.test(\"--NAME--C$#V\"))\nconsole.log(regex.test(\"--NAME--C$#Vf34F#$f3ftbalc93h34vs#$3gfsddn;yu67u4g3dfvrv34f3f3ff\"))" }, { "answer_id": 74668525, "author": "Amadan", "author_id": 240443, "author_profile": "https://Stackoverflow.com/users/240443", "pm_score": 1, "selected": false, "text": "/^(?=.{50})--NAME--.*$/\n --NAME--" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17906689/" ]
74,668,477
<p>looking to create a title style where the text breaks in-between the line, not sure if this would be considered a border or what. Any ideas?</p> <img src="https://i.stack.imgur.com/LQ7Ek.png"> <p>Haven't tried anything yet - have been playing around but can't figure it out</p>
[ { "answer_id": 74668388, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 3, "selected": true, "text": "/^--NAME--.{42,}$/ .{42,} --NAME-- const regex = /^--NAME--.{42,}$/\n\nconsole.log(regex.test(\"--NAME--C$#V\"))\nconsole.log(regex.test(\"--NAME--C$#Vf34F#$f3ftbalc93h34vs#$3gfsddn;yu67u4g3dfvrv34f3f3ff\"))" }, { "answer_id": 74668525, "author": "Amadan", "author_id": 240443, "author_profile": "https://Stackoverflow.com/users/240443", "pm_score": 1, "selected": false, "text": "/^(?=.{50})--NAME--.*$/\n --NAME--" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20675746/" ]
74,668,533
<p>I think I remember something like this from python, maybe it was the walrus operator? idk.</p> <p>but is there a way to set an attribute while returning the value? something like this:</p> <pre><code>class Foo { late String foo; Foo(); String setFoo() =&gt; foo := 'foo'; } f = Foo(); x = f.setFoo(); print(x); // 'foo' </code></pre>
[ { "answer_id": 74668388, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 3, "selected": true, "text": "/^--NAME--.{42,}$/ .{42,} --NAME-- const regex = /^--NAME--.{42,}$/\n\nconsole.log(regex.test(\"--NAME--C$#V\"))\nconsole.log(regex.test(\"--NAME--C$#Vf34F#$f3ftbalc93h34vs#$3gfsddn;yu67u4g3dfvrv34f3f3ff\"))" }, { "answer_id": 74668525, "author": "Amadan", "author_id": 240443, "author_profile": "https://Stackoverflow.com/users/240443", "pm_score": 1, "selected": false, "text": "/^(?=.{50})--NAME--.*$/\n --NAME--" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3071728/" ]
74,668,559
<p>JVM up from java 11 is using by Default G1.</p> <p>If i wont change anything by myself, will JVM make any improvements by it own and change for example to Serial if my app will be lacking resources. Or whether app is in the container or not? Or i have to manage it by myself?</p>
[ { "answer_id": 74668388, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 3, "selected": true, "text": "/^--NAME--.{42,}$/ .{42,} --NAME-- const regex = /^--NAME--.{42,}$/\n\nconsole.log(regex.test(\"--NAME--C$#V\"))\nconsole.log(regex.test(\"--NAME--C$#Vf34F#$f3ftbalc93h34vs#$3gfsddn;yu67u4g3dfvrv34f3f3ff\"))" }, { "answer_id": 74668525, "author": "Amadan", "author_id": 240443, "author_profile": "https://Stackoverflow.com/users/240443", "pm_score": 1, "selected": false, "text": "/^(?=.{50})--NAME--.*$/\n --NAME--" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1894980/" ]
74,668,561
<p>I know similar questions exist.</p> <p>I've gone through most of them but, so far, none of the solutions worked.</p> <p>Here is the context:</p> <p>Operating system: <strong>macOS Ventura 13.0.1</strong> (Intel processor)</p> <p>Here are some commands output:</p> <pre><code>$ ruby -v ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x86_64-darwin22] $ which ruby /Users/..../.rbenv/shims/ruby $ bundler -v Bundler version 2.3.26 $ which bundler /Users/..../.rbenv/shims/bundler </code></pre> <p>My <strong>~/.bash_profile</strong> and <strong>~/.zshrc</strong> contain:</p> <pre><code>export PATH=&quot;$HOME/.rbenv/bin:$PATH&quot; eval &quot;$(rbenv init -)&quot; export PATH=&quot;$HOME/.rbenv/shims:$PATH&quot; eval &quot;$(rbenv init -)&quot; </code></pre> <p>I know nothing about <strong>ruby</strong>, I'm using <code>rbenv</code> to manage <strong>ruby</strong> versions.</p> <p>I've done a similar setup on another macOS system but for some reason, on this system, nothing I have tried works.</p> <p>Any helps is appreciated.</p> <p>Thanks.</p>
[ { "answer_id": 74668388, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 3, "selected": true, "text": "/^--NAME--.{42,}$/ .{42,} --NAME-- const regex = /^--NAME--.{42,}$/\n\nconsole.log(regex.test(\"--NAME--C$#V\"))\nconsole.log(regex.test(\"--NAME--C$#Vf34F#$f3ftbalc93h34vs#$3gfsddn;yu67u4g3dfvrv34f3f3ff\"))" }, { "answer_id": 74668525, "author": "Amadan", "author_id": 240443, "author_profile": "https://Stackoverflow.com/users/240443", "pm_score": 1, "selected": false, "text": "/^(?=.{50})--NAME--.*$/\n --NAME--" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1552587/" ]
74,668,578
<p>I am running WSL2 and trying to get Git Credential Manager (GCM) set up so that I don't have to always copy-paste my Github Personal Access Token into my terminal. Once I added the credential manager I was unable to access my remote repositories, this is what my <code>.gitconfig</code> looks like:</p> <pre><code> 1 [user] 1 email = myemail@gmail.com 2 name = Name 3 [credential] 4 helper = /mnt/c/Program\\ Files/Git/mingw64/libexec/git-core/git-credential-wincred.exe </code></pre> <p>Now when I do a <code>git pull</code> on the remote repository Git is telling me that it cannot be found. It's not clear to me why GCM is blocking me now, but would you have any recommendations for next steps?</p>
[ { "answer_id": 74668388, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 3, "selected": true, "text": "/^--NAME--.{42,}$/ .{42,} --NAME-- const regex = /^--NAME--.{42,}$/\n\nconsole.log(regex.test(\"--NAME--C$#V\"))\nconsole.log(regex.test(\"--NAME--C$#Vf34F#$f3ftbalc93h34vs#$3gfsddn;yu67u4g3dfvrv34f3f3ff\"))" }, { "answer_id": 74668525, "author": "Amadan", "author_id": 240443, "author_profile": "https://Stackoverflow.com/users/240443", "pm_score": 1, "selected": false, "text": "/^(?=.{50})--NAME--.*$/\n --NAME--" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11460992/" ]
74,668,585
<p>I was wondering regarding Kubernetes HPA custom metrics HPA how it is calculated with targetAverageValue. If for example I’m using the metric that scales pods based on the number of nginx request then each pod now have is own specific metric and I was wondering if it takes each pod and check regarding its value or if it takes all of their metrics and divide this by the number of the pods?</p>
[ { "answer_id": 74668388, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 3, "selected": true, "text": "/^--NAME--.{42,}$/ .{42,} --NAME-- const regex = /^--NAME--.{42,}$/\n\nconsole.log(regex.test(\"--NAME--C$#V\"))\nconsole.log(regex.test(\"--NAME--C$#Vf34F#$f3ftbalc93h34vs#$3gfsddn;yu67u4g3dfvrv34f3f3ff\"))" }, { "answer_id": 74668525, "author": "Amadan", "author_id": 240443, "author_profile": "https://Stackoverflow.com/users/240443", "pm_score": 1, "selected": false, "text": "/^(?=.{50})--NAME--.*$/\n --NAME--" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11722396/" ]
74,668,605
<p>I'm using MudBlazor component library. In order to show loading on form buttons, the <a href="https://mudblazor.com/components/button#loading-button" rel="nofollow noreferrer">documentation</a> guides like this:</p> <pre><code>&lt;MudButton Disabled=&quot;@_processing&quot; OnClick=&quot;ProcessSomething&quot; Variant=&quot;Variant.Filled&quot; Color=&quot;Color.Primary&quot;&gt; @if (_processing) { &lt;MudProgressCircular Class=&quot;ms-n1&quot; Size=&quot;Size.Small&quot; Indeterminate=&quot;true&quot;/&gt; &lt;MudText Class=&quot;ms-2&quot;&gt;Processing&lt;/MudText&gt; } else { &lt;MudText&gt;Click me&lt;/MudText&gt; } &lt;/MudButton&gt; </code></pre> <p>Now since I'm doing this a lot, I wanted to wrap this logic inside another component.</p> <p>The following component does not do the job:</p> <pre><code>@inherits MudButton @code { bool _loading; [Parameter] public bool Loading { get =&gt; _loading; set { _loading = value; Disabled = value; } } [Parameter] public new RenderFragment ChildContent { get =&gt; base.ChildContent; set =&gt; base.ChildContent = ExtendContent(value); } private RenderFragment ExtendContent(RenderFragment baseContent) =&gt; __builder =&gt; { if (Loading) { &lt;MudProgressCircular Class=&quot;ms-n2&quot; Size=&quot;Size.Small&quot; Indeterminate=&quot;true&quot; /&gt; } @baseContent }; } </code></pre> <p>I get this error:</p> <blockquote> <p>The type '&lt;my_component&gt;' declares more than one parameter matching the name 'childcontent'. Parameter names are case-insensitive and must be unique.</p> </blockquote>
[ { "answer_id": 74668388, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 3, "selected": true, "text": "/^--NAME--.{42,}$/ .{42,} --NAME-- const regex = /^--NAME--.{42,}$/\n\nconsole.log(regex.test(\"--NAME--C$#V\"))\nconsole.log(regex.test(\"--NAME--C$#Vf34F#$f3ftbalc93h34vs#$3gfsddn;yu67u4g3dfvrv34f3f3ff\"))" }, { "answer_id": 74668525, "author": "Amadan", "author_id": 240443, "author_profile": "https://Stackoverflow.com/users/240443", "pm_score": 1, "selected": false, "text": "/^(?=.{50})--NAME--.*$/\n --NAME--" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19363672/" ]
74,668,608
<p>I have a JSON code like this:</p> <pre><code>final String response = await rootBundle.loadString('assets/Schools.json'); List data = await json.decode(response); print(data); /* output: [{ &quot;city&quot;: &quot;ISTANBUL&quot;, &quot;districty&quot;: &quot;Kagithane&quot;, &quot;name&quot;: &quot;Kagithane anadolu lisesi&quot;}, { &quot;city&quot;: &quot;ISTANBUL&quot;, &quot;districty&quot;: &quot;Sisli&quot;, &quot;name&quot;: &quot;Aziz Sancar anadolu lisesi&quot;}, { &quot;city&quot;: &quot;IZMIR&quot;, &quot;districty&quot;: &quot;Adalar&quot;, &quot;name&quot;: &quot;Kemal Sunal anadolu lisesi&quot;}, { &quot;city&quot;: &quot;ISTANBUL&quot;, &quot;districty&quot;: &quot;Bagcilar&quot;, &quot;name&quot;: &quot;Bagcilar Fen lisesi&quot;}, { &quot;city&quot;: &quot;ISTANBUL&quot;, &quot;districty&quot;: &quot;Kagithane&quot;, &quot;name&quot;: &quot;Kagithane Meslek lisesi&quot;}] */ </code></pre> <p>AI also wrote a model like this:</p> <pre><code>List &lt;School&gt; schools = []; List&lt;School&gt; allSchools() { return schools; } class School { String city; String districty; String name; School({required this.city, required this.name, required this.districty}); } </code></pre> <p>How can I export data from JSON to list? So I want to pass it like this:</p> <pre><code>List &lt;School&gt; schools = [ School(city: &quot;ISTANBUL&quot;, districty: &quot;Kagithane&quot;, name: &quot;Kagithane anadolu lisesi&quot;), School(city: &quot;ISTANBUL&quot;, districty: &quot;Sisli&quot;, name: &quot;Aziz Sancar anadolu lisesi&quot;), School(city: &quot;IZMIR&quot;, districty: &quot;ADALAR&quot;, name: &quot;Kemal Sunal anadolu lisesi&quot;), School(city: &quot;ISTANBUL&quot;, districty: &quot;BAGCILAR&quot;, name: &quot;Bagcilar Fen lisesi&quot;), School(city: &quot;ISTANBUL&quot;, districty: &quot;Kagithane&quot;, name: &quot;Kagithane Meslek lisesi&quot;) ]; </code></pre> <p>I appreciate your help in advance, thanks.</p>
[ { "answer_id": 74668388, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 3, "selected": true, "text": "/^--NAME--.{42,}$/ .{42,} --NAME-- const regex = /^--NAME--.{42,}$/\n\nconsole.log(regex.test(\"--NAME--C$#V\"))\nconsole.log(regex.test(\"--NAME--C$#Vf34F#$f3ftbalc93h34vs#$3gfsddn;yu67u4g3dfvrv34f3f3ff\"))" }, { "answer_id": 74668525, "author": "Amadan", "author_id": 240443, "author_profile": "https://Stackoverflow.com/users/240443", "pm_score": 1, "selected": false, "text": "/^(?=.{50})--NAME--.*$/\n --NAME--" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18003111/" ]
74,668,617
<p>Note, if it is single element I can extract but I need to extract all of them together.</p> <p>Hi I am trying to extract the text and link from a list of items from a page using Selenium and Java. I am able to extract all link text but facing issue to figure out the link text. The html code looks like below:</p> <pre><code>&lt;div class=&quot;col-12&quot;&gt; &lt;a href=&quot;/category/agricultural-products-service&quot;&gt; &lt;img src=&quot;/assets/images/icon/1.jpg&quot; alt=&quot;icon&quot; class=&quot;img-fluid category_icon&quot;&gt; &lt;h5 class=&quot;category_title&quot;&gt;Agricultural &lt;/h5&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class=&quot;col-12&quot;&gt; &lt;a href=&quot;/category/products-service&quot;&gt; &lt;img src=&quot;/assets/images/icon/7.jpg&quot; alt=&quot;icon&quot; class=&quot;img-fluid category_icon&quot;&gt; &lt;h5 class=&quot;category_title&quot;&gt;Products&lt;/h5&gt; &lt;/a&gt; &lt;/div&gt; </code></pre> <p>Using <code>h5</code> I can extract all the elements but I need to extract all href of those elements</p>
[ { "answer_id": 74668388, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 3, "selected": true, "text": "/^--NAME--.{42,}$/ .{42,} --NAME-- const regex = /^--NAME--.{42,}$/\n\nconsole.log(regex.test(\"--NAME--C$#V\"))\nconsole.log(regex.test(\"--NAME--C$#Vf34F#$f3ftbalc93h34vs#$3gfsddn;yu67u4g3dfvrv34f3f3ff\"))" }, { "answer_id": 74668525, "author": "Amadan", "author_id": 240443, "author_profile": "https://Stackoverflow.com/users/240443", "pm_score": 1, "selected": false, "text": "/^(?=.{50})--NAME--.*$/\n --NAME--" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20551699/" ]
74,668,626
<p>I am trying to control the input I took from a form with joi validation. The function <code>validateCampgrount</code> is a middleware to check it but when I try to write the next function it says next is not defined.*</p> <p>Where I am using <code>next()</code></p> <pre><code>const validateCampground = (req, res, next) =&gt; { const { error } = campgroundSchema.validate(req.body); if (error) { const msg = error.details.map((el) =&gt; el.message).join(&quot;,&quot;); throw new ExpressError(msg, 400); } else { next(); } }; </code></pre> <p>Error Message</p> <pre><code>next(); ^ ReferenceError: next is not defined </code></pre> <p>Where I am using function</p> <pre><code>app.post( &quot;/campgrounds&quot;, validateCampground( catchAsync(async (req, res, next) =&gt; { // if(!req.body.campground) throw new ExpressError('Invalid Data', 400) const campground = new Campground(req.body.campground); await campground.save(); res.redirect(`/campgrounds/${campground._id}`); }) ) ); </code></pre>
[ { "answer_id": 74668718, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 3, "selected": true, "text": "app.post() app.post(\"/campgrounds\", validateCampground, async (req, res, next) => {\n const campground = new Campground(req.body.campground);\n await campground.save();\n res.redirect(`/campgrounds/${campground._id}`);\n});\n" }, { "answer_id": 74668804, "author": "gentleslaughter", "author_id": 20676002, "author_profile": "https://Stackoverflow.com/users/20676002", "pm_score": 1, "selected": false, "text": "next() validateCampground() req res next catchAsync() catchAsync() catchAsync() app.post(\n \"/campgrounds\",\n catchAsync(async (req, res, next) => {\n validateCampground(req, res, next);\n\n // if(!req.body.campground) throw new ExpressError('Invalid Data', 400)\n const campground = new Campground(req.body.campground);\n await campground.save();\n res.redirect(`/campgrounds/${campground._id}`);\n })\n);\n validateCampground() catchAsync() next()" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15845644/" ]
74,668,627
<p>I had given a technical interview in which I have been asked to find intersection point of n link list. I could come up to find intersection point of 2 link list but couldn't extend it. Could someone help me reach the algorithm</p> <p>I tried to call the function to find integration point of 2 link list for every pair, but that didn't work.</p>
[ { "answer_id": 74668718, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 3, "selected": true, "text": "app.post() app.post(\"/campgrounds\", validateCampground, async (req, res, next) => {\n const campground = new Campground(req.body.campground);\n await campground.save();\n res.redirect(`/campgrounds/${campground._id}`);\n});\n" }, { "answer_id": 74668804, "author": "gentleslaughter", "author_id": 20676002, "author_profile": "https://Stackoverflow.com/users/20676002", "pm_score": 1, "selected": false, "text": "next() validateCampground() req res next catchAsync() catchAsync() catchAsync() app.post(\n \"/campgrounds\",\n catchAsync(async (req, res, next) => {\n validateCampground(req, res, next);\n\n // if(!req.body.campground) throw new ExpressError('Invalid Data', 400)\n const campground = new Campground(req.body.campground);\n await campground.save();\n res.redirect(`/campgrounds/${campground._id}`);\n })\n);\n validateCampground() catchAsync() next()" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8111583/" ]
74,668,631
<p>I have a CSV file that contains chemical matter names and some info.What I need to do is add new columns and write their formulas, molecular weights and count H,C,N,O,S atom numbers in each formula.I am stuck with the counting atom numbers part.I have the function related it but I don't know how to merge it and make code work.</p> <pre><code>import pandas as pd import urllib.request import copy import re df = pd.read_csv('AminoAcids.csv') def countAtoms(string, dict={}): curDict = copy.copy(dict) atoms = re.findall(&quot;[A-Z]{1}[a-z]*[0-9]*&quot;, string) for j in atoms: atomGroups = re.match('([A-Z]{1}[a-z]*)([0-9]*)', j) atom = atomGroups.group(1) number = atomGroups.group(2) try : curDict[atom] = curDict[atom] + int(number) except KeyError: try : curDict[atom] = int(number) except ValueError: curDict[atom] = 1 except ValueError: curDict[atom] = curDict[atom] + 1 return curDict df[&quot;Formula&quot;] = ['C3H7NO2', 'C6H14N4O2 ','C4H8N2O3','C4H7NO4 ', 'C3H7NO2S ','C5H9NO4','C5H10N2O3','C2H5NO2 ','C6H9N3O2', 'C6H13NO2','C6H13NO2','C6H14N2O2 ','C5H11NO2S ','C9H11NO2', 'C5H9NO2 ','C3H7NO3','C4H9NO3 ','C11H12N2O2 ','C9H11NO3 ','C5H11NO2'] df[&quot;Molecular Weight&quot;] = ['89.09','174.2','132.12', '133.1','121.16','147.13','146.14','75.07','155.15', '131.17','131.17','146.19','149.21','165.19','115.13', '105.09','119.12','204.22','181.19','117.15'] df[&quot;H&quot;] = 0 df[&quot;C&quot;] = 0 df[&quot;N&quot;] = 0 df[&quot;O&quot;] = 0 df[&quot;S&quot;] = 0 df.to_csv(&quot;AminoAcids.csv&quot;, index=False) print(df.to_string()) </code></pre>
[ { "answer_id": 74668718, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 3, "selected": true, "text": "app.post() app.post(\"/campgrounds\", validateCampground, async (req, res, next) => {\n const campground = new Campground(req.body.campground);\n await campground.save();\n res.redirect(`/campgrounds/${campground._id}`);\n});\n" }, { "answer_id": 74668804, "author": "gentleslaughter", "author_id": 20676002, "author_profile": "https://Stackoverflow.com/users/20676002", "pm_score": 1, "selected": false, "text": "next() validateCampground() req res next catchAsync() catchAsync() catchAsync() app.post(\n \"/campgrounds\",\n catchAsync(async (req, res, next) => {\n validateCampground(req, res, next);\n\n // if(!req.body.campground) throw new ExpressError('Invalid Data', 400)\n const campground = new Campground(req.body.campground);\n await campground.save();\n res.redirect(`/campgrounds/${campground._id}`);\n })\n);\n validateCampground() catchAsync() next()" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19828152/" ]
74,668,665
<p>This is a follow up on <a href="https://stackoverflow.com/questions/74667477/no-user-defined-conversion-when-using-standard-variants-and-visitor-pattern/74667677#74667677">No user defined conversion when using standard variants and visitor pattern</a></p> <p>I need to implement a <strong>templated version</strong> of the <a href="https://en.wikipedia.org/wiki/Visitor_pattern" rel="nofollow noreferrer">visitor pattern</a> as shown below, however it looks like the <code>accept</code> function has to be virtual which is not possible. Could you please help me?</p> <pre><code>#include &lt;variant&gt; #include &lt;iostream&gt; class Visitable //I need this to be non-templated (no template for Visitable!!): Otherwise I could use CRTP to solve this issue. { public: virtual ~Visitable() = default; template&lt;typename Visitor&gt; /*virtual*/ double accept(Visitor* visitor) //I can't do virtual here. { throw(&quot;I don't want to end up here&quot;); }; protected: Visitable() = default; }; struct DoubleVisitable : public Visitable { template&lt;typename Visitor&gt; double accept(Visitor* visitor) { return visitor-&gt;visit(*this); }; double m_val = 1.0; }; struct StringVisitable : public Visitable { template&lt;typename Visitor&gt; double accept(Visitor* visitor) { return visitor-&gt;visit(*this); }; double m_val = 0.0; }; template&lt;typename... args&gt; class Visitor { public: virtual ~Visitor() = default; virtual double visit(typename std::variant&lt;args...&gt; visitable) { auto op = [this](typename std::variant&lt;args...&gt; visitable) -&gt; double { return this-&gt;apply(visitable); }; return std::visit(std::ref(op), visitable); } virtual double apply(typename std::variant&lt;args...&gt; visitable) = 0; Visitor() = default; }; class SubVisitor : public Visitor&lt;DoubleVisitable, StringVisitable&gt; { public: virtual ~SubVisitor() = default; SubVisitor() : Visitor&lt;DoubleVisitable, StringVisitable&gt;() {}; virtual double apply(std::variant&lt;DoubleVisitable, StringVisitable&gt; visitable) override { return std::visit( [this](auto&amp;&amp; v){return process(v);}, visitable ); }; virtual double process(const StringVisitable&amp; visitable) { std::cout &lt;&lt; &quot;STRING HANDLED&quot; &lt;&lt; std::endl; return 0.0; } virtual double process(const DoubleVisitable&amp; visitable) { std::cout &lt;&lt; &quot;DOUBLE HANDLED&quot; &lt;&lt; std::endl; return 1.0; } }; int main(int argc, char* argv[]) { SubVisitor visitor; DoubleVisitable visitable; visitable.accept(&amp;visitor); //I want to be doing this: Visitable* doubleV = new DoubleVisitable(); doubleV-&gt;accept(&amp;visitor); delete doubleV; return 1; } </code></pre> <p>The code is here <a href="https://godbolt.org/z/4e4K54dbv" rel="nofollow noreferrer">Link</a>. Could you please help me make this not throw but collapses to the right child class <code>DoubleVisitable</code> or <code>StringVisitable</code>. It looks like I need virtual templated member function which is not possible as mentioned here <a href="https://stackoverflow.com/questions/2354210/can-a-class-member-function-template-be-virtual">Can a class member function template be virtual?</a></p>
[ { "answer_id": 74668896, "author": "lorro", "author_id": 6292621, "author_profile": "https://Stackoverflow.com/users/6292621", "pm_score": 2, "selected": false, "text": "template virtual std::variant<>" }, { "answer_id": 74670891, "author": "Rulle", "author_id": 1008794, "author_profile": "https://Stackoverflow.com/users/1008794", "pm_score": 2, "selected": true, "text": "Visitable Visitable template <typename ... T> class AcceptMethods {};\ntemplate <> class AcceptMethods<> {};\ntemplate <typename First, typename ... Rest>\nclass AcceptMethods<First, Rest...> : public AcceptMethods<Rest...> {\npublic:\n virtual double accept(First* ) = 0;\n virtual ~AcceptMethods() {}\n};\n\ntypedef AcceptMethods<SubVisitor> AllAcceptMethods;\n\nclass Visitable : public AllAcceptMethods\n{\npublic:\n virtual ~Visitable() = default;\n};\n SubVisitor AcceptMethods typedef AcceptMethods<A, B, C, D, AndSoOn> AllAcceptMethods; WithGenericAcceptMethod accept AcceptMethods acceptT template <typename This, typename ... T> class WithGenericAcceptMethod {};\ntemplate <typename This> class WithGenericAcceptMethod<This, AcceptMethods<>> : public Visitable {};\ntemplate <typename This, typename First, typename ... Rest>\nclass WithGenericAcceptMethod<This, AcceptMethods<First, Rest...>> : public WithGenericAcceptMethod<This, AcceptMethods<Rest...>> {\npublic:\n double accept(First* visitor) override {\n return ((This*)this)->template acceptT<First>(visitor);\n }\n virtual ~WithGenericAcceptMethod() {}\n};\n This WithGenericAcceptMethod acceptT struct DoubleVisitable : public WithGenericAcceptMethod<DoubleVisitable, AllAcceptMethods>\n{\n template<typename Visitor> \n double acceptT(Visitor* visitor) \n {\n return visitor->visit(*this);\n };\n\n double m_val = 1.0;\n};\n\nstruct StringVisitable : public WithGenericAcceptMethod<StringVisitable, AllAcceptMethods>\n{\n template<typename Visitor> \n double acceptT(Visitor* visitor) \n {\n return visitor->visit(*this);\n };\n double m_val = 0.0;\n};\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18718251/" ]
74,668,675
<p>I want to use a python script to call it in the <strong>pam_exec</strong> module.</p> <p>The <a href="https://stackoverflow.com/questions/53820496/using-my-own-python-script-to-authenticate-into-my-computer">first answer</a> in this question says that I can't use a python script and a PAM module together.</p> <blockquote> <p>First off - you cannot use python code as a PAM module, it has to be compiled code that satisfies certain interface requirements. See here for more info.</p> </blockquote> <p><a href="https://man7.org/linux/man-pages/man8/pam_exec.8.html" rel="nofollow noreferrer">Here</a> we are clearly given to understand that pam_exec is a PAM module.</p> <blockquote> <p>pam_exec - PAM module which calls an external command</p> </blockquote> <p>So is it possible to use python or not? (This also applies to my <a href="https://stackoverflow.com/questions/74668478/how-do-i-get-variables-from-a-python-script-that-are-visible-in-the-sh-script">previous question.</a>)</p>
[ { "answer_id": 74668694, "author": "August Vilakia", "author_id": 20314495, "author_profile": "https://Stackoverflow.com/users/20314495", "pm_score": 0, "selected": false, "text": "/etc/pam.d/common-password file." }, { "answer_id": 74669028, "author": "TrentP", "author_id": 1934800, "author_profile": "https://Stackoverflow.com/users/1934800", "pm_score": 2, "selected": true, "text": "/usr/lib64/security/pam_exec.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=d0c1dbb05c0689e3645193b45d3125d3b27b32ce, stripped\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15151531/" ]
74,668,679
<p>I have a script running that reformats borders on a variable range on the active sheet. I would like to have it cycle through other sheets in the same workbook, without those changes being visible to the user (ie - the GUI of the current screen stays as the only thing visible while the script runs).</p> <p>Currently each sheet is displayed as it loops and performs the reformat. How can I keep the initial sheet visible, and have the script run in the background? Obviously it is the use of &quot;.setActiveSheet&quot; and &quot;.getActiveSheet&quot; causing this.</p> <p>Still pretty new at all this, so any suggestions to otherwise cleanup/condense/speed up greatly appreciated.</p> <pre><code>function allBorders(){ var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); var ss = SpreadsheetApp.getActiveSheet(); var sheetname = ss.getSheetName(); var range; var headrows = 3; var lr = ss.getLastRow() //last row with data var lc = ss.getLastColumn() var mr = ss.getMaxRows() //max possible rows var ns = SpreadsheetApp.getActiveSpreadsheet().getNumSheets() Logger.log(&quot;Number of sheets: &quot;+ns) for (var i = 0; i &lt; ns; i++){ Logger.log(&quot;i value: &quot;+i) spreadsheet.setActiveSheet(spreadsheet.getSheets()[i]); sheetname = spreadsheet.getSheetName(); Logger.log(&quot;Sheetname: &quot;+sheetname) switch(sheetname){ case &quot;Openings&quot;: ss = SpreadsheetApp.getActiveSheet(); headrows = 6; lr = ss.getLastRow() //last row with data lc = ss.getLastColumn() mr = ss.getMaxRows() //max possible rows break; case &quot;My Trips&quot;: ss = SpreadsheetApp.getActiveSheet(); headrows = 6; lr = ss.getLastRow() //last row with data lc = ss.getLastColumn() mr = ss.getMaxRows() //max possible rows break; case &quot;All_Trips&quot;: ss = SpreadsheetApp.getActiveSheet(); headrows = 6; lr = ss.getLastRow() //last row with data lc = ss.getLastColumn() mr = ss.getMaxRows() //max possible rows break; default: break; } range = ss.getRange((1+headrows),1,mr,lc) //clear all rows below header range.setBorder(false,false,false,false,false,false); range = ss.getRange((1+headrows),1,(lr-headrows),lc) //border active rows range.setBorder(true, true, true, true, true, true); } } </code></pre>
[ { "answer_id": 74668694, "author": "August Vilakia", "author_id": 20314495, "author_profile": "https://Stackoverflow.com/users/20314495", "pm_score": 0, "selected": false, "text": "/etc/pam.d/common-password file." }, { "answer_id": 74669028, "author": "TrentP", "author_id": 1934800, "author_profile": "https://Stackoverflow.com/users/1934800", "pm_score": 2, "selected": true, "text": "/usr/lib64/security/pam_exec.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=d0c1dbb05c0689e3645193b45d3125d3b27b32ce, stripped\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20583572/" ]
74,668,687
<p>I have this problem. When I click on menù link, the page scroll but the menù remain open. This is my code-pen link (For some reason, codepen don't read che css color link, but don't worry about it) Js suggestions? I have just tried with on click function, but don't work.</p> <p>Thank you every body can help me!</p> <p>[Link Codepen][MyCodepen]</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>.nav-link{ font-weight: 300; } .text-menu{ font-weight: 200; } .navbar-toggler{ border: none; } .offcanvas-header{ background-color: #0c0c0c; padding-left: 2.5rem; color: #eab736; } .offcanvas-body{ background-color: #0c0c0c; } .nav-link{ font-size: 1.3rem; color: white; padding-left: 2rem; } .nav-link:hover{ font-size: 1.3rem; color: rgba(255, 255, 255, 0.20); padding-left: 2rem; } .text-menu{ font-size: 0.7rem; color: rgba(255, 255, 255, 0.20); padding-left: 2rem; } .icon-white{ color: white; font-size: 2rem; } .header-nav__social { padding-top: 3rem; list-style: none; display: inline-block; margin: 0; font-size: 1.2rem; } .header-nav__social li { margin-right: 12px; padding-left: 0; display: inline-block; } .header-nav__social li a { color: rgba(255, 255, 255, 0.20); } .header-nav__social li a:hover, .header-nav__social li a:focus { color: white; transition: all 0.5s; } .header-nav__social li:last-child { margin: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"&gt; &lt;title&gt;Example&lt;/title&gt; &lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"&gt; &lt;link href="https://getbootstrap.com/docs/5.2/assets/css/docs.css" rel="stylesheet"&gt; &lt;link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.2/font/bootstrap-icons.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;nav class="navbar fixed-top" id="mainNav"&gt; &lt;div class="container-fluid"&gt; &lt;a class="navbar-brand text-black js-scroll-trigger" href="#home"&gt;Brand name&lt;/a&gt; &lt;button class="navbar-toggler" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasNavbar" aria-controls="offcanvasNavbar"&gt; &lt;i class="bi bi-list icon-black"&gt;&lt;/i&gt; &lt;/button&gt; &lt;div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasNavbar" aria-labelledby="offcanvasNavbarLabel"&gt; &lt;div class="offcanvas-header"&gt; &lt;p class="offcanvas-title" id="offcanvasNavbarLabel"&gt;Menù&lt;/p&gt; &lt;button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas" aria-label="Close" &gt;&lt;/button&gt; &lt;/div&gt; &lt;div class="offcanvas-body"&gt; &lt;ul class="navbar-nav justify-content-end flex-grow-1 pe-3 text-white"&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link js-scroll-trigger" href="#home"&gt;Home&lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link js-scroll-trigger" href="#about"&gt;About&lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link js-scroll-trigger" href="#works"&gt;Gallery&lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link js-scroll-trigger" href="#contacts"&gt;Contacts&lt;/a&gt; &lt;/li&gt; &lt;p class="text-menu mt-5"&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quam minima beatae, repudiandae voluptatibus in suscipit dicta, facere consequuntur.&lt;/p&gt; &lt;/ul&gt; &lt;ul class="header-nav__social"&gt; &lt;li&gt; &lt;a href="#"&gt;&lt;i class="bi bi-facebook"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt;&lt;i class="bi bi-twitter"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt;&lt;i class="bi bi-instagram"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt;&lt;i class="bi bi-behance"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/nav&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>]<a href="https://codepen.io/edalbe/pen/YzvRxga" rel="nofollow noreferrer">1</a></p>
[ { "answer_id": 74668694, "author": "August Vilakia", "author_id": 20314495, "author_profile": "https://Stackoverflow.com/users/20314495", "pm_score": 0, "selected": false, "text": "/etc/pam.d/common-password file." }, { "answer_id": 74669028, "author": "TrentP", "author_id": 1934800, "author_profile": "https://Stackoverflow.com/users/1934800", "pm_score": 2, "selected": true, "text": "/usr/lib64/security/pam_exec.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=d0c1dbb05c0689e3645193b45d3125d3b27b32ce, stripped\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15910389/" ]
74,668,688
<p>Please I am trying to plot a scatter plot as shown in the attached image.</p> <p>I have tried the below code but it is not working. This is in python by the way.</p> <pre><code>hours = [n / 3600 for n in seconds] fig, ax = plt.subplots(figsize=(8, 6)) ## Your code here ax.plot(hours, fish_counts, marker=&quot;x&quot;) ax.set_xlabel(&quot;Hours since low tide&quot;) ax.set_ylabel(&quot;Jellyfish entering bay over 15 minutes&quot;) ax.legend()[![enter image description here][1]][1] </code></pre> <p>Attached image is how the output should look. Thank you. [1]: <a href="https://i.stack.imgur.com/5KQiz.png" rel="nofollow noreferrer">https://i.stack.imgur.com/5KQiz.png</a></p>
[ { "answer_id": 74668694, "author": "August Vilakia", "author_id": 20314495, "author_profile": "https://Stackoverflow.com/users/20314495", "pm_score": 0, "selected": false, "text": "/etc/pam.d/common-password file." }, { "answer_id": 74669028, "author": "TrentP", "author_id": 1934800, "author_profile": "https://Stackoverflow.com/users/1934800", "pm_score": 2, "selected": true, "text": "/usr/lib64/security/pam_exec.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=d0c1dbb05c0689e3645193b45d3125d3b27b32ce, stripped\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13863465/" ]
74,668,708
<p>So i am trying to add radio button on my survey form and the button and the text is completly in different positions so here is a picture of how it looks --&gt; <a href="https://i.stack.imgur.com/TKUQl.png" rel="nofollow noreferrer">enter image description here</a></p> <p>i tried display: inline; but still nothing changed</p>
[ { "answer_id": 74668694, "author": "August Vilakia", "author_id": 20314495, "author_profile": "https://Stackoverflow.com/users/20314495", "pm_score": 0, "selected": false, "text": "/etc/pam.d/common-password file." }, { "answer_id": 74669028, "author": "TrentP", "author_id": 1934800, "author_profile": "https://Stackoverflow.com/users/1934800", "pm_score": 2, "selected": true, "text": "/usr/lib64/security/pam_exec.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=d0c1dbb05c0689e3645193b45d3125d3b27b32ce, stripped\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20675973/" ]
74,668,716
<p>I'm trying to add a custom field in Word (in the shape { CUSTOM_FIELD } ) that uses the current page number and outputs its text representation (12 =&gt; twelve), but in multiple exotic (not supported) languages, which is why the built-in English variant (page * cardtext) isn't sufficient.</p> <p>The VBA code won't be a problem, but I need to know how to create a custom field.</p> <p>The field would be added to the footer template, before 100s of pages would be added programmatically.</p> <p>I tried using a custom DocProperty, but wasn't able to find a way to integrate the needed behavior. Another linked answer seems to be using the existing { PAGE } field, which wouldn't help, as I need to insert the new field (once only) into the footer template.</p>
[ { "answer_id": 74669462, "author": "Charles Kenyon", "author_id": 14133995, "author_profile": "https://Stackoverflow.com/users/14133995", "pm_score": 0, "selected": false, "text": "Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _\n PreserveFormatting:=False\nSelection.TypeText Text:=\"Page \\* CardText\"\n" }, { "answer_id": 74671965, "author": "jonsson", "author_id": 17523866, "author_profile": "https://Stackoverflow.com/users/17523866", "pm_score": 2, "selected": true, "text": "{ DOCVARIABLE \"LANG{ PAGE }\" }\n EN1 One\nEN2 Two\nEN3 Three\nFR1 Un\nFR2 Deux\nFR3 Trois\nDE1 Ein\nDE2 Zwei\nDE3 Drei\n \\* Cardtext ActiveDocument.Variables(\"EN1\").Value = \"One\"\n { DOCVARIABLE \"EN{ PAGE }\" }\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2890731/" ]
74,668,741
<p>I have a data file that consists of a calorie count. the calorie count it separated by each elf that owns it and how many calories are in each fruit. so this represents 3 elves</p> <pre><code>4323 4004 4070 1780 5899 1912 2796 5743 3008 1703 4870 5048 2485 1204 30180 33734 19662 </code></pre> <p>all the numbers next to each other are the same elf. the separated ones are seperate.</p> <p>i tried to detect the double line break like so</p> <pre><code>import java.util.*; import java.io.*; public class Main { public static void main(String [] args) throws FileNotFoundException { int[] elf = new int[100000]; int cnt = 0; Scanner input = new Scanner(new File(&quot;Elf.dat&quot;)); while(input.hasNext()) { elf[cnt] += input.nextInt(); if (input.next().equals(&quot;\n\n&quot;)); { cnt++; } } int big = elf[0]; for (int lcv = 0; lcv &lt; elf.length; lcv++) { if (big &lt; elf[lcv]) { big = elf[lcv]; } } System.out.println(big); } } </code></pre> <p>I'm trying this to detect the double line break</p> <pre><code>if (input.next().equals(&quot;\n\n&quot;)); </code></pre> <p>but its giving me errors. how would i detect it</p>
[ { "answer_id": 74669462, "author": "Charles Kenyon", "author_id": 14133995, "author_profile": "https://Stackoverflow.com/users/14133995", "pm_score": 0, "selected": false, "text": "Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _\n PreserveFormatting:=False\nSelection.TypeText Text:=\"Page \\* CardText\"\n" }, { "answer_id": 74671965, "author": "jonsson", "author_id": 17523866, "author_profile": "https://Stackoverflow.com/users/17523866", "pm_score": 2, "selected": true, "text": "{ DOCVARIABLE \"LANG{ PAGE }\" }\n EN1 One\nEN2 Two\nEN3 Three\nFR1 Un\nFR2 Deux\nFR3 Trois\nDE1 Ein\nDE2 Zwei\nDE3 Drei\n \\* Cardtext ActiveDocument.Variables(\"EN1\").Value = \"One\"\n { DOCVARIABLE \"EN{ PAGE }\" }\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20675966/" ]
74,668,764
<p>I have a function that prints the first multiples of a number (n) starting with zero and stopping at num_multiples, but it keeps printing out one too many multiples. I'm hoping someone can explain what I'm doing wrong so I can understand recursion a bit more.</p> <pre><code>def print_first_multiples(n, num_multiples): if num_multiples &lt; 0: return else: print_first_multiples(n, num_multiples - 1) print(n * num_multiples, end=' ') </code></pre> <p>for example, passing 5 as n and 10 as num_multiples, it should print: <code>0 5 10 15 20 25 30 35 40 45</code></p> <p>but is instead printing an extra &quot;50&quot; at the end.</p>
[ { "answer_id": 74668799, "author": "Yevhen Kuzmovych", "author_id": 4727702, "author_profile": "https://Stackoverflow.com/users/4727702", "pm_score": 0, "selected": false, "text": "if num_multiples < 0 num_multiples = 3 num_multiples=3 num_multiples=2 num_multiples=1 num_multiples=0 if num_multiples < 0 if num_multiples == 0" }, { "answer_id": 74668823, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 1, "selected": false, "text": "num_multiples def print_first_multiples(n, num_multiples): \n if num_multiples == 0:\n return\n else:\n print_first_multiples(n, num_multiples - 1)\n print(n * num_multiples, end=' ')\n\n\nprint_first_multiples(5, 10)\n num_multiples def print_first_multiples(n, num_multiples): \n if num_multiples == 0:\n return\n else:\n print_first_multiples(n, num_multiples - 1)\n print(n * (num_multiples-1), end=' ')\n\n\nprint_first_multiples(5, 10)\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,668,802
<p>I have a component where-in I need to fetch some data and render it. The component gets rendered initially. The problem I'm facing is when the handler function <code>switchDocumentType</code> is called after clicking the button for a particular type, the whole component gets unmounted/un-rendered.</p> <p>While debugging on my own I found this happens after <code>setDocumentType</code> is run inside event handler function. What is wrong in the below code snippet that could possibly cause this issue? I can see the <code>useEffect</code> is not going in infinite-loop as well.</p> <p>Code snippet:</p> <pre class="lang-js prettyprint-override"><code>import * as React from 'react'; const MyComponent = (props) =&gt; { const [documentType, setDocumentType] = React.useState('alpha'); const [documentData, setDocumentData] = React.useState(''); const types = ['alpha', 'beta', 'gamma']; React.useEffect(() =&gt; { myDataFetch('https://example.com/foo/?bar=123').then(async (response) =&gt; { const data = await response.json(); setDocumentData(data.terms); // html string const myDiv = document.getElementById('spacial-div'); myDiv.innerHTML = data; // need to render raw HTML inside a div }); }, [documentType]); const switchDocumentType = (type) =&gt; { setDocumentType(type); // send some analytics events }; const convertToPDF = () =&gt; { // uses documentData to generate PDF }; return ( &lt;div className=&quot;container-div&quot;&gt; {types.map((type) =&gt; { return ( &lt;button key={type} onClick={(type) =&gt; switchDocumentType(type)}&gt; {type} &lt;/button&gt; ); })} &lt;div id=&quot;special-div&quot; /&gt; &lt;/div&gt; ); }; export default MyComponent; </code></pre>
[ { "answer_id": 74668799, "author": "Yevhen Kuzmovych", "author_id": 4727702, "author_profile": "https://Stackoverflow.com/users/4727702", "pm_score": 0, "selected": false, "text": "if num_multiples < 0 num_multiples = 3 num_multiples=3 num_multiples=2 num_multiples=1 num_multiples=0 if num_multiples < 0 if num_multiples == 0" }, { "answer_id": 74668823, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 1, "selected": false, "text": "num_multiples def print_first_multiples(n, num_multiples): \n if num_multiples == 0:\n return\n else:\n print_first_multiples(n, num_multiples - 1)\n print(n * num_multiples, end=' ')\n\n\nprint_first_multiples(5, 10)\n num_multiples def print_first_multiples(n, num_multiples): \n if num_multiples == 0:\n return\n else:\n print_first_multiples(n, num_multiples - 1)\n print(n * (num_multiples-1), end=' ')\n\n\nprint_first_multiples(5, 10)\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10977818/" ]
74,668,808
<p>I am implementing a simple arithmetic calculation on a server which includes add, sub, mul and Div, for the simplicity purposes no other operations are being done and also no parentheses &quot;()&quot; to change the precedence. The input I will have for the client is something like &quot;1-2.1+3.6*5+10/2&quot;(no dot product, 2.1 or 3.6 is a floating number). I have created a function to send the operands and operators but at a time I can send udp message of 1 computation in the format of (num1,op,num2)</p> <pre><code>import struct import socket ip = &quot;127.0.0.1&quot; port = 11200 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) #creating socket print(&quot;Do Ctrl+c to exit the program !!&quot;) def sendRecv( num1, op, num2): #sending udp message with num1,op and num #receiving udp message with the result as res res = s.recieve() return res sendRecv(in1, in_op, in2) </code></pre> <p>I was able to split the operators and operands using the regular split and separated them like</p> <p>str = ['1', '-', '2.1', '+', '3.6', '*', '5', '+', '10', '/', '2']</p> <p>since the multiplication and the division takes precedence over addition and subtraction (3.6, *, 5) should be sent first followed by the division, I am trying to write a while loop with while(len(str&gt;0)), I am trying to understand how I can send multiplication first, store the intermediate result in the list itself and do a recurring function till all the computations are sent through message. I am not allowed to perform ny operation on client side, I can only send values to &quot;SendRecv()&quot;. Any suggestions or ideas on how to proceed will be helpful.</p> <p>Thanks in advance</p>
[ { "answer_id": 74668799, "author": "Yevhen Kuzmovych", "author_id": 4727702, "author_profile": "https://Stackoverflow.com/users/4727702", "pm_score": 0, "selected": false, "text": "if num_multiples < 0 num_multiples = 3 num_multiples=3 num_multiples=2 num_multiples=1 num_multiples=0 if num_multiples < 0 if num_multiples == 0" }, { "answer_id": 74668823, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 1, "selected": false, "text": "num_multiples def print_first_multiples(n, num_multiples): \n if num_multiples == 0:\n return\n else:\n print_first_multiples(n, num_multiples - 1)\n print(n * num_multiples, end=' ')\n\n\nprint_first_multiples(5, 10)\n num_multiples def print_first_multiples(n, num_multiples): \n if num_multiples == 0:\n return\n else:\n print_first_multiples(n, num_multiples - 1)\n print(n * (num_multiples-1), end=' ')\n\n\nprint_first_multiples(5, 10)\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12229319/" ]
74,668,816
<p>I am wondering whether there is a difference in performance between these two if-statements:</p> <pre class="lang-cs prettyprint-override"><code>if(myObject != null &amp;&amp; myObject.someBoolean) { // do something } if (myObject?.someBoolean ?? false) { // do something } </code></pre> <p>If there is a difference in performance, in favor of which approach and why?</p> <p><strong>Edit:</strong> This is not a bottleneck in my application, I am not trying to over-optimize, I am simply curious.</p>
[ { "answer_id": 74669235, "author": "August Vilakia", "author_id": 20314495, "author_profile": "https://Stackoverflow.com/users/20314495", "pm_score": -1, "selected": false, "text": "?. if (obj != null) if (obj != null)\n{\n int x = obj.Value;\n}\n obj Value obj int x = obj?.Value;\n Value obj" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11257746/" ]
74,668,849
<p>I need to select 3 random events from the database by a certain parameter (their type). How can I do this?</p> <p>Right now, I use foreach to select everything, but I need to select 3 objects and select them randomly.</p> <pre><code>@foreach (Event entity in Model) { @if (entity.Type==&quot;Концерт&quot;) { &lt;img class=&quot;slider&quot; src=&quot;~/images/@entity.TitleImagePath&quot;/&gt; } } </code></pre>
[ { "answer_id": 74669235, "author": "August Vilakia", "author_id": 20314495, "author_profile": "https://Stackoverflow.com/users/20314495", "pm_score": -1, "selected": false, "text": "?. if (obj != null) if (obj != null)\n{\n int x = obj.Value;\n}\n obj Value obj int x = obj?.Value;\n Value obj" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20183977/" ]
74,668,853
<p>I am trying to use the fold operation on a range returned by <code>byLine()</code>. I want the lambda which is passed to fold to be a multi-line function. I have searched google and read the documentation, but cannot find a description as to what the signature of the function should be. I surmize that one of the pair is the accumulated sum and one is the current element. This is what I have but it will not build</p> <pre><code> auto sum = File( fileName, &quot;r&quot; ) .byLine .fold!( (a, b) { auto len = b.length; return a + len; }); </code></pre> <p>The error I get back from dmd is:</p> <pre><code>main.d(22): Error: no property `fold` for `(File(null, null)).this(fileName, &quot;r&quot;).byLine(Flag.no, '\n')` of type `std.stdio.File.ByLineImpl!(char, char)` </code></pre> <p>So my question is two fold:</p> <ol> <li>Is my use of fold in this case valid?</li> <li>How do I pass a curley brace lambda to fold?</li> </ol> <p>I have tried searching google and reading the dlang documentation for fold. All documentation uses the shortcut lambda syntax <code>(a, b) =&gt; a + b</code>.</p>
[ { "answer_id": 74668971, "author": "Akshay", "author_id": 3881787, "author_profile": "https://Stackoverflow.com/users/3881787", "pm_score": 3, "selected": true, "text": "import std.algorithm.iteration : fold;\n\n// Import the byLine function from the File module\nimport std.stdio.File : byLine;\n\nvoid main() {\n string fileName = \"some/file/name.txt\";\n auto sum = File(fileName, \"r\")\n .byLine\n .fold!((a, b) => {\n // You can define the lambda function using the `{}` syntax\n auto len = b.length;\n return a + len;\n })(0); // Initialize the fold with a value of 0\n}\n" }, { "answer_id": 74669910, "author": "Commodore63", "author_id": 524644, "author_profile": "https://Stackoverflow.com/users/524644", "pm_score": 0, "selected": false, "text": "module example;\n\nimport std.stdio;\nimport std.algorithm.iteration : fold;\n\nvoid main() {\n string fileName = \"test1.txt\";\n auto sum = File(fileName, \"r\")\n .byLine\n .fold!( (a, b) {\n // You can define the lambda function using the `{}` syntax\n auto len = b.length;\n return a + len;\n })(0); // Initialize the fold with a value of 0\n}\n\n" }, { "answer_id": 74672160, "author": "Steven Schveighoffer", "author_id": 6268422, "author_profile": "https://Stackoverflow.com/users/6268422", "pm_score": 1, "selected": false, "text": "fold fold!(fun)(range, seed) result result = fun(result, x) result fold!(fun)(range) 0 fold" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/524644/" ]
74,668,854
<p>I have this kind of code</p> <pre><code>typedef struct { int x; int y; } Test; Test* getTest(int *length) { Test *toReturn = malloc(sizeof(Test)); // Some operations with realloc return toReturn; } void printTest(Test *arrTest, int length) { for(int i = 0; i &lt; length; i++) { // Some operations } } int main() { int testlength = 0; Test *myTest = getTest(&amp;testlength); printTest(myTest, testLength) // Gives random numbers } </code></pre> <p>Don't know why it gives random numbers, when I'm in the main tho (the whole code) it does not give these kinds of errors</p>
[ { "answer_id": 74668942, "author": "Akshay", "author_id": 3881787, "author_profile": "https://Stackoverflow.com/users/3881787", "pm_score": -1, "selected": false, "text": "typedef struct {\n int x;\n int y;\n} Test;\n\nTest* getTest(int *length) {\n Test *toReturn = malloc(sizeof(Test));\n // Some operations with realloc\n return toReturn;\n}\n\nvoid printTest(Test *arrTest, int *length) {\n // Loop through the array and print the values\n for(int i = 0; i < *length; i++) {\n printf(\"Test[%d]: x = %d, y = %d\\n\", i, arrTest[i].x, arrTest[i].y);\n }\n}\n\nint main() {\n int testlength = 0;\n Test *myTest = getTest(&testlength);\n // Pass a pointer to the testLength variable to the printTest function\n printTest(myTest, &testLength) // Should not give random numbers\n}\n" }, { "answer_id": 74669004, "author": "MZM", "author_id": 20551381, "author_profile": "https://Stackoverflow.com/users/20551381", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n\ntypedef struct {\n int x;\n int y;\n} Test;\n\nTest* getTest(int *length) {\n Test *toReturn = (Test *)malloc(sizeof(Test));\n // Some operations with realloc\n return toReturn;\n}\n\nvoid printTest(Test *arrTest, int length) {\n printf(\"%d \", length);\n for(int i = 0; i < length; i++) {\n // Some operations\n }\n}\n\nint main() {\n int tlen = 0;\n Test *myTest = getTest(&tlen);\n printTest(myTest, tlen); // Gives random numbers\n printf(\"....Exit....\");\n return 0;\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16881135/" ]
74,668,873
<p>in my C99-programme I want to use pseudo-random numbers between 0 an 1. Unfortunatly, my programme always generates a first number that is almost identical. It just steps up ever so slightly every time I rerun my programme.</p> <p>This is the relevant part of my programme:</p> <pre><code>srand(time(NULL)); for(int i = 0; i &lt; 10; i++){ float a = (float)rand()/RAND_MAX; printf(&quot;%f\n&quot;,a); </code></pre> <p>And here are the results of two Iterations with a time difference of below 10 seconds:</p> <pre><code>0.717103 0.357464 0.903628 0.271930 0.327478 0.917489 0.231215 0.026307 0.135259 0.290941 0.717221 0.330531 0.237708 0.151682 0.318986 0.201876 0.936884 0.209277 0.324705 0.311334 </code></pre> <p>I tried to generate completely different numbers no matter how many I computed before, but the first is alway close to the same.</p>
[ { "answer_id": 74668942, "author": "Akshay", "author_id": 3881787, "author_profile": "https://Stackoverflow.com/users/3881787", "pm_score": -1, "selected": false, "text": "typedef struct {\n int x;\n int y;\n} Test;\n\nTest* getTest(int *length) {\n Test *toReturn = malloc(sizeof(Test));\n // Some operations with realloc\n return toReturn;\n}\n\nvoid printTest(Test *arrTest, int *length) {\n // Loop through the array and print the values\n for(int i = 0; i < *length; i++) {\n printf(\"Test[%d]: x = %d, y = %d\\n\", i, arrTest[i].x, arrTest[i].y);\n }\n}\n\nint main() {\n int testlength = 0;\n Test *myTest = getTest(&testlength);\n // Pass a pointer to the testLength variable to the printTest function\n printTest(myTest, &testLength) // Should not give random numbers\n}\n" }, { "answer_id": 74669004, "author": "MZM", "author_id": 20551381, "author_profile": "https://Stackoverflow.com/users/20551381", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n\ntypedef struct {\n int x;\n int y;\n} Test;\n\nTest* getTest(int *length) {\n Test *toReturn = (Test *)malloc(sizeof(Test));\n // Some operations with realloc\n return toReturn;\n}\n\nvoid printTest(Test *arrTest, int length) {\n printf(\"%d \", length);\n for(int i = 0; i < length; i++) {\n // Some operations\n }\n}\n\nint main() {\n int tlen = 0;\n Test *myTest = getTest(&tlen);\n printTest(myTest, tlen); // Gives random numbers\n printf(\"....Exit....\");\n return 0;\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20676050/" ]
74,668,885
<p>I wish to create a custom calculator where the user defines two parameters and a function using a GUI and when they click on calculate it executes their user defined function passing the two parameters.</p> <pre class="lang-py prettyprint-override"><code>argument1 = IntSlider( … ) argument2 = IntSlider( … ) userDefinedFunction = TextArea( … ) calculateButton = Button ( … ) calculateButton.on_click(userDefinedFunction) </code></pre> <p>So that let’s say somebody defines :</p> <ol> <li><code>argument1 = 3</code></li> <li><code>argument2 = 4</code></li> <li><code>userDefinedFunction = def udf(arg1,arg2): return arg1**2 + arg2**2</code></li> </ol> <p>Would return 25 as <code>3*3 + 4*4 = 25</code>.</p>
[ { "answer_id": 74668942, "author": "Akshay", "author_id": 3881787, "author_profile": "https://Stackoverflow.com/users/3881787", "pm_score": -1, "selected": false, "text": "typedef struct {\n int x;\n int y;\n} Test;\n\nTest* getTest(int *length) {\n Test *toReturn = malloc(sizeof(Test));\n // Some operations with realloc\n return toReturn;\n}\n\nvoid printTest(Test *arrTest, int *length) {\n // Loop through the array and print the values\n for(int i = 0; i < *length; i++) {\n printf(\"Test[%d]: x = %d, y = %d\\n\", i, arrTest[i].x, arrTest[i].y);\n }\n}\n\nint main() {\n int testlength = 0;\n Test *myTest = getTest(&testlength);\n // Pass a pointer to the testLength variable to the printTest function\n printTest(myTest, &testLength) // Should not give random numbers\n}\n" }, { "answer_id": 74669004, "author": "MZM", "author_id": 20551381, "author_profile": "https://Stackoverflow.com/users/20551381", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n\ntypedef struct {\n int x;\n int y;\n} Test;\n\nTest* getTest(int *length) {\n Test *toReturn = (Test *)malloc(sizeof(Test));\n // Some operations with realloc\n return toReturn;\n}\n\nvoid printTest(Test *arrTest, int length) {\n printf(\"%d \", length);\n for(int i = 0; i < length; i++) {\n // Some operations\n }\n}\n\nint main() {\n int tlen = 0;\n Test *myTest = getTest(&tlen);\n printTest(myTest, tlen); // Gives random numbers\n printf(\"....Exit....\");\n return 0;\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13224380/" ]
74,668,891
<p>so i'm taking a python class right now and am struggling with dictionaries at the moment. my assignment is simple, i have to create a fucntion &quot;letter_positions&quot; which will return a dictionary of all positions of a letter in a string.</p> <p>for example</p> <pre><code>positions = letter_positions(&quot;fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's&quot;) positions['e'] </code></pre> <p>should return</p> <pre><code>{4, 5, 8, 14, 16, 43, 67, 83, 88, 89, 97, 121, 122, 141, 142} </code></pre> <p>so i'm pretty much done with the assignment but i'm running into the issue that i have all values (positions) assigned to the keys (letters) as a list.</p> <p>here's my code:</p> <pre><code>def letter_positions(n): answer = {} n = n.lower() x = 0 for letter in n: if letter.isalpha(): if letter not in answer: answer[letter] = [] answer[letter].append(x) x += 1 return answer </code></pre> <p>so instead of getting a dictionary of positions i'm getting a list of positions.</p> <pre><code>positions = letter_positions(&quot;fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's&quot;) positions['e'] </code></pre> <p>returns</p> <pre><code> [4, 5, 8, 14, 16, 43, 67, 83, 88, 89, 97, 121, 122, 141, 142] </code></pre> <p>is there any way for me to simply change the list into a dictionary or am i approaching this in a completely wrong way?</p>
[ { "answer_id": 74669560, "author": "Daniel Hao", "author_id": 10760768, "author_profile": "https://Stackoverflow.com/users/10760768", "pm_score": 1, "selected": false, "text": "from collections import defaultdict\n\ndef letter_index(sentence):\n answer = defaultdict(list)\n \n for idx, ch in enumerate(sentence):\n answer[ch].append(idx)\n \n return answer\n \npositions = letter_index(\"fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's\")\n\nch = 'e'\n\nfor k, v in positions.items():\n if k == ch:\n print(k, v)\n\n# e [4, 5, 8, 14, 16, 43, 67, 83, 88, 89, 97, 121, 122, 141, 142]\n" }, { "answer_id": 74670343, "author": "virxen", "author_id": 12860757, "author_profile": "https://Stackoverflow.com/users/12860757", "pm_score": 0, "selected": false, "text": "def letter_positions(n):\n answer = {}\n n = n.lower()\n x = 0\n for letter in n:\n if letter.isalpha():\n answer[letter] = answer.get(letter,[])#if there is not the key letter add it as key with value an empty list\n answer[letter].append(x)\n x=x+1\n return answer\npositions = letter_positions(\"fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's\")\nprint(positions['e'])\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20676037/" ]
74,668,899
<p>why this is not working?? anything else i need to doo??? (note: i don't want to call any <code>boot</code> method from <code>model</code>). in models its working fine with <code>booted</code> method</p> <pre class="lang-php prettyprint-override"><code>// route Route::get('/tests', function () { return Test::find(1)-&gt;update([ 'name' =&gt; Str::random(6) ]); }); // models namespace App\Models; use App\Http\Traits\Sortable; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Test extends Model { use HasFactory; use Sortable; protected $guarded = [&quot;id&quot;]; } // traits namespace App\Http\Traits; trait Sortable { protected static function bootSort() { static::updated(function ($model) { dd(&quot;updated&quot;, $model-&gt;toArray()); }); static::updating(function ($model) { dd(&quot;updating&quot;, $model-&gt;toArray()); }); static::saving(function ($model) { dd(&quot;saving&quot;, $model-&gt;toArray()); }); static::saved(function ($model) { dd(&quot;saved&quot;, $model-&gt;toArray()); }); } } </code></pre>
[ { "answer_id": 74669308, "author": "kundefine", "author_id": 10691416, "author_profile": "https://Stackoverflow.com/users/10691416", "pm_score": 1, "selected": false, "text": "boot Sortable bootSortable // route\nRoute::get('/tests', function () {\n\n return Test::find(1)->update([\n 'name' => Str::random(6)\n ]);\n});\n\n// models\nnamespace App\\Models;\n\nuse App\\Http\\Traits\\Sortable;\nuse Illuminate\\Database\\Eloquent\\Factories\\HasFactory;\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass Test extends Model\n{\n use HasFactory;\n use Sortable;\n protected $guarded = [\"id\"];\n}\n\n// traits\nnamespace App\\Http\\Traits;\n\ntrait Sortable\n{\n // before\n protected static function bootSort()\n // after fix\n protected static function bootSortable()\n {\n static::updated(function ($model) {\n dd(\"updated\", $model->toArray());\n });\n static::updating(function ($model) {\n dd(\"updating\", $model->toArray());\n });\n static::saving(function ($model) {\n dd(\"saving\", $model->toArray());\n });\n static::saved(function ($model) {\n dd(\"saved\", $model->toArray());\n });\n }\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10691416/" ]
74,668,908
<p>I have a dataset like below:</p> <pre><code>data=&quot;&quot;&quot;vJrwpWtwJgWrhcsFMMfFFhFp jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL PmmdzqPrVvPwwTWBwg wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn ttgJtRGJQctTZtZT CrZsJsPPZsGzwwsLwLmpwMDw&quot;&quot;&quot; </code></pre> <p>These are separate lines. Now, I want to group the data in a <code>set of 3 rows</code> and find the intersecting character in those lines. For example, <code>r</code> is the common character in the first group and <code>Z</code> is the typical character in the second group. So, below is my code:</p> <pre><code>lines = [] for i in range(len(data.splitlines())): lines.append(data[i]) for j in lines: new_line = [k for k in j[i] if k in j[i + 1]] print(new_line) </code></pre> <p>It gives me a string index out-of-range error.</p> <pre><code>new_line = [k for k in j[i] if k in j[i + 1]] IndexError: string index out of range </code></pre>
[ { "answer_id": 74669308, "author": "kundefine", "author_id": 10691416, "author_profile": "https://Stackoverflow.com/users/10691416", "pm_score": 1, "selected": false, "text": "boot Sortable bootSortable // route\nRoute::get('/tests', function () {\n\n return Test::find(1)->update([\n 'name' => Str::random(6)\n ]);\n});\n\n// models\nnamespace App\\Models;\n\nuse App\\Http\\Traits\\Sortable;\nuse Illuminate\\Database\\Eloquent\\Factories\\HasFactory;\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass Test extends Model\n{\n use HasFactory;\n use Sortable;\n protected $guarded = [\"id\"];\n}\n\n// traits\nnamespace App\\Http\\Traits;\n\ntrait Sortable\n{\n // before\n protected static function bootSort()\n // after fix\n protected static function bootSortable()\n {\n static::updated(function ($model) {\n dd(\"updated\", $model->toArray());\n });\n static::updating(function ($model) {\n dd(\"updating\", $model->toArray());\n });\n static::saving(function ($model) {\n dd(\"saving\", $model->toArray());\n });\n static::saved(function ($model) {\n dd(\"saved\", $model->toArray());\n });\n }\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9363181/" ]
74,668,915
<p>I have a scenario where I have a git branch (b), based off of develop.</p> <p>I then made changes to branch (b) and pushed to remote (b)</p> <p>Some other developer made a PR and had their code merged into develop.</p> <p>I then pull the changes from remote/develop and rebased my local branch (b) onto develop</p> <p>I then make more changes to my local branch (b)</p> <p>When I commit and push my changes, I get a rejected error: [! [rejected] feature/b-&gt; feature/b (non-fast-forward) error: failed to push some refs to 'gitlab' hint: Updates were rejected because the tip of your current branch is behind]</p> <p>What I normally tend to do is to do a --force push</p> <p>But I'm wondering if this is the right approach?</p>
[ { "answer_id": 74669016, "author": "gentleslaughter", "author_id": 20676002, "author_profile": "https://Stackoverflow.com/users/20676002", "pm_score": -1, "selected": false, "text": "git reset git pull --force git reset git pull" }, { "answer_id": 74669105, "author": "Rusly - Mices", "author_id": 1645312, "author_profile": "https://Stackoverflow.com/users/1645312", "pm_score": -1, "selected": false, "text": "--force --force --force" }, { "answer_id": 74669319, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": -1, "selected": false, "text": "b develop b b b b develop b develop" }, { "answer_id": 74669418, "author": "Caleb", "author_id": 643383, "author_profile": "https://Stackoverflow.com/users/643383", "pm_score": 1, "selected": false, "text": "force develop" }, { "answer_id": 74678062, "author": "moses mccabe", "author_id": 12712741, "author_profile": "https://Stackoverflow.com/users/12712741", "pm_score": -1, "selected": false, "text": "git branch\n git checkout \"branch-name\"\n git add .\ngit commit -m \"enter you commit message here\"\n git merge \"branch-name\"\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8556469/" ]
74,668,934
<p>I wrote this code in C and it shows me this error. I don't know what it is or how can I solve it.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;math.h&gt; int main() { int z; scanf(&quot;%d&quot;, &amp;z); double x1 , x2 , x3 , x4 , y1 , y2 , y3 , y4; for(int i = 0;i&lt;=z;i++) { scanf(&quot;%lf %lf&quot;, &amp;x1 , &amp;y1); scanf(&quot;%lf %lf&quot;, &amp;x2 , &amp;y2); scanf(&quot;%lf %lf&quot;, &amp;x3 , &amp;y3); scanf(&quot;%lf %lf&quot;, &amp;x4 , &amp;y4); double tule_parekhat1 = sqrt(pow(y2-y1, 2) + (pow(x2-x1), 2)); double tule_parekhat2 = sqrt(pow(y3-y2, 2) + (pow(x3-x2), 2)); double tule_parekhat3 = sqrt(pow(y4-y1, 2) + (pow(x4-x1), 2)); double tule_parekhat4 = sqrt(pow(y4-y3, 2) + (pow(x4-x3), 2)); } } </code></pre> <p>I get the error (line 15, error : too few arguments to function 'pow')</p> <p>I don't know what it is.</p>
[ { "answer_id": 74669042, "author": "m3ow", "author_id": 20474278, "author_profile": "https://Stackoverflow.com/users/20474278", "pm_score": 1, "selected": false, "text": "double tule_parekhat1 = sqrt(pow(y2-y1, 2) + (pow(x2-x1), 2));\n (pow(x2-x1), 2)) double tule_parekhat1 = sqrt(pow(y2-y1, 2) + pow(x2-x1, 2));\n pow x2-x1" }, { "answer_id": 74669102, "author": "Serge Ballesta", "author_id": 3545273, "author_profile": "https://Stackoverflow.com/users/3545273", "pm_score": 1, "selected": true, "text": "double tule_parekhat1 = sqrt(pow(y2-y1, 2) + (pow(x2-x1), 2));\n pow pow(y2-y1, 2) (pow(x2-x1), 2)\n pow x2-x1 , pow(x2-x1, 2) pow double tule_parekhat1 = sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1));\n...\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20676147/" ]
74,668,944
<p>I want to build a program that takes the amount of rainfall each day for 7 days and then output the total and average rainfall for those days.</p> <p>Initially, I've created a while loop to take the input:</p> <pre class="lang-py prettyprint-override"><code>rainfall = 0 rain = [] counter = 1 while counter &lt; 8: rain.append(rainfall) rainfall = float(input(&quot;Enter the rainfall of day {0}: &quot;.format(counter))) counter += 1 print(rain) </code></pre> <p>But the output that is generated is not what I expected:</p> <pre class="lang-py prettyprint-override"><code>[0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0] </code></pre> <p>It will enter a 0 as first value and then omit the last input (here the input is 1 to 7 as an example)</p>
[ { "answer_id": 74669042, "author": "m3ow", "author_id": 20474278, "author_profile": "https://Stackoverflow.com/users/20474278", "pm_score": 1, "selected": false, "text": "double tule_parekhat1 = sqrt(pow(y2-y1, 2) + (pow(x2-x1), 2));\n (pow(x2-x1), 2)) double tule_parekhat1 = sqrt(pow(y2-y1, 2) + pow(x2-x1, 2));\n pow x2-x1" }, { "answer_id": 74669102, "author": "Serge Ballesta", "author_id": 3545273, "author_profile": "https://Stackoverflow.com/users/3545273", "pm_score": 1, "selected": true, "text": "double tule_parekhat1 = sqrt(pow(y2-y1, 2) + (pow(x2-x1), 2));\n pow pow(y2-y1, 2) (pow(x2-x1), 2)\n pow x2-x1 , pow(x2-x1, 2) pow double tule_parekhat1 = sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1));\n...\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4212022/" ]
74,668,972
<p>I have simple istream_view and then I am trying to use ranges::copy on result.</p> <pre><code>auto t = ranges::istream_view&lt;int&gt;(is); ranges::copy(t, std::back_inserter(v)); </code></pre> <p><a href="https://godbolt.org/z/1ro9x3nh1" rel="nofollow noreferrer">Live example on godbolt</a></p> <p>GCC does everything ok, clang fails with error:</p> <pre><code>error: no matching function for call to object of type 'const std::ranges::__copy_fn' ranges::copy(t, std::back_inserter(v)); </code></pre> <p>Probably it is because istream_view is moveonly view.</p> <p>How to argue in this case who is right?</p> <p>Standard C++20 [range.istream.overview] have similar example:</p> <pre><code>auto ints = istringstream{&quot;0 1 2 3 4&quot;}; ranges::copy(ranges::istream_view&lt;int&gt;(ints), ostream_iterator&lt;int&gt;{cout, &quot;-&quot;}); </code></pre> <p>Which also fails in clang (and this is definitely a bug but I am not sure that reason is the same for both compile-time errors).</p>
[ { "answer_id": 74669169, "author": "IM_AG", "author_id": 921330, "author_profile": "https://Stackoverflow.com/users/921330", "pm_score": 1, "selected": false, "text": "std::ranges::copy std::ranges::copy std::ranges::istream_view std::ranges::copy std::ranges::istream_view std::ranges::istream_view std::move std::ranges::copy std::ranges::copy std::ranges::copy" }, { "answer_id": 74669201, "author": "August Vilakia", "author_id": 20314495, "author_profile": "https://Stackoverflow.com/users/20314495", "pm_score": 0, "selected": false, "text": "ranges::copy() ranges::istream_view std::vector ranges::copy() ranges::copy() ranges::istream_view ranges::copy() ranges::istream_view std::vector std::copy() ranges::copy() auto t = ranges::istream_view<int>(is);\nstd::copy(std::begin(t), std::end(t), std::back_inserter(v));\n std::copy() ranges::copy() ranges::copy()" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1595323/" ]
74,668,974
<p>I am working on a homework problem which is similar to this post:- <a href="https://stackoverflow.com/questions/5859519/quickest-algorithm-to-find-at-most-n-2-1-liars-in-n-people">Quickest algorithm to find at most (n/2)-1 liars in n people</a></p> <p>The problem is given below:- This problem is couched in terms of liars and truth tellers, but it has real applications in identifying which components of a complex system are good (functioning correctly) and which are faulty. Assume we have a community of n people and we know an integer number t &lt; n/2, which has the property that most t of the n people are liars. This does not say that there actually are t liars, but only that there are at most t liars.</p> <p>The difference in my case is that the truth-tellers are always truthful and correct and a liar always speaks a lie.</p> <p>We will identify the liars in the community by successively picking pairs of people, (X, Y) say, and asking X: Is Y a liar?. The response is either “yes” or “no&quot;;</p> <p>What is the optimum algorithm(minimum number of steps) to find all the liars?</p>
[ { "answer_id": 74669088, "author": "David G", "author_id": 701092, "author_profile": "https://Stackoverflow.com/users/701092", "pm_score": 2, "selected": true, "text": "const int MAX_N = 100;\nint n;\nint t;\nbool people[MAX_N]; // True if the person is a liar, false otherwise\n\nvoid findLiars(void)\n{\n // Select a random person and ask them about the next person\n int p = rand() % n;\n if (people[p] != people[(p + 1) % n])\n {\n // The next person is a liar\n people[(p + 1) % n] = true;\n }\n else\n {\n // The first person is a liar\n people[p] = true;\n }\n\n // Select the first non-liar and ask them about the next non-liar\n for (int i = 0; i < n; i++)\n {\n if (!people[i])\n {\n p = i;\n break;\n }\n }\n\n while (true)\n {\n // Find the next non-liar\n int q = (p + 1) % n;\n while (people[q])\n {\n q = (q + 1) % n;\n }\n\n if (people[p] != people[q])\n {\n // The next non-liar is a liar\n people[q] = true;\n }\n else\n {\n // The first non-liar is a liar\n people[p] = true;\n break;\n }\n\n p = q;\n }\n}\n findLiars people" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74668974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19572566/" ]
74,669,001
<p>I'm trying to get common characters from two separate vectors.</p> <p>Example:</p> <pre><code>x &lt;- c(&quot;abcde&quot;) y &lt;- c(&quot;efghi&quot;) df &lt;- data.frame(x, y) </code></pre> <p>Desired output</p> <pre><code> x y z abcde efghi e lmnop uvmxw m </code></pre> <p>I've tried something like this, but it is a bad result:</p> <pre><code>df |&gt; mutate(m = unique(x, y)) </code></pre> <p>If there are multiple matches, returning a list would work great.</p>
[ { "answer_id": 74669128, "author": "Eric", "author_id": 7091646, "author_profile": "https://Stackoverflow.com/users/7091646", "pm_score": 2, "selected": false, "text": "str_intersect <- function(s1,s2) {\n paste0(intersect(strsplit(s1,\"\")[[1]],strsplit(s2,\"\")[[1]]),collapse = \"\")\n}\n\nx <- c(\"abcde\",\"abc\")\ny <- c(\"efghi\",\"b\")\ndf <- data.frame(x, y)\n\nlibrary(dplyr)\ndf %>%\n rowwise() %>%\n mutate(m = str_intersect(x,y))\n" }, { "answer_id": 74669251, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 2, "selected": false, "text": "> df$z <- intersect(unlist(strsplit(df$x, \"\")), unlist(strsplit(df$y, \"\")))\n> df\n x y z\n1 abcde efghi e\n2 lmnop uvmxw m\n structure(list(x = c(\"abcde\", \"lmnop\"), y = c(\"efghi\", \"uvmxw\"\n), z = c(\"e\", \"m\")), row.names = c(NA, -2L), class = \"data.frame\")\n" }, { "answer_id": 74669354, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "[] ^ pattern str_remove_all library(stringr)\nlibrary(dplyr)\ndf %>%\n mutate(z = str_remove_all(x, sprintf(\"[^%s]\", y)))\n x y z\n1 abcde efghi e\n2 lmnop uvmxw m\n df1 %>%\n mutate(z = str_remove_all(x, sprintf(\"[^%s]\", y)))\n x y z\n1 abcde efghi e\n2 lmnop ovmxw mo\n df <- structure(list(x = c(\"abcde\", \"lmnop\"), y = c(\"efghi\", \"uvmxw\"\n)), row.names = c(NA, -2L), class = \"data.frame\")\ndf1 <- structure(list(x = c(\"abcde\", \"lmnop\"), y = c(\"efghi\", \"ovmxw\"\n)), class = \"data.frame\", row.names = c(NA, -2L))\n" }, { "answer_id": 74669394, "author": "Chris Ruehlemann", "author_id": 8039978, "author_profile": "https://Stackoverflow.com/users/8039978", "pm_score": 2, "selected": false, "text": "tidyverse stringr library(stringr)\ndf %>%\n mutate(\n # convert `x` to alternation pattern:\n y1 = str_replace_all(x, \"(?<=.)(?=.)\", \"|\"),\n # which of `y1` are contained in `x`?:\n match = str_extract_all(y, y1)\n ) \n x y y1 match\n1 abcde efghi a|b|c|d|e e\n2 lmnop ovmxw l|m|n|o|p o, m\n y1 %>% select(-y1) x <- c(\"abcde\", \"lmnop\")\ny <- c(\"efghi\", \"ovmxw\")\ndf <- data.frame(x, y)\n" }, { "answer_id": 74670519, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 0, "selected": false, "text": "strsplit intersect strintr <- \\(x) {\n o <- apply(x, 1, \\(.) do.call(intersect, strsplit(., '')))\n dx <- dim(x)[1]\n if (!identical(o, dx)) length(o) <- dx\n o[lengths(o) == 0L] <- NA_character_\n if (any(lengths(o) > 1L)) lapply(o, as.list) else o\n}\n cols <- c('x', 'y')\n within within(df1, foo <- strintr(df1[cols]))\n# x y foo\n# 1 abcde efghi e\nwithin(df2, foo <- strintr(df2[cols]))\n# x y foo\n# 1 abcde efghi e\n# 2 lmnop uvmxw m\nwithin(df3, foo <- strintr(df3[cols]))\n# x y foo\n# 1 abcde defghi d, e\n# 2 lmnop uvmxw m\nwithin(df4, foo <- strintr(df4[cols]))\n# x y foo\n# 1 abcde xyz <NA>\n# 2 lmnop xyz <NA>\nwithin(df5, foo <- strintr(df5[cols]))\n# x y foo\n# 1 abcde defghi d, e\n# 2 lmnop xyz NA\n $ df3$foo <- strintr(df3[cols])\ndf3\n# x y foo\n# 1 abcde defghi d, e\n# 2 lmnop uvmxw m\n dplyr::mutate dplyr::mutate(df3, fo=strintr(df3[cols]))\n# x y fo\n# 1 abcde defghi d, e\n# 2 lmnop uvmxw m\n transform df1 <- data.frame(x=\"abcde\", y=\"efghi\")\ndf2 <- data.frame(x=c('abcde', 'lmnop'),\n y=c('efghi', 'uvmxw'))\ndf3 <- data.frame(x=c('abcde', 'lmnop'),\n y=c('defghi', 'uvmxw'))\ndf4 <- data.frame(x=c('abcde', 'lmnop'),\n y=c('xyz', 'xyz'))\ndf5 <- data.frame(x=c('abcde', 'lmnop'),\n y=c('defghi', 'xyz'))\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13874036/" ]
74,669,005
<p>i keep getting <code>404 image not found</code> when viewing the uploaded image on my project but the image is there. im using laravel's <code>asset()</code> helper to retrieve the image. the url in chrome shows <code>http://127.0.0.1:8000/images/dU8oaVTAwQyTor86jvDtdGKvE7H3MYkHZuUG60gH.png</code> and ive already done <code>php artisan storage:link</code>. any help is greatly appreciated.</p>
[ { "answer_id": 74669128, "author": "Eric", "author_id": 7091646, "author_profile": "https://Stackoverflow.com/users/7091646", "pm_score": 2, "selected": false, "text": "str_intersect <- function(s1,s2) {\n paste0(intersect(strsplit(s1,\"\")[[1]],strsplit(s2,\"\")[[1]]),collapse = \"\")\n}\n\nx <- c(\"abcde\",\"abc\")\ny <- c(\"efghi\",\"b\")\ndf <- data.frame(x, y)\n\nlibrary(dplyr)\ndf %>%\n rowwise() %>%\n mutate(m = str_intersect(x,y))\n" }, { "answer_id": 74669251, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 2, "selected": false, "text": "> df$z <- intersect(unlist(strsplit(df$x, \"\")), unlist(strsplit(df$y, \"\")))\n> df\n x y z\n1 abcde efghi e\n2 lmnop uvmxw m\n structure(list(x = c(\"abcde\", \"lmnop\"), y = c(\"efghi\", \"uvmxw\"\n), z = c(\"e\", \"m\")), row.names = c(NA, -2L), class = \"data.frame\")\n" }, { "answer_id": 74669354, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "[] ^ pattern str_remove_all library(stringr)\nlibrary(dplyr)\ndf %>%\n mutate(z = str_remove_all(x, sprintf(\"[^%s]\", y)))\n x y z\n1 abcde efghi e\n2 lmnop uvmxw m\n df1 %>%\n mutate(z = str_remove_all(x, sprintf(\"[^%s]\", y)))\n x y z\n1 abcde efghi e\n2 lmnop ovmxw mo\n df <- structure(list(x = c(\"abcde\", \"lmnop\"), y = c(\"efghi\", \"uvmxw\"\n)), row.names = c(NA, -2L), class = \"data.frame\")\ndf1 <- structure(list(x = c(\"abcde\", \"lmnop\"), y = c(\"efghi\", \"ovmxw\"\n)), class = \"data.frame\", row.names = c(NA, -2L))\n" }, { "answer_id": 74669394, "author": "Chris Ruehlemann", "author_id": 8039978, "author_profile": "https://Stackoverflow.com/users/8039978", "pm_score": 2, "selected": false, "text": "tidyverse stringr library(stringr)\ndf %>%\n mutate(\n # convert `x` to alternation pattern:\n y1 = str_replace_all(x, \"(?<=.)(?=.)\", \"|\"),\n # which of `y1` are contained in `x`?:\n match = str_extract_all(y, y1)\n ) \n x y y1 match\n1 abcde efghi a|b|c|d|e e\n2 lmnop ovmxw l|m|n|o|p o, m\n y1 %>% select(-y1) x <- c(\"abcde\", \"lmnop\")\ny <- c(\"efghi\", \"ovmxw\")\ndf <- data.frame(x, y)\n" }, { "answer_id": 74670519, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 0, "selected": false, "text": "strsplit intersect strintr <- \\(x) {\n o <- apply(x, 1, \\(.) do.call(intersect, strsplit(., '')))\n dx <- dim(x)[1]\n if (!identical(o, dx)) length(o) <- dx\n o[lengths(o) == 0L] <- NA_character_\n if (any(lengths(o) > 1L)) lapply(o, as.list) else o\n}\n cols <- c('x', 'y')\n within within(df1, foo <- strintr(df1[cols]))\n# x y foo\n# 1 abcde efghi e\nwithin(df2, foo <- strintr(df2[cols]))\n# x y foo\n# 1 abcde efghi e\n# 2 lmnop uvmxw m\nwithin(df3, foo <- strintr(df3[cols]))\n# x y foo\n# 1 abcde defghi d, e\n# 2 lmnop uvmxw m\nwithin(df4, foo <- strintr(df4[cols]))\n# x y foo\n# 1 abcde xyz <NA>\n# 2 lmnop xyz <NA>\nwithin(df5, foo <- strintr(df5[cols]))\n# x y foo\n# 1 abcde defghi d, e\n# 2 lmnop xyz NA\n $ df3$foo <- strintr(df3[cols])\ndf3\n# x y foo\n# 1 abcde defghi d, e\n# 2 lmnop uvmxw m\n dplyr::mutate dplyr::mutate(df3, fo=strintr(df3[cols]))\n# x y fo\n# 1 abcde defghi d, e\n# 2 lmnop uvmxw m\n transform df1 <- data.frame(x=\"abcde\", y=\"efghi\")\ndf2 <- data.frame(x=c('abcde', 'lmnop'),\n y=c('efghi', 'uvmxw'))\ndf3 <- data.frame(x=c('abcde', 'lmnop'),\n y=c('defghi', 'uvmxw'))\ndf4 <- data.frame(x=c('abcde', 'lmnop'),\n y=c('xyz', 'xyz'))\ndf5 <- data.frame(x=c('abcde', 'lmnop'),\n y=c('defghi', 'xyz'))\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3089096/" ]
74,669,017
<p><em><a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2021&amp;gist=d69eee7953a6392d12c81a77a21cf15a" rel="nofollow noreferrer">Playground</a></em></p> <p>I have the following type definition:</p> <pre class="lang-rust prettyprint-override"><code>pub struct UTF8Chars { bytes: Peekable&lt;Box&lt;dyn Iterator&lt;Item = u8&gt;&gt;&gt;, } </code></pre> <p>Now I'm wondering how to actually create an instance of this struct.</p> <p>I've tried <em>(and yes, this is inside a trait implementation if that is an important detail)</em>:</p> <pre class="lang-rust prettyprint-override"><code>impl&lt;'a&gt; ToUTF8Chars for &amp;'a str { fn utf8_chars(self) -&gt; UTF8Chars { let bytes = Box::new(self.bytes()).peekable(); UTF8Chars { bytes } } } </code></pre> <p>That gives me the error:</p> <pre><code>expected struct `Peekable&lt;Box&lt;(dyn Iterator&lt;Item = u8&gt; + 'static)&gt;&gt;` found struct `Peekable&lt;Box&lt;std::str::Bytes&lt;'_&gt;&gt;&gt;` </code></pre> <p>Forgive me if I try weird things, but I haven't gotten the hang of this intricate trait stuff yet. For all I know, rust-analyzer was telling me that <code>Bytes</code> in fact an <code>impl Iterator&lt;Item = u8&gt;</code>. So, next thing I tried was casting it first:</p> <pre class="lang-rust prettyprint-override"><code>let bytes = Box::new(self.bytes()) as Box&lt;dyn Iterator&lt;Item = u8&gt;&gt;; UTF8Chars { bytes: bytes.peekable() } </code></pre> <p>That sort of works, but now the lifetime checker is complaining:</p> <pre><code>impl&lt;'a&gt; ToUTF8Chars for &amp;'a str { -- lifetime `'a` defined here fn utf8_chars(self) -&gt; UTF8Chars { let bytes = Box::new(self.bytes()) as Box&lt;dyn Iterator&lt;Item = u8&gt;&gt;; ^^^^^^^^^^^^^^^^^^^^^^ cast requires that `'a` must outlive `'static` </code></pre> <p>I'm not exactly sure what is going out of scope here... as far as I know, I own the result from <code>.bytes()</code> (I also tried with an additional <code>.clone()</code> in case that assumption was incorrect), I own the <code>Box</code>, the <code>Box</code> is passed to <code>Peekable</code>, and finally <code>Peekable</code> is passed to <code>UTF8Chars</code>. What <em>exactly</em> is the issue here? Why do I somehow need to outlive <code>static</code>...?</p> <p>I found this issue that seems similar, sadly no answer: <a href="https://stackoverflow.com/questions/59551656/peekable-of-an-iterator-in-struct">Peekable of an Iterator in struct</a>.</p> <h3>Why I want to do this?</h3> <p>Well, mainly because I don't really care, or am unable to care what exactly the underlying data is. I just need to know that I can <code>.peek()</code>, and <code>.next()</code>, etc. This is, because sometimes I want to assign different things to <code>self.bytes</code>. For example, <code>Chain&lt;...&gt;</code>, or <code>Copied&lt;...&gt;</code> instead of a simple <code>vec::IntoIter&lt;...&gt;</code>.</p> <p>If there is an alternative approach to this, I'm happy to hear about it.</p>
[ { "answer_id": 74669911, "author": "Kevin Reid", "author_id": 99692, "author_profile": "https://Stackoverflow.com/users/99692", "pm_score": 3, "selected": true, "text": "let bytes = Box::new(self.bytes()) as Box<dyn Iterator<Item = u8>>;\n let as let bytes: Box<dyn Iterator<Item = u8>> = Box::new(self.bytes());\n Box<Bytes> Box<dyn Iterator<Item = u8>> Box Box as _ dyn Box 'static Bytes<'a> 'static use core::iter::Peekable;\n\npub struct UTF8Chars<'a> {\n bytes: Peekable<Box<dyn Iterator<Item = u8> + 'a>>,\n}\n\ntrait ToUTF8Chars<'a> {\n fn utf8_chars(self) -> UTF8Chars<'a>;\n}\n\nimpl<'a> ToUTF8Chars<'a> for &'a str {\n fn utf8_chars(self) -> UTF8Chars<'a> {\n let bytes: Box<dyn Iterator<Item = u8> + 'a> = Box::new(self.bytes());\n\n UTF8Chars {\n bytes: bytes.peekable(),\n }\n }\n}\n String::into_bytes(s).into_iter()" }, { "answer_id": 74669927, "author": "isaactfa", "author_id": 11423104, "author_profile": "https://Stackoverflow.com/users/11423104", "pm_score": 1, "selected": false, "text": "dyn Trait dyn Trait + 'static bytes() &'a str str 'a 'a 'static dyn Iterator + 'static pub struct UTF8Chars<'a> {\n // ^^^^ now generic over 'a\n bytes: Peekable<Box<dyn Iterator<Item = u8> + 'a>>,\n // ------------------------^^^^\n // the iterator is now allowed to borrow data for 'a\n}\n trait ToUTF8Chars {\n fn utf8_chars<'a>(self) -> UTF8Chars<'a> where Self: 'a;\n // ^^^^ also generic over 'a ^^^^^^^^ self can borrow data for 'a\n}\n trait ToUTF8Chars {\n fn utf8_chars<'a>(&'a self) -> UTF8Chars<'a>;\n // ^^^^ just borrow `self` for 'a\n}\n impl<'b> ToUTF8Chars for &'b str {\n fn utf8_chars<'a>(self) -> UTF8Chars<'a> where Self: 'a {\n let bytes = Box::new(self.bytes()) as Box<dyn Iterator<Item = u8>>;\n\n UTF8Chars { bytes: bytes.peekable() }\n }\n}\n impl ToUTF8Chars for str {\n fn utf8_chars<'a>(&'a str) -> UTF8Chars<'a> {\n let bytes = Box::new(self.bytes()) as Box<dyn Iterator<Item = u8>>;\n\n UTF8Chars { bytes: bytes.peekable() }\n }\n}\n ToUTF8Chars" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10315665/" ]
74,669,044
<p>I have a transposed Dataframe tr:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;"></th> <th style="text-align: center;">7128</th> <th style="text-align: center;">8719</th> <th style="text-align: center;">14051</th> <th style="text-align: center;">14636</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">JDUTC_0</td> <td style="text-align: center;">2451957.36</td> <td style="text-align: center;">2452149.36</td> <td style="text-align: center;">2457243.98</td> <td style="text-align: center;">2452531.89</td> </tr> <tr> <td style="text-align: left;">JDUTC_1</td> <td style="text-align: center;">2451957.37</td> <td style="text-align: center;">2452149.36</td> <td style="text-align: center;">2457243.99</td> <td style="text-align: center;">2452531.90</td> </tr> <tr> <td style="text-align: left;">JDUTC_2</td> <td style="text-align: center;">2451957.37</td> <td style="text-align: center;">2452149.36</td> <td style="text-align: center;">2457244.00</td> <td style="text-align: center;">2452531.91</td> </tr> <tr> <td style="text-align: left;">JDUTC_3</td> <td style="text-align: center;">NaN</td> <td style="text-align: center;">2452149.36</td> <td style="text-align: center;">NaN</td> <td style="text-align: center;">NaN</td> </tr> <tr> <td style="text-align: left;">JDUTC_4</td> <td style="text-align: center;">NaN</td> <td style="text-align: center;">2452149.36</td> <td style="text-align: center;">NaN</td> <td style="text-align: center;">NaN</td> </tr> <tr> <td style="text-align: left;">JDUTC_5</td> <td style="text-align: center;">NaN</td> <td style="text-align: center;">2452149.36</td> <td style="text-align: center;">NaN</td> <td style="text-align: center;">NaN</td> </tr> <tr> <td style="text-align: left;">JDUTC_6</td> <td style="text-align: center;">1.23</td> <td style="text-align: center;">2452149.37</td> <td style="text-align: center;">NaN</td> <td style="text-align: center;">NaN</td> </tr> <tr> <td style="text-align: left;">JDUTC_7</td> <td style="text-align: center;">NaN</td> <td style="text-align: center;">NaN</td> <td style="text-align: center;">NaN</td> <td style="text-align: center;">NaN</td> </tr> <tr> <td style="text-align: left;">JDUTC_8</td> <td style="text-align: center;">NaN</td> <td style="text-align: center;">NaN</td> <td style="text-align: center;">NaN</td> <td style="text-align: center;">NaN</td> </tr> <tr> <td style="text-align: left;">JDUTC_9</td> <td style="text-align: center;">NaN</td> <td style="text-align: center;">NaN</td> <td style="text-align: center;">NaN</td> <td style="text-align: center;">NaN</td> </tr> </tbody> </table> </div> <p>And I create dict 'a' with this block of code:</p> <pre><code>a = {} b=[] for _, contents in tr.items(): b.clear() for ind, val in enumerate(contents): if np.isnan(val): b.append(ind) continue else: pass print(_) print(b) a[_] = b print(a) </code></pre> <p>Which gives me this output:</p> <pre><code>7128 [3, 4, 5, 7, 8, 9] {7128: [3, 4, 5, 7, 8, 9]} 8719 [7, 8, 9] {7128: [7, 8, 9], 8719: [7, 8, 9]} 14051 [3, 4, 5, 6, 7, 8, 9] {7128: [3, 4, 5, 6, 7, 8, 9], 8719: [3, 4, 5, 6, 7, 8, 9], 14051: [3, 4, 5, 6, 7, 8, 9]} 14636 [3, 4, 5, 6, 7, 8, 9] {7128: [3, 4, 5, 6, 7, 8, 9], 8719: [3, 4, 5, 6, 7, 8, 9], 14051: [3, 4, 5, 6, 7, 8, 9], 14636: [3, 4, 5, 6, 7, 8, 9]} </code></pre> <p>What I expect dict 'a' to look like is this:</p> <pre><code>{7128: [3, 4, 5, 7, 8, 9] 8719: [7, 8, 9] 14051: [3, 4, 5, 6, 7, 8, 9] 14636: [3, 4, 5, 6, 7, 8, 9]} </code></pre> <p>What I am doing wrong? Why is <code>a[_] = b</code> overwriting all the previous keys when <code>print(_)</code> is verifying that _ is always the next column label?</p>
[ { "answer_id": 74669911, "author": "Kevin Reid", "author_id": 99692, "author_profile": "https://Stackoverflow.com/users/99692", "pm_score": 3, "selected": true, "text": "let bytes = Box::new(self.bytes()) as Box<dyn Iterator<Item = u8>>;\n let as let bytes: Box<dyn Iterator<Item = u8>> = Box::new(self.bytes());\n Box<Bytes> Box<dyn Iterator<Item = u8>> Box Box as _ dyn Box 'static Bytes<'a> 'static use core::iter::Peekable;\n\npub struct UTF8Chars<'a> {\n bytes: Peekable<Box<dyn Iterator<Item = u8> + 'a>>,\n}\n\ntrait ToUTF8Chars<'a> {\n fn utf8_chars(self) -> UTF8Chars<'a>;\n}\n\nimpl<'a> ToUTF8Chars<'a> for &'a str {\n fn utf8_chars(self) -> UTF8Chars<'a> {\n let bytes: Box<dyn Iterator<Item = u8> + 'a> = Box::new(self.bytes());\n\n UTF8Chars {\n bytes: bytes.peekable(),\n }\n }\n}\n String::into_bytes(s).into_iter()" }, { "answer_id": 74669927, "author": "isaactfa", "author_id": 11423104, "author_profile": "https://Stackoverflow.com/users/11423104", "pm_score": 1, "selected": false, "text": "dyn Trait dyn Trait + 'static bytes() &'a str str 'a 'a 'static dyn Iterator + 'static pub struct UTF8Chars<'a> {\n // ^^^^ now generic over 'a\n bytes: Peekable<Box<dyn Iterator<Item = u8> + 'a>>,\n // ------------------------^^^^\n // the iterator is now allowed to borrow data for 'a\n}\n trait ToUTF8Chars {\n fn utf8_chars<'a>(self) -> UTF8Chars<'a> where Self: 'a;\n // ^^^^ also generic over 'a ^^^^^^^^ self can borrow data for 'a\n}\n trait ToUTF8Chars {\n fn utf8_chars<'a>(&'a self) -> UTF8Chars<'a>;\n // ^^^^ just borrow `self` for 'a\n}\n impl<'b> ToUTF8Chars for &'b str {\n fn utf8_chars<'a>(self) -> UTF8Chars<'a> where Self: 'a {\n let bytes = Box::new(self.bytes()) as Box<dyn Iterator<Item = u8>>;\n\n UTF8Chars { bytes: bytes.peekable() }\n }\n}\n impl ToUTF8Chars for str {\n fn utf8_chars<'a>(&'a str) -> UTF8Chars<'a> {\n let bytes = Box::new(self.bytes()) as Box<dyn Iterator<Item = u8>>;\n\n UTF8Chars { bytes: bytes.peekable() }\n }\n}\n ToUTF8Chars" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11896087/" ]
74,669,065
<p>I want to scrape the tweets of a specific account on Twitter via SB but it is not working for me</p> <p>this is my code :</p> <pre><code> import facebook as fb from bs4 import BeautifulSoup as bs import requests myUrl = requests.get('https://twitter.com/search?q=(from%3AAlMosahf)&amp;src=typed_query&amp;f=live') source = myUrl.content soup = bs(source, 'html.parser') twi = soup.find_all('div', {'data-testid':'tweetText'}) myTW = twi[1].text print(myTW) </code></pre> <p>The result is &quot;list index out of range&quot; .. because &quot;twi&quot; is empty</p>
[ { "answer_id": 74669613, "author": "palash gupta", "author_id": 12719634, "author_profile": "https://Stackoverflow.com/users/12719634", "pm_score": 2, "selected": false, "text": "import tweepy\nfrom bs4 import BeautifulSoup as bs\n\n# Authenticate with the Twitter API\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth)\n\n# Get the tweets from the user with the username \"AlMosahf\"\ntweets = api.user_timeline(screen_name=\"AlMosahf\")\n\n# Parse the tweets using Beautiful Soup\nfor tweet in tweets:\n soup = bs(tweet.text, 'html.parser')\n # Do something with the parsed tweet\n" }, { "answer_id": 74671470, "author": "GAP2002", "author_id": 14608493, "author_profile": "https://Stackoverflow.com/users/14608493", "pm_score": 0, "selected": false, "text": "twi find_all() import tweepy\n\n# Set up your API keys and access tokens\nconsumer_key = 'your-consumer-key'\nconsumer_secret = 'your-consumer-secret'\naccess_token = 'your-access-token'\naccess_token_secret = 'your-access-token-secret'\n\n# Authenticate with the Twitter API\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth)\n\n# Extract the tweets from the specified account\naccount = 'AlMosahf'\ntweets = api.user_timeline(screen_name=account)\n\n# Print the tweets\nfor tweet in tweets:\n print(tweet.text)\n limit since_id max_id" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19739550/" ]
74,669,082
<p>I installed the latest nodejs 19.2.0 on my windows 11 OS rather than the recommended for most users 18.12.1 <code>npx create-react-app my-first-app</code> works just fine, it creates all the files and folders without any errors, shows happy hacking message as well, recommends to use <code>npm start</code> command. I go inside <code>my-first-app</code> folder, go <code>npm start</code> and I get a module not found error...like this picture <a href="https://i.stack.imgur.com/Y1tci.png" rel="nofollow noreferrer">Error Message Screenshot</a></p> <p>In youtube tutorials, there is no any error in their pc. <code>npm start</code> runs just as easily as <code>npx create-react-app &lt;anyappname&gt;</code>.</p>
[ { "answer_id": 74669613, "author": "palash gupta", "author_id": 12719634, "author_profile": "https://Stackoverflow.com/users/12719634", "pm_score": 2, "selected": false, "text": "import tweepy\nfrom bs4 import BeautifulSoup as bs\n\n# Authenticate with the Twitter API\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth)\n\n# Get the tweets from the user with the username \"AlMosahf\"\ntweets = api.user_timeline(screen_name=\"AlMosahf\")\n\n# Parse the tweets using Beautiful Soup\nfor tweet in tweets:\n soup = bs(tweet.text, 'html.parser')\n # Do something with the parsed tweet\n" }, { "answer_id": 74671470, "author": "GAP2002", "author_id": 14608493, "author_profile": "https://Stackoverflow.com/users/14608493", "pm_score": 0, "selected": false, "text": "twi find_all() import tweepy\n\n# Set up your API keys and access tokens\nconsumer_key = 'your-consumer-key'\nconsumer_secret = 'your-consumer-secret'\naccess_token = 'your-access-token'\naccess_token_secret = 'your-access-token-secret'\n\n# Authenticate with the Twitter API\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth)\n\n# Extract the tweets from the specified account\naccount = 'AlMosahf'\ntweets = api.user_timeline(screen_name=account)\n\n# Print the tweets\nfor tweet in tweets:\n print(tweet.text)\n limit since_id max_id" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20635970/" ]
74,669,137
<p>I have 4 inputs in my panel; when user clicks <code>cancel</code> I need to revert to the original values before they're modified. Is there a Vuetify or Vue.js way to achieve this? or do I have to manage it using JS by storing all values in a tmp variable?</p>
[ { "answer_id": 74669613, "author": "palash gupta", "author_id": 12719634, "author_profile": "https://Stackoverflow.com/users/12719634", "pm_score": 2, "selected": false, "text": "import tweepy\nfrom bs4 import BeautifulSoup as bs\n\n# Authenticate with the Twitter API\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth)\n\n# Get the tweets from the user with the username \"AlMosahf\"\ntweets = api.user_timeline(screen_name=\"AlMosahf\")\n\n# Parse the tweets using Beautiful Soup\nfor tweet in tweets:\n soup = bs(tweet.text, 'html.parser')\n # Do something with the parsed tweet\n" }, { "answer_id": 74671470, "author": "GAP2002", "author_id": 14608493, "author_profile": "https://Stackoverflow.com/users/14608493", "pm_score": 0, "selected": false, "text": "twi find_all() import tweepy\n\n# Set up your API keys and access tokens\nconsumer_key = 'your-consumer-key'\nconsumer_secret = 'your-consumer-secret'\naccess_token = 'your-access-token'\naccess_token_secret = 'your-access-token-secret'\n\n# Authenticate with the Twitter API\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth)\n\n# Extract the tweets from the specified account\naccount = 'AlMosahf'\ntweets = api.user_timeline(screen_name=account)\n\n# Print the tweets\nfor tweet in tweets:\n print(tweet.text)\n limit since_id max_id" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4480164/" ]
74,669,147
<p>I'm not very good in English or in R but hopefully I can manage to explain the problem</p> <p>I have a dataset where there is one column with years, from 1952 to 2007. I want to recode and reorganize it so that the first year is number 0, the next year nr. 1 and so on...</p> <p>Can anyone help me?</p> <p>I have tried recode(), arrange (),</p>
[ { "answer_id": 74669204, "author": "margusl", "author_id": 646761, "author_profile": "https://Stackoverflow.com/users/646761", "pm_score": 3, "selected": true, "text": "df <- data.frame(years = 1952:2007)\nis.na(df$years[sample(1:nrow(df), size = 10)]) <- TRUE\n\nhead(df)\n#> years\n#> 1 NA\n#> 2 1953\n#> 3 1954\n#> 4 1955\n#> 5 1956\n#> 6 1957\n\ndf$years_recoded <- df$years - min(df$years, na.rm = T)\nhead(df)\n#> years years_recoded\n#> 1 NA NA\n#> 2 1953 0\n#> 3 1954 1\n#> 4 1955 2\n#> 5 1956 3\n#> 6 1957 4\n" }, { "answer_id": 74669414, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 1, "selected": false, "text": "row_number() library(dplyr)\n\ndf %>% \n mutate(year_recoded = row_number()-1) %>% \n head()\n years year_recoded\n1 1952 0\n2 1953 1\n3 1954 2\n4 1955 3\n5 1956 4\n6 1957 5\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20676291/" ]
74,669,178
<p>Here is an example of some of the information in the text file:</p> <pre><code>Ticker : Ticker representing the company | Company: Name | Title: Position of trader | Trade Type: Buy or sell | Value: Monetary value Ticker : AKUS | Company: Akouos, Inc. | Title: 10% | Trade Type: P - Purchase | Value: +$374,908,350 Ticker : HHC | Company: Howard Hughes Corp | Title: Dir, 10% | Trade Type: P - Purchase | Value: +$109,214,243 </code></pre> <p>Where each time it says ticker, it's a new line. Is there a way to pull out specific information and set it to a dictionary? For example, would I be able to get a dictionary filled with all the tickers, all the positions and all of the monetary values?</p>
[ { "answer_id": 74669435, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 3, "selected": true, "text": "import pandas as pd\n\nfilename = 'file1.txt'\n\ndf = pd.read_csv(filename,\n sep = ':\\s+|\\s\\|',\n engine='python',\n usecols=[1,3,5,7,9]\n )\ndf.columns = ['Ticker', 'Company', 'Title', 'Trade Type', 'Value']\n\nprint(df)\n data_dictionary = df.to_dict()\nprint(data_dictionary)\n {'Ticker': {0: 'AKUS', 1: 'HHC'}, 'Company': {0: 'Akouos, Inc.', 1: 'Howard Hughes Corp'}, 'Title': {0: '10%', 1: 'Dir, 10%'}, 'Trade Type': {0: 'P - Purchase', 1: 'P - Purchase'}, 'Value': {0: '+$374,908,350', 1: '+$109,214,243'}}\n Value 'AKUS' tickers = {v:k for k,v in data_dictionary.get('Ticker').items()}\n\nprint('AKUS Value:', data_dictionary['Value'][tickers.get('AKUS')])\n AKUS Value: +$374,908,350\n" }, { "answer_id": 74669906, "author": "Cobra", "author_id": 17580381, "author_profile": "https://Stackoverflow.com/users/17580381", "pm_score": 1, "selected": false, "text": "ticker = {}\n\nwith open('ticker.txt') as tdata:\n next(tdata) # skip first line\n for row in tdata:\n if columns := row.split('|'):\n _, t = columns[0].split(':')\n ticker[t.strip()] = {k.strip(): v.strip() for k, v in [column.split(':') for column in columns[1:]]}\n\nprint(ticker)\n {'AKUS': {'Company': 'Akouos, Inc.', 'Title': '10%', 'Trade Type': 'P - Purchase', 'Value': '+$374,908,350'}, 'HHC': {'Company': 'Howard Hughes Corp', 'Title': 'Dir, 10%', 'Trade Type': 'P - Purchase', 'Value': '+$109,214,243'}}\n ticker['HHC']['Value']\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20404244/" ]
74,669,191
<p>Please help write a C++ Program to print this sequence</p> <p>1,2,5,6,9,10,13,14,17,18 up to 500. I need it for my homework as a student. I tried</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { for (int i = 1; i &lt; 454; i++) { if (i = i + 1) { continue; } } return 0; } </code></pre>
[ { "answer_id": 74669537, "author": "john", "author_id": 882003, "author_profile": "https://Stackoverflow.com/users/882003", "pm_score": 1, "selected": false, "text": "#include <iostream>\n\nint main()\n{\n for (int i = 1; i <= 500; i++) {\n if (i % 4 == 1 || i % 4 == 2) {\n std::cout << i << ',';\n }\n }\n std::cout << '\\n';\n}\n" }, { "answer_id": 74669654, "author": "Sash Sinha", "author_id": 6328256, "author_profile": "https://Stackoverflow.com/users/6328256", "pm_score": 0, "selected": false, "text": "+1, +3, +1, +3, +1, ... #include <iostream>\n\nint main()\n{\n int i = 0, x = 1;\n while (x <= 500)\n {\n std::cout << x << '\\n'; // Print current value of x.\n x += i == 1 ? 3 : 1; // Increment x based on value of i.\n i ^= 1; // Toggle i between 1 and 0.\n }\n}\n 1\n2\n5\n6\n9\n10\n13\n14\n17\n18\n21\n22\n25\n26\n29\n30\n33\n34\n37\n38\n41\n42\n45\n46\n49\n50\n53\n54\n57\n58\n61\n62\n65\n66\n69\n70\n73\n74\n77\n78\n81\n82\n85\n86\n89\n90\n93\n94\n97\n98\n101\n102\n105\n106\n109\n110\n113\n114\n117\n118\n121\n122\n125\n126\n129\n130\n133\n134\n137\n138\n141\n142\n145\n146\n149\n150\n153\n154\n157\n158\n161\n162\n165\n166\n169\n170\n173\n174\n177\n178\n181\n182\n185\n186\n189\n190\n193\n194\n197\n198\n201\n202\n205\n206\n209\n210\n213\n214\n217\n218\n221\n222\n225\n226\n229\n230\n233\n234\n237\n238\n241\n242\n245\n246\n249\n250\n253\n254\n257\n258\n261\n262\n265\n266\n269\n270\n273\n274\n277\n278\n281\n282\n285\n286\n289\n290\n293\n294\n297\n298\n301\n302\n305\n306\n309\n310\n313\n314\n317\n318\n321\n322\n325\n326\n329\n330\n333\n334\n337\n338\n341\n342\n345\n346\n349\n350\n353\n354\n357\n358\n361\n362\n365\n366\n369\n370\n373\n374\n377\n378\n381\n382\n385\n386\n389\n390\n393\n394\n397\n398\n401\n402\n405\n406\n409\n410\n413\n414\n417\n418\n421\n422\n425\n426\n429\n430\n433\n434\n437\n438\n441\n442\n445\n446\n449\n450\n453\n454\n457\n458\n461\n462\n465\n466\n469\n470\n473\n474\n477\n478\n481\n482\n485\n486\n489\n490\n493\n494\n497\n498\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20676384/" ]
74,669,219
<p>I have a socket server which creates unix socket and then reads data from this unix socket. Then I have another long-process application and I want to redirect stdout of this process to my unix socket. I tried this command to test</p> <pre><code>ping 127.0.0.1 &gt; /tmp/unixsockettest.sock </code></pre> <p>But I get <code>-bash: /tmp/unixsockettest.sock: No such device or address</code>. Is it possible to redirect application output to unix socket?</p>
[ { "answer_id": 74669345, "author": "larsks", "author_id": 147356, "author_profile": "https://Stackoverflow.com/users/147356", "pm_score": 1, "selected": false, "text": "ping 127.0.0.1 | socat - unix-connect:/tmp/unixsockettest.sock\n" }, { "answer_id": 74669467, "author": "PSkocik", "author_id": 1084774, "author_profile": "https://Stackoverflow.com/users/1084774", "pm_score": 0, "selected": false, "text": "open() dup2() open connect() struct sockaddr_un socat netcat ping 127.0.0.1 | nc -U /tmp/unixsockettest.sock #add -u it the socket isn't streaming but datagram\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6246418/" ]
74,669,259
<p>I am a bit confused about the use of <code>srcset</code> attribute in the HTML <code>img</code> tag. I read several tutorials on the Web but I think stuff doesn't work as these tutorial report. First of all, let's start with an easy example:</p> <pre><code>&lt;img src=&quot;assets/img/software-developer.jpeg&quot; alt=&quot;Some Stuff&quot; srcset=&quot;assets/img/software-developer-300.jpeg 300w, assets/img/software-developer.jpeg 450w&quot;&gt; </code></pre> <p>I have two images:</p> <ul> <li><code>assets/img/software-developer.jpeg</code> 450x450 pixels</li> <li><code>assets/img/software-developer-300.jpeg</code> 300x300 pixels</li> </ul> <p>Now I use Chrome Developer Tools for tests, but whatever screen size I select I always see that <code>assets/img/software-developer.jpeg</code> is downloaded. I can see it in the Developer Tools Properties tab looking at the property <code>currentSrc</code>.</p> <p><strong>Can anyone help me to understand why?</strong> I want that:</p> <ul> <li>for screen with size &gt;= 450px then <code>assets/img/software-developer.jpeg</code> is downloaded</li> <li>for screen with size &lt; 450px then <code>assets/img/software-developer-300.jpeg</code> is downloaded</li> </ul> <p>Another thing that it's not clear to me is: <strong>what happens with screen size &lt; 300px?</strong></p> <p>If the image with lowest width is <code>assets/img/software-developer-300.jpeg</code> that is 300x300 pixels, how I can modify the code to let it resize (become smaller in this case) to fit the viewport?</p> <p>For example, Developer Tools by defaul has Galaxy Fold device that has a width of 280 pixel. In this case, both the images don't fit the screen size: <strong>how I can define my srcset to let it resize in this situation?</strong></p> <p>Web is full of information about this stuff, at a first read things are a bit confusing so I decided to start with small tests. The first tests I decided to work on is with <code>srcset</code> and check if the image downloaded is the one expected. It seems the tag doesn't work as expected. I know that I am missing something, hoping someone here can help to clarify.</p>
[ { "answer_id": 74669706, "author": "Anand MS", "author_id": 12179934, "author_profile": "https://Stackoverflow.com/users/12179934", "pm_score": 1, "selected": false, "text": "sizes sizes <img src=\"assets/img/software-developer.jpeg\" alt=\"Some Stuff\" sizes=\"(max-width: 449px) 300px, 450px\" srcset=\"assets/img/software-developer-300.jpeg 300w, assets/img/software-developer.jpeg 450w\">\n" }, { "answer_id": 74678316, "author": "Salvatore D'angelo", "author_id": 6286900, "author_profile": "https://Stackoverflow.com/users/6286900", "pm_score": 0, "selected": false, "text": "srcset sizes srcset srcset=\"assets/img/software-developer-300.jpeg 300w, assets/img/software-developer.jpeg 450w\"\n sizes srcset=\"assets/img/software-developer-300.jpeg 300w, assets/img/software-developer.jpeg 450w\" sizes=\"(max-width: 449px) 300px, (min-width: 450px) 450px\"\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6286900/" ]
74,669,313
<p>My project is using Spring and I wanted to test with Mockito but I have a NullPointerException that I can't solve... Isn't MockBean supposed to inject in my TeacherService ? I have tried to put @Autowired in front of MockMvc but it's worse...</p> <p>I want to test my Controller by adding a new Teacher :</p> <p>This is my test :</p> <pre><code>@ExtendWith(MockitoExtension.class) @ExtendWith(SpringExtension.class) @AutoConfigureMockMvc public class TeacherControllerMockTest { private MockMvc mvc; @InjectMocks private TeacherForm teacherForm; @MockBean private TeacherService teacherService; @Captor ArgumentCaptor&lt;Teacher&gt; teacherCaptor; @Test void addTeacherPostNonExistingTeacher() throws Exception { when(teacherService.findById(teacherForm.getId())).thenReturn(null); //il y aura un teacherService.saveTeacher(t) : mais par defaut ça ne le fera pas this.mvc.perform(post(&quot;/addTeacher&quot;) .param(&quot;firstName&quot;, &quot;Anne-Marie&quot;) .param(&quot;lastName&quot;, &quot;Kermarrec&quot;) ) .andExpect(status().is3xxRedirection()) .andReturn(); //teacherController.addTeacher(teacherForm); verify(teacherService, atLeastOnce()).saveTeacher(teacherCaptor.capture()); Teacher capturedTeacher = teacherCaptor.getValue(); assertEquals(&quot;Kermarrec&quot;, capturedTeacher.getLastName()); } </code></pre> <p>This is my Controller :</p> <pre><code>@PostMapping(value = { &quot;/addTeacher&quot;}) public String addTeacher(@ModelAttribute(&quot;TeacherForm&quot;) TeacherForm teacherForm) { Teacher t; if(teacherService.findById(teacherForm.getId()).isPresent()){ // teacher already existing : update t = teacherService.findById(teacherForm.getId()).get(); t.setFirstName(teacherForm.getFirstName()); t.setLastName(teacherForm.getLastName()); } else { // teacher not existing : create t=new Teacher(teacherForm.getFirstName(), teacherForm.getLastName(), terManagerService.getTERManager()); } teacherService.saveTeacher(t); return &quot;redirect:/listTeachers&quot;; } </code></pre> <p>And the error :</p> <pre><code>java.lang.NullPointerException: Cannot invoke &quot;org.springframework.test.web.servlet.MockMvc.perform(org.springframework.test.web.servlet.RequestBuilder)&quot; because &quot;this.mvc&quot; is null at um.fds.agl.ter22.controllers.mockito.TeacherControllerMockTest.addTeacherPostNonExistingTeacher(TeacherControllerMockTest.java:59) at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) at java.base/java.lang.reflect.Method.invoke(Method.java:578) at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725) at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60) at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131) at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149) at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140) at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84) at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115) at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105) at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37) at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104) at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86) at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86) at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53) at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71) at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38) at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11) at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35) at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235) at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54) </code></pre> <p>EDIT 2 : I have tried to initilize this.mvc without @Autowired but I got another error :</p> <pre><code> @BeforeEach public void setUp() { this.mvc = MockMvcBuilders.standaloneSetup(new TeacherController()).build(); //I have add this line because I got thie.teacherService is null this.teacherService = new TeacherService(); } </code></pre> <p>I got a problem with this.teacherRepository is null (teacherRepository is an interface), it is used when I'm calling teacherService.findById</p> <p>In TeacherService</p> <pre><code>public Optional&lt;Teacher&gt; findById(long id) { return teacherRepository.findById(id); } </code></pre> <pre><code>java.lang.NullPointerException: Cannot invoke &quot;um.fds.agl.ter22.repositories.TeacherRepository.findById(Object)&quot; because &quot;this.teacherRepository&quot; is null at um.fds.agl.ter22.services.TeacherService.findById(TeacherService.java:41) at um.fds.agl.ter22.controllers.mockito.TeacherControllerMockTest.addTeacherPostNonExistingTeacher(TeacherControllerMockTest.java:64) at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) at java.base/java.lang.reflect.Method.invoke(Method.java:578) at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725) at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60) at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131) at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149) at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140) at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84) at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115) at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105) at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37) at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104) at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86) at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86) at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53) at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71) at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38) at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11) at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35) at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235) at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54) </code></pre>
[ { "answer_id": 74669378, "author": "Begging", "author_id": 16606223, "author_profile": "https://Stackoverflow.com/users/16606223", "pm_score": 1, "selected": false, "text": "@BeforeEach\npublic void setup() {\n this.mvc = MockMvcBuilders.standaloneSetup(new TeacherController()).build();\n}\n" }, { "answer_id": 74669422, "author": "Alien", "author_id": 6572971, "author_profile": "https://Stackoverflow.com/users/6572971", "pm_score": -1, "selected": false, "text": "@Autowired @Autowired\nprivate MockMvc mvc;\n" }, { "answer_id": 74673964, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 0, "selected": false, "text": "mockMvc java.lang.NullPointerException: Cannot invoke \"org.springframework.test.web.servlet.MockMvc.perform(org.springframework.test.web.servlet.RequestBuilder)\" because \"this.mvc\" is null\n at um.fds.agl.ter22.controllers.mockito.TeacherControllerMockTest.addTeacherPostNonExistingTeacher(TeacherControllerMockTest.java:59)\n @SpringBootTest\n@AutoConfigureMockMvc\npublic class TeacherControllerMockTest {\n @Autowired\n private MockMvc mvc;\n\n // ...\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13542212/" ]
74,669,346
<p>I am trying to make an tracker app in witch I an user can create a group and when clicked on &quot;show on map&quot; it would show all of members position. I have made group info page in witch there is a Add members button. When clicked it takes the user to a new page. In that new page he searches for an different user witch he wants to add. When clicked on search icon under the TextFormField there is an ListTile. When tapped on that ListTile searched user should be added to that group and the searcher should be redirected back to group info page.</p> <p>I am stuck at the part in which I try to add users to an existing group but I get an error:</p> <blockquote> <p>Bad state: field does not exist within the DocumentSnapshotPlatform.</p> </blockquote> <p>Here is the code for adding different users to a group</p> <pre><code>import 'package:cloud_firestore/cloud_firestore.dart'; class DatabaseService { final String? uid; DatabaseService({this.uid}); // reference for collection final CollectionReference userCollection = FirebaseFirestore.instance.collection(&quot;users&quot;); final CollectionReference groupCollection = FirebaseFirestore.instance.collection(&quot;groups&quot;); // saving the user data Future savingUserData(String name, String email) async { return await userCollection.doc(uid).set({ &quot;name&quot;: name, &quot;email&quot;: email, &quot;friends&quot;: [], &quot;groups&quot;: [], &quot;profilePicture&quot;: &quot;&quot;, &quot;uid&quot;: uid, &quot;latitude&quot;: &quot;&quot;, &quot;longitude&quot;: &quot;&quot;, }); } //getting user data Future gettingUserData(String email) async { QuerySnapshot snapshot = await userCollection.where(&quot;email&quot;, isEqualTo: email).get(); return snapshot; } // create a group Future createGroup(String name, String groupName, String id) async { DocumentReference groupDocumentReference = await groupCollection.add({ &quot;groupName&quot;: groupName, &quot;groupIcon&quot;: &quot;&quot;, &quot;groupCreator&quot;: &quot;&quot;, &quot;admins&quot;: [], &quot;members&quot;: [], &quot;groupId&quot;: &quot;&quot;, }); await groupDocumentReference.update({ &quot;admins&quot;: FieldValue.arrayUnion([&quot;${uid}_$name&quot;]), &quot;groupCreator&quot;: FieldValue.arrayUnion([&quot;${id}_$name&quot;]), &quot;groupId&quot;: groupDocumentReference.id }); DocumentReference userDocumentReference = userCollection.doc(uid); return await userDocumentReference.update({ &quot;groups&quot;: FieldValue.arrayUnion([&quot;${groupDocumentReference.id}_$groupName&quot;]) }); } getUserGroups() async { return userCollection.doc(uid).snapshots(); } //search searchByEmail(String userEmail) async { return userCollection.where('email', isEqualTo: userEmail).get(); } //get group admins getGroupAdmins(String groupId) async { return groupCollection.doc(groupId).snapshots(); } getGroupMembers(String groupId) async { return groupCollection.doc(groupId).snapshots(); } Future addMember( String groupId, String groupName, String memeberId, memberName, ) async { DocumentReference userDocumentReference = userCollection.doc(memeberId); DocumentReference groupDocumentReference = groupCollection.doc(groupId); DocumentSnapshot userdocumentSnapshot = await userDocumentReference.get(); List&lt;dynamic&gt; groups = await userdocumentSnapshot['groups']; DocumentSnapshot groupDocumentSnapshot = await groupDocumentReference.get(); List&lt;dynamic&gt; members = await groupDocumentSnapshot['members']; if (groups.contains(&quot;${groupId}_$groupName&quot;) &amp; members.contains(&quot;${memeberId}_$memberName&quot;)) { return null; } else { await groupCollection.doc(groupId).update({ &quot;members&quot;: FieldValue.arrayUnion([&quot;${memeberId}_$memberName&quot;]) }); } } } </code></pre> <p>Here is the AddMemberPage</p> <pre><code>import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:tracker_app/page_changer/page_changer.dart'; import 'package:tracker_app/pages/app_pages/info_page.dart'; import 'package:tracker_app/services/database_service.dart'; import '../../theme/theme.dart'; class AddMembers extends StatefulWidget { final String groupId; final String groupName; const AddMembers({super.key, required this.groupId, required this.groupName}); @override State&lt;AddMembers&gt; createState() =&gt; _AddMembersState(); } class _AddMembersState extends State&lt;AddMembers&gt; { QuerySnapshot? searchSnapshot; TextEditingController emailController = TextEditingController(); String email = &quot;&quot;; String friendId = &quot;&quot;; String friendName = &quot;&quot;; bool isLoading = false; bool hasUserSearched = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text( &quot;Add members&quot;, style: TextStyle(fontSize: 30, fontWeight: FontWeight.w500), ), centerTitle: true, ), body: SingleChildScrollView( child: Column(children: [ const Divider( height: 5, indent: 5, endIndent: 5, thickness: 1.5, ), Container( height: 10, ), Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: TextFormField( controller: emailController, cursorColor: AppColors.secondary, decoration: InputDecoration( errorBorder: OutlineInputBorder( borderSide: const BorderSide(color: Colors.red), borderRadius: BorderRadius.circular(50)), focusedBorder: OutlineInputBorder( borderSide: const BorderSide( color: AppColors.secondary, ), borderRadius: BorderRadius.circular(50)), enabledBorder: OutlineInputBorder( borderSide: const BorderSide( color: AppColors.secondary, ), borderRadius: BorderRadius.circular(50)), labelText: &quot;email&quot;, labelStyle: const TextStyle( color: AppColors.secondary, fontWeight: FontWeight.w500, ), suffixIcon: InkWell( splashColor: AppColors.secondary, borderRadius: BorderRadius.circular(360), onTap: () { initiateSearchMethod(); }, child: const Icon( Icons.search, color: AppColors.secondary, ), ), hintText: &quot;Enter persons email&quot;), onChanged: (value) { setState(() { email = value; }); }, ), ), userList(), ]), ), ); } initiateSearchMethod() async { if (emailController != null) { setState(() { isLoading = true; }); await DatabaseService(uid: FirebaseAuth.instance.currentUser!.uid) .searchByEmail(email) .then((snapshot) { setState(() { searchSnapshot = snapshot; isLoading = false; hasUserSearched = true; friendId = snapshot!.docs[0]['id']; friendName = snapshot!.docs[0]['name']; }); }); } } userList() { return hasUserSearched ? ListView.builder( shrinkWrap: true, itemCount: searchSnapshot!.docs.length, itemBuilder: (context, index) { return friendSearchTile(); }, ) : Container(); } friendSearchTile() { // check if user is friend //GdzhH8YGCsTMhmPf6aAeXvb09GH3 return ListTile( leading: CircleAvatar( radius: 25, backgroundColor: AppColors.secondary, child: Text( searchSnapshot!.docs[0]['name'].substring(0, 1).toUpperCase(), style: const TextStyle(color: Colors.white)), ), title: Text(friendName), subtitle: Text(searchSnapshot!.docs[0]['email']), trailing: InkWell( borderRadius: BorderRadius.circular(360), onTap: () { DatabaseService(uid: FirebaseAuth.instance.currentUser!.uid) .addMember( widget.groupId, widget.groupName, searchSnapshot!.docs[0]['id'], searchSnapshot!.docs[0]['name']); nextScreenReplace(context, InfoPage(groupName: widget.groupName, groupId: widget.groupId)); print(&quot;friendId: $friendId&quot;); }, splashColor: AppColors.secondary, child: Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), child: const Icon( Icons.add, ), ), ), ); } } </code></pre>
[ { "answer_id": 74669378, "author": "Begging", "author_id": 16606223, "author_profile": "https://Stackoverflow.com/users/16606223", "pm_score": 1, "selected": false, "text": "@BeforeEach\npublic void setup() {\n this.mvc = MockMvcBuilders.standaloneSetup(new TeacherController()).build();\n}\n" }, { "answer_id": 74669422, "author": "Alien", "author_id": 6572971, "author_profile": "https://Stackoverflow.com/users/6572971", "pm_score": -1, "selected": false, "text": "@Autowired @Autowired\nprivate MockMvc mvc;\n" }, { "answer_id": 74673964, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 0, "selected": false, "text": "mockMvc java.lang.NullPointerException: Cannot invoke \"org.springframework.test.web.servlet.MockMvc.perform(org.springframework.test.web.servlet.RequestBuilder)\" because \"this.mvc\" is null\n at um.fds.agl.ter22.controllers.mockito.TeacherControllerMockTest.addTeacherPostNonExistingTeacher(TeacherControllerMockTest.java:59)\n @SpringBootTest\n@AutoConfigureMockMvc\npublic class TeacherControllerMockTest {\n @Autowired\n private MockMvc mvc;\n\n // ...\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20183230/" ]
74,669,384
<p>So I'm writing a simple C program that essentially creates a 2D array and allows the user to input values into the 2D array. Then other functions find the smallest and largest value within that array, as well as their position in the array. When I print the matrix in the function, it prints correctly as it should. However, whenever I print it in main as a test or try to access it in my other functions, my array goes from 1, 2, 3, 4, etc. to 1, 1, 1, 1. I used the same function in a previous code I wrote, and it worked just fine, so I'm kind of stumped. Also, I'm not allowed to modify main, I just put a simple loop to print the array there as a test. This is my first time posting here, so I apologize if my formatting is wrong. Any help would be greatly appreciated.</p> <p>Here is my code:</p> <pre><code>#include &lt;stdio.h&gt; #define ROWS 4 #define COLS 3 void generateMtx(int mtx[ROWS][COLS]) { for (int i = 0; i &lt; ROWS; i++) { for (int j = 0; j &lt; COLS; j++) { printf(&quot;Enter row %d, column %d: &quot;, i, j); scanf(&quot;%d&quot;, &amp;mtx[i][j]); } } //Test print in function for (int i = 0; i &lt; ROWS; i++) { for (int j = 0; j &lt; COLS; j++) { printf(&quot;%d &quot;, mtx[i][j]); } printf(&quot;\n&quot;); } } int matrixSmallest(int arr[ROWS][COLS]) { int smallest = arr[0][0]; for (int i = 0; i &lt; ROWS; i++) { for (int j = 0; j &lt; COLS; j++) { if (smallest &gt; arr[i][j]) { smallest = arr[i][j]; } } } return smallest; } int matrixLargest(int arr[ROWS][COLS]) { int largest = arr[0][0]; for (int i = 0; i &lt; ROWS; i++) { for (int j = 0; j &lt; COLS; j++) { if (largest &lt; arr[i][j]) { largest = arr[i][j]; } } } return largest; } int elementPosition(int arr[ROWS][COLS], int num, int pos[2]) { for (int i = 0; i &lt; ROWS; i++) { for (int j = 0; j &lt; COLS; j++) { if (arr[i][j] = num) { pos[0] = i; pos[1] = j; } } } return pos[2]; } int main() { int mtx[ROWS][COLS]; generateMtx(mtx); int smallest = matrixSmallest(mtx); int smallPosition[2] = {-1, -1}; elementPosition(mtx, smallest, smallPosition); int largest = matrixLargest(mtx); int largePosition[2] = {-1, -1}; elementPosition(mtx, largest, largePosition); printf(&quot;Largest element: %d\n&quot;, largest); printf(&quot; found at row %d, column %d\n&quot;, largePosition[0], largePosition[1]); printf(&quot;Smallest element: %d\n&quot;, smallest); printf(&quot; found at row %d, column %d\n&quot;, smallPosition[0], smallPosition[1]); //Test print in main //Can't modify main for (int i = 0; i &lt; ROWS; i++) { for (int j = 0; j &lt; COLS; j++) { printf(&quot;%d &quot;, mtx[i][j]); } printf(&quot;\n&quot;); } return 0; } </code></pre> <p>Code for the same function I used on my previous problem:</p> <pre><code>#include &lt;stdio.h&gt; #define ROWS 5 #define COLS 3 float generateMtx(float arr[ROWS][COLS]) { for (int i = 0; i &lt; ROWS; i++) { for (int j = 0; j &lt; COLS; j++) { printf(&quot;Enter row %d, column %d: &quot;, i, j); scanf(&quot;%f&quot;, &amp;arr[i][j]); } } printf(&quot;\n&quot;); return arr[ROWS][COLS]; } float columnAverages(float arr[ROWS][COLS], float colavg[COLS]) { float sum = 0; float avg = 0; for (int i = 0; i &lt; COLS; i++) { for (int j = 0; j &lt; ROWS; j++) { sum += arr[j][i]; } avg = sum/5.0; colavg[i] = avg; sum = 0; } return colavg[COLS]; } float rowAverages(float arr[ROWS][COLS], float rowavg[ROWS]) { float sum = 0; float avg = 0; for (int i = 0; i &lt; ROWS; i++) { for (int j = 0; j &lt; COLS; j++) { sum += arr[i][j]; } avg = sum/3.0; rowavg[i] = avg; sum = 0; } return rowavg[ROWS]; } void regionAverage(float arr[ROWS][COLS], int top, int bottom, int left, int right) { printf(&quot;\n\nEnter top region boundary: &quot;); scanf(&quot;%d&quot;, &amp;top); printf(&quot;Enter bottom region boundary: &quot;); scanf(&quot;%d&quot;, &amp;bottom); printf(&quot;Enter left region boundary: &quot;); scanf(&quot;%d&quot;, &amp;left); printf(&quot;Enter right region boundary: &quot;); scanf(&quot;%d&quot;, &amp;right); float sum = 0; float avg = 0; float count = 0; for (int i = top; i &lt;= bottom; i++) { for (int j = left; j &lt;= right; j++) { sum += arr[i][j]; count++; } } avg = sum/count; printf(&quot;Region average: %.1f&quot;, avg); } int main(void) { float mtx[ROWS][COLS]; generateMtx(mtx); float rowavg[ROWS]; float colavg[COLS]; int top, bottom, left, right; columnAverages(mtx, colavg); rowAverages(mtx, rowavg); printf(&quot; &quot;); for (int c = 0; c &lt; 3; c++) { printf(&quot;Col %d &quot;, c); } printf(&quot;\n&quot;); for (int i = 0; i &lt; ROWS; i++) { printf(&quot;Row %d &quot;, i); for (int j = 0; j &lt; COLS; j++) { printf(&quot;%8.1f&quot;, mtx[i][j]); } printf(&quot;\n&quot;); } printf(&quot;\n&quot;); printf(&quot; &quot;); for (int c = 0; c &lt; 3; c++) { printf(&quot;Col %d &quot;, c); } printf(&quot; Avg&quot;); printf(&quot;\n&quot;); for (int i = 0; i &lt; ROWS; i++) { printf(&quot;Row %d &quot;, i); for (int j = 0; j &lt; COLS; j++) { printf(&quot;%8.1f&quot;, mtx[i][j]); } printf(&quot;%8.1f&quot;, rowavg[i]); printf(&quot;\n&quot;); } printf(&quot; Avg &quot;); for (int i = 0; i &lt; COLS; i++) { printf(&quot;%8.1f&quot;, colavg[i]); } regionAverage(mtx, top, bottom, left, right); return 0; } </code></pre> <p>Output when printed from generateMTX function:</p> <pre class="lang-none prettyprint-override"><code>1 2 3 4 5 6 7 8 9 10 11 12 </code></pre> <p>Output when printed from main:</p> <pre class="lang-none prettyprint-override"><code>1 1 1 1 1 1 1 1 1 1 1 1 </code></pre>
[ { "answer_id": 74669451, "author": "anton-tchekov", "author_id": 4724047, "author_profile": "https://Stackoverflow.com/users/4724047", "pm_score": 3, "selected": true, "text": "if (arr[i][j] = num)\n elementPosition if (arr[i][j] == num)\n" }, { "answer_id": 74669572, "author": "Zameel Hassan", "author_id": 18693614, "author_profile": "https://Stackoverflow.com/users/18693614", "pm_score": 0, "selected": false, "text": "int elementPosition(int arr[ROWS][COLS], int num, int pos[2])\n{\n for (int i = 0; i < ROWS; i++)\n {\n for (int j = 0; j < COLS; j++)\n {\n if (arr[i][j] = num)\n {\n pos[0] = i;\n pos[1] = j;\n }\n }\n }\n return pos[2];\n}\n if (arr[i][j] = num) = is assigning operator == is used for equal condition checking" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20676402/" ]
74,669,395
<p>I've got XML files that contain HTML snippets. I'm trying to write a Python script that opens such an XML file, searches for the elements containing the HTML, renames the classes, and then writes back the new XML file to file. Here's an XML example:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;question_categories&gt; &lt;question_category id=&quot;18883&quot;&gt; &lt;name&gt;templates&lt;/name&gt; &lt;questions&gt; &lt;question id=&quot;1419226&quot;&gt; &lt;parent&gt;0&lt;/parent&gt; &lt;name&gt;_template_master&lt;/name&gt; &lt;questiontext&gt; &amp;lt;div class=&amp;quot;wrapper&amp;quot;&amp;gt; &amp;lt;div class=&amp;quot;wrapper element&amp;quot;&amp;gt; &amp;lt;span&amp;gt;Exercise 1&amp;lt;/span&amp;gt; &amp;lt;/div&amp;gt; &amp;lt;/div&amp;gt; &lt;/questiontext&gt; &lt;/question&gt; &lt;question id=&quot;1419238&quot;&gt; &lt;parent&gt;0&lt;/parent&gt; &lt;name&gt;_template_singleDropDown&lt;/name&gt; &lt;questiontext&gt; &amp;lt;div class=&amp;quot;wrapper&amp;quot;&amp;gt; &amp;lt;div class=&amp;quot;element wrapper&amp;quot;&amp;gt; &amp;lt;span&amp;gt;Exercise 2&amp;lt;/span&amp;gt; &amp;lt;/div&amp;gt; &amp;lt;/div&amp;gt; &lt;/questiontext&gt; &lt;/question&gt; &lt;/questions&gt; &lt;/question_category&gt; &lt;/question_categories&gt; </code></pre> <p>The element containing the HTML is <code>&lt;questiontext&gt;</code>, the HTML class to be renamed is <code>wrapper</code>, and the new class name should be <code>prefixed-wrapper</code>.</p> <p>I succeeded to loop through the XML, extracting the HTML and also to rename the class, but I don't know how to put everything together, so at the end I get an XML file with the renamed class names. This is my code so far:</p> <pre><code>from bs4 import BeautifulSoup with open('dummy_short.xml', 'r') as f: file = f.read() soup_xml = BeautifulSoup(file, 'xml') for questiontext in soup_xml.find_all('questiontext'): for singleclass in BeautifulSoup(questiontext.text, 'html.parser').find_all(class_='wrapper'): pos = singleclass.attrs['class'].index('wrapper') singleclass.attrs['class'][pos] = 'prefixed-wrapper' print(soup_xml) </code></pre> <p>Unfortunately, when printing soup_xml at the end, the contents are unchanged, i.e. the class names aren't renamed.</p> <p><strong>EDIT:</strong> Since one and the same class name can occur in very different and complex contexts (for example along with other classes, i.e. <code>class=&quot;xxx yyy wrapper zzz&quot;</code>), a static match isn't working. And instead of using complicated and non-comprehensible regexes, I have to use a parser like beautifulsoup (because they are made exactly for this purpose!).</p>
[ { "answer_id": 74670892, "author": "Hermann12", "author_id": 12621346, "author_profile": "https://Stackoverflow.com/users/12621346", "pm_score": 1, "selected": false, "text": "tree.write() import xml.etree.ElementTree as ET\nfrom html import escape, unescape\n\ntree = ET.parse('source.xml')\nroot = tree.getroot()\n\ndef replace_html(elem):\n dummyXML = ET.fromstring(elem)\n for htm in dummyXML.iter('div'):\n if htm.tag == \"div\" and htm.get('class') ==\"wrapper\":\n htm.set('class', \"prefixed-wrapper\") \n return ET.tostring(dummyXML, method='html').decode('utf-8')\n \nfor elem in root.iter(\"questiontext\"):\n html = replace_html(unescape(elem.text))\n elem.text = escape(html)\n \nwith open('new.xml', 'w') as f:\n f.write(f'<?xml version=\"1.0\" encoding=\"UTF-8\"?>')\n\nwith open('new.xml', 'a') as f:\n f.write(ET.tostring(root).decode('utf-8').replace('&amp;','&'))\n \"source.xml\" \"new.xml\" <questiontext>\n &lt;div class=&quot;prefixed-wrapper&quot;&gt;\n &lt;div class=&quot;wrapper element&quot;&gt;\n &lt;span&gt;Exercise 1&lt;/span&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n</questiontext>\n" }, { "answer_id": 74677048, "author": "Hermann12", "author_id": 12621346, "author_profile": "https://Stackoverflow.com/users/12621346", "pm_score": 0, "selected": false, "text": "from bs4 import BeautifulSoup\n#from xml.sax.saxutils import quoteattr, escape, unescape\nimport re\n\n# Get the XML soup\nwith open('source.xml', 'r') as f:\n file = f.read() \nsoup_xml = BeautifulSoup(file, 'xml')\n\ndef soup_htm(elm):\n \"\"\"Modify attributes according request \"\"\"\n # Get the html soup\n soup = BeautifulSoup(elm.string, 'html.parser')\n \n \n for elem in soup.find_all('div'):\n if elem.attrs== {'class': ['wrapper']}:\n elem['class'] = ['prefixed-wrapper']\n if elem.attrs== {'class': ['wrapper', 'element']}:\n elem['class'] = ['prefixed-wrapper', 'element']\n if elem.attrs== {'class': ['element', 'wrapper']}:\n elem['class'] = ['element', 'prefixed-wrapper'] \n return re.sub('\"','&quot;', str(soup))\n\n# Find element and replace it \nfor questiontext in soup_xml.find_all('questiontext'):\n htm_changed = soup_htm(questiontext)\n questiontext = questiontext.string.wrap(soup_xml.new_tag(\"questiontext\")).replace_with(htm_changed)\n \n# Print result\nprint(soup_xml.prettify())\n single/ double quotes" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1116675/" ]
74,669,406
<p>I have a form in Excel and I need to return data from a table in access. When executing an instruction like the image it returns the error &quot;Data Type Mismatch in Criterion Expression&quot;. I already reviewed the data types in the table and still could not resolve. What could be happening?</p> <pre><code> Sub pesquisar() Set rs = New ADODB.Recordset conectdb rs.Open &quot;SELECT * FROM TbApolice WHERE Contrato='&quot; &amp; UserForm.txt_certificado.Value &amp; &quot;'&quot;, db, adOpenKeyset, adLockReadOnly If UserForm.txt_certificado.Value &lt;&gt; &quot;&quot; Then UserForm.txt_nome = rs!Nome UserForm.txt_cpf = rs!CPF UserForm.txt_iniciovigencia = rs!Inicio_vigencia UserForm.txt_fimvigencia = rs!Fim_de_vigencia UserForm.txt_premio = rs!Premio Else MsgBox &quot;Segurado não localizado&quot;, vbInformation, &quot;LOCALIZAR&quot; End If If Not rs Is Nothing Then rs.Close Set rs = Nothing End If fechadb End Sub </code></pre> <p>I've already made some attempts to point break and debug the code, in addition to validating all fields and data types, but I didn't get any results.</p>
[ { "answer_id": 74669566, "author": "rwffh", "author_id": 4561966, "author_profile": "https://Stackoverflow.com/users/4561966", "pm_score": -1, "selected": false, "text": "rs.Open \"SELECT * FROM TbApolice WHERE Contrato='\" & UserForm.txt_certificado.Value & \"''\", db, adOpenKeyset, adLockReadOnly\n\n" }, { "answer_id": 74677306, "author": "CDP1802", "author_id": 12704593, "author_profile": "https://Stackoverflow.com/users/12704593", "pm_score": 0, "selected": false, "text": "Option Explicit\n\nSub pesquisar()\n\n Const SQL = \"SELECT * FROM TbApolice WHERE Contrato = ?\"\n\n Dim Db As ADODB.Connection, cmd As ADODB.Command\n Dim rs As ADODB.Recordset, sContrato As String, n As Long\n \n With UserForm\n sContrato = Trim(.txt_certificado.Value)\n If Len(sContrato) > 0 Then\n \n Set Db = conectdb(\"Database11.accdb\")\n Set cmd = New ADODB.Command\n With cmd\n .ActiveConnection = Db\n .CommandText = SQL\n .Parameters.Append .CreateParameter(\"p1\", adVarWChar, adParamInput, 255)\n Set rs = .Execute(n, sContrato)\n End With\n \n If rs.EOF Then\n MsgBox \"Segurado não localizado\", vbInformation, \"LOCALIZAR\"\n Else\n .txt_nome = rs!Nome\n .txt_cpf = rs!CPF\n .txt_iniciovigencia = rs!Inicio_vigencia\n .txt_fimvigencia = rs!Fim_de_vigencia\n .txt_premio = rs!Premio\n rs.Close\n Set rs = Nothing\n End If\n \n End If\n End With\n 'fechadb\n\nEnd Sub\n\nFunction conectdb(s As String) As ADODB.Connection\n Set conectdb = New ADODB.Connection\n conectdb.Open \"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\" & s\nEnd Function\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12829731/" ]
74,669,407
<p>I'm trying to create custom function in WordPress with ACF, and use it as a shortcode.</p> <p>What I want to do is quite simple:</p> <ul> <li>Get a field from ACF</li> <li>Check if the text is &quot;not found&quot; or something else</li> <li>If it's something else, I'll show an H2 and a sentence with field content.</li> <li>If its &quot;not found&quot; I don't want to show anything</li> </ul> <p>I tried various code, here's my last one:</p> <pre><code>// write a shortcode that creates a text if the field is not &quot;not found&quot; function show_alliance() { $alliance = get_field('field_6383d4b46deed'); if ($alliance !='not found'): { return '&lt;h2&gt;TITLE&lt;/h2&gt;&lt;p&gt;This is... '. $alliance .' &lt;/p&gt;'; } else: { return '';} } add_shortcode('alliance', 'show_alliance') </code></pre> <p>By WordPress always comes up with errors when I save my snippet. I can't find a way to make it work.</p> <p>(I use Code Snippets in WordPress)</p> <p>Any ideas? (I'm sure it's very simple...)</p> <p>--</p> <p>Tried different syntax, but WordPress never validates the code snippet.</p> <p>Last one is:</p> <p>`L’extrait de code que vous essayez d’enregistrer a produit une erreur fatale à la ligne 11 :</p> <p>syntax error, unexpected '}'`</p> <p>When I delete the } to put it a the end it tells me that I should not have it there...</p>
[ { "answer_id": 74669566, "author": "rwffh", "author_id": 4561966, "author_profile": "https://Stackoverflow.com/users/4561966", "pm_score": -1, "selected": false, "text": "rs.Open \"SELECT * FROM TbApolice WHERE Contrato='\" & UserForm.txt_certificado.Value & \"''\", db, adOpenKeyset, adLockReadOnly\n\n" }, { "answer_id": 74677306, "author": "CDP1802", "author_id": 12704593, "author_profile": "https://Stackoverflow.com/users/12704593", "pm_score": 0, "selected": false, "text": "Option Explicit\n\nSub pesquisar()\n\n Const SQL = \"SELECT * FROM TbApolice WHERE Contrato = ?\"\n\n Dim Db As ADODB.Connection, cmd As ADODB.Command\n Dim rs As ADODB.Recordset, sContrato As String, n As Long\n \n With UserForm\n sContrato = Trim(.txt_certificado.Value)\n If Len(sContrato) > 0 Then\n \n Set Db = conectdb(\"Database11.accdb\")\n Set cmd = New ADODB.Command\n With cmd\n .ActiveConnection = Db\n .CommandText = SQL\n .Parameters.Append .CreateParameter(\"p1\", adVarWChar, adParamInput, 255)\n Set rs = .Execute(n, sContrato)\n End With\n \n If rs.EOF Then\n MsgBox \"Segurado não localizado\", vbInformation, \"LOCALIZAR\"\n Else\n .txt_nome = rs!Nome\n .txt_cpf = rs!CPF\n .txt_iniciovigencia = rs!Inicio_vigencia\n .txt_fimvigencia = rs!Fim_de_vigencia\n .txt_premio = rs!Premio\n rs.Close\n Set rs = Nothing\n End If\n \n End If\n End With\n 'fechadb\n\nEnd Sub\n\nFunction conectdb(s As String) As ADODB.Connection\n Set conectdb = New ADODB.Connection\n conectdb.Open \"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\" & s\nEnd Function\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20676468/" ]
74,669,431
<p>I'm trying to change the color of the top border by passing the color value as props to the component, but It doesn't make any effects.</p> <p>I'm looking for a solution. Please help me!</p> <pre><code>export default function TargetsProgressInfo(props) { return ( &lt;ul&gt; &lt;span className={` after:border-[7px] after:w-4 ${props.colorTip} after:border-b-transparent`}&gt;&lt;/span&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div &gt; ) } **home.jsx** &lt;TargetsProgressInfo colorTip=&quot;after-border-t-red-600&quot;/&gt; </code></pre>
[ { "answer_id": 74669770, "author": "Necati Turan", "author_id": 4335325, "author_profile": "https://Stackoverflow.com/users/4335325", "pm_score": 0, "selected": false, "text": "<ul>\n <li className=\"after:border-[7px] after:w-4 after:border-t-{props.colorTip} after:border-b-transparent\">\n {/* ... */}\n </li>\n</ul>\n" }, { "answer_id": 74670500, "author": "Zana Suleiman", "author_id": 20675823, "author_profile": "https://Stackoverflow.com/users/20675823", "pm_score": 1, "selected": false, "text": " <TargetsProgressInfo colorTip=\"after:border-t-red-600\"/>\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20675823/" ]
74,669,460
<p>When I try to send mail from a web page - on the mail.bg and abv.bg mail I receive letters like this :</p> <pre><code>РќРѕРІРѕ </code></pre> <p>where I must receive &quot;Ново&quot; What can I do so I can fix it - on gmail.com I receive the normal &quot;Ново&quot; and when I use echo - I also receive the normal &quot;Ново&quot; , but on the mail.bg and abv.bg - I receive this strange words...is there something wrong with the encoding ?</p> <pre><code>&lt;?php header('Content-Type: text/html; charset=utf-8'); header('Content-Transfer-Encoding: base64'); $errors = ''; $myemail = 'example@mail.bg';//&lt;-----Put Your email address here. if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])) { $errors .= &quot;\n Error: all fields are required&quot;; } $name = $_POST['name']; $email_address = $_POST['email']; $message = $_POST['message']; $subject = $_POST['subject']; if (!preg_match( &quot;/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i&quot;, $email_address)) { $errors .= &quot;\n Error: Invalid email address&quot;; } if( empty($errors)) { $to = $myemail; $email_subject = &quot;$subject, $name&quot;; $email_body = &quot;You have received a new message. &quot;. &quot; Here are the details:\n Name: $name \n Email: $email_address \n Message \n $message&quot;; $headers = &quot;From: $myemail\n&quot;; $headers .= &quot;Reply-To: $email_address&quot;; $headers .= 'Content-Type: text/plain; charset=utf-8' . &quot;\r\n&quot;; $headers .= 'Content-Transfer-Encoding: base64'. &quot;\n\r\n&quot;; mail($to, '=?utf-8?B?'.base64_encode($email_subject).'?=', $email_body, $headers); //redirect to the 'thank you' page header('Location: contact-form-thank-you.html'); } ?&gt; </code></pre> <p>When I try to send mail from a web page - on the mail.bg and abv.bg mail I receive letters like this :</p> <pre><code>РќРѕРІРѕ </code></pre> <p>where I must receive &quot;Ново&quot; What can I do so I can fix it - on gmail.com I receive the normal &quot;Ново&quot; and when I use echo - I also receive the normal &quot;Ново&quot; , but on the mail.bg and abv.bg - I receive this strange words...is there something wrong with the encoding ?</p>
[ { "answer_id": 74669483, "author": "Necati Turan", "author_id": 4335325, "author_profile": "https://Stackoverflow.com/users/4335325", "pm_score": -1, "selected": false, "text": "mb_internal_encoding(\"UTF-8\");\n" }, { "answer_id": 74670256, "author": "Ken Lee", "author_id": 11854986, "author_profile": "https://Stackoverflow.com/users/11854986", "pm_score": 1, "selected": true, "text": "Content-Transfer-Encoding: base64 base64_encode $email_body \\r\\n $headers = \"From: $myemail\\n\"; \n$headers .= \"Reply-To: $email_address\";\n$headers .= 'Content-Type: text/plain; charset=utf-8' . \"\\r\\n\";\n$headers .= 'Content-Transfer-Encoding: base64'. \"\\n\\r\\n\";\nmail($to, '=?utf-8?B?'.base64_encode($email_subject).'?=', $email_body, $headers);\n\n $email_body=base64_encode($email_body);\n\n$headers = \"From: $myemail\\r\\n\"; \n$headers .= \"Reply-To: $email_address\\r\\n\";\n$headers .= 'Content-Type: text/plain; charset=utf-8' . \"\\r\\n\";\n$headers .= 'Content-Transfer-Encoding: base64'. \"\\r\\n\";\nmail($to, '=?utf-8?B?'.base64_encode($email_subject).'?=', $email_body, $headers);\n Content-Transfer-Encoding: base64 specification //$email_body=base64_encode($email_body);\n\n$headers = \"From: $myemail\\r\\n\"; \n$headers .= \"Reply-To: $email_address\\r\\n\";\n$headers .= 'Content-Type: text/plain; charset=utf-8' . \"\\r\\n\";\n//$headers .= 'Content-Transfer-Encoding: base64'. \"\\r\\n\";\nmail($to, '=?utf-8?B?'.base64_encode($email_subject).'?=', $email_body, $headers);\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20659496/" ]
74,669,469
<p>I'm working a project for school in T-SQL.</p> <p>I have an Advisors table that is fully set up. I'm trying to update the Student table so that each StudentID is associated with an AdvisorID (referencing the Advisors table). The Student table is fully set up, minus the AdvisorID column. Both tables have Name_Full, Name_First, and Name_Last for every Advisor and Student in the respective tables.</p> <p>I'm trying to find all students that have a Name_Last starting with 'R'. I know for a fact that there is at least one student that qualifies since there is a student with a Name_Last = 'Ramos'.</p> <p>I tried searching for every student with a Name_Last starting with the letter 'R' using the following code.</p> <pre><code>SELECT Name_Last FROM Student WHERE Name_Last IN ('R%') </code></pre> <p>This query returns nothing. I've tried using '=' and 'LIKE' instead of 'IN' and those did not work either. I've tried using 'CONTAINS' which also didn't work. I tried:</p> <pre><code>WHERE CHARINDEX('R', Name_Last) = 1 </code></pre> <p>This did not work either. Once I get this working, I'd like to be able to copy it into a WHERE clause using BETWEEN, as I want to assign an AdvisorID to students within certain ranges.</p>
[ { "answer_id": 74669629, "author": "Özenç Çelik", "author_id": 8506390, "author_profile": "https://Stackoverflow.com/users/8506390", "pm_score": -1, "selected": false, "text": "SELECT Name_Last\n FROM Student\n WHERE Name_Last IN ('R%')\n SELECT Name_Last\n FROM Student\n WHERE Name_Last LIKE '% R%'\n" }, { "answer_id": 74669713, "author": "Faraday12", "author_id": 17480944, "author_profile": "https://Stackoverflow.com/users/17480944", "pm_score": 1, "selected": false, "text": "SELECT Name_Last\n FROM Student\n where Name_Last like ' R%'\n" }, { "answer_id": 74681309, "author": "Vitaly Borisov", "author_id": 4119599, "author_profile": "https://Stackoverflow.com/users/4119599", "pm_score": 0, "selected": false, "text": "SELECT Name_Last\nFROM Student\nWHERE LEFT(LTRIM(Name_Last),1) = 'R'\n;\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17480944/" ]
74,669,479
<p>So I havd a problem</p> <p>1 Im trying to make the website responsive and the paragraph ( and the <h1>World's Biggest University</h1> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget iaculis dui, quis dapibus diam. Etiam tellus erat, consectetur eget eros sit amet, tincidunt consectetur erat</p> Visit Us To Know More ) is showing in the menu and it should be behind the nav it so the red nav should show only half the text</p> <p>this is the problem <a href="https://i.stack.imgur.com/6dQdP.png" rel="nofollow noreferrer">enter image description here</a> and it should look like this <a href="https://i.stack.imgur.com/LW7GR.png" rel="nofollow noreferrer">enter image description here</a></p> <p>this is the code</p> <pre><code>@media(max-width: 700px) { .text-box h1 { font-size: 20px; } .nav-links ul li { display: block; } .nav-links { position: absolute; background: #f44336; height: 100vh; width: 200px; top: 0; right: 0; text-align: left; z-index: 2; } } </code></pre> <p>this is the whole css code</p> <pre><code>* { margin: 0; padding: 0; font-family: 'Poppins', sans-serif; } .header { min-height: 100vh; width: 100%; background-image: linear-gradient(rgba(4, 9, 30, 0.7), rgba(4, 9, 30, 0.7)), url(./img/banner.png); background-position: center; background-size: cover; position: relative; } nav { display: flex; padding: 2% 6%; justify-content: space-between; align-items: center; position: sticky; } nav img { width: 150px; } .nav-links { flex: 1; text-align: right; } .nav-links ul li { list-style: none; display: inline-block; padding: 8px 12px; position: relative; } .nav-links ul li a { color: #fff; text-decoration: none; font-size: 13px; } .nav-links ul li::after { content: ''; width: 0%; height: 2px; background: #a85d58; display: block; margin: auto; transition: 0.5s; } .nav-links ul li:hover::after { width: 100%; } .text-box { width: 90%; color: #fff; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; } .text-box h1 { font-size: 62px; } .text-box p { margin: 10px 0 40px; font-size: 14px; color: #fff; } .hero-btn { display: inline-block; text-decoration: none; color: #fff; border: 1px solid #fff; padding: 12px 34px; font-size: 13px; background: transparent; position: relative; cursor: pointer; } .hero-btn:hover { border: 1px solid #f44336; background: #f44336; transition: 1s; } @media(max-width: 700px) { .text-box h1 { font-size: 20px; } .nav-links ul li { display: block; } .nav-links { position: absolute; background: #f44336; height: 100vh; width: 200px; top: 0; right: 0; text-align: left; z-index: 2; } } </code></pre> <p>and this is the html code</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;University&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt; &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.googleapis.com&quot;&gt; &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,700;1,700&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.2.1/css/fontawesome.min.css&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;section class=&quot;header&quot;&gt; &lt;nav&gt; &lt;a href=&quot;index.html&quot;&gt;&lt;img src=&quot;img/logo.png&quot;&gt;&lt;/a&gt; &lt;div class=&quot;nav-links&quot;&gt; &lt;i class=&quot;fa fa-times&quot;&gt;&lt;/i&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=&quot;&quot;&gt;HOME&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;&quot;&gt;ABOUT&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;&quot;&gt;COURSE&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;&quot;&gt;BLOG&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;&quot;&gt;CONTACT&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;i class=&quot;fa fa-bars&quot;&gt;&lt;/i&gt; &lt;/nav&gt; &lt;div class=&quot;text-box&quot;&gt; &lt;h1&gt;World's Biggest University&lt;/h1&gt; &lt;p&gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget iaculis dui, quis dapibus diam. Etiam tellus erat, consectetur eget eros sit amet, tincidunt consectetur erat&lt;/p&gt; &lt;a href=&quot;&quot; class=&quot;hero-btn&quot;&gt;Visit Us To Know More&lt;/a&gt; &lt;/div&gt; &lt;/section&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 74669664, "author": "Jameson", "author_id": 20637346, "author_profile": "https://Stackoverflow.com/users/20637346", "pm_score": 2, "selected": false, "text": "<!DOCTYPE html>\n<html>\n\n<head>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>University</title>\n <link rel=\"stylesheet\" href=\"style.css\">\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n <link href=\"https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,700;1,700&display=swap\" rel=\"stylesheet\">\n <link rel=\"stylesheet\"\n href=\"https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.2.1/css/fontawesome.min.css\">\n</head>\n\n<body>\n <header class=\"header\">\n <nav>\n <a href=\"index.html\"><img src=\"img/logo.png\"></a>\n <div class=\"nav-links\">\n <i class=\"fa fa-times\"></i>\n <ul>\n <li><a href=\"\">HOME</a></li>\n <li><a href=\"\">ABOUT</a></li>\n <li><a href=\"\">COURSE</a></li>\n <li><a href=\"\">BLOG</a></li>\n <li><a href=\"\">CONTACT</a></li>\n </ul>\n </div>\n <i class=\"fa fa-bars\"></i>\n </nav>\n </header>\n <main>\n <div class=\"text-box\">\n <h1>World's Biggest University</h1>\n <p>\n Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget iaculis dui, quis dapibus diam.\n Etiam tellus erat, consectetur eget eros sit amet, tincidunt consectetur erat</p>\n <a href=\"\" class=\"hero-btn\">Visit Us To Know More</a>\n </div>\n </main>\n</body>\n\n</html>\n * {\n margin: 0;\n padding: 0;\n font-family: 'Poppins', sans-serif;\n}\n\nbody {\n display: grid;\n height: fit-content;\n grid-template-areas:\n 'header'\n 'section'\n ;\n}\n\nmain {\n grid-area: section;\n display: flex;\n width: auto;\n background-image: linear-gradient(rgba(4, 9, 30, 0.7), rgba(4, 9, 30, 0.7)), url(./img/banner.png);\n height: 100vh;\n vertical-align: middle;\n}\n\n.text-box {\n background-color: gray;\n}\n\nheader {\n grid-area: header;\n width: auto;\n background-image: linear-gradient(rgba(4, 9, 30, 0.7), rgba(4, 9, 30, 0.7)), url(./img/banner.png);\n background-position: center;\n background-size: cover;\n position: relative;\n}\n\n\nnav {\n display: flex;\n padding: 2% 6%;\n justify-content: space-between;\n align-items: center;\n position: sticky;\n z-index: 1000;\n}\n\nnav img {\n width: 150px;\n}\n\n.nav-links {\n flex: 1;\n text-align: right;\n}\n\n.nav-links ul li {\n list-style: none;\n display: inline-block;\n padding: 8px 12px;\n position: relative;\n}\n\n.nav-links ul li a {\n color: #fff;\n text-decoration: none;\n font-size: 13px;\n}\n\n.nav-links ul li::after {\n content: '';\n width: 0%;\n height: 2px;\n background: #a85d58;\n display: block;\n margin: auto;\n transition: 0.5s;\n}\n\n.nav-links ul li:hover::after {\n width: 100%;\n}\n\n.text-box {\n padding-top: 5rem;\n height: 100%;\n width: 100%;\n color: #fff;\n margin: 0 auto;\n text-align: center;\n\n}\n\n.text-box h1 {\n font-size: 62px;\n}\n\n.text-box p {\n margin: 10px 0 40px;\n font-size: 14px;\n color: #fff;\n}\n\n.hero-btn {\n display: inline-block;\n text-decoration: none;\n color: #fff;\n border: 1px solid #fff;\n padding: 12px 34px;\n font-size: 13px;\n background: transparent;\n position: relative;\n cursor: pointer;\n}\n\n.hero-btn:hover {\n border: 1px solid #f44336;\n background: #f44336;\n transition: 1s;\n}\n\n@media all and (max-width: 700px) {\n body {\n display: grid;\n grid-template-areas:\n 'section header'\n 'section header'\n ;\n }\n\n .text-box h1 {\n padding-top: 10rem;\n font-size: 20px;\n }\n\n .nav-links ul li {\n display: block;\n }\n\n header {\n background: #f44336;\n text-align: left;\n }\n}\n" }, { "answer_id": 74670165, "author": "KnightTheLion", "author_id": 20432259, "author_profile": "https://Stackoverflow.com/users/20432259", "pm_score": 2, "selected": true, "text": "* {\n margin: 0;\n padding: 0;\n font-family: 'Poppins', sans-serif;\n}\n\nbody{ \n z-index: 0;\n}\n\n.header {\n min-height: 100vh;\n width: 100%;\n background-image: linear-gradient(rgba(4, 9, 30, 0.7), rgba(4, 9, 30, 0.7)), url(./img/banner.png);\n background-position: center;\n background-size: cover;\n position: relative;\n}\n\nnav {\n display: flex;\n padding: 2% 6%;\n justify-content: space-between;\n align-items: center;\n position: sticky;\n}\n\nnav img {\n width: 150px;\n}\n\n.nav-links {\n flex: 1;\n text-align: right;\n}\n\n.nav-links ul li {\n list-style: none;\n display: inline-block;\n padding: 8px 12px;\n position: relative;\n}\n\n.nav-links ul li a {\n color: #fff;\n text-decoration: none;\n font-size: 13px;\n}\n\n.nav-links ul li::after {\n content: '';\n width: 0%;\n height: 2px;\n background: #a85d58;\n display: block;\n margin: auto;\n transition: 0.5s;\n}\n\n.nav-links ul li:hover::after {\n width: 100%;\n}\n\n.text-box {\n width: 90%;\n color: #fff;\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n text-align: center;\n}\n\n.text-box h1 {\n font-size: 62px;\n}\n\n.text-box p {\n margin: 10px 0 40px;\n font-size: 14px;\n color: #fff;\n}\n\n.hero-btn {\n display: inline-block;\n text-decoration: none;\n color: #fff;\n border: 1px solid #fff;\n padding: 12px 34px;\n font-size: 13px;\n background: transparent;\n position: relative;\n cursor: pointer;\n}\n\n.hero-btn:hover {\n border: 1px solid #f44336;\n background: #f44336;\n transition: 1s;\n}\n\n@media(max-width: 700px) {\n .text-box h1 {\n font-size: 20px;\n }\n\n .nav-links ul li {\n display: block;\n }\n\n .nav-links{\n position: absolute;\n background: #f44336;\n height: 100vh;\n width: 200px;\n top: 0;\n right: 0;\n text-align: left;\n z-index: 20; /*This index brings forth the nav links */\n }\n nav {\n z-index: 19; /* this brings the nav forward as well */\n }\n} <!DOCTYPE html>\n<html>\n\n<head>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>University</title>\n <link rel=\"stylesheet\" href=\"style.css\">\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n <link href=\"https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,700;1,700&display=swap\" rel=\"stylesheet\">\n <link rel=\"stylesheet\" \nhref=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css\">\n<!--This is the correct link to the fontawesome icons you want-->\n</head>\n\n<body>\n\n <section class=\"header\">\n <nav>\n <a href=\"index.html\"><img src=\"img/logo.png\"></a>\n <div class=\"nav-links\">\n <i class=\"fa-solid fa-xmark\"></i><!--This is a 6.2.1 version icon-->\n <ul>\n <li><a href=\"\">HOME</a></li>\n <li><a href=\"\">ABOUT</a></li>\n <li><a href=\"\">COURSE</a></li>\n <li><a href=\"\">BLOG</a></li>\n <li><a href=\"\">CONTACT</a></li>\n </ul>\n </div>\n <i class=\"fa-solid fa-bars\"></i><!--This is a 6.2.1 version icon-->\n </nav>\n\n <div class=\"text-box\">\n <h1>World's Biggest University</h1>\n <p>\n Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget iaculis dui, quis dapibus diam.\n Etiam tellus erat, consectetur eget eros sit amet, tincidunt consectetur erat</p>\n <a href=\"\" class=\"hero-btn\">Visit Us To Know More</a>\n </div>\n\n\n </section>\n\n</body>\n\n</html>" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20675904/" ]
74,669,492
<p>I have cards that render it from an api that has many objs including date and I wane to render the cards based on recent dates ... What I need is to sort based on recent dates using react</p> <p>snippets of code also a link that works <a href="https://codesandbox.io/s/sleepy-glitter-ru6dvu?file=/src/App.js:166-207" rel="nofollow noreferrer">https://codesandbox.io/s/sleepy-glitter-ru6dvu?file=/src/App.js:166-207</a></p> <p>my api <a href="https://api.npoint.io/d275425a434e02acf2f7" rel="nofollow noreferrer">https://api.npoint.io/d275425a434e02acf2f7</a></p> <pre><code> { filteredDate &amp;&amp; filteredCat?.map((list) =&gt; { if (list.showOnHomepage === &quot;yes&quot;) { const date = format( new Date(list.publishedDate), &quot;EEE dd MMM yyyy&quot; ); const showCat = news.map((getid) =&gt; { if (getid.id == list.categoryID) return getid.name; }); // const rec = list.publishedDate.sort((date1, date2) =&gt; date1 - date2); return ( &lt;Card className=&quot; extraCard col-lg-3&quot; style={{ width: &quot;&quot; }} id={list.categoryID} &gt; &lt;Card.Img variant=&quot;top&quot; src={list.urlToImage} alt=&quot;Image&quot; /&gt; &lt;Card.Body&gt; &lt;Card.Title className=&quot;textTitle&quot;&gt; {list.title} &lt;/Card.Title&gt; &lt;Card.Text&gt;&lt;/Card.Text&gt; &lt;small className=&quot;text-muted d-flex&quot;&gt; &lt;FaRegCalendarAlt className=&quot;m-1&quot; style={{ color: &quot;#0aceff&quot; }} /&gt; {date} &lt;/small&gt; &lt;div style={{ color: &quot;#0aceff&quot; }} className=&quot;d-flex justify-content-between&quot; &gt; &lt;Button variant=&quot;&quot; className={classes[&quot;btn-cat&quot;]}&gt; {showCat} &lt;/Button&gt; &lt;div&gt; &lt;FaRegHeart /&gt; &lt;p&gt; &lt;FaLink /&gt; &lt;BrowserRouter&gt; {/* &lt;Link to='./Newsitem.js'&gt; {''} &lt;button &gt;Close&lt;/button&gt; &lt;/Link&gt; */} &lt;/BrowserRouter&gt; {/* &lt;button onClick={() =&gt; window.open(&quot;/src/components/News/Newsitem&quot;) } &gt; Go to another &lt;/button&gt; */} &lt;a href=&quot;/Newsitem&quot; target=&quot;/src/components/News/Newsitem&quot; rel=&quot;noopener noreferrer&quot; &gt; &lt;button &gt;Go to another page&lt;/button&gt; &lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/Card.Body&gt; &lt;/Card&gt; ); } })} &lt;/div&gt; } &lt;/div&gt; </code></pre>
[ { "answer_id": 74670228, "author": "Zion", "author_id": 2179970, "author_profile": "https://Stackoverflow.com/users/2179970", "pm_score": -1, "selected": false, "text": "News fetchDataList const fetchDataList = () => {\n setIsLoading(true);\n\n return fetch(\"https://api.npoint.io/d275425a434e02acf2f7\")\n .then((response) => response.json())\n .then((data) => {\n // sort news \n data.News.sort(function(x, y) {\n if (x.publishedDate > y.publishedDate) {\n return -1;\n }\n if (x.publishedDate < y.publishedDate) {\n return 1;\n }\n return 0;\n });\n // **************\n setLists(data.News);\n setIsLoading(false);\n });\n};\n" }, { "answer_id": 74670950, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 0, "selected": false, "text": "const [news, setNews] = useState([]);\n\nconst fetchNews = () => {\n fetch(\"https://api.npoint.io/d275425a434e02acf2f7\").then((response) => response.json()).then((data) => {\n const sortedNews = data.News.sort(function(a, b) {\n const firstPublishedDate = new Date(a.publishedDate);\n const secondPublishedDate = new Date(b.publishedDate);\n return firstPublishedDate.getTime() - secondPublishedDate.getTime();\n });\n setNews(sortedNews);\n }).catch((error) => {\n console.log(error);\n });\n};\n\nuseEffect(() => {\n fetchNews();\n}, []);\n\nreturn (\n <div>\n {\n news.map((newsItem) => {\n return (\n ...\n );\n })\n }\n </div>\n);\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20676584/" ]
74,669,511
<p>I am working on Reactjs and using nextjs, Right now i am trying to get value of &quot;textarea&quot; and &quot;dropdown/select&quot;, but i am getting empty result,How can i do this ? I tried with following code</p> <pre><code> const msgChange = (e) =&gt; { const value = e.target.value; setState({ ...state, [e.target.msg]: value }); }; const countryChange = (e) =&gt; { const value = e.target.value; setState({ ...state, [e.target.country]: value }); }; const handleSubmit = (e) =&gt; { var msg = state.msg; alert('msg is '+msg); } &lt;form className='row' onSubmit={handleSubmit}&gt; &lt;select className=&quot;form-select&quot; aria-label=&quot;Default select example&quot; onChange={countryChange} name=&quot;country&quot;&gt; &lt;option selected&gt;Country&lt;/option&gt; &lt;option value=&quot;abc&quot;&gt;abc&lt;/option&gt; &lt;option value=&quot;xyz&quot;&gt;xyz&lt;/option&gt; &lt;/select&gt; &lt;textarea onChange={msgChange} name=&quot;msgs&quot;&gt;&lt;/textarea&gt; &lt;input type=&quot;submit&quot; value=&quot;send&quot; className='sendbtn' /&gt; &lt;/form&gt; </code></pre>
[ { "answer_id": 74669604, "author": "Andy", "author_id": 1377002, "author_profile": "https://Stackoverflow.com/users/1377002", "pm_score": 2, "selected": false, "text": "e.target.msg name const { useEffect, useState } = React;\n\nfunction Example() {\n\n const [ state, setState ] = useState({});\n\n const handleChange = (e) => {\n \n // Destructure the name and value from\n // the changed element\n const { name, value } = e.target;\n setState({ ...state, [name]: value });\n };\n\n // Log the change in state\n useEffect(() => console.log(state), [state]);\n\n return (\n <form className='row'>\n <select\n className=\"form-select\"\n aria-label=\"Default select example\"\n onChange={handleChange}\n name=\"country\"\n >\n <option selected disabled>Country</option>\n <option value=\"abc\">abc</option>\n <option value=\"xyz\">xyz</option>\n </select>\n <textarea\n onChange={handleChange}\n name=\"msg\"\n ></textarea>\n </form>\n );\n\n}\n\nReactDOM.render(\n <Example />,\n document.getElementById('react')\n); <script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js\"></script>\n<div id=\"react\"></div>" }, { "answer_id": 74669628, "author": "Rohit Khandelwal", "author_id": 15220748, "author_profile": "https://Stackoverflow.com/users/15220748", "pm_score": 1, "selected": false, "text": "onChange textArea select useState const [state, setState] = useState({});\n const msgChange = (e) => {\n const value = e.target.value;\n setState({\n ...state,\n [e.target.name]: value\n });\n};\n\nconst countryChange = (e) => {\n const value = e.target.value;\n setState({\n ...state,\n [e.target.name]: value\n });\n};\n const handleSubmit = (e) => {\n const msg = state.msgs;\n const country = state.country;\n console.log(\"message ---->\", msg, \"country --->\", country); \n};\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20641395/" ]
74,669,545
<p>I want to make multiple calls for which I have to wait for the answer, and afterwards I want to group all responses in an array. I've not succeeded to do this.</p> <p>The <code>res</code> constant in code below still retains the array of promises, not their results. I have no idea what else to try. No other stackoverflow answers have been helpful.</p> <p>What I've tried:</p> <pre><code>const getProjectData = async (projectID) =&gt; await callAPI(`/projects/${projectID}`); const solve = async () =&gt; { const projects = []; currentUserProjectIDs.forEach((project) =&gt; { projects.push(getProjectData(project)); }); console.log(&quot;projects&quot;, projects); const res = await Promise.all(projects); console.log(&quot;solve res&quot;, res); return res; }; const res = await solve(); console.log(&quot;res&quot;, res); </code></pre> <p>Below is the result of the last console log:</p> <pre><code> res [ Response { size: 0, timeout: 0, [Symbol(Body internals)]: { body: [PassThrough], disturbed: false, error: null }, [Symbol(Response internals)]: { url: 'http://localhost:4000/projects/1', status: 200, statusText: 'OK', headers: [Headers], counter: 0 } }, Response { size: 0, timeout: 0, [Symbol(Body internals)]: { body: [PassThrough], disturbed: false, error: null }, [Symbol(Response internals)]: { url: 'http://localhost:4000/projects/4', status: 200, statusText: 'OK', headers: [Headers], counter: 0 } } ] </code></pre> <p><code>callAPI</code> function:</p> <pre><code>export const callAPI = async (path, body, method = &quot;GET&quot;) =&gt; { const config = { method: method, headers: { &quot;Content-Type&quot;: &quot;application/json&quot;, }, }; if (body) { config.body = JSON.stringify(body); } const URL = `${process.env.HOST}${path}`; return await fetch(URL, config); }; </code></pre> <p>EDIT: I have tried another way, but still unsuccessful. In the code below, the console.log inside the second <code>.then()</code> logs the correct data, but the returned <code>prj</code> is still an empty array...</p> <pre><code>const solve = async () =&gt; { const projects = []; currentUserProjectIDs.map((p) =&gt; { callAPI(`/projects/${p}`) .then((r) =&gt; { return r.json(); }) .then((a) =&gt; { console.log(&quot;a&quot;, a); projects.push(a); return a; }); }); return projects; }; const prj = await solve(); console.log(&quot;prj&quot;, prj); </code></pre>
[ { "answer_id": 74670078, "author": "helloitsjoe", "author_id": 8852158, "author_profile": "https://Stackoverflow.com/users/8852158", "pm_score": 3, "selected": true, "text": ".map Promise.all const solve = async () => {\n const projects = currentUserProjectIDs.map((p) => {\n return callAPI(`/projects/${p}`)\n .then((r) => {\n return r.json();\n });\n });\n return Promise.all(projects);\n };\n\n const prj = await solve();\n console.log(\"prj\", prj);\n .then .catch" }, { "answer_id": 74670324, "author": "ivanatias", "author_id": 17195992, "author_profile": "https://Stackoverflow.com/users/17195992", "pm_score": 1, "selected": false, "text": "export const callAPI = async (path, body, method = 'GET') => {\n const config = {\n method: method,\n headers: {\n 'Content-Type': 'application/json'\n }\n }\n\n if (body) {\n config.body = JSON.stringify(body)\n }\n\n const URL = `${process.env.HOST}${path}`\n const res = await fetch(URL, config)\n\n if (!res.ok) throw new Error('Error fetching data')\n\n return res.json()\n}\n\nconst getProjectData = (projectID) => callAPI(`/projects/${projectID}`)\n\nconst solve = () => {\n const projects = currentUserProjectIDs.map((project) => {\n return getProjectData(project)\n })\n\n return Promise.all(projects)\n}\n\nsolve()\n .then((data) => console.log(data))\n .catch((err) => console.error(err))\n json() Response" }, { "answer_id": 74670613, "author": "Alexandr Chazov", "author_id": 15806432, "author_profile": "https://Stackoverflow.com/users/15806432", "pm_score": 0, "selected": false, "text": " const getProjectData = async (projectID) => await callAPI(`/projects/${projectID}`);\n \n const solve = async () => {\n const res = await Promise.all(\n currentUserProjectIDs\n .map(id => getProjectData(id)\n .then(res => res.json())\n );\n return res;\n };\n const res = await solve();\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14523632/" ]
74,669,548
<p>`` hi everyone, I want to take color as input and then change the color of text according to it but it's not working can anybody help me.</p> <pre><code>import React, {useState} from 'react' export default function Textform(props) { //this is function const newColor =()=&gt;{ const x = document.getElementById(&quot;mybox&quot;) let newc =color; if(x.style.color===&quot;black&quot;){ x.style.color = setcolor(newc) } else{ x.style.color = &quot;black&quot; } } const changeColor =(event)=&gt;{ setcolor(event.target.value); } const onChange =(event)=&gt;{ setText(event.target.value); } const [text, setText] = useState(&quot;&quot;); const [color, setcolor] = useState(&quot;&quot;) return ( &lt;&gt; //text area input &lt;div className=&quot;mb-3&quot;&gt; &lt;textarea className=&quot;form-control&quot; value={text} onChange={onChange} placeholder=&quot;Enter text &quot; name=&quot;&quot; id=&quot;mybox&quot; rows=&quot;8&quot;&gt;&lt;/textarea&gt; &lt;/div&gt; //our color choice input &lt;div className=&quot;mb-3&quot;&gt; &lt;textarea className=&quot;form-control&quot; value={color} onChange={changeColor} placeholder=&quot;Enter your color choice&quot; name=&quot;&quot; id=&quot;mybox&quot; rows=&quot;3&quot;&gt;&lt;/textarea&gt; &lt;/div&gt; //this is my button &lt;button className=&quot;btn btn-primary mx-1&quot; onClick={newColor}&gt; Change Color&lt;/button&gt; &lt;/&gt; ) } </code></pre> <p>I tried to create a text Area which take text as input and another text Area which take color as input and then created a button. when we press the button, it will change the color of text as per our choice. but I am going wrong in implementing this logic.</p>
[ { "answer_id": 74670078, "author": "helloitsjoe", "author_id": 8852158, "author_profile": "https://Stackoverflow.com/users/8852158", "pm_score": 3, "selected": true, "text": ".map Promise.all const solve = async () => {\n const projects = currentUserProjectIDs.map((p) => {\n return callAPI(`/projects/${p}`)\n .then((r) => {\n return r.json();\n });\n });\n return Promise.all(projects);\n };\n\n const prj = await solve();\n console.log(\"prj\", prj);\n .then .catch" }, { "answer_id": 74670324, "author": "ivanatias", "author_id": 17195992, "author_profile": "https://Stackoverflow.com/users/17195992", "pm_score": 1, "selected": false, "text": "export const callAPI = async (path, body, method = 'GET') => {\n const config = {\n method: method,\n headers: {\n 'Content-Type': 'application/json'\n }\n }\n\n if (body) {\n config.body = JSON.stringify(body)\n }\n\n const URL = `${process.env.HOST}${path}`\n const res = await fetch(URL, config)\n\n if (!res.ok) throw new Error('Error fetching data')\n\n return res.json()\n}\n\nconst getProjectData = (projectID) => callAPI(`/projects/${projectID}`)\n\nconst solve = () => {\n const projects = currentUserProjectIDs.map((project) => {\n return getProjectData(project)\n })\n\n return Promise.all(projects)\n}\n\nsolve()\n .then((data) => console.log(data))\n .catch((err) => console.error(err))\n json() Response" }, { "answer_id": 74670613, "author": "Alexandr Chazov", "author_id": 15806432, "author_profile": "https://Stackoverflow.com/users/15806432", "pm_score": 0, "selected": false, "text": " const getProjectData = async (projectID) => await callAPI(`/projects/${projectID}`);\n \n const solve = async () => {\n const res = await Promise.all(\n currentUserProjectIDs\n .map(id => getProjectData(id)\n .then(res => res.json())\n );\n return res;\n };\n const res = await solve();\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19189932/" ]
74,669,565
<p>Innocent React question here.</p> <p>I have a <code>useEffect</code> method that closes a modal on the <code>escape</code> keypress, that is duplicated a few times in my code, that looks like this:</p> <pre><code>const [shouldShowModal, setShouldShowModal] = useProfileModal(); useEffect(() =&gt; { const closeModalOnEscape = (e: KeyboardEvent | any): void =&gt; { if (e.key === &quot;Escape&quot;) setShouldShowModal(false); }; document.addEventListener(&quot;keydown&quot;, closeModalOnEscape); return () =&gt; { document.removeEventListener(&quot;keydown&quot;, closeModalOnEscape); }; }, [setShouldShowModal]); </code></pre> <p>Is there a way I can define the <code>useEffect</code> piece to use across multiple components?</p>
[ { "answer_id": 74669594, "author": "Necati Turan", "author_id": 4335325, "author_profile": "https://Stackoverflow.com/users/4335325", "pm_score": 0, "selected": false, "text": "// Define a custom hook to handle the keydown event\nfunction useCloseModalOnEscape(toggleModal) {\n useEffect(() => {\n const closeModalOnEscape = (e: KeyboardEvent | any): void => {\n if (e.key === \"Escape\") toggleModal({ shouldShowModal: false });\n };\n document.addEventListener(\"keydown\", closeModalOnEscape);\n return () => {\n document.removeEventListener(\"keydown\", closeModalOnEscape);\n };\n }, [toggleModal]);\n}\n\n// Define a component that uses the custom hook\nfunction MyComponent() {\n const [{ shouldShowModal, profile }, toggleModal] = useProfileModal();\n\n // Call the custom hook to handle the keydown event\n useCloseModalOnEscape(toggleModal);\n\n // Other component code...\n}\n" }, { "answer_id": 74669607, "author": "Samathingamajig", "author_id": 12101554, "author_profile": "https://Stackoverflow.com/users/12101554", "pm_score": 2, "selected": true, "text": "const useCloseModalOnEscape = (setShouldShowModal) => {\n useEffect(() => {\n const closeModalOnEscape = (e: KeyboardEvent | any): void => {\n if (e.key === \"Escape\") setShouldShowModal(false);\n };\n document.addEventListener(\"keydown\", closeModalOnEscape);\n return () => {\n document.removeEventListener(\"keydown\", closeModalOnEscape);\n };\n }, [setShouldShowModal]);\n}\n const [shouldShowModal, setShouldShowModal] = useProfileModal();\n\nuseCloseModalOnEscape(setShouldShowModal);\n setShouldShowModal useCloseModalOnEscape useProfileModal useEffect useCloseModalOnEscape useProfileModal" }, { "answer_id": 74669940, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 1, "selected": false, "text": "useProfileModal useProfileModal const [shouldShowModal, setShouldShowModal] = useProfileModal();\n useProfileModal const useProfileModal = () => {\n // ...\n useEffect(() => {\n const closeModalOnEscape = (e: KeyboardEvent | any): void => {\n if (e.key === \"Escape\") setShouldShowModal(false);\n };\n document.addEventListener(\"keydown\", closeModalOnEscape);\n return () => {\n document.removeEventListener(\"keydown\", closeModalOnEscape);\n };\n }, [setShouldShowModal]);\n // ...\n return [shouldShowModal, setShouldShowModal];\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13966698/" ]
74,669,570
<p>Take this vector:</p> <pre><code>std::vector&lt;int&gt; v = {1, 2, 3, 4, 5}; </code></pre> <p>Let's say I want to remove some elements of a vector at some arbitrary indices: 0, 1, and 3. It's tedious to have to write something like this:</p> <pre><code>v.erase(v.begin()); v.erase(v.begin()); v.erase(v.begin() + 1); </code></pre> <p>Is there any standard function that takes in an arbitrary number of indices to erase from a vector? Something like this: <code>v.erase(0, 1, 3);</code></p>
[ { "answer_id": 74669621, "author": "Jerry Coffin", "author_id": 179910, "author_profile": "https://Stackoverflow.com/users/179910", "pm_score": 2, "selected": true, "text": "erase // erase the first two elements\nv.erase(v.begin(), v.begin() + 2);\n" }, { "answer_id": 74670789, "author": "Ayush Sachan", "author_id": 19519011, "author_profile": "https://Stackoverflow.com/users/19519011", "pm_score": -1, "selected": false, "text": " std::vector<int> v = {1, 2, 3, 4, 5};\n v.erase(v.begin(),v.begin()+3);\n v.erase(v.begin(),v.end()-2);\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19333949/" ]
74,669,579
<p>What's happening:<br> <a href="https://i.stack.imgur.com/mdtyX.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mdtyX.gif" alt="enter image description here" /></a></p> <p>Everytime I add value to height.. the 'top-most' area is causing to mess-up the y.position of the gameObject.</p> <p>The <strong>GOAL</strong> is: <br> <a href="https://i.stack.imgur.com/X8Fqv.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X8Fqv.gif" alt="enter image description here" /></a></p> <br> How to achieve this kind of approach/behavior via script that makes the 'top-most' area stay? <p><strong>Thank you in advance. Best regards.</strong></p> <p><a href="https://i.stack.imgur.com/my5aZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/my5aZ.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74669757, "author": "vik", "author_id": 1145747, "author_profile": "https://Stackoverflow.com/users/1145747", "pm_score": 0, "selected": false, "text": "anchoredPosition" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19903247/" ]
74,669,588
<pre><code>var1 = tensor([[[[0., 1., 1., ..., 1., 0., 0.], [0., 0., 1., ..., 0., 0., 0.], [0., 0., 0., ..., 0., 0., 1.], ..., [0., 0., 0., ..., 1., 1., 1.], [0., 0., 0., ..., 1., 1., 1.], [0., 0., 0., ..., 1., 1., 1.]]]]) print(var1.size()) print(type(var1)) print(var1.dtype) </code></pre> <p>Output:</p> <pre><code>torch.Size([1, 1, 480, 640]) &lt;class 'torch.Tensor'&gt; torch.float32 </code></pre> <p><strong>When I tried to convert torch tensor into numpy.ndarray, all values became zero.</strong></p> <pre><code>nump_var1 = var1.argmax(dim=1).squeeze(0).cpu().numpy() print(nump_var1) print(nump_var1.shape) print(type(nump_var1)) print(nump_var1.dtype) </code></pre> <p>Output:</p> <pre><code> [[0 0 0 ... 0 0 0] [0 0 0 ... 0 0 0] [0 0 0 ... 0 0 0] ... [0 0 0 ... 0 0 0] [0 0 0 ... 0 0 0] [0 0 0 ... 0 0 0]] (480, 640) &lt;class 'numpy.ndarray'&gt; int64 </code></pre> <p>Can anyone point out the mistake I have made?</p> <p>Thanks for the help.</p>
[ { "answer_id": 74669757, "author": "vik", "author_id": 1145747, "author_profile": "https://Stackoverflow.com/users/1145747", "pm_score": 0, "selected": false, "text": "anchoredPosition" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17763433/" ]
74,669,595
<p>Django admin site used to have a form to change the password for a user that wasn't the logged in user. You would look at the user's update page, and by the password field, there was a change password link. You would click it, and it would take you to a different page for changing the password. I used to take advantage of that page to allow changing of a user's password, without having to open the admin. In Django 4, it seems to now be missing. In fact, I can't figure out how one would change a user's password other than their own, without writing my own view.</p> <p>I have 2 questions:</p> <ol> <li>Is there a way in the admin site now to change a different user's password?</li> <li>If this view is gone, what is now the best way for a superuser to have a view that can change passwords for a user?</li> </ol> <p><strong>Edit:</strong> This is what I see. There is no link to change the password where there used to be. <a href="https://i.stack.imgur.com/BXZZH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BXZZH.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74669757, "author": "vik", "author_id": 1145747, "author_profile": "https://Stackoverflow.com/users/1145747", "pm_score": 0, "selected": false, "text": "anchoredPosition" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/801902/" ]
74,669,658
<p>I want a gray overlay above all children except for the <code>selected</code> one. Given the following structure:</p> <pre><code>&lt;div class=&quot;parent&quot;&gt; &lt;!-- I have this subparent which is absolute. I cannot remove it... --&gt; &lt;div class=&quot;subParent1&quot;&gt; &lt;div class=&quot;subParent2&quot;&gt; &lt;!-- This child I want to be above the OVERLAY, aka not greyed out --&gt; &lt;div class=&quot;child selected&quot;&gt;child&lt;/div&gt; &lt;div class=&quot;child&quot;&gt;child&lt;/div&gt; &lt;div class=&quot;child&quot;&gt;child&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- This component is underneat subParent in the tree structure --&gt; &lt;div class=&quot;grayOverlay&quot;&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p><a href="https://jsfiddle.net/xyfb3e2h/2/" rel="nofollow noreferrer">Here's an exact fiddle</a>. Maybe, I could use a pseudo-element instead?</p> <p>PS: I updated the children to be a bit more nested to align with my actual code.</p>
[ { "answer_id": 74670008, "author": "Rohit Khandelwal", "author_id": 15220748, "author_profile": "https://Stackoverflow.com/users/15220748", "pm_score": 3, "selected": true, "text": "z-index position: absolute; subParent1 top: 0; left: 0; grayOverlay .parent {\n width: 300px;\n height: 300px;\n position: relative;\n background-color: gray;\n}\n\n.grayOverlay {\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n background-color: rgb(107 114 128 / 0.8);\n z-index: 11000;\n}\n\n.subParent1 {\n display: flex;\n flex-direction: column;\n width: 100%;\n z-index: 12000;\n}\n\n.child {\n color: black;\n width: 50px;\n height: 20px;\n background-color: white;\n margin: 10px;\n z-index: 10000;\n}\n\n.childIWantOverOverlay {\n background-color: red;\n z-index: 12000;\n} <div class=\"parent\">\n\n <div class=\"subParent1\">\n <div class=\"child childIWantOverOverlay\">child</div>\n <div class=\"child\">child</div>\n <div class=\"child\">child</div>\n </div>\n\n <!-- This component is underneat subParent in the tree structure -->\n <div class=\"grayOverlay\"></div>\n\n</div>" }, { "answer_id": 74670048, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 1, "selected": false, "text": "const btn = document.querySelector(\"button\");\nconst divs = document.querySelectorAll(\"div.child\");\n\nlet i = 0;\n\nbtn.addEventListener(\"click\", () => {\n divs[i].classList.toggle(\"selected\");\n if (i < 2) {\n divs[i + 1].classList.toggle(\"selected\")\n i++;\n return;\n };\n if (i >= 2) {\n i = 0;\n divs[i].classList.toggle(\"selected\");\n }\n\n}); /* Can Change */\n\n.parent {\n width: 300px;\n height: 300px;\n position: relative;\n}\n\n\n/* Add this */\n\n.parent::after {\n content: \"\";\n position: absolute;\n inset: 0;\n background-color: rgb(107 114 128 / 0.5);\n z-index: 50;\n}\n\n\n/* Disabled for now\n.grayOverlay {\n position: absolute;\n width: 100%;\n height: 100%;\n background-color: rgb(107 114 128 / 0.5);\n z-index: 50;\n}\n*/\n\n\n/* CANNOT CHANGE */\n\n.subParent1 {\n position: absolute;\n display: flex;\n flex-direction: column;\n width: 100%;\n}\n\n\n/* Can Change */\n\n.child {\n color: black;\n width: 50px;\n height: 20px;\n background-color: pink;\n margin: 10px;\n z-index: 25;\n position: relative;\n}\n\n\n/* Can Change */\n\n.selected {\n background-color: red;\n /* Add z-index */\n z-index: 100;\n}\n\nbutton {\n margin-bottom: 1em;\n padding: 6px;\n} <button>Toggle</button>\n<div class=\"parent\">\n\n <div class=\"subParent1\">\n <div class=\"subParent2\">\n <div class=\"child selected\">child</div>\n <div class=\"child\">child</div>\n <div class=\"child\">child</div>\n </div>\n </div>\n\n <!-- This component is underneat subParent in the tree structure. I cannot move this into subParent1 -->\n <!-- <div class=\"grayOverlay\"></div> -->\n\n</div> position: relative child z-index grayOverlay subParent1 grayOverlay z-index selected const btn = document.querySelector(\"button\");\nconst divs = document.querySelectorAll(\"div.child\");\n\nlet i = 0;\n\nbtn.addEventListener(\"click\", () => {\n divs[i].classList.toggle(\"selected\");\n if (i < 2) {\n divs[i + 1].classList.toggle(\"selected\")\n i++;\n return;\n };\n if (i >= 2) {\n i = 0;\n divs[i].classList.toggle(\"selected\");\n }\n\n}); /* Can Change */\n\n.parent {\n width: 300px;\n height: 300px;\n position: relative;\n}\n\n\n/* Can Change */\n\n.grayOverlay {\n position: absolute;\n width: 100%;\n height: 100%;\n background-color: rgb(107 114 128 / 0.5);\n /* Removed z-index */\n}\n\n\n/* CANNOT CHANGE */\n\n.subParent1 {\n position: absolute;\n display: flex;\n flex-direction: column;\n width: 100%;\n /* Removed z-index */\n}\n\n\n/* Can Change */\n\n.child {\n color: black;\n width: 50px;\n height: 20px;\n background-color: pink;\n margin: 10px;\n /* Add position */\n position: relative;\n}\n\n\n/* Can Change */\n\n.selected {\n background-color: red;\n /* Add z-index */\n z-index: 100;\n}\n\nbutton {\n margin-bottom: 1em;\n padding: 6px;\n} <button>Toggle</button>\n<div class=\"parent\">\n\n <div class=\"subParent1\">\n <div class=\"subParent2\">\n <div class=\"child selected\">child</div>\n <div class=\"child\">child</div>\n <div class=\"child\">child</div>\n </div>\n </div>\n \n <!-- This component is underneat subParent in the tree structure. I cannot move this into subParent1 --> \n <div class=\"grayOverlay\"></div>\n \n</div>" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7513683/" ]
74,669,688
<p>I have table Buyer</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>BuyId</th> <th>QuantityOrdered</th> <th>dateordered</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>10</td> <td>2021-11-04</td> </tr> <tr> <td>1</td> <td>20</td> <td>2022-01-22</td> </tr> <tr> <td>2</td> <td>50</td> <td>2022-02-20</td> </tr> <tr> <td>2</td> <td>60</td> <td>2022-05-02</td> </tr> <tr> <td>3</td> <td>10</td> <td>2022-05-02</td> </tr> <tr> <td>4</td> <td>10</td> <td>2022-05-02</td> </tr> </tbody> </table> </div> <p>I need to select all BuyId's who consecutively had higher QuantityOrder in each new record</p> <ul> <li>buyid=1 had first order with quantity=10, second order with quantity=20</li> <li>buyid=2 had first order with quantity=50, second order with quantity=60</li> </ul> <p>So BuyId=1 and 2 would enter the results, while 3 and 4 would be filtered out because they had only one order or they did not have orders with consecutively higher quantities ordered</p> <p>I tried with this, and I'm aware that this query gives me only buyid's who have more than one order, but I am missing the rule where I have to filter results out by quantity increased with each new order</p> <pre><code>select buyid, count(*) as ordered from buyer group by buyid having count(*) &gt;1 </code></pre> <p>How would I write out that rule in a query, to select only BuyId's who had multiple orders, and in each new order they ordered higher quantities than in previous orders?</p>
[ { "answer_id": 74670008, "author": "Rohit Khandelwal", "author_id": 15220748, "author_profile": "https://Stackoverflow.com/users/15220748", "pm_score": 3, "selected": true, "text": "z-index position: absolute; subParent1 top: 0; left: 0; grayOverlay .parent {\n width: 300px;\n height: 300px;\n position: relative;\n background-color: gray;\n}\n\n.grayOverlay {\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n background-color: rgb(107 114 128 / 0.8);\n z-index: 11000;\n}\n\n.subParent1 {\n display: flex;\n flex-direction: column;\n width: 100%;\n z-index: 12000;\n}\n\n.child {\n color: black;\n width: 50px;\n height: 20px;\n background-color: white;\n margin: 10px;\n z-index: 10000;\n}\n\n.childIWantOverOverlay {\n background-color: red;\n z-index: 12000;\n} <div class=\"parent\">\n\n <div class=\"subParent1\">\n <div class=\"child childIWantOverOverlay\">child</div>\n <div class=\"child\">child</div>\n <div class=\"child\">child</div>\n </div>\n\n <!-- This component is underneat subParent in the tree structure -->\n <div class=\"grayOverlay\"></div>\n\n</div>" }, { "answer_id": 74670048, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 1, "selected": false, "text": "const btn = document.querySelector(\"button\");\nconst divs = document.querySelectorAll(\"div.child\");\n\nlet i = 0;\n\nbtn.addEventListener(\"click\", () => {\n divs[i].classList.toggle(\"selected\");\n if (i < 2) {\n divs[i + 1].classList.toggle(\"selected\")\n i++;\n return;\n };\n if (i >= 2) {\n i = 0;\n divs[i].classList.toggle(\"selected\");\n }\n\n}); /* Can Change */\n\n.parent {\n width: 300px;\n height: 300px;\n position: relative;\n}\n\n\n/* Add this */\n\n.parent::after {\n content: \"\";\n position: absolute;\n inset: 0;\n background-color: rgb(107 114 128 / 0.5);\n z-index: 50;\n}\n\n\n/* Disabled for now\n.grayOverlay {\n position: absolute;\n width: 100%;\n height: 100%;\n background-color: rgb(107 114 128 / 0.5);\n z-index: 50;\n}\n*/\n\n\n/* CANNOT CHANGE */\n\n.subParent1 {\n position: absolute;\n display: flex;\n flex-direction: column;\n width: 100%;\n}\n\n\n/* Can Change */\n\n.child {\n color: black;\n width: 50px;\n height: 20px;\n background-color: pink;\n margin: 10px;\n z-index: 25;\n position: relative;\n}\n\n\n/* Can Change */\n\n.selected {\n background-color: red;\n /* Add z-index */\n z-index: 100;\n}\n\nbutton {\n margin-bottom: 1em;\n padding: 6px;\n} <button>Toggle</button>\n<div class=\"parent\">\n\n <div class=\"subParent1\">\n <div class=\"subParent2\">\n <div class=\"child selected\">child</div>\n <div class=\"child\">child</div>\n <div class=\"child\">child</div>\n </div>\n </div>\n\n <!-- This component is underneat subParent in the tree structure. I cannot move this into subParent1 -->\n <!-- <div class=\"grayOverlay\"></div> -->\n\n</div> position: relative child z-index grayOverlay subParent1 grayOverlay z-index selected const btn = document.querySelector(\"button\");\nconst divs = document.querySelectorAll(\"div.child\");\n\nlet i = 0;\n\nbtn.addEventListener(\"click\", () => {\n divs[i].classList.toggle(\"selected\");\n if (i < 2) {\n divs[i + 1].classList.toggle(\"selected\")\n i++;\n return;\n };\n if (i >= 2) {\n i = 0;\n divs[i].classList.toggle(\"selected\");\n }\n\n}); /* Can Change */\n\n.parent {\n width: 300px;\n height: 300px;\n position: relative;\n}\n\n\n/* Can Change */\n\n.grayOverlay {\n position: absolute;\n width: 100%;\n height: 100%;\n background-color: rgb(107 114 128 / 0.5);\n /* Removed z-index */\n}\n\n\n/* CANNOT CHANGE */\n\n.subParent1 {\n position: absolute;\n display: flex;\n flex-direction: column;\n width: 100%;\n /* Removed z-index */\n}\n\n\n/* Can Change */\n\n.child {\n color: black;\n width: 50px;\n height: 20px;\n background-color: pink;\n margin: 10px;\n /* Add position */\n position: relative;\n}\n\n\n/* Can Change */\n\n.selected {\n background-color: red;\n /* Add z-index */\n z-index: 100;\n}\n\nbutton {\n margin-bottom: 1em;\n padding: 6px;\n} <button>Toggle</button>\n<div class=\"parent\">\n\n <div class=\"subParent1\">\n <div class=\"subParent2\">\n <div class=\"child selected\">child</div>\n <div class=\"child\">child</div>\n <div class=\"child\">child</div>\n </div>\n </div>\n \n <!-- This component is underneat subParent in the tree structure. I cannot move this into subParent1 --> \n <div class=\"grayOverlay\"></div>\n \n</div>" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20649041/" ]
74,669,702
<p>I looked through so many tutorials and it's still not working for me. I have a database that looks like this: <a href="https://i.stack.imgur.com/QdXeB.png" rel="nofollow noreferrer">databaseImage</a> Note that the actual row does not match up with the id. I would like to delete from the actual row rather than using the id.</p> <p>I have the following function:</p> <pre><code>`fun deleteDBData(TABLE_NAME:String, rowID : Int) { val db = this.writableDatabase db.delete(TABLE_NAME, &quot;$ID_COL=$rowID&quot;, null) }` </code></pre> <p>This however, deletes using the number in the id column rather than the actual row. So with this function, if I tell it to delete rowID = 4, it will delete row 1 rather than row 4. How do I get sqlite to delete row 4?</p>
[ { "answer_id": 74670008, "author": "Rohit Khandelwal", "author_id": 15220748, "author_profile": "https://Stackoverflow.com/users/15220748", "pm_score": 3, "selected": true, "text": "z-index position: absolute; subParent1 top: 0; left: 0; grayOverlay .parent {\n width: 300px;\n height: 300px;\n position: relative;\n background-color: gray;\n}\n\n.grayOverlay {\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n background-color: rgb(107 114 128 / 0.8);\n z-index: 11000;\n}\n\n.subParent1 {\n display: flex;\n flex-direction: column;\n width: 100%;\n z-index: 12000;\n}\n\n.child {\n color: black;\n width: 50px;\n height: 20px;\n background-color: white;\n margin: 10px;\n z-index: 10000;\n}\n\n.childIWantOverOverlay {\n background-color: red;\n z-index: 12000;\n} <div class=\"parent\">\n\n <div class=\"subParent1\">\n <div class=\"child childIWantOverOverlay\">child</div>\n <div class=\"child\">child</div>\n <div class=\"child\">child</div>\n </div>\n\n <!-- This component is underneat subParent in the tree structure -->\n <div class=\"grayOverlay\"></div>\n\n</div>" }, { "answer_id": 74670048, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 1, "selected": false, "text": "const btn = document.querySelector(\"button\");\nconst divs = document.querySelectorAll(\"div.child\");\n\nlet i = 0;\n\nbtn.addEventListener(\"click\", () => {\n divs[i].classList.toggle(\"selected\");\n if (i < 2) {\n divs[i + 1].classList.toggle(\"selected\")\n i++;\n return;\n };\n if (i >= 2) {\n i = 0;\n divs[i].classList.toggle(\"selected\");\n }\n\n}); /* Can Change */\n\n.parent {\n width: 300px;\n height: 300px;\n position: relative;\n}\n\n\n/* Add this */\n\n.parent::after {\n content: \"\";\n position: absolute;\n inset: 0;\n background-color: rgb(107 114 128 / 0.5);\n z-index: 50;\n}\n\n\n/* Disabled for now\n.grayOverlay {\n position: absolute;\n width: 100%;\n height: 100%;\n background-color: rgb(107 114 128 / 0.5);\n z-index: 50;\n}\n*/\n\n\n/* CANNOT CHANGE */\n\n.subParent1 {\n position: absolute;\n display: flex;\n flex-direction: column;\n width: 100%;\n}\n\n\n/* Can Change */\n\n.child {\n color: black;\n width: 50px;\n height: 20px;\n background-color: pink;\n margin: 10px;\n z-index: 25;\n position: relative;\n}\n\n\n/* Can Change */\n\n.selected {\n background-color: red;\n /* Add z-index */\n z-index: 100;\n}\n\nbutton {\n margin-bottom: 1em;\n padding: 6px;\n} <button>Toggle</button>\n<div class=\"parent\">\n\n <div class=\"subParent1\">\n <div class=\"subParent2\">\n <div class=\"child selected\">child</div>\n <div class=\"child\">child</div>\n <div class=\"child\">child</div>\n </div>\n </div>\n\n <!-- This component is underneat subParent in the tree structure. I cannot move this into subParent1 -->\n <!-- <div class=\"grayOverlay\"></div> -->\n\n</div> position: relative child z-index grayOverlay subParent1 grayOverlay z-index selected const btn = document.querySelector(\"button\");\nconst divs = document.querySelectorAll(\"div.child\");\n\nlet i = 0;\n\nbtn.addEventListener(\"click\", () => {\n divs[i].classList.toggle(\"selected\");\n if (i < 2) {\n divs[i + 1].classList.toggle(\"selected\")\n i++;\n return;\n };\n if (i >= 2) {\n i = 0;\n divs[i].classList.toggle(\"selected\");\n }\n\n}); /* Can Change */\n\n.parent {\n width: 300px;\n height: 300px;\n position: relative;\n}\n\n\n/* Can Change */\n\n.grayOverlay {\n position: absolute;\n width: 100%;\n height: 100%;\n background-color: rgb(107 114 128 / 0.5);\n /* Removed z-index */\n}\n\n\n/* CANNOT CHANGE */\n\n.subParent1 {\n position: absolute;\n display: flex;\n flex-direction: column;\n width: 100%;\n /* Removed z-index */\n}\n\n\n/* Can Change */\n\n.child {\n color: black;\n width: 50px;\n height: 20px;\n background-color: pink;\n margin: 10px;\n /* Add position */\n position: relative;\n}\n\n\n/* Can Change */\n\n.selected {\n background-color: red;\n /* Add z-index */\n z-index: 100;\n}\n\nbutton {\n margin-bottom: 1em;\n padding: 6px;\n} <button>Toggle</button>\n<div class=\"parent\">\n\n <div class=\"subParent1\">\n <div class=\"subParent2\">\n <div class=\"child selected\">child</div>\n <div class=\"child\">child</div>\n <div class=\"child\">child</div>\n </div>\n </div>\n \n <!-- This component is underneat subParent in the tree structure. I cannot move this into subParent1 --> \n <div class=\"grayOverlay\"></div>\n \n</div>" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18284391/" ]
74,669,705
<p>Following is my array, and I need to replace the keys <code>name</code> with <code>title</code> and <code>Email</code> with <code>subtitle</code>.</p> <p>I tried some ways, but I still need to fulfill my requirement. Please provide any solution to this.</p> <pre><code>const newUpdatedList = []; resArr.forEach((res) =&gt; { const obj = { title: res.name, subtitle: res.attributes.Email }; if (res.children) { const newList = res.children.map((ch) =&gt; { return { title: ch.name, subtitle: ch.attributes.Email, }; }); obj.children = newList; } newUpdatedList.push(obj); }); </code></pre> <pre><code>const resArr = [ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2' , name : 'Harsha ABC' , custom_id : 'mani78989-1gfqv04bo' , attributes : { Email: 'harsha@gmail.com', Role: 'admin'} , children: [ { user_id : 'd748037a-b445-41c2-b82f-4d6ee9396714' , name : 'Lavaraju Allu' , custom_id : 'mani78989-1gfqv472q' , attributes : { Email: 'raju@gmail.com', Role: 'Manager'} , children: [ { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1' , name : 'Ramesh Allu' , custom_id : 'mani78989-1gh14i13t' , attributes : { Email: 'ramesh@gmail.com', Role: 'Retailer'} , children: [ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2' , name : 'Harsha ABC' , custom_id : 'mani78989-1gh15nrev' , attributes : { Email: 'harsha@gmail.com', Role: 'Delivery Manager'} , children : [] } ] } ] } , { user_id : '550cc296-d7e4-44fb-9d62-4c6755b3f6f2' , name : 'Suresh Kunisetti' , custom_id : 'mani78989-1gfqv6idi' , attributes : { Email: 'suresh@gmail.com', Role: 'Super Admin'} , children: [ { user_id : '45cf19f8-36c1-4669-9333-1226c4f7b66b' , name : 'Harish Three' , custom_id : 'mani78989-1ggv5vffb' , attributes : { Email: 'harish234@gmail.com', Role: 'Delivery Manager'} , children : [] } ] } , { user_id : '2c8535be-5fe7-40f0-892f-0f9bcffe0baa' , name : 'Sandeep Bbb' , custom_id : 'mani78989-1gh14m5p4' , attributes : { Email: 'sandeep@gmail.com', Role: 'Delivery Manager'} , children : [] } , { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1' , name : 'Ramesh Allu' , custom_id : 'mani78989-1gh14pc6p' , attributes : { Email: 'ramesh@gmail.com', Role: 'Manager'} , children : [ ] } ] } ] </code></pre> <p>Expected output is</p> <pre><code>const resArr = [ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2' , title : 'Harsha ABC' , custom_id : 'mani78989-1gfqv04bo' , attributes : { subtitle: 'harsha@gmail.com', Role: 'admin'} , children: [ { user_id : 'd748037a-b445-41c2-b82f-4d6ee9396714' , title : 'Lavaraju Allu' , custom_id : 'mani78989-1gfqv472q' , attributes : { subtitle: 'raju@gmail.com', Role: 'Manager'} , children: [ { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1' , title : 'Ramesh Allu' , custom_id : 'mani78989-1gh14i13t' , attributes : { subtitle: 'ramesh@gmail.com', Role: 'Retailer'} , children: [ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2' , title : 'Harsha ABC' , custom_id : 'mani78989-1gh15nrev' , attributes : { subtitle: 'harsha@gmail.com', Role: 'Delivery Manager'} , children : [] } ] } ] } , { user_id : '550cc296-d7e4-44fb-9d62-4c6755b3f6f2' , title : 'Suresh Kunisetti' , custom_id : 'mani78989-1gfqv6idi' , attributes : { subtitle: 'suresh@gmail.com', Role: 'Super Admin'} , children: [ { user_id : '45cf19f8-36c1-4669-9333-1226c4f7b66b' , title : 'Harish Three' , custom_id : 'mani78989-1ggv5vffb' , attributes : { subtitle: 'harish234@gmail.com', Role: 'Delivery Manager'} , children : [] } ] } , { user_id : '2c8535be-5fe7-40f0-892f-0f9bcffe0baa' , title : 'Sandeep Bbb' , custom_id : 'mani78989-1gh14m5p4' , attributes : { subtitle: 'sandeep@gmail.com', Role: 'Delivery Manager'} , children : [] } , { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1' , title : 'Ramesh Allu' , custom_id : 'mani78989-1gh14pc6p' , attributes : { subtitle: 'ramesh@gmail.com', Role: 'Manager'} , children : [] } ] } ] </code></pre>
[ { "answer_id": 74669884, "author": "Jesse Schoonveld", "author_id": 7774656, "author_profile": "https://Stackoverflow.com/users/7774656", "pm_score": 0, "selected": false, "text": "const arrayOfObj = [{\n name: 'value1',\n email: 'value2'\n }, {\n name: 'value1',\n email: 'value2'\n }];\n const newArrayOfObj = arrayOfObj.map(({\n name: title,\n email: subtitle,\n ...rest\n }) => ({\n title,\n subtitle,\n ...rest\n }));\n \n console.log(newArrayOfObj);\n" }, { "answer_id": 74669942, "author": "brandt.codes", "author_id": 7972867, "author_profile": "https://Stackoverflow.com/users/7972867", "pm_score": 0, "selected": false, "text": "const asString = JSON.stringify(resArr);\nconst replacedNames = asString.replace(/name/g, \"title\");\nconst replacedEmail = replacedNames.replace(/Email/g, \"subtitle\");\nconst result = JSON.parse(replacedEmail);\n result" }, { "answer_id": 74669950, "author": "Brother58697", "author_id": 17804016, "author_profile": "https://Stackoverflow.com/users/17804016", "pm_score": 2, "selected": true, "text": "const resArr= [{\"user_id\": \"f7ba4795-d279-4c38-9a84-7a49522c50a2\",\"name\": \"Harsha ABC\",\"custom_id\": \"mani78989-1gfqv04bo\",\"attributes\": {\"Email\": \"harsha@gmail.com\",\"Role\": \"admin\"},\"children\": [{\"user_id\": \"d748037a-b445-41c2-b82f-4d6ee9396714\",\"name\": \"Lavaraju Allu\",\"custom_id\": \"mani78989-1gfqv472q\",\"attributes\": {\"Email\": \"raju@gmail.com\",\"Role\": \"Manager\"},\"children\": [{\"user_id\": \"881c7731-b853-4ebc-b271-8f9e9215f7a1\",\"name\": \"Ramesh Allu\",\"custom_id\": \"mani78989-1gh14i13t\",\"attributes\": {\"Email\": \"ramesh@gmail.com\",\"Role\": \"Retailer\"},\"children\": [{\"user_id\": \"f7ba4795-d279-4c38-9a84-7a49522c50a2\",\"name\": \"Harsha ABC\",\"custom_id\": \"mani78989-1gh15nrev\",\"attributes\": {\"Email\": \"harsha@gmail.com\",\"Role\": \"Delivery Manager\"},\"children\": []}]}]},{\"user_id\": \"550cc296-d7e4-44fb-9d62-4c6755b3f6f2\",\"name\": \"Suresh Kunisetti\",\"custom_id\": \"mani78989-1gfqv6idi\",\"attributes\": {\"Email\": \"suresh@gmail.com\",\"Role\": \"Super Admin\"},\"children\": [{\"user_id\": \"45cf19f8-36c1-4669-9333-1226c4f7b66b\",\"name\": \"Harish Three\",\"custom_id\": \"mani78989-1ggv5vffb\",\"attributes\": {\"Email\": \"harish234@gmail.com\",\"Role\": \"Delivery Manager\"},\"children\": []}]},{\"user_id\": \"2c8535be-5fe7-40f0-892f-0f9bcffe0baa\",\"name\": \"Sandeep Bbb\",\"custom_id\": \"mani78989-1gh14m5p4\",\"attributes\": {\"Email\": \"sandeep@gmail.com\",\"Role\": \"Delivery Manager\"},\"children\": []},{\"user_id\": \"881c7731-b853-4ebc-b271-8f9e9215f7a1\",\"name\": \"Ramesh Allu\",\"custom_id\": \"mani78989-1gh14pc6p\",\"attributes\": {\"Email\": \"ramesh@gmail.com\",\"Role\": \"Manager\"},\"children\": []}]}]\n\nfunction changeTitles(Obj){\n Obj.title = Obj.name;\n Obj.attributes.subtitle = Obj.attributes.Email;\n delete Obj.name;\n delete Obj.attributes.Email;\n if (Obj.children) {\n Obj.children.forEach(changeTitles)\n }\n}\n\nconst clone = JSON.parse(JSON.stringify(resArr)) // Because the function mutates the object\nclone.forEach(changeTitles)\n\nconsole.log(clone)" }, { "answer_id": 74670006, "author": "Carsten Massmann", "author_id": 2610061, "author_profile": "https://Stackoverflow.com/users/2610061", "pm_score": 1, "selected": false, "text": "structuredClone() const resArr= [ { \"user_id\": \"f7ba4795-d279-4c38-9a84-7a49522c50a2\", \"name\": \"Harsha ABC\", \"custom_id\": \"mani78989-1gfqv04bo\", \"attributes\": { \"Email\": \"harsha@gmail.com\", \"Role\": \"admin\" }, \"children\": [ { \"user_id\": \"d748037a-b445-41c2-b82f-4d6ee9396714\", \"name\": \"Lavaraju Allu\", \"custom_id\": \"mani78989-1gfqv472q\", \"attributes\": { \"Email\": \"raju@gmail.com\", \"Role\": \"Manager\" }, \"children\": [ { \"user_id\": \"881c7731-b853-4ebc-b271-8f9e9215f7a1\", \"name\": \"Ramesh Allu\", \"custom_id\": \"mani78989-1gh14i13t\", \"attributes\": { \"Email\": \"ramesh@gmail.com\", \"Role\": \"Retailer\" }, \"children\": [ { \"user_id\": \"f7ba4795-d279-4c38-9a84-7a49522c50a2\", \"name\": \"Harsha ABC\", \"custom_id\": \"mani78989-1gh15nrev\", \"attributes\": { \"Email\": \"harsha@gmail.com\", \"Role\": \"Delivery Manager\" }, \"children\": [] } ] } ] }, { \"user_id\": \"550cc296-d7e4-44fb-9d62-4c6755b3f6f2\", \"name\": \"Suresh Kunisetti\", \"custom_id\": \"mani78989-1gfqv6idi\", \"attributes\": { \"Email\": \"suresh@gmail.com\", \"Role\": \"Super Admin\" }, \"children\": [ { \"user_id\": \"45cf19f8-36c1-4669-9333-1226c4f7b66b\", \"name\": \"Harish Three\", \"custom_id\": \"mani78989-1ggv5vffb\", \"attributes\": { \"Email\": \"harish234@gmail.com\", \"Role\": \"Delivery Manager\" }, \"children\": [] } ] }, { \"user_id\": \"2c8535be-5fe7-40f0-892f-0f9bcffe0baa\", \"name\": \"Sandeep Bbb\", \"custom_id\": \"mani78989-1gh14m5p4\", \"attributes\": { \"Email\": \"sandeep@gmail.com\", \"Role\": \"Delivery Manager\" }, \"children\": [] }, { \"user_id\": \"881c7731-b853-4ebc-b271-8f9e9215f7a1\", \"name\": \"Ramesh Allu\", \"custom_id\": \"mani78989-1gh14pc6p\", \"attributes\": { \"Email\": \"ramesh@gmail.com\", \"Role\": \"Manager\" }, \"children\": [] } ] } ];\n\nfunction trans(arr){\n arr.forEach((o)=>{\n o.title=o.name; delete(o.name);\n o.attributes.subtitle=o.attributes.Email; delete(o.attributes.Email);\n trans(o.children)\n })\n}\nlet result=structuredClone(resArr);\ntrans(result);\nconsole.log(result);" }, { "answer_id": 74670057, "author": "mukhtar alam", "author_id": 10705362, "author_profile": "https://Stackoverflow.com/users/10705362", "pm_score": 0, "selected": false, "text": "Object.assign a={'name': 'xyz', 'Email': 'xyz@gmail.com'};\nb= Object.assign({'title': a.name, 'subtitle': a.Email});\n" }, { "answer_id": 74670446, "author": "Mussemou", "author_id": 2585314, "author_profile": "https://Stackoverflow.com/users/2585314", "pm_score": 1, "selected": false, "text": "sample_obj resArr title subtitle function recursive_fix(obj) {\n const sample_obj = {\n user_id: obj.user_id,\n title: obj.name,\n custom_id: obj.custom_id,\n attributes: {subtitle: obj.attributes.Email, Role: obj.attributes.Role},\n children: []\n };\n \n // only adding recursive if the children array is not empty\n if (obj.children.length !== 0) {\n obj.children.forEach((childz) => {\n sample_obj.children.push({children: [recursive_fix(childz)]})\n })\n }\n\n return sample_obj\n};\n\nconst newUpdatedList = [];\nresArr.forEach((res) => {\n newUpdatedList.push(recursive_fix(res))\n})" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8293561/" ]
74,669,711
<p>I have to write a program that has a <strong>constructor without parameters</strong>. I created another short program as an example to show what I do not understand. So I have a class with the main-method:</p> <pre><code>public class Dog { public static void main(String[] args) { CharacteristicsOfTheDog Dog1 = new CharacteristicsOfTheDog(20, 40); System.out.println(Dog1.toString()); } } </code></pre> <p>Now implemented another class:</p> <pre><code>public class CharacteristicsOfTheDog { int size = 0; int kilogram = 0; public CharacteristicsOfTheDog(/*int size, int kilogram*/) { // this.size = size; // this.kilogram = kilogram; } public double getSize() { return size; } public double getKilogram() { return kilogram; } public String toString() { return &quot;The Dog is &quot; + getSize() + &quot; cm and &quot; + getKilogram() + &quot; kg&quot;; } } </code></pre> <p>In the class &quot;CharacteristicsOfTheDog&quot; in &quot;public CharacteristicsOfTheDog()&quot; I removed the parameters by commenting them out. So the Problem is: if I remove the parameters the program does not work:/ but my task is to do this without the parameters (as far as I understood). Can someone help me please?</p>
[ { "answer_id": 74669823, "author": "Kevin Hooke", "author_id": 406290, "author_profile": "https://Stackoverflow.com/users/406290", "pm_score": 3, "selected": true, "text": "public class CharacteristicsOfTheDog {\n\n int size = 0;\n int kilogram = 0;\n\n public CharacteristicsOfTheDog() {\n }\n\n public void setSize(int size){\n this.size = size;\n }\n\n public void setKilogram(int kilogram){\n this.kilogram = kilogram;\n }\n}\n CharacteristicsOfTheDog dog1 = new CharacteristicsOfTheDog();\ndog.setSize(20);\ndog.setKilogram(40);\n" }, { "answer_id": 74669944, "author": "WJS", "author_id": 1552534, "author_profile": "https://Stackoverflow.com/users/1552534", "pm_score": 1, "selected": false, "text": "CharacteristicsOfTheDog CharacteristicsOfTheDog cotd = new CharacteristicsOfTheDog();\n cotd.setKilogram(100);\n}\n\nclass CharacteristicsOfTheDog {\n int size = 0;\n int kilogram = 0;\n\n\n public void setSize(int size){\n this.size = size;\n }\n\n public void setKilogram(int kilogram){\n this.kilogram = kilogram;\n }\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20472612/" ]
74,669,715
<p>I have a data frame <code>tweets_df</code> that looks like this:</p> <pre><code> sentiment id date text 0 0 1502071360117424136 2022-03-10 23:58:14+00:00 AngelaRaeBoon1 Same Alabama Republicans charge... 1 0 1502070916318121994 2022-03-10 23:56:28+00:00 This ’ w/the sentencing JussieSmollett But mad... 2 0 1502057466267377665 2022-03-10 23:03:01+00:00 DannyClayton Not hard find takes smallest amou... 3 0 1502053718711316512 2022-03-10 22:48:08+00:00 I make fake scenarios getting fights protectin... 4 0 1502045714486022146 2022-03-10 22:16:19+00:00 WipeHomophobia Well people lands wildest thing... .. ... ... ... ... 94 0 1501702542899691525 2022-03-09 23:32:41+00:00 There 's reason deep look things kill bad peop... 95 0 1501700281729433606 2022-03-09 23:23:42+00:00 Shame UN United Dictators Shame NATO Repeat We... 96 0 1501699859803516934 2022-03-09 23:22:01+00:00 GayleKing The difference Ukrainian refugees IL... 97 0 1501697172441550848 2022-03-09 23:11:20+00:00 hrkbenowen And includes new United States I un... 98 0 1501696149853511687 2022-03-09 23:07:16+00:00 JLaw_OTD A world women minorities POC LGBTQ÷ d... </code></pre> <p>And the second dataFrame <code>globe_df</code> that looks like this:</p> <pre><code> Country Region 0 Andorra Europe 1 United Arab Emirates Middle east 2 Afghanistan Asia &amp; Pacific 3 Antigua and Barbuda South/Latin America 4 Anguilla South/Latin America .. ... ... 243 Guernsey Europe 244 Isle of Man Europe 245 Jersey Europe 246 Saint Barthelemy South/Latin America 247 Saint Martin South/Latin America </code></pre> <p>I want to delete all rows of the dataframe <code>tweets_df</code> which have 'text' that does not contain a 'Country' or 'Region'.</p> <p>This was my attempt:</p> <pre><code>globe_df = pd.read_csv('countriesAndRegions.csv') tweets_df = pd.read_csv('tweetSheet.csv') for entry in globe_df['Country']: tweet_index = tweets_df[entry in tweets_df['text']].index # if tweets that *contain*, not equal...... entry in tweets_df['text] .... (in)or (not in)? tweets_df.drop(tweet_index , inplace=True) print(tweets_df) </code></pre> <p>Edit: Also, fuzzy, case-insensitive matching with stemming would be preferred when searching the 'text' for countries and regions.</p> <p>Ex) If the text contained 'Ukrainian', 'british', 'engliSH', etc... then it would not be deleted</p>
[ { "answer_id": 74669764, "author": "Tron", "author_id": 9917285, "author_profile": "https://Stackoverflow.com/users/9917285", "pm_score": -1, "selected": false, "text": "tweets_df[tweets_df['text'].contains('{}|{}'.format(entry['Country'],entry['Region'])]\n True" }, { "answer_id": 74670011, "author": "VolkanM", "author_id": 14531831, "author_profile": "https://Stackoverflow.com/users/14531831", "pm_score": -1, "selected": false, "text": "# Import data\nglobe_df = pd.read_csv('countriesAndRegions.csv')\ntweets_df = pd.read_csv('tweetSheet.csv')\n# Get country and region column as list\nglobe_df_country = globe_df['Country'].values.tolist()\nglobe_df_region = globe_df['Region'].values.tolist()\n# merge_lists, cause you want to check with or operator\nmerged_list = globe_df_country + globe_df_region\n# If you want to update df while iterating it, best way to do it with using copy df\ndf_tweets2 = tweets_df.copy()\nfor index,row in tweets_df.iterrows():\n # Check if splitted row's text values are intersecting with merged_list\n if [i for i in merged_list if i in row['text'].split()] == []:\n df_tweets2 = df_tweets2.drop[index]\ntweets_df_new = df_tweets2.copy()\nprint(tweets_df_new) \n \n" }, { "answer_id": 74670202, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 0, "selected": false, "text": "#with case insensitive\nvals=globe_df.stack().to_list()\n\ntweets_df = tweets_df[tweets_df ['text'].str.contains('|'.join(vals), regex=True, case=False)]\n vals=\"({})\".format('|'.join(globe_df.stack().str.lower().to_list())) #make all letters lowercase\ntweets_df['matched'] = tweets_df.text.str.lower().str.extract(vals, expand=False)\ntweets_df = tweets_df.dropna()\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20056124/" ]
74,669,723
<p>I got tasked with writing a Python script that would output the longest chain of consecutive words of the same length from a sentence. For example, if the input is &quot;To be or not to be&quot;, the output should be &quot;To, be, or&quot;.</p> <pre><code>text = input(&quot;Enter text: &quot;) words = text.replace(&quot;,&quot;, &quot; &quot;).replace(&quot;.&quot;, &quot; &quot;).split() x = 0 same = [] same.append(words[x]) for i in words: if len(words[x]) == len(words[x+1]): same.append(words[x+1]) x += 1 elif len(words[x]) != len(words[x+1]): same = [] x += 1 else: print(&quot;No consecutive words of the same length&quot;) print(words) print(&quot;Longest chain of words with similar length: &quot;, same) </code></pre> <p>In order to turn the string input into a list of words and to get rid of any punctuation, I used the replace() and split() methods. The first word of this list would then get appended to a new list called &quot;same&quot;, which would hold the words with the same length. A for-loop would then compare the lengths of the words one by one, and either append them to this list if their lengths match, or clear the list if they don't.</p> <pre><code>if len(words[x]) == len(words[x+1]): ~~~~~^^^^^ IndexError: list index out of range </code></pre> <p>This is the problem I keep getting, and I just can't understand why the index is out of range.</p> <p>I will be very grateful for any help with solving this issue and fixing the program. Thank you in advance.</p>
[ { "answer_id": 74669797, "author": "sahasrara62", "author_id": 5086255, "author_profile": "https://Stackoverflow.com/users/5086255", "pm_score": 3, "selected": true, "text": "groupby from itertools import groupby\nstring = \"To be or not to be\"\nsol = ', '.join(max([list(b) for a, b in groupby(string.split(), key=len)], key=len))\nprint(sol)\n# 'To, be, or'\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20676556/" ]
74,669,803
<pre><code>def paren(s, cnt=0): if s == '': return True if s[0] == '(': return paren(s[1:], cnt + 1) elif s[0] == ')': return paren(s[1:], cnt - 1) return cnt == 0 </code></pre> <p>So this code works for all cases if there is the same number of &quot;(&quot; and &quot;)&quot;. But for example it doesn't work for &quot;))(( &quot;. how can I modify the code for this to work that for every opening bracket there is a closing one, then it returns True.</p>
[ { "answer_id": 74669797, "author": "sahasrara62", "author_id": 5086255, "author_profile": "https://Stackoverflow.com/users/5086255", "pm_score": 3, "selected": true, "text": "groupby from itertools import groupby\nstring = \"To be or not to be\"\nsol = ', '.join(max([list(b) for a, b in groupby(string.split(), key=len)], key=len))\nprint(sol)\n# 'To, be, or'\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74669803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20676763/" ]