qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,510,159
<p>I am having a text file in which some binary numbers are there. I want to count number of occurrence of some digits/characters using pattern, and I want to sort it in descending order (till this point code working fine. but I want result should show only more than 7 characters. it means i can change in my selection pattern = r&quot;(0+1+0+1+0+1+)&quot; {&lt;7}</p> <pre><code>import re from collections import Counter pattern = r&quot;0+1+0+1+0+1+&quot; test_str = '0101010110110110110110110101010111011101110111101111010101111010111010101111011010101011011011011011011011' cnt = Counter(re.findall(pattern, test_str)) print(cnt.most_common()) # result [('011011011', 2), ('010101', 1), ('0111011101111', 1), ('010111101', 1), ('0111101101', 1)] </code></pre> <p>result should be display only more than 8 character it no supposed to show ('010101', 1)</p>
[ { "answer_id": 74510236, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 1, "selected": true, "text": "Counter from collections import Counter\n\ncnt = Counter(re.findall(pattern, test_str))\nprint(cnt.most_common()) # [('110110', 3), ('110100', 2), ('101110', 2)]\n" }, { "answer_id": 74510246, "author": "MDavidson", "author_id": 20556118, "author_profile": "https://Stackoverflow.com/users/20556118", "pm_score": -1, "selected": false, "text": "print(max(cnt.items()))\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17500419/" ]
74,510,168
<p>I have a Photo Share web app and I am trying to add comments in photos. I can't spot any mistakes. Maybe in the controller class in index function is the problem. There is an undefined method error when I try to show-post comments below the photo. Error in HAML code.</p> <pre><code>Error: - if @photo_comments.any? </code></pre> <p>Controller:</p> <pre><code>class CommentsController &lt; ApplicationController def index @photo_comments = Comment.where(photo_id: =&gt; photo_id) end def create @comment = Comment.create(user_id: params[:user_id], photo_id: params[:photo_id], text: params[:comment][:text]) flash[:notice] = &quot;Successfully added a comment&quot; redirect_to :back end private def comment_params params.require(:comment).permit(:user_id, :photo_id, :text) end end </code></pre> <p>Model:</p> <pre><code>class Comment &lt; ActiveRecord::Base belongs_to :user belongs_to :photo end </code></pre> <p>Database:</p> <pre><code>class CreateComments &lt; ActiveRecord::Migration def change create_table :comments do |t| t.integer :user_id t.integer :photo_id t.string :text t.timestamps end end end </code></pre> <p>View:</p> <pre><code>%p Comments - if @photo_comments.any? - @photo_comments.each do |comment| .bold-text= &quot;#{comment.user.email}: &quot; .normal-text= comment.text %br - else .text No comments for this photo yet! %br %br %p = form_for Comment.new(), :url =&gt; user_photo_comments_path do |form| = form.label :text, 'Add a Comment' %br = form.text_area :text %br = form.submit 'Post' </code></pre> <p>Routes:</p> <pre><code>Rails.application.routes.draw do get '/' =&gt; 'home#index' resources :users do resources :photos do resources :comments end resources :follows end resources :tags, only: [:create, :destroy] get '/log-in' =&gt; &quot;sessions#new&quot; post '/log-in' =&gt; &quot;sessions#create&quot; get '/log-out' =&gt; &quot;sessions#destroy&quot;, as: :log_out end </code></pre>
[ { "answer_id": 74510198, "author": "spickermann", "author_id": 2483313, "author_profile": "https://Stackoverflow.com/users/2483313", "pm_score": 0, "selected": false, "text": "- if @photo_comments.nil?\n - @photo_comments.each do |comment|\n @photo_comments nil undefined method 'each' for nil:NilClass - unless @photo_comments.nil?\n - @photo_comments.each do |comment|\n" }, { "answer_id": 74510274, "author": "markets", "author_id": 3033649, "author_profile": "https://Stackoverflow.com/users/3033649", "pm_score": 2, "selected": true, "text": "@photo_comments = Comment.where(photo_id: => photo_id)\n photo_id: photo_id :photo_id => photo_id photo_id params[:photo_id]" }, { "answer_id": 74512716, "author": "Orce", "author_id": 20365430, "author_profile": "https://Stackoverflow.com/users/20365430", "pm_score": 1, "selected": false, "text": "@photo_comments = Comment.where(photo_id: => photo_id)\n photo_id @photo_comments = Comment.where(photo_id: params[:photo_id])\n undefined_method nil @photo_comments" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11353686/" ]
74,510,180
<p>Using visual studio 2022 with Xamarin I am following the steps to prepare and reduce the size of my app for publishing</p> <p><a href="https://docs.microsoft.com/en-us/xamarin/android/deploy-test/release-prep/proguard" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/xamarin/android/deploy-test/release-prep/proguard</a></p> <p>So selecting ProGuard from Code Shrinker dropdown When I rebuild the app, I get the following error:</p> <p><em><strong>&quot;Using ProGuard with the D8 DEX compiler is no longer supported. Please set the code shrinker to 'r8' in the Visual Studio project property pages or edit the project file in a text editor and set the 'AndroidLinkTool' MSBuild property to 'r8'.&quot;</strong></em></p> <p>Seeing this error <em><strong>&quot;Using ProGuard with the D8 DEX compiler is no longer supported&quot;</strong></em> I tried to find another option but in Dex Compiler dropdown there is no other option rather than d8 and dex. If I set the dex compiler to dx, I get the following:</p> <p><em><strong>&quot;Using the DX DEX Compiler is not supported. Please set the DEX compiler to 'd8' in the Visual Studio project property pages or edit the project file in a text editor and set the 'AndroidDexTool' MSBuild property to 'd8'.&quot;</strong></em></p> <p>So now my question is how do I enable ProGuard Shrinker option in my app. I am using visual studio 2022 and android version is 13.0</p>
[ { "answer_id": 74510198, "author": "spickermann", "author_id": 2483313, "author_profile": "https://Stackoverflow.com/users/2483313", "pm_score": 0, "selected": false, "text": "- if @photo_comments.nil?\n - @photo_comments.each do |comment|\n @photo_comments nil undefined method 'each' for nil:NilClass - unless @photo_comments.nil?\n - @photo_comments.each do |comment|\n" }, { "answer_id": 74510274, "author": "markets", "author_id": 3033649, "author_profile": "https://Stackoverflow.com/users/3033649", "pm_score": 2, "selected": true, "text": "@photo_comments = Comment.where(photo_id: => photo_id)\n photo_id: photo_id :photo_id => photo_id photo_id params[:photo_id]" }, { "answer_id": 74512716, "author": "Orce", "author_id": 20365430, "author_profile": "https://Stackoverflow.com/users/20365430", "pm_score": 1, "selected": false, "text": "@photo_comments = Comment.where(photo_id: => photo_id)\n photo_id @photo_comments = Comment.where(photo_id: params[:photo_id])\n undefined_method nil @photo_comments" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16753008/" ]
74,510,237
<p>I'm trying to apply the same rule to different columns, which will fill the cell with the color green if it is empty.</p> <p>I'm getting the rule through recording a Macro, but cannot figure out a successful way of removing the reference to range B2 below.</p> <p>I would like to have it as a rule I can apply to multiple selected columns.</p> <p>Is there anything I can substitute in?</p> <pre><code>Public Sub FillGreenIfCellNotEmpty() selection.FormatConditions.Add Type:=xlExpression, Formula1:= _ &quot;=LEN(TRIM(B2))&gt;0&quot; selection.FormatConditions(selection.FormatConditions.count).SetFirstPriority With selection.FormatConditions(1).Interior .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorAccent6 .TintAndShade = 0 End With selection.FormatConditions(1).StopIfTrue = False End sub </code></pre> <p>I have tried substituting &quot;cells(1,1)&quot; instead of B2 to reference the first cell of the selection and also substituting &quot;selection&quot;.</p> <p>Currently, I don't fully understand how rules work with instant updating. I would have thought the formula would be more along the lines of if not isempty(selection) rather than LEN() and TRIM()</p>
[ { "answer_id": 74510565, "author": "Red Hare", "author_id": 19618751, "author_profile": "https://Stackoverflow.com/users/19618751", "pm_score": 2, "selected": true, "text": "Option Explicit\n\nPublic Sub FillGreenIfCellNotEmpty()\nDim x As String\nx = Selection.Address(0, 0) \n\n Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _\n \"=LEN(TRIM(\" & x & \" ))>0\"\n Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority\n With Selection.FormatConditions(1).Interior\n .PatternColorIndex = xlAutomatic\n .ThemeColor = xlThemeColorAccent6\n .TintAndShade = 0\n End With\n Selection.FormatConditions(1).StopIfTrue = False\n\nEnd Sub\n" }, { "answer_id": 74514512, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 0, "selected": false, "text": "Selection.FormatConditions.Add _\n Type:=xlCellValue, _\n Operator:=xlNotEqual, _\n Formula1:=\"=\"\"\"\"\"\n Selection.FormatConditions.Add _\n Type:=xlCellValue, _\n Operator:=xlEqual, _\n Formula1:=\"=\"\"\"\"\"\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7107774/" ]
74,510,269
<p>The <code>Safe</code> extension method can never return null, but the compiler seemingly isn't able to detect that. I think I read something about this being an intentional design decision for strings, but don't recall when or where. Can anyone explain how to fix this (i.e., help the compiler along) or explain why it's intentionally this way?</p> <pre class="lang-cs prettyprint-override"><code>Foo? foo = null; Bar bar = new(); // CS8601: Possible null reference assignment. bar.NoNullsHere = foo?.Text().Safe(); // No error with the trailing exclamation point bar.NoNullsHere = foo?.Text().Safe()!; public static class StringExtensionMethods { public static string Safe(this string? obj) =&gt; obj is null ? string.Empty : obj!; } public class Foo { public string? Text() =&gt; &quot;has a value, but could be null or empty&quot;; } public class Bar { public string NoNullsHere { get; set; } = string.Empty; } </code></pre> <p>Edit: the &quot;right associative&quot; answer provided by @sweeper is correct - the <code>Safe</code> method will not get invoked. Given that, is it possible to do what I set out to accomplish? I really prefer the syntax and intellisense support. Also, my actual implementation accepts other arguments to the <code>Safe</code> method to optionally do things like surround the resulting string with some token (e.g., double quote).</p> <pre class="lang-cs prettyprint-override"><code>bar.NoNullsHere = foo?.Text().Safe(); </code></pre> <p>instead of either of these</p> <pre class="lang-cs prettyprint-override"><code>bar.NoNullsHere = StringExtensionMethods.Safe(foo?.Text()); bar.NoNullsHere = foo?.Text() ?? string.Empty; </code></pre> <p>Edit 2: forgot to mention that @sweeper does provide a work around. The required parentheses are a little annoying, but better than the alternatives. Thanks all!</p> <pre class="lang-cs prettyprint-override"><code>bar.NoNullsHere = (foo?.Text()).Safe(); </code></pre>
[ { "answer_id": 74510311, "author": "Etienne de Martel", "author_id": 71141, "author_profile": "https://Stackoverflow.com/users/71141", "pm_score": 1, "selected": false, "text": "Safe() foo?.Text().Safe();\n foo ?. foo Safe() bar.NoNullsHere = foo?.Text() ?? string.Empty;\n foo Text()" }, { "answer_id": 74510338, "author": "Orkad", "author_id": 8656043, "author_profile": "https://Stackoverflow.com/users/8656043", "pm_score": 2, "selected": false, "text": " bar.NoNullsHere = foo?.Text().Safe();\n\n // consider it will work like below\n if (foo != null)\n {\n bar.NoNullsHere = foo.Text().Safe();\n }else\n {\n bar.NoNullsHere = null;\n }\n bar.NoNullsHere" }, { "answer_id": 74510389, "author": "Sweeper", "author_id": 5133585, "author_profile": "https://Stackoverflow.com/users/5133585", "pm_score": 3, "selected": true, "text": "?. foo?.Text().Safe();\n Text().Safe() foo foo null // not valid syntax, but IMO a good mental image\nfoo?.(Text().Safe());\n ? someNullableThing?.Property1.Property2.Property3\n ?. someNullableThing?.Property1 ? PropertyN bar.NoNullsHere = (foo?.Text()).Safe();\n foo.Safe() foo" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15679808/" ]
74,510,270
<p>I am coding something using the YouTubeV3 API to upload a video. I was going through the demo script Google gives, but don't fully understand this piece of code. It uses <code>argparser.add_argument()</code> to add information like the file or title through the command line, however I want to add this info in the script itself. How do I do this?</p> <p>I have tried setting the value by using the &quot;default&quot; attribute, however this doesn't work in a loop, as you end up adding it twice. I cant find anything about this online.</p> <p>Here is a basic verison of the code with print statements to show what the values are:</p> <pre><code>argparser.add_argument(&quot;--file&quot;, default=&quot;video.mp4&quot;) argparser.add_argument(&quot;--title&quot;, default=&quot;hello world&quot;) print(f&quot;argparser:\n{argparser}\n&quot;) print(f&quot;argparser.parse_args():\n{argparser.parse_args()}\n&quot;) args = argparser.parse_args() print(f&quot;args:\n{args}\n&quot;) </code></pre> <p>Here is the output (I change the value of &quot;auth_host_port&quot;, dont think I needed to censor it but better safe then sorry):</p> <pre><code>argparser: ArgumentParser(prog='script.py', usage=None, description=None, formatter_class=&lt;class 'argparse.HelpFormatter'&gt;, conflict_handler='error', add_help=False) argparser.parse_args(): Namespace(auth_host_name='localhost', noauth_local_webserver=False, auth_host_port=[0000, 0000], logging_level='ERROR', file='video.mp4', title='hello world') args: Namespace(auth_host_name='localhost', noauth_local_webserver=False, auth_host_port=[0000, 0000], logging_level='ERROR', file='video.mp4', title='hello world') </code></pre>
[ { "answer_id": 74510340, "author": "Nave Twizer", "author_id": 17254732, "author_profile": "https://Stackoverflow.com/users/17254732", "pm_score": 0, "selected": false, "text": "argparse print(f\"Video title: {argparser.title}\")\n# This stores the \"--title\" argument you pass in through the command line.\n# If you do not pass a title argument, it takes the default value.\n# In your case, it will be \"hello world\", as you specified in the second line\n title = \"My video title\"\nprint(f\"Video title: {title}\")\n" }, { "answer_id": 74510435, "author": "qkz9ro", "author_id": 20556193, "author_profile": "https://Stackoverflow.com/users/20556193", "pm_score": 1, "selected": false, "text": "args.[varaible] = [value] args.file = \"video.mp4\" args.title = \"hello world\" args.[varaible] = [value]" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20556193/" ]
74,510,287
<p>given data and my own DataFrame class which takes the dict as a parameter like this.</p> <pre><code>frame = { &quot;a&quot;: [&quot;X4E&quot;, &quot;T3B&quot;, &quot;F8D&quot;, &quot;C7X&quot;], &quot;b&quot;: [7.0, 3.5, 8.0, 6.0], &quot;c&quot;: [5, 3, 1, 10], &quot;d&quot;: [False, False, True, False] } df = DataFrame(frame) </code></pre> <p>How would one override the <code>__getitem__</code> method for dicts to allow actions such as</p> <pre><code>res = df[(df[&quot;b&quot;] + 5.0 &gt; 10.0)][&quot;a&quot;] </code></pre> <p>which would return all the cases where b + 5.0 is greater than 10.0. Like a list/series of booleans. This will eventually extend to something like this</p> <pre><code>res = df[(df[&quot;b&quot;] + 5.0 &gt; 10.0) &amp; (df[&quot;c&quot;] &gt; 3) &amp; ~df[&quot;d&quot;]][&quot;a&quot;] </code></pre> <p>I am not sure how to start with this. I learnt about the <code>__getitem__</code> but have no idea how to use this to add a value to values in a dict and perform element wise math ops. This is similar to pandas data frames but not sure how to implement this myself</p>
[ { "answer_id": 74510340, "author": "Nave Twizer", "author_id": 17254732, "author_profile": "https://Stackoverflow.com/users/17254732", "pm_score": 0, "selected": false, "text": "argparse print(f\"Video title: {argparser.title}\")\n# This stores the \"--title\" argument you pass in through the command line.\n# If you do not pass a title argument, it takes the default value.\n# In your case, it will be \"hello world\", as you specified in the second line\n title = \"My video title\"\nprint(f\"Video title: {title}\")\n" }, { "answer_id": 74510435, "author": "qkz9ro", "author_id": 20556193, "author_profile": "https://Stackoverflow.com/users/20556193", "pm_score": 1, "selected": false, "text": "args.[varaible] = [value] args.file = \"video.mp4\" args.title = \"hello world\" args.[varaible] = [value]" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11864678/" ]
74,510,288
<pre><code>double _sqrt(double n) { double sqrt = 0, c = 0, prec = 1; for (;; sqrt += prec) //increments sqrt per precision { c = sqrt * sqrt; if (c == n) { return sqrt; } if (c &gt; n) // if square is greater then.. { sqrt -= prec; // decrement squareroot by previous precision prec *= 0.1; // increase precision eg. 1, 0.1, 0.01, 0.001 .....INF } } } </code></pre> <p>This is the square root function that I've done. It works for some numbers but for others its just blank, doesn't return a thing. Where am I getting this wrong?</p>
[ { "answer_id": 74511189, "author": "UniformSoup", "author_id": 13357306, "author_profile": "https://Stackoverflow.com/users/13357306", "pm_score": 3, "selected": true, "text": "increment double _sqrt(const double& n)\n{\n const double precision = 0.000001;\n double increment = 1.0, sqrt = 0.0;\n\n while (true)\n {\n if (increment <= precision)\n break;\n else if (sqrt * sqrt > n)\n {\n sqrt -= increment;\n increment *= 0.1;\n }\n else \n sqrt += increment;\n }\n\n return sqrt;\n}\n std::sqrt double _sqrt(const double& n)\n{\n const double precision = 0.00001;\n double sqrt, x = n;\n\n while (true)\n {\n sqrt = 0.5 * (x + (n / x));\n\n if (std::abs(sqrt - x) < precision)\n break;\n\n x = sqrt;\n }\n\n return sqrt;\n}\n" }, { "answer_id": 74515926, "author": "Spektre", "author_id": 2521214, "author_profile": "https://Stackoverflow.com/users/2521214", "pm_score": 2, "selected": false, "text": "prec = 1; sqrt += prec sqrt sqrt += prec sqrt prec prec *= 0.1; |x|>1 sqrt(x) int(x) prec y = log2(|x|)\nprec = y*0.1\n log2 log2 y = 2^((exponent_extracted_from_x>>1)+1)\n (|x|<=1) prec = 0.5 sqrt ...\nfor (sqrt0=sqrt-prec; sqrt!=sqrt0; sqrt0=sqrt,sqrt+=prec)\n {\n ... your original code ...\n }\nreturn sqrt;\n}\n x<0" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16743990/" ]
74,510,331
<p>When writing to a file in python, you should typically use the using structure in order to have the file closed after writing, like so:</p> <pre><code>with open(&quot;myfile.txt&quot;, &quot;a&quot;) as file1: file1.write(&quot;Hello \n&quot;) </code></pre> <p>But if I, during the execution of my script, wants to write to the same file from different places in the code, I might be tempted to encapsulate the above structure in some kind of method like so:</p> <pre><code>def write_to_file(self, string_to_write): with open(self.myfile_path, &quot;w&quot;) as file1: file1.write(f&quot;{string_to_write}\n&quot;) </code></pre> <p>The above would likely give me a pretty bad performance hit since the file is opened every time I call the method.</p> <p>The alternative that I can see is opening the file early in the program and having a file.close() call in some <em>finally</em> clause somewhere and hope for the best. But I understand this to be associated with some risk.</p> <p>So given the above, how should one approach this task in a pythonic as well as a performant way?</p>
[ { "answer_id": 74510447, "author": "scotscotmcc", "author_id": 15804190, "author_profile": "https://Stackoverflow.com/users/15804190", "pm_score": 2, "selected": false, "text": "with def main():\n with open('file.txt','w') as file:\n my_func_1()\n my_func_2(file)\n my_func_3\n my_func_4(file)\n ...\n\ndef my_func_1():\n ...\n\ndef my_func_2(file):\n ...\n file.write('thing to write')\n ...\n\ndef my_func_3():\n ...\n\ndef my_func_4(file):\n ...\n file.write('thing to write')\n ...\n" }, { "answer_id": 74606169, "author": "Fontanka16", "author_id": 108390, "author_profile": "https://Stackoverflow.com/users/108390", "pm_score": 0, "selected": false, "text": "import json\nimport logging\nimport os\nfrom pathlib import Path\nfrom typing import List\n\n\nclass MyWriter:\n\n __instance = None\n __inited = False\n\n def __new__(cls, path_to_file: Path) -> \"MyWriter\":\n if cls.__instance is None:\n cls.__instance = super().__new__(cls)\n return cls.__instance\n\n def __init__(self, path_to_file: Path) -> None:\n if type(self).__inited:\n return\n self.cache: List[str] = []\n self.path_to_file: Path = path_to_file\n if self.path_to_file.is_file():\n os.remove(self.path_to_file)\n type(self).__inited = True\n\n def write(self, string_to_write: str, flush=False):\n try:\n if string_to_write:\n self.cache.append(f\"{string_to_write)}\\n\")\n if len(self.cache) > 1000 or flush:\n with open(self.path_to_file, \"a\") as my_file:\n extradata_file.writelines(self.cache)\n self.cache = []\n logging.debug(\"My Writer flushing the cache\")\n except Exception as ee:\n error_message = \"Something went wrong in My Writer\"\n logging.error(error_message)\n raise ee\n\n def flush(self):\n self.write(\"\", True)\n" }, { "answer_id": 74649385, "author": "Kelly Bundy", "author_id": 12671057, "author_profile": "https://Stackoverflow.com/users/12671057", "pm_score": 1, "selected": false, "text": "with with open .close() with with def printer(filename):\n with open(filename, 'w') as f:\n while True:\n print((yield), file=f)\n\n# Demo usage\np = printer('test.txt')\nnext(p)\np.send('foo')\np.send('bar')\np.close()\n\n# Check the resulting file\nwith open('test.txt') as f:\n print(repr(f.read()))\n 'foo\\nbar\\n'\n open close" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/108390/" ]
74,510,343
<p>I am new to tkinter and encounter this strange behavior with the images. Please pay attention to the *.mainloop() in the code below.</p> <pre><code> import tkinter as tk from tkinter import ttk from PIL import Image, ImageTk class BaseWindow(tk.Tk): def __init__(self): super(BaseWindow, self).__init__() self.geometry(&quot;800x700&quot;) self.title(&quot;test title&quot;) frame = ttk.Frame(self) frame.pack() ttk.Label(frame, text=&quot;test label&quot;).pack() img = ImageTk.PhotoImage(Image.open(&quot;res/male_avatar.png&quot;).resize( (200, 200))) ttk.Label(frame, image=img).pack() frame_parent = ttk.Frame(self) frame_parent.pack() ParentWindow(frame_parent, self) # self.mainloop() class ParentWindow(ttk.Frame): def __init__(self, parent, app): super(ParentWindow, self).__init__(parent) self.pack() ttk.Label(self, text=&quot;parent label test&quot;).pack() img = ImageTk.PhotoImage(Image.open(&quot;res/male_avatar.png&quot;).resize( (200, 200))) ttk.Label(self, image=img).pack() ttk.Label(self, text=&quot;test label&quot;).pack() frame_child = ttk.Frame(self) frame_child.pack() ChildWindow(frame_child, app) # app.mainloop() class ChildWindow(ttk.Frame): def __init__(self, parent, app): super(ChildWindow, self).__init__(parent) self.pack() ttk.Label(self, text=&quot;child label test&quot;).pack() img = ImageTk.PhotoImage(Image.open(&quot;res/male_avatar.png&quot;).resize( (200, 200))) ttk.Label(self, image=img).pack() ttk.Label(self, text=&quot;test label&quot;).pack() # app.mainloop() if __name__ == '__main__': # BaseWindow().mainloop() BaseWindow() </code></pre> <p>There are three classes, but the image is created by each class is shown only if the mainloop() is called in the respective class.</p> <p>All the other widgets work just fine regardless of where I call the mainloop() for instance the Label() widget as in example code below.</p> <p>Only the images do not display if I don't call the mainloop() in the proper way.</p> <p><strong>Explaination</strong></p> <p>1.) if <strong>name</strong> == .............. in this block if I call the <strong>BaseWindow().mainloop()</strong> then everything works fine, all the widgets are displayed, but the images are not displayed. Images created in all the classes are not shown.</p> <p>2.) class BaseWindow()....... if the <strong>self.mainloop()</strong> is called here then, one image i.e. image created in this class is shown/displayed and other images are not displayed.</p> <p>3.) class ParentWindow().......... if the <strong>app.mainloop()</strong> is called here then, two images are displayed, i.e. the image created in the BaseWindow class and ParentWindow class are displayed.</p> <p>4.) similarly the image in the ChildWindow() class is only displayed if the app.mainloop() is called in this class.</p> <p>So, in order to display all the images, I need to call the mainloop in the last class, but in this way, I need to pass the app object to all the child classes. <strong>Isn't there a way to call mainloop only once in the app and get everything work.?</strong> How do I display the images by calling mainloop() only in the BaseWindow() class...?</p>
[ { "answer_id": 74510447, "author": "scotscotmcc", "author_id": 15804190, "author_profile": "https://Stackoverflow.com/users/15804190", "pm_score": 2, "selected": false, "text": "with def main():\n with open('file.txt','w') as file:\n my_func_1()\n my_func_2(file)\n my_func_3\n my_func_4(file)\n ...\n\ndef my_func_1():\n ...\n\ndef my_func_2(file):\n ...\n file.write('thing to write')\n ...\n\ndef my_func_3():\n ...\n\ndef my_func_4(file):\n ...\n file.write('thing to write')\n ...\n" }, { "answer_id": 74606169, "author": "Fontanka16", "author_id": 108390, "author_profile": "https://Stackoverflow.com/users/108390", "pm_score": 0, "selected": false, "text": "import json\nimport logging\nimport os\nfrom pathlib import Path\nfrom typing import List\n\n\nclass MyWriter:\n\n __instance = None\n __inited = False\n\n def __new__(cls, path_to_file: Path) -> \"MyWriter\":\n if cls.__instance is None:\n cls.__instance = super().__new__(cls)\n return cls.__instance\n\n def __init__(self, path_to_file: Path) -> None:\n if type(self).__inited:\n return\n self.cache: List[str] = []\n self.path_to_file: Path = path_to_file\n if self.path_to_file.is_file():\n os.remove(self.path_to_file)\n type(self).__inited = True\n\n def write(self, string_to_write: str, flush=False):\n try:\n if string_to_write:\n self.cache.append(f\"{string_to_write)}\\n\")\n if len(self.cache) > 1000 or flush:\n with open(self.path_to_file, \"a\") as my_file:\n extradata_file.writelines(self.cache)\n self.cache = []\n logging.debug(\"My Writer flushing the cache\")\n except Exception as ee:\n error_message = \"Something went wrong in My Writer\"\n logging.error(error_message)\n raise ee\n\n def flush(self):\n self.write(\"\", True)\n" }, { "answer_id": 74649385, "author": "Kelly Bundy", "author_id": 12671057, "author_profile": "https://Stackoverflow.com/users/12671057", "pm_score": 1, "selected": false, "text": "with with open .close() with with def printer(filename):\n with open(filename, 'w') as f:\n while True:\n print((yield), file=f)\n\n# Demo usage\np = printer('test.txt')\nnext(p)\np.send('foo')\np.send('bar')\np.close()\n\n# Check the resulting file\nwith open('test.txt') as f:\n print(repr(f.read()))\n 'foo\\nbar\\n'\n open close" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10136531/" ]
74,510,354
<p>I am specifically using python version <code>3.10</code> to run a websocket (or any long <code>asyncio</code> process) for a <strong>specified period of time</strong> which is covered in the python docs. The <code>.wait_for()</code> method looks like the correct solution.</p> <p>I run this code (from the docs):</p> <pre class="lang-py prettyprint-override"><code>import asyncio async def eternity(): # Sleep for one hour await asyncio.sleep(3600) print('yay!') async def main(): # Wait for at most 1 second print('wait for at most 1 second...') try: await asyncio.wait_for(eternity(), timeout=1.0) except TimeoutError: print('timeout!') asyncio.run(main()) </code></pre> <p>The docs are here: <a href="https://docs.python.org/3/library/asyncio-task.html?highlight=wait_for#asyncio.wait_for" rel="nofollow noreferrer">https://docs.python.org/3/library/asyncio-task.html?highlight=wait_for#asyncio.wait_for</a></p> <p>However, I get the following error:</p> <pre><code>Exception has occurred: TimeoutError exception: no description </code></pre> <p>...basically, the <code>TimeoutError</code> exception is not handled as expected.</p> <p>My research shows that others have struggled with errors, for example here: <a href="https://stackoverflow.com/questions/11865685/handling-a-timeout-error-in-python-sockets">Handling a timeout error in Python sockets</a></p> <p>but the fixes are either aged (not relevant for 3.10) or do not work. I also notice that the docs specify this &quot;<em>Changed in version 3.10: Removed the loop parameter</em>&quot;. So i am only interested in version <code>3.10</code> and above.</p> <p>So I am wondering how to get the min reproducible example working or what i have done wrong please ?</p>
[ { "answer_id": 74510578, "author": "Zz_GhostM4n_zZ", "author_id": 20555553, "author_profile": "https://Stackoverflow.com/users/20555553", "pm_score": 2, "selected": true, "text": "except Exception as exc:\n print(f'The exception: {exc!r}')\n" }, { "answer_id": 74540603, "author": "fancidev", "author_id": 1465038, "author_profile": "https://Stackoverflow.com/users/1465038", "pm_score": 0, "selected": false, "text": "import asyncio\n\nasync def eternity():\n # Sleep for one hour\n await asyncio.sleep(3600)\n print('yay!')\n\nasync def main():\n # Wait for at most 1 second\n print('wait for at most 1 second...')\n try:\n await asyncio.wait_for(eternity(), timeout=1.0)\n except asyncio.TimeoutError: \n print('timeout!')\n\nasyncio.run(main())\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7318120/" ]
74,510,357
<p>Can anyone help with the below, I am getting the following error Cannot read properties of undefined (reading 'getters')</p> <p>I am working on a project where my stores should return an array to my index.vue</p> <p>Is there also any way I can get around this without having to use the Vuex store?</p> <p>My store directory contains the below files</p> <p>index.js</p> <pre><code>export const state = () =&gt; ({}) </code></pre> <p>parkingPlaces.js</p> <pre><code>import {getters} from '../plugins/base' const state = () =&gt; ({ all: [] }); export default { state, mutations: { SET_PARKINGPLACES(state, parkingPlaces) { state.all = parkingPlaces } }, actions: { async ENSURE({commit}) { commit('SET_PARKINGPLACES', [ { &quot;id&quot;: 1, &quot;name&quot;: &quot;Chandler Larson&quot;, &quot;post&quot;: &quot;37757&quot;, &quot;coordinates&quot;: { &quot;lng&quot;: -1.824377, &quot;lat&quot;: 52.488583 }, &quot;total_spots&quot;: 0, &quot;free_spots&quot;: 0 }, ] ) } }, getters: { ...getters } } </code></pre> <p>index.vue</p> <pre><code>&lt;template&gt; &lt;div class=&quot;min-h-screen relative max-6/6&quot; &gt; &lt;GMap class=&quot;absolute inset-0 h-100% bg-blue-400&quot; ref=&quot;gMap&quot; language=&quot;en&quot; :cluster=&quot;{options: {styles: clusterStyle}}&quot; :center=&quot;{lat:parkingPlaces[0].coordinates.lat, lng: parkingPlaces[0].coordinates.lng}&quot; :options=&quot;{fullscreenControl: false, styles: mapStyle}&quot; :zoom=&quot;5&quot; &gt; &lt;GMapMarker v-for=&quot;location in parkingPlaces&quot; :key=&quot;location.id&quot; :position=&quot;{lat: location.coordinates.lat, lng: location.coordinates.lng}&quot; :options=&quot;{icon: location.free_spots &gt; 0 ? pins.spacefree : pins.spacenotfree}&quot; @click=&quot;currentLocation = location&quot; &gt; &lt;GMapInfoWindow :options=&quot;{maxWidth: 200}&quot;&gt; &lt;code&gt; lat: {{ location.coordinates.lat }}, lng: {{ location.coordinates.lng }} &lt;/code&gt; &lt;/GMapInfoWindow&gt; &lt;/GMapMarker&gt; &lt;GMapCircle :options=&quot;circleOptions&quot;/&gt; &lt;/GMap&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import {mapGetters, mapActions} from 'vuex'; export default { // async mounted() { // // // console.log('http://localhost:8000/api/parkingPlace') // // console.log(process.env.API_URL) // // const response = await this.$axios.$get('PARKING_PLACE') // // // // console.log('response', response) // // // console.log(location) // }, data() { return { currentLocation: {}, circleOptions: {}, // parkingPlaces: [ //array of parkingPlaces // ], pins: { spacefree: &quot;/parkingicongreen3.png&quot;, spacenotfree: &quot;/parkingiconred3.png&quot;, }, mapStyle: [], clusterStyle: [ { url: &quot;https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m1.png&quot;, width: 56, height: 56, textColor: &quot;#fff&quot; } ] } }, computed: { ...mapGetters({ 'parkingPlaces': &quot;parkingPlaces/all&quot; }) }, async fetch() { await this.ensureParking() }, methods: { ...mapActions({ ensureParking: 'parkingPlaces/ENSURE' }) } } &lt;/script&gt; </code></pre> <p>base.js</p> <pre><code>import getters from &quot;./getters&quot;; export {getters}; </code></pre> <p>getters.js</p> <pre><code>export default { all: state =&gt; state.all }; </code></pre> <p>Image of my file directory below <a href="https://i.stack.imgur.com/Vxjv6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vxjv6.png" alt="enter image description here" /></a></p> <p>image of error <a href="https://i.stack.imgur.com/9Wmzm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9Wmzm.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74510578, "author": "Zz_GhostM4n_zZ", "author_id": 20555553, "author_profile": "https://Stackoverflow.com/users/20555553", "pm_score": 2, "selected": true, "text": "except Exception as exc:\n print(f'The exception: {exc!r}')\n" }, { "answer_id": 74540603, "author": "fancidev", "author_id": 1465038, "author_profile": "https://Stackoverflow.com/users/1465038", "pm_score": 0, "selected": false, "text": "import asyncio\n\nasync def eternity():\n # Sleep for one hour\n await asyncio.sleep(3600)\n print('yay!')\n\nasync def main():\n # Wait for at most 1 second\n print('wait for at most 1 second...')\n try:\n await asyncio.wait_for(eternity(), timeout=1.0)\n except asyncio.TimeoutError: \n print('timeout!')\n\nasyncio.run(main())\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13095514/" ]
74,510,362
<p>I have a huge data frame with several columns and rows, and I would like to get all values by rows skipping the first column.</p> <pre><code>import pandas as pd df = pd.DataFrame([['A', 2, 4, 7], ['B', 6, 1, 5], ['C', 4, 2, 2], ['D', 3, 9, 8]], columns = [&quot;Pen&quot;, &quot;A&quot;, 'B', 'C']) values = [] for row in df.iterrows(0, 1): values. Append(values) print(values) </code></pre> <p>expected:</p> <p>[2, 4, 7, 6, 1, 5, 4, 2, 2, 3, 9, 8]</p> <p>My code does not work.</p>
[ { "answer_id": 74510578, "author": "Zz_GhostM4n_zZ", "author_id": 20555553, "author_profile": "https://Stackoverflow.com/users/20555553", "pm_score": 2, "selected": true, "text": "except Exception as exc:\n print(f'The exception: {exc!r}')\n" }, { "answer_id": 74540603, "author": "fancidev", "author_id": 1465038, "author_profile": "https://Stackoverflow.com/users/1465038", "pm_score": 0, "selected": false, "text": "import asyncio\n\nasync def eternity():\n # Sleep for one hour\n await asyncio.sleep(3600)\n print('yay!')\n\nasync def main():\n # Wait for at most 1 second\n print('wait for at most 1 second...')\n try:\n await asyncio.wait_for(eternity(), timeout=1.0)\n except asyncio.TimeoutError: \n print('timeout!')\n\nasyncio.run(main())\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5889450/" ]
74,510,396
<p>Is pseudocode really as simple as it sounds? Or am I completely missing something? I need to write pseudocode for a simple program to display months of the year including the number of month. Will this work??</p> <pre><code>Create list containing months Use for statement to create loop Display month number w/ name </code></pre> <p>Reading various sources and currently attending an online class that provides very little feedback when needed.</p>
[ { "answer_id": 74510459, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": 1, "selected": false, "text": "myList = [\"Jan\", \"Feb\", ...]\nfor i = 0 to 11:\n print(i + \":\" + myList[i])\n" }, { "answer_id": 74510481, "author": "MDavidson", "author_id": 20556118, "author_profile": "https://Stackoverflow.com/users/20556118", "pm_score": 2, "selected": false, "text": "months_list = [list containing each month]\n\nfor month in months_list\n\nprint month and index of month\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20556365/" ]
74,510,404
<p>I have a css background image that i displayed as cover so that it covers entire screen but it does not show lower part of the image.</p> <p>used this image: <a href="https://pixabay.com/vectors/winter-landscape-houses-background-2840549/" rel="nofollow noreferrer">https://pixabay.com/vectors/winter-landscape-houses-background-2840549/</a></p> <p>unable to see the lower part of the white houses in the screen.</p> <p>using chrome browser.</p> <p>CSS Code:</p> <pre><code>banner{ width: 100%; height: 100vh; background-image: url(./images/winter.png); background-size: cover; background-repeat: position: relative; text-align: center; background-attachment: fixed; } </code></pre> <p>any help appreciated.</p> <p>edit: html code</p> <pre><code>&lt;div class=&quot;banner&quot; &gt; &lt;div class=&quot;navigation&quot;&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 74510446, "author": "Emre", "author_id": 6468955, "author_profile": "https://Stackoverflow.com/users/6468955", "pm_score": 1, "selected": false, "text": "body{\n background-image: url(https://cdn.pixabay.com/photo/2017/10/11/10/05/winter-2840549_960_720.png);\n \n /* Center and scale the image nicely */\n background-position: center bottom;\n background-repeat: no-repeat;\n background-size: cover;\n background-attachment: fixed;\n}" }, { "answer_id": 74510621, "author": "HappyHands31", "author_id": 3546086, "author_profile": "https://Stackoverflow.com/users/3546086", "pm_score": 0, "selected": false, "text": "background-size: cover; background-size: contain; background-size: 100% 100%; body {\n background-image: url(https://cdn.pixabay.com/photo/2017/10/11/10/05/winter-2840549_960_720.png);\n background-position: center;\n background-repeat: no-repeat;\n background-size: contain;\n background-attachment: fixed;\n background-size: 100% 100%;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3888135/" ]
74,510,406
<p>I have a URL</p> <pre><code> http://localhost/xxxx/cat/History?randomArg=2 </code></pre> <p>that I want to run</p> <p><strike>http://localhost/xxxx/cat/edit.php?name=History&amp;randomArg=2</strike></p> <pre><code> http://localhost/xxxx/cat.php?name=History&amp;randomArg=2 </code></pre> <blockquote> <p>(POST EDIT#2 Correction I did originally ask for <em>edit.php</em> but I meant <em>cat.php</em>)</p> </blockquote> <p>and I have a RewriteRule that works on my live server</p> <pre><code>RewriteRule &quot;^(.*)xxxx.*/cat/(.*)?(.*)$&quot; $1/xxxx/cat.php?name=$2&amp;t=123$3[QSA] </code></pre> <p>and when I run a test via the htaccess tester <a href="https://htaccess.madewithlove.com?share=f9987308-2570-4fbe-a769-4e5031a96578" rel="nofollow noreferrer">https://htaccess.madewithlove.com?share=f9987308-2570-4fbe-a769-4e5031a96578</a>, I get...</p> <pre><code>RewriteRule &quot;^(.*)xxxx.*/cat/(.*)?(.*)$&quot; $1/xxxx/cat.php?name=$2&amp;t=123$3[QSA] </code></pre> <p>... <a href="https://i.stack.imgur.com/6TZKa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6TZKa.png" alt="enter image description here" /></a></p> <p>Firstly, I can't see why $3 (e.g. &quot;randomArg=2&quot;) isn't coming through on the <a href="https://htaccess.madewithlove.com" rel="nofollow noreferrer">https://htaccess.madewithlove.com</a> tester site.</p> <p>Secondly, I have plugged this into my WAMP environment and although I see cat.php running I don't see the RewriteRule working**</p> <p>my cat.php code reads:</p> <pre><code>echo &quot;&lt;LI&gt;_GET[*]:&lt;PRE&gt;&quot; . print_r($_GET, true) . &quot;&lt;/PRE&gt;&quot;; echo &quot;&lt;LI&gt;_SERVER[SCRIPT_NAME]:&lt;PRE&gt;&quot; . $_SERVER['SCRIPT_NAME'] . &quot;&lt;/PRE&gt;&quot;; echo &quot;&lt;LI&gt;_SERVER[REQUEST_URI]:&lt;PRE&gt;&quot; . $_SERVER['REQUEST_URI'] . &quot;&lt;/PRE&gt;&quot;; if (isset($_GET['name'])) { echo &quot;&lt;LI&gt;GET[name]=&lt;PRE&gt;&quot; . $_GET['name'] . &quot;&lt;/PRE&gt;&quot;; $params = explode(&quot;/&quot;, $_GET['name']); $site = array_shift($params); echo &quot;&lt;LI&gt;shifted:[$site]&quot;; } else echo &quot;&lt;LI&gt;No GET[name]&quot;; if (isset($_GET['t'])) echo &quot;&lt;LI&gt;t:&lt;PRE&gt;&quot; . $_GET['t'] . &quot;&lt;/PRE&gt;&quot;; else echo &quot;&lt;LI&gt;No GET[t]&quot;; </code></pre> <p>and the output for <code>http://localhost/xxxx/cat/History?randomArg=2</code> reads:</p> <pre><code>_GET[*]:Array ( [randomArg] =&gt; 2 ) _SERVER[SCRIPT_NAME]:/xxxx/cat.php _SERVER[REQUEST_URI]:/xxxx/cat/History?randomArg=2 No GET[name] No GET[t] </code></pre> <p>** But if the rule isn't working then why is cat.php running (as the URL asks for &quot;cat/History&quot;?</p> <p>(Windows, Apache 2.4.41, PHP5.4)</p> <UL> <UL> As a sidenote/test, putting this into my LAMP (Apache 2.4.6) environment using a similar rule (but using sss.xxx.com/testHtaccess/History) with the following rule... <pre><code>RewriteRule &quot;^(.*)testHtaccess/(.*)?(.*)$&quot; $1/testHtaccess.php?name=$2&amp;t=123$3[QSA] </code></pre> <p>... does partially work (it passes &quot;name&quot; through, but still no $3)!</p> </UL> </UL> <p>So how can I get my localhost rule to work?</p> <p>** <strong>ADDITIONAL (POST EDIT#1):</strong></p> <p>For what it's worth, and as it's pointed out by anubhava (below) I notice I have the following <code>httpd-vhosts.conf</code> default settings:</p> <pre><code> # Virtual Hosts # &lt;VirtualHost *:80&gt; ServerName localhost ServerAlias localhost DocumentRoot &quot;${INSTALL_DIR}/www&quot; &lt;Directory &quot;${INSTALL_DIR}/www/&quot;&gt; Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require local &lt;/Directory&gt; &lt;/VirtualHost&gt; </code></pre> <blockquote> <p>+MultiViews will explain &quot;cat&quot; turning into &quot;cat.php&quot;</p> </blockquote>
[ { "answer_id": 74510491, "author": "anubhava", "author_id": 548225, "author_profile": "https://Stackoverflow.com/users/548225", "pm_score": 2, "selected": false, "text": "RewriteRule MultiViews Options -MultiViews\nRewriteEngine On\n\nRewriteCond ^(.*/cat)/([\\w-]+)/?$ [NC]\nRewriteRule ^ %1.php?name=%2 [L,QSA,NC]\n QSA" }, { "answer_id": 74522654, "author": "user1432181", "author_id": 1432181, "author_profile": "https://Stackoverflow.com/users/1432181", "pm_score": 1, "selected": false, "text": "RewriteRule \"^(cat)/([\\w- ]+)/?.*$\" xxxx/cat.php?name=$2&t=12345 [L,QSA,NC]\n http://localhost/xxxx/cat/Histor5ys?o=91 echo \"<LI>_GET[*]:<PRE>\" . print_r($_GET, true) . \"</PRE>\";\necho \"<LI>_SERVER[SCRIPT_NAME]:<PRE>\" . $_SERVER['SCRIPT_NAME'] . \"</PRE>\";\necho \"<LI>_SERVER[REQUEST_URI]:<PRE>\" . $_SERVER['REQUEST_URI'] . \"</PRE>\";\n\n\nif (isset($_GET['name'])) {\n echo \"<LI>GET[name]=<PRE>\" . $_GET['name'] . \"</PRE>\";\n}\nelse echo \"<LI>No GET[name]\";\n\n\nif (isset($_GET['t'])) echo \"<LI>t:<PRE>\" . $_GET['t'] . \"</PRE>\";\nelse echo \"<LI>No GET[t]\";\n\n\nif (isset($_GET['o'])) echo \"<LI>o:<PRE>\" . $_GET['o'] . \"</PRE>\";\nelse echo \"<LI>No GET[o]\";\n _GET[*]:Array\n(\n [name] => Histor5ys\n [t] => 123456\n [o] => 91\n)\n_SERVER[SCRIPT_NAME]:/xxxx/cat.php\n_SERVER[REQUEST_URI]:/xxxx/cat/Histor5ys?o=91\nGET[name]=Histor5ys\nshifted:[Histor5ys]\nt:123456\no:91\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1432181/" ]
74,510,410
<p><a href="https://i.stack.imgur.com/iSxwM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iSxwM.png" alt="enter image description here" /></a>On event change I'm trying to capture the value of an object that's displayed in a select drop down.</p> <pre class="lang-html prettyprint-override"><code>&lt;ion-select placeholder=&quot;Select your itinerary&quot; (ionChange)=&quot;handleChange($event)&quot; (ionCancel)=&quot;pushLog('ionCancel fired')&quot; (ionDismiss)=&quot;pushLog('ionDismiss fired')&quot;&gt; &lt;ion-select-option *ngFor=&quot;let itinerary of myItineraries&quot; value=&quot;{{itinerary?.itinerary}}&quot;&gt;{{itinerary?.itinerary.destination}}&lt;/ion-select-option&gt; &lt;/ion-select&gt; </code></pre> <p>There are several properties in itinerary that I need but I'm only displaying the destination. However, I need those other properties on event change.</p> <p>However, when I attempt to capture the change I'm only getting [Object object].</p> <pre><code>handleChange(e) { console.log('event', e.target); this.pushLog('ionChange fired with value: ' + e.detail.value); } </code></pre> <p>and this is the console.log:</p> <blockquote> <p>ionChange fired with value: '[Object object]</p> </blockquote> <p>After searching online I've tried using <code>JSON.stringify(e.detail.value)</code> simply gives me <code>&quot;[Object object]&quot;</code></p> <p>How do I get the actual values of the object's other properties?</p>
[ { "answer_id": 74511881, "author": "D.Hodges", "author_id": 7797500, "author_profile": "https://Stackoverflow.com/users/7797500", "pm_score": 0, "selected": false, "text": "const test = e.detail.value.split(\"*\");\n console.log('event', test);\n this.pushLog('ionChange fired with value: ' + test); value=\"{{itinerary?.itinerary.destination}}, * {{itinerary?.itinerary.moreProperties}}\"" }, { "answer_id": 74515412, "author": "sebaferreras", "author_id": 3915438, "author_profile": "https://Stackoverflow.com/users/3915438", "pm_score": 3, "selected": true, "text": "[value]=\"itinerary?.itinerary\" <ion-select\n placeholder=\"Select your itinerary\"\n (ionChange)=\"handleChange($event)\"\n (ionCancel)=\"pushLog('ionCancel fired')\"\n (ionDismiss)=\"pushLog('ionDismiss fired')\">\n <ion-select-option *ngFor=\"let itinerary of myItineraries\" [value]=\"itinerary?.itinerary\">\n {{ itinerary?.itinerary.destination }}\n </ion-select-option>\n</ion-select>\n handleChange(e) {\n console.log(e.detail.value);\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7797500/" ]
74,510,444
<p>I have a simple React App using Firestore. I have a document in Firestore:</p> <pre><code>{ date: November 20, 2022 at 11:24:44 AM UTC+1, description: &quot;...&quot;, title: &quot;Dummy title&quot;, type: &quot;student&quot;, userRef: /users/0AjB4yFFcIS6VMQMi7rUnF3eJXk2 } </code></pre> <p>Now I have a custom hook, that fetches the data:</p> <pre><code>export const useAnnouncements = () =&gt; { const [announcements, setAnnouncements] = useState([]); useEffect(() =&gt; { getAnnouncements().then((documents) =&gt; { const documentsList = []; documents.forEach((doc) =&gt; { const document = { id: doc.id, ...doc.data() }; getUser(document.userRef).then((u) =&gt; { document.user = u.data(); // &lt;-- HERE is problem }); documentsList.push(document); setAnnouncements(documentsList); }); }); }, []); return [announcements]; }; </code></pre> <p>Problem is that I have a REFERENCE field type, and it has to be fetched separately. Result? My list is populated, but first without user. Later, when the users' data is fetched, the state is not being updated.</p> <p>How to deal with React + Firestore's reference field?</p>
[ { "answer_id": 74510959, "author": "Elvin", "author_id": 11743253, "author_profile": "https://Stackoverflow.com/users/11743253", "pm_score": 2, "selected": true, "text": " useEffect(() => {\n getAnnouncements().then((documents) => {\n const promises = documents.map((doc) => {\n return getUser(doc.userRef).then((u) => {\n const document = { id: doc.id, user: u.data(), ...doc.data() };\n return document;\n });\n });\n\n Promise.all(promises).then((documentsList) => {\n setAnnouncements(documentsList);\n });\n\n });\n }, []);\n" }, { "answer_id": 74511020, "author": "Azzy", "author_id": 2122822, "author_profile": "https://Stackoverflow.com/users/2122822", "pm_score": 0, "selected": false, "text": "export const useAnnouncements = () => {\n\n const [announcements, setAnnouncements] = useState([]);\n\n useEffect(() => {\n\n let isValidScope = true;\n \n const fetchData = async () => {\n\n const documents = await getAnnouncements();\n\n if (!isValidScope) { return; }\n\n const allPromises = documents?.map(doc => {\n return getUser(doc.userRef)\n .then(user => {\n return {\n id: doc.id, \n ...doc.data(),\n user: user.data()\n }\n })\n }\n\n const documentsList = await Promise.all(allPromises);\n\n if (!isValidScope) { return; }\n\n setAnnouncements(documentsList);\n\n }\n\n fetchData()\n\n return () => { isValidScope = false }\n\n }, []);\n\n return [announcements];\n\n };\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2096859/" ]
74,510,448
<p>I want to custumize my DatePicker and only show days cause i want the user to choose one or multiple day from 1 to 31 with ignoring the month and the year</p> <p>I am using the date picker from <code>&quot;react-multi-date-picker&quot;</code></p> <pre class="lang-js prettyprint-override"><code>&lt;DatePicker id={&quot;startDate&quot;} className=&quot;form-control&quot; multiple format=&quot;DD&quot; /&gt;; </code></pre>
[ { "answer_id": 74510575, "author": "Elvin", "author_id": 11743253, "author_profile": "https://Stackoverflow.com/users/11743253", "pm_score": 1, "selected": true, "text": " <DatePicker\n id={'startDate'}\n className=\"form-control\"\n multiple\n format=\"DD\"\n buttons={false}\n disableYearPicker\n disableMonthPicker\n />\n" }, { "answer_id": 74517816, "author": "Isra_Yas", "author_id": 15174378, "author_profile": "https://Stackoverflow.com/users/15174378", "pm_score": 0, "selected": false, "text": "button={false} <DatePicker\n id={\"startDate\"}\n value={editedDates}\n className=\"form-control\"\n multiple\n format=\"DD\"\n buttons={false}\n disableYearPicker\n disableMonthPicker\n hideMonth\n hideYear\n hideWeekDays\n />\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15174378/" ]
74,510,454
<pre><code>var books = new List&lt;Book&gt;(3); foreach (Book item in books) { item.Title = Console.ReadLine(); item.Countofpage = int.Parse(Console.ReadLine()); } </code></pre> <p>When I enter the title into the console, my program just closes.</p> <p>Please help</p>
[ { "answer_id": 74510575, "author": "Elvin", "author_id": 11743253, "author_profile": "https://Stackoverflow.com/users/11743253", "pm_score": 1, "selected": true, "text": " <DatePicker\n id={'startDate'}\n className=\"form-control\"\n multiple\n format=\"DD\"\n buttons={false}\n disableYearPicker\n disableMonthPicker\n />\n" }, { "answer_id": 74517816, "author": "Isra_Yas", "author_id": 15174378, "author_profile": "https://Stackoverflow.com/users/15174378", "pm_score": 0, "selected": false, "text": "button={false} <DatePicker\n id={\"startDate\"}\n value={editedDates}\n className=\"form-control\"\n multiple\n format=\"DD\"\n buttons={false}\n disableYearPicker\n disableMonthPicker\n hideMonth\n hideYear\n hideWeekDays\n />\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19653276/" ]
74,510,470
<p>i have the following data structure</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>[ { id: 1, name: 'Top Level Topic 1', parentTopic: undefined }, { id: 2, name: 'Some topic internally', parentTopic: 1 }, { id: 3, name: 'Another topic', parentTopic: 2 }, { id: 4, name: 'Just another topic', parentTopic: 2 }, { id: 5, name: 'Another topic', parentTopic: 1 }, { id: 6, name: 'Another topic', parentTopic: 5 }, { id: 7, name: 'Another topic', parentTopic: 5 }, { id: 8, name: 'Another topic', parentTopic: 1 }, { id: 9, name: 'Another topic', parentTopic: 8 }, { id: 10, name: 'Another topic', parentTopic: 9 }, { id: 11, name: 'Another topic', parentTopic: 10 }, { id: 12, name: 'Another Top Level Topic', parentTopic: undefined }, { id: 13, name: 'Another Important Topic', parentTopic: 12 }]</code></pre> </div> </div> </p> <p>I am trying to convert &amp; construct it in the following manner</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>[ { id: 1, name: 'Top Level Topic 1', parentTopic: undefined, index: 1, children: [ { id: 2, name: 'Some topic internally', parentTopic: 1, index: 1.1, children: [ { id: 3, name: 'Another topic', parentTopic: 2, index: 1.1.1, children: [] }, { id: 4, name: 'Just another topic', parentTopic: 2, index: 1.1.2, children: [] }, ] }, { id: 5, name: 'Another topic', parentTopic: 1, index: 1.2, children: [ { id: 6, name: 'Another topic', parentTopic: 5, index: 1.2.1, children: [] }, { id: 7, name: 'Another topic', parentTopic: 5, index: 1.2.2, children: [] }, ] }, { id: 8, name: 'Another topic', parentTopic: 1, index: 1.3, children: [ { id: 9, name: 'Another topic', parentTopic: 8, index: 1.3.1, children: [ { id: 10, name: 'Another topic', parentTopic: 9, index: 1.3.1.1, children: [] }, ] }, ] }, ] }, { id: 12, name: 'Another Top Level Topic', parentTopic: undefined, index: 2 children: [ { id: 13, name: 'Another Important Topic', parentTopic: 12, index: 2.1, children: [] }, ] }, ]</code></pre> </div> </div> </p> <p>My challenge is that I am not sure how to recursively perform this. Also in the output you will notice an index, which could be nice to generate as one iterates or it could just come from the db, meaning my original data structure would already have it.</p> <p>I would really appreciate if anyone could help me with this :)</p> <p>Here is my code which works but at the top level its a dictionary instead of being list of dictionaries</p> <pre><code> const invertHierarchy = (arr) =&gt; { const map = {}; let root; for (const ele of arr) { map[ele.id] = ele; ele.topics = []; } for (const ele of arr) { if (map[ele.parentTopic] != null) map[ele.parentTopic].topics.push(ele); else root = ele; } return root; }; </code></pre>
[ { "answer_id": 74510596, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 3, "selected": true, "text": "const data = [{\"id\":1,\"name\":\"Top Level Topic 1\"},{\"id\":2,\"name\":\"Some topic internally\",\"parentTopic\":1},{\"id\":3,\"name\":\"Another topic\",\"parentTopic\":2},{\"id\":4,\"name\":\"Just another topic\",\"parentTopic\":2},{\"id\":5,\"name\":\"Another topic\",\"parentTopic\":1},{\"id\":6,\"name\":\"Another topic\",\"parentTopic\":5},{\"id\":7,\"name\":\"Another topic\",\"parentTopic\":5},{\"id\":8,\"name\":\"Another topic\",\"parentTopic\":1},{\"id\":9,\"name\":\"Another topic\",\"parentTopic\":8},{\"id\":10,\"name\":\"Another topic\",\"parentTopic\":9},{\"id\":11,\"name\":\"Another topic\",\"parentTopic\":10},{\"id\":12,\"name\":\"Another Top Level Topic\"},{\"id\":13,\"name\":\"Another Important Topic\",\"parentTopic\":12}];\n\nconst getPrefix = (prefix, i) => prefix ? `${prefix}.${i+1}` : `${i+1}`\n\nconst f = (arr, parentTopic, prefix) =>\n arr.filter(e=>e.parentTopic===parentTopic).map((e,i)=>({\n ...e,\n index: getPrefix(prefix,i),\n children: f(arr, e.id, getPrefix(prefix,i))\n}))\n\nconsole.log(f(data))" }, { "answer_id": 74510738, "author": "Nina Scholz", "author_id": 1447675, "author_profile": "https://Stackoverflow.com/users/1447675", "pm_score": 0, "selected": false, "text": "const\n data = [{ id: 1, name: 'Top Level Topic 1', parentTopic: undefined }, { id: 2, name: 'Some topic internally', parentTopic: 1 }, { id: 3, name: 'Another topic', parentTopic: 2 }, { id: 4, name: 'Just another topic', parentTopic: 2 }, { id: 5, name: 'Another topic', parentTopic: 1 }, { id: 6, name: 'Another topic', parentTopic: 5 }, { id: 7, name: 'Another topic', parentTopic: 5 }, { id: 8, name: 'Another topic', parentTopic: 1 }, { id: 9, name: 'Another topic', parentTopic: 8 }, { id: 10, name: 'Another topic', parentTopic: 9 }, { id: 11, name: 'Another topic', parentTopic: 10 }, { id: 12, name: 'Another Top Level Topic', parentTopic: undefined }, { id: 13, name: 'Another Important Topic', parentTopic: 12 }],\n tree = function(data, root) {\n const t = {};\n data.forEach(o => {\n Object.assign(t[o.id] ??= {}, { ...o });\n ((t[o.parentTopic] ??= {}).children ??= []).push(t[o.id]);\n const index = t[o.parentTopic].index || '';\n t[o.id].index = index + (index && '.') + t[o.parentTopic].children.length;\n });\n return t[root].children;\n }(data, undefined);\n\nconsole.log(tree); .as-console-wrapper { max-height: 100% !important; top: 0; }" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2906950/" ]
74,510,540
<p>On classes/methods that work with several properties, what's the best or more pythonic way to work with default parameters (on object instantiation) and overwrite those defaults on calls to that object's methods?</p> <p>I'd like to be able to create an object with a set of default parameters (being a large amount of possible parameters) and then, when calling that object's methods, either use those default parameters or be able to easily overwrite any of them in the method call.</p> <p>I have it already working (example below) but I'd like to know what's the most pythonic way to do it.</p> <p>Let's illustrate my question:</p> <p><strong>Class definition</strong>:</p> <pre><code>class SimpleInputText: def __init__(self, basicFont, **kwargs): self._basicFont = basicFont self.text = '' self.set_defaults(**kwargs) def set_defaults(self, **kwargs): self.default_text = kwargs.get('default_text', '') self.color = kwargs.get('color', (0, 0, 0)) self.inactive_color = kwargs.get('inactive_color', (50, 50, 50)) self.error_color = kwargs.get('error_color', None) self.background_color = kwargs.get('background_color', None) self.border_color = kwargs.get('border_color', (0, 0, 0)) self.border_size = kwargs.get('border_size', 0) self.border_radius = kwargs.get('border_radius', 0) self.padding_left = kwargs.get('padding_left', 0) self.padding_top = kwargs.get('padding_top', 0) self.padding = kwargs.get('padding', 2) self.shadow_offset = kwargs.get('shadow_offset', 0) self.shadow_color = kwargs.get('shadow_color', (0, 0, 0)) # (and more possible properties) def input_modal(self, x, y, default_text='', color=None, background_color=None, inactive_color=None, border_color=None, border_size=None, border_radius=None, padding_left=None, padding_top=None, padding=None, shadow_offset=None, shadow_color=None, etc... ): # Set specific values if passed, otherwise use defaults cursor_char = self.cursor_char if cursor_char is None else cursor_char input_type = self.input_type if input_type is None else input_type check_type = self.check_type if check_type is None else check_type color = self.color if color is None else color inactive_color = self.inactive_color if inactive_color is None else inactive_color inactive_border_color = self.inactive_border_color if inactive_border_color is None else inactive_border_color error_color = self.error_color if error_color is None else error_color background_color = self.background_color if background_color is None else background_color border_color = self.border_color if border_color is None else border_color border_size = self.border_size if border_size is None else border_size padding_left = self.padding_left if padding_left is None else padding_left padding_top = self.padding_top if padding_top is None else padding_top padding = self.padding if padding is None else padding border_radius = self.border_radius if border_radius is None else border_radius shadow_offset = self.shadow_offset if shadow_offset is None else shadow_offset shadow_color = self.shadow_color if shadow_color is None else shadow_color # etc... # the method uses, from now on, the local versions of the variables # (i.e. color and not self.color) to do its work. </code></pre> <p>This way I can instantiate an inputBox object with specific values and overwrite any of these values in the moment of calling <code>input_modal()</code>.</p> <p>I also considered the possibility of using a <code>dict</code> for <code>self.defaults</code> and then get a merge of the defaults and the parameters:</p> <pre><code> def input_modal(self, x, y, default_text='', **kwargs ): params = dict(**self.defaults, **kwargs) # now use params.color, params.border_size, etc in the method </code></pre> <p>I'm not sure what's the best approach for this specific use-case (allowing defaults and having a large number of possible parameters due to styling options).</p>
[ { "answer_id": 74510872, "author": "dskrypa", "author_id": 19070573, "author_profile": "https://Stackoverflow.com/users/19070573", "pm_score": 1, "selected": false, "text": "from __future__ import annotations\n\nfrom typing import Optional, Union\n\n\nclass TextAttribute:\n __slots__ = ('default', 'type', 'name')\n\n def __init__(self, default, type=None): # noqa\n self.default = default\n self.type = type\n\n def __set_name__(self, owner, name: str):\n self.name = name\n owner.FIELDS.add(name)\n\n def __get__(self, instance, owner):\n if instance is None:\n return self\n try:\n return instance.__dict__[self.name]\n except KeyError:\n return self.default\n\n def __set__(self, instance, value):\n if self.type is not None:\n value = self.type(value)\n instance.__dict__[self.name] = value\n\n def __delete__(self, instance):\n try:\n del instance.__dict__[self.name]\n except KeyError as e:\n raise AttributeError(f'No {self.name!r} attribute was stored for {instance}') from e\n\n\nclass Color:\n # You could implement __get__ and __iter__ to act more like a tuple\n def __init__(self, red: int, green: int, blue: int):\n self.red = red\n self.green = green\n self.blue = blue\n\n @classmethod\n def normalize(cls, obj: Union[Color, tuple[int, int, int], None]) -> Optional[Color]:\n if isinstance(obj, cls) or obj is None:\n return obj\n return cls(*obj)\n\n def __repr__(self) -> str:\n return f'<Color({self.red}, {self.green}, {self.blue})>'\n\n\nclass SimpleInputText:\n FIELDS = set()\n\n default_text = TextAttribute('', str)\n color = TextAttribute(Color(0, 0, 0), Color.normalize)\n inactive_color = TextAttribute(Color(50, 50, 50), Color.normalize)\n error_color = TextAttribute(None, Color.normalize)\n padding = TextAttribute(2, int)\n\n def __init__(self, basic_font, **kwargs):\n self.basic_font = basic_font\n self.text = ''\n self._update_attrs(**kwargs)\n\n def _update_attrs(self, **kwargs):\n bad = {}\n for key, val in kwargs.items():\n if key in self.FIELDS:\n setattr(self, key, val)\n else:\n bad[key] = val\n if bad:\n raise ValueError('Invalid text attributes - unsupported args: ' + ', '.join(sorted(bad)))\n\n def input_modal(self, x, y, **kwargs):\n self._update_attrs(**kwargs)\n Color _update_attrs input_modal setattr >>> SimpleInputText('tahoma', padding=5, foo='bar')\nTraceback (most recent call last):\n...\nValueError: Invalid text attributes - unsupported args: foo\n\n>>> sit = SimpleInputText('tahoma', padding=5)\n\n>>> sit.padding\n5\n\n>>> sit.default_text\n''\n\n>>> sit.color\n<Color(0, 0, 0)>\n __init__ init_modal typing.overload _update_attrs >>> sit.color = (1, 2, 3)\n\n>>> sit.color\n<Color(1, 2, 3)>\n\n>>> sit.color = 3\nTraceback (most recent call last):\n...\nTypeError: __main__.Color() argument after * must be an iterable, not int\n init_modal ChainMap def __getitem__(self, item):\n return getattr(self, item)\n\ndef init_modal(self, x, y, **kwargs):\n settings = ChainMap(kwargs, self)\n ...\n >>> sit = SimpleInputText('tahoma', padding=5)\n\n>>> settings = ChainMap({'padding': 10}, sit)\n\n>>> settings['padding']\n10\n\n>>> settings['color']\n<Color(0, 0, 0)>\n" }, { "answer_id": 74510934, "author": "gimix", "author_id": 15844296, "author_profile": "https://Stackoverflow.com/users/15844296", "pm_score": 0, "selected": false, "text": "dataclass from dataclasses import dataclass\n\n@dataclass\nclass SimpleInputText:\n self._basicFont : str\n self.text : str = ''\n self.default_text : str = ''\n self.color : tuple[int] = (0, 0, 0)\n self.inactive_color: tuple[int] = (50, 50, 50)\n # and so on\n\n def input_modal(self, **kwargs):\n for k,v in kwargs.items():\n if k in self.__dict__:\n self.__dict__[k] = v\n else:\n raise NameError(f'{k} is not an attribute')\n if/else" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/844578/" ]
74,510,541
<p>in my sql table I have decimal data with dot as a separator but the display in my page is done with commas</p> <p>I would like to display them with dot</p> <p>in my settings i have this</p> <pre><code>LANGUAGE_CODE = &quot;fr-fr&quot; TIME_ZONE = &quot;UTC&quot; USE_I18N = True USE_TZ = True </code></pre> <p>my models</p> <pre><code>class VilleStation(models.Model): nomVille = models.CharField(max_length=255) adresse = models.CharField(max_length=255) cp = models.CharField(max_length=5) latitude = models.DecimalField(max_digits=9, decimal_places=6) longitude = models.DecimalField(max_digits=9, decimal_places=6) </code></pre> <p>in the templates i have this</p> <pre><code>{% for c in object_list %} {{c.nomVille}} {{c.adresse}} {{c.cp}} {{c.latitude}} {{c.longitude}} {% endfor %} </code></pre> <p>thank</p>
[ { "answer_id": 74510872, "author": "dskrypa", "author_id": 19070573, "author_profile": "https://Stackoverflow.com/users/19070573", "pm_score": 1, "selected": false, "text": "from __future__ import annotations\n\nfrom typing import Optional, Union\n\n\nclass TextAttribute:\n __slots__ = ('default', 'type', 'name')\n\n def __init__(self, default, type=None): # noqa\n self.default = default\n self.type = type\n\n def __set_name__(self, owner, name: str):\n self.name = name\n owner.FIELDS.add(name)\n\n def __get__(self, instance, owner):\n if instance is None:\n return self\n try:\n return instance.__dict__[self.name]\n except KeyError:\n return self.default\n\n def __set__(self, instance, value):\n if self.type is not None:\n value = self.type(value)\n instance.__dict__[self.name] = value\n\n def __delete__(self, instance):\n try:\n del instance.__dict__[self.name]\n except KeyError as e:\n raise AttributeError(f'No {self.name!r} attribute was stored for {instance}') from e\n\n\nclass Color:\n # You could implement __get__ and __iter__ to act more like a tuple\n def __init__(self, red: int, green: int, blue: int):\n self.red = red\n self.green = green\n self.blue = blue\n\n @classmethod\n def normalize(cls, obj: Union[Color, tuple[int, int, int], None]) -> Optional[Color]:\n if isinstance(obj, cls) or obj is None:\n return obj\n return cls(*obj)\n\n def __repr__(self) -> str:\n return f'<Color({self.red}, {self.green}, {self.blue})>'\n\n\nclass SimpleInputText:\n FIELDS = set()\n\n default_text = TextAttribute('', str)\n color = TextAttribute(Color(0, 0, 0), Color.normalize)\n inactive_color = TextAttribute(Color(50, 50, 50), Color.normalize)\n error_color = TextAttribute(None, Color.normalize)\n padding = TextAttribute(2, int)\n\n def __init__(self, basic_font, **kwargs):\n self.basic_font = basic_font\n self.text = ''\n self._update_attrs(**kwargs)\n\n def _update_attrs(self, **kwargs):\n bad = {}\n for key, val in kwargs.items():\n if key in self.FIELDS:\n setattr(self, key, val)\n else:\n bad[key] = val\n if bad:\n raise ValueError('Invalid text attributes - unsupported args: ' + ', '.join(sorted(bad)))\n\n def input_modal(self, x, y, **kwargs):\n self._update_attrs(**kwargs)\n Color _update_attrs input_modal setattr >>> SimpleInputText('tahoma', padding=5, foo='bar')\nTraceback (most recent call last):\n...\nValueError: Invalid text attributes - unsupported args: foo\n\n>>> sit = SimpleInputText('tahoma', padding=5)\n\n>>> sit.padding\n5\n\n>>> sit.default_text\n''\n\n>>> sit.color\n<Color(0, 0, 0)>\n __init__ init_modal typing.overload _update_attrs >>> sit.color = (1, 2, 3)\n\n>>> sit.color\n<Color(1, 2, 3)>\n\n>>> sit.color = 3\nTraceback (most recent call last):\n...\nTypeError: __main__.Color() argument after * must be an iterable, not int\n init_modal ChainMap def __getitem__(self, item):\n return getattr(self, item)\n\ndef init_modal(self, x, y, **kwargs):\n settings = ChainMap(kwargs, self)\n ...\n >>> sit = SimpleInputText('tahoma', padding=5)\n\n>>> settings = ChainMap({'padding': 10}, sit)\n\n>>> settings['padding']\n10\n\n>>> settings['color']\n<Color(0, 0, 0)>\n" }, { "answer_id": 74510934, "author": "gimix", "author_id": 15844296, "author_profile": "https://Stackoverflow.com/users/15844296", "pm_score": 0, "selected": false, "text": "dataclass from dataclasses import dataclass\n\n@dataclass\nclass SimpleInputText:\n self._basicFont : str\n self.text : str = ''\n self.default_text : str = ''\n self.color : tuple[int] = (0, 0, 0)\n self.inactive_color: tuple[int] = (50, 50, 50)\n # and so on\n\n def input_modal(self, **kwargs):\n for k,v in kwargs.items():\n if k in self.__dict__:\n self.__dict__[k] = v\n else:\n raise NameError(f'{k} is not an attribute')\n if/else" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11230924/" ]
74,510,542
<p>Im making a platform with different roles with laravel , I wanted to ask if the following code its secure to use to define the roles</p> <p>For example i want to use different paths for admin and user and to show them some specific content based on roles : Is this a good way to check the roles or i must modify the code :</p> <pre><code> @if(auth()-&gt;user()-&gt;role=='user') You'are user @elseif(auth()-&gt;user()-&gt;role=='admin') You're admin @endif </code></pre> <p>I also want the login to be the same page not to change on the url</p>
[ { "answer_id": 74510872, "author": "dskrypa", "author_id": 19070573, "author_profile": "https://Stackoverflow.com/users/19070573", "pm_score": 1, "selected": false, "text": "from __future__ import annotations\n\nfrom typing import Optional, Union\n\n\nclass TextAttribute:\n __slots__ = ('default', 'type', 'name')\n\n def __init__(self, default, type=None): # noqa\n self.default = default\n self.type = type\n\n def __set_name__(self, owner, name: str):\n self.name = name\n owner.FIELDS.add(name)\n\n def __get__(self, instance, owner):\n if instance is None:\n return self\n try:\n return instance.__dict__[self.name]\n except KeyError:\n return self.default\n\n def __set__(self, instance, value):\n if self.type is not None:\n value = self.type(value)\n instance.__dict__[self.name] = value\n\n def __delete__(self, instance):\n try:\n del instance.__dict__[self.name]\n except KeyError as e:\n raise AttributeError(f'No {self.name!r} attribute was stored for {instance}') from e\n\n\nclass Color:\n # You could implement __get__ and __iter__ to act more like a tuple\n def __init__(self, red: int, green: int, blue: int):\n self.red = red\n self.green = green\n self.blue = blue\n\n @classmethod\n def normalize(cls, obj: Union[Color, tuple[int, int, int], None]) -> Optional[Color]:\n if isinstance(obj, cls) or obj is None:\n return obj\n return cls(*obj)\n\n def __repr__(self) -> str:\n return f'<Color({self.red}, {self.green}, {self.blue})>'\n\n\nclass SimpleInputText:\n FIELDS = set()\n\n default_text = TextAttribute('', str)\n color = TextAttribute(Color(0, 0, 0), Color.normalize)\n inactive_color = TextAttribute(Color(50, 50, 50), Color.normalize)\n error_color = TextAttribute(None, Color.normalize)\n padding = TextAttribute(2, int)\n\n def __init__(self, basic_font, **kwargs):\n self.basic_font = basic_font\n self.text = ''\n self._update_attrs(**kwargs)\n\n def _update_attrs(self, **kwargs):\n bad = {}\n for key, val in kwargs.items():\n if key in self.FIELDS:\n setattr(self, key, val)\n else:\n bad[key] = val\n if bad:\n raise ValueError('Invalid text attributes - unsupported args: ' + ', '.join(sorted(bad)))\n\n def input_modal(self, x, y, **kwargs):\n self._update_attrs(**kwargs)\n Color _update_attrs input_modal setattr >>> SimpleInputText('tahoma', padding=5, foo='bar')\nTraceback (most recent call last):\n...\nValueError: Invalid text attributes - unsupported args: foo\n\n>>> sit = SimpleInputText('tahoma', padding=5)\n\n>>> sit.padding\n5\n\n>>> sit.default_text\n''\n\n>>> sit.color\n<Color(0, 0, 0)>\n __init__ init_modal typing.overload _update_attrs >>> sit.color = (1, 2, 3)\n\n>>> sit.color\n<Color(1, 2, 3)>\n\n>>> sit.color = 3\nTraceback (most recent call last):\n...\nTypeError: __main__.Color() argument after * must be an iterable, not int\n init_modal ChainMap def __getitem__(self, item):\n return getattr(self, item)\n\ndef init_modal(self, x, y, **kwargs):\n settings = ChainMap(kwargs, self)\n ...\n >>> sit = SimpleInputText('tahoma', padding=5)\n\n>>> settings = ChainMap({'padding': 10}, sit)\n\n>>> settings['padding']\n10\n\n>>> settings['color']\n<Color(0, 0, 0)>\n" }, { "answer_id": 74510934, "author": "gimix", "author_id": 15844296, "author_profile": "https://Stackoverflow.com/users/15844296", "pm_score": 0, "selected": false, "text": "dataclass from dataclasses import dataclass\n\n@dataclass\nclass SimpleInputText:\n self._basicFont : str\n self.text : str = ''\n self.default_text : str = ''\n self.color : tuple[int] = (0, 0, 0)\n self.inactive_color: tuple[int] = (50, 50, 50)\n # and so on\n\n def input_modal(self, **kwargs):\n for k,v in kwargs.items():\n if k in self.__dict__:\n self.__dict__[k] = v\n else:\n raise NameError(f'{k} is not an attribute')\n if/else" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20556576/" ]
74,510,559
<p>I have an array of integer arrays like:</p> <p><code>i = [[1,3,8],[1,7,4],[1,9,1],[1,0,3],[1,11,-2]]</code></p> <p>And I want a result like:</p> <p><code>i = [[1,9,1],[1,11,-2],[1,0,3],[1,7,4],[1,3,8]]</code></p> <p>where the &quot;i&quot; array is sorted in a way that i[x][2] is closest to 0.</p> <p>I tried to change the lambda in: <code>sorted_i = sorted(i, key=lambda x: x[2])</code> but with no success.</p>
[ { "answer_id": 74510580, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 3, "selected": true, "text": "sorted_i = sorted(i, key=lambda x: abs(x[2]))\n" }, { "answer_id": 74510613, "author": "El Mehdi", "author_id": 14529779, "author_profile": "https://Stackoverflow.com/users/14529779", "pm_score": 0, "selected": false, "text": "x[2] if x[2] > 0 else -x[2] arr = [[1, 3, 8], [1, 7, 4], [1, 9, 1], [1, 0, 3], [1, 11, -2]]\nsorted_arr = sorted(arr, key=lambda x: x[2] if x[2] > 0 else -x[2])\nprint(sorted_arr) #[[1, 9, 1], [1, 11, -2], [1, 0, 3], [1, 7, 4], [1, 3, 8]]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13160638/" ]
74,510,598
<p>I want to find ObjectId of a user, but I can't use Get-AzADUser module as I don't have privilege to install this module.</p> <p>Get-AzRoleAssignment, Get-AzContext is accessible to me</p> <p>Is there any other way to find ObjectId of a user with any other module.</p> <p>Any help would be GREATLY appreciated</p>
[ { "answer_id": 74510580, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 3, "selected": true, "text": "sorted_i = sorted(i, key=lambda x: abs(x[2]))\n" }, { "answer_id": 74510613, "author": "El Mehdi", "author_id": 14529779, "author_profile": "https://Stackoverflow.com/users/14529779", "pm_score": 0, "selected": false, "text": "x[2] if x[2] > 0 else -x[2] arr = [[1, 3, 8], [1, 7, 4], [1, 9, 1], [1, 0, 3], [1, 11, -2]]\nsorted_arr = sorted(arr, key=lambda x: x[2] if x[2] > 0 else -x[2])\nprint(sorted_arr) #[[1, 9, 1], [1, 11, -2], [1, 0, 3], [1, 7, 4], [1, 3, 8]]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11722543/" ]
74,510,602
<p>i have a dataframe, namely data, with a datetime index and the below columns :</p> <pre><code> id activity x y z datetime 1970-01-01 00:42:00.219142823 1623 A -0.152512 -8.585220 -1.219192 1970-01-01 00:42:00.269496827 1623 A 0.999466 -8.196548 -0.758926 1970-01-01 00:42:00.319850830 1623 A 0.450241 -8.701187 -1.290024 1970-01-01 00:42:00.370204834 1623 A -0.042175 -9.739563 -1.787415 1970-01-01 00:42:00.420558838 1623 A 3.551483 -10.745132 -1.266403 ... ... ... ... ... ... 1970-01-22 01:26:29.872699000 1644 A 2.239343 -8.408914 2.074087 1970-01-22 01:26:29.892898000 1644 A 2.548301 -8.157437 1.820215 1970-01-22 01:26:29.912994000 1644 A 2.636917 -7.786209 2.057322 1970-01-22 01:26:29.933195000 1644 A 2.545906 -7.743098 1.801055 1970-01-22 01:26:29.953291000 1644 A 2.373464 -8.071217 1.585503 279817 rows × 5 columns </code></pre> <p>every 119 rows i want to extract only the values of x, y, z columns, as well with the activity label, and put them in a new dataframe row by row. the values of each column followed up by the next column. like below :</p> <pre><code>values of column x|values of column y|values of column z|activity </code></pre> <p>next row after 119 rows of values of the dataframe data</p> <pre><code>values of column x|values of column y|values of column z|activity </code></pre> <p>etc</p> <p>any ideas would be very helpful and much appreciated.</p> <p>Thanks in advance for your time!</p>
[ { "answer_id": 74510580, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 3, "selected": true, "text": "sorted_i = sorted(i, key=lambda x: abs(x[2]))\n" }, { "answer_id": 74510613, "author": "El Mehdi", "author_id": 14529779, "author_profile": "https://Stackoverflow.com/users/14529779", "pm_score": 0, "selected": false, "text": "x[2] if x[2] > 0 else -x[2] arr = [[1, 3, 8], [1, 7, 4], [1, 9, 1], [1, 0, 3], [1, 11, -2]]\nsorted_arr = sorted(arr, key=lambda x: x[2] if x[2] > 0 else -x[2])\nprint(sorted_arr) #[[1, 9, 1], [1, 11, -2], [1, 0, 3], [1, 7, 4], [1, 3, 8]]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12391776/" ]
74,510,610
<p>i am trying to get a balance column in a python dataframe with an initial static value.</p> <p><strong>The logic:</strong></p> <p>start balance = 1000</p> <p>current balance = previous current balance*(1+df['return'])</p> <p><strong>My attempt:</strong></p> <pre><code>df.at[1,'current balance'] = 1000 df['current balance'] = df['current balance'].shift(1)*(1+df['return]) </code></pre> <p>I can't get this output</p> <p><strong>Output dataframe:</strong></p> <pre><code>return current balance 0.01 1010.00 0.03 1040.30 0.045 1087.11 </code></pre>
[ { "answer_id": 74510580, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 3, "selected": true, "text": "sorted_i = sorted(i, key=lambda x: abs(x[2]))\n" }, { "answer_id": 74510613, "author": "El Mehdi", "author_id": 14529779, "author_profile": "https://Stackoverflow.com/users/14529779", "pm_score": 0, "selected": false, "text": "x[2] if x[2] > 0 else -x[2] arr = [[1, 3, 8], [1, 7, 4], [1, 9, 1], [1, 0, 3], [1, 11, -2]]\nsorted_arr = sorted(arr, key=lambda x: x[2] if x[2] > 0 else -x[2])\nprint(sorted_arr) #[[1, 9, 1], [1, 11, -2], [1, 0, 3], [1, 7, 4], [1, 3, 8]]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6883721/" ]
74,510,620
<p>Code to drop rows based on a partial string is not working.</p> <p>Very simple code, and it runs fine but doesn't drop the rows I want.</p> <p>The original table in the pdf looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Chemical</th> <th>Value</th> <th>Unit</th> <th>Type</th> </tr> </thead> <tbody> <tr> <td>Fluoride</td> <td>0.23</td> <td>ug/L</td> <td>Lab</td> </tr> <tr> <td>Mercury</td> <td>0.15</td> <td>ug/L</td> <td>Lab</td> </tr> <tr> <td>Sum of Long Chained Polymers</td> <td>0.33</td> <td></td> <td></td> </tr> <tr> <td>Partialsum of Short Chained Polymers</td> <td>0.40</td> <td></td> <td></td> </tr> </tbody> </table> </div> <p>What I did:</p> <pre><code>import csv import tabula dfs = tabula.read _pdf(&quot;Test.pdf&quot;, pages= 'all') file = &quot;Test.pdf&quot; tables = tabula.read_pdf(file, pages=2, stream=True, multiple_tables=True) table1 = tables[1] table1.drop('Unit', axis=1, inplace=True) table1.drop('Type', axis=1, inplace=True) discard = ['sum','Sum'] table1[~table1.Chemical.str.contains('|'.join(discard))] print(table1) table1.to_csv('test.csv') </code></pre> <p>The results are that it drops the 2 columns I don't want, so that's fine. But it did not delete the rows with the words &quot;sum&quot; or &quot;Sum&quot; in them. Any insights?</p>
[ { "answer_id": 74510580, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 3, "selected": true, "text": "sorted_i = sorted(i, key=lambda x: abs(x[2]))\n" }, { "answer_id": 74510613, "author": "El Mehdi", "author_id": 14529779, "author_profile": "https://Stackoverflow.com/users/14529779", "pm_score": 0, "selected": false, "text": "x[2] if x[2] > 0 else -x[2] arr = [[1, 3, 8], [1, 7, 4], [1, 9, 1], [1, 0, 3], [1, 11, -2]]\nsorted_arr = sorted(arr, key=lambda x: x[2] if x[2] > 0 else -x[2])\nprint(sorted_arr) #[[1, 9, 1], [1, 11, -2], [1, 0, 3], [1, 7, 4], [1, 3, 8]]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20556520/" ]
74,510,633
<p>I have a class that calls a mocked function in the initializer list. I want to use EXPECT_CALL in order to verify that the mocked function is called only once. The problem is that I can't use the macro before the constructor because it's the first function that runs, neither after it because the mocked function is called in the constructor.</p> <p>For example: <em>ui.cpp</em></p> <pre><code>class UI { public: UI() = default; ~UI() = default; virtual std::string get_name() { std::string name; std::cin &gt;&gt; name; return name; } }; </code></pre> <p><em>foo.cpp</em></p> <pre><code>class Foo { public: Foo(UI&amp; ui) : m_name(ui.get_name()) {} ~Foo() = default; }; </code></pre> <p><em>mock_ui.hpp</em></p> <pre><code>class MockUI : public UI { MockUI() : UI() = default; ~MockUI() = default; MOCK_METHOD(std::string, get_name, (), (override)); }; </code></pre> <p>The problem occurs here: <em>foo_test.cpp</em></p> <pre><code>class FooTest : ::testing::Test { public: // I want to call EXPECT_CALL(m_ui, get_name()) before this line executes. FooTest() : m_foo(MockUI()) {} ~FooTest() = default; protected: void SetUp() override {} void TearDown() override {} Foo m_foo; MockUI m_ui; }; </code></pre> <p>I tried initializing the <code>Foo</code> object in the <code>SetUp()</code> function, but Foo doesn't have default constructor so it has to be initialized in the <code>FooTest</code> constructor.</p> <p><strong>The Solution?</strong> The only idea I have is to call <code>EXPECT_CALL()</code> in MockUI constructor like this: <em>mock_ui.hpp</em></p> <pre><code>class MockUI : public UI { MockUI() : UI() { EXPECT_CALL(*this, get_name()); } ~MockUI() = default; MOCK_METHOD(std::string, get_name, (), (override); }; </code></pre> <p>The problem is that I might use MockUI without calling <code>get_name()</code> or calling it multiple times, but this is the best solution I have.</p> <p>Any other suggestions?</p>
[ { "answer_id": 74510580, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 3, "selected": true, "text": "sorted_i = sorted(i, key=lambda x: abs(x[2]))\n" }, { "answer_id": 74510613, "author": "El Mehdi", "author_id": 14529779, "author_profile": "https://Stackoverflow.com/users/14529779", "pm_score": 0, "selected": false, "text": "x[2] if x[2] > 0 else -x[2] arr = [[1, 3, 8], [1, 7, 4], [1, 9, 1], [1, 0, 3], [1, 11, -2]]\nsorted_arr = sorted(arr, key=lambda x: x[2] if x[2] > 0 else -x[2])\nprint(sorted_arr) #[[1, 9, 1], [1, 11, -2], [1, 0, 3], [1, 7, 4], [1, 3, 8]]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14220253/" ]
74,510,668
<p>A process I have that's been running for a couple of years suddenly stopped working. I avoided updating much in the way of python and packages to avoid that..</p> <p>I've now updated ib_insync to the latest version, and no improvement. debugging a little gives me this:</p> <p>the code import ib_insync as ibis ib = ibis.IB() contract = ibis.Contract() contract.secType = 'STK' contract.currency = 'USD' contract.exchange = 'SMART' contract.localSymbol = 'AAPL' ib.qualifyContracts(contract)</p> <p>Result: File &quot;/Users/macuser/anaconda3/lib/python3.6/site-packages/ib_insync/client.py&quot;, line 244, in send if field in empty: File &quot;/Users/macuser/anaconda3/lib/python3.6/site-packages/ib_insync/contract.py&quot;, line 153, in <strong>hash</strong> raise ValueError(f'Contract {self} can't be hashed') ValueError: Contract Contract(secType='STK', exchange='SMART', currency='USD', localSymbol='AAPL') can't be hashed Exception ignored in: &lt;bound method IB.<strong>del</strong> of &lt;IB connected to 127.0.0.1:7497 clientId=6541&gt;&gt; Traceback (most recent call last): File &quot;/Users/macuser/anaconda3/lib/python3.6/site-packages/ib_insync/ib.py&quot;, line 233, in <strong>del</strong> File &quot;/Users/macuser/anaconda3/lib/python3.6/site-packages/ib_insync/ib.py&quot;, line 281, in disconnect File &quot;/Users/macuser/anaconda3/lib/python3.6/logging/<strong>init</strong>.py&quot;, line 1306, in info File &quot;/Users/macuser/anaconda3/lib/python3.6/logging/<strong>init</strong>.py&quot;, line 1442, in _log File &quot;/Users/macuser/anaconda3/lib/python3.6/logging/<strong>init</strong>.py&quot;, line 1452, in handle File &quot;/Users/macuser/anaconda3/lib/python3.6/logging/<strong>init</strong>.py&quot;, line 1514, in callHandlers File &quot;/Users/macuser/anaconda3/lib/python3.6/logging/<strong>init</strong>.py&quot;, line 863, in handle File &quot;/Users/macuser/anaconda3/lib/python3.6/logging/<strong>init</strong>.py&quot;, line 1069, in emit File &quot;/Users/macuser/anaconda3/lib/python3.6/logging/<strong>init</strong>.py&quot;, line 1059, in _open NameError: name 'open' is not defined</p> <pre><code> | =&gt; python --version Python 3.6.4 :: Anaconda, Inc. </code></pre>
[ { "answer_id": 74510580, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 3, "selected": true, "text": "sorted_i = sorted(i, key=lambda x: abs(x[2]))\n" }, { "answer_id": 74510613, "author": "El Mehdi", "author_id": 14529779, "author_profile": "https://Stackoverflow.com/users/14529779", "pm_score": 0, "selected": false, "text": "x[2] if x[2] > 0 else -x[2] arr = [[1, 3, 8], [1, 7, 4], [1, 9, 1], [1, 0, 3], [1, 11, -2]]\nsorted_arr = sorted(arr, key=lambda x: x[2] if x[2] > 0 else -x[2])\nprint(sorted_arr) #[[1, 9, 1], [1, 11, -2], [1, 0, 3], [1, 7, 4], [1, 3, 8]]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20556632/" ]
74,510,705
<p>I have a flexbox container in which I have around 128 items(the amount can change). I'll use 14 here. They go like this:</p> <pre><code>----------------- | 1 2 3 4 | | 5 6 7 8 | | 9 10 11 12 | | 13 14 | ----------------- </code></pre> <p>what im trying to achieve is reversing the order so that if the number of items is not divisible by 4 the items are always aligned to the left and the half-empty row is always at the bottom and the items arent stretched in any way. Like this:</p> <pre><code>----------------- | 14 13 12 11 | | 10 9 8 7 | | 6 5 4 3 | | 2 1 | ----------------- </code></pre> <p>I tried doing <code>flex-wrap: wrap-reverse;</code> and <code>flex-direction: row-reverse;</code> but that leaves me with a half-empty row at the top.</p> <pre><code>----------------- | 14 13 | | 12 11 10 9 | | 8 7 6 5 | | 4 3 2 1 | ----------------- </code></pre> <p>After not finding any solution to this I resorted to javascript where I tried changing the order properly.</p> <pre><code>let itemsCount = $('.flex-container').children().length; for (let item of $('.flex-container').children()) { item.style.order = itemsCount; itemsCount--; } </code></pre> <p>Which indeed worked! Well, kinda.. Because when I press the reverse button, I can actually see how the items each move during the for loop and it looks very ugly. I need it to be instant.</p> <p>This is probably a beginner mistake so I really didn't want to ask here but after hours of unsuccessful attempts I gave up. Any feedback is very much appreciated.</p> <p><strong>Demo:</strong></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>.flexbox-container { display: flex; flex-wrap: wrap; flex-direction: row; padding-left: 30px; padding-right: 30px; padding-bottom: 60px; } .item { width: 330px; max-width: 330px; height: 400px; margin: 15px; position: relative; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="flexbox-container"&gt; &lt;div class="item item-1"&gt;&lt;/div&gt; &lt;div class="item item-2"&gt;&lt;/div&gt; &lt;div class="item item-3"&gt;&lt;/div&gt; &lt;div class="item item-4"&gt;&lt;/div&gt; &lt;div class="item item-5"&gt;&lt;/div&gt; &lt;div class="item item-6"&gt;&lt;/div&gt; &lt;div class="item item-7"&gt;&lt;/div&gt; &lt;div class="item item-8"&gt;&lt;/div&gt; &lt;div class="item item-9"&gt;&lt;/div&gt; &lt;div class="item item-10"&gt;&lt;/div&gt; &lt;div class="item item-11"&gt;&lt;/div&gt; &lt;div class="item item-12"&gt;&lt;/div&gt; &lt;div class="item item-13"&gt;&lt;/div&gt; &lt;div class="item item-14"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74510918, "author": "nourhomsi", "author_id": 4859502, "author_profile": "https://Stackoverflow.com/users/4859502", "pm_score": 0, "selected": false, "text": ".flexbox-container {\n display: flex;\n flex-wrap: wrap-reverse;\n flex-direction: row-reverse;\n}\n\n.item {\n flex: 1 1 24%;\n \n background-color: #111;\n width: 100px;\n height: 100px;\n color: white;\n border: 2px solid tomato;\n text-align: center;\n display: grid;\n place-content: center;\n font-size: 2rem;\n font-family: 'Courier New', Courier, monospace;\n} <div class=\"flexbox-container\">\n <div class=\"item item-1\">1</div>\n <div class=\"item item-2\">2</div>\n <div class=\"item item-3\">3</div>\n <div class=\"item item-4\">4</div>\n <div class=\"item item-5\">5</div>\n <div class=\"item item-6\">6</div>\n <div class=\"item item-7\">7</div>\n <div class=\"item item-8\">8</div>\n <div class=\"item item-9\">9</div>\n <div class=\"item item-10\">10</div>\n <div class=\"item item-11\">11</div>\n <div class=\"item item-12\">12</div>\n <div class=\"item item-13\">13</div>\n <div class=\"item item-14\">14</div>\n </div>" }, { "answer_id": 74511368, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 1, "selected": false, "text": "order order style width const items = document.querySelectorAll(\".item\");\nconst btnReverse = document.querySelector(\".btn.reverse\");\nconst btnNormal = document.querySelector(\".btn.normal\");\n\nbtnReverse.addEventListener(\"click\", () => items.forEach((item, index, arr)=>item.style.order = arr.length - index))\nbtnNormal.addEventListener(\"click\", () => items.forEach((item)=>item.style.order = \"\")) .flexbox-container {\n display: flex;\n flex-wrap: wrap;\n max-width: 220px;\n gap: 6px;\n margin-top: 12px;\n}\n\n.item {\n order: revert;\n width: 50px;\n max-width: 50px;\n height: 50px;\n display: flex;\n justify-content: center;\n align-items: center;\n font-size: large;\n position: relative;\n background-color: pink;\n}\n\n.btn {\n padding: 3px;\n} <button class=\"btn reverse\">REVERSE</button>\n<button class=\"btn normal\">NORMAL</button>\n\n<div class=\"flexbox-container\">\n <div class=\"item item-1\">1</div>\n <div class=\"item item-2\">2</div>\n <div class=\"item item-3\">3</div>\n <div class=\"item item-4\">4</div>\n <div class=\"item item-5\">5</div>\n <div class=\"item item-6\">6</div>\n <div class=\"item item-7\">7</div>\n <div class=\"item item-8\">8</div>\n <div class=\"item item-9\">9</div>\n <div class=\"item item-10\">10</div>\n <div class=\"item item-11\">11</div>\n <div class=\"item item-12\">12</div>\n <div class=\"item item-13\">13</div>\n <div class=\"item item-14\">14</div>\n</div>" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18565217/" ]
74,510,706
<p>Im trying to return a subset of list of dictionaries, derived from a list of dictionaries.</p> <p>Input:</p> <pre><code>dicts = [ {'name': 'Sam', 'age': 12}, {'name': 'Pete', 'age': 14}, {'name': 'Sarah', 'age': 16} ] </code></pre> <p>Im trying to get this output:</p> <pre><code>res = [ {'name': 'Sam'}, {'name': 'Pete'}, {'name': 'Sarah'} ] </code></pre> <p>So far i've been trying with this approach:</p> <pre><code> res = [] def new_dict(dicts): for i in range(len(dicts)): for k, v in dicts[i]: if dicts[i][k] == 'name' res.append(dicts[i][k] = v) print(new_dict(dicts)) </code></pre>
[ { "answer_id": 74510754, "author": "QWERTYL", "author_id": 11777402, "author_profile": "https://Stackoverflow.com/users/11777402", "pm_score": 2, "selected": false, "text": "[{'name': x['name']} for x in dicts]\n" }, { "answer_id": 74512967, "author": "BeRT2me", "author_id": 11865956, "author_profile": "https://Stackoverflow.com/users/11865956", "pm_score": 0, "selected": false, "text": "name [{'name': x['name']} for x in dicts if 'name' in x]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19307593/" ]
74,510,708
<p>I wanted to know if anyone has had success concurrently capturing images or videos on an Android device from 2 rear cameras, using this API: <a href="https://source.android.com/docs/core/camera/concurrent-streaming" rel="nofollow noreferrer">https://source.android.com/docs/core/camera/concurrent-streaming</a> . The phone I had available to test (S21) supported the API, but the only pairs of cameras supported were front+rear facing combos. In kotlin, the code to get the supported pairs is:</p> <pre><code>val cameraManager = applicationContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager val concurrentCameras = cameraManager.concurrentCameraIds </code></pre> <p>Hoping someone has a newer Samsung, Xiaomi, or Huawei phone to test if the API is supported? Thanks a lot!</p>
[ { "answer_id": 74642837, "author": "Arda Kazancı", "author_id": 5595926, "author_profile": "https://Stackoverflow.com/users/5595926", "pm_score": 1, "selected": false, "text": " fun CameraManager.directCamera(cameraId: String): LensDirect {\n val lensFacing = getCameraCharacteristics(cameraId).get(CameraCharacteristics.LENS_FACING)\n return when (lensFacing) {\n CameraMetadata.LENS_FACING_FRONT -> LensDirect.FRONT\n CameraMetadata.LENS_FACING_BACK -> LensDirect.BACK\n else -> throw IllegalArgumentException(\"unknown direction\")\n }\n }\n" }, { "answer_id": 74648773, "author": "Erhan URGUN", "author_id": 9476192, "author_profile": "https://Stackoverflow.com/users/9476192", "pm_score": 0, "selected": false, "text": "// CameraManager.java\npublic class CameraManager {\n private static final String TAG = \"CameraManager\";\n private static final boolean DEBUG = false;\n\n private final Context mContext;\n private final CameraManagerGlobal mCameraManagerGlobal;\n\n /**\n * Create a new CameraManager instance.\n *\n * @param context the application context\n */\n public CameraManager(Context context) {\n mContext = context;\n mCameraManagerGlobal = CameraManagerGlobal.getInstance();\n }\n\n /**\n * Return the list of camera ids that match the given facing.\n *\n * @param facing the facing to match\n * @return the list of camera ids that match the given facing\n */\n public String[] getCameraIdList(int facing) {\n return mCameraManagerGlobal.getCameraIdList(facing);\n }\n\n /**\n * Return the list of camera ids that match the given facing.\n *\n * @return the list of camera ids that match the given facing\n */\n public String[] getCameraIdList() {\n return mCameraManagerGlobal.getCameraIdList();\n }\n\n /**\n * Return the characteristics for the given camera id.\n *\n * @param cameraId the id of the camera to get the characteristics for\n * @return the characteristics for the given camera id\n * @throws CameraAccessException if the camera id is invalid\n */\n public CameraCharacteristics getCameraCharacteristics(String cameraId)\n throws CameraAccessException {\n return mCameraManagerGlobal.getCameraCharacteristics(cameraId);\n }\n\n /**\n * Open a connection to a camera device.\n *\n * <p>Once the camera device is opened, the camera device object can be used to\n * create capture sessions and capture requests.</p>\n *\n * <p>Opening a camera device is an asynchronous operation. The result of the\n * operation is delivered to the given {@link CameraDevice.StateCallback}.</p>\n *\n * <p>Opening a camera device may take some time, especially if the camera device\n * is currently in use by another camera client. The camera service will send\n * the result of the operation to the given callback on the application's main\n * thread.</p>\n *\n * <p>Once the camera device is opened, it can be used to create capture sessions\n * and capture requests. The camera device can be closed by calling\n * {@link CameraDevice#close}.</p>\n *\n * @param cameraId the id of the camera device to open\n * @param stateCallback the callback to receive the result of the open operation\n * @param handler the handler on which the callback should be invoked, or null to use the\n * application's main thread\n * @throws CameraAccessException if the camera id is invalid, or the camera device is in use\n * by a higher-priority camera API client, or the camera device\n * could not be opened due to a device policy\n * @throws IllegalArgumentException if the stateCallback is null\n * @throws SecurityException if the application does not have permission to access the camera\n * device\n */\n public void openCamera(String cameraId, CameraDevice.StateCallback stateCallback,\n Handler handler) throws CameraAccessException {\n if (stateCallback == null) {\n throw new IllegalArgumentException(\"callback was null\");\n }\n\n if (DEBUG) {\n Log.v(TAG, \"Opening camera \" + cameraId);\n }\n\n mCameraManagerGlobal.getCameraDeviceUserAsync(cameraId, stateCallback, handler,\n mContext.getOpPackageName(), mContext.getAttributionTag());\n }\n \n}\n" }, { "answer_id": 74650381, "author": "regex", "author_id": 9470979, "author_profile": "https://Stackoverflow.com/users/9470979", "pm_score": 0, "selected": false, "text": "CAMERA_INFO_SUPPORTED_CONCURRENT_STREAM_CONFIGURATIONS concurrentCameraIds CameraManager" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2023394/" ]
74,510,769
<pre><code>const obj = { uid: &quot;893212&quot;, a: {name: &quot;Down here!&quot;, uid: &quot;1231&quot;}, b: { c: {uid: &quot;5965&quot;}, name: &quot;bud name&quot;, }, d: {name: &quot;doodle name&quot;}, e: {name: &quot;alexa name&quot;}, f: [&quot;kk&quot;, &quot;jj&quot;], g: [ { h: {uid: &quot;47895&quot;}, i: {uid: &quot;4785&quot;} }, { j: {uid: &quot;4895&quot;} } ] }; </code></pre> <p>in the above object if &quot;uid&quot; exist its value should be applied to its parent as a value. result should be as below</p> <pre><code>var result = { uid: &quot;893212&quot;, a: &quot;1231&quot;, b: {c: &quot;5965&quot;, name: &quot;bud name&quot;}, d: {name: &quot;doodle name&quot;}, e: {name: &quot;alexa name&quot;}, f: [&quot;kk&quot;, &quot;jj&quot;], g: [ {h: &quot;47895&quot;, i: &quot;4795&quot;}, {j: &quot;4895&quot;} ] } </code></pre> <p>I tried to use recursive function to manipulate object.</p> <pre><code>const mapObj = (obj = {}) =&gt; { if (isObject(obj)) { const entries = Object.entries(obj); for (let i = 0; i &lt; entries.length; i += 1) { const [objK, objV] = entries[i]; if (isObject(objV) &amp;&amp; 'uid' in objV) { obj[objK] = objV['uid']; } else if(isObject(objV)){ findNestedObject(objV); } else if(isArray(objV)) { objV.forEach(val =&gt; { findNestedObject(val); }) } } } }; </code></pre> <p>is there any simple way to do it and array of objects are converted</p>
[ { "answer_id": 74511084, "author": "IT goldman", "author_id": 3807365, "author_profile": "https://Stackoverflow.com/users/3807365", "pm_score": -1, "selected": false, "text": "const obj = {uid:\"893212\",a:{name:\"Down here!\",uid:\"1231\"},b:{c:{uid:\"5965\"},name:\"bud name\"},d:{name:\"doodle name\"},e:{name:\"alexa name\"},f:[\"kk\",\"jj\"],g:[{h:{uid:\"47895\"},i:{uid:\"4785\"}},{j:{uid:\"4895\"}}]};\n\nfunction do_obj(obj, parent, parent_key) {\n Object.keys(obj).forEach(function(key) {\n var item = obj[key];\n if (key === 'uid' && parent) {\n parent[parent_key] = item;\n }\n if (typeof item === 'object' && item !== null) {\n do_obj(item, obj, key);\n }\n })\n}\n\ndo_obj(obj)\nconsole.log(obj) .as-console-wrapper {\n max-height: 100% !important\n}" }, { "answer_id": 74511341, "author": "Archon", "author_id": 7388203, "author_profile": "https://Stackoverflow.com/users/7388203", "pm_score": 0, "selected": false, "text": "const obj = {\n uid: \"893212\",\n a: {name: \"Down here!\", uid: \"1231\"},\n b: {\n c: {uid: \"5965\"},\n name: \"bud name\",\n }, \n d: {name: \"doodle name\"},\n e: {name: \"alexa name\"},\n f: [\"kk\", \"jj\"],\n g: [\n {\n h: {uid: \"47895\"},\n i: {uid: \"4785\"}\n },\n {\n j: {uid: \"4895\"}\n }\n ]\n};\n\nconst process = (anObject) => {\n const toReturn = {};\n Object.keys(anObject).forEach((key, index) => {\n const currentProperty = anObject[key]; \n if(Array.isArray(currentProperty)) { \n toReturn[key] = currentProperty;\n }\n else if(typeof(currentProperty) === 'object') {\n const uid = currentProperty?.uid;\n if(uid) {\n toReturn[key] = uid;\n } \n else {\n toReturn[key] = process(currentProperty);\n } \n } else {\n toReturn[key] = currentProperty;\n }\n });\n return toReturn;\n}\n\nconst target = process(obj);\nconsole.log(JSON.stringify(target, null, 2));" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12189334/" ]
74,510,794
<p>On my input component, using Tailwind css, i added this classes:</p> <pre><code>focus:ring focus:outline-none focus-visible:ring </code></pre> <p>These classes are responsible to add styles when the input is focused. Ex: <a href="https://tailwindcss.com/docs/hover-focus-and-other-states" rel="nofollow noreferrer">https://tailwindcss.com/docs/hover-focus-and-other-states</a> <br> <strong>Question</strong>: I want to disable the focus style on the left side when the input will be focused, is this possible in tailwind css?</p>
[ { "answer_id": 74517054, "author": "Tom", "author_id": 16688813, "author_profile": "https://Stackoverflow.com/users/16688813", "pm_score": 1, "selected": false, "text": "border focus:border-4 focus:border-solid focus:border-l-transparent\n" }, { "answer_id": 74521417, "author": "Ihar Aliakseyenka", "author_id": 14305076, "author_profile": "https://Stackoverflow.com/users/14305076", "pm_score": 0, "selected": false, "text": "<button class=\"focus:ring focus:[--tw-ring-shadow:var(--tw-ring-inset)_3px_0_0_calc(3px_+_var(--tw-ring-offset-width))_var(--tw-ring-color)]\"></button>\n @tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n@layer utilities {\n .ringed {\n box-shadow: 3px 0 0 3px var(--tw-ring-color);\n }\n}\n <button class=\"focus:ringed\"></button>\n ring-{color}" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12540500/" ]
74,510,810
<p>I have a vue.js 3 frontend, and I am calling a Golang backend via <code>grpc-gateway</code>. I have been at this for a while but I see light at the end of the tunnel.</p> <p>I am currently facing a CORS issue. However, I am reading conflicting information on how to handle it. Therefore, I want to post and hopefully it helps someone.</p> <p>Here is the code on how I init my mux server for GRPC (gateway)</p> <pre><code>func RunHttpServer(server *http.Server, httpEndpoint, grpcEndpoint, swaggerPath string) (err error) { server.Addr = httpEndpoint ctx, cancel := context.WithCancel(context.Background()) defer cancel() // Register gROC server endpoint mux := runtime.NewServeMux( runtime.WithErrorHandler(func(ctx context.Context, mux *runtime.ServeMux, marshaler runtime.Marshaler, w http.ResponseWriter, r *http.Request, err error, ) { s, ok := status.FromError(err) if ok { if s.Code() == codes.Unavailable { err = status.Error(codes.Unavailable, ErrUnavailable) } } runtime.DefaultHTTPErrorHandler(ctx, mux, marshaler, w, r, err) }), ) opts := []grpc.DialOption{ grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithChainUnaryInterceptor(), } if err = api.RegisterApiServiceHandlerFromEndpoint(ctx, mux, grpcEndpoint, opts); err != nil { return } swMux := http.NewServeMux() swMux.Handle(&quot;/&quot;, mux) serveSwagger(swMux, swaggerPath) server.Handler = swMux return server.ListenAndServe() } </code></pre> <p>Here is where I believe I should add the cors config, but I am not sure this is how I set it up in the server.go file..</p> <pre><code>var httpServer http.Server // Run Http Server with gRPC gateway g.Go(func() error { fmt.Println(&quot;Starting Http sever (port {}) and gRPC gateway (port {})&quot;, strconv.Itoa(cfg.Server.HTTPPort), strconv.Itoa(cfg.Server.GRPCPort), ) return rest.RunHttpServer( &amp;httpServer, &quot;:&quot;+strconv.Itoa(cfg.Server.HTTPPort), &quot;:&quot;+strconv.Itoa(cfg.Server.GRPCPort), &quot;/webapi&quot;, ) }) </code></pre> <p>error in console:</p> <pre><code>Access to XMLHttpRequest at 'http://localhost:8080/v1/test' from origin 'http://localhost:9000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' </code></pre> <p>I am not sure where to add something like</p> <pre><code>func enableCors(w *http.ResponseWriter) { (*w).Header().Set(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;) } </code></pre> <p>and I feel the golang GRPC gateway should have something built in but I cannot find anything?</p> <p>Any advice would be greatly appreciated.</p> <p>----- update 1 -----</p> <p>I have tried</p> <pre><code>func enableCors(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set(&quot;Access-Control-Allow-Origin&quot;, &quot;http://localhost:9000&quot;) w.Header().Set(&quot;Access-Control-Allow-Methods&quot;, &quot;GET, PUT, POST, DELETE, HEAD, OPTIONS&quot;) h.ServeHTTP(w, r) }) } </code></pre> <p>and</p> <pre><code>func enableCors(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;) w.Header().Set(&quot;Access-Control-Allow-Methods&quot;, &quot;GET, PUT, POST, DELETE, HEAD, OPTIONS&quot;) h.ServeHTTP(w, r) }) } </code></pre> <p>and</p> <pre><code>func enableCors(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set(&quot;Access-Control-Allow-Origin&quot;, &quot;http://localhost&quot;) w.Header().Set(&quot;Access-Control-Allow-Methods&quot;, &quot;GET, PUT, POST, DELETE, HEAD, OPTIONS&quot;) h.ServeHTTP(w, r) }) } </code></pre> <p>in conjuction with</p> <pre><code>func serveSwagger(mux *http.ServeMux, swaggerPath string) { fileServer := http.FileServer(http.Dir(swaggerPath)) prefix := &quot;/swagger-ui&quot; mux.Handle(prefix, http.StripPrefix(prefix, fileServer)) } </code></pre> <p>and still have the same issue.. Very frustrating</p>
[ { "answer_id": 74538299, "author": "Emin Laletovic", "author_id": 7567579, "author_profile": "https://Stackoverflow.com/users/7567579", "pm_score": 1, "selected": false, "text": "swMux func enableCors(h http.Handler) http.Handler {\n return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\n h.ServeHTTP(w, r)\n })\n}\n RunHttpServer swMux := http.NewServeMux()\nswMux.Handle(\"/\", mux)\nserveSwagger(swMux, swaggerPath)\n\nserver.Handler = enableCors(swMux)\n grpc-gateway" }, { "answer_id": 74572349, "author": "nj_", "author_id": 5993518, "author_profile": "https://Stackoverflow.com/users/5993518", "pm_score": 2, "selected": true, "text": "OPTIONS enableCors OPTIONS < HTTP/1.1 501 Not Implemented\n< Content-Type: application/json\n< Vary: Origin\n< Date: Fri, 25 Nov 2022 11:17:52 GMT\n< Content-Length: 55\n< \n{\"code\":12,\"message\":\"Method Not Allowed\",\"details\":[]}\n func enableCors(h http.Handler) http.Handler {\n return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Access-Control-Allow-Origin\", \"http://localhost:9000\")\n w.Header().Set(\"Access-Control-Allow-Methods\", \"GET, PUT, POST, DELETE, HEAD, OPTIONS\")\n if r.Method == http.MethodOptions {\n w.WriteHeader(http.StatusNoContent)\n return\n }\n h.ServeHTTP(w, r)\n })\n}\n github.com/rs/cors server.Handler = cors.AllowAll().Handler(swMux)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4753897/" ]
74,510,816
<p>I have sparsed dataframe that I needed to convert it to list which I already did it. Now I want to transform this list to dictionary, so I can do key-value comparison in my actual use case. To do so, I attempted to convert list to dictionary but I have value error instead. How can I do this correctly in python? Does anyone knows what is correct way to do this in python?</p> <p><strong>reproducible data and my attempt</strong></p> <pre><code>mydict={'code0': {0: 'nan', 1: &quot; '40'&quot;, 2: &quot; '98'&quot;, 3: &quot; '98'&quot;, 4: &quot; '52'&quot;, 5: &quot; '52'&quot;, 6: &quot; '52'&quot;, 7: &quot; '52'&quot;, 8: &quot; '40'&quot;, 9: &quot; '58'&quot;}, 'code1': {0: &quot; ('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL')&quot;, 1: 'nan', 2: &quot; ('ATT','NC')&quot;, 3: &quot; ('ATT','VA','NC')&quot;, 4: &quot; 'NC'&quot;, 5: &quot; 'NC'&quot;, 6: &quot; 'NC'&quot;, 7: &quot; 'NC'&quot;, 8: &quot; 'VA'&quot;, 9: &quot; 'CE'&quot;}, 'code2': {0: 'nan', 1: 'nan', 2: &quot; ('103','104','105','106','31')&quot;, 3: &quot; ('104','105','106','31')&quot;, 4: &quot; '109'&quot;, 5: &quot; '109'&quot;, 6: &quot; '109'&quot;, 7: &quot; '109'&quot;, 8: &quot; '11'&quot;, 9: &quot; ('109')&quot;}, 'code3': {0: 'nan', 1: &quot; '518'&quot;, 2: &quot; '810'&quot;, 3: 'nan', 4: &quot; ('610','620','682','642','621','611')&quot;, 5: &quot; ('396','340','394','393','240')&quot;, 6: &quot; ('612','790','110')&quot;, 7: &quot; ('730','320','350','379','812','374')&quot;, 8: &quot; ('113','174','131','115')&quot;, 9: &quot; ('423','114')&quot;}, 'code4': {0: 'nan', 1: 'nan', 2: &quot; 'computer science'&quot;, 3: &quot; 'computer science'&quot;, 4: &quot; 'biology'&quot;, 5: &quot; 'biology'&quot;, 6: &quot;biology'&quot;, 7: &quot;biology'&quot;, 8: 'nan', 9: 'nan'}, 'code5': {0: 'nan', 1: 'nan', 2: 'nan', 3: 'nan', 4: 'nan', 5: &quot; ('12','18')&quot;, 6: &quot; ('12','16','18','19')&quot;, 7: &quot; ('12','18','19')&quot;, 8: &quot; ('11','19','31')&quot;, 9: &quot; '31'&quot;}, 'code6': {0: 'nan', 1: &quot; '594'&quot;, 2: 'nan', 3: 'nan', 4: &quot; ('712','479','297','639','452','172')&quot;, 5: 'nan', 6: &quot; ('285','295','236','239','269','284','237')&quot;, 7: 'nan', 8: &quot; ('164','157','388','158')&quot;, 9: &quot; ('372','238')&quot;}, 'rules_desc': {0: 'rules1', 1: 'rules2', 2: 'rules2', 3: 'rules2', 4: 'rules2', 5: 'rules2', 6: 'rules2', 7: 'rules2', 8: 'rules2', 9: 'rules2'}} mydf=pd.DataFrame.from_dict(my_dict) cols = mydf.columns.values res=[&quot;,&quot;.join(&quot;{}:{}&quot;.format(*t) for t in zip(cols, row)) for _, row in mydf[cols].iterrows()] res=[list(s.split('&quot;&quot;')) for s in res] intconv = lambda x: (x[0], int(x[1])) for s in res: b = dict([i.split(':') for i in s]) final = dict((k, int(v)) for k, v in b.items()) print(final) </code></pre> <p>but I have value error as follow:</p> <blockquote> <p>--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Input In [60], in &lt;cell line: 9&gt;() 8 intconv = lambda x: (x[0], int(x[1])) 9 for s in res: ---&gt; 10 b = dict([i.split(':') for i in s]) 11 final = dict((k, int(v)) for k, v in b.items()) 12 print(final)</p> <p>ValueError: dictionary update sequence element #0 has length 9; 2 is required</p> </blockquote> <p>not sure how to debug this, seems value can't accept list of string. the reason why I am doing this because I want to do key-value comparison. Does anyone know any workaround on this?</p> <p><strong>desired output</strong></p> <p>I don't want to try hard here. basically I want to create list of dictionary for each row of dataframe, where column_name is key and column value is value. I know in some column, its value is list of string, that's why I don't know how to create dictionary from it. here is the sample dictionary that I want:</p> <pre><code>output_dict={{'code0':'nan', 'code1': ('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL'), 'code2':'nan', 'code3':'nan', 'code4':'nan', 'code5':'nan', 'code6':'nan','rules_desc': rules1}, {'code0': 40, 'code1':'nan','code2':'nan','code3':518, 'code4':'nan', 'code5':'nan','code6':594, 'rules_desc': rules2}, ... } </code></pre> <p>can we get dictionary something like this? because I want to create such list or dictionary to filter out another big dataframe. Any help would be appreciated. thanks</p>
[ { "answer_id": 74511145, "author": "lmaayanl", "author_id": 5714034, "author_profile": "https://Stackoverflow.com/users/5714034", "pm_score": 1, "selected": false, "text": "mydf.to_dict(orient='records') \n" }, { "answer_id": 74511186, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 3, "selected": true, "text": "mydf ast.literal_eval int() \nfrom ast import literal_eval\n\nout = []\nfor _, row in mydf.iterrows():\n tmp = {}\n for k, v in zip(row.index, row):\n try:\n tmp[k] = literal_eval(v)\n\n if isinstance(tmp[k], str) and tmp[k].isnumeric():\n tmp[k] = int(tmp[k])\n except (ValueError, SyntaxError):\n tmp[k] = v\n\n out.append(tmp)\n\nprint(out)\n [\n {\n \"code0\": \"nan\",\n \"code1\": (\"VA\", \"HC\", \"NIH\", \"SAP\", \"AUS\", \"HOL\", \"ATT\", \"COL\", \"UCL\"),\n \"code2\": \"nan\",\n \"code3\": \"nan\",\n \"code4\": \"nan\",\n \"code5\": \"nan\",\n \"code6\": \"nan\",\n \"rules_desc\": \"rules1\",\n },\n {\n \"code0\": 40,\n \"code1\": \"nan\",\n \"code2\": \"nan\",\n \"code3\": 518,\n \"code4\": \"nan\",\n \"code5\": \"nan\",\n \"code6\": 594,\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 98,\n \"code1\": (\"ATT\", \"NC\"),\n \"code2\": (\"103\", \"104\", \"105\", \"106\", \"31\"),\n \"code3\": 810,\n \"code4\": \"computer science\",\n \"code5\": \"nan\",\n \"code6\": \"nan\",\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 98,\n \"code1\": (\"ATT\", \"VA\", \"NC\"),\n \"code2\": (\"104\", \"105\", \"106\", \"31\"),\n \"code3\": \"nan\",\n \"code4\": \"computer science\",\n \"code5\": \"nan\",\n \"code6\": \"nan\",\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 52,\n \"code1\": \"NC\",\n \"code2\": 109,\n \"code3\": (\"610\", \"620\", \"682\", \"642\", \"621\", \"611\"),\n \"code4\": \"biology\",\n \"code5\": \"nan\",\n \"code6\": (\"712\", \"479\", \"297\", \"639\", \"452\", \"172\"),\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 52,\n \"code1\": \"NC\",\n \"code2\": 109,\n \"code3\": (\"396\", \"340\", \"394\", \"393\", \"240\"),\n \"code4\": \"biology\",\n \"code5\": (\"12\", \"18\"),\n \"code6\": \"nan\",\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 52,\n \"code1\": \"NC\",\n \"code2\": 109,\n \"code3\": (\"612\", \"790\", \"110\"),\n \"code4\": \"biology'\",\n \"code5\": (\"12\", \"16\", \"18\", \"19\"),\n \"code6\": (\"285\", \"295\", \"236\", \"239\", \"269\", \"284\", \"237\"),\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 52,\n \"code1\": \"NC\",\n \"code2\": 109,\n \"code3\": (\"730\", \"320\", \"350\", \"379\", \"812\", \"374\"),\n \"code4\": \"biology'\",\n \"code5\": (\"12\", \"18\", \"19\"),\n \"code6\": \"nan\",\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 40,\n \"code1\": \"VA\",\n \"code2\": 11,\n \"code3\": (\"113\", \"174\", \"131\", \"115\"),\n \"code4\": \"nan\",\n \"code5\": (\"11\", \"19\", \"31\"),\n \"code6\": (\"164\", \"157\", \"388\", \"158\"),\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 58,\n \"code1\": \"CE\",\n \"code2\": 109,\n \"code3\": (\"423\", \"114\"),\n \"code4\": \"nan\",\n \"code5\": 31,\n \"code6\": (\"372\", \"238\"),\n \"rules_desc\": \"rules2\",\n },\n]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7114383/" ]
74,510,824
<p>I have a roll the dice game I have to make for school, I have come far.. the game is working but my problem is that I have to make a highscore system and restrict 6,7,8,9 (if the total is any of those depends on what the player is choosing) it fails the game and you start over.</p> <p>I just wanna make a highscore and that fail part for my project.</p> <p>I have done this so far:</p> <pre class="lang-js prettyprint-override"><code>let images = [&quot;dice1.png&quot;, &quot;dice2.png&quot;, &quot;dice3.png&quot;, &quot;dice4.png&quot;, &quot;dice5.png&quot;, &quot;dice6.png&quot;]; let dice = document.querySelectorAll(&quot;img&quot;); function roll(){ dice.forEach(function(die){ die.classList.add(&quot;shake&quot;); }); setTimeout(function(){ dice.forEach(function(die){ die.classList.remove(&quot;shake&quot;); }); let dieOneValue = Math.floor(Math.random()*6) ; let dieTwoValue = Math.floor(Math.random()*6) ; console.log(dieOneValue,dieTwoValue); document.querySelector(&quot;#die-1&quot;).setAttribute (&quot;src&quot;, images[dieOneValue]); document.querySelector(&quot;#die-2&quot;).setAttribute (&quot;src&quot;, images[dieTwoValue]); document.querySelector(&quot;#total&quot;).innerHTML = &quot;Du rullade &quot; + ( (dieOneValue +1) + (dieTwoValue + 1 ) ) }, 1000 ); } </code></pre> <p>And this is the part they only can choose a number or els they get a error message.</p> <pre class="lang-js prettyprint-override"><code>var numb=document.forms['myform']['num']; var error=document.getElementById('error'); function validation() { if(numb.value=='') { error.innerHTML=&quot;Bara nummer funkar&quot;; error.style.display=&quot;block&quot;; return false; } if(numb.value&gt;9) { error.innerHTML=&quot;Bara nummer 6,7,8,9 funkar&quot;; error.style.display=&quot;block&quot;; return false; } if (numb.value&lt;6) { error.innerHTML=&quot;Bara nummer 6,7,8,9 funkar&quot;; error.style.display=&quot;block&quot;; return false; } return true; } </code></pre>
[ { "answer_id": 74511145, "author": "lmaayanl", "author_id": 5714034, "author_profile": "https://Stackoverflow.com/users/5714034", "pm_score": 1, "selected": false, "text": "mydf.to_dict(orient='records') \n" }, { "answer_id": 74511186, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 3, "selected": true, "text": "mydf ast.literal_eval int() \nfrom ast import literal_eval\n\nout = []\nfor _, row in mydf.iterrows():\n tmp = {}\n for k, v in zip(row.index, row):\n try:\n tmp[k] = literal_eval(v)\n\n if isinstance(tmp[k], str) and tmp[k].isnumeric():\n tmp[k] = int(tmp[k])\n except (ValueError, SyntaxError):\n tmp[k] = v\n\n out.append(tmp)\n\nprint(out)\n [\n {\n \"code0\": \"nan\",\n \"code1\": (\"VA\", \"HC\", \"NIH\", \"SAP\", \"AUS\", \"HOL\", \"ATT\", \"COL\", \"UCL\"),\n \"code2\": \"nan\",\n \"code3\": \"nan\",\n \"code4\": \"nan\",\n \"code5\": \"nan\",\n \"code6\": \"nan\",\n \"rules_desc\": \"rules1\",\n },\n {\n \"code0\": 40,\n \"code1\": \"nan\",\n \"code2\": \"nan\",\n \"code3\": 518,\n \"code4\": \"nan\",\n \"code5\": \"nan\",\n \"code6\": 594,\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 98,\n \"code1\": (\"ATT\", \"NC\"),\n \"code2\": (\"103\", \"104\", \"105\", \"106\", \"31\"),\n \"code3\": 810,\n \"code4\": \"computer science\",\n \"code5\": \"nan\",\n \"code6\": \"nan\",\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 98,\n \"code1\": (\"ATT\", \"VA\", \"NC\"),\n \"code2\": (\"104\", \"105\", \"106\", \"31\"),\n \"code3\": \"nan\",\n \"code4\": \"computer science\",\n \"code5\": \"nan\",\n \"code6\": \"nan\",\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 52,\n \"code1\": \"NC\",\n \"code2\": 109,\n \"code3\": (\"610\", \"620\", \"682\", \"642\", \"621\", \"611\"),\n \"code4\": \"biology\",\n \"code5\": \"nan\",\n \"code6\": (\"712\", \"479\", \"297\", \"639\", \"452\", \"172\"),\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 52,\n \"code1\": \"NC\",\n \"code2\": 109,\n \"code3\": (\"396\", \"340\", \"394\", \"393\", \"240\"),\n \"code4\": \"biology\",\n \"code5\": (\"12\", \"18\"),\n \"code6\": \"nan\",\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 52,\n \"code1\": \"NC\",\n \"code2\": 109,\n \"code3\": (\"612\", \"790\", \"110\"),\n \"code4\": \"biology'\",\n \"code5\": (\"12\", \"16\", \"18\", \"19\"),\n \"code6\": (\"285\", \"295\", \"236\", \"239\", \"269\", \"284\", \"237\"),\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 52,\n \"code1\": \"NC\",\n \"code2\": 109,\n \"code3\": (\"730\", \"320\", \"350\", \"379\", \"812\", \"374\"),\n \"code4\": \"biology'\",\n \"code5\": (\"12\", \"18\", \"19\"),\n \"code6\": \"nan\",\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 40,\n \"code1\": \"VA\",\n \"code2\": 11,\n \"code3\": (\"113\", \"174\", \"131\", \"115\"),\n \"code4\": \"nan\",\n \"code5\": (\"11\", \"19\", \"31\"),\n \"code6\": (\"164\", \"157\", \"388\", \"158\"),\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 58,\n \"code1\": \"CE\",\n \"code2\": 109,\n \"code3\": (\"423\", \"114\"),\n \"code4\": \"nan\",\n \"code5\": 31,\n \"code6\": (\"372\", \"238\"),\n \"rules_desc\": \"rules2\",\n },\n]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20556780/" ]
74,510,845
<p>So I am trying to build a LAMP-app with Docker because I always have issues with installing PHP and such on my local machine.</p> <p>Currently I am following a tutorial from Brad Traversy: PHP Crash Course on youtube and I am getting stuck at the part where he explains 'filehandling'. Part 14.</p> <p>This is the error I am getting:</p> <pre><code>Warning: fopen(users.txt): Failed to open stream: Permission denied in /var/www/html/filehandling.php on line 13 </code></pre> <pre><code>Fatal error: Uncaught TypeError: fwrite(): Argument #1 ($stream) must be of type resource, bool given in /var/www/html/filehandling.php:15 Stack trace: #0 /var/www/html/filehandling.php(15): fwrite(false, 'Brad') #1 {main} thrown in /var/www/html/filehandling.php on line 15 </code></pre> <p>I also added screenshots of the error and file itself, my Dockerfile, and the docker-compose.yaml file.</p> <p><a href="https://i.stack.imgur.com/De9cj.png" rel="nofollow noreferrer">errormessage in browser</a></p> <p><a href="https://i.stack.imgur.com/7Ojse.png" rel="nofollow noreferrer">filehandling.php</a></p> <p><a href="https://i.stack.imgur.com/K82j0.png" rel="nofollow noreferrer">Dockerfile</a></p> <p><a href="https://i.stack.imgur.com/ckXZk.png" rel="nofollow noreferrer">docker-compose.yml</a></p> <p>When I look up the user with 'whoami', I get user'root' in the Docker container. When I try 'whoami' outside of the container, I get my regular username.</p> <pre><code>I have tried changing permissions with chmod 755 and chmod 777 inside the Dockerfile, but that didn't work either. </code></pre> <p>Is there anybody who can help?</p> <p>Thanks so much in advance!</p> <p>Following @hakre advice: This is what I get when I do ls -altrh inside of the containers shell:</p> <p>This is what I get when I do ls -altrh inside the container:</p> <pre><code># ls -altrh total 68K drwxr-xr-x 1 root root 4.0K Sep 13 09:45 .. -rwxr-xr-x 1 1000 1000 14 Oct 14 14:57 phpinfo.php drwxr-xr-x 2 1000 1000 4.0K Oct 14 18:51 db -rwxr-xr-x 1 1000 1000 0 Oct 15 17:18 .env -rwxr-xr-x 1 1000 1000 90 Oct 15 17:23 .env.example -rwxr-xr-x 1 1000 1000 5 Oct 15 17:25 .gitignore -rwxr-xr-x 1 1000 1000 3.7K Nov 9 17:15 variables.php -rwxr-xr-x 1 1000 1000 468 Nov 9 17:32 getpost.php -rwxr-xr-x 1 1000 1000 599 Nov 14 15:15 sanitizinginput.php -rwxr-xr-x 1 1000 1000 167 Nov 14 15:38 cookies.php -rwxr-xr-x 1 1000 1000 904 Nov 14 16:03 sessions.php -rwxr-xr-x 1 1000 1000 225 Nov 19 17:10 package.json drwxr-xr-x 4 1000 1000 4.0K Nov 20 15:26 . -rwxr-xr-x 1 1000 1000 734 Nov 20 15:26 docker-compose.yml -rwxr-xr-x 1 1000 1000 335 Nov 20 15:26 index.php drwxr-xr-x 2 1000 1000 4.0K Nov 20 16:29 extras -rwxr-xr-x 1 1000 1000 283 Nov 20 18:07 filehandling.php -rwxr-xr-x 1 1000 1000 73 Nov 20 18:12 Dockerfile # </code></pre> <p>Edit: Also this is what I get when looking for the user of apache in the container's shell:</p> <pre><code># ps aux | egrep '(apache|httpd)' root 1 0.3 0.1 219560 28892 ? Ss 09:28 0:00 apache2 -DFOREGROUND www-data 23 0.0 0.0 219592 7804 ? S 09:28 0:00 apache2 -DFOREGROUND www-data 24 0.0 0.0 219592 7804 ? S 09:28 0:00 apache2 -DFOREGROUND www-data 25 0.0 0.0 219592 7804 ? S 09:28 0:00 apache2 -DFOREGROUND www-data 26 0.0 0.0 219592 7804 ? S 09:28 0:00 apache2 -DFOREGROUND www-data 27 0.0 0.0 219592 7804 ? S 09:28 0:00 apache2 -DFOREGROUND root 35 0.0 0.0 3180 652 pts/0 S+ 09:29 0:00 grep -E (apache|httpd) </code></pre> <p>And tried changing these in the Dockerfile, not at the same time of course:</p> <pre><code>RUN chown -R www-data /var/www/html/ and this: RUN chown -R www-data:www-data /var/www/html/ and this: RUN chown 777 /var/www/html and this: RUN chown 777 www-data /var/www/html </code></pre> <p>But no success –</p>
[ { "answer_id": 74511145, "author": "lmaayanl", "author_id": 5714034, "author_profile": "https://Stackoverflow.com/users/5714034", "pm_score": 1, "selected": false, "text": "mydf.to_dict(orient='records') \n" }, { "answer_id": 74511186, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 3, "selected": true, "text": "mydf ast.literal_eval int() \nfrom ast import literal_eval\n\nout = []\nfor _, row in mydf.iterrows():\n tmp = {}\n for k, v in zip(row.index, row):\n try:\n tmp[k] = literal_eval(v)\n\n if isinstance(tmp[k], str) and tmp[k].isnumeric():\n tmp[k] = int(tmp[k])\n except (ValueError, SyntaxError):\n tmp[k] = v\n\n out.append(tmp)\n\nprint(out)\n [\n {\n \"code0\": \"nan\",\n \"code1\": (\"VA\", \"HC\", \"NIH\", \"SAP\", \"AUS\", \"HOL\", \"ATT\", \"COL\", \"UCL\"),\n \"code2\": \"nan\",\n \"code3\": \"nan\",\n \"code4\": \"nan\",\n \"code5\": \"nan\",\n \"code6\": \"nan\",\n \"rules_desc\": \"rules1\",\n },\n {\n \"code0\": 40,\n \"code1\": \"nan\",\n \"code2\": \"nan\",\n \"code3\": 518,\n \"code4\": \"nan\",\n \"code5\": \"nan\",\n \"code6\": 594,\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 98,\n \"code1\": (\"ATT\", \"NC\"),\n \"code2\": (\"103\", \"104\", \"105\", \"106\", \"31\"),\n \"code3\": 810,\n \"code4\": \"computer science\",\n \"code5\": \"nan\",\n \"code6\": \"nan\",\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 98,\n \"code1\": (\"ATT\", \"VA\", \"NC\"),\n \"code2\": (\"104\", \"105\", \"106\", \"31\"),\n \"code3\": \"nan\",\n \"code4\": \"computer science\",\n \"code5\": \"nan\",\n \"code6\": \"nan\",\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 52,\n \"code1\": \"NC\",\n \"code2\": 109,\n \"code3\": (\"610\", \"620\", \"682\", \"642\", \"621\", \"611\"),\n \"code4\": \"biology\",\n \"code5\": \"nan\",\n \"code6\": (\"712\", \"479\", \"297\", \"639\", \"452\", \"172\"),\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 52,\n \"code1\": \"NC\",\n \"code2\": 109,\n \"code3\": (\"396\", \"340\", \"394\", \"393\", \"240\"),\n \"code4\": \"biology\",\n \"code5\": (\"12\", \"18\"),\n \"code6\": \"nan\",\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 52,\n \"code1\": \"NC\",\n \"code2\": 109,\n \"code3\": (\"612\", \"790\", \"110\"),\n \"code4\": \"biology'\",\n \"code5\": (\"12\", \"16\", \"18\", \"19\"),\n \"code6\": (\"285\", \"295\", \"236\", \"239\", \"269\", \"284\", \"237\"),\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 52,\n \"code1\": \"NC\",\n \"code2\": 109,\n \"code3\": (\"730\", \"320\", \"350\", \"379\", \"812\", \"374\"),\n \"code4\": \"biology'\",\n \"code5\": (\"12\", \"18\", \"19\"),\n \"code6\": \"nan\",\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 40,\n \"code1\": \"VA\",\n \"code2\": 11,\n \"code3\": (\"113\", \"174\", \"131\", \"115\"),\n \"code4\": \"nan\",\n \"code5\": (\"11\", \"19\", \"31\"),\n \"code6\": (\"164\", \"157\", \"388\", \"158\"),\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 58,\n \"code1\": \"CE\",\n \"code2\": 109,\n \"code3\": (\"423\", \"114\"),\n \"code4\": \"nan\",\n \"code5\": 31,\n \"code6\": (\"372\", \"238\"),\n \"rules_desc\": \"rules2\",\n },\n]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20556673/" ]
74,510,859
<p>I am new to programming and i want to develop a application but i need show to users very large text in my application. I am not sure widget.NewRichTextWithText() is for this purpose. This code working as i expected.</p> <pre><code>package main import ( &quot;strings&quot; &quot;fyne.io/fyne/v2&quot; &quot;fyne.io/fyne/v2/app&quot; &quot;fyne.io/fyne/v2/container&quot; &quot;fyne.io/fyne/v2/widget&quot; ) func main() { a := app.New() w := a.NewWindow(&quot;Some Practice&quot;) w.Resize(fyne.NewSize(400, 400)) text := widget.NewRichTextWithText((strings.Repeat(&quot;this\n&quot;, 100))) c := container.NewMax(container.NewVScroll(text)) w.SetContent(c) w.ShowAndRun() } </code></pre> <p>But this one does not work.</p> <pre><code>package main import ( &quot;image/color&quot; &quot;strings&quot; &quot;fyne.io/fyne/v2&quot; &quot;fyne.io/fyne/v2/app&quot; &quot;fyne.io/fyne/v2/canvas&quot; &quot;fyne.io/fyne/v2/container&quot; ) func main() { a := app.New() w := a.NewWindow(&quot;Some Practice&quot;) w.Resize(fyne.NewSize(400, 400)) text := canvas.NewText(strings.Repeat(&quot;this\n&quot;, 100), color.White) c := container.NewMax(container.NewVScroll(text)) w.SetContent(c) w.ShowAndRun() } </code></pre> <p>Becuase the &quot; \n &quot; showing as invalid character instead of new line when i run the application. My aim is showing very large text &quot;top to bottom scrollable&quot; with canvas.NewText() but &quot; \n &quot; character does not work. Instead of top to bottom scrollable showing text it is printing this as this?this?this?</p>
[ { "answer_id": 74511145, "author": "lmaayanl", "author_id": 5714034, "author_profile": "https://Stackoverflow.com/users/5714034", "pm_score": 1, "selected": false, "text": "mydf.to_dict(orient='records') \n" }, { "answer_id": 74511186, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 3, "selected": true, "text": "mydf ast.literal_eval int() \nfrom ast import literal_eval\n\nout = []\nfor _, row in mydf.iterrows():\n tmp = {}\n for k, v in zip(row.index, row):\n try:\n tmp[k] = literal_eval(v)\n\n if isinstance(tmp[k], str) and tmp[k].isnumeric():\n tmp[k] = int(tmp[k])\n except (ValueError, SyntaxError):\n tmp[k] = v\n\n out.append(tmp)\n\nprint(out)\n [\n {\n \"code0\": \"nan\",\n \"code1\": (\"VA\", \"HC\", \"NIH\", \"SAP\", \"AUS\", \"HOL\", \"ATT\", \"COL\", \"UCL\"),\n \"code2\": \"nan\",\n \"code3\": \"nan\",\n \"code4\": \"nan\",\n \"code5\": \"nan\",\n \"code6\": \"nan\",\n \"rules_desc\": \"rules1\",\n },\n {\n \"code0\": 40,\n \"code1\": \"nan\",\n \"code2\": \"nan\",\n \"code3\": 518,\n \"code4\": \"nan\",\n \"code5\": \"nan\",\n \"code6\": 594,\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 98,\n \"code1\": (\"ATT\", \"NC\"),\n \"code2\": (\"103\", \"104\", \"105\", \"106\", \"31\"),\n \"code3\": 810,\n \"code4\": \"computer science\",\n \"code5\": \"nan\",\n \"code6\": \"nan\",\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 98,\n \"code1\": (\"ATT\", \"VA\", \"NC\"),\n \"code2\": (\"104\", \"105\", \"106\", \"31\"),\n \"code3\": \"nan\",\n \"code4\": \"computer science\",\n \"code5\": \"nan\",\n \"code6\": \"nan\",\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 52,\n \"code1\": \"NC\",\n \"code2\": 109,\n \"code3\": (\"610\", \"620\", \"682\", \"642\", \"621\", \"611\"),\n \"code4\": \"biology\",\n \"code5\": \"nan\",\n \"code6\": (\"712\", \"479\", \"297\", \"639\", \"452\", \"172\"),\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 52,\n \"code1\": \"NC\",\n \"code2\": 109,\n \"code3\": (\"396\", \"340\", \"394\", \"393\", \"240\"),\n \"code4\": \"biology\",\n \"code5\": (\"12\", \"18\"),\n \"code6\": \"nan\",\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 52,\n \"code1\": \"NC\",\n \"code2\": 109,\n \"code3\": (\"612\", \"790\", \"110\"),\n \"code4\": \"biology'\",\n \"code5\": (\"12\", \"16\", \"18\", \"19\"),\n \"code6\": (\"285\", \"295\", \"236\", \"239\", \"269\", \"284\", \"237\"),\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 52,\n \"code1\": \"NC\",\n \"code2\": 109,\n \"code3\": (\"730\", \"320\", \"350\", \"379\", \"812\", \"374\"),\n \"code4\": \"biology'\",\n \"code5\": (\"12\", \"18\", \"19\"),\n \"code6\": \"nan\",\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 40,\n \"code1\": \"VA\",\n \"code2\": 11,\n \"code3\": (\"113\", \"174\", \"131\", \"115\"),\n \"code4\": \"nan\",\n \"code5\": (\"11\", \"19\", \"31\"),\n \"code6\": (\"164\", \"157\", \"388\", \"158\"),\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": 58,\n \"code1\": \"CE\",\n \"code2\": 109,\n \"code3\": (\"423\", \"114\"),\n \"code4\": \"nan\",\n \"code5\": 31,\n \"code6\": (\"372\", \"238\"),\n \"rules_desc\": \"rules2\",\n },\n]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18572278/" ]
74,510,879
<p>I am trying to build a Yocto image but it keeps failing on trying to fetch the GIT repositories as below. I can reach <code>https://github.com/PROJECT/linux-imx</code> from a browser, but no joy fetching the GIT repository from Yocto. Any ideas on how to solve it would be appreciated.</p> <pre><code> WARNING: linux-imx-5.4-r0 do_fetch: Failed to fetch URL git://github.com/PROJECT/linux-imx.git;protocol=https;branch=master </code></pre>
[ { "answer_id": 74516046, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "Missing SRC_URI checksum" }, { "answer_id": 74521244, "author": "Talel BELHADJSALEM", "author_id": 7553704, "author_profile": "https://Stackoverflow.com/users/7553704", "pm_score": 1, "selected": false, "text": "git git git://URL;protocol=PROTOCOL;branch=BRANCH SRCREV https git ssh SRC_URI = \"git://github.com/PROJECT/linux-imx;protocol=https;branch=BRANCH\"\nSRCREV = \"aaaa..\"\n SRC_URI = \"git://github.com/PROJECT/linux-imx;protocol=ssh;branch=BRANCH\"\nSRCREV = \"aaaa..\"\n branch SRCREV SRCREV Missing SRC_URI checksum SRC_URI https git SRC_URI = \"https://github.com/PROJECT/linux-imx\"\n linux-imx SRC_URI" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4768946/" ]
74,510,887
<p>Hello I want to look for a specific block of data inside a dataframe with python and pandas. Lets assume I have a dataframe like this:</p> <pre><code>A B C D E 1 3 5 7 9 5 6 7 8 9 2 4 6 8 8 5 4 3 2 1 </code></pre> <p>and I want to iterate over the dataframe and look for a specific block of data and return the location of that data. Lets say this one:</p> <pre><code>7 8 9 6 8 8 </code></pre> <p>How can I achieve this in a reasonable runtime?</p> <p>My solution is taking to much time since I'm looping over and over over the dataframes and I'm sure there is a way better solution for this kind of problem.</p>
[ { "answer_id": 74516046, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "Missing SRC_URI checksum" }, { "answer_id": 74521244, "author": "Talel BELHADJSALEM", "author_id": 7553704, "author_profile": "https://Stackoverflow.com/users/7553704", "pm_score": 1, "selected": false, "text": "git git git://URL;protocol=PROTOCOL;branch=BRANCH SRCREV https git ssh SRC_URI = \"git://github.com/PROJECT/linux-imx;protocol=https;branch=BRANCH\"\nSRCREV = \"aaaa..\"\n SRC_URI = \"git://github.com/PROJECT/linux-imx;protocol=ssh;branch=BRANCH\"\nSRCREV = \"aaaa..\"\n branch SRCREV SRCREV Missing SRC_URI checksum SRC_URI https git SRC_URI = \"https://github.com/PROJECT/linux-imx\"\n linux-imx SRC_URI" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1771213/" ]
74,510,898
<p>I have a nested list (see image) and I'd like to change the position of elements that are in the second level to first level and the name of this elements also changes. For example, element [<a href="https://i.stack.imgur.com/o5Md9.png" rel="nofollow noreferrer">1</a>][<a href="https://i.stack.imgur.com/o5Md9.png" rel="nofollow noreferrer">1</a>] turns into [[1.1]], element [<a href="https://i.stack.imgur.com/o5Md9.png" rel="nofollow noreferrer">1</a>][[2]] turns into [[1.2]], element [<a href="https://i.stack.imgur.com/o5Md9.png" rel="nofollow noreferrer">1</a>][[3]] turns into [[1.3]] and so on. It needs to be happen in all elements.</p> <p>It's a huge list where a put some regressions results and I want to compare them using compare_performance from Performance package.</p> <p>Does anyone know how to do it in fast and easily way ?</p> <p>I tried unlist but it becomes a mess. I tried flatten from rlist but I get the same result unlist.</p> <p><a href="https://i.stack.imgur.com/o5Md9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o5Md9.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74516046, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "Missing SRC_URI checksum" }, { "answer_id": 74521244, "author": "Talel BELHADJSALEM", "author_id": 7553704, "author_profile": "https://Stackoverflow.com/users/7553704", "pm_score": 1, "selected": false, "text": "git git git://URL;protocol=PROTOCOL;branch=BRANCH SRCREV https git ssh SRC_URI = \"git://github.com/PROJECT/linux-imx;protocol=https;branch=BRANCH\"\nSRCREV = \"aaaa..\"\n SRC_URI = \"git://github.com/PROJECT/linux-imx;protocol=ssh;branch=BRANCH\"\nSRCREV = \"aaaa..\"\n branch SRCREV SRCREV Missing SRC_URI checksum SRC_URI https git SRC_URI = \"https://github.com/PROJECT/linux-imx\"\n linux-imx SRC_URI" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20504985/" ]
74,510,905
<p>Now I have another problem:</p> <p>Another subtask tells me to derive a data type from the classes.</p> <p>I don't know how to compare it. Do you have an idea and could you explain it to me so that I can understand?</p> <p>``</p> <p>instance Eq where ...</p> <p>instance Ord where ...</p> <pre><code></code></pre>
[ { "answer_id": 74511336, "author": "DDub", "author_id": 14802384, "author_profile": "https://Stackoverflow.com/users/14802384", "pm_score": 3, "selected": true, "text": "eqCurrency eqCurrency :: Currency -> Currency -> Bool\neqCurrency ...\n eqCurrency :: Currency -> Currency -> Bool\neqCurrency (Dollar d1 c1) (Dollar d2 c2) = ... \neqCurrency (Yen y1) (Yen y2) = ...\neqCurrency (Euro d1 c1) (Euro d2 c2) = ...\n eqCurrency _c1 _c2 = False\n instance Eq Currency where\n (==) = eqCurrency\n Ord Ord <= compare leqCurrency :: Currency -> Currency -> Bool\nleqCurrency ...\n Dollar Euro Yen instance Ord Currency where\n (<=) = leqCurrency\n" }, { "answer_id": 74511362, "author": "Quelklef", "author_id": 4608364, "author_profile": "https://Stackoverflow.com/users/4608364", "pm_score": 2, "selected": false, "text": "Eq Ord instance Ord Currency where\n compare (Dollar dollars cents) (Yen yen) = compare ((dollars*100 + cents) * 1.4) yen\n -- ...\n Ord compare (Yen ...) (Dollar ...) compare (Dollar ...) (Euro ...) normalize :: Currency -> Integer\nnormalize (Dollar dollars cents) = (dollars*100 + cents) * 1.4\n-- you fill in the rest\n Ord instance Ord Currency where\n compare c1 c2 = compare (normalize c1) (normalize c2)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,510,913
<p>i am trying to make a program in which you have a list of workers,where you can add new workers and delete workers. I made a function which contained 5 names. i then want to make a second function to add 2 new names to the 1. function.</p> <pre><code>public static void Zaposlenici() { List&lt;string&gt; imena = new List&lt;string&gt; { &quot;Marko&quot;,&quot;Ivan&quot;,&quot;Miljenko&quot;,&quot;Josip&quot;,&quot;Luka&quot;}; foreach (var ime in imena) { Console.WriteLine(ime); } } public static void Izbornik() { Console.WriteLine(&quot;1. Zaposlenici u firmi&quot;); Console.WriteLine(&quot;2. Dodaj novog zaposlenika&quot;); Console.WriteLine(&quot;3. Izbrisite zaposlenika&quot;); Console.WriteLine(&quot;0. Izlaz&quot;); Console.WriteLine(&quot;--------------------&quot;); Console.WriteLine(&quot;&quot;); Console.WriteLine(&quot;Odaberite opciju: &quot;); } public static void DodajZaposlenika() { List&lt;string&gt; NovaImena = new List&lt;string&gt; { &quot;Francis&quot;, &quot;Matea&quot; }; } public static void Opcije() { int opcija= Int32.Parse(Console.ReadLine()); switch (opcija) { case 1: Zaposlenici(); break; default: break; } } static void Main(string[] args) { Console.WriteLine(&quot;Pozdrav!&quot;); Console.WriteLine(&quot;---------------&quot;); Izbornik(); Opcije(); } } </code></pre> <p>I simply tried using the 1. function in the 2. so i thought i could just change it but i cant seem to be able to use the contents from the 1. function</p>
[ { "answer_id": 74511336, "author": "DDub", "author_id": 14802384, "author_profile": "https://Stackoverflow.com/users/14802384", "pm_score": 3, "selected": true, "text": "eqCurrency eqCurrency :: Currency -> Currency -> Bool\neqCurrency ...\n eqCurrency :: Currency -> Currency -> Bool\neqCurrency (Dollar d1 c1) (Dollar d2 c2) = ... \neqCurrency (Yen y1) (Yen y2) = ...\neqCurrency (Euro d1 c1) (Euro d2 c2) = ...\n eqCurrency _c1 _c2 = False\n instance Eq Currency where\n (==) = eqCurrency\n Ord Ord <= compare leqCurrency :: Currency -> Currency -> Bool\nleqCurrency ...\n Dollar Euro Yen instance Ord Currency where\n (<=) = leqCurrency\n" }, { "answer_id": 74511362, "author": "Quelklef", "author_id": 4608364, "author_profile": "https://Stackoverflow.com/users/4608364", "pm_score": 2, "selected": false, "text": "Eq Ord instance Ord Currency where\n compare (Dollar dollars cents) (Yen yen) = compare ((dollars*100 + cents) * 1.4) yen\n -- ...\n Ord compare (Yen ...) (Dollar ...) compare (Dollar ...) (Euro ...) normalize :: Currency -> Integer\nnormalize (Dollar dollars cents) = (dollars*100 + cents) * 1.4\n-- you fill in the rest\n Ord instance Ord Currency where\n compare c1 c2 = compare (normalize c1) (normalize c2)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18754506/" ]
74,510,914
<p>I need to automatically calculate the most recent <strong>End Date (aka QRT_END) in the format YYYYMMDD</strong>. So since, we are in 20221120, the End Date would be the previous quarter end before today which is <strong>20220930</strong>.

</p> <p>I need to add to the below VBA syntax and not drastically change it. The previous syntax should stay as much as possible. The problem is, for any month on/before October (10th month), it works well and would display the correct previous quarter end such as 20220331, 20220630. However, when it is run in November or December, it incorrectly add a “0”, for example: when I ran today it shows 202201030. It should instead show <strong>20220930</strong>.

</p> <p>The reason the “0” exists is to account for the fact that for the first 3 Quarters, the date for example cannot be 2022331 or 2022630 or 2022930, but should display as 20220331 or 20220630 or 20220930. When it is run in January, February or March of next year, 20221231 should be displayed.

</p> <pre><code>Private Function getQRT_END() As String
 Dim endmonth As Variant Dim endyear As Variant Dim Day As Variant endmonth = Month(Date) - 1 If endmonth = 0 Then endyear = Year(Date) - 1 endmonth = 12 day = 31 Else endyear = Year(Date) If endmonth = 3 Then day = 31 Else day = 30 End if endmonth = “0” &amp; endmonth End If getQRT_END = endyear &amp; endmonth &amp; day End Function </code></pre>
[ { "answer_id": 74511336, "author": "DDub", "author_id": 14802384, "author_profile": "https://Stackoverflow.com/users/14802384", "pm_score": 3, "selected": true, "text": "eqCurrency eqCurrency :: Currency -> Currency -> Bool\neqCurrency ...\n eqCurrency :: Currency -> Currency -> Bool\neqCurrency (Dollar d1 c1) (Dollar d2 c2) = ... \neqCurrency (Yen y1) (Yen y2) = ...\neqCurrency (Euro d1 c1) (Euro d2 c2) = ...\n eqCurrency _c1 _c2 = False\n instance Eq Currency where\n (==) = eqCurrency\n Ord Ord <= compare leqCurrency :: Currency -> Currency -> Bool\nleqCurrency ...\n Dollar Euro Yen instance Ord Currency where\n (<=) = leqCurrency\n" }, { "answer_id": 74511362, "author": "Quelklef", "author_id": 4608364, "author_profile": "https://Stackoverflow.com/users/4608364", "pm_score": 2, "selected": false, "text": "Eq Ord instance Ord Currency where\n compare (Dollar dollars cents) (Yen yen) = compare ((dollars*100 + cents) * 1.4) yen\n -- ...\n Ord compare (Yen ...) (Dollar ...) compare (Dollar ...) (Euro ...) normalize :: Currency -> Integer\nnormalize (Dollar dollars cents) = (dollars*100 + cents) * 1.4\n-- you fill in the rest\n Ord instance Ord Currency where\n compare c1 c2 = compare (normalize c1) (normalize c2)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13794066/" ]
74,510,915
<p>I need to write out a R querie that I already have in SQL. The task is to &quot;transcribe&quot; a querie from SQL to R. I have also imported the &quot;Posts&quot; library. I'm required to do the task in 3 ways: 1-Only base functions 2-Dplyr 3-Data.table</p> <p>The SQL querie is the following: SELECT STRFTIME('%Y', CreationDate) AS Year, COUNT(*) AS TotalNumber FROM Posts GROUP BY Year</p> <p>Help will be really appreciated. thanks ^^</p> <p>I haven't written anything because I have no clue, but I have an example of some queries that are already done.</p>
[ { "answer_id": 74511302, "author": "DashdotdotDashdotdot", "author_id": 20548300, "author_profile": "https://Stackoverflow.com/users/20548300", "pm_score": 1, "selected": false, "text": "install.packages(\"sqldf\")\nlibrary(\"sqldf\")\n\nPosts <- data.frame(year = rep(c(2021, 2022), each = 2))\nsqldf(\"select year,count(*) as TotalNumber from Posts group by Year\")\n" }, { "answer_id": 74511780, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 1, "selected": true, "text": "as.data.frame(\n table(Year = format(dat$CreationDate, format = \"%Y\")),\n responseName = \"TotalNumber\")\n library(dplyr)\ndat %>%\n transmute(Year = format(CreationDate, format = \"%Y\")) %>%\n count(Year)\n library(data.table)\nas.data.table(dat)[, as.data.table(table(Year = format(CreationDate, format = \"%Y\")))]\n# or\nas.data.table(dat)[, Year := format(CreationDate, format = \"%Y\")][, .N, by = Year]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20556786/" ]
74,510,923
<p>I'm trying to run a simple Spring application that adds an item to a database. I want to use the <strong>H2 in-memory database</strong> without defining a schema.sql.</p> <p>However, when I add a <strong>data.sql</strong> file inside the resources folder and start the application, I get the error: <code>Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table &quot;ITEMS&quot; not found (this database is empty); INSERT INTO ITEMS(id, value) VALUES(1, &quot;EXAMPLE&quot;) [42104-214]</code></p> <p>Even when I don't have a data.sql file and just add an item to the database using the api I receive the same error. I don't understand what's wrong. I've searched everywhere trying to find a fix, but nothing worked.</p> <p>Can someone please help me?</p> <p>The entity:</p> <pre><code>import javax.persistence.*; @Entity @Table(name = &quot;ITEMS&quot;) public class Item { @Id @GeneratedValue(strategy= GenerationType.AUTO) private Long id; private String value; } </code></pre> <p>application.properties:</p> <pre><code>spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1 spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=sa spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.h2.console.enabled=true spring.jpa.defer-datasource-initialization=true </code></pre> <p>data.sql:</p> <pre><code>INSERT INTO ITEMS(id, value) VALUES(1, &quot;EXAMPLE&quot;); </code></pre> <p>pom.xml:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;2.7.5&lt;/version&gt; &lt;relativePath/&gt; &lt;/parent&gt; &lt;groupId&gt;com.example&lt;/groupId&gt; &lt;artifactId&gt;simple-project&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;name&gt;simple-project&lt;/name&gt; &lt;description&gt;simple-project&lt;/description&gt; &lt;properties&gt; &lt;java.version&gt;17&lt;/java.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;optional&gt;true&lt;/optional&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.h2database&lt;/groupId&gt; &lt;artifactId&gt;h2&lt;/artifactId&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre>
[ { "answer_id": 74511302, "author": "DashdotdotDashdotdot", "author_id": 20548300, "author_profile": "https://Stackoverflow.com/users/20548300", "pm_score": 1, "selected": false, "text": "install.packages(\"sqldf\")\nlibrary(\"sqldf\")\n\nPosts <- data.frame(year = rep(c(2021, 2022), each = 2))\nsqldf(\"select year,count(*) as TotalNumber from Posts group by Year\")\n" }, { "answer_id": 74511780, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 1, "selected": true, "text": "as.data.frame(\n table(Year = format(dat$CreationDate, format = \"%Y\")),\n responseName = \"TotalNumber\")\n library(dplyr)\ndat %>%\n transmute(Year = format(CreationDate, format = \"%Y\")) %>%\n count(Year)\n library(data.table)\nas.data.table(dat)[, as.data.table(table(Year = format(CreationDate, format = \"%Y\")))]\n# or\nas.data.table(dat)[, Year := format(CreationDate, format = \"%Y\")][, .N, by = Year]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11292161/" ]
74,510,929
<p>How to get array of strings from nested object</p> <p>Based on type it is required to get array of 'link'(s) Source object:</p> <pre><code>const obj = { id: '01', options: {}, children: [ { id: '02', type: 'green', options: { link: 'http://some-page-023' }, children: [ { id: '03', type: 'black', options: {}, children: [], }, { id: '04', type: 'green', options: { link: 'http://some-page-044' }, children: [ { id: '05', type: 'white', options: {}, children: [], } ], } ], }, { id: '06', type: 'black', options: { link: 'http://some-page-258' }, children: [ { id: '07', type: 'green', options: { link: 'http://some-page-055' }, children: [], }, { id: '08', type: 'white', options: {}, children: [ { id: '09', type: 'green', options: { link: 'http://some-page-023' }, children: [], } ], } ], }, ] } </code></pre> <p>What I am doing:</p> <pre><code>const a = [] const getLinks = (data, ltype) =&gt; { if (data.children) { for( let el in data.children) { if (data.children[el].type === ltype) { a.push(data.children[el].options.link) } getLinks(data.children[el], ltype) } } return a } const result = getLinks(obj, 'green') console.dir(result, { depth: null }) </code></pre> <p>this works fine, result: [ 'http://some-page-023', 'http://some-page-044', 'http://some-page-055', 'http://some-page-023' ]</p> <p>But I need the function to return the array of strings (array should be init and returned by function), so I need something like:</p> <pre><code>const getLinks = (data, ltype) =&gt; { const a = [] function recursiveFind(children, ltype) { if (data.children) { for (let el in data.children) { if (data.children[el].type === ltype) { a.push(data.children[el].options.link) } else { recursiveFind(data.children[el], ltype) } } } } recursiveFind(data, ltype) return a } const result = getLinks(obj, 'green') console.dir(result, { depth: null }) </code></pre>
[ { "answer_id": 74511022, "author": "Nina Scholz", "author_id": 1447675, "author_profile": "https://Stackoverflow.com/users/1447675", "pm_score": 2, "selected": false, "text": "const\n getLinks = (object, ltype) => {\n const links = [];\n if (object.type === ltype) links.push(object.options.link);\n links.push(...object.children.flatMap(o => getLinks(o, ltype)));\n return links;\n },\n obj = { id: '01', options: {}, children: [{ id: '02', type: 'green', options: { link: 'http://some-page-023' }, children: [{ id: '03', type: 'black', options: {}, children: [] }, { id: '04', type: 'green', options: { link: 'http://some-page-044' }, children: [{ id: '05', type: 'white', options: {}, children: [] }] }] }, { id: '06', type: 'black', options: { link: 'http://some-page-258' }, children: [{ id: '07', type: 'green', options: { link: 'http://some-page-055' }, children: [] }, { id: '08', type: 'white', options: {}, children: [{ id: '09', type: 'green', options: { link: 'http://some-page-023' }, children: [] }] }] }] },\n result = getLinks(obj, 'green');\n\nconsole.dir(result); const\n getLinks = (data, ltype) => {\n const\n gl = ({ type, options: { link }, children }) => [\n ...(type === ltype ? [link] : []),\n ...children.flatMap(gl)\n ];\n return gl(data);\n },\n obj = { id: '01', options: {}, children: [{ id: '02', type: 'green', options: { link: 'http://some-page-023' }, children: [{ id: '03', type: 'black', options: {}, children: [] }, { id: '04', type: 'green', options: { link: 'http://some-page-044' }, children: [{ id: '05', type: 'white', options: {}, children: [] }] }] }, { id: '06', type: 'black', options: { link: 'http://some-page-258' }, children: [{ id: '07', type: 'green', options: { link: 'http://some-page-055' }, children: [] }, { id: '08', type: 'white', options: {}, children: [{ id: '09', type: 'green', options: { link: 'http://some-page-023' }, children: [] }] }] }] },\n result = getLinks(obj, 'green');\n\nconsole.dir(result);" }, { "answer_id": 74511577, "author": "gog", "author_id": 3494774, "author_profile": "https://Stackoverflow.com/users/3494774", "pm_score": 2, "selected": true, "text": "const getLinks = (data, ltype) => {\n const a = []\n \n function recursiveFind(data, ltype) {\n if (data.children) {\n for (let child of data.children) {\n if (child.type === ltype)\n a.push(child.options.link)\n recursiveFind(child, ltype)\n }\n }\n }\n \n recursiveFind(data, ltype)\n return a\n}\n for..of for..in function *getLinks (data, ltype) {\n if (data.children) {\n for (let c of data.children) {\n if (c.type === ltype)\n yield c.options.link\n yield *getLinks(c, ltype)\n }\n }\n}\n\nresult = [...getLinks(obj, 'green')]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11020843/" ]
74,510,931
<p>I’m trying to pass data from child to parent component with a variable value from child to parent, unfortunately no changes are being made in parent component. Any ideas whats going on? Or does @Output decorator strictly works only with events that come from clicks in child component? I also would expact that it doesnt matter if i use method for eventemitter or not, so for example setting emit for eventemitters from inside constructor or ngOnInit methods, i tried it and still doesnt work.</p> <p>Child component:</p> <pre><code>import { Component, EventEmitter, Output } from '@angular/core'; @Component({ selector: 'app-server', templateUrl: './server.component.html', styles: [ `.online { color: white; } ` ] }) export class ServerComponent { serverId: number = 10; serverStatus: string = 'offline'; serverName: 'Random server'; @Output() serverNameEmitter = new EventEmitter&lt;string&gt;(); constructor() { this.serverStatus = Math.random() &gt; 0.5 ? 'online' : 'offline'; } ngOnInit(): void { this.passServerName(this.serverName); } passServerName(serverName: string) { this.serverNameEmitter.emit(serverName); } getColor() { return this.serverStatus == 'online' ? 'green' : 'red'; } getServerStatus() { return this.serverStatus; } } </code></pre> <p>Parent component</p> <pre><code>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-servers', templateUrl: './servers.component.html', styleUrls: ['./servers.component.css'], }) export class ServersComponent implements OnInit { allowNewServer = false; serverCreationStatus = 'No server was created!'; serverNames = &quot;&quot;; serverStatus = false; servers = []; serverName = { name: &quot;Test server&quot; }; constructor() { setTimeout(() =&gt; { this.allowNewServer = true; }, 2000); } ngOnInit(): void {} onCreateServer() { this.serverStatus = true; this.servers.push(this.serverName.name); this.serverCreationStatus = 'Server has been created! Name is ' + this.serverName.name; } onUpdateServerName(event: Event) { this.serverNames = (event.target as HTMLInputElement).value; } changeServerName() { this.serverName.name = this.serverNames; } gettingServerName(serverName: string) { this.serverNames = serverName; } } </code></pre> <p>Parent component HTML</p> <pre><code>&lt;label&gt;Server Name&lt;/label&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; (input)=&quot;onUpdateServerName($event)&quot;&gt; &lt;!--&lt;input type=&quot;text&quot; class=&quot;form-control&quot; [(ngModel)]=&quot;serverName.name&quot;&gt;--&gt; &lt;!--&lt;p&gt;{{serverName}}&lt;/p&gt;--&gt; &lt;button class=&quot;btn btn-primary&quot; [disabled]=&quot;!allowNewServer&quot; (click)=&quot;onCreateServer()&quot;&gt;Add Server&lt;/button&gt; &lt;!--&lt;p [innerText]=&quot;allowNewServer&quot;&gt;&lt;/p&gt;--&gt; &lt;!--&lt;p&gt;{{serverCreationStatus}}&lt;/p&gt;--&gt; &lt;p&gt;Here's {{ serverNames }}&lt;/p&gt; &lt;p *ngIf=&quot;serverStatus; else noServer&quot;&gt;Server was created, server name is {{ serverName.name }}&lt;/p&gt; &lt;ng-template #noServer&gt; &lt;p&gt;No server was created!&lt;/p&gt; &lt;/ng-template&gt; &lt;button class=&quot;btn btn-primary&quot; (click)=&quot;changeServerName()&quot;&gt;Change server name&lt;/button&gt; &lt;app-server *ngFor=&quot;let server of servers&quot; (serverNameEmitter)=&quot;gettingServerName($event)&quot;&gt;&lt;/app-server&gt; </code></pre>
[ { "answer_id": 74511371, "author": "Flo", "author_id": 4472932, "author_profile": "https://Stackoverflow.com/users/4472932", "pm_score": 2, "selected": true, "text": "setTimeout" }, { "answer_id": 74511481, "author": "kellermat", "author_id": 20035486, "author_profile": "https://Stackoverflow.com/users/20035486", "pm_score": 2, "selected": false, "text": "gettingServerName() ChangeDetectorRef import { ChangeDetectorRef } from '@angular/core';\n detectChanges() gettingServerName() constructor(private cdRef: ChangeDetectorRef) {}\n\n gettingServerName(serverName: string) {\n this.serverNames = serverName;\n this.cdRef.detectChanges();\n }\n @Output" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9723070/" ]
74,510,938
<p>I'm trying to separate a widget that contains GetBuilder. I want to send type as parameter to the widget but unfortunately unable to achieve it till now.</p> <p>What I'm trying to do:</p> <pre><code>class Widget extends StatelessWidget { final type; // A class type that extends GetxController const Widget({required this.type}); @override Widget build(BuildContext context) { return GetBuilder&lt;type&gt;( builder: (controller) { return const SizedBox(); }, ); } } </code></pre> <p>I want to make it reusable in multiple places in my project, but different uses require different Controllers, so the type of the GetBuilder is different for every use. Unfortunately, I've never implemented anything like this before, so I'm pretty confused because it is different than normal parameters.</p> <p>The errors:</p> <blockquote> <p>The name 'type' isn't a type so it can't be used as a type argument. Try correcting the name to an existing type, or defining a type named 'type'. dart(non_type_as_type_argument)</p> </blockquote> <blockquote> <p>'dynamic' doesn't conform to the bound 'GetxController' of the type parameter 'T'. Try using a type that is or is a subclass of 'GetxController'. dart(type_argument_not_matching_bounds)</p> </blockquote>
[ { "answer_id": 74510961, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 0, "selected": false, "text": "Widget class MyWidget extends StatelessWidget {\n final Type type; \n\n const MyWidget({required this.type});\n\n @override\n Widget build(BuildContext context) {\n if(type is XWidget){\n \n }\n }\n}\n" }, { "answer_id": 74510971, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 1, "selected": false, "text": "class CustomWidget<T extends GetxController> extends StatelessWidget {\n \n const CustomWidget();\n @override\n Widget build(BuildContext context) {\n\n return GetBuilder<T>(\n builder: (controller) {\n return const SizedBox();\n },\n );\n }\n}\n CustomWidget<YourCustomType>();\n" }, { "answer_id": 74511093, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "class Widget<T extends GetxController> extends StatelessWidget {\n const Widget({\n super.key,\n });\n\n @override\n build(BuildContext context) {\n return GetBuilder<T>(\n builder: (T controller) {\n return const SizedBox();\n },\n );\n }\n}\n init return GetBuilder<T>(\n init: T(), // you can't\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15343446/" ]
74,510,942
<p>I recently came to this language, and I do not fully understand how some actions work.</p> <pre><code>package com.example.carapp; public class Calculate { static int[] benzmoney= {12,8,10}; static float[] factor = {1F, 0.5F,0.8F}; public static float calculateresult(int position,float fresult) { if (fresult == 0) { return 0; } else if (fresult &lt; 10000){ return (&quot;something&quot;); } else{ float v = (fresult * factor[position]) / 10000 * 6300 + (fresult * factor[position]) / 40000 * 11000 + (fresult * factor[position]) / 80000 * 21000 + (fresult * factor[position]) / 150000 * 7000; return v; } } public static float calculatebenz(int position,float fresult,float cost){ float a=(fresult/100)*cost*benzmoney[position]; return a; } } </code></pre> <p>A number will be entered into the column on the screen, and I will have to count how many times it will contain the number 10000, 40000, 80000, 150000. These numbers indicate the mileage of the car, certain parts need to be changed at these kilometers. the quantity will be calculated and multiplied by the cost of the parts. I assumed that if I divide the original number by each of them completely, and multiply by the amount I need, I will get the desired result. But, as I found out, 10000/50000 = 0.2 instead of 0. How can I solve this problem, so that two fractional numbers would be divided by each other entirely, would not give something other than zero, if the second number is greater. In this line: float v = (fresult * factor[position]) / 10000 * 6300 + (fresult * factor[position]) / 40000 * 11000 + (fresult * factor[position]) / 80000 * 21000 + (fresult * factor[position]) / 150000 * 7000;</p> <p>everything I tried didn't work</p>
[ { "answer_id": 74511074, "author": "laban_luka", "author_id": 14152014, "author_profile": "https://Stackoverflow.com/users/14152014", "pm_score": 1, "selected": false, "text": "Math.floor(result) Math.round(result) Math.floor a = 10_000\nb = 50_000\nc = a / b = 0.2\nMath.round(c) = 0\nMath.floor(c) = 0\n\n\na = 10_000\nb = 11_000\nc = a / b = 0.91\nMath.round(c) = 1\nMath.floor(c) = 0\n return v return Math.floor(v)" }, { "answer_id": 74511772, "author": "cactustictacs", "author_id": 13598222, "author_profile": "https://Stackoverflow.com/users/13598222", "pm_score": 0, "selected": false, "text": "int long int num1 = 5;\nint num2 = 2;\nfloat result = num1 / (float) num2;\n float float float num1 = 5f;\nfloat num2 = 2f;\nint result = (int) num1 / (int) num2;\n int / int int int * float float * float double + float double + double Math int" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20433755/" ]
74,510,992
<p>I am pretty new to Machine Learning and have some confusion, so sorry for trivial question. I have time series data set, very simple with two columns - Date and Price. I'm predicting the price and want to add some features to my model like moving average for last 10 days. If I split dataset learn:validation 80:20. For the first 80 days I can calculate moving avergage. What about my validation set? Should I use predicted value as input for moving average? Are there ready implementation for such a solution? I'm using python scikit-learn library.</p>
[ { "answer_id": 74511074, "author": "laban_luka", "author_id": 14152014, "author_profile": "https://Stackoverflow.com/users/14152014", "pm_score": 1, "selected": false, "text": "Math.floor(result) Math.round(result) Math.floor a = 10_000\nb = 50_000\nc = a / b = 0.2\nMath.round(c) = 0\nMath.floor(c) = 0\n\n\na = 10_000\nb = 11_000\nc = a / b = 0.91\nMath.round(c) = 1\nMath.floor(c) = 0\n return v return Math.floor(v)" }, { "answer_id": 74511772, "author": "cactustictacs", "author_id": 13598222, "author_profile": "https://Stackoverflow.com/users/13598222", "pm_score": 0, "selected": false, "text": "int long int num1 = 5;\nint num2 = 2;\nfloat result = num1 / (float) num2;\n float float float num1 = 5f;\nfloat num2 = 2f;\nint result = (int) num1 / (int) num2;\n int / int int int * float float * float double + float double + double Math int" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74510992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20556923/" ]
74,511,000
<p>I have a <code>.mboy</code> json file that are build with bpm 128 which is the audio original bpm.</p> <p>have a look below at the file.</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code> export default { "editor": "mboy-editor-2.1.1", "format_version": "2.0", "audio": { "artist": "test", "title": "NO COPYRIGHT SHORT MUSIC (SOLO RECORD)", "album": "", "subgenre": "", "date": "", "download_link": "https://www.youtube.com/watch?v=Atv-zwhSyFE", "comments": "", "genre": "Other" }, "author": "&lt;zx&lt;zx", "date": "2022-11-17", "tempo": 128, "start_pos": 0, "tracks": [{ "instrument": "bass", "name": "", "color": "ff009fff", "bars": [{ "index": 0, "quarters_count": 4, "notes": [{ "pos": 400, "len": 100, "markers": [] }, { "pos": 800, "len": 100, "markers": [] }, { "pos": 1100, "len": 100, "markers": [] }, { "pos": 1200, "len": 100, "markers": [] } ] }, { "index": 1, "quarters_count": 4, "notes": [{ "pos": 100, "len": 100, "markers": [] }, { "pos": 1000, "len": 100, "markers": [] } ] }, { "index": 2, "quarters_count": 4, "notes": [{ "pos": 100, "len": 100, "markers": [] }, { "pos": 900, "len": 100, "markers": [] }, { "pos": 1400, "len": 100, "markers": [] } ] }, { "index": 3, "quarters_count": 4, "notes": [{ "pos": 1000, "len": 100, "markers": [] } ] }, { "index": 4, "quarters_count": 4, "notes": [{ "pos": 200, "len": 100, "markers": [] }, { "pos": 1200, "len": 100, "markers": [] } ] }, { "index": 5, "quarters_count": 4, "notes": [{ "pos": 100, "len": 100, "markers": [] }, { "pos": 900, "len": 100, "markers": [] } ] }, { "index": 6, "quarters_count": 4, "notes": [{ "pos": 300, "len": 100, "markers": [] }, { "pos": 500, "len": 100, "markers": [] }, { "pos": 1200, "len": 100, "markers": [] } ] }, { "index": 7, "quarters_count": 4, "notes": [{ "pos": 400, "len": 100, "markers": [] }, { "pos": 500, "len": 100, "markers": [] }, { "pos": 900, "len": 100, "markers": [] }, { "pos": 1400, "len": 100, "markers": [] } ] }, { "index": 8, "quarters_count": 4, "notes": [{ "pos": 400, "len": 100, "markers": [] }, { "pos": 500, "len": 100, "markers": [] }, { "pos": 700, "len": 100, "markers": [] }, { "pos": 1300, "len": 100, "markers": [] }, { "pos": 1400, "len": 100, "markers": [] } ] }, { "index": 9, "quarters_count": 4, "notes": [{ "pos": 100, "len": 100, "markers": [] }, { "pos": 700, "len": 100, "markers": [] }, { "pos": 1300, "len": 100, "markers": [] }, { "pos": 1500, "len": 100, "markers": [] } ] }, { "index": 10, "quarters_count": 4, "notes": [{ "pos": 500, "len": 100, "markers": [] }, { "pos": 700, "len": 100, "markers": [] } ] }, { "index": 11, "quarters_count": 4, "notes": [{ "pos": 900, "len": 100, "markers": [] } ] }, { "index": 12, "quarters_count": 4, "notes": [{ "pos": 0, "len": 100, "markers": [] }, { "pos": 1400, "len": 100, "markers": [] } ] }, { "index": 13, "quarters_count": 4, "notes": [{ "pos": 0, "len": 100, "markers": [] }, { "pos": 1200, "len": 100, "markers": [] } ] }, { "index": 14, "quarters_count": 4, "notes": [{ "pos": 800, "len": 100, "markers": [] } ] }, { "index": 15, "quarters_count": 4, "notes": [{ "pos": 200, "len": 100, "markers": [] }, { "pos": 1000, "len": 100, "markers": [] } ] }, { "index": 16, "quarters_count": 4, "notes": [] }, { "index": 17, "quarters_count": 4, "notes": [{ "pos": 500, "len": 100, "markers": ["ToLeft"] } ] }, { "index": 18, "quarters_count": 4, "notes": [] }, { "index": 19, "quarters_count": 4, "notes": [] }, { "index": 20, "quarters_count": 4, "notes": [] } ] }, { "instrument": "drums", "name": "", "color": "ff009fff", "bars": [{ "index": 0, "quarters_count": 4, "notes": [{ "pos": 400, "len": 100, "markers": [] }, { "pos": 800, "len": 100, "markers": [] }, { "pos": 1400, "len": 100, "markers": [] } ] }, { "index": 1, "quarters_count": 4, "notes": [{ "pos": 800, "len": 100, "markers": [] }, { "pos": 1300, "len": 100, "markers": [] } ] }, { "index": 2, "quarters_count": 4, "notes": [{ "pos": 100, "len": 100, "markers": [] }, { "pos": 500, "len": 100, "markers": [] }, { "pos": 900, "len": 100, "markers": [] }, { "pos": 1400, "len": 100, "markers": [] } ] }, { "index": 3, "quarters_count": 4, "notes": [{ "pos": 100, "len": 100, "markers": [] }, { "pos": 500, "len": 100, "markers": [] }, { "pos": 1000, "len": 100, "markers": [] }, { "pos": 1300, "len": 100, "markers": [] } ] }, { "index": 4, "quarters_count": 4, "notes": [{ "pos": 200, "len": 100, "markers": [] }, { "pos": 600, "len": 100, "markers": [] }, { "pos": 1000, "len": 100, "markers": [] }, { "pos": 1500, "len": 100, "markers": [] } ] }, { "index": 5, "quarters_count": 4, "notes": [{ "pos": 200, "len": 100, "markers": [] }, { "pos": 400, "len": 100, "markers": [] }, { "pos": 1100, "len": 100, "markers": [] }, { "pos": 1200, "len": 100, "markers": [] }, { "pos": 1400, "len": 100, "markers": [] } ] }, { "index": 6, "quarters_count": 4, "notes": [{ "pos": 200, "len": 100, "markers": [] }, { "pos": 400, "len": 100, "markers": [] }, { "pos": 700, "len": 100, "markers": [] }, { "pos": 900, "len": 100, "markers": [] }, { "pos": 1400, "len": 100, "markers": [] } ] }, { "index": 7, "quarters_count": 4, "notes": [{ "pos": 200, "len": 100, "markers": [] }, { "pos": 600, "len": 100, "markers": [] }, { "pos": 800, "len": 100, "markers": [] }, { "pos": 1000, "len": 100, "markers": [] }, { "pos": 1300, "len": 100, "markers": [] } ] }, { "index": 8, "quarters_count": 4, "notes": [{ "pos": 200, "len": 100, "markers": [] }, { "pos": 600, "len": 100, "markers": [] }, { "pos": 900, "len": 100, "markers": [] }, { "pos": 1100, "len": 100, "markers": [] }, { "pos": 1300, "len": 100, "markers": [] } ] }, { "index": 9, "quarters_count": 4, "notes": [{ "pos": 200, "len": 100, "markers": [] }, { "pos": 500, "len": 100, "markers": [] }, { "pos": 1100, "len": 100, "markers": [] } ] }, { "index": 10, "quarters_count": 4, "notes": [{ "pos": 0, "len": 100, "markers": [] }, { "pos": 100, "len": 100, "markers": [] }, { "pos": 500, "len": 100, "markers": [] }, { "pos": 900, "len": 100, "markers": [] }, { "pos": 1000, "len": 100, "markers": [] }, { "pos": 1300, "len": 100, "markers": [] } ] }, { "index": 11, "quarters_count": 4, "notes": [{ "pos": 200, "len": 100, "markers": [] }, { "pos": 500, "len": 100, "markers": [] }, { "pos": 800, "len": 100, "markers": [] }, { "pos": 1200, "len": 100, "markers": [] } ] }, { "index": 12, "quarters_count": 4, "notes": [{ "pos": 200, "len": 100, "markers": [] }, { "pos": 400, "len": 100, "markers": [] }, { "pos": 1100, "len": 100, "markers": [] } ] } ] } ], "markers": [{ "id": "extended", "code": "*", "color": "ffffff00" }, { "id": "ToLeft", "code": "&lt;", "color": "ffffff00" }, { "id": "ToRight", "code": "&gt;", "color": "ffffff00" } ] }</code></pre> </div> </div> </p> <p>my game play just fine with the current file, but what I want is to make it slower and that mean I have to change the bpm from 128 to 240.</p> <p>I have the current <code>pos</code> and <code>len</code> for the bpm 128.</p> <p>I want to know if I can change the position of the notes based on the new bpm.</p> <p>I do not want to change the audio file only the notes above so it can follow the new speed and still use the same audio file.</p> <h2>Update about mboy editor.</h2> <p><code>mboy editor</code> is a free application for making charts for rythm games, here is the link <a href="https://vfpe.itch.io/mboy-editor" rel="nofollow noreferrer">https://vfpe.itch.io/mboy-editor</a>. the <code>pos</code> is a position of the note in the chart where each <code>bar</code> represent 0 to 1500 in length, in it there is <code>x</code> <code>notes</code>. the next bar represent p+n where n is the next bar <code>notes</code> and p is the previous length of the notes.</p> <p>This below is the equation I came up with to write calculate the right pos of the notes</p> <pre><code> const getYPosition = (mboyNote: any, bar: any, trackIndex: number) =&gt; { const q = bar.index * (bar.quarters_count * windowPropeties.noteHeight) let appender = (bar.index * 15 * (windowPropeties.noteHeight)); let y = windowPropeties.height - (appender + mboyNote.pos + q); return y; } </code></pre>
[ { "answer_id": 74511074, "author": "laban_luka", "author_id": 14152014, "author_profile": "https://Stackoverflow.com/users/14152014", "pm_score": 1, "selected": false, "text": "Math.floor(result) Math.round(result) Math.floor a = 10_000\nb = 50_000\nc = a / b = 0.2\nMath.round(c) = 0\nMath.floor(c) = 0\n\n\na = 10_000\nb = 11_000\nc = a / b = 0.91\nMath.round(c) = 1\nMath.floor(c) = 0\n return v return Math.floor(v)" }, { "answer_id": 74511772, "author": "cactustictacs", "author_id": 13598222, "author_profile": "https://Stackoverflow.com/users/13598222", "pm_score": 0, "selected": false, "text": "int long int num1 = 5;\nint num2 = 2;\nfloat result = num1 / (float) num2;\n float float float num1 = 5f;\nfloat num2 = 2f;\nint result = (int) num1 / (int) num2;\n int / int int int * float float * float double + float double + double Math int" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4828524/" ]
74,511,006
<p>I have a dataset like this.</p> <p><a href="https://i.stack.imgur.com/u5keU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u5keU.png" alt="enter image description here" /></a></p> <p>As you can see in the column &quot;Year&quot; there is not only the year. There is also other information that I would need to move into a different column. Does anybody have any idea of how to do it? Thank you in advance</p> <p>I tried many things but none of the was successful</p>
[ { "answer_id": 74511036, "author": "DaveArmstrong", "author_id": 8206434, "author_profile": "https://Stackoverflow.com/users/8206434", "pm_score": 1, "selected": false, "text": "separate() tidyr library(tidyr)\ndat <- data.frame(x =c(\"1994 2 3.69 2.4\", \n \"1998 16 24.33 5.28\"))\ndat\n#> x\n#> 1 1994 2 3.69 2.4\n#> 2 1998 16 24.33 5.28\nseparate(dat, x, c(\"year\", \"v1\", \"v2\", \"v3\"), sep = \" \")\n#> year v1 v2 v3\n#> 1 1994 2 3.69 2.4\n#> 2 1998 16 24.33 5.28\n" }, { "answer_id": 74511060, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 0, "selected": false, "text": "read.table base R read.table(text = df1$x, header = FALSE)\n V1 V2 V3 V4\n1 1994 2 3.69 2.40\n2 1998 16 24.33 5.28\n df1 <- structure(list(x = c(\"1994 2 3.69 2.4\", \n\"1998 16 24.33 5.28\")), class = \"data.frame\", row.names = c(NA, \n-2L))\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20352415/" ]
74,511,007
<pre><code>#include &lt;stdio.h&gt; int main(){ while(1 == 1){ int a; int b; scanf(&quot;%d&quot;, &amp;a); scanf(&quot;%d&quot;, &amp;b); if(a &gt; b){ printf(&quot;A is bigger than B\n&quot;); } else if(a == b){ printf(&quot;A and B are equal\n&quot;); } else{ printf(&quot;B is bigger than A\n&quot;); } } } </code></pre> <p>Everything worked as expected but i ran the program again and it broke, im not sure why but it kept printing the last message over and over again</p>
[ { "answer_id": 74511285, "author": "Beyondo", "author_id": 8524922, "author_profile": "https://Stackoverflow.com/users/8524922", "pm_score": 1, "selected": false, "text": "scanf int a; // -2, -1, 0, 1, 2, 3, 4, ...\nint b;\nscanf(\"%d\", &a);\nscanf(\"%d\", &b);\n float a; // -1.0, -0.5, 0.0, -0.5, 1.0, 2.0, ...\nfloat b;\nscanf(\"%f\", &a);\nscanf(\"%f\", &b);\n" }, { "answer_id": 74511546, "author": "Haris", "author_id": 20017547, "author_profile": "https://Stackoverflow.com/users/20017547", "pm_score": 0, "selected": false, "text": "if (scanf(\"%d\", &a) != 1)\n{\n fprintf(stderr, \"Error: Invalid input.”);\n exit(EXIT_FAILURE);\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20432396/" ]
74,511,050
<p>I have this python practice question which is to return True if a word is an isogram (word with nonrepeating characters). It is also supposed to return True if the isogram is a blank string. My answer didn't work out.</p> <pre><code>from string import ascii_lowercase def is_isogram(iso): for x in iso: return False if (iso.count(x) &gt; 1) and (x in ascii_lowercase) else True #None </code></pre> <p>While another answered:</p> <pre><code>def is_isogram(word): word = str(word).lower() alphabet_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] for i in word: if word.count(i) &gt; 1 and i in alphabet_list: return False return True #True </code></pre> <p>I'm not sure why the return value is different with just a slightly different structure or is it how to return statement is defined?</p>
[ { "answer_id": 74511984, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "set str.count set def is_isogram(iso):\n return len(set(iso)) == len(iso)\n\nprint(is_isogram('abc'))\nprint(is_isogram('abac'))\nprint(is_isogram(''))\nprint(is_isogram(' '))\n True\nFalse\nTrue\nTrue\n iso = [x for x in iso if x not in excluded_set]" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18821294/" ]
74,511,077
<p>While my CSS works sometimes the specific properties are not executed. This can been seen in the Chrome Console where they have a line thru them, indicating that they are not being applied. I thought the more specific DIV classes would have a higher execution priority than the general Div.</p> <p>In particular, I'm trying to set the padding for p.note I can set a separate text size for &lt;p.note&gt; smaller than p but not the margins or padding. I call it in my HTML using:</p> <pre><code> &lt;p class=&quot;note&quot;&gt; </code></pre> <p>As apparently &lt;p.note&gt; does not work.</p> <p>Following is the relevant CSS fragment and some pix showing that it's not applied. A lot of what I'm trying to apply in the &lt;p.note&gt; isn't be applied due to priorities. How can I fix this?</p> <pre><code>* { margin: 1rem; padding: 1rem; /* outline: solid black 2px; */ box-sizing: border-box; } /* define all paragraph font for main pg */ p { color: black; text-align: left; font-family: palatino; font-size: 1.1rem; background-color: rgba(238,238,238,0.7); /* off-white translucent */ /* margin: 4 prop is Top R Bott L no , but spaces*/ margin: 1.7rem; padding: 1rem; outline: solid black 1px; box-sizing: border-box; } p.note { background-color: rgba(88,190,238,0.23); /* purple translucent */ font-size: .8rem; /* margin: 4 prop is Top R Bott L no , but spaces*/ margin: 1.7rem; padding: .25,1,.25,1rem; outline: solid black 1px; box-sizing: border-box; } p::first-letter { font-family: Georgia, serif; /* font-family: Luminary, fantasy; not allowed by Chrome */ font-size:2.0rem; color: #2f2f2f; } </code></pre> <p>Any suggestions from CSS experts would be appreciated as I'm very slowly trying to learn CSS bit by bit.</p> <p><a href="https://i.stack.imgur.com/564wp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/564wp.png" alt="Classes voided out by Chrome" /></a></p>
[ { "answer_id": 74511142, "author": "Ignacio Delgado", "author_id": 9352541, "author_profile": "https://Stackoverflow.com/users/9352541", "pm_score": 3, "selected": true, "text": "p.note { background-color: rgba(88,190,238,0.23); /* purple translucent */\nfont-size: .8rem;\n/* margin: 4 prop is Top R Bott L no , but spaces*/\nmargin: 1.7rem;\npadding: .25,1,.25,1rem;\noutline: solid black 1px;\nbox-sizing: border-box;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9922157/" ]
74,511,090
<p><code>gregexpr</code> returns a list containing a vector with some additional data:</p> <pre><code>[[1]] [1] 21 136 409 512 587 693 attr(,&quot;match.length&quot;) [1] 3 4 5 5 4 9 </code></pre> <p>How do I extract just one element with a corresponding attribute at once?</p> <pre><code>[[1]] [1] 409 attr(,&quot;match.length&quot;) [1] 5 </code></pre> <p>UPD: The final object must be compatible with <code>regmatches</code> function.</p>
[ { "answer_id": 74511142, "author": "Ignacio Delgado", "author_id": 9352541, "author_profile": "https://Stackoverflow.com/users/9352541", "pm_score": 3, "selected": true, "text": "p.note { background-color: rgba(88,190,238,0.23); /* purple translucent */\nfont-size: .8rem;\n/* margin: 4 prop is Top R Bott L no , but spaces*/\nmargin: 1.7rem;\npadding: .25,1,.25,1rem;\noutline: solid black 1px;\nbox-sizing: border-box;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17720640/" ]
74,511,117
<p>I have a useRef hook and two components. In one component, I increase the value on click by 1 unit, and in the second component, I draw the value. I pass the value itself through useContext.</p> <p>Now the problem is that the value is not being redrawn. How can this be fixed?</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>export const ContactContext = React.createContext(); function App() { const countItem = useRef(1); const value = { countItem }; return ( &lt;ContactContext.Provider value={value}&gt; &lt;div&gt; &lt;AddValue /&gt; &lt;/div&gt; &lt;div&gt; &lt;Logo /&gt; &lt;/div&gt; &lt;/ContactContext.Provider&gt; ); }</code></pre> </div> </div> </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const AddValue = () =&gt; { const { countItem } = useContext(ContactContext); const addItemHandler = () =&gt; { countItem.current = countItem.current + 1; }; return ( &lt;&gt; &lt;div&gt; &lt;button onClick={addItemHandler} &gt; &lt;img src="plus.svg" alt="plus logo" /&gt; &lt;/button&gt; &lt;/div&gt; &lt;/&gt; ); };</code></pre> </div> </div> </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>function Logo() { const { countItem } = useContext(ContactContext); return ( &lt;p data-testid="statistics"&gt; {`Count of channels: ${countItem.current}`} &lt;br /&gt; &lt;/p&gt; ); }</code></pre> </div> </div> </p>
[ { "answer_id": 74511142, "author": "Ignacio Delgado", "author_id": 9352541, "author_profile": "https://Stackoverflow.com/users/9352541", "pm_score": 3, "selected": true, "text": "p.note { background-color: rgba(88,190,238,0.23); /* purple translucent */\nfont-size: .8rem;\n/* margin: 4 prop is Top R Bott L no , but spaces*/\nmargin: 1.7rem;\npadding: .25,1,.25,1rem;\noutline: solid black 1px;\nbox-sizing: border-box;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20553149/" ]
74,511,136
<p>I am using Jest to test a react component. I am trying to mock a function from other dependency. The function from dependency should return an array, but it is showing undefined on the console.</p> <p>Below file is the tsx file, when I click the button, it should call the dependency function to get the list of the Frames. ExitAppButton.tsx:</p> <pre><code>import React, { useContext, useState } from 'react'; import { TestContext } from '../ContextProvider'; import { useDispatch } from 'react-redux'; const ExitAppButton = (props: any): JSX.Element =&gt; { const { sdkInstance } = useContext(TestContext); const exitAppClicked = () =&gt; { const appList = sdkInstance.getFrames().filter((app: any) =&gt; {app.appType === &quot;Test App&quot;}).length} </code></pre> <p>test file, SignOutOverlay.test.tsx:</p> <pre><code>import * as React from 'react'; import { fireEvent, render, screen } from '@testing-library/react'; import SignOutOverlay from '.'; import ExitAppButton from './ExitAppButton'; import { TestContext } from '../ContextProvider'; import { Provider } from 'react-redux'; import configureStore from 'redux-mock-store'; const api = require('@praestosf/container-sdk/src/api'); const mockStore = configureStore([]); jest.mock('@praestosf/container-sdk/src/api'); api.getFrames.mockReturnValue([{appType:&quot;Test App&quot;},{appType:&quot;Test App&quot;},{appType:&quot;Not Test App&quot;}]); describe('Test Exit app Button', () =&gt; { const renderExitAppButton = () =&gt; { const store = mockStore([{}]); render( &lt;Provider store={store}&gt; &lt;TestContext.Provider value={{ sdkInstance: api }}&gt; &lt;SignOutOverlay&gt; &lt;ExitAppButton/&gt; &lt;/SignOutOverlay&gt; &lt;/TestContext.Provider&gt; &lt;/Provider&gt; ); }; it('should to be clicked and logged out', () =&gt; { renderExitAppButton(); fireEvent.click(screen.getByTestId('exit-app-button-id')); }); </code></pre> <p>This is the dependency file, api.js</p> <pre><code>const getFrames = () =&gt; { let frames = window.sessionStorage.getItem('TestList'); frames = frames ? JSON.parse(frames) : []; return frames }; const API = function () { }; API.prototype = { constructor: API, getFrames }; module.exports = new API(); </code></pre> <p>I mocked the getFrame function to return an array of 3 objects, but when running the test case, it is returning undefined. Below error was showing:</p> <pre><code>TypeError: Cannot read property 'filter' of undefined </code></pre> <p>Am I mocking this correct?</p>
[ { "answer_id": 74511142, "author": "Ignacio Delgado", "author_id": 9352541, "author_profile": "https://Stackoverflow.com/users/9352541", "pm_score": 3, "selected": true, "text": "p.note { background-color: rgba(88,190,238,0.23); /* purple translucent */\nfont-size: .8rem;\n/* margin: 4 prop is Top R Bott L no , but spaces*/\nmargin: 1.7rem;\npadding: .25,1,.25,1rem;\noutline: solid black 1px;\nbox-sizing: border-box;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5935705/" ]
74,511,179
<p>I am trying to create a token collection using the Aptos Typescript SDK.</p> <pre><code>const account = new AptosAccount(Uint8Array.from(Buffer.from(PRIVATE_KEY)), ACCOUNT_ADDR); await tokenClient.createCollection( account, &quot;A test collection 1&quot;, &quot;A test collection&quot;, &quot;https://google.com&quot;, ); </code></pre> <p>But I get the following error:</p> <p><code>ApiError2: {&quot;message&quot;:&quot;Invalid transaction: Type: Validation Code: INVALID_AUTH_KEY&quot;,&quot;error_code&quot;:&quot;vm_error&quot;,&quot;vm_error_code&quot;:2}</code></p> <p>What am I doing wrong?</p> <p>Tried replicating the Aptos official example but instead of creating a new account, I want to use an existing funded account.</p>
[ { "answer_id": 74517870, "author": "Daniel Porteous", "author_id": 3846032, "author_profile": "https://Stackoverflow.com/users/3846032", "pm_score": 2, "selected": false, "text": "import { AptosAccount, HexString } from \"aptos\";\n\nconst privateKeyHex = \"0xdcaf65ead38f7cf0eb4f81961f8fc7f9b7f1e2f45e2d4a6da0dbef85f46f6057\";\nconst privateKeyBytes = HexString.ensure(privateKeyHex).toUint8Array();\nconst account = new AptosAccount(privateKeyBytes);\n" }, { "answer_id": 74558321, "author": "P.H", "author_id": 20176319, "author_profile": "https://Stackoverflow.com/users/20176319", "pm_score": 0, "selected": false, "text": "private_key = ed25519.PrivateKey.from_hex(bip_private_key)\n" }, { "answer_id": 74610336, "author": "Kirill Arutyunov", "author_id": 1486383, "author_profile": "https://Stackoverflow.com/users/1486383", "pm_score": 0, "selected": false, "text": "import { AptosAccount } from \"aptos\";\n\nconst wallet = new AptosAccount();\nconst privateKeyHex = wallet.toPrivateKeyObject().privateKeyHex;\n\n// ...\n\nconst privateKeyBytes = HexString.ensure(privateKeyHex).toUint8Array();\nconst account = new AptosAccount(privateKeyBytes);\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7927410/" ]
74,511,185
<p>I want to fetch data from the nextjs server on the front end, however the code after fetch() doesn't work in the onSubmit() function. here is the <strong>/test</strong> page</p> <p><strong>pages/test</strong></p> <pre><code> const onSubmit = (data) =&gt; { console.log(&quot;________&quot;); users.map(async (user, index) =&gt; { if (data.email === user.email) { if (data.password === user.password) { console.log(&quot;hi&quot;); const data = await fetch(&quot;http://localhost:3000/api/test&quot;); // after the fetch, this code does not run console.log(&quot;back-end is: &quot;, data); } } }); }; </code></pre> <p>and here is my code in <strong>/api/test</strong></p> <pre><code>export default async function student_method(req, res) { return console.log(&quot;get in server&quot;); } </code></pre> <p>so please what is the problem??</p> <p>i'm try to get the data inside the database so we need to use fetch() method but fetch() work succesfully but code after fetch() does not work</p>
[ { "answer_id": 74511223, "author": "great_pan", "author_id": 20200173, "author_profile": "https://Stackoverflow.com/users/20200173", "pm_score": 2, "selected": true, "text": "return res res.status(200).send(\"get in server\");\n" }, { "answer_id": 74511225, "author": "Francisco Gomez", "author_id": 11053602, "author_profile": "https://Stackoverflow.com/users/11053602", "pm_score": 0, "selected": false, "text": "const data = await fetch(\"http://localhost:3000/api/test\");\n" }, { "answer_id": 74511253, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 0, "selected": false, "text": "export default async function student_method(req, res) {\n /* status code 200 or any other status codes */\n res.status(200).send(\"get in server\");\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19633029/" ]
74,511,206
<p>I have a csv file with say 500 users details (id, pwd) i want 50 users to login every 2 hours for ex , at morning 8 am 50 users should login, at 10 am 50, 12 pm - 50 users and so on please help in details i am complete newbie</p> <p><a href="https://i.stack.imgur.com/e1uaZ.png" rel="nofollow noreferrer">image</a></p>
[ { "answer_id": 74511223, "author": "great_pan", "author_id": 20200173, "author_profile": "https://Stackoverflow.com/users/20200173", "pm_score": 2, "selected": true, "text": "return res res.status(200).send(\"get in server\");\n" }, { "answer_id": 74511225, "author": "Francisco Gomez", "author_id": 11053602, "author_profile": "https://Stackoverflow.com/users/11053602", "pm_score": 0, "selected": false, "text": "const data = await fetch(\"http://localhost:3000/api/test\");\n" }, { "answer_id": 74511253, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 0, "selected": false, "text": "export default async function student_method(req, res) {\n /* status code 200 or any other status codes */\n res.status(200).send(\"get in server\");\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557067/" ]
74,511,207
<p>I am trying to calculate the value of the potentiometer equivalent to the angle, so I need to multiply by 180 and then divide by the range. Upon doing so, I noticed that the number I'm getting is not the number I was expecting so I started debugging by multiplying by 180 only and realized the output was not as predicted. <strong>Here is the simple code that outputs the weird readings:</strong> `</p> <pre><code>#define POTENTIOMETER_PIN A0 int val; void setup() { // put your setup code here, to run once: Serial.begin(9600); } // put your main code here, to run repeatedly: void loop() { val = analogRead(POTENTIOMETER_PIN); Serial.println(val*180); delay(250); } </code></pre> <p>`</p> <p>A value between (0 to 1023)*180 was expected, rather the serial monitor spits out values such as: -18932 -18752 -18572 -18392 -18392</p>
[ { "answer_id": 74511663, "author": "ti7", "author_id": 4541045, "author_profile": "https://Stackoverflow.com/users/4541045", "pm_score": 0, "selected": false, "text": "map() int val = 0; // assign at declaration\n\nvoid loop()\n{\n val = analogRead(POTENTIOMETER_PIN); // read value\n val = map(val, 0, 1023, 0, 180); // convert into 180 range\n Serial.println(val); // display value\n}\n int long long map(long x, long in_min, long in_max, long out_min, long out_max) {\n return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;\n}\n map() int int uint32_t int" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19814257/" ]
74,511,215
<p>I get this exception when mapping record to entity:</p> <pre class="lang-none prettyprint-override"><code>org.jooq.exception.DataTypeException: No Converter found for types java.util.UUID and java.util.List at org.jooq.impl.Tools.converterOrFail(Tools.java:1208) ~[jooq-3.15.0.jar:na] at org.jooq.impl.Tools.converterOrFail(Tools.java:1217) ~[jooq-3.15.0.jar:na] at org.jooq.impl.AbstractRecord.get(AbstractRecord.java:351) ~[jooq-3.15.0.jar:na] at org.jooq.impl.DefaultRecordMapper$ImmutablePOJOMapper.set(DefaultRecordMapper.java:1146) ~[jooq-3.15.0.jar:na] at org.jooq.impl.DefaultRecordMapper$ImmutablePOJOMapper.mapNonnested(DefaultRecordMapper.java:1137) ~[jooq-3.15.0.jar:na] at org.jooq.impl.DefaultRecordMapper$ImmutablePOJOMapper.map(DefaultRecordMapper.java:1124) ~[jooq-3.15.0.jar:na] at org.jooq.impl.DefaultRecordMapper.map(DefaultRecordMapper.java:610) ~[jooq-3.15.0.jar:na] at org.jooq.impl.DelayedRecordMapper.map(DelayedRecordMapper.java:69) ~[jooq-3.15.0.jar:na] at org.jooq.RecordMapper.apply(RecordMapper.java:80) ~[jooq-3.15.0.jar:na] at org.jooq.RecordMapper.apply(RecordMapper.java:65) ~[jooq-3.15.0.jar:na] at java.base/java.util.stream.Collectors.lambda$mapping$13(Collectors.java:469) ~[na:na] at java.base/java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169) ~[na:na] at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133) ~[na:na] at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1845) ~[na:na] at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509) ~[na:na] at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499) ~[na:na] at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:921) ~[na:na] at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na] at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682) ~[na:na] at org.jooq.impl.AbstractCursor.collect(AbstractCursor.java:78) ~[jooq-3.15.0.jar:na] at org.jooq.impl.ResultQueryTrait.collect(ResultQueryTrait.java:358) ~[jooq-3.15.0.jar:na] at org.jooq.impl.ResultQueryTrait.fetchInto(ResultQueryTrait.java:1423) ~[jooq-3.15.0.jar:na] at com.example.jooqsample.posts.JOOQPostRepository.getAll(JOOQPostRepository.java:45) ~[classes/:na] at com.example.jooqsample.posts.PostFacade.getAllPosts(PostFacade.java:34) ~[classes/:na] at com.example.jooqsample.posts.rest.PostController.getAllPosts(PostController.java:27) ~[classes/:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-5.3.23.jar:5.3.23] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150) ~[spring-web-5.3.23.jar:5.3.23] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) ~[spring-webmvc-5.3.23.jar:5.3.23] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.3.23.jar:5.3.23] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.23.jar:5.3.23] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.23.jar:5.3.23] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1071) ~[spring-webmvc-5.3.23.jar:5.3.23] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:964) ~[spring-webmvc-5.3.23.jar:5.3.23] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.23.jar:5.3.23] at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.3.23.jar:5.3.23] at javax.servlet.http.HttpServlet.service(HttpServlet.java:670) ~[tomcat-embed-core-9.0.68.jar:4.0.FR] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.23.jar:5.3.23] at javax.servlet.http.HttpServlet.service(HttpServlet.java:779) ~[tomcat-embed-core-9.0.68.jar:4.0.FR] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.68.jar:9.0.68] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.23.jar:5.3.23] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.23.jar:5.3.23] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.23.jar:5.3.23] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.23.jar:5.3.23] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.23.jar:5.3.23] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.23.jar:5.3.23] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.68.jar:9.0.68] at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na] </code></pre> <p>Entities:</p> <pre class="lang-java prettyprint-override"><code>@AllArgsConstructor(access = AccessLevel.PACKAGE) @Getter @ToString @EqualsAndHashCode(of = &quot;id&quot;) class Post { private UUID id; private String content; private Instant createdAt; private List&lt;Comment&gt; comments; PostDTO toDTO() { return PostDTO .builder() .id(this.id) .content(this.content) .comments(this.comments.stream().map(Comment::toDTO).toList()) .build(); } } @AllArgsConstructor(access = AccessLevel.PACKAGE) @Getter @ToString @EqualsAndHashCode(of = &quot;id&quot;) class Comment { private UUID id; private String content; private Instant createdAt; UUID postId; CommentDTO toDTO() { return new CommentDTO(this.id, this.content); } } </code></pre> <p>Method:</p> <pre class="lang-java prettyprint-override"><code>public List&lt;Post&gt; getAll() { return dslContext .select() .from(POSTS) .leftJoin(COMMENTS) .onKey() .fetchInto(Post.class); } </code></pre> <ul> <li>JOOQ version: 3.15</li> <li>Spring Boot version: 2.7.5</li> <li>Java version: 17</li> </ul>
[ { "answer_id": 74511663, "author": "ti7", "author_id": 4541045, "author_profile": "https://Stackoverflow.com/users/4541045", "pm_score": 0, "selected": false, "text": "map() int val = 0; // assign at declaration\n\nvoid loop()\n{\n val = analogRead(POTENTIOMETER_PIN); // read value\n val = map(val, 0, 1023, 0, 180); // convert into 180 range\n Serial.println(val); // display value\n}\n int long long map(long x, long in_min, long in_max, long out_min, long out_max) {\n return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;\n}\n map() int int uint32_t int" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14033074/" ]
74,511,226
<p>i try create star rating in tailwindcss, I only know that I have to use 'peer' and 'group' class</p> <pre><code>&lt;div class=&quot;text-center&quot;&gt; &lt;span class=&quot;flex flex-row-reverse&quot;&gt; &lt;i class='peer'&gt;start icon 1&lt;/i&gt; &lt;i class='peer'&gt;start icon 2&lt;/i&gt; &lt;i class='peer'&gt;start icon 3&lt;/i&gt; &lt;i class='peer'&gt;start icon 4&lt;/i&gt; &lt;i class='peer'&gt;start icon 5&lt;/i&gt; &lt;/span&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 74511663, "author": "ti7", "author_id": 4541045, "author_profile": "https://Stackoverflow.com/users/4541045", "pm_score": 0, "selected": false, "text": "map() int val = 0; // assign at declaration\n\nvoid loop()\n{\n val = analogRead(POTENTIOMETER_PIN); // read value\n val = map(val, 0, 1023, 0, 180); // convert into 180 range\n Serial.println(val); // display value\n}\n int long long map(long x, long in_min, long in_max, long out_min, long out_max) {\n return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;\n}\n map() int int uint32_t int" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20397070/" ]
74,511,246
<p>I’m trying to write a function that tells the user if they are old enough to drink.</p> <p>Whenever I run what I wrote it says there is a syntax error in line 3 where it says “If age&gt; 20: ”. What am I doing wrong:</p> <pre><code>age = int(input(&quot;how old are you?&quot;) if age &gt; 20: print(&quot;You're old enough to drink&quot;) else: print(&quot;Go drink some apple juice&quot;) </code></pre>
[ { "answer_id": 74511663, "author": "ti7", "author_id": 4541045, "author_profile": "https://Stackoverflow.com/users/4541045", "pm_score": 0, "selected": false, "text": "map() int val = 0; // assign at declaration\n\nvoid loop()\n{\n val = analogRead(POTENTIOMETER_PIN); // read value\n val = map(val, 0, 1023, 0, 180); // convert into 180 range\n Serial.println(val); // display value\n}\n int long long map(long x, long in_min, long in_max, long out_min, long out_max) {\n return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;\n}\n map() int int uint32_t int" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20463556/" ]
74,511,287
<p>Wanted to reset back to selected option once user click's reset or cancel certain form step in scenario</p> <pre><code>&lt;button&gt;Reset&lt;/button&gt; &lt;select&gt; &lt;option&gt;1&lt;/option&gt; &lt;option&gt;2&lt;/option&gt; &lt;option&gt;3&lt;/option&gt; &lt;/select&gt; &lt;select class=&quot;jbselect&quot;&gt; &lt;option&gt;a&lt;/option&gt; &lt;option &gt;b&lt;/option&gt; &lt;option selected&gt;c&lt;/option&gt; &lt;/select&gt; </code></pre>
[ { "answer_id": 74511663, "author": "ti7", "author_id": 4541045, "author_profile": "https://Stackoverflow.com/users/4541045", "pm_score": 0, "selected": false, "text": "map() int val = 0; // assign at declaration\n\nvoid loop()\n{\n val = analogRead(POTENTIOMETER_PIN); // read value\n val = map(val, 0, 1023, 0, 180); // convert into 180 range\n Serial.println(val); // display value\n}\n int long long map(long x, long in_min, long in_max, long out_min, long out_max) {\n return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;\n}\n map() int int uint32_t int" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1575795/" ]
74,511,299
<p>I want that the div panel_pricing-table becomes an flexbox so that all elements in it stay in this box also when i make my window smaller. My problem is that the elements in the flexbox wont shrink, if i make my browser window smaller. The mistake is in CSS but i dont find it. Can you help me pls?</p> <p><a href="https://i.stack.imgur.com/CFcGt.png" rel="nofollow noreferrer">Screenshot of the problem</a></p> <p>Here is my HTML:</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>html { box-sizing: border-box; font-family: 'Open Sans', sans-serif; } body{ background-color: #3a86ff; } .panel_pricing-table{ width:80%; margin: 0 auto; display :flex; transform: translateY(70%); background-color: aliceblue; min-width: 40px; max-width: 34200px; }</code></pre> <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 name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;title&gt;Price Tiers&lt;/title&gt; &lt;link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,600,700"&gt; &lt;link rel="stylesheet" href="app.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="panel_pricing-table"&gt; &lt;div class="pricing-plan"&gt; &lt;img src="icons/icon1.png" alt="" class="pricing-img"&gt; &lt;h2 class="pricing-header"&gt;Personal&lt;/h2&gt; &lt;ul class="pricing-features"&gt; &lt;li class="pricing-features-item"&gt;Custom domains&lt;/li&gt; &lt;li class="pricing-features-item"&gt;Sleeps after 30 mins of inactivity&lt;/li&gt; &lt;/ul&gt; &lt;span class="pricing-price"&gt;Free&lt;/span&gt; &lt;a href="#/" class="pricing-button"&gt;Sign up&lt;/a&gt; &lt;/div&gt; &lt;div class="pricing-plan"&gt; &lt;img src="icons/icon2.png" alt="" class="pricing-img"&gt; &lt;h2 class="pricing-header"&gt;Small team&lt;/h2&gt; &lt;ul class="pricing-features"&gt; &lt;li class="pricing-features-item"&gt;Never sleeps&lt;/li&gt; &lt;li class="pricing-features-item"&gt;Multiple workers for more powerful apps&lt;/li&gt; &lt;/ul&gt; &lt;span class="pricing-price"&gt;$150&lt;/span&gt; &lt;a href="#/" class="pricing-button is-featured"&gt;Free trial&lt;/a&gt; &lt;/div&gt; &lt;div class="pricing-plan"&gt; &lt;img src="icons/icon3.png" alt="" class="pricing-img"&gt; &lt;h2 class="pricing-header"&gt;Enterprise&lt;/h2&gt; &lt;ul class="pricing-features"&gt; &lt;li class="pricing-features-item"&gt;Dedicated&lt;/li&gt; &lt;li class="pricing-features-item"&gt;Simple horizontal scalability&lt;/li&gt; &lt;/ul&gt; &lt;span class="pricing-price"&gt;$400&lt;/span&gt; &lt;a href="#/" class="pricing-button"&gt;Free trial&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74511663, "author": "ti7", "author_id": 4541045, "author_profile": "https://Stackoverflow.com/users/4541045", "pm_score": 0, "selected": false, "text": "map() int val = 0; // assign at declaration\n\nvoid loop()\n{\n val = analogRead(POTENTIOMETER_PIN); // read value\n val = map(val, 0, 1023, 0, 180); // convert into 180 range\n Serial.println(val); // display value\n}\n int long long map(long x, long in_min, long in_max, long out_min, long out_max) {\n return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;\n}\n map() int int uint32_t int" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557099/" ]
74,511,329
<p>I am trying to open a random .sql file off the internet using the following command:</p> <pre><code>psql -h localhost -d database_name -U postgres &lt; file_name.sql </code></pre> <p>But when I run this command I just get errors like the following:</p> <blockquote> <p>invalid command 's</p> </blockquote> <blockquote> <p>invalid command 's</p> </blockquote> <blockquote> <p>invalid command 'll</p> </blockquote> <blockquote> <p>invalid command 'Moving</p> </blockquote> <blockquote> <p>invalid command 's</p> </blockquote> <blockquote> <p>invalid command &quot;frequently</p> </blockquote> <p>It just continuously prints out these invalid command error messages. I thought it might be an encoding problem but I confirmed the file is UTF-8 encoded.</p> <p>Any suggestions on how I can open this file</p>
[ { "answer_id": 74511426, "author": "Jonathan Nathanson", "author_id": 4933165, "author_profile": "https://Stackoverflow.com/users/4933165", "pm_score": 2, "selected": false, "text": "youruser@yourmachine:~$ psql -h localhost -d database_name -U postgres < file_name.sql" }, { "answer_id": 74514392, "author": "Laurenz Albe", "author_id": 6464308, "author_profile": "https://Stackoverflow.com/users/6464308", "pm_score": 1, "selected": false, "text": "-f psql -h localhost -d database_name -U postgres -f file_name.sql\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14176855/" ]
74,511,342
<p>So I have a main dataframe 'df' that contains date ranges grouped by categories 'name' and 'values'. Values is a subcategory of name.</p> <p>I have a second dataframe with a list of dates also by category, 'filterdf'. What I need to do is say given data from filterdf$baddates, exclude all dates in gooddates 0 to 2 days before the date in baddates by category.</p> <pre><code>df &lt;- data.frame (name = c(&quot;name_1&quot;, &quot;name_1&quot;, &quot;name_2&quot;, &quot;name_2&quot;, &quot;name_2&quot;, &quot;name_3&quot;, &quot;name_3&quot;, &quot;name_3&quot;), values = c(&quot;value_1&quot;, &quot;value_1&quot;, &quot;value_2&quot;,&quot;value_4&quot;,&quot;value_4&quot;,&quot;value_3&quot;,&quot;value_3&quot;,&quot;value_3&quot;), gooddates = c(&quot;2022-02-02&quot;,&quot;2022-02-03&quot;,&quot;2022-02-04&quot;,&quot;2022-02-03&quot;,&quot;2022-02-04&quot;,&quot;2022-02-03&quot;,&quot;2022-02-04&quot;,&quot;2022-02-06&quot;)) name values gooddates 1 name_1 value_1 2022-02-02 2 name_1 value_1 2022-02-03 3 name_2 value_2 2022-02-04 4 name_2 value_4 2022-02-03 5 name_2 value_4 2022-02-04 6 name_3 value_3 2022-02-03 7 name_3 value_3 2022-02-04 8 name_3 value_3 2022-02-06 filterdf &lt;- data.frame(name = c(&quot;name_1&quot;, &quot;name_2&quot;, &quot;name_3&quot;, &quot;name_3&quot;), baddates = c(&quot;2022-02-03&quot;,&quot;2022-02-03&quot;,&quot;2022-02-04&quot;,&quot;2022-02-05&quot;)) name baddates 1 name_1 2022-02-03 2 name_2 2022-02-03 3 name_3 2022-02-04 4 name_3 2022-02-05 </code></pre> <p>Since I need an asymmetrical filter, I can't use the strategy I had hoped (when the dates were both in the original df), which is:</p> <pre><code>result &lt;- df %&gt;% filter( abs(baddates - gooddates) &lt; 2 ) </code></pre> <p>I need the result to be:</p> <pre><code>result &lt;- data.frame (name = c( &quot;name_2&quot;, &quot;name_2&quot;,&quot;name_3&quot;), values = c( &quot;value_2&quot;,&quot;value_4&quot;,&quot;value_3&quot;), gooddates = c(&quot;2022-02-04&quot;,&quot;2022-02-04&quot;,&quot;2022-02-06&quot;)) name values gooddates 1 name_2 value_2 2022-02-04 2 name_2 value_4 2022-02-04 3 name_3 value_3 2022-02-06 </code></pre> <p>This will be on a larger dataframe where name and values will need to be filtered by as a group on both name and value so I would like a dplyr solution if possible.</p>
[ { "answer_id": 74511426, "author": "Jonathan Nathanson", "author_id": 4933165, "author_profile": "https://Stackoverflow.com/users/4933165", "pm_score": 2, "selected": false, "text": "youruser@yourmachine:~$ psql -h localhost -d database_name -U postgres < file_name.sql" }, { "answer_id": 74514392, "author": "Laurenz Albe", "author_id": 6464308, "author_profile": "https://Stackoverflow.com/users/6464308", "pm_score": 1, "selected": false, "text": "-f psql -h localhost -d database_name -U postgres -f file_name.sql\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3348414/" ]
74,511,348
<p>The code below allows me to display a grid with items I pass to as a list of Titem of a generic type. Internally the Grid component creates a collection of rows (Rows) of type GridRow which also hold the generic Item for each row.</p> <p>Index.razor</p> <pre><code>&lt;Grid Items=&quot;Transactions&quot; @ref=&quot;MyGrid&quot;&gt; &lt;GridBody Context=&quot;transaction&quot;&gt; &lt;GridCell&gt;@transaction.Date&lt;/GridCell&gt; &lt;GridCell&gt; &lt;/GridCell&gt; &lt;/GridBody&gt; &lt;/Grid&gt; </code></pre> <p>Grid.razor</p> <pre><code>@typeparam TItem @attribute [CascadingTypeParameter(nameof(TItem))]; &lt;table&gt; &lt;tbody&gt; @foreach (var row in Rows) { &lt;tr&gt; @GridBody(row.Item) &lt;/tr&gt; } &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>Grid.razor.cs</p> <pre><code>public class GridRow&lt;TItem&gt; { public TItem Item { get; set; } = default!; public int Id { get; set; } = default!; } public partial class Grid&lt;TItem&gt; { [Parameter] public RenderFragment&lt;TItem&gt; GridBody { get; set; } = default!; [Parameter] public IList&lt;TItem&gt; Items { get; set; } = default!; public List&lt;GridRow&lt;TItem&gt;&gt; Rows { get; set; } = new(); protected override void OnInitialized() { int i = 1; foreach (var item in Items) { var gridRow = new GridRow&lt;TItem&gt;() { Id = i, Item = item, }; Rows.Add(gridRow); i++; } } } </code></pre> <p>All works well, but I wish to access the row.Id in index.razor, but I can't do this because the content provided is of type TItem. I would like to the following:</p> <pre><code>&lt;Grid Items=&quot;Transactions&quot; @ref=&quot;MyGrid&quot;&gt; &lt;GridBody Context=&quot;transaction&quot;&gt; &lt;GridCell&gt;@transaction.Date&lt;/GridCell&gt; &lt;GridCell&gt; @row.Id // .. this is what I need &lt;/GridCell&gt; &lt;/GridBody&gt; &lt;/Grid&gt; </code></pre> <p>Is the above possible while also preserving the use the transaction context? The Id cannot come from the transaction object as the Grid component should know nothing about the type of objects it is rendering and therefore not rely on an ID in the transaction object.</p>
[ { "answer_id": 74511511, "author": "MrC aka Shaun Curtis", "author_id": 13065781, "author_profile": "https://Stackoverflow.com/users/13065781", "pm_score": 1, "selected": false, "text": "Titem Id public interface IWithIntId\n{\n public int Id {get;}\n} \n public class GridRow<TItem> : \n where TItem : class, IWithIntId\n{\n public TItem Item { get; set; } = default!;\n public int Id { get; set; } = default!;\n}\n GridRow" }, { "answer_id": 74511543, "author": "Musaffar Patel", "author_id": 3469841, "author_profile": "https://Stackoverflow.com/users/3469841", "pm_score": 0, "selected": false, "text": "<Grid Items=\"Transactions\" @ref=\"MyGrid\">\n <GridBody Context=\"row\">\n <GridCell>@row.Item.Date</GridCell>\n <GridCell>\n @row.Id\n </GridCell>\n </GridBody>\n</Grid> \n <table>\n <tbody>\n @foreach (var row in Rows)\n {\n <tr>\n @GridBody(row)\n </tr>\n }\n </tbody>\n</table>\n public class GridRow<TItem>\n{\n public TItem Item { get; set; } = default!;\n public int Id { get; set; } = default!;\n}\n\npublic partial class Grid<TItem>\n{\n [Parameter]\n public RenderFragment<GridRow<TItem>> GridBody { get; set; } = default!;\n\n [Parameter]\n public IList<TItem> Items { get; set; } = default!;\n\n public List<GridRow<TItem>> Rows { get; set; } = new();\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3469841/" ]
74,511,435
<p>I am working on a shopping cart application. I'm facing issue while displaying the user selected products in the cart.component.html, as the data is not rendering. DOM is being created every time but the data is not displaying in the cart.component.html ? can anyone suggest how to solve this problem ?</p> <p>cart.component.html</p> <p>`</p> <pre><code>&lt;ng-container *ngIf=&quot;products.length !=0&quot;&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;card-table&quot;&gt; &lt;div class=&quot;cart-product&quot;&gt; &lt;table class=&quot;table table-responsive&quot;&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Sr.No&lt;/th&gt; &lt;th&gt;Product Name&lt;/th&gt; &lt;th&gt;Product Image&lt;/th&gt; &lt;th&gt;Description&lt;/th&gt; &lt;th&gt;Price&lt;/th&gt; &lt;th&gt;Quantity&lt;/th&gt; &lt;th&gt;Total&lt;/th&gt; &lt;!-- &lt;th&gt;Action&lt;/th&gt; --&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr *ngFor=&quot;let item of products; let i = index&quot;&gt; &lt;td&gt;{{ i + 1 }}&lt;/td&gt; &lt;td&gt;{{ item.title }}&lt;/td&gt; &lt;td&gt; &lt;img style=&quot;width: 120px&quot; src=&quot;{{ item.image }}&quot; alt=&quot;&quot; /&gt; &lt;/td&gt; &lt;td style=&quot;width: 25%&quot;&gt;{{ item.description }}&lt;/td&gt; &lt;th style=&quot;width: 12%&quot;&gt;{{ item.price }}&lt;/th&gt; &lt;td style=&quot;width: 12%&quot;&gt;{{ item.quantity }}&lt;/td&gt; &lt;td style=&quot;width: 12%&quot;&gt;{{ item.total }}&lt;/td&gt; &lt;td&gt; &lt;!-- &lt;button (click)=&quot;removeItem(item)&quot; class=&quot;btn btn-danger&quot;&gt;&lt;i class=&quot;fas fa-trash-alt&quot;&gt;&lt;/i&gt;&lt;/button&gt; --&gt; &lt;!-- &lt;/td&gt; --&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan=&quot;4&quot;&gt;&lt;/td&gt; &lt;!-- &lt;td&gt;&lt;button (click)=&quot;emptycart()&quot; class=&quot;btn btn-danger&quot;&gt;Empty Cart&lt;/button&gt;&lt;/td&gt; --&gt; &lt;td&gt; &lt;button routerLink=&quot;/products&quot; class=&quot;btn btn-primary&quot;&gt; Shop More &lt;/button&gt; &lt;/td&gt; &lt;!-- &lt;td&gt;&lt;button class=&quot;btn btn-success&quot;&gt;Checkout&lt;/button&gt;&lt;/td&gt; --&gt; &lt;td&gt; &lt;strong&gt;Grand Total : ${{ grandTotal }}&lt;/strong&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/ng-container&gt; &lt;ng-container *ngIf=&quot;products.length == 0&quot;&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;card&quot;&gt; &lt;h5 class=&quot;card-title&quot;&gt;My Cart&lt;/h5&gt; &lt;/div&gt; &lt;div class=&quot;center&quot;&gt; &lt;img src=&quot;https://rukminim1.flixcart.com/www/800/800/promos/16/05/2019/d438a32e-765a-4d8b-b4a6-520b560971e8.png?q=90&quot; alt=&quot;&quot; /&gt; &lt;h4&gt;Your cart is empty!&lt;/h4&gt; &lt;h6&gt;Add item to it now&lt;/h6&gt; &lt;button routerLink=&quot;/products&quot; class=&quot;btn btn-primary&quot;&gt;Shop Now&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/ng-container&gt; </code></pre> <p>cart.component.ts</p> <p>`</p> <pre><code>import { Component, OnInit } from '@angular/core'; import { NavbarserviceService } from 'src/app/navbarservice.service'; import { CartService } from 'src/app/service/cart.service'; @Component({ selector: 'app-cart', templateUrl: './cart.component.html', styleUrls: ['./cart.component.css'] }) export class CartComponent implements OnInit { public products : any = []; public grandTotal !: number; constructor(private cartService : CartService, public nav: NavbarserviceService) { } ngOnInit(): void { this.nav.show(); this.cartService.getProducts() .subscribe(res=&gt;{ this.products = res; this.grandTotal = this.cartService.getTotalPrice(); }); } // removeItem(item: any){ // this.cartService.removeCartItem(item); // } // emptycart(){ // this.cartService.removeAllCart(); // } } </code></pre> <p>cart.service.ts</p> <p>`</p> <pre><code>import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; import { HttpClient } from '@angular/common/http'; import { LoginService } from '../component/login/login.service'; import { UserCart } from './cart'; import { item } from './product'; @Injectable({ providedIn: 'root' }) export class CartService { public cartItemList: any = [] public productList = new BehaviorSubject&lt;any&gt;([]); public search = new BehaviorSubject&lt;string&gt;(&quot;&quot;); constructor(private http: HttpClient, private login: LoginService) { console.log (&quot;constrcutor called&quot;) } populateDataFromBackend() { console.log (&quot;populateDataFromBackend called&quot;) var cartItemListLocal: any = [] //return this.productList.asObservable(); //Return data from backend var apiRequest: string = &quot;http://localhost:3000/userCart?emailId=&quot; + this.login.loggedInUserID; this.http.get&lt;UserCart[]&gt;(apiRequest) .subscribe(res =&gt; { console.log(res); res.forEach(element =&gt; { console.log(element.emailId, element.productId); var getProductAPI: string = &quot;http://localhost:3000/products?id=&quot; + element.productId; this.http.get&lt;item&gt;(getProductAPI).subscribe(res =&gt; { // console.log(res); cartItemListLocal.push(res); // this.productList.next (res); // productListNew.next (cartItemListLocal); }) }); } ) console.log(&quot;cartItemsLocal\n&quot;); console.log(cartItemListLocal); this.productList.next(cartItemListLocal); } getProducts() { this.populateDataFromBackend(); return this.productList.asObservable(); } setProduct(product: any) { this.cartItemList.push(...product); this.productList.next(product); } addtoCart(product: any) { var cartItem = new UserCart(this.login.loggedInUserID, product.id); console.log(cartItem, &quot;cartItem&quot;); this.http.post(&quot;http://localhost:3000/userCart&quot;, cartItem).subscribe( (data) =&gt; { console.log(&quot;Datasent to cart &quot;, data); } ) /* this.cartItemList.push(cartItem); this.productList.next(this.cartItemList); this.getTotalPrice(); console.log(this.cartItemList,&quot;this.cartItemlist&quot;) this.http.post(&quot;http://localhost:3000/userCart&quot;,this.cartItemList).subscribe( (data) =&gt; { console.log(&quot;Datasent to cart &quot;,data); } ) */ } getTotalPrice(): number { let grandTotal = 0; this.cartItemList.map((a: any) =&gt; { grandTotal += a.total; }) return grandTotal; } // removeCartItem(product: any){ // this.cartItemList.map((a:any, index:any)=&gt;{ // if(product.id=== a.id){ // this.cartItemList.splice(index,1); // } // }) // this.productList.next(this.cartItemList); // } // removeAllCart(){ // this.cartItemList = [] // this.productList.next(this.cartItemList); // } } </code></pre> <p>product.ts</p> <pre><code>export class item { id!: number; title!: string; price!: number; description!: string; category!: string; image!: string; /* &quot;rating&quot;: { &quot;rate&quot;: 3.9, &quot;count&quot;: 120 }*/ </code></pre> <p>}</p>
[ { "answer_id": 74511511, "author": "MrC aka Shaun Curtis", "author_id": 13065781, "author_profile": "https://Stackoverflow.com/users/13065781", "pm_score": 1, "selected": false, "text": "Titem Id public interface IWithIntId\n{\n public int Id {get;}\n} \n public class GridRow<TItem> : \n where TItem : class, IWithIntId\n{\n public TItem Item { get; set; } = default!;\n public int Id { get; set; } = default!;\n}\n GridRow" }, { "answer_id": 74511543, "author": "Musaffar Patel", "author_id": 3469841, "author_profile": "https://Stackoverflow.com/users/3469841", "pm_score": 0, "selected": false, "text": "<Grid Items=\"Transactions\" @ref=\"MyGrid\">\n <GridBody Context=\"row\">\n <GridCell>@row.Item.Date</GridCell>\n <GridCell>\n @row.Id\n </GridCell>\n </GridBody>\n</Grid> \n <table>\n <tbody>\n @foreach (var row in Rows)\n {\n <tr>\n @GridBody(row)\n </tr>\n }\n </tbody>\n</table>\n public class GridRow<TItem>\n{\n public TItem Item { get; set; } = default!;\n public int Id { get; set; } = default!;\n}\n\npublic partial class Grid<TItem>\n{\n [Parameter]\n public RenderFragment<GridRow<TItem>> GridBody { get; set; } = default!;\n\n [Parameter]\n public IList<TItem> Items { get; set; } = default!;\n\n public List<GridRow<TItem>> Rows { get; set; } = new();\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20532213/" ]
74,511,438
<p>I'm trying to create a tkinter window in which I have a timer counting down, and a button. Once I press the button, I'd like the timer to continuously count down. The text in the window should count down once every second as well, up until it hits 0:00.</p> <p>So far, I've used this code. I've tried time.sleep() and window.after() to try and time it, but all my tkinter window is showing is either 2:00 before I press the button, and 0:00 one second later.</p> <pre><code> def countdown(): total_seconds = 60 total_minutes = 2 while total_seconds != 0: if total_seconds == 60: total_seconds -= 1 total_minutes -= 1 time.sleep(1) canvas.itemconfig(timer_text, text=f&quot;{total_minutes}:{total_seconds}&quot;) elif total_seconds == 1 and total_minutes != 0: total_seconds += 59 time.sleep(1) canvas.itemconfig(timer_text, text=f&quot;{total_minutes}:00&quot;) elif total_seconds == 0 and total_minutes &gt; 0: total_seconds = 59 total_minutes -= 1 time.sleep(1) canvas.itemconfig(timer_text, text=f&quot;{total_minutes}:{total_seconds}&quot;) elif total_seconds &lt; 10: total_seconds -= 1 time.sleep(1) canvas.itemconfig(timer_text, text=f&quot;{total_minutes}:0{total_seconds}&quot;) else: total_seconds -= 1 time.sleep(1) canvas.itemconfig(timer_text, text=f&quot;{total_minutes}:{total_seconds}&quot;) window = Tk() window.title(&quot;Title comes here&quot;) window.config(padx=100, pady=50, bg=BLUE) canvas = Canvas(width=400, height=450, bg=BLUE, highlightthickness=0) timer_text = canvas.create_text(210, 100, text=&quot;2:00&quot;, fill=&quot;white&quot;, font=(FONT_NAME, 35, &quot;bold&quot;)) canvas.grid(column=1, row=1) start_button = Button(text=&quot;Start&quot;, command=countdown) start_button.grid(column=0, row=2) </code></pre>
[ { "answer_id": 74511511, "author": "MrC aka Shaun Curtis", "author_id": 13065781, "author_profile": "https://Stackoverflow.com/users/13065781", "pm_score": 1, "selected": false, "text": "Titem Id public interface IWithIntId\n{\n public int Id {get;}\n} \n public class GridRow<TItem> : \n where TItem : class, IWithIntId\n{\n public TItem Item { get; set; } = default!;\n public int Id { get; set; } = default!;\n}\n GridRow" }, { "answer_id": 74511543, "author": "Musaffar Patel", "author_id": 3469841, "author_profile": "https://Stackoverflow.com/users/3469841", "pm_score": 0, "selected": false, "text": "<Grid Items=\"Transactions\" @ref=\"MyGrid\">\n <GridBody Context=\"row\">\n <GridCell>@row.Item.Date</GridCell>\n <GridCell>\n @row.Id\n </GridCell>\n </GridBody>\n</Grid> \n <table>\n <tbody>\n @foreach (var row in Rows)\n {\n <tr>\n @GridBody(row)\n </tr>\n }\n </tbody>\n</table>\n public class GridRow<TItem>\n{\n public TItem Item { get; set; } = default!;\n public int Id { get; set; } = default!;\n}\n\npublic partial class Grid<TItem>\n{\n [Parameter]\n public RenderFragment<GridRow<TItem>> GridBody { get; set; } = default!;\n\n [Parameter]\n public IList<TItem> Items { get; set; } = default!;\n\n public List<GridRow<TItem>> Rows { get; set; } = new();\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19296266/" ]
74,511,536
<p>I'm trying capture 2 groups of numbers, where each group is optional and should only be captured if contains numbers. Here is a list of all valid combinations that it supposed to match:</p> <ol> <li><code>123(456)</code></li> <li><code>123</code></li> <li><code>(456)</code></li> <li><code>abc(456)</code></li> <li><code>123(efg)</code></li> </ol> <p>And these are not valid combinations and should <strong>not</strong> be matched:</p> <ol start="6"> <li><code>abc(efg)</code></li> <li><code>abc</code></li> <li><code>(efg)</code></li> </ol> <p>However, my regex fails on <code>#4</code> and <code>#5</code> combinations even though they contain numbers.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const list = ["123(456)", "123", "(456)", "abc(456)", "123(def)", "abc(def)", "abc", "(def)"]; const regex = /^(?:(\d+))?(?:\((\d+)\))?$/; list.map((a,i) =&gt; console.log(i+1+". ", a + "=&gt;".padStart(11-a.length," "), JSON.stringify((a.match(regex)||[]).slice(1))));</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{top:0;max-height:unset!important;overflow:auto!important;}</code></pre> </div> </div> </p> <p>So, the question is why when used <code>?</code> behind a group, it doesn't &quot;skip&quot; that group if nothing matched?</p> <p>P.S. With this regex it also captures <code>#4</code>, but not <code>#5</code>: <code>/(?:^|(\d+)?)(?:\((\d+)\))?$/</code></p>
[ { "answer_id": 74511511, "author": "MrC aka Shaun Curtis", "author_id": 13065781, "author_profile": "https://Stackoverflow.com/users/13065781", "pm_score": 1, "selected": false, "text": "Titem Id public interface IWithIntId\n{\n public int Id {get;}\n} \n public class GridRow<TItem> : \n where TItem : class, IWithIntId\n{\n public TItem Item { get; set; } = default!;\n public int Id { get; set; } = default!;\n}\n GridRow" }, { "answer_id": 74511543, "author": "Musaffar Patel", "author_id": 3469841, "author_profile": "https://Stackoverflow.com/users/3469841", "pm_score": 0, "selected": false, "text": "<Grid Items=\"Transactions\" @ref=\"MyGrid\">\n <GridBody Context=\"row\">\n <GridCell>@row.Item.Date</GridCell>\n <GridCell>\n @row.Id\n </GridCell>\n </GridBody>\n</Grid> \n <table>\n <tbody>\n @foreach (var row in Rows)\n {\n <tr>\n @GridBody(row)\n </tr>\n }\n </tbody>\n</table>\n public class GridRow<TItem>\n{\n public TItem Item { get; set; } = default!;\n public int Id { get; set; } = default!;\n}\n\npublic partial class Grid<TItem>\n{\n [Parameter]\n public RenderFragment<GridRow<TItem>> GridBody { get; set; } = default!;\n\n [Parameter]\n public IList<TItem> Items { get; set; } = default!;\n\n public List<GridRow<TItem>> Rows { get; set; } = new();\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2930038/" ]
74,511,561
<p>I was trying to search the docs for a method similar but I was only able to find pythons all() and any(). But that's not the same because it just checks if the val is truthy instead of creating your own condition like in js' every and some method. i.e</p> <pre><code>// return true if all vals are greater than 1 const arr1 = [2, 3, 6, 10, 4, 23]; console.log(arr1.every(val =&gt; val &gt; 1)); // true // return true if any val is greater than 20 const arr2 = [2, 3, 6, 10, 4, 23]; console.log(arr2.some(val =&gt; val &gt; 20)); // true </code></pre> <p>Is there a similar method that can do this in python?</p>
[ { "answer_id": 74511596, "author": "juanpa.arrivillaga", "author_id": 5014455, "author_profile": "https://Stackoverflow.com/users/5014455", "pm_score": 3, "selected": true, "text": "arr1 = [2, 3, 6, 10, 4, 23]\nprint(all(val > 1 for val in arr1))\n\narr2 = [2, 3, 6, 10, 4, 23]\nprint(any(val > 20 for val in arr2))\n map arr1 = [2, 3, 6, 10, 4, 23]\nprint(all(map(lambda val: val > 1, arr1)))\n\narr2 = [2, 3, 6, 10, 4, 23]\nprint(any(map(lambda val: val > 20, arr2)))\n" }, { "answer_id": 74511609, "author": "Nave Twizer", "author_id": 17254732, "author_profile": "https://Stackoverflow.com/users/17254732", "pm_score": 1, "selected": false, "text": "numbers = [1, 2, 3, 4, 5]\nall_are_one = all(elem == 1 for elem in numbers)\nsome_are_one = any(elem == 1 for elem in numbers)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16693156/" ]
74,511,582
<p>I want to return just some of the data of my lovely printer. (The name always contains <code>STMicroelectronics printer</code></p> <p>I can print out all plugged USB devices with the <code>lsusb</code> command. This will give me (first line obviously being the printer):</p> <pre><code>Bus 001 Device 004: ID 0483:5743 STMicroelectronics printer-80 Bus 001 Device 003: ID 0424:ec00 Microchip Technology, Inc. (formerly SMSC) SMSC9512/9514 Fast Ethernet Adapter Bus 001 Device 002: ID 0424:9514 Microchip Technology, Inc. (formerly SMSC) SMC9514 Hub Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub` </code></pre> <p>I can now find the device's details via <code>lsusb -vvv -d 0483:5743</code>, which returns:</p> <pre><code>Bus 001 Device 004: ID 0483:5743 STMicroelectronics printer-80 Device Descriptor: bLength 18 bDescriptorType 1 bcdUSB 2.00 bDeviceClass 0 bDeviceSubClass 0 bDeviceProtocol 0 bMaxPacketSize0 64 idVendor 0x0483 STMicroelectronics idProduct 0x5743 bcdDevice 1.00 iManufacturer 1 Printer iProduct 2 printer-80 iSerial 3 012345678AB bNumConfigurations 1 Configuration Descriptor: bLength 9 bDescriptorType 2 wTotalLength 0x0020 bNumInterfaces 1 bConfigurationValue 1 iConfiguration 0 bmAttributes 0xc0 Self Powered MaxPower 2mA Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber 0 bAlternateSetting 0 bNumEndpoints 2 bInterfaceClass 7 Printer bInterfaceSubClass 1 Printer bInterfaceProtocol 2 Bidirectional iInterface 0 Endpoint Descriptor: bLength 7 bDescriptorType 5 bEndpointAddress 0x01 EP 1 OUT bmAttributes 2 Transfer Type Bulk Synch Type None Usage Type Data wMaxPacketSize 0x0040 1x 64 bytes bInterval 0 Endpoint Descriptor: bLength 7 bDescriptorType 5 bEndpointAddress 0x81 EP 1 IN bmAttributes 2 Transfer Type Bulk Synch Type None Usage Type Data wMaxPacketSize 0x0040 1x 64 bytes bInterval 0 can't get device qualifier: Resource temporarily unavailable can't get debug descriptor: Resource temporarily unavailable Device Status: 0x0001 Self Powered </code></pre> <p>Now... How can I just return these data via bash:</p> <pre><code>idVendor (0x0483) idProduct (0x5743) endpointOUT (0x01) endpointIN (0x81) </code></pre> <p>There must be some grep/regex magic that I just couldn't manage to master.</p> <p>Thanks for any help in advance!</p> <p>Searing for solutions to extract the line containing the printer description with regex.</p>
[ { "answer_id": 74511596, "author": "juanpa.arrivillaga", "author_id": 5014455, "author_profile": "https://Stackoverflow.com/users/5014455", "pm_score": 3, "selected": true, "text": "arr1 = [2, 3, 6, 10, 4, 23]\nprint(all(val > 1 for val in arr1))\n\narr2 = [2, 3, 6, 10, 4, 23]\nprint(any(val > 20 for val in arr2))\n map arr1 = [2, 3, 6, 10, 4, 23]\nprint(all(map(lambda val: val > 1, arr1)))\n\narr2 = [2, 3, 6, 10, 4, 23]\nprint(any(map(lambda val: val > 20, arr2)))\n" }, { "answer_id": 74511609, "author": "Nave Twizer", "author_id": 17254732, "author_profile": "https://Stackoverflow.com/users/17254732", "pm_score": 1, "selected": false, "text": "numbers = [1, 2, 3, 4, 5]\nall_are_one = all(elem == 1 for elem in numbers)\nsome_are_one = any(elem == 1 for elem in numbers)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5436196/" ]
74,511,585
<p>Short version: Hi, how do i open ttf or otf (whichever is easier) in text like manner so i can manually edit/delete vectors for each letter inside the font?</p> <p>Long version: I made font in FontForge (single stroke) for CAD/CAM from SVG files. Its good and looks like single line font as it should until i convert the letters into entities inside CAD, each and every line inside the font has duplicates stacked on eachother (my suspision is that font generator creates these duplicates to trick windows into readable text). So i would like to open font i made in like xml manner or whatever and delete the duplicated vectors generated by FontForge.</p> <p>I do have true single stroke font (in ttf format) that when converted into entities in CAD it doesnt have any duplicates, so i opened the font in FontForge and generated new version of it. When new version converted into entities inside CAD it does have duplicates (but original doesnt). I tried also FontCreator which yielded same results. I also opened the font in 010 Editor but even if i knew what to look for i doubt it would work anyway. I understand that font is some kind of table format but if FontForge can read any font you throw at it, knows vectors for each letter and shows it in graphical setup i kinda dont understand why i cant seem to find a way to edit the vectors manually in text editor of some sort. (I need new single stroke font as customer doesnt like the one i already got). Also i need to convert the font into entities inside CAD so i can move the letters separatly on 3D curve where equal spacing of letters next to eachother or putting {space} between them yields somewhat unusable results.</p>
[ { "answer_id": 74511596, "author": "juanpa.arrivillaga", "author_id": 5014455, "author_profile": "https://Stackoverflow.com/users/5014455", "pm_score": 3, "selected": true, "text": "arr1 = [2, 3, 6, 10, 4, 23]\nprint(all(val > 1 for val in arr1))\n\narr2 = [2, 3, 6, 10, 4, 23]\nprint(any(val > 20 for val in arr2))\n map arr1 = [2, 3, 6, 10, 4, 23]\nprint(all(map(lambda val: val > 1, arr1)))\n\narr2 = [2, 3, 6, 10, 4, 23]\nprint(any(map(lambda val: val > 20, arr2)))\n" }, { "answer_id": 74511609, "author": "Nave Twizer", "author_id": 17254732, "author_profile": "https://Stackoverflow.com/users/17254732", "pm_score": 1, "selected": false, "text": "numbers = [1, 2, 3, 4, 5]\nall_are_one = all(elem == 1 for elem in numbers)\nsome_are_one = any(elem == 1 for elem in numbers)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557111/" ]
74,511,594
<p>C++ standard allows <code>constexpr volatile</code> variables per <a href="https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4093.html#1688" rel="noreferrer">defect report 1688</a>, which was resolved in September 2013:</p> <blockquote> <p>The combination is intentionally permitted and could be used in some circumstances to force constant initialization.</p> </blockquote> <p>It looks though that the intention was to allow only <code>constinit volatile</code>, which was not available before C++20.</p> <p>Still the current compilers diverge in treatment of <code>constexpr volatile</code> in certain circumstances. For example, this program initializes one such variable by the other one:</p> <pre><code>int main() { constexpr volatile int i = 0; constexpr volatile int j = i; return j; } </code></pre> <p>It is accepted in GCC and MSVC, but Clang complains:</p> <pre><code>error: constexpr variable 'j' must be initialized by a constant expression constexpr volatile int j = i; ^ ~ note: read of volatile-qualified type 'const volatile int' is not allowed in a constant expression constexpr volatile int j = i; </code></pre> <p>Online demo: <a href="https://gcc.godbolt.org/z/43ee65Peq" rel="noreferrer">https://gcc.godbolt.org/z/43ee65Peq</a></p> <p>Which compiler is right here and why?</p>
[ { "answer_id": 74512560, "author": "Maciej Polański", "author_id": 19165018, "author_profile": "https://Stackoverflow.com/users/19165018", "pm_score": 4, "selected": false, "text": "volatile" }, { "answer_id": 74512715, "author": "Brian Bi", "author_id": 481267, "author_profile": "https://Stackoverflow.com/users/481267", "pm_score": 5, "selected": true, "text": "j i i volatile i constexpr" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7325599/" ]
74,511,656
<p>I'm working on a text-based Choose Your Own Adventure game in Python for an online class. The game has a list of random &quot;villains&quot; that you may encounter. The original project just has you going to the cave and finding a magical sword that you use to fight the villain. I wanted to set it so that the &quot;weapon&quot; would change according to whatever villian is selected randomly for the list. I listed the code I came up with (below), but it is not recognizing the choice of creature. Instead, it is returning the sword each time. What am I doing wrong?</p> <pre><code>creatures = [&quot;wicked fairy&quot;, &quot;gorgon&quot;, &quot;troll&quot;, &quot;dragon&quot;, &quot;small child&quot;, &quot;Karen&quot;, &quot;ex-wife&quot;] weapons = [&quot;Sword of Ogoroth&quot;, &quot;Nintendo Switch&quot;, &quot;social media&quot;, &quot;alimony&quot;] creature = random.choice(creatures) items = [] if {creature} == &quot;wicked fairy&quot; or &quot;gorgon&quot; or &quot;troll&quot; or &quot;dragon&quot;: # print messages here items.append(&quot;sword&quot;) elif {creature} == &quot;small child&quot;: # print messages here items.append(&quot;Switch&quot;) elif {creature} == &quot;Karen&quot;: # print messages here items.append(&quot;phone&quot;) else: # print messages here items.append(&quot;money&quot;) # edited to pare down the code so that only the relevant sections were listed I tried using random choice and conditional statements. </code></pre>
[ { "answer_id": 74511799, "author": "Claudio", "author_id": 7711283, "author_profile": "https://Stackoverflow.com/users/7711283", "pm_score": 1, "selected": false, "text": "if {creature} == \"wicked fairy\" or \"gorgon\" or \"troll\" or \"dragon\":\n or if creature in [\"wicked fairy\", \"gorgon\", \"troll\", \"dragon\"]:\n elif" }, { "answer_id": 74511837, "author": "Jan", "author_id": 16483054, "author_profile": "https://Stackoverflow.com/users/16483054", "pm_score": 0, "selected": false, "text": "if creature == \"wicked fairy\" or creature == \"gorgon\" or creature == \"troll\" or creature == \"dragon\":" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557363/" ]
74,511,666
<p>I have the following from a MIME message;</p> <pre><code>--------------ra650umTsDNeI5lwXmFy5luF Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: base64 TG9yZW0gSXBzdW0NCg0KSGVyZSBpcyBzb21lIG1vcmUgdGV4dA0KDQpOb3cgb24gYSAzcmQg bGluZQ0KDQoNClRoYW5rcw0KDQo= --------------ra650umTsDNeI5lwXmFy5luF-- </code></pre> <p>I want to extract the base64 encoded message, regardless of how many lines it is.</p> <p>The following will indeed find matches on each individual line, but how can I group them so that if there are multiple lines of base64 that matches, it will group them as &quot;together&quot;</p> <pre><code>var base64Regex = /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{4}|[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{2}={2})$/gm </code></pre> <p>When the MIME content for example also contains a PGP signature, this would give me 4 or 5 matches, so I can't simply join them, because it will find that base64 as well.</p> <p>Ideally I'd modify this so it gets everything from/including the first match to <code>----------</code> and says that is &quot;match 1&quot; and if it finds another block of base64, that is &quot;match 2&quot;, etc.</p> <p>Here is a link to regex101 showing 2 matches. In short, I would like for this to be one match.</p> <p><a href="https://regex101.com/r/32WjKa/1" rel="nofollow noreferrer">https://regex101.com/r/32WjKa/1</a></p>
[ { "answer_id": 74511736, "author": "Beyondo", "author_id": 8524922, "author_profile": "https://Stackoverflow.com/users/8524922", "pm_score": 1, "selected": false, "text": "var base64Regex = /Content-Transfer-Encoding: base64([\\s\\S]*?)\\s*?--/g;\n Content-Transfer-Encoding: base64 [\\s\\S]*? \\s*? -- g" }, { "answer_id": 74511741, "author": "Andy Ray", "author_id": 743464, "author_profile": "https://Stackoverflow.com/users/743464", "pm_score": 0, "selected": false, "text": ". /s . replace() const str = `--------------ra650umTsDNeI5lwXmFy5luF\nContent-Type: text/plain; charset=UTF-8; format=flowed\nContent-Transfer-Encoding: base64\n\nTG9yZW0gSXBzdW0NCg0KSGVyZSBpcyBzb21lIG1vcmUgdGV4dA0KDQpOb3cgb24gYSAzcmQg\nbGluZQ0KDQoNClRoYW5rcw0KDQo=\n\n--------------ra650umTsDNeI5lwXmFy5luF--`\n\nconst payload = str.match(/base64\\n\\n(.+)\\n\\n--------------.+/ms)[1].replace(/\\n/g, '')\n" }, { "answer_id": 74513231, "author": "Peter Thoeny", "author_id": 7475450, "author_profile": "https://Stackoverflow.com/users/7475450", "pm_score": 0, "selected": false, "text": ".replace() .match() const input = `--------------ra650umTsDNeI5lwXmFy5luF\nContent-Type: text/plain; charset=UTF-8; format=flowed\nContent-Transfer-Encoding: base64\n\nTG9yZW0gSXBzdW0NCg0KSGVyZSBpcyBzb21lIG1vcmUgdGV4dA0KDQpOb3cgb24gYSAzcmQg\nbGluZQ0KDQoNClRoYW5rcw0KDQo=\n\n--------------ra650umTsDNeI5lwXmFy5luF--`;\n\nconst regex1 = /^.*?Content-Transfer-Encoding: base64\\s+(.*?)\\s*---.*$/is;\nlet result1 = input.replace(regex1, '$1');\nconsole.log(result1);\n\nconst regex2 = /(?<=Content-Transfer-Encoding: base64\\s+).*?(?=\\s*---)/is;\nlet result2 = input.match(regex2);\nconsole.log(result2[0]); TG9yZW0gSXBzdW0NCg0KSGVyZSBpcyBzb21lIG1vcmUgdGV4dA0KDQpOb3cgb24gYSAzcmQg\nbGluZQ0KDQoNClRoYW5rcw0KDQo=\n\nTG9yZW0gSXBzdW0NCg0KSGVyZSBpcyBzb21lIG1vcmUgdGV4dA0KDQpOb3cgb24gYSAzcmQg\nbGluZQ0KDQoNClRoYW5rcw0KDQo=\n .replace() ^ .*?Content-Transfer-Encoding: base64\\s+ base 64 (.*?) \\s*---.* --- $ is . .match() (?<=Content-Transfer-Encoding: base64\\s+) ...base64 .*? (?=\\s*---) --- is . ---" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/229072/" ]
74,511,705
<p>I am currently working with the <a href="https://pokeapi.co/" rel="nofollow noreferrer">PokeAPI</a>, I am doing fetch requests to recieve back the JSON at a given endpoint, then trying to parse and return it. The function for doing this can be found here:</p> <pre class="lang-js prettyprint-override"><code>function getPokemon(id){ pokemonData = { name:&quot;&quot;, image:&quot;&quot;, id:id, description:&quot;&quot; } // Documentation https://pokeapi.co/docs/v2#pokemon-species fetch(`https://pokeapi.co/api/v2/pokemon-species/${id}/`) .then((response) =&gt; response.json()) .then((data) =&gt; { pokemonData.description = data.flavor_text_entries[0].flavor_text.toString() } ) // Documentation: https://pokeapi.co/docs/v2#pokemon fetch(`https://pokeapi.co/api/v2/pokemon/${id}/`) .then((response) =&gt; response.json()) .then((data) =&gt; { pokemonData[&quot;image&quot;] = data.sprites.other[&quot;official-artwork&quot;].front_default.toString() pokemonData[&quot;name&quot;] = data.name.toString() } ) return pokemonData } </code></pre> <p>Once the data is returned trying to access attributes are blank, but the object displays the correct info:</p> <p><a href="https://i.stack.imgur.com/a15KY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a15KY.png" alt="enter image description here" /></a></p> <p>I'm not sure what seems to be going wrong here. I have tried every different attribute access format <code>data.name</code> vs <code>data[&quot;name&quot;]</code> and none seem to make a difference. Any help would be appreciated</p>
[ { "answer_id": 74511706, "author": "Kieran Wood", "author_id": 11602400, "author_profile": "https://Stackoverflow.com/users/11602400", "pm_score": 0, "selected": false, "text": ".then() async function getPokemon(id){\n \n pokemonData = {\n name:\"\",\n image:\"\",\n id:id,\n description:\"\"\n }\n \n // Documentation https://pokeapi.co/docs/v2#pokemon-species\n await fetch(`https://pokeapi.co/api/v2/pokemon-species/${id}/`)\n .then((response) => response.json())\n .then((data) => {\n \n pokemonData.description = data.flavor_text_entries[0].flavor_text.toString()\n \n }\n )\n \n // Documentation: https://pokeapi.co/docs/v2#pokemon\n await fetch(`https://pokeapi.co/api/v2/pokemon/${id}/`)\n .then((response) => response.json())\n .then((data) => {\n \n pokemonData.image = data.sprites.other[\"official-artwork\"].front_default\n pokemonData.name = data.name\n console.log(data.name)\n \n }\n )\n return pokemonData\n}\n" }, { "answer_id": 74511845, "author": "Emiel Zuurbier", "author_id": 11619647, "author_profile": "https://Stackoverflow.com/users/11619647", "pm_score": 2, "selected": true, "text": "async / await await fetch fetch Promise.all() pokemonData async function getPokemon(id) {\n const speciesRequest = fetch(`https://pokeapi.co/api/v2/pokemon-species/${id}/`)\n .then((response) => response.json())\n \n const pokemonRequest fetch(`https://pokeapi.co/api/v2/pokemon/${id}/`)\n .then((response) => response.json())\n \n try {\n const [speciesData, pokemonData] = await Promise.all([speciesRequest, pokemonRequest]);\n\n return ({\n id,\n image: pokemonData.sprites.other[\"official-artwork\"].front_default,\n name: pokemonData.name,\n description: speciesData.flavor_text_entries[0].flavor_text.toString()\n });\n catch (error) {\n return Promise.reject(error);\n }\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11602400/" ]
74,511,731
<p>How can be converted integers from string in C?</p> <p>What is the easiest way? I need programm function like:</p> <pre><code>fraction create_fraction_from_string(char *str) </code></pre> <p>Where I will in the main file call function like:</p> <pre><code>fraction create_fraction_from_string(&quot;-12/4&quot;) </code></pre> <p>And the result should be two integers:</p> <pre><code>int a = -12; int b = 4; </code></pre> <p>I think, that I split the string and after that convert these two strings... I am new in C programming...</p> <p>EDIT:</p> <p>fractions is:</p> <pre><code>typedef struct { int a; int b; } fraction; </code></pre> <p>And the input always be in &quot;x/y&quot; or &quot;-x/y&quot;</p> <p>And the result should be:</p> <pre><code>fraction res = { .a = -12, .b = 4 }; </code></pre>
[ { "answer_id": 74515966, "author": "David C. Rankin", "author_id": 3422102, "author_profile": "https://Stackoverflow.com/users/3422102", "pm_score": 1, "selected": true, "text": "fgets() EOF sscanf() create_fraction_from_string() bool true/false int 0/1 fraction main() create_fraction_from_string() #include <stdio.h>\n\n#define FRACFMT \"%d/%d\" /* if you need a constant, #define one (or more) */\n#define FRACCNV 2\n\ntypedef struct { \n int a, b; \n} fraction;\n\n/* fill frac from str using sscanf (str, fmt, ...), validate nconv\n * conversions. Returns 1 on success, O otherwise.\n */\nint create_fraction_from_string (fraction *frac, const char *str,\n const char *fmt, const int nconv)\n{\n /* parse fmt from string into frac->a, frac->b, validate nconv */\n if (sscanf (str, fmt, &frac->a, &frac->b) != nconv) {\n return 0; /* return failure */\n }\n \n return 1; /* return success */\n}\n\nint main (void) {\n /* BUFSIZ 4096 on Linux, 512 on Windows */\n char line[BUFSIZ]; /* buffer to hold line of input */\n fraction frac = { .a = 0 }; /* fraction to hold result */\n \n fputs (\"enter fraction (\\\"int/int\\\"): \", stdout); /* prompt */\n \n if (!fgets (line, BUFSIZ, stdin)) { /* read into buffer, validate */\n puts (\"(user canceled input)\"); /* handle manual EOF */\n return 0;\n }\n \n /* call create_fraction_from_string(), validate return */\n if (!create_fraction_from_string (&frac, line, FRACFMT, FRACCNV)) {\n fputs (\"error: invalid input, must be \\\"int / int\\\".\\n\", stderr);\n return 1;\n } \n \n /* output result */\n printf (\"\\nfrac.a : %d\\nfrac.b : %d\\n\", frac.a, frac.b);\n}\n 0 create_fraction_from_string() $ ./bin/readfraction\nenter fraction (\"int/int\"): -12/4\n\nfrac.a : -12\nfrac.b : 4\n" }, { "answer_id": 74516247, "author": "klutt", "author_id": 6699433, "author_profile": "https://Stackoverflow.com/users/6699433", "pm_score": 1, "selected": false, "text": "int create_fraction_from_string (fraction *frac, const char *str)\n{\n const char *fmt = \"%d/%d\";\n\n return (sscanf (str, fmt, &frac->a, &frac->b) == 2);\n}\n frac" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18905898/" ]
74,511,732
<p>i have the following code in a footer of a web app. i would like to know how could i add an image instead of text. thanks here is my code `</p> <pre><code>&lt;footer id=&quot;page-footer&quot; class=&quot;bg-body-light border-top&quot;&gt; &lt;div class=&quot;content py-0&quot;&gt; &lt;div class=&quot;row font-size-sm&quot;&gt; &lt;div class=&quot;col-sm-6 order-sm-2 mb-1 mb-sm-0 text-center text-sm-right&quot;&gt; Crafted with &lt;i class=&quot;fa fa-heart text-danger&quot;&gt;&lt;/i&gt; by &lt;a class=&quot;font-w600&quot; href=&quot;javascript:void(0);&quot; target=&quot;_blank&quot;&gt;ORTHOLogika&lt;/a&gt; ** &lt;img src=&quot;../assets/media/photos/logo1.png&quot; alt=&quot;Responsive image&quot; &gt;** &lt;/div&gt; &lt;div class=&quot;col-sm-6 order-sm-1 text-center text-sm-left&quot;&gt; &lt;a class=&quot;font-w600&quot; href=&quot;javascript:void(0);&quot; target=&quot;_blank&quot;&gt;ORTHOLogika 1.0&lt;/a&gt; &amp;copy; &lt;span data-toggle=&quot;year-copy&quot;&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/footer&gt; </code></pre> <p>` <a href="https://i.stack.imgur.com/GLorL.png" rel="nofollow noreferrer">enter image description here</a></p> <p>i dont know how to import the image in the footer</p>
[ { "answer_id": 74511830, "author": "Abdulkhaliq Ghwainm", "author_id": 4879561, "author_profile": "https://Stackoverflow.com/users/4879561", "pm_score": 1, "selected": false, "text": "<img> <img> src alt <img src=\"img_girl.jpg\" alt=\"Girl in a jacket\" width=\"500\" height=\"600\">\n" }, { "answer_id": 74512455, "author": "Prerna Jena", "author_id": 11519496, "author_profile": "https://Stackoverflow.com/users/11519496", "pm_score": 0, "selected": false, "text": "<header>\n <div id=\"top-header\"> \n <!-- Logo -->\n <div id=\"logo\">\n <img src=\"images/logo.png\" />\n </div> \n <!-- Navigation Menu -->\n <nav>\n <ul>\n <li class=\"active\"><a href=\"#\">Home</a></li>\n <li><a href=\"#\">About Us</a></li>\n <li><a href=\"#\">Our Products</a></li>\n <li><a href=\"#\">Careers</a></li>\n <li><a href=\"#\">Contact Us</a></li>\n </ul>\n </nav>\n </div>\n <!-- Image menu in Header to contain an Image and\n a sample text over that image -->\n <div id=\"header-image-menu\">\n </div>\n</header>\n\n#header-image-menu{\n top: 10px;\n position: relative;\n}\n#header-image-menu img{\n width: 100%;\n margin: none;\n padding: none;\n}\n#image-text{\n position: absolute;\n top: 60%;\n left: 60%;\n font-family: 'Roboto';\n color: #000;\n transform: translate(-30%, -30%);\n text-align: center;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557381/" ]
74,511,760
<p>I'm using the official Airflow Helm to try out the new LocalKubernetesExecutor feature. However, I also wanted the following:</p> <ol> <li>allow helm to bring up the postgresql container</li> <li>change the credentials, username and database for that container.</li> </ol> <p>I don't really know how to do this. I tried overriding the file section postgresql:</p> <pre><code>postgresql: enabled: true postgresqlPassword: airflow postgresqlUsername: airflow </code></pre> <p>But it doesn't seem to do anything. I fetched the connection that was created and decoded the base64 string:</p> <pre><code> kubectl get secret airflow-airflow-metadata -o json { &quot;apiVersion&quot;: &quot;v1&quot;, &quot;data&quot;: { &quot;connection&quot;: &quot;cG9zdGdyZXNxbDovL3Bvc3RncmVzOnBvc3RncmVzQGFpcmZsb3ctcG9zdGdyZXNxbC5haXJmbG93OjU0MzIvcG9zdGdyZXM/c3NsbW9kZT1kaXNhYmxl&quot; }, &quot;kind&quot;: &quot;Secret&quot;, &quot;metadata&quot;: { &quot;annotations&quot;: { &quot;meta.helm.sh/release-name&quot;: &quot;airflow&quot;, &quot;meta.helm.sh/release-namespace&quot;: &quot;airflow&quot; }, &quot;creationTimestamp&quot;: &quot;2022-11-20T20:14:30Z&quot;, &quot;labels&quot;: { &quot;app.kubernetes.io/managed-by&quot;: &quot;Helm&quot;, &quot;chart&quot;: &quot;airflow&quot;, &quot;heritage&quot;: &quot;Helm&quot;, &quot;release&quot;: &quot;airflow&quot;, &quot;tier&quot;: &quot;airflow&quot; }, &quot;name&quot;: &quot;airflow-airflow-metadata&quot;, &quot;namespace&quot;: &quot;airflow&quot;, &quot;resourceVersion&quot;: &quot;7643&quot;, &quot;uid&quot;: &quot;14fff962-aec8-4862-b598-4ae3dbeca26f&quot; }, &quot;type&quot;: &quot;Opaque&quot; } </code></pre> <p>When I decode the connection:</p> <pre><code>echo cG9zdGdyZXNxbDovL3Bvc3RncmVzOnBvc3RncmVzQGFpcmZsb3ctcG9zdGdyZXNxbC5haXJmbG93OjU0MzIvcG9zdGdyZXM/c3NsbW9kZT1kaXNhYmxl | base64 -D postgresql://postgres:postgres@airflow-postgresql.airflow:5432/postgres?sslmode=disable% </code></pre> <p>I'm beginning to think that it is something very simple I'm missing, or it can't be done.</p> <p>So, the question is - how to override postgres user, password, and database when using official Airflow Helm? Can it be done?</p>
[ { "answer_id": 74511830, "author": "Abdulkhaliq Ghwainm", "author_id": 4879561, "author_profile": "https://Stackoverflow.com/users/4879561", "pm_score": 1, "selected": false, "text": "<img> <img> src alt <img src=\"img_girl.jpg\" alt=\"Girl in a jacket\" width=\"500\" height=\"600\">\n" }, { "answer_id": 74512455, "author": "Prerna Jena", "author_id": 11519496, "author_profile": "https://Stackoverflow.com/users/11519496", "pm_score": 0, "selected": false, "text": "<header>\n <div id=\"top-header\"> \n <!-- Logo -->\n <div id=\"logo\">\n <img src=\"images/logo.png\" />\n </div> \n <!-- Navigation Menu -->\n <nav>\n <ul>\n <li class=\"active\"><a href=\"#\">Home</a></li>\n <li><a href=\"#\">About Us</a></li>\n <li><a href=\"#\">Our Products</a></li>\n <li><a href=\"#\">Careers</a></li>\n <li><a href=\"#\">Contact Us</a></li>\n </ul>\n </nav>\n </div>\n <!-- Image menu in Header to contain an Image and\n a sample text over that image -->\n <div id=\"header-image-menu\">\n </div>\n</header>\n\n#header-image-menu{\n top: 10px;\n position: relative;\n}\n#header-image-menu img{\n width: 100%;\n margin: none;\n padding: none;\n}\n#image-text{\n position: absolute;\n top: 60%;\n left: 60%;\n font-family: 'Roboto';\n color: #000;\n transform: translate(-30%, -30%);\n text-align: center;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1835567/" ]
74,511,761
<p>I try to use polarproxy on a linux station (I try also with Charles proxy and one I develop myself) to intercept SSL traffic from browser and application from an rooted android (version 8). On the phone I use Drony to define the IP of the proxy and the protocol (SOCKS 5). I have copied the certificate of the proxy in the phone.</p> <p>I start Polarporxy with ./PolarProxy -v --socks 192.168.0.42:1080 -w ../aaa.pcap and I got the following message :</p> <pre><code>&lt;6&gt;[1080] SOCKS proxy SOCKS5 connection request from 192.168.0.29:47803 to 92.122.219.187:443 &lt;6&gt;[1080] SOCKS proxy SOCKS5 connection request from 192.168.0.29:47802 to 92.122.219.187:443 &lt;6&gt;[1080] 192.168.0.29:1080 -&gt; ?:443 Connection from: 192.168.0.29:47803 &lt;6&gt;[1080] 192.168.0.29:1080 -&gt; ?:443 Connection from: 192.168.0.29:47802 &lt;6&gt;Loading certificate from /root/.local/share/PolarProxy/e249f9c497d7b5c41339f153a31eda1c.p12 &lt;6&gt;Loading certificate from /root/.local/share/PolarProxy/e249f9c497d7b5c41339f153a31eda1c.p12 &lt;6&gt;[1080] 192.168.0.29:1080 -&gt; www.francetvinfo.fr:443 Connection request for www.francetvinfo.fr from 192.168.0.29:47802 &lt;6&gt;[1080] 192.168.0.29:1080 -&gt; www.francetvinfo.fr:443 Connection request for www.francetvinfo.fr from 192.168.0.29:47803 &lt;3&gt;[1080] 192.168.0.29:1080 -&gt; www.francetvinfo.fr:443 Internal TLS session Exception: SSL Handshake failed with OpenSSL error - SSL_ERROR_SSL. &lt;3&gt;[1080] 192.168.0.29:1080 -&gt; www.francetvinfo.fr:443 Internal TLS session Exception: SSL Handshake failed with OpenSSL error - SSL_ERROR_SSL. &lt;6&gt;Saving debug log to /root/.local/share/IsolatedStorage/la30tgqz.sld/25qha4s2.1bn/Url.pcsrcbwdoyksnrgnsyyusyo5w2jml1vv/AssemFiles/_221120-210434.log &lt;4&gt;[1080] ?:1080 -&gt; www.francetvinfo.fr:443 Internal SSL session did not authenticate successfully &lt;4&gt;[1080] ?:1080 -&gt; www.francetvinfo.fr:443 Internal SSL session did not authenticate successfully </code></pre> <p><a href="https://i.stack.imgur.com/VHnA0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VHnA0.png" alt="Wireshark capture " /></a></p> <p>I am a little lost, I think there is a probleme with the certificate, but I don't know what to do. Thanks in advance. Laurent</p>
[ { "answer_id": 74511830, "author": "Abdulkhaliq Ghwainm", "author_id": 4879561, "author_profile": "https://Stackoverflow.com/users/4879561", "pm_score": 1, "selected": false, "text": "<img> <img> src alt <img src=\"img_girl.jpg\" alt=\"Girl in a jacket\" width=\"500\" height=\"600\">\n" }, { "answer_id": 74512455, "author": "Prerna Jena", "author_id": 11519496, "author_profile": "https://Stackoverflow.com/users/11519496", "pm_score": 0, "selected": false, "text": "<header>\n <div id=\"top-header\"> \n <!-- Logo -->\n <div id=\"logo\">\n <img src=\"images/logo.png\" />\n </div> \n <!-- Navigation Menu -->\n <nav>\n <ul>\n <li class=\"active\"><a href=\"#\">Home</a></li>\n <li><a href=\"#\">About Us</a></li>\n <li><a href=\"#\">Our Products</a></li>\n <li><a href=\"#\">Careers</a></li>\n <li><a href=\"#\">Contact Us</a></li>\n </ul>\n </nav>\n </div>\n <!-- Image menu in Header to contain an Image and\n a sample text over that image -->\n <div id=\"header-image-menu\">\n </div>\n</header>\n\n#header-image-menu{\n top: 10px;\n position: relative;\n}\n#header-image-menu img{\n width: 100%;\n margin: none;\n padding: none;\n}\n#image-text{\n position: absolute;\n top: 60%;\n left: 60%;\n font-family: 'Roboto';\n color: #000;\n transform: translate(-30%, -30%);\n text-align: center;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9122776/" ]
74,511,786
<p>I have an image (blue rect). I want to cut a part of the image by path (red triangle) and create a smaller widget (green rect) that shows this part of the image and has size which equals bounds of cutting path. How can I do it in Flutter?</p> <p><a href="https://i.stack.imgur.com/fkbIR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fkbIR.png" alt="Example" /></a></p> <p>I tried to use <code>ClipPath</code> and <code>CustomClipper&lt;Path&gt;</code>, but I was able to create only widget which has size of the image.</p>
[ { "answer_id": 74511830, "author": "Abdulkhaliq Ghwainm", "author_id": 4879561, "author_profile": "https://Stackoverflow.com/users/4879561", "pm_score": 1, "selected": false, "text": "<img> <img> src alt <img src=\"img_girl.jpg\" alt=\"Girl in a jacket\" width=\"500\" height=\"600\">\n" }, { "answer_id": 74512455, "author": "Prerna Jena", "author_id": 11519496, "author_profile": "https://Stackoverflow.com/users/11519496", "pm_score": 0, "selected": false, "text": "<header>\n <div id=\"top-header\"> \n <!-- Logo -->\n <div id=\"logo\">\n <img src=\"images/logo.png\" />\n </div> \n <!-- Navigation Menu -->\n <nav>\n <ul>\n <li class=\"active\"><a href=\"#\">Home</a></li>\n <li><a href=\"#\">About Us</a></li>\n <li><a href=\"#\">Our Products</a></li>\n <li><a href=\"#\">Careers</a></li>\n <li><a href=\"#\">Contact Us</a></li>\n </ul>\n </nav>\n </div>\n <!-- Image menu in Header to contain an Image and\n a sample text over that image -->\n <div id=\"header-image-menu\">\n </div>\n</header>\n\n#header-image-menu{\n top: 10px;\n position: relative;\n}\n#header-image-menu img{\n width: 100%;\n margin: none;\n padding: none;\n}\n#image-text{\n position: absolute;\n top: 60%;\n left: 60%;\n font-family: 'Roboto';\n color: #000;\n transform: translate(-30%, -30%);\n text-align: center;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2587661/" ]
74,511,805
<p>i have system of log that write logs each day with this format: &quot;stat.dat_20220901_235900.txt&quot;,&quot;stat.dat_20220902_235900.txt&quot;,... i need to get content of all files by month and create file named like &quot;September&quot; with all content of daily.</p> <pre><code>$Date= -Format(&quot;MMddyyyy_hhmmss&quot;) $path=&quot;C:\Users\**\**\**\**\stat.dat_$Date&quot; $CharArray =Get-Content -Path $path </code></pre>
[ { "answer_id": 74511830, "author": "Abdulkhaliq Ghwainm", "author_id": 4879561, "author_profile": "https://Stackoverflow.com/users/4879561", "pm_score": 1, "selected": false, "text": "<img> <img> src alt <img src=\"img_girl.jpg\" alt=\"Girl in a jacket\" width=\"500\" height=\"600\">\n" }, { "answer_id": 74512455, "author": "Prerna Jena", "author_id": 11519496, "author_profile": "https://Stackoverflow.com/users/11519496", "pm_score": 0, "selected": false, "text": "<header>\n <div id=\"top-header\"> \n <!-- Logo -->\n <div id=\"logo\">\n <img src=\"images/logo.png\" />\n </div> \n <!-- Navigation Menu -->\n <nav>\n <ul>\n <li class=\"active\"><a href=\"#\">Home</a></li>\n <li><a href=\"#\">About Us</a></li>\n <li><a href=\"#\">Our Products</a></li>\n <li><a href=\"#\">Careers</a></li>\n <li><a href=\"#\">Contact Us</a></li>\n </ul>\n </nav>\n </div>\n <!-- Image menu in Header to contain an Image and\n a sample text over that image -->\n <div id=\"header-image-menu\">\n </div>\n</header>\n\n#header-image-menu{\n top: 10px;\n position: relative;\n}\n#header-image-menu img{\n width: 100%;\n margin: none;\n padding: none;\n}\n#image-text{\n position: absolute;\n top: 60%;\n left: 60%;\n font-family: 'Roboto';\n color: #000;\n transform: translate(-30%, -30%);\n text-align: center;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4082943/" ]
74,511,807
<p>I have a list with an Image and Text in a Row. Both are in an <code>Expanded</code> widget to get the same width.</p> <pre><code> Widget item(String value, String imageLocation) =&gt; Row(children: [ Expanded( child: Image.asset( 'assets/images/$imageLocation.png', )), Expanded( child: Text( value, textAlign: TextAlign.center, style: const TextStyle( color: Colors.black54, ), ), ), ]); </code></pre> <p>That, everything is well drawn, but the images are too big. Initially, all images have not the same size. And when I want to reduce it on screen by putting them in a Container with a definite size, many images are well reduced, but not the smallest which appear always big. I also tried different fit properties, but without any success.</p> <p>What I want is to reduce all images with the same ratio, so that they keep the same aspect as currently but smaller.</p> <p>How can I do that? Thanks</p>
[ { "answer_id": 74511830, "author": "Abdulkhaliq Ghwainm", "author_id": 4879561, "author_profile": "https://Stackoverflow.com/users/4879561", "pm_score": 1, "selected": false, "text": "<img> <img> src alt <img src=\"img_girl.jpg\" alt=\"Girl in a jacket\" width=\"500\" height=\"600\">\n" }, { "answer_id": 74512455, "author": "Prerna Jena", "author_id": 11519496, "author_profile": "https://Stackoverflow.com/users/11519496", "pm_score": 0, "selected": false, "text": "<header>\n <div id=\"top-header\"> \n <!-- Logo -->\n <div id=\"logo\">\n <img src=\"images/logo.png\" />\n </div> \n <!-- Navigation Menu -->\n <nav>\n <ul>\n <li class=\"active\"><a href=\"#\">Home</a></li>\n <li><a href=\"#\">About Us</a></li>\n <li><a href=\"#\">Our Products</a></li>\n <li><a href=\"#\">Careers</a></li>\n <li><a href=\"#\">Contact Us</a></li>\n </ul>\n </nav>\n </div>\n <!-- Image menu in Header to contain an Image and\n a sample text over that image -->\n <div id=\"header-image-menu\">\n </div>\n</header>\n\n#header-image-menu{\n top: 10px;\n position: relative;\n}\n#header-image-menu img{\n width: 100%;\n margin: none;\n padding: none;\n}\n#image-text{\n position: absolute;\n top: 60%;\n left: 60%;\n font-family: 'Roboto';\n color: #000;\n transform: translate(-30%, -30%);\n text-align: center;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1568148/" ]
74,511,812
<p>I have this piece element, which represents a coin in my connect four game, however, I want to change the background color of the coin using inline styling in JS. Is it possible to convert the CSS format to inline js styling? I have tried using getAttribute but don't think I am using right. Any suggestions would be helpful.</p> <p>style.css:</p> <pre><code>.piece{ border-radius: 50%; background-color: red; flex-grow: 1; margin: 5%; } .piece[data-placed = &quot;false&quot;]{ transform: translateY(-10vmin); } .piece[data-player = &quot;1&quot;]{ //This is the element I want to inline style in my js file background-color: rgb(25, 0, 255); } .piece[data-player = &quot;2&quot;]{ //This is the element I want to inline style in my js file background-color: rgb(255, 0, 0); } </code></pre> <p>JS:</p> <p>//Convert to inline styling</p> <p>I have tried using the getattribute but doesn't change anything in my webpage.</p>
[ { "answer_id": 74511830, "author": "Abdulkhaliq Ghwainm", "author_id": 4879561, "author_profile": "https://Stackoverflow.com/users/4879561", "pm_score": 1, "selected": false, "text": "<img> <img> src alt <img src=\"img_girl.jpg\" alt=\"Girl in a jacket\" width=\"500\" height=\"600\">\n" }, { "answer_id": 74512455, "author": "Prerna Jena", "author_id": 11519496, "author_profile": "https://Stackoverflow.com/users/11519496", "pm_score": 0, "selected": false, "text": "<header>\n <div id=\"top-header\"> \n <!-- Logo -->\n <div id=\"logo\">\n <img src=\"images/logo.png\" />\n </div> \n <!-- Navigation Menu -->\n <nav>\n <ul>\n <li class=\"active\"><a href=\"#\">Home</a></li>\n <li><a href=\"#\">About Us</a></li>\n <li><a href=\"#\">Our Products</a></li>\n <li><a href=\"#\">Careers</a></li>\n <li><a href=\"#\">Contact Us</a></li>\n </ul>\n </nav>\n </div>\n <!-- Image menu in Header to contain an Image and\n a sample text over that image -->\n <div id=\"header-image-menu\">\n </div>\n</header>\n\n#header-image-menu{\n top: 10px;\n position: relative;\n}\n#header-image-menu img{\n width: 100%;\n margin: none;\n padding: none;\n}\n#image-text{\n position: absolute;\n top: 60%;\n left: 60%;\n font-family: 'Roboto';\n color: #000;\n transform: translate(-30%, -30%);\n text-align: center;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20435142/" ]
74,511,824
<p>This is a small part of a df.</p> <p>In this case, I have 3 y-values I need to map: <code>0.933883</code>, <code>97.658330</code> and <code>1.650013</code></p> <p>I have this <code>df</code></p> <pre><code> x y1 y2 y3 y4 d1 d2 d3 d4 23 5.3 NaN NaN 0.933883 NaN NaN NaN 0.174866 NaN 25 5.3 NaN NaN NaN 97.658330 NaN NaN NaN 0.038670 26 5.3 NaN NaN 1.650013 NaN NaN NaN 0.541264 NaN 29 5.3 NaN NaN 97.658330 NaN NaN NaN 96.549581 NaN 30 5.3 NaN NaN NaN 1.650013 NaN NaN NaN 96.046987 </code></pre> <p>There is not more than one of these values per column, I already dropped duplicates.</p> <p><strong>What I need:</strong></p> <p>I can not have the same value in more than one column.</p> <p>The condition to choose which row to remove is as shown in this <strong>example:</strong></p> <p>There is <code>97.658330</code> in column <code>y3</code> and <code>y4</code>. Since, for that value, <code>d3</code>(96.549581) is bigger than <code>d4</code>(0.038670), row <code>29</code> is removed.</p> <p>There is <code>1.650013</code> in column <code>y3</code> and <code>y4</code>. Since <code>d4</code>(96.046987) is bigger than <code>d3</code>(0.541264), row <code>30</code> is removed.</p> <p>Output:</p> <pre><code> x y1 y2 y3 y4 d1 d2 d3 d4 23 5.3 NaN NaN 0.933883 NaN NaN NaN 0.174866 NaN 25 5.3 NaN NaN NaN 97.658330 NaN NaN NaN 0.038670 26 5.3 NaN NaN 1.650013 NaN NaN NaN 0.541264 NaN </code></pre> <p><strong>P.S.</strong> There are a lot more values to map inside the complete data frame.</p>
[ { "answer_id": 74512239, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 1, "selected": false, "text": "vals=sorted(list(df[['y3','y4']].stack()))\ndupes = list(set(vals[::2]) & set(vals[1::2])) #https://stackoverflow.com/a/64956890/15415267\n#dupes= [1.650013, 97.65833]\n\nfor i in dupes:\n v1=df[df['y3']==i]['d3'].iloc[0]\n v2=df[df['y4']==i]['d4'].iloc[0]\n if v1 > v2:\n df=df.drop(df[df['y3']==i]['d3'].index)\n else:\n df=df.drop(df[df['y4']==i]['d4'].index)\nprint(df)\n'''\n x y1 y2 y3 y4 d1 d2 d3 d4\n23 5.3 NaN NaN 0.933883 NaN NaN NaN 0.174866 NaN\n25 5.3 NaN NaN NaN 97.65833 NaN NaN NaN 0.03867\n26 5.3 NaN NaN 1.650013 NaN NaN NaN 0.541264 NaN\n'''\n" }, { "answer_id": 74512309, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "y = df.filter(regex=r'y\\d+')\nd = df.filter(regex=r'd\\d+')\n\n# target = [0.933883, 97.658330, 1.650013]\n\n# define the target values automatically\ns = y.stack()\ntarget = set(s[s.duplicated()])\n# {1.650013, 97.65833}\n\ndrop = set()\nfor x in target:\n s = d.where(y.eq(x).to_numpy()).stack().droplevel(1)\n drop.update(s.index.difference([s.idxmin()]))\n\n# drop is {29, 30}\n\nout = df.drop(drop)\n x y1 y2 y3 y4 d1 d2 d3 d4\n23 5.3 NaN NaN 0.933883 NaN NaN NaN 0.174866 NaN\n25 5.3 NaN NaN NaN 97.65833 NaN NaN NaN 0.03867\n26 5.3 NaN NaN 1.650013 NaN NaN NaN 0.541264 NaN\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20458338/" ]
74,511,839
<p>I keep getting this E404 error in my shell when trying to create a react app. I may have deleted important files from my computer like an absolute noob. A possible solution I tried was using <code>npm set registry https://registry.npmjs.org</code> but this didn't help. I've been searching for ways to resolve this issue but haven't found a solution. Has anyone encountered this? Any advice? Thanks for reading!</p> <p><code>npm get registry</code> returns <code>https://skimdb.npmjs.com/registry</code></p> <pre class="lang-none prettyprint-override"><code>Creating a new React app in /home/elilogbro/portfolio. Installing packages. This might take a couple of minutes. Installing react, react-dom, and react-scripts with cra-template... npm ERR! code E404 npm ERR! 404 Not Found - GET https://skimdb.npmjs.com/registry/lodash.sortby/-/lodash.sortby-4.7.0.tgz - not_found npm ERR! 404 npm ERR! 404 'lodash.sortby@https://skimdb.npmjs.com/registry/lodash.sortby/-/lodash.sortby-4.7.0.tgz' is not in this registry. npm ERR! 404 npm ERR! 404 Note that you can also install from a npm ERR! 404 tarball, folder, http url, or git url. npm ERR! A complete log of this run can be found in: npm ERR! /home/elilogbro/.npm/_logs/2022-11-20T20_32_00_327Z-debug-0.log Aborting installation. npm install --no-audit --save --save-exact --loglevel error react react-dom react-scripts cra-template has failed. Deleting generated file... package.json Deleting portfolio/ from /home/elilogbro Done. </code></pre>
[ { "answer_id": 74512239, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 1, "selected": false, "text": "vals=sorted(list(df[['y3','y4']].stack()))\ndupes = list(set(vals[::2]) & set(vals[1::2])) #https://stackoverflow.com/a/64956890/15415267\n#dupes= [1.650013, 97.65833]\n\nfor i in dupes:\n v1=df[df['y3']==i]['d3'].iloc[0]\n v2=df[df['y4']==i]['d4'].iloc[0]\n if v1 > v2:\n df=df.drop(df[df['y3']==i]['d3'].index)\n else:\n df=df.drop(df[df['y4']==i]['d4'].index)\nprint(df)\n'''\n x y1 y2 y3 y4 d1 d2 d3 d4\n23 5.3 NaN NaN 0.933883 NaN NaN NaN 0.174866 NaN\n25 5.3 NaN NaN NaN 97.65833 NaN NaN NaN 0.03867\n26 5.3 NaN NaN 1.650013 NaN NaN NaN 0.541264 NaN\n'''\n" }, { "answer_id": 74512309, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "y = df.filter(regex=r'y\\d+')\nd = df.filter(regex=r'd\\d+')\n\n# target = [0.933883, 97.658330, 1.650013]\n\n# define the target values automatically\ns = y.stack()\ntarget = set(s[s.duplicated()])\n# {1.650013, 97.65833}\n\ndrop = set()\nfor x in target:\n s = d.where(y.eq(x).to_numpy()).stack().droplevel(1)\n drop.update(s.index.difference([s.idxmin()]))\n\n# drop is {29, 30}\n\nout = df.drop(drop)\n x y1 y2 y3 y4 d1 d2 d3 d4\n23 5.3 NaN NaN 0.933883 NaN NaN NaN 0.174866 NaN\n25 5.3 NaN NaN NaN 97.65833 NaN NaN NaN 0.03867\n26 5.3 NaN NaN 1.650013 NaN NaN NaN 0.541264 NaN\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19316102/" ]
74,511,853
<p>I am working with some open data through Deep Note with the pandas library and since it is in Spanish there are accents and characters like 'ñ' in the DataFrame</p> <p>Searching I have been able to solve part of the problem by putting 'encoding'. The problem is when I publish the page that they appear as strange signs because of the accents like 'á é í ó ú ñ' and then I would like to know if there is any way to read the columns that contain words and change it to their respective without accent.</p> <pre><code>datos = pd.read_csv(&quot;/work/avisos&quot;,delimiter = ';', encoding=&quot;ISO-8859-1&quot;) </code></pre>
[ { "answer_id": 74512239, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 1, "selected": false, "text": "vals=sorted(list(df[['y3','y4']].stack()))\ndupes = list(set(vals[::2]) & set(vals[1::2])) #https://stackoverflow.com/a/64956890/15415267\n#dupes= [1.650013, 97.65833]\n\nfor i in dupes:\n v1=df[df['y3']==i]['d3'].iloc[0]\n v2=df[df['y4']==i]['d4'].iloc[0]\n if v1 > v2:\n df=df.drop(df[df['y3']==i]['d3'].index)\n else:\n df=df.drop(df[df['y4']==i]['d4'].index)\nprint(df)\n'''\n x y1 y2 y3 y4 d1 d2 d3 d4\n23 5.3 NaN NaN 0.933883 NaN NaN NaN 0.174866 NaN\n25 5.3 NaN NaN NaN 97.65833 NaN NaN NaN 0.03867\n26 5.3 NaN NaN 1.650013 NaN NaN NaN 0.541264 NaN\n'''\n" }, { "answer_id": 74512309, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "y = df.filter(regex=r'y\\d+')\nd = df.filter(regex=r'd\\d+')\n\n# target = [0.933883, 97.658330, 1.650013]\n\n# define the target values automatically\ns = y.stack()\ntarget = set(s[s.duplicated()])\n# {1.650013, 97.65833}\n\ndrop = set()\nfor x in target:\n s = d.where(y.eq(x).to_numpy()).stack().droplevel(1)\n drop.update(s.index.difference([s.idxmin()]))\n\n# drop is {29, 30}\n\nout = df.drop(drop)\n x y1 y2 y3 y4 d1 d2 d3 d4\n23 5.3 NaN NaN 0.933883 NaN NaN NaN 0.174866 NaN\n25 5.3 NaN NaN NaN 97.65833 NaN NaN NaN 0.03867\n26 5.3 NaN NaN 1.650013 NaN NaN NaN 0.541264 NaN\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557452/" ]
74,511,880
<p>I'm trying to assign a (char*)0 pointer to a string in C, but it doesn't work... Here is my code: `</p> <pre><code>char* token = strtok(command, &quot; &quot;); int counter = 0; while (token) { if(counter == 0){ strcpy(req.command, token); } printf(&quot;Token: %s\n&quot;, token); strcpy(req.arguments[counter], token); counter++; token = strtok(NULL, &quot; &quot;); } // strcpy(req.arguments[counter], &quot;\0&quot;); printf(&quot;Ok\n&quot;); req.arguments_size = counter; req.arguments[counter] = (char)* 0; </code></pre> <p><code>The req structure is this:</code></p> <pre><code>typedef struct { char command[LENGTH]; char *const arguments[LENGTH]; int arguments_size; } Request; </code></pre> <p>`</p> <p>I'm doing this because I want to use execv() function on a server and I need that there is a (char*) 0 after the command arguments in the array. Thank you for your help!</p> <p>I tried to assign the pointer to the array element in different ways, but it doesn't work and i can't use strcpy because arguments must be not null!</p> <p>Here it is what the compiler says to me: client-1.c:55:32: error: assignment of read-only location</p> <p><code>client-1.c:55:32: error: assignment of read-only location ‘req.arguments[counter]’ 55 | req.arguments[counter] = zero; | ^ </code></p>
[ { "answer_id": 74511926, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 2, "selected": false, "text": "char *const arguments[LENGTH];\n const char * arguments[LENGTH];\n strcpy(req.arguments[counter], token);\n req.arguments[counter] = malloc( strlen( token ) + 1 );\nstrcpy(req.arguments[counter], token);\n req.arguments[counter] = (char *) 0;\n req.arguments[counter] = NULL;\n" }, { "answer_id": 74513762, "author": "Dan Bonachea", "author_id": 3528321, "author_profile": "https://Stackoverflow.com/users/3528321", "pm_score": 1, "selected": false, "text": "req.arguments[counter] = (char)* 0; (char *)0 NULL const const char * arguments[LENGTH]; char * const arguments[LENGTH];" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15095487/" ]
74,511,901
<p>I am currently working on some research of online forums. I have a database with thousands of posts and want to create a binary variable on the specific post (which is an observation in my dataset) when a certain word is mentioned.</p> <p>I want to see when posters talk about being lonely, so I have come up with the following code, but I keep getting an error when I use <code>ignore_case = T</code>.</p> <pre><code>library(dplyr) library(string) dataset &lt;- dataset %&gt;% mutate(loneliness = ifelse(str_detect(text,&quot;loneliness|blackpilled|lonely&quot;), 1, 0, ignore_case = TRUE)) </code></pre> <p>I have also tried:</p> <pre><code>mutate(loneliness = ifelse( str_detect(dataset$text, regex(&quot;loneliness|blackpilled|black pill|lonely&quot;, ignore_case = TRUE)))) </code></pre> <p>Using that I get this error: argument &quot;no&quot; is missing, with no default.</p> <p>What am I missing in my code that it is not working?</p>
[ { "answer_id": 74511945, "author": "FactOREO", "author_id": 20462305, "author_profile": "https://Stackoverflow.com/users/20462305", "pm_score": 1, "selected": false, "text": "ignore_case ifelse() dplyr stringr Data <- data.frame(text = c('I am lonely','I am happy'))\nlibrary(tidyverse)\nData |>\n mutate(\n loneliness = if_else(\n condition = str_detect(text, pattern = \"loneliness|blackpilled|lonely\"),\n 1L, 0L\n )\n )\n#> text loneliness\n#> 1 I am lonely 1\n#> 2 I am happy 0\n" }, { "answer_id": 74512028, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 0, "selected": false, "text": "str_detect ignore_case str_detect ifelse regex dataset %>% \n mutate(loneliness = ifelse(\n str_detect(text, \n regex(\"loneliness|blackpilled|lonely\", ignore_case = T)\n ), 1, 0))\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19331857/" ]
74,511,906
<p>I have a csv data of a test scores. The current program is able to read this data into a 2D list with the test out of marks. I later created a function to remove test out of row so only the student's marks can be displayed. I'm now struggling to write a function which can print the scores so that each student's percentage appears on a separate line of output.</p> <p><strong>My code so far</strong></p> <pre><code>def getData(): with open(&quot;testscores.csv&quot;,&quot;r&quot;) as file: lineArray = file.read().splitlines() matrix = [] for line in lineArray: matrix.append(line.split(&quot;,&quot;)) return matrix def fullScores(matrix): matrix.pop(0) return matrix def printscores(matrix): for counter in matrix: for values in counter: print(values, end= &quot; &quot;) print() matrix = getData() matrix = fullScores(matrix) print() printscores(matrix) </code></pre> <p><strong>output</strong></p> <pre class="lang-none prettyprint-override"><code>Bob 10 9 7 8 10 9 9 9 10 8 8 10 9 9 Sue 8 8 8 9 4 8 9 7 8 3 10 10 7 9 Jan 6 6 0 5 7 9 4 7 8 5 7 1 5 9 Sam 8 8 8 7 7 7 9 9 9 9 8 9 10 8 Tom 9 9 9 9 9 9 9 9 9 10 9 9 9 9 </code></pre> <p><strong>expected output</strong></p> <pre class="lang-none prettyprint-override"><code>Bob 100% 90% 70% 80% 100% 90% 90% 90% 100% 80% 80% 100% 90% 90% Average = 89% Sue 80% 80% 80% 90% 40% 80% 90% 70% 80% 30% 100% 100% 70% 90% Average = 77% ... </code></pre> <p><strong>csv data</strong></p> <pre class="lang-none prettyprint-override"><code>Testoutof,10,11,12,11,10,11,9,10,10,11,10,12,10,9 Bob,10,9,7,8,10,9,9,9,10,8,8,10,9,9 Sue,8,8,8,9,4,8,9,7,8,3,10,10,7,9 Jan,6,6,0,5,7,9,4,7,8,5,7,1,5,9 Sam,8,8,8,7,7,7,9,9,9,9,8,9,10,8 Tom,9,9,9,9,9,9,9,9,9,10,9,9,9,9 </code></pre>
[ { "answer_id": 74511945, "author": "FactOREO", "author_id": 20462305, "author_profile": "https://Stackoverflow.com/users/20462305", "pm_score": 1, "selected": false, "text": "ignore_case ifelse() dplyr stringr Data <- data.frame(text = c('I am lonely','I am happy'))\nlibrary(tidyverse)\nData |>\n mutate(\n loneliness = if_else(\n condition = str_detect(text, pattern = \"loneliness|blackpilled|lonely\"),\n 1L, 0L\n )\n )\n#> text loneliness\n#> 1 I am lonely 1\n#> 2 I am happy 0\n" }, { "answer_id": 74512028, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 0, "selected": false, "text": "str_detect ignore_case str_detect ifelse regex dataset %>% \n mutate(loneliness = ifelse(\n str_detect(text, \n regex(\"loneliness|blackpilled|lonely\", ignore_case = T)\n ), 1, 0))\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4174508/" ]
74,511,914
<p>I have two components: <code>&lt;Header/&gt;</code> with hamburger button on it, and <code>&lt;Sidebar/&gt;</code>.</p> <p>The idea is: if I click hamburger button the sidebar should be removed, or it should be appeared if I click back.</p> <p>I have no issues to do so in one component where I use useRef:</p> <pre><code> const sideBarRef = useRef() function toogleSideBar() { sideBarRef.current.classList.toggle('-translate-x-full') } </code></pre> <p>but I am not sure how to do it between components, where I have a layout with <code>&lt;Header/&gt;</code> and <code>&lt;Sidebar/&gt;</code> in it, and I need to initiate <code>toogleSidebar()</code> in <code>&lt;Header/&gt;</code> and some how pass <code>ref={sideBarRef}</code> in <code>&lt;Sidebar/&gt;</code>.</p>
[ { "answer_id": 74512064, "author": "Andrew Hartnell", "author_id": 7202344, "author_profile": "https://Stackoverflow.com/users/7202344", "pm_score": -1, "selected": false, "text": " //App.js\n let sideBarRef = useRef(false); \n\n let content = (\n {sideBarRef? (<SideBar sideBarRef ={sideBarRef} />\n ): null} \n <Header sideBarRef ={sideBarRef} />\n \n\n\nexport default function SideBar({sideBarRef,}) { \n<use sideBarRef in code as if declare here>\n}\n\nexport default function Header({sideBarRef,}) { \n<use sideBarRef as if declare here >\n}\n" }, { "answer_id": 74512366, "author": "szaman", "author_id": 4908847, "author_profile": "https://Stackoverflow.com/users/4908847", "pm_score": 0, "selected": false, "text": "Header Sidebar App const App = () => {\n const [showSidebar, setShowSidebar] = useState(true);\n\n const toggleSidebar = () => setShowSidebar(prev => !prev);\n \n return (\n <main>\n <Header onClickMenu={toggleSidebar} />\n {showSidebar && <Sidebar />}\n </main>\n );\n};\n const Header = ({ onClickMenu }) => { \n return (\n <nav>\n <Hamburger onClick={onClickMenu} />\n ...\n </nav>\n );\n};\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4655668/" ]
74,511,943
<p>I am getting confused on the PriorityQueue, not sure if there is a different method for my use case.</p> <p>Instead of comparing two Strings, I want to compare the incoming Strings against a String[].</p> <p>It somewhat works but the head node does not move.</p> <p>Main:</p> <pre><code>public class App { public static void main( String[] args ) { PriorityString priorityString = new PriorityString(); PriorityQueue&lt;String&gt; priorityQueue = new PriorityQueue&lt;String&gt;(priorityString); priorityQueue.add(&quot;test&quot;); priorityQueue.add(&quot;john&quot;); priorityQueue.add(&quot;blue&quot;); priorityQueue.add(&quot;orange&quot;); priorityQueue.add(&quot;grape&quot;); priorityQueue.add(&quot;handle&quot;); while (!priorityQueue.isEmpty()) { System.out.println(&quot;Removed: &quot; + priorityQueue.remove()); } } } </code></pre> <p>Comparator class:</p> <pre><code>public class PriorityString implements Comparator&lt;String&gt; { String[] valueStrings; PriorityString() { valueStrings = new String[] {&quot;all&quot;, &quot;john&quot;, &quot;door&quot;, &quot;floor&quot;, &quot;record&quot;, &quot;desk&quot;, &quot;orange&quot;}; } public int compare(String o1, String o2) { if (Arrays.asList(valueStrings).contains(o1)) return 0; else return 1; } } </code></pre> <p>Result:</p> <pre><code>Removed: test Removed: john Removed: orange Removed: blue Removed: handle Removed: grape </code></pre> <p>The values 'test' comes first all the time even though it is not in the String[]. The other values seem to be in the correct order since 'john' and 'orange' are in the String[] and the rest is not.</p> <p>What is the issue and is this the right way to implement my use case?</p> <p>Edit: I have also tried this</p> <pre><code> public int compare(String o1, String o2) { if (Arrays.asList(valueStrings).contains(o1)) return -1; else if (Arrays.asList(valueStrings).contains(o2)) return 0; else return 1; } </code></pre> <p>Which gives this result:</p> <pre><code>Removed: orange Removed: handle Removed: grape Removed: test Removed: blue Removed: john </code></pre> <p>orange is in the right place by john is at the bottom when it should be right after orange</p> <p>New Edit: after rereading the doc as per the comment, I managed to get a working version implemented in this way. Probably will add @Progman else return.</p> <pre><code> public int compare(String o1, String o2) { if (Arrays.asList(valueStrings).contains(o1)) return -1; else if (Arrays.asList(valueStrings).contains(o2)) return 1; else return 0; } </code></pre> <p>Result:</p> <pre><code>Removed: orange Removed: john Removed: grape Removed: test Removed: blue Removed: handle </code></pre>
[ { "answer_id": 74512064, "author": "Andrew Hartnell", "author_id": 7202344, "author_profile": "https://Stackoverflow.com/users/7202344", "pm_score": -1, "selected": false, "text": " //App.js\n let sideBarRef = useRef(false); \n\n let content = (\n {sideBarRef? (<SideBar sideBarRef ={sideBarRef} />\n ): null} \n <Header sideBarRef ={sideBarRef} />\n \n\n\nexport default function SideBar({sideBarRef,}) { \n<use sideBarRef in code as if declare here>\n}\n\nexport default function Header({sideBarRef,}) { \n<use sideBarRef as if declare here >\n}\n" }, { "answer_id": 74512366, "author": "szaman", "author_id": 4908847, "author_profile": "https://Stackoverflow.com/users/4908847", "pm_score": 0, "selected": false, "text": "Header Sidebar App const App = () => {\n const [showSidebar, setShowSidebar] = useState(true);\n\n const toggleSidebar = () => setShowSidebar(prev => !prev);\n \n return (\n <main>\n <Header onClickMenu={toggleSidebar} />\n {showSidebar && <Sidebar />}\n </main>\n );\n};\n const Header = ({ onClickMenu }) => { \n return (\n <nav>\n <Hamburger onClick={onClickMenu} />\n ...\n </nav>\n );\n};\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74511943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7391720/" ]