qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,511,956
<p>I want to do a split by &quot;{&quot; and keep the &quot;{&quot;.</p> <p>The result should be an array:</p> <pre><code>[ &quot;{ \&quot;&quot;text\&quot; : \&quot;alinea 1\&quot;, \&quot;type\&quot; : \&quot;paragraph\&quot; }&quot;, &quot;{ \&quot;&quot;text\&quot; : \&quot;alinea 2\&quot;, \&quot;type\&quot; : \&quot;paragraph\&quot; }&quot; ] </code></pre> <p>The code I have got so far:</p> <pre><code>(&quot;{ \&quot;text\&quot;: \&quot;alinea 1\&quot;, \&quot;type\&quot;: \&quot;paragraph\&quot; }, { \&quot;text\&quot;: \&quot;alinea2\&quot;, \&quot;type\&quot;: \&quot;paragraph\&quot; }&quot;).split(/([?={?&gt;={]+)/g) </code></pre> <p>But the output is not as expected:</p> <p><a href="https://i.stack.imgur.com/mNPJj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mNPJj.jpg" alt="enter image description here" /></a></p> <p>I am not a hero with regex... and tried to fiddle a bit with this: <a href="https://stackoverflow.com/questions/12001953/javascript-and-regex-split-string-and-keep-the-separator">Javascript and regex: split string and keep the separator</a></p>
[ { "answer_id": 74512064, "author": "Andrew Hartnell", "author_id": 7202344, "author_profile": "https://Stackoverflow.com/users/7202344", "pm_score": -1, "selected": false, "text": " //App.js\n let sideBarRef = useRef(false); \n\n let content = (\n {sideBarRef? (<SideBar sideBarRef ={sideBarRef} />\n ): null} \n <Header sideBarRef ={sideBarRef} />\n \n\n\nexport default function SideBar({sideBarRef,}) { \n<use sideBarRef in code as if declare here>\n}\n\nexport default function Header({sideBarRef,}) { \n<use sideBarRef as if declare here >\n}\n" }, { "answer_id": 74512366, "author": "szaman", "author_id": 4908847, "author_profile": "https://Stackoverflow.com/users/4908847", "pm_score": 0, "selected": false, "text": "Header Sidebar App const App = () => {\n const [showSidebar, setShowSidebar] = useState(true);\n\n const toggleSidebar = () => setShowSidebar(prev => !prev);\n \n return (\n <main>\n <Header onClickMenu={toggleSidebar} />\n {showSidebar && <Sidebar />}\n </main>\n );\n};\n const Header = ({ onClickMenu }) => { \n return (\n <nav>\n <Hamburger onClick={onClickMenu} />\n ...\n </nav>\n );\n};\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1624835/" ]
74,512,056
<p>When I ran my react code, I get a Syntax error</p> <pre><code>App.jsx:8 Uncaught (in promise) SyntaxError: Unexpected end of input (at App.jsx:8:1) at App.jsx:8:1 </code></pre> <p>i dont understand why this is wrong if you look at App.jsx:</p> <pre><code>import React, {useState, useEffect} from &quot;react&quot;; function App() { const [backendData, setBackendData] = useState([{}]) useEffect( () =&gt; { fetch(&quot;http://localhost:8000/api&quot;, {mode: 'no-cors'}) .then( res =&gt; res.json() ) .then( data =&gt; { setBackendData(data) } ) }, []) return ( &lt;div className=&quot;App&quot;&gt; &lt;/div&gt; ); } export default App; </code></pre> <p>There is nothing wrong?</p>
[ { "answer_id": 74512087, "author": "Vortezz", "author_id": 19103809, "author_profile": "https://Stackoverflow.com/users/19103809", "pm_score": 0, "selected": false, "text": "Access-Control-Allow-Origin: * Access-Control-Allow-Origin: domain.com" }, { "answer_id": 74512107, "author": "Sofiane", "author_id": 11564760, "author_profile": "https://Stackoverflow.com/users/11564760", "pm_score": 0, "selected": false, "text": " useEffect( () => {\nfetch(\"http://localhost:8000/api\", {mode: 'no-cors'})\n .then(result => result.text())\n .then(\n data => {\n setBackendData(data)\n }\n )\n }, [])\n" }, { "answer_id": 74512143, "author": "persedi", "author_id": 8754360, "author_profile": "https://Stackoverflow.com/users/8754360", "pm_score": 2, "selected": false, "text": "{mode: 'no-cors'} Access-Control-Allow-Origin" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18944968/" ]
74,512,080
<p>I'm sorry for the weird title. I don't know how to word this. If I have function func() How do I do this:</p> <pre><code>func(func(func(func(func(x))))) </code></pre> <p>where it repeats N times?</p> <p>I'm trying to implement Conway's Game of Life. I have a function that takes a vector and outputs another vector, which is the next generation of the input vector. So generation 3's vector would be func(func(func(x))).</p>
[ { "answer_id": 74512087, "author": "Vortezz", "author_id": 19103809, "author_profile": "https://Stackoverflow.com/users/19103809", "pm_score": 0, "selected": false, "text": "Access-Control-Allow-Origin: * Access-Control-Allow-Origin: domain.com" }, { "answer_id": 74512107, "author": "Sofiane", "author_id": 11564760, "author_profile": "https://Stackoverflow.com/users/11564760", "pm_score": 0, "selected": false, "text": " useEffect( () => {\nfetch(\"http://localhost:8000/api\", {mode: 'no-cors'})\n .then(result => result.text())\n .then(\n data => {\n setBackendData(data)\n }\n )\n }, [])\n" }, { "answer_id": 74512143, "author": "persedi", "author_id": 8754360, "author_profile": "https://Stackoverflow.com/users/8754360", "pm_score": 2, "selected": false, "text": "{mode: 'no-cors'} Access-Control-Allow-Origin" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8074184/" ]
74,512,116
<pre><code>def exponentiation(base,n): if n == 0: return 1 if n % 2 == 0: return exponentiation(base*base, n/2) else: return base * exponentiation(base * base, (n-1)/2) if __name__ == '__main__': print(len(str(exponentiation(2, 66666666)))) </code></pre> <p>For very large integers, the computer becomes quite sluggish at finding the product of numbers; And I know that 1 Gigabyte of RAM can store atleast 2^8000000000 digits, but this program slows down far before this limit is reached.</p> <p>I wished to use Exponentiation by squaring in order to improve the rate at which the program did the multiplications, but yet it seems as though there is a problem with the program storing such large integers.</p>
[ { "answer_id": 74512171, "author": "LeopardShark", "author_id": 8425824, "author_profile": "https://Stackoverflow.com/users/8425824", "pm_score": 0, "selected": false, "text": "exponentiation = pow\n int(math.log10(n)) + 1" }, { "answer_id": 74512194, "author": "Pi Marillion", "author_id": 2892254, "author_profile": "https://Stackoverflow.com/users/2892254", "pm_score": 1, "selected": false, "text": "** big_number_a = 2 ** 66666666\nbig_number_b = exponentiation(2, 66666666)\nbig_number_a == big_number_b # True\n str" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557592/" ]
74,512,147
<p>I need to make a realistic 3d shadow that looks like the container is standing. Just like the image shows.</p> <p><a href="https://i.stack.imgur.com/Mod6x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mod6x.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/e3cT3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e3cT3.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74512171, "author": "LeopardShark", "author_id": 8425824, "author_profile": "https://Stackoverflow.com/users/8425824", "pm_score": 0, "selected": false, "text": "exponentiation = pow\n int(math.log10(n)) + 1" }, { "answer_id": 74512194, "author": "Pi Marillion", "author_id": 2892254, "author_profile": "https://Stackoverflow.com/users/2892254", "pm_score": 1, "selected": false, "text": "** big_number_a = 2 ** 66666666\nbig_number_b = exponentiation(2, 66666666)\nbig_number_a == big_number_b # True\n str" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16413657/" ]
74,512,166
<p>I am working on a vector sorting algorithm for my personal particle physics studies but I am very new to coding.</p> <p>Going through individual scenarios (specific vector sizes and combinations) by brute force becomes extremely chaotic for greater numbers of net vector elements, especially since this whole code will be looped up to 1e5 times.</p> <p>Take four vectors of 'flavors' A and B: A+, A-, B+, and B-. I need to find two total pairs of elements such that some value k(V+, V-) is maximized with the restriction that different flavors cannot be combined! (V is just a flavor placeholder)</p> <p>For example:</p> <p>A+ = {a1+} A- = {a1-}</p> <p>B+ = {b1+, b2+} B- = {b1-}</p> <p>Since A+ and A- only have one element each, the value k(A+, A-) -&gt; k(a1+, a1-). But for flavor B, there are two possible combinations.</p> <p>k(b1+, b1-) OR k(b2+, b1-)</p> <p>I would like to ensure that the combination of elements with the greater value of k is retained. As I said previously, this specific example is not TOO bad by brute force, but say B+ and B- had two elements each? The possible values would be:</p> <p>k(b1+, b1-) or k(b2+,b2-) or k(b1+, b2-) or k(b2+, b1-)</p> <p>where only one of these is correct. Furthermore, say two of those four B+B- combinations had greater k than that of A+A-. This would also be valid!</p> <p>Any help would be appreciated!!! I can clarify if anything above is overly confusing!</p> <p>I tried something like this,</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; using namespace std; static bool sortbypair(const pair&lt;double, double&gt; &amp;a, const pair&lt;double, double&gt; &amp;b) { return (k(a.first, a.second) &gt; k(b.first, b.second)) &amp;&amp; k(a.first, b.second) &lt; k(a.second, b.first); } </code></pre> <p>But I can't flesh it out.</p>
[ { "answer_id": 74519979, "author": "joergbrech", "author_id": 12173376, "author_profile": "https://Stackoverflow.com/users/12173376", "pm_score": 1, "selected": false, "text": "k double std::pair<double, double> double double std::vector<double> aplus aminus bplus bminus std::pair<double, double> aplus aminus bplus bminus k k Vplus Vminus Vplus x Vminus aplus x aminus bplus x bminus k double k(double x, double y) { return x*x + y*y; }\n std::vector<double> ap{0., 4., 2., 3., 1.};\nstd::vector<double> am{2., -1.};\n\nstd::vector<double> bp{1., 0.5};\nstd::vector<double> bm{-1., 2.};\n using namespace ranges;\n\nauto pairs_view = view::concat(\n view::cartesian_product(ap, am),\n view::cartesian_product(bp, bm)\n);\n pairs_view auto print = [](auto const& p){\n auto first = std::get<0>(p);\n auto second = std::get<1>(p);\n std::cout << \"[\" << first << \", \" << second << \"] k = \" << k(first, second) << std::endl;\n};\n\nfor_each(pairs_view, print);\n [0, 2] k = 4\n[0, -1] k = 1\n[4, 2] k = 20\n[4, -1] k = 17\n[2, 2] k = 8\n[2, -1] k = 5\n[3, 2] k = 13\n[3, -1] k = 10\n[1, 2] k = 5\n[1, -1] k = 2\n[1, -1] k = 2\n[1, 2] k = 5\n[0.5, -1] k = 1.25\n[0.5, 2] k = 4.25\n k auto k_proj = [](auto const& p){\n return k(std::get<0>(p), std::get<1>(p));\n};\n k auto it = max_element(pairs_view, less{}, k_proj);\nprint(*it);\n [4, 2] k = 20\n max_element less k_proj pairs_view k std::vector<std::pair<double, double>> cartesian_product std::pair<double, double auto to_std_pair = [](auto const& p){\n return std::pair<double, double>{std::get<0>(p), std::get<1>(p)};\n};\nauto pairs_vec = pairs_view | view::transform(to_std_pair) | to_vector;\n | to_vector(view::transform(pairs_view, to_std_pair)) sort(pairs_vec, less{}, k_proj);\n for_each(pairs_vec, print);\n [0, -1] k = 1\n[0.5, -1] k = 1.25\n[1, -1] k = 2\n[1, -1] k = 2\n[0, 2] k = 4\n[0.5, 2] k = 4.25\n[2, -1] k = 5\n[1, 2] k = 5\n[1, 2] k = 5\n[2, 2] k = 8\n[3, -1] k = 10\n[3, 2] k = 13\n[4, -1] k = 17\n[4, 2] k = 20\n concat cartesian_product to_vector max_element sort" }, { "answer_id": 74552120, "author": "mangoman", "author_id": 20557343, "author_profile": "https://Stackoverflow.com/users/20557343", "pm_score": 1, "selected": true, "text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <tuple>\n\nusing namespace std;\n\nstatic bool weirdsort(const tuple<int, int, double> &a, const tuple<int, int, double> &b)\n{\n return get<2>(a) > get<2>(b);\n}\n\nint main()\n{\n vector<tuple<int, int, double>> net;\n// Sample ptcl list\n// \n// A+ A- B+ B-\n// 0 a1+ \n// 1 a1-\n// 2 b1-\n// 3 b1+\n// 4 a2+\n// 5 a2-\n \n \n for(int i = 0; i < A+.size(); i++)\n {\n for (int j = 0; j < A-.size(); j++)\n {\n net.push_back(A+[i], A-[j], k(A+[i], A-[j]));\n }\n }\n sort(net.begin(), net.end(), weirdsort);\n //Now another for loop that erases a tuple (with a lower k value) if it has a repeated ptcl index.\n for (int i = 0; i < net.size(); i++)\n {\n if (get<0>(net[i]) == get<0>(net[i + 1]) || get<1>(net[i]) == get<1>(net[i + 1]))\n {\n net.erase(net.begin() + i + 1);\n }\n }\n //Now can plot third tuple element of net[0] and net[1]\n\n return 0;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557343/" ]
74,512,183
<p>Terraform syntax question. I am trying to minimise the logic creating security groups by simply looping over a list of local variables, here is the example</p> <pre><code>locals { egress = { udp = [ 53, 123 ] } ingress = { tcp = [ 443, 22, ] } } </code></pre> <p>and a resource:</p> <pre><code>resource &quot;aws_security_group_rule&quot; &quot;in_tcp&quot; { #for_each = [ for k, v in local.ingress : local.ingress.k =&gt; v ] #for_each = [ for port in local.ingress : port =&gt; port ] #for_each = [ for proto in local.ingress : proto ] #for_each = [ for k, v in local.ingress : k ] for_each = local.ingress type = &quot;ingress&quot; from_port = each.value to_port = each.value protocol = tostring(each.key) self = true security_group_id = aws_security_group.main.id } </code></pre> <p>I have tried everything but nothing works. I guess I do not understand the meaning of [ for ... ] and { for ... }</p> <p>The best result so far is as above, using simple <code>for_each = local.ingress</code>, but I get the error:</p> <pre><code> Error: Incorrect attribute value type │ │ on sg-rules/main.tf line 38, in resource &quot;aws_security_group_rule&quot; &quot;in_tcp&quot;: │ 38: from_port = each.value │ ├──────────────── │ │ each.value is tuple with 2 elements │ │ Inappropriate value for attribute &quot;from_port&quot;: number required. </code></pre> <p>when I convert each.value to number using <code>from_port = tonumber(each.value)</code> I get another error:</p> <pre><code>│ Error: Invalid function argument │ │ on sg-rules/main.tf line 38, in resource &quot;aws_security_group_rule&quot; &quot;in_tcp&quot;: │ 38: from_port = tonumber(each.value) │ ├──────────────── │ │ while calling tonumber(v) │ │ each.value is tuple with 2 elements │ │ Invalid value for &quot;v&quot; parameter: cannot convert tuple to number. </code></pre>
[ { "answer_id": 74512592, "author": "Helder Sepulveda", "author_id": 7599833, "author_profile": "https://Stackoverflow.com/users/7599833", "pm_score": 3, "selected": true, "text": "locals {\n ingress = {\n 443 : \"tcp\",\n 22 : \"tcp\"\n }\n}\n\nresource \"aws_security_group_rule\" \"in_tcp\" {\n for_each = local.ingress\n type = \"ingress\"\n from_port = each.key\n to_port = each.key\n protocol = each.value\n self = true\n security_group_id = \"sg-123456\"\n}\n Terraform will perform the following actions:\n\n # aws_security_group_rule.in_tcp[\"22\"] will be created\n + resource \"aws_security_group_rule\" \"in_tcp\" {\n + from_port = 22\n + id = (known after apply)\n + protocol = \"tcp\"\n + security_group_id = \"sg-123456\"\n + security_group_rule_id = (known after apply)\n + self = true\n + source_security_group_id = (known after apply)\n + to_port = 22\n + type = \"ingress\"\n }\n\n # aws_security_group_rule.in_tcp[\"443\"] will be created\n + resource \"aws_security_group_rule\" \"in_tcp\" {\n + from_port = 443\n + id = (known after apply)\n + protocol = \"tcp\"\n + security_group_id = \"sg-123456\"\n + security_group_rule_id = (known after apply)\n + self = true\n + source_security_group_id = (known after apply)\n + to_port = 443\n + type = \"ingress\"\n }\n\nPlan: 2 to add, 0 to change, 0 to destroy.\n" }, { "answer_id": 74512601, "author": "Kombajn zbożowy", "author_id": 2890093, "author_profile": "https://Stackoverflow.com/users/2890093", "pm_score": 2, "selected": false, "text": "local.ingress foreach {\n \"tcp_22\" = {\n \"port\" = 22\n \"proto\" = \"tcp\"\n }\n \"tcp_443\" = {\n \"port\" = 443\n \"proto\" = \"tcp\"\n }\n}\n resource \"aws_security_group_rule\" \"in_tcp\" {\n for_each = {\n for p in flatten([\n for proto, ports in local.ingress: [\n for port in ports: { proto = proto, port = port }\n ]\n ]): \"${p.proto}_${p.port}\" => p\n }\n type = \"ingress\"\n from_port = tonumber(each.value.port)\n to_port = tonumber(each.value.port)\n protocol = tostring(each.value.proto)\n self = true\n security_group_id = aws_security_group.main.id\n}\n" }, { "answer_id": 74512917, "author": "sbehl", "author_id": 20557263, "author_profile": "https://Stackoverflow.com/users/20557263", "pm_score": 1, "selected": false, "text": "locals {\n egress = {\n udp = [\n \"53\",\n \"123\"\n ]\n }\n ingress = {\n tcp = [\n \"443\",\n \"22\",\n ]\n }\n}\n resource \"aws_security_group_rule\" \"in_tcp\" {\n for_each = toset(local.ingress.tcp)\n type = \"ingress\"\n from_port = tonumber(each.value)\n to_port = tonumber(each.value)\n protocol = \"tcp\"\n self = true\n security_group_id = aws_security_group.main.id\n}\n resource \"aws_security_group_rule\" \"out_udp\" {\n for_each = toset(local.egress.udp)\n type = \"egress\"\n from_port = tonumber(each.value)\n to_port = tonumber(each.value)\n protocol = \"udp\"\n self = true\n security_group_id = aws_security_group.main.id\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4696089/" ]
74,512,262
<p>I would like to fetch a &quot;board_ID&quot;: fetch(&quot;http://localhost:4000/NewGame&quot;) and then use that board_ID in the address of the following fetch: fetch(&quot;http://localhost:4000/Turn/&quot; + board_ID). The problem is that setboard_ID (initialized previously with useState) does not update the board_ID quick enough so there is an error in the fetch for the &quot;Turn.&quot; What is the best way to solve this problem?</p> <pre><code>useEffect(() =&gt; { if (didFetch == false) { fetch(&quot;http://localhost:4000/NewGame&quot;) .then(res =&gt; res.text()) .then( (result) =&gt;{ console.log(result) **setboard_ID(result)** }, (error) =&gt; { setisLoaded(true) seterror(error) } ) } }) useEffect(() =&gt; { if (getplayer == true){ console.log(&quot;http://localhost:4000/Turn/&quot; + board_ID) **fetch(&quot;http://localhost:4000/Turn/&quot; + board_ID)** .then(res =&gt; res.text()) .then( (result) =&gt;{ console.log(result) player = result setGetplayer(false) }, (error) =&gt; { seterror(error) } ) } }) </code></pre>
[ { "answer_id": 74512350, "author": "ColdDarkness", "author_id": 20480318, "author_profile": "https://Stackoverflow.com/users/20480318", "pm_score": 1, "selected": false, "text": "useEffect(function, [dependency]) \n" }, { "answer_id": 74512449, "author": "Rishabh Kumar Mayank", "author_id": 13844203, "author_profile": "https://Stackoverflow.com/users/13844203", "pm_score": 0, "selected": false, "text": " useEffect(() => {\n if (getplayer && board_ID !='' ){ // == true is redundant and board_ID != <your initial state means it has some valid value>\n console.log(\"http://localhost:4000/Turn/\" + board_ID)\n **fetch(\"http://localhost:4000/Turn/\" + board_ID)**\n .then(res => res.text())\n .then(\n (result) =>{\n console.log(result)\n player = result\n setGetplayer(false)\n },\n (error) => {\n seterror(error)\n }\n )\n }\n},[board_ID])\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19394369/" ]
74,512,269
<p>I'm trying to write a Java code to check if password includes characters, numbers and special characters. Everything fine until the special characters part. The idea is that the index of specialChars and the characters of the Password file are confront and, if there's a match, it would print a positive message, else it would throw an error. But it returns both the positive message and the error. Not sure why.</p> <pre><code>import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PasswordApp { public static void main(String[] args) { String filename = &quot;C:\\Users\\gabri\\Desktop\\Generale\\Programmazione\\Java\\Password_Criteria\\Fakepassword.txt&quot;; File file = new File(filename); String Password = null; try { BufferedReader br = new BufferedReader(new FileReader(file)); Password = br.readLine(); br.close(); } catch (FileNotFoundException e) { System.out.println(&quot;ERROR: File not found: &quot; + filename); } catch (IOException e) { System.out.println(&quot;ERROR: Could not read the data: &quot; + filename); } // Password valida: ha almeno un numero, una lettera e un carattere speciale try { String esitoPositivocarattere = &quot;Carattere incluso.&quot;; String esitoPositivonumero = &quot;Numero incluso.&quot;; String esitoPositivospeciale = &quot;Carattere speciale incluso.&quot;; char[] specialChars = &quot;!@#*+-_(%?/{}[].,;:&quot;.toCharArray(); for (int n = 0; n &lt; Password.length(); n++) { if (Password.substring(n).matches(&quot;.*[a-z].*&quot;)) { { System.out.println(esitoPositivocarattere); } } else { throw new MissingCharacterException(); } if (Password.substring(n).matches(&quot;.*\\d.*&quot;)) { System.out.println(esitoPositivonumero); } else { throw new MissingNumberException(); } for (int i = 0; i &lt; specialChars.length; i++) { if (Password.indexOf(specialChars[i]) &gt; -1) { System.out.println(esitoPositivospeciale); } else { throw new MissingSpecialCharacterException(); } } } } catch (MissingSpecialCharacterException e) { System.out.println(&quot;ERRORE: Manca un carattere speciale.&quot;); } catch (MissingNumberException e) { System.out.println(&quot;ERRORE: Manca un numero.&quot;); } catch (MissingCharacterException e) { System.out.println(&quot;ERRORE: Manca un carattere.&quot;); } } } class MissingSpecialCharacterException extends Exception { } class MissingNumberException extends Exception { } class MissingCharacterException extends Exception { } </code></pre>
[ { "answer_id": 74512416, "author": "Bohemian", "author_id": 256196, "author_profile": "https://Stackoverflow.com/users/256196", "pm_score": 1, "selected": false, "text": "public boolean passwordValid(String password) {\n return password.matches(\"(?=.*[a-zA-Z])(?=.*\\\\d)(?=.*[!@#*+_(%?/{}\\\\[\\\\].,;:-]).*\");\n}\n (?=.*[a-zA-Z]) (?=.*\\\\d) (?=.*[!@#*+_(%?/{}\\\\[\\\\].,;:-]\")" }, { "answer_id": 74512468, "author": "access violation", "author_id": 19322069, "author_profile": "https://Stackoverflow.com/users/19322069", "pm_score": 4, "selected": true, "text": "for (int i = 0; i < specialChars.length; i++) {\n if (Password.indexOf(specialChars[i]) > -1) {\n System.out.println(esitoPositivospeciale);\n } else {\n throw new MissingSpecialCharacterException();\n }\n}\n boolean foundSpecial = false;\nfor (int i = 0; i < specialChars.length; i++) {\n if (Password.indexOf(specialChars[i]) > -1) {\n foundSpecial = true;\n }\n}\nif (foundSpecial) {\n System.out.println(esitoPositivospeciale);\n} else {\n throw new MissingSpecialCharacterException();\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13707732/" ]
74,512,281
<p>I've been trying to install java on vs code for a couple hours now and I can't seem to get it to work. I've already downloaded all the extensions necessary and I've downloaded the coding pack from <a href="https://code.visualstudio.com/docs/languages/java" rel="nofollow noreferrer">https://code.visualstudio.com/docs/languages/java</a> for windows (I'm on windows 11). According to multiple tutorials, this is all I should have to do, but when I make a test.java file, the &quot;run java&quot; does nothing and &quot;run code&quot; gives me an error.</p> <p><a href="https://i.stack.imgur.com/mx3h5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mx3h5.png" alt="code" /></a></p> <p>and this is the output when I click that run button in the top right: <a href="https://i.stack.imgur.com/OY9PK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OY9PK.png" alt="output" /></a></p> <p>Does anybody have any suggestions? the coding pack was supposed to come with a jdk, its working for everybody else so I'm not sure what the issue is.</p>
[ { "answer_id": 74512416, "author": "Bohemian", "author_id": 256196, "author_profile": "https://Stackoverflow.com/users/256196", "pm_score": 1, "selected": false, "text": "public boolean passwordValid(String password) {\n return password.matches(\"(?=.*[a-zA-Z])(?=.*\\\\d)(?=.*[!@#*+_(%?/{}\\\\[\\\\].,;:-]).*\");\n}\n (?=.*[a-zA-Z]) (?=.*\\\\d) (?=.*[!@#*+_(%?/{}\\\\[\\\\].,;:-]\")" }, { "answer_id": 74512468, "author": "access violation", "author_id": 19322069, "author_profile": "https://Stackoverflow.com/users/19322069", "pm_score": 4, "selected": true, "text": "for (int i = 0; i < specialChars.length; i++) {\n if (Password.indexOf(specialChars[i]) > -1) {\n System.out.println(esitoPositivospeciale);\n } else {\n throw new MissingSpecialCharacterException();\n }\n}\n boolean foundSpecial = false;\nfor (int i = 0; i < specialChars.length; i++) {\n if (Password.indexOf(specialChars[i]) > -1) {\n foundSpecial = true;\n }\n}\nif (foundSpecial) {\n System.out.println(esitoPositivospeciale);\n} else {\n throw new MissingSpecialCharacterException();\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19945992/" ]
74,512,285
<p>I am working with an SIR model using R. I need to plot multiple curves of I on the same figure for different values of beta, say for the values of 0.001, 0.002, 0.003, 0.004, and 0.005. Given below is the code that I have been working with so far. I know this might be a very simple problem, but I am new to R and couldn't find anything helpful yet.</p> <pre><code>library(deSolve) sir_model &lt;- function(time, variables, parameters) { with(as.list(c(variables, parameters)), { dS &lt;- -beta * I * S dI &lt;- beta * I * S - gamma * I dR &lt;- gamma * I return(list(c(dS, dI, dR))) }) } parameters &lt;- c(beta = 0.001, gamma = 0.3) initial_values &lt;- c(S = 999, I = 1, R = 0) time_series &lt;- seq(0, 100) sir_model_1 &lt;- ode( y = initial_values, times = time_series, func = sir_model, parms = parameters ) sir_model_1 &lt;- as.data.frame(sir_model_1) with(sir_model_1, { plot(time, I, type = &quot;l&quot;, col = &quot;black&quot;, xlab = &quot;time (days)&quot;, ylab = &quot;Number of infections&quot;) }) </code></pre> <p>I tried to use a for loop, but I think I am not doing it right.</p>
[ { "answer_id": 74512416, "author": "Bohemian", "author_id": 256196, "author_profile": "https://Stackoverflow.com/users/256196", "pm_score": 1, "selected": false, "text": "public boolean passwordValid(String password) {\n return password.matches(\"(?=.*[a-zA-Z])(?=.*\\\\d)(?=.*[!@#*+_(%?/{}\\\\[\\\\].,;:-]).*\");\n}\n (?=.*[a-zA-Z]) (?=.*\\\\d) (?=.*[!@#*+_(%?/{}\\\\[\\\\].,;:-]\")" }, { "answer_id": 74512468, "author": "access violation", "author_id": 19322069, "author_profile": "https://Stackoverflow.com/users/19322069", "pm_score": 4, "selected": true, "text": "for (int i = 0; i < specialChars.length; i++) {\n if (Password.indexOf(specialChars[i]) > -1) {\n System.out.println(esitoPositivospeciale);\n } else {\n throw new MissingSpecialCharacterException();\n }\n}\n boolean foundSpecial = false;\nfor (int i = 0; i < specialChars.length; i++) {\n if (Password.indexOf(specialChars[i]) > -1) {\n foundSpecial = true;\n }\n}\nif (foundSpecial) {\n System.out.println(esitoPositivospeciale);\n} else {\n throw new MissingSpecialCharacterException();\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557703/" ]
74,512,291
<p>If I beta-reduce the following expression:</p> <pre class="lang-hs prettyprint-override"><code> foldr (mappend . Sum) 1 [2] = (mappend . Sum) 2 (foldr (mappend . Sum) 1 []) = (mappend . Sum) 2 1 = mappend (Sum 2) 1 ... </code></pre> <p>Looking at the type of:</p> <pre class="lang-hs prettyprint-override"><code>// mappend (&lt;&gt;) :: Monoid a =&gt; a -&gt; a -&gt; a </code></pre> <p>We can see the last line has a type error, because the constant <code>1</code> should belong to <code>Monoid</code> class (and it does not).</p> <p>However, <code>ghci</code> doesn't complain.</p> <p>Why does that expression type checks ?</p>
[ { "answer_id": 74512324, "author": "Willem Van Onsem", "author_id": 67579, "author_profile": "https://Stackoverflow.com/users/67579", "pm_score": 3, "selected": false, "text": "1 Sum a foldr (mappend . Sum) 1 [2] :: Num a => Sum a\n 2 a 1 Sum a Sum a Num a Num newtype Sum a = Sum { getSum :: a }\n deriving ( Eq -- ^ @since 2.01\n , Ord -- ^ @since 2.01\n , Read -- ^ @since 2.01\n , Show -- ^ @since 2.01\n , Bounded -- ^ @since 2.01\n , Generic -- ^ @since 4.7.0.0\n , Generic1 -- ^ @since 4.7.0.0\n , Num -- ^ @since 4.7.0.0\n )\n 1 Sum a a Num 1 :: Sum Integer Sum 1 1 foldr Sum a mappend (Sum 2 :: Sum Integer) (1 :: Sum Integer)\n-> Sum (2 + 1)\n-> Sum 3\n" }, { "answer_id": 74512340, "author": "Robin Zigmond", "author_id": 8475054, "author_profile": "https://Stackoverflow.com/users/8475054", "pm_score": 2, "selected": true, "text": "Num a => Num (Sum a)\n Sum a a Sum 1 Num mappend (Sum 2) 1 mappend (Sum 2) (Sum 1) Num Sum a fromInteger 1 Sum 1" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9759263/" ]
74,512,312
<p>I am working through some messy data where, after reading it in, it appears as the following:</p> <pre><code>&gt; glimpse(il_births) Rows: 106 Columns: 22 $ x1989 &lt;dbl&gt; 190247, 928, 175, 187, 445, 57, 425, 41, 207, 166, 2662, 48… $ x1990 &lt;dbl&gt; 195499, 960, 192, 195, 462, 68, 449, 53, 222, 187, 2574, 47… $ x1991 &lt;dbl&gt; 194066, 971, 164, 195, 464, 72, 448, 54, 179, 211, 2562, 49… $ x1992 &lt;dbl&gt; 190923, 881, 189, 185, 462, 72, 414, 55, 201, 161, 2426, 46… $ x1993 &lt;dbl&gt; 190709, 893, 152, 206, 497, 50, 389, 75, 202, 183, 2337, 43… $ x1994 &lt;dbl&gt; 189182, 865, 158, 200, 538, 58, 429, 48, 189, 171, 2240, 41… $ x1995 &lt;dbl&gt; 185801, 828, 140, 202, 566, 58, 417, 48, 173, 166, 2117, 43… $ x1996 &lt;dbl&gt; 183079, 830, 147, 194, 529, 58, 417, 49, 175, 150, 2270, 41… $ x1997 &lt;dbl&gt; 180649, 812, 132, 193, 531, 64, 389, 37, 163, 185, 2175, 43… $ x1998 &lt;dbl&gt; 182503, 862, 140, 201, 545, 41, 417, 57, 185, 188, 2128, 41… $ x1999 &lt;dbl&gt; 182027, 843, 117, 188, 595, 51, 396, 47, 193, 191, 2194, 39… $ x2000 &lt;dbl&gt; 185003, 825, 132, 184, 587, 63, 434, 51, 170, 181, 2260, 40… $ x2001 &lt;dbl&gt; 184022, 866, 138, 196, 629, 57, 420, 49, 147, 215, 2312, 39… $ x2002 &lt;dbl&gt; 180555, 760, 129, 172, 629, 54, 434, 48, 191, 185, 2226, 39… $ x2003 &lt;dbl&gt; 182393, 794, 141, 239, 668, 76, 458, 58, 154, 208, 2288, 39… $ x2004 &lt;dbl&gt; 180665, 802, 126, 209, 646, 56, 396, 51, 151, 181, 2291, 42… $ x2005 &lt;dbl&gt; 178872, 883, 122, 189, 744, 54, 409, 58, 160, 199, 2490, 40… $ x2006 &lt;dbl&gt; 180503, 805, 112, 215, 737, 57, 392, 55, 140, 177, 2455, 41… $ x2007 &lt;dbl&gt; 180530, 890, 136, 185, 736, 60, 413, 49, 163, 195, 2508, 44… $ x2008 &lt;dbl&gt; 176634, 817, 120, 173, 676, 64, 409, 59, 142, 200, 2482, 40… $ x2009 &lt;dbl&gt; 171077, 804, 114, 198, 622, 65, 381, 53, 123, 164, 2407, 40… $ county_name &lt;chr&gt; &quot;ILLINOIS TOTAL&quot;, &quot;ADAMS&quot;, &quot;ALEXANDER&quot;, &quot;BOND&quot;, &quot;BOONE&quot;, &quot;B… </code></pre> <p>The data comes from <a href="https://data.illinois.gov/dataset/77all_live_births_in_illinois_19892009" rel="nofollow noreferrer">All Live Births In Illinois, 1989-2009</a>. The data frame is difficult to work with, as the years are the column headers in addition to a column with all of the counties. I would prefer if the table were formatted such that there is a year column and a county column, and each row contains an observation for one year and one county. This would make it easier to work with in ggplot such that I can make some quick visualizations of the data.</p> <p>I first tried transposing the data frame, but that leaves counties as rows so that does not help much.</p> <p>I also tried using the <code>pivot_longer()</code> function but was not sure how to set my parameters based on my issue.</p> <p>Any help or suggestions are appreciated!</p>
[ { "answer_id": 74512378, "author": "Ricardo Semião e Castro", "author_id": 13048728, "author_profile": "https://Stackoverflow.com/users/13048728", "pm_score": 2, "selected": true, "text": "pivot_longer data il_births cols -county_name names_to \"name\" values_to \"value\" pivot_longer(il_births, -county_name, names_to = \"year\")\n pivot_longer(il_births, -county_name, names_to = \"year\",\n names_prefix = \"x\", names_transform = list(year = as.numeric))\n" }, { "answer_id": 74512569, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 0, "selected": false, "text": "slice_max library(tidyverse)\n\ndata <- \"https://data.illinois.gov/dataset/\" %>%\n paste0(\"ac7f40df-b256-4867-9953-78c8c4a52590/\",\n \"resource/d7ec861b-6b7c-4260-82d8-3f05f49053f9/\",\n \"download/data.csv\") %>%\n read.csv(check.names = FALSE) %>%\n filter(row_number() != 1) %>%\n slice_max(`_2009`, n = 5) %>% # Remove this line to keep all data \n mutate(county_name = str_to_title(county_name)) %>%\n mutate(county_name = reorder(county_name, -`_2009`)) %>%\n pivot_longer(-county_name, names_to = \"Year\", values_to = \"Births\") %>%\n mutate(Year = as.numeric(substr(Year, 2, 5)))\n data\n#> # A tibble: 105 x 3\n#> county_name Year Births\n#> <fct> <dbl> <dbl>\n#> 1 \"Cook \" 1989 94096\n#> 2 \"Cook \" 1990 97005\n#> 3 \"Cook \" 1991 96387\n#> 4 \"Cook \" 1992 95140\n#> 5 \"Cook \" 1993 94614\n#> 6 \"Cook \" 1994 92881\n#> 7 \"Cook \" 1995 90029\n#> 8 \"Cook \" 1996 87747\n#> 9 \"Cook \" 1997 85589\n#> 10 \"Cook \" 1998 85970\n#> # ... with 95 more rows\n ggplot(data, aes(Year, Births, color = county_name)) +\n geom_line(alpha = 0.5) +\n scale_y_continuous(labels = scales::comma) +\n geom_point() +\n theme_minimal(base_size = 16) +\n scale_color_brewer(palette = \"Set1\", name = \"County\") +\n ggtitle(\"Live births in five most populous Illinois counties, 1989-2009\") +\n labs(caption = \"Source: Illinois Department of Public Health\")\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20472222/" ]
74,512,322
<p>This is my first question on my first project. I'm struggling to display my make any progress can someone point me in the right direction, not sure if its my code or set as newbie and a friend set up my html doc</p> <pre><code>&lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;Foil Checker&lt;/TITLE&gt; &lt;META http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;META http-equiv='cache-control' content='no-cache'&gt; &lt;META http-equiv='expires' content='0'&gt; &lt;META http-equiv='pragma' content='no-cache'&gt; &lt;SCRIPT type=&quot;text/javascript&quot; src=&quot;/XMII/JavaScript/bootstrap.js&quot; data-libs=&quot;i5Chart,i5Grid,i5SPCChart,i5Command&quot;&gt;&lt;/SCRIPT&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;stylesheet.css&quot;&gt; &lt;script src=&quot;https://code.jquery.com/jquery-3.6.0.js&quot; integrity=&quot;sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;main&gt; &lt;table&gt; &lt;thead&gt; &lt;th&gt;Stack Id&lt;/th&gt; &lt;th&gt;PO Number&lt;/th&gt; &lt;th&gt;Material&lt;/th&gt; &lt;th&gt;Describtion&lt;/th&gt; &lt;th&gt;PO QTY&lt;/th&gt; &lt;Th&gt;Stack Qty&lt;/Th&gt; &lt;th&gt;Extract time&lt;/th&gt; &lt;/thead&gt; &lt;Tbody id=&quot;data-output&quot;&gt; &lt;/Tbody&gt; &lt;/table&gt; &lt;/main&gt; &lt;/BODY&gt; &lt;script type=&quot;text/javascript&quot; src=&quot;main.js&quot;&gt;&lt;/script&gt; &lt;/HTML&gt; </code></pre> <p>JS</p> <pre><code>var data = fetch('./Data.json') .then(function(responce){ return responce.json(); }).then(function(data){ let placeholder = document.querySelector(&quot;#data-output&quot;); let out = &quot;&quot;; for(let product of products){ out += ` &lt;tr&gt; &lt;td&gt;${product.STACKID}&lt;/td&gt; &lt;td&gt;${product.PONUMBER}&lt;/td&gt; &lt;td&gt;${product.MATERIAL}&lt;/td&gt; &lt;td&gt;${product.DESCRIPTIONTEXT}&lt;/td&gt; &lt;td&gt;${product.POQTY}&lt;/td&gt; &lt;td&gt;${product.STACKQTY}&lt;/td&gt; &lt;td&gt;${product.EXTRACTTIME}&lt;/td&gt; &lt;/tr&gt; `; } placeholder.innerHTML = out; }); </code></pre> <p>I just seems to get a index out of the directory</p>
[ { "answer_id": 74512378, "author": "Ricardo Semião e Castro", "author_id": 13048728, "author_profile": "https://Stackoverflow.com/users/13048728", "pm_score": 2, "selected": true, "text": "pivot_longer data il_births cols -county_name names_to \"name\" values_to \"value\" pivot_longer(il_births, -county_name, names_to = \"year\")\n pivot_longer(il_births, -county_name, names_to = \"year\",\n names_prefix = \"x\", names_transform = list(year = as.numeric))\n" }, { "answer_id": 74512569, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 0, "selected": false, "text": "slice_max library(tidyverse)\n\ndata <- \"https://data.illinois.gov/dataset/\" %>%\n paste0(\"ac7f40df-b256-4867-9953-78c8c4a52590/\",\n \"resource/d7ec861b-6b7c-4260-82d8-3f05f49053f9/\",\n \"download/data.csv\") %>%\n read.csv(check.names = FALSE) %>%\n filter(row_number() != 1) %>%\n slice_max(`_2009`, n = 5) %>% # Remove this line to keep all data \n mutate(county_name = str_to_title(county_name)) %>%\n mutate(county_name = reorder(county_name, -`_2009`)) %>%\n pivot_longer(-county_name, names_to = \"Year\", values_to = \"Births\") %>%\n mutate(Year = as.numeric(substr(Year, 2, 5)))\n data\n#> # A tibble: 105 x 3\n#> county_name Year Births\n#> <fct> <dbl> <dbl>\n#> 1 \"Cook \" 1989 94096\n#> 2 \"Cook \" 1990 97005\n#> 3 \"Cook \" 1991 96387\n#> 4 \"Cook \" 1992 95140\n#> 5 \"Cook \" 1993 94614\n#> 6 \"Cook \" 1994 92881\n#> 7 \"Cook \" 1995 90029\n#> 8 \"Cook \" 1996 87747\n#> 9 \"Cook \" 1997 85589\n#> 10 \"Cook \" 1998 85970\n#> # ... with 95 more rows\n ggplot(data, aes(Year, Births, color = county_name)) +\n geom_line(alpha = 0.5) +\n scale_y_continuous(labels = scales::comma) +\n geom_point() +\n theme_minimal(base_size = 16) +\n scale_color_brewer(palette = \"Set1\", name = \"County\") +\n ggtitle(\"Live births in five most populous Illinois counties, 1989-2009\") +\n labs(caption = \"Source: Illinois Department of Public Health\")\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557754/" ]
74,512,333
<p>I am trying to make a 4-bit adder and test it. I decided to use <code>wait</code> to determine when the adder circuit is done by checking when my <code>sum</code> and <code>carry_out</code> are &gt;= 0. The inputs for the circuit are given as command line arguments. I am constructing my 4-bit adder using my full adder which I was able test successfully using this method.</p> <h2>full_adder.v</h2> <pre><code>//Behavioral Verilog module full_adder (input a, input b, input cin, output s, output cout); assign s = a ^ b ^ cin; assign cout = (a &amp;&amp; b) || (a &amp;&amp; cin) || (b &amp;&amp; cin); endmodule </code></pre> <h2>4_bit_adder.v</h2> <pre><code>module four_bit_adder(input [0:3] x, input [0:3] y, input carry_in, output [0:3] sum, output carry_out); full_adder add1(x[0], y[0], sum[0], carry_in, carry1); full_adder add2(x[1], y[1], sum[1], carry1, carry2); full_adder add3(x[2], y[2], sum[2], carry2, carry3); full_adder add4(x[3], y[3], sum[3], carry3, carry_out); endmodule </code></pre> <h2>4_bit_adder_tester.v</h2> <pre><code>module four_bit_adder_test; reg [0:3]x; reg [0:3]y; reg carry_in; wire sum; wire carry_out; four_bit_adder adder(x, y, carry_in, sum, carry_out); initial begin $display(&quot;Here&quot;); if (!$value$plusargs(&quot;x=%d&quot;, x)) begin $display(&quot;ERROR: please specify +x=&lt;value&gt; to start.&quot;); $finish; end if (!$value$plusargs(&quot;y=%d&quot;, y)) begin $display(&quot;ERROR: please specify +y=&lt;value&gt; to start.&quot;); $finish; end if (!$value$plusargs(&quot;carry_in=%d&quot;, carry_in)) begin $display(&quot;ERROR: please specify +carry_in=&lt;value&gt; to start.&quot;); $finish; end wait(sum &gt;= 0 &amp;&amp; carry_out&gt;= 0) $display(&quot;sum=%d, carry_out=%d&quot;, sum, carry_out); $finish; end endmodule </code></pre> <p>The problem is that <code>carry_out</code> remains at <code>x</code> so the <code>sum</code> and <code>carry_out</code> variables never get printed. I tried printing out the value of <code>carry_out</code>, and I think the logic in my circuits should work. Is this a valid way of testing my Verilog code?</p>
[ { "answer_id": 74512378, "author": "Ricardo Semião e Castro", "author_id": 13048728, "author_profile": "https://Stackoverflow.com/users/13048728", "pm_score": 2, "selected": true, "text": "pivot_longer data il_births cols -county_name names_to \"name\" values_to \"value\" pivot_longer(il_births, -county_name, names_to = \"year\")\n pivot_longer(il_births, -county_name, names_to = \"year\",\n names_prefix = \"x\", names_transform = list(year = as.numeric))\n" }, { "answer_id": 74512569, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 0, "selected": false, "text": "slice_max library(tidyverse)\n\ndata <- \"https://data.illinois.gov/dataset/\" %>%\n paste0(\"ac7f40df-b256-4867-9953-78c8c4a52590/\",\n \"resource/d7ec861b-6b7c-4260-82d8-3f05f49053f9/\",\n \"download/data.csv\") %>%\n read.csv(check.names = FALSE) %>%\n filter(row_number() != 1) %>%\n slice_max(`_2009`, n = 5) %>% # Remove this line to keep all data \n mutate(county_name = str_to_title(county_name)) %>%\n mutate(county_name = reorder(county_name, -`_2009`)) %>%\n pivot_longer(-county_name, names_to = \"Year\", values_to = \"Births\") %>%\n mutate(Year = as.numeric(substr(Year, 2, 5)))\n data\n#> # A tibble: 105 x 3\n#> county_name Year Births\n#> <fct> <dbl> <dbl>\n#> 1 \"Cook \" 1989 94096\n#> 2 \"Cook \" 1990 97005\n#> 3 \"Cook \" 1991 96387\n#> 4 \"Cook \" 1992 95140\n#> 5 \"Cook \" 1993 94614\n#> 6 \"Cook \" 1994 92881\n#> 7 \"Cook \" 1995 90029\n#> 8 \"Cook \" 1996 87747\n#> 9 \"Cook \" 1997 85589\n#> 10 \"Cook \" 1998 85970\n#> # ... with 95 more rows\n ggplot(data, aes(Year, Births, color = county_name)) +\n geom_line(alpha = 0.5) +\n scale_y_continuous(labels = scales::comma) +\n geom_point() +\n theme_minimal(base_size = 16) +\n scale_color_brewer(palette = \"Set1\", name = \"County\") +\n ggtitle(\"Live births in five most populous Illinois counties, 1989-2009\") +\n labs(caption = \"Source: Illinois Department of Public Health\")\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12104593/" ]
74,512,341
<p>So I'm trying to make a barplot on R that has a categorical label, not a number scale, as the x-axis. I then need to knit the RMarkdown file as a pdf. This is what it looks like before I knit it as a RMD:</p> <p><img src="https://i.stack.imgur.com/6JBwg.png" alt="enter image description here" /></p> <p>This is what it looks like after I knit it as an RMD:</p> <p><img src="https://i.stack.imgur.com/4hesO.png" alt="enter image description here" /></p> <p>This is the code for the plot (I know there are no issues with this code for my purposes; I'm just including it so that stack overflow doesn't think I'm spamming):</p> <p>`</p> <pre><code>barplot(t1, legend = TRUE, main=&quot;Commitment to Conserving Water vs. Age of Voice and Familiarity of Imagery&quot;, xlab = &quot;Voice - Familiarity Level&quot;, ylab = &quot;Number of Participants&quot;, ylim = c(0,40), beside = TRUE) </code></pre> <p>`</p> <p>As you can see in the images, hopefully, I lose some of the labels on the x-axis when I knit into RMD. I think this is because the x labels are too long, so R is just cutting every other one out to make the graph look neater. I either need a way to prevent R from doing this, or to make the x labels smaller.</p> <p>This is a school assignment where I can't use ggplot2 or anything like that; I have to do this in base R. I tried using cex.axis, but for some reason it would only change the size of the y axis font and not the x axis font, which might be because there's not really an axis for x. I also tried looking into rotating the x axis labels, if I can't make it smaller, but I couldn't find out how to do that in base R.</p>
[ { "answer_id": 74514737, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 1, "selected": false, "text": "fig.width= fig.height= ---\noutput: pdf_document\n---\n\n```{r, echo=FALSE, fig.width=7, fig.height=4.67}\n\n## simulate some data\nset.seed(580509)\nt1 <- replicate(10, runif(5, 0, 40)) |> `dimnames<-`(list(1:5, outer(c('AV', 'CV'), 0:4, paste)))\n\n## plot\nbarplot(t1,\n legend=TRUE, \n main=\"Commitment to Conserving Water vs. Age of Voice \n and Familiarity of Imagery\", \n xlab=\"Voice - Familiarity Level\", \n ylab=\"Number of Participants\",\n ylim=c(0, 40),\n beside=TRUE)\n```\n cex.names= args.legend= ?legend ## sim. data\nset.seed(580509)\nt1 <- replicate(10, runif(5, 0, 40)) |> `dimnames<-`(list(1:5, outer(c('AV', 'CV'), 0:4, paste)))\n\nbarplot(t1, legend=TRUE, ylim=c(0, 40), beside=TRUE, \n cex.names=.8,\n args.legend=list(x='topleft', cex=.8, title='levels')\n )\n ?barplot ggplot" }, { "answer_id": 74514744, "author": "Eva", "author_id": 12806202, "author_profile": "https://Stackoverflow.com/users/12806202", "pm_score": 0, "selected": false, "text": "{r}\nbarplot(t1,\n legend = TRUE, \n main=\"Commitment to Conserving Water vs. Age of Voice \n and Familiarity of Imagery\", \n xlab = \"Voice - Familiarity Level\", \n ylab = \"Number of Participants\",\n ylim = c(0,40), \n beside = TRUE)\n {r fig.width=7}\nbarplot(t1,\n legend = TRUE, \n main=\"Commitment to Conserving Water vs. Age of Voice \n and Familiarity of Imagery\", \n xlab = \"Voice - Familiarity Level\", \n ylab = \"Number of Participants\",\n ylim = c(0,40), \n beside = TRUE)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557773/" ]
74,512,351
<p>I have an index that returns something like this</p> <pre><code>Company_All { name : string; id : string; agentDocumentId : string } </code></pre> <p>is it possible to load the related agent document and then generate a nested result with selectFields and QueryData like this</p> <pre><code>ICompanyView { companyName : 'Warner', user { documentId : 'A/1' firstName : 'john', lastName : 'paul' } } </code></pre> <p>I need something like the below query that obviously doesn't work as I expect:</p> <pre><code> const queryData = new QueryData( [&quot;name&quot;, &quot;agentDocumentId&quot;, &quot;agent.firstName&quot;, &quot;agent.lastName&quot;], [&quot;companyName&quot;, &quot;user.documentId&quot;, &quot;user.lastName&quot;, &quot;user.firstName&quot;]); return await session.query&lt;Company_AllResult&gt;({ index: Company_All }) .whereEquals(&quot;companyId&quot;, request.companyId) .include(`agents/${agentDocumentId}`) // ???? .selectFields(queryData,ICompanyView) .single(); </code></pre>
[ { "answer_id": 74515345, "author": "Ayende Rahien", "author_id": 6366, "author_profile": "https://Stackoverflow.com/users/6366", "pm_score": 2, "selected": false, "text": "filter load" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1187394/" ]
74,512,361
<p>I have a simple java rest api with a mysql server. I need to deploy this on WSO2 APIM. I used mocky to make a fake rest api but the only call I can make is /songs to get all songs. /songs/6 will not give song with id 6. Same for put, delete, post. I don't know how to approach this. Do I need to host it on a public domain for it to work or are there workarounds? Would love some help here. I also have been trying to create a rest api with my existing java code and Integration studio. I am able to deploy but without much luck. I have also tried creating a react rest api but this approach is effectively no different and does not work either. i'm able to do localhost:3000/songs &amp; localhost:3000/songs/1 to get the song with id 1. But when this same json list used in wso apim i can only do a simple getall request to get the entire list.</p> <p><strong>APIControllers.class</strong></p> <pre><code>package com.music.app.rest.Controller; import com.music.app.rest.Models.Song; import com.music.app.rest.Repo.SongRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @RestController public class ApiControllers { @Autowired private SongRepo songRepo; @GetMapping(value = &quot;/&quot;) public String getPage(){ return &quot;Welcome&quot;; } @GetMapping(value=&quot;/songs&quot;) public List&lt;Song&gt; getSongs(){ return songRepo.findAll(); } @GetMapping(value = &quot;/song/{id}&quot;) public Optional&lt;Song&gt; getSongById(@PathVariable long id){ Song searchSong = songRepo.findById(id).get(); return songRepo.findById(searchSong.getId()); } @PostMapping(value=&quot;/save&quot;) public String saveSong(@RequestBody Song song){ songRepo.save(song); return &quot;Saved...&quot;; } @PutMapping(value=&quot;update/{id}&quot;) public String updateSong(@PathVariable long id, @RequestBody Song song){ Song updatedSong = songRepo.findById(id).get(); updatedSong.setTitle(song.getTitle()); updatedSong.setArtist(song.getArtist()); updatedSong.setYear(song.getYear()); songRepo.save(updatedSong); return &quot;Updated...&quot;; } @DeleteMapping(value=&quot;delete/{id}&quot;) public String deleteSong(@PathVariable long id){ Song deletedSong = songRepo.findById(id).get(); songRepo.delete((deletedSong)); return &quot;Deleted song with : &quot; + id + &quot;title: &quot; + deletedSong.getTitle() + &quot; and artist: &quot; + deletedSong.getArtist() + &quot; release in year: &quot; + deletedSong.getYear(); } } </code></pre> <p><strong>json file</strong></p> <pre><code>{ &quot;songs&quot;: [ { &quot;id&quot;: 1, &quot;title&quot;: &quot;1904&quot;, &quot;artist&quot;: &quot;The Tallest Man on Earth&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 2, &quot;title&quot;: &quot;#40&quot;, &quot;artist&quot;: &quot;Dave Matthews&quot;, &quot;year&quot;: &quot;1999&quot; }, { &quot;id&quot;: 4, &quot;title&quot;: &quot;#41&quot;, &quot;artist&quot;: &quot;Dave Matthews&quot;, &quot;year&quot;: &quot;1996&quot; }, { &quot;id&quot;: 5, &quot;title&quot;: &quot;American Girl&quot;, &quot;artist&quot;: &quot;Tom Petty&quot;, &quot;year&quot;: &quot;1977&quot; }, { &quot;id&quot;: 6, &quot;title&quot;: &quot;American Music&quot;, &quot;artist&quot;: &quot;Violent Femmes&quot;, &quot;year&quot;: &quot;1991&quot; }, { &quot;id&quot;: 7, &quot;title&quot;: &quot;American Pie&quot;, &quot;artist&quot;: &quot;Don McLean&quot;, &quot;year&quot;: &quot;1972&quot; }, { &quot;id&quot;: 8, &quot;title&quot;: &quot;And it Stoned Me&quot;, &quot;artist&quot;: &quot;Van Morrison&quot;, &quot;year&quot;: &quot;1970&quot; }, { &quot;id&quot;: 9, &quot;title&quot;: &quot;A Sailor's Christmas&quot;, &quot;artist&quot;: &quot;Jimmy Buffett&quot;, &quot;year&quot;: &quot;1996&quot; }, { &quot;id&quot;: 10, &quot;title&quot;: &quot;Badfish&quot;, &quot;artist&quot;: &quot;Sublime&quot;, &quot;year&quot;: &quot;1996&quot; }, { &quot;id&quot;: 11, &quot;title&quot;: &quot;Banana Pancakes&quot;, &quot;artist&quot;: &quot;Jack Johnson&quot;, &quot;year&quot;: &quot;2005&quot; }, { &quot;id&quot;: 12, &quot;title&quot;: &quot;Barefoot Children&quot;, &quot;artist&quot;: &quot;Jimmy Buffett&quot;, &quot;year&quot;: &quot;1995&quot; }, { &quot;id&quot;: 13, &quot;title&quot;: &quot;Big Parade&quot;, &quot;artist&quot;: &quot;The Lumineers&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 14, &quot;title&quot;: &quot;Brown Eyed Girl&quot;, &quot;artist&quot;: &quot;Van Morrison&quot;, &quot;year&quot;: &quot;1967&quot; }, { &quot;id&quot;: 15, &quot;title&quot;: &quot;Cape Canaveral&quot;, &quot;artist&quot;: &quot;Conor Oberst&quot;, &quot;year&quot;: &quot;2008&quot; }, { &quot;id&quot;: 16, &quot;title&quot;: &quot;Carry On&quot;, &quot;artist&quot;: &quot;fun.&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 17, &quot;title&quot;: &quot;Catch the Wind&quot;, &quot;artist&quot;: &quot;Donovan&quot;, &quot;year&quot;: &quot;1965&quot; }, { &quot;id&quot;: 18, &quot;title&quot;: &quot;Cat's in the Cradle&quot;, &quot;artist&quot;: &quot;Harry Chapin&quot;, &quot;year&quot;: &quot;1974&quot; }, { &quot;id&quot;: 19, &quot;title&quot;: &quot;Changes in Latitudes, Changes in Attitudes&quot;, &quot;artist&quot;: &quot;Jimmy Buffett&quot;, &quot;year&quot;: &quot;1977&quot; }, { &quot;id&quot;: 20, &quot;title&quot;: &quot;Classy Lumineers&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 21, &quot;title&quot;: &quot;Creep&quot;, &quot;artist&quot;: &quot;Radiohead&quot;, &quot;year&quot;: &quot;1993&quot; }, { &quot;id&quot;: 22, &quot;title&quot;: &quot;Danny Boy&quot;, &quot;artist&quot;: &quot;Johnny Cash&quot;, &quot;year&quot;: &quot;2002&quot; }, { &quot;id&quot;: 23, &quot;title&quot;: &quot;Darkness Between the Fireflies&quot;, &quot;artist&quot;: &quot;Mason Jennings&quot;, &quot;year&quot;: &quot;1997&quot; }, { &quot;id&quot;: 24, &quot;title&quot;: &quot;Dead Sea&quot;, &quot;artist&quot;: &quot;The Lumineers&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 25, &quot;title&quot;: &quot;Distantly in Love&quot;, &quot;artist&quot;: &quot;Jimmy Buffett&quot;, &quot;year&quot;: &quot;1983&quot; }, { &quot;id&quot;: 26, &quot;title&quot;: &quot;Don't Leave Me (Ne Me Quitte Pas)&quot;, &quot;artist&quot;: &quot;Regina Spektor&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 27, &quot;title&quot;: &quot;Don't Look Back in Anger&quot;, &quot;artist&quot;: &quot;Oasis&quot;, &quot;year&quot;: &quot;1996&quot; }, { &quot;id&quot;: 28, &quot;title&quot;: &quot;Don't Stop Believin'&quot;, &quot;artist&quot;: &quot;Journey&quot;, &quot;year&quot;: &quot;1981&quot; }, { &quot;id&quot;: 29, &quot;title&quot;: &quot;Doomsday&quot;, &quot;artist&quot;: &quot;Elvis Perkins&quot;, &quot;year&quot;: &quot;2009&quot; }, { &quot;id&quot;: 30, &quot;title&quot;: &quot;Do You Remember&quot;, &quot;artist&quot;: &quot;Jack Johnson&quot;, &quot;year&quot;: &quot;2005&quot; }, { &quot;id&quot;: 31, &quot;title&quot;: &quot;Drink the Water&quot;, &quot;artist&quot;: &quot;Jack Johnson&quot;, &quot;year&quot;: &quot;2001&quot; }, { &quot;id&quot;: 32, &quot;title&quot;: &quot;Emmylou&quot;, &quot;artist&quot;: &quot;First Aid Kit&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 33, &quot;title&quot;: &quot;Fall Line&quot;, &quot;artist&quot;: &quot;Jack Johnson&quot;, &quot;year&quot;: &quot;2003&quot; }, { &quot;id&quot;: 34, &quot;title&quot;: &quot;Father and Son&quot;, &quot;artist&quot;: &quot;Cat Stevens&quot;, &quot;year&quot;: &quot;1970&quot; }, { &quot;id&quot;: 35, &quot;title&quot;: &quot;Flake&quot;, &quot;artist&quot;: &quot;Jack Johnson&quot;, &quot;year&quot;: &quot;2001&quot; }, { &quot;id&quot;: 36, &quot;title&quot;: &quot;Flapper Girl&quot;, &quot;artist&quot;: &quot;The Lumineers&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 37, &quot;title&quot;: &quot;Flowers in Your Hair&quot;, &quot;artist&quot;: &quot;The Lumineers&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 38, &quot;title&quot;: &quot;Folsom Prison Blues&quot;, &quot;artist&quot;: &quot;Johnny Cash&quot;, &quot;year&quot;: &quot;1957&quot; }, { &quot;id&quot;: 39, &quot;title&quot;: &quot;Free Fallin'&quot;, &quot;artist&quot;: &quot;Tom Petty&quot;, &quot;year&quot;: &quot;1989&quot; }, { &quot;id&quot;: 40, &quot;title&quot;: &quot;Furr&quot;, &quot;artist&quot;: &quot;Blitzen Trapper&quot;, &quot;year&quot;: &quot;2008&quot; }, { &quot;id&quot;: 41, &quot;title&quot;: &quot;Get Well Cards&quot;, &quot;artist&quot;: &quot;Conor Oberst&quot;, &quot;year&quot;: &quot;2008&quot; }, { &quot;id&quot;: 42, &quot;title&quot;: &quot;Gulf Coast Highway&quot;, &quot;artist&quot;: &quot;Emmylou Harris&quot;, &quot;year&quot;: &quot;2000&quot; }, { &quot;id&quot;: 43, &quot;title&quot;: &quot;Half Light I&quot;, &quot;artist&quot;: &quot;Arcade Fire&quot;, &quot;year&quot;: &quot;2010&quot; }, { &quot;id&quot;: 44, &quot;title&quot;: &quot;Half Light II (No Celebration)&quot;, &quot;artist&quot;: &quot;Arcade Fire&quot;, &quot;year&quot;: &quot;2010&quot; }, { &quot;id&quot;: 45, &quot;title&quot;: &quot;Harvest&quot;, &quot;artist&quot;: &quot;Neil Young&quot;, &quot;year&quot;: &quot;1972&quot; }, { &quot;id&quot;: 46, &quot;title&quot;: &quot;Heart of Gold&quot;, &quot;artist&quot;: &quot;Neil Young&quot;, &quot;year&quot;: &quot;1972&quot; }, { &quot;id&quot;: 47, &quot;title&quot;: &quot;here i go again&quot;, &quot;artist&quot;: &quot;whitesnake&quot;, &quot;year&quot;: &quot;1982&quot; }, { &quot;id&quot;: 48, &quot;title&quot;: &quot;Hey Jealousy&quot;, &quot;artist&quot;: &quot;Gin Blossoms&quot;, &quot;year&quot;: &quot;1992&quot; }, { &quot;id&quot;: 49, &quot;title&quot;: &quot;Hey Soul Sister&quot;, &quot;artist&quot;: &quot;Train&quot;, &quot;year&quot;: &quot;2009&quot; }, { &quot;id&quot;: 50, &quot;title&quot;: &quot;High and Dry&quot;, &quot;artist&quot;: &quot;Radiohead&quot;, &quot;year&quot;: &quot;1995&quot; }, { &quot;id&quot;: 51, &quot;title&quot;: &quot;Ho Hey&quot;, &quot;artist&quot;: &quot;The Lumineers&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 52, &quot;title&quot;: &quot;Hollywood Forever Cemetery Sings&quot;, &quot;artist&quot;: &quot;Father John Misty&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 53, &quot;title&quot;: &quot;Home&quot;, &quot;artist&quot;: &quot;Edward Sharpe &amp; The Magnetic Zeros&quot;, &quot;year&quot;: &quot;2009&quot; }, { &quot;id&quot;: 54, &quot;title&quot;: &quot;Honey Do&quot;, &quot;artist&quot;: &quot;Jimmy Buffett&quot;, &quot;year&quot;: &quot;1983&quot; }, { &quot;id&quot;: 55, &quot;title&quot;: &quot;Hospitals and Jails&quot;, &quot;artist&quot;: &quot;Mason Jennings&quot;, &quot;year&quot;: &quot;2002&quot; }, { &quot;id&quot;: 56, &quot;title&quot;: &quot;Hotel California&quot;, &quot;artist&quot;: &quot;The Eagles&quot;, &quot;year&quot;: &quot;1977&quot; }, { &quot;id&quot;: 57, &quot;title&quot;: &quot;Hotel Yorba&quot;, &quot;artist&quot;: &quot;The White Stripes&quot;, &quot;year&quot;: &quot;2001&quot; }, { &quot;id&quot;: 58, &quot;title&quot;: &quot;I Feel Home&quot;, &quot;artist&quot;: &quot;OAR&quot;, &quot;year&quot;: &quot;1999&quot; }, { &quot;id&quot;: 59, &quot;title&quot;: &quot;I Knew You Were Trouble&quot;, &quot;artist&quot;: &quot;Taylor Swift&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 60, &quot;title&quot;: &quot;I'm Writing a Novel&quot;, &quot;artist&quot;: &quot;Father John Misty&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 61, &quot;title&quot;: &quot;Island in the Sun&quot;, &quot;artist&quot;: &quot;Weezer&quot;, &quot;year&quot;: &quot;2001&quot; }, { &quot;id&quot;: 62, &quot;title&quot;: &quot;I Mraz&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 63, &quot;title&quot;: &quot;Jack &amp; Diane&quot;, &quot;artist&quot;: &quot;John Mellencamp&quot;, &quot;year&quot;: &quot;1982&quot; }, { &quot;id&quot;: 64, &quot;title&quot;: &quot;Karma Police&quot;, &quot;artist&quot;: &quot;Radiohead&quot;, &quot;year&quot;: &quot;1997&quot; }, { &quot;id&quot;: 65, &quot;title&quot;: &quot;King of Spain&quot;, &quot;artist&quot;: &quot;The Tallest Man on Earth&quot;, &quot;year&quot;: &quot;2010&quot; }, { &quot;id&quot;: 66, &quot;title&quot;: &quot;King of the World&quot;, &quot;artist&quot;: &quot;First Aid Kit&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 67, &quot;title&quot;: &quot;Lean On Me&quot;, &quot;artist&quot;: &quot;Bill Withers&quot;, &quot;year&quot;: &quot;1972&quot; }, { &quot;id&quot;: 68, &quot;title&quot;: &quot;Little Talks&quot;, &quot;artist&quot;: &quot;Of Monsters and Men&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 69, &quot;title&quot;: &quot;Live and Die&quot;, &quot;artist&quot;: &quot;The Avett Brothers&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 70, &quot;title&quot;: &quot;Lola&quot;, &quot;artist&quot;: &quot;The Kinks&quot;, &quot;year&quot;: &quot;1970&quot; }, { &quot;id&quot;: 71, &quot;title&quot;: &quot;Lonesome Town&quot;, &quot;artist&quot;: &quot;Ricky Nelson&quot;, &quot;year&quot;: &quot;1958&quot; }, { &quot;id&quot;: 72, &quot;title&quot;: &quot;Love in the Library&quot;, &quot;artist&quot;: &quot;Jimmy Buffett&quot;, &quot;year&quot;: &quot;1994&quot; }, { &quot;id&quot;: 73, &quot;title&quot;: &quot;Love Story&quot;, &quot;artist&quot;: &quot;Taylor Swift&quot;, &quot;year&quot;: &quot;2008&quot; }, { &quot;id&quot;: 74, &quot;title&quot;: &quot;Margaritaville&quot;, &quot;artist&quot;: &quot;Jimmy Buffett&quot;, &quot;year&quot;: &quot;1977&quot; }, { &quot;id&quot;: 75, &quot;title&quot;: &quot;Me and Julio Down by the Schoolyard&quot;, &quot;artist&quot;: &quot;Paul Simon&quot;, &quot;year&quot;: &quot;1972&quot; }, { &quot;id&quot;: 76, &quot;title&quot;: &quot;Migration&quot;, &quot;artist&quot;: &quot;Jimmy Buffett&quot;, &quot;year&quot;: &quot;1974&quot; }, { &quot;id&quot;: 77, &quot;title&quot;: &quot;Moonshadow&quot;, &quot;artist&quot;: &quot;Cat Stevens&quot;, &quot;year&quot;: &quot;1971&quot; }, { &quot;id&quot;: 78, &quot;title&quot;: &quot;Mudfootball&quot;, &quot;artist&quot;: &quot;Jack Johnson&quot;, &quot;year&quot;: &quot;2001&quot; }, { &quot;id&quot;: 79, &quot;title&quot;: &quot;My Antonia&quot;, &quot;artist&quot;: &quot;Emmylou Harris&quot;, &quot;year&quot;: &quot;2000&quot; }, { &quot;id&quot;: 80, &quot;title&quot;: &quot;New Realization&quot;, &quot;artist&quot;: &quot;Sublime&quot;, &quot;year&quot;: &quot;1996&quot; }, { &quot;id&quot;: 81, &quot;title&quot;: &quot;No Surprises&quot;, &quot;artist&quot;: &quot;Radiohead&quot;, &quot;year&quot;: &quot;1997&quot; }, { &quot;id&quot;: 82, &quot;title&quot;: &quot;Nothing&quot;, &quot;artist&quot;: &quot;Mason Jennings&quot;, &quot;year&quot;: &quot;1997&quot; }, { &quot;id&quot;: 83, &quot;title&quot;: &quot;Nothing Else Matters&quot;, &quot;artist&quot;: &quot;Metallica&quot;, &quot;year&quot;: &quot;1992&quot; }, { &quot;id&quot;: 84, &quot;title&quot;: &quot;Only Son of the Ladiesman&quot;, &quot;artist&quot;: &quot;Father John Misty&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 85, &quot;title&quot;: &quot;Out on the Weekend&quot;, &quot;artist&quot;: &quot;Neil Young&quot;, &quot;year&quot;: &quot;1972&quot; }, { &quot;id&quot;: 86, &quot;title&quot;: &quot;Party Cyrus&quot;, &quot;year&quot;: &quot;2009&quot; }, { &quot;id&quot;: 87, &quot;title&quot;: &quot;Patience&quot;, &quot;artist&quot;: &quot;Guns N' Roses&quot;, &quot;year&quot;: &quot;1989&quot; }, { &quot;id&quot;: 88, &quot;title&quot;: &quot;Redemption Song&quot;, &quot;artist&quot;: &quot;Bob Marley&quot;, &quot;year&quot;: &quot;1980&quot; }, { &quot;id&quot;: 89, &quot;title&quot;: &quot;Rivers of Babylon&quot;, &quot;artist&quot;: &quot;Sublime&quot;, &quot;year&quot;: &quot;1998&quot; }, { &quot;id&quot;: 90, &quot;title&quot;: &quot;Rocket Man&quot;, &quot;artist&quot;: &quot;Elton John&quot;, &quot;year&quot;: &quot;1972&quot; }, { &quot;id&quot;: 91, &quot;title&quot;: &quot;Rodeo Clowns&quot;, &quot;artist&quot;: &quot;JackJohnson&quot;, &quot;year&quot;: &quot;2003&quot; }, { &quot;id&quot;: 92, &quot;title&quot;: &quot;Send My Fond Regards to Lonelyville&quot;, &quot;artist&quot;: &quot;Elvis Perkins&quot;, &quot;year&quot;: &quot;2009&quot; }, { &quot;id&quot;: 93, &quot;title&quot;: &quot;Sentimental Heart&quot;, &quot;artist&quot;: &quot;She &amp; Him&quot;, &quot;year&quot;: &quot;2008&quot;, &quot;web_url&quot;: &quot;http://www.songnotes.cc/songs/109-she-and-him-volume-one&quot;, &quot;img_url&quot;: &quot;http://fireflygrove.com/songnotes/images/artists/SheAndHim.jpg&quot; }, { &quot;id&quot;: 94, &quot;title&quot;: &quot;Shelter from the Storm&quot;, &quot;artist&quot;: &quot;Bob Dylan&quot;, &quot;year&quot;: &quot;1975&quot; }, { &quot;id&quot;: 95, &quot;title&quot;: &quot;Some Nights&quot;, &quot;artist&quot;: &quot;fun.&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 96, &quot;title&quot;: &quot;Somewhere Only We Know&quot;, &quot;artist&quot;: &quot;Keane&quot;, &quot;year&quot;: &quot;2004&quot; }, { &quot;id&quot;: 97, &quot;title&quot;: &quot;Space Oddity&quot;, &quot;artist&quot;: &quot;David Bowie&quot;, &quot;year&quot;: &quot;1969&quot; }, { &quot;id&quot;: 98, &quot;title&quot;: &quot;Stay or Leave&quot;, &quot;artist&quot;: &quot;Dave Matthews&quot;, &quot;year&quot;: &quot;2003&quot; }, { &quot;id&quot;: 99, &quot;title&quot;: &quot;Stubborn Love&quot;, &quot;artist&quot;: &quot;The Lumineers&quot;, &quot;year&quot;: &quot;2012&quot; }, { &quot;id&quot;: 100, &quot;title&quot;: &quot;Stuck in the Middle With You&quot;, &quot;artist&quot;: &quot;Stealers Wheel&quot;, &quot;year&quot;: &quot;1972&quot; }, { &quot;id&quot;: 101, &quot;title&quot;: &quot;test&quot;, &quot;artist&quot;: &quot;test&quot;, &quot;year&quot;: &quot;2012&quot; } ] } </code></pre>
[ { "answer_id": 74515345, "author": "Ayende Rahien", "author_id": 6366, "author_profile": "https://Stackoverflow.com/users/6366", "pm_score": 2, "selected": false, "text": "filter load" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12446621/" ]
74,512,363
<p>I am an R User that is trying to learn more about Python.</p> <p>I found this Python library that I would like to use for address parsing: <a href="https://github.com/zehengl/ez-address-parser" rel="nofollow noreferrer">https://github.com/zehengl/ez-address-parser</a></p> <p>I was able to try an example over here:</p> <pre><code>from ez_address_parser import AddressParser ap = AddressParser() result = ap.parse(&quot;290 Bremner Blvd, Toronto, ON M5V 3L9&quot;) print(results) [('290', 'StreetNumber'), ('Bremner', 'StreetName'), ('Blvd', 'StreetType'), ('Toronto', 'Municipality'), ('ON', 'Province'), ('M5V', 'PostalCode'), ('3L9', 'PostalCode')] </code></pre> <p>I have the following file that I imported:</p> <pre><code>df = pd.read_csv(r'C:/Users/me/OneDrive/Documents/my_file.csv', encoding='latin-1') name address 1 name1 290 Bremner Blvd, Toronto, ON M5V 3L9 2 name2 291 Bremner Blvd, Toronto, ON M5V 3L9 3 name3 292 Bremner Blvd, Toronto, ON M5V 3L9 </code></pre> <p>I tried to apply the above function and export the file:</p> <pre><code>df['Address_Parse'] = df['ADDRESS'].apply(ap.parse) df = pd.DataFrame(df) df.to_csv(r'C:/Users/me/OneDrive/Documents/python_file.csv', index=False, header=True) </code></pre> <p>This seems to have worked - but everything appears to be in one line!</p> <pre><code>[('290', 'StreetNumber'), ('Bremner', 'StreetName'), ('Blvd', 'StreetType'), ('Toronto', 'Municipality'), ('ON', 'Province'), ('M5V', 'PostalCode'), ('3L9', 'PostalCode')] </code></pre> <p>Is there a way in Python to make each of these &quot;elements&quot; (e.g. StreetNumber, StreetName, etc.) into a separate column?</p> <p>Thank you!</p>
[ { "answer_id": 74512440, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "Series join def parse(x):\n return pd.Series({k:v for v,k in ap.parse(x)})\n\nout = df.join(df['ADDRESS'].apply(parse))\n\nprint(out)\n" }, { "answer_id": 74512667, "author": "BeRT2me", "author_id": 11865956, "author_profile": "https://Stackoverflow.com/users/11865956", "pm_score": 1, "selected": false, "text": "pd.DataFrame.apply axis=1 result_type='expand' # df\n name address\n0 name1 290 Bremner Blvd, Toronto, ON M5V 3L9\n def parse_address(row):\n return {k:v for v,k in ap.parse(row.address)}\n\ndf = df.join(df.apply(parse_address, axis=1, result_type='expand'))\n\n# OR Something like this would also work:\n\ndef parse_address(row):\n return [x[0] for x in ap.parse(row.address)]\n\nnew_cols = [\n 'StreetNumber', \n 'StreetName',\n 'StreetType',\n 'Municipality',\n 'Province',\n 'PostalCode',\n 'PostalCode'\n]\n\ndf[new_cols] = df.apply(parse_address, axis=1, result_type='expand')\n # Method 1\n name address Municipality PostalCode Province StreetName StreetNumber StreetType\n0 name1 290 Bremner Blvd, Toronto, ON M5V 3L9 Toronto 3L9 ON Bremner 290 Blvd\n\n\n# Method 2\n name address StreetNumber StreetName StreetType Municipality Province PostalCode\n0 name1 290 Bremner Blvd, Toronto, ON M5V 3L9 290 Bremner Blvd Toronto ON 3L9\n # This:\nout = {k:v for v,k in [('a', 'b')]}\n\n# Is like writing this:\n\nout = {}\nfor v, k in [('a', 'b')]:\n out[k] = v\n\n# Both result in:\n{'b': 'a'}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13203841/" ]
74,512,381
<p>I just stated learning Python. My teacher asked me to take this string <code>&quot;quick brown fox, jumps over the lazy dog!&quot;</code>, iterate all letter using <code>i in range()</code> function, and whenever I find a whitespace in the string I need to make the next character uppercase. So that the final output would be <code>Quick Brown Fox, Jumps Over The Lazy Dog!</code></p> <p>The teacher said that I may need to use <code>len(mastering)-1</code> for this homework.</p> <p>Below is my code. I don’t know why I see the uppercase letter and then the repeated lower case of the same letter. I don't know how to skip them from the string during looping. Any suggestions are greatly appreciated!</p> <p>I tried using different sequences in the for loop function but none worked.</p> <pre><code>mystring = 'quick brown fox, jumps over the lazy dog!' newstring = mystring[0].upper() for i in range (1,len(mystring)): newstring = newstring + mystring [i] if mystring [i] == ' ': newstring = newstring + mystring[i+1].upper() print (newstring) </code></pre> <p>I am getting double letters. Here is the output -</p> <pre><code>Quick Bbrown Ffox, Jjumps Oover Tthe Llazy Ddog! </code></pre>
[ { "answer_id": 74512452, "author": "kosciej16", "author_id": 3361462, "author_profile": "https://Stackoverflow.com/users/3361462", "pm_score": 1, "selected": true, "text": "i == 6 mystring[i] nestring \"Quick\" + \"b\".upper() i==7 newstring mystring[i] for i in range (1,len(mystring)):\n if mystring [i-1] == ' ':\n newstring = newstring + mystring[i].upper()\n else:\n newstring = newstring + mystring[i]\n \" \".join(word.capitalize() for word in mystring.split(\" \"))\n" }, { "answer_id": 74512474, "author": "Pranav Hosangadi", "author_id": 843953, "author_profile": "https://Stackoverflow.com/users/843953", "pm_score": 1, "selected": false, "text": "for i in range(len(container)) for element in container enumerate str1 = str1 + new_character str.join mystring = 'quick brown fox, jumps over the lazy dog!'\n\nresult = []\n\nuppercase_next = True # Since you want to uppercase the first character, we default this to True\n\nfor char in mystring:\n if uppercase_next:\n result.append(char.upper())\n else:\n result.append(char)\n\n uppercase_next = (char == \" \") # char == \" \" figures out if the character is a space, \n # Then we assign the result to the variable uppercase_next\n \nnewstring = \"\".join(result) \nprint(newstring)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557782/" ]
74,512,390
<p>I am currently doing a python program to convert from image to hex string and the other way around. I need two functions, one that takes an image and returns a hex string that corresponds to the RGB values of each pixel, and another function that takes a hex string, two ints, and generates a visible image of that size corresponding to that hex string.</p> <p>I currently use imageio to get an RGB matrix from the image and then convert that to hex. That one is fast, around 2.5 seconds for a 442KB image of 918 x 575 pixels.</p> <p>In order to get the image from the string, I convert that to a matrix of hex values and then convert that to RGB to use imageio to create an image. This one is where the problem arises since it takes 36 seconds to do the process on the string corresponding to the same 918 x 575 image.</p> <p>How could I make it quicker?</p> <p>Here's the code:</p> <pre><code>def rgb2hex(rgb): &quot;&quot;&quot; convert a list or tuple of RGB values to a string in hex &quot;&quot;&quot; r,g,b = rgb return '{:02x}{:02x}{:02x}'.format(r, g, b) def arrayToString(array): &quot;&quot;&quot; convert an array to a string &quot;&quot;&quot; string = &quot;&quot; for element in array: string += str(element) return string def sliceStr(string,sliceLenght): &quot;&quot;&quot; slice a string in chunks of sliceLenght lenght &quot;&quot;&quot; string = str(string) array = np.array([string[i:i+sliceLenght] for i in range(0,len(string),sliceLenght)]) return array def hexToRGB(hexadecimal): &quot;&quot;&quot; convert a hex string to an array of RGB values &quot;&quot;&quot; h = hexadecimal.lstrip('#') if len(h)!=6: return return [int(h[i:i+2], 16) for i in (0, 2, 4)] def ImageToBytes(image): &quot;&quot;&quot; Image to convert from image to bytes &quot;&quot;&quot; dataToEncrypt =imageio.imread(image) if dataToEncrypt.shape[2] ==4: dataToEncrypt = np.delete(dataToEncrypt,3,2) originalRows, originalColumns,_ = dataToEncrypt.shape #converting rgb to hex hexVal = np.apply_along_axis(rgb2hex, 2, dataToEncrypt) hexVal = np.apply_along_axis(arrayToString, 1, hexVal) hexVal = str(np.apply_along_axis(arrayToString, 0, hexVal)) byteImage = bytes.fromhex(hexVal) return (byteImage, [originalRows,originalColumns]) def BytesToImage(byteToConvert,originalRows,originalColumns,name): &quot;&quot;&quot; Convert from Bytes to Image &quot;&quot;&quot; Data = byteToConvert.hex() stepOne = sliceStr(Data,originalColumns*6) stepTwo = [] for i in stepOne: step = sliceStr(i,6) #Add lost pixels while len(step) != originalColumns: step = np.append(step,&quot;ffffff&quot;) stepTwo.append(step) stepThree = [] for i in stepTwo: d = [] for j in i: d.append(hexToRGB(j)) if len(stepThree) &lt; originalRows: stepThree.append(d) Img = np.asarray(stepThree) imageio.imwrite(name,Img) </code></pre>
[ { "answer_id": 74512452, "author": "kosciej16", "author_id": 3361462, "author_profile": "https://Stackoverflow.com/users/3361462", "pm_score": 1, "selected": true, "text": "i == 6 mystring[i] nestring \"Quick\" + \"b\".upper() i==7 newstring mystring[i] for i in range (1,len(mystring)):\n if mystring [i-1] == ' ':\n newstring = newstring + mystring[i].upper()\n else:\n newstring = newstring + mystring[i]\n \" \".join(word.capitalize() for word in mystring.split(\" \"))\n" }, { "answer_id": 74512474, "author": "Pranav Hosangadi", "author_id": 843953, "author_profile": "https://Stackoverflow.com/users/843953", "pm_score": 1, "selected": false, "text": "for i in range(len(container)) for element in container enumerate str1 = str1 + new_character str.join mystring = 'quick brown fox, jumps over the lazy dog!'\n\nresult = []\n\nuppercase_next = True # Since you want to uppercase the first character, we default this to True\n\nfor char in mystring:\n if uppercase_next:\n result.append(char.upper())\n else:\n result.append(char)\n\n uppercase_next = (char == \" \") # char == \" \" figures out if the character is a space, \n # Then we assign the result to the variable uppercase_next\n \nnewstring = \"\".join(result) \nprint(newstring)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13090510/" ]
74,512,411
<p>I'd like to write functions that do common matrix operations. This can be done by 2-dim arrays or pointer arithmetic. I prefer a pointer version. Now with pointers I'd write a function like this:</p> <pre><code>void matmult(double *a, double *b, double *c, int m, int n, int k); </code></pre> <p>The problem is that I have to use a cast when I pass 2-dim arrays to the function. Is there a good solution to avoid this problem?</p> <p>Works without cast (of course), but I want to avoid compiler warnings.</p> <p>Update: the arrays are defined as 2-dim array and the calling function looks like this:</p> <pre><code>// M, N, K are constants double a[M][N]; double b[N][K]; double c[M][K]; matmult((double *)a, (double *)b, (double *)c, M, N, K); </code></pre> <p>The function matmult is a straight forward implementation of matrix multiplication (three nested for loops using pointers)</p> <pre><code>*(c + i*k + j) += *(a + i*n + p) * *(b + p*k + j); </code></pre> <p>I just want to get rid of the cast.</p>
[ { "answer_id": 74512452, "author": "kosciej16", "author_id": 3361462, "author_profile": "https://Stackoverflow.com/users/3361462", "pm_score": 1, "selected": true, "text": "i == 6 mystring[i] nestring \"Quick\" + \"b\".upper() i==7 newstring mystring[i] for i in range (1,len(mystring)):\n if mystring [i-1] == ' ':\n newstring = newstring + mystring[i].upper()\n else:\n newstring = newstring + mystring[i]\n \" \".join(word.capitalize() for word in mystring.split(\" \"))\n" }, { "answer_id": 74512474, "author": "Pranav Hosangadi", "author_id": 843953, "author_profile": "https://Stackoverflow.com/users/843953", "pm_score": 1, "selected": false, "text": "for i in range(len(container)) for element in container enumerate str1 = str1 + new_character str.join mystring = 'quick brown fox, jumps over the lazy dog!'\n\nresult = []\n\nuppercase_next = True # Since you want to uppercase the first character, we default this to True\n\nfor char in mystring:\n if uppercase_next:\n result.append(char.upper())\n else:\n result.append(char)\n\n uppercase_next = (char == \" \") # char == \" \" figures out if the character is a space, \n # Then we assign the result to the variable uppercase_next\n \nnewstring = \"\".join(result) \nprint(newstring)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557746/" ]
74,512,464
<p>I am using bloc state management in the Flutter framework, and I am working on an application that uses a socket with chat. I want as soon as the user leaves the room, I send an event to the socket so that he leaves the chat, but I see the error attached to you in the address, what is the solution?</p> <p><a href="https://i.stack.imgur.com/7rXTh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7rXTh.png" alt="Where I call method leave room" /></a></p>
[ { "answer_id": 74512452, "author": "kosciej16", "author_id": 3361462, "author_profile": "https://Stackoverflow.com/users/3361462", "pm_score": 1, "selected": true, "text": "i == 6 mystring[i] nestring \"Quick\" + \"b\".upper() i==7 newstring mystring[i] for i in range (1,len(mystring)):\n if mystring [i-1] == ' ':\n newstring = newstring + mystring[i].upper()\n else:\n newstring = newstring + mystring[i]\n \" \".join(word.capitalize() for word in mystring.split(\" \"))\n" }, { "answer_id": 74512474, "author": "Pranav Hosangadi", "author_id": 843953, "author_profile": "https://Stackoverflow.com/users/843953", "pm_score": 1, "selected": false, "text": "for i in range(len(container)) for element in container enumerate str1 = str1 + new_character str.join mystring = 'quick brown fox, jumps over the lazy dog!'\n\nresult = []\n\nuppercase_next = True # Since you want to uppercase the first character, we default this to True\n\nfor char in mystring:\n if uppercase_next:\n result.append(char.upper())\n else:\n result.append(char)\n\n uppercase_next = (char == \" \") # char == \" \" figures out if the character is a space, \n # Then we assign the result to the variable uppercase_next\n \nnewstring = \"\".join(result) \nprint(newstring)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11247805/" ]
74,512,472
<p>Regex to find even occurrence of a character in a string every time it repeats in a string</p> <p>Example:</p> <pre><code>YYMMDD-YYYY-DD true YYMDD false </code></pre> <p>Y,M,D are case sensitive Y,M,D can appear multiple time at multiple postion in pairs in string but each pair must be even.</p> <p>I have applied the above even check using for loop but have to replace for loop with regex I have also tried it with the below regex but it didn’t worked</p> <pre class="lang-js prettyprint-override"><code>if (result.match(/M{2,}/) || result.match(/D{2,}/) || result.match(/Y{2,}/)) {} </code></pre> <p><a href="https://i.stack.imgur.com/8ZKP1.jpg" rel="nofollow noreferrer">solution using for loop which i have implemented </a></p>
[ { "answer_id": 74512452, "author": "kosciej16", "author_id": 3361462, "author_profile": "https://Stackoverflow.com/users/3361462", "pm_score": 1, "selected": true, "text": "i == 6 mystring[i] nestring \"Quick\" + \"b\".upper() i==7 newstring mystring[i] for i in range (1,len(mystring)):\n if mystring [i-1] == ' ':\n newstring = newstring + mystring[i].upper()\n else:\n newstring = newstring + mystring[i]\n \" \".join(word.capitalize() for word in mystring.split(\" \"))\n" }, { "answer_id": 74512474, "author": "Pranav Hosangadi", "author_id": 843953, "author_profile": "https://Stackoverflow.com/users/843953", "pm_score": 1, "selected": false, "text": "for i in range(len(container)) for element in container enumerate str1 = str1 + new_character str.join mystring = 'quick brown fox, jumps over the lazy dog!'\n\nresult = []\n\nuppercase_next = True # Since you want to uppercase the first character, we default this to True\n\nfor char in mystring:\n if uppercase_next:\n result.append(char.upper())\n else:\n result.append(char)\n\n uppercase_next = (char == \" \") # char == \" \" figures out if the character is a space, \n # Then we assign the result to the variable uppercase_next\n \nnewstring = \"\".join(result) \nprint(newstring)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17505682/" ]
74,512,473
<p>I have a file (&quot;my_file&quot;) in R that looks something like this:</p> <pre><code> NAME Address_Parse 1 name1 [('372', 'StreetNumber'), ('river', 'StreetName'), ('St', 'StreetType'), ('S', 'StreetDirection'), ('toronto', 'Municipality'), ('ON', 'Province'), ('A1C', 'PostalCode'), ('9R7', 'PostalCode')] 2 name2 [('208', 'StreetNumber'), ('ocean', 'StreetName'), ('St', 'StreetType'), ('E', 'StreetDirection'), ('Toronto', 'Municipality'), ('ON', 'Province'), ('J8N', 'PostalCode'), ('1G8', 'PostalCode')] </code></pre> <p>In case the structure is confusing, here is how the file looks like</p> <pre><code>my_file = structure(list(NAME = c(&quot;name1&quot;, &quot;name2&quot;), Address_Parse = c(&quot;[('372', 'StreetNumber'), ('river', 'StreetName'), ('St', 'StreetType'), ('S', 'StreetDirection'), ('toronto', 'Municipality'), ('ON', 'Province'), ('A1C', 'PostalCode'), ('9R7', 'PostalCode')]&quot;, &quot;[('208', 'StreetNumber'), ('ocean', 'StreetName'), ('St', 'StreetType'), ('E', 'StreetDirection'), ('Toronto', 'Municipality'), ('ON', 'Province'), ('J8N', 'PostalCode'), ('1G8', 'PostalCode')]&quot; )), class = &quot;data.frame&quot;, row.names = c(NA, -2L)) </code></pre> <p><strong>Objective: For each row, I would like to take each of the &quot;elements&quot; (e.g. &quot;StreetNumber&quot;, &quot;StreetName&quot;, &quot;StreetType&quot;, etc.) and convert it into a new column. This would look something like this:</strong></p> <pre><code> name StreetNumber StreetName StreetType StreetDirection Municipality Province PostalCode 1 name1 372 river St S toronto ON A1C9R7 2 name2 208 ocean St E Toronto ON J8N1G8 </code></pre> <p>To me, it appears that the address field is in JSON format (I could be wrong about this). I tried to look at different ways I could parse the JSON. For example, I tried to apply the answer provided here (<a href="https://stackoverflow.com/questions/49633803/r-convert-nested-json-in-a-data-frame-column-to-addtional-columns-in-the-same-d">R: convert nested JSON in a data frame column to addtional columns in the same data frame</a>):</p> <pre><code>library(dplyr) library(tidyr) library(purrr) library(jsonlite) final = my_file %&gt;% mutate( json_parsed = map(Address_Parse, ~ fromJSON(., flatten=TRUE)) ) %&gt;% unnest(json_parsed) </code></pre> <p>However, this is giving me the following error:</p> <pre><code>Error in `mutate()`: ! Problem while computing `json_parsed = map(Address_Parse, ~fromJSON(., flatten = TRUE))`. Caused by error: ! lexical error: invalid char in json text. [('372', 'StreetNumber'), ('rive (right here) ------^ Run `rlang::last_error()` to see where the error occurred. </code></pre> <p>I then tried another approach:</p> <pre><code>final &lt;- my_file %&gt;% rowwise() %&gt;% do(data.frame(fromJSON(.$Address_Parse , flatten = T))) %&gt;% ungroup() %&gt;% bind_cols(my_file %&gt;% select(-Address_Parse )) </code></pre> <p>But I now get a new error:</p> <pre><code>Error: lexical error: invalid char in json text. [('372', 'StreetNumber'), ('rive (right here) ------^ </code></pre> <p>Can someone please show me to resolve this?</p> <p>Thank you!</p>
[ { "answer_id": 74512633, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": true, "text": "fromJSON \"key\":value (value, 'key') { } [ ] library(dplyr)\nlibrary(purrr)\nlibrary(stringr)\nlibrary(jsonlite)\nlibrary(tidyr)\nmy_file %>% \n mutate(Address_Parse = str_replace_all(Address_Parse,\n \"\\\\(([^,]+),\\\\s*([^)]+)\\\\)\", \"\\\\2:\\\\1\") %>% \n str_replace(fixed(\"[\"), \"[{\") %>%\n str_replace(fixed(\"]\"), \"}]\") %>%\n str_replace_all(fixed(\"'\"), '\"') %>% \n map(fromJSON)) %>%\n unnest(Address_Parse) %>%\n type.convert(as.is = TRUE)\n A tibble: 2 × 8\n NAME StreetNumber StreetName StreetType StreetDirection Municipality Province PostalCode\n <chr> <int> <chr> <chr> <chr> <chr> <chr> <chr> \n1 name1 372 river St S toronto ON A1C \n2 name2 208 ocean St E Toronto ON J8N \n reticulate library(reticulate)\npy_run_string(paste0(\"tmp=\", paste(my_file$Address_Parse, \n collapse = \",\")))\nout <- cbind(my_file[1], do.call(rbind, lapply(py$tmp, \\(x) \n do.call(cbind, lapply(x, \\(y) setNames(data.frame(y[[1]]), \n y[[2]]))))))\n > out\n NAME StreetNumber StreetName StreetType StreetDirection Municipality Province PostalCode PostalCode\n1 name1 372 river St S toronto ON A1C 9R7\n2 name2 208 ocean St E Toronto ON J8N 1G8\n" }, { "answer_id": 74512643, "author": "thelatemail", "author_id": 496803, "author_profile": "https://Stackoverflow.com/users/496803", "pm_score": 2, "selected": false, "text": "stream_in fromJSON library(jsonlite)\nout <- stream_in(textConnection(chartr(\"()'\", '[]\"', my_file$Address_Parse)))\ns <- seq(1, ncol(out)/2)\nsetNames(out[s], unlist(out[1, -s]))\n\n# StreetNumber StreetName StreetType StreetDirection Municipality Province PostalCode PostalCode\n#1 372 river St S toronto ON A1C 9R7\n#2 208 ocean St E Toronto ON J8N 1G8\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13203841/" ]
74,512,509
<p>I have to combine these 2 lists:</p> <pre><code>dots = [['.', '.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.', '.']] spaces = [[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']] </code></pre> <p>I want every dot separeted by a space and turn them into string just like this:</p> <pre><code>. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . </code></pre> <p>I wrote this code but it only work for the first line:</p> <pre><code>lists = [a for b in zip(dots[0], spaces[0]) for a in b] line = ''.join(liste) </code></pre> <p>I wanted to know how to loop in for every other sublist in these two lists.</p>
[ { "answer_id": 74512554, "author": "Pranav Hosangadi", "author_id": 843953, "author_profile": "https://Stackoverflow.com/users/843953", "pm_score": 3, "selected": true, "text": "zip lines = [\n \"\".join(\n dot + space \n for dot, space in zip(row_dots, row_spaces)\n )\n for row_dots, row_spaces in zip(dots, spaces) \n ]\n '\\n' output = \"\\n\".join(lines)\nprint(output)\n\n. . . . . . . . .\n. . . . . . . . .\n. . . . . . . . .\n. . . . . . . . .\n. . . . . . . . .\n. . . . . . . . .\n. . . . . . . . .\n. . . . . . . . .\n. . . . . . . . .\n output = \"\\n\".join(\n \"\".join(\n dot + space \n for dot, space in zip(row_dots, row_spaces)\n )\n for row_dots, row_spaces in zip(dots, spaces) \n )\n" }, { "answer_id": 74512568, "author": "kosciej16", "author_id": 3361462, "author_profile": "https://Stackoverflow.com/users/3361462", "pm_score": 1, "selected": false, "text": "result = []\nfor i in range(len(dots)):\n lists = [a for b in zip(dots[i], spaces[i]) for a in b]\n line = ''.join(lists)\n result.append(line)\n lists = [a for i in range(len(dots)) for b in zip(dots[i], spaces[i]) for a in b]\nline = \"\".join(lists)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18115952/" ]
74,512,510
<p>How can I iterate over a byte slice and assign them to the fields of a struct?</p> <pre class="lang-golang prettyprint-override"><code>type s struct { f1 []byte f2 []byte f3 []byte } func S s { x := s{} x.f1 = make([]byte, 4) x.f1 = make([]byte, 2) x.f1 = make([]byte, 2) return x } func main() { data := []byte{83, 117, 110, 83, 0, 1, 0, 65} Z := S() //pesudo code from here i:= 0 for field in Z { field = data[i:len(field)] i += len(field) } </code></pre> <p>Expecting:</p> <ul> <li>f1 = [83,117,110,83]</li> <li>f2 = [0,1]</li> <li>f3 = [0,65]</li> </ul> <p>I've done this in C/C++ before but I can't figure out how to do it in Go. I need the assigning function to be generic as I'm going to have several different structs some of which may not exist in the stream.</p> <p>Ideally I want to pass in the initialized struct and my code would iterate over the struct fields filling them in.</p>
[ { "answer_id": 74512719, "author": "blackgreen", "author_id": 4108803, "author_profile": "https://Stackoverflow.com/users/4108803", "pm_score": 0, "selected": false, "text": "reflect.Copy copy func main() {\n data := []byte{83, 117, 110, 83, 0, 1, 0, 65}\n\n z := S{\n F1: make([]byte, 4),\n F2: make([]byte, 2),\n F3: make([]byte, 2),\n }\n SetBytes(&z, data)\n fmt.Println(z) // {[83 117 110 83] [0 1] [0 65]}\n}\n\nfunc SetBytes(dst any, data []byte) {\n v := reflect.ValueOf(dst)\n if v.Kind() != reflect.Ptr {\n panic(\"dst must be addressable\")\n }\n v = v.Elem()\n\n j := 0\n for i := 0; i < v.NumField(); i++ {\n field := v.Field(i)\n if field.Kind() != reflect.Slice {\n continue\n }\n j += reflect.Copy(v.Field(i), reflect.ValueOf(data[j:]))\n }\n}\n data []byte reflect.Value#Slice d := reflect.ValueOf(data)\n// and later\nj += reflect.Copy(v.Field(i), d.Slice(j, d.Len()))\n" }, { "answer_id": 74513480, "author": "Fluent Gopher", "author_id": 20558765, "author_profile": "https://Stackoverflow.com/users/20558765", "pm_score": 2, "selected": true, "text": "type S struct {\n F1 [4]byte\n F2 [2]byte\n F3 [2]byte\n}\n var s S\ndata := []byte{83, 117, 110, 83, 0, 1, 0, 65}\nerr := binary.Read(bytes.NewReader(data), binary.LittleEndian, &s)\nif err != nil {\n log.Fatal(err)\n}\n fmt.Print(s) // prints {[83 117 110 83] [0 1] [0 65]}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2432240/" ]
74,512,511
<p>I want that the div panel_pricing-table become a flexbox so that all elements in it stay in this box also when I make my window smaller. My problem is that the elements in the flexbox won't shrink, if I make my browser window smaller. The mistake is in CSS but I don't find it. Can you help me pls? `</p> <pre><code>html { box-sizing: border-box; font-family: 'Open Sans', sans-serif; } body{ background-color: #3a86ff; } .panel_pricing-table{ width:80%; margin: 0 auto; display :flex; transform: translateY(70%); background-color: aliceblue; min-width: 40px; max-width: 34200px; } </code></pre> <p>`</p> <p>`</p> <pre><code> &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot; /&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt; &lt;title&gt;Price Tiers&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://fonts.googleapis.com/css?family=Open+Sans:400,600,700&quot; /&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;app.css&quot; /&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot;panel_pricing-table&quot;&gt; &lt;div class=&quot;pricing-plan&quot;&gt; &lt;img src=&quot;icons/icon1.png&quot; alt=&quot;&quot; class=&quot;pricing-img&quot; /&gt; &lt;h2 class=&quot;pricing-header&quot;&gt;Personal&lt;/h2&gt; &lt;ul class=&quot;pricing-features&quot;&gt; &lt;li class=&quot;pricing-features-item&quot;&gt;Custom domains&lt;/li&gt; &lt;li class=&quot;pricing-features-item&quot;&gt; Sleeps after 30 mins of inactivity &lt;/li&gt; &lt;/ul&gt; &lt;span class=&quot;pricing-price&quot;&gt;Free&lt;/span&gt; &lt;a href=&quot;#/&quot; class=&quot;pricing-button&quot;&gt;Sign up&lt;/a&gt; &lt;/div&gt; &lt;div class=&quot;pricing-plan&quot;&gt; &lt;img src=&quot;icons/icon2.png&quot; alt=&quot;&quot; class=&quot;pricing-img&quot; /&gt; &lt;h2 class=&quot;pricing-header&quot;&gt;Small team&lt;/h2&gt; &lt;ul class=&quot;pricing-features&quot;&gt; &lt;li class=&quot;pricing-features-item&quot;&gt;Never sleeps&lt;/li&gt; &lt;li class=&quot;pricing-features-item&quot;&gt; Multiple workers for more powerful apps &lt;/li&gt; &lt;/ul&gt; &lt;span class=&quot;pricing-price&quot;&gt;$150&lt;/span&gt; &lt;a href=&quot;#/&quot; class=&quot;pricing-button is-featured&quot;&gt;Free trial&lt;/a&gt; &lt;/div&gt; &lt;div class=&quot;pricing-plan&quot;&gt; &lt;img src=&quot;icons/icon3.png&quot; alt=&quot;&quot; class=&quot;pricing-img&quot; /&gt; &lt;h2 class=&quot;pricing-header&quot;&gt;Enterprise&lt;/h2&gt; &lt;ul class=&quot;pricing-features&quot;&gt; &lt;li class=&quot;pricing-features-item&quot;&gt;Dedicated&lt;/li&gt; &lt;li class=&quot;pricing-features-item&quot;&gt; Simple horizontal scalability &lt;/li&gt; &lt;/ul&gt; &lt;span class=&quot;pricing-price&quot;&gt;$400&lt;/span&gt; &lt;a href=&quot;#/&quot; class=&quot;pricing-button&quot;&gt;Free trial&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>`</p>
[ { "answer_id": 74512719, "author": "blackgreen", "author_id": 4108803, "author_profile": "https://Stackoverflow.com/users/4108803", "pm_score": 0, "selected": false, "text": "reflect.Copy copy func main() {\n data := []byte{83, 117, 110, 83, 0, 1, 0, 65}\n\n z := S{\n F1: make([]byte, 4),\n F2: make([]byte, 2),\n F3: make([]byte, 2),\n }\n SetBytes(&z, data)\n fmt.Println(z) // {[83 117 110 83] [0 1] [0 65]}\n}\n\nfunc SetBytes(dst any, data []byte) {\n v := reflect.ValueOf(dst)\n if v.Kind() != reflect.Ptr {\n panic(\"dst must be addressable\")\n }\n v = v.Elem()\n\n j := 0\n for i := 0; i < v.NumField(); i++ {\n field := v.Field(i)\n if field.Kind() != reflect.Slice {\n continue\n }\n j += reflect.Copy(v.Field(i), reflect.ValueOf(data[j:]))\n }\n}\n data []byte reflect.Value#Slice d := reflect.ValueOf(data)\n// and later\nj += reflect.Copy(v.Field(i), d.Slice(j, d.Len()))\n" }, { "answer_id": 74513480, "author": "Fluent Gopher", "author_id": 20558765, "author_profile": "https://Stackoverflow.com/users/20558765", "pm_score": 2, "selected": true, "text": "type S struct {\n F1 [4]byte\n F2 [2]byte\n F3 [2]byte\n}\n var s S\ndata := []byte{83, 117, 110, 83, 0, 1, 0, 65}\nerr := binary.Read(bytes.NewReader(data), binary.LittleEndian, &s)\nif err != nil {\n log.Fatal(err)\n}\n fmt.Print(s) // prints {[83 117 110 83] [0 1] [0 65]}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20556795/" ]
74,512,521
<p>I had this school project that I'm working on. I am done, I just need to edit it a bit and am running into a issue. I sent my code to my professor so he could check it over and there's only one thing wrong with it.</p> <blockquote> <p>All your array notations need to change to pure pointer notations such as <code>*s1</code> or <code>s1++</code>, etc. nothing like <code>*(random + 41 - 1)</code> or <code>*(s2_input + count)</code> - you need to update your pointer and use dereference (exactly what you are doing in <code>strfilter</code> function.</p> </blockquote> <p>He wouldn't explain further, so I am just confused on how exactly I would change my code. I have figured out my code is still in a array notation in a couple spots but any help would be appreciated. Such as <code>*(random + 41 - 1) = '\0';</code> , <code>*(s2_input + count) = '\0';</code> , and <code>*(s2_input + count) = input;</code>. What can I do to fix this?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; /*Function Prototypes*/ int main(); void s1(char *random); void s2(char *s2_input, int index); void strfilter(char *random, char *s2_input, char replacement); int main() { for(;;) { int s1_index = 41; char s1_random[s1_index]; s1(s1_random); printf(&quot;\ns1 = &quot;); puts(s1_random); printf(&quot;s2 = &quot;); int s2_index = 21; char s2_input[s2_index]; s2(s2_input, s2_index); if(s2_input[1] == '\0') { printf(&quot;Size too small&quot;); exit(0); } if(s2_input[21] != '\0' ) { printf(&quot;Size too big&quot;); exit(0); } printf(&quot;ch = &quot;); int replacement = getchar(); if(replacement == EOF) break; while(getchar() != '\n'); printf(&quot;\n&quot;); strfilter(s1_random, s2_input, replacement); printf(&quot;\ns1 filtered = &quot;); puts(s1_random); printf(&quot;Do you wish to run again? Yes(Y), No(N) &quot;); int run = getchar(); // or include ctype.h and do: // run == EOF || toupper(run) == 'N' if(run == EOF || run == 'N' || run == 'n') break; while(getchar() != '\n'); } } void s1(char *random) { int limit = 0; char characters; while((characters = (('A' + (rand() % 26))))) /* random generatro */ { if(limit == 41) { *(random + 41 - 1) = '\0'; break; } *(random + limit) = characters; limit++; } } void s2(char *s2_input, int index) { char array[21] = &quot;123456789012345678901&quot;; /* populated array to make sure no random memory is made */ char input; int count = 0; int check = 0; while((input = getchar() )) { if(input == '\n') { *(s2_input + count) = '\0'; break; } else if(input &lt; 65 || input &gt; 90) { printf(&quot;invalid input&quot;); exit(0); } *(s2_input + count) = input; count++; } index = count; } void strfilter(char *random, char *s2_input, char replacement) /* replacement function */ { while(*s2_input) { char *temp = random; while(*temp) { if(*temp == *s2_input) *temp = replacement; temp++; } s2_input++; } } </code></pre> <p>I tried a making a temporary pointer and replacing it with the array notation but I still would need to have the array notation somewhere. I can have the array defined somewhere but that's it. Any help would be greatly appreciated!</p> <p>I just got clarification from the professor on what he wants. You don't have to initialize s2 as an array you can initialize it as pointer to integer (int s2;) then you can do a pointer to an array (int (s1)[41];) then point to the single element of the array by doing this: s2 = s1; and incriminating to the next element by doing this: s2++</p> <p>Does this make sense to anyone? I understand that he wants me to make a int pointer, and then use that to point to a certain element in the array however I am not sure on how to implement that.</p>
[ { "answer_id": 74512719, "author": "blackgreen", "author_id": 4108803, "author_profile": "https://Stackoverflow.com/users/4108803", "pm_score": 0, "selected": false, "text": "reflect.Copy copy func main() {\n data := []byte{83, 117, 110, 83, 0, 1, 0, 65}\n\n z := S{\n F1: make([]byte, 4),\n F2: make([]byte, 2),\n F3: make([]byte, 2),\n }\n SetBytes(&z, data)\n fmt.Println(z) // {[83 117 110 83] [0 1] [0 65]}\n}\n\nfunc SetBytes(dst any, data []byte) {\n v := reflect.ValueOf(dst)\n if v.Kind() != reflect.Ptr {\n panic(\"dst must be addressable\")\n }\n v = v.Elem()\n\n j := 0\n for i := 0; i < v.NumField(); i++ {\n field := v.Field(i)\n if field.Kind() != reflect.Slice {\n continue\n }\n j += reflect.Copy(v.Field(i), reflect.ValueOf(data[j:]))\n }\n}\n data []byte reflect.Value#Slice d := reflect.ValueOf(data)\n// and later\nj += reflect.Copy(v.Field(i), d.Slice(j, d.Len()))\n" }, { "answer_id": 74513480, "author": "Fluent Gopher", "author_id": 20558765, "author_profile": "https://Stackoverflow.com/users/20558765", "pm_score": 2, "selected": true, "text": "type S struct {\n F1 [4]byte\n F2 [2]byte\n F3 [2]byte\n}\n var s S\ndata := []byte{83, 117, 110, 83, 0, 1, 0, 65}\nerr := binary.Read(bytes.NewReader(data), binary.LittleEndian, &s)\nif err != nil {\n log.Fatal(err)\n}\n fmt.Print(s) // prints {[83 117 110 83] [0 1] [0 65]}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20544996/" ]
74,512,541
<p>I’ve created an array to get the sum, biggest number, and smallest number from all the numbers in an array. When I use a cout statement to print out the numbers I’m given garbage. Can anyone help me understand what went wrong and what to do</p> <p>I previously asked a question on the same code asking about why my array wouldn’t print but I’ve fixed that problem so now the arrays are printing but after adding more functions to analyze the array and get info from it the outputs from the functions are garbage. Here’s what I have:</p> <pre><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;fstream&gt; #include &lt;cstdlib&gt; using namespace std; const int Ro = 4; const int Co = 5; void fillArray(int myArray[Ro][Co]); void printArray(int myArray[Ro][Co]); void doubleArray(int myArray[Ro][Co]); int max(int myArray[Ro][Co]); int min(int myArray[Ro][Co]); int sum(int myArray[Ro][Co]); int main() { srand(time(NULL)); int myArray[Ro][Co]; int sum, max, min; cout &lt;&lt; &quot;\n\n\n&quot;; fillArray(myArray); printArray(myArray); cout &lt;&lt; &quot;\n&quot;; cout &lt;&lt; &quot;The largest number is : &quot; &lt;&lt; max; cout &lt;&lt; &quot;\n&quot;; cout &lt;&lt; &quot;The smallest number is : &quot; &lt;&lt; min; cout &lt;&lt; &quot;\n&quot;; cout &lt;&lt; &quot;The sum is : &quot; &lt;&lt; sum; cout &lt;&lt; &quot;\n\n&quot;; doubleArray(myArray); printArray(myArray); return 0; } void fillArray(int myArray[Ro][Co]){ for (int r = 0; r &lt;= Ro; r++) { for(int c = 0; c &lt;= Co; c++){ myArray[r][c] = (rand()%100); } } } void printArray(int myArray[Ro][Co]){ for(int r = 0; r &lt; Ro; r++){ for(int c = 0; c &lt; Co; c++){ cout &lt;&lt; myArray[r][c] &lt;&lt; &quot; &quot;; } cout &lt;&lt; &quot;\n&quot;; } } void doubleArray(int myArray[Ro][Co]){ for(int r = 0; r &lt; Ro; r++){ for(int c = 0; c &lt; Co; c++){ myArray[r][c] = myArray[r][c]*2; } } } int max(int myArray[Ro][Co]) { int max = myArray[0][0]; for(int r = 0; r &lt; Ro; r++) { for(int c = 0; c &lt; Co; c++) { if(myArray[r][c] &gt; max){ max = myArray[r][c]; } } } return max; } int min(int myArray[Ro][Co]) { int min = myArray[0][0]; for(int r = 0; r &lt; Ro; r++) { for(int c = 0; c &lt; Co; c++) { if(myArray[r][c] &lt; min){ min = myArray[r][c]; } } } return min; } int sum(int myArray[Ro][Co]) { int sum = 0; for(int r = 0; r &lt; Ro; r++) { for(int c = 0; c &lt; Co; c++) { sum += myArray[r][c]; } } return sum; } </code></pre>
[ { "answer_id": 74512719, "author": "blackgreen", "author_id": 4108803, "author_profile": "https://Stackoverflow.com/users/4108803", "pm_score": 0, "selected": false, "text": "reflect.Copy copy func main() {\n data := []byte{83, 117, 110, 83, 0, 1, 0, 65}\n\n z := S{\n F1: make([]byte, 4),\n F2: make([]byte, 2),\n F3: make([]byte, 2),\n }\n SetBytes(&z, data)\n fmt.Println(z) // {[83 117 110 83] [0 1] [0 65]}\n}\n\nfunc SetBytes(dst any, data []byte) {\n v := reflect.ValueOf(dst)\n if v.Kind() != reflect.Ptr {\n panic(\"dst must be addressable\")\n }\n v = v.Elem()\n\n j := 0\n for i := 0; i < v.NumField(); i++ {\n field := v.Field(i)\n if field.Kind() != reflect.Slice {\n continue\n }\n j += reflect.Copy(v.Field(i), reflect.ValueOf(data[j:]))\n }\n}\n data []byte reflect.Value#Slice d := reflect.ValueOf(data)\n// and later\nj += reflect.Copy(v.Field(i), d.Slice(j, d.Len()))\n" }, { "answer_id": 74513480, "author": "Fluent Gopher", "author_id": 20558765, "author_profile": "https://Stackoverflow.com/users/20558765", "pm_score": 2, "selected": true, "text": "type S struct {\n F1 [4]byte\n F2 [2]byte\n F3 [2]byte\n}\n var s S\ndata := []byte{83, 117, 110, 83, 0, 1, 0, 65}\nerr := binary.Read(bytes.NewReader(data), binary.LittleEndian, &s)\nif err != nil {\n log.Fatal(err)\n}\n fmt.Print(s) // prints {[83 117 110 83] [0 1] [0 65]}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20259675/" ]
74,512,543
<p>I want to get values ​​from an array every day, respectively, and set these values ​​to a textbox. I can get values ​​from array and set them in textbox but next day value stays same. does not set the next value in array? what can I do?</p> <pre><code>&lt;string-array name=&quot;morning&quot;&gt; &lt;item&gt;Good Morning. Message 1.&lt;/item&gt; &lt;item&gt;Good Morning. Message 2.&lt;/item&gt; &lt;item&gt;Good Morning. Message 3.&lt;/item&gt; &lt;/string-array&gt; </code></pre> <pre><code>mTestArray = getResources().getStringArray(R.array.morning); preference_shared = this.getSharedPreferences(&quot;PREFERENCE&quot;, MODE_PRIVATE); text_shared = this.getSharedPreferences(&quot;TEXT&quot;, MODE_PRIVATE); Calendar c = Calendar.getInstance(); int timeOfDay = c.get(Calendar.DAY_OF_YEAR); if (timeOfDay &gt;= 0 &amp;&amp; timeOfDay &lt; 24) { if (preference_shared.getBoolean(&quot;isFirstRun&quot;, true)) { dailyGreetings.setText(mTestArray[(0) % (mTestArray.length)]); saveDate(); }else { if (!Objects.equals(preference_shared.getString(&quot;Date&quot;, &quot;&quot;), dateFormat.format(date))) { int idx = new Random().nextInt(mTestArray.length); dailyGreetings.setText(mTestArray[idx]); text_shared.edit().putString(&quot;TEXT&quot;, dailyGreetings.getText().toString()).apply(); saveDate(); } else { dailyGreetings.setText(text_shared.getString(&quot;TEXT&quot;, &quot;&quot;)); } } } </code></pre>
[ { "answer_id": 74512719, "author": "blackgreen", "author_id": 4108803, "author_profile": "https://Stackoverflow.com/users/4108803", "pm_score": 0, "selected": false, "text": "reflect.Copy copy func main() {\n data := []byte{83, 117, 110, 83, 0, 1, 0, 65}\n\n z := S{\n F1: make([]byte, 4),\n F2: make([]byte, 2),\n F3: make([]byte, 2),\n }\n SetBytes(&z, data)\n fmt.Println(z) // {[83 117 110 83] [0 1] [0 65]}\n}\n\nfunc SetBytes(dst any, data []byte) {\n v := reflect.ValueOf(dst)\n if v.Kind() != reflect.Ptr {\n panic(\"dst must be addressable\")\n }\n v = v.Elem()\n\n j := 0\n for i := 0; i < v.NumField(); i++ {\n field := v.Field(i)\n if field.Kind() != reflect.Slice {\n continue\n }\n j += reflect.Copy(v.Field(i), reflect.ValueOf(data[j:]))\n }\n}\n data []byte reflect.Value#Slice d := reflect.ValueOf(data)\n// and later\nj += reflect.Copy(v.Field(i), d.Slice(j, d.Len()))\n" }, { "answer_id": 74513480, "author": "Fluent Gopher", "author_id": 20558765, "author_profile": "https://Stackoverflow.com/users/20558765", "pm_score": 2, "selected": true, "text": "type S struct {\n F1 [4]byte\n F2 [2]byte\n F3 [2]byte\n}\n var s S\ndata := []byte{83, 117, 110, 83, 0, 1, 0, 65}\nerr := binary.Read(bytes.NewReader(data), binary.LittleEndian, &s)\nif err != nil {\n log.Fatal(err)\n}\n fmt.Print(s) // prints {[83 117 110 83] [0 1] [0 65]}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18611618/" ]
74,512,555
<p>SO basically it keeps saying error at line 14 which is the &quot;else&quot; code is at i dont get it why it is synta error please help</p> <pre><code>clear clc function f=f(x) f = x^3 + 2*x^2 - 3*x -1 endfunction disp (&quot;sample input&quot;): regulaFalsi (1,2,10^-4, 100) function regulaFalsi(a, b, TOL, N) i = 1 FA = f(a) finalOutput =(i, a , b , a + (b-a)/2, f(a + (b-a) /2) printf (&quot;%-20s%-20s%-20s%-20s%-20s\n&quot;,&quot;n&quot;,&quot;a_n&quot;,&quot;b_n&quot;,&quot;p_n&quot;,&quot;f(p_n)&quot;) while (i &lt;= N), p = (a*f(b)-b*f(a))/f(b) - f(a)) FP = f(p) if (FP == 0 | aba (f(p)) &lt; TOL) then break else printf(&quot;%-20.8g %-20.8g %-20.8g %-20.8g %-20.8g\n&quot;, i, a, b, p, f(p)) end i = i + 1 if (FA + FP &gt; 0) then a = p else b = p end end </code></pre> <p>I have been trying to fix this code for my assignment but i dont know why it keeps giving me syntax error</p>
[ { "answer_id": 74512719, "author": "blackgreen", "author_id": 4108803, "author_profile": "https://Stackoverflow.com/users/4108803", "pm_score": 0, "selected": false, "text": "reflect.Copy copy func main() {\n data := []byte{83, 117, 110, 83, 0, 1, 0, 65}\n\n z := S{\n F1: make([]byte, 4),\n F2: make([]byte, 2),\n F3: make([]byte, 2),\n }\n SetBytes(&z, data)\n fmt.Println(z) // {[83 117 110 83] [0 1] [0 65]}\n}\n\nfunc SetBytes(dst any, data []byte) {\n v := reflect.ValueOf(dst)\n if v.Kind() != reflect.Ptr {\n panic(\"dst must be addressable\")\n }\n v = v.Elem()\n\n j := 0\n for i := 0; i < v.NumField(); i++ {\n field := v.Field(i)\n if field.Kind() != reflect.Slice {\n continue\n }\n j += reflect.Copy(v.Field(i), reflect.ValueOf(data[j:]))\n }\n}\n data []byte reflect.Value#Slice d := reflect.ValueOf(data)\n// and later\nj += reflect.Copy(v.Field(i), d.Slice(j, d.Len()))\n" }, { "answer_id": 74513480, "author": "Fluent Gopher", "author_id": 20558765, "author_profile": "https://Stackoverflow.com/users/20558765", "pm_score": 2, "selected": true, "text": "type S struct {\n F1 [4]byte\n F2 [2]byte\n F3 [2]byte\n}\n var s S\ndata := []byte{83, 117, 110, 83, 0, 1, 0, 65}\nerr := binary.Read(bytes.NewReader(data), binary.LittleEndian, &s)\nif err != nil {\n log.Fatal(err)\n}\n fmt.Print(s) // prints {[83 117 110 83] [0 1] [0 65]}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557994/" ]
74,512,558
<p>My approach with this function is that it only accepts an integer as an input, otherwise if the person enters a letter or something else it goes back to the while loop and continues asking for the input until it receives the correct input which in this case it can only be 1-9.</p> <pre><code>import string string.ascii_letters def player_choice(board): position = 0 while position not in list(range(1,10)) or space_check(board, position) or position in list[string.ascii_letters]: if position in list[string.ascii_letters]: pass position = int(input(&quot;Please enter a position(1-9): &quot;)) return position </code></pre> <p>I tried importing ascii_letters from the string library to tell python that if the input is inside of the that list to go back to the while loop, but everytime I run the code i get a syntax error saying that the input only accepts an integer.</p>
[ { "answer_id": 74512782, "author": "puf", "author_id": 6583203, "author_profile": "https://Stackoverflow.com/users/6583203", "pm_score": 1, "selected": false, "text": "def player_choice(board):\n while True:\n position = input(\"Please enter a position(1-9): \")\n if position.isdecimal() and len(position) == 1 and position != '0':\n position = int(position)\n break\n return position\n import re\n\ndef player_choice(board):\n while True:\n position = input(\"Please enter a position(1-9): \")\n if re.match('^[1-9]$', position):\n position = int(position)\n break\n return position\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19865345/" ]
74,512,591
<p>I looked everywhere, but there are not any guides or explanations of how to use QSkyBoxEntity.</p> <p>I created Entity and filled it with transform (set translation and 3d scale). Also changed name and extension.</p> <p>When I'm trying to run program it says</p> <p>&quot;Qt3D.Renderer.OpenGL.Backend: Unable to find suitable Texture Unit for &quot;skyboxTexture&quot;&quot;</p> <p>I checked several times and tried different png files but no luck.<a href="https://i.stack.imgur.com/xA9Eq.png" rel="nofollow noreferrer"><br /> My image</a> (I know it's fake transparency, but it shouldn't change anything, right?)</p> <p>And here's part of a code:</p> <pre><code>Qt3DCore::QEntity *resultEntity = new Qt3DCore::QEntity; Qt3DExtras::QSkyboxEntity *skyboxEntity = new Qt3DExtras::QSkyboxEntity(resultEntity); skyboxEntity-&gt;setBaseName(&quot;skybox&quot;); //I tried using path as well skyboxEntity-&gt;setExtension(&quot;png&quot;); Qt3DCore::QTransform *skyTransform = new Qt3DCore::QTransform(skyboxEntity); skyTransform-&gt;setTranslation(QVector3D(0.0f,0.0f,0.0f)); skyTransform-&gt;setScale3D(QVector3D(0.1f,0.1f,0.1f)); skyboxEntity-&gt;addComponent(skyTransform); </code></pre>
[ { "answer_id": 74512782, "author": "puf", "author_id": 6583203, "author_profile": "https://Stackoverflow.com/users/6583203", "pm_score": 1, "selected": false, "text": "def player_choice(board):\n while True:\n position = input(\"Please enter a position(1-9): \")\n if position.isdecimal() and len(position) == 1 and position != '0':\n position = int(position)\n break\n return position\n import re\n\ndef player_choice(board):\n while True:\n position = input(\"Please enter a position(1-9): \")\n if re.match('^[1-9]$', position):\n position = int(position)\n break\n return position\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11019083/" ]
74,512,645
<p>I've been trying to debug this simple code for 20 minutes and it's driving me crazy, I'm starting to think there's a bug in Python. What I want to do is add two lists, element by element (there probably is some more efficient way to do this or even an in-build function, I'm just doing it as an exercise):</p> <pre><code>def add(l1,l2): if l1&gt;=l2: l=l1 for i in range(len(l2)): l1[i]+=l2[i] else: l=l2 for i in range(len(l1)): l2[i]+=l1[i] return l </code></pre> <p>Now for example:</p> <pre><code>add([1,2],[2,6,5]) [3, 8, 5] </code></pre> <p>But when the first number of the second list is negative, I get an error message:</p> <pre><code>add([1,2],[-2,6,5]) l1[i]+=l2[i] IndexError: list index out of range </code></pre> <p>How can the sign of one element affect the index whatsoever?</p> <p>To make things weirder, the code works just fine if I take out the if condition (I assume that the second list is longer here):</p> <pre><code>def add(l1,l2): l=l2 for i in range(len(l1)): l2[i]+=l1[i] return l </code></pre> <p>Then:</p> <pre><code>&gt;&gt;&gt; add([1,2],[-2,6,5]) [-1, 8, 5] </code></pre>
[ { "answer_id": 74512675, "author": "kosciej16", "author_id": 3361462, "author_profile": "https://Stackoverflow.com/users/3361462", "pm_score": 2, "selected": true, "text": "l1 = [1, 2]\nl2 = [2, 1]\nassert l1 < l2 (because l1[0] < l2[0])\n len if len(l1) >= len(l2):\n ...\n" }, { "answer_id": 74512721, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 0, "selected": false, "text": "def add(l1,l2):\n large, small = (l1, l2) if len(l1) >= len(l2) else (l2, l1)\n for i in range(len(small)):\n large[i] += small[i]\n return large\n\nprint(add([1,2], [2,6,5]))\nprint(add([1,2], [-2,6,5]))\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20558032/" ]
74,512,687
<p><a href="https://jsfiddle.net/wv3hmub1/14/" rel="nofollow noreferrer">https://jsfiddle.net/wv3hmub1/14/</a></p> <p>I want to achive this</p> <pre><code>Header -------------------- </code></pre> <p>or</p> <pre><code>My Header many letters second line --------------- </code></pre> <p>I tried this:</p> <pre class="lang-html prettyprint-override"><code>&lt;div class=&quot;max-width&quot;&gt; &lt;h5 class=&quot;h-line&quot;&gt;Horizontal line not displayed when too many letters &lt;/h5&gt; &lt;/div&gt; &lt;div class=&quot;max-width&quot;&gt; &lt;h5 class=&quot;h-line&quot;&gt;Horizontal line visible&lt;/h5&gt; &lt;/div&gt; </code></pre> <p>and CSS</p> <pre class="lang-css prettyprint-override"><code>.max-width { width: 300px; border: 1px solid red; } .h-line { display: flex; align-items: center; } .h-line::after { content: &quot;&quot;; flex: 1 1; margin-left: 1rem; height: 1px; background-color: rgb(100, 91, 91); } </code></pre> <p>It works fine for one line text, but horizontal line is not displayed for multiple lines header. Example code <a href="https://jsfiddle.net/wv3hmub1/14/" rel="nofollow noreferrer">https://jsfiddle.net/wv3hmub1/14/</a></p> <p>How to display the horizontal line for multiple line headers? (add one red line) <a href="https://i.stack.imgur.com/384aB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/384aB.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74512675, "author": "kosciej16", "author_id": 3361462, "author_profile": "https://Stackoverflow.com/users/3361462", "pm_score": 2, "selected": true, "text": "l1 = [1, 2]\nl2 = [2, 1]\nassert l1 < l2 (because l1[0] < l2[0])\n len if len(l1) >= len(l2):\n ...\n" }, { "answer_id": 74512721, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 0, "selected": false, "text": "def add(l1,l2):\n large, small = (l1, l2) if len(l1) >= len(l2) else (l2, l1)\n for i in range(len(small)):\n large[i] += small[i]\n return large\n\nprint(add([1,2], [2,6,5]))\nprint(add([1,2], [-2,6,5]))\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14120204/" ]
74,512,701
<p>I have components that have redundant code. I want to create a reusable component that will accept the property of a state that I want to update as a prop. How could I do so?</p> <pre><code>&lt;Text&gt; Calories&lt;/Text&gt; &lt;TextInput style={styles.input} onChangeText={(event) =&gt; setItem(prevState =&gt; ({ ...prevState, calories: parseInt(event) }))} keyboardType={'numeric'} value={item.calories} /&gt; &lt;Text&gt; Protein&lt;/Text&gt; &lt;TextInput style={styles.input} onChangeText={(event) =&gt; setItem(prevState =&gt; ({ ...prevState, protein: parseInt(event) }))} keyboardType={'numeric'} value={item.protein} /&gt; </code></pre> <p>Tried doing something like this with template literals but it doesnt work</p> <pre><code>export const Test = ({value}) =&gt; { return (&lt;&gt; &lt;Text&gt; {value}&lt;/Text&gt; &lt;TextInput style={styles.input} onChangeText={(event) =&gt; setItem(prevState =&gt; (`{ ...prevState, $(value): parseInt(event) }`))} keyboardType={'numeric'} value={`item.${value}`} /&gt; &lt;/&gt;) } </code></pre>
[ { "answer_id": 74512675, "author": "kosciej16", "author_id": 3361462, "author_profile": "https://Stackoverflow.com/users/3361462", "pm_score": 2, "selected": true, "text": "l1 = [1, 2]\nl2 = [2, 1]\nassert l1 < l2 (because l1[0] < l2[0])\n len if len(l1) >= len(l2):\n ...\n" }, { "answer_id": 74512721, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 0, "selected": false, "text": "def add(l1,l2):\n large, small = (l1, l2) if len(l1) >= len(l2) else (l2, l1)\n for i in range(len(small)):\n large[i] += small[i]\n return large\n\nprint(add([1,2], [2,6,5]))\nprint(add([1,2], [-2,6,5]))\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18604870/" ]
74,512,703
<p>I want to make one method which will be responsible to get value based on input arg key and to lookup for type of that value because its an object (can be int, string, datetime...)</p> <p>I created something like this:</p> <pre><code>public T GetValueForKeyFromHeader&lt;T&gt; (string key) { object value = null; var hasValue = Headers?.TryGetValue(key, out value!); //IDcitionary&lt;string, object&gt; return (T)Convert.ChangeType(typeof(value), typeof(T)); //here on this line I have an error: 'value' is a variable but its used like a type } </code></pre> <p>some examples of this IDictionary collection: //&quot;apiKeyId&quot;, &quot;guid&quot; //&quot;CorrelationId&quot;, 333 // &quot;test&quot;: &quot;hello world&quot;</p> <p>I want to extract these values, and to put them in my non-anemic model for each property:</p> <pre><code>public string Test{get;set;} = GetValueForKeyFromHeader(&quot;test&quot;); public int CorrelationId{get;set;} = GetValueForKeyFromHeader(&quot;CorrelationId&quot;); public string ApiKeyId {get;set;} = GetValueForKeyFromHeader(&quot;api_key_id&quot;); </code></pre>
[ { "answer_id": 74522435, "author": "t.ouvre", "author_id": 5658778, "author_profile": "https://Stackoverflow.com/users/5658778", "pm_score": 2, "selected": false, "text": "public static bool TryGetValue<TValue>(this IDictionary<string, object> self, string key, out TValue value)\n{\n if (!self.TryGetValue(key, out var _value))\n {\n value = default;\n return false;\n }\n if (_value is TValue casted)\n {\n value = casted;\n return true;\n }\n if (_value is string str)\n {\n var converter = TypeDescriptor.GetConverter(typeof(TValue));\n if (converter.CanConvertFrom(typeof(string)))\n {\n value = (TValue)converter.ConvertFromInvariantString(str);\n return true;\n }\n }\n value = default;\n return false;\n}\n public T GetValueForKeyFromHeader<T> (string key)\n{\n return Headers?.TryGetValue(key, out var value) == true ? value : default;\n}\n" }, { "answer_id": 74523124, "author": "Derrick Moeller", "author_id": 3194005, "author_profile": "https://Stackoverflow.com/users/3194005", "pm_score": 2, "selected": true, "text": "Convert.ChangeType return (T)Convert.ChangeType(value, typeof(T));\n TryGetValue KeyNotFoundException InvalidCastException null var value = Headers[key];\nreturn (T)Convert.ChangeType(value, typeof(T));\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5383872/" ]
74,512,733
<p>I am trying to calculate running (cumulative) totals per column on a range (please see picture below).</p> <p>If I use one SCAN function per column, it works. But I have to write as many SCAN functions as I have columns.</p> <p>The problem is that I want to use a single dynamic array formula that includes all the columns, whether current or future.</p> <p>When I try to use BYCOL together with LAMBDA and SCAN, it does not work. I wonder whether BYCOL is able to work with functions that SPILL.</p> <p>If BYCOL is incompatible with SCAN, is there a workaround to use a single formula for all my running totals?</p> <p><a href="https://i.stack.imgur.com/40Sqw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/40Sqw.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74513299, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 2, "selected": false, "text": "D2 =LET(set, A2:B5, m, COLUMNS(set), seq, SEQUENCE(m,1),\n CUMULATE, LAMBDA(x, SCAN(0, x, LAMBDA(acc,item, acc+item))),\n DROP(REDUCE(0,seq, LAMBDA(acc,idx, HSTACK(acc, CUMULATE(INDEX(set,,idx))))),,1)\n)\n DROP =LET(set, A2:B5, m, COLUMNS(set), seq, SEQUENCE(m,1),\n CUMULATE, LAMBDA(x, SCAN(0, x, LAMBDA(acc,item, acc+item))),\n REDUCE(0,seq, LAMBDA(acc,idx, IF(idx = 1, CUMULATE(INDEX(set,,idx)),\n HSTACK(acc, CUMULATE(INDEX(set,,idx))))))\n)\n MAP DROP/REDUCE/HSTACK =LET(n, ROWS(A2:B5), m, COLUMNS(A2:B5), \n rows, MAKEARRAY(n, m, LAMBDA(r, c, r)),cols, MAKEARRAY(n, m, LAMBDA(r, c, c)),\n MAP(rows, cols, LAMBDA(r, c, SUM(INDEX(A2:B5, 1, c):INDEX(A2:B5, r, c)) ))\n)\n LET A2:B5 LAMBDA INDEX() : INDEX() BYCOL #CALC! DROP/REDUCE/HSTACK LAMBDA CUMULATE LAMBDA(x, SCAN(0, x, LAMBDA(acc, item, acc+item)))\n REDUCE seq set INDEX(set,,idx) idx DROP/REDUCE/HSTACK DROP(REDUCE(0, arr, LAMBDA(acc, x, HSTACK(acc, func(x)))),,1)\n func(x) LAMBDA CUMULATE DROP(REDUCE(0,seq, LAMBDA(acc,idx, HSTACK(acc, CUMULATE(INDEX(set,,idx))))),,1)\n set CUMULATE LAMBDA HSTACK acc 0 HSTACK DROP(result,,1) 0\n#N/A\n#N/A\n#N/A\n HSTACK #N/A" }, { "answer_id": 74514685, "author": "Jos Woolley", "author_id": 17007704, "author_profile": "https://Stackoverflow.com/users/17007704", "pm_score": 2, "selected": false, "text": "=LET(ζ,A2:B5,ξ,ROWS(A2:B5),MMULT(N(SEQUENCE(ξ)>=SEQUENCE(,ξ)),ζ))" }, { "answer_id": 74518217, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 2, "selected": false, "text": "=SCAN(0,B4:C7,LAMBDA(a,b,IFERROR(SUM(OFFSET(b,-ROW(b)+1,0,ROW(b))),b)))\n =SCAN(0,B4:C7,LAMBDA(a,b,SUM(TAKE(CHOOSECOLS(B4:C7,COLUMN(b)-1),ROW(b)-3))))\n =LET(a,B4:C7,b,@COLUMN(a)-1,c,@ROW(a)-1,SCAN(0,a,LAMBDA(d,e,SUM(TAKE(CHOOSECOLS(a,COLUMN(e)-b),ROW(e)-c)))))\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6304284/" ]
74,512,738
<p>I have a problem with <code>audioplayers</code> in Flutter. The application runs on a Desktop but it doesn't run on Android and here is the error:</p> <pre><code>C:\flutter\.pub-cache\hosted\pub.dartlang.org\audioplayers_android-1.1.1\android\src\main\kotlin\xyz\luan\audioplayers\player\WrappedPlayer.kt:271:21: warning: parameter 'percent' is never used fun onBuffering(percent: Int) { ^ Note: Some input files use or override a deprecated API. Note: Recompile with -Xlint:deprecation for details. FileSystemException: readSync failed, path = 'C:\Users\Aburas\Desktop\adhan\build\app\outputs\flutter-apk\app-debug.apk' (OS Error: The operation completed successfully. , errno = 0) </code></pre> <p><img src="https://i.stack.imgur.com/Bgwly.png" alt="the result of that" /></p> <p>I tried to search on the internet, but I couldn't find a solution</p>
[ { "answer_id": 74513299, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 2, "selected": false, "text": "D2 =LET(set, A2:B5, m, COLUMNS(set), seq, SEQUENCE(m,1),\n CUMULATE, LAMBDA(x, SCAN(0, x, LAMBDA(acc,item, acc+item))),\n DROP(REDUCE(0,seq, LAMBDA(acc,idx, HSTACK(acc, CUMULATE(INDEX(set,,idx))))),,1)\n)\n DROP =LET(set, A2:B5, m, COLUMNS(set), seq, SEQUENCE(m,1),\n CUMULATE, LAMBDA(x, SCAN(0, x, LAMBDA(acc,item, acc+item))),\n REDUCE(0,seq, LAMBDA(acc,idx, IF(idx = 1, CUMULATE(INDEX(set,,idx)),\n HSTACK(acc, CUMULATE(INDEX(set,,idx))))))\n)\n MAP DROP/REDUCE/HSTACK =LET(n, ROWS(A2:B5), m, COLUMNS(A2:B5), \n rows, MAKEARRAY(n, m, LAMBDA(r, c, r)),cols, MAKEARRAY(n, m, LAMBDA(r, c, c)),\n MAP(rows, cols, LAMBDA(r, c, SUM(INDEX(A2:B5, 1, c):INDEX(A2:B5, r, c)) ))\n)\n LET A2:B5 LAMBDA INDEX() : INDEX() BYCOL #CALC! DROP/REDUCE/HSTACK LAMBDA CUMULATE LAMBDA(x, SCAN(0, x, LAMBDA(acc, item, acc+item)))\n REDUCE seq set INDEX(set,,idx) idx DROP/REDUCE/HSTACK DROP(REDUCE(0, arr, LAMBDA(acc, x, HSTACK(acc, func(x)))),,1)\n func(x) LAMBDA CUMULATE DROP(REDUCE(0,seq, LAMBDA(acc,idx, HSTACK(acc, CUMULATE(INDEX(set,,idx))))),,1)\n set CUMULATE LAMBDA HSTACK acc 0 HSTACK DROP(result,,1) 0\n#N/A\n#N/A\n#N/A\n HSTACK #N/A" }, { "answer_id": 74514685, "author": "Jos Woolley", "author_id": 17007704, "author_profile": "https://Stackoverflow.com/users/17007704", "pm_score": 2, "selected": false, "text": "=LET(ζ,A2:B5,ξ,ROWS(A2:B5),MMULT(N(SEQUENCE(ξ)>=SEQUENCE(,ξ)),ζ))" }, { "answer_id": 74518217, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 2, "selected": false, "text": "=SCAN(0,B4:C7,LAMBDA(a,b,IFERROR(SUM(OFFSET(b,-ROW(b)+1,0,ROW(b))),b)))\n =SCAN(0,B4:C7,LAMBDA(a,b,SUM(TAKE(CHOOSECOLS(B4:C7,COLUMN(b)-1),ROW(b)-3))))\n =LET(a,B4:C7,b,@COLUMN(a)-1,c,@ROW(a)-1,SCAN(0,a,LAMBDA(d,e,SUM(TAKE(CHOOSECOLS(a,COLUMN(e)-b),ROW(e)-c)))))\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20558088/" ]
74,512,771
<p>I have a huge list of dictionaries (I have shortened it here for clarity), where some values are duplicates (let's assume 'ID' is my target). How can I print the dictionary/ies where the ID occurs more than once?</p> <pre><code>[{'ID': 2501, 'First Name': 'Edward', 'Last Name': 'Crawford', 'Email': 'c.crawford@randatmail.com', 'Location': '[1.24564352 0.94323637]', 'Registration': '12/12/2000', 'Phone': '398-2890-30'}, {'ID': 3390936, 'First Name': 'Pepe', 'Last Name': 'Slim', 'Email': 'pepe.slim@somemail.com', 'Location': '[1.7297525 0.54631239]', 'Registration': '3/8/2020', 'Phone': '341-3456-85'}] </code></pre> <p>I have only been able to print certain values from the list of dict, but unable to parse through and identify duplicates.</p> <pre><code>all_phone = [i['Phone'] for i in comments] all_email = [i['Email'] for i in comments] </code></pre>
[ { "answer_id": 74512822, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 0, "selected": false, "text": "collections.Counter ID lst = [\n {\n \"ID\": 2501,\n \"First Name\": \"Edward\",\n \"Last Name\": \"Crawford\",\n \"Email\": \"c.crawford@randatmail.com\",\n \"Location\": \"[1.24564352 0.94323637]\",\n \"Registration\": \"12/12/2000\",\n \"Phone\": \"398-2890-30\",\n },\n {\n \"ID\": 3390936,\n \"First Name\": \"Pepe\",\n \"Last Name\": \"Slim\",\n \"Email\": \"pepe.slim@somemail.com\",\n \"Location\": \"[1.7297525 0.54631239]\",\n \"Registration\": \"3/8/2020\",\n \"Phone\": \"341-3456-85\",\n },\n # duplicate ID here:\n {\n \"ID\": 2501,\n \"First Name\": \"XXX\",\n \"Last Name\": \"XXX\",\n },\n]\n\nfrom collections import Counter\n\n# create a counter:\nc = Counter(d[\"ID\"] for d in lst)\n\n# print duplicated dictionaries:\nfor d in lst:\n if c[d[\"ID\"]] > 1:\n print(d)\n {\n \"ID\": 2501,\n \"First Name\": \"Edward\",\n \"Last Name\": \"Crawford\",\n \"Email\": \"c.crawford@randatmail.com\",\n \"Location\": \"[1.24564352 0.94323637]\",\n \"Registration\": \"12/12/2000\",\n \"Phone\": \"398-2890-30\",\n}\n{\"ID\": 2501, \"First Name\": \"XXX\", \"Last Name\": \"XXX\"}\n" }, { "answer_id": 74512824, "author": "IndexZero", "author_id": 18423808, "author_profile": "https://Stackoverflow.com/users/18423808", "pm_score": 0, "selected": false, "text": "if key not in d:\n d[key] = value\nelse:\n # you have a duplicate\n" }, { "answer_id": 74512849, "author": "AziMez", "author_id": 13809290, "author_profile": "https://Stackoverflow.com/users/13809290", "pm_score": 0, "selected": false, "text": "comments=[{'ID': 1111,\n 'First Name': 'foo1',\n 'Last Name': 'bar1'},\n {'ID': 2222,\n 'First Name': 'foo2',\n 'Last Name': 'bar2'},\n {'ID': 1111,\n 'First Name': 'foo3',\n 'Last Name': 'bar3'},\n {'ID': 3333,\n 'First Name': 'foo4',\n 'Last Name': 'bar4'},\n {'ID': 2222,\n 'First Name': 'foo5',\n 'Last Name': 'bar5'},]\n \nall_ID = [i['ID'] for i in comments]\n\nDuplicates =list(set([x for x in all_ID if all_ID.count(x) > 1]))\n \nprint(\"Duplicates found! =>\", Duplicates )\n Duplicates found! => [2222, 1111]\n" }, { "answer_id": 74513043, "author": "bn_ln", "author_id": 10535824, "author_profile": "https://Stackoverflow.com/users/10535824", "pm_score": 2, "selected": true, "text": "Counter def find_duplicates(dicts, field):\n counts = {}\n for d in dicts:\n counts[d[field]] = counts.get(d[field], 0) + 1\n return [d for d in dicts if counts[d[field]]>1]\n\nphone_duplicates = find_duplicates(comments, 'Phone')\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20558078/" ]
74,512,813
<p>I have 50 text files that looks like this. All the file names begin with ENSG00000...</p> <pre><code>&quot;number&quot; &quot;variant_id&quot; &quot;gene_id&quot; &quot;tss_distance&quot; &quot;ma_samples&quot; &quot;ma_count&quot; &quot;maf&quot; &quot;pval_nominal&quot;&quot;slope&quot; &quot;slope_se&quot; &quot;hg38_chr&quot; &quot;hg38_pos&quot; &quot;ref_allele&quot; &quot;alt_allele&quot; &quot;hg19_chr&quot; &quot;hg19_pos&quot; &quot;ID&quot; &quot;new_MAF&quot; &quot;CHROM&quot; &quot;POS&quot; &quot;REF&quot; &quot;ALT&quot; &quot;A1&quot; &quot;OBS_CT&quot; &quot;BETA&quot; &quot;SE&quot; &quot;P&quot; &quot;SD&quot; &quot;Variance&quot; &quot;14&quot; 6253456 &quot;chr1_17726150_G_A_b38&quot; &quot;ENSG00000186715.10&quot; 955913 68 78 0.0644628 0.895156 0.0139683 0.105945 &quot;chr1&quot; 17726150 &quot;G&quot; &quot;A&quot; &quot;chr1&quot; 18052645 &quot;rs260514:18052645:G:A0.058155 1 18052645 &quot;G&quot; &quot;A&quot; &quot;G&quot; 1597 0.0147047 0.0656528 0.822804 2.62364886486368 6.88353336610048 </code></pre> <p>I want to get rid of the speech marks surrounding every value in the file, so it looks like this below. I am using the script below which works for when I try with one file.</p> <pre><code>number variant_id gene_id tss_distance ma_samples ma_count maf pval_nominal slope slope_se hg38_chr hg38_pos ref_allele alt_allele hg19_chr hg19_pos ID new_MAF CHROM POS REF ALT A1 OBS_CT BETA SE P SD Variance 14 6253456 chr1_17726150_G_A_b38 ENSG00000186715.10 955913 68 78 0.0644628 0.895156 0.0139683 0.105945 chr1 17726150 G A chr1 18052645 rs260514:18052645:G:A0.058155 1 18052645 G A G 1597 0.0147047 0.0656528 0.822804 2.62364886486368 6.88353336610048 </code></pre> <p>However, I want to apply the awk script to all 50 files via a loop. However, when I use the script below I get no output.</p> <pre><code>#!/bin/bash #PBS -N Edit #PBS -l walltime=01:00:00 #PBS -l nodes=1:ppn=8 #PBS -l vmem=10gb #PBS -m bea for i in ENSG00000*; do awk '{ gsub(/&quot;/, &quot;&quot;); print }' &gt; $i.out done </code></pre>
[ { "answer_id": 74512881, "author": "Cameron Priest", "author_id": 13306247, "author_profile": "https://Stackoverflow.com/users/13306247", "pm_score": 3, "selected": true, "text": "for i in ENSG00000*; do\n awk '{ gsub(/\"/, \"\"); print }' $i > $i.out\ndone\n" }, { "answer_id": 74513406, "author": "Diego Torres Milano", "author_id": 236465, "author_profile": "https://Stackoverflow.com/users/236465", "pm_score": 2, "selected": false, "text": "sed -i '' 's/\"//g' ENSG00000*\n" }, { "answer_id": 74515601, "author": "user1934428", "author_id": 1934428, "author_profile": "https://Stackoverflow.com/users/1934428", "pm_score": 2, "selected": false, "text": "tr -d '\"' <$i >$i.out\n" }, { "answer_id": 74516756, "author": "Dudi Boy", "author_id": 6266192, "author_profile": "https://Stackoverflow.com/users/6266192", "pm_score": 1, "selected": false, "text": "awk awk -i inplace '{ gsub(/\"/, \"\"); print }' ENSG00000*\n sed sed -i '' 's/\"//g' ENSG00000*\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14614150/" ]
74,512,819
<p>I have this code. I need to group by CustomerName and then sum the filegroups.</p> <pre><code>def consolidated_df(): df = breakdown_df() df.pivot_table(index='CustomerName', columns='FileGroup', aggfunc=&quot;sum&quot;) return df </code></pre> <p><code>breakdown_df()</code> looks like</p> <pre><code>ID CustomerName FileGroup Size Size(Bytes) 1 CustomerA Database 99.8 M 104667648 1 CustomerA Database 99.8 M 104667648 1 CustomerA Backup 99.8 M 104667648 1 CustomerA Backup 99.8 M 104667648 1 CustomerA Site 99.8 M 104667648 1 CustomerA Site 99.8 M 104667648 2 CustomerB Database 99.8 M 104667648 2 CustomerB Database 99.8 M 104667648 2 CustomerB Backup 99.8 M 104667648 2 CustomerB Backup 99.8 M 104667648 2 CustomerB Site 99.8 M 104667648 2 CustomerB Site 99.8 M 104667648 </code></pre> <p>I am trying to roll it up into</p> <pre><code>ID CustomerName DatabaseSize DatabaseSizeBytes BackupSize BackupSizeBytes SiteSize SiteSizeByte TotalSize 1 CustomerA [Total Size] [Total Size Bytes] [TotalSize] [Total Size Bites] [Total Site Size] [Total Site Bites] [Total Bytes for everything] 2 CustomerB [Total Size] [Total Size Bytes] [TotalSize] [Total Size Bites] [Total Site Size] [Total Site Bites] [Total Bytes for everything] </code></pre> <p>I'm not so worried about actually summing <code>Size</code> because I can convert the bites. I just can't seem to get my pivot to work and unsure where I am going wrong.</p>
[ { "answer_id": 74512881, "author": "Cameron Priest", "author_id": 13306247, "author_profile": "https://Stackoverflow.com/users/13306247", "pm_score": 3, "selected": true, "text": "for i in ENSG00000*; do\n awk '{ gsub(/\"/, \"\"); print }' $i > $i.out\ndone\n" }, { "answer_id": 74513406, "author": "Diego Torres Milano", "author_id": 236465, "author_profile": "https://Stackoverflow.com/users/236465", "pm_score": 2, "selected": false, "text": "sed -i '' 's/\"//g' ENSG00000*\n" }, { "answer_id": 74515601, "author": "user1934428", "author_id": 1934428, "author_profile": "https://Stackoverflow.com/users/1934428", "pm_score": 2, "selected": false, "text": "tr -d '\"' <$i >$i.out\n" }, { "answer_id": 74516756, "author": "Dudi Boy", "author_id": 6266192, "author_profile": "https://Stackoverflow.com/users/6266192", "pm_score": 1, "selected": false, "text": "awk awk -i inplace '{ gsub(/\"/, \"\"); print }' ENSG00000*\n sed sed -i '' 's/\"//g' ENSG00000*\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20497632/" ]
74,512,827
<p>Ok so I want to subtract 9 to numbers(elements in an array) over 9:</p> <pre><code>finalCredDigits = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8] </code></pre> <p>Thats what I tried</p> <pre><code>finalCredDigits.forEach(arr =&gt;{ if(arr &gt; 9){ finalCredDigits.push(arr - 9); } }); </code></pre> <pre><code>Output = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8, 1, 9, 7, 7, 5, 5, 1] </code></pre> <p>I know its cuz the result is being pushed in the array but i want to mutate it and replace the answer with numbers over 9</p>
[ { "answer_id": 74512886, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 1, "selected": false, "text": "forEach() const finalCredDigits = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8];\n\nfinalCredDigits.forEach((el, i) =>{\n if(el > 9){\n finalCredDigits[i] = el - 9;\n } \n});\n\nconsole.log(finalCredDigits);" }, { "answer_id": 74512952, "author": "user2519141", "author_id": 2519141, "author_profile": "https://Stackoverflow.com/users/2519141", "pm_score": -1, "selected": true, "text": "let finalCredDigits = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8]\n\nfinalCredDigits = finalCredDigits.map(number => {\n if (number > 9) {\n return number - 9\n }\n\n return number\n})\n\nconsole.log(finalCredDigits)\n" }, { "answer_id": 74512963, "author": "Oskar Grosser", "author_id": 13561410, "author_profile": "https://Stackoverflow.com/users/13561410", "pm_score": 2, "selected": false, "text": "Array.map() const finalCredDigits = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8];\nconst newFinalCredDigits = finalCredDigits.map(v => {\n if (v > 9) {\n return v - 9;\n } else {\n return v;\n }\n});\n\nconsole.log(newFinalCredDigits.join());\nconsole.log(\"Is new array?\", newFinalCredDigits !== finalCredDigits); Array.forEach() const finalCredDigits = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8];\nfinalCredDigits.forEach((v, i, array) => {\n if (v > 9) {\n array[i] = v - 9;\n }\n});\n\nconsole.log(finalCredDigits.join()); Array.forEach() const finalCredDigits = [10, 8, 18, 9, 16, 6, 16, 5, 14, 3, 14, 6, 10, 5, 8];\n{\n const l = finalCredDigits.length;\n for (let i = 0; i < l; ++i) {\n if (finalCredDigits[i] > 9) finalCredDigits[i] -= 9;\n }\n}\n\nconsole.log(finalCredDigits.join());" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20409564/" ]
74,512,877
<p>I'm trying to upload a CSV file to google drive and I'm getting the error described in the subject of this post.</p> <p>this is my code:</p> <p>I think my error is in the content generation. I've seen some other posts but I can't resolve it yet.</p> <p>this is the code</p> <pre><code>public function uploadFileToDrive($token, $fileContent){ echo &quot;Iniciando subida de archivo a drive .... \n&quot;; try { $apiUrl = 'https://www.googleapis.com/'; $ch1 = curl_init(); /* MEtODO 1 */ $mime_type = 'text/csv'; $data = ' --section_divider Content-Type: application/json; charset=UTF-8 { &quot;name&quot;: &quot;test.xlsx&quot;, } --section_divider Content-Type: '.$mime_type.', '.$fileContent.' --section_divider-- '; //print_r($body);die(); curl_setopt($ch1, CURLOPT_URL, $apiUrl . 'upload/drive/v3/files?uploadType=multipart'); curl_setopt($ch1, CURLOPT_POST, 1); curl_setopt($ch1, CURLOPT_POSTFIELDS, $data); curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch1, CURLOPT_HTTPHEADER, array('Content-Type: multipart/related;section_divider', 'Authorization: Bearer' . $token) ); $response = curl_exec($ch1); if ($response === false) { echo 'Curl error: ' . curl_error($ch1); } else { echo &quot;Operation completed without any errors \n&quot;; $output = $response; } curl_close($ch1); var_dump($output);die(); return $output; } catch (Exception $e) { print &quot;An error occurred: &quot; . $e-&gt;getMessage(); } } </code></pre> <p>I don't know what I'm doing wrong</p> <p>I hope you can give some advice<br /> thanks</p> <p>The expected results. See the CSV file uploaded on google drive.</p> <p>See in the console a response indicating that all it's done</p>
[ { "answer_id": 74513046, "author": "Tanaike", "author_id": 7108653, "author_profile": "https://Stackoverflow.com/users/7108653", "pm_score": 3, "selected": true, "text": "$data Content-Type $data = '\n--section_divider\nContent-Type: application/json; charset=UTF-8\n{\n \"name\": \"test.xlsx\",\n}\n\n--section_divider\nContent-Type: '.$mime_type.',\n'.$fileContent.'\n--section_divider--\n';\n\n\n//print_r($body);die();\ncurl_setopt($ch1, CURLOPT_URL, $apiUrl . 'upload/drive/v3/files?uploadType=multipart');\ncurl_setopt($ch1, CURLOPT_POST, 1);\ncurl_setopt($ch1, CURLOPT_POSTFIELDS, $data);\ncurl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);\n\ncurl_setopt($ch1, CURLOPT_HTTPHEADER, array('Content-Type: multipart/related;section_divider', 'Authorization: Bearer' . $token) );\n $data = '\n--section_divider\nContent-Type: application/json; charset=UTF-8\n\n{\"name\": \"test.csv\", \"mimeType\": \"text/csv\"}\n\n--section_divider\nContent-Type: '.$mime_type.',\n\n'.$fileContent.'\n\n--section_divider--';\n\n//print_r($body);die();\ncurl_setopt($ch1, CURLOPT_URL, $apiUrl . 'upload/drive/v3/files?uploadType=multipart');\ncurl_setopt($ch1, CURLOPT_POST, 1);\ncurl_setopt($ch1, CURLOPT_POSTFIELDS, $data);\ncurl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);\n\ncurl_setopt($ch1, CURLOPT_HTTPHEADER, array('Content-Type: multipart/related;boundary=section_divider', 'Authorization: Bearer ' . $token) );\n {\n \"kind\": \"drive#file\",\n \"id\": \"###\",\n \"name\": \"test.csv\",\n \"mimeType\": \"text/csv\"\n }\n test.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet text/csv \"mimeType\": \"application/vnd.google-apps.spreadsheet\" \"mimeType\": \"text/csv\" 'Authorization: Bearer' . $token $token ya29.### 'Authorization: Bearer ' . $token 'Authorization: Bearer ' . $token multipart/related $data = implode([\n \"--section_divider\\r\\n\",\n \"Content-Type: application/json; charset=UTF-8\\r\\n\\r\\n\",\n \"{\\\"name\\\": \\\"test.csv\\\", \\\"mimeType\\\": \\\"text/csv\\\"}\\r\\n\\r\\n\",\n \"--section_divider\\r\\n\",\n \"Content-Type: \".$mime_type.\"\\r\\n\\r\\n\",\n $fileContent.\"\\r\\n\\r\\n\",\n \"--section_divider--\",\n], \"\");\n\n//print_r($body);die();\ncurl_setopt($ch1, CURLOPT_URL, $apiUrl . 'upload/drive/v3/files?uploadType=multipart');\ncurl_setopt($ch1, CURLOPT_POST, 1);\ncurl_setopt($ch1, CURLOPT_POSTFIELDS, $data);\ncurl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);\n\ncurl_setopt($ch1, CURLOPT_HTTPHEADER, array('Content-Type: multipart/related;boundary=section_divider', 'Authorization: Bearer ' . $token) );\n multipart/related { \"kind\": \"drive#file\", \"id\": \"1Qorzy6e5Vm_x2PU_lGdF066SI8c76DZy\", \"name\": \"test.csv\", \"mimeType\": \"text/csv\" } Invalid multipart request with 0 mime parts. BUT the big \"but\", the file isn't appears on google drive. BUT the big \"but\", the file isn't appears on google drive. \"{\\\"name\\\": \\\"test.csv\\\", \\\"mimeType\\\": \\\"text/csv\\\"}\\r\\n\\r\\n\",\n \"{\\\"name\\\": \\\"test.csv\\\", \\\"mimeType\\\": \\\"text/csv\\\", \\\"parents\\\": [\\\"###folderID###\\\"]}\\r\\n\\r\\n\",\n ###folderID###" }, { "answer_id": 74513699, "author": "Misunderstood", "author_id": 3813605, "author_profile": "https://Stackoverflow.com/users/3813605", "pm_score": 1, "selected": false, "text": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet key,value\nkey,value\nkey,value\n POST /<my curl test> HTTP/1.1\nHost: mycurltest.com\nAccept: */*\nContent-Type: multipart/related;section_divider\nAuthorization: Bearer 12345\nContent-Length: 294\n --section_divider\n Content-Type: application/json; charset=UTF-8\n {\n \"name\": \"test.xlsx\",\n }\n\n --section_divider\n Content-Type: text/csv,key,value\nkey,value\nkey,value\n --section_divider--\n \n 'Authorization: Bearer' . $token)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5158716/" ]
74,512,899
<p>I have a function defined e.g.</p> <pre><code>Public Function calc_x(ByVal x As Integer) ...do some stuff calc_x = x+x End Function </code></pre> <p>This function gets called within the excel sheet from a cell lets say (A2), with a &quot;pointer&quot; to A1 which contains a value 20:</p> <pre><code>content cell A1: &quot;20&quot; content cell A2: &quot;=calc_c(A1)&quot; </code></pre> <p>However, everytime I insert new rows or columns in excel (even after row A or after col 2) the function gets recalculated. Is there a way to prevent that?</p>
[ { "answer_id": 74513046, "author": "Tanaike", "author_id": 7108653, "author_profile": "https://Stackoverflow.com/users/7108653", "pm_score": 3, "selected": true, "text": "$data Content-Type $data = '\n--section_divider\nContent-Type: application/json; charset=UTF-8\n{\n \"name\": \"test.xlsx\",\n}\n\n--section_divider\nContent-Type: '.$mime_type.',\n'.$fileContent.'\n--section_divider--\n';\n\n\n//print_r($body);die();\ncurl_setopt($ch1, CURLOPT_URL, $apiUrl . 'upload/drive/v3/files?uploadType=multipart');\ncurl_setopt($ch1, CURLOPT_POST, 1);\ncurl_setopt($ch1, CURLOPT_POSTFIELDS, $data);\ncurl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);\n\ncurl_setopt($ch1, CURLOPT_HTTPHEADER, array('Content-Type: multipart/related;section_divider', 'Authorization: Bearer' . $token) );\n $data = '\n--section_divider\nContent-Type: application/json; charset=UTF-8\n\n{\"name\": \"test.csv\", \"mimeType\": \"text/csv\"}\n\n--section_divider\nContent-Type: '.$mime_type.',\n\n'.$fileContent.'\n\n--section_divider--';\n\n//print_r($body);die();\ncurl_setopt($ch1, CURLOPT_URL, $apiUrl . 'upload/drive/v3/files?uploadType=multipart');\ncurl_setopt($ch1, CURLOPT_POST, 1);\ncurl_setopt($ch1, CURLOPT_POSTFIELDS, $data);\ncurl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);\n\ncurl_setopt($ch1, CURLOPT_HTTPHEADER, array('Content-Type: multipart/related;boundary=section_divider', 'Authorization: Bearer ' . $token) );\n {\n \"kind\": \"drive#file\",\n \"id\": \"###\",\n \"name\": \"test.csv\",\n \"mimeType\": \"text/csv\"\n }\n test.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet text/csv \"mimeType\": \"application/vnd.google-apps.spreadsheet\" \"mimeType\": \"text/csv\" 'Authorization: Bearer' . $token $token ya29.### 'Authorization: Bearer ' . $token 'Authorization: Bearer ' . $token multipart/related $data = implode([\n \"--section_divider\\r\\n\",\n \"Content-Type: application/json; charset=UTF-8\\r\\n\\r\\n\",\n \"{\\\"name\\\": \\\"test.csv\\\", \\\"mimeType\\\": \\\"text/csv\\\"}\\r\\n\\r\\n\",\n \"--section_divider\\r\\n\",\n \"Content-Type: \".$mime_type.\"\\r\\n\\r\\n\",\n $fileContent.\"\\r\\n\\r\\n\",\n \"--section_divider--\",\n], \"\");\n\n//print_r($body);die();\ncurl_setopt($ch1, CURLOPT_URL, $apiUrl . 'upload/drive/v3/files?uploadType=multipart');\ncurl_setopt($ch1, CURLOPT_POST, 1);\ncurl_setopt($ch1, CURLOPT_POSTFIELDS, $data);\ncurl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);\n\ncurl_setopt($ch1, CURLOPT_HTTPHEADER, array('Content-Type: multipart/related;boundary=section_divider', 'Authorization: Bearer ' . $token) );\n multipart/related { \"kind\": \"drive#file\", \"id\": \"1Qorzy6e5Vm_x2PU_lGdF066SI8c76DZy\", \"name\": \"test.csv\", \"mimeType\": \"text/csv\" } Invalid multipart request with 0 mime parts. BUT the big \"but\", the file isn't appears on google drive. BUT the big \"but\", the file isn't appears on google drive. \"{\\\"name\\\": \\\"test.csv\\\", \\\"mimeType\\\": \\\"text/csv\\\"}\\r\\n\\r\\n\",\n \"{\\\"name\\\": \\\"test.csv\\\", \\\"mimeType\\\": \\\"text/csv\\\", \\\"parents\\\": [\\\"###folderID###\\\"]}\\r\\n\\r\\n\",\n ###folderID###" }, { "answer_id": 74513699, "author": "Misunderstood", "author_id": 3813605, "author_profile": "https://Stackoverflow.com/users/3813605", "pm_score": 1, "selected": false, "text": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet key,value\nkey,value\nkey,value\n POST /<my curl test> HTTP/1.1\nHost: mycurltest.com\nAccept: */*\nContent-Type: multipart/related;section_divider\nAuthorization: Bearer 12345\nContent-Length: 294\n --section_divider\n Content-Type: application/json; charset=UTF-8\n {\n \"name\": \"test.xlsx\",\n }\n\n --section_divider\n Content-Type: text/csv,key,value\nkey,value\nkey,value\n --section_divider--\n \n 'Authorization: Bearer' . $token)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20558245/" ]
74,512,904
<p>Are there any tricks that could get me from table 1 to table 2. I don't see a solution at this time. Is it doable?</p> <p><a href="https://i.stack.imgur.com/7tJO7.png" rel="nofollow noreferrer">table 1</a></p> <p><a href="https://i.stack.imgur.com/z1SYK.png" rel="nofollow noreferrer">table 2</a></p> <p>Thank you</p> <p>I tried transpose and pivot but it doesn't help.</p>
[ { "answer_id": 74513776, "author": "Ping", "author_id": 20288037, "author_profile": "https://Stackoverflow.com/users/20288037", "pm_score": 0, "selected": false, "text": "\"Class A name\" \"Class B name\" \"Class A name\" \"Class B name\" \"Class B name\" =LAMBDA(SOURCE,A,B,HEADERS,\n LAMBDA(NAME,TYPE,NR,\n LAMBDA(INDEXA,INDEXB,INDEXE,\n LAMBDA(DATAA,DATAB,\n {HEADERS;DATAA;DATAB}\n )(FILTER(SOURCE,ROW(NAME)>INDEXA,ROW(NAME)<INDEXB),\n FILTER(SOURCE,ROW(NAME)>INDEXB,ROW(NAME)<INDEXE))\n )(XMATCH(A,NAME),XMATCH(B,NAME),COUNTA(NAME)+1)\n )(INDEX(SOURCE,,1),INDEX(SOURCE,,2),INDEX(SOURCE,,3))\n)(A1:C7,\"Class A name\",\"Class B name\",{\"Class name\",\"Group name\",\"Nr students group\"})\n" }, { "answer_id": 74514121, "author": "Martín", "author_id": 20363318, "author_profile": "https://Stackoverflow.com/users/20363318", "pm_score": 2, "selected": true, "text": "=query({BYROW(B1:B,lambda(each,if(each=\"\",\"\",XLOOKUP(\"class\",INDIRECT(\"b1:b\"&ROW(each)),INDIRECT(\"a1:a\"&ROW(each)),,,-1)))),A1:C},\"Select Col1,Col3,Col4 where not Col3 contains 'Class' AND Col2 is not null label Col1 'Class Name'\",1)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3182345/" ]
74,512,926
<p>I would like to find character after <code>|</code> and check in a loop in C#.</p> <p>Like I have <code>Test|T1</code>. After pipe the character could be anything like <code>Test|T2</code> or <code>Test|T3</code>.</p> <p>The first value is <code>Table|Y</code> and second value could be <code>Test|T1</code>, <code>Test|T2</code> or <code>Test|T3</code>.</p> <p>So I would like to check the character after <code>|</code> in else block.</p> <pre><code> foreach (var testing in TestQuestion.Split(',')) { if(testing.Equals(&quot;Table|Y&quot;)) { order.OrderProperties.Add(new OrderProperty(&quot;A&quot;) { ... }); } else { //check the value after &quot;|&quot; } } </code></pre> <p>So I would like to check the character after <code>|</code> in else block.</p>
[ { "answer_id": 74512991, "author": "Gambi", "author_id": 14766188, "author_profile": "https://Stackoverflow.com/users/14766188", "pm_score": 1, "selected": false, "text": "if (testing.Split('|')[0] == \"Test\" && testing.Split('|')[1] == \"T1\")\n{\n \n}\n" }, { "answer_id": 74513060, "author": "Charles Han", "author_id": 11514907, "author_profile": "https://Stackoverflow.com/users/11514907", "pm_score": 2, "selected": false, "text": "var tokens = test.Split('|');\n\nif (tokens.FirstOrDefault() == \"Test\" && tokens.LastOrDefault() == \"T1\")\n{\n\n}\n" }, { "answer_id": 74513127, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": 3, "selected": true, "text": "var s = \"XXX|T1234\";\nvar idx = s.IndexOf(\"|\");\nif (idx > -1) // found\n{\n var nextChar = s.Substring(idx + 1, 1);\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20505175/" ]
74,512,941
<p>I want to convert the given array</p> <pre><code>arr = ['abc', 'def', 'hij']; </code></pre> <p>into this object:</p> <pre><code>result = { 'key': 'abc', 'key': 'def', 'key': 'hij' } </code></pre> <p>----EDIT----</p> <p>I want this structure because there is no way around other than this to pass this as queryParams in my project</p>
[ { "answer_id": 74512986, "author": "symlink", "author_id": 818326, "author_profile": "https://Stackoverflow.com/users/818326", "pm_score": 2, "selected": false, "text": "const arr = ['abc', 'def', 'hij'];\n\nconst result = arr.map(str => Object.create({key: str}));\nconsole.log(result);" }, { "answer_id": 74513564, "author": "Ping", "author_id": 20288037, "author_profile": "https://Stackoverflow.com/users/20288037", "pm_score": 2, "selected": false, "text": "const arr = ['abc', 'def', 'hij'];\nconst obj = {};\nobj.key = arr;\n\nconsole.log(JSON.stringify(obj));\n\n// output: {\"key\":[\"abc\",\"def\",\"hij\"]}" }, { "answer_id": 74513809, "author": "Unmitigated", "author_id": 9513184, "author_profile": "https://Stackoverflow.com/users/9513184", "pm_score": 1, "selected": false, "text": "URLSearchParams let arr = ['abc', 'def', 'hij'];\nconst params = new URLSearchParams;\nfor (const x of arr) params.append('key', x);\nconsole.log(params.toString());" }, { "answer_id": 74513821, "author": "Samathingamajig", "author_id": 12101554, "author_profile": "https://Stackoverflow.com/users/12101554", "pm_score": 1, "selected": false, "text": "URLSearchParams const arr = ['abc', 'def', 'hij'];\nconst key = \"key\";\n\nconst urlSearchParams = new URLSearchParams();\nfor (const val of arr) {\n urlSearchParams.append(key, val);\n}\n\n\nconsole.log(urlSearchParams.toString());\nconsole.log([...urlSearchParams.entries()]);" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74512941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12466554/" ]
74,512,975
<p>I want to create a large array of random numbers drawn from the gaussian distribution. I found <a href="https://netlib.org/lapack/explore-html/df/dd1/group___o_t_h_e_rauxiliary_ga77e05a87ced667cbdb502aa87c72d056.html#ga77e05a87ced667cbdb502aa87c72d056" rel="nofollow noreferrer">dlarnv</a>, but I am not sure how to use it in Swift. Specifically, the type signature XCode shows is as follows:</p> <pre class="lang-swift prettyprint-override"><code>dlarnv_( __idist: UnsafeMutablePointer&lt;__CLPK_integer&gt;, __iseed: UnsafeMutablePointer&lt;__CLPK_integer&gt;, __n: UnsafeMutablePointer&lt;__CLPK_integer&gt;, __x: UnsafeMutablePointer&lt;__CLPK_doublereal&gt; ) </code></pre> <p>How do I use this to fill an array with <strong>single</strong> precision floating point numbers? This is how far I have gotten:</p> <pre class="lang-swift prettyprint-override"><code>n = 10000 var data: [Float] data.reserveCapacity(n) data dlarnv_( 3, // for normal distribution seed, // not sure how to seed n, data, // not sure how to pass a pointer ) </code></pre>
[ { "answer_id": 74513559, "author": "Priyatham", "author_id": 2542516, "author_profile": "https://Stackoverflow.com/users/2542516", "pm_score": 0, "selected": false, "text": "dlarnv_ GameplayKit var n: Int32 = 500 // Array size\nvar d: Int32 = 3 // 3 for Normal(0, 1)\nvar seed: [Int32] = [1, 1, 1, 1] \\\\ Ideally pick a random seed\nvar x: [Double] = Array<Double>(unsafeUninitializedCapacity: Int(n)) { buffer, count in\n dlarnv_(&d, &seed, &n, buffer.baseAddress)\n count = Int(n)\n}\n" }, { "answer_id": 74513806, "author": "Rob Napier", "author_id": 97337, "author_profile": "https://Stackoverflow.com/users/97337", "pm_score": 2, "selected": false, "text": "dlarnv_ dlarnv_ import GameplayKit\nlet random = GKLinearCongruentialRandomSource()\n\nfunc randomNormalValue(average: Double, standardDeviation: Double) -> Double {\n let x1 = Double(random.nextUniform())\n let x2 = Double(random.nextUniform())\n let z1 = sqrt(-2 * log(x1)) * cos(2 * .pi * x2)\n\n return z1 * standardDeviation + average\n}\n dlarnv_ let random = GKRandomSource()\n dlarnv_" }, { "answer_id": 74516570, "author": "Flex Monkey", "author_id": 351826, "author_profile": "https://Stackoverflow.com/users/351826", "pm_score": 1, "selected": false, "text": "func randomFloats(n: Int,\n mean: Float,\n standardDeviation: Float) -> [Float] {\n \n let result = [Float](unsafeUninitializedCapacity: n) {\n \n buffer, unsafeUninitializedCapacity in\n \n guard\n var arrayDescriptor = BNNSNDArrayDescriptor(\n data: buffer,\n shape: .vector(n)),\n let randomNumberGenerator = BNNSCreateRandomGenerator(\n BNNSRandomGeneratorMethodAES_CTR,\n nil) else {\n fatalError()\n }\n \n BNNSRandomFillNormalFloat(\n randomNumberGenerator,\n &arrayDescriptor,\n mean,\n standardDeviation)\n \n unsafeUninitializedCapacity = n\n BNNSDestroyRandomGenerator(randomNumberGenerator)\n }\n return result\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74512975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2542516/" ]
74,512,987
<p>I'm trying to create a modal window that can be closed by clicking on either ouside the modal window itself or by clicking on a close button</p> <pre><code>const onCloseHandler = (e) =&gt; { e.stopPropagation(); setIsModalOpen(false); }; return ( &lt;div className=&quot;overlay&quot; onClick={onCloseHandler}&gt; &lt;div className=&quot;modal-window&quot;&gt; &lt;div type=&quot;button&quot; className=&quot;close-button&quot; onClick={onCloseHandler}&gt; &lt;CloseIcon /&gt; &lt;/div&gt; &lt;img src={image} alt=&quot;task&quot; className=&quot;modal-image&quot; /&gt; &lt;/div&gt; &lt;/div&gt; ); </code></pre> <p>The problem is <code>preventDefault</code> does not work so the modal window closes even if I click on an image or div with <code>modal-window</code> class.</p> <p>I tried to use</p> <pre><code>const onCloseHandler = (e) =&gt; { if (e.target !== e.currentTarget) { return; } setIsModalOpen(false); }; </code></pre> <p>And it works but it does not seem like a good solution. And also it does not close the modal window when click on a CloseIcon. It is just an svg inside so it's not possible to use <code>pointer-events: none</code> on it.</p>
[ { "answer_id": 74513054, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 1, "selected": true, "text": "modal-window overlay modal-window overlay overlay modal-window modal-window overlay <>\n<div className=\"overlay\" onClick=\"{onCloseHandler}\"></div>\n\n<div className=\"modal-window\">\n <div type=\"button\" className=\"close-button\" onClick=\"{onCloseHandler}\">\n <CloseIcon />\n </div>\n <img src=\"{image}\" alt=\"task\" className=\"modal-image\" />\n</div>\n</>\n e.target const onCloseHandler = (e) => {\n if (e.target.className === \"modal-window\") return;\n setIsModalOpen(false);\n};\n" }, { "answer_id": 74513166, "author": "dwjohnston", "author_id": 1068446, "author_profile": "https://Stackoverflow.com/users/1068446", "pm_score": 1, "selected": false, "text": "stopPropagation modal-window modal-window overlay modal-window overlay overlay modal-window `overlay` -> Close the modal \n`modal-window` -> stopPropagation, do nothing. \n`close-button` -> Close the modal, allow propagation (propagation will stop at `modal-window`) \n\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74512987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20395932/" ]
74,513,017
<pre><code>class DR(nn.Module): def __init__(self, orginal, latent_dims): super(DR, self).__init__() self.latent_dims=latent_dims self.linear1 = nn.Linear(orginal, 1000) self.linear2 = nn.Linear(1000, 2000) self.linear3 = nn.Linear(2000, latent_dims) def forward(self, x): x = F.relu(self.linear1(x)) x = F.relu(self.linear2(x)) x = F.relu(self.linear3(x)) return x </code></pre> <p>In this DR class, i don't want to update linear1, and linear2 in the traning time. That means, the layer should be same as it initialized, I only want to update linear3 in the traning time. How can i do this ?</p> <p>I expect a solution of this proeblem. Thank you</p>
[ { "answer_id": 74513054, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 1, "selected": true, "text": "modal-window overlay modal-window overlay overlay modal-window modal-window overlay <>\n<div className=\"overlay\" onClick=\"{onCloseHandler}\"></div>\n\n<div className=\"modal-window\">\n <div type=\"button\" className=\"close-button\" onClick=\"{onCloseHandler}\">\n <CloseIcon />\n </div>\n <img src=\"{image}\" alt=\"task\" className=\"modal-image\" />\n</div>\n</>\n e.target const onCloseHandler = (e) => {\n if (e.target.className === \"modal-window\") return;\n setIsModalOpen(false);\n};\n" }, { "answer_id": 74513166, "author": "dwjohnston", "author_id": 1068446, "author_profile": "https://Stackoverflow.com/users/1068446", "pm_score": 1, "selected": false, "text": "stopPropagation modal-window modal-window overlay modal-window overlay overlay modal-window `overlay` -> Close the modal \n`modal-window` -> stopPropagation, do nothing. \n`close-button` -> Close the modal, allow propagation (propagation will stop at `modal-window`) \n\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20487645/" ]
74,513,018
<p>I have a large MySQL table and when it had a low number of records the searches were fast, however the table now has over 400,000 records and searches take less than a second between 0.60 and 0.75. I've tried using indexes to bring this down to a nearer the 0.10 second or at least lower than 0.60 with no success. This estimate was from using <code>microtime</code> in PHP immediately before and after the SQL query.</p> <p>This is a snippet of the table structure output from <code>SHOW CREATE TABLE</code>, there are other fields in the table but these aren't used in the SQL search statement.</p> <pre><code>CREATE TABLE `mytable` ( `id` int(11) NOT NULL AUTO_INCREMENT, `url` longtext COLLATE utf8_unicode_ci NOT NULL, `url_sha512hash` char(128) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'no hash.', `viewdate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), UNIQUE KEY `uniq-web_url` (`url_sha512hash`), KEY `idx-viewdate` (`viewdate`) ) ENGINE=MyISAM AUTO_INCREMENT=404899 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci </code></pre> <p>This is the SQL statement which takes between 60 and 75 seconds that I would like to speed up.</p> <pre><code>SELECT `id`, `url` FROM `mytable` USE INDEX(`idx-viewdate`) WHERE (`url` LIKE &quot;https://www.domain.tld/path/to/dir&quot; AND `viewdate` &gt; &quot;2022-11-20 23:23:00&quot;) OR (`url` LIKE &quot;https://www.domain.tld/path/to/dir/&quot; AND `viewdate` &gt; &quot;INSERT SAME VIEW DATE AS BEFORE&quot;) ORDER BY `id` DESC; </code></pre> <p>Output from <code>EXPLAIN</code></p> <pre><code>+------+-------------+---------+-------+---------------+--------------+---------+------+------+----------------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +------+-------------+---------+-------+---------------+--------------+---------+------+------+----------------------------------------------------+ | 1 | SIMPLE | mytable | range | idx-viewdate | idx-viewdate | 4 | NULL | 28 | Using index condition; Using where; Using filesort | +------+-------------+---------+-------+---------------+--------------+---------+------+------+----------------------------------------------------+ </code></pre>
[ { "answer_id": 74513123, "author": "MatBailie", "author_id": 53341, "author_profile": "https://Stackoverflow.com/users/53341", "pm_score": 0, "selected": false, "text": "url, viewdate, id WHERE WHERE\n viewdate > ?\n AND url IN (?, CONCAT(?,'/'))\n LIKE IN() = ALTER TABLE `mysql` ADD INDEX `idx-visited2` (`url_sha512hash`, `viewdate`, `id`)\n WHERE\n viewdate > DATE\n AND url_sha512hash IN (HASHED_URL, HASHED_URL_WITH_SLASH)\n" }, { "answer_id": 74515901, "author": "nnichols", "author_id": 1191247, "author_profile": "https://Stackoverflow.com/users/1191247", "pm_score": 1, "selected": false, "text": "SELECT VERSION();\nANALYZE TABLE `mytable`;\nSHOW INDEX FROM `mytable`;\nSHOW TABLE STATUS LIKE 'mytable';\nSHOW VARIABLES LIKE 'innodb_buffer_pool_size';\n SELECT\n COUNT(*) countAll,\n COUNT(IF(LENGTH(url) <= 32, 1, NULL)) count32,\n COUNT(DISTINCT LEFT(url, 32)) distinct32,\n COUNT(IF(LENGTH(url) <= 48, 1, NULL)) count48,\n COUNT(DISTINCT LEFT(url, 48)) distinct48,\n COUNT(IF(LENGTH(url) <= 64, 1, NULL)) count64,\n COUNT(DISTINCT LEFT(url, 64)) distinct64,\n COUNT(IF(LENGTH(url) <= 80, 1, NULL)) count80,\n COUNT(DISTINCT LEFT(url, 80)) distinct80,\n COUNT(IF(LENGTH(url) <= 96, 1, NULL)) count96,\n COUNT(DISTINCT LEFT(url, 96)) distinct96\nFROM mytable;\n ALTER TABLE `mytable` \n CHANGE COLUMN `url` `url` VARCHAR(300) NOT NULL,\n ADD INDEX `idx_url_viewed` (`url`(64), `viewdate`);\n # Add the binary column\nALTER TABLE `mytable`\n CHANGE COLUMN `url` `url` VARCHAR(300) NOT NULL,\n ADD COLUMN `url_bin_hash` BINARY(64);\n\n# Populate it\nUPDATE `mytable` SET `url_bin_hash` = UNHEX(`url_sha512hash`);\n\n# Drop the old column, change the new one to NOT NULL, and add index\nALTER TABLE `mytable`\n DROP COLUMN `url_sha512hash`,\n CHANGE COLUMN `url_bin_hash` `url_bin_hash` BINARY(64) NOT NULL,\n ADD UNIQUE KEY `uq_url_bin_hash` (`url_bin_hash`);\n INSERT INTO `mytable` (`url`, `url_bin_hash`, `viewdate`)\n VALUES ('url', UNHEX(SHA2('url', 512)), NOW());\n SELECT `id`, `url`\nFROM `mytable`\nWHERE `viewdate` > ?\nAND `url_bin_hash` IN (UNHEX(SHA2(?, 512)), UNHEX(SHA2(CONCAT(?, '/'), 512)))\nORDER BY `id` DESC;\n id mytable" }, { "answer_id": 74523407, "author": "Rick James", "author_id": 1766831, "author_profile": "https://Stackoverflow.com/users/1766831", "pm_score": 2, "selected": false, "text": "id ORDER BY id ORDER BY viewdate OR UNION url REGEXP LIKE OR WHERE URL LIKE 'blah%'\n AND URL REGEXP 'blah/?'\n id SELECT url, view_date\n FROM mytable\n WHERE view_date > '2022...'\n AND URL LIKE 'blah%'\n AND URL REGEXP 'blah/?'\n ORDER BY view_date DESC\n PRIMARY KEY(url_sha512hash)\nINDEX(view_date, URL(191))\n ( SELECT id, url, view_date\n FROM mytable\n WHERE view_date > '2022...'\n AND url_sha512hash = sha256('blah') -- w/0 slash\n) UNION ALL\n) SELECT id, url, view_date\n FROM mytable\n WHERE view_date > '2022...'\n AND url_sha512hash = sha256('blah/') -- with slash\n)\nORDER BY view_date DESC\n PRIMARY KEY(url_sha512hash, view_date)\n INSERTing SELECTing SELECT id, url, view_date\n FROM mytable\n WHERE view_date > '2022...'\n AND url_sha512hash = sha256('blah')\nORDER BY view_date DESC\n PRIMARY KEY(url_sha512hash, view_date)\n id INDEX(id) -- to keep `AUTO_INCREMENT` happy.\n BINARY(nn) UNHEX" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/997934/" ]
74,513,025
<p>at the moment I am struggling to figure out this problem. I am attempting to make a textbox set the background of the website. Here is my code:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; Enter URL: &lt;input type=&quot;text&quot; id=&quot;myText&quot;&gt; &lt;button onclick=&quot;myFunction()&quot;&gt;Set Wallpaper&lt;/button&gt; &lt;script&gt; function myFunction() { var x = document.getElementById(&quot;myText&quot;).value; document.body.style.background = x; } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 74513050, "author": "OwnageIsMagic", "author_id": 5647513, "author_profile": "https://Stackoverflow.com/users/5647513", "pm_score": 2, "selected": false, "text": "background green red document.body.style.background = 'green';\n let img_url = 'path_to.jpg';\ndocument.body.style.background = `url(${img_url})`;\n" }, { "answer_id": 74513055, "author": "chrislacorunna", "author_id": 7268329, "author_profile": "https://Stackoverflow.com/users/7268329", "pm_score": -1, "selected": false, "text": "function myFunction() {\n var x = document.getElementById(\"myText\").value;\n document.body.style = 'background-image: url(${x});';\n}\n\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19971880/" ]
74,513,029
<p>How do I convert a number to Text in Excel based on what the number is.</p> <p>For eg, I have the following logic to be implemented:</p> <pre><code>pob &gt; 1 ? &quot;Strong Buy&quot; : pob &gt; 0 ? &quot;Buy&quot; : pob &lt; -1 ? &quot;Strong Sell&quot; : pob &lt; 0 ? &quot;Sell&quot; : &quot;Neutral&quot; </code></pre> <p>Column A has values 0, 1, 2, -1 In Column B, I have to replace these numbers with the following words.</p> <pre><code>0 = Neutral 1 = Buy 2 = Strong Buy -1 = Sell -2 = Strong Sell </code></pre> <p>How do I do this in Excel?</p>
[ { "answer_id": 74513497, "author": "Harun24hr", "author_id": 5514747, "author_profile": "https://Stackoverflow.com/users/5514747", "pm_score": 3, "selected": true, "text": "XLOOKUP() =XLOOKUP(A1,{-2,-1,0,1,2},{\"Strong Sell\",\"Sell\",\"Neutral\",\"Buy\",\"Strong Buy\"},\"\",-1)\n" }, { "answer_id": 74513635, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 0, "selected": false, "text": "B1 =LET(set, A1:A14, CONV, LAMBDA(x, SWITCH(x, -2, \"Strong Sell\",-1, \"Sell\", \n 0, \"Neutral\", 1, \"Buy\",2, \"Strong Buy\", \"CASE NOT DEFINED\")),\n MAP(set, LAMBDA(x, CONV(x))))\n SWITCH LAMBDA CONV MAP CASE NOT DEFINED LET" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1089173/" ]
74,513,036
<p>I am developing a python script that will run as a azure app function. It should read a parquet file from our gen1 datalake and do some processing over it. When running in debug mode in VS Code it works perfectly but when I deploy the script to the app function it retrieve a error with a not very meaninfull message.</p> <p>Executed 'Functions.get_warehouse_from_sap' (Failed, Id=227a48b8-0486-4c3f-8758-1f6298afaf68, Duration=9122ms)</p> <p>This happens when it tries to read the parquet file. I tried to use pyarrow and pandas.read_parquet function but both give the same error. I tried to put a try/execept around this particular point of the code but any excepetion is retrieved. To read the datalake I am using AzureDLFileSystem from azure.datalake.store.core python libray. Here is part of my code.</p> <pre><code> from azure.datalake.store import lib from azure.datalake.store.core import AzureDLFileSystem import pandas as pd adlCreds = lib.auth(tenant_id=tenant_id, client_id=client_id, client_secret=secret_key, resource = 'https://datalake.azure.net/') adlsFileSystemClient = AzureDLFileSystem(adlCreds, store_name='&lt;repository name&gt;') f=adlsFileSystemClient.ls('&lt;path to my file&gt;') #until here it works fine. It can open the file #here is where the problem happens. try: df=pd.read_parquet(f) except Exception as e: logging.info(str(e)) </code></pre> <p>Any idea? Thanks</p>
[ { "answer_id": 74513497, "author": "Harun24hr", "author_id": 5514747, "author_profile": "https://Stackoverflow.com/users/5514747", "pm_score": 3, "selected": true, "text": "XLOOKUP() =XLOOKUP(A1,{-2,-1,0,1,2},{\"Strong Sell\",\"Sell\",\"Neutral\",\"Buy\",\"Strong Buy\"},\"\",-1)\n" }, { "answer_id": 74513635, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 0, "selected": false, "text": "B1 =LET(set, A1:A14, CONV, LAMBDA(x, SWITCH(x, -2, \"Strong Sell\",-1, \"Sell\", \n 0, \"Neutral\", 1, \"Buy\",2, \"Strong Buy\", \"CASE NOT DEFINED\")),\n MAP(set, LAMBDA(x, CONV(x))))\n SWITCH LAMBDA CONV MAP CASE NOT DEFINED LET" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4802101/" ]
74,513,079
<p>I've created a Notification Bot in VS Code using the Teams Toolkit template (Teams Toolkit v4.1.2).</p> <p>The Bot runs fine locally and I'm able to trigger it by sending a <code>HTTP Post</code> request from Postman.</p> <p>It deploys fine to Azure, but when I call it from Postman (using the url from the Azure App Service), I get a <code>401 Unauthorized</code> response.</p> <p>I've followed the <a href="https://learn.microsoft.com/en-us/azure/bot-service/bot-service-troubleshoot-authentication-problems?view=azure-bot-service-4.0&amp;tabs=csharp" rel="nofollow noreferrer">Troubleshooting Bot Framework authentication</a> guide to generate an access token from my bot's App Id &amp; App Password using the following command:</p> <p><code>curl -k -X POST https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token -d &quot;grant_type=client_credentials&amp;client_id=APP_ID&amp;client_secret=APP_PASSWORD&amp;scope=https%3A%2F%2Fapi.botframework.com%2F.default&quot; </code></p> <p>This generates an access token, but when I add that to the header of my Postman request I get a <code>403 Forbidden</code> response.</p> <p>How do I trigger my bot in Azure from an HTTP Post request?</p>
[ { "answer_id": 74515873, "author": "Qianhao Dong", "author_id": 8646368, "author_profile": "https://Stackoverflow.com/users/8646368", "pm_score": 2, "selected": true, "text": "401 Unauthorized" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4707807/" ]
74,513,097
<p>Hello I have a project which uses react, typescript, and webpack. Previously I had some errors which caused the code to not compile but now when it is fixed, webpack does serve the HTML file on localhost:8000 but nothing else, so no CSS, or any scripts, here is my webpack.config if you think the issue might be somewhere else just ask and I will make an update thank you.</p> <p><a href="https://i.stack.imgur.com/2qM4v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2qM4v.png" alt="enter image description here" /></a></p> <pre class="lang-js prettyprint-override"><code>const path = require(&quot;path&quot;); module.exports = { entry: &quot;./src/index.tsx&quot;, mode: &quot;development&quot;, module: { rules: [ { test: /\.css$/, exclude: /(node_modules)/, use: [{ loader: &quot;style-loader&quot; }, { loader: &quot;css-loader&quot; }], }, { test: /\.json$/, use: &quot;json-loader&quot;, }, { test: /\.(ts)x?$|\.d\.ts$/, exclude: /node_modules|\.d\.ts$/, use: { loader: &quot;ts-loader&quot;, }, }, ], }, devServer: { static: { directory: path.join(__dirname, &quot;public&quot;), }, compress: true, port: 8080, }, resolve: { extensions: [&quot;.tsx&quot;, &quot;.ts&quot;, &quot;.js&quot;], modules: [&quot;src&quot;, &quot;node_modules&quot;], fallback: { fs: false, tls: false, net: false, path: require.resolve(&quot;path-browserify&quot;), zlib: false, http: false, https: false, stream: false, crypto: false, }, }, experiments: { topLevelAwait: true, }, output: { path: `${__dirname}/build`, filename: &quot;bundle.js&quot; }, }; </code></pre>
[ { "answer_id": 74515873, "author": "Qianhao Dong", "author_id": 8646368, "author_profile": "https://Stackoverflow.com/users/8646368", "pm_score": 2, "selected": true, "text": "401 Unauthorized" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17286169/" ]
74,513,104
<p>How do I write open(SCRPT, &quot;&gt;$script&quot;) or die...; in python?? Im trying to run a script in python to automate a slurm job. For that, I am trying to create and open a file names SCRPT and write a block of code to be read and executed.</p> <p>Is it SCRPT = open(script) with open(SCRPT)</p>
[ { "answer_id": 74513319, "author": "Pi Marillion", "author_id": 2892254, "author_profile": "https://Stackoverflow.com/users/2892254", "pm_score": 1, "selected": false, "text": "with ... as open script = '/path/to/some/script.sh'\nwith open(script, 'w') as file:\n file.write(\n '#!/bin/bash\\n'\n 'echo hello world\\n'\n )\nos.chmod(script, 0o755) # optional\n os.chmod" }, { "answer_id": 74513601, "author": "mob", "author_id": 168657, "author_profile": "https://Stackoverflow.com/users/168657", "pm_score": 2, "selected": false, "text": "open open IOError open(SCRIPT,\">$script\") or die $error_message import sys\ntry:\n script = open(\"script\", \"w\")\nexcept IOError as ioe:\n print(error_message, file=sys.stderr)\n sys.exit(1)\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20558422/" ]
74,513,184
<p>Im trying to learn scheme and Im having trouble with the arithmetic in the Scheme syntax.</p> <p>Would anyone be able to write out a function in Scheme that represents the Geometric Series?</p>
[ { "answer_id": 74513439, "author": "Sylwester", "author_id": 1565698, "author_profile": "https://Stackoverflow.com/users/1565698", "pm_score": 2, "selected": false, "text": "expt (expt 2 8) ; ==> 256 * (* 2 3) ; ==> 6 n expt expt (define (range from to)\n (let loop ((n to) (acc '())\n (if (< n from)\n acc\n (loop (- 1 n) (cons n acc)))))\n\n(range 3 10) ; ==> (3 4 5 6 7 8 9 10)\n (reverse acc)" }, { "answer_id": 74517949, "author": "ignis volens", "author_id": 17026934, "author_profile": "https://Stackoverflow.com/users/17026934", "pm_score": 0, "selected": false, "text": "(define/contract (geometric-series x n)\n ;; Return a list of x^k for k from 0 to n (inclusive).\n ;; This will be questionable if x is not exact.\n (-> number? natural-number/c (listof number?))\n (let gsl ((m n)\n (c (expt x n))\n (a '()))\n (if (zero? m)\n (cons 1 a)\n (gsl (- m 1)\n (/ c x)\n (cons c a)))))\n" }, { "answer_id": 74525460, "author": "Gwang-Jin Kim", "author_id": 9690090, "author_profile": "https://Stackoverflow.com/users/9690090", "pm_score": 1, "selected": false, "text": "range (define (range from (below '()) (step 1) (acc '()))\n (cond ((null? below) (range 0 from step))\n ((> (+ from step) below) (reverse acc))\n (else (range (+ from step) below step (cons from acc)))))\n from below (define (range from below (step 1) (acc '()))\n (cond ((> (+ from step) below) (reverse acc))\n (else (range (+ from step) below step (cons from acc)))))\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20005085/" ]
74,513,188
<pre><code>df = pd.DataFrame({ &quot;Continent&quot;: list(&quot;AAABBBCCD&quot;), &quot;Country&quot;: list(&quot;FGHIJKLMN&quot;), &quot;Population&quot;: [90, 140, 50, 80, 80, 70, 50, 125, 50]}) </code></pre> <p>As explained, I want to return all of the rows, where all countries in each continent are less than 100.</p> <pre><code> Continent Country Population 0 A F 90 1 A G 140 2 A H 50 3 B I 80 4 B J 80 5 B K 70 6 C L 50 7 C M 125 8 D N 50 </code></pre> <p>Every row in Continent A is removed because Country G has a population greater than 100. Every row in Continent C is removed because of Country M. I want the returned DataFrame to look like below:</p> <pre><code> Continent Country Population 3 B I 80 4 B J 80 5 B K 70 8 D N 50 </code></pre> <p>I tried <code>df[df[&quot;Population&quot;] &lt;= 100]</code> but couldn't determine how to adjust for Continent.</p>
[ { "answer_id": 74513439, "author": "Sylwester", "author_id": 1565698, "author_profile": "https://Stackoverflow.com/users/1565698", "pm_score": 2, "selected": false, "text": "expt (expt 2 8) ; ==> 256 * (* 2 3) ; ==> 6 n expt expt (define (range from to)\n (let loop ((n to) (acc '())\n (if (< n from)\n acc\n (loop (- 1 n) (cons n acc)))))\n\n(range 3 10) ; ==> (3 4 5 6 7 8 9 10)\n (reverse acc)" }, { "answer_id": 74517949, "author": "ignis volens", "author_id": 17026934, "author_profile": "https://Stackoverflow.com/users/17026934", "pm_score": 0, "selected": false, "text": "(define/contract (geometric-series x n)\n ;; Return a list of x^k for k from 0 to n (inclusive).\n ;; This will be questionable if x is not exact.\n (-> number? natural-number/c (listof number?))\n (let gsl ((m n)\n (c (expt x n))\n (a '()))\n (if (zero? m)\n (cons 1 a)\n (gsl (- m 1)\n (/ c x)\n (cons c a)))))\n" }, { "answer_id": 74525460, "author": "Gwang-Jin Kim", "author_id": 9690090, "author_profile": "https://Stackoverflow.com/users/9690090", "pm_score": 1, "selected": false, "text": "range (define (range from (below '()) (step 1) (acc '()))\n (cond ((null? below) (range 0 from step))\n ((> (+ from step) below) (reverse acc))\n (else (range (+ from step) below step (cons from acc)))))\n from below (define (range from below (step 1) (acc '()))\n (cond ((> (+ from step) below) (reverse acc))\n (else (range (+ from step) below step (cons from acc)))))\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20126844/" ]
74,513,237
<p>Trying to perform a fairly simple gzip command across my fastq files, but a strange error returns.</p> <pre><code>#!/usr/bin/env nextflow nextflow.enable.dsl=2 params.gzip = &quot;sequences/sequences_split/sequences_trimmed/trimmed*fastq&quot; workflow { gzip_ch = Channel.fromPath(params.gzip) GZIP(gzip_ch) GZIP.out.view() } process GZIP { input: path read output: stdout script: &quot;&quot;&quot; gzip ${read} &quot;&quot;&quot; } </code></pre> <p>Error:</p> <pre><code>Command error: gzip: trimmed_SRR19573319_R2.fastq: Too many levels of symbolic links </code></pre> <p>Tried running a loop in the script instead or run gzip on individual files which works, but would rather use the nextflow syntax.</p>
[ { "answer_id": 74513439, "author": "Sylwester", "author_id": 1565698, "author_profile": "https://Stackoverflow.com/users/1565698", "pm_score": 2, "selected": false, "text": "expt (expt 2 8) ; ==> 256 * (* 2 3) ; ==> 6 n expt expt (define (range from to)\n (let loop ((n to) (acc '())\n (if (< n from)\n acc\n (loop (- 1 n) (cons n acc)))))\n\n(range 3 10) ; ==> (3 4 5 6 7 8 9 10)\n (reverse acc)" }, { "answer_id": 74517949, "author": "ignis volens", "author_id": 17026934, "author_profile": "https://Stackoverflow.com/users/17026934", "pm_score": 0, "selected": false, "text": "(define/contract (geometric-series x n)\n ;; Return a list of x^k for k from 0 to n (inclusive).\n ;; This will be questionable if x is not exact.\n (-> number? natural-number/c (listof number?))\n (let gsl ((m n)\n (c (expt x n))\n (a '()))\n (if (zero? m)\n (cons 1 a)\n (gsl (- m 1)\n (/ c x)\n (cons c a)))))\n" }, { "answer_id": 74525460, "author": "Gwang-Jin Kim", "author_id": 9690090, "author_profile": "https://Stackoverflow.com/users/9690090", "pm_score": 1, "selected": false, "text": "range (define (range from (below '()) (step 1) (acc '()))\n (cond ((null? below) (range 0 from step))\n ((> (+ from step) below) (reverse acc))\n (else (range (+ from step) below step (cons from acc)))))\n from below (define (range from below (step 1) (acc '()))\n (cond ((> (+ from step) below) (reverse acc))\n (else (range (+ from step) below step (cons from acc)))))\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19926037/" ]
74,513,251
<p>I am looking for a way to display an image when the link is posted on Twitter, Discord, etc.</p> <p>There is a spot for the text but I am not aware of a place for an image.</p> <p>I am expecting an image to display like this:</p> <hr /> <p><img src="https://cdn.discordapp.com/attachments/1036663369400324108/1044060206168018964/image.png" alt="Twitter Preview #1" /></p> <h2>This is what I am getting:</h2> <p><img src="https://i.stack.imgur.com/uEUOW.png" alt="Twitter Preview #2" /></p> <p>The description text was changed in <code>config.yml</code> so is there a parameter for the image there also?</p> <p>I am unaware of how to make the link preview image appear. Think it might be in the <code>config.yml</code> file.</p>
[ { "answer_id": 74513439, "author": "Sylwester", "author_id": 1565698, "author_profile": "https://Stackoverflow.com/users/1565698", "pm_score": 2, "selected": false, "text": "expt (expt 2 8) ; ==> 256 * (* 2 3) ; ==> 6 n expt expt (define (range from to)\n (let loop ((n to) (acc '())\n (if (< n from)\n acc\n (loop (- 1 n) (cons n acc)))))\n\n(range 3 10) ; ==> (3 4 5 6 7 8 9 10)\n (reverse acc)" }, { "answer_id": 74517949, "author": "ignis volens", "author_id": 17026934, "author_profile": "https://Stackoverflow.com/users/17026934", "pm_score": 0, "selected": false, "text": "(define/contract (geometric-series x n)\n ;; Return a list of x^k for k from 0 to n (inclusive).\n ;; This will be questionable if x is not exact.\n (-> number? natural-number/c (listof number?))\n (let gsl ((m n)\n (c (expt x n))\n (a '()))\n (if (zero? m)\n (cons 1 a)\n (gsl (- m 1)\n (/ c x)\n (cons c a)))))\n" }, { "answer_id": 74525460, "author": "Gwang-Jin Kim", "author_id": 9690090, "author_profile": "https://Stackoverflow.com/users/9690090", "pm_score": 1, "selected": false, "text": "range (define (range from (below '()) (step 1) (acc '()))\n (cond ((null? below) (range 0 from step))\n ((> (+ from step) below) (reverse acc))\n (else (range (+ from step) below step (cons from acc)))))\n from below (define (range from below (step 1) (acc '()))\n (cond ((> (+ from step) below) (reverse acc))\n (else (range (+ from step) below step (cons from acc)))))\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20044815/" ]
74,513,270
<p>I am new to react and I am trying to pass props from a parent function to a child. The parameters I am passing &quot;square_state&quot; and &quot;setSquare_state&quot; are not being recognized in the useSquare or handle_square_click function. I am using the following <a href="https://designcode.io/react-hooks-handbook-props" rel="nofollow noreferrer">https://designcode.io/react-hooks-handbook-props</a> as a reference.</p> <pre><code> const handle_square_click = (props) =&gt; { props.setSquare_state(player) setGetplayer(true) } const useSquare = (square_state, setSquare_state) =&gt; { // Hook for square state management and rendering return ( &lt;button className=&quot;square&quot; onClick={&lt;handle_square_click setSquare_state={setSquare_state}/&gt; }&gt; {square_state} &lt;/button&gt; ); } // ------------------------------------------------------------------ // Board Function const Board = ({player}) =&gt; { let status = &quot;Next Player : &quot; + player const [square1_state, setSquare1_state] = useState(1); return ( &lt;div&gt; &lt;div className=&quot;status&quot;&gt;{status}&lt;/div&gt; &lt;div className=&quot;board-row&quot;&gt; &lt;useSquare square_state={square1_state} setSquare_state={setSquare1_state} /&gt; </code></pre>
[ { "answer_id": 74513367, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 1, "selected": false, "text": "use use Square square_state={square1_state}\n setSquare_state={setSquare1_state}\n handle_square_click const useSquare = (square_state, setSquare_state) => {\n const Square = ({ squareState, setSquareState }) => {\n handle_square_click onClick={<handle_square_click onClick player setGetplayer const Board = ({ player }) => {\n const [squareState, setSquareState] = useState(1);\n return (\n <div>\n <div className=\"status\">{status}</div>\n <div className=\"board-row\">\n <Square\n squareState={squareState}\n setSquareState={setSquareState}\n player={player}\n />\n const Square = ({ squareState, setSquareState, player }) => {\n const handleSquareClick = () => {\n setSquareState(player);\n // setGetplayer(true);\n };\n return (\n <button className=\"square\" onClick={handleSquareClick}>\n {squareState}\n </button>\n );\n};\n" }, { "answer_id": 74513387, "author": "user18821127", "author_id": 18821127, "author_profile": "https://Stackoverflow.com/users/18821127", "pm_score": 0, "selected": false, "text": " <useSquare\n square_state={square1_state}\n setSquare_state={setSquare1_state}\n />\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19394369/" ]
74,513,281
<p>I am making a minesweeper program in C.</p> <p>I have this as a global variable:</p> <pre class="lang-c prettyprint-override"><code>typedef struct box_t { int box_type; int num_mines_bordering; int is_flagged; } box_t; // my global box_t * gameboard = NULL; </code></pre> <p>Later in the application it is allocated in the heap based on the number of rows and columns:</p> <pre class="lang-c prettyprint-override"><code> gameboard = (box_t *)malloc((rows * cols) * sizeof(box_t)); </code></pre> <p>All is well, however, they way I index it now seems incorrect and error-prone. I can't simply do <code> gameboard[x][y]</code> because I get compiler errors and what I have now seems incorrect:</p> <pre class="lang-c prettyprint-override"><code>#define GET_LOC(ROW, COL) gameboard[(ROW * sizeof(box_t)) + (COL * sizeof(box_t)) * sizeof(box_t)] // if you call this it would look like: box_t * loc = &amp;GET_LOC(somerow, somecol); </code></pre> <p>Is there a better way to index it?</p>
[ { "answer_id": 74513318, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 3, "selected": true, "text": "cols box_t *gameboard = malloc((rows * cols) * sizeof(*gameboard));\ngameboard[row * cols + col] = ...;\n" }, { "answer_id": 74520064, "author": "tstanisl", "author_id": 4989451, "author_profile": "https://Stackoverflow.com/users/4989451", "pm_score": 1, "selected": false, "text": "void* void* gameboard_glob = NULL;\nint gameboard_rows, gameboard_cols;\n\nvoid allocate(int rows, int cols) {\n gameboard_rows = rows;\n gameboard_cols = cols;\n gameboard_glob = malloc(sizeof(box_t[rows][cols]);\n}\n\nvoid foo(void) {\n box_t (*gameboard)[gameboard_cols] = gameboard_glob;\n\n .. do stuff with `gameboard[r][c]`\n}\n box_t (*gameboard)[cols] = calloc(rows, sizeof *gameboard);\n\n... initialize with gameboard[r][c]\n\ngamebard_glob = gameboard;\n free(gamebard_glob) malloc calloc realloc" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18673273/" ]
74,513,309
<p>I'm writing a code to enter subjects' information where I put void function and array as an object. But not sure when I wanna loop it, it doesn't come until the end. Have a look at the code.</p> <pre><code>void calculateCGPA::getGPA() { cout &lt;&lt; &quot;Enter the the name of the subject: &quot;; cin &gt;&gt; subjectName; cout &lt;&lt; &quot;Enter the credit hour:&quot;; cin &gt;&gt; credithour; cout &lt;&lt; &quot;Enter the grade: &quot;; cin &gt;&gt; grade; } int main () { for (year=1; year&lt;=4; year++) { for (sem=1; sem&lt;=2; sem++) { cout &lt;&lt; &quot;Enter total subject you take in Year &quot; &lt;&lt; year &lt;&lt; &quot; Semester &quot; &lt;&lt; sem &lt;&lt;&quot;: &quot;; cin &gt;&gt; totalSubjectSem; calculateCGPA ob[totalSubjectSem]; for(int i = 1; i &lt;= totalSubjectSem; i++) { cout &lt;&lt; &quot;Subject &quot; &lt;&lt; i &lt;&lt; &quot;: \n&quot;; ob[i].getGPA(); } } } return 0; } </code></pre> <p><img src="https://i.stack.imgur.com/Y3c8B.png" alt="enter image description here" /></p> <p>Here's the error. You can see the compiler only shows until entering the subject name but credit hour and grade are omitted. What should I do?</p> <p>Expected: It should everything in void function until 3 (since I put 3) and then start over again &quot;Enter total subject you take in Year 1 sem 2&quot; but it also omits that</p>
[ { "answer_id": 74513353, "author": "Wang Zerui", "author_id": 16232205, "author_profile": "https://Stackoverflow.com/users/16232205", "pm_score": 3, "selected": true, "text": "void calculateCGPA::getGPA() {\n cout << \"Enter the the name of the subject: \";\n cin >> subjectName;\n cout << \"Enter the credit hour:\";\n cin >> credithour;\n cout << \"Enter the grade: \";\n cin >> grade;\n}\n\nint main () {\n for (year=0; year<4; year++) {\n for (sem=0; sem<2; sem++) {\n cout << \"Enter total subject you take in Year \" << year << \" Semester \" << sem <<\": \";\n cin >> totalSubjectSem;\n calculateCGPA ob[totalSubjectSem];\n for(int i = 0; i < totalSubjectSem; i++) {\n cout << \"Subject \" << i << \": \\n\";\n ob[i].getGPA();\n }\n }\n }\n}\n" }, { "answer_id": 74513354, "author": "OwnageIsMagic", "author_id": 5647513, "author_profile": "https://Stackoverflow.com/users/5647513", "pm_score": 1, "selected": false, "text": "totalSubjectSem const std::vector<calculateCGPA> array_length - 1" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,513,361
<p>How can I find out the amount of susceptible, infected and recovered individuals in time = 50, where S(50), I(50), R(50)? (SIR MODEL)</p> <pre><code># Equações diferenciais e suas condições iniciais h = 0.05 beta = 0.8 nu = 0.3125 def derivada_S(time,I,S): return -beta*I*S def derivada_I(time,I,S): return beta*I*S - nu*I def derivada_R(time,I): return nu*I S0 = 0.99 I0 = 0.01 R0 = 0.0 time_0 = 0.0 time_k = 100 data = 1000 </code></pre> <pre><code># vetor representativo do tempo time = np.linspace(time_0,time_k,data) S = np.zeros(data) I = np.zeros(data) R = np.zeros(data) S[0] = S0 I[0] = I0 R[0] = R0 for i in range(data-1): S_k1 = derivada_S(time[i], I[i], S[i]) S_k2 = derivada_S(time[i] + (1/2)*h, I[i], S[i] + h + (1/2)*S_k1) S_k3 = derivada_S(time[i] + (1/2)*h, I[i], S[i] + h + (1/2)*S_k2) S_k4 = derivada_S(time[i] + h, I[i], S[i] + h + S_k3) S[i+1] = S[i] + (h/6)*(S_k1 + 2*S_k2 + 2*S_k3 + S_k4) I_k1 = derivada_I(time[i], I[i], S[i]) I_k2 = derivada_I(time[i] + (1/2)*h, I[i], S[i] + h + (1/2)*I_k1) I_k3 = derivada_I(time[i] + (1/2)*h, I[i], S[i] + h + (1/2)*I_k2) I_k4 = derivada_I(time[i] + h, I[i], S[i] + h + I_k3) I[i+1] = I[i] + (h/6)*(I_k1 + 2*I_k2 + 2*I_k3 + I_k4) R_k1 = derivada_R(time[i], I[i]) R_k2 = derivada_R(time[i] + (1/2)*h, I[i]) R_k3 = derivada_R(time[i] + (1/2)*h, I[i]) R_k4 = derivada_R(time[i] + h, I[i]) R[i+1] = R[i] + (h/6)*(R_k1 + 2*R_k2 + 2*R_k3 + R_k4) </code></pre> <pre><code>plt.figure(figsize=(8,6)) plt.plot(time,S, label = 'S') plt.plot(time,I, label = 'I') plt.plot(time,R, label = 'R') plt.xlabel('tempo (t)') plt.ylabel('Susceptível, Infectado e Recuperado') plt.grid() plt.legend() plt.show() </code></pre> <p>I'm solving an university problem with python applying Runge-Kutta's fourth order, but a I don't know how to collect the data for time = 50.</p>
[ { "answer_id": 74513822, "author": "Nindi", "author_id": 20505208, "author_profile": "https://Stackoverflow.com/users/20505208", "pm_score": 2, "selected": false, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nBeta = 1.00205\nGamma = 0.23000\nN = 1000\n\ndef func_S(t,I,S):\n return - Beta*I*S/N\n\ndef func_I(t,I,S):\n return Beta*I*S/N - Gamma*I\n\ndef func_R(t,I):\n return Gamma*I\n\n\n# physical parameters\nI0 = 1\nR0 = 0\nS0 = N - I0 - R0\nt0 = 0\ntn = 50\n\n\n\n# Numerical Parameters\nndata = 1000\n\n\n\nt = np.linspace(t0,tn,ndata)\nh = t[2] - t[1]\n\nS = np.zeros(ndata)\nI = np.zeros(ndata)\nR = np.zeros(ndata)\n\nS[0] = S0\nI[0] = I0\nR[0] = R0\n\n\nfor i in range(ndata-1):\n k1 = func_S(t[i], I[i], S[i])\n k2 = func_S(t[i]+0.5*h, I[i], S[i]+h+0.5*k1)\n k3 = func_S(t[i]+0.5*h, I[i], S[i]+h+0.5*k2)\n k4 = func_S(t[i]+h, I[i], S[i]+h+k3)\n \n S[i+1] = S[i] + (h/6)*(k1 + 2*k2 + 2*k3 + k4)\n \n kk1 = func_I(t[i], I[i], S[i])\n kk2 = func_I(t[i]+0.5*h, I[i], S[i]+h+0.5*kk1)\n kk3 = func_I(t[i]+0.5*h, I[i], S[i]+h+0.5*kk2)\n kk4 = func_I(t[i]+h, I[i], S[i]+h+kk3)\n \n I[i+1] = I[i] + (h/6)*(kk1 + 2*kk2 + 2*kk3 + kk4)\n \n l1 = func_R(t[i], I[i])\n l2 = func_R(t[i]+0.5*h, I[i])\n l3 = func_R(t[i]+0.5*h, I[i])\n l4 = func_R(t[i]+h, I[i])\n \n R[i+1] = R[i] + (h/6)*(l1 + 2*l2 + 2*l3 + l4)\n \n \nplt.figure(1)\nplt.plot(t,S)\nplt.plot(t,I)\nplt.plot(t,R)\nplt.show()\n" }, { "answer_id": 74514912, "author": "Lutz Lehmann", "author_id": 3088138, "author_profile": "https://Stackoverflow.com/users/3088138", "pm_score": 1, "selected": true, "text": "time = np.linspace(0,days,10*days+1)\n linspace(a,b,N) N (b-a)/(N-1) S_k2 = derivada_S(time[i] + (h/2), I[i] + (h/2)*I_k1, S[i] + (h/2)*S_k1)\n I_k1 h S_k1 for i in range(data-1):\n S_k1 = derivada_S(time[i], I[i], S[i])\n I_k1 = derivada_I(time[i], I[i], S[i])\n R_k1 = derivada_R(time[i], I[i])\n\n S_k2 = derivada_S(time[i] + (1/2)*h, I[i] + (h/2)*I_k1, S[i] + (h/2)*S_k1)\n I_k2 = derivada_I(time[i] + (1/2)*h, I[i] + (h/2)*I_k1, S[i] + (h/2)*S_k1)\n R_k2 = derivada_R(time[i] + (1/2)*h, I[i] + (h/2)*I_k1)\n\n S_k3 = derivada_S(time[i] + (h/2), I[i] + (h/2)*I_k2, S[i] + (h/2)*S_k2)\n I_k3 = derivada_I(time[i] + (h/2), I[i] + (h/2)*I_k2, S[i] + (h/2)*S_k2)\n R_k3 = derivada_R(time[i] + (h/2), I[i] + (h/2)*I_k2)\n\n S_k4 = derivada_S(time[i] + h, I[i] + I_k3, S[i] + S_k3)\n I_k4 = derivada_I(time[i] + h, I[i] + I_k3, S[i] + S_k3)\n R_k4 = derivada_R(time[i] + h, I[i] + I_k3)\n \n S[i+1] = S[i] + (h/6)*(S_k1 + 2*S_k2 + 2*S_k3 + S_k4)\n I[i+1] = I[i] + (h/6)*(I_k1 + 2*I_k2 + 2*I_k3 + I_k4)\n R[i+1] = R[i] + (h/6)*(R_k1 + 2*R_k2 + 2*R_k3 + R_k4)\n h I_k1, S_k1 0.05 t=50 x 2 data = 10*time_k+1 S[-1]=0.10483, I[-1]=8.11098e-05, R[-1]=0.89509\n h=t[1]-t[0] t=50 i=500" }, { "answer_id": 74646998, "author": "Carllos Limma", "author_id": 20080193, "author_profile": "https://Stackoverflow.com/users/20080193", "pm_score": 0, "selected": false, "text": "##########################################\n# AUTHOR : CARLOS DUARDO DA SILVA LIMA #\n# DATE : 12/01/2022 #\n# LANGUAGE: python #\n# IDE : GOOGLE COLAB #\n# PROBLEM : MODEL SIR #\n##########################################\n\nimport numpy as np\nfrom scipy.integrate import odeint, solve_ivp, RK45\nimport matplotlib.pyplot as plt\n\nt_i = 0.0 # START TIME\nt_f = 50.0 # FINAL TIME\nN = 1000\n\n#t = np.linspace(t_i,t_f,N)\nt_span = np.array([t_i,t_f])\n\n# INITIAL CONDITIONS OF THE SOR MODEL\nS0 = 0.99\nI0 = 0.01\nR0 = 0.0\nr0 = np.array([S0,I0,R0])\n\n# ORDINARY DIFFERENTIAL EQUATIONS OF THE SIR MODEL\ndef SIR(t,y,b,k):\n s,i,r = y\n ode1 = -b*s*i\n ode2 = b*s*i-k*i\n ode3 = k*i\n return np.array([ode1,ode2,ode3])\n\n# INTEGRATION OF ORDINARY DIFFERENTIAL EQUATIONS (FOURTH ORDER RUNGE-KUTTA, RADAU)\n#sol_solve_ivp = solve_ivp(SIR,t_span,y0 = r0,method='Radau', rtol=1E-09, atol=1e-09, args = (0.8,0.3125))\nsol_solve_ivp = solve_ivp(SIR,t_span,y0 = r0,method='RK45', rtol=1E-09, atol=1e-09, args = (0.8,0.3125))\n\n# T, S, I, R FUNCTIONS\nt_= sol_solve_ivp.t\ns = sol_solve_ivp.y[0, :]\ni = sol_solve_ivp.y[1, :]\nr = sol_solve_ivp.y[2, :]\n\n# GRAPHIC\nplt.figure(1)\nplt.style.use('dark_background')\nplt.figure(figsize = (8,8))\nplt.plot(t_,s,'c-',t_,i,'g-',t_,r,'y-',lw=1.5)\n#plt.title(r'$\\frac{dS(t)}{dt} = -bs(t)i(t)$, $\\frac{dI(t)}{dt} = bs(t)i(t)-ki(t)$ and $\\frac{dR(t)}{dt} = ki(t)$')\nplt.title(r'SIR Model', color = 'm')\nplt.xlabel(r'$t(t)$', color = 'm')\nplt.ylabel(r'$S(t)$, $I(t)$ and $R(t)$', color = 'm')\nplt.legend(['S', 'I', 'R'], shadow=True)\nplt.grid(lw = 0.95,color = 'white',linestyle = '--')\nplt.show()\n\n''' SEARCH WEBSITES\nhttps://en.wikipedia.org/wiki/Compartmental_models_in_epidemiology\nhttps://www.maa.org/press/periodicals/loci/joma/the-sir-model-for-spread-of-disease-the-differential-equation-model\n'''\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18180897/" ]
74,513,362
<p>I've made a spreadsheet that is essentially a world cup prediction league.</p> <p>5 points are awarded for a correct score 2 points are awarded for a correct outcome</p> <p>The calculation sheet works as follows:</p> <p><a href="https://i.stack.imgur.com/vMy7c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vMy7c.png" alt="enter image description here" /></a></p> <p>In the score column, a football emoji is displayed if the results match. It uses this IF statement: =IF(AND(I4=I$2,J4=J$2),&quot;⚽&quot;,&quot;&quot;)</p> <p>In the outcome column, a tick emoji is displayed if the outcome is correct and a x if it's incorrect. It uses this IF statement: =IF(OR(AND(I$2&gt;J$2,I4&gt;J4),AND(I$2=J$2,I4=J4),AND(I$2&lt;J$2,I4&lt;J4)),&quot;✅&quot;,&quot;✖️&quot;)</p> <p>In the end column, either 0, 2, or 5 points are awarded.</p> <p>I wanted an easy way of inputting every player's predictions submitted via a google form, rather than having to type each prediction in manually.</p> <p>I duplicated the form responses sheet so that I could re-order the player data, so their results matched up to the calculations sheet.</p> <p><a href="https://i.stack.imgur.com/j4UpV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j4UpV.png" alt="enter image description here" /></a></p> <p>Each column is a separate fixture (eg - E2 England v Iran, F2 Senegal v Holland etc) The results have been submitted in each cell in the following format: 2-1</p> <p>So I used =LEFT(E2,1) to capture the first teams score and =RIGHT(E2,1) to capture the second teams score. This was so I could split the score into two values in order to apply the formulas.</p> <p>This worked, but the problem is that the football emoji doesn't appear if the score is correct, because the cell is referencing a formula rather than a value. This subsequently means that it doesn't award the player the correct number of points in the end column. (5)</p> <p>Is there a way to tweak it so that correct score column reads the value rather than the forumula thus displaying the football emoji?</p> <p>Help appreciated. Many thanks in advance!</p> <p>I tried copying and special pasting the cells so it just displayed the values, but this didn't work unfortunately.</p>
[ { "answer_id": 74513822, "author": "Nindi", "author_id": 20505208, "author_profile": "https://Stackoverflow.com/users/20505208", "pm_score": 2, "selected": false, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nBeta = 1.00205\nGamma = 0.23000\nN = 1000\n\ndef func_S(t,I,S):\n return - Beta*I*S/N\n\ndef func_I(t,I,S):\n return Beta*I*S/N - Gamma*I\n\ndef func_R(t,I):\n return Gamma*I\n\n\n# physical parameters\nI0 = 1\nR0 = 0\nS0 = N - I0 - R0\nt0 = 0\ntn = 50\n\n\n\n# Numerical Parameters\nndata = 1000\n\n\n\nt = np.linspace(t0,tn,ndata)\nh = t[2] - t[1]\n\nS = np.zeros(ndata)\nI = np.zeros(ndata)\nR = np.zeros(ndata)\n\nS[0] = S0\nI[0] = I0\nR[0] = R0\n\n\nfor i in range(ndata-1):\n k1 = func_S(t[i], I[i], S[i])\n k2 = func_S(t[i]+0.5*h, I[i], S[i]+h+0.5*k1)\n k3 = func_S(t[i]+0.5*h, I[i], S[i]+h+0.5*k2)\n k4 = func_S(t[i]+h, I[i], S[i]+h+k3)\n \n S[i+1] = S[i] + (h/6)*(k1 + 2*k2 + 2*k3 + k4)\n \n kk1 = func_I(t[i], I[i], S[i])\n kk2 = func_I(t[i]+0.5*h, I[i], S[i]+h+0.5*kk1)\n kk3 = func_I(t[i]+0.5*h, I[i], S[i]+h+0.5*kk2)\n kk4 = func_I(t[i]+h, I[i], S[i]+h+kk3)\n \n I[i+1] = I[i] + (h/6)*(kk1 + 2*kk2 + 2*kk3 + kk4)\n \n l1 = func_R(t[i], I[i])\n l2 = func_R(t[i]+0.5*h, I[i])\n l3 = func_R(t[i]+0.5*h, I[i])\n l4 = func_R(t[i]+h, I[i])\n \n R[i+1] = R[i] + (h/6)*(l1 + 2*l2 + 2*l3 + l4)\n \n \nplt.figure(1)\nplt.plot(t,S)\nplt.plot(t,I)\nplt.plot(t,R)\nplt.show()\n" }, { "answer_id": 74514912, "author": "Lutz Lehmann", "author_id": 3088138, "author_profile": "https://Stackoverflow.com/users/3088138", "pm_score": 1, "selected": true, "text": "time = np.linspace(0,days,10*days+1)\n linspace(a,b,N) N (b-a)/(N-1) S_k2 = derivada_S(time[i] + (h/2), I[i] + (h/2)*I_k1, S[i] + (h/2)*S_k1)\n I_k1 h S_k1 for i in range(data-1):\n S_k1 = derivada_S(time[i], I[i], S[i])\n I_k1 = derivada_I(time[i], I[i], S[i])\n R_k1 = derivada_R(time[i], I[i])\n\n S_k2 = derivada_S(time[i] + (1/2)*h, I[i] + (h/2)*I_k1, S[i] + (h/2)*S_k1)\n I_k2 = derivada_I(time[i] + (1/2)*h, I[i] + (h/2)*I_k1, S[i] + (h/2)*S_k1)\n R_k2 = derivada_R(time[i] + (1/2)*h, I[i] + (h/2)*I_k1)\n\n S_k3 = derivada_S(time[i] + (h/2), I[i] + (h/2)*I_k2, S[i] + (h/2)*S_k2)\n I_k3 = derivada_I(time[i] + (h/2), I[i] + (h/2)*I_k2, S[i] + (h/2)*S_k2)\n R_k3 = derivada_R(time[i] + (h/2), I[i] + (h/2)*I_k2)\n\n S_k4 = derivada_S(time[i] + h, I[i] + I_k3, S[i] + S_k3)\n I_k4 = derivada_I(time[i] + h, I[i] + I_k3, S[i] + S_k3)\n R_k4 = derivada_R(time[i] + h, I[i] + I_k3)\n \n S[i+1] = S[i] + (h/6)*(S_k1 + 2*S_k2 + 2*S_k3 + S_k4)\n I[i+1] = I[i] + (h/6)*(I_k1 + 2*I_k2 + 2*I_k3 + I_k4)\n R[i+1] = R[i] + (h/6)*(R_k1 + 2*R_k2 + 2*R_k3 + R_k4)\n h I_k1, S_k1 0.05 t=50 x 2 data = 10*time_k+1 S[-1]=0.10483, I[-1]=8.11098e-05, R[-1]=0.89509\n h=t[1]-t[0] t=50 i=500" }, { "answer_id": 74646998, "author": "Carllos Limma", "author_id": 20080193, "author_profile": "https://Stackoverflow.com/users/20080193", "pm_score": 0, "selected": false, "text": "##########################################\n# AUTHOR : CARLOS DUARDO DA SILVA LIMA #\n# DATE : 12/01/2022 #\n# LANGUAGE: python #\n# IDE : GOOGLE COLAB #\n# PROBLEM : MODEL SIR #\n##########################################\n\nimport numpy as np\nfrom scipy.integrate import odeint, solve_ivp, RK45\nimport matplotlib.pyplot as plt\n\nt_i = 0.0 # START TIME\nt_f = 50.0 # FINAL TIME\nN = 1000\n\n#t = np.linspace(t_i,t_f,N)\nt_span = np.array([t_i,t_f])\n\n# INITIAL CONDITIONS OF THE SOR MODEL\nS0 = 0.99\nI0 = 0.01\nR0 = 0.0\nr0 = np.array([S0,I0,R0])\n\n# ORDINARY DIFFERENTIAL EQUATIONS OF THE SIR MODEL\ndef SIR(t,y,b,k):\n s,i,r = y\n ode1 = -b*s*i\n ode2 = b*s*i-k*i\n ode3 = k*i\n return np.array([ode1,ode2,ode3])\n\n# INTEGRATION OF ORDINARY DIFFERENTIAL EQUATIONS (FOURTH ORDER RUNGE-KUTTA, RADAU)\n#sol_solve_ivp = solve_ivp(SIR,t_span,y0 = r0,method='Radau', rtol=1E-09, atol=1e-09, args = (0.8,0.3125))\nsol_solve_ivp = solve_ivp(SIR,t_span,y0 = r0,method='RK45', rtol=1E-09, atol=1e-09, args = (0.8,0.3125))\n\n# T, S, I, R FUNCTIONS\nt_= sol_solve_ivp.t\ns = sol_solve_ivp.y[0, :]\ni = sol_solve_ivp.y[1, :]\nr = sol_solve_ivp.y[2, :]\n\n# GRAPHIC\nplt.figure(1)\nplt.style.use('dark_background')\nplt.figure(figsize = (8,8))\nplt.plot(t_,s,'c-',t_,i,'g-',t_,r,'y-',lw=1.5)\n#plt.title(r'$\\frac{dS(t)}{dt} = -bs(t)i(t)$, $\\frac{dI(t)}{dt} = bs(t)i(t)-ki(t)$ and $\\frac{dR(t)}{dt} = ki(t)$')\nplt.title(r'SIR Model', color = 'm')\nplt.xlabel(r'$t(t)$', color = 'm')\nplt.ylabel(r'$S(t)$, $I(t)$ and $R(t)$', color = 'm')\nplt.legend(['S', 'I', 'R'], shadow=True)\nplt.grid(lw = 0.95,color = 'white',linestyle = '--')\nplt.show()\n\n''' SEARCH WEBSITES\nhttps://en.wikipedia.org/wiki/Compartmental_models_in_epidemiology\nhttps://www.maa.org/press/periodicals/loci/joma/the-sir-model-for-spread-of-disease-the-differential-equation-model\n'''\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20558529/" ]
74,513,394
<p>I'm trying to import a .csv file to MySQL using the table data import wizard, but I keep getting this error. Could someone explain what this means and how I would go about fixing it.</p>
[ { "answer_id": 74513822, "author": "Nindi", "author_id": 20505208, "author_profile": "https://Stackoverflow.com/users/20505208", "pm_score": 2, "selected": false, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nBeta = 1.00205\nGamma = 0.23000\nN = 1000\n\ndef func_S(t,I,S):\n return - Beta*I*S/N\n\ndef func_I(t,I,S):\n return Beta*I*S/N - Gamma*I\n\ndef func_R(t,I):\n return Gamma*I\n\n\n# physical parameters\nI0 = 1\nR0 = 0\nS0 = N - I0 - R0\nt0 = 0\ntn = 50\n\n\n\n# Numerical Parameters\nndata = 1000\n\n\n\nt = np.linspace(t0,tn,ndata)\nh = t[2] - t[1]\n\nS = np.zeros(ndata)\nI = np.zeros(ndata)\nR = np.zeros(ndata)\n\nS[0] = S0\nI[0] = I0\nR[0] = R0\n\n\nfor i in range(ndata-1):\n k1 = func_S(t[i], I[i], S[i])\n k2 = func_S(t[i]+0.5*h, I[i], S[i]+h+0.5*k1)\n k3 = func_S(t[i]+0.5*h, I[i], S[i]+h+0.5*k2)\n k4 = func_S(t[i]+h, I[i], S[i]+h+k3)\n \n S[i+1] = S[i] + (h/6)*(k1 + 2*k2 + 2*k3 + k4)\n \n kk1 = func_I(t[i], I[i], S[i])\n kk2 = func_I(t[i]+0.5*h, I[i], S[i]+h+0.5*kk1)\n kk3 = func_I(t[i]+0.5*h, I[i], S[i]+h+0.5*kk2)\n kk4 = func_I(t[i]+h, I[i], S[i]+h+kk3)\n \n I[i+1] = I[i] + (h/6)*(kk1 + 2*kk2 + 2*kk3 + kk4)\n \n l1 = func_R(t[i], I[i])\n l2 = func_R(t[i]+0.5*h, I[i])\n l3 = func_R(t[i]+0.5*h, I[i])\n l4 = func_R(t[i]+h, I[i])\n \n R[i+1] = R[i] + (h/6)*(l1 + 2*l2 + 2*l3 + l4)\n \n \nplt.figure(1)\nplt.plot(t,S)\nplt.plot(t,I)\nplt.plot(t,R)\nplt.show()\n" }, { "answer_id": 74514912, "author": "Lutz Lehmann", "author_id": 3088138, "author_profile": "https://Stackoverflow.com/users/3088138", "pm_score": 1, "selected": true, "text": "time = np.linspace(0,days,10*days+1)\n linspace(a,b,N) N (b-a)/(N-1) S_k2 = derivada_S(time[i] + (h/2), I[i] + (h/2)*I_k1, S[i] + (h/2)*S_k1)\n I_k1 h S_k1 for i in range(data-1):\n S_k1 = derivada_S(time[i], I[i], S[i])\n I_k1 = derivada_I(time[i], I[i], S[i])\n R_k1 = derivada_R(time[i], I[i])\n\n S_k2 = derivada_S(time[i] + (1/2)*h, I[i] + (h/2)*I_k1, S[i] + (h/2)*S_k1)\n I_k2 = derivada_I(time[i] + (1/2)*h, I[i] + (h/2)*I_k1, S[i] + (h/2)*S_k1)\n R_k2 = derivada_R(time[i] + (1/2)*h, I[i] + (h/2)*I_k1)\n\n S_k3 = derivada_S(time[i] + (h/2), I[i] + (h/2)*I_k2, S[i] + (h/2)*S_k2)\n I_k3 = derivada_I(time[i] + (h/2), I[i] + (h/2)*I_k2, S[i] + (h/2)*S_k2)\n R_k3 = derivada_R(time[i] + (h/2), I[i] + (h/2)*I_k2)\n\n S_k4 = derivada_S(time[i] + h, I[i] + I_k3, S[i] + S_k3)\n I_k4 = derivada_I(time[i] + h, I[i] + I_k3, S[i] + S_k3)\n R_k4 = derivada_R(time[i] + h, I[i] + I_k3)\n \n S[i+1] = S[i] + (h/6)*(S_k1 + 2*S_k2 + 2*S_k3 + S_k4)\n I[i+1] = I[i] + (h/6)*(I_k1 + 2*I_k2 + 2*I_k3 + I_k4)\n R[i+1] = R[i] + (h/6)*(R_k1 + 2*R_k2 + 2*R_k3 + R_k4)\n h I_k1, S_k1 0.05 t=50 x 2 data = 10*time_k+1 S[-1]=0.10483, I[-1]=8.11098e-05, R[-1]=0.89509\n h=t[1]-t[0] t=50 i=500" }, { "answer_id": 74646998, "author": "Carllos Limma", "author_id": 20080193, "author_profile": "https://Stackoverflow.com/users/20080193", "pm_score": 0, "selected": false, "text": "##########################################\n# AUTHOR : CARLOS DUARDO DA SILVA LIMA #\n# DATE : 12/01/2022 #\n# LANGUAGE: python #\n# IDE : GOOGLE COLAB #\n# PROBLEM : MODEL SIR #\n##########################################\n\nimport numpy as np\nfrom scipy.integrate import odeint, solve_ivp, RK45\nimport matplotlib.pyplot as plt\n\nt_i = 0.0 # START TIME\nt_f = 50.0 # FINAL TIME\nN = 1000\n\n#t = np.linspace(t_i,t_f,N)\nt_span = np.array([t_i,t_f])\n\n# INITIAL CONDITIONS OF THE SOR MODEL\nS0 = 0.99\nI0 = 0.01\nR0 = 0.0\nr0 = np.array([S0,I0,R0])\n\n# ORDINARY DIFFERENTIAL EQUATIONS OF THE SIR MODEL\ndef SIR(t,y,b,k):\n s,i,r = y\n ode1 = -b*s*i\n ode2 = b*s*i-k*i\n ode3 = k*i\n return np.array([ode1,ode2,ode3])\n\n# INTEGRATION OF ORDINARY DIFFERENTIAL EQUATIONS (FOURTH ORDER RUNGE-KUTTA, RADAU)\n#sol_solve_ivp = solve_ivp(SIR,t_span,y0 = r0,method='Radau', rtol=1E-09, atol=1e-09, args = (0.8,0.3125))\nsol_solve_ivp = solve_ivp(SIR,t_span,y0 = r0,method='RK45', rtol=1E-09, atol=1e-09, args = (0.8,0.3125))\n\n# T, S, I, R FUNCTIONS\nt_= sol_solve_ivp.t\ns = sol_solve_ivp.y[0, :]\ni = sol_solve_ivp.y[1, :]\nr = sol_solve_ivp.y[2, :]\n\n# GRAPHIC\nplt.figure(1)\nplt.style.use('dark_background')\nplt.figure(figsize = (8,8))\nplt.plot(t_,s,'c-',t_,i,'g-',t_,r,'y-',lw=1.5)\n#plt.title(r'$\\frac{dS(t)}{dt} = -bs(t)i(t)$, $\\frac{dI(t)}{dt} = bs(t)i(t)-ki(t)$ and $\\frac{dR(t)}{dt} = ki(t)$')\nplt.title(r'SIR Model', color = 'm')\nplt.xlabel(r'$t(t)$', color = 'm')\nplt.ylabel(r'$S(t)$, $I(t)$ and $R(t)$', color = 'm')\nplt.legend(['S', 'I', 'R'], shadow=True)\nplt.grid(lw = 0.95,color = 'white',linestyle = '--')\nplt.show()\n\n''' SEARCH WEBSITES\nhttps://en.wikipedia.org/wiki/Compartmental_models_in_epidemiology\nhttps://www.maa.org/press/periodicals/loci/joma/the-sir-model-for-spread-of-disease-the-differential-equation-model\n'''\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14281557/" ]
74,513,408
<p>I wish to be able to add projects in a subcollection called projects. Currently my tree is: db/membres/[membreID]/projects/(here I want project ID that firebase generates)/(information of project) Here is my firebase: <a href="https://i.stack.imgur.com/r96nY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r96nY.png" alt="enter image description here" /></a></p> <p>here's what i've tried: <a href="https://i.stack.imgur.com/viob9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/viob9.png" alt="enter image description here" /></a></p> <p>This is the error I get: Invalid document reference. Document references must have an even number of segments, but membres/UVLPL9kxP1hGuiwCStS4oDLJvxo1/projets has 3.</p>
[ { "answer_id": 74513822, "author": "Nindi", "author_id": 20505208, "author_profile": "https://Stackoverflow.com/users/20505208", "pm_score": 2, "selected": false, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nBeta = 1.00205\nGamma = 0.23000\nN = 1000\n\ndef func_S(t,I,S):\n return - Beta*I*S/N\n\ndef func_I(t,I,S):\n return Beta*I*S/N - Gamma*I\n\ndef func_R(t,I):\n return Gamma*I\n\n\n# physical parameters\nI0 = 1\nR0 = 0\nS0 = N - I0 - R0\nt0 = 0\ntn = 50\n\n\n\n# Numerical Parameters\nndata = 1000\n\n\n\nt = np.linspace(t0,tn,ndata)\nh = t[2] - t[1]\n\nS = np.zeros(ndata)\nI = np.zeros(ndata)\nR = np.zeros(ndata)\n\nS[0] = S0\nI[0] = I0\nR[0] = R0\n\n\nfor i in range(ndata-1):\n k1 = func_S(t[i], I[i], S[i])\n k2 = func_S(t[i]+0.5*h, I[i], S[i]+h+0.5*k1)\n k3 = func_S(t[i]+0.5*h, I[i], S[i]+h+0.5*k2)\n k4 = func_S(t[i]+h, I[i], S[i]+h+k3)\n \n S[i+1] = S[i] + (h/6)*(k1 + 2*k2 + 2*k3 + k4)\n \n kk1 = func_I(t[i], I[i], S[i])\n kk2 = func_I(t[i]+0.5*h, I[i], S[i]+h+0.5*kk1)\n kk3 = func_I(t[i]+0.5*h, I[i], S[i]+h+0.5*kk2)\n kk4 = func_I(t[i]+h, I[i], S[i]+h+kk3)\n \n I[i+1] = I[i] + (h/6)*(kk1 + 2*kk2 + 2*kk3 + kk4)\n \n l1 = func_R(t[i], I[i])\n l2 = func_R(t[i]+0.5*h, I[i])\n l3 = func_R(t[i]+0.5*h, I[i])\n l4 = func_R(t[i]+h, I[i])\n \n R[i+1] = R[i] + (h/6)*(l1 + 2*l2 + 2*l3 + l4)\n \n \nplt.figure(1)\nplt.plot(t,S)\nplt.plot(t,I)\nplt.plot(t,R)\nplt.show()\n" }, { "answer_id": 74514912, "author": "Lutz Lehmann", "author_id": 3088138, "author_profile": "https://Stackoverflow.com/users/3088138", "pm_score": 1, "selected": true, "text": "time = np.linspace(0,days,10*days+1)\n linspace(a,b,N) N (b-a)/(N-1) S_k2 = derivada_S(time[i] + (h/2), I[i] + (h/2)*I_k1, S[i] + (h/2)*S_k1)\n I_k1 h S_k1 for i in range(data-1):\n S_k1 = derivada_S(time[i], I[i], S[i])\n I_k1 = derivada_I(time[i], I[i], S[i])\n R_k1 = derivada_R(time[i], I[i])\n\n S_k2 = derivada_S(time[i] + (1/2)*h, I[i] + (h/2)*I_k1, S[i] + (h/2)*S_k1)\n I_k2 = derivada_I(time[i] + (1/2)*h, I[i] + (h/2)*I_k1, S[i] + (h/2)*S_k1)\n R_k2 = derivada_R(time[i] + (1/2)*h, I[i] + (h/2)*I_k1)\n\n S_k3 = derivada_S(time[i] + (h/2), I[i] + (h/2)*I_k2, S[i] + (h/2)*S_k2)\n I_k3 = derivada_I(time[i] + (h/2), I[i] + (h/2)*I_k2, S[i] + (h/2)*S_k2)\n R_k3 = derivada_R(time[i] + (h/2), I[i] + (h/2)*I_k2)\n\n S_k4 = derivada_S(time[i] + h, I[i] + I_k3, S[i] + S_k3)\n I_k4 = derivada_I(time[i] + h, I[i] + I_k3, S[i] + S_k3)\n R_k4 = derivada_R(time[i] + h, I[i] + I_k3)\n \n S[i+1] = S[i] + (h/6)*(S_k1 + 2*S_k2 + 2*S_k3 + S_k4)\n I[i+1] = I[i] + (h/6)*(I_k1 + 2*I_k2 + 2*I_k3 + I_k4)\n R[i+1] = R[i] + (h/6)*(R_k1 + 2*R_k2 + 2*R_k3 + R_k4)\n h I_k1, S_k1 0.05 t=50 x 2 data = 10*time_k+1 S[-1]=0.10483, I[-1]=8.11098e-05, R[-1]=0.89509\n h=t[1]-t[0] t=50 i=500" }, { "answer_id": 74646998, "author": "Carllos Limma", "author_id": 20080193, "author_profile": "https://Stackoverflow.com/users/20080193", "pm_score": 0, "selected": false, "text": "##########################################\n# AUTHOR : CARLOS DUARDO DA SILVA LIMA #\n# DATE : 12/01/2022 #\n# LANGUAGE: python #\n# IDE : GOOGLE COLAB #\n# PROBLEM : MODEL SIR #\n##########################################\n\nimport numpy as np\nfrom scipy.integrate import odeint, solve_ivp, RK45\nimport matplotlib.pyplot as plt\n\nt_i = 0.0 # START TIME\nt_f = 50.0 # FINAL TIME\nN = 1000\n\n#t = np.linspace(t_i,t_f,N)\nt_span = np.array([t_i,t_f])\n\n# INITIAL CONDITIONS OF THE SOR MODEL\nS0 = 0.99\nI0 = 0.01\nR0 = 0.0\nr0 = np.array([S0,I0,R0])\n\n# ORDINARY DIFFERENTIAL EQUATIONS OF THE SIR MODEL\ndef SIR(t,y,b,k):\n s,i,r = y\n ode1 = -b*s*i\n ode2 = b*s*i-k*i\n ode3 = k*i\n return np.array([ode1,ode2,ode3])\n\n# INTEGRATION OF ORDINARY DIFFERENTIAL EQUATIONS (FOURTH ORDER RUNGE-KUTTA, RADAU)\n#sol_solve_ivp = solve_ivp(SIR,t_span,y0 = r0,method='Radau', rtol=1E-09, atol=1e-09, args = (0.8,0.3125))\nsol_solve_ivp = solve_ivp(SIR,t_span,y0 = r0,method='RK45', rtol=1E-09, atol=1e-09, args = (0.8,0.3125))\n\n# T, S, I, R FUNCTIONS\nt_= sol_solve_ivp.t\ns = sol_solve_ivp.y[0, :]\ni = sol_solve_ivp.y[1, :]\nr = sol_solve_ivp.y[2, :]\n\n# GRAPHIC\nplt.figure(1)\nplt.style.use('dark_background')\nplt.figure(figsize = (8,8))\nplt.plot(t_,s,'c-',t_,i,'g-',t_,r,'y-',lw=1.5)\n#plt.title(r'$\\frac{dS(t)}{dt} = -bs(t)i(t)$, $\\frac{dI(t)}{dt} = bs(t)i(t)-ki(t)$ and $\\frac{dR(t)}{dt} = ki(t)$')\nplt.title(r'SIR Model', color = 'm')\nplt.xlabel(r'$t(t)$', color = 'm')\nplt.ylabel(r'$S(t)$, $I(t)$ and $R(t)$', color = 'm')\nplt.legend(['S', 'I', 'R'], shadow=True)\nplt.grid(lw = 0.95,color = 'white',linestyle = '--')\nplt.show()\n\n''' SEARCH WEBSITES\nhttps://en.wikipedia.org/wiki/Compartmental_models_in_epidemiology\nhttps://www.maa.org/press/periodicals/loci/joma/the-sir-model-for-spread-of-disease-the-differential-equation-model\n'''\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20495003/" ]
74,513,416
<p><a href="https://i.stack.imgur.com/HQR4F.jpg" rel="nofollow noreferrer">this is my problem and the photo of it</a></p> <p>i have no idea why it didn't work</p>
[ { "answer_id": 74513822, "author": "Nindi", "author_id": 20505208, "author_profile": "https://Stackoverflow.com/users/20505208", "pm_score": 2, "selected": false, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nBeta = 1.00205\nGamma = 0.23000\nN = 1000\n\ndef func_S(t,I,S):\n return - Beta*I*S/N\n\ndef func_I(t,I,S):\n return Beta*I*S/N - Gamma*I\n\ndef func_R(t,I):\n return Gamma*I\n\n\n# physical parameters\nI0 = 1\nR0 = 0\nS0 = N - I0 - R0\nt0 = 0\ntn = 50\n\n\n\n# Numerical Parameters\nndata = 1000\n\n\n\nt = np.linspace(t0,tn,ndata)\nh = t[2] - t[1]\n\nS = np.zeros(ndata)\nI = np.zeros(ndata)\nR = np.zeros(ndata)\n\nS[0] = S0\nI[0] = I0\nR[0] = R0\n\n\nfor i in range(ndata-1):\n k1 = func_S(t[i], I[i], S[i])\n k2 = func_S(t[i]+0.5*h, I[i], S[i]+h+0.5*k1)\n k3 = func_S(t[i]+0.5*h, I[i], S[i]+h+0.5*k2)\n k4 = func_S(t[i]+h, I[i], S[i]+h+k3)\n \n S[i+1] = S[i] + (h/6)*(k1 + 2*k2 + 2*k3 + k4)\n \n kk1 = func_I(t[i], I[i], S[i])\n kk2 = func_I(t[i]+0.5*h, I[i], S[i]+h+0.5*kk1)\n kk3 = func_I(t[i]+0.5*h, I[i], S[i]+h+0.5*kk2)\n kk4 = func_I(t[i]+h, I[i], S[i]+h+kk3)\n \n I[i+1] = I[i] + (h/6)*(kk1 + 2*kk2 + 2*kk3 + kk4)\n \n l1 = func_R(t[i], I[i])\n l2 = func_R(t[i]+0.5*h, I[i])\n l3 = func_R(t[i]+0.5*h, I[i])\n l4 = func_R(t[i]+h, I[i])\n \n R[i+1] = R[i] + (h/6)*(l1 + 2*l2 + 2*l3 + l4)\n \n \nplt.figure(1)\nplt.plot(t,S)\nplt.plot(t,I)\nplt.plot(t,R)\nplt.show()\n" }, { "answer_id": 74514912, "author": "Lutz Lehmann", "author_id": 3088138, "author_profile": "https://Stackoverflow.com/users/3088138", "pm_score": 1, "selected": true, "text": "time = np.linspace(0,days,10*days+1)\n linspace(a,b,N) N (b-a)/(N-1) S_k2 = derivada_S(time[i] + (h/2), I[i] + (h/2)*I_k1, S[i] + (h/2)*S_k1)\n I_k1 h S_k1 for i in range(data-1):\n S_k1 = derivada_S(time[i], I[i], S[i])\n I_k1 = derivada_I(time[i], I[i], S[i])\n R_k1 = derivada_R(time[i], I[i])\n\n S_k2 = derivada_S(time[i] + (1/2)*h, I[i] + (h/2)*I_k1, S[i] + (h/2)*S_k1)\n I_k2 = derivada_I(time[i] + (1/2)*h, I[i] + (h/2)*I_k1, S[i] + (h/2)*S_k1)\n R_k2 = derivada_R(time[i] + (1/2)*h, I[i] + (h/2)*I_k1)\n\n S_k3 = derivada_S(time[i] + (h/2), I[i] + (h/2)*I_k2, S[i] + (h/2)*S_k2)\n I_k3 = derivada_I(time[i] + (h/2), I[i] + (h/2)*I_k2, S[i] + (h/2)*S_k2)\n R_k3 = derivada_R(time[i] + (h/2), I[i] + (h/2)*I_k2)\n\n S_k4 = derivada_S(time[i] + h, I[i] + I_k3, S[i] + S_k3)\n I_k4 = derivada_I(time[i] + h, I[i] + I_k3, S[i] + S_k3)\n R_k4 = derivada_R(time[i] + h, I[i] + I_k3)\n \n S[i+1] = S[i] + (h/6)*(S_k1 + 2*S_k2 + 2*S_k3 + S_k4)\n I[i+1] = I[i] + (h/6)*(I_k1 + 2*I_k2 + 2*I_k3 + I_k4)\n R[i+1] = R[i] + (h/6)*(R_k1 + 2*R_k2 + 2*R_k3 + R_k4)\n h I_k1, S_k1 0.05 t=50 x 2 data = 10*time_k+1 S[-1]=0.10483, I[-1]=8.11098e-05, R[-1]=0.89509\n h=t[1]-t[0] t=50 i=500" }, { "answer_id": 74646998, "author": "Carllos Limma", "author_id": 20080193, "author_profile": "https://Stackoverflow.com/users/20080193", "pm_score": 0, "selected": false, "text": "##########################################\n# AUTHOR : CARLOS DUARDO DA SILVA LIMA #\n# DATE : 12/01/2022 #\n# LANGUAGE: python #\n# IDE : GOOGLE COLAB #\n# PROBLEM : MODEL SIR #\n##########################################\n\nimport numpy as np\nfrom scipy.integrate import odeint, solve_ivp, RK45\nimport matplotlib.pyplot as plt\n\nt_i = 0.0 # START TIME\nt_f = 50.0 # FINAL TIME\nN = 1000\n\n#t = np.linspace(t_i,t_f,N)\nt_span = np.array([t_i,t_f])\n\n# INITIAL CONDITIONS OF THE SOR MODEL\nS0 = 0.99\nI0 = 0.01\nR0 = 0.0\nr0 = np.array([S0,I0,R0])\n\n# ORDINARY DIFFERENTIAL EQUATIONS OF THE SIR MODEL\ndef SIR(t,y,b,k):\n s,i,r = y\n ode1 = -b*s*i\n ode2 = b*s*i-k*i\n ode3 = k*i\n return np.array([ode1,ode2,ode3])\n\n# INTEGRATION OF ORDINARY DIFFERENTIAL EQUATIONS (FOURTH ORDER RUNGE-KUTTA, RADAU)\n#sol_solve_ivp = solve_ivp(SIR,t_span,y0 = r0,method='Radau', rtol=1E-09, atol=1e-09, args = (0.8,0.3125))\nsol_solve_ivp = solve_ivp(SIR,t_span,y0 = r0,method='RK45', rtol=1E-09, atol=1e-09, args = (0.8,0.3125))\n\n# T, S, I, R FUNCTIONS\nt_= sol_solve_ivp.t\ns = sol_solve_ivp.y[0, :]\ni = sol_solve_ivp.y[1, :]\nr = sol_solve_ivp.y[2, :]\n\n# GRAPHIC\nplt.figure(1)\nplt.style.use('dark_background')\nplt.figure(figsize = (8,8))\nplt.plot(t_,s,'c-',t_,i,'g-',t_,r,'y-',lw=1.5)\n#plt.title(r'$\\frac{dS(t)}{dt} = -bs(t)i(t)$, $\\frac{dI(t)}{dt} = bs(t)i(t)-ki(t)$ and $\\frac{dR(t)}{dt} = ki(t)$')\nplt.title(r'SIR Model', color = 'm')\nplt.xlabel(r'$t(t)$', color = 'm')\nplt.ylabel(r'$S(t)$, $I(t)$ and $R(t)$', color = 'm')\nplt.legend(['S', 'I', 'R'], shadow=True)\nplt.grid(lw = 0.95,color = 'white',linestyle = '--')\nplt.show()\n\n''' SEARCH WEBSITES\nhttps://en.wikipedia.org/wiki/Compartmental_models_in_epidemiology\nhttps://www.maa.org/press/periodicals/loci/joma/the-sir-model-for-spread-of-disease-the-differential-equation-model\n'''\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20544056/" ]
74,513,435
<p>I have a json file with lot of information so I'm trying to just extract specific data where there is a position and I need to get the immediate name data, also trying to implement search in python. I'm uploading a part of sample json data from the file ex.json</p> <p>`</p> <pre><code>{ &quot;storables&quot;: [ { &quot;columns&quot;: [ { &quot;position&quot;: 0, &quot;header&quot;: { &quot;id&quot;: &quot;&quot;, &quot;indexVersion&quot;: 35643, &quot;generationNum&quot;: 35643, &quot;name&quot;: &quot;CAT&quot;, &quot;author&quot;: &quot;&quot;, &quot;created&quot;: 1620247188226, &quot;modified&quot;: 1668544812673, &quot;modifiedBy&quot;: &quot;&quot;, &quot;owner&quot;: &quot;&quot;, &quot;isDeleted&quot;: false, &quot;isHidden&quot;: false, &quot;tags&quot;: [], &quot;isExternal&quot;: false, &quot;isDeprecated&quot;: false }, &quot;complete&quot;: true, &quot;incompleteDetail&quot;: [], &quot;isDerived&quot;: true, &quot;dataType&quot;: &quot;VARCHAR&quot;, &quot;type&quot;: &quot;ATTRIBUTE&quot;, &quot;sageOutputColumnId&quot;: &quot;&quot;, &quot;defaultAggrType&quot;: &quot;NONE&quot;, &quot;ownerName&quot;: &quot;&quot;, &quot;ownerType&quot;: &quot;WORKSHEET&quot;, &quot;entityCategory&quot;: &quot;DEFAULT&quot;, &quot;spotiqPreference&quot;: &quot;DEFAULT&quot;, &quot;isAdditive&quot;: false, &quot;indexType&quot;: &quot;DEFAULT&quot;, &quot;indexPriority&quot;: 1, &quot;sources&quot;: [ { &quot;tableId&quot;: &quot;&quot;, &quot;tableName&quot;: &quot;&quot;, &quot;columnId&quot;: &quot;&quot;, &quot;columnName&quot;: &quot;CATASTROPHE&quot; } ], &quot;synonyms&quot;: [], &quot;injectedInlineValues&quot;: [], &quot;precision&quot;: -1, &quot;scale&quot;: 0, &quot;isPrimaryKey&quot;: false, &quot;isAttributionDimension&quot;: true, &quot;derivationExpr&quot;: { &quot;exprType&quot;: &quot;LOGICAL_COLUMN_REFERENCE&quot;, &quot;logicalColumn&quot;: { &quot;header&quot;: { &quot;id&quot;: &quot;&quot;, &quot;indexVersion&quot;: 35499, &quot;generationNum&quot;: 35499, &quot;name&quot;: &quot;CATASTROPHE&quot;, &quot;author&quot;: &quot;&quot;, &quot;created&quot;: 1630716505804, &quot;modified&quot;: 1668211006637, &quot;modifiedBy&quot;: &quot;&quot;, &quot;owner&quot;: &quot;&quot;, &quot;isDeleted&quot;: false, &quot;isHidden&quot;: false, &quot;schemaStripe&quot;: &quot;&quot;, &quot;databaseStripe&quot;: &quot;&quot;, &quot;tags&quot;: [], &quot;isExternal&quot;: false, &quot;isDeprecated&quot;: false } }, &quot;joinPaths&quot;: [ { &quot;joins&quot;: [ { &quot;sourceTable&quot;: &quot;&quot;, &quot;destinationTable&quot;: &quot;&quot;, &quot;content&quot;: { &quot;relationships&quot;: [ { &quot;sourceColumn&quot;: &quot;&quot;, &quot;destinationColumn&quot;: &quot;&quot; } ], &quot;weight&quot;: 1 }, &quot;joinType&quot;: &quot;INNER&quot;, &quot;type&quot;: &quot;USER_DEFINED&quot;, &quot;isOneToOneJoin&quot;: false, &quot;header&quot;: { &quot;id&quot;: &quot;&quot;, &quot;indexVersion&quot;: 35499, &quot;generationNum&quot;: 35499, &quot;name&quot;: &quot;&quot;, &quot;description&quot;: &quot;&quot;, &quot;author&quot;: &quot;&quot;, &quot;created&quot;: 1650658367043, &quot;modified&quot;: 1668211006686, &quot;modifiedBy&quot;: &quot;&quot;, &quot;owner&quot;: &quot;&quot;, &quot;isDeleted&quot;: false, &quot;isHidden&quot;: false, &quot;tags&quot;: [], &quot;type&quot;: &quot;USER_DEFINED&quot;, &quot;isExternal&quot;: false, &quot;isDeprecated&quot;: false }, &quot;complete&quot;: true, &quot;incompleteDetail&quot;: [], &quot;sourceColumns&quot;: [ &quot;&quot; ], &quot;targetColumns&quot;: [ &quot;&quot; ] } ] } ] } }, { &quot;position&quot;: 1, &quot;header&quot;: { &quot;id&quot;: &quot;&quot;, &quot;indexVersion&quot;: 35643, &quot;generationNum&quot;: 35643, &quot;name&quot;: &quot;Peril&quot;, &quot;author&quot;: &quot;&quot;, &quot;created&quot;: 1620247188226, &quot;modified&quot;: 1668544812673, &quot;modifiedBy&quot;: &quot;&quot;, &quot;owner&quot;: &quot;&quot;, &quot;isDeleted&quot;: false, &quot;isHidden&quot;: false, &quot;tags&quot;: [], &quot;isExternal&quot;: false, &quot;isDeprecated&quot;: false }, &quot;complete&quot;: true, &quot;incompleteDetail&quot;: [], &quot;isDerived&quot;: true, &quot;dataType&quot;: &quot;VARCHAR&quot;, &quot;type&quot;: &quot;ATTRIBUTE&quot;, &quot;sageOutputColumnId&quot;: &quot;&quot;, &quot;defaultAggrType&quot;: &quot;NONE&quot;, &quot;ownerName&quot;: &quot;&quot;, &quot;ownerType&quot;: &quot;WORKSHEET&quot;, &quot;entityCategory&quot;: &quot;DEFAULT&quot;, &quot;spotiqPreference&quot;: &quot;DEFAULT&quot;, &quot;isAdditive&quot;: false, &quot;indexType&quot;: &quot;DEFAULT&quot;, &quot;indexPriority&quot;: 1, &quot;sources&quot;: [ { &quot;tableId&quot;: &quot;&quot;, &quot;tableName&quot;: &quot;&quot;, &quot;columnId&quot;: &quot;&quot;, &quot;columnName&quot;: &quot;TYPE_OF&quot; } ], &quot;synonyms&quot;: [], &quot;injectedInlineValues&quot;: [], &quot;precision&quot;: -1, &quot;scale&quot;: 0, &quot;isPrimaryKey&quot;: false, &quot;isAttributionDimension&quot;: true, &quot;derivationExpr&quot;: { &quot;exprType&quot;: &quot;LOGICAL_COLUMN_REFERENCE&quot;, &quot;logicalColumn&quot;: { &quot;header&quot;: { &quot;id&quot;: &quot;&quot;, &quot;indexVersion&quot;: 35499, &quot;generationNum&quot;: 35499, &quot;name&quot;: &quot;TYPE_OF&quot;, &quot;author&quot;: &quot;&quot;, &quot;created&quot;: 1630716505804, &quot;modified&quot;: 1668211006637, &quot;modifiedBy&quot;: &quot;&quot;, &quot;owner&quot;: &quot;&quot;, &quot;isDeleted&quot;: false, &quot;isHidden&quot;: false, &quot;schemaStripe&quot;: &quot;&quot;, &quot;databaseStripe&quot;: &quot;&quot;, &quot;tags&quot;: [], &quot;isExternal&quot;: false, &quot;isDeprecated&quot;: false } }, &quot;joinPaths&quot;: [ { &quot;joins&quot;: [ { &quot;sourceTable&quot;: &quot;&quot;, &quot;destinationTable&quot;: &quot;&quot;, &quot;content&quot;: { &quot;relationships&quot;: [ { &quot;sourceColumn&quot;: &quot;&quot;, &quot;destinationColumn&quot;: &quot;&quot; } ], &quot;weight&quot;: 1 }, &quot;joinType&quot;: &quot;INNER&quot;, &quot;type&quot;: &quot;USER_DEFINED&quot;, &quot;isOneToOneJoin&quot;: false, &quot;header&quot;: { &quot;id&quot;: &quot;&quot;, &quot;indexVersion&quot;: 35499, &quot;generationNum&quot;: 35499, &quot;name&quot;: &quot;&quot;, &quot;description&quot;: &quot;Copy of user table relationship&quot;, &quot;author&quot;: &quot;&quot;, &quot;created&quot;: 1650658367043, &quot;modified&quot;: 1668211006686, &quot;modifiedBy&quot;: &quot;&quot;, &quot;owner&quot;: &quot;&quot;, &quot;isDeleted&quot;: false, &quot;isHidden&quot;: false, &quot;tags&quot;: [], &quot;type&quot;: &quot;USER_DEFINED&quot;, &quot;isExternal&quot;: false, &quot;isDeprecated&quot;: false }, &quot;complete&quot;: true, &quot;incompleteDetail&quot;: [], &quot;sourceColumns&quot;: [ &quot;&quot; ], &quot;targetColumns&quot;: [ &quot;&quot; ] } ] } ] } }, { &quot;position&quot;: 2, &quot;header&quot;: { &quot;id&quot;: &quot;&quot;, &quot;indexVersion&quot;: 35643, &quot;generationNum&quot;: 35643, &quot;name&quot;: &quot;Job&quot;, &quot;author&quot;: &quot;&quot;, &quot;created&quot;: 1620247188226, &quot;modified&quot;: 1668544812673, &quot;modifiedBy&quot;: &quot;&quot;, &quot;owner&quot;: &quot;&quot;, &quot;isDeleted&quot;: false, &quot;isHidden&quot;: false, &quot;tags&quot;: [], &quot;isExternal&quot;: false, &quot;isDeprecated&quot;: false }, &quot;complete&quot;: true, &quot;incompleteDetail&quot;: [], &quot;isDerived&quot;: true, &quot;dataType&quot;: &quot;VARCHAR&quot;, &quot;type&quot;: &quot;ATTRIBUTE&quot;, &quot;sageOutputColumnId&quot;: &quot;&quot;, &quot;defaultAggrType&quot;: &quot;NONE&quot;, &quot;ownerName&quot;: &quot;&quot;, &quot;ownerType&quot;: &quot;WORKSHEET&quot;, &quot;entityCategory&quot;: &quot;DEFAULT&quot;, &quot;spotiqPreference&quot;: &quot;DEFAULT&quot;, &quot;isAdditive&quot;: false, &quot;indexType&quot;: &quot;DEFAULT&quot;, &quot;indexPriority&quot;: 1, &quot;sources&quot;: [ { &quot;tableId&quot;: &quot;&quot;, &quot;tableName&quot;: &quot;&quot;, &quot;columnId&quot;: &quot;&quot;, &quot;columnName&quot;: &quot;&quot; } ], &quot;synonyms&quot;: [], &quot;injectedInlineValues&quot;: [], &quot;precision&quot;: -1, &quot;scale&quot;: 0, &quot;isPrimaryKey&quot;: false, &quot;isAttributionDimension&quot;: true, &quot;derivationExpr&quot;: { &quot;exprType&quot;: &quot;LOGICAL_COLUMN_REFERENCE&quot;, &quot;logicalColumn&quot;: { &quot;header&quot;: { &quot;id&quot;: &quot;&quot;, &quot;indexVersion&quot;: 35499, &quot;generationNum&quot;: 35499, &quot;name&quot;: &quot;ROTATION_TRADE&quot;, &quot;author&quot;: &quot;&quot;, &quot;created&quot;: 1630716505804, &quot;modified&quot;: 1668211006637, &quot;modifiedBy&quot;: &quot;&quot;, &quot;owner&quot;: &quot;&quot;, &quot;isDeleted&quot;: false, &quot;isHidden&quot;: false, &quot;schemaStripe&quot;: &quot;&quot;, &quot;databaseStripe&quot;: &quot;&quot;, &quot;tags&quot;: [], &quot;isExternal&quot;: false, &quot;isDeprecated&quot;: false } }, &quot;joinPaths&quot;: [ { &quot;joins&quot;: [ { &quot;sourceTable&quot;: &quot;&quot;, &quot;destinationTable&quot;: &quot;&quot;, &quot;content&quot;: { &quot;relationships&quot;: [ { &quot;sourceColumn&quot;: &quot;&quot;, &quot;destinationColumn&quot;: &quot;&quot; } ], &quot;weight&quot;: 1 }, &quot;joinType&quot;: &quot;INNER&quot;, &quot;type&quot;: &quot;USER_DEFINED&quot;, &quot;isOneToOneJoin&quot;: false, &quot;header&quot;: { &quot;id&quot;: &quot;&quot;, &quot;indexVersion&quot;: 35499, &quot;generationNum&quot;: 35499, &quot;name&quot;: &quot;&quot;, &quot;description&quot;: &quot;Copy of user table relationship&quot;, &quot;author&quot;: &quot;&quot;, &quot;created&quot;: 1650658367043, &quot;modified&quot;: 1668211006686, &quot;modifiedBy&quot;: &quot;&quot;, &quot;owner&quot;: &quot;&quot;, &quot;isDeleted&quot;: false, &quot;isHidden&quot;: false, &quot;tags&quot;: [], &quot;type&quot;: &quot;USER_DEFINED&quot;, &quot;isExternal&quot;: false, &quot;isDeprecated&quot;: false }, &quot;complete&quot;: true, &quot;incompleteDetail&quot;: [], &quot;sourceColumns&quot;: [ &quot;&quot; ], &quot;targetColumns&quot;: [ &quot;&quot; ] } ] } ] } }, { &quot;position&quot;: 3, &quot;header&quot;: { &quot;id&quot;: &quot;&quot;, &quot;indexVersion&quot;: 35643, &quot;generationNum&quot;: 35643, &quot;name&quot;: &quot;Job Lenghth&quot;, &quot;author&quot;: &quot;&quot;, &quot;created&quot;: 1620247188226, &quot;modified&quot;: 1668544812673, &quot;modifiedBy&quot;: &quot;&quot;, &quot;owner&quot;: &quot;&quot;, &quot;isDeleted&quot;: false, &quot;isHidden&quot;: false, &quot;tags&quot;: [], &quot;isExternal&quot;: false, &quot;isDeprecated&quot;: false }, &quot;complete&quot;: true, &quot;incompleteDetail&quot;: [], &quot;isDerived&quot;: true, &quot;dataType&quot;: &quot;VARCHAR&quot;, &quot;type&quot;: &quot;ATTRIBUTE&quot;, </code></pre> <p>`</p> <p>`</p> <pre><code>with open('ex.json', 'r') as f: for line in f: if 'position' in line: for line in f: if ' name: ' in line: print(line) </code></pre> <p>` I tried this python piece of code but it din't work. I'm not sure how to return just the immediate name after the position. There are multiple name instances in the file but I need just the one after position...</p>
[ { "answer_id": 74513822, "author": "Nindi", "author_id": 20505208, "author_profile": "https://Stackoverflow.com/users/20505208", "pm_score": 2, "selected": false, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nBeta = 1.00205\nGamma = 0.23000\nN = 1000\n\ndef func_S(t,I,S):\n return - Beta*I*S/N\n\ndef func_I(t,I,S):\n return Beta*I*S/N - Gamma*I\n\ndef func_R(t,I):\n return Gamma*I\n\n\n# physical parameters\nI0 = 1\nR0 = 0\nS0 = N - I0 - R0\nt0 = 0\ntn = 50\n\n\n\n# Numerical Parameters\nndata = 1000\n\n\n\nt = np.linspace(t0,tn,ndata)\nh = t[2] - t[1]\n\nS = np.zeros(ndata)\nI = np.zeros(ndata)\nR = np.zeros(ndata)\n\nS[0] = S0\nI[0] = I0\nR[0] = R0\n\n\nfor i in range(ndata-1):\n k1 = func_S(t[i], I[i], S[i])\n k2 = func_S(t[i]+0.5*h, I[i], S[i]+h+0.5*k1)\n k3 = func_S(t[i]+0.5*h, I[i], S[i]+h+0.5*k2)\n k4 = func_S(t[i]+h, I[i], S[i]+h+k3)\n \n S[i+1] = S[i] + (h/6)*(k1 + 2*k2 + 2*k3 + k4)\n \n kk1 = func_I(t[i], I[i], S[i])\n kk2 = func_I(t[i]+0.5*h, I[i], S[i]+h+0.5*kk1)\n kk3 = func_I(t[i]+0.5*h, I[i], S[i]+h+0.5*kk2)\n kk4 = func_I(t[i]+h, I[i], S[i]+h+kk3)\n \n I[i+1] = I[i] + (h/6)*(kk1 + 2*kk2 + 2*kk3 + kk4)\n \n l1 = func_R(t[i], I[i])\n l2 = func_R(t[i]+0.5*h, I[i])\n l3 = func_R(t[i]+0.5*h, I[i])\n l4 = func_R(t[i]+h, I[i])\n \n R[i+1] = R[i] + (h/6)*(l1 + 2*l2 + 2*l3 + l4)\n \n \nplt.figure(1)\nplt.plot(t,S)\nplt.plot(t,I)\nplt.plot(t,R)\nplt.show()\n" }, { "answer_id": 74514912, "author": "Lutz Lehmann", "author_id": 3088138, "author_profile": "https://Stackoverflow.com/users/3088138", "pm_score": 1, "selected": true, "text": "time = np.linspace(0,days,10*days+1)\n linspace(a,b,N) N (b-a)/(N-1) S_k2 = derivada_S(time[i] + (h/2), I[i] + (h/2)*I_k1, S[i] + (h/2)*S_k1)\n I_k1 h S_k1 for i in range(data-1):\n S_k1 = derivada_S(time[i], I[i], S[i])\n I_k1 = derivada_I(time[i], I[i], S[i])\n R_k1 = derivada_R(time[i], I[i])\n\n S_k2 = derivada_S(time[i] + (1/2)*h, I[i] + (h/2)*I_k1, S[i] + (h/2)*S_k1)\n I_k2 = derivada_I(time[i] + (1/2)*h, I[i] + (h/2)*I_k1, S[i] + (h/2)*S_k1)\n R_k2 = derivada_R(time[i] + (1/2)*h, I[i] + (h/2)*I_k1)\n\n S_k3 = derivada_S(time[i] + (h/2), I[i] + (h/2)*I_k2, S[i] + (h/2)*S_k2)\n I_k3 = derivada_I(time[i] + (h/2), I[i] + (h/2)*I_k2, S[i] + (h/2)*S_k2)\n R_k3 = derivada_R(time[i] + (h/2), I[i] + (h/2)*I_k2)\n\n S_k4 = derivada_S(time[i] + h, I[i] + I_k3, S[i] + S_k3)\n I_k4 = derivada_I(time[i] + h, I[i] + I_k3, S[i] + S_k3)\n R_k4 = derivada_R(time[i] + h, I[i] + I_k3)\n \n S[i+1] = S[i] + (h/6)*(S_k1 + 2*S_k2 + 2*S_k3 + S_k4)\n I[i+1] = I[i] + (h/6)*(I_k1 + 2*I_k2 + 2*I_k3 + I_k4)\n R[i+1] = R[i] + (h/6)*(R_k1 + 2*R_k2 + 2*R_k3 + R_k4)\n h I_k1, S_k1 0.05 t=50 x 2 data = 10*time_k+1 S[-1]=0.10483, I[-1]=8.11098e-05, R[-1]=0.89509\n h=t[1]-t[0] t=50 i=500" }, { "answer_id": 74646998, "author": "Carllos Limma", "author_id": 20080193, "author_profile": "https://Stackoverflow.com/users/20080193", "pm_score": 0, "selected": false, "text": "##########################################\n# AUTHOR : CARLOS DUARDO DA SILVA LIMA #\n# DATE : 12/01/2022 #\n# LANGUAGE: python #\n# IDE : GOOGLE COLAB #\n# PROBLEM : MODEL SIR #\n##########################################\n\nimport numpy as np\nfrom scipy.integrate import odeint, solve_ivp, RK45\nimport matplotlib.pyplot as plt\n\nt_i = 0.0 # START TIME\nt_f = 50.0 # FINAL TIME\nN = 1000\n\n#t = np.linspace(t_i,t_f,N)\nt_span = np.array([t_i,t_f])\n\n# INITIAL CONDITIONS OF THE SOR MODEL\nS0 = 0.99\nI0 = 0.01\nR0 = 0.0\nr0 = np.array([S0,I0,R0])\n\n# ORDINARY DIFFERENTIAL EQUATIONS OF THE SIR MODEL\ndef SIR(t,y,b,k):\n s,i,r = y\n ode1 = -b*s*i\n ode2 = b*s*i-k*i\n ode3 = k*i\n return np.array([ode1,ode2,ode3])\n\n# INTEGRATION OF ORDINARY DIFFERENTIAL EQUATIONS (FOURTH ORDER RUNGE-KUTTA, RADAU)\n#sol_solve_ivp = solve_ivp(SIR,t_span,y0 = r0,method='Radau', rtol=1E-09, atol=1e-09, args = (0.8,0.3125))\nsol_solve_ivp = solve_ivp(SIR,t_span,y0 = r0,method='RK45', rtol=1E-09, atol=1e-09, args = (0.8,0.3125))\n\n# T, S, I, R FUNCTIONS\nt_= sol_solve_ivp.t\ns = sol_solve_ivp.y[0, :]\ni = sol_solve_ivp.y[1, :]\nr = sol_solve_ivp.y[2, :]\n\n# GRAPHIC\nplt.figure(1)\nplt.style.use('dark_background')\nplt.figure(figsize = (8,8))\nplt.plot(t_,s,'c-',t_,i,'g-',t_,r,'y-',lw=1.5)\n#plt.title(r'$\\frac{dS(t)}{dt} = -bs(t)i(t)$, $\\frac{dI(t)}{dt} = bs(t)i(t)-ki(t)$ and $\\frac{dR(t)}{dt} = ki(t)$')\nplt.title(r'SIR Model', color = 'm')\nplt.xlabel(r'$t(t)$', color = 'm')\nplt.ylabel(r'$S(t)$, $I(t)$ and $R(t)$', color = 'm')\nplt.legend(['S', 'I', 'R'], shadow=True)\nplt.grid(lw = 0.95,color = 'white',linestyle = '--')\nplt.show()\n\n''' SEARCH WEBSITES\nhttps://en.wikipedia.org/wiki/Compartmental_models_in_epidemiology\nhttps://www.maa.org/press/periodicals/loci/joma/the-sir-model-for-spread-of-disease-the-differential-equation-model\n'''\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19779238/" ]
74,513,447
<p>Dear pythonist that question is for you! I don't ask to solve my task, just ask for explaining why it happens) I know what is args and kwargs when they using but has been really shoked, when have found one thing. So, please check my example, here we pass arguments to the function</p> <pre><code>def firstFunc(*args, **kwargs): print('args' ) print(args) print('kwargs') print(kwargs) firstFunc([1, 2], {'firstFirst': 'firstFirst', 'first' : '123', 'second' : '999'}) </code></pre> <p><a href="https://i.stack.imgur.com/l6181.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l6181.png" alt="And thats the result of it, all that we passed we have in args, but kwargs is empty, first of all why we don't have kwargs as dictionary like that we have passed ?" /></a></p> <p>My second question is, why we can get the dictonary from the second function, if we will set it like this kwargs['second'] = 222, that's my code</p> <pre><code>def firstFunc(*args, **kwargs): print('args' ) print(*args) print('kwargs') print(**kwargs) kwargs['second'] = 222 secondFunc([1, 2], **kwargs) def secondFunc(*args, **kwargs): print('args' ) print(args) print('kwargs') print(kwargs) firstFunc([1, 2], {'firstFirst': 'firstFirst', 'first' : '123', 'second' : '999'}) </code></pre> <p><a href="https://i.stack.imgur.com/vbnD6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vbnD6.png" alt="but my second function seing kwargs dictonary, how i set it in the first function" /></a></p> <p>hope I described understandable, I am waiting for u answer, please tell me why it hapens, and why I cannot just pass dictionarie as kwargs! many thanks for u</p> <p>#python #pythonic #kwargs #args #functions</p> <p>I expected just mine dictionary in kwargs</p>
[ { "answer_id": 74513457, "author": "Samwise", "author_id": 3799759, "author_profile": "https://Stackoverflow.com/users/3799759", "pm_score": 2, "selected": true, "text": "*args **kwargs * firstFunc(*[1, 2])\n ** firstFunc(\n *[1, 2],\n **{'firstFirst': 'firstFirst', 'first' : '123', 'second' : '999'}\n)\n firstFunc(\n 1,\n 2,\n firstFirst='firstFirst',\n first='123',\n second='999'\n)\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11798363/" ]
74,513,451
<p>My code: <a href="https://colab.research.google.com/drive/1qjfy2OsHYewhHDej-W83CMNercB7o7r8?usp=sharing" rel="nofollow noreferrer">https://colab.research.google.com/drive/1qjfy2OsHYewhHDej-W83CMNercB7o7r8?usp=sharing</a></p> <p>the error: ValueError: Using a target size (torch.Size([16])) that is different to the input size (torch.Size([13456, 1])) is deprecated. Please ensure they have the same size.</p> <p>the dataset consists of 2 folders: 0 and 1, and in each of these two folders, there’re about 2500 512*512 images and a json file for each image.</p> <p>the code was from the pytorch gan tutorial, i just changed the dataset.</p> <p>I wonder where does the 13456 come from?</p>
[ { "answer_id": 74520507, "author": "Clement Hui", "author_id": 10675215, "author_profile": "https://Stackoverflow.com/users/10675215", "pm_score": 0, "selected": false, "text": "label = torch.full((b_size,), real_label, dtype=torch.float, device=device)\n output = netD(real_cpu).view(-1)\noutput = output.unsqueeze(1)\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20558722/" ]
74,513,453
<p>I have Strapi CMS deployed in Cloud Run and have exposed it via Google Cloud Load Balancer. CMS exposes unauthenticated URL to expose static content. If I hit the Cloud Run URL directly without authentication, it works fine and serves me the content.</p> <p>Then I configured Google Cloud Load Balancer with backend configuration (via Service Endpoint Group) to Cloud Run instance. COnfiguration is successful. However If i try to hit the CLoud Run URL via Cloud Load Balancer, it is throwing 403 Forbidded error.</p> <p>If the same cloud load balancer URL is accessed with Authorization header it works fine. I need unauthenticated requests to be made.</p> <p>Any help will be much appriciated.</p>
[ { "answer_id": 74520507, "author": "Clement Hui", "author_id": 10675215, "author_profile": "https://Stackoverflow.com/users/10675215", "pm_score": 0, "selected": false, "text": "label = torch.full((b_size,), real_label, dtype=torch.float, device=device)\n output = netD(real_cpu).view(-1)\noutput = output.unsqueeze(1)\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1597814/" ]
74,513,494
<p>Consider the following dataframe:</p> <pre class="lang-py prettyprint-override"><code>df = pl.DataFrame({ &quot;letters&quot;: [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;H&quot;], &quot;values&quot;: [&quot;aa&quot;, &quot;bb&quot;, &quot;cc&quot;, &quot;dd&quot;, &quot;ee&quot;, &quot;ff&quot;, &quot;gg&quot;, &quot;hh&quot;] }) print(df) shape: (8, 2) ┌─────────┬────────┐ │ letters ┆ values │ │ --- ┆ --- │ │ str ┆ str │ ╞═════════╪════════╡ │ A ┆ aa │ ├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤ │ B ┆ bb │ ├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤ │ C ┆ cc │ ├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤ │ D ┆ dd │ ├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤ │ E ┆ ee │ ├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤ │ F ┆ ff │ ├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤ │ G ┆ gg │ ├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤ │ H ┆ hh │ └─────────┴────────┘ </code></pre> <p>How do I take a window of size +/- N around any row that satisfies a given condition? For example, the condition is <code>pl.col(&quot;letters&quot;).contains(&quot;D|F&quot;)</code> and <code>N = 2</code>. Then, the output should be:</p> <pre><code>┌─────────┬────────────────────────────────┐ │ letters ┆ output │ │ --- ┆ --- │ │ str ┆ list[str] │ ╞═════════╪════════════════════════════════╡ │ D ┆ [&quot;bb&quot;, &quot;cc&quot;, &quot;dd&quot;, &quot;ee&quot;, &quot;ff&quot;] │ ├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤ │ F ┆ [&quot;dd&quot;, &quot;ee&quot;, &quot;ff&quot;, &quot;gg&quot;, &quot;hh&quot;] │ └─────────┴────────────────────────────────┘ </code></pre> <p>Note that the windows are overlapping in this case (the <code>F</code> window also contains <code>dd</code> and the <code>D</code> windows also contains <code>ff</code>). Also, note that N = 2 for the sake of simplicity here but, in reality, it'll be larger (~10 - 20). And the dataset is relatively large so I'd like to do this as efficiently as possible without exploding memory usage.</p> <hr /> <p><strong>EDIT:</strong> To make the ask more explicit, here's the query in DuckDB's SQL syntax that gives the right answer (and I'd like to know how to translate it to Polars):</p> <pre class="lang-py prettyprint-override"><code>df_table = df.to_arrow() con = duckdb.connect() query = &quot;&quot;&quot; SELECT letters, list(values) OVER ( ROWS BETWEEN 2 PRECEDING AND 2 FOLLOWING ) as combined FROM df_table QUALIFY letters in ('D', 'F') &quot;&quot;&quot; print(pl.from_arrow(con.execute(query).arrow())) shape: (2, 2) ┌─────────┬────────────────────────┐ │ letters ┆ combined │ │ --- ┆ --- │ │ str ┆ list[str] │ ╞═════════╪════════════════════════╡ │ D ┆ [&quot;bb&quot;, &quot;cc&quot;, ... &quot;ff&quot;] │ ├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤ │ F ┆ [&quot;dd&quot;, &quot;ee&quot;, ... &quot;hh&quot;] │ └─────────┴────────────────────────┘ </code></pre> <hr /> <h1>Benchmarks of suggested solutions</h1> <p>I ran the suggested solutions in a Jupyter notebook on one of Amazon's <code>ml.c5.xlarge</code> machines. While the notebook was running, I also kept <code>htop</code> open in a terminal to observe CPU and memory use. The dataset had 12M+ rows.</p> <p>I ran both solutions via both the eager and lazy APIs. For good measure, I also tried using a simple Python for loop to extract the slices after identifying the rows of interest and also DuckDB.</p> <h2>Summary Table</h2> <p>Polars had really robust performance and judicious memory use (with the @jqurious' method) because of the clever, no-copy implementation of <code>.shift()</code> . Surprisingly, a well-thought out Python for loop did just as well. DuckDB had performed rather poorly in both speed and memory use.</p> <p>Neither Polars nor DuckDB uses more than one core for the operation. Not sure if that's due to a lack of optimization or if this problem is just amenable to parallelization. I suppose we're only filtering over one column and then taking slices of that same column so there's not much multiple threads can do.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>method</th> <th>cpu use</th> <th>memory use</th> <th>time</th> </tr> </thead> <tbody> <tr> <td>ΩΠΟΚΕΚΡΥΜΜΕΝΟΣ</td> <td>single core</td> <td>explosion</td> <td></td> </tr> <tr> <td>jqurious</td> <td>single core</td> <td>2.53G to 2.53G</td> <td>4.63 s</td> </tr> <tr> <td>(smart) for loop</td> <td>single core</td> <td>2.53G to 2.58G</td> <td>4.91 s</td> </tr> <tr> <td>DuckDB</td> <td>single core</td> <td>1.62G to 6.13G</td> <td>38.6 s</td> </tr> </tbody> </table> </div> <ul> <li>cpu use shows if multiple cores were taxes during the operation</li> <li>memory use shows how much memory was being used before the operation and the maximum memory use during the operation.</li> </ul> <h2>@ΩΠΟΚΕΚΡΥΜΜΕΝΟΣ's solution:</h2> <pre><code>preceding = 2 following = 2 look_around = [pl.col(&quot;body&quot;).shift(-i) for i in range(-preceding, following + 1)] ( df .with_column( pl.when(pl.col('body').str.contains(regex)) .then(pl.concat_list(look_around)) .alias('combined') ) .filter(pl.col('combined').is_not_null()) ) </code></pre> <p>Unfortunately, on my rather large dataset, this solution caused the memory use to explode and the kernel to crash with both the eager and lazy APIs.</p> <h2>@jqurious' solution</h2> <pre><code>preceding = 2 following = 2 look_around = [ pl.col(&quot;body&quot;).shift(-i).alias(f&quot;lag_{i}&quot;) for i in range(-preceding, following + 1) ] ( df .with_columns( look_around ) .filter(pl.col(&quot;body&quot;).str.contains(regex)) .select([ pl.col(&quot;body&quot;), pl.concat_list([f&quot;lag_{i}&quot; for i in range(-2, 3)]).alias(&quot;output&quot;) ]) ) </code></pre> <ul> <li><p><strong>eager:</strong></p> <ul> <li><strong>cpu use:</strong> single-core</li> <li><strong>memory use:</strong> 2.53G -&gt; 2.53G</li> <li><strong>time:</strong> 4.63 s ± 6.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</li> </ul> </li> <li><p><strong>lazy:</strong></p> <ul> <li><strong>cpu use:</strong> single-core</li> <li><strong>memory use:</strong> 2.53G -&gt; 2.53G</li> <li><strong>time:</strong> 4.63 s ± 3.85 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</li> </ul> </li> </ul> <h2>(Smart) Python for loop</h2> <pre><code>preceding = 2 following = 2 output = [] indices = df.with_row_count().select( pl.col(&quot;row_nr&quot;).filter(pl.col(&quot;body&quot;).str.contains(regex)) )[&quot;row_nr&quot;] for idx, x in enumerate(indices): offset = max(0, x - preceding) length = preceding + following + 1 output.append(df[&quot;body&quot;].slice(offset, length)) </code></pre> <ul> <li><strong>cpu use:</strong> single-core</li> <li><strong>memory use:</strong> 2.53G -&gt; 2.58G</li> <li><strong>time:</strong> 4.91 s ± 24.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</li> </ul> <h2>DuckDB</h2> <p>Note that I first converted the <code>df</code> to an <code>Arrow.Table</code> before running the query so DuckDB could directly act on it. Also, I'm not sure if the conversion of the result back to Arrow takes up a huge amount of computation and is unfair to it.</p> <pre><code>preceding = 2 following = 2 query = f&quot;&quot;&quot; SELECT body, list(body) OVER ( ROWS BETWEEN {preceding} PRECEDING AND {following} FOLLOWING ) as combined FROM df_table QUALIFY regexp_matches(body, '{regex}') &quot;&quot;&quot; result = con.execute(query).arrow() </code></pre> <p>With DuckDB, my first attempt to run the computation crashed. I had to retry by reading to an Arrow Table directly without using Polars (this saved about 1GB of memory) to give DuckDB more memory to use.</p> <ul> <li><p><strong>first try:</strong></p> <ul> <li><strong>cpu:</strong> single-core</li> <li><strong>memory:</strong> 2.53G -&gt; 6.93G -&gt; crash!</li> <li><strong>time:</strong> NA</li> </ul> </li> <li><p><strong>second try:</strong></p> <ul> <li><strong>cpu:</strong> single-core</li> <li><strong>memory:</strong> 1.62G -&gt; 6.13G</li> <li><strong>time:</strong> 38.6 s ± 311 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</li> </ul> </li> </ul>
[ { "answer_id": 74520507, "author": "Clement Hui", "author_id": 10675215, "author_profile": "https://Stackoverflow.com/users/10675215", "pm_score": 0, "selected": false, "text": "label = torch.full((b_size,), real_label, dtype=torch.float, device=device)\n output = netD(real_cpu).view(-1)\noutput = output.unsqueeze(1)\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12744116/" ]
74,513,506
<p>I've written a PowerShell script to create a custom Boot.wim file that contains some useful utilities and custom .ps1 scripts along with the PowerShell executable. This all works just as it should. What I can't figure is how to add to the environment path variable the directory for the utilities &quot;x:\Users\Utilities&quot; to the Mounted Image.</p> <p>Here's a code snippet from the program that shows how I manipulate the mounted image to add the utilities, etc.</p> <pre><code>$WinADK=&quot;C:\Program Files (x86)\Windows Kits\10\&quot; + &quot;Assessment and Deployment Kit&quot; + &quot;\Windows Preinstallation Environment\&quot; + &quot;$(Get-ArchitectureString)&quot; $WinPETemp='G:\TempPE' New-Item -ItemType Directory -Path &quot;$($WinPETemp)\Media&quot; -force $CIArgs = @{path = $(Join-Path $WinAdk -ChildPath &quot;en-us\winpe.wim&quot;) Destination = &quot;$($WinPETemp)\Media\boot.wim&quot;} Copy-Item @CIArgs New-Item -ItemType Directory -Path $(Join-Path $WinPETemp -ChildPath &quot;\Mount&quot;) –Force #----- Mount the WinPE WIM file for Editing ----- $MTArgs = @{ImagePath = $(Join-Path $($WinPETemp) -ChildPath &quot;\Media\boot.wim&quot;) Index = 1 path = $(Join-Path $($WinPETemp) -ChildPath &quot;\Mount&quot;) } Try { Mount-WindowsImage @MTArgs -ErrorAction Stop} Catch { Get-WindowsImage -mounted | Dismount-Windowsimage -discard Mount-WindowsImage @MTArgs } #--- Packages List - PowerShell, Storage, and DISM cmdlets --# $PkgList = @( &quot;WinPE-WMI.cab&quot;, &quot;en-us\WinPE-WMI_en-us.cab&quot;, &quot;WinPE-NetFx.cab&quot;, &quot;en-us\WinPE-NetFx_en-us.cab&quot;, &quot;WinPE-Scripting.cab&quot;, &quot;en-us\WinPE-Scripting_en-us.cab&quot;, &quot;WinPE-PowerShell.cab&quot;, &quot;en-us\WinPE-PowerShell_en-us.cab&quot;, &quot;WinPE-DismCmdlets.cab&quot;, &quot;en-us\WinPE-DismCmdlets_en-us.cab&quot;, &quot;WinPE-EnhancedStorage.cab&quot;, &quot;en-us\WinPE-EnhancedStorage_en-us.cab&quot;, &quot;WinPE-StorageWMI.cab&quot;, &quot;en-us\WinPE-StorageWMI_en-us.cab&quot;) ForEach ($Pkg in $PkgList) { $AWPArgs = @{PackagePath = &quot;$($WinAdk)\Winpe_OCS\$($Pkg)&quot; Path = &quot;$($WinPETemp)\Mount&quot; IgnoreCheck = $true } Add-WindowsPackage @AWPArgs } #End ForEach ($Pkg... &lt;# Add your modifications now... Such as Directory for User Scripts, Registry Modifications, specifically Powershell Execution Policy #&gt; #--- Add User Directories --- $UserDirectories = @(&quot;Utilities&quot;,&quot;Scripts&quot;) ForEach ($Dir in $UserDirectories) { $NIArgs = @{ItemType = 'Directory' Path = &quot;$($WinPETemp)\Mount\Users\$($Dir)&quot;} New-Item @NIArgs } #--- Add PowerShell Profile --- $CIArgs = @{Path = &quot;G:\WinPE Include Files\Microsoft.PowerShell_profile.ps1&quot; Destination = &quot;$($WinPETemp)\Mount\Windows\System32\WindowsPowerShell\V1.0&quot;} Copy-Item @CIArgs #--- Add User Scripts to Directory --- $Scripts = @(&quot;Get-DotNetVersionsInstalled.ps1&quot;) ForEach ($FN in $Scripts) { $CIArgs = @{Path = &quot;G:\BEKDocs\Scripts\Production\$FN&quot; Destination = &quot;$($WinPETemp)\Mount\Users\Scripts&quot;} Copy-Item @CIArgs } #--- Add Portable Pgms to the Utilities Directory --- #--- Note: Must be 64 bit Programs no support for WOW --- $Utilities = @(&quot;Speccy64\Speccy64.exe&quot;, &quot;HWiNFO64\HWiNFO64.exe&quot;, &quot;NirSoftx64\*.*&quot;) ForEach ($FN in $Utilities) { $CIArgs = @{Path = &quot;G:\BEKDocs\NonInstPrograms\$FN&quot; Destination = &quot;$($WinPETemp)\Mount\Users\Utilities&quot; Recurse = $True } If (Test-Path -Path &quot;$(($CIArgs).Path)&quot; ) { Copy-Item @CIArgs } Else { &quot;Error:&quot; + $CIArgs.Path + &quot; Does NOT Exist!&quot; } } #--- Mount WinPE Registry to the Local Registry for mods --- $RegLoc = &quot;$($WinPETemp)\Mount\Windows\System32\config\software&quot; reg load &quot;HKLM\WimPE&quot; &quot;$RegLoc&quot; #--- Modify PowerShell Execution Policy in WIM Registry --- $RegPath = &quot;HKLM:\WimPE\Microsoft\PowerShell\1\ShellIds&quot; + &quot;\Microsoft.PowerShell\&quot; $NIArgs = @{Path = $RegPath Name = 'ExecutionPolicy' Value = &quot;RemoteSigned&quot; PropertyType = 'String' Force = $True} New-ItemProperty @NIArgs reg unload &quot;HKLM\WimPE&quot; #--- UnMount WinPE registry --- #----- DisMount the Modified WinPE WIM File ----- Dismount-WindowsImage -path &quot;$($WinPETemp)\Mount&quot; -Save #----- Make a Backup of the Modified WIM file ----- $Destination='G:\Pewim' New-Item -Path $Destination -ItemType Directory –Force $CIArgs = @{Path = &quot;$($WinPETemp)\Media\boot.wim&quot; Destination = &quot;$($Destination)\&quot;} Copy-Item @CIArgs </code></pre>
[ { "answer_id": 74520507, "author": "Clement Hui", "author_id": 10675215, "author_profile": "https://Stackoverflow.com/users/10675215", "pm_score": 0, "selected": false, "text": "label = torch.full((b_size,), real_label, dtype=torch.float, device=device)\n output = netD(real_cpu).view(-1)\noutput = output.unsqueeze(1)\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13702221/" ]
74,513,532
<p>The problem I was given to solve is &quot;The number of students who will take the exam is entered from the keyboard, and then the IDs of all the students who will take the exam are entered. The program should divide the students into three groups: students with IDs ending in the digits 0, 1, and 2, students with IDs ending in the digits 3, 4, 5, and students with IDs ending in the digits 6, 7, 8, 9 .The program should print the IDs for each group, in the same order as they were entered. The maximum number of students that can be entered is 1000.&quot;.</p> <p>The code that I can come up with is</p> <pre><code>#include &lt;stdio.h&gt; int main() { int n,br,gr1,gr2,gr3; scanf(&quot;%d&quot;,&amp;n); for (int i = 0; i &lt; n; ++i) { scanf(&quot;%d&quot;, &amp;br); if (br % 10 == 0 || br % 10 == 1 || br % 10 == 2) { gr1 = br; } else if (br % 10 == 3 || br % 10 == 4 || br % 10 == 5) { gr2 = br; } else if (br % 10 == 6 || br % 10 == 7 || br % 10 == 8 || br % 10 == 9) { gr3 = br; } } printf(&quot;Grupa 1\n%d\n&quot;,gr1); printf(&quot;Grupa 2\n%d\n&quot;,gr2); printf(&quot;Grupa 1\n%d\n&quot;,gr3); return 0; } </code></pre> <p>Instead of printing all the IDs and sorting them into groups it is only printing the last input number and group number. I am in no way an experienced programmer so I can't really tell what is wrong with the way I have written this or how to solve it. I would appreciate it if you can guide me through</p> <p>The output I am expecting is:</p> <pre class="lang-none prettyprint-override"><code>Grupa 1 20010 20581 19452 Grupa 2 20145 19873 19825 20653 Grupa 3 20147 20139 19458 </code></pre> <p>The output I am getting is</p> <pre class="lang-none prettyprint-override"><code>Grupa 1 19452 Grupa 2 20653 Grupa 3 19458 </code></pre>
[ { "answer_id": 74520507, "author": "Clement Hui", "author_id": 10675215, "author_profile": "https://Stackoverflow.com/users/10675215", "pm_score": 0, "selected": false, "text": "label = torch.full((b_size,), real_label, dtype=torch.float, device=device)\n output = netD(real_cpu).view(-1)\noutput = output.unsqueeze(1)\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20525204/" ]
74,513,537
<p>I have an array for the position of the particle in cartesian coordinates and velocity in 3D. So that position[0] represents the x component of the position and so on. I'm curious if there is a better way to write this code, maybe shorter, maybe faster.</p> <p>`</p> <pre><code>def update_position(self): self.position[0] = self.position[0] + self.velocity[0] * self.tick # x coordinate update self.position[1] = self.position[1] + self.velocity[1] * self.tick # y coordinate update self.position[2] = self.position[2] + self.velocity[2] * self.tick # z coordinate update ... </code></pre> <p>`</p>
[ { "answer_id": 74520507, "author": "Clement Hui", "author_id": 10675215, "author_profile": "https://Stackoverflow.com/users/10675215", "pm_score": 0, "selected": false, "text": "label = torch.full((b_size,), real_label, dtype=torch.float, device=device)\n output = netD(real_cpu).view(-1)\noutput = output.unsqueeze(1)\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2401559/" ]
74,513,546
<p>I'm having problem returning spesific amount of decimal numbers from this function, i would like it to get that info from &quot;dec&quot; argument, but i'm stuck with this right now. Edit: Made it work with the edited version bellow but isn't there a better way?</p> <pre><code>local function remove_decimal(t, dec) if type(dec) == &quot;number&quot; then for key, num in pairs(type(t) == &quot;table&quot; and t or {}) do if type(num) == &quot;number&quot; then local num_to_string = tostring(num) local mod, d = math.modf(num) -- find only decimal numbers local num_dec = num_to_string:sub(#tostring(mod) + (mod == 0 and num &lt; 0 and 3 or 2)) if dec &lt;= #num_dec then -- return amount of deciamls in the num by dec local r = d &lt; 0 and &quot;-0.&quot; or &quot;0.&quot; local r2 = r .. num_dec:sub(1, dec) t[key] = mod + tonumber(r2) end end end end return t end </code></pre> <p>By passing the function bellow i want a result like this:</p> <pre><code>result[1] &gt; 0.12 result[2] &gt; -0.12 result[3] &gt; 123.45 result[4] &gt; -1.23 local result = remove_decimal({0.123, -0.123, 123.456, -1.234}, 2) print(result[1]) print(result[2]) print(result[3]) print(result[4]) </code></pre> <p>I tried this but it seems to only work with one integer numbers and if number is 12.34 instead of 1.34 e.g, the decimal place will be removed and become 12.3. Using other methods</p> <pre><code>local d = dec + (num &lt; 0 and 2 or 1) local r = tonumber(num_to_string:sub(1, -#num_to_string - d)) or 0 </code></pre>
[ { "answer_id": 74514519, "author": "Robert", "author_id": 10953006, "author_profile": "https://Stackoverflow.com/users/10953006", "pm_score": 0, "selected": false, "text": "% %% function KeepDecimals (Number, DecimalCount)\n local FloatFormat = string.format(\"%%.%df\", DecimalCount)\n local String = string.format(FloatFormat, Number)\n return tonumber(String)\nend\n for Count = 1, 5 do\n print(KeepDecimals(1.123456789, Count))\nend\n 1.1\n1.12\n1.123\n1.1235\n1.12346\n keep_decimal function keep_decimal (Table, Count)\n local NewTable = {}\n local NewIndex = 1\n for Index = 1, #Table do\n NewTable[NewIndex] = KeepDecimal(Table[Index], Count)\n NewIndex = NewIndex + 1\n end\n return NewTable\nend\n Result = keep_decimal({0.123, -0.123, 123.456, -1.234}, 2)\n\nfor Index = 1, #Result do\n print(Result[Index])\nend\n 0.12\n-0.12\n123.46\n-1.23\n truncate function Truncate (Number, Digits)\n local Divider = Digits * 10\n local TruncatedValue = math.floor(Number * Divider) / Divider\n return TruncatedValue\nend\n > Truncate(123.456, 2)\n123.45\n" }, { "answer_id": 74530634, "author": "Zakk", "author_id": 16835308, "author_profile": "https://Stackoverflow.com/users/16835308", "pm_score": 2, "selected": true, "text": ". local function truncate(number, dec)\n local strnum = tostring(number)\n local i, j = string.find(strnum, '%.')\n \n if not i then\n return number\n end\n \n local strtrn = string.sub(strnum, 1, i+dec)\n return tonumber(strtrn)\nend\n print(truncate(123.456, 2))\nprint(truncate(1234567, 2))\n 123.45\n1234567\n local function truncate_all(t, dec)\n for key, value in pairs(t) do\n t[key] = truncate(t[key], dec)\n end\n return t\nend\n local result = truncate_all({0.123, -0.123, 123.456, -1.234}, 2)\n\nfor key, value in pairs(result) do\n print(key, value)\nend\n 1 0.12\n2 -0.12\n3 123.45\n4 -1.23\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8515925/" ]
74,513,552
<p>I currently need to dynamically load events in my database, however after numerous attempts, I still have not gotten it to work with React FullCalendar. Has anyone successfully gotten this to work?</p> <p>In this method, I am successfully able to get the events to load in the calendar, however, my API is being continuously being called. This led me to think it was because I do not have an arrow function in events</p> <pre><code>const [events, setEvents] = useState(0); const getEvents = async () =&gt; { //Get events from database const theEvents = await ... setEvents(theEvents); }; const returnEvent = () =&gt; { getEvents(); return events; } &lt;FullCalendar timeZone={'Europe/London'} now={DateTime.local().setZone('Europe/London').toISO()} ref={calendarRef} initialView=&quot;dayGridMonth&quot; height='100%' ... events = {returnEvent()} /&gt; </code></pre> <p>However, if I do</p> <pre><code>&lt;FullCalendar timeZone={'Europe/London'} now={DateTime.local().setZone('Europe/London').toISO()} ref={calendarRef} initialView=&quot;dayGridMonth&quot; height='100%' ... events = {() =&gt; returnEvent()} /&gt; </code></pre> <p>My API gets called continuously called and none of the events load on the calendar. I think if you do arrow functions on events, none of the events will load as when I do something like this, it does not even work.</p> <pre><code>const returnEvent = () =&gt; { let todayStr = new Date().toISOString().replace(/T.*$/, '') // YYYY-MM-DD of today const events = [ { id: createEventId(), title: 'All-day event', start: todayStr }, { id: createEventId(), title: 'Timed event', start: todayStr + 'T12:00:00' } ] // getEvents(); return events; } &lt;FullCalendar timeZone={'Europe/London'} now={DateTime.local().setZone('Europe/London').toISO()} ref={calendarRef} initialView=&quot;dayGridMonth&quot; height='100%' ... events = {() =&gt; returnEvent()} /&gt; </code></pre> <p>However, if I change <code>events = {returnEvent()}</code> it does work. Can someone please send an example or guide me on how to call events as a function in React FullCalendar?</p>
[ { "answer_id": 74513788, "author": "Willey Ohana", "author_id": 17002604, "author_profile": "https://Stackoverflow.com/users/17002604", "pm_score": 0, "selected": false, "text": "events = {returnEvent()} returnEvent() returnEvent() events events <FullCalendar> events = {events} <FullCalendar\n timeZone={'Europe/London'}\n now={DateTime.local().setZone('Europe/London').toISO()}\n ref={calendarRef}\n initialView=\"dayGridMonth\"\n height='100%'\n ...\n events={events}\n/>\n 0 useState const [events, setEvents] = useState(() => {\n const res = await fetch('/api/events');\n const data = await res.json();\n\n return data;\n})\n" }, { "answer_id": 74536506, "author": "Bryan Dellinger", "author_id": 2744722, "author_profile": "https://Stackoverflow.com/users/2744722", "pm_score": 1, "selected": false, "text": " <FullCalendar\n displayEventEnd\n initialView=\"dayGridMonth\"\n headerToolbar={{\n left: \"prev,next\",\n center: \"title\",\n right: \"dayGridMonth,timeGridWeek,timeGridDay\"\n }}\n plugins={[dayGridPlugin, timeGridPlugin]}\n events={(info, successCallback) => getEvents(info, successCallback)}\n />\n const getEvents = (info : any, successCallback: any) =>{\n getAcademicCalendarEvents(info.startStr, info.endStr).then((events) =>{\n successCallback(events)\n })\n }\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557704/" ]
74,513,611
<p>I am currently doing a python program to convert from image to hex string and the other way around. I need two functions, one that takes an image and returns a hex string that corresponds to the RGB values of each pixel, and another function that takes a hex string, two ints, and generates a visible image of that size corresponding to that hex string.</p> <p>I currently use imageio to get an RGB matrix from the image and then convert that to hex. I'm trying to optimize the Image to bytes part, as it takes around 2.5 seconds for a 442KB image of 918 x 575 pixels.</p> <p>How could I make it quicker?</p> <p>Here's the code:</p> <pre><code>def rgb2hex(rgb): &quot;&quot;&quot; convert a list or tuple of RGB values to a string in hex &quot;&quot;&quot; r,g,b = rgb return '{:02x}{:02x}{:02x}'.format(r, g, b) def arrayToString(array): &quot;&quot;&quot; convert an array to a string &quot;&quot;&quot; string = &quot;&quot; for element in array: string += str(element) return string def sliceStr(string,sliceLenght): &quot;&quot;&quot; slice a string in chunks of sliceLenght lenght &quot;&quot;&quot; string = str(string) array = np.array([string[i:i+sliceLenght] for i in range(0,len(string),sliceLenght)]) return array def hexToRGB(hexadecimal): &quot;&quot;&quot; convert a hex string to an array of RGB values &quot;&quot;&quot; h = hexadecimal.lstrip('#') if len(h)!=6: return return [int(h[i:i+2], 16) for i in (0, 2, 4)] def ImageToBytes(image): &quot;&quot;&quot; Image to convert from image to bytes &quot;&quot;&quot; dataToEncrypt =imageio.imread(image) if dataToEncrypt.shape[2] ==4: dataToEncrypt = np.delete(dataToEncrypt,3,2) originalRows, originalColumns,_ = dataToEncrypt.shape #converting rgb to hex hexVal = np.apply_along_axis(rgb2hex, 2, dataToEncrypt) hexVal = np.apply_along_axis(arrayToString, 1, hexVal) hexVal = str(np.apply_along_axis(arrayToString, 0, hexVal)) byteImage = bytes.fromhex(hexVal) return (byteImage, [originalRows,originalColumns]) </code></pre>
[ { "answer_id": 74513703, "author": "wrbp", "author_id": 16662333, "author_profile": "https://Stackoverflow.com/users/16662333", "pm_score": 1, "selected": false, "text": "def ImageToBytes2(image):\n \"\"\"\n Image to convert from image to bytes\n \"\"\"\n dataToEncrypt =imageio.imread(image)\n\n if dataToEncrypt.shape[2] ==4:\n dataToEncrypt = np.delete(dataToEncrypt,3,2)\n\n originalRows, originalColumns,_ = dataToEncrypt.shape\n\n dataToEncrypt = dataToEncrypt.reshape(1,originalRows*originalColumns*3)\n\n #converting rgb to hex\n byteImage = bytes(dataToEncrypt)\n\n return (byteImage, [originalRows,originalColumns])\n" }, { "answer_id": 74513733, "author": "Till Hoffmann", "author_id": 1150961, "author_profile": "https://Stackoverflow.com/users/1150961", "pm_score": 3, "selected": true, "text": "tobytes image = imageio.imread(filename)\n# Drop the alpha channel.\nif image.shape[2] == 4:\n image = image[..., :3]\n# Convert to bytes directly.\nbyte_image = image.tobytes()\n uint8 imread" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13090510/" ]
74,513,759
<p>This is my table</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> <th>Column B</th> <th>Column C</th> <th>Column D</th> </tr> </thead> <tbody> <tr> <td>Cell 1</td> <td>Cell 2</td> <td>Cell 1</td> <td>Cell 2</td> </tr> <tr> <td>Cell 3</td> <td>Cell 4</td> <td>Cell 3</td> <td>Cell 4</td> </tr> </tbody> </table> </div> <p>Where Column A is the primary key and Column D is a TINYINT column. Column D contains values from 0 to 3 only. (0,1,2,3) I want to partition this table based on column D.</p> <p>I tried this code to partition the table.</p> <p><code>ALTER TABLE to_be_partitioned PARTITION BY HASH(Column D) PARTITIONS 4; </code></p> <blockquote> <p>It says A PRIMARY KEY must include all columns in the table's partitioning function</p> </blockquote> <p>How can I partition this table based on Column D values please???</p> <p>I tried using KEY partition type and it also gives an error.</p> <p>I'm expecting something like this.</p> <p>P0 contains all records with column D value of 0</p> <p>P1 contains all records with column D value of 1</p> <p>P2 contains all records with column D value of 2</p> <p>P3 contains all records with column D value of 3</p>
[ { "answer_id": 74514670, "author": "JHH", "author_id": 20127235, "author_profile": "https://Stackoverflow.com/users/20127235", "pm_score": 2, "selected": false, "text": "SQL Error [1503] [HY000] create table to_be_partitioned (\n col_a int,\n col_b int,\n col_c int,\n col_d int,\n primary key (col_a, col_d))\npartition by list (col_d) (\n partition p0 values in (0),\n partition p1 values in (1),\n partition p2 values in (2),\n partition p3 values in (3)\n);\n create table to_be_partitioned (\n col_a int,\n col_b int,\n col_c int,\n col_d int,\n primary key (col_d, col_a))\npartition by list (col_d) (\n partition p0 values in (0),\n partition p1 values in (1),\n partition p2 values in (2),\n partition p3 values in (3)\n);\n col_a col_a col_a col_d -- answer per comment\ncreate table to_be_partitioned (\n col_a int auto_increment,\n col_b int,\n col_c int,\n col_d int,\n primary key (col_a, col_d))\npartition by list (col_d) (\n partition p0 values in (0),\n partition p1 values in (1),\n partition p2 values in (2),\n partition p3 values in (3)\n);\n\ninsert into to_be_partitioned (col_b, col_c, col_d) values (1, 1, last_insert_id() mod 4);\ninsert into to_be_partitioned (col_b, col_c, col_d) values (2, 1, last_insert_id() mod 4);\ninsert into to_be_partitioned (col_b, col_c, col_d) values (3, 1, last_insert_id() mod 4);\ninsert into to_be_partitioned (col_b, col_c, col_d) values (4, 1, last_insert_id() mod 4);\ninsert into to_be_partitioned (col_b, col_c, col_d) values (5, 1, last_insert_id() mod 4);\ninsert into to_be_partitioned (col_b, col_c, col_d) values (6, 1, last_insert_id() mod 4);\ninsert into to_be_partitioned (col_b, col_c, col_d) values (7, 1, last_insert_id() mod 4);\n select * from to_be_partitioned order by col_a;\n\ncol_a|col_b|col_c|col_d|\n-----+-----+-----+-----+\n 1| 1| 1| 1|\n 2| 2| 1| 1|\n 3| 3| 1| 2|\n 4| 4| 1| 3|\n 5| 5| 1| 0|\n 6| 6| 1| 1|\n 7| 7| 1| 2|\n\n-- from a partition p2\nselect * from to_be_partitioned partition(p2);\n\ncol_a|col_b|col_c|col_d|\n-----+-----+-----+-----+\n 3| 3| 1| 2|\n 7| 7| 1| 2|\n " }, { "answer_id": 74515455, "author": "Akina", "author_id": 10138734, "author_profile": "https://Stackoverflow.com/users/10138734", "pm_score": 3, "selected": true, "text": "CREATE TABLE main (\n colA INT NOT NULL, -- should be AI PK\n colB INT,\n colC TINYINT CHECK (colC BETWEEN 0 AND 3)\n)\n PARTITION BY LIST (colC) (\n PARTITION zero VALUES IN (0),\n PARTITION one VALUES IN (1),\n PARTITION two VALUES IN (2),\n PARTITION three VALUES IN (3)\n);\n CREATE TABLE main_ai_pk (\n colA INT AUTO_INCREMENT PRIMARY KEY\n);\n colA CREATE TRIGGER tr_bi_main_set_pk\nBEFORE INSERT ON main\nFOR EACH ROW\nBEGIN\n INSERT INTO main_ai_pk VALUES (DEFAULT); -- generate new AI value\n SET NEW.colA = LAST_INSERT_ID(); -- assign it to \"PK\" in main table\n DELETE FROM main_ai_pk WHERE colA < NEW.colA; -- clear excess rows\nEND\n colA INSERT INTO main (colB, colC) VALUES (11,1), (22,2), (111,1);\nINSERT INTO main VALUES (NULL,33,3), (3333,333,3);\n SELECT * FROM main ORDER BY colA;\nSELECT * FROM main_ai_pk;\nSELECT PARTITION_NAME, TABLE_ROWS\n FROM INFORMATION_SCHEMA.PARTITIONS\n WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'main'\n ORDER BY PARTITION_ORDINAL_POSITION;\n" }, { "answer_id": 74537330, "author": "Rick James", "author_id": 1766831, "author_profile": "https://Stackoverflow.com/users/1766831", "pm_score": 1, "selected": false, "text": "SELECT WHERE colc = ...\n AND cola = ...\n INDEX(colc, cola)\n PARTITION BY ...(colc)" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6579409/" ]
74,513,764
<p>anchor tag is not being styled Here's the particular code I'm having trouble with</p> <pre><code>HTML &lt;a href=&quot;tel:9149417020&quot; class=&quot;tele&quot;&gt;914-941-7020&lt;/a&gt; CSS .tele a{ color: #2bab0d; text-decoration: none; font: 1em sans-serif; } </code></pre> <pre><code> I expected it to be styled but for some reason no changes are made </code></pre>
[ { "answer_id": 74514040, "author": "K JOHN", "author_id": 10031834, "author_profile": "https://Stackoverflow.com/users/10031834", "pm_score": -1, "selected": false, "text": "a{} .tele{} a.tele{}" }, { "answer_id": 74514094, "author": "Hussain", "author_id": 20041730, "author_profile": "https://Stackoverflow.com/users/20041730", "pm_score": 0, "selected": false, "text": "<a href=\"tel:9149417020\" class=\"tele\">914-941-7020</a>\n\na.tele{\n color: #2bab0d;\n text-decoration: none;\n font: 1em sans-serif;\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19936555/" ]
74,513,785
<p>I recently started learning React. I wanted to make my first app and have done the following.</p> <ol> <li>Created a project folder</li> <li>Ran npx create-react-app App.js</li> <li>Ran npm start</li> </ol> <p>My src/App.js is as follows:</p> <pre><code>import React from &quot;react&quot;; import ReactDOM from &quot;react-dom/client&quot;; const navbar = ( &lt;nav&gt; &lt;h1&gt;Wiggly's&lt;/h1&gt; &lt;ul&gt; &lt;li&gt;Menu&lt;/li&gt; &lt;li&gt;About&lt;/li&gt; &lt;li&gt;Contact&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; ); const root = ReactDOM.createRoot(document.getElementById(&quot;root&quot;)); root.render(navbar); </code></pre> <p>My index.html is as follows:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt; &lt;title&gt;HTML 5 Boilerplate&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;div id=&quot;root&quot;&gt; &lt;/div&gt; &lt;script src=&quot;App.js&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>When I refresh my localhost I still see the react splash screen.</p> <p>I've looked everywhere on the forums and haven't been able to figure out what I'm doing wrong. It's my first time using react so I'm likely making a simple error. I appreciate anyone's help.</p>
[ { "answer_id": 74513815, "author": "G_S", "author_id": 1594337, "author_profile": "https://Stackoverflow.com/users/1594337", "pm_score": 0, "selected": false, "text": "const navbar = ( const Navbar = (" }, { "answer_id": 74513869, "author": "Dan Philip Bejoy", "author_id": 6412847, "author_profile": "https://Stackoverflow.com/users/6412847", "pm_score": 3, "selected": true, "text": "root.render() index.js root.render index.js App App.js" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19996942/" ]
74,513,805
<p>The default <code>std::allocator</code> class is stateless in C++. This means any instance of an <code>std::allocator</code> can deallocate memory allocated by another <code>std::allocator</code> instance. What is then the point of having instances of allocators to allocate memory?</p> <p>For instance, why is memory allocated like this:</p> <pre><code>allocator&lt;T&gt; alloc, alloc2; T* buffer = alloc.allocate(42); alloc2.deallocate(buffer); </code></pre> <p>When functions could easily do that same job:</p> <pre><code>T* buffer = allocate(42); deallocate(buffer); </code></pre>
[ { "answer_id": 74513839, "author": "Nicol Bolas", "author_id": 734069, "author_profile": "https://Stackoverflow.com/users/734069", "pm_score": 1, "selected": false, "text": "allocator std::allocator std::allocator A std::allocator" }, { "answer_id": 74513888, "author": "user17732522", "author_id": 17732522, "author_profile": "https://Stackoverflow.com/users/17732522", "pm_score": 4, "selected": true, "text": "std::allocator new delete std::allocator std::allocator std::allocator_traits std::allocator_traits" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19333949/" ]
74,513,836
<p>I have a website that creates a session when a user logs in, but the sessions are just the email &amp; username, which works fine for customers that create an account, but I want to generate a unique session key for users that <em>dont</em> want to signup/login, the reason is because currently if a user is not logged in and they add an item to the checkout page, the item will be visible to every customer who is not logged in, so I would like to create a session based on a unique string so that there are no conflicts for customers who dont want to signup/sign-in.</p> <p>The problem is that when I redirect to the test.php page it cant find the session key.</p> <p>Here is my session file that generates the unique key..</p> <pre><code>&lt;?php session_start(); $_SESSION['sessionKey'] = $randomString; if(!isset($_SESSION['sessionKey'])) { function generateRandomString($length = 64) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i &lt; $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } echo generateRandomString(); } ?&gt; &lt;br&gt;&lt;br&gt; &lt;a href=&quot;test.php&quot;&gt;Go to test page&lt;/a&gt; </code></pre> <p>and then my test.php page...</p> <pre><code>&lt;?php session_start(); if(!isset($_SESSION['sessionKey'])) { echo &quot;cant find unique session key&quot;; } else { echo $_SESSION['sessionKey']; } ?&gt; </code></pre>
[ { "answer_id": 74513839, "author": "Nicol Bolas", "author_id": 734069, "author_profile": "https://Stackoverflow.com/users/734069", "pm_score": 1, "selected": false, "text": "allocator std::allocator std::allocator A std::allocator" }, { "answer_id": 74513888, "author": "user17732522", "author_id": 17732522, "author_profile": "https://Stackoverflow.com/users/17732522", "pm_score": 4, "selected": true, "text": "std::allocator new delete std::allocator std::allocator std::allocator_traits std::allocator_traits" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19421765/" ]
74,513,873
<p>Hello guys im new in flutter and i need help with my app, to put a button under an image in my app main menu,</p> <p>here is my code so far i build based on <a href="https://docs.flutter.dev/development/ui/layout/tutorial" rel="nofollow noreferrer">https://docs.flutter.dev/development/ui/layout/tutorial</a></p> <pre><code>import 'package:flutter/material.dart'; import 'package:get/get_core/src/get_main.dart'; import 'package:get/get_navigation/get_navigation.dart'; import 'Reminder/ui/home_reminder.dart'; import 'Reminder/ui/widgets/button.dart'; void main() { // debugPaintSizeEnabled = true; runApp(const HomePage()); } class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar( title: const Text('Medicine Reminder App'), ), body: Stack( children: [ Image.asset( 'images/MenuImg.jpg', width: 600, height: 200, fit: BoxFit.cover, ), ], ), ), ); } } </code></pre> <p>what i wanna do is put a button to navigate to a different page.</p> <p>Here is a little illustration where i want to put my button</p> <p><img src="https://i.stack.imgur.com/fTmSx.png" alt="Here is a little illustration where i want to put my button, thanks" /></p>
[ { "answer_id": 74513909, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 1, "selected": false, "text": "Column MainAxisAlignment.spaceBetween import 'package:flutter/material.dart';\nimport 'package:get/get_core/src/get_main.dart';\nimport 'package:get/get_navigation/get_navigation.dart';\nimport 'Reminder/ui/home_reminder.dart';\nimport 'Reminder/ui/widgets/button.dart';\n\nvoid main() {\n // debugPaintSizeEnabled = true;\n runApp(const HomePage());\n}\n\nclass HomePage extends StatelessWidget {\n const HomePage({super.key});\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n debugShowCheckedModeBanner: false,\n home: Scaffold(\n appBar: AppBar(\n title: const Text('Medicine Reminder App'),\n ),\n body: Column(\n children: [\n Stack(\n children: [\n Image.asset(\n 'images/MenuImg.jpg',\n width: 600,\n height: 200,\n fit: BoxFit.cover,\n ),\n ],\n ),\n Row(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n ElevatedButton(\n child: Text('btn 1'),\n onPressed: () {},\n ),\n ElevatedButton(\n child: Text('btn 2'),\n onPressed: () {},\n ),\n ElevatedButton(\n child: Text('btn 3'),\n onPressed: () {},\n ),\n ],\n ),\n ],\n ),\n ),\n );\n }\n}\n" }, { "answer_id": 74513939, "author": "BLKKKBVSIK", "author_id": 11550065, "author_profile": "https://Stackoverflow.com/users/11550065", "pm_score": 3, "selected": true, "text": "Column Scaffold import 'package:flutter/material.dart';\n\nvoid main() {\n // debugPaintSizeEnabled = true;\n runApp(const HomePage());\n}\n\nclass HomePage extends StatelessWidget {\n const HomePage({super.key});\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n debugShowCheckedModeBanner: false,\n home: Scaffold(\n appBar: AppBar(\n title: const Text('Medicine Reminder App'),\n ),\n body: Column(children: [\n Stack(\n children: [\n Image.network(\n 'https://i.imgur.com/9ZOaH1m.jpeg',\n width: 600,\n height: 200,\n fit: BoxFit.cover,\n ),\n ],\n ),\n Row(\n mainAxisAlignment: MainAxisAlignment.spaceAround,\n children: [\n TextButton(\n style: ButtonStyle(\n backgroundColor: MaterialStateProperty.all(Colors.black)),\n onPressed: () {},\n child: Text(\"Button1\"),\n ),\n TextButton(\n style: ButtonStyle(\n backgroundColor: MaterialStateProperty.all(Colors.black)),\n onPressed: () {},\n child: Text(\"Button2\"),\n ),\n TextButton(\n style: ButtonStyle(\n backgroundColor: MaterialStateProperty.all(Colors.black)),\n onPressed: () {},\n child: Text(\"Button3\"),\n ),\n ],\n )\n ]),\n ),\n );\n }\n}\n" }, { "answer_id": 74513950, "author": "pmatatias", "author_id": 12838877, "author_profile": "https://Stackoverflow.com/users/12838877", "pm_score": 2, "selected": false, "text": "Stack body: Column(\n children: [\n Image.asset(\n 'images/MenuImg.jpg',\n width: 600,\n height: 200,\n fit: BoxFit.cover,\n ),\n /// your button is here:\n Row(\n children:[\n ElevetedButton(),// btn 1\n ElevetedButton(),// btn 2\n ... \n ],\n),\n" }, { "answer_id": 74528487, "author": "My Car", "author_id": 16124033, "author_profile": "https://Stackoverflow.com/users/16124033", "pm_score": 1, "selected": false, "text": "import 'package:flutter/material.dart';\nimport 'package:get/get_core/src/get_main.dart';\nimport 'package:get/get_navigation/get_navigation.dart';\nimport 'Reminder/ui/home_reminder.dart';\nimport 'Reminder/ui/widgets/button.dart';\n\nvoid main() {\n // debugPaintSizeEnabled = true;\n runApp(const HomePage());\n}\n\nclass HomePage extends StatelessWidget {\n const HomePage({super.key});\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n debugShowCheckedModeBanner: false,\n home: Scaffold(\n appBar: AppBar(\n title: const Text('Medicine Reminder App'),\n ),\n body: Column(\n children: [\n Stack(\n children: [\n Image.asset(\n 'images/MenuImg.jpg',\n width: 600,\n height: 200,\n fit: BoxFit.cover,\n ),\n ],\n ),\n const SizedBox(height: 10.0),\n Row(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n ElevatedButton(\n child: const Text('Button 1'),\n onPressed: () {\n Navigator.push(\n context,\n MaterialPageRoute(\n builder: (context) => const Scaffold(\n body: body,\n ),\n ),\n );\n },\n ),\n ElevatedButton(\n child: const Text('Button 2'),\n onPressed: () {\n Navigator.push(\n context,\n MaterialPageRoute(\n builder: (context) => const Scaffold(\n body: body,\n ),\n ),\n );\n },\n ),\n ElevatedButton(\n child: const Text('Button 3'),\n onPressed: () {\n Navigator.push(\n context,\n MaterialPageRoute(\n builder: (context) => const Scaffold(\n body: body,\n ),\n ),\n );\n },\n ),\n ],\n ),\n ],\n ),\n ),\n );\n }\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20229067/" ]
74,513,877
<p>How to remove comma at the end of an array? Need output: 1,2,3,4,5 and not 1,2,3,4, <strong>5,</strong></p> <p>I know I can use implode, but is there another way?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$massive = [1, 2, 3, 4, 5]; foreach($massive as $items){ echo $items. ', '; }</code></pre> </div> </div> </p>
[ { "answer_id": 74513893, "author": "vivek modi", "author_id": 5790791, "author_profile": "https://Stackoverflow.com/users/5790791", "pm_score": 2, "selected": true, "text": "<?php\n$massive = [1, 2, 3, 4, 5];\n$str=\"\";\n \nforeach($massive as $items){\n $str .= $items.\",\";\n}\necho substr($str,0,-1)\n?>\n" }, { "answer_id": 74514411, "author": "ryantxr", "author_id": 6032547, "author_profile": "https://Stackoverflow.com/users/6032547", "pm_score": 0, "selected": false, "text": "$arr = [100, 200, 300, 400, 500, 600];\n$out = null;\nforeach ( $arr as $a ) {\n // The trick is to output the comma before each element\n // except the first one.\n if ( ! empty($out) ) {\n $out .= ',';\n }\n $out .= $a;\n}\n// Now I can output the string\n $arr = [100, 200, 300, 400, 500, 600];\n$first = true;\nforeach ( $arr as $a ) {\n // The trick is to output the comma before each element\n // except the first one.\n if ( $first ) {\n echo ',';\n $first = false;\n }\n echo $a;\n}\n foreach ( $arr as $a ) {\n // see if it is the first element\n if ( $a == first($arr) ) {\n echo ',';\n $first = false;\n }\n echo $a;\n}\n foreach ( $arr as $a ) {\n echo $a;\n if ( last($arr) != $a ) {\n echo ',';\n }\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20289598/" ]
74,513,925
<p>I would like to find duplicate parameters and then consider the one which has value and eliminate the duplicate one which does not contain value.</p> <p>Scenario 1 - Suppose I have parameters like <code>firstname, lastname, firstname,middlename</code> and the value is like <code>firstname=</code>, <code>lastname=con</code>, <code>firstname=abc</code>, <code>middlename=</code></p> <p>And decryptedRequest is something like</p> <p><code>lastname=con&amp;firstname=&amp;firstname=abc&amp;middlename=</code></p> <p>Scenario 2 - Suppose I have parameters like <code>firstname, lastname, firstname,middlename</code> and the value is like <code>firstname=test</code>,<code>lastname=con</code>, <code>firstname=abc</code>,<code>middlename=</code></p> <p>decryptedRequest is something like</p> <p><code>lastname=con&amp;firstname=test&amp;firstname=abc&amp;middlename=</code></p> <pre><code> private NameValueCollection parameters; foreach (var parameter in parameters) { if (IsDuplicatedParam(parameter.ToString(), decryptedRequest)) { LogManager.Publish(LogTypes.Exception | LogTypes.Error, &quot;Duplicate parameter &quot; + parameter + &quot; received in request : &quot; + decryptedRequest); return false; } } private bool IsDuplicatedParam(string parameter, string decryptedRequest) { var requestWithoutParameter = decryptedRequest.Replace(parameter + &quot;=&quot;, &quot;&quot;); if (decryptedRequest.Length - requestWithoutParameter.Length &gt; parameter.Length + 1) return true; return false; } </code></pre> <p>In my first scenario, out of duplicate parameter, it should only return that has value and ignore the duplicate with blank.</p> <ul> <li>Expected output should be, <code>lastname=con</code>, <code>firstname=abc</code>,<code>middlename=</code></li> </ul> <p>In my second scenario, both duplicate parameters have values so ignore and return and log an error.</p> <ul> <li>Expected output should be, <code>Bad request</code></li> </ul> <p>But I would like to combine all these logic in my <code>IsDuplicatedParam</code> method.</p> <p>if there are duplicate parameters and those both parameters have values then return false. But, If either one of the parameter has value then return true. In my code, <code>IsDuplicatedParam()</code> always return true. So I would like to rewrite my <code>IsDuplicatedParam</code> in such a way that it handles my scenarios.</p>
[ { "answer_id": 74513893, "author": "vivek modi", "author_id": 5790791, "author_profile": "https://Stackoverflow.com/users/5790791", "pm_score": 2, "selected": true, "text": "<?php\n$massive = [1, 2, 3, 4, 5];\n$str=\"\";\n \nforeach($massive as $items){\n $str .= $items.\",\";\n}\necho substr($str,0,-1)\n?>\n" }, { "answer_id": 74514411, "author": "ryantxr", "author_id": 6032547, "author_profile": "https://Stackoverflow.com/users/6032547", "pm_score": 0, "selected": false, "text": "$arr = [100, 200, 300, 400, 500, 600];\n$out = null;\nforeach ( $arr as $a ) {\n // The trick is to output the comma before each element\n // except the first one.\n if ( ! empty($out) ) {\n $out .= ',';\n }\n $out .= $a;\n}\n// Now I can output the string\n $arr = [100, 200, 300, 400, 500, 600];\n$first = true;\nforeach ( $arr as $a ) {\n // The trick is to output the comma before each element\n // except the first one.\n if ( $first ) {\n echo ',';\n $first = false;\n }\n echo $a;\n}\n foreach ( $arr as $a ) {\n // see if it is the first element\n if ( $a == first($arr) ) {\n echo ',';\n $first = false;\n }\n echo $a;\n}\n foreach ( $arr as $a ) {\n echo $a;\n if ( last($arr) != $a ) {\n echo ',';\n }\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20505175/" ]
74,513,931
<p><a href="https://codesandbox.io/s/getattribute-question-h0ds37" rel="nofollow noreferrer">This</a> is the test I made in a sandbox.</p> <p>If you run the code and click the 2 buttons like this: first, back, first, back ... a few times you will see at the console that the name attribute of the target event becomes null even if it was not null the first time I pressed that button.</p> <p>I also attached an image with some comments in the lower right corner to clarify the behaviour.</p> <p>This is the code:</p> <pre><code> handleSearchChange(event) { const target = event.target; const name = target.getAttribute(&quot;name&quot;); console.log(&quot;Test name &quot; + name + &quot;\n&quot;); } render() { return ( &lt;div&gt; &lt;div style={{ height: &quot;30px&quot;, width: &quot;30px&quot; }}&gt; &lt;FirstSVG name=&quot;first_page&quot; onClick={this.handleSearchChange} /&gt; &lt;/div&gt; &lt;div style={{ height: &quot;30px&quot;, width: &quot;30px&quot; }}&gt; &lt;BackSVG name=&quot;back_page&quot; onClick={this.handleSearchChange} /&gt; &lt;/div&gt; &lt;/div&gt; ); } </code></pre> <p><a href="https://i.stack.imgur.com/JQOzI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JQOzI.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74513893, "author": "vivek modi", "author_id": 5790791, "author_profile": "https://Stackoverflow.com/users/5790791", "pm_score": 2, "selected": true, "text": "<?php\n$massive = [1, 2, 3, 4, 5];\n$str=\"\";\n \nforeach($massive as $items){\n $str .= $items.\",\";\n}\necho substr($str,0,-1)\n?>\n" }, { "answer_id": 74514411, "author": "ryantxr", "author_id": 6032547, "author_profile": "https://Stackoverflow.com/users/6032547", "pm_score": 0, "selected": false, "text": "$arr = [100, 200, 300, 400, 500, 600];\n$out = null;\nforeach ( $arr as $a ) {\n // The trick is to output the comma before each element\n // except the first one.\n if ( ! empty($out) ) {\n $out .= ',';\n }\n $out .= $a;\n}\n// Now I can output the string\n $arr = [100, 200, 300, 400, 500, 600];\n$first = true;\nforeach ( $arr as $a ) {\n // The trick is to output the comma before each element\n // except the first one.\n if ( $first ) {\n echo ',';\n $first = false;\n }\n echo $a;\n}\n foreach ( $arr as $a ) {\n // see if it is the first element\n if ( $a == first($arr) ) {\n echo ',';\n $first = false;\n }\n echo $a;\n}\n foreach ( $arr as $a ) {\n echo $a;\n if ( last($arr) != $a ) {\n echo ',';\n }\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1510155/" ]
74,513,956
<p>I would like to get the amount of time the process took to fully complete. I have this code:<br></p> <pre class="lang-js prettyprint-override"><code>console.log(`Ran ${ran} equations in ${console.timeEnd()}`) </code></pre> <p>but I don't get my expected output, which is:</p> <pre><code>Ran X equations in 33.099ms // eg </code></pre> <p>instead I get</p> <pre><code>default: 33.099ms Ran X Equations in undefined </code></pre> <p>Note that I didn't give my <code>console.time()</code> a label. <br> How can I achieve my expected output?</p>
[ { "answer_id": 74513893, "author": "vivek modi", "author_id": 5790791, "author_profile": "https://Stackoverflow.com/users/5790791", "pm_score": 2, "selected": true, "text": "<?php\n$massive = [1, 2, 3, 4, 5];\n$str=\"\";\n \nforeach($massive as $items){\n $str .= $items.\",\";\n}\necho substr($str,0,-1)\n?>\n" }, { "answer_id": 74514411, "author": "ryantxr", "author_id": 6032547, "author_profile": "https://Stackoverflow.com/users/6032547", "pm_score": 0, "selected": false, "text": "$arr = [100, 200, 300, 400, 500, 600];\n$out = null;\nforeach ( $arr as $a ) {\n // The trick is to output the comma before each element\n // except the first one.\n if ( ! empty($out) ) {\n $out .= ',';\n }\n $out .= $a;\n}\n// Now I can output the string\n $arr = [100, 200, 300, 400, 500, 600];\n$first = true;\nforeach ( $arr as $a ) {\n // The trick is to output the comma before each element\n // except the first one.\n if ( $first ) {\n echo ',';\n $first = false;\n }\n echo $a;\n}\n foreach ( $arr as $a ) {\n // see if it is the first element\n if ( $a == first($arr) ) {\n echo ',';\n $first = false;\n }\n echo $a;\n}\n foreach ( $arr as $a ) {\n echo $a;\n if ( last($arr) != $a ) {\n echo ',';\n }\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20278223/" ]
74,513,958
<p>Also what's the minimum space that a program can occupy in memory?</p> <p>I know that every register in 8086 have a maximum capacity of 16 bits</p>
[ { "answer_id": 74513893, "author": "vivek modi", "author_id": 5790791, "author_profile": "https://Stackoverflow.com/users/5790791", "pm_score": 2, "selected": true, "text": "<?php\n$massive = [1, 2, 3, 4, 5];\n$str=\"\";\n \nforeach($massive as $items){\n $str .= $items.\",\";\n}\necho substr($str,0,-1)\n?>\n" }, { "answer_id": 74514411, "author": "ryantxr", "author_id": 6032547, "author_profile": "https://Stackoverflow.com/users/6032547", "pm_score": 0, "selected": false, "text": "$arr = [100, 200, 300, 400, 500, 600];\n$out = null;\nforeach ( $arr as $a ) {\n // The trick is to output the comma before each element\n // except the first one.\n if ( ! empty($out) ) {\n $out .= ',';\n }\n $out .= $a;\n}\n// Now I can output the string\n $arr = [100, 200, 300, 400, 500, 600];\n$first = true;\nforeach ( $arr as $a ) {\n // The trick is to output the comma before each element\n // except the first one.\n if ( $first ) {\n echo ',';\n $first = false;\n }\n echo $a;\n}\n foreach ( $arr as $a ) {\n // see if it is the first element\n if ( $a == first($arr) ) {\n echo ',';\n $first = false;\n }\n echo $a;\n}\n foreach ( $arr as $a ) {\n echo $a;\n if ( last($arr) != $a ) {\n echo ',';\n }\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13613804/" ]
74,513,972
<p>I have been tasked with taking the following data and creating two permanent data sets from it. One of these permanent data sets is supposed to contain the average of the &quot;value&quot; column for each group (meaning there should only be four rows in the end, with a new column that represents the average of respective values for A, B, C, and D). Averages should exclude missing values, meaning that if category A has a missing value, it should be divided by 3, not 4. The second permanent data set needs to be the one row with the highest overall value in the &quot;value&quot; column (in this case, the row with D 09JUL2021 951 should be the only row exported). I am having a tough time extracting that single row for the second data set. If you know of a way to perform these operations simultaneously, please let me know. Thank you for your time!</p> <p>Example data:</p> <pre><code>data work.have; input type $ date DATE9. value; datalines; A 08JUL2021 . A 09JUL2021 20 A 20JUL2021 55 A 20JUL2021 2 B 02JUL2021 9 B 22JUL2021 6 B 04JUL2021 8 B 07JUL2021 406 C 01JUL2021 215 C 28JUL2021 63 C 30JUL2021 78 C 21JUL2021 80 D 18JUL2021 951 D 09JUL2021 . D 14JUL2021 54 D 08JUL2021 73 ; </code></pre> <p>Here is what I tried:</p> <pre><code>data mylib.data1(keep=type date value value_avg) mylib.data2; set work.have; by type; if value ne . then NotMissing=1; else NotMissing=0; if first.type then call missing(of value_avg); value_avg+value; if first.type then call missing(of num_per_cat); num_per_cat+NotMissing; Avg=divide((value_avg+value),(num_per_cat+NotMissing)); if last.type then output mylib.data1; run; </code></pre> <p>This was successful for me with calculating averages, but I have no idea how to extract the row with the highest value in the &quot;value&quot; column to a second data set.</p>
[ { "answer_id": 74513893, "author": "vivek modi", "author_id": 5790791, "author_profile": "https://Stackoverflow.com/users/5790791", "pm_score": 2, "selected": true, "text": "<?php\n$massive = [1, 2, 3, 4, 5];\n$str=\"\";\n \nforeach($massive as $items){\n $str .= $items.\",\";\n}\necho substr($str,0,-1)\n?>\n" }, { "answer_id": 74514411, "author": "ryantxr", "author_id": 6032547, "author_profile": "https://Stackoverflow.com/users/6032547", "pm_score": 0, "selected": false, "text": "$arr = [100, 200, 300, 400, 500, 600];\n$out = null;\nforeach ( $arr as $a ) {\n // The trick is to output the comma before each element\n // except the first one.\n if ( ! empty($out) ) {\n $out .= ',';\n }\n $out .= $a;\n}\n// Now I can output the string\n $arr = [100, 200, 300, 400, 500, 600];\n$first = true;\nforeach ( $arr as $a ) {\n // The trick is to output the comma before each element\n // except the first one.\n if ( $first ) {\n echo ',';\n $first = false;\n }\n echo $a;\n}\n foreach ( $arr as $a ) {\n // see if it is the first element\n if ( $a == first($arr) ) {\n echo ',';\n $first = false;\n }\n echo $a;\n}\n foreach ( $arr as $a ) {\n echo $a;\n if ( last($arr) != $a ) {\n echo ',';\n }\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74513972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16584840/" ]
74,514,019
<p>I'm new to flutter and I want to implement the <a href="https://pub.dev/documentation/flutter_hooks/latest/flutter_hooks/useEffect.html" rel="nofollow noreferrer"><code>useEffect</code></a> hook.</p> <p>Here is my widget:</p> <pre class="lang-dart prettyprint-override"><code>import 'dart:developer'; import 'package:flutter/material.dart'; class MarketRunnerChart extends StatefulWidget { const MarketRunnerChart({Key? key}) : super(key: key); @override State&lt;MarketRunnerChart&gt; createState() =&gt; _MarketRunnerChartState(); } class _MarketRunnerChartState extends State&lt;MarketRunnerChart&gt; { @override Widget build(BuildContext context) { useEffect(() { log('okok'); }, []); return Text(&quot;Some text&quot;); } } </code></pre> <p>But I got the error <code>The method 'useEffect' isn't defined for the type '_MarketRunnerChartState'.</code> <a href="https://i.stack.imgur.com/HLwZm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HLwZm.png" alt="enter image description here" /></a> When I remove the <code>useEffect</code> hook out of the <code>build</code> function and put it directly in the class I got error <code>'useEffect' must have a method body because '_MarketRunnerChartState' isn't abstract.</code> <a href="https://i.stack.imgur.com/ZCXeJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZCXeJ.png" alt="enter image description here" /></a> I'm used to work with React, but right now with flutter I can't figure out how to implement that hook.</p> <p>How am I supposed to do this ?</p>
[ { "answer_id": 74514056, "author": "manhtuan21", "author_id": 8921450, "author_profile": "https://Stackoverflow.com/users/8921450", "pm_score": 3, "selected": true, "text": "import 'package:flutter_hooks/flutter_hooks.dart';" }, { "answer_id": 74514099, "author": "Aditya Patil", "author_id": 10135062, "author_profile": "https://Stackoverflow.com/users/10135062", "pm_score": 2, "selected": false, "text": "import 'package:flutter_hooks/flutter_hooks.dart';\n\nclass MarketRunnerChart extends StatefulWidget {\n const MarketRunnerChart({Key? key}) : super(key: key);\n\n @override\n State<MarketRunnerChart> createState() => _MarketRunnerChartState();\n}\n\nclass _MarketRunnerChartState extends State<MarketRunnerChart> {\n useEffect(() {\n print('your log');\n }, []);\n\n @override\n Widget build(BuildContext context) {\n\n return Text(\"Some text\");\n }\n}\n" }, { "answer_id": 74514729, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 1, "selected": false, "text": "flutter_hooks HookWidget import 'package:flutter_hooks/flutter_hooks.dart';\n\nclass Example extends HookWidget {\n const Example({Key? key, })\n : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n //your variable/instance like to listen\n useEffect(() {\n log('okok');\n }, [...listenThisInstance...]);\n return Container();\n }\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74514019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6824121/" ]
74,514,041
<p>I am using asp.net core identity, but have deliberately separated the user specific information into another table which is linked via the application user class.</p> <p>How would I access this information from the login partial view?</p> <p>Other answers only define so far as to pull the information from the application user class. ie:</p> <pre><code>var personID = UserManager.GetUserAsync(User).Result.PersonID; </code></pre> <p>Where as I need something like:</p> <pre><code>var fullName = UserManager.GetUserAsync(User).Result.Person.FullName; </code></pre> <p>I'm guessing the code behind doesn't load the child table, as I get the the following error on the Person object:</p> <pre><code>'Object reference not set to an instance of an object.' </code></pre> <p>The rest of my code is below for reference.</p> <p>Application User:</p> <pre><code> public class ApplicationUser : IdentityUser { [ForeignKey(&quot;Person&quot;)] public int PersonID { get; set; } public virtual Person Person { get; set; } } </code></pre> <p>Person Class</p> <pre><code>public class Person { public int PersonID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } [NotMapped] [Display(Name = &quot;Full Name&quot;)] public string FullName { get { return LastName + &quot;, &quot; + FirstName; } } public string Address { get; set; } public ApplicationUser ApplicationUser { get; set; } } </code></pre> <p>Login Partial:</p> <pre><code>@using Microsoft.AspNetCore.Identity @using Models; @inject SignInManager&lt;ApplicationUser&gt; SignInManager @inject UserManager&lt;ApplicationUser&gt; UserManager &lt;ul class=&quot;navbar-nav&quot;&gt; @if (SignInManager.IsSignedIn(User)) { &lt;li class=&quot;nav-item&quot;&gt; &lt;a class=&quot;nav-link text-dark&quot; asp-area=&quot;Identity&quot; asp-page=&quot;/Account/Manage/Index&quot; title=&quot;Manage&quot;&gt;Hello @User.Identity?.Name!&lt;/a&gt; @{ var personResult = UserManager.GetUserAsync(User).Result; var fullName = personResult.Person.FullName; } &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;form class=&quot;form-inline&quot; asp-area=&quot;Identity&quot; asp-page=&quot;/Account/Logout&quot; asp-route-returnUrl=&quot;@Url.Page(&quot;/&quot;, new { area = &quot;&quot; })&quot; method=&quot;post&quot; &gt; &lt;button type=&quot;submit&quot; class=&quot;nav-link btn btn-link text-dark&quot;&gt;Logout&lt;/button&gt; &lt;/form&gt; &lt;/li&gt; } else { &lt;li class=&quot;nav-item&quot;&gt; &lt;a class=&quot;nav-link text-dark&quot; asp-area=&quot;Identity&quot; asp-page=&quot;/Account/Register&quot;&gt;Register&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a class=&quot;nav-link text-dark&quot; asp-area=&quot;Identity&quot; asp-page=&quot;/Account/Login&quot;&gt;Login&lt;/a&gt; &lt;/li&gt; } &lt;/ul&gt; </code></pre>
[ { "answer_id": 74514056, "author": "manhtuan21", "author_id": 8921450, "author_profile": "https://Stackoverflow.com/users/8921450", "pm_score": 3, "selected": true, "text": "import 'package:flutter_hooks/flutter_hooks.dart';" }, { "answer_id": 74514099, "author": "Aditya Patil", "author_id": 10135062, "author_profile": "https://Stackoverflow.com/users/10135062", "pm_score": 2, "selected": false, "text": "import 'package:flutter_hooks/flutter_hooks.dart';\n\nclass MarketRunnerChart extends StatefulWidget {\n const MarketRunnerChart({Key? key}) : super(key: key);\n\n @override\n State<MarketRunnerChart> createState() => _MarketRunnerChartState();\n}\n\nclass _MarketRunnerChartState extends State<MarketRunnerChart> {\n useEffect(() {\n print('your log');\n }, []);\n\n @override\n Widget build(BuildContext context) {\n\n return Text(\"Some text\");\n }\n}\n" }, { "answer_id": 74514729, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 1, "selected": false, "text": "flutter_hooks HookWidget import 'package:flutter_hooks/flutter_hooks.dart';\n\nclass Example extends HookWidget {\n const Example({Key? key, })\n : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n //your variable/instance like to listen\n useEffect(() {\n log('okok');\n }, [...listenThisInstance...]);\n return Container();\n }\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74514041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/795231/" ]
74,514,042
<p>For some reason this permissions line in my ban command is not working. Here is the error I get while trying to run my bot:</p> <pre><code>if(!message.guild.member(message.author).hasPermission(&quot;ADMINISTRATOR&quot;)) {return message.channel.send( ^ SyntaxError: Unexpected token '!' </code></pre> <p>Here is also my ban command:</p> <pre class="lang-js prettyprint-override"><code>const { MessageEmbed, Message } = require('discord.js'); const fs = require('fs'); const os = require('os'); const config = require('../config.json'); const CatLoggr = require('cat-loggr'); // Functions const log = new CatLoggr(); module.exports = { name: 'ban', // Command name (can be different from the file name) description: 'Bans a member.', // Command description displays in the help command if(!message.guild.member(message.author).hasPermission(&quot;ADMINISTRATOR&quot;)) {return message.channel.send( new MessageEmbed() .setColor(config.color.red) .setTitle('Error occurred!') .setDescription('You do not have permission to use this command!') .setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 })) .setTimestamp() ) }; //get first mentioned member const member = message.mentions.users.first() if (!member) return message.channel.send( new MessageEmbed() .setColor(config.color.red) .setTitle('Missing parameters!') .setDescription('Please mention the member you want to ban!') .setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 })) .setTimestamp() ) //Convert member to a user so we can use it const user = message.guild.member(member) try { //Ban user user.ban() message.channel.send( new MessageEmbed() .setColor(config.color.red) .setTitle('Member Banned!') .setDescription(`\`${member.username}\ has been banned!`) .setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 })) .setTimestamp() ) } catch (err) { console.log(err) return message.channel.send( new MessageEmbed() .setColor(config.color.red) .setTitle('Error occurred!') .setDescription(`Couldn't ban \`${member.username}\` make sure I have the right roles!`) .setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true, size: 64 })) .setTimestamp() ) </code></pre> <p>I tried rewriting the code and also deleting and adding some parts, but still doesn't work. If you can help me solve this that would be much appreciated, thank you.</p>
[ { "answer_id": 74514063, "author": "MrDiamond", "author_id": 15364728, "author_profile": "https://Stackoverflow.com/users/15364728", "pm_score": 0, "selected": false, "text": "module.exports" }, { "answer_id": 74522869, "author": "votavl", "author_id": 20548261, "author_profile": "https://Stackoverflow.com/users/20548261", "pm_score": -1, "selected": false, "text": "async execute(message) const { MessageEmbed, Message } = require('discord.js');\n const fs = require('fs');\n const os = require('os');\n const config = require('../config.json');\n const CatLoggr = require('cat-loggr');\n \n // Functions\n const log = new CatLoggr();\n \n module.exports = {\n name: 'ban', // Command name (can be different from the file name)\n description: 'Bans a member.', // Command description displays in the help command\n \n async execute(message){ \nif(!message.guild.member(message.author).hasPermission(\"ADMINISTRATOR\")) {return message.channel.send(..........\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74514042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20559148/" ]
74,514,050
<p>Every time I try to create a class, it gives me the <code>IndentationError</code> when I haven't even added indentations yet.</p> <p><a href="https://i.stack.imgur.com/j0zOA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j0zOA.png" alt="Error Screenshot" /></a></p> <p>I have tried restarting Jupyter and my PC and there is no luck. I have also tried using another notebook but still face the error.</p>
[ { "answer_id": 74514072, "author": "ilyasbbu", "author_id": 16475089, "author_profile": "https://Stackoverflow.com/users/16475089", "pm_score": 2, "selected": false, "text": "class Animal():\n pass\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74514050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19343411/" ]
74,514,064
<pre><code>limit = int(input(&quot;Limit: &quot;)) allvalue = &quot;&quot; count = 0 number = 0 while count &lt; limit: number += 1 count += number allvalue += str(number) + &quot; + &quot; print(allvalue) </code></pre> <p>This is my output <strong>1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +</strong></p> <p>I want the + symbol only in between the numbers.Not to be in the last or the first.</p>
[ { "answer_id": 74514152, "author": "ti7", "author_id": 4541045, "author_profile": "https://Stackoverflow.com/users/4541045", "pm_score": 1, "selected": false, "text": "\" + \".join() \" + \" >>> values = \"1 2 3 4 5\".split()\n>>> \" + \".join(values)\n'1 + 2 + 3 + 4 + 5'\n" }, { "answer_id": 74514167, "author": "Nguyễn Vũ Trung Hiếu", "author_id": 7562213, "author_profile": "https://Stackoverflow.com/users/7562213", "pm_score": 1, "selected": false, "text": "limit = int(input(\"Limit: \"))\nallvalue = \"\"\ncount = 0\nnumber = 0\nwhile count < limit:\n number += 1\n count += number\n if count != limit:\n allvalue += str(number) + \" + \" \n else:\n allvalue += str(number)\n\nprint(allvalue)\n" }, { "answer_id": 74514204, "author": "bn_ln", "author_id": 10535824, "author_profile": "https://Stackoverflow.com/users/10535824", "pm_score": 0, "selected": false, "text": "number count + limit = int(input(\"Limit: \"))\ncount = 1\nallvalue = str(count)\nwhile count < limit:\n count += 1\n allvalue += \" + \" + str(count)\n \nprint(allvalue)\n" }, { "answer_id": 74514250, "author": "HIMANSHU PANDEY", "author_id": 14952627, "author_profile": "https://Stackoverflow.com/users/14952627", "pm_score": 1, "selected": false, "text": "Sum of n numbers sum limit n import math\n\nlimit = int(input(\"Limit: \")) # n * (n + 1) / 2 >= limit\nn = math.ceil( ((1 + 4*2*limit)**0.5 - 1) / 2 ) # ((b^2 - 4ac)^(1/2) - b) / 2a where a = b = 1, c = 2*limit\n\nallValue = \" + \".join([str(i) for i in range(1, n+1)])\nprint(allValue)\n" }, { "answer_id": 74514253, "author": "Tan WZ", "author_id": 13159701, "author_profile": "https://Stackoverflow.com/users/13159701", "pm_score": 0, "selected": false, "text": "limit = int(input(\"Limit: \"))\nallvalue = \"\"\n\nfor i in range(0, limit):\n if i+1 == limit:\n allvalue += str(i+1)\n else:\n allvalue += str(i+1) + \"+\"\n\nprint(allvalue)\n" }, { "answer_id": 74514267, "author": "user8811698", "author_id": 8811698, "author_profile": "https://Stackoverflow.com/users/8811698", "pm_score": 0, "selected": false, "text": "print(allvalue[:-2])\n limit = int(input(\"Limit: \"))\nallvalue = \"\"\ncount = 0\nnumber = 0\n\n\nwhile count < limit:\n number += 1\n count += number \n allvalue += str(number) + \" + \"\n\nprint(allvalue)\nprint(allvalue[:-2])\n Limit: 9\n1 + 2 + 3 + 4 + \n1 + 2 + 3 + 4 \n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74514064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19791187/" ]
74,514,076
<p>I have an app that persists some values in a cookie. I know that there are other tools such as <code>useState</code>, <code>useContext</code>, etc... but this particular app works with a library that stores information in a jwt so I have to read certain values by fetching the jwt. I am porting the app from next.js 12 (with webpack) to next.js 13 (with turbopack).</p> <p>I've already ported the app structurally to fit the <code>app</code> style routing of next.js 13. My pages all go in their individual folders with sub layouts WITHIN the <code>app</code> directory, and I have a master layout and homepage directly in the <code>app</code> directory.</p> <p>The old code for my protected page in next.js 12 looked like this:</p> <p>protected.tsx</p> <pre><code>import type { NextPage } from 'next'; import { GetServerSideProps } from 'next'; import { useContext } from 'react'; //@ts-ignore import Cookies from 'cookies'; const Protected: NextPage = (props: any) =&gt; { if (!props.authorized) { return ( &lt;h2&gt;Unauthorized&lt;/h2&gt; ) } else { return ( &lt;div className=&quot;max-w-md&quot;&gt; &lt;h1 className=&quot;font-bold&quot;&gt;This is the Protected Section&lt;/h1&gt; &lt;/div&gt; )} } export const getServerSideProps: GetServerSideProps = async ({ req, res, query }) =&gt; { const { id } = query const cookies = new Cookies(req, res) const jwt = cookies.get('&lt;MY TOKEN NAME&gt;') if (!jwt) { return { props: { authorized: false }, } } const { verified } = &lt;MY TOKEN SDK INSTANCE&gt;.verifyJwt({ jwt }) return { props: { authorized: verified ? true : false }, } } export default Protected </code></pre> <p>I have this page moved into it's own directory now.</p> <p>&quot;getServerSideProps&quot; isn't supported in Next.js 13 <a href="https://beta.nextjs.org/docs/data-fetching/fundamentals" rel="nofollow noreferrer">https://beta.nextjs.org/docs/data-fetching/fundamentals</a>. The docs say &quot;previous Next.js APIs such as getServerSideProps, getStaticProps, and getInitialProps are not supported in the new app directory.&quot; So how would I change my code to work in Next.js 13?</p> <p>P.S. I know what it looks like but this cookie IS NOT HANDLING USER AUTHENTICATION. I understand that someone could alter the cookie and gain access to the protected page. This is just a small piece of a larger app with other security mechanisms that I have in place.</p>
[ { "answer_id": 74519515, "author": "Evans Benedict", "author_id": 20560614, "author_profile": "https://Stackoverflow.com/users/20560614", "pm_score": 0, "selected": false, "text": "\"cookies-next\"" }, { "answer_id": 74521768, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 3, "selected": true, "text": "import { cookies } from \"next/headers\";\n next/headers.js function cookies() {\n (0, _staticGenerationBailout).staticGenerationBailout('cookies');\n const requestStore = _requestAsyncStorage.requestAsyncStorage && 'getStore' in _requestAsyncStorage.requestAsyncStorage ? _requestAsyncStorage.requestAsyncStorage.getStore() : _requestAsyncStorage.requestAsyncStorage;\n return requestStore.cookies;\n}\n app const cookie = cookies().get(\"cookieName\")?.value\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74514076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13215988/" ]