qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,402,769
<p>a program that will iterates over each number in a the list then the if statement will check whether the iteration/number is greater than 15 then the loop will stop, otherwise the number from the list will be printed. List = [1, 4, 7, 8, 15, 20, 35, 45, 55]</p> <pre><code>List = [1, 4, 7, 8, 15, 20, 35, 45, 55] for i in List: if i &gt; 15: break elif i &gt; 1: continue print(i) </code></pre>
[ { "answer_id": 74402858, "author": "Hasan", "author_id": 5571471, "author_profile": "https://Stackoverflow.com/users/5571471", "pm_score": -1, "selected": false, "text": "elif check" }, { "answer_id": 74402969, "author": "Mohamed MERABET", "author_id": 20351963, "author_profile": "https://Stackoverflow.com/users/20351963", "pm_score": 0, "selected": false, "text": "List = [1, 4, 7, 8, 15, 20, 35, 45, 55]\nfor i in List:\n#print(i)\nif i > 15:\n break\nelif i > 1:\n pass\nprint(i)\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74402769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,402,777
<p>I have a <code>long</code> timestamp that is milliseconds since Epoch.</p> <p>I am calling a third-party API that takes a <code>TemporalAccessor</code>.</p> <p>How do I get one from the other?</p> <p>Is <code>Instant.ofEpochMilli(timestamp)</code> sufficiently correct, given epoch is UTC?</p>
[ { "answer_id": 74402945, "author": "xlm", "author_id": 885922, "author_profile": "https://Stackoverflow.com/users/885922", "pm_score": 3, "selected": true, "text": "long" }, { "answer_id": 74403122, "author": "Vihung", "author_id": 15452, "author_profile": "https://Stackoverflow.com/users/15452", "pm_score": 1, "selected": false, "text": "TemporalAccessor" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74402777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15452/" ]
74,402,780
<h1>Context:</h1> <p>I'm currently coding a bot on Discord. The bot has a server class within it (with none of the fancy websockets and http requests) and a client class that serves as a bridge between the user and the server. The instance of the client class manages sending log messages to its corresponding user, updating its GUI (which is just an embed and a bunch of buttons attached to it which), and calling methods on the server class.</p> <p>Currently I'm stuck on log messages. The current system is that a GUI message that contains the controls would always be the most recently sent message.</p> <p>If another user were to join a room on the server class, this would cause the GUI message to not be updated anymore. Additionally, a log message would be sent to the user, which would cause the GUI message to not be the most recently sent message. Both problems are solved by the bot deleting the old GUI message and sending the updated one after that.</p> <p>However, concurrent room joins may occur, so there's a chance the bot would interleave the &quot;delete message&quot; and &quot;send message&quot; parts of updating the GUI message like this:</p> <pre class="lang-py prettyprint-override"><code>delete_message() delete_message() # !!! send_message() send_message() </code></pre> <p>The second <code>delete_message()</code> would cause an error, since it can't find a message that has already been deleted.</p> <p>My proposed solution would be the problem below.</p> <hr /> <h1>Problem:</h1> <p>Let's say I have an async function called <code>foo</code>:</p> <pre class="lang-py prettyprint-override"><code>import asyncio limit: int async def foo(): print(&quot;bar&quot;) async def foo_caller(): await asyncio.gather(foo(), foo(), foo(), foo(), foo()) await foo() await foo() </code></pre> <p>This function would be called multiple times using the <code>foo_caller</code> function. Currently, this would print <code>bar</code> <strong>7 times</strong>.</p> <p>The problem is, <strong>How to execute only one function call when <code>foo</code> is called multiple times in a short timeframe?</strong></p> <p>The solution should print <code>bar</code> only <strong>three times</strong>. One for the <code>await asyncio.gather(foo(), foo(), foo(), foo(), foo())</code>, and one each for the <code>await foo()</code>.</p>
[ { "answer_id": 74403053, "author": "Stepan Filonov", "author_id": 8363510, "author_profile": "https://Stackoverflow.com/users/8363510", "pm_score": 0, "selected": false, "text": "async def foo():\n if lock_exists():\n return\n async with lock(ttl=5): # lock is alive for 5 seconds, the rest don't execute. Not released upon execution, but on a timer\n print(\"bar\")\n\n\nasync def foo_caller():\n await asyncio.gather(foo(), foo(), foo(), foo(), foo())\n await foo()\n await foo()\n" }, { "answer_id": 74407703, "author": "Paul Cornelius", "author_id": 2442613, "author_profile": "https://Stackoverflow.com/users/2442613", "pm_score": 2, "selected": true, "text": "main" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74402780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17191838/" ]
74,402,826
<p>Please excuse my noobness regarding this language, I am very much a beginner. I've been tasked with creating a Quiz Maker and I'm stuck on how I am supposed to put some of my class elements into a List. The reason I need to put these into a list is because I don't want to handle each user inputted answer separately, rather in a list and have everything dependant on the list size and set a limit for how many answers I want to store in it. Any help would be hugely appreciated.</p> <p>Here is my class:</p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quiz_Maker { public class QuestionAndAnswers { public string userQuestion { get; set; } List&lt;string&gt; QnAList = new List&lt;string&gt;(); public string falseAnswerOne { get; set; } //TODO: this could maybe perhaps possilby be a list of string public string falseAnswerTwo { get; set; } //TODO: this could maybe perhaps possilby be a list of string public string falseAnswerThree { get; set; } //TODO: this could maybe perhaps possilby be a list of string public string correctAnswer { get; set; } //TODO: this could maybe perhaps possilby be a list of string private int correctAnswerIndex; } } </code></pre> <p>Here is my object method:</p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quiz_Maker { public static class UserInterface { public static QuestionAndAnswers GetQuestionAndAnswers() { QuestionAndAnswers UserQnA = new QuestionAndAnswers(); string userQuestion; string correctAnswer; string falseAnswerOne; string falseAnswerTwo; string falseAnswerThree; Console.WriteLine(&quot;Please type your question: &quot;); UserQnA.userQuestion = Console.ReadLine(); Console.WriteLine(&quot;Please type the correct answer: &quot;); UserQnA.correctAnswer = Console.ReadLine(); Console.WriteLine(&quot;Please type your first false answer: &quot;); UserQnA.falseAnswerOne = Console.ReadLine(); Console.WriteLine(&quot;Please type your second false answer: &quot;); UserQnA.falseAnswerTwo = Console.ReadLine(); Console.WriteLine(&quot;Please type your third false answer: &quot;); UserQnA.falseAnswerThree = Console.ReadLine(); return UserQnA; } } } </code></pre> <p>I've googled this topic to death and have not found anything that makes sense.</p>
[ { "answer_id": 74403053, "author": "Stepan Filonov", "author_id": 8363510, "author_profile": "https://Stackoverflow.com/users/8363510", "pm_score": 0, "selected": false, "text": "async def foo():\n if lock_exists():\n return\n async with lock(ttl=5): # lock is alive for 5 seconds, the rest don't execute. Not released upon execution, but on a timer\n print(\"bar\")\n\n\nasync def foo_caller():\n await asyncio.gather(foo(), foo(), foo(), foo(), foo())\n await foo()\n await foo()\n" }, { "answer_id": 74407703, "author": "Paul Cornelius", "author_id": 2442613, "author_profile": "https://Stackoverflow.com/users/2442613", "pm_score": 2, "selected": true, "text": "main" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74402826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18231242/" ]
74,402,846
<p>I want to shorten the if conditions. Is there any alternative other than switch case?</p> <pre><code> public void check(String name){ String parentFolder = &quot;&quot;; if(name.matches(&quot;birds&quot;)) parentFolder = birdPFUuid; if (name.matches(&quot;dogs&quot;)) parentFolder = dogPFUuid; if (name.matches(&quot;cats&quot;)) parentFolder = catPFUuid; if (name.matches(&quot;vehicles&quot;)) parentFolder = vehiclesPFUuid; } </code></pre> <p>Thank you</p>
[ { "answer_id": 74403137, "author": "Syed Asad Manzoor", "author_id": 20477563, "author_profile": "https://Stackoverflow.com/users/20477563", "pm_score": 1, "selected": false, "text": "((condition == value)?'expr1':'expr2')\n" }, { "answer_id": 74403289, "author": "ANISH SAJI KUMAR", "author_id": 12309235, "author_profile": "https://Stackoverflow.com/users/12309235", "pm_score": 1, "selected": true, "text": "Map<String, String> uuidMap = new HashMap<>();\nuuidMap.put(\"birds\", birdPFUuid);\nuuidMap.put(\"dogs\", dogPFUuid);\nuuidMap.put(\"cats\", catPFUuid);\nuuidMap.put(\"vehicles\", vehiclesPFUuid);\n\npublic void check(String name){\n String parentFolder = uuidMap.get(name);\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74402846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19672397/" ]
74,402,881
<p>I have a view that needs to be displayed with a slanted corner on one side. I've already done it when the view has a background color like this:</p> <p><a href="https://i.stack.imgur.com/TbMh0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TbMh0.png" alt="enter image description here" /></a></p> <p>But I also need it to be displayed with a clear background. After setting its background to clear and adding a border to it this is the output:</p> <p><a href="https://i.stack.imgur.com/mAQIB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mAQIB.png" alt="enter image description here" /></a></p> <p>Here is the code for the custom view that I'm using to create the diagonal corner:</p> <pre class="lang-swift prettyprint-override"><code>class PointedView: UIImageView { @IBInspectable var borderColor: UIColor = UIColor.clear { didSet { layer.borderColor = borderColor.cgColor } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable /// Percentage of the slant based on the width var slopeFactor: CGFloat = 15 { didSet { updatePath() } } private let shapeLayer: CAShapeLayer = { let shapeLayer = CAShapeLayer() shapeLayer.lineWidth = 0 // with masks, the color of the shape layer doesn’t matter; // it only uses the alpha channel; the color of the view is // dictate by its background color shapeLayer.fillColor = UIColor.white.cgColor return shapeLayer }() override func layoutSubviews() { super.layoutSubviews() updatePath() } private func updatePath() { let path = UIBezierPath() // Start from x = 0 but the mid point of y of the view path.move(to: CGPoint(x: 0, y: bounds.midY*2)) // Create the top slanting line path.addLine(to: CGPoint(x: bounds.minX, y: bounds.minY)) // Straight line from end of slant to the end of the view path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY)) // Straight line to come down to the bottom, perpendicular to view path.addLine(to: CGPoint(x: bounds.maxX, y: ((bounds.maxY*3)/4) + 20)) // Go back to the slant end position but from the bottom path.addLine(to: CGPoint(x: (bounds.maxX*3)/4, y: bounds.maxY)) // Close path back to where you started path.close() shapeLayer.path = path.cgPath layer.mask = shapeLayer } } </code></pre> <p>Is there any possible solution to this?</p>
[ { "answer_id": 74426395, "author": "David Mempin", "author_id": 9629494, "author_profile": "https://Stackoverflow.com/users/9629494", "pm_score": 1, "selected": true, "text": "let borderLayer = CAShapeLayer()\nborderLayer.path = path.cgPath\nborderLayer.lineWidth = 2\nborderLayer.strokeColor = borderColor.cgColor\nborderLayer.fillColor = UIColor.clear.cgColor\nborderLayer.frame = bounds\n \nlayer.addSublayer(borderLayer)\n" }, { "answer_id": 74428787, "author": "Jaykant", "author_id": 6402508, "author_profile": "https://Stackoverflow.com/users/6402508", "pm_score": 1, "selected": false, "text": "class PointedView: UIView {\n\noverride init(frame: CGRect) {\n super.init(frame: frame)\n setup()\n}\nrequired init?(coder aDecoder: NSCoder) {\n super.init(coder: aDecoder)\n setup()\n}\nfunc setup() {\n let shapeLayer = CAShapeLayer()\n shapeLayer.path = createBezierPath().cgPath\n shapeLayer.strokeColor = UIColor.blue.cgColor\n shapeLayer.fillColor = UIColor.blue.cgColor\n shapeLayer.lineWidth = 1.0\n shapeLayer.position = CGPoint(x: 10, y: 10)\n self.layer.addSublayer(shapeLayer)\n}\n\nfunc createBezierPath() -> UIBezierPath {\n let path = UIBezierPath()\n \n // Start from x = 0 but the mid point of y of the view\n path.move(to: CGPoint(x: 0, y: bounds.midY*2))\n \n // Create the top slanting line\n path.addLine(to: CGPoint(x: bounds.minX, y: bounds.minY))\n \n // Straight line from end of slant to the end of the view\n path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY))\n \n // Straight line to come down to the bottom, perpendicular to view\n path.addLine(to: CGPoint(x: bounds.maxX, y: ((bounds.maxY*3)/4) + 20))\n \n // Go back to the slant end position but from the bottom\n path.addLine(to: CGPoint(x: (bounds.maxX*3)/4, y: bounds.maxY))\n \n // Close path back to where you started\n path.close() // draws the final line to close the path\n return path\n}\n}\n" }, { "answer_id": 74529482, "author": "Muhammad Manzar", "author_id": 16153772, "author_profile": "https://Stackoverflow.com/users/16153772", "pm_score": 0, "selected": false, "text": "func roundCorners(corners: UIRectCorner = .allCorners, radius: CGFloat = 0.0, borderColor: UIColor = .clear, borderWidth: CGFloat = 0.0, clipToBonds: Bool = true) {\n clipsToBounds = clipToBonds\n layer.cornerRadius = radius\n layer.borderWidth = borderWidth\n layer.borderColor = borderColor.cgColor\n \n if corners.contains(.allCorners){\n layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner]\n return\n }\n \n var maskedCorners = CACornerMask()\n if corners.contains(.topLeft) { maskedCorners.insert(.layerMinXMinYCorner) }\n if corners.contains(.topRight) { maskedCorners.insert(.layerMaxXMinYCorner) }\n if corners.contains(.bottomLeft) { maskedCorners.insert(.layerMinXMaxYCorner) }\n if corners.contains(.bottomRight) { maskedCorners.insert(.layerMaxXMaxYCorner) }\n layer.maskedCorners = maskedCorners\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74402881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9629494/" ]
74,402,886
<p>I have a dataframe and in one of the columns i have quite a lot of missing data, i tried to impute these values but as there is so much that is missing it doesn't do a very good job. The column in question here has a value given for roughly every 5 years, normally i would just delete it but i want to see if i can salvage something from it. What im looking to go is to carry forward the value provided, filling in the NA until a new value appears. So for example in my data provided im looking for an output like this;</p> <pre><code>df Country_Name year gdp_per_capita freshwaster_production_pc Albania 1997 717.3800 4.543622e-07 #use this value Albania 1998 813.7894 4.543622e-07 Albania 1999 1033.2425 4.543622e-07 Albania 2000 1126.6833 4.543622e-07 Albania 2001 1281.6598 4.543622e-07 Albania 2002 1425.1242 5.451047e-07 #new value so now we use this Albania 2003 1846.1201 5.451047e-07 Albania 2004 2373.5813 5.451047e-07 </code></pre> <p>Im also open to ideas on better ways to deal with this so feel free to suggest anything thats better. I thought about averaging the values and using them but i think this is a better way of showing the changes in time</p> <p>sample data;</p> <pre><code>head(df, 30) Country_Name year gdp_per_capita freshwaster_production_pc 1 Albania 1997 717.3800 4.543622e-07 2 Albania 1998 813.7894 NA 3 Albania 1999 1033.2425 NA 4 Albania 2000 1126.6833 NA 5 Albania 2001 1281.6598 NA 6 Albania 2002 1425.1242 5.451047e-07 7 Albania 2003 1846.1201 NA 8 Albania 2004 2373.5813 NA 9 Albania 2005 2673.7866 NA 10 Albania 2006 2972.7429 NA 11 Albania 2007 3595.0381 4.201121e-07 12 Albania 2008 4370.5399 NA 13 Albania 2009 4114.1349 NA 14 Albania 2010 4094.3484 NA 15 Albania 2011 4437.1426 NA 16 Albania 2012 4247.6300 3.876498e-07 17 Albania 2013 4413.0620 NA 18 Albania 2014 4578.6332 NA 19 Albania 2015 3952.8025 NA 20 Albania 2016 4124.0554 NA 21 Albania 2017 4531.0194 3.796820e-07 22 Albania 2018 5287.6637 3.342199e-07 23 Albania 2019 5396.2159 NA 24 Albania 2020 5332.1605 NA 25 Albania 2021 6494.3857 NA 26 Algeria 1997 1619.7977 1.773179e-07 27 Algeria 1998 1596.0039 NA 28 Algeria 1999 1588.3489 NA 29 Algeria 2000 1765.0271 NA 30 Algeria 2001 1740.6067 NA 31 Algeria 2002 1781.8289 1.897217e-07 32 Algeria 2003 2103.3813 NA 33 Algeria 2004 2610.1854 NA 34 Algeria 2005 3113.0949 NA 35 Algeria 2006 3478.7100 NA </code></pre>
[ { "answer_id": 74426395, "author": "David Mempin", "author_id": 9629494, "author_profile": "https://Stackoverflow.com/users/9629494", "pm_score": 1, "selected": true, "text": "let borderLayer = CAShapeLayer()\nborderLayer.path = path.cgPath\nborderLayer.lineWidth = 2\nborderLayer.strokeColor = borderColor.cgColor\nborderLayer.fillColor = UIColor.clear.cgColor\nborderLayer.frame = bounds\n \nlayer.addSublayer(borderLayer)\n" }, { "answer_id": 74428787, "author": "Jaykant", "author_id": 6402508, "author_profile": "https://Stackoverflow.com/users/6402508", "pm_score": 1, "selected": false, "text": "class PointedView: UIView {\n\noverride init(frame: CGRect) {\n super.init(frame: frame)\n setup()\n}\nrequired init?(coder aDecoder: NSCoder) {\n super.init(coder: aDecoder)\n setup()\n}\nfunc setup() {\n let shapeLayer = CAShapeLayer()\n shapeLayer.path = createBezierPath().cgPath\n shapeLayer.strokeColor = UIColor.blue.cgColor\n shapeLayer.fillColor = UIColor.blue.cgColor\n shapeLayer.lineWidth = 1.0\n shapeLayer.position = CGPoint(x: 10, y: 10)\n self.layer.addSublayer(shapeLayer)\n}\n\nfunc createBezierPath() -> UIBezierPath {\n let path = UIBezierPath()\n \n // Start from x = 0 but the mid point of y of the view\n path.move(to: CGPoint(x: 0, y: bounds.midY*2))\n \n // Create the top slanting line\n path.addLine(to: CGPoint(x: bounds.minX, y: bounds.minY))\n \n // Straight line from end of slant to the end of the view\n path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY))\n \n // Straight line to come down to the bottom, perpendicular to view\n path.addLine(to: CGPoint(x: bounds.maxX, y: ((bounds.maxY*3)/4) + 20))\n \n // Go back to the slant end position but from the bottom\n path.addLine(to: CGPoint(x: (bounds.maxX*3)/4, y: bounds.maxY))\n \n // Close path back to where you started\n path.close() // draws the final line to close the path\n return path\n}\n}\n" }, { "answer_id": 74529482, "author": "Muhammad Manzar", "author_id": 16153772, "author_profile": "https://Stackoverflow.com/users/16153772", "pm_score": 0, "selected": false, "text": "func roundCorners(corners: UIRectCorner = .allCorners, radius: CGFloat = 0.0, borderColor: UIColor = .clear, borderWidth: CGFloat = 0.0, clipToBonds: Bool = true) {\n clipsToBounds = clipToBonds\n layer.cornerRadius = radius\n layer.borderWidth = borderWidth\n layer.borderColor = borderColor.cgColor\n \n if corners.contains(.allCorners){\n layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner]\n return\n }\n \n var maskedCorners = CACornerMask()\n if corners.contains(.topLeft) { maskedCorners.insert(.layerMinXMinYCorner) }\n if corners.contains(.topRight) { maskedCorners.insert(.layerMaxXMinYCorner) }\n if corners.contains(.bottomLeft) { maskedCorners.insert(.layerMinXMaxYCorner) }\n if corners.contains(.bottomRight) { maskedCorners.insert(.layerMaxXMaxYCorner) }\n layer.maskedCorners = maskedCorners\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74402886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18338223/" ]
74,402,901
<p>I have a very simple expression below. I am checking each character of a password to ensure it has at least one of the below special characters. However, Flake8 registers the example as bad. How can I address this within Flake8?</p> <p>W605 invalid escape sequence '!'</p> <p>W605 invalid escape sequence '$'</p> <p>W605 invalid escape sequence '^'</p> <p>W605 invalid escape sequence '*'</p> <p>W605 invalid escape sequence '('</p> <p>W605 invalid escape sequence ')'</p> <p>W605 invalid escape sequence '+'</p> <p>W605 invalid escape sequence '['</p> <p>W605 invalid escape sequence ']'</p> <pre><code>def clean_password(self): special_characters = &quot;[~\!@#\$%\^&amp;\*\(\)_\+{}\&quot;:;'\[\]]&quot; if len(self.data[&quot;password&quot;]) &lt; 8: raise ValidationError(&quot;Password length must be greater than 8 characters.&quot;) if not any(char.isdigit() for char in self.data[&quot;password&quot;]): raise ValidationError(&quot;Password must contain at least 1 digit.&quot;) if not any(char.isalpha() for char in self.data[&quot;password&quot;]): raise ValidationError(&quot;Password must contain at least 1 letter.&quot;) if not any(char in special_characters for char in self.data[&quot;password&quot;]): raise ValidationError(&quot;Password must contain at least 1 special character.&quot;) return self.data[&quot;password&quot;] </code></pre>
[ { "answer_id": 74426395, "author": "David Mempin", "author_id": 9629494, "author_profile": "https://Stackoverflow.com/users/9629494", "pm_score": 1, "selected": true, "text": "let borderLayer = CAShapeLayer()\nborderLayer.path = path.cgPath\nborderLayer.lineWidth = 2\nborderLayer.strokeColor = borderColor.cgColor\nborderLayer.fillColor = UIColor.clear.cgColor\nborderLayer.frame = bounds\n \nlayer.addSublayer(borderLayer)\n" }, { "answer_id": 74428787, "author": "Jaykant", "author_id": 6402508, "author_profile": "https://Stackoverflow.com/users/6402508", "pm_score": 1, "selected": false, "text": "class PointedView: UIView {\n\noverride init(frame: CGRect) {\n super.init(frame: frame)\n setup()\n}\nrequired init?(coder aDecoder: NSCoder) {\n super.init(coder: aDecoder)\n setup()\n}\nfunc setup() {\n let shapeLayer = CAShapeLayer()\n shapeLayer.path = createBezierPath().cgPath\n shapeLayer.strokeColor = UIColor.blue.cgColor\n shapeLayer.fillColor = UIColor.blue.cgColor\n shapeLayer.lineWidth = 1.0\n shapeLayer.position = CGPoint(x: 10, y: 10)\n self.layer.addSublayer(shapeLayer)\n}\n\nfunc createBezierPath() -> UIBezierPath {\n let path = UIBezierPath()\n \n // Start from x = 0 but the mid point of y of the view\n path.move(to: CGPoint(x: 0, y: bounds.midY*2))\n \n // Create the top slanting line\n path.addLine(to: CGPoint(x: bounds.minX, y: bounds.minY))\n \n // Straight line from end of slant to the end of the view\n path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY))\n \n // Straight line to come down to the bottom, perpendicular to view\n path.addLine(to: CGPoint(x: bounds.maxX, y: ((bounds.maxY*3)/4) + 20))\n \n // Go back to the slant end position but from the bottom\n path.addLine(to: CGPoint(x: (bounds.maxX*3)/4, y: bounds.maxY))\n \n // Close path back to where you started\n path.close() // draws the final line to close the path\n return path\n}\n}\n" }, { "answer_id": 74529482, "author": "Muhammad Manzar", "author_id": 16153772, "author_profile": "https://Stackoverflow.com/users/16153772", "pm_score": 0, "selected": false, "text": "func roundCorners(corners: UIRectCorner = .allCorners, radius: CGFloat = 0.0, borderColor: UIColor = .clear, borderWidth: CGFloat = 0.0, clipToBonds: Bool = true) {\n clipsToBounds = clipToBonds\n layer.cornerRadius = radius\n layer.borderWidth = borderWidth\n layer.borderColor = borderColor.cgColor\n \n if corners.contains(.allCorners){\n layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner]\n return\n }\n \n var maskedCorners = CACornerMask()\n if corners.contains(.topLeft) { maskedCorners.insert(.layerMinXMinYCorner) }\n if corners.contains(.topRight) { maskedCorners.insert(.layerMaxXMinYCorner) }\n if corners.contains(.bottomLeft) { maskedCorners.insert(.layerMinXMaxYCorner) }\n if corners.contains(.bottomRight) { maskedCorners.insert(.layerMaxXMaxYCorner) }\n layer.maskedCorners = maskedCorners\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74402901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16178069/" ]
74,402,927
<p>I'm trying to achive an hard try in google sheet.</p> <p>Let's start from what I right now, the A structure in the image.</p> <p>What I would like to achieve using functions like =QUERY, is the B or C (whatever is fine for me) structore.</p> <p><a href="https://i.stack.imgur.com/FxF58.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FxF58.png" alt="Exemple" /></a></p> <p>Can u help me with the sintax?</p> <p>I appreciate it so much and thank you very much</p> <p>Luco</p> <p>I tried a couplo of function but can't get to the point using QUERY function, maybe I'm using bad syntax.</p>
[ { "answer_id": 74426395, "author": "David Mempin", "author_id": 9629494, "author_profile": "https://Stackoverflow.com/users/9629494", "pm_score": 1, "selected": true, "text": "let borderLayer = CAShapeLayer()\nborderLayer.path = path.cgPath\nborderLayer.lineWidth = 2\nborderLayer.strokeColor = borderColor.cgColor\nborderLayer.fillColor = UIColor.clear.cgColor\nborderLayer.frame = bounds\n \nlayer.addSublayer(borderLayer)\n" }, { "answer_id": 74428787, "author": "Jaykant", "author_id": 6402508, "author_profile": "https://Stackoverflow.com/users/6402508", "pm_score": 1, "selected": false, "text": "class PointedView: UIView {\n\noverride init(frame: CGRect) {\n super.init(frame: frame)\n setup()\n}\nrequired init?(coder aDecoder: NSCoder) {\n super.init(coder: aDecoder)\n setup()\n}\nfunc setup() {\n let shapeLayer = CAShapeLayer()\n shapeLayer.path = createBezierPath().cgPath\n shapeLayer.strokeColor = UIColor.blue.cgColor\n shapeLayer.fillColor = UIColor.blue.cgColor\n shapeLayer.lineWidth = 1.0\n shapeLayer.position = CGPoint(x: 10, y: 10)\n self.layer.addSublayer(shapeLayer)\n}\n\nfunc createBezierPath() -> UIBezierPath {\n let path = UIBezierPath()\n \n // Start from x = 0 but the mid point of y of the view\n path.move(to: CGPoint(x: 0, y: bounds.midY*2))\n \n // Create the top slanting line\n path.addLine(to: CGPoint(x: bounds.minX, y: bounds.minY))\n \n // Straight line from end of slant to the end of the view\n path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY))\n \n // Straight line to come down to the bottom, perpendicular to view\n path.addLine(to: CGPoint(x: bounds.maxX, y: ((bounds.maxY*3)/4) + 20))\n \n // Go back to the slant end position but from the bottom\n path.addLine(to: CGPoint(x: (bounds.maxX*3)/4, y: bounds.maxY))\n \n // Close path back to where you started\n path.close() // draws the final line to close the path\n return path\n}\n}\n" }, { "answer_id": 74529482, "author": "Muhammad Manzar", "author_id": 16153772, "author_profile": "https://Stackoverflow.com/users/16153772", "pm_score": 0, "selected": false, "text": "func roundCorners(corners: UIRectCorner = .allCorners, radius: CGFloat = 0.0, borderColor: UIColor = .clear, borderWidth: CGFloat = 0.0, clipToBonds: Bool = true) {\n clipsToBounds = clipToBonds\n layer.cornerRadius = radius\n layer.borderWidth = borderWidth\n layer.borderColor = borderColor.cgColor\n \n if corners.contains(.allCorners){\n layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner]\n return\n }\n \n var maskedCorners = CACornerMask()\n if corners.contains(.topLeft) { maskedCorners.insert(.layerMinXMinYCorner) }\n if corners.contains(.topRight) { maskedCorners.insert(.layerMaxXMinYCorner) }\n if corners.contains(.bottomLeft) { maskedCorners.insert(.layerMinXMaxYCorner) }\n if corners.contains(.bottomRight) { maskedCorners.insert(.layerMaxXMaxYCorner) }\n layer.maskedCorners = maskedCorners\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74402927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20477986/" ]
74,402,985
<p>My problem:</p> <p>I have 2 defined records</p> <ul> <li>CreateObjectRequest</li> <li>UpdateObjectRequest</li> </ul> <p>that must be verified by an utility method.</p> <p>As those 2 objects have the same fields, the same verify method can be applied on both types.<br /> Right now I'm just overloading by using 2 methods, but it's verbosy.</p> <pre class="lang-java prettyprint-override"><code>public record CreateObjectRequest ( CustomObjectA a, CustomObjectB b, CustomObjectC c ) {} public record UpdateObjectRequest ( CustomObjectA a, CustomObjectB b ) {} public void validateRequest(CreateObjectRequest createObjectRequest) { //long body //... } public void validateRequest(UpdateObjectRequest updateObjectRequest) { //same long body... //... } </code></pre> <p>How can I reduce the verbosity of this code ?</p>
[ { "answer_id": 74403117, "author": "OH GOD SPIDERS", "author_id": 6073886, "author_profile": "https://Stackoverflow.com/users/6073886", "pm_score": 1, "selected": false, "text": "public abstract class ObjectRequest {\n CustomObject a;\n CustomObject b;\n\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74402985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19896324/" ]
74,403,002
<p>In haskell one can make an infinite list with</p> <pre class="lang-hs prettyprint-override"><code>f = let ones = &quot;ones&quot;:ones in ones </code></pre> <p>Is there a way to do this in google sheets?</p> <p>I tried searching, but I only could find examples of infinite scrolling in google sheets, not infinite strings.</p>
[ { "answer_id": 74403117, "author": "OH GOD SPIDERS", "author_id": 6073886, "author_profile": "https://Stackoverflow.com/users/6073886", "pm_score": 1, "selected": false, "text": "public abstract class ObjectRequest {\n CustomObject a;\n CustomObject b;\n\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17749920/" ]
74,403,065
<p>Suppose a PostgreSQL table, <code>articles</code>, contains two nullable String columns of <code>name</code> and <code>alt_name</code>. Now, I want to find records (rows) in the table that have</p> <ul> <li>a <strong>combination of</strong> String <code>name</code> and <code>alt_name</code> matches another combination of the same type in the same table: <ul> <li>i.e., <code>[a.name, a.alt_name]</code> is equal to either <code>[b.name, b.alt_name]</code> or <code>[b.alt_name, b.name]</code></li> </ul> </li> <li>where <code>name</code> or <code>alt_name</code> may be <code>NULL</code> or an empty String, and in any circumstances <code>NULL</code> and an empty String should be treated as identical; <ul> <li>e.g., when <code>[a.name, a.alt_name] == [&quot;abc&quot;, NULL]</code>, a record of <code>[b.name, b.alt_name] == [&quot;&quot;, &quot;abc&quot;]</code> should match, because one of them is <code>&quot;abc&quot;</code> and the other is NULL or empty String.</li> </ul> </li> </ul> <p>Is there any neat query to achieve this?</p> <p>I thought if there is a way to concatenate both columns with a UTF-8 <em>replacement character</em> (<code>U+FFFD</code>) in between, where NULL is converted into an empty String, that would solve the problem. Say, if the function were <code>magic_fn()</code>, the following would do a job, providing there is a unique column <code>id</code>:</p> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM articles a INNER JOIN places b ON a.id &lt;&gt; b.id WHERE magic_fn(a.name, a.alt_name) = magic_fn(b.name, b.alt_name) OR magic_fn(a.name, a.alt_name) = magic_fn(b.alt_name, b.name); -- [EDIT] corrected from the original post, which was simply wrong. </code></pre> <p>However, <a href="https://stackoverflow.com/q/12378904/3577922"><strike>concatnation is not a built-in function in PostgreSQL</strike></a> and I don't know how to do this.<br /> [<strong>EDIT</strong>] As commented by @Serg and in answers, a string-concatnation function is now available in PostgreSQL from Ver.9.1 (<a href="https://www.postgresql.org/docs/current/functions-string.html" rel="nofollow noreferrer">CONCAT or ||</a>); n.b., it actually accepts non-String input as long as one of them is a String-type as of Ver.15.</p> <p>Or, maybe there is simply a better way?</p>
[ { "answer_id": 74403811, "author": "Mitko Keckaroski", "author_id": 12041280, "author_profile": "https://Stackoverflow.com/users/12041280", "pm_score": 1, "selected": false, "text": "SELECT * FROM articles a\ncross join articles b \nwhere \n(ARRAY[COALESCE(a.name,''),COALESCE(a.alt_name,'')] @> ARRAY[COALESCE(b.name,''),COALESCE(b.alt_name,'')]) \nand (ARRAY[COALESCE(a.name,''),COALESCE(a.alt_name,'')] <@ ARRAY[COALESCE(b.name,''),COALESCE(b.alt_name,'')]) \nand a.id<>b.id\nand a.id<b.id --optional (to avoid reverse matching) \n" }, { "answer_id": 74403820, "author": "Ajax1234", "author_id": 7326738, "author_profile": "https://Stackoverflow.com/users/7326738", "pm_score": 2, "selected": true, "text": "name" }, { "answer_id": 74403841, "author": "MMAARR", "author_id": 3218453, "author_profile": "https://Stackoverflow.com/users/3218453", "pm_score": 0, "selected": false, "text": "(coalesce(a.name,'') || coalesce(a.altname,'')) = (coalesce(b.name,'') || coalesce(b.altname,'')) \n or \n (coalesce(a.name,'') || coalesce(a.altname,'')) = (coalesce(b.altname,'') || coalesce(b.name,'')) \n" }, { "answer_id": 74406045, "author": "a_horse_with_no_name", "author_id": 330315, "author_profile": "https://Stackoverflow.com/users/330315", "pm_score": 0, "selected": false, "text": "select *\nfrom articles\nwhere array_remove(array[nullif(name,''), nullif(alt_name,'')], null) && array['abc']\n" }, { "answer_id": 74415532, "author": "Masa Sakano", "author_id": 3577922, "author_profile": "https://Stackoverflow.com/users/3577922", "pm_score": 1, "selected": false, "text": "\\U+FFFD" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3577922/" ]
74,403,086
<p>I need to sum a range of cells across rows, but I need to be able to specify the amount with a variable.</p> <p>For example. If i write 5 in cell B1, I want to sum range A1:A5. If i write 10 in cell B1, I want to sum range A1:A10. If i write 20 in cell B1, I want to sum range A1:A20.</p> <p>And so on.</p> <p>Does anyone know a formula for this?</p> <p>Kind regards.</p> <p>I tried writing( in cell B1) =SUM(A1:A(1+B1)). This didn't work at all, instead a =NAME? appeared.</p>
[ { "answer_id": 74403141, "author": "Martín", "author_id": 20363318, "author_profile": "https://Stackoverflow.com/users/20363318", "pm_score": 1, "selected": false, "text": "INDIRECT" }, { "answer_id": 74403301, "author": "Ping", "author_id": 20288037, "author_profile": "https://Stackoverflow.com/users/20288037", "pm_score": 0, "selected": false, "text": "=SUM(BYROW(SEQUENCE(B1),LAMBDA(ROW,INDEX(A1:A,ROW))))" }, { "answer_id": 74407583, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 0, "selected": false, "text": "=SUM(A1:INDEX(A:A; B1))\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16290932/" ]
74,403,097
<pre><code> #define OLED_RESET -1 Adafruit_SSD1306 display(OLED_RESET); char buff[10]=&quot;hola&quot;; char buff2[10]=&quot;&quot;; int cnt=0; int b=0; int alpha=1; void setup() { display.begin(SSD1306_SWITCHCAPVCC, 0x3C); display.clearDisplay(); display.setTextColor(WHITE); Serial.begin(9600); } void loop() { while (Serial.available()) { char a = Serial.read(); buff[cnt++] = a; alpha=1; } if(alpha==1){ display.clearDisplay(); display.setCursor(0,0); display.setTextSize(1); display.println(buff); display.display(); cnt=0; alpha=0; } } </code></pre> <p>it prints first incoming string at place where i wat but when it receives second string it shifts to new line mean changes y position and after that it does not print any thing on display. Could any one can tell me the error i have made here.</p>
[ { "answer_id": 74403141, "author": "Martín", "author_id": 20363318, "author_profile": "https://Stackoverflow.com/users/20363318", "pm_score": 1, "selected": false, "text": "INDIRECT" }, { "answer_id": 74403301, "author": "Ping", "author_id": 20288037, "author_profile": "https://Stackoverflow.com/users/20288037", "pm_score": 0, "selected": false, "text": "=SUM(BYROW(SEQUENCE(B1),LAMBDA(ROW,INDEX(A1:A,ROW))))" }, { "answer_id": 74407583, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 0, "selected": false, "text": "=SUM(A1:INDEX(A:A; B1))\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19503639/" ]
74,403,142
<p>So, I got my Dopdown for Languages, I want to make a href if I press on &quot;English&quot;, how can I do that?</p> <pre><code> &lt;div class=&quot;nav-wrapper&quot;&gt; &lt;div class=&quot;sl-nav&quot;&gt; Sprache: &lt;ul&gt; &lt;li&gt;&lt;b&gt;Deutsch&lt;/b&gt; &lt;i class=&quot;fa fa-angle-down&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt; &lt;div class=&quot;triangle&quot;&gt;&lt;/div&gt; &lt;ul&gt; &lt;li&gt;&lt;i class=&quot;sl-flag flag-de&quot;&gt;&lt;div id=&quot;germany&quot;&gt;&lt;/div&gt;&lt;/i&gt; &lt;span class=&quot;active&quot;&gt;Deutsch&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;i class=&quot;sl-flag flag-usa&quot;&gt;&lt;div id=&quot;germany&quot;&gt;&lt;/div&gt;&lt;/i&gt; &lt;span&gt;English&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;i class=&quot;sl-flag flag-cz&quot;&gt;&lt;div id=&quot;germany&quot;&gt;&lt;/div&gt;&lt;/i&gt; &lt;span&gt;Česky&lt;/span&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Im pretty new, to HTML and don't know where to put my href</p>
[ { "answer_id": 74403167, "author": "Henryc17", "author_id": 14595300, "author_profile": "https://Stackoverflow.com/users/14595300", "pm_score": 0, "selected": false, "text": "<a>" }, { "answer_id": 74403203, "author": "PataFoos", "author_id": 3092931, "author_profile": "https://Stackoverflow.com/users/3092931", "pm_score": 1, "selected": false, "text": "<li><a href=\"your_link\"><i class=\"sl-flag flag-usa\"><div id=\"germany\"></div></i> <span>English</span></a></li> \n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20302661/" ]
74,403,155
<p>I can't seem to find a way to intentionally yield or throw an error in a stream in such a way that can be used by an AsyncValue widget in the tree (using Riverpod for State Management).</p> <pre><code>class AsyncValueWidget&lt;T&gt; extends StatelessWidget { AsyncValueWidget( {Key? key, required this.value, required this.data : super(key: key); final AsyncValue&lt;T&gt; value; final Widget Function(T) data; @override Widget build(BuildContext context) { return value.when( data: data error: (e, st) =&gt; Center(child: ErrorMessageWidget(e.toString())), loading: () =&gt; const Center(child: CircularProgressIndicator()), ); } } </code></pre> <p>I want the stream in my fake repo to return a value in certain cases and Exception in other cases: `</p> <pre><code> Stream&lt;T&gt; function() async* { await Future.delayed(const Duration(milliseconds: 500)); switch (condition) { case condition 1: yield value1; break; case condition 2: yield value2; break; case condition 3: // neither these work throw Exception('You should not be able to call this function under this condition'); yield* Stream.error()... case condition 4: yield null; break; } } </code></pre> <p>`</p> <p>Unfortunately, the Exception/Error does not seem to make it to the widget and I get a nasty red screen. I've also tried try/catch to no avail. Any ideas?</p>
[ { "answer_id": 74403167, "author": "Henryc17", "author_id": 14595300, "author_profile": "https://Stackoverflow.com/users/14595300", "pm_score": 0, "selected": false, "text": "<a>" }, { "answer_id": 74403203, "author": "PataFoos", "author_id": 3092931, "author_profile": "https://Stackoverflow.com/users/3092931", "pm_score": 1, "selected": false, "text": "<li><a href=\"your_link\"><i class=\"sl-flag flag-usa\"><div id=\"germany\"></div></i> <span>English</span></a></li> \n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13873955/" ]
74,403,181
<p>I have a pandas dataframe <code>df</code> that I built using 3 levels of columns, as follows:</p> <pre><code> a1 a2 a3 b1 b2 b1 b3 b1 b4 c1 c2 c1 c2 c1 c2 c1 c2 c1 c2 c1 c2 ... (data) ... </code></pre> <p>Note that each <code>a</code> column may have different <code>b</code> subcolumns, but each <code>b</code> column has the same <code>c</code> subcolumns.</p> <p>I can extract e.g. the subcolumns from <code>a2</code> using <code>df[&quot;a2&quot;]</code>.</p> <p>How can I select based on the second or third level without having to specify the first and second level respectively? For instance I would like to say &quot;give me all the <code>c2</code> columns you can find&quot; and I would get:</p> <pre><code> a1 a2 a3 b1 b2 b1 b3 b1 b4 ... (data for the c2 columns) ... </code></pre> <p>Or &quot;give me all the <code>b1</code> columns&quot; and I would get:</p> <pre><code> a1 a2 a3 c1 c2 c1 c2 c1 c2 ... (data for the b1 columns) ... </code></pre>
[ { "answer_id": 74403413, "author": "fsimonjetz", "author_id": 15873043, "author_profile": "https://Stackoverflow.com/users/15873043", "pm_score": 3, "selected": true, "text": "slice" }, { "answer_id": 74403468, "author": "Matteo Zanoni", "author_id": 13384774, "author_profile": "https://Stackoverflow.com/users/13384774", "pm_score": 1, "selected": false, "text": "MultiIndex" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1028138/" ]
74,403,187
<p>I want the image in my site to completely change when the browser is resized. I've been using media-queries, but I can't seem to get it right. Any thoughts/tips? The thing is I have tried the display trick with media query but its not working</p> <p>I did this, but it's not working even when I am lowering the viewport. The image in the laptop viewport remains the same in the phone viewport.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.blocks { height: 58%; } .mob { display: none; } @media (max-width:400px) { .mob { display: block; } .blocks { display: none; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="col-lg-6 border:1px"&gt; &lt;img class="blocks" src="https://via.placeholder.com/200" alt="laptop-mockup"&gt; &lt;img class="mob" src="https://via.placeholder.com/200/ff0000" alt="android-mockup"&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>The whole html and css code: HTML</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt;News homepage&lt;/title&gt; &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; sizes=&quot;32x32&quot; href=&quot;./images/favicon-32x32.png&quot;&gt; &lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js&quot; integrity=&quot;sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot; integrity=&quot;sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;css/styles.css&quot;&gt; &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.googleapis.com&quot;&gt; &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.gstatic.com&quot; crossorigin&gt; &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Poppins:wght@400&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt; &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Noto+Sans:wght@600;700;800&amp;family=PT+Sans:wght@700&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;navigator&quot;&gt; &lt;nav class=&quot;navbar navbar-expand-sm navbar-dark navbar-light&quot;&gt; &lt;a class=&quot;navbar-brand&quot; href=&quot;&quot;&gt; &lt;img src=&quot;C:\Users\91826\Desktop\news-homepage-main\css\images\logo.svg&quot; alt=&quot;My Happy SVG&quot; /&gt;&lt;/a&gt; &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-bs-toggle=&quot;collapse&quot; data-bs-target=&quot;#navbarSupportedContent&quot; aria-controls=&quot;navbarSupportedContent&quot; aria-expanded=&quot;false&quot; aria-label=&quot;Toggle navigation navbar-light&quot;&gt; &lt;span class=&quot;navbar-toggler-icon navi&quot;&gt;&lt;/span&gt; &lt;/button&gt; &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarSupportedContent&quot;&gt; &lt;ul class=&quot;navbar-nav ms-auto&quot;&gt; &lt;li class=&quot;nav-item ms-auto navelement&quot;&gt; &lt;a class=&quot;nav-link &quot; href=&quot;#footer&quot;&gt;Home &lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item ms-auto navelement&quot;&gt; &lt;a class=&quot;nav-link &quot; href=&quot;#pricing&quot;&gt; New &lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item ms-auto navelement&quot;&gt; &lt;a class=&quot;nav-link &quot; href=&quot;#cta&quot;&gt; Popular &lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item ms-auto navelement&quot;&gt; &lt;a class=&quot;nav-link&quot; href=&quot;#footer&quot;&gt; Trending &lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item ms-auto navelement&quot;&gt; &lt;a class=&quot;nav-link &quot; href=&quot;#footer&quot;&gt; Categories &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/nav&gt; &lt;/div&gt; &lt;div class=&quot;row &quot;&gt; &lt;div class=&quot;col-lg-6 border:1px&quot;&gt; &lt;img class=&quot;blocks&quot; src=&quot;C:\Users\91826\Desktop\news-homepage-main\css\images\image-web-3-desktop.jpg&quot; alt=&quot;laptop-mockup&quot;&gt; &lt;img class=&quot;mob&quot; src=&quot;C:\Users\91826\Desktop\news-homepage-main\css\images\image-web-3-mobile.jpg&quot; alt=&quot;android-mockup&quot;&gt; &lt;/div&gt; &lt;div class=&quot;tag&quot;&gt; &lt;h1 class=&quot;tagline&quot;&gt;The Bright&lt;br /&gt;Future of&lt;br /&gt;Web 3.0?&lt;/h1&gt; &lt;/div&gt; &lt;div class=&quot;read&quot;&gt; &lt;h1 class=&quot;readline&quot;&gt;We dive into the next evolution of the web that claims to put the power of the platforms back into the hands of the people. But is it really fulfilling its promise?&lt;/h1&gt; &lt;/div&gt; &lt;button class=&quot;button-50 readmore&quot; type=&quot;button&quot; name=&quot;button&quot;&gt;READ MORE&lt;/button&gt; &lt;div class=&quot;col-lg-6 border:1px&quot;&gt; &lt;div class=&quot;new&quot;&gt; &lt;h1&gt;New&lt;/h1&gt; &lt;h2&gt;Hydrogen VS Electric Cars&lt;/h2&gt; &lt;h3&gt;Will hydrogen-fueled cars ever catch up to EVs?&lt;/h3&gt; &lt;hr&gt; &lt;h2&gt;The Downsides of AI Artistry&lt;/h2&gt; &lt;h3&gt;What are the possible adverse effects of on-demand AI image generation?&lt;/h3&gt; &lt;hr&gt; &lt;h2&gt;Is VC Funding Drying Up?&lt;/h2&gt; &lt;h3&gt;Private funding by VC firms is down 50% YOY. We take a look at what that means.&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;info&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-lg-4 box&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-lg-2 box&quot;&gt; &lt;img class=&quot;infoimg&quot; src=&quot;C:\Users\91826\Desktop\news-homepage-main\css\images\image-retro-pcs.jpg&quot; alt=&quot;&quot; /&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-2 box&quot;&gt; &lt;div class=&quot;inf&quot;&gt; &lt;h1 class=&quot;infohead1 &quot;&gt; 01&lt;/h1&gt; &lt;h2 class=&quot;infohead2&quot;&gt; Reviving Retro PCs&lt;/h2&gt; &lt;h3 class=&quot;infohead3&quot;&gt; What happens when old PCs&lt;br&gt;are given modern upgrades?&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-4 box2&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-lg-2 box&quot;&gt; &lt;img class=&quot;infoimg&quot; src=&quot;C:\Users\91826\Desktop\news-homepage-main\css\images\image-gaming-growth.jpg&quot; alt=&quot;&quot;&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-2 box&quot;&gt; &lt;div class=&quot;inf1 inf&quot;&gt; &lt;h1 class=&quot;infohead1&quot;&gt; 02&lt;/h1&gt; &lt;h2 class=&quot;infohead2&quot;&gt; Top 10 laptops of 2022&lt;/h2&gt; &lt;h3 class=&quot;infohead3&quot;&gt;Our best picks for various &lt;br&gt; needs and budgets.&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-4 box2&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-lg-2 box&quot;&gt; &lt;img class=&quot;infoimg&quot; src=&quot;C:\Users\91826\Desktop\news-homepage-main\css\images\image-top-laptops.jpg&quot; alt=&quot;&quot;&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-2 box&quot;&gt; &lt;div class=&quot;inf&quot;&gt; &lt;h1 class=&quot;infohead1&quot;&gt; 03&lt;/h1&gt; &lt;h2 class=&quot;infohead2&quot;&gt; The Growth of Gaming&lt;/h2&gt; &lt;h3 class=&quot;infohead3&quot;&gt;How the pandemic has sparked &lt;br&gt; fresh opportunities.&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;hr class=&quot;hori&quot;&gt; &lt;div class=&quot;attribution&quot;&gt; Challenge by &lt;a href=&quot;https://www.frontendmentor.io?ref=challenge&quot; target=&quot;_blank&quot;&gt;Frontend Mentor&lt;/a&gt;. Coded by &lt;a href=&quot;https://cyberoctane29.github.io/MySite/&quot;&gt;Saswat Seth&lt;/a&gt;. &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>CSS</p> <pre><code> .navigator { margin-bottom: 2%; } body { padding: 0% 10% 2% 10%; } .nav-link { color: black; } :hover.nav-link { color: #6B728E; } .navigator { padding: 2% 5% 0% 0%; } .blocks { height: 58%; } .mob { display: none; } @media (max-width:400px) { .mob { display:block; } .blocks { display:none; } } .new { height: 85%; width: 23%; background: hsl(240, 100%, 5%); position: absolute; right: 140px; padding: 2%; } .navelement { padding-right: 6%; font-size: 100%; } h1 { color: hsl(35, 77%, 62%); font-family: 'noto sans'; font-weight: 600; } h2 { color: #fff; font-size: 23px; margin-top: 10%; font-family: 'noto sans'; font-weight: 700; } h3 { color: #6B728E; font-size: 15px; padding: 4% 0%; line-height: 25px; } hr { color: #fff; border-top: solid white; } .tag { position: absolute; bottom: 20px; } .tagline { font-family: 'noto sans'; color: #000; font-weight: 800; font-size: 60px; } .read { padding: 2% 38%; position: absolute; bottom: 54px; right: -15px; } .readline { font-size: 110%; color: #6B728E; line-height: 27px; } .button-50 { height: 49px; width: 200px; appearance: button; background-color: hsl(5, 85%, 63%); background-image: none; border: 1px solid #000; border-radius: 4px; box-shadow: #B73E3E 4px 4px 0 0, #000 4px 4px 0 1px; box-sizing: border-box; color: #fff; cursor: pointer; display: inline-block; font-family: &quot;Montserrat&quot;; font-size: 18px; font-weight: 400; line-height: 20px; margin: 20% 5% 10% 0%; overflow: visible; padding: 14px 30px; text-align: center; text-transform: none; touch-action: manipulation; user-select: none; -webkit-user-select: none; vertical-align: middle; white-space: nowrap; position: absolute; bottom: -45px; right: 45%; } .button-50:focus { text-decoration: none; } .button-50:hover { text-decoration: none; } .button-50:active { box-shadow: rgba(0, 0, 0, .125) 0 3px 5px inset; outline: 0; } .button-50:not([disabled]):active { box-shadow: #C9BBCF 2px 2px 0 0, #1d1716 2px 2px 0 1px; transform: translate(2px, 2px); } .readmore { margin: 10% 3% 5% 0; font-family: 'Poppins'; font-weight: 400; } .info { margin-top: 5%; margin-left: 10%; position: absolute; right: 10%; } .infoimg { width: 315%; padding: 20%; } .infohead1 { color: #7D9D9C; } .infohead2 { color: #000; } .inf { padding: 30%; margin-left: 68px; white-space: nowrap; } .hori { margin-top: 10%; color: #000; border-top: solid black; } </code></pre>
[ { "answer_id": 74403413, "author": "fsimonjetz", "author_id": 15873043, "author_profile": "https://Stackoverflow.com/users/15873043", "pm_score": 3, "selected": true, "text": "slice" }, { "answer_id": 74403468, "author": "Matteo Zanoni", "author_id": 13384774, "author_profile": "https://Stackoverflow.com/users/13384774", "pm_score": 1, "selected": false, "text": "MultiIndex" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20477983/" ]
74,403,200
<p>There are multiple parts of Compose that deal with environment variables in one sense or another. So how do I pass Environment variables in Compose ( docker-compose )</p> <p>According to the documentation If you have multiple environment variables, you can substitute them by adding them to a default environment variable file named .env or by providing a path to your environment variables file using the --env-file command line option.</p> <pre><code>version: '3.9' services: nginx: image: nginx:stable-alpine container_name: nginx ports: - 80:80 - 443:443 restart: always volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf postgres: container_name: postgres image: postgres:13-alpine environment: - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} - POSTGRES_DB=${DB_DATABASE} volumes: - ./pgdata:/var/lib/postgresql/data - ./database/app.sql:/docker-entrypoint-initdb.d/app.sql restart: always ports: - &quot;35000:5432&quot; networks: - app_network app-api: container_name: app-api build: dockerfile: Dockerfile context: ./app-api target: production environment: - DB_TYPE=${DATABASE_TYPE} - POSTGRES_HOST=${DB_HOST} - POSTGRES_USER=${DB_USER} - POSTGRES_PASS=${DB_PASSWORD} - POSTGRES_DB=${DB_DATABASE} - POSTGRES_PORT=${DB_PORT} - APP_PORT=${SERVER_PORT} - NODE_ENV:production ## AWS - AWS_S3_ACCESS_KEY=${AWS_S3_ACCESS_KEY} - AWS_S3_SECRET_ACCESS_KEY=${AWS_S3_SECRET_ACCESS_KEY} - AWS_S3_BUCKET=${AWS_S3_BUCKET} - AWS_S3_REGION=${AWS_S3_REGION} ports: - &quot;5050:80&quot; volumes: - ./pgadmin-data:/var/lib/pgadmin depends_on: - postgres links: - postgres networks: - app_network pgadmin: container_name: pgadmin image: dpage/pgadmin4 restart: always environment: - PGADMIN_DEFAULT_EMAIL=${PGADMIN_DEFAULT_EMAIL} - PGADMIN_DEFAULT_PASSWORD=${PGADMIN_DEFAULT_PASSWORD} - PGADMIN_LISTEN_PORT=${PGADMIN_LISTEN_PORT} restart: always ports: - &quot;5400:5400&quot; depends_on: - postgres links: - postgres networks: - app_network </code></pre>
[ { "answer_id": 74403413, "author": "fsimonjetz", "author_id": 15873043, "author_profile": "https://Stackoverflow.com/users/15873043", "pm_score": 3, "selected": true, "text": "slice" }, { "answer_id": 74403468, "author": "Matteo Zanoni", "author_id": 13384774, "author_profile": "https://Stackoverflow.com/users/13384774", "pm_score": 1, "selected": false, "text": "MultiIndex" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14447569/" ]
74,403,222
<p>I'am quite new to F#, and was solving some basic exercises when i stumbled upon this function</p> <ol> <li>Give the (most general) types of g1 and g2 and describe what each of these two functions computes. Your description for each function should focus on what it computes, rather than on individual computation steps</li> </ol> <pre class="lang-ml prettyprint-override"><code> let rec g1 p = function | x::xs when p x -&gt; x :: g1 p xs | _ -&gt; [];; </code></pre> <p>i don't the understand &quot; when p x &quot; part, or how to call the function. can someone please explain what this function takes in as an argument? as just calling the function like that &quot; g1 [1;2;3] &quot; gives me an error.</p> <p>Tried calling the function, and tried reading some text books to figure it out</p>
[ { "answer_id": 74403413, "author": "fsimonjetz", "author_id": 15873043, "author_profile": "https://Stackoverflow.com/users/15873043", "pm_score": 3, "selected": true, "text": "slice" }, { "answer_id": 74403468, "author": "Matteo Zanoni", "author_id": 13384774, "author_profile": "https://Stackoverflow.com/users/13384774", "pm_score": 1, "selected": false, "text": "MultiIndex" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20478173/" ]
74,403,229
<p>I am trying to replace multiple categorical variables from a dataframe with a set of values.</p> <p>I tried the following codes:</p> <pre><code>data['Gender'] = data['Gender'].replace(to_replace={&quot;male&quot;,&quot;M&quot;,&quot;m&quot;,&quot;female&quot;,&quot;f&quot;,&quot;F&quot;}, value={&quot;Male&quot;,&quot;Male&quot;,&quot;Male&quot;,&quot;Female&quot;, &quot;Female&quot;, &quot;Female&quot;}). </code></pre> <p>I want every m, M, or male to be replaced by Male. Same for the female category.</p> <p>I got error:</p> <p>ValueError: Replacement lists must match in length. Expecting 6 got 2</p>
[ { "answer_id": 74403413, "author": "fsimonjetz", "author_id": 15873043, "author_profile": "https://Stackoverflow.com/users/15873043", "pm_score": 3, "selected": true, "text": "slice" }, { "answer_id": 74403468, "author": "Matteo Zanoni", "author_id": 13384774, "author_profile": "https://Stackoverflow.com/users/13384774", "pm_score": 1, "selected": false, "text": "MultiIndex" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20478096/" ]
74,403,249
<p>I'm using this command to compare two files and print out lines in which $1 is different:</p> <p><code>awk -F, 'NR==FNR {exclude[$1];next} !($1 in exclude)' old.list new.list &gt; changes.list</code></p> <p>the files I'm working with have been sorted numerically with -n</p> <p>old.list:</p> <pre><code>30606,10,57561 30607,100,26540 30611,300,35,5.068 30612,100,211,0.035 30613,200,5479,0.005 30616,100,2,15.118 30618,0,1257,0.009 30620,14,8729,0.021 </code></pre> <p>new.list</p> <pre><code>30606,10,57561 30607,100,26540 30611,300,35,5.068 30612,100,211,0.035 30613,200,5479,0.005 30615,50,874,00.2 30616,100,2,15.118 30618,0,1257,0.009 30620,14,8729,0.021 30690,10,87,0.021 30800,20,97,1.021 </code></pre> <p>Result</p> <pre><code>30615,50,874,00.2 30690,10,87,0.021 30800,20,97,1.021 </code></pre> <p>I'm looking for a way to tweak my command and make awk print lines only if $1 from new.list is not only unique but also &gt; $1 from the last line of the old.list</p> <p>Expected result:</p> <pre><code>30690,10,87,0.021 30800,20,97,1.021 </code></pre> <p>because 30690 and 30800 ($1) &gt; 30620 ($1 from the last line of old.list) in this case, 30615,50,874,00.2 would not be printed because 30615 is admitedly unique to new.list but it's also &lt; 30620 ($1 from the last line of the old.list)</p> <p><code>awk -F, '{if ($1 #from new.list &gt; $1 #from_the_last_line_of_old.list) print }'</code></p> <p>something like that, but I'm not sure it can be done this way?</p> <p>Thank you</p>
[ { "answer_id": 74403594, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 3, "selected": true, "text": "sort" }, { "answer_id": 74409771, "author": "RARE Kpop Manifesto", "author_id": 14672114, "author_profile": "https://Stackoverflow.com/users/14672114", "pm_score": 0, "selected": false, "text": "awk" }, { "answer_id": 74409929, "author": "steffen", "author_id": 845034, "author_profile": "https://Stackoverflow.com/users/845034", "pm_score": 0, "selected": false, "text": "awk -F, 'NR==FNR{x=$1}; $1>x{x=$1; print}' <(tail -n1 old) new\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1444848/" ]
74,403,270
<p>I've built a view that has scroll view of horizontal type with HStack for macOS app. Is there a way to circle those items using keyboard arrows?</p> <p>(I see that ListView has a default behavior but for other custom view types there are none)</p> <p><a href="https://share.cleanshot.com/BwEn6x" rel="nofollow noreferrer">click here to see the screenshot</a></p> <pre><code>var body: some View { VStack { ScrollView(.horizontal, { HStack { ForEach(items.indices, id: \.self) { index in //custom view for default state and highlighted state } } } } } any help is appreciated :) </code></pre>
[ { "answer_id": 74403594, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 3, "selected": true, "text": "sort" }, { "answer_id": 74409771, "author": "RARE Kpop Manifesto", "author_id": 14672114, "author_profile": "https://Stackoverflow.com/users/14672114", "pm_score": 0, "selected": false, "text": "awk" }, { "answer_id": 74409929, "author": "steffen", "author_id": 845034, "author_profile": "https://Stackoverflow.com/users/845034", "pm_score": 0, "selected": false, "text": "awk -F, 'NR==FNR{x=$1}; $1>x{x=$1; print}' <(tail -n1 old) new\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4150758/" ]
74,403,285
<p>I need to have modifed_at fields in my Django project. A field that updates every time a row updates in the database, despite where the update comes from: through calling <code>.save()</code> or through <code>queryset.update()</code> or even when updates happen in the database directly and not from the Django app.</p> <p>there is an <code>auto_now</code> property that does not solve my problem according to <a href="https://stackoverflow.com/questions/59332214/django-update-modified-at-when-doing-update">this SO question(based on Django document)</a>. other SO questions(like <a href="https://stackoverflow.com/questions/52159958/auto-now-field-is-not-updating-with-updating-using-filter">this</a> and <a href="https://stackoverflow.com/questions/37766018/how-to-create-a-datetimefiled-that-keeps-the-last-edited-time-in-django">this</a>) ask the same thing, update instance at every change not only <code>.save()</code></p> <p>This problem can be solved using triggers as said <a href="https://stackoverflow.com/questions/1035980/update-timestamp-when-row-is-updated-in-postgresql">here</a> but this way we need to write the same trigger for every modifed_at field in models.</p> <p>as discussed in <a href="https://code.djangoproject.com/ticket/15566" rel="nofollow noreferrer">this Django ticket</a> this problem will not be addressed and solved in Django. even <a href="https://gist.github.com/anonymous/1872523#L83" rel="nofollow noreferrer">the suggested patch</a> only updates the instance if it changes via Django.</p> <p>the only way that comes to my mind is to do <a href="https://stackoverflow.com/questions/10924619/setting-database-level-defaults-for-fields-in-django">something like this</a> in a mixin. a mixin that when inherited creates a trigger for fields with auto_now=True. maybe change SQL when Django creates the model creation SQL. but I don't know how to implement this.</p> <p>so I have two questions:</p> <ol> <li>what is the best way to achieve database-level updates for modified_at fields</li> <li>If my suggested way is the best option how to implement it?</li> </ol> <p>I would like to have a database-agnostic solution but FYI currently I'm using PostgreSQL.</p>
[ { "answer_id": 74403428, "author": "kwamito", "author_id": 19922269, "author_profile": "https://Stackoverflow.com/users/19922269", "pm_score": -1, "selected": false, "text": "auto_now" }, { "answer_id": 74403921, "author": "Felix Eklöf", "author_id": 7088596, "author_profile": "https://Stackoverflow.com/users/7088596", "pm_score": 0, "selected": false, "text": "makemigrations" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3310179/" ]
74,403,293
<p>I want to create a function to find the lowest value within a set of numbers, but I do not wish to use the Math.min(); method. Below is my code I have constructed:</p> <pre><code>function min(arr) { var lowest = arr.sort((x, y) =&gt; x - y); return lowest[0]; } </code></pre> <p>but 'arr.sort' is not a function, as it has not been defined for obvious reasons: I want to be able to input <em>any</em> array into the 'min' function.</p> <p>I tried creating a JavaScript function for finding the lowest value in an array of numbers, expecting to have a function that would accept any array and would output the lowest value in that array.</p>
[ { "answer_id": 74403375, "author": "mplungjan", "author_id": 295783, "author_profile": "https://Stackoverflow.com/users/295783", "pm_score": 1, "selected": false, "text": "const min = arr => arr.sort((a, b) => b - a).pop();\n\n\nconsole.log(min([7,6,8,99,100]))\nconsole.log(min([1000,999,998,997]))\nconst arr1 = [1000,999,998,997]\nconsole.log(\"---------------\")\nconsole.log(arr1)\nconsole.log(min(arr1))\nconsole.log(arr1)" }, { "answer_id": 74403395, "author": "Konstantinos Solakis", "author_id": 14844442, "author_profile": "https://Stackoverflow.com/users/14844442", "pm_score": -1, "selected": false, "text": "function min(arr) {\n arr.sort( (a, b) => a - b );\n return arr[0]\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20181987/" ]
74,403,326
<p>I'm trying to set up a Functions class that will handle functions for my NN projects. I've figured out I'd like the list of functions to be somewhat flexible (easily add, or remove functions used).</p> <p>I've created a list of functions, defined a bunch of lambda functions, added a method that adds all the functions in the body to the list. When I try to check the length of the list it shows the correct number, but when I try to retrieve a function into a variable and pass it an argument I get an information that lambda takes 1 argument and I gave it 2. I don't understand what is the second argument.</p> <pre><code> import numpy as np class Functions(): f0 = identity = lambda x: x f1 = linear_step = lambda x: 1 if x &gt; 0 else 0 f2 = sigmoid = lambda x: 1/(1+np.exp(-x)) f3 = tanh = lambda x: np.tanh(x) f4 = swish = lambda x: x/(1+np.exp(-x)) f5 = absolute = lambda x: abs(x) f6 = cubic = lambda x: x**3 f7 = square = lambda x: x**2 f8 = sinusoid = lambda x: np.sin(x) f9 = square_root = lambda x: np.sqrt(x) f10 = cubic_root = lambda x: np.cbrt(x) f11 = opposite = lambda x: -x f12 = inverse = lambda x: 1/x f13 = exponential = lambda x: np.exp(x) def __init__(self): #constructor self._functions = [] self.add_functions(self.f0, self.f1, self.f2, self.f3, self.f4, self.f5, self.f6, self.f7, self.f8, self.f9, self.f10, self.f11, self.f12, self.f13) #add a fyunction to the list, if it is not already there def _add_function(self, function): if function not in self._functions: self._functions.append(function) #print(f&quot;Added function: {function.__name__}&quot;) return True else: #print(f&quot;Function: {function.__name__} already exists at index: {functions.index(function)}&quot;) return False #add multiple functions to the list def add_functions(self, *args): for function in args: self._add_function(function) #get the number of functions in the list def number_of_functions(self): return len(self._functions) #return the function at the given index def get_function(self, index): try: return self._functions[index] except IndexError: print(&quot;Index out of range&quot;); return None def get_all_functions(self): return self._functions functs = Functions() print(f&quot;number of functions {functs.number_of_functions()}&quot;) iden = functs.get_function(0) print(f&quot;identity of one is {iden(1)}&quot;) </code></pre> <p>What's causing the issue? Alternatively what would be a better way to have an enumerable data structure to store and load the activation functions?</p>
[ { "answer_id": 74403435, "author": "Temba", "author_id": 3593621, "author_profile": "https://Stackoverflow.com/users/3593621", "pm_score": 3, "selected": true, "text": "add_function" }, { "answer_id": 74403533, "author": "LeopardShark", "author_id": 8425824, "author_profile": "https://Stackoverflow.com/users/8425824", "pm_score": 2, "selected": false, "text": "self.f1" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18218285/" ]
74,403,337
<p>The __index of the table originally set a meta table, and the actual access is to the function under this meta table.</p> <p><code>setmetatable(flatTbl, {__index = metaTbl}</code></p> <p>I want to access the function of the same name of the meta table when the field of the table is not accessible, but I have used two methods without success</p> <pre><code>function FlatBufferTools:SetMeta(flatTbl) setmetatable(flatTbl, { __index = function(tbl, key) metaTbl = getmetatable(tbl).__index return metaTbl[key](metaTbl) end }) end function FlatBufferTools:SetMeta2(flatTbl) metaTbl = getmetatable(flatTbl).__index setmetatable(metaTbl, { __index = function(tbl, key) return tbl[key](tbl) end }) end </code></pre> <p>The first method is to reset the <code>__index</code> of the table, but the <code>metaTbl</code> that i get is a function</p> <p>The second method is to set <code>__index</code> to the table's meta table(<code>metaTbl</code>), but the setmetatable function skips it</p> <p>I checked the <code>metaTbl</code> and there is no <code>__metatable</code></p>
[ { "answer_id": 74404137, "author": "Piglet", "author_id": 2858170, "author_profile": "https://Stackoverflow.com/users/2858170", "pm_score": 1, "selected": false, "text": "local meta = { myFunc = function () print(\"metatable here\") end }\nmeta.__index = meta\n\nlocal a = setmetatable({}, meta)\na.myFunc()\n" }, { "answer_id": 74407199, "author": "koyaanisqatsi", "author_id": 11740758, "author_profile": "https://Stackoverflow.com/users/11740758", "pm_score": 0, "selected": false, "text": "table" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20128147/" ]
74,403,352
<p>I am trying to use Python to automate a number of work processes that primarily take place in an online content management system, and to access the CMS, I need to be logged into my work profile on Chrome. While I could sign in once Chromedriver is open, I would have to approve the login on my authenticator each time, somewhat defeating the purpose of automation.</p> <p>I am using the following code for opening Chromedriver and attempting to load my regular Chrome profile. However, while the rest of the code works as intended, it does not load my profile and I am unsure why.</p> <pre><code>from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.add_argument(&quot;--start-maximized&quot;) options.add_argument(&quot;--user-data-dir=C:\\Users\\Saul\\AppData\\Local\\Google\\Chrome\\User Data\\Default&quot;) driver = webdriver.Chrome(&quot;C:\\Users\\Saul\\Downloads\\chromedriver_win32\\chromedriver.exe&quot;, options=options) driver.get(&quot;https://myaccount.google.com/&quot;) while(True): pass </code></pre> <p>I do get the following error while running the code, but I don't believe this is affecting my issue.</p> <blockquote> </blockquote> <pre><code>C:\Users\Saul\PycharmProjects\OnlineAutomation\main.py:12: DeprecationWarning: executable_path has been deprecated, please pass in a Service object driver = webdriver.Chrome(&quot;C:\\Users\\Saul\\Downloads\\chromedriver_win32\\chromedriver.exe&quot;, options=options) </code></pre>
[ { "answer_id": 74404137, "author": "Piglet", "author_id": 2858170, "author_profile": "https://Stackoverflow.com/users/2858170", "pm_score": 1, "selected": false, "text": "local meta = { myFunc = function () print(\"metatable here\") end }\nmeta.__index = meta\n\nlocal a = setmetatable({}, meta)\na.myFunc()\n" }, { "answer_id": 74407199, "author": "koyaanisqatsi", "author_id": 11740758, "author_profile": "https://Stackoverflow.com/users/11740758", "pm_score": 0, "selected": false, "text": "table" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20476541/" ]
74,403,355
<p>Folks, I am new to Next.js 13.</p> <p>I have created a project using Next.js 13 and playing around with the new <code>app</code> directory.</p> <p>I am trying to apply styling using Tailwind CSS. I have followed the Next.js documentation below:</p> <p><a href="https://beta.nextjs.org/docs/styling/tailwind-css" rel="nofollow noreferrer">https://beta.nextjs.org/docs/styling/tailwind-css</a></p> <p>The documentation says to import the <code>global.css</code> stylesheet to the root layout (<code>app/layout.js</code>) in order to apply the styles to every route in your application. I tried to follow this step, but I am getting the following error:</p> <p><a href="https://i.stack.imgur.com/gh4tv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gh4tv.png" alt="enter image description here" /></a></p> <p>Here is my folder structure:</p> <p><a href="https://i.stack.imgur.com/wuFUf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wuFUf.png" alt="enter image description here" /></a></p> <p>Here are my code snippets:</p> <p>app/layout.js</p> <pre><code>import React from &quot;react&quot;; import Link from &quot;next/link&quot;; import &quot;../styles/global.css&quot;; const Layout = ({ children }) =&gt; { return ( &lt;&gt; &lt;nav className=&quot;w-full h-20 bg-white border-b border-gray-300&quot;&gt; &lt;ul className=&quot;w-40 h-20 p-4 flex justify-between items-center list-none&quot;&gt; &lt;li&gt; &lt;Link href=&quot;/blog&quot;&gt;Blog&lt;/Link&gt; &lt;/li&gt; &lt;li&gt; &lt;Link href=&quot;/projects&quot;&gt;Projects&lt;/Link&gt; &lt;/li&gt; &lt;li&gt; &lt;Link href=&quot;/books&quot;&gt;Books&lt;/Link&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;main&gt;{children}&lt;/main&gt; &lt;/&gt; ); }; export default Layout; </code></pre> <p>styles/global.css</p> <pre><code>@tailwind base; @tailwind components; @tailwind utilities; </code></pre> <p>What am I doing wrong?</p>
[ { "answer_id": 74404137, "author": "Piglet", "author_id": 2858170, "author_profile": "https://Stackoverflow.com/users/2858170", "pm_score": 1, "selected": false, "text": "local meta = { myFunc = function () print(\"metatable here\") end }\nmeta.__index = meta\n\nlocal a = setmetatable({}, meta)\na.myFunc()\n" }, { "answer_id": 74407199, "author": "koyaanisqatsi", "author_id": 11740758, "author_profile": "https://Stackoverflow.com/users/11740758", "pm_score": 0, "selected": false, "text": "table" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9409877/" ]
74,403,374
<p>my code looks like this:</p> <pre><code>library(tidyverse) df &lt;- read.table(header=TRUE, text=' subject sex control q1 q2 1 M 7.9 1 1 2 F 6.3 2 3 3 F 9.5 3 1 4 M 11.5 7 6 ') df %&gt;% mutate_all(~case_when( . == 1 ~ 7, . == 7 ~ 1, TRUE ~ . ) ) </code></pre> <p>I want to replace all 1 with 7 and vice versa but keep everything else.</p> <p>The error states:</p> <blockquote> <p>Error: Problem with <code>mutate()</code> column <code>subject</code>. i <code>subject = (structure(function (..., .x = ..1, .y = ..2, . = ..1) ...</code>. x must be a double vector, not an integer vector.</p> </blockquote> <p>A solution indicates <code>TRUE ~ as.numeric(as.character(.)) )</code> works, but then the sex colum is NA</p> <p>How can I fix this?</p> <p>Edit (add): A suggestion was to use nested if-else, which would work, but I really hope there is a better solution than: <code>df %&gt;% mutate_all(~ifelse(. == 1, 7, ifelse(. == 7, 1, .)))</code></p> <p>imagine a long list of values to be replaced.</p>
[ { "answer_id": 74403451, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 0, "selected": false, "text": "ifelse()" }, { "answer_id": 74403494, "author": "Jonny Phelps", "author_id": 5990938, "author_profile": "https://Stackoverflow.com/users/5990938", "pm_score": 0, "selected": false, "text": "mutate_all" }, { "answer_id": 74403520, "author": "Dave2e", "author_id": 5792244, "author_profile": "https://Stackoverflow.com/users/5792244", "pm_score": 3, "selected": true, "text": "mutate_at()" }, { "answer_id": 74403529, "author": "Chris Ruehlemann", "author_id": 8039978, "author_profile": "https://Stackoverflow.com/users/8039978", "pm_score": 1, "selected": false, "text": "df %>% \n mutate(across(starts_with(\"q\"), \n ~ ifelse(. == 1, 7,\n ifelse(. == 7, 1, .))\n ))\n subject sex control q1 q2\n1 1 M 7.9 7 7\n2 2 F 6.3 2 3\n3 3 F 9.5 3 7\n4 4 M 11.5 1 6\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2032712/" ]
74,403,387
<ul> <li>I pull data from multiple excel and write it back to an aggregated excel file</li> </ul> <p>so I have a list of tuples and each tuple consists of two values like this:</p> <pre><code>tuple = (entity-ID, debitor-name) list = [tuple1, tuple2, ..., tupleN] </code></pre> <p>So it can happen that there are multiple entries with the same debitor-name but with different entity-ID. I want to find all entries where the debitor-name is equal and then merge the diffrent entity-IDs into a list. Context is that there are multiple entities within my company who can all have a credit relation to the same debitor-name. I hope this is understandable.</p> <pre><code>for deb in debitor_list: if deb not in agg_debitor_list: agg_debitor_list.append(deb) </code></pre> <p>This already filters for double entries within a certain entity so for example my debitor_list has following entries: <code>[(&quot;1&quot;, &quot;X AG&quot;), (&quot;1&quot;, &quot;X AG&quot;), (&quot;1&quot;, &quot;Z AG&quot;), (&quot;2&quot;, &quot;X AG&quot;), (&quot;2&quot;, &quot;X AG&quot;)]</code> it gives me <code>[(&quot;1&quot;, &quot;X AG&quot;), (&quot;1&quot;, &quot;Z AG&quot;), (&quot;2&quot;, &quot;X AG&quot;)]</code> as result I need something like this <code>[([&quot;1&quot;, &quot;2&quot;], &quot;X AG&quot;), ([&quot;1&quot;], &quot;Z AG&quot;)]</code> to write in back in the aggregated excel file.</p>
[ { "answer_id": 74403451, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 0, "selected": false, "text": "ifelse()" }, { "answer_id": 74403494, "author": "Jonny Phelps", "author_id": 5990938, "author_profile": "https://Stackoverflow.com/users/5990938", "pm_score": 0, "selected": false, "text": "mutate_all" }, { "answer_id": 74403520, "author": "Dave2e", "author_id": 5792244, "author_profile": "https://Stackoverflow.com/users/5792244", "pm_score": 3, "selected": true, "text": "mutate_at()" }, { "answer_id": 74403529, "author": "Chris Ruehlemann", "author_id": 8039978, "author_profile": "https://Stackoverflow.com/users/8039978", "pm_score": 1, "selected": false, "text": "df %>% \n mutate(across(starts_with(\"q\"), \n ~ ifelse(. == 1, 7,\n ifelse(. == 7, 1, .))\n ))\n subject sex control q1 q2\n1 1 M 7.9 7 7\n2 2 F 6.3 2 3\n3 3 F 9.5 3 7\n4 4 M 11.5 1 6\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16965070/" ]
74,403,390
<p>Print elements from object. Ex.</p> <pre><code>const emps = { &quot;Jacobs&quot;: [&quot;Emiel&quot;, &quot;Svjetlana&quot;, &quot;Ivanna&quot;], &quot;Ivanna&quot;: [&quot;Michael&quot;, &quot;Lawson&quot;], &quot;Emiel&quot;: [&quot;John&quot;, &quot;Ruby&quot;], &quot;Lawson&quot;: [], &quot;Michael&quot;: [&quot;Lindsay&quot;, &quot;Ferguson&quot;], &quot;Ferguson&quot;: [] } </code></pre> <p>In above example lets suppose &quot;Jacob&quot; is Parent of &quot;Emiel&quot;, &quot;Svjetlana&quot;, &quot;Ivanna&quot;, so we have to print sequence &quot;Jacob&quot; &quot;Emiel&quot;, &quot;Svjetlana&quot;, &quot;Ivanna&quot; means first Parent then childs.</p> <pre><code>Output should be: &quot;Jacob&quot; &quot;Emiel&quot; &quot;Svjetlana&quot; &quot;Ivanna&quot; &quot;Emiel&quot; &quot;John&quot; &quot;Ruby&quot; &quot;Ivanna&quot; &quot;Michael&quot; &quot;Lawson&quot; &quot;Michael&quot; &quot;Lindsay&quot; &quot;Ferguson&quot; </code></pre>
[ { "answer_id": 74403451, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 0, "selected": false, "text": "ifelse()" }, { "answer_id": 74403494, "author": "Jonny Phelps", "author_id": 5990938, "author_profile": "https://Stackoverflow.com/users/5990938", "pm_score": 0, "selected": false, "text": "mutate_all" }, { "answer_id": 74403520, "author": "Dave2e", "author_id": 5792244, "author_profile": "https://Stackoverflow.com/users/5792244", "pm_score": 3, "selected": true, "text": "mutate_at()" }, { "answer_id": 74403529, "author": "Chris Ruehlemann", "author_id": 8039978, "author_profile": "https://Stackoverflow.com/users/8039978", "pm_score": 1, "selected": false, "text": "df %>% \n mutate(across(starts_with(\"q\"), \n ~ ifelse(. == 1, 7,\n ifelse(. == 7, 1, .))\n ))\n subject sex control q1 q2\n1 1 M 7.9 7 7\n2 2 F 6.3 2 3\n3 3 F 9.5 3 7\n4 4 M 11.5 1 6\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20478139/" ]
74,403,397
<p>I have a dataframe like below</p> <pre><code>+--+--+-----------+ | a| b| date| +--+--+-----------+ | 1| 2| 01/01/2022| | 2| 3| 01/01/2021| | 3| 4| 12/20/2021| +--+--+-----------+ </code></pre> <p>I have tried the code below but it keeps showing the 01/01/2022 date even though 30/12/2021 is not greater than 01/01/2022.</p> <pre><code> df.filter((&quot;30/12/2021&quot; &gt; col(&quot;date&quot;)) </code></pre> <p>I have tried casting both to dates and it returns 0 records then.</p> <pre><code>df.filter(&quot;cast(StartDate as date) &gt;= cast('2017-02-03' as date)&quot;) </code></pre> <p>Below is sample code</p> <pre><code>from pyspark.shell import spark from pyspark.sql.functions import col from pyspark.sql.types import StructType, StructField, StringType, IntegerType data2 = [(1, 2,&quot;01/01/2022&quot;), (1, 3,&quot;01/01/2021&quot;), (2, 4,&quot;12/20/2021&quot;), ] schema = StructType([ \ StructField(&quot;a&quot;, IntegerType(), True), \ StructField(&quot;b&quot;, IntegerType(), True), \ StructField(&quot;date&quot;, StringType(), True), \ ]) df = spark.createDataFrame(data=data2, schema=schema) df.filter((&quot;30/12/2021&quot; &gt; col(&quot;date&quot;))).show() </code></pre>
[ { "answer_id": 74403666, "author": "import random", "author_id": 2280890, "author_profile": "https://Stackoverflow.com/users/2280890", "pm_score": 1, "selected": false, "text": "01/01/2022" }, { "answer_id": 74403918, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 0, "selected": false, "text": "df[\"date\"] = df[\"date\"].map(lambda x: datetime.strptime(x, \"%m/%d/%Y\"))\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9390633/" ]
74,403,400
<pre><code>### created arrays $cell = [System.Collections.ArrayList]@() $filepath = [System.Collections.ArrayList]@() $index = $cell.IndexOf($_) ### this code pulls values from excel spread sheet as well as that files name and path Get-ChildItem C:\UserS\chaos\OneDrive\Documents\working\srs\dynamic* | ForEach-Object { $xl = New-Object -ComObject excel.application $xl.Visible = $false $woorkbookactive = $xl.Workbooks.Open($_.FullName) $woorksheetactive = $woorkbookactive.Worksheets(&quot;Sheet1&quot;) $RANGE = $woorksheetactive.Range(&quot;A4&quot;) $cell.Add($RANGE.Value()) $filepath.Add($_.FullName) $xl.Quit() } ### the Above code produces these values Selected Criteria: Enrolment Status: Left Selected Criteria: Enrolment Status: Active Selected Criteria: Enrolment Status: Active Permission Type: RESOURCE SCHEME ### $cell Start-Sleep -Seconds 2 switch -exact ($cell) { 'Selected Criteria: Enrolment Status: Active Permission Type: RESOURCE SCHEME'{Write-Host &quot;Found RS&quot;;Write-Host $index};#Rename-Item -Path $filepath[$index] -NewName &quot;DynamicRS.xlsx&quot;;continue} 'Selected Criteria: Enrolment Status: Left'{Write-Host &quot;Found Left&quot;;Write-Host $index};#Rename-Item -Path $filepath[$index] -NewName &quot;DynamicLeft.xlsx&quot;;continue} 'Selected Criteria: Enrolment Status: Active' {Write-Host &quot;Found Active&quot;;Write-Host $index};#Rename-Item -Path $filepath[$index] -NewName &quot;DynamicActive.xlsx&quot;;continue} default{write-host &quot;no match found&quot;} } </code></pre> <p>I have tried with both regex and if statements however the values keep saying no match even though I can clearly see the matches</p> <p>the output i received was this</p> <pre><code>no match found no match found no match found </code></pre> <p>I was expecting this</p> <pre><code>Found RS found Left Found Active </code></pre> <p>and sometimes it does detect them however the output it classes was wrong for example RS become Left and active Become Left.</p>
[ { "answer_id": 74403666, "author": "import random", "author_id": 2280890, "author_profile": "https://Stackoverflow.com/users/2280890", "pm_score": 1, "selected": false, "text": "01/01/2022" }, { "answer_id": 74403918, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 0, "selected": false, "text": "df[\"date\"] = df[\"date\"].map(lambda x: datetime.strptime(x, \"%m/%d/%Y\"))\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19678866/" ]
74,403,448
<p>I have the following vectors:</p> <pre><code>v1 &lt;- c(&quot;R&quot;, &quot;H&quot;, &quot;K&quot;) # * (asterisk sign) v2 &lt;- c(&quot;D&quot;, &quot;E&quot;) # + (plus sign) v3 &lt;- c(&quot;A&quot;) # - (minus sign) </code></pre> <p>Given another string, I'd like to count how many characters belong to <code>v1</code> and <code>v2</code>. For example:</p> <pre><code>x1 &lt;- &quot;GMRRRARRRS&quot; # ***-*** # v1_count = 6 # v2_count = 0 # v3_count = 1 x2 &lt;- &quot;KMRDFRHRAE&quot; # * *+ ***-+ # v1_count = 5 # v2_count = 2 # v3_count = 1 </code></pre> <p>So any character that belongs to the vector will be counted as a single count.</p> <p>The final output will be a data frame or tibble:</p> <pre><code> R,H,K D,E A GMRRRARRRS 6 0 1 KMRDFRHRAE 5 2 1 </code></pre> <p>How can I achieve that with R?</p>
[ { "answer_id": 74403666, "author": "import random", "author_id": 2280890, "author_profile": "https://Stackoverflow.com/users/2280890", "pm_score": 1, "selected": false, "text": "01/01/2022" }, { "answer_id": 74403918, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 0, "selected": false, "text": "df[\"date\"] = df[\"date\"].map(lambda x: datetime.strptime(x, \"%m/%d/%Y\"))\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8391698/" ]
74,403,459
<p>I have some client-side validation against a input type number which</p> <ul> <li>Will accept any number 0 through 99 with 2 decimal places</li> <li>And the values of the decimals must be .00, .25, .33, .5, .67, .75</li> </ul> <p>I've tried with 2 digit length validation but how can I validate specific list of decimal numbers with regex ?</p> <p>/^\d{1,2}(\.\d{1,2})?$/</p> <p><strong>VALID CASES</strong></p> <p>5.25</p> <p>78.5</p> <p>99.75</p> <p><strong>INVALID CASES</strong></p> <p>88.12</p> <p>50.78</p>
[ { "answer_id": 74403666, "author": "import random", "author_id": 2280890, "author_profile": "https://Stackoverflow.com/users/2280890", "pm_score": 1, "selected": false, "text": "01/01/2022" }, { "answer_id": 74403918, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 0, "selected": false, "text": "df[\"date\"] = df[\"date\"].map(lambda x: datetime.strptime(x, \"%m/%d/%Y\"))\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5789013/" ]
74,403,461
<p>I've tried several methods, especially all listed here:</p> <ul> <li><p><a href="https://stackoverflow.com/questions/29884654/button-that-refreshes-the-page-on-click">Button that refreshes the page on click</a></p> </li> <li><p><a href="https://stackoverflow.com/questions/2573979/force-page-reload-with-html-anchors-html-js">Force page reload with html anchors (#) - HTML &amp; JS</a></p> </li> </ul> <p>...but they all seem to only trigger a reload using local cache.</p> <p>Is there any way to trigger a forced reload, bypassing any cache (especially for images) via an HTML button?</p> <p>Alternatively, is there a line of HTML code that would force the page to not use cache at all?</p> <p>The page is a simple static html page that changes a few times a day.</p>
[ { "answer_id": 74404054, "author": "Medrupaloscil", "author_id": 5127494, "author_profile": "https://Stackoverflow.com/users/5127494", "pm_score": 2, "selected": false, "text": "window.location.reload(true)" }, { "answer_id": 74404099, "author": "Cazlo", "author_id": 19743717, "author_profile": "https://Stackoverflow.com/users/19743717", "pm_score": 1, "selected": false, "text": "function reloadClear() {\n window.localStorage.clear();\n window.location.reload(true);\n return false;\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1388921/" ]
74,403,510
<p>I am trying to build a simple video game engine using C#. This is a long time project, which I only want to do out of interest. For the beginning I wanted to implement a math library for linear algebra. I am just a hobby programmer and I am unsure how to make my code as maintainable as possible in the long term. The following questions represent only examples of a problem, which I assume to have a lot more often in this project. <strong>I ask this question with the hope to structure my project properly from the beginning to keep it easy to test and to maintain.</strong></p> <p><strong>What is the best way to define repeating methods like for example the dot product for vector classes of different dimensions?</strong></p> <p>The first implementation I made was to hard code the methods for all vector classes:</p> <pre><code>class Vector2 { public float X { get; } public float Y { get; } // Operations public static float Dot(Vector2 a, Vector2 b) =&gt; a.X * b.X + a.Y * b.Y; ... } class Vector3 { public float X { get; } public float Y { get; } public float Z { get; } // Operations public static float Dot(Vector3 a, Vector3 b) =&gt; a.X * b.X + a.Y * b.Y + a.Z * b.Z; ... } </code></pre> <p>The code is simple, but it doesn't take advantage of the pattern behind the dot product. I would have to do this for all the other vector operations (addition, scalar multiplication, etc.). It is redundant and opens room for errors.</p> <p>An alternative approach would be to define the vector operations once in a base class and to put the vector values in an indexer. In this approach, I would only need to define the abstract method for the indexer in the subclasses:</p> <pre><code>class abstract Vector { // Indexer public float this[int index] values { get =&gt; GetValueByIndex(index) }; protected abstract float GetValueByIndex(int index); // Operations public static float Dot(Vector a, Vector b) { float DotProduct = 0; for (int i = 0; i &lt; values.Length; i++){ DotProduct += a[i] * b[i]; } return DotProduct; } ... } class Vector2 : Vector { public float X { get; } public float Y { get; } protected override float GetValueByIndex(int index) { if (index == 0) return X; if (index == 1) return Y; throw new ArgumentOutOfRangeException(&quot;index must be 0 or 1&quot;); } } class Vector3 : Vector { public float X { get; } public float Y { get; } public float Z { get; } protected override float GetValueByIndex(int index) { if (index == 0) return X; if (index == 1) return Y; if (index == 2) return Z; throw new ArgumentOutOfRangeException(&quot;index must be 0, 1 or 2&quot;); } } </code></pre> <p>The hard coding approach should run faster, which is good considering it should be used for a game engine, but it is also opens more room for error. The base class approach is easier to maintain, but the for loops and conditions would make all calculations slower.</p> <p><strong>Which approach would you prefer or is there an alternative, which allows to get fast and maintainable code at the same time?</strong></p>
[ { "answer_id": 74404054, "author": "Medrupaloscil", "author_id": 5127494, "author_profile": "https://Stackoverflow.com/users/5127494", "pm_score": 2, "selected": false, "text": "window.location.reload(true)" }, { "answer_id": 74404099, "author": "Cazlo", "author_id": 19743717, "author_profile": "https://Stackoverflow.com/users/19743717", "pm_score": 1, "selected": false, "text": "function reloadClear() {\n window.localStorage.clear();\n window.location.reload(true);\n return false;\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20477878/" ]
74,403,513
<p>How to sync an action of many microservices and return a single response to the client that takes into consideration each microservice's response?</p> <p>I'm making a social network application (like Facebook) with microservices, for learning purposes. I've divided the app into following microservices, each will have its own database:</p> <ol> <li><p>Authentication - Login/Register, returns a JWT token. Database stored properties are: UserName, Email, PasswordHash, PasswordSalt.</p> </li> <li><p>UserProfiles - Gets and Updates profiles. Database stored properties are: UserName, FirstName, LastName, Gender, Photos</p> </li> <li><p>UserPosts - user can publish Posts with anything he likes, others can comment. Database stored properties are: UserName, UserPosts, Comments</p> </li> <li><p>Gateway - collects http requests from clients, forwards them to correct microservices</p> </li> </ol> <p>THere will be more, like Messages between users.</p> <p>Some properties in databases will duplicate (UserName, but there can be more). I suppose I cannot avoid that if I want to make the services independent.</p> <p>Now, what do I do if the user decides to change a shared property, like UserName? Obviously it will require every service to update its database. But what if one of services cannot connect to the database or meets some other error? The response should be 500 Internal Server Error. I can see two options for that:</p> <ol> <li>Make the Gateway send an HTTP request to each microservice, requesting an update. How do I pass information about an error in one of the services? This seems a bad approach</li> <li>Publish a message (MassTransit, RabbitMQ) to all microservices with update request. This way I can await a response from each service and decide what to return to client. But who should be the publisher here? Gateway? Authentication?</li> </ol> <p>Is there some other way I have not thought about? I'll be thankful for any good-practice, clean-code advices.</p> <p>Thank you</p> <p>I tried messaging services from Authentication services, since it's the one that creates the User entity in the first place. But it doesn't feel like a good reason to make it there.</p>
[ { "answer_id": 74403815, "author": "Bohdan Stupak", "author_id": 11306392, "author_profile": "https://Stackoverflow.com/users/11306392", "pm_score": 0, "selected": false, "text": "UsernameUpdated" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8455324/" ]
74,403,545
<p>Basically the title. Is there a relatively fast way to modify all, or a bunch of elements of a vector by a given value, for eg. 1? If not, is there some other datatype that would perform this kind of an operation better?</p> <p>I have implemented a for loop that basically adds 1 to every element of a vector. Is there some cleaner/shorter way to go about this?</p> <pre><code>vector&lt;int&gt; vct; for (int i = 0;i&lt;10;i++){ vct.push_back(i); } for (int i = 0;i&lt;vct.size();i++){ vct[i]++; } </code></pre>
[ { "answer_id": 74403762, "author": "Lasersköld", "author_id": 3748275, "author_profile": "https://Stackoverflow.com/users/3748275", "pm_score": 0, "selected": false, "text": "-O3" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16400339/" ]
74,403,548
<p>I have a string that contains an &lt;img&gt;, I need to get the content of the &quot;alt&quot; attribute using regex</p> <p><code>\&lt;p\&gt;this is text\&lt;img src=&quot;https://storage.googleapis.com/staging-grapedata-task-helpful-resource-files-967a/e83759c9-85c8-4b22-b3b7-f3ab76d97f30/0c5185b7-0afd-4bca-882b-b23589fb3255_photo_2022-11-04_16-04-42.jpg%5C&quot; alt=&quot;photo_2022-11-04_16-04-42&quot; /\&gt; and more text\&lt;/p\&gt; </code></p> <p>should return string</p> <p><code>photo_2022-11-04_16-04-42</code></p>
[ { "answer_id": 74403616, "author": "Vincent Flotron", "author_id": 20436111, "author_profile": "https://Stackoverflow.com/users/20436111", "pm_score": 0, "selected": false, "text": "(?<=alt=\")[^\"]*(?=\")\n" }, { "answer_id": 74403653, "author": "pcenta", "author_id": 13416574, "author_profile": "https://Stackoverflow.com/users/13416574", "pm_score": -1, "selected": false, "text": "/alt=\\\"(.*)\\\"/" }, { "answer_id": 74403659, "author": "Mr. Polywhirl", "author_id": 1762224, "author_profile": "https://Stackoverflow.com/users/1762224", "pm_score": 1, "selected": true, "text": "<img>" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19772161/" ]
74,403,580
<p>I have a dataset (df1) with a column that contains Remaining_points for each owner</p> <p>Df1:</p> <pre><code>Id Owner Remaining_points 00001 John 18 00008 Paul 34 00011 Alba 52 00004 Martha 67 </code></pre> <p>And another one with different id’s that contains points Df2</p> <pre><code>Id Points 00025 17 00076 35 00089 51 00092 68 </code></pre> <p>I need to add to df2 a Owner column with most similar Remaining_points on df1</p> <p>Desired dataframe:</p> <pre><code>Id Points Owner 00025 17 John 00076 35 Paul 00089 51 Alba 00092 68 Martha </code></pre> <p>Please, could anyone help me on this? I’m used to work with dplyr but any solution would be very appreciated.</p>
[ { "answer_id": 74403970, "author": "tacoman", "author_id": 10043323, "author_profile": "https://Stackoverflow.com/users/10043323", "pm_score": 2, "selected": false, "text": "df1 <- data.frame(ID = c(\"00001\", \"00008\", \"00011\", \"00004\"),\n Owner = c(\"John\", \"Paul\", \"Alba\", \"Martha\"),\n Remaining_points = c(18, 34, 52, 67))\n\ndf2 <- data.frame(ID = c(\"00025\", \"00076\", \"00089\", \"00092\"),\n Points = c(17, 35, 51, 68))\n\nind <- which(apply(abs(outer(df1$Remaining_points,df2$Points, \"-\")), 2, function(x) x == min(x)), arr.ind = TRUE)\ndf2$Owner <- df1$Owner[ind[,1]]\ndf2\n ID Points Owner\n1 00025 17 John\n2 00076 35 Paul\n3 00089 51 Alba\n4 00092 68 Martha\n\n" }, { "answer_id": 74436530, "author": "wibeasley", "author_id": 1082435, "author_profile": "https://Stackoverflow.com/users/1082435", "pm_score": 1, "selected": false, "text": "outer()" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11351821/" ]
74,403,581
<p>I'm trying to split a column <code>Class</code> into multiple columns and change column names based on that.</p> <pre><code> ID Name Class 0 12 John A 1 13 Mark A 2 14 Tony B 3 15 Marcus C 4 16 Phill D 5 17 Jack A </code></pre> <p>final df</p> <pre><code> ID Name Class A B C D 0 12 John A A 1 13 Mark A A 2 14 Tony B B 3 15 Marcus C C 4 16 Phill D D 5 17 Jack A A </code></pre>
[ { "answer_id": 74403818, "author": "Philip09", "author_id": 13397545, "author_profile": "https://Stackoverflow.com/users/13397545", "pm_score": 1, "selected": false, "text": "#define a function to see if matched value\ndef new_column_val(row, value, column):\n \n if row[column] == value:\n return value\n else:\n return None\n\n#create the new columns\nfor class_name in df[\"class\"].unique():\n\n df[class] = df.apply(new_column_val, args = (class_name, \"class\")\n" }, { "answer_id": 74404184, "author": "LazyClown", "author_id": 3392461, "author_profile": "https://Stackoverflow.com/users/3392461", "pm_score": 2, "selected": false, "text": "import numpy as np\nuniq_class = df['Class'].unique().tolist()\n# create a diagonal matrix with unique class as value\nD = np.diag(uniq_class).tolist()\n# map the diagonal matrix dictionary for each class value\ntemp = dict(zip(uniq_class, D))\n# map class values to the temp dictionary\ndf[uniq_class] = df['Class'].map(temp).tolist()\ndf\n" }, { "answer_id": 74404240, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 1, "selected": false, "text": "mask=pd.get_dummies(df.Class).replace(1,np.nan)\nfor col in mask.columns:\n mask[col].fillna(col, inplace=True)\n\nfinal=df.join(mask.replace(0,np.nan))\nfinal\n ID Name Class A B C D \n\n0 12 John A A\n1 13 Mark A A\n2 14 Tony B B\n3 15 Marcus C C\n4 16 Phill D D\n5 17 Jack A A\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16197819/" ]
74,403,589
<p>There's a request where we need to pick the person with the lowest amount of tasks assigned from each group. Like this:</p> <p>A new task is received. Group A has 10 employees. Employee ABC has the lowest amount of tasks assigned out of the 10, therefore ABC will be assigned to this newly received task.</p> <p>My tables have the following structure:</p> <pre><code>Group Employee Task A John Walk the dog A Jane Pet the cat A Jane Feed the chicken B Mozart Play violin B Mozart Play something B Bach Fix piano C James Cook Eggs C James Fry something C Emma Salad C Emma Hummus </code></pre> <p>If a new task is received for group A, the algorithm would pick John, since he has 1 task only. If a new task is received for group B, the algorithm would pick Back, since he has 1 task only. If a new task is received for group C, how can we pick one using order ASC since they both have 2 tasks?</p> <p>Anybody has any idea how to do it?</p> <p>Thank you</p>
[ { "answer_id": 74403818, "author": "Philip09", "author_id": 13397545, "author_profile": "https://Stackoverflow.com/users/13397545", "pm_score": 1, "selected": false, "text": "#define a function to see if matched value\ndef new_column_val(row, value, column):\n \n if row[column] == value:\n return value\n else:\n return None\n\n#create the new columns\nfor class_name in df[\"class\"].unique():\n\n df[class] = df.apply(new_column_val, args = (class_name, \"class\")\n" }, { "answer_id": 74404184, "author": "LazyClown", "author_id": 3392461, "author_profile": "https://Stackoverflow.com/users/3392461", "pm_score": 2, "selected": false, "text": "import numpy as np\nuniq_class = df['Class'].unique().tolist()\n# create a diagonal matrix with unique class as value\nD = np.diag(uniq_class).tolist()\n# map the diagonal matrix dictionary for each class value\ntemp = dict(zip(uniq_class, D))\n# map class values to the temp dictionary\ndf[uniq_class] = df['Class'].map(temp).tolist()\ndf\n" }, { "answer_id": 74404240, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 1, "selected": false, "text": "mask=pd.get_dummies(df.Class).replace(1,np.nan)\nfor col in mask.columns:\n mask[col].fillna(col, inplace=True)\n\nfinal=df.join(mask.replace(0,np.nan))\nfinal\n ID Name Class A B C D \n\n0 12 John A A\n1 13 Mark A A\n2 14 Tony B B\n3 15 Marcus C C\n4 16 Phill D D\n5 17 Jack A A\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13552281/" ]
74,403,606
<p>I'm having trouble saving the return output from my getLastMatchData() function outside of the function itself. Tried a bunch of different things but to no result. Any help would be very appreciated!</p> <pre><code>import fetch from &quot;node-fetch&quot;; const premier_League_Id = '39' const tottenhamId = '47' const options = { method: 'GET', headers: { 'X-RapidAPI-Key': 'REDACTED', 'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com' } }; function getLastMatchData() { fetch('https://api-football-v1.p.rapidapi.com/v3/fixtures?season=2022&amp;team=47&amp;last=1', options) .then(response =&gt; response.json().then(data =&gt;{ let generalLastMatchData = data['response']; let leagueName = generalLastMatchData[0]['league'].name; let teamNames = generalLastMatchData[0]['teams']; let homeTeam = teamNames['home'].name; let awayTeam = teamNames['away'].name; return [homeTeam, awayTeam]; })) } const lastMatchNames = getLastMatchData(); console.log(lastMatchNames); </code></pre>
[ { "answer_id": 74403818, "author": "Philip09", "author_id": 13397545, "author_profile": "https://Stackoverflow.com/users/13397545", "pm_score": 1, "selected": false, "text": "#define a function to see if matched value\ndef new_column_val(row, value, column):\n \n if row[column] == value:\n return value\n else:\n return None\n\n#create the new columns\nfor class_name in df[\"class\"].unique():\n\n df[class] = df.apply(new_column_val, args = (class_name, \"class\")\n" }, { "answer_id": 74404184, "author": "LazyClown", "author_id": 3392461, "author_profile": "https://Stackoverflow.com/users/3392461", "pm_score": 2, "selected": false, "text": "import numpy as np\nuniq_class = df['Class'].unique().tolist()\n# create a diagonal matrix with unique class as value\nD = np.diag(uniq_class).tolist()\n# map the diagonal matrix dictionary for each class value\ntemp = dict(zip(uniq_class, D))\n# map class values to the temp dictionary\ndf[uniq_class] = df['Class'].map(temp).tolist()\ndf\n" }, { "answer_id": 74404240, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 1, "selected": false, "text": "mask=pd.get_dummies(df.Class).replace(1,np.nan)\nfor col in mask.columns:\n mask[col].fillna(col, inplace=True)\n\nfinal=df.join(mask.replace(0,np.nan))\nfinal\n ID Name Class A B C D \n\n0 12 John A A\n1 13 Mark A A\n2 14 Tony B B\n3 15 Marcus C C\n4 16 Phill D D\n5 17 Jack A A\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14628674/" ]
74,403,613
<p>I'm trying to come up with a SP that creates a certain task, appended by year, for a generic approach. I can create the tasks outside, alone, with the $$ marks, but I can't do it inside JS SP like this:</p> <pre><code>CREATE OR REPLACE PROCEDURE create_exec_tasks_by_year_range() RETURNS varchar LANGUAGE JAVASCRIPT EXECUTE AS OWNER AS $$ var return_value = &quot;&quot;; var range_years = Array.from(Array(new Date().getUTCFullYear() - 2006), (_, i) =&gt; (i + 2007).toString()); //CREATE a task TO CALL SP BY YEAR, FROM 2007-current year range_years.forEach((year_elem) =&gt; { rs = snowflake.createStatement( { sqlText: `CREATE OR REPLACE TASK MY_TSK_YEAR_`+year_elem+` SCHEDULE = 'USING CRON 30 22 * * SUN UTC' AS EXECUTE IMMEDIATE $$ DECLARE year_track float; rs resultset; BEGIN year_track := :1; rs := (execute IMMEDIATE 'INSERT INTO MY_TABLE VALUES(?)' using (year_track)); return TABLE(rs); END; $$ ;` , binds: [year_elem] }).execute(); rs.next(); //rs.getColumnValue(1); return_value += &quot;MY_TSK_YEAR_&quot;+year_elem+&quot;, &quot;; to_exec = snowflake.createStatement( { sqlText: `EXECUTE TASK MY_TSK_YEAR_`+year_elem+` to_exec.next(); return_value += to_exec.getColumnValue(1)+&quot;, &quot;; }); return return_value; $$; </code></pre> <p>because it throws me</p> <pre><code>syntax error line ...at position 2 unexpected 'DECLARE' </code></pre> <p>while creating the TASK manually, works, because I don't have a conflict between $$?</p> <pre><code>CREATE OR REPLACE TASK SHARED.SRC_EXT_WEATHER.TSK_DUMMY SCHEDULE = 'USING CRON 30 22 * * SUN UTC' AS EXECUTE IMMEDIATE $$ DECLARE year_track float; rs resultset; BEGIN year_track := 2007; rs := (execute IMMEDIATE 'INSERT INTO MY_TABLE VALUES(?)' using (year_track)); return TABLE(rs); END; $$; </code></pre> <p>Is it possible to make the SP to work for the TASK created with EXECUTE_IMMEDIATE block and bind parameter? The problem seems to be the way I write in inside the $$ scope of the stored procedure, no?</p>
[ { "answer_id": 74403818, "author": "Philip09", "author_id": 13397545, "author_profile": "https://Stackoverflow.com/users/13397545", "pm_score": 1, "selected": false, "text": "#define a function to see if matched value\ndef new_column_val(row, value, column):\n \n if row[column] == value:\n return value\n else:\n return None\n\n#create the new columns\nfor class_name in df[\"class\"].unique():\n\n df[class] = df.apply(new_column_val, args = (class_name, \"class\")\n" }, { "answer_id": 74404184, "author": "LazyClown", "author_id": 3392461, "author_profile": "https://Stackoverflow.com/users/3392461", "pm_score": 2, "selected": false, "text": "import numpy as np\nuniq_class = df['Class'].unique().tolist()\n# create a diagonal matrix with unique class as value\nD = np.diag(uniq_class).tolist()\n# map the diagonal matrix dictionary for each class value\ntemp = dict(zip(uniq_class, D))\n# map class values to the temp dictionary\ndf[uniq_class] = df['Class'].map(temp).tolist()\ndf\n" }, { "answer_id": 74404240, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 1, "selected": false, "text": "mask=pd.get_dummies(df.Class).replace(1,np.nan)\nfor col in mask.columns:\n mask[col].fillna(col, inplace=True)\n\nfinal=df.join(mask.replace(0,np.nan))\nfinal\n ID Name Class A B C D \n\n0 12 John A A\n1 13 Mark A A\n2 14 Tony B B\n3 15 Marcus C C\n4 16 Phill D D\n5 17 Jack A A\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/250371/" ]
74,403,620
<p>I have a Google CloudRun Service, that is can be accessed either by the CloudRun URL or by a custom domain via a Load Balancer in the Google Cloud.</p> <p>Now I am trying to setup some kind of access control, so that the Service which run the Development Stage can only be accessed by logged-in developers.</p> <p>So far I tried to set the Trigger Configuration of the CloudRun Service to authentication required. That works for the base CloudRun URL, but on adding a path to the base URL I get a Forbidden error, even if I could access the base URL. And Accessing the Service via the LoadBalancer always gives a Forbidden.</p> <p>Is there a way to make the CloudRun Service Accessible (including different Paths) only to LoggedIn Developers?</p> <p>And also is there a way to make the Service only accessible by the LoadBalancer URL and not the CloudRun URL?</p>
[ { "answer_id": 74407158, "author": "Justin Mahood", "author_id": 20480651, "author_profile": "https://Stackoverflow.com/users/20480651", "pm_score": 2, "selected": false, "text": "gcloud" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14771706/" ]
74,403,648
<p>I'm currently working on a project, which includes a website, built and run by Django. On this website, I'm trying to load data through fast API and try to load this data through JavaScript and the Fetch API. But I always get instead of the Data provided through the API, an [object Promise]. I've tried many different methods but none seem to work.</p> <p>I've tried for example:</p> <pre><code>document.getElementById(&quot;1.1&quot;).innerHTML = fetch('the URL') .then(response =&gt; response.text()) </code></pre> <p>or</p> <pre><code>document.getElementById(&quot;1.1&quot;).innerHTML = fetch('the URL') .then(response =&gt; response.text()) .then((response) =&gt; { console.log(response) }) </code></pre> <p>and many other methods. I've also checked and the API request works perfectly, returning a string.</p>
[ { "answer_id": 74407158, "author": "Justin Mahood", "author_id": 20480651, "author_profile": "https://Stackoverflow.com/users/20480651", "pm_score": 2, "selected": false, "text": "gcloud" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20478256/" ]
74,403,673
<p>How can i render the data value in a h1 element? i have created a simple function its work is to just console random meme name and that function works fine but i want that that random name which iam consoling display in a h1 element in my web page so how can i do that? i want that when i click the button that random name display in my web page in a h1 element not in console</p> <pre><code>import React from 'react' import Card from './Card' import memesData from './memesData'; import './MainContent.css'; function MainContent() { function getMemeImage() { const memesArray = memesData.data.memes const randomNumber = Math.floor(Math.random() * memesArray.length) const n = memesArray[randomNumber].name console.log(n) } return ( &lt;div&gt; &lt;button onClick={getMemeImage}&gt; Click me &lt;/button&gt; &lt;/div&gt; ) } export default MainContent </code></pre> <h1>I tried</h1> <p>its not working correct me anyone</p> <pre><code>import React, { useState } from 'react' import Card from './Card' import memesData from './memesData'; import './MainContent.css'; function MainContent() { const [data, setData] = useState('') function getMemeImage() { const memesArray = memesData.data.memes const randomNumber = Math.floor(Math.random() * memesArray.length) const n = memesArray[randomNumber].name console.log(n) setData(data + n) } return ( &lt;div&gt; &lt;button onClick={getMemeImage}&gt; Click me &lt;/button&gt; &lt;h1&gt;{setData}&lt;/h1&gt; &lt;/div&gt; ) } export default MainContent </code></pre>
[ { "answer_id": 74403834, "author": "Foxy", "author_id": 20450170, "author_profile": "https://Stackoverflow.com/users/20450170", "pm_score": 2, "selected": true, "text": "import React, {useState} from 'react'\nimport Card from './Card'\nimport memesData from './memesData';\nimport './MainContent.css';\n\nfunction MainContent() {\n\nconst [state, setState] = useState();\n\n function getMemeImage() {\n\n const memesArray = memesData.data.memes;\n const randomNumber = Math.floor(Math.random() * memesArray.length);\n const n = memesArray[randomNumber].name;\n setState(n);\n console.log(n)\n }\n\n return (\n <div>\n <button onClick={getMemeImage}> Click me </button>\n <h1>{state}</h1>\n </div>\n )\n}\n\nexport default MainContent\n" }, { "answer_id": 74403874, "author": "0stone0", "author_id": 5625547, "author_profile": "https://Stackoverflow.com/users/5625547", "pm_score": 0, "selected": false, "text": "getMemeImage" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,403,679
<p>I'm trying to use the makefile on windows, it seems not to be very common to use Makefile on Windows, so I followed some steps installing MingW, which is used for compilation, but when running make, this error occurred:</p> <pre><code> mkdir -p ./obj/ The command syntax is incorrect. Makefile:30: recipe for target 'obj/main.o' failed mingw32-make.exe: *** [obj/main.o] Error 1 </code></pre> <p>Here's the code:</p> <pre><code>NAME = minishell LIBFT = libft.a CC = cc CF = -g -Wall -Wextra -Werror CFI = -I $(INCLUDE) CREADLINE = -lreadline LIBFT_PATH = ./libs/libft/ SRC_PATH = ./sources/ OBJ_PATH = ./obj/ INCLUDE = ./includes/ SRC = main.c\ prompt.c\ exec.c pipe.c paths.c command.c\ utils_pipes.c\ signals.c\ VPATH := $(SRC_PATH)\ $(SRC_PATH)prompt\ $(SRC_PATH)execute\ $(SRC_PATH)utils\ OBJ = $(addprefix $(OBJ_PATH), $(notdir $(SRC:.c=.o))) RM = rm -rf $(OBJ_PATH)%.o: %.c mkdir -p $(OBJ_PATH) $(CC) $(CF) $(CFI) -c $&lt; -o $@ $(NAME): $(OBJ) make -C $(LIBFT_PATH) $(LIBFT) $(CC) -g $(CF) -I $(INCLUDE) -o $(NAME) $(OBJ) -L $(LIBFT_PATH) -lft $(CREADLINE) @echo &quot;$(GREEN)$(NAME) created$(DEFAULT)&quot; all: $(NAME) re: fclean all clean: make -C $(LIBFT_PATH) clean $(RM) $(OBJ) $(OBJDIR) @echo &quot;$(YELLOW)object files deleted$(DEFAULT)&quot; fclean: clean make -C $(LIBFT_PATH) fclean $(RM) $(NAME) @echo &quot;$(RED)all deleted$(DEFAULT)&quot; install: sudo apt-get install -y libreadline-dev valgrind leak: valgrind --suppressions=readline.supp --leak-check=full --track-origins=yes --show-leak-kinds=all ./$(NAME) .PHONY: all clean fclean re bonus rebonus #COLORS RED = \033[1;31m GREEN = \033[1;32m YELLOW = \033[1;33m DEFAULT = \033[0m` </code></pre> <p>Could anyone give an idea how to fix this?</p>
[ { "answer_id": 74403974, "author": "the busybee", "author_id": 11294831, "author_profile": "https://Stackoverflow.com/users/11294831", "pm_score": 0, "selected": false, "text": "'\\t'" }, { "answer_id": 74404126, "author": "MadScientist", "author_id": 939557, "author_profile": "https://Stackoverflow.com/users/939557", "pm_score": 1, "selected": false, "text": "make" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16468283/" ]
74,403,684
<p>since the last update of the Logicmonitor provider in Terraform we're struggling with a sorting isse.</p> <p>In LogicMonitor the properties of a device are a name-value pair, and they are presented alfabetically by name. Also in API requests the result is alphabetical. So far nothing fancy.</p> <p>But... We build our Cloud devices using a module. Calling the module we provide some LogicMonitor properties specially for this device, and a lot more are provided in the module itself.</p> <p>In the module this looks like this: `</p> <pre><code>custom_properties = concat([ { name = &quot;host_fqdn&quot; value = &quot;${var.name}.${var.dns_domain}&quot; }, { name = &quot;ocid&quot; value = oci_core_instance.server.id }, { name = &quot;private_ip&quot; value = oci_core_instance.server.private_ip }, { name = &quot;snmp.version&quot; value = &quot;v2c&quot; } ], var.logicmonitor_properties) </code></pre> <p>`</p> <p>The first 4 properties are from the module and combined with anyting what is in var.logicmonitor_properties. On the creation of the device in LogicMonitor all properties are set in the order the are and no problem.</p> <p>The issue arises when there is any update on a terraform file in this environment. Due to the fact the properties are presented in alphabetical order, Terraform is showing a lot of changes if finds (but which are in fact just a mixed due to sorting).</p> <p>The big question is: How can I sort the complete list of properties bases on the &quot;name&quot;.</p> <p>Tried to work with maps, sort and several other functions and examples, but got nothing working on key-value pairs. Merging single key's works fine in a map, but how to deal with name/value pairs/</p>
[ { "answer_id": 74403974, "author": "the busybee", "author_id": 11294831, "author_profile": "https://Stackoverflow.com/users/11294831", "pm_score": 0, "selected": false, "text": "'\\t'" }, { "answer_id": 74404126, "author": "MadScientist", "author_id": 939557, "author_profile": "https://Stackoverflow.com/users/939557", "pm_score": 1, "selected": false, "text": "make" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20478378/" ]
74,403,690
<p>How can I allow a non-root user to run 'docker exec' ?</p> <p>For example, I would like to allow a user to execute the following command without him obtaining root permissions to the whole system: <code>docker exec -it containerName /bin/bash</code></p> <p>This command would allow him to get inside his 'working environment' and do whatever he wants... It would be great to be able to allow this command to him, without password requests</p> <p>The operating system is Ubuntu server</p>
[ { "answer_id": 74404320, "author": "Damiano", "author_id": 11268685, "author_profile": "https://Stackoverflow.com/users/11268685", "pm_score": 0, "selected": false, "text": "visudo" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11268685/" ]
74,403,713
<p>I have the following directory:</p> <ul> <li>IoT [Folder] <ul> <li>DC [Folder] <ul> <li>main.py</li> <li>config.ini</li> </ul> </li> </ul> </li> </ul> <p>inside <code>main.py</code> I have:</p> <pre><code>config.read('config.ini') </code></pre> <p>which works perfect if I run my python script after doing <code>cd .....IoT/DC</code></p> <p>But it doesn't work once I run my python script directly from IoT folder, how can I solve this?</p> <p>I can't know from which folder my program will be run...</p> <p>If I have to choose one I prefer running it directly from IoT like this:</p> <pre><code>python3 DC/main.py </code></pre>
[ { "answer_id": 74404320, "author": "Damiano", "author_id": 11268685, "author_profile": "https://Stackoverflow.com/users/11268685", "pm_score": 0, "selected": false, "text": "visudo" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20470733/" ]
74,403,721
<p>I have the following Pandas DataFrame:</p> <pre><code>ID CAT 1 A 1 B 1 A 2 A 2 B 2 A 1 B 1 A </code></pre> <p>I'd like to have a table that indicates the number of occurance per CAT values for each ID in different columns like this:</p> <pre><code>ID CAT_A_NUM CAT_B_NUM 1 3 2 2 2 1 </code></pre> <p>I tried in many ways, like this one with pivot table, but unsuccessfully:</p> <pre><code>df.pivot_table(values='CAT', index='ID', columns='CAT', aggfunc='count') </code></pre>
[ { "answer_id": 74403930, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 3, "selected": true, "text": "df=pd.DataFrame(data={'ID':[1,1,1,2,2,2,1,1],'CAT':['A','B','A','A','B','A','B','A']})\nfinal = pd.crosstab(df['ID'], df['CAT'])\nfinal.columns=['CAT_A_NUM','CAT_B_NUM']\nfinal\n\nID CAT_A_NUM CAT_B_NUM\n1 3 2\n2 2 1\n\n\n" }, { "answer_id": 74404474, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 0, "selected": false, "text": "groupby" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4495790/" ]
74,403,748
<p>We have a scenario where we need to migrate more than a 100 projects that are in one ADO organization to another ADO organization.</p> <p>Is there way how to do perform this migration org to org?</p> <p>We have tried using the Azure migration devops tool by installing it in DEV test lab in A tenant and installed the tool. Started with workitem migration but couldn't due to the errors. So is there a way out to directly migrate org to org in two different ADO's?</p>
[ { "answer_id": 74403930, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 3, "selected": true, "text": "df=pd.DataFrame(data={'ID':[1,1,1,2,2,2,1,1],'CAT':['A','B','A','A','B','A','B','A']})\nfinal = pd.crosstab(df['ID'], df['CAT'])\nfinal.columns=['CAT_A_NUM','CAT_B_NUM']\nfinal\n\nID CAT_A_NUM CAT_B_NUM\n1 3 2\n2 2 1\n\n\n" }, { "answer_id": 74404474, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 0, "selected": false, "text": "groupby" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20478414/" ]
74,403,756
<p>I have created a tibble consisting of 6 columns containing 6 different variables that will be input for a user defined function. I am new to r, and I don't know how to connect the tibble with user defined function. Please help.</p> <p>I have replaced the complex user defined function with simple <code>user_defined_function</code> for the sake of discussion. `</p> <pre><code>library(tidyr) library(dplyr) rgb_val &lt;- seq(from=0, to=255, by=10) rgb_grid &lt;- expand_grid(r1 = rgb_val, g1 = rgb_val, b1 = rgb_val, r2 = rgb_val, g2 = rgb_val, b3 = rgb_val) user_defined_function &lt;- function(x) { x[,1] + x[,2] + x[,3] + x[,4] + x[,5] + x[,6] } rgb_grid %&gt;% mutate(new_cols = user_defined_function ()) </code></pre> <p>I want the results of the <code>user_defined_function</code> to be added as new column to the tibble <code>rgb_grid</code>. However, if what I have tried, unsuprisingly, throws an error.</p>
[ { "answer_id": 74403958, "author": "Josh White", "author_id": 20289207, "author_profile": "https://Stackoverflow.com/users/20289207", "pm_score": 3, "selected": true, "text": "rgb_val" }, { "answer_id": 74404006, "author": "langtang", "author_id": 4447540, "author_profile": "https://Stackoverflow.com/users/4447540", "pm_score": 0, "selected": false, "text": "rgb_grid %>% mutate(new_cols = user_defined_function(rgb_grid)[,1])\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20427544/" ]
74,403,784
<p>A <code>Collector</code> has three generic types:</p> <pre><code>public interface Collector&lt;T, A, R&gt; </code></pre> <p>With <code>A</code> being <em>the mutable accumulation type of the reduction operation (often hidden as an implementation detail)</em>.</p> <p>If I want to create my custom collector, I need to create two classes:</p> <ul> <li>one for the custom accumulation type</li> <li>one for the custom collector itself</li> </ul> <p>Is there any library function/trick that takes the accumulation type and provides a corresponding Collector?</p> <h3>Simple example</h3> <p>This example is extra simple to illustrate the question, <strong>I know I could use <code>reduce</code> for this case, but this is not what I am looking for</strong>. Here is a <a href="https://stackoverflow.com/a/74401856/7424948">more complex example</a> that sharing here would make the question too long, but it is the same idea.</p> <p>Let's say I want to collect the sum of a stream and return it as a <code>String</code>.</p> <p>I can implement my accumulator class:</p> <pre><code>public static class SumCollector { Integer value; public SumCollector(Integer value) { this.value = value; } public static SumCollector supply() { return new SumCollector(0); } public void accumulate(Integer next) { value += next; } public SumCollector combine(SumCollector other) { return new SumCollector(value + other.value); } public String finish(){ return Integer.toString(value); } } </code></pre> <p>And then I can create a <code>Collector</code> from this class:</p> <pre><code>Collector.of(SumCollector::supply, SumCollector::accumulate, SumCollector::combine, SumCollector::finish); </code></pre> <p>But it seems strange to me that they all refer to the the other class, I feel that there is a more direct way to do this.</p> <p>What I could do to keep only one class would be <code>implements Collector&lt;Integer, SumCollector, String&gt;</code> but then every function would be duplicated (<code>supplier()</code> would return <code>SumCollector::supply</code>, etc).</p>
[ { "answer_id": 74403914, "author": "Silvio Mayolo", "author_id": 2288659, "author_profile": "https://Stackoverflow.com/users/2288659", "pm_score": 2, "selected": false, "text": "Collector" }, { "answer_id": 74404441, "author": "Holger", "author_id": 2711488, "author_profile": "https://Stackoverflow.com/users/2711488", "pm_score": 2, "selected": false, "text": "public static Collector<Integer, ?, Integer> sum() {\n return Collector.of(() -> new int[1],\n (a, i) -> a[0] += i,\n (a, b) -> { a[0] += b[0]; return a; },\n a -> a[0],\n Collector.Characteristics.UNORDERED);\n}\n" }, { "answer_id": 74407964, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": true, "text": "Collector" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7424948/" ]
74,403,798
<p>I'm trying to print out the multiplication table using js. Is there a cleaner way to do this than with nested for loops? I was thinking of reduce as an alternative. Any onther ideas out there? ;)</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> let table = () =&gt; { let x, y, sum; let table = ''; for (y = 10; y &lt;= 20; y++) { for (x = 10; x &lt;= 20; x++) { sum = x * y; table += `|${sum} `; } table += '|\n'; } result.innerText = table; };</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8" /&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge" /&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt; &lt;title&gt;Task 4&lt;/title&gt; &lt;/head&gt; &lt;body onload="table()"&gt; &lt;h2&gt;Multiplication table&lt;/h2&gt; &lt;div id="result"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74403914, "author": "Silvio Mayolo", "author_id": 2288659, "author_profile": "https://Stackoverflow.com/users/2288659", "pm_score": 2, "selected": false, "text": "Collector" }, { "answer_id": 74404441, "author": "Holger", "author_id": 2711488, "author_profile": "https://Stackoverflow.com/users/2711488", "pm_score": 2, "selected": false, "text": "public static Collector<Integer, ?, Integer> sum() {\n return Collector.of(() -> new int[1],\n (a, i) -> a[0] += i,\n (a, b) -> { a[0] += b[0]; return a; },\n a -> a[0],\n Collector.Characteristics.UNORDERED);\n}\n" }, { "answer_id": 74407964, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": true, "text": "Collector" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19895948/" ]
74,403,825
<p>Sorry I'm struggling with something that should be simple.</p> <p>I have table &quot;Risks_For_Task_1&quot;:</p> <pre><code>+--------------+-------------+--------------+ | RiskName | Mitigation | RiskLevel | +--------------+-------------+--------------+ | Risk A | Mitigate#1 | Medium | | Risk B | Mitigate#2 | Low | | Risk C | Mitigate#3 | High | +--------------+-------------+--------------+ </code></pre> <p>And a table &quot;Risks_For_Task_2&quot;:</p> <pre><code>+--------------+-------------+--------------+ | RiskName | Mitigation | RiskLevel | +--------------+-------------+--------------+ | Risk D | Mitigate#4 | Low | | Risk E | Mitigate#5 | Low | | Risk F | Mitigate#6 | Medium | +--------------+-------------+--------------+ </code></pre> <p>And a table &quot;Risks_For_Task_3&quot;:</p> <pre><code>+--------------+-------------+--------------+ | RiskName | Mitigation | RiskLevel | +--------------+-------------+--------------+ | Risk G | Mitigate#7 | Medium | | Risk H | Mitigate#8 | High | | Risk I | Mitigate#9 | Medium | +--------------+-------------+--------------+ </code></pre> <p>And a table &quot;Tasks&quot;:</p> <pre><code>+--------------+-------------+ | ID | TaskName | +--------------+-------------+ | 1 | Task#1 | | 2 | Task#2 | | 3 | Task#3 | +--------------+-------------+ </code></pre> <p>I wish to combine Risks_For_Task_1, Risks_For_Task_2, and Risks_For_Task_3, and put them into an existing table called &quot;Task_Risks&quot; with an extra column referencing the ID from the table Tasks. So the result should look like this:</p> <pre><code>+--------------+-------------+--------------+--------------+ | RiskName | Mitigation | RiskLevel | TaskID | +--------------+-------------+--------------+--------------+ | Risk A | Mitigate#1 | Medium | 1 | | Risk B | Mitigate#2 | Low | 1 | | Risk C | Mitigate#3 | High | 1 | | Risk D | Mitigate#4 | Low | 2 | | Risk E | Mitigate#5 | Low | 2 | | Risk F | Mitigate#6 | Medium | 2 | | Risk G | Mitigate#7 | Medium | 3 | | Risk H | Mitigate#8 | High | 3 | | Risk I | Mitigate#9 | Medium | 3 | +--------------+-------------+--------------+--------------+ </code></pre> <p>This is what I wrote:</p> <pre><code>INSERT INTO Task_Risks (RiskName, Mitigation, RiskLevel, TaskID) Select RiskName, Mitigation, RiskLevel, TaskID from ((Select RiskName, Mitigation, RiskLevel from Risks_For_Task_1 Full Join Select ID from Tasks where TaskName='Task#1') Union All (Select RiskName, Mitigation, RiskLevel from Risks_For_Task_2 Full Join Select ID from Tasks where TaskName='Task#2') Union All (Select RiskName, Mitigation, RiskLevel from Risks_For_Task_3 Full Join Select ID from Tasks where TaskName='Task#3')); </code></pre> <p>Above code gives the error &quot;invalid table name&quot;.</p>
[ { "answer_id": 74403901, "author": "WandererAboveTheSea", "author_id": 9680817, "author_profile": "https://Stackoverflow.com/users/9680817", "pm_score": 0, "selected": false, "text": "Union All" }, { "answer_id": 74403964, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 3, "selected": true, "text": "tasks" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13709246/" ]
74,403,887
<p>What I've generated so far..... [<img src="https://i.stack.imgur.com/0G8j5.jpg" alt="What i've generated so far(https://i.stack.imgur.com/0G8j5.jpg)" /></p> <p>VERSUS</p> <p>What needs to be recreated [<img src="https://i.stack.imgur.com/kVmZx.png" alt="the original plot(https://i.stack.imgur.com/kVmZx.png)" /></p> <p>my code so far:</p> <pre><code>Recreated_figure_DHRP %&gt;% ggplot(aes(x = Insurers, y =`INR BN`,fill = FY,group=FY)) + geom_bar(stat = &quot;identity&quot;, position = position_dodge(), alpha = 0.75,)+ theme(axis.text.x = element_text(angle = 60, hjust = 1)) + theme(legend.position=&quot;top&quot;) + ylim(0,400)+ geom_text(aes(label = `INR BN`), fontface = &quot;bold&quot;, vjust = 1.5, position = position_dodge(.9), size = 2.25) </code></pre>
[ { "answer_id": 74403901, "author": "WandererAboveTheSea", "author_id": 9680817, "author_profile": "https://Stackoverflow.com/users/9680817", "pm_score": 0, "selected": false, "text": "Union All" }, { "answer_id": 74403964, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 3, "selected": true, "text": "tasks" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20075726/" ]
74,403,919
<p>I have a problem with sorting function.</p> <p>I have following struct:</p> <pre><code>struct Object { int value, height; Object(int v, int h) { this-&gt;value = v; this-&gt;height = h; } }; </code></pre> <p>I am storing vector of this objects: <code>std::vector&lt;Object&gt; v</code></p> <p>And I'd like to sort it such that if the height is greater than some <code>i</code> then it should go at the end, and if it is less or equal sort by value.</p> <p>I've tried this before:</p> <pre><code>// some value int i = 4; std::sort(v.begin(), v.end(), [ &amp; ](Object a, Object b) { if (b.height &gt; i) { return false; } if (a.height &gt; i) { return false; } return a.value &gt; b.value; }); </code></pre> <p>But it does not seem to work..</p> <p>When I have these elements:</p> <p><code>std::vector&lt;Object&gt; v = {{3, 10}, {5, 2}, {3, 2}, {2, 10}, {2, 1000000000}};</code> and <code>i = 2</code></p> <p>When I print values of v, after sorting I see that they appear in the exact same order</p> <p>And I'd like them in the following order: <code>{{5, 2}, {3, 2}, {3, 10}, {2, 10}, {2, 1000000000}}</code></p>
[ { "answer_id": 74404000, "author": "Jarod42", "author_id": 2684539, "author_profile": "https://Stackoverflow.com/users/2684539", "pm_score": 3, "selected": true, "text": "std::sort(v.begin(), v.end(), [ & ](const Object& lhs, const Object& rhs) {\n return std::make_pair(lhs.height > i, rhs.value) < std::make_pair(rhs.height > i, lhs.value);\n});\n" }, { "answer_id": 74404268, "author": "sp Kruten", "author_id": 19910248, "author_profile": "https://Stackoverflow.com/users/19910248", "pm_score": 0, "selected": false, "text": "std::sort(v.begin(), v.end(), [ & ](Object a, Object b) {\n if (b.height > i) {\n // Here is change\n return true;\n }\n if (a.height > i) {\n return false;\n }\n\n return a.value > b.value;\n});\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19809278/" ]
74,403,955
<p>I have a table like this in SQL Server:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Rank</th> <th>Tag</th> <th>Name</th> <th>Size</th> <th>Seq</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td></td> <td>One</td> <td>14</td> <td>7</td> </tr> <tr> <td>2</td> <td>2</td> <td>A</td> <td>Two</td> <td>12</td> <td>4</td> </tr> <tr> <td>3</td> <td>2</td> <td>B</td> <td>Three</td> <td>0</td> <td>5</td> </tr> <tr> <td>4</td> <td>2</td> <td>C</td> <td>Four</td> <td>0</td> <td>6</td> </tr> <tr> <td>5</td> <td>3</td> <td></td> <td>Five</td> <td>8</td> <td>1</td> </tr> <tr> <td>6</td> <td>4</td> <td>A</td> <td>Six</td> <td>18</td> <td>2</td> </tr> <tr> <td>7</td> <td>4</td> <td>B</td> <td>Seven</td> <td>0</td> <td>3</td> </tr> </tbody> </table> </div> <ul> <li>&quot;ID&quot; is an identity field.</li> <li>Rank is an always increasing integer that does the same job as &quot;Tag&quot;</li> <li>&quot;Tag&quot; groups rows together into Single or Multiple type rows: if &quot;Tag&quot; is blank or null the row is selected by itself (single). If 'A', 'B' 'C' or 'D' they must all be rolled up to one 'A' (Multiple) row by concatenating the &quot;Name&quot; fields separated by commas.</li> <li>The &quot;Size&quot; value for the rolled-up rows is the value for the 'A' row. For all rows with 'B','C' or 'D' Size is zero and on rollup will take on the previous 'A' value.</li> <li>Finally, the Seq field is a user-specified sort order value the final ORDER BY Field.</li> </ul> <p>So, I need the following output:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Tag</th> <th>Name</th> <th>Size</th> </tr> </thead> <tbody> <tr> <td></td> <td>Five</td> <td>8</td> </tr> <tr> <td>A</td> <td>Six,Seven</td> <td>18</td> </tr> <tr> <td>A</td> <td>Two,Three,Four</td> <td>12</td> </tr> <tr> <td></td> <td>One</td> <td>14</td> </tr> </tbody> </table> </div> <p>I know I need sub queries and some combinations of GROUP BY and/or PARTITION BY, plus ROW_OVER to roll up the rows. I've tried all combinations I can think of with no success. There must be TSQL query to do this without resorting to cursors. Can anyone help? Thanks in advance.</p>
[ { "answer_id": 74404328, "author": "DannySlor", "author_id": 19174570, "author_profile": "https://Stackoverflow.com/users/19174570", "pm_score": 1, "selected": false, "text": "select min(tag) as tag\n ,string_agg(name, ', ') as name\n ,sum(size) as size\nfrom t\ngroup by rank\n" }, { "answer_id": 74404477, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "rank" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/822381/" ]
74,403,962
<p>I am writing a rest api method. I have to get a zip file, then read the data in that file and write it to the database. But I have to achieve this without writing or extracting the zip file in the local. So I can't use the file path. How can I access the file?</p> <p>I tried to directly convert the file to inputstream with the following method. But it cannot find the file. (java.io.IOException: Couldn't find file /zipFile.zip)</p> <pre><code>InputStream getZipFileContentAsInputStream(@Nonnull String fileName) throws IOException { if (!fileName.startsWith(&quot;/&quot;)) { fileName = &quot;/&quot; + fileName; // NOSONAR This &quot;/&quot; is portable, it's inside a JAR. } val inputStream = getClass().getResourceAsStream(fileName); if (inputStream == null) { throw new IOException(&quot;Couldn't find file &quot; + fileName); } if (fileName.endsWith(ZIP)) { try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { try (ZipInputStream bzIn = new ZipInputStream(inputStream)) { final byte[] buffer = new byte[ZIP_BUFFER_SIZE]; int n; while (-1 != (n = bzIn.read(buffer))) { out.write(buffer, 0, n); } return new ByteArrayInputStream(out.toByteArray()); } } } else { return inputStream; } } </code></pre> <p>I send the file as the request param.</p> <pre><code>@PostMapping(&quot;/import/zip&quot;) public ResponseEntity&lt;Object&gt; uploadFile(@RequestParam(&quot;file&quot;) MultipartFile file) throws IOException, UnsupportedOperationException { ... } </code></pre>
[ { "answer_id": 74404328, "author": "DannySlor", "author_id": 19174570, "author_profile": "https://Stackoverflow.com/users/19174570", "pm_score": 1, "selected": false, "text": "select min(tag) as tag\n ,string_agg(name, ', ') as name\n ,sum(size) as size\nfrom t\ngroup by rank\n" }, { "answer_id": 74404477, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "rank" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19767957/" ]
74,403,978
<pre><code>class ModelCreateView(CreateView): model = Message fields=['message'] template_name = &quot;page.html&quot; succes_url = reverse='page' </code></pre> <p>No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model. this is error but if i put get absolute url reverse going detail page</p>
[ { "answer_id": 74404328, "author": "DannySlor", "author_id": 19174570, "author_profile": "https://Stackoverflow.com/users/19174570", "pm_score": 1, "selected": false, "text": "select min(tag) as tag\n ,string_agg(name, ', ') as name\n ,sum(size) as size\nfrom t\ngroup by rank\n" }, { "answer_id": 74404477, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "rank" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74403978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17916939/" ]
74,404,059
<p><a href="https://i.stack.imgur.com/3kV1H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3kV1H.png" alt="enter image description here" /></a></p> <p>The Current dimension size is set to 32 characters. Is there any way to increase this using H5PY?</p> <p>I am having a problem where the values in my datasets are getting cut off because they are too long. <a href="https://i.stack.imgur.com/llGIf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/llGIf.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74404328, "author": "DannySlor", "author_id": 19174570, "author_profile": "https://Stackoverflow.com/users/19174570", "pm_score": 1, "selected": false, "text": "select min(tag) as tag\n ,string_agg(name, ', ') as name\n ,sum(size) as size\nfrom t\ngroup by rank\n" }, { "answer_id": 74404477, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "rank" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19401660/" ]
74,404,092
<p><a href="https://i.stack.imgur.com/TRf7O.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TRf7O.png" alt="enter image description here" /></a></p> <p>Compose - removeProperty(variables('Message')['Appointment'],'CustomerInfo')</p> <p><a href="https://i.stack.imgur.com/GZ2vJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GZ2vJ.png" alt="enter image description here" /></a></p> <p>What I want to see if the following. <a href="https://i.stack.imgur.com/mRMqO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mRMqO.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74406452, "author": "RithwikBojja", "author_id": 17623802, "author_profile": "https://Stackoverflow.com/users/17623802", "pm_score": 0, "selected": false, "text": "removeproperty(variables('emo')['appointment'],'customerInfo')" }, { "answer_id": 74420008, "author": "Skin", "author_id": 5772095, "author_profile": "https://Stackoverflow.com/users/5772095", "pm_score": 1, "selected": false, "text": "removeProperty" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7581658/" ]
74,404,106
<p>I have been looking through some legacy code and found this little snippet:</p> <pre><code>std::vector&lt;int&gt;** grid = new std::vector&lt;int&gt;*[10]; for (int k = 0; k &lt; 10; k++) grid[k] = new std::vector&lt;int&gt;[10]; </code></pre> <p>And then later on, the original developer is calling this command here:</p> <pre><code>grid [i][j].push_back(temp); </code></pre> <p>I was under the impression that the <code>[i][j]</code> would return the value in the nested vector, but by using <code>push_back</code> implies that there is a pointer to a vector at that location? I'm confused where this third vector arises from.</p> <p>Also, is there a better approach? would a triple nested vector also achieve the same results as the above code?</p> <p>Thanks in advance!</p>
[ { "answer_id": 74404284, "author": "Ben", "author_id": 9177735, "author_profile": "https://Stackoverflow.com/users/9177735", "pm_score": 1, "selected": false, "text": "grid[] -> contains 10 pointers which each point to an array of vector pointers\ngrid[][] -> contains 10 pointers to vectors\n*grid[][] -> a vector of integers\n" }, { "answer_id": 74404318, "author": "Caleth", "author_id": 2610810, "author_profile": "https://Stackoverflow.com/users/2610810", "pm_score": 2, "selected": false, "text": "grid[i][j]" }, { "answer_id": 74404685, "author": "rturrado", "author_id": 260313, "author_profile": "https://Stackoverflow.com/users/260313", "pm_score": 3, "selected": true, "text": "grid[i][j]" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14182500/" ]
74,404,109
<p>If I have following print statements:</p> <pre class="lang-py prettyprint-override"><code>print(&quot;#&quot;*80) print(f&quot;##{'':.^76}##&quot;) print(f&quot;##{'Hello World':.^76}##&quot;) print(f&quot;##{'':.^76}##&quot;) print(&quot;#&quot;*80) </code></pre> <p>I will get a nice border around my &quot;Hello World&quot; but with dots:</p> <pre class="lang-bash prettyprint-override"><code>################################################################################ ##............................................................................## ##................................Hello World.................................## ##............................................................................## ################################################################################ </code></pre> <p>If I use a <code>' '</code> instead of the <code>.</code> in the second to fourth print statement, I will get a <code>ValueError: Invalid format specifier</code>.</p> <p>How can replace the dot with whitespace or any other ascii symbol?</p>
[ { "answer_id": 74404284, "author": "Ben", "author_id": 9177735, "author_profile": "https://Stackoverflow.com/users/9177735", "pm_score": 1, "selected": false, "text": "grid[] -> contains 10 pointers which each point to an array of vector pointers\ngrid[][] -> contains 10 pointers to vectors\n*grid[][] -> a vector of integers\n" }, { "answer_id": 74404318, "author": "Caleth", "author_id": 2610810, "author_profile": "https://Stackoverflow.com/users/2610810", "pm_score": 2, "selected": false, "text": "grid[i][j]" }, { "answer_id": 74404685, "author": "rturrado", "author_id": 260313, "author_profile": "https://Stackoverflow.com/users/260313", "pm_score": 3, "selected": true, "text": "grid[i][j]" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10985257/" ]
74,404,117
<p>when add this code, the app runs as suposed to, but when i reload the app, it stops rendering as it should and give me a full blanck page</p> <pre><code> &lt;/div&gt; &lt;div className=&quot;chat__body&quot;&gt; {messages.map((message) =&gt; ( &lt;p className={`chat__message ${true &amp;&amp; &quot;chat__reciever&quot;}`}&gt; &lt;span className=&quot;chat__name&quot;&gt;{message.name}&lt;/span&gt; {message.message} &lt;span className=&quot;chat__timestamp&quot;&gt; {new Date(message.timestamp?.toDate()).toUTCString()} &lt;/span&gt; &lt;/p&gt; ))} &lt;/div&gt; </code></pre> <p>whith this message error when inspecting Uncaught TypeError: messages.map is not a function</p> <p>do someone know what am i doing wrong?</p>
[ { "answer_id": 74404284, "author": "Ben", "author_id": 9177735, "author_profile": "https://Stackoverflow.com/users/9177735", "pm_score": 1, "selected": false, "text": "grid[] -> contains 10 pointers which each point to an array of vector pointers\ngrid[][] -> contains 10 pointers to vectors\n*grid[][] -> a vector of integers\n" }, { "answer_id": 74404318, "author": "Caleth", "author_id": 2610810, "author_profile": "https://Stackoverflow.com/users/2610810", "pm_score": 2, "selected": false, "text": "grid[i][j]" }, { "answer_id": 74404685, "author": "rturrado", "author_id": 260313, "author_profile": "https://Stackoverflow.com/users/260313", "pm_score": 3, "selected": true, "text": "grid[i][j]" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20418013/" ]
74,404,118
<p>I can't run or debug start a Flutter project in Android Emulator. Even if android emulator works normally, when I run the project the editor always gives me this error:</p> <pre><code> Running Gradle task 'assembleDebug'... Exception in thread &quot;main&quot; java.util.zip.ZipException: zip END header not found at java.base/java.util.zip.ZipFile$Source.zerror(ZipFile.java:1607) at java.base/java.util.zip.ZipFile$Source.findEND(ZipFile.java:1497) at java.base/java.util.zip.ZipFile$Source.initCEN(ZipFile.java:1504) at java.base/java.util.zip.ZipFile$Source.&lt;init&gt;(ZipFile.java:1308) at java.base/java.util.zip.ZipFile$Source.get(ZipFile.java:1271) at java.base/java.util.zip.ZipFile$CleanableResource.&lt;init&gt;(ZipFile.java:733) at java.base/java.util.zip.ZipFile$CleanableResource.get(ZipFile.java:850) at java.base/java.util.zip.ZipFile.&lt;init&gt;(ZipFile.java:248) at java.base/java.util.zip.ZipFile.&lt;init&gt;(ZipFile.java:177) at java.base/java.util.zip.ZipFile.&lt;init&gt;(ZipFile.java:191) at org.gradle.wrapper.Install.unzip(Install.java:214) at org.gradle.wrapper.Install.access$600(Install.java:27) at org.gradle.wrapper.Install$1.call(Install.java:74) at org.gradle.wrapper.Install$1.call(Install.java:48) at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65) at org.gradle.wrapper.Install.createDist(Install.java:48) at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128) at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61) Exception: Gradle task assembleDebug failed with exit code 1 </code></pre> <p>My MAC is 2020 MacBook Pro with M1 chip, my system is Ventura 3.0.1 and Flutter 3.3.8. This problem was there before upgrading MacOS to Ventura.</p>
[ { "answer_id": 74404206, "author": "CidQu", "author_id": 14755443, "author_profile": "https://Stackoverflow.com/users/14755443", "pm_score": 0, "selected": false, "text": "cd ~\nrm -rf .gradle\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13654126/" ]
74,404,150
<p>My GCP cloud SQL has SSL enabled. With that, my client will require the server CA cert, client cert and key to connect to the database. The client is configured to retrieve the certs and key from Secret Manager.</p> <p>I am deploying my setup using Terraform. Once the SQL instance is created, it needs to output the certs and key so that I can create them in Secret Manager. However, Secret Manager only takes in string format but the output of the certs and keys are in list format.</p> <p>I am quite new to Terraform, what can I do to import the SQL certs and key into Secret Manager?</p> <p>The following are my Terraform code snippets:</p> <p><strong>Cloud SQL</strong></p> <pre><code>output &quot;server_ca_cert&quot; { description = &quot;Server ca certificate for the SQL DB&quot; value = google_sql_database_instance.instance.server_ca_cert } output &quot;client_key&quot; { description = &quot;Client private key for the SQL DB&quot; value = google_sql_ssl_cert.client_cert.private_key } output &quot;client_cert&quot; { description = &quot;Client cert for the SQL DB&quot; value = google_sql_ssl_cert.client_cert.cert </code></pre> <p><strong>Secret Manager</strong></p> <pre><code>module &quot;server_ca&quot; { source = &quot;../siac-modules/modules/secretManager&quot; project_id = var.project_id region_id = local.default_region secret_ids = local.server_ca_key # secret_datas = file(&quot;${path.module}/certs/server-ca.pem&quot;) secret_datas = module.sql_db_timeslot_manager.server_ca_cert } </code></pre> <p><strong>Terraform plan error</strong> Error: Invalid value for input variable │ │ on ..\siac-modules\modules\secretManager\variables.tf line 21: │ 21: variable &quot;secret_datas&quot; { │ │ The given value is not suitable for module.server_ca.var.secret_datas, which is sensitive: string required. Invalid value defined at 30-secret_manager.tf:71,18-63.</p>
[ { "answer_id": 74404206, "author": "CidQu", "author_id": 14755443, "author_profile": "https://Stackoverflow.com/users/14755443", "pm_score": 0, "selected": false, "text": "cd ~\nrm -rf .gradle\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20478658/" ]
74,404,167
<p>I made a regex to extract values from a templated string. The regex is working smooth on websites like regexr.com but it's failing when I try to run in shell.</p> <p>As example, let's use those lines:</p> <blockquote> <p>[2022-11-11T12:07:00.789Z] &quot;GET /check?subject=johnbegucci HTTP/1.1&quot; 200 - &quot;-&quot; 0 17 3 2 &quot;-&quot; &quot;-&quot; &quot;4e4c4fb1-a4d8-4075-8e42-b5fb9216f863&quot; &quot;laundry.transaction.svc.cluster.local:4466&quot; &quot;172.16.107.246:4466&quot; outbound|4466||laundry.transaction.svc.cluster.local 172.16.67.246:51630 10.100.111.246:4466 172.16.67.246:48610 - default</p> <p>[2022-11-11T13:31:41.189Z] &quot;GET /v1/campaign/198237-jsd-1231 HTTP/1.1&quot; 200 - &quot;-&quot; 0 674 63 63 &quot;-&quot; &quot;Apache-HttpClient/4.5.10 (Java/11.0.7)&quot; &quot;9b3afd5b-c092-4e84-9f29-6380b7f2cafc&quot; &quot;mkt-extractor.mkt-extractor&quot; &quot;172.16.108.138:80&quot; outbound|80||mkt-extractor.mkt-extractor.svc.cluster.local 172.16.65.24:57134 10.100.19.249:80 172.16.65.24:38816 - default</p> </blockquote> <p>Both lines follows the pattern:</p> <blockquote> <p>[%START_TIME%] &quot;%REQ(:METHOD)% %REQ(X-ENVOY-ORIGINAL-PATH?:PATH)% %PROTOCOL%&quot; %RESPONSE_CODE% %RESPONSE_FLAGS% %BYTES_RECEIVED% %BYTES_SENT% %DURATION% %RESP(X-ENVOY-UPSTREAM-SERVICE-TIME)% &quot;%REQ(X-FORWARDED-FOR)%&quot; &quot;%REQ(USER-AGENT)%&quot; &quot;%REQ(X-REQUEST-ID)%&quot; &quot;%REQ(:AUTHORITY)%&quot; &quot;%UPSTREAM_HOST%&quot; %UPSTREAM_CLUSTER% %UPSTREAM_LOCAL_ADDRESS% %DOWNSTREAM_LOCAL_ADDRESS% %DOWNSTREAM_REMOTE_ADDRESS% %REQUESTED_SERVER_NAME%\n</p> </blockquote> <p>Based on that, I created this regex to extract values from <code>UPSTREAM_HOST</code>. Values like <code>outbound|4466||laundry.transaction.svc.cluster.local</code>:</p> <pre><code>(\[.*\])\s(\&quot;.*\&quot;)\s([0-9]*)\s(.*)\s(\&quot;.*\&quot;)\s([0-9]*)\s([0-9]*)\s([0-9]*)\s([0-9]*)\s(\&quot;.*\&quot;)\s(\&quot;.*\&quot;)\s(\&quot;.*\&quot;)\s(\&quot;.*\&quot;)\s(\&quot;.*\&quot;)\s(.*)\s(.*)\s(.*)\s(.*)\s(.*)\s(.*)+ </code></pre> <p>I have tested this regex on website regexr.com and it displays right values as group 14 for both lines:</p> <pre><code>outbound|4466||laundry.transaction.svc.cluster.local outbound|80||mkt-extractor.mkt-extractor.svc.cluster.local </code></pre> <p>After that, I tried to execute an <code>awk -v FPAT</code> but the groups looks wrong. To get values from <code>UPSTREAM_HOST</code>, I need to change print value and it's not viable because I'm creating an automation to process log:</p> <pre><code>echo '[2022-11-11T12:07:00.789Z] &quot;GET /check?subject=johnbegucci HTTP/1.1&quot; 200 - &quot;-&quot; 0 17 3 2 &quot;-&quot; &quot;-&quot; &quot;4e4c4fb1-a4d8-4075-8e42-b5fb9216f863&quot; &quot;laundry.transaction.svc.cluster.local:4466&quot; &quot;172.16.107.246:4466&quot; outbound|4466||laundry.transaction.svc.cluster.local 172.16.67.246:51630 10.100.111.246:4466 172.16.67.246:48610 - default' | awk -v FPAT='(\[.*\])\s(\&quot;.*\&quot;)\s([0-9]*)\s(.*)\s(\&quot;.*\&quot;)\s([0-9]*)\s([0-9]*)\s([0-9]*)\s([0-9]*)\s(\&quot;.*\&quot;)\s(\&quot;.*\&quot;)\s(\&quot;.*\&quot;)\s(\&quot;.*\&quot;)\s(\&quot;.*\&quot;)\s(.*)\s(.*)\s(.*)\s(.*)\s(.*)\s(.*)+' -v OFS='|' '{print $15}' # above example im using '{print $15}' echo '[2022-11-11T13:31:41.189Z] &quot;GET /v1/campaign/198237-jsd-1231 HTTP/1.1&quot; 200 - &quot;-&quot; 0 674 63 63 &quot;-&quot; &quot;Apache-HttpClient/4.5.10 (Java/11.0.7)&quot; &quot;9b3afd5b-c092-4e84-9f29-6380b7f2cafc&quot; &quot;mkt-extractor.mkt-extractor&quot; &quot;172.16.108.138:80&quot; outbound|80||mkt-extractor.mkt-extractor.svc.cluster.local 172.16.65.24:57134 10.100.19.249:80 172.16.65.24:38816 - default' | | awk -v FPAT='(\[.*\])\s(\&quot;.*\&quot;)\s([0-9]*)\s(.*)\s(\&quot;.*\&quot;)\s([0-9]*)\s([0-9]*)\s([0-9]*)\s([0-9]*)\s(\&quot;.*\&quot;)\s(\&quot;.*\&quot;)\s(\&quot;.*\&quot;)\s(\&quot;.*\&quot;)\s(\&quot;.*\&quot;)\s(.*)\s(.*)\s(.*)\s(.*)\s(.*)\s(.*)+' -v OFS='|' '{print $18}' # above example im using '{print $18}' </code></pre> <p>Is there any way to make it work for both logs with same <code>print</code> position?</p>
[ { "answer_id": 74404306, "author": "anubhava", "author_id": 548225, "author_profile": "https://Stackoverflow.com/users/548225", "pm_score": 2, "selected": false, "text": "awk" }, { "answer_id": 74405039, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 0, "selected": false, "text": "s1='[2022-11-11T12:07:00.789Z] \"GET /check?subject=johnbegucci HTTP/1.1\" 200 - \"-\" 0 17 3 2 \"-\" \"-\" \"4e4c4fb1-a4d8-4075-8e42-b5fb9216f863\" \"laundry.transaction.svc.cluster.local:4466\" \"172.16.107.246:4466\" outbound|4466||laundry.transaction.svc.cluster.local 172.16.67.246:51630 10.100.111.246:4466 172.16.67.246:48610 - default'\n\ns2='[2022-11-11T13:31:41.189Z] \"GET /v1/campaign/198237-jsd-1231 HTTP/1.1\" 200 - \"-\" 0 674 63 63 \"-\" \"Apache-HttpClient/4.5.10 (Java/11.0.7)\" \"9b3afd5b-c092-4e84-9f29-6380b7f2cafc\" \"mkt-extractor.mkt-extractor\" \"172.16.108.138:80\" outbound|80||mkt-extractor.mkt-extractor.svc.cluster.local 172.16.65.24:57134 10.100.19.249:80 172.16.65.24:38816 - default'\n\n\necho \"$s1\" | perl -lnE 'say $14 if /(\\[.*\\])\\s(\\\".*\\\")\\s([0-9]*)\\s(.*)\\s(\\\".*\\\")\\s([0-9]*)\\s([0-9]*)\\s([0-9]*)\\s([0-9]*)\\s(\\\".*\\\")\\s(\\\".*\\\")\\s(\\\".*\\\")\\s(\\\".*\\\")\\s(\\\".*\\\")\\s(.*)\\s(.*)\\s(.*)\\s(.*)\\s(.*)\\s(.*)+/'\n\"172.16.107.246:4466\"\n\necho \"$s2\" | perl -lnE 'say $14 if /(\\[.*\\])\\s(\\\".*\\\")\\s([0-9]*)\\s(.*)\\s(\\\".*\\\")\\s([0-9]*)\\s([0-9]*)\\s([0-9]*)\\s([0-9]*)\\s(\\\".*\\\")\\s(\\\".*\\\")\\s(\\\".*\\\")\\s(\\\".*\\\")\\s(\\\".*\\\")\\s(.*)\\s(.*)\\s(.*)\\s(.*)\\s(.*)\\s(.*)+/'\n\"172.16.108.138:80\"\n" }, { "answer_id": 74409897, "author": "RavinderSingh13", "author_id": 5866580, "author_profile": "https://Stackoverflow.com/users/5866580", "pm_score": 2, "selected": false, "text": "awk" }, { "answer_id": 74410093, "author": "RARE Kpop Manifesto", "author_id": 14672114, "author_profile": "https://Stackoverflow.com/users/14672114", "pm_score": 0, "selected": false, "text": "\"" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13764824/" ]
74,404,178
<p>I'm new at python. I struggle how to count how many people have died from each country. I use pandas dataframe. 0 - means that person died, 1 - survived. I have ~2000rows. Maybe it is not enough info, but I dont know how to solve this and from what exactly to start...</p> <pre><code>df['survived'] = df['survived'].replace(['no'], 0) df['survived'] = df['survived'].replace(['yes'], 1) countries_list = list(df['country']) survived_list = list(df['survived']) for i in range(len(survived_list)): print(f'{survived_list[i]}: {countries_list[i]}') </code></pre> <p>I only get to this point and dont know what to do. With IF statement I also get nowhere: If i write like this (below) it shows me an error I dont know why. I hope that you get the idea what I want to do. Thank you in advance</p> <pre><code>if survived_list == 0: </code></pre> <p>0: United States 0: United States 0: United States 1: England 1: Norway 1: United States 0: France 1: France 1: Lebanon 1: Finland 0: Sweden 0: England ...</p>
[ { "answer_id": 74404251, "author": "bichanna", "author_id": 17558100, "author_profile": "https://Stackoverflow.com/users/17558100", "pm_score": 1, "selected": true, "text": "counts = {}\n\nfor i in range(len(survived_list)):\n try:\n counts[countries_list[i]] += survived_list[i]\n except:\n counts[countries_list[i]] = survived_list[i]\n" }, { "answer_id": 74404337, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 1, "selected": false, "text": "df[\"died\"] = df[\"survived\"].map(lambda x: 1 if x==0 else 0)\ndf.groupby(['country']).sum()\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20478626/" ]
74,404,207
<p>I have a pandas dataframe below,</p> <pre><code>data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2], 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017], 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]} df = pd.DataFrame(data) </code></pre> <p>Here df is a Pandas dataframe.</p> <p>I am trying to convert this dataframe to pandas API on spark</p> <pre><code>import pyspark.pandas as ps pdf = ps.from_pandas(df) print(type(pdf)) </code></pre> <p>Now the dataframe type is '&lt;class 'pyspark.pandas.frame.DataFrame'&gt; ' No I am applying group by function on pdf like below,</p> <pre><code>for i,j in pdf.groupby(&quot;Team&quot;): print(i) print(j) </code></pre> <p>I am getting an error below like</p> <pre><code>KeyError: (0,) </code></pre> <p>Not sure this functionality will work on pandas API on spark ?</p>
[ { "answer_id": 74404251, "author": "bichanna", "author_id": 17558100, "author_profile": "https://Stackoverflow.com/users/17558100", "pm_score": 1, "selected": true, "text": "counts = {}\n\nfor i in range(len(survived_list)):\n try:\n counts[countries_list[i]] += survived_list[i]\n except:\n counts[countries_list[i]] = survived_list[i]\n" }, { "answer_id": 74404337, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 1, "selected": false, "text": "df[\"died\"] = df[\"survived\"].map(lambda x: 1 if x==0 else 0)\ndf.groupby(['country']).sum()\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14076103/" ]
74,404,227
<p>In Google Sheets I have the following formula:</p> <pre><code>=IF(REGEXMATCH(B1;&quot;offers&quot;);&quot;spring&quot;;0) </code></pre> <p>If the cell B1 contains the text &quot;offers&quot; the output will be &quot;spring&quot;, otherwise the output will be &quot;0&quot;. This works fine but now I want the formular to look at B1 and C1 and if either of them contains &quot;offers&quot; the output should be &quot;spring&quot;.</p> <p><strong>Example Output with formula in column D:</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>B</th> <th>C</th> <th>D</th> </tr> </thead> <tbody> <tr> <td>test offers test</td> <td>lorem ipsum</td> <td>spring</td> </tr> <tr> <td>lorem ipsum</td> <td>test offers test</td> <td>spring</td> </tr> <tr> <td>lorem ipsum</td> <td>lorem ipsum</td> <td>0</td> </tr> </tbody> </table> </div> <p>I tried the obvious using</p> <pre><code>=IF(REGEXMATCH(B1:C1;&quot;offers&quot;);&quot;spring&quot;;0) </code></pre> <p>but it gives back a <code>#VALUE!</code></p> <p>In the second step I want to use this formula in a nested if function like here:</p> <pre><code>=IF(REGEXMATCH(B1;&quot;offers&quot;);&quot;spring&quot;;IF(REGEXMATCH(B1;&quot;shop&quot;);&quot;summer&quot;;0)) </code></pre>
[ { "answer_id": 74404251, "author": "bichanna", "author_id": 17558100, "author_profile": "https://Stackoverflow.com/users/17558100", "pm_score": 1, "selected": true, "text": "counts = {}\n\nfor i in range(len(survived_list)):\n try:\n counts[countries_list[i]] += survived_list[i]\n except:\n counts[countries_list[i]] = survived_list[i]\n" }, { "answer_id": 74404337, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 1, "selected": false, "text": "df[\"died\"] = df[\"survived\"].map(lambda x: 1 if x==0 else 0)\ndf.groupby(['country']).sum()\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20478666/" ]
74,404,244
<p>I have a problem to make migration with relationship.</p> <p>case :</p> <ul> <li>1 Department will have many Employees</li> <li>1 Employee belongTo 1 Department</li> <li>1 Department will have one manager (from employees table)</li> </ul> <p>Here is my migration</p> <pre><code>Schema::create('departments', function (Blueprint $table) { $table-&gt;id(); $table-&gt;string('name'); $table-&gt;foreignId('manager_id')-&gt;nullable() -&gt;references('id')-&gt;on('employees') -&gt;nullOnDelete(); $table-&gt;timestamps(); }); </code></pre> <hr /> <pre><code>Schema::create('employees', function (Blueprint $table) { $table-&gt;id(); $table-&gt;string('name', 255)-&gt;nullable(); $table-&gt;string('picture', 1024)-&gt;nullable(); $table-&gt;foreignId('user_id')-&gt;nullable() -&gt;references('id')-&gt;on('users') -&gt;nullOnDelete(); $table-&gt;foreignId('department_id')-&gt;nullable() -&gt;references('id')-&gt;on('departments') -&gt;nullOnDelete(); $table-&gt;timestamps(); }); </code></pre> <hr /> <p>when I do php artisan migrate:fresh it show up error :</p> <pre><code> SQLSTATE[42000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Foreign key 'departments_manager_id_foreign' references invalid table 'employees'. (SQL: alter table &quot;departments&quot; add constraint &quot;departments_manager_id_foreign&quot; foreign key (&quot;manager_id&quot;) references &quot;employees&quot; (&quot;id&quot;) on delete set null) </code></pre> <hr /> <p>This because there is no employees table when trying to create departments. But if I trying to create employees first, then no departments tables.</p> <p>Any suggestion for my problem ?</p> <p>Thank you</p>
[ { "answer_id": 74404655, "author": "Delano van londen", "author_id": 19923550, "author_profile": "https://Stackoverflow.com/users/19923550", "pm_score": -1, "selected": false, "text": "Schema::create('departments', function (Blueprint $table) {\n $table->increments(\"id\")->unsigned(false);\n $table->string('name');\n\n $table->unsignedInteger('manager_id')->value(11)->nullable(true);\n $table->foreign('manager_id')->references('id')->on('employees')->onDelete('cascade');\n $table->timestamps();\n });\n" }, { "answer_id": 74404808, "author": "N69S", "author_id": 4369919, "author_profile": "https://Stackoverflow.com/users/4369919", "pm_score": 1, "selected": false, "text": "Schema::create('departments', function (Blueprint $table) {\n $table->id();\n $table->string('name');\n\n $table->unsignedBigInteger('manager_id')->nullable();\n\n $table->timestamps();\n });\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17482687/" ]
74,404,261
<p>I have a list of strings called words such that</p> <pre><code>words = ['house', 'garden', 'kitchen', 'balloon', 'home', 'park', 'affair', 'kite', 'hello', 'portrait', 'angel', 'surfing'] </code></pre> <p>I have to find the most occurring letter in every position the strings, example, let's find the most occurring first letter, so I'll check every first letter of my strings and get 'h' because is the letter that most repeat it self. (If I get two letters that repeat themselves the same amount of times I'll consider the alphabetic order), so the second letter is 'a' because is the letter that repeat itself most time at the second position of all letters, then 'r' because of every third letter in every string is the one that is repeated mostly and so on, at the end I want the string <code>maxOccurs = &quot;hareennt&quot;</code> that is a string that contains all the most frequent letter. This is what I coded so far:</p> <pre><code>maxOccurs = &quot;&quot; listOfChars = [] for i in range(len(words)): for item in words: listOfChars.append(item[i]) maxOccurs += max(set(listOfChars), key=listOfChars.count) listOfChars.clear() </code></pre> <p>It raises me and index error out of bound when <code>i == 4</code>, obviously because not every letter has the same length, but I cannot get done with it, I will appreciate any help. P.S. I can't use any import.</p>
[ { "answer_id": 74404655, "author": "Delano van londen", "author_id": 19923550, "author_profile": "https://Stackoverflow.com/users/19923550", "pm_score": -1, "selected": false, "text": "Schema::create('departments', function (Blueprint $table) {\n $table->increments(\"id\")->unsigned(false);\n $table->string('name');\n\n $table->unsignedInteger('manager_id')->value(11)->nullable(true);\n $table->foreign('manager_id')->references('id')->on('employees')->onDelete('cascade');\n $table->timestamps();\n });\n" }, { "answer_id": 74404808, "author": "N69S", "author_id": 4369919, "author_profile": "https://Stackoverflow.com/users/4369919", "pm_score": 1, "selected": false, "text": "Schema::create('departments', function (Blueprint $table) {\n $table->id();\n $table->string('name');\n\n $table->unsignedBigInteger('manager_id')->nullable();\n\n $table->timestamps();\n });\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18943770/" ]
74,404,271
<p>I have read almost all similar topics but haven't found a working solution for my case. Sorry for posting similar question again.</p> <p>Let's imagine I have two strings:</p> <pre><code>String string1 = &quot;this is my string &quot;; String string2 = &quot;this is not my string that I want&quot;; </code></pre> <p>In my case I want my <em>string2</em> to be equal to <em>string1</em></p> <p>To do so I need to remove <strong>not</strong> and <strong>that I want</strong> parts from <em>string2</em> while collecting these mismatchings.</p> <p>As a result I would like to have something like this in my code:</p> <pre><code>List&lt;String&gt; mismatchings = ...; // consists of &quot;not&quot; and &quot;that I want&quot; String string2Adjusted = &quot;this is my string &quot;; // string2 after adjustment </code></pre> <p>Is there any util to do so, Or I might need to do some hard stuff with strings myself?</p>
[ { "answer_id": 74404636, "author": "Amir MB", "author_id": 7098758, "author_profile": "https://Stackoverflow.com/users/7098758", "pm_score": 1, "selected": false, "text": "public static void main(String[] args) {\n String string1 = \"this is my string \";\n String string2 = \"this is not my string that I want\";\n\n String[] str1Parts = string1.split(\"\\s+\");\n String[] str2Parts = string2.split(\"\\s+\");\n\n ArrayList<String> missMatches = new ArrayList<>();\n int i = 0;\n for (String part: str1Parts) {\n for (; i < str2Parts.length; i++) {\n String toCompare = str2Parts[i];\n if (!part.equals(toCompare)) {\n missMatches.add(toCompare);\n continue;\n }\n i++;\n break;\n }\n } \n StringBuilder rest = new StringBuilder();\n for (int start = i; i < str2Parts.length; i++) {\n if (start != i)\n rest.append(\" \");\n rest.append(str2Parts[i]);\n }\n\n missMatches.add(rest.toString());\n\n for (String missMatched: missMatches) {\n System.out.println(missMatched);\n }\n}\n" }, { "answer_id": 74405381, "author": "Serhii Kachan", "author_id": 11830541, "author_profile": "https://Stackoverflow.com/users/11830541", "pm_score": 0, "selected": false, "text": "<dependency>\n <groupId>org.bitbucket.cowwoc</groupId>\n <artifactId>diff-match-patch</artifactId>\n <version>1.2</version>\n</dependency>\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11830541/" ]
74,404,354
<p>My schema in MongoDB looks like this:</p> <pre><code>{ &quot;_id&quot;: &quot;be9e9198-86ab-456e-97e1-f1039cb07b59&quot;, &quot;isDeleted&quot;: false, &quot;user&quot;: { &quot;name&quot;: &quot;john2&quot;, &quot;surname&quot;: &quot;doe2&quot;, &quot;email&quot;: &quot;123.abcd@gmail.com&quot;, &quot;phone&quot;: &quot;+012345678912&quot;, &quot;age&quot;: 20, &quot;gender&quot;: &quot;male&quot;, &quot;nationality&quot;: &quot;smth&quot;, &quot;universityMajor&quot;: &quot;ENGINEERING&quot;, &quot;preferences&quot;: null, &quot;highPrivacy&quot;: false, } (Other stuff) . . . } </code></pre> <p>I am trying to include the field <code>user.phone</code> only when <code>user.highPrivacy</code> is set to False. Otherwise, I want to exclude the field.</p> <p>For example, given the above user, I should return the phone number. But if <code>user.highPrivacy</code> was later set to True, it should not include it.</p> <p>What I have tried so far is this:</p> <pre><code>dbConnection.aggregate([ {&quot;$match&quot; : {&quot;_id&quot;: userId, &quot;isDeleted&quot; : False} }, { &quot;$project&quot; : { &quot;postings&quot; : 0, &quot;starredPostings&quot; : 0, &quot;user.timestamp&quot; : 0, &quot;user.phone&quot; : { &quot;$cond&quot; : [{&quot;$eq&quot;: [&quot;$user.highPrivacy&quot;, True]}, 0, &quot;$user.phone&quot;] }, } }, ]) </code></pre> <p>This keep giving me the error:</p> <pre><code>pymongo.errors.OperationFailure: Invalid $project :: caused by :: Cannot use expression other than $meta in exclusion projection </code></pre> <p>But the answers that are here:</p> <ul> <li><a href="https://stackoverflow.com/questions/37933221/conditionally-include-a-field-id-or-other-in-mongodb-project-aggregation?rq=1">Conditionally include a field (_id or other) in mongodb project aggregation?</a></li> <li><a href="https://stackoverflow.com/questions/41635878/project-different-fields-based-on-different-condition">Project different fields based on different condition</a></li> <li><a href="https://kb.objectrocket.com/mongo-db/mongodb-project-condition-how-to-use-project-with-a-condition-469" rel="nofollow noreferrer">https://kb.objectrocket.com/mongo-db/mongodb-project-condition-how-to-use-project-with-a-condition-469</a></li> </ul> <p>are using the same projection as me, or at least I think they are.</p> <p>So where exactly is the issue in my aggregation?</p>
[ { "answer_id": 74404636, "author": "Amir MB", "author_id": 7098758, "author_profile": "https://Stackoverflow.com/users/7098758", "pm_score": 1, "selected": false, "text": "public static void main(String[] args) {\n String string1 = \"this is my string \";\n String string2 = \"this is not my string that I want\";\n\n String[] str1Parts = string1.split(\"\\s+\");\n String[] str2Parts = string2.split(\"\\s+\");\n\n ArrayList<String> missMatches = new ArrayList<>();\n int i = 0;\n for (String part: str1Parts) {\n for (; i < str2Parts.length; i++) {\n String toCompare = str2Parts[i];\n if (!part.equals(toCompare)) {\n missMatches.add(toCompare);\n continue;\n }\n i++;\n break;\n }\n } \n StringBuilder rest = new StringBuilder();\n for (int start = i; i < str2Parts.length; i++) {\n if (start != i)\n rest.append(\" \");\n rest.append(str2Parts[i]);\n }\n\n missMatches.add(rest.toString());\n\n for (String missMatched: missMatches) {\n System.out.println(missMatched);\n }\n}\n" }, { "answer_id": 74405381, "author": "Serhii Kachan", "author_id": 11830541, "author_profile": "https://Stackoverflow.com/users/11830541", "pm_score": 0, "selected": false, "text": "<dependency>\n <groupId>org.bitbucket.cowwoc</groupId>\n <artifactId>diff-match-patch</artifactId>\n <version>1.2</version>\n</dependency>\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13349539/" ]
74,404,358
<p>I'm trying to find the remainder of each number in a list that is equal to one, but the problem is I get an index error</p> <p>Here I compare the current item in the list to the next one:</p> <pre><code>numbers = [1,2,3,4,5,6] sorted_number = sorted(numbers) for index, num in enumerate(sorted_number): if sorted_number[index + 1] % sorted_number[index] == 1: print(index, num) </code></pre>
[ { "answer_id": 74404397, "author": "jprebys", "author_id": 3268228, "author_profile": "https://Stackoverflow.com/users/3268228", "pm_score": 3, "selected": true, "text": "sorted_number" }, { "answer_id": 74404405, "author": "svfat", "author_id": 2419628, "author_profile": "https://Stackoverflow.com/users/2419628", "pm_score": 0, "selected": false, "text": "for index, num in enumerate(sorted_number):\n if index < len(sorted_number) - 1:\n if sorted_number[index + 1] % sorted_number[index] == 1:\n print(index, num)\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1020623/" ]
74,404,371
<p>So I'm querying something like the following, however, some of my rows are NULL and I want the query to replace the values where NULL to a specific different value in the same row:</p> <pre><code>SELECT * FROM table &gt;&gt;&gt; table &quot;ID&quot; &quot;First Name&quot; &quot;Last Name&quot; &quot;Default - First Name&quot; &quot;Default - Last Name&quot; &quot;1111&quot; &quot;Bill&quot; &quot;Jones&quot; &quot;FN Name 1&quot; &quot;LN Name 1&quot; &quot;2222&quot; NULL NULL &quot;FN Name 2&quot; &quot;LN Name 2&quot; &quot;3333&quot; &quot;Emma&quot; &quot;Jean&quot; &quot;FN Name 3&quot; &quot;LN Name 3&quot; </code></pre> <p>So I want my final Query result to be this:</p> <pre><code>Final Query Result &quot;ID&quot; &quot;First Name&quot; &quot;Last Name&quot; &quot;Default - First Name&quot; &quot;Default - Last Name&quot; &quot;1111&quot; &quot;Bill&quot; &quot;Jones&quot; &quot;FN Name 1&quot; &quot;LN Name 1&quot; &quot;2222&quot; &quot;FN Name 2&quot; &quot;LN Name 2&quot; &quot;FN Name 2&quot; &quot;LN Name 2&quot; &quot;3333&quot; &quot;Emma&quot; &quot;Jean&quot; &quot;FN Name 3&quot; &quot;LN Name 3&quot; </code></pre> <p>So I want to replace the NULL values with the values in the same row in the default First and Last name columns.</p> <p>Any ideas on how I can query this?</p>
[ { "answer_id": 74404397, "author": "jprebys", "author_id": 3268228, "author_profile": "https://Stackoverflow.com/users/3268228", "pm_score": 3, "selected": true, "text": "sorted_number" }, { "answer_id": 74404405, "author": "svfat", "author_id": 2419628, "author_profile": "https://Stackoverflow.com/users/2419628", "pm_score": 0, "selected": false, "text": "for index, num in enumerate(sorted_number):\n if index < len(sorted_number) - 1:\n if sorted_number[index + 1] % sorted_number[index] == 1:\n print(index, num)\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13675684/" ]
74,404,392
<p>For example java code</p> <pre><code>public abstract class BindingElement&lt;T extends ViewDataBinding&gt; { T binding; abstract public T createBinding(LayoutInflater inflater, ViewGroup parent); public BindingElement(ViewGroup parent) { binding = createBinding(LayoutInflater.from(parent.getContext()), parent); binding.setLifecycleOwner(ViewTreeLifecycleOwner.get(parent)); } } </code></pre> <p>I need some necessary property that defined in constructor. And then i will do something with that property. What is the best way write it in kotlin?</p>
[ { "answer_id": 74404500, "author": "Steyrix", "author_id": 7221362, "author_profile": "https://Stackoverflow.com/users/7221362", "pm_score": 0, "selected": false, "text": "abstract class BindingElement<T: ViewDataBinding> {\n\n val binding: T\n\n abstract fun createBinding(LayoutInflater inflater, ViewGroup parent): T\n\n init {\n binding = createBinding(...)\n }\n}\n" }, { "answer_id": 74404902, "author": "WetABQ", "author_id": 16587904, "author_profile": "https://Stackoverflow.com/users/16587904", "pm_score": 0, "selected": false, "text": "abstract class BindingElement<T: ViewDataBinding>(\n val parent: ViewGroup\n) {\n val binding = createBinding(..., parent)\n\n abstract fun createBinding(LayoutInflater inflater, ViewGroup parent): T\n\n}\n" }, { "answer_id": 74406728, "author": "Tenfour04", "author_id": 506796, "author_profile": "https://Stackoverflow.com/users/506796", "pm_score": 2, "selected": true, "text": "class ViewBindingParameter<T: ViewBindingData> (\n parent: ViewGroup,\n inflateBinding: (LayoutInflater, ViewGroup)->T\n) {\n\n val binding: T = inflateBinding(LayoutInflater.from(parent.context), parent)\n\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14335049/" ]
74,404,411
<p>I want to create a folder and write a file in real external storage (real extern sd card). I can write to the internal storage, the external storage, but not to the external sd card (I mean the external storage card you put into a cell phone for more space to store images, videos, ...). The path of the external sd-card is: &quot;/storage/1234-5678/&quot; and it is on a samsung smartphone. Reading from the external sd card works without problems. I am testing with Android 8 (and later with higher versions).</p> <p>I have searched through internet and try but not getting the result, I have added permissions in Android Manifest file as well.</p> <pre><code>&lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; android:maxSdkVersion=&quot;29&quot; tools:ignore=&quot;ScopedStorage&quot; /&gt; </code></pre> <p>and an easy test is:</p> <pre><code>File directory = new File(&quot;/storage/1234-5678/new_folder/&quot;); if (!directory.exists()) { boolean ok = directory.mkdirs(); } </code></pre> <p>The result to ok is always false, when I use the path to the external / removable sd card.<br /> What I am doing wrong?</p>
[ { "answer_id": 74404500, "author": "Steyrix", "author_id": 7221362, "author_profile": "https://Stackoverflow.com/users/7221362", "pm_score": 0, "selected": false, "text": "abstract class BindingElement<T: ViewDataBinding> {\n\n val binding: T\n\n abstract fun createBinding(LayoutInflater inflater, ViewGroup parent): T\n\n init {\n binding = createBinding(...)\n }\n}\n" }, { "answer_id": 74404902, "author": "WetABQ", "author_id": 16587904, "author_profile": "https://Stackoverflow.com/users/16587904", "pm_score": 0, "selected": false, "text": "abstract class BindingElement<T: ViewDataBinding>(\n val parent: ViewGroup\n) {\n val binding = createBinding(..., parent)\n\n abstract fun createBinding(LayoutInflater inflater, ViewGroup parent): T\n\n}\n" }, { "answer_id": 74406728, "author": "Tenfour04", "author_id": 506796, "author_profile": "https://Stackoverflow.com/users/506796", "pm_score": 2, "selected": true, "text": "class ViewBindingParameter<T: ViewBindingData> (\n parent: ViewGroup,\n inflateBinding: (LayoutInflater, ViewGroup)->T\n) {\n\n val binding: T = inflateBinding(LayoutInflater.from(parent.context), parent)\n\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17060353/" ]
74,404,422
<p>Hello I'm trying out CSS transition property, and I'm having some trouble, when I hover the main tag, the images transitions into their respective positions which I have given, but as soon as I remove the cursor, the images disappear in an instant, without the transition property which I have set, it works just fine when I'm using only background color instead of image, I want the transition to be applied also when I remove the hover from the images,</p> <p>This is the CSS code that I have written</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { margin: 0; padding: 0; box-sizing: border-box; } main { width: 900px; height: 600px; margin: 10px auto; border: 1px solid black; position: relative; overflow: hidden; } .box { width: 300px; height: 600px; position: absolute; top: 0; left: -300px; transition: ease-out; transition: 2s; } main:hover .box:nth-child(1) { top: 0; left: 0; background: url('https://picsum.photos/seed/picsum/300/600'); background-size: cover; } main:hover .box:nth-child(2) { top: 0; left: 300px; background: url('https://picsum.photos/id/237/300/600'); background-size: cover; } main:hover .box:nth-child(3) { top: 0; left: 600px; background: url('https://picsum.photos/300/600.jpg'); background-size: cover; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;main&gt; &lt;div class="box"&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;/div&gt; &lt;/main&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74404822, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 1, "selected": false, "text": "* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\nmain {\n width: 900px;\n height: 600px;\n margin: 10px auto;\n border: 1px solid black;\n position: relative;\n overflow: hidden;\n transition: ease-in-out;\n transition: 2s;\n}\n\n.box {\n width: 300px;\n height: 600px;\n position: absolute;\n top: 0;\n left: -300px;\n transition: ease-in-out;\n transition: 2s;\n left: 0;\n background-size: cover;\n}\n\nmain:hover .box:nth-child(1) {\n top: 0;\n left: 0;\n background: url('https://picsum.photos/seed/picsum/300/600');\n background-size: cover;\n}\n.box:nth-child(1) {\n top: 0;\n left: -300px;\n background: url('https://picsum.photos/seed/picsum/300/600');\n background-size: cover;\n}\n.box:nth-child(2) {\n top: 0;\n left: -300px;\n background: url('https://picsum.photos/id/237/300/600');\n background-size: cover;\n }\n.box:nth-child(3) {\n top: 0;\n left: -300px;\n background: url('https://picsum.photos/id/237/300/600');\n background-size: cover;\n }\n\nmain:hover .box:nth-child(2) {\n top: 0;\n left: 300px;\n background: url('https://picsum.photos/id/237/300/600');\n background-size: cover;\n}\n\nmain:hover .box:nth-child(3) {\n top: 0;\n left: 600px;\n background: url('https://picsum.photos/300/600.jpg');\n background-size: cover;\n}" }, { "answer_id": 74404993, "author": "Skin_phil", "author_id": 13258195, "author_profile": "https://Stackoverflow.com/users/13258195", "pm_score": 0, "selected": false, "text": "var x = document.getElementsByClassName(\"box\");\n\nvar animations = {\n \"animation\": \"animationiteration\",\n \"OAnimation\": \"oAnimationIteration\",\n \"MozAnimation\": \"animationiteration\",\n \"WebkitAnimation\": \"webkitAnimationIteration\"\n};\n\n\nfor (let i = 0; i < x.length; i++) {\n\n x[i].addEventListener(\"animationend\", function(e) {\n if (i == 0) {\n x[i].style.left = \"0\";\n }\n if (i == 1) {\n x[i].style.left = \"300px\";\n }\n if (i == 2) {\n x[i].style.left = \"600px\";\n }\n for (let t in animations) {\n if (x[i].style[t] !== undefined) {\n x[i].style[t]=\"none\";\n }\n }\n \n});\n x[i].addEventListener(\"webkitAnimationEnd\", function(e) {\n if (i == 0) {\n x[i].style.left = \"0\";\n }\n if (i == 1) {\n x[i].style.left = \"300px\";\n }\n if (i == 2) {\n x[i].style.left = \"600px\";\n }\n for (let t in animations) {\n if (x[i].style[t] !== undefined) {\n x[i].style[t]=\"none\";\n }\n }\n \n});\n}\n// Code for Chrome, Safari and Opera\n\n\n// Standard syntax\nfunction myEndFunction(el,i) {\n console.log(\"hi\")\n}" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12138807/" ]
74,404,424
<p>I'm setting up a new development environment (moved from Windows 7 to Lubuntu), and now I'm trying to set up a React app on it for the first time. Well, second. <code>create-react-app</code> worked, but I like to do things by hand. I finally have <code>webpack</code> and <code>webpack-dev-server</code> working, but when I go to <code>localhost:8080</code>, the React components don't render, and I get three errors relating to an invalid element type.</p> <p>I read <a href="https://stackoverflow.com/questions/42813342/react-createelement-type-is-invalid-expected-a-string">here</a> that it's usually an import/export problem, but I haven't been able to find it, after following the suggestions given. Here's what I have:</p> <p>index.js</p> <pre><code>const React = require('react'); // syntax made no difference import * as ReactDOMClient from 'react-dom/client' const App = require('./components/App.js'); const root = ReactDOMClient.createRoot(document.getElementById('app')); root.render(&lt;App /&gt;); </code></pre> <p>index.html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en-US&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;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;style.css&quot; /&gt; &lt;/head&gt; &lt;body&gt; &lt;div id=&quot;app&quot;&gt;This does appear&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>App.js</p> <pre><code>const React = require('react'); export default class App extends React.Component { constructor(props) { super(props); console.log(&quot;App constructed?&quot;); } render() { return (&lt;h1&gt;This should appear&lt;/h1&gt;); } } </code></pre> <p>The three errors:</p> <blockquote> <p>Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.</p> </blockquote> <blockquote> <p>Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.</p> </blockquote> <blockquote> <p>Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.</p> </blockquote> <p>The only thing on the stack trace that made any sense to me (I can post the rest if you want) comes from the first warning and points to line 7 of index.js, which is <code>root.render(&lt;App /&gt;);</code>. I'm not sure how to post my file structure neatly, but I can assure you ./components/App.js (with or without extension) is the correct relative path here.</p> <p>Any suggestions?</p> <p>I'm using npm, so I think I have the best versions of each module. Here is my package.json:</p> <pre><code>{ &quot;name&quot;: &quot;try-word&quot;, &quot;version&quot;: &quot;1.0.0&quot;, &quot;description&quot;: &quot;&quot;, &quot;main&quot;: &quot;index.js&quot;, &quot;scripts&quot;: { &quot;dev&quot;: &quot;webpack --mode development&quot;, &quot;build&quot;: &quot;webpack&quot;, &quot;start&quot;: &quot;webpack-dev-server&quot;, &quot;devstart&quot;: &quot;webpack-dev-server --mode development&quot; }, &quot;author&quot;: &quot;&quot;, &quot;license&quot;: &quot;ISC&quot;, &quot;dependencies&quot;: { &quot;react&quot;: &quot;^18.2.0&quot;, &quot;react-dom&quot;: &quot;^18.2.0&quot; }, &quot;devDependencies&quot;: { &quot;@babel/core&quot;: &quot;^7.20.2&quot;, &quot;@babel/preset-react&quot;: &quot;^7.18.6&quot;, &quot;babel-loader&quot;: &quot;^9.1.0&quot;, &quot;html-webpack-plugin&quot;: &quot;^5.5.0&quot;, &quot;webpack&quot;: &quot;^5.75.0&quot;, &quot;webpack-cli&quot;: &quot;^4.10.0&quot;, &quot;webpack-dev-server&quot;: &quot;^4.11.1&quot; } } </code></pre> <p>Anything logged in index.js prints out fine, amidst the errors, but the log in the App constructor never does. It seems like App isn't getting imported correctly, but I'm not sure how to fix that.</p> <p>EDIT</p> <p>webpack.config.js</p> <pre><code>const HTMLWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: __dirname + '/app/index.js', module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: [ { loader: 'babel-loader' } ] } ] }, output: { filename: 'transformed.js', path: __dirname + '/dist' }, plugins: [new HTMLWebpackPlugin({ template: __dirname + '/app/index.html', filename: 'index.html', inject: 'body' })], performance: { hints: false, maxEntrypointSize: 512000, maxAssetSize: 512000 } }; </code></pre>
[ { "answer_id": 74404822, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 1, "selected": false, "text": "* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\nmain {\n width: 900px;\n height: 600px;\n margin: 10px auto;\n border: 1px solid black;\n position: relative;\n overflow: hidden;\n transition: ease-in-out;\n transition: 2s;\n}\n\n.box {\n width: 300px;\n height: 600px;\n position: absolute;\n top: 0;\n left: -300px;\n transition: ease-in-out;\n transition: 2s;\n left: 0;\n background-size: cover;\n}\n\nmain:hover .box:nth-child(1) {\n top: 0;\n left: 0;\n background: url('https://picsum.photos/seed/picsum/300/600');\n background-size: cover;\n}\n.box:nth-child(1) {\n top: 0;\n left: -300px;\n background: url('https://picsum.photos/seed/picsum/300/600');\n background-size: cover;\n}\n.box:nth-child(2) {\n top: 0;\n left: -300px;\n background: url('https://picsum.photos/id/237/300/600');\n background-size: cover;\n }\n.box:nth-child(3) {\n top: 0;\n left: -300px;\n background: url('https://picsum.photos/id/237/300/600');\n background-size: cover;\n }\n\nmain:hover .box:nth-child(2) {\n top: 0;\n left: 300px;\n background: url('https://picsum.photos/id/237/300/600');\n background-size: cover;\n}\n\nmain:hover .box:nth-child(3) {\n top: 0;\n left: 600px;\n background: url('https://picsum.photos/300/600.jpg');\n background-size: cover;\n}" }, { "answer_id": 74404993, "author": "Skin_phil", "author_id": 13258195, "author_profile": "https://Stackoverflow.com/users/13258195", "pm_score": 0, "selected": false, "text": "var x = document.getElementsByClassName(\"box\");\n\nvar animations = {\n \"animation\": \"animationiteration\",\n \"OAnimation\": \"oAnimationIteration\",\n \"MozAnimation\": \"animationiteration\",\n \"WebkitAnimation\": \"webkitAnimationIteration\"\n};\n\n\nfor (let i = 0; i < x.length; i++) {\n\n x[i].addEventListener(\"animationend\", function(e) {\n if (i == 0) {\n x[i].style.left = \"0\";\n }\n if (i == 1) {\n x[i].style.left = \"300px\";\n }\n if (i == 2) {\n x[i].style.left = \"600px\";\n }\n for (let t in animations) {\n if (x[i].style[t] !== undefined) {\n x[i].style[t]=\"none\";\n }\n }\n \n});\n x[i].addEventListener(\"webkitAnimationEnd\", function(e) {\n if (i == 0) {\n x[i].style.left = \"0\";\n }\n if (i == 1) {\n x[i].style.left = \"300px\";\n }\n if (i == 2) {\n x[i].style.left = \"600px\";\n }\n for (let t in animations) {\n if (x[i].style[t] !== undefined) {\n x[i].style[t]=\"none\";\n }\n }\n \n});\n}\n// Code for Chrome, Safari and Opera\n\n\n// Standard syntax\nfunction myEndFunction(el,i) {\n console.log(\"hi\")\n}" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17950927/" ]
74,404,427
<p><strong>EDIT:</strong></p> <p>Thank you guys for all your input, I'm not sure if the case is resolved but it seems so.</p> <p>In my former Data preparation function I have shuffled the training sequences, which resulted in LSTM predicting an average. I was browsing the internet and I have found by accident that other people do not shuffle their data.</p> <p>I'm not sure if not shuffling the data is ok - it seems strange to me, and I couldn't find the 0-1 answer on this topic, but when I tried, the LSTM infact did well on test dataset: <a href="https://i.stack.imgur.com/Wkm0H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wkm0H.png" alt="enter image description here" /></a></p> <p>Can someone please elaborate why shuffling the data criplles the model? Or not shuffling the data in case of LSTM is just as bad as in case of other models?</p> <p>I am trying to make an LSTM to predict the next value of an indicator but it predicts mean.</p> <p><strong>Data:</strong> (Note: Data preparation function is on the bottom of the post so the post itself will be more readable) I have around <code>25 000</code> entries in each data record and I have <code>14 columns</code> of characteristics. So my main array is <code>25 000 x 14</code>. When I prepare my data I am creating sequences in a shape of [number of sequences, samples in a sequence, features] and from then on <code>6 sets</code> of data:</p> <ol> <li>X_train, Y_train</li> <li>X_valid, Y_valid</li> <li>X_test, Y_test</li> </ol> <p>Where Y test is the one step ahead value of a feature I am trying to predict. Note: All datasets are scaled with <code>MinMaxScaler</code> in range <code>(-1, 1)</code> hence some data is below zero.</p> <p>The value I am trying to predicts behaves in a following manner (previous values are inside X datasets): <a href="https://i.stack.imgur.com/slvoq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/slvoq.png" alt="How data I am trying to predict looks like" /></a></p> <p><strong>Example of the data sample:</strong> (Hence, different level of values I've plotted some series on another chart):</p> <p><a href="https://i.stack.imgur.com/exxVK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/exxVK.png" alt="enter image description here" /></a></p> <p><strong>The Problem:</strong></p> <p>The problem is that no matter how many neurons, layers, what activation functions I use it predicts the mean value of a characteristic no matter what, and basically when the neural net hits loss of value around <code>0.078</code> the loss stops decreasing, If I waint longer and give it more epochs on the same <code>learning rate</code> sometimes loss skyrockets to '<code>NaN</code> or <code>10^30</code>.</p> <p>Here is my Model:</p> <pre><code>X_train, Y_train, X_valid, Y_valid, X_test, Y_test, scaler = prepare_datasets_lstm_backup(dataset=dataset, samples=200) optimizer = keras.optimizers.Adam(learning_rate=0.001) initializer = keras.initializers.he_normal model = keras.models.Sequential() model.add(keras.layers.LSTM(64, activation='relu', input_shape=(200, 14), return_sequences=True)) model.add(keras.layers.LSTM(64, activation='relu', return_sequences=True)) model.add(keras.layers.LSTM(3, kernel_regularizer='l2', bias_regularizer='l2', return_sequences=False)) model.add(keras.layers.Activation('sigmoid')) model.compile(loss='mse', optimizer=optimizer) history = model.fit(X_train, Y_train, epochs=10, validation_data=(X_valid, Y_valid)) plt.plot(history.history['loss'], label='loss') plt.plot(history.history['val_loss'], label='val_loss') plt.legend() plt.xlabel('Epochs') plt.ylabel('loss function value') plt.grid() plt.show() prediction = model.predict(X_test) </code></pre> <p><strong>The possible solution</strong></p> <p>While simply increasing number of neurons and layers didn't helped I found a post on <code>CrossValidated</code> stackexchange forum: <a href="https://stats.stackexchange.com/questions/261704/training-a-neural-network-for-regression-always-predicts-the-mean">https://stats.stackexchange.com/questions/261704/training-a-neural-network-for-regression-always-predicts-the-mean</a> Where I've read two important things, below I will describe in short words what I've read but you can go and check out these answers:</p> <ol> <li>go to the @mhdadk's answer and check it out.</li> <li>got to the Bob's answer and check it out.</li> </ol> <p>So the conculsion is that maybe my Neural Network is not complex enough even with <code>1000 neurons</code> in <code>two layers</code>. It would certainly be interesting to chekc out the neural net with <code>10000 neurons</code> and see if it works, but the problem is I would have to run it on Google Cloud VM, where it would propably compute for a month hence I have a limit of 8 CPU's per VM.</p> <p><strong>The first Question:</strong></p> <p>Is it even worth trying to build a neural net with 10k-50k neurons, since I have no idea if it would bring some positive results, and if not I would wast 500 USD or 1000 USD or even more and a month or more of time. What do you think?</p> <p><strong>Second Question</strong></p> <p>If predicting the raw value seems undoable, then could the neural network actually work with classification i.e. predicting if the next value will be between certain treshold, above it or beneath it? Or would it predict mean value of class also i.e. most frequent class for all predictions?</p> <p><strong>Third question</strong></p> <p>Can it be the case that I am feeding a neural net with too much data and limitng the data to 5 000 or 10 000 entries would help?</p> <p><strong>Fourth question</strong></p> <p>Do you have any other ideas that might help with the prediction?</p> <p>Thank you all for your time reading this and thank you for your help in advance :)</p> <p>As I wrote above here is the data preparation function:</p> <pre><code>def prepare_datasets_lstm(dataset : pd.DataFrame, samples : int): main_data_df = dataset.copy() main_data_df = main_data_df.dropna(how='any').copy() main_data_df = main_data_df[main_data_df.columns[~main_data_df.columns.isin(['timestamp', 'datetime'])]].copy() main_data_np = main_data_df.copy().to_numpy(dtype='float32') scaler = StandardScaler() signal_data = main_data_np[:, 5] main_data_scaled = scaler.fit_transform(main_data_np.copy()) joblib.dump(scaler, 'lstm_scaler.save') samples_val = samples sequences_val = (main_data_scaled.shape[0] - samples_val) - 1 columns_val = main_data_scaled.shape[1] # seqeunces = np.empty((liczba sekwencji, liczba sampli w sekwencji, kolumny)) seqeunces = np.empty((sequences_val + 1, samples_val, columns_val)) # etiquets = np.empty((liczba sekwencji - 1, 1 element w sekwencji, liczba przewidywanych wartości)) etiquets = np.empty((sequences_val, 1, 1)) for i in range(sequences_val + 1): for j in range(samples_val): for k in range(columns_val): seqeunces[i, j, k] = main_data_scaled[i + j, k] for i in range(sequences_val): etiquets[i, 0, 0] = signal_data[i]#seqeunces[i + 1, 0, 5] # CCI seqeunces = seqeunces[:-1, :, :].copy() shape_x = main_data_scaled.shape[0] train_len = math.floor(0.7 * shape_x) valid_len = math.floor((shape_x - train_len) * 0.5) + train_len train_dataset = seqeunces[:train_len, :, :].copy() train_etiquets = etiquets[:train_len, :, :].copy() valid_dataset = seqeunces[train_len : valid_len, :, :].copy() valid_etiquets = etiquets[train_len : valid_len, :, :].copy() test_dataset = seqeunces[valid_len:, :, :].copy() test_etiquets = etiquets[valid_len:, :, :].copy() train_etiquets_shuffled, train_dataset_shuffled = shuffle((train_dataset, train_etiquets), random_state=0) valid_etiquets_shuffled, valid_dataset_shuffled = shuffle((valid_dataset, valid_etiquets), random_state=0) X_train = train_dataset_shuffled.copy() Y_train = train_etiquets_shuffled.copy() X_valid = valid_dataset_shuffled.copy() Y_valid = valid_etiquets_shuffled.copy() X_test = test_dataset.copy() Y_test = test_etiquets.copy() return X_train, Y_train, X_valid, Y_valid, X_test, Y_test, scaler </code></pre>
[ { "answer_id": 74404822, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 1, "selected": false, "text": "* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\nmain {\n width: 900px;\n height: 600px;\n margin: 10px auto;\n border: 1px solid black;\n position: relative;\n overflow: hidden;\n transition: ease-in-out;\n transition: 2s;\n}\n\n.box {\n width: 300px;\n height: 600px;\n position: absolute;\n top: 0;\n left: -300px;\n transition: ease-in-out;\n transition: 2s;\n left: 0;\n background-size: cover;\n}\n\nmain:hover .box:nth-child(1) {\n top: 0;\n left: 0;\n background: url('https://picsum.photos/seed/picsum/300/600');\n background-size: cover;\n}\n.box:nth-child(1) {\n top: 0;\n left: -300px;\n background: url('https://picsum.photos/seed/picsum/300/600');\n background-size: cover;\n}\n.box:nth-child(2) {\n top: 0;\n left: -300px;\n background: url('https://picsum.photos/id/237/300/600');\n background-size: cover;\n }\n.box:nth-child(3) {\n top: 0;\n left: -300px;\n background: url('https://picsum.photos/id/237/300/600');\n background-size: cover;\n }\n\nmain:hover .box:nth-child(2) {\n top: 0;\n left: 300px;\n background: url('https://picsum.photos/id/237/300/600');\n background-size: cover;\n}\n\nmain:hover .box:nth-child(3) {\n top: 0;\n left: 600px;\n background: url('https://picsum.photos/300/600.jpg');\n background-size: cover;\n}" }, { "answer_id": 74404993, "author": "Skin_phil", "author_id": 13258195, "author_profile": "https://Stackoverflow.com/users/13258195", "pm_score": 0, "selected": false, "text": "var x = document.getElementsByClassName(\"box\");\n\nvar animations = {\n \"animation\": \"animationiteration\",\n \"OAnimation\": \"oAnimationIteration\",\n \"MozAnimation\": \"animationiteration\",\n \"WebkitAnimation\": \"webkitAnimationIteration\"\n};\n\n\nfor (let i = 0; i < x.length; i++) {\n\n x[i].addEventListener(\"animationend\", function(e) {\n if (i == 0) {\n x[i].style.left = \"0\";\n }\n if (i == 1) {\n x[i].style.left = \"300px\";\n }\n if (i == 2) {\n x[i].style.left = \"600px\";\n }\n for (let t in animations) {\n if (x[i].style[t] !== undefined) {\n x[i].style[t]=\"none\";\n }\n }\n \n});\n x[i].addEventListener(\"webkitAnimationEnd\", function(e) {\n if (i == 0) {\n x[i].style.left = \"0\";\n }\n if (i == 1) {\n x[i].style.left = \"300px\";\n }\n if (i == 2) {\n x[i].style.left = \"600px\";\n }\n for (let t in animations) {\n if (x[i].style[t] !== undefined) {\n x[i].style[t]=\"none\";\n }\n }\n \n});\n}\n// Code for Chrome, Safari and Opera\n\n\n// Standard syntax\nfunction myEndFunction(el,i) {\n console.log(\"hi\")\n}" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19797660/" ]
74,404,433
<p>I am VERY new to rust, and really programming in general. I am writing a rust program that will detect idle and print out the time since the last input. I am using the winapi crate. The code below returns between 0ns and 31ms, regardless of how long it's been since I pressed a key or moved the mouse. It never gets higher than 31ms.</p> <pre><code>use winapi::um::{ winuser::{ LASTINPUTINFO, PLASTINPUTINFO, GetLastInputInfo }, }; fn sleep(milliseconds: u64){ let mills = std::time::Duration::from_millis(milliseconds); std::thread::sleep(mills); } fn main() { loop { let now = unsafe { winapi::um::sysinfoapi::GetTickCount() }; let mut last_input_info = LASTINPUTINFO { cbSize: std::mem::size_of::&lt;LASTINPUTINFO&gt;() as u32, dwTime: 0 }; let p_last_input_info: PLASTINPUTINFO = &amp;mut last_input_info as *mut LASTINPUTINFO; let ok = unsafe { GetLastInputInfo(p_last_input_info) } != 0; let logvar = match ok { true =&gt; { let millis = now - last_input_info.dwTime; Ok(std::time::Duration::from_millis(millis as u64)) }, false =&gt; Err(format!(&quot;GetLastInputInfo failed&quot;)) }.unwrap(); println!(&quot;{:?}&quot;, logvar); sleep(1000); }; } </code></pre> <p>I considered that it might be some program that is keeping the PC from going idle, so using powercfg -requests, I found some audio streams open (still don't know how to fix that). I just don't know if that could be what's happening here. Community expertise requested!</p>
[ { "answer_id": 74407016, "author": "shy45", "author_id": 20313707, "author_profile": "https://Stackoverflow.com/users/20313707", "pm_score": 1, "selected": false, "text": "#include <windows.h>\n\nint main() {\n LASTINPUTINFO lii;\n lii.cbSize = sizeof(LASTINPUTINFO);\n\n for (;;) {\n int ret = GetLastInputInfo(&lii);\n printf(\"ret=%d diff=%d\\n\", ret, GetTickCount() - lii.dwTime);\n Sleep(1000);\n }\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14357420/" ]
74,404,471
<p>So, I don't know how can I print elements of such a list.</p> <pre><code>list&lt;int&gt;* a; a = new list&lt;int&gt;(4); a[0].push_back(1); a[0].push_back(3); a[2].push_back(5); a[2].push_back(7); cout &lt;&lt; a[0].front() &lt;&lt; '\n'; cout &lt;&lt; a[1].back() &lt;&lt; '\n'; </code></pre> <p>Firstly, I tried to print it via range-based for loop, but it didn't work either.</p> <pre><code>for(auto element: a[0]) cout &lt;&lt; element &lt;&lt; '\n'; // doesn't work </code></pre>
[ { "answer_id": 74404551, "author": "Cory Kramer", "author_id": 2296458, "author_profile": "https://Stackoverflow.com/users/2296458", "pm_score": 0, "selected": false, "text": "std::vector" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16327378/" ]
74,404,516
<p>I'm having troubles returning errors on my server. when running on localhost - everything works fine, custom errors are returning great to the client. After deploying to a host (Heroku, Render etc...) the valid requests are working as expected, but when error is occuring - Im receiving 500 instead of the custom error I'd like to return.</p> <p>Tried several error handlers and no work.</p> <p>ERROR HANDLER (SERVER)</p> <pre><code>const errorHandler = (error, request, response, next) =&gt; { console.log(error); if (error.errorType !== undefined &amp;&amp; error.errorType.isShowStackTrace){ response.status(error.errorType.httpCode).json({message: error.errorType.message}); return; } response.status(700).json({message: 'GENERAL ERROR OCCURED'}); } module.exports = errorHandler; </code></pre> <p>REQUEST (CLIENT)</p> <pre><code> try{ const response = await axios.post(&quot;https://myUrl.com/users/login&quot;, user); localStorage.setItem(&quot;token&quot;, response.data.token); return response.data; } catch (err : any){ return err; } </code></pre> <p>Expected custom error, and got 500</p>
[ { "answer_id": 74404551, "author": "Cory Kramer", "author_id": 2296458, "author_profile": "https://Stackoverflow.com/users/2296458", "pm_score": 0, "selected": false, "text": "std::vector" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15092986/" ]
74,404,527
<p>I'm trying to make a crossword in google sheets, and would like the clue numbers to be as far up in the top left of the cell as possible. Using the normal alignment buttons puts in in the corner, but still further away from the cell edge than I like. Is there way to specify the margins within a cell between text and the borders?</p> <p>Thanks!</p>
[ { "answer_id": 74404551, "author": "Cory Kramer", "author_id": 2296458, "author_profile": "https://Stackoverflow.com/users/2296458", "pm_score": 0, "selected": false, "text": "std::vector" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20037532/" ]
74,404,561
<p>I have two tables, <code>table_A</code> and <code>table_B</code>. I want to do a left join on both tables so that each record in table_A is matched with a record in table_B using the date as a key. However some dates in A will be missing in B and vice-versa. So my goal is to join A and B using the closest earlier date in B.</p> <p>There is one other condition I need to join on. So take the following code for example:</p> <pre><code> SELECT a.*, b.* FROM table_A a LEFT JOIN table_B b ON a.product = b.product AND a.date = b.date </code></pre> <p>If the dates were exactly the same, I could use the above code. However they're not, so I want the closest lesser date in table_B to use a match for table_A.</p> <p>Based on some solutions I saw, I tried the following:</p> <pre><code> SELECT a.*, b.* FROM table_A a LEFT JOIN table_B b ON a.product = b.product AND a.date = (SELECT MAX(date) FROM table_B WHERE date &lt;= a.date) </code></pre> <p>I thought this would work becuase I am searching for the max date in table_B that is still less than the date in table_A, however I returning nulls for the fields in table_B.</p> <p>Perhaps it has to do with the other condition which is <code>a.product = b.product</code>?</p>
[ { "answer_id": 74404795, "author": "p3consulting", "author_id": 4956336, "author_profile": "https://Stackoverflow.com/users/4956336", "pm_score": 0, "selected": false, "text": "SELECT product_id, dat_1, dat_2 FROM (\n SELECT t1.product_id, t1.dat as dat_1, t2.dat as dat_2,\n row_number() over(partition by t1.product_id order by t2.dat desc) as rn\n FROM table_1 t1\n LEFT JOIN table_2 t2 ON t1.product_id = t2.product_id AND t1.dat >= t2.dat\n)\nWHERE rn = 1 ;\n" }, { "answer_id": 74404830, "author": "BishNaboB", "author_id": 1872455, "author_profile": "https://Stackoverflow.com/users/1872455", "pm_score": 1, "selected": false, "text": "select a.*, b.*\nfrom table_A as [a]\n outer apply\n (\n select top 1 c.*\n from table_B as [c]\n where c.product = a.product\n and c.date <= a.date\n order by c.date desc\n ) as [b]\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13034428/" ]
74,404,562
<p>I'm a beginner trying to get this while loop so that the println table reads 2.00 15.000010, however it consistently stops on 1.9999993.</p> <pre><code>float weight = 60 ; float height01 = 1.20 ; float height02 = 2.00 ; while( height01 &lt; height02 ) { float BMI = ( weight / (height01 * height01) ) ; println( height01 + &quot; , &quot; + BMI ) ; height01 = height01 + 0.02 ; } </code></pre> <p>The output reads:</p> <pre><code>1.9999993 , 15.0000105 </code></pre> <p>I've tried using Math.round(height01) in order to convert the float to an int but this seems to do absolutely nothing.</p>
[ { "answer_id": 74404631, "author": "jtryon", "author_id": 17950927, "author_profile": "https://Stackoverflow.com/users/17950927", "pm_score": -1, "selected": false, "text": "while(height01 <= height02) {\n...\n}\n" }, { "answer_id": 74404941, "author": "Rogue", "author_id": 1786065, "author_profile": "https://Stackoverflow.com/users/1786065", "pm_score": 0, "selected": false, "text": "float weight = 60 ;\nint height01 = 120 ; //scaled by 100\nint height02 = 200 ; //scaled by 100 (think centimeters!)\n\nwhile( height01 < height02 ) {\n //100*100 in denominator, multiply numerator by 10000\n float BMI = ( (weight * 10000) / (height01 * height01) ) ;\n //scale our integer into a float (100F == (float) 100.0)\n println( (height01 / 100F) + \" , \" + BMI ) ;\n height01 = height01 + 2 ;\n}\n" }, { "answer_id": 74405713, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 0, "selected": false, "text": "float" }, { "answer_id": 74412124, "author": "Andrew", "author_id": 11844224, "author_profile": "https://Stackoverflow.com/users/11844224", "pm_score": 0, "selected": false, "text": "Mac_3.2.57$cat floatPlayground1.c\n#include <stdio.h>\n\nint main(void){\n float weight = 60;\n float height01 = 1.20;\n float height02 = 2.00;\n\n while(height01 <= height02){\n float BMI = (weight/(height01 * height01));\n printf(\"%10.2f, %10.6fi\\n\", height01, BMI);\n height01 = height01 + 0.02;\n }\n\n return(0);\n}\nMac_3.2.57$cc floatPlayground1.c\nMac_3.2.57$./a.out \n 1.20, 41.666664\n 1.22, 40.311741\n 1.24, 39.021851\n...\n 1.96, 15.618504\n 1.98, 15.304571\n 2.00, 15.000010\nMac_3.2.57$\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13830594/" ]
74,404,584
<pre><code>#include&lt;stdio.h&gt; int main() { char main[]=&quot;Structured Programming&quot;; char copy[30]; for (int i = 0; main[i] !='\0' ; i++) { copy[i]=main[i]; } printf(&quot;%s&quot;,copy); } </code></pre> <p>In the above problem this just should print <code>Structured Programming</code>, but I'm getting <code>Structured Programming a</code>, this happens on all ide's, but not on online compilers, online compilers are working fine, can anyone tell me the reason?</p>
[ { "answer_id": 74404725, "author": "cooleck", "author_id": 10371918, "author_profile": "https://Stackoverflow.com/users/10371918", "pm_score": 0, "selected": false, "text": "printf" }, { "answer_id": 74404840, "author": "Paul Lynch", "author_id": 18146287, "author_profile": "https://Stackoverflow.com/users/18146287", "pm_score": 1, "selected": false, "text": "copy" }, { "answer_id": 74405259, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 1, "selected": true, "text": "for (int i = 0; main[i] !='\\0' ; i++)\n{\n copy[i]=main[i];\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12545665/" ]
74,404,595
<p>I have a csv file with dates as characters in the following format: 202211, 202210, 202209 etc.</p> <p>I tried using</p> <pre><code>xdate&lt;- as.Date(&quot;202211&quot;, format=&quot;%Y%m&quot;) xdate </code></pre> <p>but the output I get is <code>NA</code></p> <p>This works if the format would be 20221111</p> <pre><code>xdate&lt;- as.Date(&quot;20221111&quot;, format=&quot;%Y%m%d&quot;) xdate </code></pre> <p><code>[1] &quot;2022-11-11&quot;</code></p> <p>Is there a way to solve this problem without adding a day to the dates?</p>
[ { "answer_id": 74404724, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 3, "selected": true, "text": "as.Date" }, { "answer_id": 74405016, "author": "Tom Clegg", "author_id": 13547776, "author_profile": "https://Stackoverflow.com/users/13547776", "pm_score": 2, "selected": false, "text": "library(lubridate)\nym(\"202211\")\n[1] \"2022-11-01\"\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20478946/" ]
74,404,604
<p>I need help with an assignment for school. I've only been doing SQL for 2 months and can't figure this out. My teacher gave me some hints about using self joins. The database has 3 more tables, but I don't think they are needed here.</p> <p>The assignment is to write a query that will help hotel staff find double bookings (same room, same date). I've made a test database that has a double booking to control the query.</p> <pre class="lang-sql prettyprint-override"><code>drop database if exists hoteltest; create database hoteltest; use hoteltest; create table Roomreservation( ResNr int not null, RoomNr int not null, FromDate date not null, ToDate date not null, primary key (ResNr, RoomNr, FromDate) ); insert into Roomreservation values (51, 102, '2008-12-05', '2008-12-07'), (51, 103, '2008-12-05', '2008-12-07'), (51, 104, '2008-12-05', '2008-12-09'), (52, 201, '2008-12-05', '2008-12-14'), (53, 102, '2008-12-04', '2008-12-10'); select * from Roomreservation; </code></pre> <p>Does anyone have a good and easy solution for this?</p> <p>Honestly, I'm kinda stuck, I've been trying different solutions with concat_ws and the dates but with no results.</p>
[ { "answer_id": 74404724, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 3, "selected": true, "text": "as.Date" }, { "answer_id": 74405016, "author": "Tom Clegg", "author_id": 13547776, "author_profile": "https://Stackoverflow.com/users/13547776", "pm_score": 2, "selected": false, "text": "library(lubridate)\nym(\"202211\")\n[1] \"2022-11-01\"\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20478970/" ]
74,404,613
<p>I'm new to React 18 and Suspense. Nearly all of my previous web development was done in asp.net mvc. I want to click a button on a form, pass the form input values to a web api HttpGet method with the [FromQuery] attribute, and render the return into a div.</p> <p>If I were doing this in asp.net mvc, I would wire up a button click event like so in javascript:</p> <pre><code>const btnSearch = document.getElementById('btnSearch'); btnSearch.addEventListener(&quot;click&quot;, function() { executeMySearch(); return false; }); </code></pre> <p>And in the executeMySearch() method I'd grab the form input values, send them to server, fetch some html from the server and plunk it into a div like so:</p> <pre><code>const searchresults = document.getElementById('searchresults'); let formData = new FormData(document.forms[0]); fetch('/Index?handler=MySearchMethod', { method: 'post', body: new URLSearchParams(formData), }).then(function (response) { return response.text(); }).then(function (html) { searchresults.innerHTML = html; </code></pre> <p>Of course in React the approach is completely different, I showed the code above only to demonstrate what I want to happen. I want the search to execute only when the search button is clicked. My problem is, I cannot figure out how to manage React state to make that happen. Currently, after the search button is clicked once, my search is executing every time the user changes the value of a form input. I understand why that is happening, but I can't figure out how to structure my components so that the search executes only when the search button is clicked.</p> <p>Server-side, my web api receives a form and returns a generic list, like so. This works fine:</p> <pre><code>[HttpGet(&quot;MySearchMethod&quot;)] public async Task&lt;List&lt;MySearchResult&gt;&gt; MySearchMethod([FromQuery]MySearchForm mySearchForm) { return await _myRepository.GetMySearchResults(mySearchForm); } </code></pre> <p>In my React app I have a search component. The component renders a form with the following elements:</p> <ul> <li>four selects, which contain the search criteria. These selects are wrapped in React components.</li> <li>a search button</li> <li>a component that renders the search results</li> </ul> <p>Each select input is a React component that contains a list of enums fetched from the web api. Each select is defined in the search component like so:</p> <pre><code>const MyEnums = lazy(() =&gt; import('./MyEnums')); </code></pre> <p>Each of these React components is tied to the React state when the search component is defined, like so:</p> <pre><code>const MySearchComponent = () =&gt; { const [myEnum, setMyEnum] = useState(0); function onChangeMyEnum(myEnumId : number){ setMyEnum(myEnumId); }... </code></pre> <p>and I tie my search button to React state like so:</p> <pre><code>const [isSearch, setIsSearch] = useState(false); </code></pre> <p>My search component returns a form with the search criteria and search button, and a div to contain the search results:</p> <pre><code> return ( &lt;&gt; &lt;form&gt; &lt;div&gt; &lt;ErrorBoundary FallbackComponent={MyErrorHandler}&gt; &lt;h2&gt;My Search Criteria Select&lt;/h2&gt; &lt;Suspense fallback={&lt;Spinner/&gt;}&gt; &lt;MyEnums onChange={onChangeMyEnum} /&gt; &lt;/Suspense&gt; &lt;/ErrorBoundary&gt; &lt;/div&gt; &lt;button className='btn btn-blue' onClick={(e) =&gt; { e.preventDefault(); setIsSearch(true); } }&gt;Search&lt;/button&gt; &lt;/form&gt; &lt;div&gt; { isSearch === true ? &lt;ErrorBoundary FallbackComponent={MyErrorHandler}&gt; &lt;Suspense fallback={&lt;Spinner/&gt;}&gt; &lt;MySearchResults myEnum={myEnum} [..other search criteria] /&gt; &lt;/Suspense&gt; &lt;/ErrorBoundary&gt; : &lt;span&gt;&amp;nbsp;&lt;/span&gt; } &lt;/div&gt; </code></pre> <p>Everything works fine. The problem is, after the first time the search button is clicked (which executes &quot;setIsSearch(true)&quot;), every time a user alters a selection in one of the form inputs, the search executes. I understand why. My &quot;isSearch&quot; variable remains true, so when the state is altered by the form input changing, and the component is re-rendered, the search happens again.</p> <p>I tried passing the &quot;setIsSearch&quot; method into the MySearchResults component, and calling setIsSearch(false) after the component rendered, but that of course does exactly what it is supposed to to. The React state changes, the component re-renders, it sees that &quot;isSearch&quot; is false, and it makes the search results disappear. When I click my search button I see the search results flicker briefly and then disappear, which is exactly what should happen.</p> <p>I also tried calling setIsSearch(false) every time a select changes, but of course this causes my search results to disappear, which is not desired.</p> <p>What am I missing? How do I structure this so that the search only occurs when I click the Search button?</p> <p>P.S. the web api call is made inside of the MySearchResults component when it renders. The MySearchResults component looks like this:</p> <pre><code>import React from 'react'; import { useQuery } from 'react-query'; import MySearchResult from './MySearchResult'; const fetchMySearchResults = async (myEnumId : number [...other criteria]) =&gt; { let url = `${process.env.REACT_APP_MY_API}/GetMySearchResults/?myEnumId=${myEnumId}&amp;[...other criterial]`; const response = await fetch(url); return response.json(); } const MySearchResults = (props : any) =&gt; { const {data} = useQuery(['myquery', props.myEnum,...other search criteria...] ,() =&gt; fetchMySearchResults(props.myEnun [...other search criteria]), { suspense:true }); return ( &lt;&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;My Column Header&lt;/th&gt; &lt;th&gt;...and so on&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; {data.map((mySearchResult: { ...and so on &lt;/tbody&gt; &lt;/table&gt; &lt;/&gt; ); }; export default MySearchResults; </code></pre>
[ { "answer_id": 74405346, "author": "Zaeem Khaliq", "author_id": 11660035, "author_profile": "https://Stackoverflow.com/users/11660035", "pm_score": 1, "selected": false, "text": "useQuery" }, { "answer_id": 74405589, "author": "Letincel", "author_id": 4735563, "author_profile": "https://Stackoverflow.com/users/4735563", "pm_score": 1, "selected": false, "text": "const [myEnum, setMyEnum] = useState(0);\nconst [searchEnum, setSearchEnum] = useState();\nsetIsSearch(true);\n\n function onChangeMyEnum(myEnumId : number){\n setMyEnum(myEnumId);\n }\n\n<Suspense fallback={<Spinner/>}>\n <MyEnums onChange={onChangeMyEnum} />\n</Suspense>\n\n<button className='btn btn-blue' onClick={(e) => {\n e.preventDefault();\n setSearchEnum(myEnum)\n setIsSearch(true);\n\n }\n }>Search</button>\n\n{\n isSearch === true ?\n <ErrorBoundary FallbackComponent={MyErrorHandler}>\n <Suspense fallback={<Spinner/>}>\n <MySearchResults myEnum={searchEnum} [..other search criteria] />\n </Suspense>\n </ErrorBoundary>\n : <span>&nbsp;</span>\n }\n" }, { "answer_id": 74408363, "author": "Tom Regan", "author_id": 303305, "author_profile": "https://Stackoverflow.com/users/303305", "pm_score": 1, "selected": true, "text": "const myEnum = useRef(0);\nfunction onChangeMyEnum(myEnumId : number){\n myEnum.current = myEnumId;\n}\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303305/" ]
74,404,615
<p>I am trying to write some stuff into the HTML document multiple times. It's the same lines of code I want to write out. Basically copy itself.</p> <pre><code> var a = &quot;asd&quot;; let added = document.createElement(&quot;div&quot;); let addedP = document.createElement(&quot;p&quot;) addedP.innerText = a; added.append(addedP); document.body.append(added); document.body.append(added); </code></pre> <p>I tried to do this, it wrote out &quot;asd&quot; on my page once, but I wanted it to do it twice.</p>
[ { "answer_id": 74404643, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": 2, "selected": false, "text": "append" }, { "answer_id": 74404926, "author": "SnNeposis", "author_id": 20347565, "author_profile": "https://Stackoverflow.com/users/20347565", "pm_score": 1, "selected": false, "text": "var a = \"asd\";\n\nlet id = 0;\n\nconst newDiv = () => {\n const x = document.createElement(\"div\");\n x.id = (id++).toString(); // sets its id and adds 1 to id simultaneously\n return x;\n}\n\nlet addedP = document.createElement(\"p\") // same thing can be done for a unique p as for the div\n\naddedP.innerText = a;\nlet added = addedP\nadded.append(newDiv()) // Can still append! (since a new element is returned)\ndocument.body.append(added);\ndocument.body.append(newDiv());\n" }, { "answer_id": 74405352, "author": "Dave Pritlove", "author_id": 2005666, "author_profile": "https://Stackoverflow.com/users/2005666", "pm_score": -1, "selected": true, "text": "element.cloneNode()" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20419896/" ]
74,404,616
<p>I am new to regex module and learning a simple case to extract key and values from a simple dictionary.</p> <p><strong>the dictionary can not contain nested dicts and any lists, but may have simple tuples</strong></p> <h1>MWE</h1> <pre class="lang-py prettyprint-override"><code>import re # note: the dictionary are simple and does NOT contains list, nested dicts, just these two example suffices for the regex matching. d = &quot;{'a':10,'b':True,'c':(5,'a')}&quot; # ['a', 10, 'b', True, 'c', (5,'a') ] d = &quot;{'c':(5,'a'), 'd': 'TX'}&quot; # ['c', (5,'a'), 'd', 'TX'] regexp = r&quot;(.*):(.*)&quot; # I am not sure how to repeat this pattern separated by , out = re.match(regexp,d).groups() out </code></pre>
[ { "answer_id": 74404823, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 3, "selected": true, "text": "ast.literal_eval" }, { "answer_id": 74405728, "author": "Swifty", "author_id": 20267366, "author_profile": "https://Stackoverflow.com/users/20267366", "pm_score": 1, "selected": false, "text": "d = \"{'c':(5,'a',1), 'd': 'TX', 1:(1,2,3)}\" \n\nd=d.replace(\"{\",\"\").replace(\"}\",\"\")\nindices = []\ninside = False\nfor i,l in enumerate(d):\n if inside:\n if l == \")\":\n inside = False\n continue\n continue\n if l == \"(\":\n inside = True\n continue\n if l in {\":\",\",\"}:\n indices.append(i)\nindices.append(len(d))\nparts = []\nstart = 0\nfor i in indices:\n parts.append(d[start:i].strip())\n start = i+1\n\nparts\n# [\"'c'\", \"(5,'a',1)\", \"'d'\", \"'TX'\", '1', '(1,2,3)']\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19853940/" ]
74,404,619
<p>I have a very large database that looks like this. For cntext, the <code>data</code> appartains to different companies with their related CEOs (<code>ID</code>) and the different years each CEO was in charge</p> <pre><code>ID &lt;- c(1,1,1,1,1,1,3,3,3,5,5,4,4,4,4,4,4,4) C &lt;- c('a','a','a','a','a','a','b','b','b','b','b','c','c','c','c','c','c','c') fyear &lt;- c(2000, 2001, 2002,2003,2004,2005,2000, 2001,2002,2003,2004,2000, 2001, 2002,2003,2004,2005,2006) data &lt;- c(30,50,22,3,6,11,5,3,7,6,9,31,5,6,7,44,33,2) df1 &lt;- data.frame(ID,C,fyear, data) ID C fyear data 1 a 2000 30 1 a 2001 50 1 a 2002 22 1 a 2003 3 1 a 2004 6 1 a 2005 11 3 b 2000 5 3 b 2001 3 3 b 2002 7 5 b 2003 6 5 b 2004 9 4 c 2000 31 4 c 2001 5 4 c 2002 6 4 c 2003 7 4 c 2004 44 4 c 2005 33 4 c 2006 2 </code></pre> <p>I need to build a code that allows me to sum up the previous 5 and 3 <code>data</code> related to each <code>ID</code> for every year. So t-3 and t-5 for each year. The result is something like this.</p> <pre><code>ID C fyear data data3data5 1 a 2000 30 NA NA 1 a 2001 50 NA NA 1 a 2002 22 102 NA 1 a 2003 3 75 NA 1 a 2004 6 31 111 1 a 2005 11 20 86 3 b 2000 5 NA NA 3 b 2001 3 NA NA 3 b 2002 7 15 NA 5 b 2003 6 NA NA 5 b 2004 9 NA NA 4 c 2000 31 NA NA 4 c 2001 5 NA NA 4 c 2002 6 42 NA 4 c 2003 7 18 NA 4 c 2004 44 57 93 4 c 2005 33 84 95 4 c 2006 2 79 92 </code></pre> <p>I have different columns of data for which I need to perform this operation, so if somebody also knows how I can do that and create a <code>data3</code> and <code>data5</code> column also for the other columns of data that I have that would be amazing. But even just being able to do the summation that I need is great! Thanks a lot. I hav looked around but don't seem to find any similar cses that satisfy my need</p>
[ { "answer_id": 74405747, "author": "Limey", "author_id": 13434871, "author_profile": "https://Stackoverflow.com/users/13434871", "pm_score": 0, "selected": false, "text": "df1 %>% \n arrange(C, ID, fyear) %>% \n group_by(C, ID) %>% \n mutate(\n fyear3=rowSums(list(sapply(1:3, function(x) lag(data, x)))[[1]]),\n fyear5=rowSums(list(sapply(1:5, function(x) lag(data, x)))[[1]])\n ) %>%\n ungroup()\n# A tibble: 18 × 6\n ID C fyear data fyear3 fyear5\n <dbl> <chr> <dbl> <dbl> <dbl> <dbl>\n 1 1 a 2000 30 NA NA\n 2 1 a 2001 50 NA NA\n 3 1 a 2002 22 NA NA\n 4 1 a 2003 3 102 NA\n 5 1 a 2004 6 75 NA\n 6 1 a 2005 11 31 111\n 7 3 b 2000 5 NA NA\n 8 3 b 2001 3 NA NA\n 9 3 b 2002 7 NA NA\n10 5 b 2003 6 NA NA\n11 5 b 2004 9 NA NA\n12 4 c 2000 31 NA NA\n13 4 c 2001 5 NA NA\n14 4 c 2002 6 NA NA\n15 4 c 2003 7 42 NA\n16 4 c 2004 44 18 NA\n17 4 c 2005 33 57 93\n18 4 c 2006 2 84 95\n" }, { "answer_id": 74432828, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 0, "selected": false, "text": "frollsum" }, { "answer_id": 74437265, "author": "G. Grothendieck", "author_id": 516548, "author_profile": "https://Stackoverflow.com/users/516548", "pm_score": 2, "selected": true, "text": "library(dplyr, exclude = c(\"filter\", \"lag\"))\nlibrary(zoo)\n\ndf1 %>%\n group_by(ID, C) %>%\n mutate(data3 = rollsumr(data, 3, fill = NA),\n data5 = rollsumr(data, 5, fill = NA)) %>%\n ungroup\n## # A tibble: 18 x 6\n## ID C fyear data data3 data5\n## <dbl> <chr> <dbl> <dbl> <dbl> <dbl>\n## 1 1 a 2000 30 NA NA\n## 2 1 a 2001 50 NA NA\n## 3 1 a 2002 22 102 NA\n## 4 1 a 2003 3 75 NA\n## 5 1 a 2004 6 31 111\n...snip...\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19335534/" ]
74,404,627
<p>I have Invoices with many Invoice Line Items. Invoice line items point to a specific item. When creating or updating an Invoice, I'd like to validate that there is not more than 1 invoice line item with the same Item (Item ID). I am using accepts nested attributes and nested forms.</p> <p>I know about <code>validates_uniqueness_of item_id: {scope: invoice_id}</code></p> <p>However, I cannot for the life of me get it to work properly. Here is my code:</p> <p><strong>Invoice Line Item</strong></p> <pre><code>belongs_to :item validates_uniqueness_of :item_id, scope: :invoice_id </code></pre> <p><strong>Invoice</strong></p> <pre><code>has_many :invoice_line_items, dependent: :destroy accepts_nested_attributes_for :invoice_line_items, allow_destroy: true </code></pre> <p><strong>Invoice Controller</strong></p> <pre><code> // strong params params.require(:invoice).permit( :id, :description, :company_id, invoice_line_items_attributes: [ :id, :invoice_id, :item_id, :quantity, :_destroy ] ) // ... // create action def create @invoice = Invoice.new(invoice_params) respond_to do |format| if @invoice.save format.html { redirect_to @invoice } else format.html { render action: 'new' } end end end </code></pre> <p>The controller code is pretty standard (what rails scaffold creates).</p> <p><strong>UPDATE</strong> - NOTE that after more diagnosing, I find that on create it always lets me create multiple line items with the same item when first creating an invoice and when editing an invoice without modifying the line items, but NOT when editing an invoice and trying to add another line item with the same item or modifying an attribute of one of the line items. It seems to be something I'm not understanding with how rails handles nested validations.</p> <p><strong>UPDATE 2</strong> If I add <code>validates_associated :invoice_line_items</code>, it <em>only</em> resolves the problem when editing an already created invoice without modifying attributes. It seems to force validation check regardless of what was modified. It presents an issues when using _destroy, however.</p> <p><strong>UPDATE 3</strong> Added controller code.</p> <p><strong>Question</strong> - how can I validate an attribute on a models has many records using nested form and accepts nested attributes?</p>
[ { "answer_id": 74405747, "author": "Limey", "author_id": 13434871, "author_profile": "https://Stackoverflow.com/users/13434871", "pm_score": 0, "selected": false, "text": "df1 %>% \n arrange(C, ID, fyear) %>% \n group_by(C, ID) %>% \n mutate(\n fyear3=rowSums(list(sapply(1:3, function(x) lag(data, x)))[[1]]),\n fyear5=rowSums(list(sapply(1:5, function(x) lag(data, x)))[[1]])\n ) %>%\n ungroup()\n# A tibble: 18 × 6\n ID C fyear data fyear3 fyear5\n <dbl> <chr> <dbl> <dbl> <dbl> <dbl>\n 1 1 a 2000 30 NA NA\n 2 1 a 2001 50 NA NA\n 3 1 a 2002 22 NA NA\n 4 1 a 2003 3 102 NA\n 5 1 a 2004 6 75 NA\n 6 1 a 2005 11 31 111\n 7 3 b 2000 5 NA NA\n 8 3 b 2001 3 NA NA\n 9 3 b 2002 7 NA NA\n10 5 b 2003 6 NA NA\n11 5 b 2004 9 NA NA\n12 4 c 2000 31 NA NA\n13 4 c 2001 5 NA NA\n14 4 c 2002 6 NA NA\n15 4 c 2003 7 42 NA\n16 4 c 2004 44 18 NA\n17 4 c 2005 33 57 93\n18 4 c 2006 2 84 95\n" }, { "answer_id": 74432828, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 0, "selected": false, "text": "frollsum" }, { "answer_id": 74437265, "author": "G. Grothendieck", "author_id": 516548, "author_profile": "https://Stackoverflow.com/users/516548", "pm_score": 2, "selected": true, "text": "library(dplyr, exclude = c(\"filter\", \"lag\"))\nlibrary(zoo)\n\ndf1 %>%\n group_by(ID, C) %>%\n mutate(data3 = rollsumr(data, 3, fill = NA),\n data5 = rollsumr(data, 5, fill = NA)) %>%\n ungroup\n## # A tibble: 18 x 6\n## ID C fyear data data3 data5\n## <dbl> <chr> <dbl> <dbl> <dbl> <dbl>\n## 1 1 a 2000 30 NA NA\n## 2 1 a 2001 50 NA NA\n## 3 1 a 2002 22 102 NA\n## 4 1 a 2003 3 75 NA\n## 5 1 a 2004 6 31 111\n...snip...\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74404627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3390279/" ]