content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
30
130
Q: Local branch and remote branch have diverged after amending commit I have a feature branch called featureA and I am the only developer who is and will be touching this branch until it gets merged to master branch. My git command history is: committed changes locally made more changes then pushed to remote by amending commit made one more change (on a single line) then pushed to remote by amending commit BUT it seems NOT pushed to the remote repository. git status outputs: Your branch and origin/featureA have diverged, and have 1 and 1 different commits each, respectively. (use git pull to merge the remote branch into yours) git diff shows that: local branch: the last single line change is applied remote origin branch: the last single line change is not applied My featureA branch will be merged to the master branch so I don't want to ruin history. I went through several threads (suggesting git pul --rebase, git reset --hard, etc) but still do not have clear idea what is the best solution. I don't mind which state I will be on with the solution. If needed, I don't mind to go back to the previous push/commit and push the new change as a new commit again because it is just a single line code change. I appreciate your help. A: Why this happened is simple: git commit --amend is a lie. It's a useful lie at most times, but it's still a lie. It's literally impossible to change any existing Git commit, so git commit --amend doesn't do that. Instead, git commit --amend makes a new and improved replacement commit, in your own local repository, pushing the old commit "out of the way" as it were. The old (bad) commit continues to exist—for a while; eventually, if you don't reclaim it (and there's no reason you should) Git will remove it for real. Because your local repository is a different repository from the other repository (the "remote"), and this change of "which commits we're supposed to use" has happened locally only at this point, your branch and their branch have indeed diverged. If you have permission—Git itself always gives permission, but many hosting sites take it away (under various conditions)—you can use git push --force to send your new-and-improved commit to the other Git software that is working with the remote repository. This "force push" tells their Git software: I know this new commit discards some previous commit. Do that anyway, even though discarding some previous commit is normally a very bad idea. Since you're quite certain that you do want to discard the commit—it's the one you "amended", and you don't want it back, ever again—it's safe to tell them this. Just be very sure that that's the commit you're going to discard: run git fetch verify that your local git status still says "diverged" and "1 commit" each: that's your "amended" commit vs their original and then run git push --force or git push --force-with-lease with the remote name (origin) and branch name featureA.
Local branch and remote branch have diverged after amending commit
I have a feature branch called featureA and I am the only developer who is and will be touching this branch until it gets merged to master branch. My git command history is: committed changes locally made more changes then pushed to remote by amending commit made one more change (on a single line) then pushed to remote by amending commit BUT it seems NOT pushed to the remote repository. git status outputs: Your branch and origin/featureA have diverged, and have 1 and 1 different commits each, respectively. (use git pull to merge the remote branch into yours) git diff shows that: local branch: the last single line change is applied remote origin branch: the last single line change is not applied My featureA branch will be merged to the master branch so I don't want to ruin history. I went through several threads (suggesting git pul --rebase, git reset --hard, etc) but still do not have clear idea what is the best solution. I don't mind which state I will be on with the solution. If needed, I don't mind to go back to the previous push/commit and push the new change as a new commit again because it is just a single line code change. I appreciate your help.
[ "Why this happened is simple: git commit --amend is a lie. It's a useful lie at most times, but it's still a lie. It's literally impossible to change any existing Git commit, so git commit --amend doesn't do that.\nInstead, git commit --amend makes a new and improved replacement commit, in your own local repository, pushing the old commit \"out of the way\" as it were. The old (bad) commit continues to exist—for a while; eventually, if you don't reclaim it (and there's no reason you should) Git will remove it for real.\nBecause your local repository is a different repository from the other repository (the \"remote\"), and this change of \"which commits we're supposed to use\" has happened locally only at this point, your branch and their branch have indeed diverged.\nIf you have permission—Git itself always gives permission, but many hosting sites take it away (under various conditions)—you can use git push --force to send your new-and-improved commit to the other Git software that is working with the remote repository. This \"force push\" tells their Git software: I know this new commit discards some previous commit. Do that anyway, even though discarding some previous commit is normally a very bad idea. Since you're quite certain that you do want to discard the commit—it's the one you \"amended\", and you don't want it back, ever again—it's safe to tell them this. Just be very sure that that's the commit you're going to discard:\n\nrun git fetch\nverify that your local git status still says \"diverged\" and \"1 commit\" each: that's your \"amended\" commit vs their original\n\nand then run git push --force or git push --force-with-lease with the remote name (origin) and branch name featureA.\n" ]
[ 2 ]
[]
[]
[ "branch", "git", "git_amend", "git_commit", "git_push" ]
stackoverflow_0074662750_branch_git_git_amend_git_commit_git_push.txt
Q: Creating a custom back button with NavigationView on SwiftUI I'm trying to create a custom back button on SwiftUI, but I can't figure out how to do it. The idea is to hide the "Back" button at the top left that provides NavigationView, and make a custom button with the same functionality. struct AnadirDatosViewA: View { @Environment(\.presentationMode) var presentation var body: some View{ NavigationView(){ Color(red: 48 / 255, green: 49 / 255, blue: 54 / 255) .edgesIgnoringSafeArea(.all) .overlay( VStack{ AnadirDatosExpB() HStack{ NavigationLink(destination:NuevoExperimentoView()){ Text("Back") //HERE NavigationLink(destination:AnadirDatosExpA()){ Text("Next") } } } } ) }.navigationBarBackButtonHidden(true) } } Right now I'm "cheating" by using the view I want go go back as destination, but it doesn't work the same... What can I do? A: You can use the presentationMode var from the environment inside a Button: See the commented example below for a possible implementation. struct ContentView: View{ var body: some View{ // I am navigating with a Navigationlink, so there is // no need for it in the AnadirDatosViewA NavigationView { NavigationLink("show AnadirDatosViewA") { AnadirDatosViewA() } } } } struct AnadirDatosViewA: View { @Environment(\.presentationMode) var presentation var body: some View{ // if you navigated to this by a Navigationlink remove the NavigationView Color(red: 48 / 255, green: 49 / 255, blue: 54 / 255) .edgesIgnoringSafeArea(.all) .overlay( HStack{ // This Button will dismiss the View Button("Back"){ // with help of th presentationMode from the environment presentation.wrappedValue.dismiss() } // This NavigationLink can forward you to another view NavigationLink("Next") { TextView(text: "last") } } // This will hide the back Button in this View ).navigationBarBackButtonHidden(true) } } // HelperView struct TextView: View{ var text: String var body: some View{ Text(text) } }
Creating a custom back button with NavigationView on SwiftUI
I'm trying to create a custom back button on SwiftUI, but I can't figure out how to do it. The idea is to hide the "Back" button at the top left that provides NavigationView, and make a custom button with the same functionality. struct AnadirDatosViewA: View { @Environment(\.presentationMode) var presentation var body: some View{ NavigationView(){ Color(red: 48 / 255, green: 49 / 255, blue: 54 / 255) .edgesIgnoringSafeArea(.all) .overlay( VStack{ AnadirDatosExpB() HStack{ NavigationLink(destination:NuevoExperimentoView()){ Text("Back") //HERE NavigationLink(destination:AnadirDatosExpA()){ Text("Next") } } } } ) }.navigationBarBackButtonHidden(true) } } Right now I'm "cheating" by using the view I want go go back as destination, but it doesn't work the same... What can I do?
[ "You can use the presentationMode var from the environment inside a Button:\nSee the commented example below for a possible implementation.\nstruct ContentView: View{\n \n var body: some View{\n // I am navigating with a Navigationlink, so there is\n // no need for it in the AnadirDatosViewA\n NavigationView {\n NavigationLink(\"show AnadirDatosViewA\") {\n AnadirDatosViewA()\n }\n }\n }\n}\n\n\nstruct AnadirDatosViewA: View {\n @Environment(\\.presentationMode) var presentation\n \n var body: some View{\n // if you navigated to this by a Navigationlink remove the NavigationView\n Color(red: 48 / 255, green: 49 / 255, blue: 54 / 255)\n .edgesIgnoringSafeArea(.all)\n .overlay(\n HStack{\n // This Button will dismiss the View\n Button(\"Back\"){\n // with help of th presentationMode from the environment\n presentation.wrappedValue.dismiss()\n }\n // This NavigationLink can forward you to another view\n NavigationLink(\"Next\") {\n TextView(text: \"last\")\n }\n }\n // This will hide the back Button in this View\n ).navigationBarBackButtonHidden(true)\n }\n}\n// HelperView\nstruct TextView: View{\n var text: String\n var body: some View{\n Text(text)\n }\n}\n\n" ]
[ 1 ]
[]
[]
[ "ios", "navigationview", "swift", "swiftui", "user_interface" ]
stackoverflow_0074659551_ios_navigationview_swift_swiftui_user_interface.txt
Q: Pagination on pandas dataframe.to_html() I have a huge pandas dataframe I am converting to html table i.e. dataframe.to_html(), its about 1000 rows. Any easy way to use pagination so that I dont have to scroll the whole 1000 rows. Say, view the first 50 rows then click next to see subsequent 50 rows? A: Update 2022 It seems that there is now a simple and modern solution, using itables. Installation: pip install itables Basic usage (from the GitHub readme): from itables import show show(df) Result: There is also a command for displaying all tables in the notebook like this by default. Original answer (exporting table to HTML file) The best solution I can think of involves a couple of external JS libraries: JQuery and its DataTables plugin. This will allow for much more than pagination, with very little effort. Let's set up some HTML, JS and python: from tempfile import NamedTemporaryFile import webbrowser base_html = """ <!doctype html> <html><head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.css"> <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script> </head><body>%s<script type="text/javascript">$(document).ready(function(){$('table').DataTable({ "pageLength": 50 });});</script> </body></html> """ def df_html(df): """HTML table with pagination and other goodies""" df_html = df.to_html() return base_html % df_html def df_window(df): """Open dataframe in browser window using a temporary file""" with NamedTemporaryFile(delete=False, suffix='.html') as f: f.write(df_html(df)) webbrowser.open(f.name) And now we can load a sample dataset to test it: from sklearn.datasets import load_iris import pandas as pd iris = load_iris() df = pd.DataFrame(iris.data, columns=iris.feature_names) df_window(df) The beautiful result: A few notes: Notice the pageLength parameter in the base_html string. This is where I defined the default number of rows per page. You can find other optional parameters in the DataTable options page. The df_window function was tested in a Jupyter Notebook, but should work in plain python as well. You can skip df_window and simply write the returned value from df_html into an HTML file. Edit: how to make this work with a remote session (e.g. Colab) When working on a remote notebook, like in Colab or Kaggle the temporary file approach won't work, since the file is saved on the remote machine and not accessible by your browser. A workaround for that would be to download the constructed HTML and open it locally (adding to the previous code): import base64 from IPython.core.display import display, HTML my_html = df_html(df) my_html_base64 = base64.b64encode(my_html.encode()).decode('utf-8') display(HTML(f'<a download href="data:text/html;base64,{my_html_base64}" target="_blank">Download HTML</a>')) This will result in a link containing the entire HTML encoded as a base64 string. Clicking it will download the HTML file and you can then open it directly and view the table. A: I developed a solution for this out of necessity: paginate_pandas, a much simpler package than itables, leveraging on ipywidgets. With some obvious bias, I feel itables might be a bit overkill. I can already filter and sort with pandas when I'm in Jupyter, so the only thing I need is pagination. paginate_pandas gives you that with a nice slider:
Pagination on pandas dataframe.to_html()
I have a huge pandas dataframe I am converting to html table i.e. dataframe.to_html(), its about 1000 rows. Any easy way to use pagination so that I dont have to scroll the whole 1000 rows. Say, view the first 50 rows then click next to see subsequent 50 rows?
[ "Update 2022\nIt seems that there is now a simple and modern solution, using itables.\nInstallation:\npip install itables\n\nBasic usage (from the GitHub readme):\nfrom itables import show\n\nshow(df)\n\nResult:\n\nThere is also a command for displaying all tables in the notebook like this by default.\nOriginal answer (exporting table to HTML file)\nThe best solution I can think of involves a couple of external JS libraries: JQuery and its DataTables plugin. This will allow for much more than pagination, with very little effort.\nLet's set up some HTML, JS and python:\nfrom tempfile import NamedTemporaryFile\nimport webbrowser\n\nbase_html = \"\"\"\n<!doctype html>\n<html><head>\n<meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\">\n<script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js\"></script>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdn.datatables.net/1.10.16/css/jquery.dataTables.css\">\n<script type=\"text/javascript\" src=\"https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js\"></script>\n</head><body>%s<script type=\"text/javascript\">$(document).ready(function(){$('table').DataTable({\n \"pageLength\": 50\n});});</script>\n</body></html>\n\"\"\"\n\ndef df_html(df):\n \"\"\"HTML table with pagination and other goodies\"\"\"\n df_html = df.to_html()\n return base_html % df_html\n\ndef df_window(df):\n \"\"\"Open dataframe in browser window using a temporary file\"\"\"\n with NamedTemporaryFile(delete=False, suffix='.html') as f:\n f.write(df_html(df))\n webbrowser.open(f.name)\n\nAnd now we can load a sample dataset to test it:\nfrom sklearn.datasets import load_iris\nimport pandas as pd\n\niris = load_iris()\ndf = pd.DataFrame(iris.data, columns=iris.feature_names)\n\ndf_window(df)\n\nThe beautiful result:\n\nA few notes:\n\nNotice the pageLength parameter in the base_html string. This is where I defined the default number of rows per page. You can find other optional parameters in the DataTable options page.\nThe df_window function was tested in a Jupyter Notebook, but should work in plain python as well.\nYou can skip df_window and simply write the returned value from df_html into an HTML file.\n\nEdit: how to make this work with a remote session (e.g. Colab)\nWhen working on a remote notebook, like in Colab or Kaggle the temporary file approach won't work, since the file is saved on the remote machine and not accessible by your browser. A workaround for that would be to download the constructed HTML and open it locally (adding to the previous code):\nimport base64\nfrom IPython.core.display import display, HTML\n\nmy_html = df_html(df)\nmy_html_base64 = base64.b64encode(my_html.encode()).decode('utf-8')\ndisplay(HTML(f'<a download href=\"data:text/html;base64,{my_html_base64}\" target=\"_blank\">Download HTML</a>'))\n\nThis will result in a link containing the entire HTML encoded as a base64 string. Clicking it will download the HTML file and you can then open it directly and view the table.\n", "I developed a solution for this out of necessity: paginate_pandas, a much simpler package than itables, leveraging on ipywidgets.\nWith some obvious bias, I feel itables might be a bit overkill. I can already filter and sort with pandas when I'm in Jupyter, so the only thing I need is pagination. paginate_pandas gives you that with a nice slider:\n\n" ]
[ 13, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0038893448_pandas_python.txt
Q: Should I convert a class with only methods to free functions in a namespace? I originally created a class like so: class A { public: void run(int x); private: void run_helper1(); void run_helper2(); void run_helper3(); int a_; double b_; bool c_; }; Later I realized it really didn't need any state, I just needed the functions. Would it make sense to drop the class and make these free functions in a namespace? If so, I lose the concept of public and private and end up with run_helper1(), run_helper2(), run_helper3() all being public, if I'm not mistaken. That seems like a poor design. A: The main difference between class and namespace that a class is closed (but possibly extensible using inheritance) and holds an invariant; while a namespace is open and can be extended at any point. Invariant might be as simple as having a unique address (and being able to compare instance addresses), but, if I understand you correctly, even that is unnecessary. If there's really no other use of A than to 'group together' functions, then your intuition might be right and you might want change it to a namespace. There is, however, an example what a namespace can't do that a class can: there are no template namespaces. Thus, if you ever need to pass the methods together, e.g. as an API (or a versioned API), then you need to keep them as a class. In that case, callee templates over the whole collection of functions and you can have multiple such collections; but it's a rather rare use-case. Thus, normally you can convert it.
Should I convert a class with only methods to free functions in a namespace?
I originally created a class like so: class A { public: void run(int x); private: void run_helper1(); void run_helper2(); void run_helper3(); int a_; double b_; bool c_; }; Later I realized it really didn't need any state, I just needed the functions. Would it make sense to drop the class and make these free functions in a namespace? If so, I lose the concept of public and private and end up with run_helper1(), run_helper2(), run_helper3() all being public, if I'm not mistaken. That seems like a poor design.
[ "The main difference between class and namespace that a class is closed (but possibly extensible using inheritance) and holds an invariant; while a namespace is open and can be extended at any point. Invariant might be as simple as having a unique address (and being able to compare instance addresses), but, if I understand you correctly, even that is unnecessary.\nIf there's really no other use of A than to 'group together' functions, then your intuition might be right and you might want change it to a namespace.\nThere is, however, an example what a namespace can't do that a class can: there are no template namespaces. Thus, if you ever need to pass the methods together, e.g. as an API (or a versioned API), then you need to keep them as a class. In that case, callee templates over the whole collection of functions and you can have multiple such collections; but it's a rather rare use-case.\nThus, normally you can convert it.\n" ]
[ 2 ]
[]
[]
[ "c++", "class", "namespaces", "non_member_functions" ]
stackoverflow_0074662886_c++_class_namespaces_non_member_functions.txt
Q: Does Skaffold has any limitations works with EKS I exploring using Skaffold with our EKS cluster and I wonder if the tool is agnostic to the cloud vendor and if he can work with any k8s cluster? Does he have any limitations regarding e.g shared volumes and other resources? A: Skaffold is a tool for deploying to any Kubernetes cluster, agnostic of cloud vendor. Skaffold can be used with any Kubernetes cluster, whether it is hosted on a cloud provider like Google's GKE, Amazon EKS, or running on-premises. Skaffold does not have any specific limitations regarding shared volumes or other resources, as it is simply a tool for deploying to a Kubernetes cluster. Any limitations you may encounter would be due to the limitations of Kubernetes itself, rather than Skaffold. NOTE: Skaffold does poll resources it deploys for changes so API rate limits might be a possible concern but this isn't an issue for most users. Disclaimer: I am contributor to this project
Does Skaffold has any limitations works with EKS
I exploring using Skaffold with our EKS cluster and I wonder if the tool is agnostic to the cloud vendor and if he can work with any k8s cluster? Does he have any limitations regarding e.g shared volumes and other resources?
[ "Skaffold is a tool for deploying to any Kubernetes cluster, agnostic of cloud vendor. Skaffold can be used with any Kubernetes cluster, whether it is hosted on a cloud provider like Google's GKE, Amazon EKS, or running on-premises. Skaffold does not have any specific limitations regarding shared volumes or other resources, as it is simply a tool for deploying to a Kubernetes cluster. Any limitations you may encounter would be due to the limitations of Kubernetes itself, rather than Skaffold.\nNOTE: Skaffold does poll resources it deploys for changes so API rate limits might be a possible concern but this isn't an issue for most users.\nDisclaimer: I am contributor to this project\n" ]
[ 0 ]
[]
[]
[ "kubernetes", "skaffold" ]
stackoverflow_0071924972_kubernetes_skaffold.txt
Q: Julia: How to save a figure without plotting/displaying it in PyPlot? I am using the PyPlot package in Julia to generate and save several figures. My current approach is to display the figure and then save it using savefig. using PyPlot a = rand(50,40) imshow(a) savefig("a.png") Is there a way to save the figure without having to first display it? A: Are you using the REPL or IJulia? If you close the figure then it won't show you the plot. Is that what you want? a = rand(50,40) ioff() #turns off interactive plotting fig = figure() imshow(a) close(fig) If that doesn't work you might need to turn off interactive plotting using ioff() or change the matplotlib backend (pygui(:Agg)) (see here: Calling pylab.savefig without display in ipython) Remember that most questions about plotting using PyPlot can be worked out by reading answers from the python community. And also using the docs at https://github.com/JuliaPy/PyPlot.jl to translate between the two :) A: close() doesn't require any arguments so you can just call close() after saving the figure and create a new figure using PyPlot a = rand(50,40) imshow(a) savefig("a.png") # call close close()
Julia: How to save a figure without plotting/displaying it in PyPlot?
I am using the PyPlot package in Julia to generate and save several figures. My current approach is to display the figure and then save it using savefig. using PyPlot a = rand(50,40) imshow(a) savefig("a.png") Is there a way to save the figure without having to first display it?
[ "Are you using the REPL or IJulia?\nIf you close the figure then it won't show you the plot. Is that what you want?\na = rand(50,40)\nioff() #turns off interactive plotting\nfig = figure()\nimshow(a)\nclose(fig)\n\nIf that doesn't work you might need to turn off interactive plotting using ioff() or change the matplotlib backend (pygui(:Agg)) (see here: Calling pylab.savefig without display in ipython)\nRemember that most questions about plotting using PyPlot can be worked out by reading answers from the python community. And also using the docs at https://github.com/JuliaPy/PyPlot.jl to translate between the two :)\n", "close() doesn't require any arguments so you can just call close() after saving the figure and create a new figure\nusing PyPlot\na = rand(50,40)\nimshow(a)\nsavefig(\"a.png\")\n# call close\nclose()\n\n" ]
[ 5, 0 ]
[]
[]
[ "figure", "julia", "matplotlib", "plot" ]
stackoverflow_0039562515_figure_julia_matplotlib_plot.txt
Q: How to search a Mongo collection for a document that contains an array that contains an element that meets a particular criteria? I'm new at Mongo and there might be a better way to do what I want. I'm dealing with a particular data structure that my application must process. Suppose that I have a collection that contains two documents that contain information about universities and their student clubs to include the name of each club and the name of each student in each club along with their age: { _id: 1, // object ID name: "Oxford University", clubs: [{ name: "Soccer", members: [{ name: "Alice", age: 22 }, { name: "Bob", age: 23 } ] }, { name: "Gymnastics", members: [{ name: "Charlie", age: 20 }, { name: "Dorothy", age: 19 } ] }] } { _id: 2, // object ID name: "Cambridge University", clubs: [{ name: "Chess", members: [{ name: "Ellen", age: 30 }, { name: "Frank", age: 35 } ] }, { name: "Go", members: [{ name: "Gilbert", age: 25 }, { name: "Hikari", age: 40 } ] }] } Suppose that I want to write a query on this collection that will find universities that have a club that has at least one member aged 40 or older. How do I do that? I sketched this example based off of the idea of taking some JSON documents and inserting them into a new collection. Maybe it would be a better idea to break this apart into multiple collections. I just had the idea to research if Mongo might be a good product to use in this situation given that a big part of my job here is to create something that can receive some JSON data, process it, and make it queryable. A: MongoDB queries have a convenient feature to query documents that have a specific value or condition in embedded objects and arrays. In the query you can specify the "path" to the object or array using "dot notation" without having to specify the exact array index, etc. Using your example, you can find the documents where a member of a club is aged 40 or older like this. db.collection.find({ "clubs.members.age": { "$gte": 40 } }) This returns the second document in your example collection. Try it on mongoplayground.net.
How to search a Mongo collection for a document that contains an array that contains an element that meets a particular criteria?
I'm new at Mongo and there might be a better way to do what I want. I'm dealing with a particular data structure that my application must process. Suppose that I have a collection that contains two documents that contain information about universities and their student clubs to include the name of each club and the name of each student in each club along with their age: { _id: 1, // object ID name: "Oxford University", clubs: [{ name: "Soccer", members: [{ name: "Alice", age: 22 }, { name: "Bob", age: 23 } ] }, { name: "Gymnastics", members: [{ name: "Charlie", age: 20 }, { name: "Dorothy", age: 19 } ] }] } { _id: 2, // object ID name: "Cambridge University", clubs: [{ name: "Chess", members: [{ name: "Ellen", age: 30 }, { name: "Frank", age: 35 } ] }, { name: "Go", members: [{ name: "Gilbert", age: 25 }, { name: "Hikari", age: 40 } ] }] } Suppose that I want to write a query on this collection that will find universities that have a club that has at least one member aged 40 or older. How do I do that? I sketched this example based off of the idea of taking some JSON documents and inserting them into a new collection. Maybe it would be a better idea to break this apart into multiple collections. I just had the idea to research if Mongo might be a good product to use in this situation given that a big part of my job here is to create something that can receive some JSON data, process it, and make it queryable.
[ "MongoDB queries have a convenient feature to query documents that have a specific value or condition in embedded objects and arrays. In the query you can specify the \"path\" to the object or array using \"dot notation\" without having to specify the exact array index, etc.\nUsing your example, you can find the documents where a member of a club is aged 40 or older like this.\ndb.collection.find({\n \"clubs.members.age\": {\n \"$gte\": 40\n }\n})\n\nThis returns the second document in your example collection.\nTry it on mongoplayground.net.\n" ]
[ 2 ]
[]
[]
[ "mongodb", "mongodb_query" ]
stackoverflow_0074662288_mongodb_mongodb_query.txt
Q: How to catch all events in Swift without breaking other event handlers How can I catch any touch up event in my application view without affecting any other event in subview or subview of the subview? Currently whenever I add UILongPressGestureRecognizer to my root view, all other addTarget functions break in subviews and their subviews. func gestureRecognizer(_: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith: UIGestureRecognizer) -> Bool { return true } override func viewDidLoad() { let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50)) button.setTitle("Click me", for: .normal) button.addTarget(self, action: #selector(buttonClick), for: .touchDown) self.view.addSubview(button) initLongTapGesture() // This kills the button click handler. } func initLongTapGesture () { let globalTap = UILongPressGestureRecognizer(target: self, action: #selector(tapHandler)) globalTap.delegate = self globalTap.minimumPressDuration = 0 self.view.addGestureRecognizer(globalTap) } @objc func tapHandler(gesture: UITapGestureRecognizer) { if ([.ended, .cancelled, .failed].contains(gesture.state)) { print("Detect global touch end / up") } } @objc func buttonClick() { print("CLICK") // Does not work when initLongTapGesture() is enabled } A: The immediate solution to allow the long press gesture to work without preventing buttons from working is to add the following line: globalTap.cancelsTouchesInView = false in the initLongTapGesture function. With that in place you don't need the gesture delegate method (which didn't solve the issue anyway). The big question is why are you setting a "long" press gesture to have a minimum press duration of 0? If your goal is to monitor all events in the app then you should override the UIApplication method sendEvent. See the following for details on how to subclass UIApplication and override sendEvent: Issues in overwriting the send event of UIApplication in Swift programming You can also go through these search results: https://stackoverflow.com/search?q=%5Bios%5D%5Bswift%5D+override+UIApplication+sendEvent Another option for monitoring all touches in a given view controller or view is to override the various touches... methods from UIResponder such as touchesBegan, touchesEnded, etc. You can override these in a view controller class, for example, to track various touch events happening within that view controller. Unrelated but it is standard to use the .touchUpInside event instead of the touchDown event when handing button events.
How to catch all events in Swift without breaking other event handlers
How can I catch any touch up event in my application view without affecting any other event in subview or subview of the subview? Currently whenever I add UILongPressGestureRecognizer to my root view, all other addTarget functions break in subviews and their subviews. func gestureRecognizer(_: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith: UIGestureRecognizer) -> Bool { return true } override func viewDidLoad() { let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50)) button.setTitle("Click me", for: .normal) button.addTarget(self, action: #selector(buttonClick), for: .touchDown) self.view.addSubview(button) initLongTapGesture() // This kills the button click handler. } func initLongTapGesture () { let globalTap = UILongPressGestureRecognizer(target: self, action: #selector(tapHandler)) globalTap.delegate = self globalTap.minimumPressDuration = 0 self.view.addGestureRecognizer(globalTap) } @objc func tapHandler(gesture: UITapGestureRecognizer) { if ([.ended, .cancelled, .failed].contains(gesture.state)) { print("Detect global touch end / up") } } @objc func buttonClick() { print("CLICK") // Does not work when initLongTapGesture() is enabled }
[ "The immediate solution to allow the long press gesture to work without preventing buttons from working is to add the following line:\nglobalTap.cancelsTouchesInView = false\n\nin the initLongTapGesture function. With that in place you don't need the gesture delegate method (which didn't solve the issue anyway).\n\nThe big question is why are you setting a \"long\" press gesture to have a minimum press duration of 0?\nIf your goal is to monitor all events in the app then you should override the UIApplication method sendEvent. See the following for details on how to subclass UIApplication and override sendEvent:\nIssues in overwriting the send event of UIApplication in Swift programming\nYou can also go through these search results:\nhttps://stackoverflow.com/search?q=%5Bios%5D%5Bswift%5D+override+UIApplication+sendEvent\n\nAnother option for monitoring all touches in a given view controller or view is to override the various touches... methods from UIResponder such as touchesBegan, touchesEnded, etc. You can override these in a view controller class, for example, to track various touch events happening within that view controller.\n\nUnrelated but it is standard to use the .touchUpInside event instead of the touchDown event when handing button events.\n" ]
[ 2 ]
[]
[]
[ "swift", "swift5", "uikit" ]
stackoverflow_0074657970_swift_swift5_uikit.txt
Q: Incremental authorization with Firebase and GoogleAuthProvider I'm using Firebase v8 with the GoogleAuthProvider. Firebase documentation provides the following code to authenticate the user. firebase.auth().signInWithPopup(provider).then((result) => { /** @type {firebase.auth.OAuthCredential} */ var credential = result.credential; // This gives you a Google Access Token. You can use it to access the Google API. var token = credential.accessToken; // The signed-in user info. var user = result.user; // ... }) Questions Google's Using OAuth 2.0 to Access Google APIs article recommends incremental authorization (it's not Firebase, but the recommendation is clear) It is generally a best practice to request scopes incrementally, at the time access is required, rather than up front. For example, an app that wants to support saving an event to a calendar should not request Google Calendar access until the user presses the "Add to Calendar" button. AFAICT, there is no way to achieve incremental authorization with Firebase without re-authenticating the user. While scopes can be added to GoogleAuthProvider using addScope, a subsequent call to signInWithPopup is required (i.e. the user is re-authenticated). Is there any way to prompt only for authorization (e.g. Drive access) without re-authenticating? Assuming the access token is short lived, can the Google ID token be used to obtain a new access token? Is re-authenticating the user the only way to obtain a new access token? Is there a way to determine whether the access token has expired? A: The best way to achieve incremental authorization with Firebase is to use the OAuth 2.0 Authorization Code Flow. This flow allows you to request additional scopes when needed, without re-authenticating the user. The Google ID Token is not suitable for obtaining a new access token. Re-authenticating the user is the only way to obtain a new access token. To determine if an access token has expired, you can use the TokenInfo endpoint of the Google OAuth 2.0 API.
Incremental authorization with Firebase and GoogleAuthProvider
I'm using Firebase v8 with the GoogleAuthProvider. Firebase documentation provides the following code to authenticate the user. firebase.auth().signInWithPopup(provider).then((result) => { /** @type {firebase.auth.OAuthCredential} */ var credential = result.credential; // This gives you a Google Access Token. You can use it to access the Google API. var token = credential.accessToken; // The signed-in user info. var user = result.user; // ... }) Questions Google's Using OAuth 2.0 to Access Google APIs article recommends incremental authorization (it's not Firebase, but the recommendation is clear) It is generally a best practice to request scopes incrementally, at the time access is required, rather than up front. For example, an app that wants to support saving an event to a calendar should not request Google Calendar access until the user presses the "Add to Calendar" button. AFAICT, there is no way to achieve incremental authorization with Firebase without re-authenticating the user. While scopes can be added to GoogleAuthProvider using addScope, a subsequent call to signInWithPopup is required (i.e. the user is re-authenticated). Is there any way to prompt only for authorization (e.g. Drive access) without re-authenticating? Assuming the access token is short lived, can the Google ID token be used to obtain a new access token? Is re-authenticating the user the only way to obtain a new access token? Is there a way to determine whether the access token has expired?
[ "The best way to achieve incremental authorization with Firebase is to use the OAuth 2.0 Authorization Code Flow. This flow allows you to request additional scopes when needed, without re-authenticating the user.\nThe Google ID Token is not suitable for obtaining a new access token. Re-authenticating the user is the only way to obtain a new access token.\nTo determine if an access token has expired, you can use the TokenInfo endpoint of the Google OAuth 2.0 API.\n" ]
[ 0 ]
[]
[]
[ "firebase", "firebase_authentication", "google_oauth" ]
stackoverflow_0074662923_firebase_firebase_authentication_google_oauth.txt
Q: How to start a new process as user "NT AUTHORITY\Network Service"? I am trying to launch a new process as NT AUTHORITY\Network Service from a process that is running as NT AUTHORITY\System. I have looked at other questions, such as the following, which does not provide a working example: CreateProcess running as user: "NT AUTHORITY/Network Service" without knowing the credentials? And, I have come across some posts which talk about copying a token from a process that is already running as NT AUTHORITY\Network Service: Windows API and Impersonation Part 1 - How to get SYSTEM using Primary Tokens. I wonder, is there a way to launch a process without having to depend on another process to copy a token from? Is there a way to hand-craft a token that can help launch a process as NT AUTHORITY\Network Service using CreateProcessAsUserW(), for example? A: I suggest you do it via a scheduled task and then delete the task after it runs (or maybe there is a one-shot setting you could use). While System has the create token privilege the NtCreateToken function is not part of the documented API and using it would be an enormous pain. If not a scheduled task then as a service (again even if you are only going to run it once). A: Is there a way to hand-craft a token that can help launch a process as NT AUTHORITY\Network Service yes. by call NtCreateToken. but for this need have SE_CREATE_TOKEN_PRIVILEGE. but services.exe and services, even running as 'NT AUTHORITY\System' have not it. so you can not just call NtCreateToken. first you need find token with this privilege and only after this. for get token with required privileges set we can use next code: extern const SECURITY_QUALITY_OF_SERVICE sqos = { sizeof (sqos), SecurityImpersonation, SECURITY_DYNAMIC_TRACKING, FALSE }; extern const OBJECT_ATTRIBUTES oa_sqos = { sizeof(oa_sqos), 0, 0, 0, 0, const_cast<SECURITY_QUALITY_OF_SERVICE*>(&sqos) }; NTSTATUS GetToken(_In_ PVOID buf, _In_ const TOKEN_PRIVILEGES* RequiredSet, _Out_ PHANDLE phToken) { NTSTATUS status; union { PVOID pv; PBYTE pb; PSYSTEM_PROCESS_INFORMATION pspi; }; pv = buf; ULONG NextEntryOffset = 0; do { pb += NextEntryOffset; HANDLE hProcess, hToken, hNewToken; CLIENT_ID ClientId = { pspi->UniqueProcessId }; if (ClientId.UniqueProcess) { if (0 <= NtOpenProcess(&hProcess, PROCESS_QUERY_LIMITED_INFORMATION, const_cast<POBJECT_ATTRIBUTES>(&oa_sqos), &ClientId)) { status = NtOpenProcessToken(hProcess, TOKEN_DUPLICATE, &hToken); NtClose(hProcess); if (0 <= status) { status = NtDuplicateToken(hToken, TOKEN_ADJUST_PRIVILEGES|TOKEN_IMPERSONATE|TOKEN_QUERY, const_cast<POBJECT_ATTRIBUTES>(&oa_sqos), FALSE, TokenImpersonation, &hNewToken); NtClose(hToken); if (0 <= status) { status = NtAdjustPrivilegesToken(hNewToken, FALSE, const_cast<PTOKEN_PRIVILEGES>(RequiredSet), 0, 0, 0); if (STATUS_SUCCESS == status) { *phToken = hNewToken; return STATUS_SUCCESS; } NtClose(hNewToken); } } } } } while (NextEntryOffset = pspi->NextEntryOffset); return STATUS_UNSUCCESSFUL; } NTSTATUS GetToken(_In_ const TOKEN_PRIVILEGES* RequiredSet, _Out_ PHANDLE phToken) /*++ Routine Description: try found process token with RequiredSet; duplicate and adjust privilege Arguments: RequiredSet - set of privileges which must be in token phToken - Impersonation Token with all privileges from RequiredSet, all it is enabled (even if some is disabled in original token) --*/ { NTSTATUS status; ULONG cb = 0x40000; do { status = STATUS_INSUFFICIENT_RESOURCES; if (PBYTE buf = new BYTE[cb += PAGE_SIZE]) { if (0 <= (status = NtQuerySystemInformation(SystemProcessInformation, buf, cb, &cb))) { status = GetToken(buf, RequiredSet, phToken); if (status == STATUS_INFO_LENGTH_MISMATCH) { status = STATUS_UNSUCCESSFUL; } } delete [] buf; } } while(status == STATUS_INFO_LENGTH_MISMATCH); return status; } with this we can do next: #define BEGIN_PRIVILEGES(name, n) static const union { TOKEN_PRIVILEGES name;\ struct { ULONG PrivilegeCount; LUID_AND_ATTRIBUTES Privileges[n];} label(_) = { n, { #define LAA(se) {{se}, SE_PRIVILEGE_ENABLED } #define LAA_D(se) {{se} } #define END_PRIVILEGES }};}; BEGIN_PRIVILEGES(tp_dbg, 2) LAA(SE_DEBUG_PRIVILEGE), // need for open processes LAA(SE_IMPERSONATE_PRIVILEGE), // need for impersonate token END_PRIVILEGES BEGIN_PRIVILEGES(tp_cai, 3) LAA(SE_CREATE_TOKEN_PRIVILEGE), LAA(SE_ASSIGNPRIMARYTOKEN_PRIVILEGE), LAA(SE_INCREASE_QUOTA_PRIVILEGE), END_PRIVILEGES EXTERN_C NTSYSCALLAPI NTSTATUS NTAPI NtCreateToken( _Out_ PHANDLE TokenHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ TOKEN_TYPE TokenType, _In_ PLUID AuthenticationId, _In_ PLARGE_INTEGER ExpirationTime, _In_ PTOKEN_USER User, _In_ PTOKEN_GROUPS Groups, _In_ PTOKEN_PRIVILEGES Privileges, _In_opt_ PTOKEN_OWNER Owner, _In_ PTOKEN_PRIMARY_GROUP PrimaryGroup, _In_opt_ PTOKEN_DEFAULT_DACL DefaultDacl, _In_ PTOKEN_SOURCE TokenSource ); NTSTATUS CreateServiceToken(HANDLE hToken, PHANDLE phToken) { NTSTATUS status; PVOID stack = alloca(guz); PVOID buf = 0; ULONG cb = 0, rcb; struct { PTOKEN_GROUPS ptg; PTOKEN_STATISTICS pts; PTOKEN_DEFAULT_DACL ptdd; PTOKEN_PRIVILEGES ptp; } s; void** ppv = (void**)&s.ptp; static const ULONG rcbV[] = { sizeof(TOKEN_GROUPS)+0x80, sizeof(TOKEN_STATISTICS), sizeof(TOKEN_DEFAULT_DACL)+0x80, sizeof(TOKEN_PRIVILEGES)+0x80, }; static TOKEN_INFORMATION_CLASS TokenInformationClassV[] = { TokenGroups, TokenStatistics, TokenDefaultDacl, TokenPrivileges, }; ULONG n = _countof(TokenInformationClassV); do { TOKEN_INFORMATION_CLASS TokenInformationClas = TokenInformationClassV[--n]; rcb = rcbV[n], cb = 0; do { if (cb < rcb) { cb = RtlPointerToOffset(buf = alloca(rcb - cb), stack); } status = NtQueryInformationToken(hToken, TokenInformationClas, buf, cb, &rcb); } while (status == STATUS_BUFFER_TOO_SMALL); if (0 > status) { return status; } *(ppv--) = buf, stack = buf; } while (n); static const SID NetworkService = { SID_REVISION, 1, SECURITY_NT_AUTHORITY, { SECURITY_NETWORK_SERVICE_RID } }; static const TOKEN_OWNER to = { const_cast<SID*>(&NetworkService) }; static const TOKEN_USER tu = { { const_cast<SID*>(&NetworkService) } }; static const TOKEN_SOURCE ts = { {"Advapi"}, SYSTEM_LUID}; return NtCreateToken(phToken, TOKEN_ALL_ACCESS, 0, TokenPrimary, &s.pts->AuthenticationId, &s.pts->ExpirationTime, const_cast<PTOKEN_USER>(&tu), s.ptg, s.ptp, const_cast<PTOKEN_OWNER>(&to), (PTOKEN_PRIMARY_GROUP)&to, s.ptdd, const_cast<PTOKEN_SOURCE>(&ts)); } NTSTATUS RunAsNetworkService() { HANDLE hMyToken, hToken; NTSTATUS status = NtOpenProcessToken(NtCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hMyToken); if (0 <= status) { if (0 <= (status = NtAdjustPrivilegesToken(hMyToken, FALSE, const_cast<PTOKEN_PRIVILEGES>(&tp_dbg), 0, 0, 0))) { if (0 <= (status = GetToken(&tp_cai, &hToken))) { status = RtlSetCurrentThreadToken(hToken); NtClose(hToken); if (0 <= status) { if (0 <= (status = CreateServiceToken(hMyToken, &hToken))) { ULONG SessionId; ProcessIdToSessionId(GetCurrentProcessId(), &SessionId); if (0 <= (status = NtSetInformationToken(hToken, TokenSessionId, &SessionId, sizeof(SessionId)))) { STARTUPINFO si = { sizeof(si) }; si.lpDesktop = const_cast<PWSTR>(L"WinSta0\\Default"); PROCESS_INFORMATION pi; WCHAR cmdline[] = L"cmd /k whoami.exe /user"; if (CreateProcessAsUserW(hToken, 0, cmdline, 0, 0, 0, 0, 0, 0, &si, &pi)) { NtClose(pi.hThread); NtClose(pi.hProcess); } else { status = RtlGetLastNtStatus(); } } NtClose(hToken); } RtlSetCurrentThreadToken(); } } } NtClose(hMyToken); } return status; } (code not use /RTCs ) A: I came across a function LogonUser which can be used to create token for required user. The doc shows an example for creating token for NT AUTHORITY\LocalService like this: LogonUser(L"LocalService", L"NT AUTHORITY", NULL, LOGON32_LOGON_SERVICE, LOGON32_PROVIDER_DEFAULT, &hToken) I used the above in combination with CreateProcessAsUser function which starts child process as NT AUTHORITY\NetworkService where the parent is running as NT AUTHORITY\System #include <Windows.h> HANDLE token; LogonUser( L"NetworkService", L"NT AUTHORITY", nullptr, LOGON32_LOGON_SERVICE, LOGON32_PROVIDER_DEFAULT, &token); // Setup required variables to start the process LPPROCESS_INFORMATION lpProcessInformation; STARTUPINFOEX si; PWCHAR path; PCWSTR environmentBlockPtr = nullptr; DWORD creationFlags; WCHAR* commandStr; CreateProcessAsUser( token, nullptr, const_cast<WCHAR*>(commandStr), nullptr, nullptr, FALSE, creationFlags, const_cast<WCHAR*>(environmentBlockPtr), path, &si.StartupInfo, lpProcessInformation);
How to start a new process as user "NT AUTHORITY\Network Service"?
I am trying to launch a new process as NT AUTHORITY\Network Service from a process that is running as NT AUTHORITY\System. I have looked at other questions, such as the following, which does not provide a working example: CreateProcess running as user: "NT AUTHORITY/Network Service" without knowing the credentials? And, I have come across some posts which talk about copying a token from a process that is already running as NT AUTHORITY\Network Service: Windows API and Impersonation Part 1 - How to get SYSTEM using Primary Tokens. I wonder, is there a way to launch a process without having to depend on another process to copy a token from? Is there a way to hand-craft a token that can help launch a process as NT AUTHORITY\Network Service using CreateProcessAsUserW(), for example?
[ "I suggest you do it via a scheduled task and then delete the task after it runs (or maybe there is a one-shot setting you could use). While System has the create token privilege the NtCreateToken function is not part of the documented API and using it would be an enormous pain. If not a scheduled task then as a service (again even if you are only going to run it once).\n", "\nIs there a way to hand-craft a token that can help launch a process\nas NT AUTHORITY\\Network Service\n\nyes. by call NtCreateToken. but for this need have SE_CREATE_TOKEN_PRIVILEGE. but services.exe and services, even running as 'NT AUTHORITY\\System' have not it. so you can not just call NtCreateToken. first you need find token with this privilege and only after this.\nfor get token with required privileges set we can use next code:\nextern const SECURITY_QUALITY_OF_SERVICE sqos = {\n sizeof (sqos), SecurityImpersonation, SECURITY_DYNAMIC_TRACKING, FALSE\n};\n\nextern const OBJECT_ATTRIBUTES oa_sqos = { sizeof(oa_sqos), 0, 0, 0, 0, const_cast<SECURITY_QUALITY_OF_SERVICE*>(&sqos) };\n\nNTSTATUS GetToken(_In_ PVOID buf, _In_ const TOKEN_PRIVILEGES* RequiredSet, _Out_ PHANDLE phToken)\n{\n NTSTATUS status;\n\n union {\n PVOID pv;\n PBYTE pb;\n PSYSTEM_PROCESS_INFORMATION pspi;\n };\n\n pv = buf;\n ULONG NextEntryOffset = 0;\n\n do \n {\n pb += NextEntryOffset;\n\n HANDLE hProcess, hToken, hNewToken;\n\n CLIENT_ID ClientId = { pspi->UniqueProcessId };\n\n if (ClientId.UniqueProcess)\n {\n if (0 <= NtOpenProcess(&hProcess, PROCESS_QUERY_LIMITED_INFORMATION, \n const_cast<POBJECT_ATTRIBUTES>(&oa_sqos), &ClientId))\n {\n status = NtOpenProcessToken(hProcess, TOKEN_DUPLICATE, &hToken);\n\n NtClose(hProcess);\n\n if (0 <= status)\n {\n status = NtDuplicateToken(hToken, TOKEN_ADJUST_PRIVILEGES|TOKEN_IMPERSONATE|TOKEN_QUERY, \n const_cast<POBJECT_ATTRIBUTES>(&oa_sqos), FALSE, TokenImpersonation, &hNewToken);\n\n NtClose(hToken);\n\n if (0 <= status)\n {\n status = NtAdjustPrivilegesToken(hNewToken, FALSE, const_cast<PTOKEN_PRIVILEGES>(RequiredSet), 0, 0, 0);\n\n if (STATUS_SUCCESS == status) \n {\n *phToken = hNewToken;\n return STATUS_SUCCESS;\n }\n\n NtClose(hNewToken);\n }\n }\n }\n }\n\n } while (NextEntryOffset = pspi->NextEntryOffset);\n\n return STATUS_UNSUCCESSFUL;\n}\n\nNTSTATUS GetToken(_In_ const TOKEN_PRIVILEGES* RequiredSet, _Out_ PHANDLE phToken)\n/*++\nRoutine Description:\n try found process token with RequiredSet; duplicate and adjust privilege \nArguments:\n RequiredSet - set of privileges which must be in token\n phToken - Impersonation Token with all privileges from RequiredSet, all it is enabled (even if some is disabled in original token)\n--*/\n{\n NTSTATUS status;\n\n ULONG cb = 0x40000;\n\n do \n {\n status = STATUS_INSUFFICIENT_RESOURCES;\n\n if (PBYTE buf = new BYTE[cb += PAGE_SIZE])\n {\n if (0 <= (status = NtQuerySystemInformation(SystemProcessInformation, buf, cb, &cb)))\n {\n status = GetToken(buf, RequiredSet, phToken);\n\n if (status == STATUS_INFO_LENGTH_MISMATCH)\n {\n status = STATUS_UNSUCCESSFUL;\n }\n }\n\n delete [] buf;\n }\n\n } while(status == STATUS_INFO_LENGTH_MISMATCH);\n\n return status;\n}\n\nwith this we can do next:\n#define BEGIN_PRIVILEGES(name, n) static const union { TOKEN_PRIVILEGES name;\\\nstruct { ULONG PrivilegeCount; LUID_AND_ATTRIBUTES Privileges[n];} label(_) = { n, {\n\n#define LAA(se) {{se}, SE_PRIVILEGE_ENABLED }\n#define LAA_D(se) {{se} }\n\n#define END_PRIVILEGES }};};\n\nBEGIN_PRIVILEGES(tp_dbg, 2)\n LAA(SE_DEBUG_PRIVILEGE), // need for open processes\n LAA(SE_IMPERSONATE_PRIVILEGE), // need for impersonate token\nEND_PRIVILEGES\n\nBEGIN_PRIVILEGES(tp_cai, 3)\n LAA(SE_CREATE_TOKEN_PRIVILEGE),\n LAA(SE_ASSIGNPRIMARYTOKEN_PRIVILEGE),\n LAA(SE_INCREASE_QUOTA_PRIVILEGE),\nEND_PRIVILEGES\n\nEXTERN_C NTSYSCALLAPI NTSTATUS NTAPI NtCreateToken(\n _Out_ PHANDLE TokenHandle,\n _In_ ACCESS_MASK DesiredAccess,\n _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,\n _In_ TOKEN_TYPE TokenType,\n _In_ PLUID AuthenticationId,\n _In_ PLARGE_INTEGER ExpirationTime,\n _In_ PTOKEN_USER User,\n _In_ PTOKEN_GROUPS Groups,\n _In_ PTOKEN_PRIVILEGES Privileges,\n _In_opt_ PTOKEN_OWNER Owner,\n _In_ PTOKEN_PRIMARY_GROUP PrimaryGroup,\n _In_opt_ PTOKEN_DEFAULT_DACL DefaultDacl,\n _In_ PTOKEN_SOURCE TokenSource \n );\n\nNTSTATUS CreateServiceToken(HANDLE hToken, PHANDLE phToken)\n{\n NTSTATUS status;\n PVOID stack = alloca(guz);\n PVOID buf = 0;\n ULONG cb = 0, rcb;\n\n struct {\n PTOKEN_GROUPS ptg;\n PTOKEN_STATISTICS pts;\n PTOKEN_DEFAULT_DACL ptdd;\n PTOKEN_PRIVILEGES ptp;\n } s;\n\n void** ppv = (void**)&s.ptp;\n\n static const ULONG rcbV[] = {\n sizeof(TOKEN_GROUPS)+0x80,\n sizeof(TOKEN_STATISTICS),\n sizeof(TOKEN_DEFAULT_DACL)+0x80,\n sizeof(TOKEN_PRIVILEGES)+0x80,\n };\n\n static TOKEN_INFORMATION_CLASS TokenInformationClassV[] = { \n TokenGroups, \n TokenStatistics,\n TokenDefaultDacl, \n TokenPrivileges, \n };\n\n ULONG n = _countof(TokenInformationClassV);\n\n do \n {\n TOKEN_INFORMATION_CLASS TokenInformationClas = TokenInformationClassV[--n];\n\n rcb = rcbV[n], cb = 0;\n\n do \n {\n if (cb < rcb)\n {\n cb = RtlPointerToOffset(buf = alloca(rcb - cb), stack);\n }\n\n status = NtQueryInformationToken(hToken, TokenInformationClas, buf, cb, &rcb);\n\n } while (status == STATUS_BUFFER_TOO_SMALL);\n\n if (0 > status)\n {\n return status;\n }\n\n *(ppv--) = buf, stack = buf;\n\n } while (n);\n\n \n static const SID NetworkService = { SID_REVISION, 1, SECURITY_NT_AUTHORITY, { SECURITY_NETWORK_SERVICE_RID } };\n static const TOKEN_OWNER to = { const_cast<SID*>(&NetworkService) };\n static const TOKEN_USER tu = { { const_cast<SID*>(&NetworkService) } };\n static const TOKEN_SOURCE ts = { {\"Advapi\"}, SYSTEM_LUID};\n\n return NtCreateToken(phToken, TOKEN_ALL_ACCESS, 0, TokenPrimary, \n &s.pts->AuthenticationId, &s.pts->ExpirationTime, \n const_cast<PTOKEN_USER>(&tu), s.ptg, s.ptp, const_cast<PTOKEN_OWNER>(&to), \n (PTOKEN_PRIMARY_GROUP)&to, s.ptdd, const_cast<PTOKEN_SOURCE>(&ts));\n}\n\nNTSTATUS RunAsNetworkService()\n{\n HANDLE hMyToken, hToken;\n NTSTATUS status = NtOpenProcessToken(NtCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hMyToken);\n if (0 <= status)\n {\n if (0 <= (status = NtAdjustPrivilegesToken(hMyToken, FALSE, const_cast<PTOKEN_PRIVILEGES>(&tp_dbg), 0, 0, 0)))\n {\n if (0 <= (status = GetToken(&tp_cai, &hToken)))\n {\n status = RtlSetCurrentThreadToken(hToken);\n\n NtClose(hToken);\n\n if (0 <= status)\n {\n if (0 <= (status = CreateServiceToken(hMyToken, &hToken)))\n {\n ULONG SessionId;\n ProcessIdToSessionId(GetCurrentProcessId(), &SessionId);\n\n if (0 <= (status = NtSetInformationToken(hToken, TokenSessionId, &SessionId, sizeof(SessionId))))\n {\n STARTUPINFO si = { sizeof(si) };\n si.lpDesktop = const_cast<PWSTR>(L\"WinSta0\\\\Default\");\n PROCESS_INFORMATION pi;\n WCHAR cmdline[] = L\"cmd /k whoami.exe /user\";\n\n if (CreateProcessAsUserW(hToken, 0, cmdline, 0, 0, 0, 0, 0, 0, &si, &pi))\n {\n NtClose(pi.hThread);\n NtClose(pi.hProcess);\n }\n else\n {\n status = RtlGetLastNtStatus();\n }\n }\n\n NtClose(hToken);\n }\n\n RtlSetCurrentThreadToken();\n }\n }\n }\n\n NtClose(hMyToken);\n }\n\n return status;\n}\n\n(code not use /RTCs )\n", "I came across a function LogonUser which can be used to create token for required user. The doc shows an example for creating token for NT AUTHORITY\\LocalService like this:\nLogonUser(L\"LocalService\", L\"NT AUTHORITY\", NULL, LOGON32_LOGON_SERVICE, LOGON32_PROVIDER_DEFAULT, &hToken)\n\nI used the above in combination with CreateProcessAsUser function which starts child process as NT AUTHORITY\\NetworkService where the parent is running as NT AUTHORITY\\System\n#include <Windows.h>\n\nHANDLE token;\nLogonUser(\n L\"NetworkService\",\n L\"NT AUTHORITY\",\n nullptr,\n LOGON32_LOGON_SERVICE,\n LOGON32_PROVIDER_DEFAULT,\n &token);\n\n// Setup required variables to start the process\nLPPROCESS_INFORMATION lpProcessInformation;\nSTARTUPINFOEX si;\nPWCHAR path;\nPCWSTR environmentBlockPtr = nullptr;\nDWORD creationFlags;\nWCHAR* commandStr;\n\nCreateProcessAsUser(\n token,\n nullptr,\n const_cast<WCHAR*>(commandStr),\n nullptr,\n nullptr,\n FALSE,\n creationFlags,\n const_cast<WCHAR*>(environmentBlockPtr),\n path,\n &si.StartupInfo,\n lpProcessInformation);\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "c++", "winapi", "windows" ]
stackoverflow_0074636046_c++_winapi_windows.txt
Q: Sum of array numbers in Powershell i am completely new using PowerShell and coding in general. I want the sum of all the numbers inside my array. after several attempts, I'm not able to get it. Please help!! This is my code: $Numbers = @(1,2,3,4,5,6,7,8,9,10) function LUFEN($Num_3){ for($Rept = 0; $Rept -le $Numbers.Length -1; $Rept++){ if($Num_3 -eq $Numbers[$Rept]){ return " The number exists." } } $Num_3= Read-Host("Type a number") LUFEN($Num_3) Also, I where can I fix the indentation in the Ps ISE? I cannot find the option. Thanks! Nothing has worked for me :( A: Sum all numbers in the array $sum = 0 foreach ($number in $Numbers) { $sum += $number } Print the sum Write-Host "The sum is $sum"
Sum of array numbers in Powershell
i am completely new using PowerShell and coding in general. I want the sum of all the numbers inside my array. after several attempts, I'm not able to get it. Please help!! This is my code: $Numbers = @(1,2,3,4,5,6,7,8,9,10) function LUFEN($Num_3){ for($Rept = 0; $Rept -le $Numbers.Length -1; $Rept++){ if($Num_3 -eq $Numbers[$Rept]){ return " The number exists." } } $Num_3= Read-Host("Type a number") LUFEN($Num_3) Also, I where can I fix the indentation in the Ps ISE? I cannot find the option. Thanks! Nothing has worked for me :(
[ "Sum all numbers in the array\n$sum = 0\nforeach ($number in $Numbers) {\n $sum += $number\n}\n\nPrint the sum\nWrite-Host \"The sum is $sum\"\n\n" ]
[ 0 ]
[]
[]
[ "powershell" ]
stackoverflow_0074662937_powershell.txt
Q: Python - Find x and y values of a 2D gaussian given a value for the function I have a 2D gaussian function f(x,y). I know the values x₀ and y₀ at which the peak g₀ of the function occurs. But then I want to find xₑ and yₑ values at which f(xₑ, yₑ) = g₀ / e¹. I know there are multiple solutions to this, but at least one is sufficient. So far I have def f(x, y, g0,x0,y0,sigma_x,sigma_y,offset): return offset + g0* np.exp(-(((x-x0)**(2)/(2*sigma_x**(2))) + ((y-y0)**(2)/(2*sigma_y**(2))))) All variables taken as parameters are known as they were extracted from a curve fit. I understand that taking the derivative in x and setting f() = 0 and similarly in y, gives a solvable linear system for (x,y), but this seems like overkill to manually implement, there must be some library or tool out there that can do what I am trying to achieve? A: There are an infinite number of possibilities (or possibly 1 trivial or none in special cases regarding the value of g0). A solution can be computed analytically in constant time using a direct method. No need for approximations or iterative methods to find roots of a given function. It is just pure maths. Gaussian kernel have interesting symmetries. One of them is the invariance to the rotation when the peak is translated to (0,0). Another on is that the 1D section of a 2D gaussian surface is a gaussian curve. Lets ignore offset for a moment: it does not really change the problem (it is just a Z-axis translation) and add additional useless term for the resolution. The geometric solution to is problem is an ellipse so the solution (xe, ye) follows the conic expression : (xe-x0)² / a² + (ye-y0)² / b² = 1. If sigma_x = sigma_y, then the solution is simpler : this is a circle with the expression (xe-x0)² + (ye-y0)² = r. Note that a, b and r are dependant of the searched value and the kernel parameters (eg. sigma_x). Changing sigma_x and sigma_y is like stretching the space, and so the solution similarly. Changing x0 and y0 is like translating the space and so the solution too. In fact, we could solve the problem for the simpler case where x0=0, y0=0, sigma_x=1 and sigma_y=1. Then we can apply a translation, followed by a linear transformation using a transformation matrix. A basic multiplication 4x4 matrix can do that. Solving the simpler case is much easier since there are are less parameter to consider. Actually, g0 and offset can also be partially discarded of f since it is on both side of the expression and one just need to solve the linear equation offset + g0 * h(xe,ye) = g0 / e so h(x,y) = 1 / e - offset / g0 where h(xe, ye) = exp(-(xe² + ye²)/2). Assuming we forget the translation and linear transformation for a moment, the problem can be solve quite easily: h(xe, ye) = 1 / e - offset / g0 exp(-(xe² + ye²)/2) = 1 / e - offset / g0 -(xe² + ye²)/2 = ln(1 / e - offset / g0) xe² + ye² = -2 * ln(1 / e - offset / g0) That's it! We got our circle expression where the radius r is -2*ln(1 / e - offset / g0)! Note that ln in the expression is basically the natural logarithm. Now we could try to find the 4x4 matrix coefficients, or actually try to directly solve the full expression which is finally not so difficult. offset + g0 * exp(-((x-x0)²/(2*sigma_x²) + (y-y0)²/(2*sigma_y²))) = g0 / e exp(-((x-x0)²/(2*sigma_x²) + (y-y0)²/(2*sigma_y²))) = 1 / e - offset / g0 -((x-x0)²/(2*sigma_x²) + (y-y0)²/(2*sigma_y²)) = ln(1 / e - offset / g0) ((x-x0)²/sigma_x² + (y-y0)²/sigma_y²)/2 = -ln(1 / e - offset / g0) (x-x0)²/sigma_x² + (y-y0)²/sigma_y² = -2 * ln(1 / e - offset / g0) That's it! We got you conic expression where r = -2 * ln(1 / e - offset / g0) is a constant, a = sigma_x and b = sigma_y are the unknown parameter in the above expression. It can be normalized using a = sigma_x/sqrt(r) and b = sigma_y/sqrt(r) so the right hand side is 1 fitting exactly with the above expression but this is just some math details. You can find one point of the ellipse easily since you know the centre of the ellipse (x0, y0) and there is at least 1 point at the intersection of the line y=y0 and the above conic expression. Lets find it: (x-x0)²/sigma_x² + (y0-y0)²/sigma_y² = -2 * ln(1 / e - offset / g0) (x-x0)²/sigma_x² = -2 * ln(1 / e - offset / g0) (x-x0)² = -2 * ln(1 / e - offset / g0) * sigma_x² x = sqrt(-2 * ln(1 / e - offset / g0) * sigma_x²) + x0 Note there are two solutions (-sqrt(...) + x0) but you only need one of them. I hope I did not make any mistake in the computation (at least the details should be enough to find it easily) and the solution is not a complex number in your case. The benefit of this solution is that it is very very fast to compute. The final solution is: (xe, ye) = (sqrt(-2*ln(1/e-offset/g0)*sigma_x²)+x0, y0) A: You can use the scipy.optimize.fsolve function to find the (xₑ, yₑ) values that satisfy the equation f(xₑ, yₑ) = g₀ / e¹. This function uses a numerical root-finding algorithm to find the roots of a system of non-linear equations. Here's an example of how you can use scipy.optimize.fsolve to find the (xₑ, yₑ) values that satisfy the equation f(xₑ, yₑ) = g₀ / e¹: from scipy.optimize import fsolve # Define the function f(x, y) def f(x, y, g0, x0, y0, sigma_x, sigma_y, offset): return offset + g0 * np.exp(-(((x-x0)**(2)/(2*sigma_x**(2))) + ((y-y0)**(2)/(2*sigma_y**(2))))) # Define the function that we want to find the roots of def g(xy, g0, x0, y0, sigma_x, sigma_y, offset): x, y = xy return f(x, y, g0, x0, y0, sigma_x, sigma_y, offset) - g0 / np.exp(1) # Define the initial guess for the root x0_guess = x0 y0_guess = y0 # Find the roots of the function g(x, y) x, y = fsolve(g, (x0_guess, y0_guess), args=(g0, x0, y0, sigma_x, sigma_y, offset)) # Print the result print(f"x = {x}, y = {y}") In this example, fsolve will use the initial guess (x0_guess, y0_guess) as a starting point and iteratively try to find the roots of the function g(x, y). If the function g(x, y) has multiple roots, fsolve will return only one of them (the one closest to the initial guess).
Python - Find x and y values of a 2D gaussian given a value for the function
I have a 2D gaussian function f(x,y). I know the values x₀ and y₀ at which the peak g₀ of the function occurs. But then I want to find xₑ and yₑ values at which f(xₑ, yₑ) = g₀ / e¹. I know there are multiple solutions to this, but at least one is sufficient. So far I have def f(x, y, g0,x0,y0,sigma_x,sigma_y,offset): return offset + g0* np.exp(-(((x-x0)**(2)/(2*sigma_x**(2))) + ((y-y0)**(2)/(2*sigma_y**(2))))) All variables taken as parameters are known as they were extracted from a curve fit. I understand that taking the derivative in x and setting f() = 0 and similarly in y, gives a solvable linear system for (x,y), but this seems like overkill to manually implement, there must be some library or tool out there that can do what I am trying to achieve?
[ "There are an infinite number of possibilities (or possibly 1 trivial or none in special cases regarding the value of g0). A solution can be computed analytically in constant time using a direct method. No need for approximations or iterative methods to find roots of a given function. It is just pure maths.\nGaussian kernel have interesting symmetries. One of them is the invariance to the rotation when the peak is translated to (0,0). Another on is that the 1D section of a 2D gaussian surface is a gaussian curve.\nLets ignore offset for a moment: it does not really change the problem (it is just a Z-axis translation) and add additional useless term for the resolution.\nThe geometric solution to is problem is an ellipse so the solution (xe, ye) follows the conic expression : (xe-x0)² / a² + (ye-y0)² / b² = 1. If sigma_x = sigma_y, then the solution is simpler : this is a circle with the expression (xe-x0)² + (ye-y0)² = r. Note that a, b and r are dependant of the searched value and the kernel parameters (eg. sigma_x). Changing sigma_x and sigma_y is like stretching the space, and so the solution similarly. Changing x0 and y0 is like translating the space and so the solution too.\nIn fact, we could solve the problem for the simpler case where x0=0, y0=0, sigma_x=1 and sigma_y=1. Then we can apply a translation, followed by a linear transformation using a transformation matrix. A basic multiplication 4x4 matrix can do that. Solving the simpler case is much easier since there are are less parameter to consider. Actually, g0 and offset can also be partially discarded of f since it is on both side of the expression and one just need to solve the linear equation offset + g0 * h(xe,ye) = g0 / e so h(x,y) = 1 / e - offset / g0 where h(xe, ye) = exp(-(xe² + ye²)/2). Assuming we forget the translation and linear transformation for a moment, the problem can be solve quite easily:\nh(xe, ye) = 1 / e - offset / g0 \nexp(-(xe² + ye²)/2) = 1 / e - offset / g0 \n-(xe² + ye²)/2 = ln(1 / e - offset / g0) \nxe² + ye² = -2 * ln(1 / e - offset / g0)\nThat's it! We got our circle expression where the radius r is -2*ln(1 / e - offset / g0)! Note that ln in the expression is basically the natural logarithm.\nNow we could try to find the 4x4 matrix coefficients, or actually try to directly solve the full expression which is finally not so difficult.\noffset + g0 * exp(-((x-x0)²/(2*sigma_x²) + (y-y0)²/(2*sigma_y²))) = g0 / e \nexp(-((x-x0)²/(2*sigma_x²) + (y-y0)²/(2*sigma_y²))) = 1 / e - offset / g0 \n-((x-x0)²/(2*sigma_x²) + (y-y0)²/(2*sigma_y²)) = ln(1 / e - offset / g0) \n((x-x0)²/sigma_x² + (y-y0)²/sigma_y²)/2 = -ln(1 / e - offset / g0) \n(x-x0)²/sigma_x² + (y-y0)²/sigma_y² = -2 * ln(1 / e - offset / g0)\nThat's it! We got you conic expression where r = -2 * ln(1 / e - offset / g0) is a constant, a = sigma_x and b = sigma_y are the unknown parameter in the above expression. It can be normalized using a = sigma_x/sqrt(r) and b = sigma_y/sqrt(r) so the right hand side is 1 fitting exactly with the above expression but this is just some math details.\nYou can find one point of the ellipse easily since you know the centre of the ellipse (x0, y0) and there is at least 1 point at the intersection of the line y=y0 and the above conic expression. Lets find it:\n(x-x0)²/sigma_x² + (y0-y0)²/sigma_y² = -2 * ln(1 / e - offset / g0) \n(x-x0)²/sigma_x² = -2 * ln(1 / e - offset / g0) \n(x-x0)² = -2 * ln(1 / e - offset / g0) * sigma_x² \nx = sqrt(-2 * ln(1 / e - offset / g0) * sigma_x²) + x0\nNote there are two solutions (-sqrt(...) + x0) but you only need one of them. I hope I did not make any mistake in the computation (at least the details should be enough to find it easily) and the solution is not a complex number in your case. The benefit of this solution is that it is very very fast to compute.\nThe final solution is: \n(xe, ye) = (sqrt(-2*ln(1/e-offset/g0)*sigma_x²)+x0, y0)\n", "You can use the scipy.optimize.fsolve function to find the (xₑ, yₑ) values that satisfy the equation f(xₑ, yₑ) = g₀ / e¹. This function uses a numerical root-finding algorithm to find the roots of a system of non-linear equations.\nHere's an example of how you can use scipy.optimize.fsolve to find the (xₑ, yₑ) values that satisfy the equation f(xₑ, yₑ) = g₀ / e¹:\nfrom scipy.optimize import fsolve\n\n# Define the function f(x, y)\ndef f(x, y, g0, x0, y0, sigma_x, sigma_y, offset):\n return offset + g0 * np.exp(-(((x-x0)**(2)/(2*sigma_x**(2))) + ((y-y0)**(2)/(2*sigma_y**(2)))))\n\n# Define the function that we want to find the roots of\ndef g(xy, g0, x0, y0, sigma_x, sigma_y, offset):\n x, y = xy\n return f(x, y, g0, x0, y0, sigma_x, sigma_y, offset) - g0 / np.exp(1)\n\n# Define the initial guess for the root\nx0_guess = x0\ny0_guess = y0\n\n# Find the roots of the function g(x, y)\nx, y = fsolve(g, (x0_guess, y0_guess), args=(g0, x0, y0, sigma_x, sigma_y, offset))\n\n# Print the result\nprint(f\"x = {x}, y = {y}\")\n\nIn this example, fsolve will use the initial guess (x0_guess, y0_guess) as a starting point and iteratively try to find the roots of the function g(x, y). If the function g(x, y) has multiple roots, fsolve will return only one of them (the one closest to the initial guess).\n" ]
[ 2, 1 ]
[]
[]
[ "gaussian", "numpy", "python" ]
stackoverflow_0074660993_gaussian_numpy_python.txt
Q: How do I print values by sections? How do I print values like this: I'm making program that returns a store invoice, but I don't know how to print the result like that. I tried .format but the values don't have the same length. A: num = 142 print("This is right-aligned by 10 units. {:>10}".format(num))
How do I print values by sections?
How do I print values like this: I'm making program that returns a store invoice, but I don't know how to print the result like that. I tried .format but the values don't have the same length.
[ "num = 142\nprint(\"This is right-aligned by 10 units. {:>10}\".format(num))\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074662835_python_python_3.x.txt
Q: Can not set form value to string if matDatepicker is set <mat-form-field> <mat-label>Choose a date</mat-label> <input matInput [matDatepicker]="picker" formControlName="date"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker></mat-datepicker> </mat-form-field> If I set the input value to a date everything works fine. this.form.controls['date'].setValue(new Date()); But I also want to manully set the input value to a string like this this.form.controls['date'].setValue('permanent'); But MatDatepicker does not allow me to do that and shows nothing (it probably expects a date format) even though my form accepts the string value 'permanent'. form: input: What I was expecting: A: Result By default, the mat-datepicker is using NativeDateAdapter as the default DateAdapter. You can create a custom date adapter class by extending from DateAdapter. For example, I created custom-date-adapter.ts and extend DateAdapter with type param <Date | string> which allow support of string. export class CustomDateAdapter extends DateAdapter<Date | string> { Inject and use the default NativeDateAdapter when overriding DateAdapter abstract methods adapter: NativeDateAdapter; ... constructor(nativeDateAdapter: NativeDateAdapter) { ... this.adapter = nativeDateAdapter; For example, for parse and isDateInstance override, check for permanent keyword, if true, then return. Else, call the nativeDateAdapter default method. NativeDateAdapter@isDateInstance is called when setValue('permanent') and NativeDateAdapter@parse is called when type inpermanent. parse(value: any, parseFormat: any): string | Date | null { if (value === 'permanent') { return 'permanent'; } return this.adapter.parse(value, parseFormat); } isDateInstance(obj: any): boolean { if (obj === 'permanent') { return true; } return this.adapter.isDateInstance(obj); } Other small details like the private _today: Date = new Date();, this variable is used in other override methods, to pass into nativeDateAdapter method when the user enters any string, so that the date picker can expand and point to today date. For example, if return 0 in getYear method, the picklist will point to 0 years when the user enters string input and expand it. Full code app.component.html <form [formGroup]="form"> <mat-form-field> <mat-label>Choose a date</mat-label> <input matInput [matDatepicker]="picker" formControlName="date"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker></mat-datepicker> </mat-form-field> <hr> date.value = {{ form.controls['date'].value }} <br/> date.valid = {{ form.controls['date'].valid }} </form> app.component.ts import { Component } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'ng-date-picker'; form = new FormGroup({ date: new FormControl('permanent') }); } app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatDatepickerModule } from '@angular/material/datepicker'; import { DateAdapter, MatNativeDateModule, MAT_DATE_FORMATS, MAT_NATIVE_DATE_FORMATS, NativeDateAdapter, } from '@angular/material/core'; import { MatInputModule } from '@angular/material/input'; import { CustomDateAdapter } from './custom-date-adapter'; import { MatButtonModule } from '@angular/material/button'; @NgModule({ declarations: [AppComponent], imports: [ BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, MatFormFieldModule, MatDatepickerModule, MatNativeDateModule, FormsModule, MatInputModule, MatButtonModule, ], providers: [ NativeDateAdapter, { provide: DateAdapter, useClass: CustomDateAdapter }, ], bootstrap: [AppComponent], }) export class AppModule {} custom-date-adapter.ts import { Injectable } from '@angular/core'; import { DateAdapter, NativeDateAdapter } from '@angular/material/core'; @Injectable() export class CustomDateAdapter extends DateAdapter<Date | string> { adapter: NativeDateAdapter; private _today: Date = new Date(); constructor(nativeDateAdapter: NativeDateAdapter) { super(); this.adapter = nativeDateAdapter; } parse(value: any, parseFormat: any): string | Date | null { if (value === 'permanent') { return 'permanent'; } return this.adapter.parse(value, parseFormat); } isDateInstance(obj: any): boolean { if (obj === 'permanent') { return true; } return this.adapter.isDateInstance(obj); } isValid(date: string | Date): boolean { return date instanceof Date ? this.adapter.isValid(date) : date === 'permanent'; } getYear(date: string | Date): number { return date instanceof Date ? this.adapter.getYear(date) : this.adapter.getYear(this._today); } getMonth(date: string | Date): number { return date instanceof Date ? this.adapter.getMonth(date) : this.adapter.getMonth(this._today); } getDate(date: string | Date): number { return date instanceof Date ? this.adapter.getDate(date) : this.adapter.getDate(this._today); } getDayOfWeek(date: string | Date): number { return date instanceof Date ? this.adapter.getDayOfWeek(date) : this.adapter.getDayOfWeek(this._today); } getMonthNames(style: 'long' | 'short' | 'narrow'): string[] { return this.adapter.getMonthNames(style); } getDateNames(): string[] { return this.adapter.getDateNames(); } getDayOfWeekNames(style: 'long' | 'short' | 'narrow'): string[] { return this.adapter.getDayOfWeekNames(style); } getYearName(date: string | Date): string { return date instanceof Date ? this.adapter.getYearName(date) : this.adapter.getYearName(this._today); } getFirstDayOfWeek(): number { return this.adapter.getFirstDayOfWeek(); } getNumDaysInMonth(date: string | Date): number { return date instanceof Date ? this.adapter.getNumDaysInMonth(date) : this.adapter.getNumDaysInMonth(this._today); } clone(date: string | Date): string | Date { return date instanceof Date ? this.adapter.clone(date) : this.adapter.clone(this._today); } createDate(year: number, month: number, date: number): string | Date { return this.adapter.createDate(year, month, date); } today(): string | Date { return this.adapter.today(); } format(date: string | Date, displayFormat: any): string { return date instanceof Date ? this.adapter.format(date, displayFormat) : (date as string); } addCalendarYears(date: string | Date, years: number): string | Date { return date instanceof Date ? this.adapter.addCalendarYears(date, years) : ''; } addCalendarMonths(date: string | Date, months: number): string | Date { return date instanceof Date ? this.adapter.addCalendarMonths(date, months) : ''; } addCalendarDays(date: string | Date, days: number): string | Date { return date instanceof Date ? this.adapter.addCalendarDays(date, days) : ''; } toIso8601(date: string | Date): string { return date instanceof Date ? this.adapter.toIso8601(date) : ''; } invalid(): string | Date { return this.adapter.invalid(); } } package.json { "name": "ng-date-picker", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "watch": "ng build --watch --configuration development", "test": "ng test" }, "private": true, "dependencies": { "@angular/animations": "^15.0.0", "@angular/cdk": "^15.0.1", "@angular/common": "^15.0.0", "@angular/compiler": "^15.0.0", "@angular/core": "^15.0.0", "@angular/forms": "^15.0.0", "@angular/material": "^15.0.1", "@angular/platform-browser": "^15.0.0", "@angular/platform-browser-dynamic": "^15.0.0", "@angular/router": "^15.0.0", "rxjs": "~7.5.0", "tslib": "^2.3.0", "zone.js": "~0.12.0" }, "devDependencies": { "@angular-devkit/build-angular": "^15.0.2", "@angular/cli": "~15.0.2", "@angular/compiler-cli": "^15.0.0", "@types/jasmine": "~4.3.0", "jasmine-core": "~4.5.0", "karma": "~6.4.0", "karma-chrome-launcher": "~3.1.0", "karma-coverage": "~2.2.0", "karma-jasmine": "~5.1.0", "karma-jasmine-html-reporter": "~2.0.0", "typescript": "~4.8.2" } }
Can not set form value to string if matDatepicker is set
<mat-form-field> <mat-label>Choose a date</mat-label> <input matInput [matDatepicker]="picker" formControlName="date"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker></mat-datepicker> </mat-form-field> If I set the input value to a date everything works fine. this.form.controls['date'].setValue(new Date()); But I also want to manully set the input value to a string like this this.form.controls['date'].setValue('permanent'); But MatDatepicker does not allow me to do that and shows nothing (it probably expects a date format) even though my form accepts the string value 'permanent'. form: input: What I was expecting:
[ "Result\n\nBy default, the mat-datepicker is using NativeDateAdapter as the default DateAdapter.\nYou can create a custom date adapter class by extending from DateAdapter.\nFor example, I created custom-date-adapter.ts and extend DateAdapter with type param <Date | string> which allow support of string.\nexport class CustomDateAdapter extends DateAdapter<Date | string> {\n\nInject and use the default NativeDateAdapter when overriding DateAdapter abstract methods\n adapter: NativeDateAdapter;\n ...\n constructor(nativeDateAdapter: NativeDateAdapter) {\n ...\n this.adapter = nativeDateAdapter;\n\nFor example, for parse and isDateInstance override, check for permanent keyword, if true, then return. Else, call the nativeDateAdapter default method.\nNativeDateAdapter@isDateInstance is called when setValue('permanent')\nand\nNativeDateAdapter@parse is called when type inpermanent.\n parse(value: any, parseFormat: any): string | Date | null {\n if (value === 'permanent') {\n return 'permanent';\n }\n return this.adapter.parse(value, parseFormat);\n }\n isDateInstance(obj: any): boolean {\n if (obj === 'permanent') {\n return true;\n }\n return this.adapter.isDateInstance(obj);\n }\n\nOther small details like the private _today: Date = new Date();, this variable is used in other override methods, to pass into nativeDateAdapter method when the user enters any string, so that the date picker can expand and point to today date.\nFor example, if return 0 in getYear method, the picklist will point to 0 years when the user enters string input and expand it.\n\nFull code\napp.component.html\n<form [formGroup]=\"form\">\n <mat-form-field>\n <mat-label>Choose a date</mat-label>\n <input matInput [matDatepicker]=\"picker\" formControlName=\"date\">\n <mat-datepicker-toggle matSuffix [for]=\"picker\"></mat-datepicker-toggle>\n <mat-datepicker #picker></mat-datepicker>\n</mat-form-field>\n\n <hr>\n\n date.value = {{ form.controls['date'].value }}\n\n <br/>\n\n date.valid = {{ form.controls['date'].valid }}\n</form>\n\n\napp.component.ts\nimport { Component } from '@angular/core';\nimport { FormControl, FormGroup } from '@angular/forms';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.scss']\n})\nexport class AppComponent {\n title = 'ng-date-picker';\n form = new FormGroup({\n date: new FormControl('permanent')\n });\n}\n\napp.module.ts\nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\n\nimport { AppComponent } from './app.component';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { FormsModule, ReactiveFormsModule } from '@angular/forms';\nimport { MatFormFieldModule } from '@angular/material/form-field';\nimport { MatDatepickerModule } from '@angular/material/datepicker';\nimport {\n DateAdapter,\n MatNativeDateModule,\n MAT_DATE_FORMATS,\n MAT_NATIVE_DATE_FORMATS,\n NativeDateAdapter,\n} from '@angular/material/core';\nimport { MatInputModule } from '@angular/material/input';\nimport { CustomDateAdapter } from './custom-date-adapter';\n\nimport { MatButtonModule } from '@angular/material/button';\n\n@NgModule({\n declarations: [AppComponent],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n ReactiveFormsModule,\n MatFormFieldModule,\n MatDatepickerModule,\n MatNativeDateModule,\n FormsModule,\n MatInputModule,\n MatButtonModule,\n ],\n providers: [\n NativeDateAdapter,\n { provide: DateAdapter, useClass: CustomDateAdapter },\n ],\n bootstrap: [AppComponent],\n})\nexport class AppModule {}\n\ncustom-date-adapter.ts\nimport { Injectable } from '@angular/core';\nimport {\n DateAdapter, NativeDateAdapter\n} from '@angular/material/core';\n\n@Injectable()\nexport class CustomDateAdapter extends DateAdapter<Date | string> {\n adapter: NativeDateAdapter;\n private _today: Date = new Date();\n\n constructor(nativeDateAdapter: NativeDateAdapter) {\n super();\n this.adapter = nativeDateAdapter;\n }\n\n parse(value: any, parseFormat: any): string | Date | null {\n if (value === 'permanent') {\n return 'permanent';\n }\n return this.adapter.parse(value, parseFormat);\n }\n isDateInstance(obj: any): boolean {\n if (obj === 'permanent') {\n return true;\n }\n return this.adapter.isDateInstance(obj);\n }\n isValid(date: string | Date): boolean {\n return date instanceof Date\n ? this.adapter.isValid(date)\n : date === 'permanent';\n }\n getYear(date: string | Date): number {\n return date instanceof Date\n ? this.adapter.getYear(date)\n : this.adapter.getYear(this._today);\n }\n getMonth(date: string | Date): number {\n return date instanceof Date\n ? this.adapter.getMonth(date)\n : this.adapter.getMonth(this._today);\n }\n getDate(date: string | Date): number {\n return date instanceof Date\n ? this.adapter.getDate(date)\n : this.adapter.getDate(this._today);\n }\n getDayOfWeek(date: string | Date): number {\n return date instanceof Date\n ? this.adapter.getDayOfWeek(date)\n : this.adapter.getDayOfWeek(this._today);\n }\n getMonthNames(style: 'long' | 'short' | 'narrow'): string[] {\n return this.adapter.getMonthNames(style);\n }\n getDateNames(): string[] {\n return this.adapter.getDateNames();\n }\n getDayOfWeekNames(style: 'long' | 'short' | 'narrow'): string[] {\n return this.adapter.getDayOfWeekNames(style);\n }\n getYearName(date: string | Date): string {\n return date instanceof Date\n ? this.adapter.getYearName(date)\n : this.adapter.getYearName(this._today);\n }\n getFirstDayOfWeek(): number {\n return this.adapter.getFirstDayOfWeek();\n }\n getNumDaysInMonth(date: string | Date): number {\n return date instanceof Date\n ? this.adapter.getNumDaysInMonth(date)\n : this.adapter.getNumDaysInMonth(this._today);\n }\n clone(date: string | Date): string | Date {\n return date instanceof Date\n ? this.adapter.clone(date)\n : this.adapter.clone(this._today);\n }\n createDate(year: number, month: number, date: number): string | Date {\n return this.adapter.createDate(year, month, date);\n }\n today(): string | Date {\n return this.adapter.today();\n }\n format(date: string | Date, displayFormat: any): string {\n return date instanceof Date\n ? this.adapter.format(date, displayFormat)\n : (date as string);\n }\n addCalendarYears(date: string | Date, years: number): string | Date {\n return date instanceof Date\n ? this.adapter.addCalendarYears(date, years)\n : '';\n }\n addCalendarMonths(date: string | Date, months: number): string | Date {\n return date instanceof Date\n ? this.adapter.addCalendarMonths(date, months)\n : '';\n }\n addCalendarDays(date: string | Date, days: number): string | Date {\n return date instanceof Date ? this.adapter.addCalendarDays(date, days) : '';\n }\n toIso8601(date: string | Date): string {\n return date instanceof Date ? this.adapter.toIso8601(date) : '';\n }\n invalid(): string | Date {\n return this.adapter.invalid();\n }\n}\n\npackage.json\n{\n \"name\": \"ng-date-picker\",\n \"version\": \"0.0.0\",\n \"scripts\": {\n \"ng\": \"ng\",\n \"start\": \"ng serve\",\n \"build\": \"ng build\",\n \"watch\": \"ng build --watch --configuration development\",\n \"test\": \"ng test\"\n },\n \"private\": true,\n \"dependencies\": {\n \"@angular/animations\": \"^15.0.0\",\n \"@angular/cdk\": \"^15.0.1\",\n \"@angular/common\": \"^15.0.0\",\n \"@angular/compiler\": \"^15.0.0\",\n \"@angular/core\": \"^15.0.0\",\n \"@angular/forms\": \"^15.0.0\",\n \"@angular/material\": \"^15.0.1\",\n \"@angular/platform-browser\": \"^15.0.0\",\n \"@angular/platform-browser-dynamic\": \"^15.0.0\",\n \"@angular/router\": \"^15.0.0\",\n \"rxjs\": \"~7.5.0\",\n \"tslib\": \"^2.3.0\",\n \"zone.js\": \"~0.12.0\"\n },\n \"devDependencies\": {\n \"@angular-devkit/build-angular\": \"^15.0.2\",\n \"@angular/cli\": \"~15.0.2\",\n \"@angular/compiler-cli\": \"^15.0.0\",\n \"@types/jasmine\": \"~4.3.0\",\n \"jasmine-core\": \"~4.5.0\",\n \"karma\": \"~6.4.0\",\n \"karma-chrome-launcher\": \"~3.1.0\",\n \"karma-coverage\": \"~2.2.0\",\n \"karma-jasmine\": \"~5.1.0\",\n \"karma-jasmine-html-reporter\": \"~2.0.0\",\n \"typescript\": \"~4.8.2\"\n }\n}\n\n" ]
[ 0 ]
[]
[]
[ "angular", "angular_material", "mat_datepicker" ]
stackoverflow_0074653420_angular_angular_material_mat_datepicker.txt
Q: Swagger-Codegen: How to stuff JSON blob in a String I'm using a swagger yaml file to define my API and generate Java code out of it. With this structure: SomeStructure: type: object properties: field1: type: string required: true field2: type: string required: true field3: type: string additionalProperties: {} Now, once API code generation is done, I would like the 3rd field to flatten any specified JSON structure into a Java String. For instance, for an input like this: { "field1":"value1", "field2":"value2", "field3":{ "subvalue1":"subvalue1", "subvalue2":"subvalue2" } } I want it to get mapped to a String containing: {"subvalue1":"subvalue1","subvalue2":"subvalue2"} I tried to use the freeform indicator '{}', but obviously, it's not working. Is it possible, and how do I do this? A: It looks like you want the field3 property to be of type string, but also to be able to contain JSON data. In this case, you can specify the format for the field3 property as json: SomeStructure: type: object properties: field1: type: string required: true field2: type: string required: true field3: type: string format: json This will tell the code generator that the field3 property should be of type string, but should be treated as a JSON object when the code is generated. This should result in the JSON data being stored in a Java String object. A: The freeform indicator ('{}') that you mentioned is used to indicate that additional properties are allowed in the JSON object for the field3 property. It does not affect the way that the JSON object is mapped to a Java object. To map the JSON object in field3 to a Java String containing the JSON object, you can define a custom Java class that has a String field to represent the JSON object, and a corresponding setter and getter methods. Then, in the Swagger yaml file, you can specify the custom Java class as the type for the field3 property, instead of using the default string type. For example, you can define a Java class named Field3 like this: public class Field3 { private String jsonString; public Field3() {} public Field3(String jsonString) { this.jsonString = jsonString; } public String getJsonString() { return jsonString; } public void setJsonString(String jsonString) { this.jsonString = jsonString; } } Then, in the Swagger yaml file, you can use the Field3 class as the type for the field3 property like this: SomeStructure: type: object properties: field1: type: string required: true field2: type: string required: true field3: type: Field3 additionalProperties: {} After code generation, the generated Java code for the SomeStructure class will have a field3 property of type Field3, which you can use to set and get the JSON object as a String. For example, you can set the JSON object in field3 like this: SomeStructure someStructure = new SomeStructure(); // Set the value for field1 and field2 someStructure.setField1("value1"); someStructure.setField2("value2"); // Create a Field3 object with the JSON object as a String Field3 field3 = new Field3("{\"subvalue1\":\"subvalue1\",\"subvalue2\":\"subvalue2\"}"); // Set the value for field3 someStructure.setField3(field3); And you can get the JSON object in field3 as a String like this: SomeStructure someStructure = ...; // Get the value of field3 Field3 field3 = someStructure.getField3(); // Get the JSON object as a String String jsonString = field3.getJsonString(); I hope this helps. Let me know if you have any other questions. My donation link if you appreciate my work :) BTC:178vgzZkLNV9NPxZiQqabq5crzBSgQWmvs,ETH:0x99753577c4ae89e7043addf7abbbdf7258a74697
Swagger-Codegen: How to stuff JSON blob in a String
I'm using a swagger yaml file to define my API and generate Java code out of it. With this structure: SomeStructure: type: object properties: field1: type: string required: true field2: type: string required: true field3: type: string additionalProperties: {} Now, once API code generation is done, I would like the 3rd field to flatten any specified JSON structure into a Java String. For instance, for an input like this: { "field1":"value1", "field2":"value2", "field3":{ "subvalue1":"subvalue1", "subvalue2":"subvalue2" } } I want it to get mapped to a String containing: {"subvalue1":"subvalue1","subvalue2":"subvalue2"} I tried to use the freeform indicator '{}', but obviously, it's not working. Is it possible, and how do I do this?
[ "It looks like you want the field3 property to be of type string, but also to be able to contain JSON data. In this case, you can specify the format for the field3 property as json:\nSomeStructure:\n type: object\n properties:\n field1: \n type: string\n required: true\n field2:\n type: string\n required: true\n field3:\n type: string\n format: json\n\nThis will tell the code generator that the field3 property should be of type string, but should be treated as a JSON object when the code is generated. This should result in the JSON data being stored in a Java String object.\n", "The freeform indicator ('{}') that you mentioned is used to indicate that additional properties are allowed in the JSON object for the field3 property. It does not affect the way that the JSON object is mapped to a Java object.\nTo map the JSON object in field3 to a Java String containing the JSON object, you can define a custom Java class that has a String field to represent the JSON object, and a corresponding setter and getter methods. Then, in the Swagger yaml file, you can specify the custom Java class as the type for the field3 property, instead of using the default string type.\nFor example, you can define a Java class named Field3 like this:\npublic class Field3 {\n private String jsonString;\n\n public Field3() {}\n\n public Field3(String jsonString) {\n this.jsonString = jsonString;\n }\n\n public String getJsonString() {\n return jsonString;\n }\n\n public void setJsonString(String jsonString) {\n this.jsonString = jsonString;\n }\n}\n\nThen, in the Swagger yaml file, you can use the Field3 class as the type for the field3 property like this:\nSomeStructure:\n type: object\n properties:\n field1: \n type: string\n required: true\n field2:\n type: string\n required: true\n field3:\n type: Field3\n additionalProperties: {}\n\nAfter code generation, the generated Java code for the SomeStructure class will have a field3 property of type Field3, which you can use to set and get the JSON object as a String.\nFor example, you can set the JSON object in field3 like this:\nSomeStructure someStructure = new SomeStructure();\n\n// Set the value for field1 and field2\nsomeStructure.setField1(\"value1\");\nsomeStructure.setField2(\"value2\");\n\n// Create a Field3 object with the JSON object as a String\nField3 field3 = new Field3(\"{\\\"subvalue1\\\":\\\"subvalue1\\\",\\\"subvalue2\\\":\\\"subvalue2\\\"}\");\n\n// Set the value for field3\nsomeStructure.setField3(field3);\n\nAnd you can get the JSON object in field3 as a String like this:\nSomeStructure someStructure = ...;\n\n// Get the value of field3\nField3 field3 = someStructure.getField3();\n\n// Get the JSON object as a String\nString jsonString = field3.getJsonString();\n\nI hope this helps. Let me know if you have any other questions.\nMy donation\nlink if you appreciate my work :) BTC:178vgzZkLNV9NPxZiQqabq5crzBSgQWmvs,ETH:0x99753577c4ae89e7043addf7abbbdf7258a74697\n" ]
[ 0, 0 ]
[]
[]
[ "java", "json", "swagger", "swagger_codegen" ]
stackoverflow_0049366012_java_json_swagger_swagger_codegen.txt
Q: Why is OutlinePass in Three.js causing everything to appear pixelated? For some reason, the way I've used OutlinePass in my code causes everything (except the added outline) to be pixelated, but the EffectComposer works fine with just the RenderPass, and I can't figure out why. According to some similar questions and answers I've seen, adding an FXAAShader might solve this, but I tried this (code commented below) and it did not seem to make any difference. What is causing this behaviour? <script type="importmap"> { "imports": { "three": "https://threejs.org/build/three.module.js" } } </script> <!-- Had to put JS in the HTML block to import THREE Also, issue is more clear with an image material, but I had to use a solid color for this example --> <script type="module"> import * as THREE from "three"; import {EffectComposer} from "https://threejs.org/examples/jsm/postprocessing/EffectComposer.js"; import {OutlinePass} from "https://threejs.org/examples/jsm/postprocessing/OutlinePass.js"; import {RenderPass} from "https://threejs.org/examples/jsm/postprocessing/RenderPass.js"; // import {ShaderPass} from "https://threejs.org/examples/jsm/postprocessing/ShaderPass.js"; // import {FXAAShader} from "https://threejs.org/examples/jsm/shaders/FXAAShader.js"; const windowSize = [256,256], mesh = new THREE.Mesh(new THREE.BoxGeometry(16,16,16), new THREE.MeshBasicMaterial({color: 0xd41313})), scene = new THREE.Scene(), camera = new THREE.OrthographicCamera(-16,16,16,-16), renderer = new THREE.WebGLRenderer(), textureLoader = new THREE.TextureLoader(), effectComposer = new EffectComposer(renderer), outline = new OutlinePass(new THREE.Vector2(...windowSize), scene, camera); // const effectFXAA = new ShaderPass(FXAAShader); // --- Swapping these two passes demonstrates it's the outline causing issues effectComposer.addPass(new RenderPass(scene, camera)); effectComposer.addPass(outline); // --- FXAAShader was an attempt to fix it, since some research showed it could be anti-aliasing issues, but this did not seem to make a difference // effectFXAA.uniforms['resolution'].value.set(1/windowSize[0],1/windowSize[1]); // effectComposer.addPass(effectFXAA); renderer.setSize(...windowSize); camera.position.set(32,32,32); camera.lookAt(0,0,0); outline.selectedObjects = [mesh]; scene.add(mesh); document.body.appendChild(renderer.domElement); effectComposer.render(); </script> A: I had the same issue, then I had to re assign the pixel ratio and the size on the resize window event, and that fixed the problem. (Is even not necessary the FXAAShader to solve the problem) ... window.addEventListener("resize", this.resize.bind(this)); resize(){ this.composer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); this.composer.setSize(this.width, this.height) }
Why is OutlinePass in Three.js causing everything to appear pixelated?
For some reason, the way I've used OutlinePass in my code causes everything (except the added outline) to be pixelated, but the EffectComposer works fine with just the RenderPass, and I can't figure out why. According to some similar questions and answers I've seen, adding an FXAAShader might solve this, but I tried this (code commented below) and it did not seem to make any difference. What is causing this behaviour? <script type="importmap"> { "imports": { "three": "https://threejs.org/build/three.module.js" } } </script> <!-- Had to put JS in the HTML block to import THREE Also, issue is more clear with an image material, but I had to use a solid color for this example --> <script type="module"> import * as THREE from "three"; import {EffectComposer} from "https://threejs.org/examples/jsm/postprocessing/EffectComposer.js"; import {OutlinePass} from "https://threejs.org/examples/jsm/postprocessing/OutlinePass.js"; import {RenderPass} from "https://threejs.org/examples/jsm/postprocessing/RenderPass.js"; // import {ShaderPass} from "https://threejs.org/examples/jsm/postprocessing/ShaderPass.js"; // import {FXAAShader} from "https://threejs.org/examples/jsm/shaders/FXAAShader.js"; const windowSize = [256,256], mesh = new THREE.Mesh(new THREE.BoxGeometry(16,16,16), new THREE.MeshBasicMaterial({color: 0xd41313})), scene = new THREE.Scene(), camera = new THREE.OrthographicCamera(-16,16,16,-16), renderer = new THREE.WebGLRenderer(), textureLoader = new THREE.TextureLoader(), effectComposer = new EffectComposer(renderer), outline = new OutlinePass(new THREE.Vector2(...windowSize), scene, camera); // const effectFXAA = new ShaderPass(FXAAShader); // --- Swapping these two passes demonstrates it's the outline causing issues effectComposer.addPass(new RenderPass(scene, camera)); effectComposer.addPass(outline); // --- FXAAShader was an attempt to fix it, since some research showed it could be anti-aliasing issues, but this did not seem to make a difference // effectFXAA.uniforms['resolution'].value.set(1/windowSize[0],1/windowSize[1]); // effectComposer.addPass(effectFXAA); renderer.setSize(...windowSize); camera.position.set(32,32,32); camera.lookAt(0,0,0); outline.selectedObjects = [mesh]; scene.add(mesh); document.body.appendChild(renderer.domElement); effectComposer.render(); </script>
[ "I had the same issue, then I had to re assign the pixel ratio and the size on the resize window event, and that fixed the problem. (Is even not necessary the FXAAShader to solve the problem)\n...\n window.addEventListener(\"resize\", this.resize.bind(this));\n\nresize(){\n this.composer.setPixelRatio(Math.min(window.devicePixelRatio, 2));\n this.composer.setSize(this.width, this.height)\n}\n\n\n" ]
[ 0 ]
[]
[]
[ "javascript", "three.js" ]
stackoverflow_0071990398_javascript_three.js.txt
Q: connecting twitter API to R with rtweet package I donwloaded the rtweet package in r as there are more functions than tweetR, but the output keeps giving me an error saying that "auth" is not found. I am not sure how to input the api key and token because of the new update. Anyone know the code? I entered the tokens and keys the twitter api gave me but can't figure out how to get it to sync/run. library(rtweet) install.packages("ROAuth") library(ROAuth) ## authenticate via access token app = "statskenyon" consumer_key = "my key" consumer_secret = "consumer secret" acess_token = "access token" access_secret = "access secret" auth <- rtweet_app("bearer token") A: In the previous version of rtweet, after You have to save your tokens to an R object first. your_token_name <- create_token(app = "statskenyon", consumer_key = "my key", consumer_secret = "consumer secret", access_token = "access token", access_secret = "access secret", set_renv = TRUE ) Then use it in a post_status(). post_tweet( status = "my first rtweet #rstats", token = your_token_name ) In newer version, instead of using auth <- rtweet_app("bearer token") I suggest You to use rtweet_bot() function, since from your code you only have 4 keys. your_new_token_name <- rtweet::rtweet_bot( api_key = "my key", api_secret = "consumer secret", access_token = "access token", access_secret = "access secret" ) Then use it to post a status message rtweet::post_tweet( status = "your_status_message", token = your_new_token_name )
connecting twitter API to R with rtweet package
I donwloaded the rtweet package in r as there are more functions than tweetR, but the output keeps giving me an error saying that "auth" is not found. I am not sure how to input the api key and token because of the new update. Anyone know the code? I entered the tokens and keys the twitter api gave me but can't figure out how to get it to sync/run. library(rtweet) install.packages("ROAuth") library(ROAuth) ## authenticate via access token app = "statskenyon" consumer_key = "my key" consumer_secret = "consumer secret" acess_token = "access token" access_secret = "access secret" auth <- rtweet_app("bearer token")
[ "In the previous version of rtweet, after You have to save your tokens to an R object first.\n your_token_name <- create_token(app = \"statskenyon\",\n consumer_key = \"my key\",\n consumer_secret = \"consumer secret\",\n access_token = \"access token\",\n access_secret = \"access secret\",\n set_renv = TRUE\n )\n\nThen use it in a post_status().\npost_tweet(\n status = \"my first rtweet #rstats\",\n token = your_token_name\n)\n\nIn newer version, instead of using\nauth <- rtweet_app(\"bearer token\")\n\nI suggest You to use rtweet_bot() function, since from your code you only have 4 keys.\nyour_new_token_name <- rtweet::rtweet_bot(\n api_key = \"my key\",\n api_secret = \"consumer secret\",\n access_token = \"access token\",\n access_secret = \"access secret\"\n)\n\nThen use it to post a status message\nrtweet::post_tweet(\n status = \"your_status_message\",\n token = your_new_token_name\n)\n\n" ]
[ 0 ]
[]
[]
[ "api_key", "r", "rtweet", "twitter_oauth" ]
stackoverflow_0074648262_api_key_r_rtweet_twitter_oauth.txt
Q: Why won't the second pushed tile show? I placed the rectangles over the images. I then bound a click to a call that flipped tiles over by lowering the rectangle below the image. It works for the first call to the function, but when I click another tile, that one won't flip over. The program still registers the second flip because it'll flip everything back over if it's an incorrect match; the only problem is that it won't have the rectangle go under the image. # ======================================= import statements import tkinter as tk import time import random import PIL import PIL.Image as Image import PIL.ImageTk as ImageTk # ======================================= class def class MemoryGame: def __init__(self): #initialize window self.window = tk.Tk() self.window.title("Sea Life Memory Game") self.window.minsize(590, 600) self.window.maxsize(590, 600) #set main canvas as background self.canvas = tk.Canvas(self.window, bg="lightblue", bd=0, highlightthickness=0, width=590, height=600) self.canvas.grid(row=0, column=0) self.canvas.bind("<Button-1>", self.chooseTile) #establish coordinates for tiles and shuffle image placement coordinates = [(5,30,105,130), (5,160,105,260), (5,290,105,390), (5,420,105,520), (125,30,225,130), (125,160,225,260), (125,290,225,390), (125,420,225,520), (245,30,345,130), (245,160,345,260), (245,290,345,390), (245,420,345,520), (365,30,465,130), (365,160,465,260), (365,290,465,390), (365,420,465,520), (485,30,585,130), (485,160,585,260), (485,290,585,390), (485,420,585,520)] imageChoices = ['cropped images/001-turtle.png','cropped images/007-blowfish.png','cropped images/010-jellyfish.png','cropped images/011-starfish.png','cropped images/018-lobster.png','cropped images/028-fish.png','cropped images/033-walrus.png','cropped images/042-goldfish.png','cropped images/045-seal.png','cropped images/046-penguin.png'] random.shuffle(coordinates) #write title to top of canvas self.canvas.create_text(295, 15, text="Sea Life Memory Game!", anchor="center", fill="white", font="Times 24 bold") self.selectedTile = None #initialize counts coordinateCount = 0 imageCount = 0 self.imageCollection = {} #for loop to attach images to each rectangle on the canvas for i in range(len(imageChoices)): otherDict = {} x1, y1, x2, y2 = coordinates[coordinateCount] # if imageCount <= 9: self.image = ImageTk.PhotoImage(Image.open(imageChoices[imageCount])) self.image.img = self.image self.id = self.canvas.create_image(x1, y1, anchor="nw", image=self.image.img) self.canvas.create_rectangle(x1, y1, x2, y2, fill="white", outline="white") coordinateCount += 1 x1, y1, x2, y2 = coordinates[coordinateCount] self.id = self.canvas.create_image(x1, y1, anchor="nw", image=self.image.img) self.canvas.create_rectangle(x1, y1, x2, y2, fill="white", outline="white") coordinateCount += 1 imageCount += 1 otherDict["faceDown"] = True self.imageCollection[self.id] = otherDict #create instructional text self.canvas.create_text(295, 550, text="Find all the pairs as fast as possible.", fill="white", font="Times 18", anchor="center") self.canvas.create_text(295, 570, text="Click on a card to turn it over and find the same matching card.", fill="white", font="Times 18", anchor="center") def run(self): self.window.mainloop() global list list = [] def chooseTile(self, event): # global list x = event.x y = event.y item = self.canvas.find_overlapping(x-5,y-5,x+5,y+5) list.append(item) print(len(list)) if len(list) < 2: self.canvas.tag_lower(list[0][1]) elif len(list) == 2: self.canvas.tag_lower(list[1][1]) if self.canvas.itemcget(list[0][0], "image") == self.canvas.itemcget(list[1][0], "image"): list.clear() else: time.sleep(1.0) self.canvas.lower(list[0][0], list[0][1]) self.canvas.lower(list[1][0], list[1][1]) list.clear() # ======================================= script calls game = MemoryGame() game.run() A: It is because the update will be performed after chooseTile() returns to tkinter mainloop(). But the images are already reset to lower layer when the function returns, so you cannot see the second selected image. The simple fix is calling self.canvas.update_idletasks() to force the update to show the second selected image before time.sleep(1.0): def chooseTile(self, event): # global list x = event.x y = event.y item = self.canvas.find_overlapping(x-5,y-5,x+5,y+5) list.append(item) print(len(list)) if len(list) < 2: self.canvas.tag_lower(list[0][1]) elif len(list) == 2: self.canvas.tag_lower(list[1][1]) if self.canvas.itemcget(list[0][0], "image") == self.canvas.itemcget(list[1][0], "image"): list.clear() else: # force the canvas to show the second selected image self.canvas.update_idletasks() time.sleep(1.0) self.canvas.lower(list[0][0], list[0][1]) self.canvas.lower(list[1][0], list[1][1]) list.clear() A: I finally got it to work!! # ======================================= import statements import tkinter as tk import random import PIL.Image as Image import PIL.ImageTk as ImageTk # ======================================= class def class MemoryGame: def __init__(self): #initialize window self.window = tk.Tk() self.window.title("Sea Life Memory Game") self.window.minsize(590, 600) self.window.maxsize(590, 600) #set main canvas as background self.canvas = tk.Canvas(self.window, bg="lightblue", bd=0, highlightthickness=0, width=590, height=600) self.canvas.grid(row=0, column=0) self.canvas.bind("<Button-1>", self.chooseTile) #establish coordinates for tiles and shuffle image placement coordinates = [(5,30,105,130), (5,160,105,260), (5,290,105,390), (5,420,105,520), (125,30,225,130), (125,160,225,260), (125,290,225,390), (125,420,225,520), (245,30,345,130), (245,160,345,260), (245,290,345,390), (245,420,345,520), (365,30,465,130), (365,160,465,260), (365,290,465,390), (365,420,465,520), (485,30,585,130), (485,160,585,260), (485,290,585,390), (485,420,585,520)] imageChoices = ['cropped images/001-turtle.png','cropped images/007-blowfish.png','cropped images/010-jellyfish.png','cropped images/011-starfish.png','cropped images/018-lobster.png','cropped images/028-fish.png','cropped images/033-walrus.png','cropped images/042-goldfish.png','cropped images/045-seal.png','cropped images/046-penguin.png'] random.shuffle(coordinates) #write title to top of canvas self.canvas.create_text(295, 15, text="Sea Life Memory Game!", anchor="center", fill="white", font="Times 24 bold") #initialize counts coordinateCount = 0 imageCount = 0 self.imageCollection = [] #for loop to attach images to each rectangle on the canvas for i in range(len(imageChoices)): x1, y1, x2, y2 = coordinates[coordinateCount] self.image = ImageTk.PhotoImage(Image.open(imageChoices[imageCount])) self.image.img = self.image self.id = self.canvas.create_image(x1, y1, anchor="nw", image=self.image.img) self.imageCollection.append(self.id) self.canvas.create_rectangle(x1, y1, x2, y2, fill="white", outline="white") coordinateCount += 1 x1, y1, x2, y2 = coordinates[coordinateCount] self.id = self.canvas.create_image(x1, y1, anchor="nw", image=self.image.img) self.canvas.create_rectangle(x1, y1, x2, y2, fill="white", outline="white") coordinateCount += 1 imageCount += 1 self.imageCollection.append(self.id) #create instructional text self.canvas.create_text(295, 550, text="Find all the pairs as fast as possible.", fill="white", font="Times 18", anchor="center") self.canvas.create_text(295, 570, text="Click on a card to turn it over and find the same matching card.", fill="white", font="Times 18", anchor="center") def run(self): self.window.mainloop() global lst lst = [] global matches matches = 0 def chooseTile(self, event): global lst global matches x = event.x y = event.y item = self.canvas.find_overlapping(x-1,y-1,x+1,y+1) lst.append(item) if len(lst) < 2: self.canvas.tag_lower(lst[0][1], lst[0][0]) elif len(lst) == 2: self.canvas.tag_lower(lst[1][1],lst[1][0]) if self.canvas.itemcget(lst[0][0], "image") == self.canvas.itemcget(lst[1][0], "image"): matches += 2 lst.clear() else: self.window.update_idletasks() self.window.after(1500) self.canvas.lower(lst[0][0], lst[0][1]) self.canvas.lower(lst[1][0], lst[1][1]) lst.clear() if matches == 20: self.window.update_idletasks() self.window.after(1000) self.window.destroy() # ======================================= script calls game = MemoryGame() game.window.mainloop()
Why won't the second pushed tile show?
I placed the rectangles over the images. I then bound a click to a call that flipped tiles over by lowering the rectangle below the image. It works for the first call to the function, but when I click another tile, that one won't flip over. The program still registers the second flip because it'll flip everything back over if it's an incorrect match; the only problem is that it won't have the rectangle go under the image. # ======================================= import statements import tkinter as tk import time import random import PIL import PIL.Image as Image import PIL.ImageTk as ImageTk # ======================================= class def class MemoryGame: def __init__(self): #initialize window self.window = tk.Tk() self.window.title("Sea Life Memory Game") self.window.minsize(590, 600) self.window.maxsize(590, 600) #set main canvas as background self.canvas = tk.Canvas(self.window, bg="lightblue", bd=0, highlightthickness=0, width=590, height=600) self.canvas.grid(row=0, column=0) self.canvas.bind("<Button-1>", self.chooseTile) #establish coordinates for tiles and shuffle image placement coordinates = [(5,30,105,130), (5,160,105,260), (5,290,105,390), (5,420,105,520), (125,30,225,130), (125,160,225,260), (125,290,225,390), (125,420,225,520), (245,30,345,130), (245,160,345,260), (245,290,345,390), (245,420,345,520), (365,30,465,130), (365,160,465,260), (365,290,465,390), (365,420,465,520), (485,30,585,130), (485,160,585,260), (485,290,585,390), (485,420,585,520)] imageChoices = ['cropped images/001-turtle.png','cropped images/007-blowfish.png','cropped images/010-jellyfish.png','cropped images/011-starfish.png','cropped images/018-lobster.png','cropped images/028-fish.png','cropped images/033-walrus.png','cropped images/042-goldfish.png','cropped images/045-seal.png','cropped images/046-penguin.png'] random.shuffle(coordinates) #write title to top of canvas self.canvas.create_text(295, 15, text="Sea Life Memory Game!", anchor="center", fill="white", font="Times 24 bold") self.selectedTile = None #initialize counts coordinateCount = 0 imageCount = 0 self.imageCollection = {} #for loop to attach images to each rectangle on the canvas for i in range(len(imageChoices)): otherDict = {} x1, y1, x2, y2 = coordinates[coordinateCount] # if imageCount <= 9: self.image = ImageTk.PhotoImage(Image.open(imageChoices[imageCount])) self.image.img = self.image self.id = self.canvas.create_image(x1, y1, anchor="nw", image=self.image.img) self.canvas.create_rectangle(x1, y1, x2, y2, fill="white", outline="white") coordinateCount += 1 x1, y1, x2, y2 = coordinates[coordinateCount] self.id = self.canvas.create_image(x1, y1, anchor="nw", image=self.image.img) self.canvas.create_rectangle(x1, y1, x2, y2, fill="white", outline="white") coordinateCount += 1 imageCount += 1 otherDict["faceDown"] = True self.imageCollection[self.id] = otherDict #create instructional text self.canvas.create_text(295, 550, text="Find all the pairs as fast as possible.", fill="white", font="Times 18", anchor="center") self.canvas.create_text(295, 570, text="Click on a card to turn it over and find the same matching card.", fill="white", font="Times 18", anchor="center") def run(self): self.window.mainloop() global list list = [] def chooseTile(self, event): # global list x = event.x y = event.y item = self.canvas.find_overlapping(x-5,y-5,x+5,y+5) list.append(item) print(len(list)) if len(list) < 2: self.canvas.tag_lower(list[0][1]) elif len(list) == 2: self.canvas.tag_lower(list[1][1]) if self.canvas.itemcget(list[0][0], "image") == self.canvas.itemcget(list[1][0], "image"): list.clear() else: time.sleep(1.0) self.canvas.lower(list[0][0], list[0][1]) self.canvas.lower(list[1][0], list[1][1]) list.clear() # ======================================= script calls game = MemoryGame() game.run()
[ "It is because the update will be performed after chooseTile() returns to tkinter mainloop(). But the images are already reset to lower layer when the function returns, so you cannot see the second selected image.\nThe simple fix is calling self.canvas.update_idletasks() to force the update to show the second selected image before time.sleep(1.0):\n def chooseTile(self, event):\n # global list\n x = event.x\n y = event.y\n item = self.canvas.find_overlapping(x-5,y-5,x+5,y+5)\n list.append(item)\n print(len(list))\n if len(list) < 2:\n self.canvas.tag_lower(list[0][1])\n elif len(list) == 2:\n self.canvas.tag_lower(list[1][1])\n if self.canvas.itemcget(list[0][0], \"image\") == self.canvas.itemcget(list[1][0], \"image\"):\n list.clear()\n else:\n # force the canvas to show the second selected image\n self.canvas.update_idletasks()\n time.sleep(1.0)\n self.canvas.lower(list[0][0], list[0][1])\n self.canvas.lower(list[1][0], list[1][1])\n list.clear()\n\n", "I finally got it to work!!\n# ======================================= import statements \nimport tkinter as tk\nimport random\nimport PIL.Image as Image\nimport PIL.ImageTk as ImageTk\n# ======================================= class def\n\nclass MemoryGame:\n\n def __init__(self):\n #initialize window\n self.window = tk.Tk()\n self.window.title(\"Sea Life Memory Game\")\n self.window.minsize(590, 600)\n self.window.maxsize(590, 600)\n\n #set main canvas as background\n self.canvas = tk.Canvas(self.window, bg=\"lightblue\",\n bd=0, highlightthickness=0,\n width=590, height=600)\n self.canvas.grid(row=0, column=0)\n self.canvas.bind(\"<Button-1>\", self.chooseTile)\n\n #establish coordinates for tiles and shuffle image placement\n coordinates = [(5,30,105,130), (5,160,105,260), (5,290,105,390), (5,420,105,520), (125,30,225,130), (125,160,225,260), (125,290,225,390), (125,420,225,520), (245,30,345,130), (245,160,345,260), (245,290,345,390), (245,420,345,520), (365,30,465,130), (365,160,465,260), (365,290,465,390), (365,420,465,520), (485,30,585,130), (485,160,585,260), (485,290,585,390), (485,420,585,520)]\n imageChoices = ['cropped images/001-turtle.png','cropped images/007-blowfish.png','cropped images/010-jellyfish.png','cropped images/011-starfish.png','cropped images/018-lobster.png','cropped images/028-fish.png','cropped images/033-walrus.png','cropped images/042-goldfish.png','cropped images/045-seal.png','cropped images/046-penguin.png']\n random.shuffle(coordinates)\n\n #write title to top of canvas\n self.canvas.create_text(295, 15, text=\"Sea Life Memory Game!\",\n anchor=\"center\", fill=\"white\",\n font=\"Times 24 bold\")\n\n\n #initialize counts\n coordinateCount = 0\n imageCount = 0\n self.imageCollection = []\n #for loop to attach images to each rectangle on the canvas\n for i in range(len(imageChoices)):\n x1, y1, x2, y2 = coordinates[coordinateCount]\n self.image = ImageTk.PhotoImage(Image.open(imageChoices[imageCount]))\n self.image.img = self.image\n self.id = self.canvas.create_image(x1, y1, anchor=\"nw\",\n image=self.image.img)\n self.imageCollection.append(self.id)\n self.canvas.create_rectangle(x1, y1, x2, y2, fill=\"white\", outline=\"white\")\n coordinateCount += 1\n x1, y1, x2, y2 = coordinates[coordinateCount]\n self.id = self.canvas.create_image(x1, y1, anchor=\"nw\",\n image=self.image.img)\n self.canvas.create_rectangle(x1, y1, x2, y2, fill=\"white\", outline=\"white\")\n coordinateCount += 1\n imageCount += 1\n\n self.imageCollection.append(self.id)\n\n #create instructional text\n self.canvas.create_text(295, 550, text=\"Find all the pairs as fast as possible.\",\n fill=\"white\", font=\"Times 18\", anchor=\"center\")\n self.canvas.create_text(295, 570, text=\"Click on a card to turn it over and find the same matching card.\",\n fill=\"white\", font=\"Times 18\", anchor=\"center\")\n\n\n def run(self):\n self.window.mainloop()\n\n global lst\n lst = []\n global matches\n matches = 0\n\n def chooseTile(self, event):\n global lst\n global matches\n x = event.x\n y = event.y\n item = self.canvas.find_overlapping(x-1,y-1,x+1,y+1)\n lst.append(item)\n if len(lst) < 2:\n self.canvas.tag_lower(lst[0][1], lst[0][0])\n elif len(lst) == 2:\n self.canvas.tag_lower(lst[1][1],lst[1][0])\n if self.canvas.itemcget(lst[0][0], \"image\") == self.canvas.itemcget(lst[1][0], \"image\"):\n matches += 2\n lst.clear()\n else:\n self.window.update_idletasks()\n self.window.after(1500)\n self.canvas.lower(lst[0][0], lst[0][1])\n self.canvas.lower(lst[1][0], lst[1][1])\n lst.clear()\n if matches == 20:\n self.window.update_idletasks()\n self.window.after(1000)\n self.window.destroy()\n\n# ======================================= script calls\n\ngame = MemoryGame()\ngame.window.mainloop()\n\n" ]
[ 0, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074650846_python_tkinter.txt
Q: Could not find method include() for arguments [:app] on root project Android Studio I am trying to import an android project to Android studio,after importing and then clicking on the green run button : FAILURE: Build failed with an exception. Where: Build file '/home/myusername/prjcts/nomadx/settings.gradle' line: 1 What went wrong: A problem occurred evaluating root project 'nomadx'. Could not find method include() for arguments [:app] on root project 'nomadx'. The content of the file settings.gradle include ':app' A: I solved the problem ; for those who have the same issue : You should build the gradle with the Terminal/console not with Android studio : ./gradlew assembleRelease A: After getting this error on first setup: capacitor.settings.gradle' as it does not exist ..I used two commands from that page: npx cap sync android and npm install --save @capacitor/core @capacitor/cli. I'm not sure which one fixed that error, but it gave me the one on this page. I didnt want to build Gradle again when Android Studio should have it, so I restarted it and it started downloading a bunch of Gradle stuff to: /home/user/.gradle. It then prompted me to upgrade Gradle. I then got a similar error to the OP Could not find method include() for arguments [:app] on root project 'android' of type org.gradle.api.Project.. So finally running the above ./gradlew assembleRelease, this error was shown: To build this project, accept the SDK license agreements and install the missing components using the Android Studio SDK Manager. All licenses can be accepted using the sdkmanager command line tool: sdkmanager.bat --licenses I installed SDK sudo snap install android-sdk but didnt have it. Installed with sudo apt install sdkmanager and then sudo sdkmanager --licences (y) to accept.. and got the same error. Found sdkmanager under Tools in AStudio. Tried to update there, but failed. Opened with sudo android-studio, had to select /home/user/.config/Google/AndroidStudioX.Y
Could not find method include() for arguments [:app] on root project Android Studio
I am trying to import an android project to Android studio,after importing and then clicking on the green run button : FAILURE: Build failed with an exception. Where: Build file '/home/myusername/prjcts/nomadx/settings.gradle' line: 1 What went wrong: A problem occurred evaluating root project 'nomadx'. Could not find method include() for arguments [:app] on root project 'nomadx'. The content of the file settings.gradle include ':app'
[ "I solved the problem ; for those who have the same issue : You should build the gradle with the Terminal/console not with Android studio : \n./gradlew assembleRelease\n\n", "After getting this error on first setup:\ncapacitor.settings.gradle' as it does not exist\n..I used two commands from that page: npx cap sync android and npm install --save @capacitor/core @capacitor/cli. I'm not sure which one fixed that error, but it gave me the one on this page. I didnt want to build Gradle again when Android Studio should have it, so I restarted it and it started downloading a bunch of Gradle stuff to: /home/user/.gradle. It then prompted me to upgrade Gradle.\nI then got a similar error to the OP Could not find method include() for arguments [:app] on root project 'android' of type org.gradle.api.Project..\nSo finally running the above ./gradlew assembleRelease, this error was shown:\nTo build this project, accept the SDK license agreements and install the missing components using the Android Studio SDK Manager. All licenses can be accepted using the sdkmanager command line tool: sdkmanager.bat --licenses\nI installed SDK sudo snap install android-sdk but didnt have it. Installed with sudo apt install sdkmanager and then sudo sdkmanager --licences (y) to accept.. and got the same error. Found sdkmanager under Tools in AStudio. Tried to update there, but failed. Opened with sudo android-studio, had to select /home/user/.config/Google/AndroidStudioX.Y\n" ]
[ 2, 0 ]
[]
[]
[ "android", "android_studio", "build", "gradle" ]
stackoverflow_0026886259_android_android_studio_build_gradle.txt
Q: Expo Go with Google/Facebook OAuth - auth.expo.io login screen - "Not Found" I am trying to set up google oauth in a react native, expo managed app. I am only having the following issue using my app within Expo Go - when I create a build of the app, the oauth flow works perfectly. But its hard to develop that way, and I need to be able to share a working app with non-dev team members via Expo Go. I have set up the flow in what I think is the same as what the expo go google auth documentation has described. An overview Create a project in google console, and set up a new ClientID for web applications. Set the authorized origins and redirect uri: Where myorg is the name of the expo organizational account that owns the project, and projectname is the same value as slug in app.json. After setting this up, I get the client id, and client secret for this oauth login method. In my app code, I follow the instructions to use the expo-auth-session library for google: import * as WebBrowser from "expo-web-browser"; import * as Google from "expo-auth-session/providers/google"; WebBrowser.maybeCompleteAuthSession(); export const OAuthButtons: React.FC = () => { const [request, response, promptAsync] = Google.useAuthRequest({ expoClientId: "clientId-from-google-console.apps.googleusercontent.com", iosClientId: "will set this up eventually", androidClientId: "will set this up eventually", }); return; // markup for sign in buttons } So now in my app, when I click the google sign in button, I get the prompt to open the web browser correctly: Clicking that correctly opens the expo web browser, but I see a "not found" message: For more details, when I log the request, I get some pretty expected values "{ "url": "https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=https%3A%2F%2Fauth.expo.io%2FMyProject&client_id=id-from-console.apps.googleusercontent.com&response_type=token&state=5xWG83SsoJ&scope=openid%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email", "responseType": "token", "clientId": "client-id-from-console.apps.googleusercontent.com", "redirectUri": "https://auth.expo.io/MyProject", "scopes": [ "openid", "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email" ], "state": "5xWG83SsoJ", "extraParams": {}, "codeChallengeMethod": "S256", "usePKCE": false }" The only values here that are a bit unexpected are the redirectUri and redirect_uri, which have a /MyProject appended to them, which is not exactly what I had put in my redirect uri in the google console. How did that get appended there? Might that be the problem? As far as I can tell, I've set everything up as described. What is it exactly that is "Not Found" here? The oauth page for this particular expo application? Where did I go wrong in my setup? Edit - Same Problem with Facebook.useAuthRequest I am having the same exact problem with the Facebook provider module as well. Similar code: const [facebookRequest, facebookResponse, facebookPromptAsync] = Facebook.useAuthRequest({ clientId: "facebook_app_id", responseType: ResponseType.Code, }); I also tried the suggestion from the article Use expo-auth-session with Facebook the Easiest Way on iOS/Android to add the useProxy: true property, but that makes no difference. const [facebookRequest, facebookResponse, facebookPromptAsync] = Facebook.useAuthRequest( { clientId: "facebook_app_id", responseType: ResponseType.Code, }, { useProxy: true } ); The facebook login also opens the expo browser to an empty page that says "Not found" What am I doing wrong here? A: Do you have your originalFullName specify on your app.json? If not, try to add it e.g originalFullName: "@your_username/your_app_name" And maybe this github issue can help you, https://github.com/expo/expo/issues/19891.
Expo Go with Google/Facebook OAuth - auth.expo.io login screen - "Not Found"
I am trying to set up google oauth in a react native, expo managed app. I am only having the following issue using my app within Expo Go - when I create a build of the app, the oauth flow works perfectly. But its hard to develop that way, and I need to be able to share a working app with non-dev team members via Expo Go. I have set up the flow in what I think is the same as what the expo go google auth documentation has described. An overview Create a project in google console, and set up a new ClientID for web applications. Set the authorized origins and redirect uri: Where myorg is the name of the expo organizational account that owns the project, and projectname is the same value as slug in app.json. After setting this up, I get the client id, and client secret for this oauth login method. In my app code, I follow the instructions to use the expo-auth-session library for google: import * as WebBrowser from "expo-web-browser"; import * as Google from "expo-auth-session/providers/google"; WebBrowser.maybeCompleteAuthSession(); export const OAuthButtons: React.FC = () => { const [request, response, promptAsync] = Google.useAuthRequest({ expoClientId: "clientId-from-google-console.apps.googleusercontent.com", iosClientId: "will set this up eventually", androidClientId: "will set this up eventually", }); return; // markup for sign in buttons } So now in my app, when I click the google sign in button, I get the prompt to open the web browser correctly: Clicking that correctly opens the expo web browser, but I see a "not found" message: For more details, when I log the request, I get some pretty expected values "{ "url": "https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=https%3A%2F%2Fauth.expo.io%2FMyProject&client_id=id-from-console.apps.googleusercontent.com&response_type=token&state=5xWG83SsoJ&scope=openid%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email", "responseType": "token", "clientId": "client-id-from-console.apps.googleusercontent.com", "redirectUri": "https://auth.expo.io/MyProject", "scopes": [ "openid", "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email" ], "state": "5xWG83SsoJ", "extraParams": {}, "codeChallengeMethod": "S256", "usePKCE": false }" The only values here that are a bit unexpected are the redirectUri and redirect_uri, which have a /MyProject appended to them, which is not exactly what I had put in my redirect uri in the google console. How did that get appended there? Might that be the problem? As far as I can tell, I've set everything up as described. What is it exactly that is "Not Found" here? The oauth page for this particular expo application? Where did I go wrong in my setup? Edit - Same Problem with Facebook.useAuthRequest I am having the same exact problem with the Facebook provider module as well. Similar code: const [facebookRequest, facebookResponse, facebookPromptAsync] = Facebook.useAuthRequest({ clientId: "facebook_app_id", responseType: ResponseType.Code, }); I also tried the suggestion from the article Use expo-auth-session with Facebook the Easiest Way on iOS/Android to add the useProxy: true property, but that makes no difference. const [facebookRequest, facebookResponse, facebookPromptAsync] = Facebook.useAuthRequest( { clientId: "facebook_app_id", responseType: ResponseType.Code, }, { useProxy: true } ); The facebook login also opens the expo browser to an empty page that says "Not found" What am I doing wrong here?
[ "Do you have your originalFullName specify on your app.json? If not, try to add it e.g originalFullName: \"@your_username/your_app_name\"\nAnd maybe this github issue can help you, https://github.com/expo/expo/issues/19891.\n" ]
[ 0 ]
[]
[]
[ "expo", "expo_go", "google_oauth", "oauth", "react_native" ]
stackoverflow_0074617285_expo_expo_go_google_oauth_oauth_react_native.txt
Q: C# InvalidArgument = Value of '2' is not valid for 'index' I am new to C# and I have encountered an error stating that: InvalidArgument=Value of '2' is not valid for 'index'. I want to set the items in checkedlistbox checked if there is a match in listbox. Can anyone help me with this problem. This the part of my code where the problems appear. for (int i = 0; i < checklistbox.Items.Count; i++) { if (checklistbox.Items[i].ToString() == listbox.Items[i].ToString()) { //Check only if they match! checklistbox.SetItemChecked(i, true); } } A: The reason you are getting this error is because you are looping through the count of checklistbox items. So, for example if there are 3 items in that array, and listbox only has 2 items, then on the third loop (when i = 2), you are trying to reference an item in the listbox array that does not exist. Another way to do it would be like this: foreach (var item in listbox.Items) { if (Array.Exists(checklistbox.Items, lbitem => lbitem.ToString() == item.ToString())) { //They match! checklistbox[item].MarkAsChecked() } } Update: answer updated to add MarkAsChecked() and loop through user inputted values held within checklist array. A: You just need to use nested for loop. Here is the code. for (int i = 0; i < listbox.Items.Count; i++) { for (int j = 0; j < checkedlistbox.Items.Count; j++) { if (listbox.Items[i].ToString() == checkedlistbox.Items[j].ToString()) { //Check only if they match! checkedlistbox.SetItemChecked(i, true); } } }
C# InvalidArgument = Value of '2' is not valid for 'index'
I am new to C# and I have encountered an error stating that: InvalidArgument=Value of '2' is not valid for 'index'. I want to set the items in checkedlistbox checked if there is a match in listbox. Can anyone help me with this problem. This the part of my code where the problems appear. for (int i = 0; i < checklistbox.Items.Count; i++) { if (checklistbox.Items[i].ToString() == listbox.Items[i].ToString()) { //Check only if they match! checklistbox.SetItemChecked(i, true); } }
[ "The reason you are getting this error is because you are looping through the count of checklistbox items. So, for example if there are 3 items in that array, and listbox only has 2 items, then on the third loop (when i = 2), you are trying to reference an item in the listbox array that does not exist.\nAnother way to do it would be like this:\nforeach (var item in listbox.Items)\n {\n if (Array.Exists(checklistbox.Items, lbitem => lbitem.ToString() == item.ToString()))\n {\n //They match! \n checklistbox[item].MarkAsChecked()\n }\n }\n\nUpdate: answer updated to add MarkAsChecked() and loop through user inputted values held within checklist array.\n", "You just need to use nested for loop. Here is the code.\n for (int i = 0; i < listbox.Items.Count; i++)\n {\n for (int j = 0; j < checkedlistbox.Items.Count; j++)\n {\n if (listbox.Items[i].ToString() == checkedlistbox.Items[j].ToString())\n {\n //Check only if they match! \n checkedlistbox.SetItemChecked(i, true);\n }\n }\n }\n\n" ]
[ 0, 0 ]
[]
[]
[ "c#", "checkedlistbox", "listbox", "winforms" ]
stackoverflow_0074628289_c#_checkedlistbox_listbox_winforms.txt
Q: How can I add multiple extensions with `git add`? I have about 10 extensions that I want to add to the index with a script in my CI pipeline. I know that git add supports file patterns such as *.c (the term used in the documentation is 'fileglob'). However, is there a way to add multiple extensions with a single command, e.g. git add *.{dll,exe,json}? I have not found any examples in the documentation or Stack overflow about this issue. A: In powershell this should be something like the following if you want to add files recursively: Get-ChildItem -Recurse -Filter "*.dll" -or -Filter "*.exe" -or -Filter "*.json" | ForEach-Object { git add $_ } (extend to your 10 extensions)
How can I add multiple extensions with `git add`?
I have about 10 extensions that I want to add to the index with a script in my CI pipeline. I know that git add supports file patterns such as *.c (the term used in the documentation is 'fileglob'). However, is there a way to add multiple extensions with a single command, e.g. git add *.{dll,exe,json}? I have not found any examples in the documentation or Stack overflow about this issue.
[ "In powershell this should be something like the following if you want to add files recursively:\nGet-ChildItem -Recurse -Filter \"*.dll\" -or -Filter \"*.exe\" -or -Filter \"*.json\" | ForEach-Object { git add $_ }\n\n(extend to your 10 extensions)\n" ]
[ 0 ]
[]
[]
[ "git", "powershell" ]
stackoverflow_0074655547_git_powershell.txt
Q: Check if Laravel object has specified item Is there a way to check a Laravel object for a specific relationship attribute? Ex: I want to check if an order has a line item with part number 12345 I already have my Order, OrderItem, and Order hasMany OrderItem relationship setup Illuminate\Database\Eloquent\Collection {#519 ▼ #items: array:1 [▼ 0 => App\Models\OrderItem {#518 ▼ #table: "order_items" #fillable: array:7 [▶] ... #attributes: array:11 [▼ "id" => 1 "order_id" => "1" "part_number" => "12345" ... ] So in this case I want it to return true I thought I could use has, but from my understanding it doens't work in this way. $order->items->has('part_number', '12345')
Check if Laravel object has specified item
Is there a way to check a Laravel object for a specific relationship attribute? Ex: I want to check if an order has a line item with part number 12345 I already have my Order, OrderItem, and Order hasMany OrderItem relationship setup Illuminate\Database\Eloquent\Collection {#519 ▼ #items: array:1 [▼ 0 => App\Models\OrderItem {#518 ▼ #table: "order_items" #fillable: array:7 [▶] ... #attributes: array:11 [▼ "id" => 1 "order_id" => "1" "part_number" => "12345" ... ] So in this case I want it to return true I thought I could use has, but from my understanding it doens't work in this way. $order->items->has('part_number', '12345')
[]
[]
[ "use where.\n$order->items->where('part_number', 12345)->first() //or ->get()\n\n" ]
[ -1 ]
[ "eloquent", "eloquent_relationship", "laravel" ]
stackoverflow_0074662850_eloquent_eloquent_relationship_laravel.txt
Q: TortoiseGit Error - Could not get all refs. libgit2 returned: corrupted loose reference file I just got an error after a recent commit using Tortoise Git: "Could not get all refs. libgit2 returned: corrupted loose reference file" which pops up when I go to check the Log. Any ideas on how to rectify this? A: Your refs are stored inside the raw repository (in .git) in directories (named for each branch) under the "refs" directory. The problem is that one of these files has been corrupted. If you check the code here you'll see that the problem is either that the ref file is less than 40 bytes long, or has a 41st byte that is not a space (or tab, newline, etc). Search through the files in the .git/refs directory and you'll find the bad one. It should contain the 40-character hash of the commit which that branch refers to. You can safely fix it using Notepad. A: In my case it was the use of "junction tool" (sysinternals). Got that error only when adding new sub directory and files. Using git bash the problem does not occur. Everything else works fine with "junction tool" and TortoiseGit ... A: I had the exact same error and managed to get my repo back without losing my changes. I: Made several backups of the corrupt git repository just in case Cloned the lasted pushed version from the remote repository Copied all the files from the corrupt .git folder EXCEPT all files related to HEAD, FETCH_HEAD, ORG_HEAD etc ... the most important are the refs, obj, and index Ended up with a valid history, but corrupt index, applied the solution from this post How to resolve "Error: bad index – Fatal: index file corrupt" when using Git And my repository was back working ... To make sure I did not push anything wrong, I cloned again from the remote, checked-out the changes I wanted to save from the restored repository, and comited them fresh.
TortoiseGit Error - Could not get all refs. libgit2 returned: corrupted loose reference file
I just got an error after a recent commit using Tortoise Git: "Could not get all refs. libgit2 returned: corrupted loose reference file" which pops up when I go to check the Log. Any ideas on how to rectify this?
[ "Your refs are stored inside the raw repository (in .git) in directories (named for each branch) under the \"refs\" directory. The problem is that one of these files has been corrupted. If you check the code here you'll see that the problem is either that the ref file is less than 40 bytes long, or has a 41st byte that is not a space (or tab, newline, etc). Search through the files in the .git/refs directory and you'll find the bad one. It should contain the 40-character hash of the commit which that branch refers to. You can safely fix it using Notepad.\n", "In my case it was the use of \"junction tool\" (sysinternals). Got that error only when adding new sub directory and files. Using git bash the problem does not occur. Everything else works fine with \"junction tool\" and TortoiseGit ...\n", "I had the exact same error and managed to get my repo back without losing my changes.\nI:\n\nMade several backups of the corrupt git repository just in case\nCloned the lasted pushed version from the remote repository\nCopied all the files from the corrupt .git folder EXCEPT all files related to HEAD, FETCH_HEAD, ORG_HEAD etc ... the most important are the refs, obj, and index\nEnded up with a valid history, but corrupt index, applied the solution from this post How to resolve \"Error: bad index – Fatal: index file corrupt\" when using Git\n\nAnd my repository was back working ...\nTo make sure I did not push anything wrong, I cloned again from the remote, checked-out the changes I wanted to save from the restored repository, and comited them fresh.\n" ]
[ 20, 0, 0 ]
[]
[]
[ "git", "tortoisegit", "windows" ]
stackoverflow_0017304710_git_tortoisegit_windows.txt
Q: Comparing columns and printing comments in a new column based on column values I have a file with multiple columns. I want to check the following conditions : file.csv A.B.P;FATH;FNAME;XTRUC;XIZE;XIZE2;ORG;ORG2 AIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;XY AIT-A;Y9A;RAIT;VIR;67;217;X;X if $4 contains UNKNOWN print in a new error column "XTRUC is UNKNOWN " Example : A.B.P;FATH;FNAME;XTRUC;XIZE;XIZE2;ORG;ORG2;error AIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;XY;"XTRUC is UNKNOWN." if for the same value in $3 we have different values in $4 print in a new column "multiple XTRUC value for the same FNAME" and if the previous error exist print the new error in a new line in the same cell. Example : A.B.P;FATH;FNAME;XTRUC;XIZE;XIZE2;ORG;ORG2;error AIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;XY;"XTRUC is UNKNOWN. multiple XTRUC value for the same FNAME." AIT-A;Y9A;RAIT;VIR;67;217;X;X;"multiple XTRUC value for the same FNAME" if $5 and $6 do not match or one of them or both contain something other tan numbers print the error in a new column "XIZE NOK" and/or "XIZE2 NOK" and/or "XIZE and XIZE2 don't match" in a new line if previous errors exist in the same cell. Example : A.B.P;FATH;FNAME;XTRUC;XIZE;XIZE2;ORG;ORG2;error AIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;XY;"XTRUC is UNKNOWN. multiple XTRUC value for the same FNAME. XIZE NOK." AIT-A;Y9A;RAIT;VIR;67;217;X;X;"multiple XTRUC value for the same FNAME. XIZE and XIZE2 don't match." if $7 and $8 do not match print the error in a new column "ORG and ORG2 don't match" in a new line if previous errors exist in the same cell. Example and expected result: A.B.P;FATH;FNAME;XTRUC;XIZE;XIZE2;ORG;ORG2;error AIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;X;"XTRUC is UNKNOWN. multiple XTRUC value for the same FNAME. XIZE NOK." AIT-A;Y9A;RAIT;VIR;67;217;X;X Y;"multiple XTRUC value for the same FNAME. XIZE and XIZE2 don't match. ORG and ORG2 don't match." Visual result from CSV file : I tried to use multiple awk commands like : awk '{if($5!=$6) print "XIZE and XIZE2 do not match" ; elif($5!='^[0-9]+$' print "`XIZE` NOK" ; elif($6!="^-\?[0-9]+$" print "`XIZE` NOK"}' file.csv It didn't work and with multiple conditions i wonder if there's a simpler way to do it. A: I assume you want to add these messages to a new final column. awk -F ';' 'BEGIN {OFS = FS} {new_field = NF + 1} $5 != $6 {$new_field = $new_field "XIZE and XIZE2 do not match\n"} $5 !~ "^[0-9]+$" {$new_field = $new_field "`XIZE` NOK\n"} $6 !~ "^-\\?[0-9]+$" {$new_field = $new_field "`XIZE` NOK\n"} {print}' file.csv > new-file.csv This may output more newlines than you want. If that's a problem, it's possible to fix that, perhaps using an array and a for loop or building a string and adding it at print time (see below) instead of simple concatenation. This script sets the field delimiter for input (-F) and output (OFS) to a semicolon calculates the field number of a new error field at the end of the row, it does this for each row, so it may be different if the lengths of rows varies for each true field test it concatenates a message to the error field regex tests use the negated regex match operator !~ each field in each row is tested (tests are not mutually exclusive (no else), if you want them to be mutually exclusive you can change the form of the tests back to using if and else prints the whole row whether an error field was added or not redirects the output to a new file I used the shorter messages from your AWK script rather than the longer ones in your examples. You can easily change them if needed. Here is an array version that eliminates an excess newline and wraps the new field in quotes: awk -F ';' 'BEGIN {OFS = FS} NR == 1 {print; next} {new_field = NF + 1; delete arr; i = 0; d = ""; msg = ""} $5 != $6 {arr[i++] = "XIZE and XIZE2 do not match"} $5 !~ "^[0-9]+$" {arr[i++] = "`XIZE` NOK"} $6 !~ "^-\\?[0-9]+$" {arr[i++] = "`XIZE` NOK"} { if (i > 0) { msg = "\""; for (idx in arr) { msg = d msg arr[idx]; d = "\n"; } msg = msg "\""; $new_field = msg; }; print }' file.csv > new-file.csv A: I think this might be what you want: $ cat tst.awk BEGIN { FS=OFS=";" } NR == 1 { print $0, "error"; next } { numErrs = 0 } ($4 == "UNKNOWN") { errs[++numErrs] = "XTRUC is UNKNOWN" } ($3 != $4) { errs[++numErrs] = "multiple XTRUC value for the same FNAME" } ($5 != $6) || ($5+0 != $5) || ($6+0 != $6) { errs[++numErrs] = "XIZE and XIZE2 don't match" } ($7 != $8) { errs[++numErrs] = "ORG and ORG2 don't match" } { printf "%s%s\"", $0, OFS for ( errNr=1; errNr<=numErrs; errNr++ ) { printf "%s%s", (errNr>1 ? "\n\t\t\t\t" : ""), errs[errNr] } print "\"" } $ awk -f tst.awk file.csv A.B.P;FATH;FNAME;XTRUC;XIZE;XIZE2;ORG;ORG2;error AIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;XY;"XTRUC is UNKNOWN multiple XTRUC value for the same FNAME XIZE and XIZE2 don't match ORG and ORG2 don't match" AIT-A;Y9A;RAIT;VIR;67;217;X;X;"multiple XTRUC value for the same FNAME XIZE and XIZE2 don't match" If you don't REALLY want a bunch of white space at the start of the lines in the quoted fields (I only added them to get output that looks ike you say you wanted in your question), then just get rid of \t\t\t\t from the printf but leave the \n, i.e. printf "%s%s", (errNr>1 ? "\n" : ""), errs[errNr]. I'd normally print ORS insead of \n but you may be doing this to create output for MS-Excel in which case you'd set ORS="\r\n" in the BEGIN section and leave that printf with a \n in it for consistency with Excels CSV format.
Comparing columns and printing comments in a new column based on column values
I have a file with multiple columns. I want to check the following conditions : file.csv A.B.P;FATH;FNAME;XTRUC;XIZE;XIZE2;ORG;ORG2 AIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;XY AIT-A;Y9A;RAIT;VIR;67;217;X;X if $4 contains UNKNOWN print in a new error column "XTRUC is UNKNOWN " Example : A.B.P;FATH;FNAME;XTRUC;XIZE;XIZE2;ORG;ORG2;error AIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;XY;"XTRUC is UNKNOWN." if for the same value in $3 we have different values in $4 print in a new column "multiple XTRUC value for the same FNAME" and if the previous error exist print the new error in a new line in the same cell. Example : A.B.P;FATH;FNAME;XTRUC;XIZE;XIZE2;ORG;ORG2;error AIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;XY;"XTRUC is UNKNOWN. multiple XTRUC value for the same FNAME." AIT-A;Y9A;RAIT;VIR;67;217;X;X;"multiple XTRUC value for the same FNAME" if $5 and $6 do not match or one of them or both contain something other tan numbers print the error in a new column "XIZE NOK" and/or "XIZE2 NOK" and/or "XIZE and XIZE2 don't match" in a new line if previous errors exist in the same cell. Example : A.B.P;FATH;FNAME;XTRUC;XIZE;XIZE2;ORG;ORG2;error AIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;XY;"XTRUC is UNKNOWN. multiple XTRUC value for the same FNAME. XIZE NOK." AIT-A;Y9A;RAIT;VIR;67;217;X;X;"multiple XTRUC value for the same FNAME. XIZE and XIZE2 don't match." if $7 and $8 do not match print the error in a new column "ORG and ORG2 don't match" in a new line if previous errors exist in the same cell. Example and expected result: A.B.P;FATH;FNAME;XTRUC;XIZE;XIZE2;ORG;ORG2;error AIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;X;"XTRUC is UNKNOWN. multiple XTRUC value for the same FNAME. XIZE NOK." AIT-A;Y9A;RAIT;VIR;67;217;X;X Y;"multiple XTRUC value for the same FNAME. XIZE and XIZE2 don't match. ORG and ORG2 don't match." Visual result from CSV file : I tried to use multiple awk commands like : awk '{if($5!=$6) print "XIZE and XIZE2 do not match" ; elif($5!='^[0-9]+$' print "`XIZE` NOK" ; elif($6!="^-\?[0-9]+$" print "`XIZE` NOK"}' file.csv It didn't work and with multiple conditions i wonder if there's a simpler way to do it.
[ "I assume you want to add these messages to a new final column.\nawk -F ';' 'BEGIN {OFS = FS}\n{new_field = NF + 1}\n$5 != $6 {$new_field = $new_field \"XIZE and XIZE2 do not match\\n\"}\n$5 !~ \"^[0-9]+$\" {$new_field = $new_field \"`XIZE` NOK\\n\"}\n$6 !~ \"^-\\\\?[0-9]+$\" {$new_field = $new_field \"`XIZE` NOK\\n\"}\n{print}' file.csv > new-file.csv\n\nThis may output more newlines than you want. If that's a problem, it's possible to fix that, perhaps using an array and a for loop or building a string and adding it at print time (see below) instead of simple concatenation.\nThis script\n\nsets the field delimiter for input (-F) and output (OFS) to a semicolon\ncalculates the field number of a new error field at the end of the row, it does this for each row, so it may be different if the lengths of rows varies\nfor each true field test it concatenates a message to the error field\nregex tests use the negated regex match operator !~\neach field in each row is tested (tests are not mutually exclusive (no else), if you want them to be mutually exclusive you can change the form of the tests back to using if and else\nprints the whole row whether an error field was added or not\nredirects the output to a new file\n\nI used the shorter messages from your AWK script rather than the longer ones in your examples. You can easily change them if needed.\nHere is an array version that eliminates an excess newline and wraps the new field in quotes:\nawk -F ';' 'BEGIN {OFS = FS}\nNR == 1 {print; next}\n{new_field = NF + 1; delete arr; i = 0; d = \"\"; msg = \"\"}\n$5 != $6 {arr[i++] = \"XIZE and XIZE2 do not match\"}\n$5 !~ \"^[0-9]+$\" {arr[i++] = \"`XIZE` NOK\"}\n$6 !~ \"^-\\\\?[0-9]+$\" {arr[i++] = \"`XIZE` NOK\"}\n{\n if (i > 0) {\n msg = \"\\\"\";\n for (idx in arr) {\n msg = d msg arr[idx];\n d = \"\\n\";\n }\n msg = msg \"\\\"\";\n $new_field = msg;\n };\n \n print\n}' file.csv > new-file.csv\n\n", "I think this might be what you want:\n$ cat tst.awk\nBEGIN { FS=OFS=\";\" }\nNR == 1 { print $0, \"error\"; next }\n\n{ numErrs = 0 }\n($4 == \"UNKNOWN\") { errs[++numErrs] = \"XTRUC is UNKNOWN\" }\n($3 != $4) { errs[++numErrs] = \"multiple XTRUC value for the same FNAME\" }\n($5 != $6) || ($5+0 != $5) || ($6+0 != $6) { errs[++numErrs] = \"XIZE and XIZE2 don't match\" }\n($7 != $8) { errs[++numErrs] = \"ORG and ORG2 don't match\" }\n{\n printf \"%s%s\\\"\", $0, OFS\n for ( errNr=1; errNr<=numErrs; errNr++ ) {\n printf \"%s%s\", (errNr>1 ? \"\\n\\t\\t\\t\\t\" : \"\"), errs[errNr]\n }\n print \"\\\"\"\n}\n\n\n$ awk -f tst.awk file.csv\nA.B.P;FATH;FNAME;XTRUC;XIZE;XIZE2;ORG;ORG2;error\nAIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;XY;\"XTRUC is UNKNOWN\n multiple XTRUC value for the same FNAME\n XIZE and XIZE2 don't match\n ORG and ORG2 don't match\"\nAIT-A;Y9A;RAIT;VIR;67;217;X;X;\"multiple XTRUC value for the same FNAME\n XIZE and XIZE2 don't match\"\n\nIf you don't REALLY want a bunch of white space at the start of the lines in the quoted fields (I only added them to get output that looks ike you say you wanted in your question), then just get rid of \\t\\t\\t\\t from the printf but leave the \\n, i.e. printf \"%s%s\", (errNr>1 ? \"\\n\" : \"\"), errs[errNr]. I'd normally print ORS insead of \\n but you may be doing this to create output for MS-Excel in which case you'd set ORS=\"\\r\\n\" in the BEGIN section and leave that printf with a \\n in it for consistency with Excels CSV format.\n" ]
[ 1, 0 ]
[ "printf \"AIT;Y9A;RAIT;UNKNOWN;UNKNOWN;80;X;XY\" | tr ';' '\\n' > stack\n\n[[ $(sed -n '/UNKNOWN/p' stack) ]] && printf \"\\\"XTRUC is UNKNOWN\\\"\" >> stack\n\ntr '\\n' ';' < stack > s2\n\nYou can do the same thing with whatever other tests you like. Just replace the semi colons with newlines, and then use ed or sed to read the line number corresponding with the line you want. After that, replace the newlines with semicolons again.\n" ]
[ -2 ]
[ "awk", "bash" ]
stackoverflow_0074657064_awk_bash.txt
Q: How do I overwrite Bootstrap SCSS variables for my django website using PyCharm? I'm using PyCharm to manage my django files and for the front end I'm using Bootstrap. I'm currently using the CDN method to point to the bootstrap files in my base.html file. I've recently come to a point where I want to customize some of the SCSS variables that bootstrap provides, but I'm puzzled and can't find a guide anywhere to how to do this with my configuration. I used npm to install the bootstrap files to my outer project folder. I've tried installing django-sass-compiler using pip, and then adding the required setting to my settings.py, but when I ran the command "python manage.py sass-compiler" (as per the PyPi docs), I got "ModuleNotFoundError: No module named 'django_sass_compiler'" I'm assuming that if I were to get that working then it would compile my custom SCSS file into a CSS file that would overwrite my current 'main.css' (is that right?), however I can't even figure out that part. If someone could please point me in the right direction then that would be great, there really isn't a lot of help out there for sass, pycharm, django & bootstrap together. A: Yes, you will have to compile the CSS manually. You can use tools like Koala. To accomplish that in Django, You will have to: Create a directory named static at your project level directory. In satic add another folder called css. Go ahead and add the compiled CSS file. Change STATIC_URL = 'static/' to STATIC_URL = '/static/' and add STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) In your base.html file at the very top add {% load static %} and you can link the base.html file to your compiled CSS file like shown below: <link rel="stylesheet" href="/static/css/mycss.css">
How do I overwrite Bootstrap SCSS variables for my django website using PyCharm?
I'm using PyCharm to manage my django files and for the front end I'm using Bootstrap. I'm currently using the CDN method to point to the bootstrap files in my base.html file. I've recently come to a point where I want to customize some of the SCSS variables that bootstrap provides, but I'm puzzled and can't find a guide anywhere to how to do this with my configuration. I used npm to install the bootstrap files to my outer project folder. I've tried installing django-sass-compiler using pip, and then adding the required setting to my settings.py, but when I ran the command "python manage.py sass-compiler" (as per the PyPi docs), I got "ModuleNotFoundError: No module named 'django_sass_compiler'" I'm assuming that if I were to get that working then it would compile my custom SCSS file into a CSS file that would overwrite my current 'main.css' (is that right?), however I can't even figure out that part. If someone could please point me in the right direction then that would be great, there really isn't a lot of help out there for sass, pycharm, django & bootstrap together.
[ "Yes, you will have to compile the CSS manually. You can use tools like Koala.\nTo accomplish that in Django, You will have to:\n\nCreate a directory named static at your project level directory. In satic add another folder called css. Go ahead and add the compiled CSS file.\nChange\n\nSTATIC_URL = 'static/'\n\nto\nSTATIC_URL = '/static/'\n\nand add\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'static'),\n)\n\n\nIn your base.html file at the very top add\n\n{% load static %}\n\nand you can link the base.html file to your compiled CSS file like shown below:\n<link rel=\"stylesheet\" href=\"/static/css/mycss.css\">\n\n" ]
[ 0 ]
[]
[]
[ "compilation", "django", "frontend", "pycharm", "sass" ]
stackoverflow_0074662175_compilation_django_frontend_pycharm_sass.txt
Q: Socket IO event sometimes doesn't get to client from a Service hosted on Google Cloud Run I have a NodeJS service hosted on Google Cloud Run that uses Socket IO to communicate back to the browser client whenever the service instance is running. However, I am noticing something weird. The weird thing is that sometimes when the server emits a socket event to the client, the client gets the event immediately but on some other occasions the event never gets to the client. This happens so randomly that it's really hard to reproduce where the disconnection is coming from. Below is my client code: client_socket.js import io from "socket.io-client"; const socketUrl = EndPoints.SOCKET_IO_BASE; let socketOptions = { transports: ["websocket"] } let socket; if (!socket) { socket = io(socketUrl, socketOptions); socket.on('connect', () => { console.log(`Connected to Server`); }) socket.on('disconnect', () => { console.log(`Disconnected from Server`); //This never gets called when the Cloud Run service instance is running, so I can assume a disconnect never happened. }) } export default socket; Funny enough, a disconnect event was never fired back to the client while the Cloud Run service instance is running, meaning the client is still connected to the service. So, it's really weird that on some occasions it doesn't get events from the server even while been connected. Please note that on the Google Cloud Run service side I have set the timeout of my service to 3600s which is more than good enough to ensure the service is running long enough to keep the socket connection in place. A: Based on this documentation on best practices: The most difficult part of creating WebSockets services on Cloud Run is synchronizing data between multiple Cloud Run container instances. This is difficult because of the autoscaling and stateless nature of container instances, and because of the limits for concurrency and request timeouts. One suggestion is by using session affinity. If enabled, Cloud Run will route sequential requests for a given client to the same container instance and will use a session affinity cookie with a TTL of 30 days. It will also inspect the value to identify requests by the same client and direct the requests to the same instance. Still, it is not guaranteed that it will be serviced by the same instance. Also, this feature is still in the preview phase and may change while still in development. It is recommended to use external data storage such as database (Cloud SQL) or external message queue (Redis Pub/Sub/Memorystore/Firestore real-time updates) that can deliver updates to all instances over connections initiated by the container instance.
Socket IO event sometimes doesn't get to client from a Service hosted on Google Cloud Run
I have a NodeJS service hosted on Google Cloud Run that uses Socket IO to communicate back to the browser client whenever the service instance is running. However, I am noticing something weird. The weird thing is that sometimes when the server emits a socket event to the client, the client gets the event immediately but on some other occasions the event never gets to the client. This happens so randomly that it's really hard to reproduce where the disconnection is coming from. Below is my client code: client_socket.js import io from "socket.io-client"; const socketUrl = EndPoints.SOCKET_IO_BASE; let socketOptions = { transports: ["websocket"] } let socket; if (!socket) { socket = io(socketUrl, socketOptions); socket.on('connect', () => { console.log(`Connected to Server`); }) socket.on('disconnect', () => { console.log(`Disconnected from Server`); //This never gets called when the Cloud Run service instance is running, so I can assume a disconnect never happened. }) } export default socket; Funny enough, a disconnect event was never fired back to the client while the Cloud Run service instance is running, meaning the client is still connected to the service. So, it's really weird that on some occasions it doesn't get events from the server even while been connected. Please note that on the Google Cloud Run service side I have set the timeout of my service to 3600s which is more than good enough to ensure the service is running long enough to keep the socket connection in place.
[ "Based on this documentation on best practices:\n\nThe most difficult part of creating WebSockets services on Cloud Run is synchronizing data between multiple Cloud Run container instances. This is difficult because of the autoscaling and stateless nature of container instances, and because of the limits for concurrency and request timeouts.\n\nOne suggestion is by using session affinity. If enabled, Cloud Run will route sequential requests for a given client to the same container instance and will use a session affinity cookie with a TTL of 30 days. It will also inspect the value to identify requests by the same client and direct the requests to the same instance. Still, it is not guaranteed that it will be serviced by the same instance.\nAlso, this feature is still in the preview phase and may change while still in development.\nIt is recommended to use external data storage such as database (Cloud SQL) or external message queue (Redis Pub/Sub/Memorystore/Firestore real-time updates) that can deliver updates to all instances over connections initiated by the container instance.\n" ]
[ 1 ]
[]
[]
[ "google_cloud_run", "node.js", "socket.io" ]
stackoverflow_0074658518_google_cloud_run_node.js_socket.io.txt
Q: Git: "Corrupt loose object" Whenever I pull from my remote, I get the following error about compression. When I run the manual compression, I get the same: $ git gc error: Could not read 3813783126d41a3200b35b6681357c213352ab31 fatal: bad tree object 3813783126d41a3200b35b6681357c213352ab31 error: failed to run repack Does anyone know, what to do about that? From cat-file I get this: $ git cat-file -t 3813783126d41a3200b35b6681357c213352ab31 error: unable to find 3813783126d41a3200b35b6681357c213352ab31 fatal: git cat-file 3813783126d41a3200b35b6681357c213352ab31: bad file And from git fsck I get this ( don't know if it's actually related): $ git fsck error: inflate: data stream error (invalid distance too far back) error: corrupt loose object '45ba4ceb93bc812ef20a6630bb27e9e0b33a012a' fatal: loose object 45ba4ceb93bc812ef20a6630bb27e9e0b33a012a (stored in .git/objects/45/ba4ceb93bc812ef20a6630bb27e9e0b33a012a) is corrupted Can anyone help me decipher this? A: I had the same problem (don't know why). This fix requires access to an uncorrupted remote copy of the repository, and will keep your locally working copy intact. But it has some drawbacks: You will lose the record of any commits that were not pushed, and will have to recommit them. You will lose any stashes. The fix Execute these commands from the parent directory above your repo (replace 'foo' with the name of your project folder): Create a backup of the corrupt directory: cp -R foo foo-backup Make a new clone of the remote repository to a new directory: git clone [email protected]:foo foo-newclone Delete the corrupt .git subdirectory: rm -rf foo/.git Move the newly cloned .git subdirectory into foo: mv foo-newclone/.git foo Delete the rest of the temporary new clone: rm -rf foo-newclone On Windows you will need to use: copy instead of cp -R rmdir /S instead of rm -rf move instead of mv Now foo has its original .git subdirectory back, but all the local changes are still there. git status, commit, pull, push, etc. work again as they should. A: Your best bet is probably to simply re-clone from the remote repository (i.e., GitHub or other). Unfortunately you will lose any unpushed commits and stashed changes, however your working copy should remain intact. First make a backup copy of your local files. Then do this from the root of your working tree: rm -fr .git git init git remote add origin [your-git-remote-url] git fetch git reset --mixed origin/master git branch --set-upstream-to=origin/master master Then commit any changed files as necessary. A: Working on a VM, in my notebook, battery died, got this error; error: object file .git/objects/ce/theRef is empty error: object file .git/objects/ce/theRef is empty fatal: loose object theRef (stored in .git/objects/ce/theRef) is corrupt I managed to get the repo working again with only 2 commands and without losing my work (modified files/uncommitted changes) find .git/objects/ -size 0 -exec rm -f {} \; git fetch origin After that I ran a git status, the repo was fine and there were my changes (waiting to be committed, do it now..). git version 1.9.1 Remember to backup all changes you remember, just in case this solution doesn't works and a more radical approach is needed. A: Looks like you have a corrupt tree object. You will need to get that object from someone else. Hopefully they will have an uncorrupted version. You could actually reconstruct it if you can't find a valid version from someone else by guessing at what files should be there. You may want to see if the dates & times of the objects match up to it. Those could be the related blobs. You could infer the structure of the tree object from those objects. Take a look at Scott Chacon's Git Screencasts regarding git internals. This will show you how git works under the hood and how to go about doing this detective work if you are really stuck and can't get that object from someone else. A: My computer crashed while I was writing a commit message. After rebooting, the working tree was as I had left it and I was able to successfully commit my changes. However, when I tried to run git status I got error: object file .git/objects/xx/12345 is empty fatal: loose object xx12345 (stored in .git/objects/xx/12345 is corrupt Unlike most of the other answers, I wasn't trying to recover any data. I just needed Git to stop complaining about the empty object file. Overview The "object file" is Git's hashed representation of a real file that you care about. Git thinks it should have a hashed version of some/file.whatever stored in .git/object/xx/12345, and fixing the error turned out to be mostly a matter of figuring out which file the "loose object" was supposed to represent. Details Possible options seemed to be Delete the empty file Get the file into a state acceptable to Git Approach 1: Remove the object file The first thing I tried was just moving the object file mv .git/objects/xx/12345 .. That didn't work - Git began complaining about a broken link. On to Approach 2. Approach 2: Fix the file Linus Torvalds has a great writeup of how to recover an object file that solved the problem for me. Key steps are summarized here. $> # Find out which file the blob object refers to $> git fsck broken link from tree 2d9263c6d23595e7cb2a21e5ebbb53655278dff8 to blob xx12345 missing blob xx12345 $> git ls-tree 2d926 ... 10064 blob xx12345 your_file.whatever This tells you what file the empty object is supposed to be a hash of. Now you can repair it. $> git hash-object -w path/to/your_file.whatever After doing this I checked .git/objects/xx/12345, it was no longer empty, and Git stopped complaining. A: Try git stash This worked for me. It stashes anything you haven't committed and that got around the problem. A: A garbage collection fixed my problem: git gc --aggressive --prune=now It takes a while to complete, but every loose object and/or corrupted index was fixed. A: simply running a git prune fixed this issue for me A: I encountered this once my system crashed. What I did is this: (Please note your corrupt commits are lost, but changes are retained. You might have to recreate those commits at the end of this procedure) Backup your code. Go to your working directory and delete the .git folder. Now clone the remote in another location and copy the .git folder in it. Paste it in your working directory. Commit as you wanted. A: I just experienced this - my machine crashed whilst writing to the Git repo, and it became corrupted. I fixed it as follows. I started with looking at how many commits I had not pushed to the remote repo, thus: gitk & If you don't use this tool it is very handy - available on all operating systems as far as I know. This indicated that my remote was missing two commits. I therefore clicked on the label indicating the latest remote commit (usually this will be /remotes/origin/master) to get the hash (the hash is 40 chars long, but for brevity I am using 10 here - this usually works anyway). Here it is: 14c0fcc9b3 I then click on the following commit (i.e. the first one that the remote does not have) and get the hash there: 04d44c3298 I then use both of these to make a patch for this commit: git diff 14c0fcc9b3 04d44c3298 > 1.patch I then did likewise with the other missing commit, i.e. I used the hash of the commit before and the hash of the commit itself: git diff 04d44c3298 fc1d4b0df7 > 2.patch I then moved to a new directory, cloned the repo from the remote: git clone [email protected]:username/repo.git I then moved the patch files into the new folder, and applied them and committed them with their exact commit messages (these can be pasted from git log or the gitk window): patch -p1 < 1.patch git commit patch -p1 < 2.patch git commit This restored things for me (and note there's probably a faster way to do it for a large number of commits). However I was keen to see if the tree in the corrupted repo can be repaired, and the answer is it can. With a repaired repo available as above, run this command in the broken folder: git fsck You will get something like this: error: object file .git/objects/ca/539ed815fefdbbbfae6e8d0c0b3dbbe093390d is empty error: unable to find ca539ed815fefdbbbfae6e8d0c0b3dbbe093390d error: sha1 mismatch ca539ed815fefdbbbfae6e8d0c0b3dbbe093390d To do the repair, I would do this in the broken folder: rm .git/objects/ca/539ed815fefdbbbfae6e8d0c0b3dbbe093390d cp ../good-repo/.git/objects/ca/539ed815fefdbbbfae6e8d0c0b3dbbe093390d .git/objects/ca/539ed815fefdbbbfae6e8d0c0b3dbbe093390d i.e. remove the corrupted file and replace it with a good one. You may have to do this several times. Finally there will be a point where you can run fsck without errors. You will probably have "dangling commit" and "dangling blob" lines in the report, these are a consequence of your rebases and amends in this folder, and are OK. The garbage collector will remove them in due course. Thus (at least in my case) a corrupted tree does not mean unpushed commits are lost. A: The answer of user1055643 is missing the last step: rm -fr .git git init git remote add origin your-git-remote-url git fetch git reset --hard origin/master git branch --set-upstream-to=origin/master master A: The solution offered by Felipe Pereira (above) in addition to Stephan's comment to that answer with the name of the branch I was on when the objects got corrupted is what worked for me. find .git/objects/ -size 0 -exec rm -f {} \; git fetch origin git symbolic-ref HEAD refs/heads/${BRANCH_NAME} A: Runnning git stash; git stash pop fixed my problem A: I followed many of the other steps here; Linus' description of how to look at the git tree/objects and find what's missing was especially helpful. git-git recover corrupted blob But in the end, for me, I had loose/corrupt tree objects caused by a partial disk failure, and tree objects are not so easily recovered/not covered by that doc. In the end, I moved the conflicting objects/<ha>/<hash> out of the way, and used git unpack-objects with a pack file from a reasonably up to date clone. It was able to restore the missing tree objects. Still left me with a lot of dangling blobs, which can be a side effect of unpacking previously archived stuff, and addressed in other questions here A: I was getting a corrupt loose object error as well. ./objects/x/x I successfully fixed it by going into the directory of the corrupt object. I saw that the users assigned to that object was not my git user's. I don't know how it happened, but I ran a chown git:git on that file and then it worked again. This may be a potential fix for some peoples' issues but not necessary all of them. A: To me this happened due to a power failure while doing a git push. The messages looked like this: $ git status error: object file .git/objects/c2/38824eb3fb602edc2c49fccb535f9e53951c74 is empty error: object file .git/objects/c2/38824eb3fb602edc2c49fccb535f9e53951c74 is empty fatal: loose object c238824eb3fb602edc2c49fccb535f9e53951c74 (stored in .git/objects/c2/38824eb3fb602edc2c49fccb535f9e53951c74) is corrupt I tried things like git fsck but that didn't help. Since the crash happened during a git push, it obviously happened during rewrite on the client side which happens after the server is updated. I looked around and figured that c2388 in my case was a commit object, because it was referred to by entries in .git/refs. So I knew that I would be able to find c2388 when I look at the history (through a web interface or second clone). On the second clone I did a git log -n 2 c2388 to identify the predecessor of c2388. Then I manually modified .git/refs/heads/master and .git/refs/remotes/origin/master to be the predecessor of c2388 instead of c2388. Then I could do a git fetch. The git fetch failed a few times for conflicts on empty objects. I removed each of these empty objects until git fetch succeeded. That has healed the repository. A: I got this error after my (Windows) machine decided to reboot itself. Thankfully my remote repository was up to date, so I just did a fresh Git clone... A: We just had the case here. It happened that the problem was the ownership of the corrupt file was root instead of our normal user. This was caused by a commit done on the server after someone has done a "sudo su --". First, identify your corrupt file with: $> git fsck --full You should receive a answer like this one: fatal: loose object 11b25a9d10b4144711bf616590e171a76a35c1f9 (stored in .git/objects/11/b25a9d10b4144711bf616590e171a76a35c1f9) is corrupt Go in the folder where the corrupt file is and do a: $> ls -la Check the ownership of the corrupt file. If that's different, just go back to the root of your repo and do a: $> sudo chown -R YOURCORRECTUSER:www-data .git/ Hope it helps! A: I solved this way: I decided to simply copy the uncorrupted object file from the backup's clone to my original repository. This worked just as well. (By the way: If you can't find the object in .git/objects/ by its name, it probably has been [packed][pack] to conserve space.) A: I had this same problem in my bare remote git repo. After much troubleshooting, I figured out one of my coworkers had made a commit in which some files in .git/objects had permissions of 440 (r--r-----) instead of 444 (r--r--r--). After asking the coworker to change the permissions with "chmod 444 -R objects" inside the bare git repo, the problem was fixed. A: I just had a problem like this. My particular problem was caused by a system crash that corrupted the most recent commit (and hence also the master branch). I hadn't pushed, and wanted to re-make that commit. In my particular case, I was able to deal with it like this: Make a backup of .git/: rsync -a .git/ git-bak/ Check .git/logs/HEAD, and find the last line with a valid commit ID. For me, this was the second most recent commit. This was good, because I still had the working directory versions of the file, and so the every version I wanted. Make a branch at that commit: git branch temp <commit-id> re-do the broken commit with the files in the working directory. git reset master temp to move the master branch to the new commit you made in step 2. git checkout master and check that it looks right with git log. git branch -d temp. git fsck --full, and it should now be safe to delete any corrupted objects that fsck finds. If it all looks good, try pushing. If that works, That worked for for me. I suspect that this is a reasonably common scenario, since the most recent commit is the most likely one to be corrupted, but if you lose one further back, you can probably still use a method like this, with careful use of git cherrypick, and the reflog in .git/logs/HEAD. A: When I had this issue I backed up my recent changes (as I knew what I had changed) then deleted that file it was complaining about in .git/location. Then I did a git pull. Take care though, this might not work for you. A: Create a backup and clone the repository into a fresh directory cp -R foo foo-backup git clone git@url:foo foo-new (optional) If you are working on a different branch than master, switch it. cd foo-new git checkout -b branch-name origin/branch-name Sync changes excluding the .git directory rsync -aP --exclude=.git foo-backup/ foo-new A: This problem usually occures when using various git clients with different versions on the same git checkout. Think of: Command line IDE build-in git Inside docker / vm container GIT gui tool Make sure you push with the same client that created the commits. A: What I did not to lose other unpushed branches: A reference to the broken object should be in refs/heads/<current_branch>. If you go to .git\logs\refs\heads\<current_branch> you can see that the last commit has the exactly same value. I copied the one from the previous commit to the first file and it solved the problem. A: This seems to be an issue with Dropbox or symlinking folders out of Dropbox for me. Probably the same for any of the other similar services. When I go to git push I'd get the Corrupt loose object error. For me, on macOS Big Sur, the fix was simply to make a recursive copy of the repo to a directory outside of Dropbox. I believe this caused Dropbox to pull the live files for the broken dynamic references. After the copy I was immediately able to git push without error. A: I had a similar issue on a Windows 10 computer with onedrive backing up my documents folder where I have my git repositories. Looking at the object in the git object directory I did not see a green checkmark but the blue sync icon for that file. All other object files appeared to have the green checkmark. Playing around, trying things, I tried selecting the option always keep this folder on this device but got an error: error 0x80071129 the tag present in the reparse point buffer is invalid. This link (https://answers.microsoft.com/en-us/msoffice/forum/all/error-0x80071129-the-tag-present-in-the-reparse/b8011cee-98c5-4c33-ba99-d0eec7c535a0) suggests to run chkdsk /r /f as an admin to fix the issue (have to reboot computer). I did that and it fixed my issue. A: I have had the same issue before. I simply get passed it by removing the object file from the .git/objects directory. For this error below. $ git fsck error: inflate: data stream error (invalid distance too far back) error: corrupt loose object '45ba4ceb93bc812ef20a6630bb27e9e0b33a012a' fatal: loose object 45ba4ceb93bc812ef20a6630bb27e9e0b33a012a (stored in .git/objects/45/ba4ceb93bc812ef20a6630bb27e9e0b33a012a) is corrupted Solution: Go to your top directory and unhide the .git folder On windows, you can do this by running this command on cmd: attrib +s +h .git Then go to .git/objects folder As mentioned on the error message above (stored in .git/objects/45/ba4ceb93bc812ef20a6630bb27e9e0b33a012a) is corrupted you can see that the object is found on a director called "45". Therefore, go to the directory .git/objects/45/ Finally find the object named ba4ceb93bc812ef20a6630bb27e9e0b33a012a and delete it. Now, you can go ahead and check with git status or git add . your change and proceed. A: Have the same issue after my linux mint crash, and I press power button to shutdown my laptop, that's why my .git is corrupt find .git/objects/ -empty -delete After that, I get error fatal: Bad object head. I just Reinitialized my git git init And fetch from remote repo git fetch To check your git, use git status And it's work again. I don't lose my local changes, so I can commit without rewriting code A: I had the exact same error and managed to get my repo back without losing my changes. I do not know if it could work for others as corruption reason can be multiple, but it's worth trying I: Made several backups of the corrupt git repository just in case Cloned the lasted pushed version from the remote repository Copied all the files from the corrupt .git folder EXCEPT all files related to HEAD, FETCH_HEAD, ORG_HEAD etc ... the most important are the refs, obj, and index Ended up with a valid history, but corrupt index, applied the solution from this post How to resolve "Error: bad index – Fatal: index file corrupt" when using Git And my repository was back working ... To make sure I did not push anything wrong, I cloned again from the remote, checked-out the changes I wanted to save from the restored repository, and comited them fresh.
Git: "Corrupt loose object"
Whenever I pull from my remote, I get the following error about compression. When I run the manual compression, I get the same: $ git gc error: Could not read 3813783126d41a3200b35b6681357c213352ab31 fatal: bad tree object 3813783126d41a3200b35b6681357c213352ab31 error: failed to run repack Does anyone know, what to do about that? From cat-file I get this: $ git cat-file -t 3813783126d41a3200b35b6681357c213352ab31 error: unable to find 3813783126d41a3200b35b6681357c213352ab31 fatal: git cat-file 3813783126d41a3200b35b6681357c213352ab31: bad file And from git fsck I get this ( don't know if it's actually related): $ git fsck error: inflate: data stream error (invalid distance too far back) error: corrupt loose object '45ba4ceb93bc812ef20a6630bb27e9e0b33a012a' fatal: loose object 45ba4ceb93bc812ef20a6630bb27e9e0b33a012a (stored in .git/objects/45/ba4ceb93bc812ef20a6630bb27e9e0b33a012a) is corrupted Can anyone help me decipher this?
[ "I had the same problem (don't know why).\nThis fix requires access to an uncorrupted remote copy of the repository, and will keep your locally working copy intact.\nBut it has some drawbacks:\n\nYou will lose the record of any commits that were not pushed, and will have to recommit them.\nYou will lose any stashes.\n\nThe fix\nExecute these commands from the parent directory above your repo (replace 'foo' with the name of your project folder):\n\nCreate a backup of the corrupt directory:\ncp -R foo foo-backup\nMake a new clone of the remote repository to a new directory:\ngit clone [email protected]:foo foo-newclone\nDelete the corrupt .git subdirectory:\nrm -rf foo/.git\nMove the newly cloned .git subdirectory into foo:\nmv foo-newclone/.git foo\nDelete the rest of the temporary new clone:\nrm -rf foo-newclone\n\nOn Windows you will need to use:\n\ncopy instead of cp -R \nrmdir /S instead of rm -rf\nmove instead of mv\n\nNow foo has its original .git subdirectory back, but all the local changes are still there. git status, commit, pull, push, etc. work again as they should.\n", "Your best bet is probably to simply re-clone from the remote repository (i.e., GitHub or other). Unfortunately you will lose any unpushed commits and stashed changes, however your working copy should remain intact.\nFirst make a backup copy of your local files. Then do this from the root of your working tree:\nrm -fr .git\ngit init\ngit remote add origin [your-git-remote-url]\ngit fetch\ngit reset --mixed origin/master\ngit branch --set-upstream-to=origin/master master\n\nThen commit any changed files as necessary.\n", "Working on a VM, in my notebook, battery died, got this error;\n\nerror: object file .git/objects/ce/theRef is empty error: object\n file .git/objects/ce/theRef is empty fatal: loose object theRef \n (stored in .git/objects/ce/theRef) is corrupt\n\nI managed to get the repo working again with only 2 commands and without losing my work (modified files/uncommitted changes)\nfind .git/objects/ -size 0 -exec rm -f {} \\;\ngit fetch origin\n\nAfter that I ran a git status, the repo was fine and there were my changes (waiting to be committed, do it now..).\ngit version 1.9.1\nRemember to backup all changes you remember, just in case this solution doesn't works and a more radical approach is needed.\n", "Looks like you have a corrupt tree object. You will need to get that object from someone else. Hopefully they will have an uncorrupted version.\nYou could actually reconstruct it if you can't find a valid version from someone else by guessing at what files should be there. You may want to see if the dates & times of the objects match up to it. Those could be the related blobs. You could infer the structure of the tree object from those objects.\nTake a look at Scott Chacon's Git Screencasts regarding git internals. This will show you how git works under the hood and how to go about doing this detective work if you are really stuck and can't get that object from someone else.\n", "My computer crashed while I was writing a commit message. After rebooting, the working tree was as I had left it and I was able to successfully commit my changes.\nHowever, when I tried to run git status I got\nerror: object file .git/objects/xx/12345 is empty\nfatal: loose object xx12345 (stored in .git/objects/xx/12345 is corrupt\n\nUnlike most of the other answers, I wasn't trying to recover any data. I just needed Git to stop complaining about the empty object file.\nOverview\nThe \"object file\" is Git's hashed representation of a real file that you care about. Git thinks it should have a hashed version of some/file.whatever stored in .git/object/xx/12345, and fixing the error turned out to be mostly a matter of figuring out which file the \"loose object\" was supposed to represent.\nDetails\nPossible options seemed to be\n\nDelete the empty file\nGet the file into a state acceptable to Git\n\nApproach 1: Remove the object file\nThe first thing I tried was just moving the object file\nmv .git/objects/xx/12345 ..\n\nThat didn't work - Git began complaining about a broken link. On to Approach 2.\nApproach 2: Fix the file\nLinus Torvalds has a great writeup of how to recover an object file that solved the problem for me. Key steps are summarized here.\n$> # Find out which file the blob object refers to\n$> git fsck\nbroken link from tree 2d9263c6d23595e7cb2a21e5ebbb53655278dff8\n to blob xx12345\nmissing blob xx12345\n\n$> git ls-tree 2d926\n...\n10064 blob xx12345 your_file.whatever\n\nThis tells you what file the empty object is supposed to be a hash of. Now you can repair it.\n$> git hash-object -w path/to/your_file.whatever\n\nAfter doing this I checked .git/objects/xx/12345, it was no longer empty, and Git stopped complaining.\n", "Try\ngit stash\n\nThis worked for me. It stashes anything you haven't committed and that got around the problem.\n", "A garbage collection fixed my problem:\ngit gc --aggressive --prune=now\n\nIt takes a while to complete, but every loose object and/or corrupted index was fixed.\n", "simply running a git prune fixed this issue for me\n", "I encountered this once my system crashed. What I did is this:\n(Please note your corrupt commits are lost, but changes are retained. You might have to recreate those commits at the end of this procedure)\n\nBackup your code.\nGo to your working directory and delete the .git folder.\nNow clone the remote in another location and copy the .git folder in it.\nPaste it in your working directory.\nCommit as you wanted.\n\n", "I just experienced this - my machine crashed whilst writing to the Git repo, and it became corrupted. I fixed it as follows.\nI started with looking at how many commits I had not pushed to the remote repo, thus:\ngitk &\n\nIf you don't use this tool it is very handy - available on all operating systems as far as I know. This indicated that my remote was missing two commits. I therefore clicked on the label indicating the latest remote commit (usually this will be /remotes/origin/master) to get the hash (the hash is 40 chars long, but for brevity I am using 10 here - this usually works anyway).\nHere it is:\n\n14c0fcc9b3\n\nI then click on the following commit (i.e. the first one that the remote does not have) and get the hash there:\n\n04d44c3298\n\nI then use both of these to make a patch for this commit:\ngit diff 14c0fcc9b3 04d44c3298 > 1.patch\n\nI then did likewise with the other missing commit, i.e. I used the hash of the commit before and the hash of the commit itself:\ngit diff 04d44c3298 fc1d4b0df7 > 2.patch\n\nI then moved to a new directory, cloned the repo from the remote:\ngit clone [email protected]:username/repo.git\n\nI then moved the patch files into the new folder, and applied them and committed them with their exact commit messages (these can be pasted from git log or the gitk window):\npatch -p1 < 1.patch\ngit commit\n\npatch -p1 < 2.patch\ngit commit\n\nThis restored things for me (and note there's probably a faster way to do it for a large number of commits). However I was keen to see if the tree in the corrupted repo can be repaired, and the answer is it can. With a repaired repo available as above, run this command in the broken folder:\ngit fsck \n\nYou will get something like this:\nerror: object file .git/objects/ca/539ed815fefdbbbfae6e8d0c0b3dbbe093390d is empty\nerror: unable to find ca539ed815fefdbbbfae6e8d0c0b3dbbe093390d\nerror: sha1 mismatch ca539ed815fefdbbbfae6e8d0c0b3dbbe093390d\n\nTo do the repair, I would do this in the broken folder:\nrm .git/objects/ca/539ed815fefdbbbfae6e8d0c0b3dbbe093390d\ncp ../good-repo/.git/objects/ca/539ed815fefdbbbfae6e8d0c0b3dbbe093390d .git/objects/ca/539ed815fefdbbbfae6e8d0c0b3dbbe093390d\n\ni.e. remove the corrupted file and replace it with a good one. You may have to do this several times. Finally there will be a point where you can run fsck without errors. You will probably have \"dangling commit\" and \"dangling blob\" lines in the report, these are a consequence of your rebases and amends in this folder, and are OK. The garbage collector will remove them in due course.\nThus (at least in my case) a corrupted tree does not mean unpushed commits are lost.\n", "The answer of user1055643 is missing the last step:\nrm -fr .git\ngit init\ngit remote add origin your-git-remote-url\ngit fetch\ngit reset --hard origin/master\ngit branch --set-upstream-to=origin/master master\n\n", "The solution offered by Felipe Pereira (above) in addition to Stephan's comment to that answer with the name of the branch I was on when the objects got corrupted is what worked for me.\nfind .git/objects/ -size 0 -exec rm -f {} \\;\ngit fetch origin\ngit symbolic-ref HEAD refs/heads/${BRANCH_NAME}\n\n", "Runnning git stash; git stash pop fixed my problem\n", "I followed many of the other steps here; Linus' description of how to look at the git tree/objects and find what's missing was especially helpful. git-git recover corrupted blob\nBut in the end, for me, I had loose/corrupt tree objects caused by a partial disk failure, and tree objects are not so easily recovered/not covered by that doc.\nIn the end, I moved the conflicting objects/<ha>/<hash> out of the way, and used git unpack-objects with a pack file from a reasonably up to date clone. It was able to restore the missing tree objects.\nStill left me with a lot of dangling blobs, which can be a side effect of unpacking previously archived stuff, and addressed in other questions here\n", "I was getting a corrupt loose object error as well.\n./objects/x/x\n\nI successfully fixed it by going into the directory of the corrupt object. I saw that the users assigned to that object was not my git user's. I don't know how it happened, but I ran a chown git:git on that file and then it worked again.\nThis may be a potential fix for some peoples' issues but not necessary all of them.\n", "To me this happened due to a power failure while doing a git push.\nThe messages looked like this:\n$ git status\nerror: object file .git/objects/c2/38824eb3fb602edc2c49fccb535f9e53951c74 is empty\nerror: object file .git/objects/c2/38824eb3fb602edc2c49fccb535f9e53951c74 is empty\nfatal: loose object c238824eb3fb602edc2c49fccb535f9e53951c74 (stored in .git/objects/c2/38824eb3fb602edc2c49fccb535f9e53951c74) is corrupt\n\nI tried things like git fsck but that didn't help.\nSince the crash happened during a git push, it obviously happened during rewrite on the client side which happens after the server is updated. I looked around and figured that c2388 in my case was a commit object, because it was referred to by entries in .git/refs. So I knew that I would be able to find c2388 when I look at the history (through a web interface or second clone).\nOn the second clone I did a git log -n 2 c2388 to identify the predecessor of c2388. Then I manually modified .git/refs/heads/master and .git/refs/remotes/origin/master to be the predecessor of c2388 instead of c2388.\nThen I could do a git fetch.\nThe git fetch failed a few times for conflicts on empty objects. I removed each of these empty objects until git fetch succeeded. That has healed the repository.\n", "I got this error after my (Windows) machine decided to reboot itself.\nThankfully my remote repository was up to date, so I just did a fresh Git clone...\n", "We just had the case here. It happened that the problem was the ownership of the corrupt file was root instead of our normal user. This was caused by a commit done on the server after someone has done a \"sudo su --\".\nFirst, identify your corrupt file with:\n$> git fsck --full\n\nYou should receive a answer like this one:\nfatal: loose object 11b25a9d10b4144711bf616590e171a76a35c1f9 (stored in .git/objects/11/b25a9d10b4144711bf616590e171a76a35c1f9) is corrupt\n\nGo in the folder where the corrupt file is and do a:\n$> ls -la\n\nCheck the ownership of the corrupt file. If that's different, just go back to the root of your repo and do a:\n$> sudo chown -R YOURCORRECTUSER:www-data .git/\n\nHope it helps!\n", "I solved this way:\nI decided to simply copy the uncorrupted object file from the backup's clone to my original repository. This worked just as well. (By the way: If you can't find the object in .git/objects/ by its name, it probably has been [packed][pack] to conserve space.)\n", "I had this same problem in my bare remote git repo. After much troubleshooting, I figured out one of my coworkers had made a commit in which some files in .git/objects had permissions of 440 (r--r-----) instead of 444 (r--r--r--). After asking the coworker to change the permissions with \"chmod 444 -R objects\" inside the bare git repo, the problem was fixed.\n", "I just had a problem like this. My particular problem was caused by a system crash that corrupted the most recent commit (and hence also the master branch). I hadn't pushed, and wanted to re-make that commit. In my particular case, I was able to deal with it like this:\n\nMake a backup of .git/: rsync -a .git/ git-bak/\nCheck .git/logs/HEAD, and find the last line with a valid commit ID. For me, this was the second most recent commit. This was good, because I still had the working directory versions of the file, and so the every version I wanted.\nMake a branch at that commit: git branch temp <commit-id>\nre-do the broken commit with the files in the working directory.\ngit reset master temp to move the master branch to the new commit you made in step 2.\ngit checkout master and check that it looks right with git log.\ngit branch -d temp.\ngit fsck --full, and it should now be safe to delete any corrupted objects that fsck finds. \nIf it all looks good, try pushing. If that works, \n\nThat worked for for me. I suspect that this is a reasonably common scenario, since the most recent commit is the most likely one to be corrupted, but if you lose one further back, you can probably still use a method like this, with careful use of git cherrypick, and the reflog in .git/logs/HEAD.\n", "When I had this issue I backed up my recent changes (as I knew what I had changed) then deleted that file it was complaining about in .git/location. Then I did a git pull. Take care though, this might not work for you.\n", "Create a backup and clone the repository into a fresh directory\ncp -R foo foo-backup\ngit clone git@url:foo foo-new\n\n(optional) If you are working on a different branch than master, switch it.\ncd foo-new\ngit checkout -b branch-name origin/branch-name\n\nSync changes excluding the .git directory\nrsync -aP --exclude=.git foo-backup/ foo-new\n\n", "This problem usually occures when using various git clients with different versions on the same git checkout. Think of:\n\nCommand line\nIDE build-in git\nInside docker / vm container\nGIT gui tool\n\nMake sure you push with the same client that created the commits.\n", "What I did not to lose other unpushed branches:\nA reference to the broken object should be in refs/heads/<current_branch>. If you go to .git\\logs\\refs\\heads\\<current_branch> you can see that the last commit has the exactly same value. I copied the one from the previous commit to the first file and it solved the problem.\n", "This seems to be an issue with Dropbox or symlinking folders out of Dropbox for me. Probably the same for any of the other similar services. When I go to git push I'd get the Corrupt loose object error. For me, on macOS Big Sur, the fix was simply to make a recursive copy of the repo to a directory outside of Dropbox. I believe this caused Dropbox to pull the live files for the broken dynamic references. After the copy I was immediately able to git push without error.\n", "I had a similar issue on a Windows 10 computer with onedrive backing up my documents folder where I have my git repositories.\nLooking at the object in the git object directory I did not see a green checkmark but the blue sync icon for that file. All other object files appeared to have the green checkmark. Playing around, trying things, I tried selecting the option always keep this folder on this device but got an error: error 0x80071129 the tag present in the reparse point buffer is invalid.\nThis link (https://answers.microsoft.com/en-us/msoffice/forum/all/error-0x80071129-the-tag-present-in-the-reparse/b8011cee-98c5-4c33-ba99-d0eec7c535a0) suggests to run chkdsk /r /f as an admin to fix the issue (have to reboot computer). I did that and it fixed my issue.\n", "I have had the same issue before.\nI simply get passed it by removing the object file from the .git/objects directory.\nFor this error below.\n$ git fsck\nerror: inflate: data stream error (invalid distance too far back)\nerror: corrupt loose object '45ba4ceb93bc812ef20a6630bb27e9e0b33a012a'\nfatal: loose object 45ba4ceb93bc812ef20a6630bb27e9e0b33a012a (stored in .git/objects/45/ba4ceb93bc812ef20a6630bb27e9e0b33a012a) is corrupted\n\nSolution:\n\nGo to your top directory and unhide the .git folder\n\n\nOn windows, you can do this by running this command on cmd: attrib +s +h .git\n\n\nThen go to .git/objects folder\n\nAs mentioned on the error message above (stored in .git/objects/45/ba4ceb93bc812ef20a6630bb27e9e0b33a012a) is corrupted\nyou can see that the object is found on a director called \"45\". Therefore, go to the directory .git/objects/45/\n\nFinally find the object named ba4ceb93bc812ef20a6630bb27e9e0b33a012a and delete it.\n\n\nNow, you can go ahead and check with git status or git add . your change and proceed.\n", "Have the same issue after my linux mint crash, and I press power button to shutdown my laptop, that's why my .git is corrupt\nfind .git/objects/ -empty -delete\n\nAfter that, I get error fatal: Bad object head. I just Reinitialized my git\ngit init\n\nAnd fetch from remote repo\ngit fetch\n\nTo check your git, use\ngit status\n\nAnd it's work again. I don't lose my local changes, so I can commit without rewriting code\n", "I had the exact same error and managed to get my repo back without losing my changes.\nI do not know if it could work for others as corruption reason can be multiple, but it's worth trying\nI:\n\nMade several backups of the corrupt git repository just in case\nCloned the lasted pushed version from the remote repository\nCopied all the files from the corrupt .git folder EXCEPT all files related to HEAD, FETCH_HEAD, ORG_HEAD etc ... the most important are the refs, obj, and index\nEnded up with a valid history, but corrupt index, applied the solution from this post How to resolve \"Error: bad index – Fatal: index file corrupt\" when using Git\n\nAnd my repository was back working ...\nTo make sure I did not push anything wrong, I cloned again from the remote, checked-out the changes I wanted to save from the restored repository, and comited them fresh.\n" ]
[ 501, 397, 329, 69, 52, 16, 16, 9, 6, 5, 4, 4, 3, 3, 3, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "You don't need to clone and you don't need to lose your uncommited changes. Just remove .git folder with git rm -rf .git/ and then restore the git folder by initiating a new repo, setting remote and resetting head. I have added instructions for restoring removed git folder here:\nhttps://stackoverflow.com/a/67610397/7584643\n", "Just remove .git folder and add it again. This simple solution worked for me.\n" ]
[ -1, -8 ]
[ "git", "version_control" ]
stackoverflow_0004254389_git_version_control.txt
Q: TypeError: undefined is not an object (evaluating '_this.camera = _ref') -App dev in React Native- Hello, I have a problem with Expo Camera. Here an error is referred when you want to take a picture. "TypeError: undefined is not an object (evaluating '_this.camera = _ref')" / Scan.js. If the app is freshly updated with Expo, everything works. But as soon as you continue programming and another error occurs, this error appears and doesn't go away until you refresh the app again. I have tried a lot, but I need help here. Scan.js import React, { Component, useState, useEffect } from 'react'; import { View, Text, StyleSheet, TouchableOpacity, Image } from 'react-native'; import {launchCamera, launchImageLibrary} from 'react-native-image-picker'; import {Camera, Constants} from 'expo-camera'; import * as MediaLibrary from 'expo-media-library'; import * as Haptics from 'expo-haptics'; import Images from '../assets/icon/index' const Scan = () => { const [hasPermission, setHasPermission] = useState(null); const [type, setType] = useState(Camera.Constants.Type.back); const [status, requestPermission] = MediaLibrary.usePermissions(); useEffect(() => { (async () => { const { status } = await Camera.requestCameraPermissionsAsync(); setHasPermission(status === 'granted'); })(); }, []); if (hasPermission === null) { return <View/>; } if (hasPermission === false) { return <Text>No access to camera</Text>; } takePicture = async () => { if (this.camera) { let photo = await this.camera.takePictureAsync(); Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium); console.log(photo.uri); MediaLibrary.saveToLibraryAsync(photo.uri); } }; return ( <View style={styles.container}> <Camera style={styles.camera} type={type} ref={ref => { this.camera = ref; }}> <View style={styles.buttonContainer}> <TouchableOpacity style={styles.button} onPress={() => { setType( type === Camera.Constants.Type.back ? Camera.Constants.Type.front : Camera.Constants.Type.back ); }} > <Image source={Images.camera} style={styles.icon}></Image> </TouchableOpacity> <TouchableOpacity style={styles.button} onPress={takePicture} > <Text style={styles.text}>Take</Text> </TouchableOpacity> </View> </Camera> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, }, camera: { flex: 1, }, buttonContainer: { flex: 1, backgroundColor: 'transparent', flexDirection: 'row', margin: 20, top: 0, }, button: { flex: 0.1, alignSelf: 'flex-end', alignItems: 'center', }, text: { fontSize: 18, color: 'white', }, icon : { tintColor: 'white', }, }) export default Scan; ``` A: Create a new camera reference and attach it to the Camera component. import { useRef } from 'react'; ... const cameraRef = useRef<Camera>(null); ... <Camera ref={cameraRef} ... /> In your takePicture function replace this.camera.takePictureAsync with cameraRef.current?.takePictureAsync A: Error: Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref. This is because the guy who answered used TypeScript. Simply replace const cameraRef = useRef(null); with const cameraRef = useRef(null);
TypeError: undefined is not an object (evaluating '_this.camera = _ref')
-App dev in React Native- Hello, I have a problem with Expo Camera. Here an error is referred when you want to take a picture. "TypeError: undefined is not an object (evaluating '_this.camera = _ref')" / Scan.js. If the app is freshly updated with Expo, everything works. But as soon as you continue programming and another error occurs, this error appears and doesn't go away until you refresh the app again. I have tried a lot, but I need help here. Scan.js import React, { Component, useState, useEffect } from 'react'; import { View, Text, StyleSheet, TouchableOpacity, Image } from 'react-native'; import {launchCamera, launchImageLibrary} from 'react-native-image-picker'; import {Camera, Constants} from 'expo-camera'; import * as MediaLibrary from 'expo-media-library'; import * as Haptics from 'expo-haptics'; import Images from '../assets/icon/index' const Scan = () => { const [hasPermission, setHasPermission] = useState(null); const [type, setType] = useState(Camera.Constants.Type.back); const [status, requestPermission] = MediaLibrary.usePermissions(); useEffect(() => { (async () => { const { status } = await Camera.requestCameraPermissionsAsync(); setHasPermission(status === 'granted'); })(); }, []); if (hasPermission === null) { return <View/>; } if (hasPermission === false) { return <Text>No access to camera</Text>; } takePicture = async () => { if (this.camera) { let photo = await this.camera.takePictureAsync(); Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium); console.log(photo.uri); MediaLibrary.saveToLibraryAsync(photo.uri); } }; return ( <View style={styles.container}> <Camera style={styles.camera} type={type} ref={ref => { this.camera = ref; }}> <View style={styles.buttonContainer}> <TouchableOpacity style={styles.button} onPress={() => { setType( type === Camera.Constants.Type.back ? Camera.Constants.Type.front : Camera.Constants.Type.back ); }} > <Image source={Images.camera} style={styles.icon}></Image> </TouchableOpacity> <TouchableOpacity style={styles.button} onPress={takePicture} > <Text style={styles.text}>Take</Text> </TouchableOpacity> </View> </Camera> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, }, camera: { flex: 1, }, buttonContainer: { flex: 1, backgroundColor: 'transparent', flexDirection: 'row', margin: 20, top: 0, }, button: { flex: 0.1, alignSelf: 'flex-end', alignItems: 'center', }, text: { fontSize: 18, color: 'white', }, icon : { tintColor: 'white', }, }) export default Scan; ```
[ "Create a new camera reference and attach it to the Camera component.\nimport { useRef } from 'react';\n...\nconst cameraRef = useRef<Camera>(null);\n...\n<Camera ref={cameraRef} ... />\n\nIn your takePicture function replace this.camera.takePictureAsync with cameraRef.current?.takePictureAsync\n", "Error: Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref.\nThis is because the guy who answered used TypeScript.\nSimply replace\nconst cameraRef = useRef(null);\nwith\nconst cameraRef = useRef(null);\n" ]
[ 0, 0 ]
[]
[]
[ "expo_camera", "javascript", "react_native" ]
stackoverflow_0071459069_expo_camera_javascript_react_native.txt
Q: NativeBase Content not rendered in Jest with react-native-testing-library I have some react-native/expo with native-base code that runs normally on the phone or emulator. I tried creating a test for it using jest and react-native-testing-library. When doing so, whatever is inside the from native-base is not rendered and cannot be found in the test. Has anyone been through this and would know a solution so the children of Content are rendered during testing? An example code is below to illustrate what I am saying. Thank you very much for the help. import { render } from 'react-native-testing-library'; import { Content, Container, Text } from 'native-base'; class App extends React.Component { render() { return ( <Container> <Content> <Text testID="textId">Hello</Text> </Content> </Container> ); } } describe('Testing Content', () => { const { queryByTestId } = render(<App />) it('renders text inside content', () => { expect(queryByTestId('textId')).not.toBeNull() }); }) The versions of the packages are: "expo": "^32.0.0", "react": "16.5.0", "native-base": "^2.12.1", "jest-expo": "^32.0.0", "react-native-testing-library": "^1.7.0" A: I asked the question in the react-native-testing-library in github (https://github.com/callstack/react-native-testing-library/issues/118). The issue is with react-native-keyboard-aware-scroll-view To solve it, we can mock it the following way jest.mock('react-native-keyboard-aware-scroll-view', () => { const KeyboardAwareScrollView = ({ children }) => children; return { KeyboardAwareScrollView }; }); I also put an example here for whoever might be looking: https://github.com/pedrohbtp/rntl-content-bug A: Update 2022 I found the solution in their docs: To fix the above issue, you can simply pass initialWindowMetrics to NativeBaseProvider in your tests. const inset = { frame: { x: 0, y: 0, width: 0, height: 0 }, insets: { top: 0, left: 0, right: 0, bottom: 0 }, }; <NativeBaseProvider initialWindowMetrics={inset}> {children} </NativeBaseProvider>;
NativeBase Content not rendered in Jest with react-native-testing-library
I have some react-native/expo with native-base code that runs normally on the phone or emulator. I tried creating a test for it using jest and react-native-testing-library. When doing so, whatever is inside the from native-base is not rendered and cannot be found in the test. Has anyone been through this and would know a solution so the children of Content are rendered during testing? An example code is below to illustrate what I am saying. Thank you very much for the help. import { render } from 'react-native-testing-library'; import { Content, Container, Text } from 'native-base'; class App extends React.Component { render() { return ( <Container> <Content> <Text testID="textId">Hello</Text> </Content> </Container> ); } } describe('Testing Content', () => { const { queryByTestId } = render(<App />) it('renders text inside content', () => { expect(queryByTestId('textId')).not.toBeNull() }); }) The versions of the packages are: "expo": "^32.0.0", "react": "16.5.0", "native-base": "^2.12.1", "jest-expo": "^32.0.0", "react-native-testing-library": "^1.7.0"
[ "I asked the question in the react-native-testing-library in github (https://github.com/callstack/react-native-testing-library/issues/118).\nThe issue is with react-native-keyboard-aware-scroll-view\nTo solve it, we can mock it the following way\njest.mock('react-native-keyboard-aware-scroll-view', () => {\n const KeyboardAwareScrollView = ({ children }) => children;\n return { KeyboardAwareScrollView };\n});\n\nI also put an example here for whoever might be looking:\nhttps://github.com/pedrohbtp/rntl-content-bug\n", "Update 2022\nI found the solution in their docs:\nTo fix the above issue, you can simply pass initialWindowMetrics to NativeBaseProvider in your tests.\nconst inset = {\n frame: { x: 0, y: 0, width: 0, height: 0 },\n insets: { top: 0, left: 0, right: 0, bottom: 0 },\n};\n\n<NativeBaseProvider initialWindowMetrics={inset}>\n {children}\n</NativeBaseProvider>;\n\n" ]
[ 6, 0 ]
[]
[]
[ "expo", "jestjs", "native_base", "react_native", "react_testing_library" ]
stackoverflow_0056333004_expo_jestjs_native_base_react_native_react_testing_library.txt
Q: Adding Rows to Tables not specified in the If Statement I am trying to add values to the end of a table in Excel. When I run the Macro, a row is added to each of the tables, even through the values are only added to the table specified in the If Statement. Code is below: Sub AddQuoteNumbers() 'ListObject is a Table in a Worksheet' Dim tbl As ListObject Dim tb2 As ListObject Dim tb3 As ListObject Set tbl = Worksheets("quote1").ListObjects("Table1") Set tb2 = Worksheets("quote2").ListObjects("Table2") Set tb3 = Worksheets("quote3").ListObjects("Table3") 'ListRows allows us to Add or Delete Rows' Dim NewRow1 As ListRow Dim NewRow2 As ListRow Dim NewRow3 As ListRow Set NewRow1 = tbl.ListRows.Add Set NewRow2 = tb2.ListRows.Add Set NewRow3 = tb3.ListRows.Add If Worksheets("Template").Range("H5") = "quote1" Then With NewRow1 .Range(1) = Worksheets("Template").Range("B9") .Range(3) = Worksheets("Template").Range("B8") .Range(4) = Worksheets("Template").Range("H4") .Range(5) = Worksheets("Template").Range("B13") End With Else If Worksheets("Template").Range("H5") = "quote2" Then With NewRow2 .Range(1) = Worksheets("Template").Range("B9") .Range(3) = Worksheets("Template").Range("B8") .Range(4) = Worksheets("Template").Range("H4") .Range(5) = Worksheets("Template").Range("B13") End With Else If Worksheets("Template").Range("H5") = "quote3" Then With NewRow3 .Range(1) = Worksheets("Template").Range("B9") .Range(3) = Worksheets("Template").Range("B8") .Range(4) = Worksheets("Template").Range("H4") .Range(5) = Worksheets("Template").Range("B13") End With End If End If End If End Sub I only want a row to be added to the table specified by the If/With Statement. If the value in H5 = "quote1" I only want it added to quote1 table. A: New Row (ListRow) in Excel Table (ListObject) Step by Step Sub AddQuoteNumbers() ' Define constants... Const SRC_NAME As String = "Template" Const SRC_DST_NAME_CELL As String = "H5" ' ... and pairs of constant arrays. Dim dwsNames() As Variant: dwsNames = VBA.Array("Quote1", "Quote2", "Quote3") Dim dloNames() As Variant: dloNames = VBA.Array("Table1", "Table2", "Table3") Dim dColumns() As Variant: dColumns = VBA.Array(1, 3, 4, 5) Dim sAddresses() As Variant: sAddresses = VBA.Array("B9", "B8", "H4", "H13") ' Reference the workbook. Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code ' From the source worksheet, retrieve the destination worksheet name... Dim sws As Worksheet: Set sws = wb.Sheets(SRC_NAME) Dim dwsName As String: dwsName = CStr(sws.Range(SRC_DST_NAME_CELL).Value) ' ... and attempt to match it against the names in the 'dwsNames' array. Dim dwsIndex As Variant: dwsIndex = Application.Match(dwsName, dwsNames, 0) ' Check if there was no match. Then inform of failure and exit. If IsError(dwsIndex) Then MsgBox "Worksheet """ & dwsName & """ is not in the list:" _ & vbLf & Join(dwsNames, vbLf), vbExclamation Exit Sub End If ' Since there was a match, add a new row in the destination table. Dim n As Long: n = CLng(dwsIndex) - 1 ' the arrays are zero-based Dim dws As Worksheet: Set dws = wb.Sheets(dwsName) ' = dwsNames(n) Dim dlo As ListObject: Set dlo = dws.ListObjects(dloNames(n)) Dim dlr As ListRow: Set dlr = dlo.ListRows.Add ' Write the values from the source cells to the new destination table row. With dlr.Range For n = 0 To UBound(dColumns) ' = UBound(sAddresses) .Cells(dColumns(n)).Value = sws.Range(sAddresses(n)).Value Next n End With ' Inform of success. MsgBox "Added new row to table """ & dlo.Name & """ in worksheet """ _ & dws.Name & """.", vbInformation End Sub
Adding Rows to Tables not specified in the If Statement
I am trying to add values to the end of a table in Excel. When I run the Macro, a row is added to each of the tables, even through the values are only added to the table specified in the If Statement. Code is below: Sub AddQuoteNumbers() 'ListObject is a Table in a Worksheet' Dim tbl As ListObject Dim tb2 As ListObject Dim tb3 As ListObject Set tbl = Worksheets("quote1").ListObjects("Table1") Set tb2 = Worksheets("quote2").ListObjects("Table2") Set tb3 = Worksheets("quote3").ListObjects("Table3") 'ListRows allows us to Add or Delete Rows' Dim NewRow1 As ListRow Dim NewRow2 As ListRow Dim NewRow3 As ListRow Set NewRow1 = tbl.ListRows.Add Set NewRow2 = tb2.ListRows.Add Set NewRow3 = tb3.ListRows.Add If Worksheets("Template").Range("H5") = "quote1" Then With NewRow1 .Range(1) = Worksheets("Template").Range("B9") .Range(3) = Worksheets("Template").Range("B8") .Range(4) = Worksheets("Template").Range("H4") .Range(5) = Worksheets("Template").Range("B13") End With Else If Worksheets("Template").Range("H5") = "quote2" Then With NewRow2 .Range(1) = Worksheets("Template").Range("B9") .Range(3) = Worksheets("Template").Range("B8") .Range(4) = Worksheets("Template").Range("H4") .Range(5) = Worksheets("Template").Range("B13") End With Else If Worksheets("Template").Range("H5") = "quote3" Then With NewRow3 .Range(1) = Worksheets("Template").Range("B9") .Range(3) = Worksheets("Template").Range("B8") .Range(4) = Worksheets("Template").Range("H4") .Range(5) = Worksheets("Template").Range("B13") End With End If End If End If End Sub I only want a row to be added to the table specified by the If/With Statement. If the value in H5 = "quote1" I only want it added to quote1 table.
[ "New Row (ListRow) in Excel Table (ListObject)\nStep by Step\nSub AddQuoteNumbers()\n\n ' Define constants...\n Const SRC_NAME As String = \"Template\"\n Const SRC_DST_NAME_CELL As String = \"H5\"\n ' ... and pairs of constant arrays.\n Dim dwsNames() As Variant: dwsNames = VBA.Array(\"Quote1\", \"Quote2\", \"Quote3\")\n Dim dloNames() As Variant: dloNames = VBA.Array(\"Table1\", \"Table2\", \"Table3\")\n Dim dColumns() As Variant: dColumns = VBA.Array(1, 3, 4, 5)\n Dim sAddresses() As Variant: sAddresses = VBA.Array(\"B9\", \"B8\", \"H4\", \"H13\")\n \n ' Reference the workbook.\n Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code\n \n ' From the source worksheet, retrieve the destination worksheet name...\n Dim sws As Worksheet: Set sws = wb.Sheets(SRC_NAME)\n Dim dwsName As String: dwsName = CStr(sws.Range(SRC_DST_NAME_CELL).Value)\n ' ... and attempt to match it against the names in the 'dwsNames' array.\n Dim dwsIndex As Variant: dwsIndex = Application.Match(dwsName, dwsNames, 0)\n \n ' Check if there was no match. Then inform of failure and exit.\n If IsError(dwsIndex) Then\n MsgBox \"Worksheet \"\"\" & dwsName & \"\"\" is not in the list:\" _\n & vbLf & Join(dwsNames, vbLf), vbExclamation\n Exit Sub\n End If\n \n ' Since there was a match, add a new row in the destination table.\n Dim n As Long: n = CLng(dwsIndex) - 1 ' the arrays are zero-based\n Dim dws As Worksheet: Set dws = wb.Sheets(dwsName) ' = dwsNames(n)\n Dim dlo As ListObject: Set dlo = dws.ListObjects(dloNames(n))\n Dim dlr As ListRow: Set dlr = dlo.ListRows.Add\n \n ' Write the values from the source cells to the new destination table row.\n With dlr.Range\n For n = 0 To UBound(dColumns) ' = UBound(sAddresses)\n .Cells(dColumns(n)).Value = sws.Range(sAddresses(n)).Value\n Next n\n End With\n \n ' Inform of success.\n MsgBox \"Added new row to table \"\"\" & dlo.Name & \"\"\" in worksheet \"\"\" _\n & dws.Name & \"\"\".\", vbInformation\n \nEnd Sub\n\n" ]
[ 0 ]
[]
[]
[ "excel", "vba" ]
stackoverflow_0074661040_excel_vba.txt
Q: Serve static files in development with Vite, alias and Vue 3 I'm trying to serve static files like images from Vue components and make it work both in development and production, using alias in vite.config.ts. Folder structure looks like this: --src --wwwroot Where src is the Vue app and wwwroot is where I serve static files in a .NET project. In a Vue sample project, a typical path looks like this: <img src="@/gfx/logo.svg" alt="Logo" /> Related Vite config: return defineConfig({ plugins: [vue()], resolve: { alias: { "@": fileURLToPath(new URL(isDevelopment ? "./" : "./wwwroot", import.meta.url)), } }, base: isDevelopment ? "/" : "/dist/", build: { outDir: "wwwroot/dist/", rollupOptions: { input: "./src/main.ts", } }, root: "./", publicDir: "public", server: { host: "localhost", port: 1000, stictPort: true, } }); tsconfig.json compilerOptions: { "include": ["src/shims-vue.d.ts", "src/env.d.ts", "src/**/*", "src/**/*.vue", "src/**/*.ts","src/**/*.js"], "baseUrl": "./", "paths": { "@/*": ["./src/*"], }, "allowJs": true, //... } With this config, production build will be correct. However development build, no matter what I do, will have wrong urls for static content. For instance, a path might look like this: /@fs/assets/gfx/logo.svg (when @ is an alias for ./) or even worse using alias mapping to ".", "/" or anything else I try. How can I make this work in both dev and production? Thanks! A: It looks like you are using the @ alias to point to different directories depending on whether your app is running in development or production. In development, the @ alias points to ./, and in production, it points to ./wwwroot. To make this work in both development and production, you can use a variable to store the correct directory path and use this variable in both the alias and base properties in the Vite configuration. Here's an example: const isDevelopment = process.env.NODE_ENV === "development"; const staticFilesDir = isDevelopment ? "./" : "./wwwroot"; return defineConfig({ plugins: [vue()], resolve: { alias: { "@": fileURLToPath(new URL(staticFilesDir, import.meta.url)), } }, base: staticFilesDir, // ... other Vite configuration options }); You can also simplify your tsconfig.json file by using the "composite": true option, which allows you to use the @ alias in your TypeScript files without needing to specify the paths property. Here's an example tsconfig.json file: { "compilerOptions": { "include": ["src/**/*"], "baseUrl": "./", "allowJs": true, "composite": true, // ... other compiler options } } This way, you can use the @ alias in your TypeScript files and Vite will automatically resolve it to the correct directory. For example, you can use @/gfx/logo.svg to reference your logo image file in both development and production.
Serve static files in development with Vite, alias and Vue 3
I'm trying to serve static files like images from Vue components and make it work both in development and production, using alias in vite.config.ts. Folder structure looks like this: --src --wwwroot Where src is the Vue app and wwwroot is where I serve static files in a .NET project. In a Vue sample project, a typical path looks like this: <img src="@/gfx/logo.svg" alt="Logo" /> Related Vite config: return defineConfig({ plugins: [vue()], resolve: { alias: { "@": fileURLToPath(new URL(isDevelopment ? "./" : "./wwwroot", import.meta.url)), } }, base: isDevelopment ? "/" : "/dist/", build: { outDir: "wwwroot/dist/", rollupOptions: { input: "./src/main.ts", } }, root: "./", publicDir: "public", server: { host: "localhost", port: 1000, stictPort: true, } }); tsconfig.json compilerOptions: { "include": ["src/shims-vue.d.ts", "src/env.d.ts", "src/**/*", "src/**/*.vue", "src/**/*.ts","src/**/*.js"], "baseUrl": "./", "paths": { "@/*": ["./src/*"], }, "allowJs": true, //... } With this config, production build will be correct. However development build, no matter what I do, will have wrong urls for static content. For instance, a path might look like this: /@fs/assets/gfx/logo.svg (when @ is an alias for ./) or even worse using alias mapping to ".", "/" or anything else I try. How can I make this work in both dev and production? Thanks!
[ "It looks like you are using the @ alias to point to different directories depending on whether your app is running in development or production. In development, the @ alias points to ./, and in production, it points to ./wwwroot.\nTo make this work in both development and production, you can use a variable to store the correct directory path and use this variable in both the alias and base properties in the Vite configuration. Here's an example:\nconst isDevelopment = process.env.NODE_ENV === \"development\";\nconst staticFilesDir = isDevelopment ? \"./\" : \"./wwwroot\";\n\nreturn defineConfig({\n plugins: [vue()],\n resolve: {\n alias: {\n \"@\": fileURLToPath(new URL(staticFilesDir, import.meta.url)),\n }\n },\n base: staticFilesDir,\n // ... other Vite configuration options\n});\n\nYou can also simplify your tsconfig.json file by using the \"composite\": true option, which allows you to use the @ alias in your TypeScript files without needing to specify the paths property. Here's an example tsconfig.json file:\n{\n \"compilerOptions\": {\n \"include\": [\"src/**/*\"],\n \"baseUrl\": \"./\",\n \"allowJs\": true,\n \"composite\": true,\n // ... other compiler options\n }\n}\n\nThis way, you can use the @ alias in your TypeScript files and Vite will automatically resolve it to the correct directory. For example, you can use @/gfx/logo.svg to reference your logo image file in both development and production.\n" ]
[ 0 ]
[]
[]
[ ".net", "asp.net", "vite", "vue.js", "vuejs3" ]
stackoverflow_0073950488_.net_asp.net_vite_vue.js_vuejs3.txt
Q: My object flies off the canvas when i move it instead of staying within the bounds of the canvas I'm currently trying to code a simple game for class. Right now I want my rectangle to stay within the bounds of my canvas when i move it by using a bounce function, but it doesn't seem to be working and I cant figure out why. I have tried implementing my bounce function and calling it at the top. When I move my rectangle it goes past the bounds of the canvas without staying inside and "bouncing" off the border. var canvas; var ctx; var w = 1000; var h = 700; var o1 = { x: 100, y: h/2, w: 100, h: 100, c: 0, a: 100, angle: 0, //changes angle that shape sits at distance: 10 } document.onkeydown = function(e){keypress(e, o1)} setUpCanvas(); // circle (o1); animationLoop(); function animationLoop(){ //clear clear(); //draw rect(o1); //update bounce(o1) requestAnimationFrame(animationLoop) } function bounce(o){ if(o.x+o.w/2 > w || o.x-o.w/2 < 0){ //makes shape bounce from edge instead of middle. collision detection o.changeX *= -1; //same as o.changeX = o.changeX = -1; } if(o.y+o.h/2 > h || o.y-o.h/2 <0){ o.changeY *= -1; } } function updateData(o){ o.x += o.changeX; o.y += o.changeY; } function keypress(e,o){ if (e.key == "ArrowUp"){ o.angle = 270; o.distance= 80; forward(o); } if (e.key == "ArrowDown"){ o.angle = 90; o.distance= 20; forward(o); } } function forward(o){ //makes shape able to move var cx; var cy; cx = o.distance*Math.cos(o.angle); cy = o.distance*Math.sin(o.angle) o.y += cy; } function rect(o){ var bufferx = o.x; var buffery = o.y o.x = o.x - o.w/2; o.y = o.y- o.h/2; ctx.beginPath(); //this is very important when we are changing certain ctx properties ctx.moveTo(o.x,o.y); ctx.lineTo(o.x+o.w,o.y); ctx.lineTo(o.x+o.w,o.y+o.h); ctx.lineTo(o.x, o.y+o.h); ctx.lineTo(o.x,o.y); ctx.fillStyle = "hsla("+String (o.c)+",100%,50%,"+o.a+")"; ctx.fill(); o.x = bufferx; //o.x = o.x + o.w/2; o.y = buffery;//o.y = o.y+ o.h/2; } function clear(){ ctx.clearRect(0, 0, w, h); } function randn(range){ var r = Math.random()*range-(range/2); return r } function rand(range){ var r = Math.random()*range return r } function setUpCanvas(){ canvas = document.querySelector("#myCanvas"); canvas.width = w; canvas.height = h; // canvas.style.width = "1000px"; // canvas.style.height = "700px"; canvas.style.border = "10px solid black"; ctx = canvas.getContext("2d"); } console.log("Final Assignment") A: You only need to setup changeX and changeY values in o1, since they are not initialized to work with updateData: changeX: initialX, changeY: initialY, var canvas; var ctx; var w = 1000; var h = 700; var o1 = { x: 100, y: h/2, w: 100, h: 100, c: 0, a: 100, angle: 0, //changes angle that shape sits at distance: 10, changeX: 5, // initialize with x vel changeY: 4, // initialize with y vel } document.onkeydown = function(e){keypress(e, o1)} setUpCanvas(); // circle (o1); animationLoop(); function animationLoop(){ //clear clear(); //draw rect(o1); //update bounce(o1) updateData(o1) requestAnimationFrame(animationLoop) } function bounce(o){ if(o.x+o.w/2 > w || o.x-o.w/2 < 0){ //makes shape bounce from edge instead of middle. collision detection o.changeX *= -1; //same as o.changeX = o.changeX = -1; } if(o.y+o.h/2 > h || o.y-o.h/2 <0){ o.changeY *= -1; } } function updateData(o){ o.x += o.changeX; o.y += o.changeY; } function keypress(e,o){ if (e.key == "ArrowUp"){ o.angle = 270; o.distance= 80; forward(o); } if (e.key == "ArrowDown"){ o.angle = 90; o.distance= 20; forward(o); } } function forward(o){ //makes shape able to move var cx; var cy; cx = o.distance*Math.cos(o.angle); cy = o.distance*Math.sin(o.angle) o.y += cy; } function rect(o){ var bufferx = o.x; var buffery = o.y o.x = o.x - o.w/2; o.y = o.y- o.h/2; ctx.beginPath(); //this is very important when we are changing certain ctx properties ctx.moveTo(o.x,o.y); ctx.lineTo(o.x+o.w,o.y); ctx.lineTo(o.x+o.w,o.y+o.h); ctx.lineTo(o.x, o.y+o.h); ctx.lineTo(o.x,o.y); ctx.fillStyle = "hsla("+String (o.c)+",100%,50%,"+o.a+")"; ctx.fill(); o.x = bufferx; //o.x = o.x + o.w/2; o.y = buffery;//o.y = o.y+ o.h/2; } function clear(){ ctx.clearRect(0, 0, w, h); } function randn(range){ var r = Math.random()*range-(range/2); return r } function rand(range){ var r = Math.random()*range return r } function setUpCanvas(){ canvas = document.querySelector("#myCanvas"); canvas.width = w; canvas.height = h; // canvas.style.width = "1000px"; // canvas.style.height = "700px"; canvas.style.border = "10px solid black"; ctx = canvas.getContext("2d"); } console.log("Final Assignment") <canvas id="myCanvas" ></canvas> A: In your code: o.changeX and o.changeY never do anything. So, it doesn't matter that bounce() changes them. But I can't suggest any easy fix. The biggest challenge here is that you're using angles. Was that required by the assignment? Game movement is super easy with vectors, but all geometry problems are extremely difficult to solve when using angles. (I've written 3D game engines and a VR sculpting app, and never used a single angle or sin / cos anywhere at all, including for rotation matrices. I promise, angles a very bad idea.) Edit: Well, anyway, here's the simple and easy fix: Just stop using angles. Only your keypress function changes: //If you want the arrow key to change the direction your square is moving: function keypress(e,o){ if (e.key == "ArrowUp"){ o.changeY = -1; } if (e.key == "ArrowDown"){ o.changeY = 1; } } //If you want the arrow key to move your square, but not change the direction it was moving: function keypress(e,o){ if (e.key == "ArrowUp"){ o.y -= 80; //This value is huge. Do you really want to move your square 80 pixels? It's going to shoot off the screen in a flash. I would set this to 2. } if (e.key == "ArrowDown"){ o.y += 20; } }
My object flies off the canvas when i move it instead of staying within the bounds of the canvas
I'm currently trying to code a simple game for class. Right now I want my rectangle to stay within the bounds of my canvas when i move it by using a bounce function, but it doesn't seem to be working and I cant figure out why. I have tried implementing my bounce function and calling it at the top. When I move my rectangle it goes past the bounds of the canvas without staying inside and "bouncing" off the border. var canvas; var ctx; var w = 1000; var h = 700; var o1 = { x: 100, y: h/2, w: 100, h: 100, c: 0, a: 100, angle: 0, //changes angle that shape sits at distance: 10 } document.onkeydown = function(e){keypress(e, o1)} setUpCanvas(); // circle (o1); animationLoop(); function animationLoop(){ //clear clear(); //draw rect(o1); //update bounce(o1) requestAnimationFrame(animationLoop) } function bounce(o){ if(o.x+o.w/2 > w || o.x-o.w/2 < 0){ //makes shape bounce from edge instead of middle. collision detection o.changeX *= -1; //same as o.changeX = o.changeX = -1; } if(o.y+o.h/2 > h || o.y-o.h/2 <0){ o.changeY *= -1; } } function updateData(o){ o.x += o.changeX; o.y += o.changeY; } function keypress(e,o){ if (e.key == "ArrowUp"){ o.angle = 270; o.distance= 80; forward(o); } if (e.key == "ArrowDown"){ o.angle = 90; o.distance= 20; forward(o); } } function forward(o){ //makes shape able to move var cx; var cy; cx = o.distance*Math.cos(o.angle); cy = o.distance*Math.sin(o.angle) o.y += cy; } function rect(o){ var bufferx = o.x; var buffery = o.y o.x = o.x - o.w/2; o.y = o.y- o.h/2; ctx.beginPath(); //this is very important when we are changing certain ctx properties ctx.moveTo(o.x,o.y); ctx.lineTo(o.x+o.w,o.y); ctx.lineTo(o.x+o.w,o.y+o.h); ctx.lineTo(o.x, o.y+o.h); ctx.lineTo(o.x,o.y); ctx.fillStyle = "hsla("+String (o.c)+",100%,50%,"+o.a+")"; ctx.fill(); o.x = bufferx; //o.x = o.x + o.w/2; o.y = buffery;//o.y = o.y+ o.h/2; } function clear(){ ctx.clearRect(0, 0, w, h); } function randn(range){ var r = Math.random()*range-(range/2); return r } function rand(range){ var r = Math.random()*range return r } function setUpCanvas(){ canvas = document.querySelector("#myCanvas"); canvas.width = w; canvas.height = h; // canvas.style.width = "1000px"; // canvas.style.height = "700px"; canvas.style.border = "10px solid black"; ctx = canvas.getContext("2d"); } console.log("Final Assignment")
[ "You only need to setup changeX and changeY values in o1, since they are not initialized to work with updateData:\nchangeX: initialX,\nchangeY: initialY,\n\n\n\nvar canvas;\nvar ctx;\nvar w = 1000;\nvar h = 700;\n \n\nvar o1 = {\n x: 100,\n y: h/2,\n w: 100,\n h: 100,\n c: 0,\n a: 100,\n angle: 0, //changes angle that shape sits at\n distance: 10,\n changeX: 5, // initialize with x vel\n changeY: 4, // initialize with y vel\n}\n \n\ndocument.onkeydown = function(e){keypress(e, o1)}\n \n \n \n \nsetUpCanvas();\n// circle (o1);\nanimationLoop();\n \n \nfunction animationLoop(){\n //clear\n clear();\n //draw\n rect(o1);\n //update\n bounce(o1)\n updateData(o1)\n requestAnimationFrame(animationLoop)\n \n}\n \n\n\nfunction bounce(o){\n if(o.x+o.w/2 > w || o.x-o.w/2 < 0){ //makes shape bounce from edge instead of middle. collision detection\n o.changeX *= -1; //same as o.changeX = o.changeX = -1;\n }\n \n if(o.y+o.h/2 > h || o.y-o.h/2 <0){\n o.changeY *= -1;\n }\n \n \n}\n \n \nfunction updateData(o){\no.x += o.changeX;\no.y += o.changeY;\n}\n\n\n\nfunction keypress(e,o){\n\n \n if (e.key == \"ArrowUp\"){\n o.angle = 270;\n o.distance= 80;\n forward(o);\n \n }\n \n if (e.key == \"ArrowDown\"){\n o.angle = 90;\n o.distance= 20;\n forward(o);\n \n }\n}\n \n \n \nfunction forward(o){ //makes shape able to move\n var cx;\n var cy;\n cx = o.distance*Math.cos(o.angle);\n cy = o.distance*Math.sin(o.angle)\n o.y += cy;\n \n }\n \n\n function rect(o){\n var bufferx = o.x;\n var buffery = o.y\n o.x = o.x - o.w/2;\n o.y = o.y- o.h/2;\n ctx.beginPath(); //this is very important when we are changing certain ctx properties\n ctx.moveTo(o.x,o.y);\n ctx.lineTo(o.x+o.w,o.y);\n ctx.lineTo(o.x+o.w,o.y+o.h);\n ctx.lineTo(o.x, o.y+o.h);\n ctx.lineTo(o.x,o.y);\n ctx.fillStyle = \"hsla(\"+String (o.c)+\",100%,50%,\"+o.a+\")\";\n ctx.fill();\n \n o.x = bufferx; //o.x = o.x + o.w/2;\n o.y = buffery;//o.y = o.y+ o.h/2;\n }\n \n \n \n \n \n \n \nfunction clear(){\n ctx.clearRect(0, 0, w, h);\n}\n \nfunction randn(range){\n var r = Math.random()*range-(range/2);\n return r\n}\nfunction rand(range){\n var r = Math.random()*range\n return r\n}\n \nfunction setUpCanvas(){\n canvas = document.querySelector(\"#myCanvas\");\n canvas.width = w;\n canvas.height = h;\n // canvas.style.width = \"1000px\";\n // canvas.style.height = \"700px\";\n canvas.style.border = \"10px solid black\";\n ctx = canvas.getContext(\"2d\");\n}\n \nconsole.log(\"Final Assignment\")\n<canvas id=\"myCanvas\" ></canvas>\n\n\n\n", "In your code: o.changeX and o.changeY never do anything. So, it doesn't matter that bounce() changes them.\nBut I can't suggest any easy fix. The biggest challenge here is that you're using angles. Was that required by the assignment? Game movement is super easy with vectors, but all geometry problems are extremely difficult to solve when using angles.\n(I've written 3D game engines and a VR sculpting app, and never used a single angle or sin / cos anywhere at all, including for rotation matrices. I promise, angles a very bad idea.)\nEdit:\nWell, anyway, here's the simple and easy fix: Just stop using angles.\nOnly your keypress function changes:\n\n//If you want the arrow key to change the direction your square is moving:\n\nfunction keypress(e,o){\n\n \n if (e.key == \"ArrowUp\"){\n o.changeY = -1;\n }\n \n if (e.key == \"ArrowDown\"){\n o.changeY = 1;\n }\n \n}\n \n//If you want the arrow key to move your square, but not change the direction it was moving:\n\nfunction keypress(e,o){\n\n \n if (e.key == \"ArrowUp\"){\n o.y -= 80;\n //This value is huge. Do you really want to move your square 80 pixels? It's going to shoot off the screen in a flash. I would set this to 2.\n }\n \n if (e.key == \"ArrowDown\"){\n o.y += 20;\n }\n \n}\n \n\n" ]
[ 0, 0 ]
[]
[]
[ "canvas", "javascript" ]
stackoverflow_0074662754_canvas_javascript.txt
Q: Drawing multiple edges between two nodes with d3 I've been following Mike Bostock's code from this example to learn how to draw directed graphs in d3 and was wondering how I would structure the code so that I could add multiple edges between two nodes in the graph. For example, if the dataset in the example above were defined as var links = [{source: "Microsoft", target: "Amazon", type: "licensing"}, {source: "Microsoft", target: "Amazon", type: "suit"}, {source: "Samsung", target: "Apple", type: "suit"}, {source: "Microsoft", target: "Amazon", type: "resolved"}]; and then run through the code, all I see is one line. All the paths are being drawn correctly in the html code, however they all have the same coordinates and orientation which causes the visual to look like 1 line. What kind of code restructuring would need to be done in this example to allow for the 3 edges to not be drawn on top of each other? A: In fact, the original visualization is a prime example of one method to show multiple links between nodes, that is - using arcs rather than direct paths, so you can see both incoming and outgoing links. This concept can be extended to show multiple of each of these types of links by changing the radius values of subsequent svg path(arc) elements representing the link. A basic example being dr = 75/d.linknum; Where d.linknum represents the number of the successive link. dr is later used as the rx and ry amounts for the arc being drawn. Full implementation here: http://jsfiddle.net/7HZcR/3/ A: Here is the source for the answer above if anyone ever needs it : var links = [{source: "Microsoft", target: "Amazon", type: "licensing"}, {source: "Microsoft", target: "Amazon", type: "suit"}, {source: "Samsung", target: "Apple", type: "suit"}, {source: "Microsoft", target: "Amazon", type: "resolved"}]; //sort links by source, then target links.sort(function(a,b) { if (a.source > b.source) {return 1;} else if (a.source < b.source) {return -1;} else { if (a.target > b.target) {return 1;} if (a.target < b.target) {return -1;} else {return 0;} } }); //any links with duplicate source and target get an incremented 'linknum' for (var i=0; i<links.length; i++) { if (i != 0 && links[i].source == links[i-1].source && links[i].target == links[i-1].target) { links[i].linknum = links[i-1].linknum + 1; } else {links[i].linknum = 1;}; }; var nodes = {}; // Compute the distinct nodes from the links. links.forEach(function(link) { link.source = nodes[link.source] || (nodes[link.source] = {name: link.source}); link.target = nodes[link.target] || (nodes[link.target] = {name: link.target}); }); var w = 600, h = 600; var force = d3.layout.force() .nodes(d3.values(nodes)) .links(links) .size([w, h]) .linkDistance(60) .charge(-300) .on("tick", tick) .start(); var svg = d3.select("body").append("svg:svg") .attr("width", w) .attr("height", h); // Per-type markers, as they don't inherit styles. svg.append("svg:defs").selectAll("marker") .data(["suit", "licensing", "resolved"]) .enter().append("svg:marker") .attr("id", String) .attr("viewBox", "0 -5 10 10") .attr("refX", 15) .attr("refY", -1.5) .attr("markerWidth", 6) .attr("markerHeight", 6) .attr("orient", "auto") .append("svg:path") .attr("d", "M0,-5L10,0L0,5"); var path = svg.append("svg:g").selectAll("path") .data(force.links()) .enter().append("svg:path") .attr("class", function(d) { return "link " + d.type; }) .attr("marker-end", function(d) { return "url(#" + d.type + ")"; }); var circle = svg.append("svg:g").selectAll("circle") .data(force.nodes()) .enter().append("svg:circle") .attr("r", 6) .call(force.drag); var text = svg.append("svg:g").selectAll("g") .data(force.nodes()) .enter().append("svg:g"); // A copy of the text with a thick white stroke for legibility. text.append("svg:text") .attr("x", 8) .attr("y", ".31em") .attr("class", "shadow") .text(function(d) { return d.name; }); text.append("svg:text") .attr("x", 8) .attr("y", ".31em") .text(function(d) { return d.name; }); // Use elliptical arc path segments to doubly-encode directionality. function tick() { path.attr("d", function(d) { var dx = d.target.x - d.source.x, dy = d.target.y - d.source.y, dr = 75/d.linknum; //linknum is defined above return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y; }); circle.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); text.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); } path.link { fill: none; stroke: #666; stroke-width: 1.5px; } marker#licensing { fill: green; } path.link.licensing { stroke: green; } path.link.resolved { stroke-dasharray: 0,2 1; } circle { fill: #ccc; stroke: #333; stroke-width: 1.5px; } text { font: 10px sans-serif; pointer-events: none; } text.shadow { stroke: #fff; stroke-width: 3px; stroke-opacity: .8; } <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> <div id="chart"></div> And for D3v4 see here : https://bl.ocks.org/mbostock/4600693 A: Thanks for the answers using linknum, it really worked. however the lines started overlapping after linkum > 10. Here is a function to generate equidistance quadratic curves // use it like 'M' + d.source.x + ',' + d.source.y + link_arc2(d) + d.target.x + ',' + d.target.y function link_arc2(d) { // draw line for 1st link if (d.linknum == 1) { return 'L'; } else { let sx = d.source.x; let sy = d.source.y; let tx = d.target.x; let ty = d.target.y; // distance b/w curve paths let cd = 30; // find middle of source and target let cx = (sx + tx) / 2; let cy = (sy + ty) / 2; // find angle of line b/w source and target var angle = Math.atan2(ty - sy, tx - sx); // add radian equivalent of 90 degree var c_angle = angle + 1.5708; // draw odd and even curves either side of line if (d.linknum & 1) { return 'Q ' + (cx - ((d.linknum - 1) * cd * Math.cos(c_angle))) + ',' + (cy - ((d.linknum - 1) * cd * Math.sin(c_angle))) + ' '; } else { return 'Q ' + (cx + (d.linknum * cd * Math.cos(c_angle))) + ',' + (cy + (d.linknum * cd * Math.sin(c_angle))) + ' '; } } }
Drawing multiple edges between two nodes with d3
I've been following Mike Bostock's code from this example to learn how to draw directed graphs in d3 and was wondering how I would structure the code so that I could add multiple edges between two nodes in the graph. For example, if the dataset in the example above were defined as var links = [{source: "Microsoft", target: "Amazon", type: "licensing"}, {source: "Microsoft", target: "Amazon", type: "suit"}, {source: "Samsung", target: "Apple", type: "suit"}, {source: "Microsoft", target: "Amazon", type: "resolved"}]; and then run through the code, all I see is one line. All the paths are being drawn correctly in the html code, however they all have the same coordinates and orientation which causes the visual to look like 1 line. What kind of code restructuring would need to be done in this example to allow for the 3 edges to not be drawn on top of each other?
[ "In fact, the original visualization is a prime example of one method to show multiple links between nodes, that is - using arcs rather than direct paths, so you can see both incoming and outgoing links. \nThis concept can be extended to show multiple of each of these types of links by changing the radius values of subsequent svg path(arc) elements representing the link. A basic example being\ndr = 75/d.linknum;\n\nWhere d.linknum represents the number of the successive link. dr is later used as the rx and ry amounts for the arc being drawn.\nFull implementation here: http://jsfiddle.net/7HZcR/3/\n\n", "Here is the source for the answer above if anyone ever needs it : \n\n\nvar links = [{source: \"Microsoft\", target: \"Amazon\", type: \"licensing\"},\r\n {source: \"Microsoft\", target: \"Amazon\", type: \"suit\"},\r\n {source: \"Samsung\", target: \"Apple\", type: \"suit\"},\r\n {source: \"Microsoft\", target: \"Amazon\", type: \"resolved\"}];\r\n//sort links by source, then target\r\nlinks.sort(function(a,b) {\r\n if (a.source > b.source) {return 1;}\r\n else if (a.source < b.source) {return -1;}\r\n else {\r\n if (a.target > b.target) {return 1;}\r\n if (a.target < b.target) {return -1;}\r\n else {return 0;}\r\n }\r\n});\r\n//any links with duplicate source and target get an incremented 'linknum'\r\nfor (var i=0; i<links.length; i++) {\r\n if (i != 0 &&\r\n links[i].source == links[i-1].source &&\r\n links[i].target == links[i-1].target) {\r\n links[i].linknum = links[i-1].linknum + 1;\r\n }\r\n else {links[i].linknum = 1;};\r\n};\r\n\r\nvar nodes = {};\r\n\r\n// Compute the distinct nodes from the links.\r\nlinks.forEach(function(link) {\r\n link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});\r\n link.target = nodes[link.target] || (nodes[link.target] = {name: link.target});\r\n});\r\n\r\nvar w = 600,\r\n h = 600;\r\n\r\nvar force = d3.layout.force()\r\n .nodes(d3.values(nodes))\r\n .links(links)\r\n .size([w, h])\r\n .linkDistance(60)\r\n .charge(-300)\r\n .on(\"tick\", tick)\r\n .start();\r\n\r\nvar svg = d3.select(\"body\").append(\"svg:svg\")\r\n .attr(\"width\", w)\r\n .attr(\"height\", h);\r\n\r\n// Per-type markers, as they don't inherit styles.\r\nsvg.append(\"svg:defs\").selectAll(\"marker\")\r\n .data([\"suit\", \"licensing\", \"resolved\"])\r\n .enter().append(\"svg:marker\")\r\n .attr(\"id\", String)\r\n .attr(\"viewBox\", \"0 -5 10 10\")\r\n .attr(\"refX\", 15)\r\n .attr(\"refY\", -1.5)\r\n .attr(\"markerWidth\", 6)\r\n .attr(\"markerHeight\", 6)\r\n .attr(\"orient\", \"auto\")\r\n .append(\"svg:path\")\r\n .attr(\"d\", \"M0,-5L10,0L0,5\");\r\n\r\nvar path = svg.append(\"svg:g\").selectAll(\"path\")\r\n .data(force.links())\r\n .enter().append(\"svg:path\")\r\n .attr(\"class\", function(d) { return \"link \" + d.type; })\r\n .attr(\"marker-end\", function(d) { return \"url(#\" + d.type + \")\"; });\r\n\r\nvar circle = svg.append(\"svg:g\").selectAll(\"circle\")\r\n .data(force.nodes())\r\n .enter().append(\"svg:circle\")\r\n .attr(\"r\", 6)\r\n .call(force.drag);\r\n\r\nvar text = svg.append(\"svg:g\").selectAll(\"g\")\r\n .data(force.nodes())\r\n .enter().append(\"svg:g\");\r\n\r\n// A copy of the text with a thick white stroke for legibility.\r\ntext.append(\"svg:text\")\r\n .attr(\"x\", 8)\r\n .attr(\"y\", \".31em\")\r\n .attr(\"class\", \"shadow\")\r\n .text(function(d) { return d.name; });\r\n\r\ntext.append(\"svg:text\")\r\n .attr(\"x\", 8)\r\n .attr(\"y\", \".31em\")\r\n .text(function(d) { return d.name; });\r\n\r\n// Use elliptical arc path segments to doubly-encode directionality.\r\nfunction tick() {\r\n path.attr(\"d\", function(d) {\r\n var dx = d.target.x - d.source.x,\r\n dy = d.target.y - d.source.y,\r\n dr = 75/d.linknum; //linknum is defined above\r\n return \"M\" + d.source.x + \",\" + d.source.y + \"A\" + dr + \",\" + dr + \" 0 0,1 \" + d.target.x + \",\" + d.target.y;\r\n });\r\n\r\n circle.attr(\"transform\", function(d) {\r\n return \"translate(\" + d.x + \",\" + d.y + \")\";\r\n });\r\n\r\n text.attr(\"transform\", function(d) {\r\n return \"translate(\" + d.x + \",\" + d.y + \")\";\r\n });\r\n}\npath.link {\r\n fill: none;\r\n stroke: #666;\r\n stroke-width: 1.5px;\r\n}\r\n\r\nmarker#licensing {\r\n fill: green;\r\n}\r\n\r\npath.link.licensing {\r\n stroke: green;\r\n}\r\n\r\npath.link.resolved {\r\n stroke-dasharray: 0,2 1;\r\n}\r\n\r\ncircle {\r\n fill: #ccc;\r\n stroke: #333;\r\n stroke-width: 1.5px;\r\n}\r\n\r\ntext {\r\n font: 10px sans-serif;\r\n pointer-events: none;\r\n}\r\n\r\ntext.shadow {\r\n stroke: #fff;\r\n stroke-width: 3px;\r\n stroke-opacity: .8;\r\n}\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js\"></script>\r\n<div id=\"chart\"></div>\n\n\n\nAnd for D3v4 see here : https://bl.ocks.org/mbostock/4600693\n", "Thanks for the answers using linknum, it really worked. however the lines started overlapping after linkum > 10.\nHere is a function to generate equidistance quadratic curves\n// use it like 'M' + d.source.x + ',' + d.source.y + link_arc2(d) + d.target.x + ',' + d.target.y\n function link_arc2(d) {\n // draw line for 1st link\n if (d.linknum == 1) {\n return 'L';\n }\n else {\n let sx = d.source.x;\n let sy = d.source.y;\n let tx = d.target.x;\n let ty = d.target.y;\n\n // distance b/w curve paths\n let cd = 30;\n\n // find middle of source and target\n let cx = (sx + tx) / 2;\n let cy = (sy + ty) / 2;\n \n // find angle of line b/w source and target\n var angle = Math.atan2(ty - sy, tx - sx);\n\n // add radian equivalent of 90 degree\n var c_angle = angle + 1.5708;\n\n // draw odd and even curves either side of line\n if (d.linknum & 1) {\n return 'Q ' + (cx - ((d.linknum - 1) * cd * Math.cos(c_angle))) + ',' + (cy - ((d.linknum - 1) * cd * Math.sin(c_angle))) + ' ';\n }\n else {\n return 'Q ' + (cx + (d.linknum * cd * Math.cos(c_angle))) + ',' + (cy + (d.linknum * cd * Math.sin(c_angle))) + ' ';\n }\n }\n }\n\n" ]
[ 40, 5, 1 ]
[]
[]
[ "d3.js", "edges", "graph", "html", "svg" ]
stackoverflow_0011368339_d3.js_edges_graph_html_svg.txt
Q: Copy and rename a file key in s3 after being saved as one csv with prefix 'part-0000-*' with boto3 After coalesce() function in pyspark(databricks), the file was saved as a single csv with a weird name that starts with part-00000 or ends with .csv extension. I would like to rename it to a more user-friendly name in a function. I trying the approach suggested below: https://medium.com/plusteam/move-and-rename-objects-within-an-s3-bucket-using-boto-3-58b164790b78 import boto3 s3_resource = boto3.resource(‘s3’) # Copy object A as object B s3_resource.Object(“bucket_name”, “newpath/to/object_B.txt”).copy_from( CopySource=”path/to/your/object_A.txt”) # Delete the former object A s3_resource.Object(“bucket_name”, “path/to/your/object_A.txt”).delete() The above code says to copy the object with the new name and delete the original file. However, after several tries, it only works when I put the whole weird name within the copy_source. What I would like to do is since there is only one weirdly-named file, is to use the *.csv just like the way it works with pandas. I tried the endswith() function but seems to cannot work. The answer from this Rename Pyspark output files in s3 renames each partition hence there is a obvious pattern. import datetime import boto3 s3 = boto3.resource('s3') for i in range(5): date = datetime.datetime(2019,4,29) date += datetime.timedelta(days=i) date = date.strftime("%Y-%m-%d") print(date) old_date = 'file_path/FLORIDA/DATE={}/part-00000-1691d1c6-2c49-4cbe-b454-d0165a0d7bde.c000.csv'.format(date) print(old_date) date = date.replace('-','') new_date = 'file_path/FLORIDA/allocation_FLORIDA_{}.csv'.format(date) print(new_date) s3.Object('my_bucket', new_date).copy_from(CopySource='my_bucket/' + old_date) s3.Object('my_bucket', old_date).delete() I think with pandas, it would have been: (note the use of *) import boto3 s3_resource = boto3.resource(‘s3’) # Copy object A as object B s3_resource.Object(“bucket_name”, “newpath/to/object_B.csv”).copy_from( CopySource=”path/to/your/*.csv”) # Delete the former object A s3_resource.Object(“bucket_name”, “path/to/your/*.csv”).delete() but if used within databricks, it returns none A: you may be able to integrate this to your function. Use the variables as arguments of your function: bucket = 'bucket_name' prefix = 'file/path/down/to/last/folder' filename = 'new_filename' s3 = boto3.resource('s3') s3_bucket = s3.Bucket(bucket) # list the objects filtered to the prefix for file in s3_bucket.objects.filter(Prefix = prefix): # look for the weirdly-named file after saving as one csv # this line below will look for the original file that ends in csv if file.key.endswith('.csv'): # copy that file s3.object(bucket, prefix+'/'+filename+'.csv').copy_from(bucket+'/'+file.key) # additionally, when you want to delete the original file ## but be careful with this line especially if you have more than 1 csv file as it will be deleted as well. s3.object(bucket, file.key).delete() let me know if this does not work and we will make the changes based on the error you will get, if any.
Copy and rename a file key in s3 after being saved as one csv with prefix 'part-0000-*' with boto3
After coalesce() function in pyspark(databricks), the file was saved as a single csv with a weird name that starts with part-00000 or ends with .csv extension. I would like to rename it to a more user-friendly name in a function. I trying the approach suggested below: https://medium.com/plusteam/move-and-rename-objects-within-an-s3-bucket-using-boto-3-58b164790b78 import boto3 s3_resource = boto3.resource(‘s3’) # Copy object A as object B s3_resource.Object(“bucket_name”, “newpath/to/object_B.txt”).copy_from( CopySource=”path/to/your/object_A.txt”) # Delete the former object A s3_resource.Object(“bucket_name”, “path/to/your/object_A.txt”).delete() The above code says to copy the object with the new name and delete the original file. However, after several tries, it only works when I put the whole weird name within the copy_source. What I would like to do is since there is only one weirdly-named file, is to use the *.csv just like the way it works with pandas. I tried the endswith() function but seems to cannot work. The answer from this Rename Pyspark output files in s3 renames each partition hence there is a obvious pattern. import datetime import boto3 s3 = boto3.resource('s3') for i in range(5): date = datetime.datetime(2019,4,29) date += datetime.timedelta(days=i) date = date.strftime("%Y-%m-%d") print(date) old_date = 'file_path/FLORIDA/DATE={}/part-00000-1691d1c6-2c49-4cbe-b454-d0165a0d7bde.c000.csv'.format(date) print(old_date) date = date.replace('-','') new_date = 'file_path/FLORIDA/allocation_FLORIDA_{}.csv'.format(date) print(new_date) s3.Object('my_bucket', new_date).copy_from(CopySource='my_bucket/' + old_date) s3.Object('my_bucket', old_date).delete() I think with pandas, it would have been: (note the use of *) import boto3 s3_resource = boto3.resource(‘s3’) # Copy object A as object B s3_resource.Object(“bucket_name”, “newpath/to/object_B.csv”).copy_from( CopySource=”path/to/your/*.csv”) # Delete the former object A s3_resource.Object(“bucket_name”, “path/to/your/*.csv”).delete() but if used within databricks, it returns none
[ "you may be able to integrate this to your function. Use the variables as arguments of your function:\nbucket = 'bucket_name'\nprefix = 'file/path/down/to/last/folder'\nfilename = 'new_filename'\n\ns3 = boto3.resource('s3')\ns3_bucket = s3.Bucket(bucket)\n\n# list the objects filtered to the prefix\nfor file in s3_bucket.objects.filter(Prefix = prefix):\n # look for the weirdly-named file after saving as one csv\n # this line below will look for the original file that ends in csv\n if file.key.endswith('.csv'):\n # copy that file\n s3.object(bucket, prefix+'/'+filename+'.csv').copy_from(bucket+'/'+file.key)\n # additionally, when you want to delete the original file\n ## but be careful with this line especially if you have more than 1 csv file as it will be deleted as well.\n s3.object(bucket, file.key).delete()\n\nlet me know if this does not work and we will make the changes based on the error you will get, if any.\n" ]
[ 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "csv", "pyspark" ]
stackoverflow_0074658269_amazon_s3_amazon_web_services_csv_pyspark.txt
Q: google cloud func simulator - limit functions to start? during development starting/restarting ALL the funcs in my app is slow, is there a way to limit the scope of functions? similar to how you can just deploy a subset with: firebase deploy --only functions:token-tokenMetadata I tried to do: npm run build:watch | firebase emulators:start --only functions:peopleai-createTune but it will start everything docs don't seem to mention: https://firebase.google.com/docs/functions/local-emulator A: That's currently not a feature. It sounds like an interesting idea though, so I recommend filing a request for it on the GitHub repo of the project.
google cloud func simulator - limit functions to start?
during development starting/restarting ALL the funcs in my app is slow, is there a way to limit the scope of functions? similar to how you can just deploy a subset with: firebase deploy --only functions:token-tokenMetadata I tried to do: npm run build:watch | firebase emulators:start --only functions:peopleai-createTune but it will start everything docs don't seem to mention: https://firebase.google.com/docs/functions/local-emulator
[ "That's currently not a feature. It sounds like an interesting idea though, so I recommend filing a request for it on the GitHub repo of the project.\n" ]
[ 0 ]
[]
[]
[ "firebase", "google_cloud_functions", "google_cloud_platform", "simulator" ]
stackoverflow_0074661022_firebase_google_cloud_functions_google_cloud_platform_simulator.txt
Q: Excel copy past using vba While Copying Data from one workbook ex. A1 to G1 Paste to Another Workbook bt i need to vlookup function in B1 cell pasting code ill write bt how to skip b1 cell or how to write vlookup function in b1 cell any one plse write the code for this scenario im new in vba any one plse help me A: This is the general or most basic way to copy a range from one workbook to another. ' > Indicate we want excel to stop us from using undeclared variables. ' This is useful for ensuring we haven't mis-spelled any variables. ' There are more important reasons for it, but for a beginner, this is a good start. Option Explicit ' > Good Clear Naming for later debugging. Sub Copy_And_Paste_Salad_Costing_Data() ' > Declare Variables and Variable Types Dim SourceWB As Workbook Dim TargetWB As Workbook ' > Set Object Variables Set SourceWB = ThisWorkbook Set TargetWB = Workbooks("NameOfMyWorkbook.xlsx") ' > Preform Copy/Paste Operation SourceWB.Worksheets("Sheet1").Range("B2:C5").Copy TargetWB.Worksheets("Sheet1").Range("A1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats ' OR Paste:=xlPasteValues or... many other options End Sub Hopefully you can understand how it works and make it work for your project. Keep in mind you cannot copy data to or from a closed workbook.
Excel copy past using vba
While Copying Data from one workbook ex. A1 to G1 Paste to Another Workbook bt i need to vlookup function in B1 cell pasting code ill write bt how to skip b1 cell or how to write vlookup function in b1 cell any one plse write the code for this scenario im new in vba any one plse help me
[ "This is the general or most basic way to copy a range from one workbook to another.\n' > Indicate we want excel to stop us from using undeclared variables.\n' This is useful for ensuring we haven't mis-spelled any variables.\n' There are more important reasons for it, but for a beginner, this is a good start.\nOption Explicit\n\n' > Good Clear Naming for later debugging.\nSub Copy_And_Paste_Salad_Costing_Data()\n \n ' > Declare Variables and Variable Types\n Dim SourceWB As Workbook\n Dim TargetWB As Workbook\n \n ' > Set Object Variables\n Set SourceWB = ThisWorkbook\n Set TargetWB = Workbooks(\"NameOfMyWorkbook.xlsx\")\n \n ' > Preform Copy/Paste Operation\n SourceWB.Worksheets(\"Sheet1\").Range(\"B2:C5\").Copy\n TargetWB.Worksheets(\"Sheet1\").Range(\"A1\").PasteSpecial Paste:=xlPasteValuesAndNumberFormats\n ' OR Paste:=xlPasteValues or... many other options\n \nEnd Sub\n\nHopefully you can understand how it works and make it work for your project.\nKeep in mind you cannot copy data to or from a closed workbook.\n" ]
[ 0 ]
[]
[]
[ "excel", "vba" ]
stackoverflow_0074622951_excel_vba.txt
Q: I've been trying to run a scheduler with clockwerk but it doesn't work I've been trying to run a scheduler in rust using the clockwerk crate. I copied a bit of the code in the docs and tried to run it but it doesn't work for me, It compiles fine but i expect to see "Periodic Task" logged to the console every 10 secs which doesn't happen. i don't know what i'm doing wrong. use clokwerk::{Scheduler, TimeUnits}; fn main() { // or a scheduler with a given timezone let mut scheduler = Scheduler::with_tz(chrono::Utc); // Add some tasks to it scheduler .every(10.seconds()) .run(|| println!("Periodic task")); } A: scheduler.every(...).run(...) doesn't execute the task, it just registers the task with the scheduler. To actually instruct the scheduler to run tasks, you need to repeatedly call run_pending() in a loop, as shown in the example in the docs: loop { scheduler.run_pending(); thread::sleep(Duration::from_millis(100)); }
I've been trying to run a scheduler with clockwerk but it doesn't work
I've been trying to run a scheduler in rust using the clockwerk crate. I copied a bit of the code in the docs and tried to run it but it doesn't work for me, It compiles fine but i expect to see "Periodic Task" logged to the console every 10 secs which doesn't happen. i don't know what i'm doing wrong. use clokwerk::{Scheduler, TimeUnits}; fn main() { // or a scheduler with a given timezone let mut scheduler = Scheduler::with_tz(chrono::Utc); // Add some tasks to it scheduler .every(10.seconds()) .run(|| println!("Periodic task")); }
[ "scheduler.every(...).run(...) doesn't execute the task, it just registers the task with the scheduler. To actually instruct the scheduler to run tasks, you need to repeatedly call run_pending() in a loop, as shown in the example in the docs:\nloop {\n scheduler.run_pending();\n thread::sleep(Duration::from_millis(100));\n}\n\n" ]
[ 1 ]
[]
[]
[ "rust", "scheduler" ]
stackoverflow_0074662506_rust_scheduler.txt
Q: How to automatically close cmd window after batch file execution? I'm running a batch file that has these two lines: start C:\Users\Yiwei\Downloads\putty.exe -load "MathCS-labMachine1" "C:\Program Files (x86)\Xming\Xming.exe" :0 -clipboard -multiwindow This batch file is used to run the Xming application and then the PuTTY app so I can SSH into my university's computer lab. However, if I run this and Xming is not already open, once I exit from the PuTTY terminal the cmd window remains open. Only if I have already run Xming does the cmd window close when I close the PuTTY terminal. I've tried adding exit to the last line of the batch file, but to no avail. A: Modify the batch file to START both programs, instead of STARTing one and CALLing another start C:\Users\Yiwei\Downloads\putty.exe -load "MathCS-labMachine1" start "" "C:\Program Files (x86)\Xming\Xming.exe" :0 -clipboard -multiwindow If you run it like this, no CMD window will stay open after starting the program. A: You normally end a batch file with a line that just says exit. If you want to make sure the file has run and the DOS window closes after 2 seconds, you can add the lines: timeout 2 >nul exit But the exit command will not work if your batch file opens another window, because while ever the second window is open the old DOS window will also be displayed. SOLUTION: For example there's a great little free program called BgInfo which will display all the info about your computer. Assuming it's in a directory called C:\BgInfo, to run it from a batch file with the /popup switch and to close the DOS window while it still runs, use: start "" "C:\BgInfo\BgInfo.exe" /popup exit A: If you want to separate the commands into one command per file, you can do cmd /c start C:\Users\Yiwei\Downloads\putty.exe -load "MathCS-labMachine1" and in the other file, you can do cmd /c start "" "C:\Program Files (x86)\Xming\Xming.exe" :0 -clipboard -multiwindow The command cmd /c will close the command-prompt window after the exe was run. A: To close the current cmd windows immediately, just add as the last command/line: move nul 2>&0 Try move nul to nowhere and redirect the stderr to stdin will result in the current window cmd.exe being closed This is different from closing a bat, or exiting it using goto :EOF or Exit /b I even opened a question to find an answer that would explain behavior. Would that be a bug? Immediate closing of the current cmd window when executing: move nul 2>&0 A: Closing cmd window after opening VSCode with batch script If you have the code command which installs with VSCode: echo | code . | exit /b If you're running the script as administrator: cd /d %~dp0 echo | code . | exit /b Using start /b will usually work to allow the cmd window to close for other programs. A: This worked for me. I just wanted to close the command window automatically after exiting the game. I just double click on the .bat file on my desktop. No shortcuts. taskkill /f /IM explorer.exe C:\"GOG Games"\Starcraft\Starcraft.exe start explorer.exe exit /B A: You could try the somewhat dangerous: taskkill /IM cmd.exe ..dangerous bcz that will kill the cmd that is open and any cmd's opened before it. Or add a verification to confirm that you had the right cmd.exe and then kill it via PID, such as this: set loc=%time%%random% title=%loc% for /f "tokens=2 delims= " %%A in ('tasklist /v ^| findstr /i "%loc%"') do (taskkill /PID %%A) Substitute (pslist &&A) or (tasklist /FI "PID eq %%A") for the (taskkill /PID %%A) if you want to check it first (and maybe have pstools installed). A: i do something like below start "" ** code exit it's work for me A: I had this, I added EXIT and initially it didn't work, I guess per requiring the called program exiting advice mentioned in another response here, however it now works without further ado - not sure what's caused this, but the point to note is that I'm calling a data file .html rather than the program that handles it browser.exe, I did not edit anything else but suffice it to say it's much neater just using a bat file to access the main access pages of those web documents and only having title.bat, contents.bat, index.bat in the root folder with the rest of the content in a subfolder. i.e.: contents.bat reads cd subfolder "contents.html" exit It also looks better if I change the bat file icons for just those items to suit the context they are in too, but that's another matter, hiding the bat files in the subfolder and creating custom icon shortcuts to them in the root folder with the images called for the customisation also hidden. A: Sometimes you can reference a Windows "shortcut" file to launch an application instead of using a ".bat" file, and it won't have the residual prompt problem. But it's not as flexible as bat files. A: After reading several answers, I learned a couple of things with experimentation: files ending with CMD vs BAT will be handled slightly differently. I was trying to run with silentCMD.exe but the problem is that silentCMD would always wait until any started program finished running before reporting task as being completed....even if the CMD window quit ahead of time. using move nul 2>&0 does seem to work, but the exit code is never delivered properly. so when using task scheduler, it may have weird results unless you can somehow detect the exact weird result and workaround it. Solution was to just run the task scheduler (or bat/cmd script) directly without using silentCMD to launch it. With .BAT file extension @echo off if not "%minimized%"=="" goto :minimized set minimized=true start /min cmd /C "%~dpnx0" goto :EOF :minimized taskkill /IM "Program.exe" /T /F start "" "C:\Program.exe" /arg1 /arg2 TIMEOUT /T 2 /NOBREAK EXIT /B The if not "%minimized%"=="" goto :minimized portion is to launch the bat (or cmd) minimized. difficult to get CMD window to be silent, so this is the next best thing. BAT files seem to just exit properly without having to do anything extra. If using .CMD file extension @echo off if not "%minimized%"=="" goto :minimized set minimized=true start /min cmd /C "%~dpnx0" goto :EOF :minimized taskkill /IM "Program.exe" /T /F cmd /c start "" "C:\Program.exe" /arg1 /arg2 TIMEOUT /T 2 /NOBREAK EXIT /B You must use the cmd /c before the start in order to get the script to close after the launch.
How to automatically close cmd window after batch file execution?
I'm running a batch file that has these two lines: start C:\Users\Yiwei\Downloads\putty.exe -load "MathCS-labMachine1" "C:\Program Files (x86)\Xming\Xming.exe" :0 -clipboard -multiwindow This batch file is used to run the Xming application and then the PuTTY app so I can SSH into my university's computer lab. However, if I run this and Xming is not already open, once I exit from the PuTTY terminal the cmd window remains open. Only if I have already run Xming does the cmd window close when I close the PuTTY terminal. I've tried adding exit to the last line of the batch file, but to no avail.
[ "Modify the batch file to START both programs, instead of STARTing one and CALLing another\nstart C:\\Users\\Yiwei\\Downloads\\putty.exe -load \"MathCS-labMachine1\"\nstart \"\" \"C:\\Program Files (x86)\\Xming\\Xming.exe\" :0 -clipboard -multiwindow\n\nIf you run it like this, no CMD window will stay open after starting the program.\n", "You normally end a batch file with a line that just says exit. If you want to make sure the file has run and the DOS window closes after 2 seconds, you can add the lines:\ntimeout 2 >nul\nexit\n\nBut the exit command will not work if your batch file opens another window, because while ever the second window is open the old DOS window will also be displayed. \nSOLUTION: For example there's a great little free program called BgInfo which will display all the info about your computer. Assuming it's in a directory called C:\\BgInfo, to run it from a batch file with the /popup switch and to close the DOS window while it still runs, use:\nstart \"\" \"C:\\BgInfo\\BgInfo.exe\" /popup\nexit\n\n", "If you want to separate the commands into one command per file, you can do\ncmd /c start C:\\Users\\Yiwei\\Downloads\\putty.exe -load \"MathCS-labMachine1\"\n\nand in the other file, you can do \ncmd /c start \"\" \"C:\\Program Files (x86)\\Xming\\Xming.exe\" :0 -clipboard -multiwindow\n\nThe command cmd /c will close the command-prompt window after the exe was run. \n", "To close the current cmd windows\nimmediately, just add as the last command/line:\nmove nul 2>&0\nTry move nul to nowhere and redirect the stderr to stdin\nwill result in the current window cmd.exe being closed\nThis is different from closing a bat, or exiting it using goto :EOF or Exit /b\nI even opened a question to find an answer that would explain behavior.\nWould that be a bug? Immediate closing of the current cmd window when executing: move nul 2>&0\n", "Closing cmd window after opening VSCode with batch script\nIf you have the code command which installs with VSCode:\necho | code . | exit /b\n\nIf you're running the script as administrator:\ncd /d %~dp0\necho | code . | exit /b\n\nUsing start /b will usually work to allow the cmd window to close for other programs.\n", "This worked for me. I just wanted to close the command window automatically after exiting the game. I just double click on the .bat file on my desktop. No shortcuts.\ntaskkill /f /IM explorer.exe\nC:\\\"GOG Games\"\\Starcraft\\Starcraft.exe\nstart explorer.exe\nexit /B\n\n", "You could try the somewhat dangerous: taskkill /IM cmd.exe ..dangerous bcz that will kill the cmd that is open and any cmd's opened before it.\nOr add a verification to confirm that you had the right cmd.exe and then kill it via PID, such as this:\nset loc=%time%%random%\ntitle=%loc%\nfor /f \"tokens=2 delims= \" %%A in ('tasklist /v ^| findstr /i \"%loc%\"') do (taskkill /PID %%A) \n\nSubstitute (pslist &&A) or (tasklist /FI \"PID eq %%A\") for the (taskkill /PID %%A) if you want to check it first (and maybe have pstools installed).\n", "i do something like below\nstart \"\"\n** code\nexit\n\nit's work for me\n", "I had this, I added EXIT and initially it didn't work, I guess per requiring the called program exiting advice mentioned in another response here, however it now works without further ado - not sure what's caused this, but the point to note is that I'm calling a data file .html rather than the program that handles it browser.exe, I did not edit anything else but suffice it to say it's much neater just using a bat file to access the main access pages of those web documents and only having title.bat, contents.bat, index.bat in the root folder with the rest of the content in a subfolder.\ni.e.: contents.bat reads\ncd subfolder\n\"contents.html\"\nexit\n\nIt also looks better if I change the bat file icons for just those items to suit the context they are in too, but that's another matter, hiding the bat files in the subfolder and creating custom icon shortcuts to them in the root folder with the images called for the customisation also hidden.\n", "Sometimes you can reference a Windows \"shortcut\" file to launch an application instead of using a \".bat\" file, and it won't have the residual prompt problem. But it's not as flexible as bat files.\n", "After reading several answers, I learned a couple of things with experimentation:\n\nfiles ending with CMD vs BAT will be handled slightly differently.\n\nI was trying to run with silentCMD.exe but the problem is that silentCMD would always wait until any started program finished running before reporting task as being completed....even if the CMD window quit ahead of time.\n\nusing move nul 2>&0 does seem to work, but the exit code is never delivered properly. so when using task scheduler, it may have weird results unless you can somehow detect the exact weird result and workaround it.\n\n\nSolution was to just run the task scheduler (or bat/cmd script) directly without using silentCMD to launch it.\n\nWith .BAT file extension\n@echo off\n\nif not \"%minimized%\"==\"\" goto :minimized\nset minimized=true\nstart /min cmd /C \"%~dpnx0\"\ngoto :EOF\n:minimized\n\ntaskkill /IM \"Program.exe\" /T /F\n\nstart \"\" \"C:\\Program.exe\" /arg1 /arg2\n\nTIMEOUT /T 2 /NOBREAK\n\nEXIT /B\n\nThe if not \"%minimized%\"==\"\" goto :minimized portion is to launch the bat (or cmd) minimized. difficult to get CMD window to be silent, so this is the next best thing.\nBAT files seem to just exit properly without having to do anything extra.\n\nIf using .CMD file extension\n@echo off\n\nif not \"%minimized%\"==\"\" goto :minimized\nset minimized=true\nstart /min cmd /C \"%~dpnx0\"\ngoto :EOF\n:minimized\n\ntaskkill /IM \"Program.exe\" /T /F\n\ncmd /c start \"\" \"C:\\Program.exe\" /arg1 /arg2\n\nTIMEOUT /T 2 /NOBREAK\n\nEXIT /B\n\nYou must use the cmd /c before the start in order to get the script to close after the launch.\n" ]
[ 161, 35, 10, 10, 5, 2, 1, 1, 0, 0, 0 ]
[ "Just try /s as listed below.\nAs the last line in the batch file type:\nexit /s\n\nThe above command will close the Windows CMD window.\n/s - stands for silent as in (it would wait for an input from the keyboard).\n" ]
[ -1 ]
[ "batch_file", "cmd" ]
stackoverflow_0014697739_batch_file_cmd.txt
Q: array(0) { } when retrieve data of formData ajax request in laravel controller I have text and image input in a form. I want to send the data through ajax request. I use dataForm as the format to send to Laravel controller. I get array(0) {} when i try to retrieve the input form. This is my ajax request code: $("form").on('submit', function(){ var data = new FormData(this); var url = "{{ route('ajaxSubmitFormWizardsEmployee') }}"; var csrf_token = $(this).find('input[name="_token"]').val(); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': csrf_token, } }); $.ajax({ type: "POST", url: url, async: false, cache: false, contentType: false, processData: false, data: { data : data, }, success:function(data){ console.log(data); }, error: function() { console.log('error); }, }); Laravel controller: public function ajaxSubmitFormWizardsEmployee(Request $request) { $input = $request->all(); print_r($input); } I managed to console log the formData before send ajax by adding this code: for (let obj of data) { console.log(obj[0],obj[1]); } Below is the picture console log the formData before send ajax: console log the formData before send ajax Below is the picture console log when try to retrieve or view data from Laravel controller: retrieve or view data from Laravel controller A: I see that you are trying to submit a file, does your form have this attribute: enctype="multipart/form-data"
array(0) { } when retrieve data of formData ajax request in laravel controller
I have text and image input in a form. I want to send the data through ajax request. I use dataForm as the format to send to Laravel controller. I get array(0) {} when i try to retrieve the input form. This is my ajax request code: $("form").on('submit', function(){ var data = new FormData(this); var url = "{{ route('ajaxSubmitFormWizardsEmployee') }}"; var csrf_token = $(this).find('input[name="_token"]').val(); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': csrf_token, } }); $.ajax({ type: "POST", url: url, async: false, cache: false, contentType: false, processData: false, data: { data : data, }, success:function(data){ console.log(data); }, error: function() { console.log('error); }, }); Laravel controller: public function ajaxSubmitFormWizardsEmployee(Request $request) { $input = $request->all(); print_r($input); } I managed to console log the formData before send ajax by adding this code: for (let obj of data) { console.log(obj[0],obj[1]); } Below is the picture console log the formData before send ajax: console log the formData before send ajax Below is the picture console log when try to retrieve or view data from Laravel controller: retrieve or view data from Laravel controller
[ "I see that you are trying to submit a file, does your form have this attribute:\nenctype=\"multipart/form-data\"\n\n" ]
[ 0 ]
[]
[]
[ "ajax", "form_data", "jquery", "laravel", "php" ]
stackoverflow_0074662581_ajax_form_data_jquery_laravel_php.txt
Q: How to downgrade a Visual Studio extension? I need to downgrade NuGet Package Manager extension for Visual Studio 2015 for testing purpose. How to do this? Is there any way to download an older version of this extension and install it into Visual Studio? A: This site lists all recent releases, you must install the VSIX file. https://github.com/NuGet/Home/releases A: You can usually try a variation of the link you can get from the download button from the extension's page on https://marketplace.visualstudio.com/ . For example, at the time of this writing Failwyn/WebCompiler64 version 1.14.9.2 has an issue, so I downloaded version 1.14.8 from https://marketplace.visualstudio.com/_apis/public/gallery/publishers/Failwyn/vsextensions/WebCompiler64/1.14.8/vspackage .
How to downgrade a Visual Studio extension?
I need to downgrade NuGet Package Manager extension for Visual Studio 2015 for testing purpose. How to do this? Is there any way to download an older version of this extension and install it into Visual Studio?
[ "This site lists all recent releases, you must install the VSIX file.\nhttps://github.com/NuGet/Home/releases\n", "You can usually try a variation of the link you can get from the download button from the extension's page on https://marketplace.visualstudio.com/ .\nFor example, at the time of this writing Failwyn/WebCompiler64 version 1.14.9.2 has an issue, so I downloaded version 1.14.8 from https://marketplace.visualstudio.com/_apis/public/gallery/publishers/Failwyn/vsextensions/WebCompiler64/1.14.8/vspackage .\n" ]
[ 2, 0 ]
[ "An easier way to downgrade any visual studio code extension is by:\n 1. search for the extension in visual studio code\n 2. Right click on the extension you want to downgrade\n 3. select Install Another Version... \n 4. Pick the version from the list if any and install\n\nVS Code - how to rollback extension/install specific extension version\n" ]
[ -1 ]
[ "visual_studio_extensions", "vs_extensibility" ]
stackoverflow_0039971012_visual_studio_extensions_vs_extensibility.txt
Q: I have a list of list. Need to merge all the elements that is only "a" letters into a single string, moving the other elements down a position x1 = ['a','1','2','b','4'] x2 = ['a','a','2','b','4'] x3 = ['a','a','a','b','4'] x4 = ['a','1','2','b','4'] xxxx = x1,x2,x3,x4 name2f = [] for i in xxxx: a1 = i[0] b1 = i[1] c1 = i[2] if a1.isalpha: if b1.isalpha: if c1.isalpha: print("false 3") p = i[0]+" "+i[1]+" "+i[2] i.remove(a1) i.remove(b1) i.remove(c1) name2f.append(p) elif a1.isalpha: if b1.isalpha: p = i[0]+" "+i[1] i.remove(a1) i.remove(b1) name2f.append(p) elif a1.isalpha: name2f.append(a1) i.remove(a1) print("false 1") else: print("broken") isalpha and isdigit route does not seem to work nor does regex, not sure what is up. My results are print3 down the line. Not sure where the issue lies. A: Figured it out, went through the elements as a range and it worked: item = [] for items in xxxx: for i in items[0:3]: if re.match(r'[A-Z]', i) and bool(re.search(r'[0-9]', i)) == False: item.append(i) items.remove(i) w = " ".join(item) print(w) print("") print(items) A: The first problem with code shown is isalpha() is a function. The function object isalpha is always non falsy. Secondly, each of your if conditions check the exact same thing, so only the top one will run. Also, your logic is only trying to generate something like name2f = ['a', 'aa', 'aaa', 'a'] since you only check first 3 elements, so the b strings are never looked at. Break your code into two parts. You can filter non-digits simply with all_chars = [x for x in lst if not x.isdigit()] Then, write a function to join all adjacent characters, such as def collect_chars(lst): combined = lst[:1] result = [] for val in lst[1:]: if val != combined[-1]: # current char not last seen char, dump the collected values so far result.append(''.join(combined)) # and start a new string combined = [val] else: # keep adding matching strings combined.append(val) # if reached end of string, dump what has been collected so far result.append(''.join(combined)) del combined return result Then run both over the original list. for i in xxxx: all_chars = [x for x in i if not x.isdigit()] lst = collect_chars(all_chars) print(lst) Outputs ['a', 'b'] ['aa', 'b'] ['aaa', 'b'] ['a', 'b']
I have a list of list. Need to merge all the elements that is only "a" letters into a single string, moving the other elements down a position
x1 = ['a','1','2','b','4'] x2 = ['a','a','2','b','4'] x3 = ['a','a','a','b','4'] x4 = ['a','1','2','b','4'] xxxx = x1,x2,x3,x4 name2f = [] for i in xxxx: a1 = i[0] b1 = i[1] c1 = i[2] if a1.isalpha: if b1.isalpha: if c1.isalpha: print("false 3") p = i[0]+" "+i[1]+" "+i[2] i.remove(a1) i.remove(b1) i.remove(c1) name2f.append(p) elif a1.isalpha: if b1.isalpha: p = i[0]+" "+i[1] i.remove(a1) i.remove(b1) name2f.append(p) elif a1.isalpha: name2f.append(a1) i.remove(a1) print("false 1") else: print("broken") isalpha and isdigit route does not seem to work nor does regex, not sure what is up. My results are print3 down the line. Not sure where the issue lies.
[ "Figured it out, went through the elements as a range and it worked:\n item = []\n for items in xxxx:\n for i in items[0:3]:\n if re.match(r'[A-Z]', i) and bool(re.search(r'[0-9]', i)) == False:\n item.append(i)\n items.remove(i)\n\n w = \" \".join(item)\n print(w)\n print(\"\")\n print(items)\n\n", "The first problem with code shown is isalpha() is a function. The function object isalpha is always non falsy.\nSecondly, each of your if conditions check the exact same thing, so only the top one will run.\nAlso, your logic is only trying to generate something like name2f = ['a', 'aa', 'aaa', 'a'] since you only check first 3 elements, so the b strings are never looked at.\n\nBreak your code into two parts.\nYou can filter non-digits simply with\nall_chars = [x for x in lst if not x.isdigit()]\n\nThen, write a function to join all adjacent characters, such as\ndef collect_chars(lst):\n combined = lst[:1]\n result = []\n for val in lst[1:]:\n if val != combined[-1]:\n # current char not last seen char, dump the collected values so far\n result.append(''.join(combined))\n # and start a new string\n combined = [val]\n else:\n # keep adding matching strings\n combined.append(val)\n # if reached end of string, dump what has been collected so far\n result.append(''.join(combined))\n del combined\n\n return result\n\nThen run both over the original list.\nfor i in xxxx:\n all_chars = [x for x in i if not x.isdigit()]\n lst = collect_chars(all_chars)\n print(lst)\n\nOutputs\n['a', 'b']\n['aa', 'b']\n['aaa', 'b']\n['a', 'b']\n\n" ]
[ 1, 0 ]
[]
[]
[ "list", "loops", "python" ]
stackoverflow_0074662229_list_loops_python.txt
Q: Add decorator to component decorator in KFP v2 in Vertex AI Usually, KFP v2 supports adding a component decorator like this: @component def test(): print("hello world") I would like to add an additional decorator to add new functionality like this: @component @added_functionality def test(): print("hello world") Where added_functionality is imported and looks like this: from functools import wraps def added_functionality(func): print("starting added functionality") @wraps(func) def wrapper(*args, **kwargs): print("starting wrapper") return func(*args, **kwargs) return wrapper The issue is that when I compile the pipeline, I see 'starting added functionality' printed to the console, but "starting wrapper" doesn't show up in the log in Vertex AI. Am I doing something wrong? A: You aren't. This is a disappointing limitation of Kubeflow currently.
Add decorator to component decorator in KFP v2 in Vertex AI
Usually, KFP v2 supports adding a component decorator like this: @component def test(): print("hello world") I would like to add an additional decorator to add new functionality like this: @component @added_functionality def test(): print("hello world") Where added_functionality is imported and looks like this: from functools import wraps def added_functionality(func): print("starting added functionality") @wraps(func) def wrapper(*args, **kwargs): print("starting wrapper") return func(*args, **kwargs) return wrapper The issue is that when I compile the pipeline, I see 'starting added functionality' printed to the console, but "starting wrapper" doesn't show up in the log in Vertex AI. Am I doing something wrong?
[ "You aren't. This is a disappointing limitation of Kubeflow currently.\n" ]
[ 0 ]
[]
[]
[ "google_cloud_vertex_ai", "kfp", "python" ]
stackoverflow_0071959035_google_cloud_vertex_ai_kfp_python.txt
Q: Does anyone have an example of merging-concatenating chunks of files stored in an AWS S3 Bucket? Currently, we are merging some output files through C# because we used to have these chunks in a drive on a server but now we are going to move these files directly from Snowflake to the S3 Bucket so it should be better to merge these files on the S3 bucket, we know that AWS has some function call Multipart Upload but we don't know if we could upload these files from Snowflake to S3 using that functionality. At this moment we are exploring options, most of what we found is that we could create a lambda function for merging the files that are already in the S3 Bucket but the examples that we found are made mostly in python and our app is on .NET we also found about AWS Glue Crawler but we are not very sure about going with this option, Multipart Upload could be a good option but we lack experience with this type of implementations, so any help or example is welcome. A: At this time, it appears that the best option for merging files from Snowflake to S3 is to use AWS Glue Crawler. AWS Glue is a serverless ETL (Extract, Transform, Load) service that can be used to automate the process of transforming and moving data from Snowflake to S3. In addition, the AWS Glue Crawler can be used to discover data, create and update schemas, and automatically generate ETL scripts. If you are looking for an example, the AWS documentation has some great examples on how to use the Glue Crawler to move data from Snowflake to S3. Additionally, there are many online tutorials and videos that can help you get started. In addition to using the Glue Crawler, you may also want to consider using AWS Lambda functions to automate the process of merging the files in S3. AWS Lambda is a serverless compute service that allows you to run code without having to manage any infrastructure. You can use Lambda functions to automate the process of merging files in S3. However, you will need to write the code in either Python or Java in order to use Lambda functions.
Does anyone have an example of merging-concatenating chunks of files stored in an AWS S3 Bucket?
Currently, we are merging some output files through C# because we used to have these chunks in a drive on a server but now we are going to move these files directly from Snowflake to the S3 Bucket so it should be better to merge these files on the S3 bucket, we know that AWS has some function call Multipart Upload but we don't know if we could upload these files from Snowflake to S3 using that functionality. At this moment we are exploring options, most of what we found is that we could create a lambda function for merging the files that are already in the S3 Bucket but the examples that we found are made mostly in python and our app is on .NET we also found about AWS Glue Crawler but we are not very sure about going with this option, Multipart Upload could be a good option but we lack experience with this type of implementations, so any help or example is welcome.
[ "At this time, it appears that the best option for merging files from Snowflake to S3 is to use AWS Glue Crawler. AWS Glue is a serverless ETL (Extract, Transform, Load) service that can be used to automate the process of transforming and moving data from Snowflake to S3. In addition, the AWS Glue Crawler can be used to discover data, create and update schemas, and automatically generate ETL scripts.\nIf you are looking for an example, the AWS documentation has some great examples on how to use the Glue Crawler to move data from Snowflake to S3. Additionally, there are many online tutorials and videos that can help you get started.\nIn addition to using the Glue Crawler, you may also want to consider using AWS Lambda functions to automate the process of merging the files in S3. AWS Lambda is a serverless compute service that allows you to run code without having to manage any infrastructure. You can use Lambda functions to automate the process of merging files in S3. However, you will need to write the code in either Python or Java in order to use Lambda functions.\n" ]
[ 0 ]
[]
[]
[ ".net", "amazon_s3", "aws_lambda", "c#", "multipart_upload" ]
stackoverflow_0074663063_.net_amazon_s3_aws_lambda_c#_multipart_upload.txt
Q: Segmentation fault in array try to get number of rows and column from user through array but it gives Segmentation fault at run time #include<stdio.h> int main(){ int rows; int column; int arr[rows]; int arr1[column]; printf("Enter the number of rows: "); scanf("%d",&rows); printf("Enter the number of column: "); scanf("%d",&column); printf("\n"); int i=0; while( i<rows) { printf("\n"); printf("Enter the value of rows index: " ); scanf("%d",&arr[i]); printf("\n"); i++; } int j=0; while(j<column) { printf("Enter the value of rows index: " ); scanf("%d",&arr1[j]); printf("\n"); j++; } } // giving Segmentation fault A: At the time of your definition for the "arr" and "arr1" arrays, the value of column and rows is undefined. int rows; int column; int arr[rows]; int arr1[column]; Move the declaration of those arrays after you have received input from the user. printf("Enter the number of rows: "); scanf("%d",&rows); printf("Enter the number of column: "); scanf("%d",&column); printf("\n"); int arr[rows]; int arr1[column]; Give that a try and see if that addresses your segmentation fault. A: The program is giving segmentation fault because the array 'arr' and 'arr1' are declared before taking the input from user. The size of both arrays must be set before they are used. To solve this issue, we need to declare the arrays after taking the input from user. #include<stdio.h> int main(){ int rows; int column; printf("Enter the number of rows: "); scanf("%d",&rows); printf("Enter the number of column: "); scanf("%d",&column); printf("\n"); int arr[rows]; int arr1[column]; int i=0; while( i<rows) { printf("\n"); printf("Enter the value of rows index: " ); scanf("%d",&arr[i]); printf("\n"); i++; } int j=0; while(j<column) { printf("Enter the value of rows index: " ); scanf("%d",&arr1[j]); printf("\n"); j++; } }
Segmentation fault in array
try to get number of rows and column from user through array but it gives Segmentation fault at run time #include<stdio.h> int main(){ int rows; int column; int arr[rows]; int arr1[column]; printf("Enter the number of rows: "); scanf("%d",&rows); printf("Enter the number of column: "); scanf("%d",&column); printf("\n"); int i=0; while( i<rows) { printf("\n"); printf("Enter the value of rows index: " ); scanf("%d",&arr[i]); printf("\n"); i++; } int j=0; while(j<column) { printf("Enter the value of rows index: " ); scanf("%d",&arr1[j]); printf("\n"); j++; } } // giving Segmentation fault
[ "At the time of your definition for the \"arr\" and \"arr1\" arrays, the value of column and rows is undefined.\nint rows;\nint column;\nint arr[rows];\nint arr1[column];\n\nMove the declaration of those arrays after you have received input from the user.\nprintf(\"Enter the number of rows: \");\nscanf(\"%d\",&rows);\nprintf(\"Enter the number of column: \");\nscanf(\"%d\",&column);\nprintf(\"\\n\");\nint arr[rows];\nint arr1[column];\n\nGive that a try and see if that addresses your segmentation fault.\n", "The program is giving segmentation fault because the array 'arr' and 'arr1' are declared before taking the input from user. The size of both arrays must be set before they are used.\nTo solve this issue, we need to declare the arrays after taking the input from user.\n#include<stdio.h>\nint main(){\n int rows;\n int column;\n \n printf(\"Enter the number of rows: \");\n scanf(\"%d\",&rows);\n printf(\"Enter the number of column: \");\n scanf(\"%d\",&column);\n printf(\"\\n\");\n \n int arr[rows];\n int arr1[column];\n \nint i=0;\nwhile( i<rows)\n{ printf(\"\\n\");\n printf(\"Enter the value of rows index: \" );\n scanf(\"%d\",&arr[i]);\n printf(\"\\n\");\n i++;\n}\nint j=0;\nwhile(j<column)\n{\n printf(\"Enter the value of rows index: \" );\n scanf(\"%d\",&arr1[j]);\n printf(\"\\n\");\n j++;\n}\n}\n\n" ]
[ 1, 0 ]
[]
[]
[ "arrays", "c", "fault", "loops", "segmentation_fault" ]
stackoverflow_0074663049_arrays_c_fault_loops_segmentation_fault.txt
Q: Azure function triggered by service bus topic doesn't work I am creating an azure function that is triggered using service bus topic using .Net 6.0. I am trying to run it on my local but it seems that the trigger is not working. I added message to my topic but the function didn't get call. Azure Function [FunctionName("TestFunction")] public static void Run( [ServiceBusTrigger("test-topic", "test-sub", Connection = "AzureWebJobsServiceBus")] string messageBodyAsString, ILogger logger) { logger.LogInformation($"C# function triggered to process a message: {messageBodyAsString}"); } local.settings.json { "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=", "FUNCTIONS_WORKER_RUNTIME": "dotnet", "AzureWebJobsServiceBus": "Endpoint=" } A: if works in azure and you can't debug locally, it could be either firewall or proxy' try first adding "transportType": "amqpWebSockets" to your host.json. that will solve the firewall problem if that is the only problem. Sometimes the proxy can block WebSockets
Azure function triggered by service bus topic doesn't work
I am creating an azure function that is triggered using service bus topic using .Net 6.0. I am trying to run it on my local but it seems that the trigger is not working. I added message to my topic but the function didn't get call. Azure Function [FunctionName("TestFunction")] public static void Run( [ServiceBusTrigger("test-topic", "test-sub", Connection = "AzureWebJobsServiceBus")] string messageBodyAsString, ILogger logger) { logger.LogInformation($"C# function triggered to process a message: {messageBodyAsString}"); } local.settings.json { "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=", "FUNCTIONS_WORKER_RUNTIME": "dotnet", "AzureWebJobsServiceBus": "Endpoint=" }
[ "if works in azure and you can't debug locally, it could be either firewall or proxy' try first adding \"transportType\": \"amqpWebSockets\" to your host.json. that will solve the firewall problem if that is the only problem. Sometimes the proxy can block WebSockets\n\n" ]
[ 1 ]
[]
[]
[ "azure", "azure_servicebus_topics", "azureservicebus", "servicebus" ]
stackoverflow_0074660940_azure_azure_servicebus_topics_azureservicebus_servicebus.txt
Q: How do I add a custom script to my package.json file that runs two commands at the same time? I need to run 2 commands at the same time: 1)npm start 2)nodemon server.js the first in /user/MatildeSalamanca_Project/web-app and second in /user/MatildeSalamanca_Project/web-app/src/server It has to be something like this but with their respective directories "run": "react-scripts start node server.js" A: Try using this instead "run": "cd /user/MatildeSalamanca_Project/web-app && npm start && cd /user/MatildeSalamanca_Project/web-app/src/server && nodemon server.js"
How do I add a custom script to my package.json file that runs two commands at the same time?
I need to run 2 commands at the same time: 1)npm start 2)nodemon server.js the first in /user/MatildeSalamanca_Project/web-app and second in /user/MatildeSalamanca_Project/web-app/src/server It has to be something like this but with their respective directories "run": "react-scripts start node server.js"
[ "Try using this instead\n\"run\": \"cd /user/MatildeSalamanca_Project/web-app && npm start && cd /user/MatildeSalamanca_Project/web-app/src/server && nodemon server.js\"\n\n" ]
[ 1 ]
[]
[]
[ "npm", "npm_start", "package.json" ]
stackoverflow_0074663066_npm_npm_start_package.json.txt
Q: check if grafana agent operator is up and running I have a grafana agent operator and I was trying to create some metrics to monitor if it's up. If I had a simple grafana agent process I would just use something along the lines of absent(up{instance="1.2.3.4:8000"} == 1 but with the Grafana Agent operator the components are dynamic. I don't see issues with monitoring the metrics part. For example, if the grafana-agent-0 stateful set for metrics goes down and a new pod is built the name would be the same. But for logs, the Grafana Agent operator runs a pod (daemon set) for every node with a different name each time. In the log case if a pod grafana-agent-log-vsq5r goes down or a new node is added to the cluster I would have a new pod to monitor with a different name which would create some problems in being able to monitor the changes in the cluster. Anyone that already had this issue or that knows some good way of tackling the issue? A: I would like to suggest using Labels in Grafana Alerting
check if grafana agent operator is up and running
I have a grafana agent operator and I was trying to create some metrics to monitor if it's up. If I had a simple grafana agent process I would just use something along the lines of absent(up{instance="1.2.3.4:8000"} == 1 but with the Grafana Agent operator the components are dynamic. I don't see issues with monitoring the metrics part. For example, if the grafana-agent-0 stateful set for metrics goes down and a new pod is built the name would be the same. But for logs, the Grafana Agent operator runs a pod (daemon set) for every node with a different name each time. In the log case if a pod grafana-agent-log-vsq5r goes down or a new node is added to the cluster I would have a new pod to monitor with a different name which would create some problems in being able to monitor the changes in the cluster. Anyone that already had this issue or that knows some good way of tackling the issue?
[ "I would like to suggest using Labels in Grafana Alerting\n\n" ]
[ 0 ]
[]
[]
[ "grafana", "metrics", "promql" ]
stackoverflow_0073108388_grafana_metrics_promql.txt
Q: Swift: Format String width What I'm wanting to do is very simple in C/C++, Java, and so many other languages. All I want to do is be able to specify the width of a string, similar to this: printf("%-15s", var); This would create of a field width of 15 characters. I've done a lot of googling. I've tried using COpaquepointeras well as String(format:in various ways with no luck. Any suggestions would be greatly appreciated. I could have missed something when googling. A: You can use withCString to quickly convert the string to an array of bytes (technically an UnsafePointer<Int8>): let str = "Hello world" let formatted = str.withCString { String(format: "%-15s", $0) } print("'\(formatted)'") A: You are better to do it yourself let str0 = "alpha" let length = 20 // right justify var str20r = String(count: (length - str0.characters.count), repeatedValue: Character(" ")) str20r.appendContentsOf(str0) // " alpha" // left justify var str20l = str0 str20l.appendContentsOf(String(count: (length - str0.characters.count), repeatedValue: Character(" "))) // "alpha " if you need something 'more general' func formatString(str: String, fixLenght: Int, spacer: Character = Character(" "), justifyToTheRigth: Bool = false)->String { let c = str.characters.count let start = str.characters.startIndex let end = str.characters.endIndex var str = str if c > fixLenght { switch justifyToTheRigth { case true: let range = start.advancedBy(c - fixLenght)..<end return String(str.characters[range]) case false: let range = start..<end.advancedBy(fixLenght - c) return String(str.characters[range]) } } else { var extraSpace = String(count: fixLenght - c, repeatedValue: spacer) if justifyToTheRigth { extraSpace.appendContentsOf(str) return extraSpace } else { str.appendContentsOf(extraSpace) return str } } } let str = "ABCDEFGH" let s0 = formatString(str, fixLenght: 3) let s1 = formatString(str, fixLenght: 3, justifyToTheRigth: true) let s2 = formatString(str, fixLenght: 10, spacer: Character("-")) let s3 = formatString(str, fixLenght: 10, spacer: Character("-"), justifyToTheRigth: true) print(s0) print(s1) print(s2) print(s3) which prints ABC FGH ABCDEFGH-- --ABCDEFGH A: The problem is that Swift strings have variable size elements, so it's ambiguous what "15 characters" is. This is a source of frustration for simple strings — but makes the language more precise when dealing with emoji, regional identifiers, ligatures, etc. You can convert the Swift string to a C-string and use normal formatters (see Santosh's answer). The "Swift" way to handle strings is to begin at the starting index of the collection of Characters and advance N times. For example: let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" let index = alphabet.characters.startIndex.advancedBy(14) // String.CharacterView.Index let allChars = alphabet.characters.prefixThrough(index) // String.CharacterView print(String(allChars)) // "ABCDEFGHIJKLMNO\n" If you want to force padding, you could use an approach like this: extension String { func formatted(characterCount characterCount:Int) -> String { if characterCount < characters.count { return String(characters.prefixThrough(characters.startIndex.advancedBy(characterCount - 1))) } else { return self + String(count: characterCount - characters.count, repeatedValue: " " as Character) } } } let abc = "ABC" let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" print("!\(abc.formatted(characterCount: 15))!") // "!ABC !\n" print("!\(alphabet.formatted(characterCount: 15))!") // "!ABCDEFGHIJKLMNOP!\n" A: Did you try this? let string1 = "string1" let string2 = "string2" let formattedString = String(format: "%-15s - %s", COpaquePointer(string1.cStringUsingEncoding(NSUTF8StringEncoding)!), COpaquePointer(string2.cStringUsingEncoding(NSUTF8StringEncoding)!) ) print(formattedString) //string1 - string2 A: From one hand %@ is used to format String objects: import Foundation var str = "Hello" print(String(format: "%@", str)) But it does not support the width modifier: print(String(format: "%-15@", str)) Will still print unpadded text: "Hello\n" However there is a modifier %s that seems to work with CStrings: var cstr = (str as NSString).utf8String //iOS10+ or .UTF8String otherwise print(String(format: "%-15s", cstr!)) Output: "Hello \n" One nice thing is that you can use the same format specification with NSLog: NSLog("%-15s", cstr!) A: We've got a ton of interesting answers now. Thank you everyone. I wrote the following: func formatLeftJustifiedWidthSpecifier(stringToChange: String, width: Int) -> String { var newString: String = stringToChange newString = newString.stringByPaddingToLength(width, withString: " ", startingAtIndex: 0) return newString } A: To augment the answer above by "Code Different" (thank you!) on Jun 29, 2016, and allow to write something like "hello".center(42); "world".alignLeft(42): extension String { // note: symbol names match to nim std/strutils lib func align (_ boxsz: UInt) -> String { self.withCString { String(format: "%\(boxsz)s", $0) } } func alignLeft (_ boxsz: UInt) -> String { self.withCString { String(format: "%-\(boxsz)s", $0) } } func center (_ boxsz: UInt) -> String { let n = self.count guard boxsz > n else { return self } let padding = boxsz - UInt(n) let R = padding / 2 guard R > 0 else { return " " + self } let L = (padding%2 == 0) ? R : (R+1) return " ".withCString { String(format: "%\(L)s\(self)%\(R)s", $0,$0) } } }
Swift: Format String width
What I'm wanting to do is very simple in C/C++, Java, and so many other languages. All I want to do is be able to specify the width of a string, similar to this: printf("%-15s", var); This would create of a field width of 15 characters. I've done a lot of googling. I've tried using COpaquepointeras well as String(format:in various ways with no luck. Any suggestions would be greatly appreciated. I could have missed something when googling.
[ "You can use withCString to quickly convert the string to an array of bytes (technically an UnsafePointer<Int8>):\nlet str = \"Hello world\"\nlet formatted = str.withCString { String(format: \"%-15s\", $0) }\n\nprint(\"'\\(formatted)'\")\n\n", "You are better to do it yourself\nlet str0 = \"alpha\"\nlet length = 20\n// right justify\nvar str20r = String(count: (length - str0.characters.count), repeatedValue: Character(\" \"))\nstr20r.appendContentsOf(str0)\n// \" alpha\"\n\n// left justify\nvar str20l = str0\nstr20l.appendContentsOf(String(count: (length - str0.characters.count), repeatedValue: Character(\" \")))\n// \"alpha \"\n\nif you need something 'more general'\nfunc formatString(str: String, fixLenght: Int, spacer: Character = Character(\" \"), justifyToTheRigth: Bool = false)->String {\n let c = str.characters.count\n let start = str.characters.startIndex\n let end = str.characters.endIndex\n var str = str\n if c > fixLenght {\n switch justifyToTheRigth {\n case true:\n let range = start.advancedBy(c - fixLenght)..<end\n return String(str.characters[range])\n case false:\n let range = start..<end.advancedBy(fixLenght - c)\n return String(str.characters[range])\n }\n } else {\n var extraSpace = String(count: fixLenght - c, repeatedValue: spacer)\n if justifyToTheRigth {\n extraSpace.appendContentsOf(str)\n return extraSpace\n } else {\n str.appendContentsOf(extraSpace)\n return str\n }\n }\n}\n\nlet str = \"ABCDEFGH\"\nlet s0 = formatString(str, fixLenght: 3)\nlet s1 = formatString(str, fixLenght: 3, justifyToTheRigth: true)\nlet s2 = formatString(str, fixLenght: 10, spacer: Character(\"-\"))\nlet s3 = formatString(str, fixLenght: 10, spacer: Character(\"-\"), justifyToTheRigth: true)\n\nprint(s0)\nprint(s1)\nprint(s2)\nprint(s3)\n\nwhich prints\nABC\nFGH\nABCDEFGH--\n--ABCDEFGH\n\n", "The problem is that Swift strings have variable size elements, so it's ambiguous what \"15 characters\" is. This is a source of frustration for simple strings — but makes the language more precise when dealing with emoji, regional identifiers, ligatures, etc.\nYou can convert the Swift string to a C-string and use normal formatters (see Santosh's answer). The \"Swift\" way to handle strings is to begin at the starting index of the collection of Characters and advance N times. For example:\nlet alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\nlet index = alphabet.characters.startIndex.advancedBy(14) // String.CharacterView.Index\nlet allChars = alphabet.characters.prefixThrough(index) // String.CharacterView\n\nprint(String(allChars)) // \"ABCDEFGHIJKLMNO\\n\"\n\nIf you want to force padding, you could use an approach like this:\nextension String {\n func formatted(characterCount characterCount:Int) -> String {\n if characterCount < characters.count {\n return String(characters.prefixThrough(characters.startIndex.advancedBy(characterCount - 1)))\n } else {\n return self + String(count: characterCount - characters.count, repeatedValue: \" \" as Character)\n }\n }\n}\n\nlet abc = \"ABC\"\nlet alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\nprint(\"!\\(abc.formatted(characterCount: 15))!\")\n// \"!ABC !\\n\"\n\nprint(\"!\\(alphabet.formatted(characterCount: 15))!\")\n// \"!ABCDEFGHIJKLMNOP!\\n\"\n\n", "Did you try this?\nlet string1 = \"string1\"\nlet string2 = \"string2\"\nlet formattedString = String(format: \"%-15s - %s\",\n COpaquePointer(string1.cStringUsingEncoding(NSUTF8StringEncoding)!),\n COpaquePointer(string2.cStringUsingEncoding(NSUTF8StringEncoding)!)\n)\n\nprint(formattedString)\n//string1 - string2\n\n", "From one hand %@ is used to format String objects:\nimport Foundation\n\nvar str = \"Hello\"\nprint(String(format: \"%@\", str))\n\nBut it does not support the width modifier:\nprint(String(format: \"%-15@\", str))\n\nWill still print unpadded text:\n\"Hello\\n\"\n\nHowever there is a modifier %s that seems to work with CStrings:\nvar cstr = (str as NSString).utf8String //iOS10+ or .UTF8String otherwise\n\nprint(String(format: \"%-15s\", cstr!))\n\nOutput:\n\"Hello \\n\"\n\nOne nice thing is that you can use the same format specification with NSLog:\nNSLog(\"%-15s\", cstr!)\n\n", "We've got a ton of interesting answers now. Thank you everyone. I wrote the following:\nfunc formatLeftJustifiedWidthSpecifier(stringToChange: String, width: Int) -> String {\n\n var newString: String = stringToChange\n newString = newString.stringByPaddingToLength(width, withString: \" \", startingAtIndex: 0)\n return newString\n}\n\n", "To augment the answer above by \"Code Different\" (thank you!) on Jun 29, 2016, and allow to write something like \"hello\".center(42); \"world\".alignLeft(42):\nextension String {\n\n // note: symbol names match to nim std/strutils lib\n\n func align (_ boxsz: UInt) -> String {\n self.withCString { String(format: \"%\\(boxsz)s\", $0) }\n }\n\n func alignLeft (_ boxsz: UInt) -> String {\n self.withCString { String(format: \"%-\\(boxsz)s\", $0) }\n }\n\n func center (_ boxsz: UInt) -> String {\n let n = self.count\n guard boxsz > n else { return self }\n let padding = boxsz - UInt(n)\n let R = padding / 2\n guard R > 0 else { return \" \" + self }\n let L = (padding%2 == 0) ? R : (R+1)\n return \" \".withCString { String(format: \"%\\(L)s\\(self)%\\(R)s\", $0,$0) }\n }\n\n}\n\n" ]
[ 3, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "format", "string", "swift" ]
stackoverflow_0038103310_format_string_swift.txt
Q: Is it possible to block malicious domains in AWS by adding them in Threat List? I am trying to block malicious domains through AWS Guard Duty which were being queried by some of the EC2 instances. During some research I found out, We can block only IP addresses by adding them in Threat list not the domains. So, is there any same way for blacklisting domains too ? If not, I would also like to know about any alternative idea. The domain for which we have received alert is not even registered. Its somewhat look like this. bpschrex***.co.in On internet, I came across a security blog which tells us that the attacker intentionally uses unregistered domains in their malwares so that if they got a hit, they will later register the domain and gain access for their benefit. A: Posting the answer to my question: "It is not possible to block domains till date in AWS with the help of the GuardDuty Threat list. Only IPs are allowed."
Is it possible to block malicious domains in AWS by adding them in Threat List?
I am trying to block malicious domains through AWS Guard Duty which were being queried by some of the EC2 instances. During some research I found out, We can block only IP addresses by adding them in Threat list not the domains. So, is there any same way for blacklisting domains too ? If not, I would also like to know about any alternative idea. The domain for which we have received alert is not even registered. Its somewhat look like this. bpschrex***.co.in On internet, I came across a security blog which tells us that the attacker intentionally uses unregistered domains in their malwares so that if they got a hit, they will later register the domain and gain access for their benefit.
[ "Posting the answer to my question:\n\"It is not possible to block domains till date in AWS with the help of the GuardDuty Threat list. Only IPs are allowed.\"\n" ]
[ 0 ]
[]
[]
[ "amazon_guardduty", "amazon_web_services", "cloud", "cloud_security" ]
stackoverflow_0071215804_amazon_guardduty_amazon_web_services_cloud_cloud_security.txt
Q: Askbot: Is posible to turn a whole askbot instance to "read only"? I need to turn a whole instance of askbot to "read only". There is a configuration param or an easy way to do that? Why I need that? I created a new instance of askbot where people will participate and put links to another askbot instance as references. I don't want people to be allowed to write in the old instance, I want them to generate content only in the new askbot instance. A: Not at the moment, but a read-only mode would be a useful feature. I'm sure we'll have it at some point (I work at Askbot). A: This option has been added in the mean time. It's available in the admin settings under "Access control settings" Look for: Make site read-only [ ] Default value: False
Askbot: Is posible to turn a whole askbot instance to "read only"?
I need to turn a whole instance of askbot to "read only". There is a configuration param or an easy way to do that? Why I need that? I created a new instance of askbot where people will participate and put links to another askbot instance as references. I don't want people to be allowed to write in the old instance, I want them to generate content only in the new askbot instance.
[ "Not at the moment, but a read-only mode would be a useful feature. I'm sure we'll have it at some point (I work at Askbot).\n", "This option has been added in the mean time. It's available in the admin settings under \"Access control settings\"\nLook for:\nMake site read-only [ ]\nDefault value: False\n\n" ]
[ 1, 0 ]
[]
[]
[ "askbot" ]
stackoverflow_0016711959_askbot.txt
Q: How to split sales from weekly data to daily without taking weekends into account? (SSMS) I have this dataset: create table ds ( dt date, summ int ); insert into ds values ('26.02.2013', 312) insert into ds values ('05.03.2013', 833) insert into ds values ('12.03.2013', 225) insert into ds values ('19.03.2013', 453) insert into ds values ('26.03.2013', 774) insert into ds values ('02.04.2013', 719) insert into ds values ('09.04.2013', 136) insert into ds values ('16.04.2013', 133) insert into ds values ('23.04.2013', 157) insert into ds values ('30.04.2013', 850) insert into ds values ('07.05.2013', 940) insert into ds values ('14.05.2013', 933) insert into ds values ('21.05.2013', 422) insert into ds values ('28.05.2013', 952) insert into ds values ('04.06.2013', 136) insert into ds values ('11.06.2013', 701) ; As the title suggests I need to split sales from weekly data to daily. The thing is that there are no sales on weekends, so the number of daily sales on Saturday and Sunday is 0. In that case the simple (week number/7) doesn't actually work. It must be (week number/5), but I don't know how to exclude weeknds from my code. For example, 05.03.2013 - 2 days of this particular week refers to February and 3 of them to March. Then I need to aggregate all sales from all days that refers to a specific month into one number. The final table should include 2 columns - 1) the sum for each month and 2) month number (from 2 to 6 in this particular example). Here is my little template where you can see a wanted result (obviously the calculations for each month are not right): drop table if exists #subtable declare @first_date date = (select top 1 dt from ds) declare @mindate date = (select DATEADD(day, -6, @first_date)) declare @maxdate date = (select max(dt) from ds) ;with cte as ( select @mindate as firstdate from ds union all select dateadd(day, 1, firstdate) from cte where firstdate < @maxdate and firstdate >= @mindate ) select distinct * into #subtable from cte option(maxrecursion 0) select month(firstdate) as MonthNumber, round(sum(dailysale), 2) as overall_sales from ( select d.firstdate, dailysale = ds.summ / 7 from ds full join #subtable d on d.firstdate <= ds.dt and d.firstdate >= DATEADD(day, -6, ds.dt) ) as newttt group by month(firstdate); A: I am posting this attempt in t-sql to clarify your question. Your sample data is very small, so it's difficult to ascertain how the final aggregation should be handled. Please run this and help us edit for you. This query assumes there is one day per week in your source table (are they always Tuesdays?) and you want to average that summ over the 5 weekdays. --SET DATEFORMAT dmy; declare @ds table ( dt date, summ int ); insert into @ds values ('26.02.2013', 312) insert into @ds values ('05.03.2013', 833) insert into @ds values ('12.03.2013', 225) insert into @ds values ('19.03.2013', 453) insert into @ds values ('26.03.2013', 774) insert into @ds values ('02.04.2013', 719) insert into @ds values ('09.04.2013', 136) insert into @ds values ('16.04.2013', 133) insert into @ds values ('23.04.2013', 157) insert into @ds values ('30.04.2013', 850) insert into @ds values ('07.05.2013', 940) insert into @ds values ('14.05.2013', 933) insert into @ds values ('21.05.2013', 422) insert into @ds values ('28.05.2013', 952) insert into @ds values ('04.06.2013', 136) insert into @ds values ('11.06.2013', 701); select *, datename(dw, s.d) as [Weekday], case when datepart(dw, s.d) not in (1,7) then summ/5. else 0 end as [DailySumm] from @ds cross apply (select dateadd(day, -n.n, dt) from (values(0),(1),(2),(3),(4),(5),(6))n(n) )s(d); This returns a row per day for the preceding week of each summ, with the daily average for each weekday: ... 2013-02-26 312 2013-02-20 Wednesday 62.400000 2013-03-05 833 2013-03-05 Tuesday 166.600000 2013-03-05 833 2013-03-04 Monday 166.600000 2013-03-05 833 2013-03-03 Sunday 0.000000 2013-03-05 833 2013-03-02 Saturday 0.000000 2013-03-05 833 2013-03-01 Friday 166.600000 2013-03-05 833 2013-02-28 Thursday 166.600000 2013-03-05 833 2013-02-27 Wednesday 166.600000 2013-03-12 225 2013-03-12 Tuesday 45.000000 ... Hopefully this helps you describe exactly how you want the weekly/monthly aggregation to be handled. With this dataset, grouping by week or month should be straightforward.
How to split sales from weekly data to daily without taking weekends into account? (SSMS)
I have this dataset: create table ds ( dt date, summ int ); insert into ds values ('26.02.2013', 312) insert into ds values ('05.03.2013', 833) insert into ds values ('12.03.2013', 225) insert into ds values ('19.03.2013', 453) insert into ds values ('26.03.2013', 774) insert into ds values ('02.04.2013', 719) insert into ds values ('09.04.2013', 136) insert into ds values ('16.04.2013', 133) insert into ds values ('23.04.2013', 157) insert into ds values ('30.04.2013', 850) insert into ds values ('07.05.2013', 940) insert into ds values ('14.05.2013', 933) insert into ds values ('21.05.2013', 422) insert into ds values ('28.05.2013', 952) insert into ds values ('04.06.2013', 136) insert into ds values ('11.06.2013', 701) ; As the title suggests I need to split sales from weekly data to daily. The thing is that there are no sales on weekends, so the number of daily sales on Saturday and Sunday is 0. In that case the simple (week number/7) doesn't actually work. It must be (week number/5), but I don't know how to exclude weeknds from my code. For example, 05.03.2013 - 2 days of this particular week refers to February and 3 of them to March. Then I need to aggregate all sales from all days that refers to a specific month into one number. The final table should include 2 columns - 1) the sum for each month and 2) month number (from 2 to 6 in this particular example). Here is my little template where you can see a wanted result (obviously the calculations for each month are not right): drop table if exists #subtable declare @first_date date = (select top 1 dt from ds) declare @mindate date = (select DATEADD(day, -6, @first_date)) declare @maxdate date = (select max(dt) from ds) ;with cte as ( select @mindate as firstdate from ds union all select dateadd(day, 1, firstdate) from cte where firstdate < @maxdate and firstdate >= @mindate ) select distinct * into #subtable from cte option(maxrecursion 0) select month(firstdate) as MonthNumber, round(sum(dailysale), 2) as overall_sales from ( select d.firstdate, dailysale = ds.summ / 7 from ds full join #subtable d on d.firstdate <= ds.dt and d.firstdate >= DATEADD(day, -6, ds.dt) ) as newttt group by month(firstdate);
[ "I am posting this attempt in t-sql to clarify your question. Your sample data is very small, so it's difficult to ascertain how the final aggregation should be handled. Please run this and help us edit for you.\nThis query assumes there is one day per week in your source table (are they always Tuesdays?) and you want to average that summ over the 5 weekdays.\n--SET DATEFORMAT dmy;\n\ndeclare @ds table\n(\ndt date,\nsumm int\n);\ninsert into @ds values ('26.02.2013', 312)\ninsert into @ds values ('05.03.2013', 833)\ninsert into @ds values ('12.03.2013', 225)\ninsert into @ds values ('19.03.2013', 453)\ninsert into @ds values ('26.03.2013', 774)\ninsert into @ds values ('02.04.2013', 719)\ninsert into @ds values ('09.04.2013', 136)\ninsert into @ds values ('16.04.2013', 133)\ninsert into @ds values ('23.04.2013', 157)\ninsert into @ds values ('30.04.2013', 850)\ninsert into @ds values ('07.05.2013', 940)\ninsert into @ds values ('14.05.2013', 933)\ninsert into @ds values ('21.05.2013', 422)\ninsert into @ds values ('28.05.2013', 952)\ninsert into @ds values ('04.06.2013', 136)\ninsert into @ds values ('11.06.2013', 701);\n\n \nselect *, \n datename(dw, s.d) as [Weekday], \n case when datepart(dw, s.d) not in (1,7) then summ/5. else 0 end as [DailySumm] \nfrom @ds \ncross\napply (select dateadd(day, -n.n, dt)\n from (values(0),(1),(2),(3),(4),(5),(6))n(n)\n)s(d);\n\nThis returns a row per day for the preceding week of each summ, with the daily average for each weekday:\n...\n2013-02-26 312 2013-02-20 Wednesday 62.400000\n2013-03-05 833 2013-03-05 Tuesday 166.600000\n2013-03-05 833 2013-03-04 Monday 166.600000\n2013-03-05 833 2013-03-03 Sunday 0.000000\n2013-03-05 833 2013-03-02 Saturday 0.000000\n2013-03-05 833 2013-03-01 Friday 166.600000\n2013-03-05 833 2013-02-28 Thursday 166.600000\n2013-03-05 833 2013-02-27 Wednesday 166.600000\n2013-03-12 225 2013-03-12 Tuesday 45.000000\n...\n\nHopefully this helps you describe exactly how you want the weekly/monthly aggregation to be handled. With this dataset, grouping by week or month should be straightforward.\n" ]
[ 1 ]
[]
[]
[ "date", "sql", "sql_server" ]
stackoverflow_0074656750_date_sql_sql_server.txt
Q: Adding edges to Graph by iterating through adjacency matrix I have this code, which adds edges with a weight to a graph from adjacency matrix: matrix = [[0, 1, 2, 3, 4], [1, 0, 5, 6, 0], [2, 5, 0, 0, 0], [3, 0, 0, 0, 6], [4, 0, 0, 6, 0]] g1 = Graph(len(matrix)) for i in range(len(matrix)): for j in range(len(matrix)): if matrix[i][j] > 0: g1.add_edge(i, j, matrix[i][j]) The problem with this code is that it adds same edges twice, f.e it adds edge 0 - 1 and 1 -0, 0 - 2 and 2 - 0. What I want is to add those edges only once. Is this possible somehow? I added this print print(f'Addind edge {i}-{j} with weight {matrix[i][j]}') statement so you could see what is happening. Output: Addind edge 0-1 with weight 1 Addind edge 0-2 with weight 2 Addind edge 0-3 with weight 3 Addind edge 0-4 with weight 4 Addind edge 1-0 with weight 1 Addind edge 1-2 with weight 5 Addind edge 1-3 with weight 6 Addind edge 2-0 with weight 2 Addind edge 2-1 with weight 5 Addind edge 3-0 with weight 3 Addind edge 3-4 with weight 6 Addind edge 4-0 with weight 4 Addind edge 4-3 with weight 6 A: One way to solve this is to add an additional check for the edge that is being added, before actually adding the edge. For example, you can add a check to make sure the edge is not already present in the graph. You can do this by looping through the graph and checking if the edge is already present before adding it. Here is an example of how to do this: g1 = Graph(len(matrix)) for i in range(len(matrix)): for j in range(len(matrix)): if matrix[i][j] > 0: # check if the edge is already present if not g1.has_edge(i, j): g1.add_edge(i, j, matrix[i][j]) A: To add edges to a graph from an adjacency matrix such that each edge is added only once, you can use the following approach: Check if the value at the current matrix[i][j] position is greater than 0. This indicates that there is an edge between the vertices i and j with weight matrix[i][j]. If matrix[i][j] is greater than 0, check if j is greater than i. This ensures that we only add each edge once, since for an undirected graph, the edge i-j is the same as the edge j-i. If j is greater than i, add the edge i-j to the graph with weight matrix[i][j]. Here is an example of how you can modify your code to implement this approach: matrix = [[0, 1, 2, 3, 4], [1, 0, 5, 6, 0], [2, 5, 0, 0, 0], [3, 0, 0, 0, 6], [4, 0, 0, 6, 0]] g1 = Graph(len(matrix)) for i in range(len(matrix)): for j in range(len(matrix)): if matrix[i][j] > 0 and j > i: # Check if matrix[i][j] is greater than 0 and j is greater than i g1.add_edge(i, j, matrix[i][j]) # Add edge i-j with weight matrix[i][j] With this change, the code will only add each edge once, resulting in the following output when you print the edges in the graph: Addind edge 0-1 with weight 1 Addind edge 0-2 with weight 2 Addind edge 0-3 with weight 3 Addind edge 0-4 with weight 4 Addind edge 1-2 with weight 5 Addind edge 1-3 with weight 6 Addind edge 3-4 with weight 6
Adding edges to Graph by iterating through adjacency matrix
I have this code, which adds edges with a weight to a graph from adjacency matrix: matrix = [[0, 1, 2, 3, 4], [1, 0, 5, 6, 0], [2, 5, 0, 0, 0], [3, 0, 0, 0, 6], [4, 0, 0, 6, 0]] g1 = Graph(len(matrix)) for i in range(len(matrix)): for j in range(len(matrix)): if matrix[i][j] > 0: g1.add_edge(i, j, matrix[i][j]) The problem with this code is that it adds same edges twice, f.e it adds edge 0 - 1 and 1 -0, 0 - 2 and 2 - 0. What I want is to add those edges only once. Is this possible somehow? I added this print print(f'Addind edge {i}-{j} with weight {matrix[i][j]}') statement so you could see what is happening. Output: Addind edge 0-1 with weight 1 Addind edge 0-2 with weight 2 Addind edge 0-3 with weight 3 Addind edge 0-4 with weight 4 Addind edge 1-0 with weight 1 Addind edge 1-2 with weight 5 Addind edge 1-3 with weight 6 Addind edge 2-0 with weight 2 Addind edge 2-1 with weight 5 Addind edge 3-0 with weight 3 Addind edge 3-4 with weight 6 Addind edge 4-0 with weight 4 Addind edge 4-3 with weight 6
[ "One way to solve this is to add an additional check for the edge that is being added, before actually adding the edge. For example, you can add a check to make sure the edge is not already present in the graph. You can do this by looping through the graph and checking if the edge is already present before adding it.\nHere is an example of how to do this:\ng1 = Graph(len(matrix))\nfor i in range(len(matrix)):\n for j in range(len(matrix)):\n if matrix[i][j] > 0:\n # check if the edge is already present\n if not g1.has_edge(i, j):\n g1.add_edge(i, j, matrix[i][j])\n\n", "To add edges to a graph from an adjacency matrix such that each edge is added only once, you can use the following approach:\n\nCheck if the value at the current matrix[i][j] position is greater than 0. This indicates that there is an edge between the vertices i and j with weight matrix[i][j].\nIf matrix[i][j] is greater than 0, check if j is greater than i. This ensures that we only add each edge once, since for an undirected graph, the edge i-j is the same as the edge j-i.\nIf j is greater than i, add the edge i-j to the graph with weight matrix[i][j].\nHere is an example of how you can modify your code to implement this approach:\n\nmatrix = [[0, 1, 2, 3, 4],\n [1, 0, 5, 6, 0],\n [2, 5, 0, 0, 0],\n [3, 0, 0, 0, 6],\n [4, 0, 0, 6, 0]]\n\ng1 = Graph(len(matrix))\nfor i in range(len(matrix)):\n for j in range(len(matrix)):\n if matrix[i][j] > 0 and j > i: # Check if matrix[i][j] is greater than 0 and j is greater than i\n g1.add_edge(i, j, matrix[i][j]) # Add edge i-j with weight matrix[i][j]\n\nWith this change, the code will only add each edge once, resulting in the following output when you print the edges in the graph:\nAddind edge 0-1 with weight 1\nAddind edge 0-2 with weight 2\nAddind edge 0-3 with weight 3\nAddind edge 0-4 with weight 4\nAddind edge 1-2 with weight 5\nAddind edge 1-3 with weight 6\nAddind edge 3-4 with weight 6\n\n" ]
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074663056_python_python_3.x.txt
Q: Draw vertical line on Signal or Entry Command? Trying to add the a vertical line on signal or strategy.entry command. Better on calibEntry // Figure out take profit price calibEntry = close - (close * prforentry) longExitPrice = strategy.position_avg_price * (1 + longProfitPerc) shortExitPrice = strategy.position_avg_price * (1 - shortProfitPerc) //Strategy Long Entry if ls strategy.entry("Long",strategy.long, limit = calibEntry) Any Help will be appreciated. Tried everything nothing working. A: Give this a shot //Strategy Short Entry if ss strategy.entry("Short",strategy.short, limit = calibEntry) // Add a vertical line plot(series=calibEntry, title="Calib Entry", color=color.green, style=plot.style_line)
Draw vertical line on Signal or Entry Command?
Trying to add the a vertical line on signal or strategy.entry command. Better on calibEntry // Figure out take profit price calibEntry = close - (close * prforentry) longExitPrice = strategy.position_avg_price * (1 + longProfitPerc) shortExitPrice = strategy.position_avg_price * (1 - shortProfitPerc) //Strategy Long Entry if ls strategy.entry("Long",strategy.long, limit = calibEntry) Any Help will be appreciated. Tried everything nothing working.
[ "Give this a shot\n//Strategy Short Entry\nif ss\n strategy.entry(\"Short\",strategy.short, limit = calibEntry)\n\n// Add a vertical line\nplot(series=calibEntry, title=\"Calib Entry\", color=color.green, style=plot.style_line)\n\n" ]
[ 0 ]
[]
[]
[ "line", "pine_script", "signals" ]
stackoverflow_0074663082_line_pine_script_signals.txt
Q: Converting markdown to HTML in Go I am writing a library to convert markdown to HTML. In Go, the common library for this use case is https://github.com/yuin/goldmark. Input: --- title: Title 1 slug: title-1 --- Post excerpt <!-- more --> # Heading 1 ## Heading 2 ... Does goldmark have any extension to extract the excerpt text? I want to merge it into the frontmatter. Is there any way to get the raw markdown text without frontmatter & excerpt (for the above example. The expected text should start from # Heading 1) How to extract image links from the input markdown? Thank you! A: The goldmark library does not have a specific extension to extract the excerpt text. However, you can use the goldmark parser and AST (Abstract Syntax Tree) to manually parse the input and extract the excerpt text. The goldmark library does not provide a built-in way to extract the raw markdown text without frontmatter and excerpt. However, you can use the goldmark parser to manually parse the input and remove the frontmatter and the excerpt. To extract image links from the input markdown, you can use the goldmark parser and AST to manually parse the input and extract the image links.
Converting markdown to HTML in Go
I am writing a library to convert markdown to HTML. In Go, the common library for this use case is https://github.com/yuin/goldmark. Input: --- title: Title 1 slug: title-1 --- Post excerpt <!-- more --> # Heading 1 ## Heading 2 ... Does goldmark have any extension to extract the excerpt text? I want to merge it into the frontmatter. Is there any way to get the raw markdown text without frontmatter & excerpt (for the above example. The expected text should start from # Heading 1) How to extract image links from the input markdown? Thank you!
[ "The goldmark library does not have a specific extension to extract the excerpt text. However, you can use the goldmark parser and AST (Abstract Syntax Tree) to manually parse the input and extract the excerpt text.\nThe goldmark library does not provide a built-in way to extract the raw markdown text without frontmatter and excerpt. However, you can use the goldmark parser to manually parse the input and remove the frontmatter and the excerpt.\nTo extract image links from the input markdown, you can use the goldmark parser and AST to manually parse the input and extract the image links.\n" ]
[ 0 ]
[]
[]
[ "converters", "go", "markdown" ]
stackoverflow_0074663091_converters_go_markdown.txt
Q: Azure: execute a container instance with parameters I have a container in a Azure Container Registry. I have made a container instance from the registry. This container runs a script.sh at the entry point and echo's a value. FROM ubuntu WORKDIR /docker COPY . . ENTRYPOINT ["./script.sh"] #!/bin/bash if [[ -z $1 ]] ; then echo "simple task: no parameters were passed" else echo $1 fi How do I execute the container and give it a different starting value ? In docker we can just put values at the end of docker run. The container runs using the referenced image, executes the script and deletes the running container. docker run --rm --name "simple-temp" "simple" "value1" "value1" I want the equivalent of this command. Create and run an instance using the registry, run the entry point once, shutdown and delete container. How do I accomplish this in Azure Container Instances ? If not Container Instances, which service to use ? A: In Azure Container Instances, you can pass parameters when creating the container instance with the --command-line argument. For example, you can use the following command: az container create --name "simple-temp" --image "simple" --command-line "./script.sh value1 value2" This will create the container instance, run the script and pass the given parameters to it.
Azure: execute a container instance with parameters
I have a container in a Azure Container Registry. I have made a container instance from the registry. This container runs a script.sh at the entry point and echo's a value. FROM ubuntu WORKDIR /docker COPY . . ENTRYPOINT ["./script.sh"] #!/bin/bash if [[ -z $1 ]] ; then echo "simple task: no parameters were passed" else echo $1 fi How do I execute the container and give it a different starting value ? In docker we can just put values at the end of docker run. The container runs using the referenced image, executes the script and deletes the running container. docker run --rm --name "simple-temp" "simple" "value1" "value1" I want the equivalent of this command. Create and run an instance using the registry, run the entry point once, shutdown and delete container. How do I accomplish this in Azure Container Instances ? If not Container Instances, which service to use ?
[ "In Azure Container Instances, you can pass parameters when creating the container instance with the --command-line argument. For example, you can use the following command:\naz container create --name \"simple-temp\" --image \"simple\" --command-line \"./script.sh value1 value2\"\n\nThis will create the container instance, run the script and pass the given parameters to it.\n" ]
[ 1 ]
[]
[]
[ "azure", "azure_container_instances" ]
stackoverflow_0074663094_azure_azure_container_instances.txt
Q: Select latest row from group Could you help me with a query I'm trying to do please? The idea is to select the latest created_date from each val1, val2 unique combination. https://www.db-fiddle.com/f/fHc6MafduyibJdkLHe9cva/0 Expected result: val1 val2 num1 num2 created_date X A 33 333 2022-11-03 X B 66 666 2022-11-06 X C 88 888 2022-11-08 X D 99 999 2022-11-09 Y A 111 1111 2022-11-11 Ps. This is different from this because I'm using 2 tables: Get records with max value for each group of grouped SQL results A: I would use the windowing function ROW_NUMBER() to avoid a self join: SELECT * FROM (SELECT d.val1, d.val2, s.created_date, s.num1, s.num2, ROW_NUMBER() OVER(PARTITION BY d.val1, d.val2 ORDER BY d.val1, d.val2, s.created_date DESC) AS row_num FROM scan AS s, dir AS d WHERE s.t2id=d.t2id) AS a WHERE a.row_num=1; https://www.db-fiddle.com/f/mj9UExg3bqeHegyVsDcxFA/0
Select latest row from group
Could you help me with a query I'm trying to do please? The idea is to select the latest created_date from each val1, val2 unique combination. https://www.db-fiddle.com/f/fHc6MafduyibJdkLHe9cva/0 Expected result: val1 val2 num1 num2 created_date X A 33 333 2022-11-03 X B 66 666 2022-11-06 X C 88 888 2022-11-08 X D 99 999 2022-11-09 Y A 111 1111 2022-11-11 Ps. This is different from this because I'm using 2 tables: Get records with max value for each group of grouped SQL results
[ "I would use the windowing function ROW_NUMBER() to avoid a self join:\nSELECT *\nFROM\n (SELECT d.val1,\n d.val2,\n s.created_date,\n s.num1,\n s.num2,\n ROW_NUMBER() OVER(PARTITION BY d.val1, d.val2\n ORDER BY d.val1, d.val2, s.created_date DESC) AS row_num\n FROM scan AS s,\n dir AS d\n WHERE s.t2id=d.t2id) AS a\nWHERE a.row_num=1;\n\nhttps://www.db-fiddle.com/f/mj9UExg3bqeHegyVsDcxFA/0\n" ]
[ 1 ]
[]
[]
[ "greatest_n_per_group", "mysql", "select", "sql" ]
stackoverflow_0074662918_greatest_n_per_group_mysql_select_sql.txt
Q: No module named 'tensorflow.tsl' I'm trying to install Tensorflow. I did the installation using the cmd.exe prompt and the installation was a success. But when I try to import TensorFlow appear the following error ModuleNotFoundError: No module named 'tensorflow.tsl' I follow this steps to install tensorflow: $ pip install -U pip $ pip install tensorflow How can I solve the issue? A: Check the version of tensorflow-serving-api and update it with $ pip install tensorflow-serving-api==X.Y.0 X and Y should match your TensorFlow version. You can determine your TensorFlow version with $ pip freeze | grep tensorflow
No module named 'tensorflow.tsl'
I'm trying to install Tensorflow. I did the installation using the cmd.exe prompt and the installation was a success. But when I try to import TensorFlow appear the following error ModuleNotFoundError: No module named 'tensorflow.tsl' I follow this steps to install tensorflow: $ pip install -U pip $ pip install tensorflow How can I solve the issue?
[ "Check the version of tensorflow-serving-api and update it with\n$ pip install tensorflow-serving-api==X.Y.0\n\nX and Y should match your TensorFlow version. You can determine your TensorFlow version with\n$ pip freeze | grep tensorflow\n\n" ]
[ 0 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0074632821_python_tensorflow.txt
Q: What does the fromIntegral type here actually do? I just want to clear my doubts on the fromIntegral type in Haskell. The output for these 2 euclidean distance functions are the same, so what's the point of putting fromIntegral? Like they both give floating point values of the euclidean distances. Also, for the type definition of my function distance2 which uses the fromIntegral type, why is it (Floating a1, Integral a2) and then => (a2, a2) -> (a2, a2) -> a1? I just don't quite get the interpretation of it here. distance2 :: (Floating a1, Integral a2) => (a2, a2) -> (a2, a2) -> a1 distance2 (x1, y1) (x2, y2) = sqrt (fromIntegral ((x2-x1)^2 + (y2 - y1)^2)) distance3 :: Floating a => (a, a) -> (a, a) -> a distance3 (x1, y1) (x2, y2) = sqrt ((x2-x1)^2 + (y2 - y1)^2) Could someone please help with an explanation, thank you :) A: The output for these 2 euclidean distance functions are the same, so what's the point of putting fromIntegral? Like they both give floating point values of the euclidean distances. They both give floating point values, but they don't both take floating point values. > distance3 (pi, 0) (0, 0) 3.141592653589793 > distance2 (pi, 0) (0, 0) <interactive>:2:1: error: • Could not deduce (Integral a20) arising from a use of ‘distance2’ from the context: Floating a1 bound by the inferred type of it :: Floating a1 => a1 <snipped considerable additional error text> Also, for the type definition of my function distance2 which uses the fromIntegral type, why is it (Floating a1, Integral a2) and then => (a2, a2) -> (a2, a2) -> a1? Your distance2 function takes numbers, and returns numbers, but not the same type of numbers. The incoming numbers must be integer-like things, so that you can apply fromIntegral to them; but the outgoing numbers must be floating-point-like things, so that you can apply sqrt to them. For example, here are some monomorphic types that distance2 can be specialized to: (Int, Int) -> (Int, Int) -> Double (Integer, Integer) -> (Integer, Integer) -> Double (Word, Word) -> (Word, Word) -> Float This English description is captured by creating two type variables, each with different constraints. An identical type for distance2, but with somewhat more human-readable variable names, might look like this: (Floating float, Integral int) => (int, int) -> (int, int) -> float A: fromIntegral is used to convert the value of type Integral a => a that your sum-of-squares produces into a value of type Floating a => a that sqrt expects. fromIntegral has type (Integral a, Num b) => a -> b. That means that, given a value of type Integral a, it will give you back a value of any type b that has a Num instance. Since Floating has Num as a superclass (by way of Fractional), that means fromIntegral can produce a value of type Floating a => a. A: There are two relevant typeclasses here: Integral is the typeclass for types representing a subset of integers each Integral type has a function toInteger that converts its values to the arbitrary-length integer type Integer Num is the typeclass for numeric types that include integers as a subset each Num type has a function fromInteger that converts arbitrary-length Integer values to values of that Num type The prelude function fromIntegral is defined as: fromIntegral = fromInteger . toInteger It uses both of those functions to convert any Integral type to any Num type. This is what lets your first function take any Integral type as input: the input type is inferred through the sum-of-squared-differences expression as the input to fromIntegral, and selects toInteger from that type's instance of Integral, while the Floating output type is inferred through the sqrt function to demand it as a result from the fromIntegral call, and selects the fromInteger from the output type's Num instance.
What does the fromIntegral type here actually do?
I just want to clear my doubts on the fromIntegral type in Haskell. The output for these 2 euclidean distance functions are the same, so what's the point of putting fromIntegral? Like they both give floating point values of the euclidean distances. Also, for the type definition of my function distance2 which uses the fromIntegral type, why is it (Floating a1, Integral a2) and then => (a2, a2) -> (a2, a2) -> a1? I just don't quite get the interpretation of it here. distance2 :: (Floating a1, Integral a2) => (a2, a2) -> (a2, a2) -> a1 distance2 (x1, y1) (x2, y2) = sqrt (fromIntegral ((x2-x1)^2 + (y2 - y1)^2)) distance3 :: Floating a => (a, a) -> (a, a) -> a distance3 (x1, y1) (x2, y2) = sqrt ((x2-x1)^2 + (y2 - y1)^2) Could someone please help with an explanation, thank you :)
[ "\nThe output for these 2 euclidean distance functions are the same, so what's the point of putting fromIntegral? Like they both give floating point values of the euclidean distances.\n\nThey both give floating point values, but they don't both take floating point values.\n> distance3 (pi, 0) (0, 0)\n3.141592653589793\n> distance2 (pi, 0) (0, 0)\n<interactive>:2:1: error:\n • Could not deduce (Integral a20) arising from a use of ‘distance2’\n from the context: Floating a1\n bound by the inferred type of it :: Floating a1 => a1\n<snipped considerable additional error text>\n\n\nAlso, for the type definition of my function distance2 which uses the fromIntegral type, why is it (Floating a1, Integral a2) and then => (a2, a2) -> (a2, a2) -> a1?\n\nYour distance2 function takes numbers, and returns numbers, but not the same type of numbers. The incoming numbers must be integer-like things, so that you can apply fromIntegral to them; but the outgoing numbers must be floating-point-like things, so that you can apply sqrt to them. For example, here are some monomorphic types that distance2 can be specialized to:\n(Int, Int) -> (Int, Int) -> Double\n(Integer, Integer) -> (Integer, Integer) -> Double\n(Word, Word) -> (Word, Word) -> Float\n\nThis English description is captured by creating two type variables, each with different constraints. An identical type for distance2, but with somewhat more human-readable variable names, might look like this:\n(Floating float, Integral int) => (int, int) -> (int, int) -> float\n\n", "fromIntegral is used to convert the value of type Integral a => a that your sum-of-squares produces into a value of type Floating a => a that sqrt expects.\nfromIntegral has type (Integral a, Num b) => a -> b. That means that, given a value of type Integral a, it will give you back a value of any type b that has a Num instance. Since Floating has Num as a superclass (by way of Fractional), that means fromIntegral can produce a value of type Floating a => a.\n", "There are two relevant typeclasses here:\n\nIntegral is the typeclass for types representing a subset of integers\n\neach Integral type has a function toInteger that converts its values to the arbitrary-length integer type Integer\n\n\nNum is the typeclass for numeric types that include integers as a subset\n\neach Num type has a function fromInteger that converts arbitrary-length Integer values to values of that Num type\n\n\n\nThe prelude function fromIntegral is defined as:\nfromIntegral = fromInteger . toInteger\n\nIt uses both of those functions to convert any Integral type to any Num type.\nThis is what lets your first function take any Integral type as input: the input type is inferred through the sum-of-squared-differences expression as the input to fromIntegral, and selects toInteger from that type's instance of Integral, while the Floating output type is inferred through the sqrt function to demand it as a result from the fromIntegral call, and selects the fromInteger from the output type's Num instance.\n" ]
[ 3, 1, 0 ]
[]
[]
[ "haskell" ]
stackoverflow_0074657444_haskell.txt
Q: how to create a new git repository from an existing one I have a remote git repository that really replaced everything we had in another older SCM. Many projects and products have been added to the repository over the years. There is a branch in this repo, corresponding to a product that I am interested in. I want to make a brand new git repository from this branch only, not really concerned about loss of history. Is git remote add the solution? I want for both of these repositories to be on the same server. Thoughts? A: In order to create a new Git repository from an existing repository one would typically create a new bare repository and push one or more branches from the existing to the new repository. The following steps illustrates this: Create a new repository. It must be bare in order for you to push to it. $ mkdir /path/to/new_repo $ cd /path/to/new_repo $ git --bare init Note: ensure that your new repository is accessible from the existing repository. There are many ways to do this; let's assume that you have made it accessible via ssh://my_host/new_repo. Push a branch from your existing repository. For example let's say we want to push the branch topic1 from the existing repository and name it master in the new repository. $ cd /path/to/existing_repo $ git push ssh://my_host/new_repo +topic1:master This technique allows you to keep the history from the existing branch. Note: the new repository is effectively a new remote repository. If you want to work with the new repository you must clone it. The following will clone the new repo into a local working directory called new_repo: $ git clone ssh://my_host/new_repo In this example, when you clone the new repository you will see that the master branch is a copy of the topic1 branch of the old repository. A: If you're not worried about losing history, do a git checkout mybranch and then copy the directory contents to another folder. Within that folder, delete the .git folder and then: git init; git commit -a -m "Imported from project Y" A: Pull down the branch like normal and then push the branch to a new repository that you have created using git init. You would use code that looks something like: git push url:///new/repo.git TheBranchFolder This method also keeps all of your previous changes if that is a plus for the situation. A: I don't know my answer still helps or not but this is another way to create a new repository using an existing one. step 1: clone the existing repo. step 2: delete the .git folder in cloned repo folder step 3: create a new repo in git. step 4: in the cloned repo folder run git init step 5: git add . step 6: git remote add origin NEW_REPO/URL step 7: git branch -M "branch_name" step 8: git push --set-upstream origin branch_name A: Our computing environment requires that git repos are created on a remote server, so git init is not a good option. I did this instead. git clone <NEW, EMPTY REPO> new git clone <EXISTING REPO> old cd new git remote add --no-tags -f old_repo ../old git checkout -b main old_repo/main git push origin main
how to create a new git repository from an existing one
I have a remote git repository that really replaced everything we had in another older SCM. Many projects and products have been added to the repository over the years. There is a branch in this repo, corresponding to a product that I am interested in. I want to make a brand new git repository from this branch only, not really concerned about loss of history. Is git remote add the solution? I want for both of these repositories to be on the same server. Thoughts?
[ "In order to create a new Git repository from an existing repository one would typically create a new bare repository and push one or more branches from the existing to the new repository.\nThe following steps illustrates this:\n\nCreate a new repository. It must be bare in order for you to push to it.\n$ mkdir /path/to/new_repo\n$ cd /path/to/new_repo\n$ git --bare init\nNote: ensure that your new repository is accessible from the existing repository. There are many ways to do this; let's assume that you have made it accessible via ssh://my_host/new_repo.\nPush a branch from your existing repository. For example let's say we want to push the branch topic1 from the existing repository and name it master in the new repository.\n$ cd /path/to/existing_repo\n$ git push ssh://my_host/new_repo +topic1:master\n\nThis technique allows you to keep the history from the existing branch.\nNote: the new repository is effectively a new remote repository. If you want to work with the new repository you must clone it. The following will clone the new repo into a local working directory called new_repo:\n$ git clone ssh://my_host/new_repo\n\nIn this example, when you clone the new repository you will see that the master branch is a copy of the topic1 branch of the old repository.\n", "If you're not worried about losing history, do a git checkout mybranch and then copy the directory contents to another folder. Within that folder, delete the .git folder and then:\ngit init; git commit -a -m \"Imported from project Y\"\n\n", "Pull down the branch like normal and then push the branch to a new repository that you have created using git init. You would use code that looks something like:\ngit push url:///new/repo.git TheBranchFolder\n\nThis method also keeps all of your previous changes if that is a plus for the situation.\n", "I don't know my answer still helps or not but this is another way to create a new repository using an existing one. \nstep 1: clone the existing repo.\nstep 2: delete the .git folder in cloned repo folder\nstep 3: create a new repo in git.\nstep 4: in the cloned repo folder run git init\nstep 5: git add .\nstep 6: git remote add origin NEW_REPO/URL \nstep 7: git branch -M \"branch_name\"\nstep 8: git push --set-upstream origin branch_name\n", "Our computing environment requires that git repos are created on a remote server, so git init is not a good option. I did this instead.\ngit clone <NEW, EMPTY REPO> new\ngit clone <EXISTING REPO> old\ncd new\ngit remote add --no-tags -f old_repo ../old\ngit checkout -b main old_repo/main\ngit push origin main\n\n" ]
[ 93, 25, 24, 2, 0 ]
[]
[]
[ "git" ]
stackoverflow_0009844082_git.txt
Q: How to create a String with format? I need to create a String with format which can convert Int, Int64, Double, etc types into String. Using Objective-C, I can do it by: NSString *str = [NSString stringWithFormat:@"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE, STRING_VALUE]; How to do same but in Swift? A: I think this could help you: import Foundation let timeNow = time(nil) let aStr = String(format: "%@%x", "timeNow in hex: ", timeNow) print(aStr) Example result: timeNow in hex: 5cdc9c8d A: nothing special let str = NSString(format:"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, LONG_VALUE, STRING_VALUE) A: let str = "\(INT_VALUE), \(FLOAT_VALUE), \(DOUBLE_VALUE), \(STRING_VALUE)" Update: I wrote this answer before Swift had String(format:) added to it's API. Use the method given by the top answer. A: No NSString required! String(format: "Value: %3.2f\tResult: %3.2f", arguments: [2.7, 99.8]) or String(format:"Value: %3.2f\tResult: %3.2f", 2.7, 99.8) A: I would argue that both let str = String(format:"%d, %f, %ld", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE) and let str = "\(INT_VALUE), \(FLOAT_VALUE), \(DOUBLE_VALUE)" are both acceptable since the user asked about formatting and both cases fit what they are asking for: I need to create a string with format which can convert int, long, double etc. types into string. Obviously the former allows finer control over the formatting than the latter, but that does not mean the latter is not an acceptable answer. A: First read Official documentation for Swift language. Answer should be var str = "\(INT_VALUE) , \(FLOAT_VALUE) , \(DOUBLE_VALUE), \(STRING_VALUE)" println(str) Here 1) Any floating point value by default double EX. var myVal = 5.2 // its double by default; -> If you want to display floating point value then you need to explicitly define such like a EX. var myVal:Float = 5.2 // now its float value; This is far more clear. A: let INT_VALUE=80 let FLOAT_VALUE:Double= 80.9999 let doubleValue=65.0 let DOUBLE_VALUE:Double= 65.56 let STRING_VALUE="Hello" let str = NSString(format:"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE, STRING_VALUE); println(str); A: The accepted answer is definitely the best general solution for this (i.e., just use the String(format:_:) method from Foundation) but... If you are running Swift ≥ 5, you can leverage the new StringInterpolationProtocol protocol to give yourself some very nice syntax sugar for common string formatting use cases in your app. Here is how the official documentation summarizes this new protocol: Represents the contents of a string literal with interpolations while it’s being built up. Some quick examples: extension String.StringInterpolation { /// Quick formatting for *floating point* values. mutating func appendInterpolation(float: Double, decimals: UInt = 2) { let floatDescription = String(format: "%.\(decimals)f%", float) appendLiteral(floatDescription) } /// Quick formatting for *hexadecimal* values. mutating func appendInterpolation(hex: Int) { let hexDescription = String(format: "0x%X", hex) appendLiteral(hexDescription) } /// Quick formatting for *percents*. mutating func appendInterpolation(percent: Double, decimals: UInt = 2) { let percentDescription = String(format: "%.\(decimals)f%%", percent * 100) appendLiteral(percentDescription) } /// Formats the *elapsed time* since the specified start time. mutating func appendInterpolation(timeSince startTime: TimeInterval, decimals: UInt = 2) { let elapsedTime = CACurrentMediaTime() - startTime let elapsedTimeDescription = String(format: "%.\(decimals)fs", elapsedTime) appendLiteral(elapsedTimeDescription) } } which could be used as: let number = 1.2345 "Float: \(float: number)" // "Float: 1.23" "Float: \(float: number, decimals: 1)" // "Float: 1.2" let integer = 255 "Hex: \(hex: integer)" // "Hex: 0xFF" let rate = 0.15 "Percent: \(percent: rate)" // "Percent: 15.00%" "Percent: \(percent: rate, decimals: 0)" // "Percent: 15%" let startTime = CACurrentMediaTime() Thread.sleep(forTimeInterval: 2.8) "∆t was \(timeSince: startTime)" // "∆t was 2.80s" "∆t was \(timeSince: startTime, decimals: 0)" // "∆t was 3s" This was introduced by SE-0228, so please be sure to read the original proposal for a deeper understanding of this new feature. Finally, the protocol documentation is helpful as well. A: I know a lot's of time has passed since this publish, but I've fallen in a similar situation and create a simples class to simplify my life. public struct StringMaskFormatter { public var pattern : String = "" public var replecementChar : Character = "*" public var allowNumbers : Bool = true public var allowText : Bool = false public init(pattern:String, replecementChar:Character="*", allowNumbers:Bool=true, allowText:Bool=true) { self.pattern = pattern self.replecementChar = replecementChar self.allowNumbers = allowNumbers self.allowText = allowText } private func prepareString(string:String) -> String { var charSet : NSCharacterSet! if allowText && allowNumbers { charSet = NSCharacterSet.alphanumericCharacterSet().invertedSet } else if allowText { charSet = NSCharacterSet.letterCharacterSet().invertedSet } else if allowNumbers { charSet = NSCharacterSet.decimalDigitCharacterSet().invertedSet } let result = string.componentsSeparatedByCharactersInSet(charSet) return result.joinWithSeparator("") } public func createFormattedStringFrom(text:String) -> String { var resultString = "" if text.characters.count > 0 && pattern.characters.count > 0 { var finalText = "" var stop = false let tempString = prepareString(text) var formatIndex = pattern.startIndex var tempIndex = tempString.startIndex while !stop { let formattingPatternRange = formatIndex ..< formatIndex.advancedBy(1) if pattern.substringWithRange(formattingPatternRange) != String(replecementChar) { finalText = finalText.stringByAppendingString(pattern.substringWithRange(formattingPatternRange)) } else if tempString.characters.count > 0 { let pureStringRange = tempIndex ..< tempIndex.advancedBy(1) finalText = finalText.stringByAppendingString(tempString.substringWithRange(pureStringRange)) tempIndex = tempIndex.advancedBy(1) } formatIndex = formatIndex.advancedBy(1) if formatIndex >= pattern.endIndex || tempIndex >= tempString.endIndex { stop = true } resultString = finalText } } return resultString } } The follow link send to the complete source code: https://gist.github.com/dedeexe/d9a43894081317e7c418b96d1d081b25 This solution was base on this article: http://vojtastavik.com/2015/03/29/real-time-formatting-in-uitextfield-swift-basics/ A: There is a simple solution I learned with "We <3 Swift" if you can't either import Foundation, use round() and/or does not want a String: var number = 31.726354765 var intNumber = Int(number * 1000.0) var roundedNumber = Double(intNumber) / 1000.0 result: 31.726 A: Use this following code: let intVal=56 let floatval:Double=56.897898 let doubleValue=89.0 let explicitDaouble:Double=89.56 let stringValue:"Hello" let stringValue="String:\(stringValue) Integer:\(intVal) Float:\(floatval) Double:\(doubleValue) ExplicitDouble:\(explicitDaouble) " A: The beauty of String(format:) is that you can save a formatting string and then reuse it later in dozen of places. It also can be localized in this single place. Where as in case of the interpolation approach you must write it again and again. A: Simple functionality is not included in Swift, expected because it's included in other languages, can often be quickly coded for reuse. Pro tip for programmers to create a bag of tricks file that contains all this reuse code. So from my bag of tricks we first need string multiplication for use in indentation. @inlinable func * (string: String, scalar: Int) -> String { let array = [String](repeating: string, count: scalar) return array.joined(separator: "") } and then the code to add commas. extension Int { @inlinable var withCommas:String { var i = self var retValue:[String] = [] while i >= 1000 { retValue.append(String(format:"%03d",i%1000)) i /= 1000 } retValue.append("\(i)") return retValue.reversed().joined(separator: ",") } @inlinable func withCommas(_ count:Int = 0) -> String { let retValue = self.withCommas let indentation = count - retValue.count let indent:String = indentation >= 0 ? " " * indentation : "" return indent + retValue } } I just wrote this last function so I could get the columns to line up. The @inlinable is great because it takes small functions and reduces their functionality so they run faster. You can use either the variable version or, to get a fixed column, use the function version. Lengths set less than the needed columns will just expand the field. Now you have something that is pure Swift and does not rely on some old objective C routine for NSString. A: Since String(format: "%s" ...) is crashing at run time, here is code to allow write something like "hello".center(42); "world".alignLeft(42): extension String { // note: symbol names match to nim std/strutils lib: func align (_ boxsz: UInt) -> String { self.withCString { String(format: "%\(boxsz)s", $0) } } func alignLeft (_ boxsz: UInt) -> String { self.withCString { String(format: "%-\(boxsz)s", $0) } } func center (_ boxsz: UInt) -> String { let n = self.count guard boxsz > n else { return self } let padding = boxsz - UInt(n) let R = padding / 2 guard R > 0 else { return " " + self } let L = (padding%2 == 0) ? R : (R+1) return " ".withCString { String(format: "%\(L)s\(self)%\(R)s", $0,$0) } } }
How to create a String with format?
I need to create a String with format which can convert Int, Int64, Double, etc types into String. Using Objective-C, I can do it by: NSString *str = [NSString stringWithFormat:@"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE, STRING_VALUE]; How to do same but in Swift?
[ "I think this could help you:\nimport Foundation\n\nlet timeNow = time(nil)\nlet aStr = String(format: \"%@%x\", \"timeNow in hex: \", timeNow)\nprint(aStr)\n\nExample result:\ntimeNow in hex: 5cdc9c8d\n\n", "nothing special\nlet str = NSString(format:\"%d , %f, %ld, %@\", INT_VALUE, FLOAT_VALUE, LONG_VALUE, STRING_VALUE)\n\n", "let str = \"\\(INT_VALUE), \\(FLOAT_VALUE), \\(DOUBLE_VALUE), \\(STRING_VALUE)\"\n\nUpdate: I wrote this answer before Swift had String(format:) added to it's API. Use the method given by the top answer.\n", "No NSString required!\nString(format: \"Value: %3.2f\\tResult: %3.2f\", arguments: [2.7, 99.8])\n\nor \nString(format:\"Value: %3.2f\\tResult: %3.2f\", 2.7, 99.8)\n\n", "I would argue that both\nlet str = String(format:\"%d, %f, %ld\", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE)\n\nand\nlet str = \"\\(INT_VALUE), \\(FLOAT_VALUE), \\(DOUBLE_VALUE)\"\n\nare both acceptable since the user asked about formatting and both cases fit what they are asking for:\n\nI need to create a string with format which can convert int, long, double etc. types into string. \n\nObviously the former allows finer control over the formatting than the latter, but that does not mean the latter is not an acceptable answer.\n", "First read Official documentation for Swift language.\nAnswer should be\nvar str = \"\\(INT_VALUE) , \\(FLOAT_VALUE) , \\(DOUBLE_VALUE), \\(STRING_VALUE)\"\nprintln(str)\n\nHere \n1) Any floating point value by default double \nEX.\n var myVal = 5.2 // its double by default;\n\n-> If you want to display floating point value then you need to explicitly define such like a\n EX.\n var myVal:Float = 5.2 // now its float value;\n\nThis is far more clear.\n", "let INT_VALUE=80\nlet FLOAT_VALUE:Double= 80.9999\nlet doubleValue=65.0\nlet DOUBLE_VALUE:Double= 65.56\nlet STRING_VALUE=\"Hello\"\n\nlet str = NSString(format:\"%d , %f, %ld, %@\", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE, STRING_VALUE);\n println(str);\n\n", "The accepted answer is definitely the best general solution for this (i.e., just use the String(format:_:) method from Foundation) but...\nIf you are running Swift ≥ 5, you can leverage the new StringInterpolationProtocol protocol to give yourself some very nice syntax sugar for common string formatting use cases in your app.\nHere is how the official documentation summarizes this new protocol:\n\nRepresents the contents of a string literal with interpolations while it’s being built up.\n\nSome quick examples:\nextension String.StringInterpolation {\n\n /// Quick formatting for *floating point* values.\n mutating func appendInterpolation(float: Double, decimals: UInt = 2) {\n let floatDescription = String(format: \"%.\\(decimals)f%\", float)\n appendLiteral(floatDescription)\n }\n\n /// Quick formatting for *hexadecimal* values.\n mutating func appendInterpolation(hex: Int) {\n let hexDescription = String(format: \"0x%X\", hex)\n appendLiteral(hexDescription)\n }\n\n /// Quick formatting for *percents*.\n mutating func appendInterpolation(percent: Double, decimals: UInt = 2) {\n let percentDescription = String(format: \"%.\\(decimals)f%%\", percent * 100)\n appendLiteral(percentDescription)\n }\n\n /// Formats the *elapsed time* since the specified start time.\n mutating func appendInterpolation(timeSince startTime: TimeInterval, decimals: UInt = 2) {\n let elapsedTime = CACurrentMediaTime() - startTime\n let elapsedTimeDescription = String(format: \"%.\\(decimals)fs\", elapsedTime)\n appendLiteral(elapsedTimeDescription)\n }\n}\n\nwhich could be used as:\nlet number = 1.2345\n\"Float: \\(float: number)\" // \"Float: 1.23\"\n\"Float: \\(float: number, decimals: 1)\" // \"Float: 1.2\"\n\nlet integer = 255\n\"Hex: \\(hex: integer)\" // \"Hex: 0xFF\"\n\nlet rate = 0.15\n\"Percent: \\(percent: rate)\" // \"Percent: 15.00%\"\n\"Percent: \\(percent: rate, decimals: 0)\" // \"Percent: 15%\"\n\nlet startTime = CACurrentMediaTime()\nThread.sleep(forTimeInterval: 2.8)\n\"∆t was \\(timeSince: startTime)\" // \"∆t was 2.80s\"\n\"∆t was \\(timeSince: startTime, decimals: 0)\" // \"∆t was 3s\"\n\nThis was introduced by SE-0228, so please be sure to read the original proposal for a deeper understanding of this new feature. Finally, the protocol documentation is helpful as well.\n", "I know a lot's of time has passed since this publish, but I've fallen in a similar situation and create a simples class to simplify my life.\npublic struct StringMaskFormatter {\n\n public var pattern : String = \"\"\n public var replecementChar : Character = \"*\"\n public var allowNumbers : Bool = true\n public var allowText : Bool = false\n\n\n public init(pattern:String, replecementChar:Character=\"*\", allowNumbers:Bool=true, allowText:Bool=true)\n {\n self.pattern = pattern\n self.replecementChar = replecementChar\n self.allowNumbers = allowNumbers\n self.allowText = allowText\n }\n\n\n private func prepareString(string:String) -> String {\n\n var charSet : NSCharacterSet!\n\n if allowText && allowNumbers {\n charSet = NSCharacterSet.alphanumericCharacterSet().invertedSet\n }\n else if allowText {\n charSet = NSCharacterSet.letterCharacterSet().invertedSet\n }\n else if allowNumbers {\n charSet = NSCharacterSet.decimalDigitCharacterSet().invertedSet\n }\n\n let result = string.componentsSeparatedByCharactersInSet(charSet)\n return result.joinWithSeparator(\"\")\n }\n\n public func createFormattedStringFrom(text:String) -> String\n {\n var resultString = \"\"\n if text.characters.count > 0 && pattern.characters.count > 0\n {\n\n var finalText = \"\"\n var stop = false\n let tempString = prepareString(text)\n\n var formatIndex = pattern.startIndex\n var tempIndex = tempString.startIndex\n\n while !stop\n {\n let formattingPatternRange = formatIndex ..< formatIndex.advancedBy(1)\n\n if pattern.substringWithRange(formattingPatternRange) != String(replecementChar) {\n finalText = finalText.stringByAppendingString(pattern.substringWithRange(formattingPatternRange))\n }\n else if tempString.characters.count > 0 {\n let pureStringRange = tempIndex ..< tempIndex.advancedBy(1)\n finalText = finalText.stringByAppendingString(tempString.substringWithRange(pureStringRange))\n tempIndex = tempIndex.advancedBy(1)\n }\n\n formatIndex = formatIndex.advancedBy(1)\n\n if formatIndex >= pattern.endIndex || tempIndex >= tempString.endIndex {\n stop = true\n }\n\n resultString = finalText\n\n }\n }\n\n return resultString\n }\n\n}\n\nThe follow link send to the complete source code:\nhttps://gist.github.com/dedeexe/d9a43894081317e7c418b96d1d081b25\nThis solution was base on this article:\nhttp://vojtastavik.com/2015/03/29/real-time-formatting-in-uitextfield-swift-basics/\n", "There is a simple solution I learned with \"We <3 Swift\" if you can't either import Foundation, use round() and/or does not want a String:\nvar number = 31.726354765\nvar intNumber = Int(number * 1000.0)\nvar roundedNumber = Double(intNumber) / 1000.0\n\nresult: 31.726\n", "Use this following code:\n let intVal=56\n let floatval:Double=56.897898\n let doubleValue=89.0\n let explicitDaouble:Double=89.56\n let stringValue:\"Hello\"\n\n let stringValue=\"String:\\(stringValue) Integer:\\(intVal) Float:\\(floatval) Double:\\(doubleValue) ExplicitDouble:\\(explicitDaouble) \"\n\n", "The beauty of String(format:) is that you can save a formatting string and then reuse it later in dozen of places. It also can be localized in this single place. Where as in case of the interpolation approach you must write it again and again.\n", "Simple functionality is not included in Swift, expected because it's included in other languages, can often be quickly coded for reuse. Pro tip for programmers to create a bag of tricks file that contains all this reuse code.\nSo from my bag of tricks we first need string multiplication for use in indentation.\n@inlinable func * (string: String, scalar: Int) -> String {\n let array = [String](repeating: string, count: scalar)\n return array.joined(separator: \"\")\n}\n\nand then the code to add commas.\nextension Int {\n @inlinable var withCommas:String {\n var i = self\n var retValue:[String] = []\n while i >= 1000 {\n retValue.append(String(format:\"%03d\",i%1000))\n i /= 1000\n }\n retValue.append(\"\\(i)\")\n return retValue.reversed().joined(separator: \",\")\n }\n\n @inlinable func withCommas(_ count:Int = 0) -> String {\n let retValue = self.withCommas\n let indentation = count - retValue.count\n let indent:String = indentation >= 0 ? \" \" * indentation : \"\"\n\n return indent + retValue\n }\n}\n\nI just wrote this last function so I could get the columns to line up.\nThe @inlinable is great because it takes small functions and reduces their functionality so they run faster.\nYou can use either the variable version or, to get a fixed column, use the function version. Lengths set less than the needed columns will just expand the field.\nNow you have something that is pure Swift and does not rely on some old objective C routine for NSString.\n", "Since String(format: \"%s\" ...) is crashing at run time, here is code to allow write something like \"hello\".center(42); \"world\".alignLeft(42):\nextension String {\n\n // note: symbol names match to nim std/strutils lib:\n\n func align (_ boxsz: UInt) -> String {\n self.withCString { String(format: \"%\\(boxsz)s\", $0) }\n }\n\n func alignLeft (_ boxsz: UInt) -> String {\n self.withCString { String(format: \"%-\\(boxsz)s\", $0) }\n }\n\n func center (_ boxsz: UInt) -> String {\n let n = self.count\n guard boxsz > n else { return self }\n let padding = boxsz - UInt(n)\n let R = padding / 2\n guard R > 0 else { return \" \" + self }\n let L = (padding%2 == 0) ? R : (R+1)\n return \" \".withCString { String(format: \"%\\(L)s\\(self)%\\(R)s\", $0,$0) }\n }\n\n}\n\n" ]
[ 457, 121, 57, 52, 16, 6, 4, 2, 1, 1, 0, 0, 0, 0 ]
[ "Success to try it:\n var letters:NSString = \"abcdefghijkl\"\n var strRendom = NSMutableString.stringWithCapacity(strlength)\n for var i=0; i<strlength; i++ {\n let rndString = Int(arc4random() % 12)\n //let strlk = NSString(format: <#NSString#>, <#CVarArg[]#>)\n let strlk = NSString(format: \"%c\", letters.characterAtIndex(rndString))\n strRendom.appendString(String(strlk))\n }\n\n" ]
[ -2 ]
[ "ios", "ios8", "nsstring", "string_formatting", "swift" ]
stackoverflow_0024074479_ios_ios8_nsstring_string_formatting_swift.txt
Q: Why doesn't mean square error work in case of angular data? Suppose, the following is a dataset for solving a regression problem: H -9.118 5.488 5.166 4.852 5.164 4.943 8.103 -9.152 7.470 6.452 6.069 6.197 6.434 8.264 9.047 2.222 H 5.488 5.166 4.852 5.164 4.943 8.103 -9.152 -8.536 6.452 6.069 6.197 6.434 8.264 9.047 11.954 2.416 C 5.166 4.852 5.164 4.943 8.103 -9.152 -8.536 5.433 6.069 6.197 6.434 8.264 9.047 11.954 6.703 3.028 C 4.852 5.164 4.943 8.103 -9.152 -8.536 5.433 4.924 6.197 6.434 8.264 9.047 11.954 6.703 6.407 -1.235 C 5.164 4.943 8.103 -9.152 -8.536 5.433 4.924 5.007 6.434 8.264 9.047 11.954 6.703 6.407 6.088 -0.953 H 4.943 8.103 -9.152 -8.536 5.433 4.924 5.007 5.057 8.264 9.047 11.954 6.703 6.407 6.088 6.410 2.233 H 8.103 -9.152 -8.536 5.433 4.924 5.007 5.057 5.026 9.047 11.954 6.703 6.407 6.088 6.410 6.206 2.313 H -9.152 -8.536 5.433 4.924 5.007 5.057 5.026 5.154 11.954 6.703 6.407 6.088 6.410 6.206 6.000 2.314 H -8.536 5.433 4.924 5.007 5.057 5.026 5.154 5.173 6.703 6.407 6.088 6.410 6.206 6.000 6.102 2.244 H 5.433 4.924 5.007 5.057 5.026 5.154 5.173 5.279 6.407 6.088 6.410 6.206 6.000 6.102 6.195 2.109 the left-most column is the class data. The rest of the features are all angular data. My initial setup for the model was as follows: def create_model(n_hidden_1, n_hidden_2, num_features): # create the model model = Sequential() model.add(tf.keras.layers.InputLayer(input_shape=(num_features,))) model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu')) model.add(tf.keras.layers.Dense(n_hidden_2, activation='relu')) model.add(tf.keras.layers.Dense(1)) # instantiate the optimizer opt = keras.optimizers.Adam(learning_rate=LEARNING_RATE) # compile the model model.compile( loss="mean_squared_error", optimizer=opt, metrics=["mean_squared_error"] ) # return model return model This model didn't produce the correct outcome. Someone told me that MSE doesn't work in the case of angular data. So, I need to use a custom output layer and a custom error function. Why doesn't mean square error work in the case of angular data? How can I solve this issue? A: Data that represent angles like 180 degrees, causes problems with most loss functions because they are not meant for radiants. MSE calculates a huge error between 0 and 359 although 0=360. It simply doesn’t understand the concepts of radiants and angles. There are a number of ways to fix this depending on what you want to predict. The easiest would be to transform your data via sinus function and then use the transformed data for training. You would need to apply the inverse function to your predictions. The other option is to customise the MSE loss function to transform x via the sinus function. A: The mean squared error (MSE) loss function is not well-suited for regression tasks involving angular data because it treats all errors (i.e. differences between predicted and true values) equally, regardless of their direction. This is problematic when working with angular data, because the difference between two angles (e.g. 0° and 359°) is not the same as the difference between 359° and 0°. To address this issue, you can use a custom loss function that accounts for the periodicity of angular data. For example, you can use the mean angular error (MAE) loss function, which calculates the mean absolute difference between the predicted and true angles in radians. The MAE loss function is defined as: MAE = 1/N * Σ|yₜ - yₚ| where N is the number of samples, yₜ is the true angle, and yₚ is the predicted angle. Here's an example of how you can use the MAE loss function in a Keras model for regression tasks involving angular data: # Define the MAE loss function def mae_loss(y_true, y_pred): # Convert the true and predicted angles from degrees to radians y_true_rad = tf.math.deg2rad(y_true) y_pred_rad = tf.math.deg2rad(y_pred) # Calculate the absolute difference between the predicted and true angles in radians diff = tf.math.abs(y_true_rad - y_pred_rad) # Calculate the mean absolute error mae = tf.reduce_mean(diff) # Return the mean absolute error return mae # Define the model architecture def create_model(n_hidden_1, n_hidden_2, num_features): # create the model model = Sequential() model.add(tf.keras.layers.InputLayer(input_shape=(num_features,))) model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu')) model.add(tf.keras.layers.Dense(n_hidden_2, activation='relu')) model.add(tf.keras.layers.Dense(1)) # instantiate the optimizer opt = keras.optimizers.Adam(learning_rate=LEARNING_RATE) # compile the model model.compile( loss=mae_loss, optimizer=opt, metrics=["mean_squared_error"] ) # return model return model In this example, we define a custom loss function called mae_loss that calculates the mean absolute error between the predicted and true angles in radians. We then use this loss function when compiling the model. A: Mean squared error (MSE) is a common loss function used for regression problems. It calculates the difference between the predicted value and the true value, squares it, and then takes the average across all the data points. MSE works well for regression problems with continuous, numeric data, but it may not be appropriate for regression problems with angular data. In the case of angular data, MSE can produce misleading results because it treats all directions equally, regardless of the direction's angle. For example, if the true value is 0 degrees and the predicted value is 5 degrees, the difference is 5 degrees and the squared error is 25. However, if the true value is 175 degrees and the predicted value is 180 degrees, the difference is also 5 degrees, but the squared error is 625 because the 175 degrees and 180 degrees are almost opposite directions. In this case, MSE would produce a much larger error even though the prediction is almost correct. To properly handle angular data, you can use a custom output layer and a custom error function that accounts for the circular nature of the data. For example, you could use a sine and cosine output layer to represent the angle as a complex number, and then use the complex error (CE) loss function to calculate the error. CE calculates the absolute difference between the predicted and true complex numbers, which accounts for the circular nature of the data and produces more accurate results for angular data. Here is an example of how you could modify the model to use a sine and cosine output layer and the CE loss function: def create_model(n_hidden_1, n_hidden_2, num_features): # create the model model = Sequential() model.add(tf.keras.layers.InputLayer(input_shape=(num_features,))) model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu')) model.add(tf.keras.layers.Dense(n_hidden_2, activation='relu')) # Add a sine and cosine output layer model.add(tf.keras.layers.Dense(1, activation="sin")) model.add(tf.keras.layers.Dense(1, activation="cos")) # instantiate the optimizer opt = keras.optimizers.Adam(learning_rate=LEARNING_RATE) # compile the model model.compile( loss=complex_error, # use the complex error loss function optimizer=opt, metrics=["mean_squared_error"] ) # return model return model This modified model will use a sine and cosine output layer to represent the angle as a complex number, and it will use the CE loss function to calculate the error. This should produce more accurate results for regression problems with angular data. A: The mean squared error (MSE) loss function is commonly used for regression tasks, but it is not suitable for data with angular features. This is because the MSE function treats all features as if they are linear, but angular features are not linear. To properly handle angular features in your regression model, you can use a custom loss function that takes the circular nature of the data into account. One such loss function is the circular mean squared error (CMSE) loss function. This loss function is defined as follows: CMSE = (1 / N) * sum(min(2 * pi, |y - y_pred|))^2 where N is the number of samples, y is the true value, and y_pred is the predicted value. To use the CMSE loss function in your model, you can modify your create_model function as follows: import tensorflow as tf def create_model(n_hidden_1, n_hidden_2, num_features): # create the model model = Sequential() model.add(tf.keras.layers.InputLayer(input_shape=(num_features,))) model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu')) model.add(tf.keras.layers.Dense(n_hidden_2, activation='relu')) model.add(tf.keras.layers.Dense(1)) # define the CMSE loss function def cmse(y_true, y_pred): pi = tf.constant(np.pi) return tf.reduce_mean(tf.square(tf.minimum(2 * pi, tf.abs(y_true - y_pred)))) # instantiate the optimizer opt = keras.optimizers.Adam(learning_rate=LEARNING_RATE) # compile the model model.compile( loss=cmse, optimizer=opt, metrics=["mean_squared_error"] ) # return model return model This will use the CMSE loss function instead of the MSE loss function, which should improve the performance of your model on angular data. You can also consider using other metrics, such as the circular mean absolute error (CMAE) or the circular mean absolute percentage error (CMAPE), to evaluate the performance of your model. I hope this helps! Let me know if you have any other questions. A: Mean squared error (MSE) is a loss function that is often used in regression tasks, where the goal is to predict a continuous value. MSE works by calculating the square of the difference between the predicted value and the true value, and then taking the mean of those squared differences. In the case of angular data, MSE may not be the best loss function to use because it does not take into account the circular nature of angles. For example, the angles 0 and 360 degrees are essentially the same, but MSE would treat them as being very different. One solution to this problem is to use a loss function that is specifically designed for angular data, such as the sine squared error or the cosine squared error. These loss functions take into account the circular nature of angles and can produce better results in regression tasks involving angular data. In a Keras/TensorFlow-based model, you can use these loss functions by defining a custom loss function and passing it to the model.compile method when you compile the model. Here is an example of how you might do this: def sine_squared_error(y_true, y_pred): # calculate the sine of the difference between the true angle and the predicted angle error = tf.sin(y_true - y_pred) # square the error and return the mean return tf.reduce_mean(tf.square(error)) # create the model model = Sequential() model.add(tf.keras.layers.InputLayer(input_shape=(num_features,))) model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu')) model.add(tf.keras.layers.Dense(n_hidden_2, activation='relu')) model.add(tf.keras.layers.Dense(1)) # instantiate the optimizer opt = keras.optimizers.Adam(learning_rate=LEARNING_RATE) # compile the model using the sine squared error as the loss function model.compile( loss=sine_squared_error, optimizer=opt, metrics=["mean_squared_error"] ) I hope this helps! My donation addresses: BTC:178vgzZkLNV9NPxZiQqabq5crzBSgQWmvs,ETH:0x99753577c4ae89e7043addf7abbbdf7258a74697 A: I am assuming that by "angular" you mean some form of representation of an angle. If this is the case, then MSE does not work well because it does not have a concept of 0 == 360 (or equivalent regularities in radians), thus e.g. predicting 359.999999 for a correct label of 0 will create a huge error, while it should produce a tiny error. A: import tensorflow as tf import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import MinMaxScaler %matplotlib inline def create_model(n_hidden_1, n_hidden_2, num_features): # create the model model = tf.keras.Sequential() model.add(tf.keras.layers.InputLayer(input_shape=(num_features,))) model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu')) model.add(tf.keras.layers.Dense(n_hidden_2, activation='sigmoid')) # relu ignores data information, so we choose sigmoid. model.add(tf.keras.layers.Dense(1)) # instantiate the optimizer opt = tf.keras.optimizers.Adam(learning_rate=LEARNING_RATE) # compile the model model.compile( loss="mean_squared_error", optimizer="adam", # metrics=["mean_squared_error"] ) # return model return model ss = [['H',-9.118,5.488,5.166,4.852,5.164,4.943,8.103,-9.152,7.470,6.452,6.069,6.197,6.434,8.264,9.047, 2.222], ['H',5.488,5.166,4.852,5.164,4.943,8.103,-9.152,-8.536,6.452,6.069,6.197,6.434,8.264,9.047,11.954, 2.416], ['C',5.166,4.852,5.164,4.943,8.103,-9.152,-8.536,5.433,6.069,6.197,6.434,8.264,9.047,11.954,6.703, 3.028], ['C',4.852,5.164,4.943,8.103,-9.152,-8.536,5.433,4.924,6.197,6.434,8.264,9.047,11.954,6.703,6.407,-1.235], ['C',5.164,4.943,8.103,-9.152,-8.536,5.433,4.924,5.007,6.434,8.264,9.047,11.954,6.703,6.407,6.088,-0.953], ['H',4.943,8.103,-9.152,-8.536,5.433,4.924,5.007,5.057,8.264,9.047,11.954,6.703,6.407,6.088,6.410, 2.233], ['H',8.103,-9.152,-8.536,5.433,4.924,5.007,5.057,5.026,9.047,11.954,6.703,6.407,6.088,6.410,6.206, 2.313], ['H',-9.152,-8.536,5.433,4.924,5.007,5.057,5.026,5.154,11.954,6.703,6.407,6.088,6.410,6.206,6.000, 2.314], ['H',-8.536,5.433,4.924,5.007,5.057,5.026,5.154,5.173,6.703,6.407,6.088,6.410,6.206,6.000,6.102, 2.244], ['H',5.433,4.924,5.007,5.057,5.026,5.154,5.173,5.279,6.407,6.088,6.410,6.206,6.000,6.102,6.195, 2.109]] data = pd.DataFrame(ss) y =data.iloc[:,-1:] x = data.iloc[:,1:-1] # scaler, Accelerating model convergence scaler = MinMaxScaler() x_model = scaler.fit(x) x = scaler.transform(x) y_model = scaler.fit(y) y = scaler.transform(y) # model LEARNING_RATE = 0.001 model = create_model(n_hidden_1=4, n_hidden_2=2, num_features=15) model.fit(x,y,epochs=1000) # predict y_pre = model.predict(x) print('predict: ',y_model.inverse_transform(y_pre)) print('y: ',y_model.inverse_transform(y)) predict: [[ 2.2238724 ] [ 2.415551 ] [ 3.0212667 ] [-1.1861311 ] [-0.98702306] [ 2.2277246 ] [ 2.3132346 ] [ 2.3148017 ] [ 2.235104 ] [ 2.1206288 ]] y: [[ 2.222] [ 2.416] [ 3.028] [-1.235] [-0.953] [ 2.233] [ 2.313] [ 2.314] [ 2.244] [ 2.109]] I wrote a piece of code and annotated it. In terms of the results, the difference is very small. Friendly tip: pay attention to the over fitting of the model. A: In general, mean squared error (MSE) is a suitable loss function for regression problems, including regression problems with angular data. However, MSE has some limitations when it comes to angular data. One issue with using MSE for regression with angular data is that MSE is not invariant under circular shifts. This means that if you shift all of the angular data by a constant angle, the MSE will change, even though the underlying data has not changed. This can lead to issues with convergence and inaccurate predictions. Another issue with using MSE for angular data is that MSE is not sensitive to the order of the data. For example, if you have two angular data points that are 180 degrees apart, the MSE will be the same regardless of which point comes first. This can cause problems with certain types of regression models that rely on the order of the data. For these reasons, it can be useful to use a custom loss function that is specifically designed for angular data. There are several options for custom loss functions that can be used for angular data, including the von Mises loss and the wrapped normal loss. These loss functions are invariant under circular shifts and are sensitive to the order of the data, which can improve the accuracy of the model. It's worth noting that using a custom loss function is not always necessary for regression with angular data. In some cases, MSE may be sufficient, depending on the specific characteristics of the data and the goals of the model. It's always a good idea to experiment with different loss functions and evaluate their performance on your data to determine the best option for your particular use case.
Why doesn't mean square error work in case of angular data?
Suppose, the following is a dataset for solving a regression problem: H -9.118 5.488 5.166 4.852 5.164 4.943 8.103 -9.152 7.470 6.452 6.069 6.197 6.434 8.264 9.047 2.222 H 5.488 5.166 4.852 5.164 4.943 8.103 -9.152 -8.536 6.452 6.069 6.197 6.434 8.264 9.047 11.954 2.416 C 5.166 4.852 5.164 4.943 8.103 -9.152 -8.536 5.433 6.069 6.197 6.434 8.264 9.047 11.954 6.703 3.028 C 4.852 5.164 4.943 8.103 -9.152 -8.536 5.433 4.924 6.197 6.434 8.264 9.047 11.954 6.703 6.407 -1.235 C 5.164 4.943 8.103 -9.152 -8.536 5.433 4.924 5.007 6.434 8.264 9.047 11.954 6.703 6.407 6.088 -0.953 H 4.943 8.103 -9.152 -8.536 5.433 4.924 5.007 5.057 8.264 9.047 11.954 6.703 6.407 6.088 6.410 2.233 H 8.103 -9.152 -8.536 5.433 4.924 5.007 5.057 5.026 9.047 11.954 6.703 6.407 6.088 6.410 6.206 2.313 H -9.152 -8.536 5.433 4.924 5.007 5.057 5.026 5.154 11.954 6.703 6.407 6.088 6.410 6.206 6.000 2.314 H -8.536 5.433 4.924 5.007 5.057 5.026 5.154 5.173 6.703 6.407 6.088 6.410 6.206 6.000 6.102 2.244 H 5.433 4.924 5.007 5.057 5.026 5.154 5.173 5.279 6.407 6.088 6.410 6.206 6.000 6.102 6.195 2.109 the left-most column is the class data. The rest of the features are all angular data. My initial setup for the model was as follows: def create_model(n_hidden_1, n_hidden_2, num_features): # create the model model = Sequential() model.add(tf.keras.layers.InputLayer(input_shape=(num_features,))) model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu')) model.add(tf.keras.layers.Dense(n_hidden_2, activation='relu')) model.add(tf.keras.layers.Dense(1)) # instantiate the optimizer opt = keras.optimizers.Adam(learning_rate=LEARNING_RATE) # compile the model model.compile( loss="mean_squared_error", optimizer=opt, metrics=["mean_squared_error"] ) # return model return model This model didn't produce the correct outcome. Someone told me that MSE doesn't work in the case of angular data. So, I need to use a custom output layer and a custom error function. Why doesn't mean square error work in the case of angular data? How can I solve this issue?
[ "Data that represent angles like 180 degrees, causes problems with most loss functions because they are not meant for radiants. MSE calculates a huge error between 0 and 359 although 0=360. It simply doesn’t understand the concepts of radiants and angles.\nThere are a number of ways to fix this depending on what you want to predict. The easiest would be to transform your data via sinus function and then use the transformed data for training. You would need to apply the inverse function to your predictions.\nThe other option is to customise the MSE loss function to transform x via the sinus function.\n", "The mean squared error (MSE) loss function is not well-suited for regression tasks involving angular data because it treats all errors (i.e. differences between predicted and true values) equally, regardless of their direction. This is problematic when working with angular data, because the difference between two angles (e.g. 0° and 359°) is not the same as the difference between 359° and 0°.\nTo address this issue, you can use a custom loss function that accounts for the periodicity of angular data. For example, you can use the mean angular error (MAE) loss function, which calculates the mean absolute difference between the predicted and true angles in radians. The MAE loss function is defined as:\nMAE = 1/N * Σ|yₜ - yₚ|\nwhere N is the number of samples, yₜ is the true angle, and yₚ is the predicted angle.\nHere's an example of how you can use the MAE loss function in a Keras model for regression tasks involving angular data:\n# Define the MAE loss function\ndef mae_loss(y_true, y_pred):\n # Convert the true and predicted angles from degrees to radians\n y_true_rad = tf.math.deg2rad(y_true)\n y_pred_rad = tf.math.deg2rad(y_pred)\n\n # Calculate the absolute difference between the predicted and true angles in radians\n diff = tf.math.abs(y_true_rad - y_pred_rad)\n\n # Calculate the mean absolute error\n mae = tf.reduce_mean(diff)\n\n # Return the mean absolute error\n return mae\n\n# Define the model architecture\ndef create_model(n_hidden_1, n_hidden_2, num_features):\n # create the model\n model = Sequential()\n model.add(tf.keras.layers.InputLayer(input_shape=(num_features,)))\n model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu'))\n model.add(tf.keras.layers.Dense(n_hidden_2, activation='relu'))\n model.add(tf.keras.layers.Dense(1))\n\n # instantiate the optimizer\n opt = keras.optimizers.Adam(learning_rate=LEARNING_RATE)\n\n # compile the model\n model.compile(\n loss=mae_loss,\n optimizer=opt,\n metrics=[\"mean_squared_error\"]\n )\n\n # return model\n return model\n\nIn this example, we define a custom loss function called mae_loss that calculates the mean absolute error between the predicted and true angles in radians. We then use this loss function when compiling the model.\n", "Mean squared error (MSE) is a common loss function used for regression problems. It calculates the difference between the predicted value and the true value, squares it, and then takes the average across all the data points. MSE works well for regression problems with continuous, numeric data, but it may not be appropriate for regression problems with angular data.\nIn the case of angular data, MSE can produce misleading results because it treats all directions equally, regardless of the direction's angle. For example, if the true value is 0 degrees and the predicted value is 5 degrees, the difference is 5 degrees and the squared error is 25. However, if the true value is 175 degrees and the predicted value is 180 degrees, the difference is also 5 degrees, but the squared error is 625 because the 175 degrees and 180 degrees are almost opposite directions. In this case, MSE would produce a much larger error even though the prediction is almost correct.\nTo properly handle angular data, you can use a custom output layer and a custom error function that accounts for the circular nature of the data. For example, you could use a sine and cosine output layer to represent the angle as a complex number, and then use the complex error (CE) loss function to calculate the error. CE calculates the absolute difference between the predicted and true complex numbers, which accounts for the circular nature of the data and produces more accurate results for angular data.\nHere is an example of how you could modify the model to use a sine and cosine output layer and the CE loss function:\ndef create_model(n_hidden_1, n_hidden_2, num_features):\n # create the model\n model = Sequential()\n model.add(tf.keras.layers.InputLayer(input_shape=(num_features,)))\n model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu'))\n model.add(tf.keras.layers.Dense(n_hidden_2, activation='relu'))\n \n # Add a sine and cosine output layer\n model.add(tf.keras.layers.Dense(1, activation=\"sin\"))\n model.add(tf.keras.layers.Dense(1, activation=\"cos\"))\n\n # instantiate the optimizer\n opt = keras.optimizers.Adam(learning_rate=LEARNING_RATE)\n\n # compile the model\n model.compile(\n loss=complex_error, # use the complex error loss function\n optimizer=opt,\n metrics=[\"mean_squared_error\"]\n )\n\n # return model\n return model\n\n\nThis modified model will use a sine and cosine output layer to represent the angle as a complex number, and it will use the CE loss function to calculate the error. This should produce more accurate results for regression problems with angular data.\n", "The mean squared error (MSE) loss function is commonly used for regression tasks, but it is not suitable for data with angular features. This is because the MSE function treats all features as if they are linear, but angular features are not linear.\nTo properly handle angular features in your regression model, you can use a custom loss function that takes the circular nature of the data into account. One such loss function is the circular mean squared error (CMSE) loss function. This loss function is defined as follows:\nCMSE = (1 / N) * sum(min(2 * pi, |y - y_pred|))^2\nwhere N is the number of samples, y is the true value, and y_pred is the predicted value.\nTo use the CMSE loss function in your model, you can modify your create_model function as follows:\nimport tensorflow as tf\n\ndef create_model(n_hidden_1, n_hidden_2, num_features):\n # create the model\n model = Sequential()\n model.add(tf.keras.layers.InputLayer(input_shape=(num_features,)))\n model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu'))\n model.add(tf.keras.layers.Dense(n_hidden_2, activation='relu'))\n model.add(tf.keras.layers.Dense(1))\n\n # define the CMSE loss function\n def cmse(y_true, y_pred):\n pi = tf.constant(np.pi)\n return tf.reduce_mean(tf.square(tf.minimum(2 * pi, tf.abs(y_true - y_pred))))\n\n # instantiate the optimizer\n opt = keras.optimizers.Adam(learning_rate=LEARNING_RATE)\n\n # compile the model\n model.compile(\n loss=cmse,\n optimizer=opt,\n metrics=[\"mean_squared_error\"]\n )\n\n # return model\n return model\n\nThis will use the CMSE loss function instead of the MSE loss function, which should improve the performance of your model on angular data. You can also consider using other metrics, such as the circular mean absolute error (CMAE) or the circular mean absolute percentage error (CMAPE), to evaluate the performance of your model.\nI hope this helps! Let me know if you have any other questions.\n", "Mean squared error (MSE) is a loss function that is often used in regression tasks, where the goal is to predict a continuous value. MSE works by calculating the square of the difference between the predicted value and the true value, and then taking the mean of those squared differences.\nIn the case of angular data, MSE may not be the best loss function to use because it does not take into account the circular nature of angles. For example, the angles 0 and 360 degrees are essentially the same, but MSE would treat them as being very different.\nOne solution to this problem is to use a loss function that is specifically designed for angular data, such as the sine squared error or the cosine squared error. These loss functions take into account the circular nature of angles and can produce better results in regression tasks involving angular data.\nIn a Keras/TensorFlow-based model, you can use these loss functions by defining a custom loss function and passing it to the model.compile method when you compile the model. Here is an example of how you might do this:\ndef sine_squared_error(y_true, y_pred):\n # calculate the sine of the difference between the true angle and the predicted angle\n error = tf.sin(y_true - y_pred)\n\n # square the error and return the mean\n return tf.reduce_mean(tf.square(error))\n\n# create the model\nmodel = Sequential()\nmodel.add(tf.keras.layers.InputLayer(input_shape=(num_features,)))\nmodel.add(tf.keras.layers.Dense(n_hidden_1, activation='relu'))\nmodel.add(tf.keras.layers.Dense(n_hidden_2, activation='relu'))\nmodel.add(tf.keras.layers.Dense(1))\n\n# instantiate the optimizer\nopt = keras.optimizers.Adam(learning_rate=LEARNING_RATE)\n\n# compile the model using the sine squared error as the loss function\nmodel.compile(\n loss=sine_squared_error,\n optimizer=opt,\n metrics=[\"mean_squared_error\"]\n)\n\nI hope this helps!\nMy donation addresses: BTC:178vgzZkLNV9NPxZiQqabq5crzBSgQWmvs,ETH:0x99753577c4ae89e7043addf7abbbdf7258a74697\n", "I am assuming that by \"angular\" you mean some form of representation of an angle. If this is the case, then MSE does not work well because it does not have a concept of 0 == 360 (or equivalent regularities in radians), thus e.g. predicting 359.999999 for a correct label of 0 will create a huge error, while it should produce a tiny error.\n", "import tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import MinMaxScaler\n%matplotlib inline\n\ndef create_model(n_hidden_1, n_hidden_2, num_features):\n # create the model\n model = tf.keras.Sequential()\n model.add(tf.keras.layers.InputLayer(input_shape=(num_features,)))\n model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu'))\n model.add(tf.keras.layers.Dense(n_hidden_2, activation='sigmoid')) # relu ignores data information, so we choose sigmoid.\n model.add(tf.keras.layers.Dense(1))\n\n # instantiate the optimizer\n opt = tf.keras.optimizers.Adam(learning_rate=LEARNING_RATE)\n\n # compile the model\n model.compile(\n loss=\"mean_squared_error\",\n optimizer=\"adam\",\n# metrics=[\"mean_squared_error\"]\n )\n\n # return model\n return model\n\nss = [['H',-9.118,5.488,5.166,4.852,5.164,4.943,8.103,-9.152,7.470,6.452,6.069,6.197,6.434,8.264,9.047, 2.222],\n['H',5.488,5.166,4.852,5.164,4.943,8.103,-9.152,-8.536,6.452,6.069,6.197,6.434,8.264,9.047,11.954, 2.416],\n['C',5.166,4.852,5.164,4.943,8.103,-9.152,-8.536,5.433,6.069,6.197,6.434,8.264,9.047,11.954,6.703, 3.028],\n['C',4.852,5.164,4.943,8.103,-9.152,-8.536,5.433,4.924,6.197,6.434,8.264,9.047,11.954,6.703,6.407,-1.235],\n['C',5.164,4.943,8.103,-9.152,-8.536,5.433,4.924,5.007,6.434,8.264,9.047,11.954,6.703,6.407,6.088,-0.953],\n['H',4.943,8.103,-9.152,-8.536,5.433,4.924,5.007,5.057,8.264,9.047,11.954,6.703,6.407,6.088,6.410, 2.233],\n['H',8.103,-9.152,-8.536,5.433,4.924,5.007,5.057,5.026,9.047,11.954,6.703,6.407,6.088,6.410,6.206, 2.313],\n['H',-9.152,-8.536,5.433,4.924,5.007,5.057,5.026,5.154,11.954,6.703,6.407,6.088,6.410,6.206,6.000, 2.314],\n['H',-8.536,5.433,4.924,5.007,5.057,5.026,5.154,5.173,6.703,6.407,6.088,6.410,6.206,6.000,6.102, 2.244],\n['H',5.433,4.924,5.007,5.057,5.026,5.154,5.173,5.279,6.407,6.088,6.410,6.206,6.000,6.102,6.195, 2.109]]\n\ndata = pd.DataFrame(ss)\ny =data.iloc[:,-1:]\nx = data.iloc[:,1:-1]\n\n# scaler, Accelerating model convergence\nscaler = MinMaxScaler()\nx_model = scaler.fit(x)\nx = scaler.transform(x)\n\ny_model = scaler.fit(y)\ny = scaler.transform(y)\n\n# model \nLEARNING_RATE = 0.001\nmodel = create_model(n_hidden_1=4, n_hidden_2=2, num_features=15)\n\nmodel.fit(x,y,epochs=1000)\n\n# predict \ny_pre = model.predict(x)\nprint('predict: ',y_model.inverse_transform(y_pre))\nprint('y: ',y_model.inverse_transform(y))\npredict: [[ 2.2238724 ]\n [ 2.415551 ]\n [ 3.0212667 ]\n [-1.1861311 ]\n [-0.98702306]\n [ 2.2277246 ]\n [ 2.3132346 ]\n [ 2.3148017 ]\n [ 2.235104 ]\n [ 2.1206288 ]]\ny: [[ 2.222]\n [ 2.416]\n [ 3.028]\n [-1.235]\n [-0.953]\n [ 2.233]\n [ 2.313]\n [ 2.314]\n [ 2.244]\n [ 2.109]]\n\nI wrote a piece of code and annotated it. In terms of the results, the difference is very small. Friendly tip: pay attention to the over fitting of the model.\n", "In general, mean squared error (MSE) is a suitable loss function for regression problems, including regression problems with angular data. However, MSE has some limitations when it comes to angular data.\nOne issue with using MSE for regression with angular data is that MSE is not invariant under circular shifts. This means that if you shift all of the angular data by a constant angle, the MSE will change, even though the underlying data has not changed. This can lead to issues with convergence and inaccurate predictions.\nAnother issue with using MSE for angular data is that MSE is not sensitive to the order of the data. For example, if you have two angular data points that are 180 degrees apart, the MSE will be the same regardless of which point comes first. This can cause problems with certain types of regression models that rely on the order of the data.\nFor these reasons, it can be useful to use a custom loss function that is specifically designed for angular data. There are several options for custom loss functions that can be used for angular data, including the von Mises loss and the wrapped normal loss. These loss functions are invariant under circular shifts and are sensitive to the order of the data, which can improve the accuracy of the model.\nIt's worth noting that using a custom loss function is not always necessary for regression with angular data. In some cases, MSE may be sufficient, depending on the specific characteristics of the data and the goals of the model. It's always a good idea to experiment with different loss functions and evaluate their performance on your data to determine the best option for your particular use case.\n" ]
[ 2, 2, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "mean_square_error", "neural_network", "python", "radians" ]
stackoverflow_0071187809_mean_square_error_neural_network_python_radians.txt
Q: .htaccess how to check if request was for specific file name and file not exists? I am trying to check if incoming request was for non existing file name and if requested file name was ending on _all.css ? I have some code like below RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-s RewriteCond %{REQUEST_FILENAME} !-d RewriteRule \.css$ getLatest.php [L] and that works if file not exists, but I would like to execute this condition only if requested file name was ending at the _all.css , how to concatenate this with this second condition ? Thanks for all tips ! I tried some htaccess rules but I am not familiar how to concatenate them :( A: Change your last rule with the requested file name ending : RewriteRule _all\.css$ getLatest.php [L] But be careful, it's also css that will be loaded by the browser, and not another html page...
.htaccess how to check if request was for specific file name and file not exists?
I am trying to check if incoming request was for non existing file name and if requested file name was ending on _all.css ? I have some code like below RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-s RewriteCond %{REQUEST_FILENAME} !-d RewriteRule \.css$ getLatest.php [L] and that works if file not exists, but I would like to execute this condition only if requested file name was ending at the _all.css , how to concatenate this with this second condition ? Thanks for all tips ! I tried some htaccess rules but I am not familiar how to concatenate them :(
[ "Change your last rule with the requested file name ending :\nRewriteRule _all\\.css$ getLatest.php [L]\n\nBut be careful, it's also css that will be loaded by the browser, and not another html page...\n" ]
[ 0 ]
[]
[]
[ ".htaccess", "apache" ]
stackoverflow_0074662176_.htaccess_apache.txt
Q: Problem with coding multi-frame jump animation (GDScript) So I am a beginner programmer using GDScript and got stuck with playing jump animation. All my animations are like 2 frames and where easy to code, but my jump is multi-frame and I couldn't find a tutorial to help. Also I'm not comfortable with anim.tree -s, I prefer to hard code them in. My code (I know its basic): extends KinematicBody2D const SPD = 100 const GRV = 15 const JUMPF = -350 const SPD_B = 50 var valocity = Vector2(0,0) func _process(delta): if Input.is_action_pressed("ui_right"): valocity.x = SPD $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = false elif Input.is_action_pressed("ui_left"): valocity.x = -SPD $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = true else: $AnimatedSprite.play("idle") valocity.y = valocity.y + GRV if Input.is_action_pressed("ui_sprint") and Input.is_action_pressed("ui_right"): valocity.x = SPD + SPD_B $AnimatedSprite.play("run") $AnimatedSprite.flip_h = false elif Input.is_action_pressed("ui_sprint") and Input.is_action_pressed("ui_left"): valocity.x = -SPD + -SPD_B $AnimatedSprite.play("run") $AnimatedSprite.flip_h = true if Input.is_action_just_pressed("ui_up") and is_on_floor(): valocity.y = JUMPF valocity = move_and_slide(valocity, Vector2.UP) valocity.x = lerp(valocity.x, 0, 0.3) func _on_Area2D_body_entered(body): get_tree().reload_current_scene() SPD_B is speed bonus for sprint Game is 2d platformer I tried anim.tree but couldn't use it. It was to confusing. Also I tried to code it like other but it didn't work. Any help is appreciated. A: I presume you would insert a line $AnimatedSprite.play("jump") or similar to play your jump animation. Correct? Then the issue is that it gets replaced by the "walk" (or "run") or "idle" animation the next frame. Well, do you want those animations to play while the character is on the air (not is_on_floor())? If you don't, then don't. usually the animations that play on the air are for jumping and falling, not for walking/running nor for idle. That could be for example: if is_on_floor(): if Input.is_action_pressed("ui_right"): valocity.x = SPD $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = false elif Input.is_action_pressed("ui_left"): valocity.x = -SPD $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = true else: $AnimatedSprite.play("idle") # … Now, presumably you still want air control (allow the player to move with the directions while it is on the air)… Thus I suggest to separate the animation concern. So, one block of code will set the motion. And another will set the animations. Something like this: if Input.is_action_pressed("ui_right"): valocity.x = SPD elif Input.is_action_pressed("ui_left"): valocity.x = -SPD # … if is_zero_approx(valocity.x): $AnimatedSprite.play("idle") elif valocity.x > 0.0: $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = false elif valocity.x < 0.0: $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = true The above code also makes it easy for the animation to change to "idle" automatically when the speed falls to zero. For example if you have some deceleration code such as valocity.x *= 0.7 (which, notice, is not frame rate independent, but you get the idea). And then it is easy to have a set of animations for the air and another for ground: if Input.is_action_pressed("ui_right"): valocity.x = SPD elif Input.is_action_pressed("ui_left"): valocity.x = -SPD # … if is_on_floor(): if is_zero_approx(valocity.x): $AnimatedSprite.play("idle") elif valocity.x > 0.0: $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = false elif valocity.x < 0.0: $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = true # … else: $AnimatedSprite.play("jump") # … You can, of course, define a thresholds for using the "run" animation instead of the "walk" animation. For example: if is_on_floor(): if is_zero_approx(valocity.x): $AnimatedSprite.play("idle") elif valocity.x > SPD: $AnimatedSprite.play("run") $AnimatedSprite.flip_h = false elif valocity.x < -SPD: $AnimatedSprite.play("run") $AnimatedSprite.flip_h = true elif valocity.x > 0.0: $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = false elif valocity.x < 0.0: $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = true And of course, you would have to call `move_and_slide``, and also insert the code for jumps, gravity, and so on.
Problem with coding multi-frame jump animation (GDScript)
So I am a beginner programmer using GDScript and got stuck with playing jump animation. All my animations are like 2 frames and where easy to code, but my jump is multi-frame and I couldn't find a tutorial to help. Also I'm not comfortable with anim.tree -s, I prefer to hard code them in. My code (I know its basic): extends KinematicBody2D const SPD = 100 const GRV = 15 const JUMPF = -350 const SPD_B = 50 var valocity = Vector2(0,0) func _process(delta): if Input.is_action_pressed("ui_right"): valocity.x = SPD $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = false elif Input.is_action_pressed("ui_left"): valocity.x = -SPD $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = true else: $AnimatedSprite.play("idle") valocity.y = valocity.y + GRV if Input.is_action_pressed("ui_sprint") and Input.is_action_pressed("ui_right"): valocity.x = SPD + SPD_B $AnimatedSprite.play("run") $AnimatedSprite.flip_h = false elif Input.is_action_pressed("ui_sprint") and Input.is_action_pressed("ui_left"): valocity.x = -SPD + -SPD_B $AnimatedSprite.play("run") $AnimatedSprite.flip_h = true if Input.is_action_just_pressed("ui_up") and is_on_floor(): valocity.y = JUMPF valocity = move_and_slide(valocity, Vector2.UP) valocity.x = lerp(valocity.x, 0, 0.3) func _on_Area2D_body_entered(body): get_tree().reload_current_scene() SPD_B is speed bonus for sprint Game is 2d platformer I tried anim.tree but couldn't use it. It was to confusing. Also I tried to code it like other but it didn't work. Any help is appreciated.
[ "I presume you would insert a line $AnimatedSprite.play(\"jump\") or similar to play your jump animation. Correct?\nThen the issue is that it gets replaced by the \"walk\" (or \"run\") or \"idle\" animation the next frame.\nWell, do you want those animations to play while the character is on the air (not is_on_floor())? If you don't, then don't. usually the animations that play on the air are for jumping and falling, not for walking/running nor for idle.\nThat could be for example:\nif is_on_floor():\n if Input.is_action_pressed(\"ui_right\"):\n valocity.x = SPD\n $AnimatedSprite.play(\"walk\")\n $AnimatedSprite.flip_h = false\n elif Input.is_action_pressed(\"ui_left\"):\n valocity.x = -SPD\n $AnimatedSprite.play(\"walk\")\n $AnimatedSprite.flip_h = true\n else:\n $AnimatedSprite.play(\"idle\")\n\n # …\n\nNow, presumably you still want air control (allow the player to move with the directions while it is on the air)… Thus I suggest to separate the animation concern.\nSo, one block of code will set the motion. And another will set the animations. Something like this:\nif Input.is_action_pressed(\"ui_right\"):\n valocity.x = SPD\nelif Input.is_action_pressed(\"ui_left\"):\n valocity.x = -SPD\n\n# …\n\nif is_zero_approx(valocity.x):\n $AnimatedSprite.play(\"idle\")\nelif valocity.x > 0.0:\n $AnimatedSprite.play(\"walk\")\n $AnimatedSprite.flip_h = false\nelif valocity.x < 0.0:\n $AnimatedSprite.play(\"walk\")\n $AnimatedSprite.flip_h = true\n\nThe above code also makes it easy for the animation to change to \"idle\" automatically when the speed falls to zero. For example if you have some deceleration code such as valocity.x *= 0.7 (which, notice, is not frame rate independent, but you get the idea).\nAnd then it is easy to have a set of animations for the air and another for ground:\nif Input.is_action_pressed(\"ui_right\"):\n valocity.x = SPD\nelif Input.is_action_pressed(\"ui_left\"):\n valocity.x = -SPD\n\n# …\n\nif is_on_floor():\n if is_zero_approx(valocity.x):\n $AnimatedSprite.play(\"idle\")\n elif valocity.x > 0.0:\n $AnimatedSprite.play(\"walk\")\n $AnimatedSprite.flip_h = false\n elif valocity.x < 0.0:\n $AnimatedSprite.play(\"walk\")\n $AnimatedSprite.flip_h = true\n\n # …\nelse:\n $AnimatedSprite.play(\"jump\")\n # …\n\nYou can, of course, define a thresholds for using the \"run\" animation instead of the \"walk\" animation. For example:\nif is_on_floor():\n if is_zero_approx(valocity.x):\n $AnimatedSprite.play(\"idle\")\n elif valocity.x > SPD:\n $AnimatedSprite.play(\"run\")\n $AnimatedSprite.flip_h = false\n elif valocity.x < -SPD:\n $AnimatedSprite.play(\"run\")\n $AnimatedSprite.flip_h = true\n elif valocity.x > 0.0:\n $AnimatedSprite.play(\"walk\")\n $AnimatedSprite.flip_h = false\n elif valocity.x < 0.0:\n $AnimatedSprite.play(\"walk\")\n $AnimatedSprite.flip_h = true\n\nAnd of course, you would have to call `move_and_slide``, and also insert the code for jumps, gravity, and so on.\n" ]
[ 0 ]
[]
[]
[ "animation", "gdscript", "godot", "python" ]
stackoverflow_0074660243_animation_gdscript_godot_python.txt
Q: Problem with communication with React-Native and ASP.NET WebService Edited I have a problem with communication between ASP.NET web service and react-native. I try to use ajax request after reading this: Simplest SOAP example and finally get error message. Error code bellow: "DONE": 4, "HEADERS_RECEIVED": 2, "LOADING": 3, "OPENED": 1, "UNSENT": 0, "_aborted": false, "_cachedResponse": undefined, "_hasError": true, "_headers": {"content-type": "text/xml"}, "_incrementalEvents": false, "_lowerCaseResponseHeaders": {}, "_method": "POST", "_perfKey": "network_XMLHttpRequest_http://localhost:44358/BikeWebService.asmx", "_performanceLogger": {"_closed": false, "_extras": {}, "_pointExtras": {}, "_points": {"initializeCore_end": 11271328.84606, "initializeCore_start": 11271264.66206}, "_timespans": {"network_XMLHttpRequest_http://localhost:44358/BikeWebService.asmx": [Object]}}, "_requestId": null, "_response": "Failed to connect to localhost/127.0.0.1:44358", "_responseType": "", "_sent": true, "_subscriptions": [], "_timedOut": false, "_trackingName": "unknown", "_url": "http://localhost:44358/BikeWebService.asmx", "readyState": 4, "responseHeaders": undefined, "status": 0, "timeout": 0, "upload": {}, withCredentials": true Ajax request in react native: var xmlhttp = new XMLHttpRequest(); xmlhttp.open('POST', 'http://localhost:44358/BikeWebService.asmx', true); var sr ='<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">\ <s:Header> <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/LogIn</Action> </s:Header> <s:Body>\ <LogIn xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/">\ <password>a</password>\ <login>1</login>\ </LogIn>\ </s:Body>\ </s:Envelope>'; xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4) { if (xmlhttp.status == 200) { console.log(xmlhttp.responseText); } } console.log(xmlhttp); } xmlhttp.setRequestHeader('Content-Type', 'text/xml'); xmlhttp.send(sr); In ASP.NET, I have a web method like this: [WebMethod] public ResponseModel<User> LogIn(string password, string login) { return new User(); } I tried for this answer using axios, but still getting network error. Make request to SOAP endpoint using axios I also try add cors to web.config as shown in this answer: How to allow CORS for ASP.NET WebForms endpoint? But it's still not working... SSL is disabled in ASP.NET service. I try to disabled firewall and tls in windows but this is not a problem I'm running on ASP.NET 4.8 Does anybody have any idea? Is XMl okey? I have it from WCF test client. A: Starting web service on IIS and add address to hosts on windos fix this connection error. SOAP request: let body = '<?xml version="1.0" encoding="utf-8"?>\ <soap12:Envelope xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">\ <soap12:Body>\ <LogIn xmlns="http://tempuri.org/">\ <password>string</password>\ <login>string</login>\ </LogIn>\ </soap12:Body>\ </soap12:Envelope>'; let SOAPAction = 'http://tempuri.org/LogIn'; requestOptions = { method: 'POST', body: body, headers: { Accept: '*/*', 'SOAPAction': SOAPAction, 'Content-Type': 'text/xml; charset=utf-8' }, }; await fetch('http://ip:port/BikeWebService.asmx', requestOptions) .then((response) => console.log(response)) .catch((error) => { console.log('er' + error) });
Problem with communication with React-Native and ASP.NET WebService
Edited I have a problem with communication between ASP.NET web service and react-native. I try to use ajax request after reading this: Simplest SOAP example and finally get error message. Error code bellow: "DONE": 4, "HEADERS_RECEIVED": 2, "LOADING": 3, "OPENED": 1, "UNSENT": 0, "_aborted": false, "_cachedResponse": undefined, "_hasError": true, "_headers": {"content-type": "text/xml"}, "_incrementalEvents": false, "_lowerCaseResponseHeaders": {}, "_method": "POST", "_perfKey": "network_XMLHttpRequest_http://localhost:44358/BikeWebService.asmx", "_performanceLogger": {"_closed": false, "_extras": {}, "_pointExtras": {}, "_points": {"initializeCore_end": 11271328.84606, "initializeCore_start": 11271264.66206}, "_timespans": {"network_XMLHttpRequest_http://localhost:44358/BikeWebService.asmx": [Object]}}, "_requestId": null, "_response": "Failed to connect to localhost/127.0.0.1:44358", "_responseType": "", "_sent": true, "_subscriptions": [], "_timedOut": false, "_trackingName": "unknown", "_url": "http://localhost:44358/BikeWebService.asmx", "readyState": 4, "responseHeaders": undefined, "status": 0, "timeout": 0, "upload": {}, withCredentials": true Ajax request in react native: var xmlhttp = new XMLHttpRequest(); xmlhttp.open('POST', 'http://localhost:44358/BikeWebService.asmx', true); var sr ='<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">\ <s:Header> <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/LogIn</Action> </s:Header> <s:Body>\ <LogIn xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/">\ <password>a</password>\ <login>1</login>\ </LogIn>\ </s:Body>\ </s:Envelope>'; xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4) { if (xmlhttp.status == 200) { console.log(xmlhttp.responseText); } } console.log(xmlhttp); } xmlhttp.setRequestHeader('Content-Type', 'text/xml'); xmlhttp.send(sr); In ASP.NET, I have a web method like this: [WebMethod] public ResponseModel<User> LogIn(string password, string login) { return new User(); } I tried for this answer using axios, but still getting network error. Make request to SOAP endpoint using axios I also try add cors to web.config as shown in this answer: How to allow CORS for ASP.NET WebForms endpoint? But it's still not working... SSL is disabled in ASP.NET service. I try to disabled firewall and tls in windows but this is not a problem I'm running on ASP.NET 4.8 Does anybody have any idea? Is XMl okey? I have it from WCF test client.
[ "Starting web service on IIS and add address to hosts on windos fix this connection error.\nSOAP request:\nlet body = '<?xml version=\"1.0\" encoding=\"utf-8\"?>\\\n<soap12:Envelope xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\\\n <soap12:Body>\\\n <LogIn xmlns=\"http://tempuri.org/\">\\\n <password>string</password>\\\n <login>string</login>\\\n </LogIn>\\\n </soap12:Body>\\\n</soap12:Envelope>';\n\nlet SOAPAction = 'http://tempuri.org/LogIn';\n\nrequestOptions = {\n method: 'POST',\n body: body,\n headers: {\n Accept: '*/*',\n 'SOAPAction': SOAPAction,\n 'Content-Type': 'text/xml; charset=utf-8'\n },\n};\n\n\nawait fetch('http://ip:port/BikeWebService.asmx', requestOptions)\n.then((response) => console.log(response))\n.catch((error) => {\n console.log('er' + error)\n});\n\n" ]
[ 0 ]
[]
[]
[ "asp.net", "c#", "react_native", "soap", "web_services" ]
stackoverflow_0074635104_asp.net_c#_react_native_soap_web_services.txt
Q: BeautifulSoup find a href in marquee I'm using bs4 to scrape links from a scrolling marquee. I'm able to get the marquee data, which is returned as a bs4 resultSet element. However, I cannot seem to access the href's within the data. I'm sure I'm missing something as I'm new to web scraping, and appreciate any guidance anyone has. Note: I can get the links easy peasy with selenium and chrome driver, but it takes forever. This returns all of the marquee data: url = 'https://drugs.globalincidentmap.com/' response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') marquee = soup.select('div', class_='h-48') print(marquee) However when I try to drill down further into the data, I get the empty list or NoneType/KeyError or AttributeError. for a in marquee.find_all('a', href=True): link = a.find('div', class_=':nth-child') or for a in marquee.find_all('a', href=True): link = a.find('div', class_='flex p-2') Links in marquee A: I can get the links easy peasy with selenium and chrome driver Probably because the div with h-48 class is loaded with JavaScript; even if it wasn't, I don't think soup.find('div', class_='h-48') would work because that element has more classes, and you need to pass all of them as class_ [and I don't think soup.select('div', class_='h-48') gives the exact results you expect it to - select isn't really supposed to have a class_ argument - just a CSS selector string]. soup.find('div', attrs={'class':'h-48'}) or soup.select('div.h-48') can be expected to work on the html that is formed after JS loading, but you need selenium to get that... Fortunately, I think the data you want is already in the fetched html, just in a different format - you can extract a list of dictionaries (mqCont) with # import json marq = soup.find('marquee', attrs={'class':'h-48'}) if marq is None: print('Could Not Find marquee.h-48') if not marq.get(':contents'): print('marquee.h-48 has no [:contents] attr') try: mqCont = json.loads(marq.get(':contents', '[]')) except Exception as e: mqCont = [] print('failed to parse marquee.h-48[:contents] <---', e) or, more shortly (if you're confident there won't be any error to debug/breakdown): mqCont = json.loads(soup.select_one('marquee.h-48').get(':contents', '[]')) You can get a list of links to news articles with [m['url'] for m in mqCont if 'url' in m], but since you were trying to get find with class_='flex p-2', you probably want the .../event_detail?id=... links. You can form them as below evtUrls = [f"{url.strip('/')}/event_detail?id={m['id']}" for m in mqCont if 'id' in m] You can also view the list of dictionaries as a table [with pandas] by doing something like: # import pandas omitKeys = ['domain_event_types', 'country'] for i, m in enumerate(mqCont): mDesc = ' '.join(w for w in BeautifulSoup( m['description'] if 'description' in m else '' ).get_text().split() if w) if mDesc: m['description'] = mDesc if 'id' in m: m['eventUrl'] = f"{url.strip('/')}/event_detail?id={m['id']}" mqCont[i] = {k:v for k, v in m.items() if k not in omitKeys} mqcDF = pandas.DataFrame(mqCont).dropna(axis='columns', how='all').set_index('id') and the first 5 rows [of 100 rows total] of mqcDF: id country_id address event_gmt_time severity infrastructure tip_text url description latitude longitude created_user_id location_granularity_id is_approved created_at updated_at eventUrl 11919404 231 Pennsylvania, USA 2022-12-01 18:36:53 Severe Unknown PENNSYLVANIA - Photos - Suspects - Evidence In Multi-County Drug Bust https://www.wfmz.com/news/area/berks/photos-suspects-evidence-in-multi-county-drug-bust/collection_bf795c98-71ad-11ed-99fe-4305f426699b.html#1 [69 NEWS] PENNSYLVANIA - PHOTOS: Suspects, evidence in multi-county drug bust "Authorities said they seized evidence that included 27.5 kilograms of cocaine with a potential street value of $2.7 million and 5.5 kilograms of fentanyl with a potential street value of $1.6 million." Read full article at: https://www.wfmz.com/news/area/berks/photos-suspects-evidence-in-multi-county-drug-bust/collection_bf795c98-71ad-11ed-99fe-4305f426699b.html#1 41.2033 -77.1945 14 8 1 2022-12-02T18:44:43.000000Z 2022-12-02T18:44:43.000000Z https://drugs.globalincidentmap.com/event_detail?id=11919404 11919401 40 Vancouver Island, British Columbia, Canada 2022-12-01 18:33:01 Severe Unknown CANADA - Drugs - Guns Seized As 4 BC Men With Hells Angels Ties Face Serious Charges https://www.terracestandard.com/news/alleged-drug-traffickers-on-vancouver-island-with-hells-angels-ties-face-serious-charges/ [terracestandard.com] CANADA - Drugs, guns seized as 4 B.C. men with Hells Angels ties face ‘serious charges’ "CFSEU said the seized drugs included 7.75kg of cocaine, 4kg of cannabis, 1.9kg of methamphetamine, 248 oxycodone pills, and more." Read full article at: https://www.terracestandard.com/news/alleged-drug-traffickers-on-vancouver-island-with-hells-angels-ties-face-serious-charges/ 49.6506 -125.449 14 5 1 2022-12-02T18:36:37.000000Z 2022-12-02T18:36:37.000000Z https://drugs.globalincidentmap.com/event_detail?id=11919401 11919397 133 Male, Maldives 2022-11-20 18:29:26 Severe Unknown MALDIVES - Drugs Worth Mvr 2 Mln Seized By Customs https://avas.mv/en/125385 [avas.mv] MALDIVES - Drugs worth MVR 2 mln seized by Customs "Maldives Customs Service has seized 1.34 kg of drugs smuggled into the Maldives via courier." Read full article at: https://avas.mv/en/125385 4.1755 73.5093 14 5 1 2022-12-02T18:32:45.000000Z 2022-12-02T18:32:45.000000Z https://drugs.globalincidentmap.com/event_detail?id=11919397 11919394 231 100 South Willow Avenue, Compton, CA, USA 2022-11-29 18:23:50 Severe Unknown CALIFORNIA - USD4 Million Worth Of Illegal Drugs Seized In Compton https://www.foxla.com/news/4-million-worth-of-illegal-drugs-seized-in-compton [foxla] CALIFORNIA - $4 million worth of illegal drugs seized in Compton "A search warrant at the home resulted in the seizure of about 5.5 lbs. of suspected tar heroin, 10 kilos of suspected powder cocaine, 6 kilos of suspected powder fentanyl, 6,000 suspected ecstasy pills containing fentanyl, and 254,000 suspected fentanyl pills all worth a combined estimated street value of $4.17 million, authorities said. " Read full article at: https://www.foxla.com/news/4-million-worth-of-illegal-drugs-seized-in-compton 33.896 -118.218 14 5 1 2022-12-02T18:29:25.000000Z 2022-12-02T18:29:25.000000Z https://drugs.globalincidentmap.com/event_detail?id=11919394 11919392 166 Gwadar, Pakistan 2022-12-01 18:22:00 Severe Unknown PAKISTAN - Convoy Of Camels Loaded With Drugs Seized https://pakobserver.net/convoy-of-camels-loaded-with-drugs-seized/ [pakobserver.net] PAKISTAN - Convoy Of Camels Loaded With Drugs Seized "While searching the goods carried by the camels, ANF officials found them to be full of drugs (hashish). The drugs weighed around 1.4 tons." Read full article at: https://pakobserver.net/convoy-of-camels-loaded-with-drugs-seized/ 25.1313 62.325 14 5 1 2022-12-02T18:23:49.000000Z 2022-12-02T18:23:49.000000Z https://drugs.globalincidentmap.com/event_detail?id=11919392 Markdown for the above table was printed with print(mqcDf.loc[mqcDf.index[:5]].to_markdown())
BeautifulSoup find a href in marquee
I'm using bs4 to scrape links from a scrolling marquee. I'm able to get the marquee data, which is returned as a bs4 resultSet element. However, I cannot seem to access the href's within the data. I'm sure I'm missing something as I'm new to web scraping, and appreciate any guidance anyone has. Note: I can get the links easy peasy with selenium and chrome driver, but it takes forever. This returns all of the marquee data: url = 'https://drugs.globalincidentmap.com/' response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') marquee = soup.select('div', class_='h-48') print(marquee) However when I try to drill down further into the data, I get the empty list or NoneType/KeyError or AttributeError. for a in marquee.find_all('a', href=True): link = a.find('div', class_=':nth-child') or for a in marquee.find_all('a', href=True): link = a.find('div', class_='flex p-2') Links in marquee
[ "\nI can get the links easy peasy with selenium and chrome driver\n\nProbably because the div with h-48 class is loaded with JavaScript; even if it wasn't, I don't think soup.find('div', class_='h-48') would work because that element has more classes, and you need to pass all of them as class_ [and I don't think soup.select('div', class_='h-48') gives the exact results you expect it to - select isn't really supposed to have a class_ argument - just a CSS selector string].\nsoup.find('div', attrs={'class':'h-48'}) or soup.select('div.h-48') can be expected to work on the html that is formed after JS loading, but you need selenium to get that...\n\n\nFortunately, I think the data you want is already in the fetched html, just in a different format - you can extract a list of dictionaries (mqCont) with\n# import json\n\nmarq = soup.find('marquee', attrs={'class':'h-48'})\nif marq is None: print('Could Not Find marquee.h-48')\nif not marq.get(':contents'): print('marquee.h-48 has no [:contents] attr')\n\ntry: mqCont = json.loads(marq.get(':contents', '[]'))\nexcept Exception as e:\n mqCont = []\n print('failed to parse marquee.h-48[:contents] <---', e)\n\nor, more shortly (if you're confident there won't be any error to debug/breakdown):\nmqCont = json.loads(soup.select_one('marquee.h-48').get(':contents', '[]'))\n\n\nYou can get a list of links to news articles with [m['url'] for m in mqCont if 'url' in m], but since you were trying to get find with class_='flex p-2', you probably want the .../event_detail?id=... links. You can form them as below\nevtUrls = [f\"{url.strip('/')}/event_detail?id={m['id']}\" for m in mqCont if 'id' in m]\n\n\nYou can also view the list of dictionaries as a table [with pandas] by doing something like:\n# import pandas\n\nomitKeys = ['domain_event_types', 'country']\nfor i, m in enumerate(mqCont):\n mDesc = ' '.join(w for w in BeautifulSoup(\n m['description'] if 'description' in m else ''\n ).get_text().split() if w)\n if mDesc: m['description'] = mDesc\n if 'id' in m: m['eventUrl'] = f\"{url.strip('/')}/event_detail?id={m['id']}\"\n mqCont[i] = {k:v for k, v in m.items() if k not in omitKeys}\n\nmqcDF = pandas.DataFrame(mqCont).dropna(axis='columns', how='all').set_index('id')\n\nand the first 5 rows [of 100 rows total] of mqcDF:\n\n\n\n\nid\ncountry_id\naddress\nevent_gmt_time\nseverity\ninfrastructure\ntip_text\nurl\ndescription\nlatitude\nlongitude\ncreated_user_id\nlocation_granularity_id\nis_approved\ncreated_at\nupdated_at\neventUrl\n\n\n\n\n11919404\n231\nPennsylvania, USA\n2022-12-01 18:36:53\nSevere\nUnknown\nPENNSYLVANIA - Photos - Suspects - Evidence In Multi-County Drug Bust\nhttps://www.wfmz.com/news/area/berks/photos-suspects-evidence-in-multi-county-drug-bust/collection_bf795c98-71ad-11ed-99fe-4305f426699b.html#1\n[69 NEWS] PENNSYLVANIA - PHOTOS: Suspects, evidence in multi-county drug bust \"Authorities said they seized evidence that included 27.5 kilograms of cocaine with a potential street value of $2.7 million and 5.5 kilograms of fentanyl with a potential street value of $1.6 million.\" Read full article at: https://www.wfmz.com/news/area/berks/photos-suspects-evidence-in-multi-county-drug-bust/collection_bf795c98-71ad-11ed-99fe-4305f426699b.html#1\n41.2033\n-77.1945\n14\n8\n1\n2022-12-02T18:44:43.000000Z\n2022-12-02T18:44:43.000000Z\nhttps://drugs.globalincidentmap.com/event_detail?id=11919404\n\n\n11919401\n40\nVancouver Island, British Columbia, Canada\n2022-12-01 18:33:01\nSevere\nUnknown\nCANADA - Drugs - Guns Seized As 4 BC Men With Hells Angels Ties Face Serious Charges\nhttps://www.terracestandard.com/news/alleged-drug-traffickers-on-vancouver-island-with-hells-angels-ties-face-serious-charges/\n[terracestandard.com] CANADA - Drugs, guns seized as 4 B.C. men with Hells Angels ties face ‘serious charges’ \"CFSEU said the seized drugs included 7.75kg of cocaine, 4kg of cannabis, 1.9kg of methamphetamine, 248 oxycodone pills, and more.\" Read full article at: https://www.terracestandard.com/news/alleged-drug-traffickers-on-vancouver-island-with-hells-angels-ties-face-serious-charges/\n49.6506\n-125.449\n14\n5\n1\n2022-12-02T18:36:37.000000Z\n2022-12-02T18:36:37.000000Z\nhttps://drugs.globalincidentmap.com/event_detail?id=11919401\n\n\n11919397\n133\nMale, Maldives\n2022-11-20 18:29:26\nSevere\nUnknown\nMALDIVES - Drugs Worth Mvr 2 Mln Seized By Customs\nhttps://avas.mv/en/125385\n[avas.mv] MALDIVES - Drugs worth MVR 2 mln seized by Customs \"Maldives Customs Service has seized 1.34 kg of drugs smuggled into the Maldives via courier.\" Read full article at: https://avas.mv/en/125385\n4.1755\n73.5093\n14\n5\n1\n2022-12-02T18:32:45.000000Z\n2022-12-02T18:32:45.000000Z\nhttps://drugs.globalincidentmap.com/event_detail?id=11919397\n\n\n11919394\n231\n100 South Willow Avenue, Compton, CA, USA\n2022-11-29 18:23:50\nSevere\nUnknown\nCALIFORNIA - USD4 Million Worth Of Illegal Drugs Seized In Compton\nhttps://www.foxla.com/news/4-million-worth-of-illegal-drugs-seized-in-compton\n[foxla] CALIFORNIA - $4 million worth of illegal drugs seized in Compton \"A search warrant at the home resulted in the seizure of about 5.5 lbs. of suspected tar heroin, 10 kilos of suspected powder cocaine, 6 kilos of suspected powder fentanyl, 6,000 suspected ecstasy pills containing fentanyl, and 254,000 suspected fentanyl pills all worth a combined estimated street value of $4.17 million, authorities said. \" Read full article at: https://www.foxla.com/news/4-million-worth-of-illegal-drugs-seized-in-compton\n33.896\n-118.218\n14\n5\n1\n2022-12-02T18:29:25.000000Z\n2022-12-02T18:29:25.000000Z\nhttps://drugs.globalincidentmap.com/event_detail?id=11919394\n\n\n11919392\n166\nGwadar, Pakistan\n2022-12-01 18:22:00\nSevere\nUnknown\nPAKISTAN - Convoy Of Camels Loaded With Drugs Seized\nhttps://pakobserver.net/convoy-of-camels-loaded-with-drugs-seized/\n[pakobserver.net] PAKISTAN - Convoy Of Camels Loaded With Drugs Seized \"While searching the goods carried by the camels, ANF officials found them to be full of drugs (hashish). The drugs weighed around 1.4 tons.\" Read full article at: https://pakobserver.net/convoy-of-camels-loaded-with-drugs-seized/\n25.1313\n62.325\n14\n5\n1\n2022-12-02T18:23:49.000000Z\n2022-12-02T18:23:49.000000Z\nhttps://drugs.globalincidentmap.com/event_detail?id=11919392\n\n\n\n\nMarkdown for the above table was printed with print(mqcDf.loc[mqcDf.index[:5]].to_markdown())\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074661666_beautifulsoup_python_web_scraping.txt
Q: What is this assignment asking me to do, about summing the digits of a value 0425h? I have this assembly problem where: Given the register AX=0425h. Write a program which adds the sum of digits of value 0425h and stores the sum in the same register AX. I have no idea what to do in it. Can anyone help me solve this thing? I tried to think of a solution and did not find anything :) A: Given the register AX=0425h The digits of this hexadecimal number are 0, 4, 2, and 5. The assignment wants you to sum these as in 0 + 4 + 2 + 5 = 11. One possible solution is the following: mov edx, eax ; -> DH=04h AL=25h aam 16 ; 25h/16 -> AH=2 AL=5 add al, ah ; (5+2) -> AL=7 xchg al, dh ; -> DH=7 AL=04h aam 16 ; 04h/16 -> AH=0 AL=4 add al, ah ; (4+0) -> AL=4 add al, dh ; (4+7) -> AL=11 cbw ; -> AX=11 The code works for any value AX=[0000h,FFFFh] producing AX=[0,60]. A solution that uses a loop and that can deal with any value EAX=[00000000h,FFFFFFFFh] producing EAX=[0,120]: xor ecx, ecx ; TempResult = 0 More: mov ebx, eax ; Copy to another temporary register where and ebx, 15 ; we only keep the lowest digit add ecx, ebx ; TempResult + LowestDigit shr eax, 4 ; Shift the original digits to the right discarding the one(s) we already added to the TempResult jnz More ; Only looping if more non-zero digits exist mov eax, ecx ; EAX = TempResult
What is this assignment asking me to do, about summing the digits of a value 0425h?
I have this assembly problem where: Given the register AX=0425h. Write a program which adds the sum of digits of value 0425h and stores the sum in the same register AX. I have no idea what to do in it. Can anyone help me solve this thing? I tried to think of a solution and did not find anything :)
[ "\nGiven the register AX=0425h\n\nThe digits of this hexadecimal number are 0, 4, 2, and 5. The assignment wants you to sum these as in 0 + 4 + 2 + 5 = 11.\nOne possible solution is the following:\nmov edx, eax ; -> DH=04h AL=25h\naam 16 ; 25h/16 -> AH=2 AL=5\nadd al, ah ; (5+2) -> AL=7\nxchg al, dh ; -> DH=7 AL=04h\naam 16 ; 04h/16 -> AH=0 AL=4\nadd al, ah ; (4+0) -> AL=4\nadd al, dh ; (4+7) -> AL=11\ncbw ; -> AX=11\n\nThe code works for any value AX=[0000h,FFFFh] producing AX=[0,60].\n\nA solution that uses a loop and that can deal with any value EAX=[00000000h,FFFFFFFFh] producing EAX=[0,120]:\n xor ecx, ecx ; TempResult = 0\nMore:\n mov ebx, eax ; Copy to another temporary register where\n and ebx, 15 ; we only keep the lowest digit\n add ecx, ebx ; TempResult + LowestDigit\n shr eax, 4 ; Shift the original digits to the right discarding the one(s) we already added to the TempResult\n jnz More ; Only looping if more non-zero digits exist\n mov eax, ecx ; EAX = TempResult\n\n" ]
[ 2 ]
[]
[]
[ "assembly", "windows", "x86" ]
stackoverflow_0074640454_assembly_windows_x86.txt
Q: Calculate checksum of a file in c I try to calculate the checksum of the file in c. I have a file of around 100MB random and I want to calculate the checksum. I try this code from here: https://stackoverflow.com/a/3464166/14888108 int CheckSumCalc(char * filename){ FILE *fp = fopen(filename,"rb"); unsigned char checksum = 0; while (!feof(fp) && !ferror(fp)) { checksum ^= fgetc(fp); } fclose(fp); return checksum; } but I got a Segmentation fault. in this line "while (!feof(fp) && !ferror(fp))" Any help will be appreciated. A: The issue here is that you are not checking for the return value of fopen. fopen returns NULL if the file cannot be opened. This means that fp is an invalid pointer, causing the segmentation fault. You should change the code to check for the return value of fopen and handle the error accordingly. int CheckSumCalc(char * filename){ FILE *fp = fopen(filename,"rb"); if(fp == NULL) { //handle error here return -1; } unsigned char checksum = 0; while (!feof(fp) && !ferror(fp)) { checksum ^= fgetc(fp); } fclose(fp); return checksum; } A: The segmentation fault that you are experiencing is likely caused by the fact that you are not checking the return value of the fopen function, which is used to open the file for reading. If the fopen function fails, it will return NULL, and attempting to read from or write to a NULL file pointer can cause a segmentation fault. To fix this issue, you can add a check for the return value of the fopen function, and handle the case where the file cannot be opened. For example, you could modify your code like this: int CheckSumCalc(char * filename){ FILE *fp = fopen(filename, "rb"); if (fp == NULL) { // Handle error: file could not be opened return -1; } unsigned char checksum = 0; while (!feof(fp) && !ferror(fp)) { checksum ^= fgetc(fp); } fclose(fp); return checksum; } In this modified code, the fopen function is called to open the file for reading, and the return value is checked to see if it is NULL. If the file could not
Calculate checksum of a file in c
I try to calculate the checksum of the file in c. I have a file of around 100MB random and I want to calculate the checksum. I try this code from here: https://stackoverflow.com/a/3464166/14888108 int CheckSumCalc(char * filename){ FILE *fp = fopen(filename,"rb"); unsigned char checksum = 0; while (!feof(fp) && !ferror(fp)) { checksum ^= fgetc(fp); } fclose(fp); return checksum; } but I got a Segmentation fault. in this line "while (!feof(fp) && !ferror(fp))" Any help will be appreciated.
[ "The issue here is that you are not checking for the return value of fopen. fopen returns NULL if the file cannot be opened. This means that fp is an invalid pointer, causing the segmentation fault.\nYou should change the code to check for the return value of fopen and handle the error accordingly.\nint CheckSumCalc(char * filename){\n FILE *fp = fopen(filename,\"rb\");\n if(fp == NULL)\n {\n //handle error here\n return -1;\n }\n unsigned char checksum = 0;\n while (!feof(fp) && !ferror(fp)) {\n checksum ^= fgetc(fp);\n }\n fclose(fp);\n return checksum;\n}\n\n", "The segmentation fault that you are experiencing is likely caused by the fact that you are not checking the return value of the fopen function, which is used to open the file for reading. If the fopen function fails, it will return NULL, and attempting to read from or write to a NULL file pointer can cause a segmentation fault.\nTo fix this issue, you can add a check for the return value of the fopen function, and handle the case where the file cannot be opened. For example, you could modify your code like this:\nint CheckSumCalc(char * filename){\nFILE *fp = fopen(filename, \"rb\");\nif (fp == NULL) {\n // Handle error: file could not be opened\n return -1;\n}\n\nunsigned char checksum = 0;\nwhile (!feof(fp) && !ferror(fp)) {\n checksum ^= fgetc(fp);\n}\nfclose(fp);\nreturn checksum;\n}\n\nIn this modified code, the fopen function is called to open the file for reading, and the return value is checked to see if it is NULL. If the file could not\n" ]
[ 1, 0 ]
[]
[]
[ "c", "checksum", "process" ]
stackoverflow_0074663097_c_checksum_process.txt
Q: jest change mocked value at later stage I have a mock where it sets up a return value before all my tests. But I was wondering if you could update a value in the test itself. As you can see I want to just update the boolean value of mockedIsloading, without calling the entire mockedLoadStatus.mockReturnValue({...}) again in my test with a new isLoading value of true this time around. Would be nice to just be able to call mockedIsloading.mockReturnValueOnce(true) but this does not seem to work. import { loadStatus, } from 'pathToMyFile' jest.mock('pathToMyFile') const mockedLoadStatus jest.mocked(loadStatus) const mockedMutate = jest.fn() const mockedIsLoading = jest.fn().mockReturnValue(false) beforeAll(() => { mockedLoadStatus.mockReturnValue({ mutate: mockedMutate, isLoading: mockedIsloading, }) }) test('my test', () => { mockedIsloading.mockReturnValueOnce(true) render(<Wrapper />) }) A: What do you mean "doesn't work"? I mean this works OK: const mockedLoadStatus = jest.fn(); const mockedMutate = jest.fn() const mockedIsLoading = jest.fn().mockReturnValue(false) beforeAll(() => { mockedLoadStatus.mockReturnValue({ mutate: mockedMutate, isLoading: mockedIsLoading, }) }) test('some test', () => { expect(mockedLoadStatus().isLoading()).toBeFalsy(); }) test('my test', () => { mockedIsLoading.mockReturnValueOnce(true) expect(mockedLoadStatus().isLoading()).toBeTruthy(); expect(mockedLoadStatus().isLoading()).toBeFalsy(); }) Or am I missing something :) ?
jest change mocked value at later stage
I have a mock where it sets up a return value before all my tests. But I was wondering if you could update a value in the test itself. As you can see I want to just update the boolean value of mockedIsloading, without calling the entire mockedLoadStatus.mockReturnValue({...}) again in my test with a new isLoading value of true this time around. Would be nice to just be able to call mockedIsloading.mockReturnValueOnce(true) but this does not seem to work. import { loadStatus, } from 'pathToMyFile' jest.mock('pathToMyFile') const mockedLoadStatus jest.mocked(loadStatus) const mockedMutate = jest.fn() const mockedIsLoading = jest.fn().mockReturnValue(false) beforeAll(() => { mockedLoadStatus.mockReturnValue({ mutate: mockedMutate, isLoading: mockedIsloading, }) }) test('my test', () => { mockedIsloading.mockReturnValueOnce(true) render(<Wrapper />) })
[ "What do you mean \"doesn't work\"? I mean this works OK:\nconst mockedLoadStatus = jest.fn();\n\nconst mockedMutate = jest.fn()\nconst mockedIsLoading = jest.fn().mockReturnValue(false)\n\nbeforeAll(() => {\n mockedLoadStatus.mockReturnValue({\n mutate: mockedMutate,\n isLoading: mockedIsLoading,\n })\n})\n\ntest('some test', () => {\n expect(mockedLoadStatus().isLoading()).toBeFalsy();\n})\n\ntest('my test', () => {\n mockedIsLoading.mockReturnValueOnce(true)\n expect(mockedLoadStatus().isLoading()).toBeTruthy();\n expect(mockedLoadStatus().isLoading()).toBeFalsy();\n})\n\nOr am I missing something :) ?\n" ]
[ 0 ]
[]
[]
[ "jestjs" ]
stackoverflow_0074635669_jestjs.txt
Q: How to get certificates list in SIM7000E (SIM7000)? SimCom SIM7600 Series use AT+CCERTDELE to delete certificates. Also here is AT+CCERTLIST command to get list certificates. Can we check the same in SIM7000? A: If you're trying to verify the modem or you're hosting a domain with the IP of your modem, then you should upload your certificate and list of trusted CA's to the device in the customer folder. You can then set them with the AT+SHSSL command. If you're just trying to make HTTPS requests you don't need to do anything with certificates on the SIMCOM modems. See this Gist for a walkthrough
How to get certificates list in SIM7000E (SIM7000)?
SimCom SIM7600 Series use AT+CCERTDELE to delete certificates. Also here is AT+CCERTLIST command to get list certificates. Can we check the same in SIM7000?
[ "If you're trying to verify the modem or you're hosting a domain with the IP of your modem, then you should upload your certificate and list of trusted CA's to the device in the customer folder. You can then set them with the AT+SHSSL command.\nIf you're just trying to make HTTPS requests you don't need to do anything with certificates on the SIMCOM modems. See this Gist for a walkthrough\n" ]
[ 0 ]
[]
[]
[ "at_command", "mqtt", "raspberry_pi", "raspberry_pi4", "ssl" ]
stackoverflow_0074347658_at_command_mqtt_raspberry_pi_raspberry_pi4_ssl.txt
Q: How to set default file viewer in SourceTree? I want to set default file viewer in SourceTree. The current one now is Notepad which does not show line break properly (all codes are in one line). A: SourceTree uses the default "Open With" application like Explorer. As far as I know other than changing the default application used by each file extension you cannot change the behavior of the menu item in SourceTree. However... You can add a custom action to achieve the same result using Tools | Options, Custom Actions tab: This will appear under the Custom Actions menu. As far as I know you cannot add a shortcut key to custom actions. The SourceTree blog has more info. A: I had this same problem for my MacBook. To have sourcetree Open selected version, or Open current version a file with your desired program, change the system-wide default app used to open the file type to your desired app: using Finder, find a file with the same file type that you are trying to open via SourceTree TIP: if cannot find file with same file type, can create one via Terminal with command: touch file.filetype right click said file in Finder click Get Info expand Open With: use revealed drop-down menu to select desired app below the drop-down menu, click Change All... in the pop-up window, click Continue done! go to SourceTree and Open selected version, or Open current version that file :) reference: https://www.laptopmag.com/articles/how-to-change-default-applications-mac A: Inspired by Eric's answer, for Windows: Open file explorer > right click any .py file > "open with" > "choose another app" > [your editor e.g. atom] > "always use this app to open .py files" (for python source files) Then simply right click your file on SourceTree > "Open selected version" A: For Macs, SourceTree uses your system's default file viewer for the file type that you open. For example if you double-click a .js file in SourceTree, it will use your Mac's default file viewer for JavaScript files. In SourceTree the fastest way to change the default file viewer for the file you want is to: Right-click the file and select "Show In Finder" In Finder right-click the file and select "Get Info" (or use keyboard shortcut Cmd-i) Look for the "Open with:" option and use the dropdown to select the program you want Click the "Change All..." button to update the default program for all files of this type Click the "Continue" button to save Once you make this change SourceTree will open the file with the program you just selected.
How to set default file viewer in SourceTree?
I want to set default file viewer in SourceTree. The current one now is Notepad which does not show line break properly (all codes are in one line).
[ "SourceTree uses the default \"Open With\" application like Explorer. As far as I know other than changing the default application used by each file extension you cannot change the behavior of the menu item in SourceTree.\nHowever...\nYou can add a custom action to achieve the same result using Tools | Options, Custom Actions tab:\n\nThis will appear under the Custom Actions menu. As far as I know you cannot add a shortcut key to custom actions.\nThe SourceTree blog has more info.\n", "I had this same problem for my MacBook.\nTo have sourcetree Open selected version, or Open current version a file with your desired program, change the system-wide default app used to open the file type to your desired app:\n\nusing Finder, find a file with the same file type that you are trying to open via SourceTree\n\nTIP: if cannot find file with same file type, can create one via Terminal with command:\ntouch file.filetype\n\n\nright click said file in Finder\nclick Get Info\nexpand Open With:\nuse revealed drop-down menu to select desired app\nbelow the drop-down menu, click Change All...\nin the pop-up window, click Continue\ndone!\ngo to SourceTree and Open selected version, or Open current version that file :)\n\nreference: https://www.laptopmag.com/articles/how-to-change-default-applications-mac\n", "Inspired by Eric's answer, for Windows:\nOpen file explorer > right click any .py file > \"open with\" > \"choose another app\" > [your editor e.g. atom] > \"always use this app to open .py files\" (for python source files)\nThen simply right click your file on SourceTree > \"Open selected version\"\n", "For Macs, SourceTree uses your system's default file viewer for the file type that you open. For example if you double-click a .js file in SourceTree, it will use your Mac's default file viewer for JavaScript files.\nIn SourceTree the fastest way to change the default file viewer for the file you want is to:\n\nRight-click the file and select \"Show In Finder\"\nIn Finder right-click the file and select \"Get Info\" (or use keyboard shortcut Cmd-i)\nLook for the \"Open with:\" option and use the dropdown to select the program you want\nClick the \"Change All...\" button to update the default program for all files of this type\nClick the \"Continue\" button to save\n\nOnce you make this change SourceTree will open the file with the program you just selected.\n" ]
[ 47, 18, 1, 0 ]
[]
[]
[ "atlassian_sourcetree" ]
stackoverflow_0020309879_atlassian_sourcetree.txt
Q: CSS - Change background color of list on button hover In simplest terms: I have a list with a button inside of that list. I would like for my list background color to change upon hovering over the button. Please don't be mistaken for me wanting the button's background color to change. Here's an example of what I want the list to do: Unfortunately, because it's Squarespace. I have limited access to changing the current CSS. Instead what I can do is overwrite CSS with custom CSS which I've done in the past. They have preset class's for each element. The following are the class names: .user-items-list .list-item-content__button I've been able to change the button color background on hover, you can reference this code here: .user-items-list li:nth-child(1) .list-item-content__button:hover{ background-color:#2547A0!important; opacity: 1; transition: 0.2s; } .user-items-list li:nth-child(1) .list-item-content__button{ transition: 0.2s; } I would like to do this on multiple list's so the code can not be generalized (cannot make all other list's change the same color if I want them to be different colors) so please specify with "nth-child" or any other means. Thanks in advance! A: You could just use the :has pseudo class. So you can do something like this: .user-items-list li:nth-child(1):has(.list-item-content__button:hover){ background-color:#2547A0!important; opacity: 1; } .user-items-list li:nth-child(1):has(.list-item-content__button){ transition: 0.2s; } jsfiddle example: https://jsfiddle.net/OoShiit/1zdyrkne/9/ Look at the mdn web docs about the :has pseudo class: https://developer.mozilla.org/en-US/docs/Web/CSS/:has
CSS - Change background color of list on button hover
In simplest terms: I have a list with a button inside of that list. I would like for my list background color to change upon hovering over the button. Please don't be mistaken for me wanting the button's background color to change. Here's an example of what I want the list to do: Unfortunately, because it's Squarespace. I have limited access to changing the current CSS. Instead what I can do is overwrite CSS with custom CSS which I've done in the past. They have preset class's for each element. The following are the class names: .user-items-list .list-item-content__button I've been able to change the button color background on hover, you can reference this code here: .user-items-list li:nth-child(1) .list-item-content__button:hover{ background-color:#2547A0!important; opacity: 1; transition: 0.2s; } .user-items-list li:nth-child(1) .list-item-content__button{ transition: 0.2s; } I would like to do this on multiple list's so the code can not be generalized (cannot make all other list's change the same color if I want them to be different colors) so please specify with "nth-child" or any other means. Thanks in advance!
[ "You could just use the :has pseudo class. So you can do something like this:\n.user-items-list li:nth-child(1):has(.list-item-content__button:hover){\n background-color:#2547A0!important;\n opacity: 1;\n}\n\n.user-items-list li:nth-child(1):has(.list-item-content__button){\n transition: 0.2s;\n}\n\njsfiddle example: https://jsfiddle.net/OoShiit/1zdyrkne/9/\nLook at the mdn web docs about the :has pseudo class:\nhttps://developer.mozilla.org/en-US/docs/Web/CSS/:has\n" ]
[ 1 ]
[]
[]
[ "css", "css_animations", "hover", "squarespace" ]
stackoverflow_0074662703_css_css_animations_hover_squarespace.txt
Q: Regex pattern to match at least 1 number and 1 character in a string I have a regex /^([a-zA-Z0-9]+)$/ this just allows only alphanumerics but also if I insert only number(s) or only character(s) then also it accepts it. I want it to work like the field should accept only alphanumeric values but the value must contain at least both 1 character and 1 number. A: Why not first apply the whole test, and then add individual tests for characters and numbers? Anyway, if you want to do it all in one regexp, use positive lookahead: /^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/ A: This RE will do: /^(?:[0-9]+[a-z]|[a-z]+[0-9])[a-z0-9]*$/i Explanation of RE: Match either of the following: At least one number, then one letter or At least one letter, then one number plus Any remaining numbers and letters (?:...) creates an unreferenced group /i is the ignore-case flag, so that a-z == a-zA-Z. A: I can see that other responders have given you a complete solution. Problem with regexes is that they can be difficult to maintain/understand. An easier solution would be to retain your existing regex, then create two new regexes to test for your "at least one alphabetic" and "at least one numeric". So, test for this :- /^([a-zA-Z0-9]+)$/ Then this :- /\d/ Then this :- /[A-Z]/i If your string passes all three regexes, you have the answer you need. A: The accepted answers is not worked as it is not allow to enter special characters. Its worked perfect for me. ^(?=.*[0-9])(?=.*[a-zA-Z])(?=\S+$).{6,20}$ one digit must one character must (lower or upper) every other things optional Thank you. A: While the accepted answer is correct, I find this regex a lot easier to read: REGEX = "([A-Za-z]+[0-9]|[0-9]+[A-Za-z])[A-Za-z0-9]*" A: This solution accepts at least 1 number and at least 1 character: [^\w\d]*(([0-9]+.*[A-Za-z]+.*)|[A-Za-z]+.*([0-9]+.*)) A: And an idea with a negative check. /^(?!\d*$|[a-z]*$)[a-z\d]+$/i ^(?! at start look ahead if string does not \d*$ contain only digits | or [a-z]*$ contain only letters [a-z\d]+$ matches one or more letters or digits until $ end. Have a look at this regex101 demo (the i flag turns on caseless matching: a-z matches a-zA-Z) A: Maybe a bit late, but this is my RE: /^(\w*(\d+[a-zA-Z]|[a-zA-Z]+\d)\w*)+$/ Explanation: \w* -> 0 or more alphanumeric digits, at the beginning \d+[a-zA-Z]|[a-zA-Z]+\d -> a digit + a letter OR a letter + a digit \w* -> 0 or more alphanumeric digits, again I hope it was understandable A: What about simply: /[0-9][a-zA-Z]|[a-zA-Z][0-9]/ Worked like a charm for me...
Regex pattern to match at least 1 number and 1 character in a string
I have a regex /^([a-zA-Z0-9]+)$/ this just allows only alphanumerics but also if I insert only number(s) or only character(s) then also it accepts it. I want it to work like the field should accept only alphanumeric values but the value must contain at least both 1 character and 1 number.
[ "Why not first apply the whole test, and then add individual tests for characters and numbers? Anyway, if you want to do it all in one regexp, use positive lookahead:\n/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/\n\n", "This RE will do:\n/^(?:[0-9]+[a-z]|[a-z]+[0-9])[a-z0-9]*$/i\n\nExplanation of RE:\n\nMatch either of the following:\n\nAt least one number, then one letter or\nAt least one letter, then one number plus\n\nAny remaining numbers and letters\n(?:...) creates an unreferenced group\n/i is the ignore-case flag, so that a-z == a-zA-Z.\n\n", "I can see that other responders have given you a complete solution. Problem with regexes is that they can be difficult to maintain/understand.\nAn easier solution would be to retain your existing regex, then create two new regexes to test for your \"at least one alphabetic\" and \"at least one numeric\".\nSo, test for this :-\n/^([a-zA-Z0-9]+)$/\n\nThen this :-\n/\\d/\n\nThen this :-\n/[A-Z]/i\n\nIf your string passes all three regexes, you have the answer you need.\n", "The accepted answers is not worked as it is not allow to enter special characters.\nIts worked perfect for me.\n^(?=.*[0-9])(?=.*[a-zA-Z])(?=\\S+$).{6,20}$\n\none digit must\none character must (lower or upper)\nevery other things optional\n\nThank you.\n", "While the accepted answer is correct, I find this regex a lot easier to read:\nREGEX = \"([A-Za-z]+[0-9]|[0-9]+[A-Za-z])[A-Za-z0-9]*\"\n\n", "This solution accepts at least 1 number and at least 1 character:\n[^\\w\\d]*(([0-9]+.*[A-Za-z]+.*)|[A-Za-z]+.*([0-9]+.*))\n\n", "And an idea with a negative check.\n/^(?!\\d*$|[a-z]*$)[a-z\\d]+$/i\n\n\n^(?! at start look ahead if string does not\n\\d*$ contain only digits | or\n[a-z]*$ contain only letters\n[a-z\\d]+$ matches one or more letters or digits until $ end.\n\nHave a look at this regex101 demo\n(the i flag turns on caseless matching: a-z matches a-zA-Z)\n", "Maybe a bit late, but this is my RE:\n/^(\\w*(\\d+[a-zA-Z]|[a-zA-Z]+\\d)\\w*)+$/\nExplanation:\n\\w* -> 0 or more alphanumeric digits, at the beginning\n\\d+[a-zA-Z]|[a-zA-Z]+\\d -> a digit + a letter OR a letter + a digit\n\\w* -> 0 or more alphanumeric digits, again\nI hope it was understandable\n", "What about simply:\n/[0-9][a-zA-Z]|[a-zA-Z][0-9]/\n\nWorked like a charm for me...\n" ]
[ 134, 23, 19, 11, 10, 7, 4, 3, 0 ]
[ "If you need the digit to be at the end of any word, this worked for me: \n/\\b([a-zA-Z]+[0-9]+)\\b/g\n\n\n\\b word boundary \n[a-zA-Z] any letter \n[0-9] any number\n\"+\" unlimited search (show all results)\n\n" ]
[ -1 ]
[ "javascript", "regex", "validation" ]
stackoverflow_0007684815_javascript_regex_validation.txt
Q: How can I set a default handler for urls that don't match any endpoints? I'm dealing with a ASP.NET Core Web API program. As we all know, when the url doesn't match any endpoints, the server will automatically return 404 code. Now that I want the service to record these requests into a log, so I want to set a default handler for them. Is it possible? How? A: Yes, it is possible. You can create a custom middleware to log all requests that don't match any endpoint. The middleware should catch all requests, and log them before they are passed on to the 404 handler. You can create the middleware by implementing the IMiddleware interface and adding it to the request pipeline in the Configure method of the Startup class. A: To set a default handler for URLs that don't match any endpoints, you can use the UseStatusCodePagesWithReExecute middleware in your ASP.NET Core Web API project. Here is an example of how you can use this middleware: public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseStatusCodePagesWithReExecute("/error/{0}"); // Other middleware and configuration } In this example, the UseStatusCodePagesWithReExecute middleware is used to handle any requests that result in a HTTP status code of 404 (not found). This middleware will re-execute the request and pass the status code to the specified URL (/error/{0} in this example), where you can handle it and log the request as needed. You can also use this middleware to handle other HTTP status codes by specifying them in the call to UseStatusCodePagesWithReExecute. For example, the following code will handle both 404 and 500 HTTP status codes: app.UseStatusCodePagesWithReExecute("/error/{0}", "404,500");
How can I set a default handler for urls that don't match any endpoints?
I'm dealing with a ASP.NET Core Web API program. As we all know, when the url doesn't match any endpoints, the server will automatically return 404 code. Now that I want the service to record these requests into a log, so I want to set a default handler for them. Is it possible? How?
[ "Yes, it is possible. You can create a custom middleware to log all requests that don't match any endpoint. The middleware should catch all requests, and log them before they are passed on to the 404 handler. You can create the middleware by implementing the IMiddleware interface and adding it to the request pipeline in the Configure method of the Startup class.\n", "To set a default handler for URLs that don't match any endpoints, you can use the UseStatusCodePagesWithReExecute middleware in your ASP.NET Core Web API project.\nHere is an example of how you can use this middleware:\npublic void Configure(IApplicationBuilder app, IWebHostEnvironment env)\n{\n app.UseStatusCodePagesWithReExecute(\"/error/{0}\");\n\n // Other middleware and configuration\n}\n\nIn this example, the UseStatusCodePagesWithReExecute middleware is used to handle any requests that result in a HTTP status code of 404 (not found). This middleware will re-execute the request and pass the status code to the specified URL (/error/{0} in this example), where you can handle it and log the request as needed.\nYou can also use this middleware to handle other HTTP status codes by specifying them in the call to UseStatusCodePagesWithReExecute. For example, the following code will handle both 404 and 500 HTTP status codes:\napp.UseStatusCodePagesWithReExecute(\"/error/{0}\", \"404,500\");\n\n" ]
[ 1, 1 ]
[]
[]
[ "asp.net", "asp.net_web_api", "c#", "http" ]
stackoverflow_0074663124_asp.net_asp.net_web_api_c#_http.txt
Q: How to loop if invalid input in prompt For the final input, your program prompts the user for their year of study. Once again, this is not a required field, that is, a default value of 1 (as in 1st year of study) should be submitted if the user chooses to leave this field blank. Additionally, you must validate the data the user provides (if provided) to ensure that it is not less than 1, and not greater than 3 (valid range is 1-3 years of study). If your solution detects invalid input, your program must loop to allow the user to re-enter year of study, this process continues indefinitely, until valid input is detected. I have tried a few different methods and this is my most recent attempt, but after 5 hours, I needed to ask for help. Code is below ( Yes, I'm a noob :( ) do { var yearofStudy = prompt("Please enter your Year of Study", "1") console.log(yearofStudy) } while ( yearofStudy > 1 && yearofStudy <4 ) A: The condition is probably the inverse of what you mean. You probably want to keep prompting while the value is outside of the range. do { var yearofStudy = parseInt(prompt("Please enter your Year of Study", "1")); console.log(yearofStudy) } while ( yearofStudy < 1 || yearofStudy > 3 ) A: As you didn't specified that you have to use do-while, then using while this way is totally okay and easier to understand. You have some logical bugs, because your if statement, then (suppose that your code does work), you are checking if user input is bigger then 1, where if you input 1 it's equal to it -> but you're requested to accept that as a yearofStudy, also you need to check if user input is greater then 3, if yes, then ask for input again, you don't want to check if input is greater then 4 as you don't want accept grades 5,6,7,8,9.... var statement = true; while (statement){ var yearofStudy = prompt("Please enter your Year of Study", "1"); if(yearofStudy > 0 && yearofStudy < 4){ break; } }
How to loop if invalid input in prompt
For the final input, your program prompts the user for their year of study. Once again, this is not a required field, that is, a default value of 1 (as in 1st year of study) should be submitted if the user chooses to leave this field blank. Additionally, you must validate the data the user provides (if provided) to ensure that it is not less than 1, and not greater than 3 (valid range is 1-3 years of study). If your solution detects invalid input, your program must loop to allow the user to re-enter year of study, this process continues indefinitely, until valid input is detected. I have tried a few different methods and this is my most recent attempt, but after 5 hours, I needed to ask for help. Code is below ( Yes, I'm a noob :( ) do { var yearofStudy = prompt("Please enter your Year of Study", "1") console.log(yearofStudy) } while ( yearofStudy > 1 && yearofStudy <4 )
[ "The condition is probably the inverse of what you mean. You probably want to keep prompting while the value is outside of the range.\n\n\ndo {\n var yearofStudy = parseInt(prompt(\"Please enter your Year of Study\", \"1\"));\n console.log(yearofStudy)\n} while ( yearofStudy < 1 || yearofStudy > 3 )\n\n\n\n", "As you didn't specified that you have to use do-while, then using while this way is totally okay and easier to understand.\nYou have some logical bugs, because your if statement, then (suppose that your code does work), you are checking if user input is bigger then 1, where if you input 1 it's equal to it -> but you're requested to accept that as a yearofStudy, also you need to check if user input is greater then 3, if yes, then ask for input again, you don't want to check if input is greater then 4 as you don't want accept grades 5,6,7,8,9....\nvar statement = true;\n while (statement){\n var yearofStudy = prompt(\"Please enter your Year of Study\", \"1\");\n if(yearofStudy > 0 && yearofStudy < 4){\n break;\n }\n }\n\n" ]
[ 1, 0 ]
[]
[]
[ "javascript" ]
stackoverflow_0074663062_javascript.txt
Q: Modifying a temporal table in EF Core 6 We're using Code First to manage a database that uses temporal tables. After a few migrations I've run into an issue, basically we needed to make a column nullable because the original data dictionary was incorrect. When I try to run Update-Database it returns an error: Setting SYSTEM_VERSIONING to ON failed because column 'MyColumn' does not have the same nullability attribute in tables 'MYDB.dbo.TableName' and 'MYDB.dbo.TableNameHistory'. It seems as though the migrationBuilder is creating the new column definition, but that is not getting applied to the history table... In SQL you can just run an ALTER TABLE command and it updates the history table, but I can't find any documentation on modifying temporal tables in EF Core. Everything is just about creating them. Is there something specific we need to do to make this work, or is this a bug in EF Core 6? A: When using Entity Framework Core (EF Core) to manage a database that uses temporal tables, you need to make sure that the nullability attributes of the columns in the base table and the history table are the same. This is because EF Core uses the SYSTEM_VERSIONING feature in SQL Server to enable temporal tables, and SQL Server requires that the nullability attributes of the columns in the base table and the history table be the same in order for the SYSTEM_VERSIONING feature to be enabled. To fix the error you are seeing, you need to update the nullability attribute of the MyColumn column in the history table to match the nullability attribute of the MyColumn column in the base table. You can do this using a regular SQL ALTER TABLE statement in a migration, like this: migrationBuilder.Sql( "ALTER TABLE dbo.TableNameHistory ALTER COLUMN MyColumn int NULL" ); This will update the nullability attribute of the MyColumn column in the history table, so that it matches the nullability attribute of the MyColumn column in the base table. Then, when you run the Update-Database command, it should not return an error and the SYSTEM_VERSIONING feature will be enabled successfully. A: To solve this issue, you will need to make sure that the desired column has the same nullability attribute in both tables. You can do this by running a SQL query like the one below: ALTER TABLE [MYDB].[dbo].[TableName] ALTER COLUMN [MyColumn] [data type] NULL; ALTER TABLE [MYDB].[dbo].[TableNameHistory] ALTER COLUMN [MyColumn] [data type] NULL; A: It looks like you're running into an issue with Entity Framework Core 6 and temporal tables. In Entity Framework Core 6, the migrationBuilder does not support modifying temporal tables. This means that you will not be able to use the migrationBuilder to make the changes you need to your temporal table. One option you have is to manually modify the table using a raw SQL query. You can use the migrationBuilder.Sql method to execute a raw SQL query that will modify the temporal table. Here's an example of how you might do this: migrationBuilder.Sql("ALTER TABLE MYDB.dbo.TableName ALTER COLUMN MyColumn INT NULL"); Alternatively, you could try upgrading to a newer version of Entity Framework Core that does support modifying temporal tables. In Entity Framework Core 6.4 and later, the migrationBuilder has support for modifying temporal tables using the HasPeriod and HasHistory methods. I hope this helps! Let me know if you have any other questions A: It sounds like you're encountering a known issue with Entity Framework Core when modifying the structure of temporal tables. As you mentioned, running an ALTER TABLE statement in SQL would typically update the corresponding history table, but this isn't currently possible with EF Core. One workaround for this issue is to drop the history table manually using a raw SQL query, then run the Update-Database command to recreate the table with the updated schema. Here is an example of how you could do this: using (var context = new MyDbContext()) { // Drop the history table using a raw SQL query context.Database.ExecuteSqlCommand("DROP TABLE MYDB.dbo.TableNameHistory"); // Run the Update-Database command to recreate the history table // with the updated schema var migrationBuilder = new MigrationBuilder(); migrationBuilder.AlterColumn<string>("MyColumn", nullable: true, table: "TableName"); migrationBuilder.UpdateTemporalTable("MYDB", "dbo", "TableName", "ValidFrom", "ValidTo", "SystemVersioning"); var migration = migrationBuilder.GetMigration(); migration.Apply(context); } Note that this approach will cause any existing data in the history table to be lost, so you should only use it if you don't need to preserve that data.
Modifying a temporal table in EF Core 6
We're using Code First to manage a database that uses temporal tables. After a few migrations I've run into an issue, basically we needed to make a column nullable because the original data dictionary was incorrect. When I try to run Update-Database it returns an error: Setting SYSTEM_VERSIONING to ON failed because column 'MyColumn' does not have the same nullability attribute in tables 'MYDB.dbo.TableName' and 'MYDB.dbo.TableNameHistory'. It seems as though the migrationBuilder is creating the new column definition, but that is not getting applied to the history table... In SQL you can just run an ALTER TABLE command and it updates the history table, but I can't find any documentation on modifying temporal tables in EF Core. Everything is just about creating them. Is there something specific we need to do to make this work, or is this a bug in EF Core 6?
[ "When using Entity Framework Core (EF Core) to manage a database that uses temporal tables, you need to make sure that the nullability attributes of the columns in the base table and the history table are the same. This is because EF Core uses the SYSTEM_VERSIONING feature in SQL Server to enable temporal tables, and SQL Server requires that the nullability attributes of the columns in the base table and the history table be the same in order for the SYSTEM_VERSIONING feature to be enabled.\nTo fix the error you are seeing, you need to update the nullability attribute of the MyColumn column in the history table to match the nullability attribute of the MyColumn column in the base table. You can do this using a regular SQL ALTER TABLE statement in a migration, like this:\nmigrationBuilder.Sql(\n \"ALTER TABLE dbo.TableNameHistory ALTER COLUMN MyColumn int NULL\"\n);\n\nThis will update the nullability attribute of the MyColumn column in the history table, so that it matches the nullability attribute of the MyColumn column in the base table. Then, when you run the Update-Database command, it should not return an error and the SYSTEM_VERSIONING feature will be enabled successfully.\n", "To solve this issue, you will need to make sure that the desired column has the same nullability attribute in both tables. You can do this by running a SQL query like the one below:\nALTER TABLE [MYDB].[dbo].[TableName] ALTER COLUMN [MyColumn] [data type] NULL;\nALTER TABLE [MYDB].[dbo].[TableNameHistory] ALTER COLUMN [MyColumn] [data type] NULL;\n\n", "It looks like you're running into an issue with Entity Framework Core 6 and temporal tables. In Entity Framework Core 6, the migrationBuilder does not support modifying temporal tables. This means that you will not be able to use the migrationBuilder to make the changes you need to your temporal table.\nOne option you have is to manually modify the table using a raw SQL query. You can use the migrationBuilder.Sql method to execute a raw SQL query that will modify the temporal table. Here's an example of how you might do this:\nmigrationBuilder.Sql(\"ALTER TABLE MYDB.dbo.TableName ALTER COLUMN MyColumn INT NULL\");\n\nAlternatively, you could try upgrading to a newer version of Entity Framework Core that does support modifying temporal tables. In Entity Framework Core 6.4 and later, the migrationBuilder has support for modifying temporal tables using the HasPeriod and HasHistory methods.\nI hope this helps! Let me know if you have any other questions\n", "It sounds like you're encountering a known issue with Entity Framework Core when modifying the structure of temporal tables. As you mentioned, running an ALTER TABLE statement in SQL would typically update the corresponding history table, but this isn't currently possible with EF Core.\nOne workaround for this issue is to drop the history table manually using a raw SQL query, then run the Update-Database command to recreate the table with the updated schema.\nHere is an example of how you could do this:\n using (var context = new MyDbContext())\n{\n // Drop the history table using a raw SQL query\n context.Database.ExecuteSqlCommand(\"DROP TABLE MYDB.dbo.TableNameHistory\");\n\n // Run the Update-Database command to recreate the history table\n // with the updated schema\n var migrationBuilder = new MigrationBuilder();\n migrationBuilder.AlterColumn<string>(\"MyColumn\", nullable: true, table: \"TableName\");\n migrationBuilder.UpdateTemporalTable(\"MYDB\", \"dbo\", \"TableName\", \"ValidFrom\", \"ValidTo\", \"SystemVersioning\");\n\n var migration = migrationBuilder.GetMigration();\n migration.Apply(context);\n}\n\nNote that this approach will cause any existing data in the history table to be lost, so you should only use it if you don't need to preserve that data.\n" ]
[ 0, 0, 0, 0 ]
[]
[]
[ "ef_core_6.0", "temporal_tables" ]
stackoverflow_0074551985_ef_core_6.0_temporal_tables.txt
Q: Why doesn't it work I'm trying to make a simple calculator def add(a, b): return a + b print("choose 1 to add and 2 to subtract") select = input("enter choice 1/2") a = float(input("enter 1st nunber: ")) b = float(input("enter 2nd number: ")) if select == 1: print(a, "+", b, "=", add(a, b)) I don't know why it doesn't wanna add A: You need to convert the select variable to integer. By default, the input is taken as string value. You can also use f-string (see more at Formatted String Literals documentation) for printing values from variables in the print statement which gives you much more flexibility to format the string: def add(a, b): return a + b print("choose 1 to add and 2 to subtract") select = int(input("enter choice 1/2: ")) a = float(input("enter 1st nunber: ")) b = float(input("enter 2nd number: ")) if select == 1: print(f"{a} + {b} = {add(a, b)}") Output: choose 1 to add and 2 to subtract enter choice 1/2: 1 enter 1st nunber: 21 enter 2nd number: 3 21.0 + 3.0 = 24.0 A: You need to convert select into an int def add(a, b): return a + b print("choose 1 to add and 2 to subtract") select = int(input("enter choice 1/2")) a = float(input("enter 1st nunber: ")) b = float(input("enter 2nd number: ")) if select == 1: print(a, "+", b, "=", add(a, b)) A: input returns a string, but in the line if select == 1 you are comparing it to an int. There are several solutions to this, but the solution I would go with is to use only strings, i.e. if select == "1". 1 and 2 are arbitrary values, so it isn't really necessary for them to be converted to numbers. You could just as easily use a and b to accomplish the same goal. Another useful thing you can do is validate the user input. I would do that with something like this: while select not in ["1", "2"]: print(f"you entered {select}, which is not a valid option") select = input("enter choice 1/2") This will continue to ask the user to select one of the choices until they enter a valid one, and also has the added bonus of helping you catch errors in your code like the int vs str issue. A: As others mentioned, since input returns a str, it should be compared with an object of same type. Just changing 1 to str(1) on line 10 will solve the issue. def add(a, b): return a + b print("choose 1 to add and 2 to subtract") select = input("enter choice 1/2") a = float(input("enter 1st nunber: ")) b = float(input("enter 2nd number: ")) if select == str(1): print(a, "+", b, "=", add(a, b))
Why doesn't it work I'm trying to make a simple calculator
def add(a, b): return a + b print("choose 1 to add and 2 to subtract") select = input("enter choice 1/2") a = float(input("enter 1st nunber: ")) b = float(input("enter 2nd number: ")) if select == 1: print(a, "+", b, "=", add(a, b)) I don't know why it doesn't wanna add
[ "You need to convert the select variable to integer. By default, the input is taken as string value. You can also use f-string (see more at Formatted String Literals documentation) for printing values from variables in the print statement which gives you much more flexibility to format the string:\ndef add(a, b):\n return a + b\n\n\nprint(\"choose 1 to add and 2 to subtract\")\nselect = int(input(\"enter choice 1/2: \"))\na = float(input(\"enter 1st nunber: \"))\nb = float(input(\"enter 2nd number: \"))\nif select == 1:\n print(f\"{a} + {b} = {add(a, b)}\")\n\nOutput:\nchoose 1 to add and 2 to subtract\nenter choice 1/2: 1\nenter 1st nunber: 21\nenter 2nd number: 3\n21.0 + 3.0 = 24.0\n\n", "You need to convert select into an int\ndef add(a, b):\n return a + b\n\nprint(\"choose 1 to add and 2 to subtract\")\nselect = int(input(\"enter choice 1/2\"))\n\na = float(input(\"enter 1st nunber: \"))\nb = float(input(\"enter 2nd number: \"))\n\nif select == 1:\n print(a, \"+\", b, \"=\", add(a, b))\n\n", "input returns a string, but in the line if select == 1 you are comparing it to an int. There are several solutions to this, but the solution I would go with is to use only strings, i.e. if select == \"1\". 1 and 2 are arbitrary values, so it isn't really necessary for them to be converted to numbers. You could just as easily use a and b to accomplish the same goal.\nAnother useful thing you can do is validate the user input. I would do that with something like this:\nwhile select not in [\"1\", \"2\"]:\n print(f\"you entered {select}, which is not a valid option\")\n select = input(\"enter choice 1/2\")\n\nThis will continue to ask the user to select one of the choices until they enter a valid one, and also has the added bonus of helping you catch errors in your code like the int vs str issue.\n", "As others mentioned, since input returns a str, it should be compared with an object of same type. Just changing 1 to str(1) on line 10 will solve the issue.\ndef add(a, b):\n return a + b\n\nprint(\"choose 1 to add and 2 to subtract\")\nselect = input(\"enter choice 1/2\")\n\na = float(input(\"enter 1st nunber: \"))\nb = float(input(\"enter 2nd number: \"))\n\nif select == str(1):\n print(a, \"+\", b, \"=\", add(a, b))\n\n" ]
[ 0, 0, 0, 0 ]
[]
[]
[ "calculator", "python", "python_3.x" ]
stackoverflow_0074662980_calculator_python_python_3.x.txt
Q: By-pass 'Select a Certificate' prompt in Chrome using Selenium (Python) When going to a specific site and logging in, it then requires me (through a prompt which I can't access the web elements of) to validate it using a specific certificate to authenticate myself. The certificate itself already appears to be loaded but the issue is just submitting / clicking the "Ok" response. So, I've tried looking online and there does appear to be answers but they conflict with me. I'm running Chrome in headless mode which doesn't allow me to use the autoit or pyautogui libs. I have the certificate itself in my Keychain and also within my VSCode but not sure how I'd supply that to my driver to perhaps get rid of that prompt. Here's a portion of my code: def webdriverSetup(): chrome_options = Options() #chrome_options.add_argument('--headless') chrome_options.add_argument("--window-size=1920,1080") chrome_options.add_argument('--ignore-certificate-errors') chrome_options.add_argument('--allow-running-insecure-content') chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--no-sandbox") driver = webdriver.Chrome(options=chrome_options) return driver Here's the prompt I'm referring to: Note: Some of the other answers found are exclusive to Windows. Would appreciate a Mac or "mixed" solution for the time being, thanks. A: I would suggest trying Following : from selenium.webdriver.chrome.options import Options as ChromeOptions chrome_options = ChromeOptions() chrome_options.add_experimental_option( 'prefs', { 'required_client_certificate_for_user': <Path_to_certificate> } ) I got the prefs list from here https://source.chromium.org/chromium/chromium/src/+/main:chrome/common/pref_names.cc following is the list of prefs which can be tried :- "required_client_certificate_for_user" and "required_client_certificate_for_device" A: Selenium doesn't support certificate authentication natively, but you can use the Selenium WebDriver to download the certificate and then use the Selenium WebDriver to import the certificate into your browser.
By-pass 'Select a Certificate' prompt in Chrome using Selenium (Python)
When going to a specific site and logging in, it then requires me (through a prompt which I can't access the web elements of) to validate it using a specific certificate to authenticate myself. The certificate itself already appears to be loaded but the issue is just submitting / clicking the "Ok" response. So, I've tried looking online and there does appear to be answers but they conflict with me. I'm running Chrome in headless mode which doesn't allow me to use the autoit or pyautogui libs. I have the certificate itself in my Keychain and also within my VSCode but not sure how I'd supply that to my driver to perhaps get rid of that prompt. Here's a portion of my code: def webdriverSetup(): chrome_options = Options() #chrome_options.add_argument('--headless') chrome_options.add_argument("--window-size=1920,1080") chrome_options.add_argument('--ignore-certificate-errors') chrome_options.add_argument('--allow-running-insecure-content') chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--no-sandbox") driver = webdriver.Chrome(options=chrome_options) return driver Here's the prompt I'm referring to: Note: Some of the other answers found are exclusive to Windows. Would appreciate a Mac or "mixed" solution for the time being, thanks.
[ "I would suggest trying Following :\nfrom selenium.webdriver.chrome.options import Options as ChromeOptions\n\n chrome_options = ChromeOptions()\n chrome_options.add_experimental_option(\n 'prefs', {\n 'required_client_certificate_for_user': <Path_to_certificate>\n }\n )\n\nI got the prefs list from here https://source.chromium.org/chromium/chromium/src/+/main:chrome/common/pref_names.cc following is the list of prefs which can be tried :-\n\"required_client_certificate_for_user\" and \"required_client_certificate_for_device\"\n", "Selenium doesn't support certificate authentication natively, but you can use the Selenium WebDriver to download the certificate and then use the Selenium WebDriver to import the certificate into your browser.\n" ]
[ 0, 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver", "webdriver" ]
stackoverflow_0074587029_python_selenium_selenium_chromedriver_selenium_webdriver_webdriver.txt
Q: function generator setTimeout with array as delay I'm trying to create a function generator prints one element in the array targets at the specified time in milliseconds in the timeArray and after the value is printed out the list will go to the next element in the time array and targets array and after the next time interval in the timeArray we print out the next value in the target array and continute to follow the same pattern until we reach the end of the array I tried using the code shown below but it only prints out the first 2 elements in the timeArray but it doesn't print all of the other elements but I'm not sure if it's printing them after the first two time intervals in timeArray let j = 0; var timeArray = [6, 68, 51, 41, 94, 65, 47, 85, 76, 136];//Array that shows how long after each number printed to the console the next value should be printed var targets = [9, 10, 8, 7, 9, 7, 7, 9, 9, 7];//Array of numbers that should be printed let generator = generateSequence(); async function* generateSequence(casiInfluence){ yield new Promise((resolve, reject) => { setTimeout(() => resolve(console.log(targetArray[j]), timeArray[j]); console.log(timeArray[j]); }); } (async function main(){ for await(var result of generateSequence()){ console.log(result); j++; result = generator.next(); } }()); A: For each step towards a generator for deferred values the OP could implement an own task ... like ... mapping both of the OP's arrays into a better processable data-structure ... here an array of tuples where each tuple is made of ... [<value>, <delay>]. mapping of each value-delay tuple into a deferred value action which is an async function that creates and returns a promise which will resolve the value after the milliseconds delay where the mapping function that creates the async function is called createDeferredValueAction. creating the async generator from the array of async functions where the generator function is called createDeferredValuesPool. // - a specific helper which creates an async function // for each to be deferred value. function createDeferredValueAction(value, delay) { return async function () { return await ( new Promise(resolve => setTimeout(resolve, delay, value)) ); }; } // - another helper which creates an async generator // from an array of async functions. async function* createDeferredValuesPool(asyncFunctions) { asyncFunctions = [...asyncFunctions]; let asyncFct; while (asyncFct = asyncFunctions.shift()) { yield (await asyncFct()); } } // - array that defines how long after each to be // processed value the next value will be processed. const valueDelays = [600, 680, 510, 410, 940, 650, 470, 850, 760, 1360]; // - array of to be processed target values. const targetValues = [9, 10, 8, 7, 9, 7, 7, 9, 9, 7] // - maps both above OP's arrays into a // better processable data-structure. const targetEntries = targetValues .map((value, idx) => [value, valueDelays[idx]]); console.log({ targetEntries }); // - helper task which creates a list of async functions. const deferredValueActions = targetEntries .map(([value, delay]) => createDeferredValueAction(value, delay) ); // create an async generator ... const deferredValuesPool = createDeferredValuesPool(deferredValueActions); (async () => { // ... and iterate over it. for await (const value of deferredValuesPool) { console.log({ value }); } })(); console.log('... running ...'); .as-console-wrapper { min-height: 100%!important; top: 0; } A: You created the generator with let generator = generateSequence(), but then you never iterated over it. (This is spread out and uses more variable names, so it's easier to read): var timeArray = [6, 68, 51, 41, 94, 65, 47, 85, 76, 136];//Array that shows how long after each number printed to the console the next value should be printed var targets = [9, 10, 8, 7, 9, 7, 7, 9, 9, 7];//Array of numbers that should be printed var generator = generateSequence(); ( async () => { for await ( const printNumber of generator ) { /* Accessing the generator's properties logs to the console, so... Nothing to do in this for{} loop. */ } } )() async function* generateSequence() { for ( const i in timeArray ) { const delay = timeArray[ i ]; const numberToPrint = targets[ i ]; await waitForPrint( numberToPrint, delay ); yield; } } function waitForPrint( text, delay ) { return new Promise( (resolve,reject) => { setTimeout( () => { console.log( text ); resolve(); }, delay ) }) } This would be easier without generators: var timeArray = [6, 68, 51, 41, 94, 65, 47, 85, 76, 136];//Array that shows how long after each number printed to the console the next value should be printed var targets = [9, 10, 8, 7, 9, 7, 7, 9, 9, 7];//Array of numbers that should be printed for( let scheduledTimeMS=0, i=0; i<timeArray.length; i++ ) { const numberToPrint = targets[ i ]; const delay = timeArray[ i ]; scheduledTimeMS += delay; setTimeout( () => console.log( numberToPrint ), scheduledTimeMS ); }
function generator setTimeout with array as delay
I'm trying to create a function generator prints one element in the array targets at the specified time in milliseconds in the timeArray and after the value is printed out the list will go to the next element in the time array and targets array and after the next time interval in the timeArray we print out the next value in the target array and continute to follow the same pattern until we reach the end of the array I tried using the code shown below but it only prints out the first 2 elements in the timeArray but it doesn't print all of the other elements but I'm not sure if it's printing them after the first two time intervals in timeArray let j = 0; var timeArray = [6, 68, 51, 41, 94, 65, 47, 85, 76, 136];//Array that shows how long after each number printed to the console the next value should be printed var targets = [9, 10, 8, 7, 9, 7, 7, 9, 9, 7];//Array of numbers that should be printed let generator = generateSequence(); async function* generateSequence(casiInfluence){ yield new Promise((resolve, reject) => { setTimeout(() => resolve(console.log(targetArray[j]), timeArray[j]); console.log(timeArray[j]); }); } (async function main(){ for await(var result of generateSequence()){ console.log(result); j++; result = generator.next(); } }());
[ "For each step towards a generator for deferred values the OP could implement an own task ... like ...\n\nmapping both of the OP's arrays into a better processable data-structure ... here an array of tuples where each tuple is made of ... [<value>, <delay>].\n\nmapping of each value-delay tuple into a deferred value action which is an async function that creates and returns a promise which will resolve the value after the milliseconds delay where the mapping function that creates the async function is called createDeferredValueAction.\n\ncreating the async generator from the array of async functions where the generator function is called createDeferredValuesPool.\n\n\n\n\n// - a specific helper which creates an async function\n// for each to be deferred value.\nfunction createDeferredValueAction(value, delay) {\n return async function () {\n return await (\n new Promise(resolve => setTimeout(resolve, delay, value))\n );\n };\n}\n\n// - another helper which creates an async generator\n// from an array of async functions.\nasync function* createDeferredValuesPool(asyncFunctions) {\n asyncFunctions = [...asyncFunctions];\n\n let asyncFct;\n while (asyncFct = asyncFunctions.shift()) {\n\n yield (await asyncFct());\n }\n}\n\n\n// - array that defines how long after each to be\n// processed value the next value will be processed.\nconst valueDelays = [600, 680, 510, 410, 940, 650, 470, 850, 760, 1360];\n\n// - array of to be processed target values.\nconst targetValues = [9, 10, 8, 7, 9, 7, 7, 9, 9, 7]\n\n\n// - maps both above OP's arrays into a\n// better processable data-structure.\nconst targetEntries = targetValues\n .map((value, idx) => [value, valueDelays[idx]]);\n\nconsole.log({ targetEntries });\n\n// - helper task which creates a list of async functions.\nconst deferredValueActions = targetEntries\n .map(([value, delay]) =>\n createDeferredValueAction(value, delay)\n );\n\n// create an async generator ...\nconst deferredValuesPool =\n createDeferredValuesPool(deferredValueActions);\n\n(async () => {\n // ... and iterate over it.\n for await (const value of deferredValuesPool) {\n console.log({ value });\n }\n})();\n\nconsole.log('... running ...');\n.as-console-wrapper { min-height: 100%!important; top: 0; }\n\n\n\n", "You created the generator with let generator = generateSequence(), but then you never iterated over it.\n(This is spread out and uses more variable names, so it's easier to read):\nvar timeArray = [6, 68, 51, 41, 94, 65, 47, 85, 76, 136];//Array that shows how long after each number printed to the console the next value should be printed\nvar targets = [9, 10, 8, 7, 9, 7, 7, 9, 9, 7];//Array of numbers that should be printed\n\nvar generator = generateSequence();\n\n( async () => {\n\n for await ( const printNumber of generator ) {\n /* Accessing the generator's properties logs to the console, so... \n Nothing to do in this for{} loop. */\n }\n\n} )()\n\nasync function* generateSequence() {\n for ( const i in timeArray ) {\n const delay = timeArray[ i ];\n const numberToPrint = targets[ i ];\n await waitForPrint( numberToPrint, delay );\n yield;\n }\n}\n\nfunction waitForPrint( text, delay ) {\n return new Promise( (resolve,reject) => {\n setTimeout(\n () => {\n console.log( text );\n resolve();\n },\n delay\n )\n })\n}\n\nThis would be easier without generators:\n\nvar timeArray = [6, 68, 51, 41, 94, 65, 47, 85, 76, 136];//Array that shows how long after each number printed to the console the next value should be printed\nvar targets = [9, 10, 8, 7, 9, 7, 7, 9, 9, 7];//Array of numbers that should be printed\n\n\nfor( let scheduledTimeMS=0, i=0; i<timeArray.length; i++ ) {\n\n const numberToPrint = targets[ i ];\n const delay = timeArray[ i ];\n\n scheduledTimeMS += delay;\n\n setTimeout( () => console.log( numberToPrint ), scheduledTimeMS );\n\n}\n\n" ]
[ 0, 0 ]
[]
[]
[ "generator", "javascript" ]
stackoverflow_0074662724_generator_javascript.txt
Q: Finding min across multiple dataframe in R I have 3 dataframes with the same dimensions. I want to create a dataframe with min value from each element in 3 dataframes. Is there a more efficient way than running loop on cloumn and then row going through each element one by one? Dataframe X | Column A | Column B | | -------- | -------- | | Cell X1 | Cell X2 | | Cell X3 | Cell X4 | Dataframe Y | Column A | Column B | | -------- | -------- | | Cell Y1 | Cell Y2 | | Cell Y3 | Cell Y4 | Dataframe Z | Column A | Column B | | -------- | -------- | | Cell Z1 | Cell Z2 | | Cell Z3 | Cell Z4 | Dataframe Target Output | Column A | Column B | | -------- | -------- | | Min (Cell X1,Y1,Z1) | Min (Cell X2,Y2,Z2) | | Min (Cell X3,Y3,Z3) | Min (Cell X4,Y4,Z4) | Thank you! I tried simple loop for each column and then each row for (c in 1:3){ for (r in 1:2){ ........ } } A: You can use the pmin() function from the base R package to get the minimum value of each row across three dataframes. For example: df_target = data.frame(c1 = pmin(X$ColumnA, Y$ColumnA, Z$ColumnA), c2 = pmin(X$ColumnB, Y$ColumnB, Z$ColumnB)) Or you can use the apply() function to apply the pmin() function to each row of the dataframes: df_target = data.frame(apply(cbind(X$ColumnA, Y$ColumnA, Z$ColumnA), 1, pmin), apply(cbind(X$ColumnB, Y$ColumnB, Z$ColumnB), 1, pmin)) A: You could loop over the columns and use pmin: as.data.frame(lapply(1:ncol(X), \(i) pmin(X[[i]], Y[[i]], Z[[i]]))) If you need to generalize to more data frames, I would put them in a list and use do.call with the pmin. (Answer is untested as no sample data is provided.) The more general solution would be to stack the data frames into a 3-d array and use apply: arr = abind(A, B, C, along = 3) result = apply(arr, 1:2, min) A: Another option is: Tidyverse: library(purrr) map_dfc(transpose(df_list), lift(pmin)) data.table: library(data.table) rbindlist(df_list, idcol = "group")[,lapply(.SD,min),rowid(group)] Base R aggregate(do.call(rbind,df_list), list(sequence(sapply(df_list, nrow))), min) EDIT: Base R approach: Reduce(function(x,y)replace(x, x>y , y[x>y]), list_df)
Finding min across multiple dataframe in R
I have 3 dataframes with the same dimensions. I want to create a dataframe with min value from each element in 3 dataframes. Is there a more efficient way than running loop on cloumn and then row going through each element one by one? Dataframe X | Column A | Column B | | -------- | -------- | | Cell X1 | Cell X2 | | Cell X3 | Cell X4 | Dataframe Y | Column A | Column B | | -------- | -------- | | Cell Y1 | Cell Y2 | | Cell Y3 | Cell Y4 | Dataframe Z | Column A | Column B | | -------- | -------- | | Cell Z1 | Cell Z2 | | Cell Z3 | Cell Z4 | Dataframe Target Output | Column A | Column B | | -------- | -------- | | Min (Cell X1,Y1,Z1) | Min (Cell X2,Y2,Z2) | | Min (Cell X3,Y3,Z3) | Min (Cell X4,Y4,Z4) | Thank you! I tried simple loop for each column and then each row for (c in 1:3){ for (r in 1:2){ ........ } }
[ "You can use the pmin() function from the base R package to get the minimum value of each row across three dataframes.\nFor example:\ndf_target = data.frame(c1 = pmin(X$ColumnA, Y$ColumnA, Z$ColumnA), \n c2 = pmin(X$ColumnB, Y$ColumnB, Z$ColumnB))\n\nOr you can use the apply() function to apply the pmin() function to each row of the dataframes:\ndf_target = data.frame(apply(cbind(X$ColumnA, Y$ColumnA, Z$ColumnA), 1, pmin), \n apply(cbind(X$ColumnB, Y$ColumnB, Z$ColumnB), 1, pmin))\n\n", "You could loop over the columns and use pmin:\nas.data.frame(lapply(1:ncol(X), \\(i) pmin(X[[i]], Y[[i]], Z[[i]])))\n\nIf you need to generalize to more data frames, I would put them in a list and use do.call with the pmin.\n(Answer is untested as no sample data is provided.)\nThe more general solution would be to stack the data frames into a 3-d array and use apply:\narr = abind(A, B, C, along = 3)\nresult = apply(arr, 1:2, min)\n\n", "Another option is:\nTidyverse:\nlibrary(purrr)\nmap_dfc(transpose(df_list), lift(pmin))\n\n\ndata.table:\nlibrary(data.table)\nrbindlist(df_list, idcol = \"group\")[,lapply(.SD,min),rowid(group)]\n\n\nBase R\naggregate(do.call(rbind,df_list), list(sequence(sapply(df_list, nrow))), min)\n\nEDIT:\nBase R approach:\nReduce(function(x,y)replace(x, x>y , y[x>y]), list_df)\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "r" ]
stackoverflow_0074662873_r.txt
Q: Python- Read values from CSV file and add columns values to REST API iteration calls I'm new to python, I'm reading csv file having 2 columns as ID and Filepath (headers not present). Trying to enter the ID into the URL and filepath into the below rest api call. Can't get the values of the row. If the value at row[0] is TDEVOPS-1 it's returning numeric value. import csv filename1 = 'E:\\Upload-PM\\attachment.csv' with open(filename1, 'rb') as csvfile: datareader = csv.reader(csvfile) for row in csvfile.readlines(): urlvalue = "https://<url>.atlassian.com/rest/api/3/issue/" + str({row[0]}) + "/attachments" url = urlvalue print(url) headers = {"X-Atlassian-Token": "nocheck"} files = {'file': open(row[1], 'rb')} r = requests.post(url, auth=('<email>','<token>'), files=files, headers=headers) print(r.status_code) print(r.text) Input: TDEVOPST-5,E:\Upload-PM\att.csv TDEVOPST-2,E:\Upload-PM\att2.csv TDEVOPST-3,E:\Upload-PM\att3.csv Error: A: It is not clear to me what is the exact error you are getting. But did you try using format? urlvalue = "https://<url>.atlassian.com/rest/api/3/issue/{}/attachments".format(row[0]) UPDATE - corresponding to the comments, the issue seems to be with how you read the csv file. Id recommend to use the “r” flag for better string parsing. See - Difference between parsing a text file in r and rb mode for more details In addition I'd suggest to use python os.path to make sure the path is valid A: If your file has not header then try to read it as symply .txt file: attachment = ["TDEVOPST-5,E:\\Upload-PM\\att.csv","TDEVOPST-2,E:\\Upload-PM\\att2.csv","TDEVOPST-3,E:\\Upload-PM\\att3.csv"] fn = "temp.txt" with open(fn, "w") as f: f.write("\n".join(attachment)) with open(fn,"r") as f: for row in f: print(row.replace("\n","")) # optional string for test els = row.split(",") print(els[0],"->",els[1]) # optional string for test Then you can use: els[0],els[1] as you need. May be like this: urlvalue = f"https://<url>.atlassian.com/rest/api/3/issue/{els[0]}/attachments"
Python- Read values from CSV file and add columns values to REST API iteration calls
I'm new to python, I'm reading csv file having 2 columns as ID and Filepath (headers not present). Trying to enter the ID into the URL and filepath into the below rest api call. Can't get the values of the row. If the value at row[0] is TDEVOPS-1 it's returning numeric value. import csv filename1 = 'E:\\Upload-PM\\attachment.csv' with open(filename1, 'rb') as csvfile: datareader = csv.reader(csvfile) for row in csvfile.readlines(): urlvalue = "https://<url>.atlassian.com/rest/api/3/issue/" + str({row[0]}) + "/attachments" url = urlvalue print(url) headers = {"X-Atlassian-Token": "nocheck"} files = {'file': open(row[1], 'rb')} r = requests.post(url, auth=('<email>','<token>'), files=files, headers=headers) print(r.status_code) print(r.text) Input: TDEVOPST-5,E:\Upload-PM\att.csv TDEVOPST-2,E:\Upload-PM\att2.csv TDEVOPST-3,E:\Upload-PM\att3.csv Error:
[ "It is not clear to me what is the exact error you are getting. But did you try using format?\nurlvalue = \"https://<url>.atlassian.com/rest/api/3/issue/{}/attachments\".format(row[0])\n\nUPDATE - corresponding to the comments, the issue seems to be with how you read the csv file. Id recommend to use the “r” flag for better string parsing. See - Difference between parsing a text file in r and rb mode for more details\nIn addition I'd suggest to use python os.path to make sure the path is valid\n", "If your file has not header then try to read it as symply .txt file:\nattachment = [\"TDEVOPST-5,E:\\\\Upload-PM\\\\att.csv\",\"TDEVOPST-2,E:\\\\Upload-PM\\\\att2.csv\",\"TDEVOPST-3,E:\\\\Upload-PM\\\\att3.csv\"]\n\nfn = \"temp.txt\"\nwith open(fn, \"w\") as f:\n f.write(\"\\n\".join(attachment))\n\nwith open(fn,\"r\") as f:\n for row in f:\n print(row.replace(\"\\n\",\"\")) # optional string for test\n els = row.split(\",\")\n print(els[0],\"->\",els[1]) # optional string for test\n\nThen you can use: els[0],els[1] as you need. May be like this:\nurlvalue = f\"https://<url>.atlassian.com/rest/api/3/issue/{els[0]}/attachments\"\n\n" ]
[ 0, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074658350_csv_python.txt
Q: How to use variables with a circleci orb? I am using the codedeploy orb to deploy my application to AWS and instead of hardcoding the values in there like application-name etc, i am trying to pass variables instead but the orb doesn’t seem to be respecting the variables. This is my code deploy: executor: aws-cli/default steps: - aws-cli/setup: profile-name: my-role - checkout - run : name: "Set stage name" command: | stage=$(echo "${CIRCLE_USERNAME}" | tr '[:upper:]' '[:lower:]') - aws-code-deploy/deploy-bundle: application-name: "my-app-$stage-application" deployment-group: "my-app-$stage-deployment-group" bundle-bucket: "my-app-$stage-bucket" bundle-key: "appspec" bundle-type: "yaml" deployment-config: "CodeDeployDefault.ECSAllAtOnce" But i am running into the following error :- An error occurred (ApplicationDoesNotExistException) when calling the CreateDeployment operation: No application found for name: my-app- -application. So clearly in my-app- -application the variables is not being set. any ideas on how to resolve it? Thank you. A: The way you're currently setting your stage variable is scoped to the "Set stage name" step only. Try the following instead: - run : name: "Set stage name" command: | echo "export stage=$(echo "${CIRCLE_USERNAME}"| tr '[:upper:]' '[:lower:]')" >> "$BASH_ENV" Related documentation: https://circleci.com/docs/set-environment-variable/#set-an-environment-variable-in-a-shell-command https://circleci.com/docs/env-vars/#parameters-and-bash-environment
How to use variables with a circleci orb?
I am using the codedeploy orb to deploy my application to AWS and instead of hardcoding the values in there like application-name etc, i am trying to pass variables instead but the orb doesn’t seem to be respecting the variables. This is my code deploy: executor: aws-cli/default steps: - aws-cli/setup: profile-name: my-role - checkout - run : name: "Set stage name" command: | stage=$(echo "${CIRCLE_USERNAME}" | tr '[:upper:]' '[:lower:]') - aws-code-deploy/deploy-bundle: application-name: "my-app-$stage-application" deployment-group: "my-app-$stage-deployment-group" bundle-bucket: "my-app-$stage-bucket" bundle-key: "appspec" bundle-type: "yaml" deployment-config: "CodeDeployDefault.ECSAllAtOnce" But i am running into the following error :- An error occurred (ApplicationDoesNotExistException) when calling the CreateDeployment operation: No application found for name: my-app- -application. So clearly in my-app- -application the variables is not being set. any ideas on how to resolve it? Thank you.
[ "The way you're currently setting your stage variable is scoped to the \"Set stage name\" step only.\nTry the following instead:\n - run :\n name: \"Set stage name\"\n command: |\n echo \"export stage=$(echo \"${CIRCLE_USERNAME}\"| tr '[:upper:]' '[:lower:]')\" >> \"$BASH_ENV\"\n\nRelated documentation:\n\nhttps://circleci.com/docs/set-environment-variable/#set-an-environment-variable-in-a-shell-command\nhttps://circleci.com/docs/env-vars/#parameters-and-bash-environment\n\n" ]
[ 0 ]
[]
[]
[ "circleci", "circleci_orb", "circleci_workflows" ]
stackoverflow_0074637144_circleci_circleci_orb_circleci_workflows.txt
Q: Issues in running virtual threads program on intellij with java19 I am trying to run below simple program with virtual threads on my intellij with java19 version selected. Code public class VTSimple { public static void main(String[] args) { Runnable runnable = () -> System.out.println("Inside Runnable"); Thread.startVirtualThread(runnable); } } pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.java19</groupId> <artifactId>java19-explore</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>19</maven.compiler.source> <maven.compiler.target>19</maven.compiler.target> </properties> </project> Project Settings SDK - 19 Language Level - X Experimental Features as last version shown was 17(preview) in Language Level dropdown Also Tried SDK Default Option as well. Error When I ran the program it gave me below error java: invalid source release 18 with --enable-preview (preview language features are only supported for release 19) Few Trials I tried to add --enable-preview in VM Options of this small program and as well as compiler settings in preferences but it didn't work. Edit 1 Setup Details : Mac OS Air M1 : 12.1 Monterey Intellij Version : IntelliJ IDEA 2021.3.3 (Community Edition) Build #IC-213.7172.25, built on March 15, 2022 Java Version : openjdk 19.0.1 2022-10-18 OpenJDK Runtime Environment (build 19.0.1+10-21) OpenJDK 64-Bit Server VM (build 19.0.1+10-21, mixed mode, sharing) Edit 2 Updated Intellij to version IntelliJ IDEA 2022.2.3 (Community Edition) and java version 19 was showing in language level. But still there is an error java: ofVirtual() is a preview API and is disabled by default. (use --enable-preview to enable preview APIs) Note : I have already passed --enable-preview in VM Options of program and Compiler settings in preferences. A: You need to use IntelliJ IDEA 2022.2 or newer for Java 19 support. A: --enable-preview should be in VM options, NOT program arguments You still need to have those settings in Java Compiler And the project settings: Also, you can run from the command line java --enable-preview --source 19 Main.java Sample code: with the following results:
Issues in running virtual threads program on intellij with java19
I am trying to run below simple program with virtual threads on my intellij with java19 version selected. Code public class VTSimple { public static void main(String[] args) { Runnable runnable = () -> System.out.println("Inside Runnable"); Thread.startVirtualThread(runnable); } } pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.java19</groupId> <artifactId>java19-explore</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>19</maven.compiler.source> <maven.compiler.target>19</maven.compiler.target> </properties> </project> Project Settings SDK - 19 Language Level - X Experimental Features as last version shown was 17(preview) in Language Level dropdown Also Tried SDK Default Option as well. Error When I ran the program it gave me below error java: invalid source release 18 with --enable-preview (preview language features are only supported for release 19) Few Trials I tried to add --enable-preview in VM Options of this small program and as well as compiler settings in preferences but it didn't work. Edit 1 Setup Details : Mac OS Air M1 : 12.1 Monterey Intellij Version : IntelliJ IDEA 2021.3.3 (Community Edition) Build #IC-213.7172.25, built on March 15, 2022 Java Version : openjdk 19.0.1 2022-10-18 OpenJDK Runtime Environment (build 19.0.1+10-21) OpenJDK 64-Bit Server VM (build 19.0.1+10-21, mixed mode, sharing) Edit 2 Updated Intellij to version IntelliJ IDEA 2022.2.3 (Community Edition) and java version 19 was showing in language level. But still there is an error java: ofVirtual() is a preview API and is disabled by default. (use --enable-preview to enable preview APIs) Note : I have already passed --enable-preview in VM Options of program and Compiler settings in preferences.
[ "You need to use IntelliJ IDEA 2022.2 or newer for Java 19 support.\n", "--enable-preview should be in VM options, NOT program arguments\n\nYou still need to have those settings in Java Compiler\n\nAnd the project settings:\n\nAlso, you can run from the command line\njava --enable-preview --source 19 Main.java\n\nSample code:\n\nwith the following results:\n\n" ]
[ 0, 0 ]
[]
[]
[ "intellij_idea", "java", "java_19", "maven", "project_loom" ]
stackoverflow_0074470221_intellij_idea_java_java_19_maven_project_loom.txt
Q: How to serialize / deserialize a FileSystemHandle JavaScript object with Dart in IndexedDB storage? I'm using js-interop to use the File System Access API with Dart in a web environment. I would like to store a FileSystemDirectoryHandle in IndexedDB to reuse it later. When storing an instance of FileSystemDirectoryHandle in IndexedDB, the data is a Dart object (Symbol when exploring the value in DevTools). When I read back, value is not a FileSystemDirectoryHandle and all informations of the object is lost and useless. I did not find a way to store a handle into IndexedDB and read it back as a FileSystemDirectoryHandle. Below is parts of the code I declare with js-interop: // Only to keep track of API's types definitions. typedef Promise<T> = dynamic; // FileSystemHandle and *Options are declared in the same way. @JS() class FileSystemDirectoryHandle extends FileSystemHandle { external Promise<FileSystemFileHandle> getFileHandle(String name, [FileSystemGetFileOptions? options]); external Promise<FileSystemDirectoryHandle> getDirectoryHandle(String name, [FileSystemGetDirectoryOptions? options]); external Promise<void> removeEntry(String name, [FileSystemRemoveOptions? options]); external Promise<List<String>?> resolve(FileSystemHandle possibleDescendant); } Here is what I'm trying to achieve: final handle = await js.promiseToFuture(window.showDirectoryPicker()); // Storage use dart:indexed_db in a homebrew implementation (tested and works fine with // primitive types). await storage.set("dir", handle); // Reload page... // Dynamic only final directory = await storage.get("dir"); print(directory.name); // Typed FileSystemDirectoryHandle dirHandle = directory as FileSystemDirectoryHandle; print(dirHandle.name); Calling dynamic directory.name throws a NoSuchMethodError: Uncaught (in promise) Error: NoSuchMethodError: 'name' method not found Receiver: Instance of 'LinkedMap<dynamic, dynamic>' Calling typed dirHandle.name throws an Error: Error: Expected a value of type 'FileSystemDirectoryHandle', but got one of type 'LinkedMap<dynamic, dynamic>' Screenshot of IndexedDB in DevTools, when storing from Dart, and storing from JavaScript My understanding of js-interop is that it translates JavaScript object into a Dart proxy. As I'm sending a Dart object, it does not serialize the JavaScript object, but the Dart proxy object. Therefore the JavaScript object is lost in the process. Is there a way to pass the JavaScript object to IndexedDB from Dart? Or at least serialize the native JavaScript object from Dart proxy and then send it into IndexedDB? Any guidance would be much appreciated. Issue on dart-lang/sdk repository #50621 More on this repository, usage in example here, and js-interop here. A: It will throw a NoSuchMethodError as the instance returned from IndexedDB is not a FileSystemDirectoryHandle. Are you saying directory.name throws a NoSuchMethodError? What is the static type of directory here? Is it possible you need to cast the result to storage.set to FileSystemDirectoryHandle? My understanding of js-interop is that it translates JavaScript object into a Dart proxy. As I'm sending a Dart object, it does not serialize the JavaScript object, but the Dart proxy object. Therefore the JavaScript object is lost in the process. This shouldn't be the case. The object is still a JavaScript object, you're just using a Dart type to interact with that object. So, you can use the Dart members you declared for it, but we don't wrap that object if you just write a @JS() interface for it. A: It sounds like you're trying to store a FileSystemDirectoryHandle object in IndexedDB, but when you retrieve the object from IndexedDB, it is no longer a FileSystemDirectoryHandle and you're unable to access its properties or methods. This is likely happening because the FileSystemDirectoryHandle class is defined using js-interop, which means that it is a Dart "proxy" for the corresponding JavaScript object, rather than a true Dart object. When you store the FileSystemDirectoryHandle in IndexedDB, it is being serialized as a Dart object, but because it is actually a proxy for a JavaScript object, the JavaScript object itself is not being serialized and is therefore lost when you retrieve the object from IndexedDB. To solve this issue, you will need to serialize the JavaScript object itself, rather than the Dart proxy, when storing the FileSystemDirectoryHandle in IndexedDB. You can do this using the jsObject property of the JsObject class, which returns the underlying JavaScript object for a given Dart proxy object. Here is an example of how you could use the jsObject property to serialize and store a FileSystemDirectoryHandle in IndexedDB: import 'dart:js' as js; // First, get the `FileSystemDirectoryHandle` object using js-interop final handle = await js.promiseToFuture(window.showDirectoryPicker()); // Use the `jsObject` property to get the underlying JavaScript object final jsObject = handle.jsObject; // Store the JavaScript object in IndexedDB await storage.set("dir", jsObject); Then, when you retrieve the object from IndexedDB, you can convert it back into a FileSystemDirectoryHandle using the JsObject constructor, which creates a Dart proxy for a given JavaScript object. Here is an example of how you could do this: // Retrieve the JavaScript object from IndexedDB final jsObject = await storage.get("dir"); // Convert the JavaScript object into a FileSystemDirectoryHandle final handle = FileSystemDirectoryHandle(jsObject); // You should now be able to access the properties and methods of the handle print(handle.name); By using the jsObject property and the JsObject constructor in this way, you should be able to store and retrieve FileSystemDirectoryHandle objects in IndexedDB and retain their functionality.
How to serialize / deserialize a FileSystemHandle JavaScript object with Dart in IndexedDB storage?
I'm using js-interop to use the File System Access API with Dart in a web environment. I would like to store a FileSystemDirectoryHandle in IndexedDB to reuse it later. When storing an instance of FileSystemDirectoryHandle in IndexedDB, the data is a Dart object (Symbol when exploring the value in DevTools). When I read back, value is not a FileSystemDirectoryHandle and all informations of the object is lost and useless. I did not find a way to store a handle into IndexedDB and read it back as a FileSystemDirectoryHandle. Below is parts of the code I declare with js-interop: // Only to keep track of API's types definitions. typedef Promise<T> = dynamic; // FileSystemHandle and *Options are declared in the same way. @JS() class FileSystemDirectoryHandle extends FileSystemHandle { external Promise<FileSystemFileHandle> getFileHandle(String name, [FileSystemGetFileOptions? options]); external Promise<FileSystemDirectoryHandle> getDirectoryHandle(String name, [FileSystemGetDirectoryOptions? options]); external Promise<void> removeEntry(String name, [FileSystemRemoveOptions? options]); external Promise<List<String>?> resolve(FileSystemHandle possibleDescendant); } Here is what I'm trying to achieve: final handle = await js.promiseToFuture(window.showDirectoryPicker()); // Storage use dart:indexed_db in a homebrew implementation (tested and works fine with // primitive types). await storage.set("dir", handle); // Reload page... // Dynamic only final directory = await storage.get("dir"); print(directory.name); // Typed FileSystemDirectoryHandle dirHandle = directory as FileSystemDirectoryHandle; print(dirHandle.name); Calling dynamic directory.name throws a NoSuchMethodError: Uncaught (in promise) Error: NoSuchMethodError: 'name' method not found Receiver: Instance of 'LinkedMap<dynamic, dynamic>' Calling typed dirHandle.name throws an Error: Error: Expected a value of type 'FileSystemDirectoryHandle', but got one of type 'LinkedMap<dynamic, dynamic>' Screenshot of IndexedDB in DevTools, when storing from Dart, and storing from JavaScript My understanding of js-interop is that it translates JavaScript object into a Dart proxy. As I'm sending a Dart object, it does not serialize the JavaScript object, but the Dart proxy object. Therefore the JavaScript object is lost in the process. Is there a way to pass the JavaScript object to IndexedDB from Dart? Or at least serialize the native JavaScript object from Dart proxy and then send it into IndexedDB? Any guidance would be much appreciated. Issue on dart-lang/sdk repository #50621 More on this repository, usage in example here, and js-interop here.
[ "\nIt will throw a NoSuchMethodError as the instance returned from IndexedDB is not a FileSystemDirectoryHandle.\n\nAre you saying directory.name throws a NoSuchMethodError? What is the static type of directory here? Is it possible you need to cast the result to storage.set to FileSystemDirectoryHandle?\n\nMy understanding of js-interop is that it translates JavaScript object into a Dart proxy. As I'm sending a Dart object, it does not serialize the JavaScript object, but the Dart proxy object. Therefore the JavaScript object is lost in the process.\n\nThis shouldn't be the case. The object is still a JavaScript object, you're just using a Dart type to interact with that object. So, you can use the Dart members you declared for it, but we don't wrap that object if you just write a @JS() interface for it.\n", "It sounds like you're trying to store a FileSystemDirectoryHandle object in IndexedDB, but when you retrieve the object from IndexedDB, it is no longer a FileSystemDirectoryHandle and you're unable to access its properties or methods.\nThis is likely happening because the FileSystemDirectoryHandle class is defined using js-interop, which means that it is a Dart \"proxy\" for the corresponding JavaScript object, rather than a true Dart object. When you store the FileSystemDirectoryHandle in IndexedDB, it is being serialized as a Dart object, but because it is actually a proxy for a JavaScript object, the JavaScript object itself is not being serialized and is therefore lost when you retrieve the object from IndexedDB.\nTo solve this issue, you will need to serialize the JavaScript object itself, rather than the Dart proxy, when storing the FileSystemDirectoryHandle in IndexedDB. You can do this using the jsObject property of the JsObject class, which returns the underlying JavaScript object for a given Dart proxy object.\nHere is an example of how you could use the jsObject property to serialize and store a FileSystemDirectoryHandle in IndexedDB:\nimport 'dart:js' as js;\n\n// First, get the `FileSystemDirectoryHandle` object using js-interop\nfinal handle = await js.promiseToFuture(window.showDirectoryPicker());\n\n// Use the `jsObject` property to get the underlying JavaScript object\nfinal jsObject = handle.jsObject;\n\n// Store the JavaScript object in IndexedDB\nawait storage.set(\"dir\", jsObject);\n\nThen, when you retrieve the object from IndexedDB, you can convert it back into a FileSystemDirectoryHandle using the JsObject constructor, which creates a Dart proxy for a given JavaScript object. Here is an example of how you could do this:\n// Retrieve the JavaScript object from IndexedDB\nfinal jsObject = await storage.get(\"dir\");\n\n// Convert the JavaScript object into a FileSystemDirectoryHandle\nfinal handle = FileSystemDirectoryHandle(jsObject);\n\n// You should now be able to access the properties and methods of the handle\nprint(handle.name);\n\nBy using the jsObject property and the JsObject constructor in this way, you should be able to store and retrieve FileSystemDirectoryHandle objects in IndexedDB and retain their functionality.\n" ]
[ 0, 0 ]
[]
[]
[ "dart_js_interop", "indexeddb", "javascript", "serialization" ]
stackoverflow_0074658816_dart_js_interop_indexeddb_javascript_serialization.txt
Q: Results called before closing connection are not showing / error: sqlite3.ProgrammingError: Cannot operate on a closed database The following code is throwing the error 'sqlite3.ProgrammingError: Cannot operate on a closed database.' Considering that I close the connection after the queries are done, I don't understand why this is happening. import sqlite3 def database(): connection = sqlite3.connect('database.db') connection.row_factory = sqlite3.Row return connection def _index(): connection = database() posts = connection.execute('SELECT P.title, P.content, P.created, U.username FROM posts P JOIN users U ON P.author_id = U.id').fetchall() users = connection.execute('SELECT U.fullname as "username", C.fullname as "committeename" FROM users U JOIN committees C ON U.committee_id = C.id') connection.close() I was trying to query the users database and posts database (2 queries) and then close the connection but an error is happening that doesn't let me do this.
Results called before closing connection are not showing / error: sqlite3.ProgrammingError: Cannot operate on a closed database
The following code is throwing the error 'sqlite3.ProgrammingError: Cannot operate on a closed database.' Considering that I close the connection after the queries are done, I don't understand why this is happening. import sqlite3 def database(): connection = sqlite3.connect('database.db') connection.row_factory = sqlite3.Row return connection def _index(): connection = database() posts = connection.execute('SELECT P.title, P.content, P.created, U.username FROM posts P JOIN users U ON P.author_id = U.id').fetchall() users = connection.execute('SELECT U.fullname as "username", C.fullname as "committeename" FROM users U JOIN committees C ON U.committee_id = C.id') connection.close() I was trying to query the users database and posts database (2 queries) and then close the connection but an error is happening that doesn't let me do this.
[]
[]
[ "The issue was that i had not added a .fetchall() clause at the end of the query.\nCorrected code:\nimport sqlite3\n\ndef database():\n connection = sqlite3.connect('database.db')\n connection.row_factory = sqlite3.Row\n return connection\n\ndef _index():\n connection = database()\n posts = connection.execute('SELECT P.title, P.content, P.created, U.username FROM posts P JOIN users U ON P.author_id = U.id').fetchall()\n users = connection.execute('SELECT U.fullname as \"username\", C.fullname as \"committeename\" FROM users U JOIN committees C ON U.committee_id = C.id')\n connection.close()\n\n" ]
[ -1 ]
[ "python", "sqlite" ]
stackoverflow_0074662203_python_sqlite.txt
Q: Github actions: test Java maven project gives error: java.lang.IllegalStateException: Failed to load ApplicationContext My Github actions workflow runs the tests in my application, but they give back the following error: java.lang.IllegalStateException: Failed to load ApplicationContext Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [longPath/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] I tested in my application and the tests only give this error back if my wamp isn't running, so when the app can't reach the local database. How do I handle this in my Github actions workflow? Test file: @SpringBootTest class WorkethicApplicationTests { @Test void contextLoads() { } } application.properties spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/testdatabase spring.datasource.username=root spring.datasource.password= spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver workflow: jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up JDK 11 uses: actions/setup-java@v3 with: java-version: '17' distribution: 'temurin' cache: maven - name: Build with Maven run: mvn clean install # Optional: Uploads the full dependency graph to GitHub to improve the quality of Dependabot alerts this repository can receive - name: Update dependency graph uses: advanced-security/maven-dependency-submission-action@571e99aab1055c2e71a1e2309b9691de18d6b7d6 A: For that to run, you must have the database running. As I can see in your post, your root password is empty and your app is not running inside a container. So, you can achieve your goal by updating your workflow configuration like this: jobs: build: runs-on: ubuntu-latest services: mysql: image: mysql:latest env: MYSQL_DATABASE: testdatabase MYSQL_ALLOW_EMPTY_PASSWORD: yes ports: - 3306:3306 steps: ... If the password is not empty and you still want to use the root user, you just have to add MYSQL_ROOT_PASSWORD: <root password> to the config. For more info you can refer to the official mysql docker image documentation. Also, if you have to wait until the database service is available you can refer to the "No connections until MySQL init completes" at the aforementioned page. From there you can open this example. With some mysql images you might have a bit nicer approach for that, like in this answer. But that actually might not be a problem if your app can handle that waiting period until the database is available. I'm sure you can achieve that with Spring, so just try running the job without any of those options. If at some point you want to run the app inside a container as well just refer to the same answer I've mentioned above.
Github actions: test Java maven project gives error: java.lang.IllegalStateException: Failed to load ApplicationContext
My Github actions workflow runs the tests in my application, but they give back the following error: java.lang.IllegalStateException: Failed to load ApplicationContext Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [longPath/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] I tested in my application and the tests only give this error back if my wamp isn't running, so when the app can't reach the local database. How do I handle this in my Github actions workflow? Test file: @SpringBootTest class WorkethicApplicationTests { @Test void contextLoads() { } } application.properties spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/testdatabase spring.datasource.username=root spring.datasource.password= spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver workflow: jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up JDK 11 uses: actions/setup-java@v3 with: java-version: '17' distribution: 'temurin' cache: maven - name: Build with Maven run: mvn clean install # Optional: Uploads the full dependency graph to GitHub to improve the quality of Dependabot alerts this repository can receive - name: Update dependency graph uses: advanced-security/maven-dependency-submission-action@571e99aab1055c2e71a1e2309b9691de18d6b7d6
[ "For that to run, you must have the database running. As I can see in your post, your root password is empty and your app is not running inside a container. So, you can achieve your goal by updating your workflow configuration like this:\njobs:\n build:\n runs-on: ubuntu-latest\n\n services:\n mysql:\n image: mysql:latest\n env:\n MYSQL_DATABASE: testdatabase\n MYSQL_ALLOW_EMPTY_PASSWORD: yes\n ports:\n - 3306:3306\n\n steps:\n ...\n\nIf the password is not empty and you still want to use the root user, you just have to add MYSQL_ROOT_PASSWORD: <root password> to the config. For more info you can refer to the official mysql docker image documentation.\nAlso, if you have to wait until the database service is available you can refer to the \"No connections until MySQL init completes\" at the aforementioned page. From there you can open this example. With some mysql images you might have a bit nicer approach for that, like in this answer. But that actually might not be a problem if your app can handle that waiting period until the database is available. I'm sure you can achieve that with Spring, so just try running the job without any of those options.\nIf at some point you want to run the app inside a container as well just refer to the same answer I've mentioned above.\n" ]
[ 0 ]
[]
[]
[ "github_actions", "java", "spring_boot" ]
stackoverflow_0074658824_github_actions_java_spring_boot.txt
Q: Python PIL 0.5 opacity, transparency, alpha Is there any way to make an image half transparent? the pseudo code is something like this: from PIL import Image image = Image.open('image.png') image = alpha(image, 0.5) I googled it for a couple of hours but I can't find anything useful. A: I realize this question is really old, but with the current version of Pillow (v4.2.1), there is a function called putalpha. It seems to work fine for me. I don't know if will work for every situation where you need to change the alpha, but it does work. It sets the alpha value for every pixel in the image. It seems, though that you can use a mask: http://www.leancrew.com/all-this/2013/11/transparency-with-pil/. Use putalpha like this: from PIL import Image img = Image.open(image) img.putalpha(127) # Half alpha; alpha argument must be an int img.save(dest) A: Could you do something like this? from PIL import Image image = Image.open('image.png') #open image image = image.convert("RGBA") #convert to RGBA rgb = image.getpixel(x,y) #Get the rgba value at coordinates x,y rgb[3] = int(rgb[3] / 2) or you could do rgb[3] = 50 maybe? #set alpha to half somehow image.putpixel((x,y), rgb) #put back the modified reba values at same pixel coordinates Definitely not the most efficient way of doing things but it might work. I wrote the code in browser so it might not be error free but hopefully it can give you an idea. EDIT: Just noticed how old this question was. Leaving answer anyways for future help. :) A: I put together Pecan's answer and cr333's question from this question: Using PIL to make all white pixels transparent? ... and came up with this: from PIL import Image opacity_level = 170 # Opaque is 255, input between 0-255 img = Image.open('img1.png') img = img.convert("RGBA") datas = img.getdata() newData = [] for item in datas: newData.append((0, 0, 0, opacity_level)) else: newData.append(item) img.putdata(newData) img.save("img2.png", "PNG") In my case, I have text with black background and wanted only the background semi-transparent, in which case: from PIL import Image opacity_level = 170 # Opaque is 255, input between 0-255 img = Image.open('img1.png') img = img.convert("RGBA") datas = img.getdata() newData = [] for item in datas: if item[0] == 0 and item[1] == 0 and item[2] == 0: newData.append((0, 0, 0, opacity_level)) else: newData.append(item) img.putdata(newData) img.save("img2.png", "PNG") A: I had an issue, where black boxes were appearing around my image when applying putalpha(). This workaround (applying alpha in a copied layer) solved it for me. from PIL import Image with Image.open("file.png") as im: im2 = im.copy() im2.putalpha(180) im.paste(im2, im) im.save("file2.png") Explanation: Like I said, putalpha modifies all pixels by setting their alpha value, so fully transparent pixels become only partially transparent. The code I posted above first sets (putalpha) all pixels to semi-transparent in a copy, then copies (paste) all pixels to the original image using the original alpha values as a mask. This means that fully transparent pixels in the original image are skipped during the paste. Credit: https://github.com/nulano @ https://github.com/python-pillow/Pillow/issues/4687#issuecomment-643567573 A: I just did this by myself...even though my code maybe a little bit weird...But it works fine. So I share it here. Hopes it could help anybody. =) The idea: To transparent a pic means lower alpha which is the 4th element in the tuple. my frame code: from PIL import Image img=open(image) img=img.convert('RGBA') #you can make sure your pic is in the right mode by check img.mode data=img.getdata() #you'll get a list of tuples newData=[] for a in data: a=a[:3] #you'll get your tuple shorten to RGB a=a+(100,) #change the 100 to any transparency number you like between (0,255) newData.append(a) img.putdata(newData) #you'll get your new img ready img.save(filename.filetype) I didn't find the right command to fulfil this job automatically, so I write this by myself. Hopes it'll help again. XD A: This method helps to reduce opacity of logo with transparency before pasting it over image # pip install Pillow # PIL.__version__ is 9.3.0 from PIL import Image, ImageEnhance im = Image.open('logo.png').convert('RGBA') alpha = im.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(.5) im.putalpha(alpha)
Python PIL 0.5 opacity, transparency, alpha
Is there any way to make an image half transparent? the pseudo code is something like this: from PIL import Image image = Image.open('image.png') image = alpha(image, 0.5) I googled it for a couple of hours but I can't find anything useful.
[ "I realize this question is really old, but with the current version of Pillow (v4.2.1), there is a function called putalpha. It seems to work fine for me. I don't know if will work for every situation where you need to change the alpha, but it does work. It sets the alpha value for every pixel in the image. It seems, though that you can use a mask: http://www.leancrew.com/all-this/2013/11/transparency-with-pil/.\nUse putalpha like this:\nfrom PIL import Image\nimg = Image.open(image)\nimg.putalpha(127) # Half alpha; alpha argument must be an int\nimg.save(dest)\n\n", "Could you do something like this?\nfrom PIL import Image\nimage = Image.open('image.png') #open image\nimage = image.convert(\"RGBA\") #convert to RGBA\nrgb = image.getpixel(x,y) #Get the rgba value at coordinates x,y\nrgb[3] = int(rgb[3] / 2) or you could do rgb[3] = 50 maybe? #set alpha to half somehow\nimage.putpixel((x,y), rgb) #put back the modified reba values at same pixel coordinates\n\nDefinitely not the most efficient way of doing things but it might work. I wrote the code in browser so it might not be error free but hopefully it can give you an idea.\nEDIT: Just noticed how old this question was. Leaving answer anyways for future help. :)\n", "I put together Pecan's answer and cr333's question from this question:\nUsing PIL to make all white pixels transparent?\n... and came up with this:\nfrom PIL import Image\n\nopacity_level = 170 # Opaque is 255, input between 0-255\n\nimg = Image.open('img1.png')\nimg = img.convert(\"RGBA\")\ndatas = img.getdata()\n\nnewData = []\nfor item in datas:\n newData.append((0, 0, 0, opacity_level))\nelse:\n newData.append(item)\n\nimg.putdata(newData)\nimg.save(\"img2.png\", \"PNG\")\n\nIn my case, I have text with black background and wanted only the background semi-transparent, in which case:\nfrom PIL import Image\n\nopacity_level = 170 # Opaque is 255, input between 0-255\n\nimg = Image.open('img1.png')\nimg = img.convert(\"RGBA\")\ndatas = img.getdata()\n\nnewData = []\nfor item in datas:\n if item[0] == 0 and item[1] == 0 and item[2] == 0:\n newData.append((0, 0, 0, opacity_level))\n else:\n newData.append(item)\n\nimg.putdata(newData)\nimg.save(\"img2.png\", \"PNG\")\n\n", "I had an issue, where black boxes were appearing around my image when applying putalpha().\nThis workaround (applying alpha in a copied layer) solved it for me.\nfrom PIL import Image\nwith Image.open(\"file.png\") as im:\n im2 = im.copy()\n im2.putalpha(180)\n im.paste(im2, im)\n im.save(\"file2.png\")\n\nExplanation:\n\nLike I said, putalpha modifies all pixels by setting their alpha value, so fully transparent pixels become only partially transparent. The code I posted above first sets (putalpha) all pixels to semi-transparent in a copy, then copies (paste) all pixels to the original image using the original alpha values as a mask. This means that fully transparent pixels in the original image are skipped during the paste.\n\nCredit: https://github.com/nulano @ https://github.com/python-pillow/Pillow/issues/4687#issuecomment-643567573\n\n\n", "I just did this by myself...even though my code maybe a little bit weird...But it works fine. So I share it here. Hopes it could help anybody. =)\nThe idea: To transparent a pic means lower alpha which is the 4th element in the tuple.\nmy frame code:\nfrom PIL import Image \nimg=open(image)\nimg=img.convert('RGBA') #you can make sure your pic is in the right mode by check img.mode\ndata=img.getdata() #you'll get a list of tuples\nnewData=[]\nfor a in data:\n a=a[:3] #you'll get your tuple shorten to RGB\n a=a+(100,) #change the 100 to any transparency number you like between (0,255)\n newData.append(a)\nimg.putdata(newData) #you'll get your new img ready\nimg.save(filename.filetype)\n\nI didn't find the right command to fulfil this job automatically, so I write this by myself. Hopes it'll help again. XD\n", "This method helps to reduce opacity of logo with transparency before pasting it over image\n# pip install Pillow\n# PIL.__version__ is 9.3.0\n\nfrom PIL import Image, ImageEnhance\n\nim = Image.open('logo.png').convert('RGBA')\nalpha = im.split()[3]\nalpha = ImageEnhance.Brightness(alpha).enhance(.5)\nim.putalpha(alpha)\n\n" ]
[ 25, 4, 2, 1, 0, 0 ]
[]
[]
[ "alpha", "opacity", "python", "python_imaging_library", "transparency" ]
stackoverflow_0024731035_alpha_opacity_python_python_imaging_library_transparency.txt
Q: AT+SHCONN failing for SIM7000E HTTPS connection I am trying to create a HTTPS connection using AT commands for a SIM7000E module but the process is failing at the AT+SHCONN step. For testing purposes I've successfully managed to send GET requests via HTTP to http://httpbin.org I know that the SIM within the module is activated and internet connection is working. Connecting to https://httpbin.org is causing the issue. The certificate file httpbin-ca.cer has successfully been uploaded to the SIM7000E using: AT+CFSINIT AT+CFSWFILE=3,"httpbin-ca.cer",0,1188,5000 AT+CFSTERM The certificate files presence is confirmed via: AT+CFSINIT AT+CFSGFIS=3,"httpbin-ca.cer" AT+CFSTERM which gives the output of: +CFSGFIS: 1188 OK The full diagnostics and connection process with output at each stage is as follows: AT OK AT+CMEE=2 OK AT+CPIN? +CPIN: READY OK AT+CGMM SIMCOM_SIM7000E OK AT+CGMR Revision:1351B07SIM7000E OK AT+COPS? +COPS: 0,0,"vodafone UK",3 OK AT+CSQ +CSQ: 28,99 OK AT+CNACT=1,"wap.vodafone.co.uk" OK AT+CNACT? +CNACT: 1,"10.239.xxx.xxx" OK The above returns a valid IP that is blanked out here. AT+CSSLCFG="convert",2,"httpbin-ca.cer" OK AT+SHSSL=1,"httpbin-ca.cer" OK AT+SHCONF="URL","https://httpbin.org" OK AT+SHCONF="BODYLEN",1024 OK AT+SHCONF="HEADERLEN",350 OK AT+SHSSL? +SHSSL: 1,"httpbin-ca.cer","" OK AT+SHCONN +CME ERROR: operation not allowed The contents of the httpbin-ca.cer file is: -----BEGIN CERTIFICATE----- MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM 9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6 VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L 93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU 5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy rqXRfboQnoZsG4q5WTP468SQvvG5 -----END CERTIFICATE----- If it is set to not use a certificate and just accept any SSL without questions asked using: AT+SHSSL=1,"" instead of setting it to the loaded certificate then AT+SHCONN works and I am able to make a successful GET request. However getting it working to only accept specific certificates is required for when it comes to POST requests. A: Assuming you're just trying to make an HTTPS request and don't need client verification, you shouldn't need to do anything with client certificates. Your AT+SHCONN step is failing most likely because the time on your modem is set to year 2080. You can check it with AT+CCLK? and set it with AT+CCLK="22/12...." You also don't need to set a client certificate. Just use AT+SHSSL=1,"" At this point you'll be able to connect to a popular domain like https://amazon.com, but probably not your serverless backend that's mapped to a domain name you bought and hosted on a machine with 100s of other certificates. For that you need to specify which domain's certificate to ask for with AT+SHSSLCFG="sni",1,"yourdomain.com" See my Gist for more info
AT+SHCONN failing for SIM7000E HTTPS connection
I am trying to create a HTTPS connection using AT commands for a SIM7000E module but the process is failing at the AT+SHCONN step. For testing purposes I've successfully managed to send GET requests via HTTP to http://httpbin.org I know that the SIM within the module is activated and internet connection is working. Connecting to https://httpbin.org is causing the issue. The certificate file httpbin-ca.cer has successfully been uploaded to the SIM7000E using: AT+CFSINIT AT+CFSWFILE=3,"httpbin-ca.cer",0,1188,5000 AT+CFSTERM The certificate files presence is confirmed via: AT+CFSINIT AT+CFSGFIS=3,"httpbin-ca.cer" AT+CFSTERM which gives the output of: +CFSGFIS: 1188 OK The full diagnostics and connection process with output at each stage is as follows: AT OK AT+CMEE=2 OK AT+CPIN? +CPIN: READY OK AT+CGMM SIMCOM_SIM7000E OK AT+CGMR Revision:1351B07SIM7000E OK AT+COPS? +COPS: 0,0,"vodafone UK",3 OK AT+CSQ +CSQ: 28,99 OK AT+CNACT=1,"wap.vodafone.co.uk" OK AT+CNACT? +CNACT: 1,"10.239.xxx.xxx" OK The above returns a valid IP that is blanked out here. AT+CSSLCFG="convert",2,"httpbin-ca.cer" OK AT+SHSSL=1,"httpbin-ca.cer" OK AT+SHCONF="URL","https://httpbin.org" OK AT+SHCONF="BODYLEN",1024 OK AT+SHCONF="HEADERLEN",350 OK AT+SHSSL? +SHSSL: 1,"httpbin-ca.cer","" OK AT+SHCONN +CME ERROR: operation not allowed The contents of the httpbin-ca.cer file is: -----BEGIN CERTIFICATE----- MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM 9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6 VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L 93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU 5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy rqXRfboQnoZsG4q5WTP468SQvvG5 -----END CERTIFICATE----- If it is set to not use a certificate and just accept any SSL without questions asked using: AT+SHSSL=1,"" instead of setting it to the loaded certificate then AT+SHCONN works and I am able to make a successful GET request. However getting it working to only accept specific certificates is required for when it comes to POST requests.
[ "Assuming you're just trying to make an HTTPS request and don't need client verification, you shouldn't need to do anything with client certificates.\nYour AT+SHCONN step is failing most likely because the time on your modem is set to year 2080. You can check it with AT+CCLK? and set it with AT+CCLK=\"22/12....\"\nYou also don't need to set a client certificate. Just use AT+SHSSL=1,\"\"\nAt this point you'll be able to connect to a popular domain like https://amazon.com, but probably not your serverless backend that's mapped to a domain name you bought and hosted on a machine with 100s of other certificates. For that you need to specify which domain's certificate to ask for with AT+SHSSLCFG=\"sni\",1,\"yourdomain.com\"\nSee my Gist for more info\n" ]
[ 0 ]
[]
[]
[ "at_command", "https", "ssl" ]
stackoverflow_0070959336_at_command_https_ssl.txt
Q: C# adding data to a SQL table “Specified cast is not valid.” C# adding data to a SQL table with asp.net It throws an error System.InvalidCastException: “Specified cast is not valid.” This is for a foreign key column with a data type of bigint. I set my type in C# to be Int64, after int definition threw an error but still get the error. Is this because I can't add to a column that has foreign keys? Do I need to cascade? This is my datacontroller: using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using SchoolDb.Models; using MySql.Data.MySqlClient; using System.Diagnostics; namespace SchoolDb.Controllers { public class CoursesDataController : ApiController { private SchoolDbContext School = new SchoolDbContext(); /// <summary> /// returns list of courses in the system /// </summary> /// <example>GET api/CoursesData/ListCourses</example> /// <returns>a list of courses</returns> [HttpGet] [Route("api/CourseData/ListCourses/{SearchKey?}")] public IEnumerable<Course> ListCourses(string SearchKey = null) { //create an instance of a connection MySqlConnection Conn = School.AccessDatabase(); //open the connection between server and database Conn.Open(); string query = "Select * from classes where lower(classname) like lower(@key) or classid like (@key)"; Debug.WriteLine("the search key is " + query); //establish a new command queery for our database MySqlCommand cmd = Conn.CreateCommand(); //SQL Quesry cmd.CommandText = query; cmd.Parameters.AddWithValue("@key", "%" + SearchKey + "%"); cmd.Prepare(); //Gather Result set of query into variable MySqlDataReader ResultSet = cmd.ExecuteReader(); //create an empty list of Courses List<Course> Courses = new List<Course> { }; while (ResultSet.Read()) { //access column information by the db column name as an index int ClassId = (int)ResultSet["classid"]; string ClassCode = (string)ResultSet["classcode"]; Int64 TeacherId = (Int64)ResultSet["teacherid"]; DateTime StartDate = (DateTime)ResultSet["startdate"]; DateTime FinishDate = (DateTime)ResultSet["finishdate"]; string ClassName = (string)ResultSet["classname"]; Course NewCourse = new Course(); NewCourse.ClassId = ClassId; NewCourse.ClassCode = ClassCode; NewCourse.TeacherId = TeacherId; NewCourse.StartDate = StartDate; NewCourse.FinishDate = FinishDate; NewCourse.ClassName = ClassName; //add the course info to the list Courses.Add(NewCourse); } Conn.Close(); //return the final list of courses return Courses; } /// <summary> /// returns a single instance of a course /// </summary> /// <param name="id">class id</param> /// <returns>info on a particular course based on classid input</returns> [HttpGet] public Course FindCourse(int id) { Course NewCourse = new Course(); //create an instance of a connection MySqlConnection Conn = School.AccessDatabase(); //open the connection between server and database Conn.Open(); //establish a new command query for our database MySqlCommand cmd = Conn.CreateCommand(); //SQL Query cmd.CommandText = "Select * from classes where classid = " + id; //Gather Result set of query into variable MySqlDataReader ResultSet = cmd.ExecuteReader(); while (ResultSet.Read()) { //access column information by the db column name as an index int ClassId = (int)ResultSet["classid"]; string ClassCode = (string)ResultSet["classcode"]; Int64 TeacherId = (Int64)ResultSet["teacherid"]; DateTime StartDate = (DateTime)ResultSet["startdate"]; DateTime FinishDate = (DateTime)ResultSet["finishdate"]; string ClassName = (string)ResultSet["classname"]; NewCourse.ClassId = ClassId; NewCourse.ClassCode = ClassCode; NewCourse.TeacherId = TeacherId; NewCourse.StartDate = StartDate; NewCourse.FinishDate = FinishDate; NewCourse.ClassName = ClassName; } return NewCourse; } /// <summary> /// /// </summary> /// <param name="id"></param> /// <example>POST: /api/CoursesData/DeleteCourse/3</example> [HttpPost] public void DeleteCourse(int id) { //create an instance of a connection MySqlConnection Conn = School.AccessDatabase(); //open the connection between server and database Conn.Open(); //establish a new command queery for our database MySqlCommand cmd = Conn.CreateCommand(); //SQL Query cmd.CommandText = "Delete from classes where classid=@id"; cmd.Parameters.AddWithValue("@id", id); cmd.Prepare(); cmd.ExecuteNonQuery(); Conn.Close(); } [HttpPost] public void AddCourse(Course NewCourse) { //create an instance of a connection MySqlConnection Conn = School.AccessDatabase(); //open the connection between server and database Conn.Open(); //establish a new command query for our database MySqlCommand cmd = Conn.CreateCommand(); //SQL Query cmd.CommandText = "insert into classes (classcode, teacherid, startdate, finishdate, classname) value (@ClassCode, @TeacherId, @StartDate,@FinishDate,@ClassName)"; cmd.Parameters.AddWithValue("@ClassCode", NewCourse.ClassCode); cmd.Parameters.AddWithValue("@TeacherId", NewCourse.TeacherId); cmd.Parameters.AddWithValue("@StartDate", NewCourse.StartDate); cmd.Parameters.AddWithValue("@FinishDate",NewCourse.FinishDate ); cmd.Parameters.AddWithValue("@ClassName", NewCourse.ClassName); cmd.Prepare(); cmd.ExecuteNonQuery(); Conn.Close(); } } } A: You didn't specify which line the InvalidCastException occurs on, so I'm going to assume it's one of the following lines with explicit casts: //access column information by the db column name as an index int ClassId = (int)ResultSet["classid"]; string ClassCode = (string)ResultSet["classcode"]; Int64 TeacherId = (Int64)ResultSet["teacherid"]; DateTime StartDate = (DateTime)ResultSet["startdate"]; DateTime FinishDate = (DateTime)ResultSet["finishdate"]; string ClassName = (string)ResultSet["classname"]; One possibility is trying to retrieve an int from a long column, or vice versa. This can be avoided by using the GetInt32 or GetInt64 method. These will convert the value to a smaller size if possible, otherwise throw an OverflowException. Another possibility is that some of the columns contain NULL. In that case, ResultSet["Name"] will return DBNull.Value, which can't be cast to a string (or int or DateTime). Depending on what columns can contain NULL values, you likely need code similar to the following: //access column information by the db column name as an index int ClassId = ResultSet.GetInt32("classid"); string ClassCode = ResultSet.IsDBNull("classcode") ? null : reader.GetString("classcode"); Int64 TeacherId = ResultSet.GetInt64("teacherid"); DateTime StartDate = (DateTime)ResultSet["startdate"]; DateTime FinishDate = (DateTime)ResultSet["finishdate"]; string ClassName = ResultSet.IsDBNull("classname") ? null : ResultSet.GetString("classname"); But I would recommend using an ORM like Dapper to simplify all of this code and map a DB row easily to a C# object.
C# adding data to a SQL table “Specified cast is not valid.”
C# adding data to a SQL table with asp.net It throws an error System.InvalidCastException: “Specified cast is not valid.” This is for a foreign key column with a data type of bigint. I set my type in C# to be Int64, after int definition threw an error but still get the error. Is this because I can't add to a column that has foreign keys? Do I need to cascade? This is my datacontroller: using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using SchoolDb.Models; using MySql.Data.MySqlClient; using System.Diagnostics; namespace SchoolDb.Controllers { public class CoursesDataController : ApiController { private SchoolDbContext School = new SchoolDbContext(); /// <summary> /// returns list of courses in the system /// </summary> /// <example>GET api/CoursesData/ListCourses</example> /// <returns>a list of courses</returns> [HttpGet] [Route("api/CourseData/ListCourses/{SearchKey?}")] public IEnumerable<Course> ListCourses(string SearchKey = null) { //create an instance of a connection MySqlConnection Conn = School.AccessDatabase(); //open the connection between server and database Conn.Open(); string query = "Select * from classes where lower(classname) like lower(@key) or classid like (@key)"; Debug.WriteLine("the search key is " + query); //establish a new command queery for our database MySqlCommand cmd = Conn.CreateCommand(); //SQL Quesry cmd.CommandText = query; cmd.Parameters.AddWithValue("@key", "%" + SearchKey + "%"); cmd.Prepare(); //Gather Result set of query into variable MySqlDataReader ResultSet = cmd.ExecuteReader(); //create an empty list of Courses List<Course> Courses = new List<Course> { }; while (ResultSet.Read()) { //access column information by the db column name as an index int ClassId = (int)ResultSet["classid"]; string ClassCode = (string)ResultSet["classcode"]; Int64 TeacherId = (Int64)ResultSet["teacherid"]; DateTime StartDate = (DateTime)ResultSet["startdate"]; DateTime FinishDate = (DateTime)ResultSet["finishdate"]; string ClassName = (string)ResultSet["classname"]; Course NewCourse = new Course(); NewCourse.ClassId = ClassId; NewCourse.ClassCode = ClassCode; NewCourse.TeacherId = TeacherId; NewCourse.StartDate = StartDate; NewCourse.FinishDate = FinishDate; NewCourse.ClassName = ClassName; //add the course info to the list Courses.Add(NewCourse); } Conn.Close(); //return the final list of courses return Courses; } /// <summary> /// returns a single instance of a course /// </summary> /// <param name="id">class id</param> /// <returns>info on a particular course based on classid input</returns> [HttpGet] public Course FindCourse(int id) { Course NewCourse = new Course(); //create an instance of a connection MySqlConnection Conn = School.AccessDatabase(); //open the connection between server and database Conn.Open(); //establish a new command query for our database MySqlCommand cmd = Conn.CreateCommand(); //SQL Query cmd.CommandText = "Select * from classes where classid = " + id; //Gather Result set of query into variable MySqlDataReader ResultSet = cmd.ExecuteReader(); while (ResultSet.Read()) { //access column information by the db column name as an index int ClassId = (int)ResultSet["classid"]; string ClassCode = (string)ResultSet["classcode"]; Int64 TeacherId = (Int64)ResultSet["teacherid"]; DateTime StartDate = (DateTime)ResultSet["startdate"]; DateTime FinishDate = (DateTime)ResultSet["finishdate"]; string ClassName = (string)ResultSet["classname"]; NewCourse.ClassId = ClassId; NewCourse.ClassCode = ClassCode; NewCourse.TeacherId = TeacherId; NewCourse.StartDate = StartDate; NewCourse.FinishDate = FinishDate; NewCourse.ClassName = ClassName; } return NewCourse; } /// <summary> /// /// </summary> /// <param name="id"></param> /// <example>POST: /api/CoursesData/DeleteCourse/3</example> [HttpPost] public void DeleteCourse(int id) { //create an instance of a connection MySqlConnection Conn = School.AccessDatabase(); //open the connection between server and database Conn.Open(); //establish a new command queery for our database MySqlCommand cmd = Conn.CreateCommand(); //SQL Query cmd.CommandText = "Delete from classes where classid=@id"; cmd.Parameters.AddWithValue("@id", id); cmd.Prepare(); cmd.ExecuteNonQuery(); Conn.Close(); } [HttpPost] public void AddCourse(Course NewCourse) { //create an instance of a connection MySqlConnection Conn = School.AccessDatabase(); //open the connection between server and database Conn.Open(); //establish a new command query for our database MySqlCommand cmd = Conn.CreateCommand(); //SQL Query cmd.CommandText = "insert into classes (classcode, teacherid, startdate, finishdate, classname) value (@ClassCode, @TeacherId, @StartDate,@FinishDate,@ClassName)"; cmd.Parameters.AddWithValue("@ClassCode", NewCourse.ClassCode); cmd.Parameters.AddWithValue("@TeacherId", NewCourse.TeacherId); cmd.Parameters.AddWithValue("@StartDate", NewCourse.StartDate); cmd.Parameters.AddWithValue("@FinishDate",NewCourse.FinishDate ); cmd.Parameters.AddWithValue("@ClassName", NewCourse.ClassName); cmd.Prepare(); cmd.ExecuteNonQuery(); Conn.Close(); } } }
[ "You didn't specify which line the InvalidCastException occurs on, so I'm going to assume it's one of the following lines with explicit casts:\n//access column information by the db column name as an index\nint ClassId = (int)ResultSet[\"classid\"];\nstring ClassCode = (string)ResultSet[\"classcode\"];\nInt64 TeacherId = (Int64)ResultSet[\"teacherid\"];\nDateTime StartDate = (DateTime)ResultSet[\"startdate\"];\nDateTime FinishDate = (DateTime)ResultSet[\"finishdate\"];\nstring ClassName = (string)ResultSet[\"classname\"];\n\nOne possibility is trying to retrieve an int from a long column, or vice versa. This can be avoided by using the GetInt32 or GetInt64 method. These will convert the value to a smaller size if possible, otherwise throw an OverflowException.\nAnother possibility is that some of the columns contain NULL. In that case, ResultSet[\"Name\"] will return DBNull.Value, which can't be cast to a string (or int or DateTime).\nDepending on what columns can contain NULL values, you likely need code similar to the following:\n//access column information by the db column name as an index\nint ClassId = ResultSet.GetInt32(\"classid\");\nstring ClassCode = ResultSet.IsDBNull(\"classcode\") ? null : reader.GetString(\"classcode\");\nInt64 TeacherId = ResultSet.GetInt64(\"teacherid\");\nDateTime StartDate = (DateTime)ResultSet[\"startdate\"];\nDateTime FinishDate = (DateTime)ResultSet[\"finishdate\"];\nstring ClassName = ResultSet.IsDBNull(\"classname\") ? null : ResultSet.GetString(\"classname\");\n\nBut I would recommend using an ORM like Dapper to simplify all of this code and map a DB row easily to a C# object.\n" ]
[ 0 ]
[]
[]
[ "asp.net", "c#", "mysql", "odatacontroller" ]
stackoverflow_0074647676_asp.net_c#_mysql_odatacontroller.txt
Q: How do I iterate over rows in Pandas and check if the sum of each row is equal to the sum of a list? I have tried: for i, row in preferences.iterrows(): if len(students_with_courses) == preferences.sum(axis = i): But gets following error: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I have tried: for i, row in preferences.iterrows(): if len(students_with_courses) == preferences.sum(axis = i): But gets following error: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). A: The reason you're getting the error you provided is that you are comparing is that len(students_with_courses) == preferences.sum(axis = i) returns a series containing True/False values, as opposed to one single True/False value. An if statement required one single True/False value. To get to a working solution, I made some assumptions about what you mean by students_with_courses and preferences. I also assume you mean the length of the list, not the sum of the list since that's what your code shows. students_with_courses = ["a", "b", "c"] preferences = pd.DataFrame({'column1': [0, 1, 1, 3], 'column2': [0, 0, 1, 1], 'column3': [3, 6, 1, 8]}) If you're just looking to see if the sum of each row is equal to the length of your list, you can simplify to the code below instead of iterating over each row. preferences.sum(axis=1) == len(students_with_courses) This returns: 0 True 1 False 2 True 3 False dtype: bool Note that if you want to compare the sum of the list instead of the length of the list, you can use the below code. students_with_courses = [1, 0, 2] preferences = pd.DataFrame({'column1': [0, 1, 1, 3], 'column2': [0, 0, 1, 1], 'column3': [3, 6, 1, 8]}) preferences.sum(axis=1) == sum(students_with_courses) This returns: 0 True 1 False 2 True 3 False dtype: bool
How do I iterate over rows in Pandas and check if the sum of each row is equal to the sum of a list?
I have tried: for i, row in preferences.iterrows(): if len(students_with_courses) == preferences.sum(axis = i): But gets following error: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I have tried: for i, row in preferences.iterrows(): if len(students_with_courses) == preferences.sum(axis = i): But gets following error: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
[ "The reason you're getting the error you provided is that you are comparing is that len(students_with_courses) == preferences.sum(axis = i) returns a series containing True/False values, as opposed to one single True/False value. An if statement required one single True/False value.\nTo get to a working solution, I made some assumptions about what you mean by students_with_courses and preferences. I also assume you mean the length of the list, not the sum of the list since that's what your code shows.\nstudents_with_courses = [\"a\", \"b\", \"c\"]\npreferences = pd.DataFrame({'column1': [0, 1, 1, 3], 'column2': [0, 0, 1, 1], 'column3': [3, 6, 1, 8]})\n\nIf you're just looking to see if the sum of each row is equal to the length of your list, you can simplify to the code below instead of iterating over each row.\npreferences.sum(axis=1) == len(students_with_courses)\n\nThis returns:\n0 True\n1 False\n2 True\n3 False\ndtype: bool\n\n\nNote that if you want to compare the sum of the list instead of the length of the list, you can use the below code.\nstudents_with_courses = [1, 0, 2]\npreferences = pd.DataFrame({'column1': [0, 1, 1, 3], 'column2': [0, 0, 1, 1], 'column3': [3, 6, 1, 8]})\npreferences.sum(axis=1) == sum(students_with_courses)\n\nThis returns:\n0 True\n1 False\n2 True\n3 False\ndtype: bool\n\n" ]
[ 0 ]
[]
[]
[ "pandas" ]
stackoverflow_0074655941_pandas.txt
Q: how to run loader on successful form submission only? I want that the loader should start ONLY and ONLY when the form has been successfully submitted (instead of just the onclick submit button event that the code does currently). How can I do so? <div id="loader" class= "lds-dual-ring hidden overlay" > <div class="lds-dual-ring hidden overlay"> </div> <div class="loadcontent"><div><strong>Working on your request...it may take up to 2 minutes.</strong></div></div> </div> Code below is the part where loader kicks upon submit button event. $('#submitBtn').click(function () { $('#loader').removeClass('hidden') // $('#loader').html('Loading').addClass('loadcontent') // $("#loading").html("Loading"); }) </script> Code below is one of the form fields that takes a value from user: <div class="form-group"> <div class="form-control"style="padding: 0;"> {% ifequal field.name 'Port' %} {% render_field field class="rowforinput marginforfields form-control" style="height: 23px; margin-left: 0; margin-right: 0" title=" For eg. 1/1/48 or 2/1/16" pattern="^[12]/1/(?:[1-3]\d|4[0-8]|[1-9])$" required=true %} {% endifequal %} </div> </div> A: To show the loader when the AJAX call is successful, you can move the code that shows the loader from the click event handler for the submit button to the success callback function in the AJAX call. Here is an example of how you can modify your code to do this: $('#submitBtn').click(function () { // Submit the form using AJAX $.ajax({ url: $(this).attr('action'), // The URL to submit the form to type: $(this).attr('method'), // The method to use when submitting the form data: $(this).serialize(), // The data to submit with the form success: function (response) { // Show the loader $('#loader').removeClass('hidden'); // Handle the successful submission of the form here // For example, you can display a success message }, error: function (error) { // Handle any errors that occurred when submitting the form here // For example, you can display an error message } }); }); This code moves the code that shows the loader from the click event handler for the submit button to the success callback function in the AJAX call. As a result, the loader will only be shown when the AJAX call is successful and the success callback function is called. Note that this code assumes that the form has a method attribute and an action attribute that specify the method and URL to submit the form to, respectively. You may need to adjust these values depending on your specific form and setup.
how to run loader on successful form submission only?
I want that the loader should start ONLY and ONLY when the form has been successfully submitted (instead of just the onclick submit button event that the code does currently). How can I do so? <div id="loader" class= "lds-dual-ring hidden overlay" > <div class="lds-dual-ring hidden overlay"> </div> <div class="loadcontent"><div><strong>Working on your request...it may take up to 2 minutes.</strong></div></div> </div> Code below is the part where loader kicks upon submit button event. $('#submitBtn').click(function () { $('#loader').removeClass('hidden') // $('#loader').html('Loading').addClass('loadcontent') // $("#loading").html("Loading"); }) </script> Code below is one of the form fields that takes a value from user: <div class="form-group"> <div class="form-control"style="padding: 0;"> {% ifequal field.name 'Port' %} {% render_field field class="rowforinput marginforfields form-control" style="height: 23px; margin-left: 0; margin-right: 0" title=" For eg. 1/1/48 or 2/1/16" pattern="^[12]/1/(?:[1-3]\d|4[0-8]|[1-9])$" required=true %} {% endifequal %} </div> </div>
[ "To show the loader when the AJAX call is successful, you can move the code that shows the loader from the click event handler for the submit button to the success callback function in the AJAX call. Here is an example of how you can modify your code to do this:\n$('#submitBtn').click(function () {\n // Submit the form using AJAX\n $.ajax({\n url: $(this).attr('action'), // The URL to submit the form to\n type: $(this).attr('method'), // The method to use when submitting the form\n data: $(this).serialize(), // The data to submit with the form\n success: function (response) {\n // Show the loader\n $('#loader').removeClass('hidden');\n\n // Handle the successful submission of the form here\n // For example, you can display a success message\n },\n error: function (error) {\n // Handle any errors that occurred when submitting the form here\n // For example, you can display an error message\n }\n });\n});\n\nThis code moves the code that shows the loader from the click event handler for the submit button to the success callback function in the AJAX call. As a result, the loader will only be shown when the AJAX call is successful and the success callback function is called.\nNote that this code assumes that the form has a method attribute and an action attribute that specify the method and URL to submit the form to, respectively. You may need to adjust these values depending on your specific form and setup.\n" ]
[ 0 ]
[]
[]
[ "django", "flask", "html", "javascript", "python" ]
stackoverflow_0074662942_django_flask_html_javascript_python.txt
Q: Script doesn't seem to be working, and I cannot understand why script dont work I am incredibly new to scripting, and I was just fooling around in ROBLOX studio and I made a script that was INTENDED to put an item stored in ReplicatedStorage into a specific players StarterPack, but no matter what I change it does not want to work. Could anyone explain why? local playerName = "plr name" local toolName = "tool name" game.Players.PlayerAdded:Connect(function(player) if player.Name == playerName then local tool = game.ReplicatedStorage:FindFirstChild(toolName) player.StarterPack:AddItem(tool) end end) A: There are a few issues with your code that are preventing it from working as expected. First, the PlayerAdded event is triggered whenever a new player joins the game, so your code will only run for players who join the game after the script is run. If the player you want to give the tool to is already in the game, your code will not affect them. Second, the playerName variable is defined as a string containing the player's name, but the Name property of the player object is not a string, it is a PlayerName object. You will need to use the .Value property of the PlayerName object to access the player's name as a string. Third, the toolName variable is defined as a string containing the name of the tool you want to give to the player, but the FindFirstChild method only accepts a string as an argument if the child you are searching for is a direct descendant of the parent object. In your code, the tool object is a descendant of the ReplicatedStorage object, so you will need to use the FindFirstItem method instead. Here is an example of how you could modify your code to fix these issues: local playerName = "plr name" local toolName = "tool name" game.Players.PlayerAdded:Connect(function(player) if player.Name.Value == playerName then local tool = game.ReplicatedStorage:FindFirstItem(toolName) player.StarterPack:AddItem(tool) end let me know if this is work
Script doesn't seem to be working, and I cannot understand why
script dont work I am incredibly new to scripting, and I was just fooling around in ROBLOX studio and I made a script that was INTENDED to put an item stored in ReplicatedStorage into a specific players StarterPack, but no matter what I change it does not want to work. Could anyone explain why? local playerName = "plr name" local toolName = "tool name" game.Players.PlayerAdded:Connect(function(player) if player.Name == playerName then local tool = game.ReplicatedStorage:FindFirstChild(toolName) player.StarterPack:AddItem(tool) end end)
[ "There are a few issues with your code that are preventing it from working as expected.\nFirst, the PlayerAdded event is triggered whenever a new player joins the game, so your code will only run for players who join the game after the script is run. If the player you want to give the tool to is already in the game, your code will not affect them.\nSecond, the playerName variable is defined as a string containing the player's name, but the Name property of the player object is not a string, it is a PlayerName object. You will need to use the .Value property of the PlayerName object to access the player's name as a string.\nThird, the toolName variable is defined as a string containing the name of the tool you want to give to the player, but the FindFirstChild method only accepts a string as an argument if the child you are searching for is a direct descendant of the parent object. In your code, the tool object is a descendant of the ReplicatedStorage object, so you will need to use the FindFirstItem method instead.\nHere is an example of how you could modify your code to fix these issues:\nlocal playerName = \"plr name\"\n\nlocal toolName = \"tool name\"\n\ngame.Players.PlayerAdded:Connect(function(player)\nif player.Name.Value == playerName then\n local tool = game.ReplicatedStorage:FindFirstItem(toolName)\n player.StarterPack:AddItem(tool)\nend\n\nlet me know if this is work\n" ]
[ 0 ]
[]
[]
[ "lua", "roblox" ]
stackoverflow_0074663120_lua_roblox.txt
Q: Unremovable space in autocomplete popup I have been working on this for an hour, and I still do not understand why the popup menu has a space before the autocompleted word. I simply want to know what the underlying cause of this issue is. Here's my attempt: body{ background-color:black; } .searchBar_child { width: 100%; height: 40px; padding-left: 15px; border-top-right-radius: 0px; border-bottom-right-radius: 0px; border-top-left-radius: 10px; border-bottom-left-radius: 10px; box-shadow: none !important; position: absolute; transform: translate(-50%, -50%); top: 50%; left: 50%; } .searchBarInput { width: 100%; padding: 15px 10px; border: none; border-bottom: 1px solid #645979; outline: none; border-radius: 5px 5px 0 0; background-color: #ffffff; font-size: 16px; } .autocomplete_popup { list-style: none; } .list { width: 100%; background-color: #ffffff; margin-top: 10px; border-radius: 10px; } .list-items { width: 100%; padding: 10px 15px; } .list-items:hover { color: white; background-color: turquoise; border-radius: 10px; width: 100% !important; } let names = [ "CSS", "HTML", "Ayla", "Jake", "Sean", "Henry", "Brad", "Stephen", "Taylor", "Timmy", "Cathy", "John", "Amanda", "Amara", "Sam", "Sandy", "Danny", "Ellen", "Camille", "Chloe", "Emily", "Nadia", "Mitchell", "Harvey", "Lucy", "Amy", "Glen", "Peter", ]; //Sort names in ascending order let sortedNames = names.sort(); //reference let input = document.getElementById("searchBar"); //Execute function on keyup input.addEventListener("keyup", (e) => { //loop through above array //Initially remove all elements ( so if user erases a letter or adds new letter then clean previous outputs) removeElements(); for (let i of sortedNames) { //convert input to lowercase and compare with each string if ( i.toLowerCase().startsWith(input.value.toLowerCase()) && input.value != "" ) { //create li element let listItem = document.createElement("li"); //One common class name listItem.classList.add("list-items"); listItem.style.cursor = "pointer"; listItem.setAttribute("onclick", "displayNames('" + i + "')"); //Display matched part in bold let word = "<b class=\"searchBarWord\">" + i.substr(0, input.value.length) + "</b>"; word += i.substr(input.value.length); //display the value in array listItem.innerHTML = word; document.querySelector(".list").appendChild(listItem); } } }); function displayNames(value) { input.value = value; removeElements(); } function removeElements() { //clear all the item let items = document.querySelectorAll(".list-items"); items.forEach((item) => { item.remove(); }); } <div class="searchBar_parent"> <form class="searchBar_child" autocomplete="off"> <div><input id="searchBar" class="form-control searchBarInput" type="text" placeholder="Type a name here..." /></div> <ul class="autocomplete_popup list"></ul> </form> </div> I experimented with padding and margins even attempted setting the width to 100%. These did not assist me in resolving the problem. Any help would be greatly appreciated; please do so. A: autocomplete_popup { list-style: none; padding: 0; margin: 0; }
Unremovable space in autocomplete popup
I have been working on this for an hour, and I still do not understand why the popup menu has a space before the autocompleted word. I simply want to know what the underlying cause of this issue is. Here's my attempt: body{ background-color:black; } .searchBar_child { width: 100%; height: 40px; padding-left: 15px; border-top-right-radius: 0px; border-bottom-right-radius: 0px; border-top-left-radius: 10px; border-bottom-left-radius: 10px; box-shadow: none !important; position: absolute; transform: translate(-50%, -50%); top: 50%; left: 50%; } .searchBarInput { width: 100%; padding: 15px 10px; border: none; border-bottom: 1px solid #645979; outline: none; border-radius: 5px 5px 0 0; background-color: #ffffff; font-size: 16px; } .autocomplete_popup { list-style: none; } .list { width: 100%; background-color: #ffffff; margin-top: 10px; border-radius: 10px; } .list-items { width: 100%; padding: 10px 15px; } .list-items:hover { color: white; background-color: turquoise; border-radius: 10px; width: 100% !important; } let names = [ "CSS", "HTML", "Ayla", "Jake", "Sean", "Henry", "Brad", "Stephen", "Taylor", "Timmy", "Cathy", "John", "Amanda", "Amara", "Sam", "Sandy", "Danny", "Ellen", "Camille", "Chloe", "Emily", "Nadia", "Mitchell", "Harvey", "Lucy", "Amy", "Glen", "Peter", ]; //Sort names in ascending order let sortedNames = names.sort(); //reference let input = document.getElementById("searchBar"); //Execute function on keyup input.addEventListener("keyup", (e) => { //loop through above array //Initially remove all elements ( so if user erases a letter or adds new letter then clean previous outputs) removeElements(); for (let i of sortedNames) { //convert input to lowercase and compare with each string if ( i.toLowerCase().startsWith(input.value.toLowerCase()) && input.value != "" ) { //create li element let listItem = document.createElement("li"); //One common class name listItem.classList.add("list-items"); listItem.style.cursor = "pointer"; listItem.setAttribute("onclick", "displayNames('" + i + "')"); //Display matched part in bold let word = "<b class=\"searchBarWord\">" + i.substr(0, input.value.length) + "</b>"; word += i.substr(input.value.length); //display the value in array listItem.innerHTML = word; document.querySelector(".list").appendChild(listItem); } } }); function displayNames(value) { input.value = value; removeElements(); } function removeElements() { //clear all the item let items = document.querySelectorAll(".list-items"); items.forEach((item) => { item.remove(); }); } <div class="searchBar_parent"> <form class="searchBar_child" autocomplete="off"> <div><input id="searchBar" class="form-control searchBarInput" type="text" placeholder="Type a name here..." /></div> <ul class="autocomplete_popup list"></ul> </form> </div> I experimented with padding and margins even attempted setting the width to 100%. These did not assist me in resolving the problem. Any help would be greatly appreciated; please do so.
[ "autocomplete_popup {\n list-style: none;\n padding: 0;\n margin: 0;\n}\n\n" ]
[ 1 ]
[]
[]
[ "css", "html", "javascript" ]
stackoverflow_0074663176_css_html_javascript.txt
Q: Data quota limit with data pack I am a newbie to git, so I made a grave mistake. On getting a new laptop, I accidentally pushed a commit that removed most of the files except the ones I edited in our repo. In Android Studio, I attempted to fix this by clicking on the git log, and trying to "reset the current branch to here". This gave me an error of: Error downloading object: java_pid2812.hprof (58df4cf): Smudge error: Error downloading java_pid2812.hprof (58df4cfb920117556d8a695631aef8a75834d2e71ec360a7fbbc5c79e4fe84e2): batch response: This repository is over its data quota. Account responsible for LFS bandwidth should purchase more data packs to restore access. I purchased a data pack on my account, and this did not resolve this issue. How can I restore the repo to before that commit was pushed? Thanks. A: If you have access to the remote repository where you pushed the commit, you can use the git revert command to undo the changes introduced by the commit. This will create a new commit that reverses the changes made by the previous commit, allowing you to restore the repository to the state it was in before the problematic commit was pushed. Here is an example of how you could use the git revert command to undo the changes introduced by the commit with the hash 58df4cfb920117556d8a695631aef8a75834d2e71ec360a7fbbc5c79e4fe84e2: git revert 58df4cfb920117556d8a695631aef8a75834d2e71ec360a7fbbc5c79e4fe84e2 This will create a new commit that undoes the changes made by the previous commit, and you can then push this new commit to the remote repository to restore the repository to its previous state. Alternatively, if you do not have access to the remote repository, you can use the git reset command to "undo" the commit on your local repository. This will reset the state of your local repository to the state it was in before the commit was made, but it will not affect the remote repository. Here is an example of how you could use the git reset command to undo the changes introduced by the commit with the hash 58df4cfb920117556d8a695631aef8a75834d2e71ec360a7fbbc5c79e4fe84e2: git reset --hard 58df4cfb920117556d8a695631aef8a75834d2e71ec360a7fbbc5c79e4fe84e2 This will reset your local repository to the state it was in before the commit was made, but it will not affect the remote repository. You will need to use the git revert command (as described above) if you want to undo the commit on the remote repository. It's important to note that using the git reset command can be dangerous, as it permanently discards any commits that were made after the specified commit. This means that you will lose any changes that were made in those commits, and they cannot be recovered. Because of this, it's generally safer to use the git revert command to undo changes, as it allows you to undo the changes without permanently discarding any commits.
Data quota limit with data pack
I am a newbie to git, so I made a grave mistake. On getting a new laptop, I accidentally pushed a commit that removed most of the files except the ones I edited in our repo. In Android Studio, I attempted to fix this by clicking on the git log, and trying to "reset the current branch to here". This gave me an error of: Error downloading object: java_pid2812.hprof (58df4cf): Smudge error: Error downloading java_pid2812.hprof (58df4cfb920117556d8a695631aef8a75834d2e71ec360a7fbbc5c79e4fe84e2): batch response: This repository is over its data quota. Account responsible for LFS bandwidth should purchase more data packs to restore access. I purchased a data pack on my account, and this did not resolve this issue. How can I restore the repo to before that commit was pushed? Thanks.
[ "If you have access to the remote repository where you pushed the commit, you can use the git revert command to undo the changes introduced by the commit. This will create a new commit that reverses the changes made by the previous commit, allowing you to restore the repository to the state it was in before the problematic commit was pushed.\nHere is an example of how you could use the git revert command to undo the changes introduced by the commit with the hash 58df4cfb920117556d8a695631aef8a75834d2e71ec360a7fbbc5c79e4fe84e2:\ngit revert 58df4cfb920117556d8a695631aef8a75834d2e71ec360a7fbbc5c79e4fe84e2\n\nThis will create a new commit that undoes the changes made by the previous commit, and you can then push this new commit to the remote repository to restore the repository to its previous state.\nAlternatively, if you do not have access to the remote repository, you can use the git reset command to \"undo\" the commit on your local repository. This will reset the state of your local repository to the state it was in before the commit was made, but it will not affect the remote repository.\nHere is an example of how you could use the git reset command to undo the changes introduced by the commit with the hash 58df4cfb920117556d8a695631aef8a75834d2e71ec360a7fbbc5c79e4fe84e2:\ngit reset --hard 58df4cfb920117556d8a695631aef8a75834d2e71ec360a7fbbc5c79e4fe84e2\n\nThis will reset your local repository to the state it was in before the commit was made, but it will not affect the remote repository. You will need to use the git revert command (as described above) if you want to undo the commit on the remote repository.\nIt's important to note that using the git reset command can be dangerous, as it permanently discards any commits that were made after the specified commit. This means that you will lose any changes that were made in those commits, and they cannot be recovered. Because of this, it's generally safer to use the git revert command to undo changes, as it allows you to undo the changes without permanently discarding any commits.\n" ]
[ 0 ]
[]
[]
[ "android_studio", "git_lfs", "github", "repo" ]
stackoverflow_0074663005_android_studio_git_lfs_github_repo.txt
Q: What is the proper way to set external task sensor in Airflow with different scheduled interval? I just joined a new company and I'm trying to learn Airflow as I used it. So far I've got the basics of most things down except External Task Sensors. I have two DAGs, DAG A that has a schedule interval of "0 6 * * *" and DAG B with schedule interval of "0 7 * * *" DAG A waits for DAG B to Complete before it Continues. However DAG B sometimes takes 3 hours to Complete and at other times 10+ hours. I created an ExternalTask Sensor as show Below but it never triggers and timesout even when DAG B is complete. ExternalTaskSensor( task_id = "wait_sensor", external_dag_id="dag_b", external_task_id = "end", poke_interval = 60*30, timeout=60*60, retries = 10, execution_delta= timedelta(hours=2), dag=dag ) Any help on properly setting up the sensor is greatly appreciated. Also, Happy Thanksgiving! A: The execution date of DAG A is one hour before DAG B, and you set the execution delta to 2 hours, meaning DAG A external sensor is trying to find DAG B with an execution date of 0 4 * * *, which doesn't exist. in this case, your external sensor task fails on timeout. you could set check_existence=True to fail immediately instead of waiting for 10 retries. Also, you can see in the external task sensor log on which external task execution date its poking: [2022-12-02, 08:21:36 UTC] {external_task.py:206} INFO - Poking for tasks ['test_task'] in dag test_dag on 2022-12-02T08:25:00+00:00 ... Solution: From the sensor docs, "For yesterday, use [positive!] datetime.timedelta(days=1)" So to resolve this, you need to provide a negative execution_delta of 1 hour, as the execution date of DAG A is exactly 1 hour after DAG B: execution_delta=timedelta(hours=-1) A: First of all timeout is set to ` hour which will cause If you pass it timeout=60*60 on start, it will fail after 1 hour. also I recommend using reschedule instead of poke The poke and reschedule modes can be configured directly when you instantiate the sensor; generally, the trade-off between them is latency. Something that is checking every second should be in poke mode, while something that is checking every minute should be in reschedule mode. you can check something like this: ExternalTaskSensor( task_id = "wait_sensor", external_dag_id="dag_b", external_task_id = "end", mode="reschedule", timeout=60*60*23, retries = 10, execution_delta= timedelta(hours=2), dag=dag ) A: To set up an external task sensor in Apache Airflow, you need to specify the external_dag_id and external_task_id of the task you want to wait for. In your case, you want to wait for the task with ID "end" in DAG B, so you would set external_dag_id to "dag_b" and external_task_id to "end". Additionally, you can specify a poke_interval to determine how often the sensor checks for the completion of the external task, and a timeout to specify how long the sensor should wait for the task to complete before timing out. You can also set the retries and execution_delta parameters to specify the number of retries and the time interval within which the external task must complete, respectively. Here is an example of how you could set up the external task sensor in your DAG A: from airflow.sensors.external_task_sensor import ExternalTaskSensor from datetime import timedelta wait_sensor = ExternalTaskSensor( task_id = "wait_sensor", external_dag_id="dag_b", external_task_id = "end", poke_interval = 60*30, # Check for task completion every 30 minutes timeout=60*60, # Timeout after 1 hour retries = 10, # Retry up to 10 times execution_delta= timedelta(hours=2), # Task must complete within 2 hours dag=dag ) Note that the external task sensor will only trigger when the specified task is complete. If the task takes a variable amount of time to complete, you may need to adjust the timeout and execution_delta values to ensure that the sensor does not time out before the task is complete. A: I found this a bit tricky in Airflow so I decided to make a function that reads execution date from your external task. I am dynamically generate task names in my DAG and this is how waiting task looks like and using text separator string so later I can read external dag and task name from my get_context function def wait_for_another_task(dag_name, task_name, table_name): task = ExternalTaskSensor( task_id=f"{table_name}{WAITING_TASK_TEXT_SEPARATOR}{dag_name}.{task_name}", external_dag_id=dag_name, external_task_id=task_name, timeout=60 * 60, # timeout is in sec, so *60 and we have timeout in minutes allowed_states=['success'], failed_states=['failed', 'skipped'], execution_date_fn = get_context, mode = 'reschedule' ) return task In my case, there is WAITING_TASK_TEXT_SEPARATOR = '_wait_for_' and here is my get_context funcion def get_context(dt, **kwargs): task_instance_str = str(kwargs["task_instance"]) # look for "_wait_for_" string as it is separator for external_dag starting_loc_of_wait_for = task_instance_str.find(WAITING_TASK_TEXT_SEPARATOR) len_of_wait_for = len(WAITING_TASK_TEXT_SEPARATOR) ending_loc_of_wait_for = starting_loc_of_wait_for + len_of_wait_for beggiging_of_dag_task = task_instance_str[ending_loc_of_wait_for:] ending_of_dag_task_loc = beggiging_of_dag_task.find(" ") dag_task = beggiging_of_dag_task[:ending_of_dag_task_loc] dag_task_lst = dag_task.split('.') dag_name = dag_task_lst[0] task_name = dag_task_lst[1] dag_runs = DagRun.find(dag_id=dag_name) dag_runs.sort(key=lambda x: x.execution_date, reverse=True) if dag_runs: last_exec_date = dag_runs[0].execution_date return last_exec_date else: return dt ExternalTaskSensor has a execution_date_fn (https://airflow.apache.org/docs/apache-airflow/stable/_api/airflow/sensors/external_task/index.html#airflow.sensors.external_task.ExternalTaskSensor) than returns current execution’s logical date so if we dont have previous external dag runs, we can still got current run of current DAG. Based on that, you can just tweak timeout in the ExternalTaskSensor and dont need to worry about timedeltas and so A: The ExternalTaskSensor in Airflow is used to wait for a specific task in another DAG to complete before continuing with the current DAG. In order to properly set up the sensor with different scheduled intervals for the two DAGs, you need to specify the execution_delta parameter in the ExternalTaskSensor configuration. The execution_delta parameter specifies the time difference between the execution time of the current DAG and the execution time of the external DAG. In your case, since DAG A has a schedule interval of "0 6 * * *" and DAG B has a schedule interval of "0 7 * * *", the execution_delta for the ExternalTaskSensor in DAG A should be set to timedelta(hours=1) to account for the 1-hour difference in the execution times of the two DAGs. Here is an example of how you can set up the ExternalTaskSensor in DAG A to properly wait for DAG B to complete with different scheduled intervals for the two DAGs: from airflow.sensors.external_task_sensor import ExternalTaskSensor from datetime import timedelta # Set up the ExternalTaskSensor in DAG A external_task_sensor = ExternalTaskSensor( task_id = "wait_sensor", external_dag_id="dag_b", external_task_id = "end", poke_interval = 60*30, timeout=60*60, retries = 10, execution_delta= timedelta(hours=1), # Set the execution_delta to account for the 1-hour difference in the execution times of the two DAGs dag=dag ) With this configuration, the ExternalTaskSensor in DAG A will wait for the task with ID "end" in DAG B to complete, taking into account the 1-hour difference in the execution times of the two DAGs. This will ensure that the sensor is triggered properly and does not time out while waiting for DAG B to complete.
What is the proper way to set external task sensor in Airflow with different scheduled interval?
I just joined a new company and I'm trying to learn Airflow as I used it. So far I've got the basics of most things down except External Task Sensors. I have two DAGs, DAG A that has a schedule interval of "0 6 * * *" and DAG B with schedule interval of "0 7 * * *" DAG A waits for DAG B to Complete before it Continues. However DAG B sometimes takes 3 hours to Complete and at other times 10+ hours. I created an ExternalTask Sensor as show Below but it never triggers and timesout even when DAG B is complete. ExternalTaskSensor( task_id = "wait_sensor", external_dag_id="dag_b", external_task_id = "end", poke_interval = 60*30, timeout=60*60, retries = 10, execution_delta= timedelta(hours=2), dag=dag ) Any help on properly setting up the sensor is greatly appreciated. Also, Happy Thanksgiving!
[ "The execution date of DAG A is one hour before DAG B, and you set the execution delta to 2 hours, meaning DAG A external sensor is trying to find DAG B with an execution date of 0 4 * * *, which doesn't exist. in this case, your external sensor task fails on timeout. you could set check_existence=True to fail immediately instead of waiting for 10 retries.\nAlso, you can see in the external task sensor log on which external task execution date its poking:\n[2022-12-02, 08:21:36 UTC] {external_task.py:206} INFO - Poking for tasks ['test_task'] in dag test_dag on 2022-12-02T08:25:00+00:00 ...\nSolution:\nFrom the sensor docs, \"For yesterday, use [positive!] datetime.timedelta(days=1)\"\nSo to resolve this, you need to provide a negative execution_delta of 1 hour, as the execution date of DAG A is exactly 1 hour after DAG B:\nexecution_delta=timedelta(hours=-1)\n", "First of all timeout is set to ` hour which will cause If you pass it timeout=60*60 on start, it will fail after 1 hour.\nalso I recommend using reschedule instead of poke\n\nThe poke and reschedule modes can be configured directly when you instantiate the sensor; generally, the trade-off between them is latency. Something that is checking every second should be in poke mode, while something that is checking every minute should be in reschedule mode.\n\nyou can check something like this:\nExternalTaskSensor(\n task_id = \"wait_sensor\",\n external_dag_id=\"dag_b\",\n external_task_id = \"end\",\n mode=\"reschedule\",\n timeout=60*60*23,\n retries = 10,\n execution_delta= timedelta(hours=2),\n dag=dag \n)\n\n", "To set up an external task sensor in Apache Airflow, you need to specify the external_dag_id and external_task_id of the task you want to wait for. In your case, you want to wait for the task with ID \"end\" in DAG B, so you would set external_dag_id to \"dag_b\" and external_task_id to \"end\".\nAdditionally, you can specify a poke_interval to determine how often the sensor checks for the completion of the external task, and a timeout to specify how long the sensor should wait for the task to complete before timing out. You can also set the retries and execution_delta parameters to specify the number of retries and the time interval within which the external task must complete, respectively.\nHere is an example of how you could set up the external task sensor in your DAG A:\nfrom airflow.sensors.external_task_sensor import ExternalTaskSensor\nfrom datetime import timedelta\n\nwait_sensor = ExternalTaskSensor(\n task_id = \"wait_sensor\",\n external_dag_id=\"dag_b\",\n external_task_id = \"end\",\n poke_interval = 60*30, # Check for task completion every 30 minutes\n timeout=60*60, # Timeout after 1 hour\n retries = 10, # Retry up to 10 times\n execution_delta= timedelta(hours=2), # Task must complete within 2 hours\n dag=dag \n)\n\n\nNote that the external task sensor will only trigger when the specified task is complete. If the task takes a variable amount of time to complete, you may need to adjust the timeout and execution_delta values to ensure that the sensor does not time out before the task is complete.\n", "I found this a bit tricky in Airflow so I decided to make a function that reads execution date from your external task. I am dynamically generate task names in my DAG and this is how waiting task looks like and using text separator string so later I can read external dag and task name from my get_context function\ndef wait_for_another_task(dag_name, task_name, table_name):\n task = ExternalTaskSensor(\n task_id=f\"{table_name}{WAITING_TASK_TEXT_SEPARATOR}{dag_name}.{task_name}\",\n external_dag_id=dag_name,\n external_task_id=task_name,\n timeout=60 * 60, # timeout is in sec, so *60 and we have timeout in minutes\n allowed_states=['success'],\n failed_states=['failed', 'skipped'],\n execution_date_fn = get_context,\n mode = 'reschedule'\n )\n return task\n\nIn my case, there is WAITING_TASK_TEXT_SEPARATOR = '_wait_for_' and here is my get_context funcion\ndef get_context(dt, **kwargs):\n task_instance_str = str(kwargs[\"task_instance\"])\n # look for \"_wait_for_\" string as it is separator for external_dag\n starting_loc_of_wait_for = task_instance_str.find(WAITING_TASK_TEXT_SEPARATOR)\n len_of_wait_for = len(WAITING_TASK_TEXT_SEPARATOR)\n ending_loc_of_wait_for = starting_loc_of_wait_for + len_of_wait_for\n\n beggiging_of_dag_task = task_instance_str[ending_loc_of_wait_for:]\n ending_of_dag_task_loc = beggiging_of_dag_task.find(\" \")\n dag_task = beggiging_of_dag_task[:ending_of_dag_task_loc]\n dag_task_lst = dag_task.split('.')\n dag_name = dag_task_lst[0]\n task_name = dag_task_lst[1]\n\n dag_runs = DagRun.find(dag_id=dag_name)\n dag_runs.sort(key=lambda x: x.execution_date, reverse=True)\n if dag_runs:\n last_exec_date = dag_runs[0].execution_date\n return last_exec_date\n else:\n return dt\n\nExternalTaskSensor has a execution_date_fn (https://airflow.apache.org/docs/apache-airflow/stable/_api/airflow/sensors/external_task/index.html#airflow.sensors.external_task.ExternalTaskSensor) than returns current execution’s logical date so if we dont have previous external dag runs, we can still got current run of current DAG.\nBased on that, you can just tweak timeout in the ExternalTaskSensor and dont need to worry about timedeltas and so\n", "The ExternalTaskSensor in Airflow is used to wait for a specific task in another DAG to complete before continuing with the current DAG. In order to properly set up the sensor with different scheduled intervals for the two DAGs, you need to specify the execution_delta parameter in the ExternalTaskSensor configuration. The execution_delta parameter specifies the time difference between the execution time of the current DAG and the execution time of the external DAG.\nIn your case, since DAG A has a schedule interval of \"0 6 * * *\" and DAG B has a schedule interval of \"0 7 * * *\", the execution_delta for the ExternalTaskSensor in DAG A should be set to timedelta(hours=1) to account for the 1-hour difference in the execution times of the two DAGs.\nHere is an example of how you can set up the ExternalTaskSensor in DAG A to properly wait for DAG B to complete with different scheduled intervals for the two DAGs:\nfrom airflow.sensors.external_task_sensor import ExternalTaskSensor\nfrom datetime import timedelta\n\n# Set up the ExternalTaskSensor in DAG A\nexternal_task_sensor = ExternalTaskSensor(\n task_id = \"wait_sensor\",\n external_dag_id=\"dag_b\",\n external_task_id = \"end\",\n poke_interval = 60*30,\n timeout=60*60,\n retries = 10,\n execution_delta= timedelta(hours=1), # Set the execution_delta to account for the 1-hour difference in the execution times of the two DAGs\n dag=dag \n)\n\nWith this configuration, the ExternalTaskSensor in DAG A will wait for the task with ID \"end\" in DAG B to complete, taking into account the 1-hour difference in the execution times of the two DAGs. This will ensure that the sensor is triggered properly and does not time out while waiting for DAG B to complete.\n" ]
[ 3, 0, 0, 0, 0 ]
[ "It sounds like the issue you're encountering with your ExternalTaskSensor might be due to the fact that you've set the poke_interval and execution_delta values to be too low. The poke_interval determines how often the sensor checks for the external task to complete, and the execution_delta determines the amount of time it allows for the external task to complete before timing out.\nIn your code, the poke_interval is set to 30 minutes and the execution_delta is set to 2 hours. This means that the sensor will check for the completion of the external task every 30 minutes, and it will time out if the external task hasn't completed within 2 hours of the sensor starting. Given that your external task sometimes takes 3 hours to complete and sometimes takes 10+ hours, it's likely that the sensor is timing out before the task completes.\nTo fix this issue, you'll need to increase the values of the poke_interval and execution_delta parameters. You can do this by setting the poke_interval to a higher value, such as 10 or 15 minutes, and setting the execution_delta to a value that's higher than the maximum amount of time it takes for the external task to complete. This will allow the sensor to check for the completion of the external task more frequently, and to allow enough time for the task to complete before timing out.\nHere's an example of how you could modify your ExternalTaskSensor to increase the values of the poke_interval and execution_delta parameters:\nExternalTaskSensor(\n task_id=\"wait_sensor\",\n external_dag_id=\"dag_b\",\n external_task_id=\"end\",\n poke_interval=60 * 10, # Check for the completion of the external task every 10 minutes\n timeout=60 * 60,\n retries=10,\n execution_delta=timedelta(hours=10), # Allow up to 10 hours for the external task to complete\n dag=dag\n)\n\nI hope this helps! Let me know if you have any other questions.\n" ]
[ -2 ]
[ "airflow" ]
stackoverflow_0074565320_airflow.txt
Q: NTP Timestamp in RTCP Sender Report is Incorrect I'm using Amazon's sample code to upload a rtsp stream from an IP camera to Kinesis video streams. Code found here: https://github.com/awslabs/amazon-kinesis-video-streams-producer-sdk-cpp/blob/master/samples/kvs_gstreamer_sample.cpp I would like to get the NTP time from the camera for each frame. My understanding is that the first step in doing this is reading the RTCP sender report to get the synchronizing time for the camera's RTP and NTP times. To do that, I've added a callback on receiving RTCP packets like so: g_signal_connect_after(session, "on-receiving-rtcp", G_CALLBACK(on_rtcp_callback), data); Then, in my callback function after getting the SR packet from the buffer, I try to get the two timestamps: gst_rtcp_packet_sr_get_sender_info (packet, ssrc, ntptime, rtptime, packet_count, octet_count); When comparing the 'ntptime' and 'rtptime' variables I get here, with what I see in Wireshark, the rtp times match perfectly. However, the NTP time I get in my C++ code is very wrong, it shows a time from about a month ago, while the Wireshark packet shows an NTP time that appears correct. Is there some setting causing gstreamer to overwrite the NTP time in my sender report packets, and if so, how do I disable that setting? A: It turns out the NTP time provided gst_rtcp_packet_sr_get_sender_info is not in any format I've seen before. To convert to a meaningful timestamp you have to use gst_rtcp_ntp_to_unix which then gives you a unix time that actually makes some sense.
NTP Timestamp in RTCP Sender Report is Incorrect
I'm using Amazon's sample code to upload a rtsp stream from an IP camera to Kinesis video streams. Code found here: https://github.com/awslabs/amazon-kinesis-video-streams-producer-sdk-cpp/blob/master/samples/kvs_gstreamer_sample.cpp I would like to get the NTP time from the camera for each frame. My understanding is that the first step in doing this is reading the RTCP sender report to get the synchronizing time for the camera's RTP and NTP times. To do that, I've added a callback on receiving RTCP packets like so: g_signal_connect_after(session, "on-receiving-rtcp", G_CALLBACK(on_rtcp_callback), data); Then, in my callback function after getting the SR packet from the buffer, I try to get the two timestamps: gst_rtcp_packet_sr_get_sender_info (packet, ssrc, ntptime, rtptime, packet_count, octet_count); When comparing the 'ntptime' and 'rtptime' variables I get here, with what I see in Wireshark, the rtp times match perfectly. However, the NTP time I get in my C++ code is very wrong, it shows a time from about a month ago, while the Wireshark packet shows an NTP time that appears correct. Is there some setting causing gstreamer to overwrite the NTP time in my sender report packets, and if so, how do I disable that setting?
[ "It turns out the NTP time provided gst_rtcp_packet_sr_get_sender_info is not in any format I've seen before. To convert to a meaningful timestamp you have to use gst_rtcp_ntp_to_unix which then gives you a unix time that actually makes some sense.\n" ]
[ 0 ]
[]
[]
[ "amazon_kinesis_video_streams", "c++", "gstreamer", "rtcp" ]
stackoverflow_0074661696_amazon_kinesis_video_streams_c++_gstreamer_rtcp.txt
Q: JSDoc - How to assign a function as a property of another function Given the following, when I run jsdoc, the output does not show anything for the foo.bar property. /** * Foo */ const foo = function foo() { //... } /** * Bar */ foo.bar = function bar() { //... } How can I display bar as being a property on foo? A: There are a lot of possibilities to achieve this. The following are just a couple of them ... Use @memberof which is the tag identifies a member symbol that belongs to a parent symbol. /** * Foo */ const foo = function foo() { //... } /** * Bar * @memberof Foo */ foo.bar = function bar() { //... } Use @prop which is the tag to easily document a list of static properties of a class, namespace or other object. /** * Foo * @namespace * @property {object} bar - is this "bar" property? */ const foo = function foo() { //... } /** * Bar */ foo.bar = function bar() { //... } You may use @alias as well, it's all depend on what is your Foo and Bar; Are they objects, namespace, functions, properties, etc. I would suggest to read a bit on JSDoc documentation to get to know all the possibilities. A: here is a @typedef solution, with property comments // types.js /** * @typedef {(s: string) => number} _SomeFunction * convert string to number * * @typedef {Object} SomeProps * @property {number} someProp1 some property 1 * @property {string} someProp2 some property 2 * @property {(s: string) => number} someProp3 * some property 3 * * @typedef {_SomeFunction & SomeProps} SomeFunction */ /** @typedef {import("./types.js").SomeFunction} SomeFunction */ /** @type {SomeFunction} */ var f = s => s.length f.someProp1 = 1 f.someProp2 = "" f.someProp3 = s => (2 * s.length)
JSDoc - How to assign a function as a property of another function
Given the following, when I run jsdoc, the output does not show anything for the foo.bar property. /** * Foo */ const foo = function foo() { //... } /** * Bar */ foo.bar = function bar() { //... } How can I display bar as being a property on foo?
[ "There are a lot of possibilities to achieve this. The following are just a couple of them ... \n\nUse @memberof which is the tag identifies a member symbol that belongs to a parent symbol.\n/**\n * Foo\n */\nconst foo = function foo() {\n //...\n}\n\n/**\n * Bar\n * @memberof Foo\n */\nfoo.bar = function bar() {\n //...\n}\n\nUse @prop which is the tag to easily document a list of static properties of a class, namespace or other object.\n/**\n * Foo\n * @namespace\n * @property {object} bar - is this \"bar\" property?\n */\nconst foo = function foo() {\n //...\n}\n\n/**\n * Bar\n */\nfoo.bar = function bar() {\n //...\n}\n\n\nYou may use @alias as well, it's all depend on what is your Foo and Bar; Are they objects, namespace, functions, properties, etc. I would suggest to read a bit on JSDoc documentation to get to know all the possibilities.\n", "here is a @typedef solution, with property comments\n// types.js\n/**\n* @typedef {(s: string) => number} _SomeFunction\n* convert string to number\n*\n* @typedef {Object} SomeProps\n* @property {number} someProp1 some property 1\n* @property {string} someProp2 some property 2\n* @property {(s: string) => number} someProp3\n* some property 3\n*\n* @typedef {_SomeFunction & SomeProps} SomeFunction\n*/\n\n/** @typedef {import(\"./types.js\").SomeFunction} SomeFunction */\n\n/** @type {SomeFunction} */\nvar f = s => s.length\nf.someProp1 = 1\nf.someProp2 = \"\"\nf.someProp3 = s => (2 * s.length)\n\n" ]
[ 2, 0 ]
[]
[]
[ "jsdoc" ]
stackoverflow_0044146018_jsdoc.txt
Q: VSCode LaTeX pdf preview line finder? I am switching over from Overleaf to VSCode for offline LaTeX. Is there an extensions that lets you click on the pdf preview and highlights the line you clicked on in the .tex file? (just like the Overleaf feature) A: LaTex Workshop can do this. SyncTex is explained here. Note: you need Latex (e.g. MikTex) installed separatelly. It does not come with the extension. A: The Function is called inverse search (a.k.a. reverse search) you do not need an extension it is a PDF viewer function. For that matter you dont even need a TeX system as you could handball or program a suitable PDF(sync)TeX file without LaTeX but have only done that as a PoC, that its possible. Here I double clicked ABC in a system without any hint of LaTeX (but it could be say a portable copy if so desired) and the reverse search shows current line for that local TeX file I can direct as I wish to any editor with or without the line number. here is a simple test set in a zip for extract into a work folder So how does that work? PDF viewers that are PDF(sync)TeX aware can be primed in a PDF file by double click (easy) or some other key combination (often two handed shift key plus mouse). If the viewer spots there is an attendant pdfsync or synctex file alongside the compiled PDF they will launch a related call-back to the pre-configured text editor. That configuration only needs to be done ONCE not (as commonly done) every time :-( For example, in latex-workshop.view.pdf.external.synctex.args these two lines should NOT be needed if configured correctly "-reuse-instance", "-inverse-search", So, for example, If I have output.pdf and output.synctex and input.txt A double click in SumatraPDF will look at the synctex block entry for that area in the PDF which might be page 42 line 42 and will launch MS notepad to open the attendant text file (NOTE it can be any suitably compiled source file not just .tex) with those requests. Clearly MS Notepad would open the text file then grumble there is no such reference as it has no concept of pages or line numbers!! blithely would most likely try to open file 42. (I have in the past proven you can open Notepad and scroll to numbered line via VBS shim but that's not efficient, just proves that you only need any basic editor to work latex both ways.) However, if it was VSCode with LaTeX extension it could understand line numbers per page. So standalone viewers that are synctex aware include Acrobat (Portable for Linux/Windows=R9), Linux/Windows Evince, Win? Foxit, GNOME/Document viewer, Mac LivePDF, Linux/Windows Okular, Mac Skim, Win/Wine SumatraPDF, Win? Tracker/X-change, plus unknown others.
VSCode LaTeX pdf preview line finder?
I am switching over from Overleaf to VSCode for offline LaTeX. Is there an extensions that lets you click on the pdf preview and highlights the line you clicked on in the .tex file? (just like the Overleaf feature)
[ "LaTex Workshop can do this.\nSyncTex is explained here.\nNote: you need Latex (e.g. MikTex) installed separatelly. It does not come with the extension.\n", "The Function is called inverse search (a.k.a. reverse search) you do not need an extension it is a PDF viewer function. For that matter you dont even need a TeX system as you could handball or program a suitable PDF(sync)TeX file without LaTeX but have only done that as a PoC, that its possible.\nHere I double clicked ABC in a system without any hint of LaTeX (but it could be say a portable copy if so desired) and the reverse search shows current line for that local TeX file I can direct as I wish to any editor with or without the line number.\n\nhere is a simple test set in a zip for extract into a work folder\nSo how does that work?\nPDF viewers that are PDF(sync)TeX aware can be primed in a PDF file by double click (easy) or some other key combination (often two handed shift key plus mouse). If the viewer spots there is an attendant pdfsync or synctex file alongside the compiled PDF they will launch a related call-back to the pre-configured text editor.\nThat configuration only needs to be done ONCE not (as commonly done) every time :-(\nFor example, in latex-workshop.view.pdf.external.synctex.args these two lines should NOT be needed if configured correctly\n \"-reuse-instance\",\n \"-inverse-search\",\n\nSo, for example, If I have output.pdf and output.synctex and input.txt A double click in SumatraPDF will look at the synctex block entry for that area in the PDF which might be page 42 line 42 and will launch MS notepad to open the attendant text file (NOTE it can be any suitably compiled source file not just .tex) with those requests.\nClearly MS Notepad would open the text file then grumble there is no such reference as it has no concept of pages or line numbers!! blithely would most likely try to open file 42. (I have in the past proven you can open Notepad and scroll to numbered line via VBS shim but that's not efficient, just proves that you only need any basic editor to work latex both ways.)\nHowever, if it was VSCode with LaTeX extension it could understand line numbers per page.\nSo standalone viewers that are synctex aware include Acrobat (Portable for Linux/Windows=R9), Linux/Windows Evince, Win? Foxit, GNOME/Document viewer, Mac LivePDF, Linux/Windows Okular, Mac Skim, Win/Wine SumatraPDF, Win? Tracker/X-change, plus unknown others.\n" ]
[ 1, 1 ]
[]
[]
[ "latex", "miktex", "pdflatex", "visual_studio_code" ]
stackoverflow_0074653032_latex_miktex_pdflatex_visual_studio_code.txt
Q: Using TLS with SIM7080 (SIM7000) AT commands. How to deal with certificates I have a module with a sim7080 chip. I want to use NBIoT to send data via mqtt to my server. But as a first step I wanted to start with http. Sending HTTP Requests works pretty well. The problem occurs if using TLS. OK AT+CSSLCFG="convert",2,"mycert.crt" OK AT+SHSSL=1,"mycert.crt" OK AT+SHCONF="URL","https://test.test.eu" OK AT+SHCONF="BODYLEN",1024 OK AT+SHCONF="HEADERLEN",350 OK AT+SHCONN ERROR Is there a verbose mode to get more information what caused AT+SHCONN not to connect? HTTP is working fine. Maybe it is the format of the certificate? I downloaded the root ca of the website with Chrome as der certificate. Is this correct? May the windows \r\n be the problem? I set header and bodylength to the value from the examples. Probably I have to change here later to the real size of the header and body (how to figure that out?) Maybe so of you has a hint. Best regards A: You must upload your certificate to the module first (one time) before calling AT+CSSLCFG="convert",2,"mycert.crt" At least the .pem format works. AT+CMEE=2 gives verbose errors, but I am not sure if you get more information on this error The header and body length are max lengths, so those are not the cause of your issue. A: The HTTP commands aren't verbose, you can first try the TCP/UDP commands, which give more detailed errors when failing. When I tried the TCP/UDP commands, I got: AT+CAOPEN=0,0,"TCP","httpbin.org",443 +CAOPEN: 0,24 Where code 24 means certificate expired. Sometimes, the internal clock is wrong, then the certification fails because of the expiration date check. First, query the clock: AT+CCLK? You may get: +CCLK: "80/01/06,10:34:34+00" Which is totally wrong, as the year is 2080, and every certificate will be expired. Set the clock using: AT+CCLK="22/06/26,22:28:00-12" After this, there won't be code 24 anymore and it will connect. Next steps would be sometimes sync the clock using NTP or GNSS info. My sequence for HTTPS connection using TCP/UDP: AT+CNTPCID=0 AT+CNTP="pool.ntp.org",-12,0,0 AT+CNTP AT+CACID=0 AT+CSSLCFG="sslversion",0,3 AT+CASSLCFG=0,"SSL",1 AT+CASSLCFG=0,"CRINDEX",0 AT+CAOPEN=0,0,"TCP","httpbin.org",443,0 If there is an error, check your SIM chip. A: @giovanni-campaner was exactly right about the modem clock preventing connection. If you don't care to check the expiration validity of the server cert you can also use AT+CSSLCFG="ignorertctime",1,1 The next issue you'll run into is that some domains are hosted on machines that serve certificates for other domains. In that case you need to use Server Name Indication(SNI) to let the server know which certificate you're looking for. AT+CSSLCFG="sni",1,"mydomain.com" See my Gist for more details
Using TLS with SIM7080 (SIM7000) AT commands. How to deal with certificates
I have a module with a sim7080 chip. I want to use NBIoT to send data via mqtt to my server. But as a first step I wanted to start with http. Sending HTTP Requests works pretty well. The problem occurs if using TLS. OK AT+CSSLCFG="convert",2,"mycert.crt" OK AT+SHSSL=1,"mycert.crt" OK AT+SHCONF="URL","https://test.test.eu" OK AT+SHCONF="BODYLEN",1024 OK AT+SHCONF="HEADERLEN",350 OK AT+SHCONN ERROR Is there a verbose mode to get more information what caused AT+SHCONN not to connect? HTTP is working fine. Maybe it is the format of the certificate? I downloaded the root ca of the website with Chrome as der certificate. Is this correct? May the windows \r\n be the problem? I set header and bodylength to the value from the examples. Probably I have to change here later to the real size of the header and body (how to figure that out?) Maybe so of you has a hint. Best regards
[ "You must upload your certificate to the module first (one time) before calling AT+CSSLCFG=\"convert\",2,\"mycert.crt\"\nAt least the .pem format works.\nAT+CMEE=2 gives verbose errors, but I am not sure if you get more information on this error\nThe header and body length are max lengths, so those are not the cause of your issue.\n", "The HTTP commands aren't verbose, you can first try the TCP/UDP commands, which give more detailed errors when failing.\nWhen I tried the TCP/UDP commands, I got:\nAT+CAOPEN=0,0,\"TCP\",\"httpbin.org\",443\n+CAOPEN: 0,24\n\nWhere code 24 means certificate expired.\nSometimes, the internal clock is wrong, then the certification fails because of the expiration date check.\nFirst, query the clock:\nAT+CCLK?\nYou may get:\n+CCLK: \"80/01/06,10:34:34+00\"\nWhich is totally wrong, as the year is 2080, and every certificate will be expired.\nSet the clock using:\nAT+CCLK=\"22/06/26,22:28:00-12\"\nAfter this, there won't be code 24 anymore and it will connect.\nNext steps would be sometimes sync the clock using NTP or GNSS info.\nMy sequence for HTTPS connection using TCP/UDP:\nAT+CNTPCID=0\nAT+CNTP=\"pool.ntp.org\",-12,0,0\nAT+CNTP\n\nAT+CACID=0\nAT+CSSLCFG=\"sslversion\",0,3\nAT+CASSLCFG=0,\"SSL\",1\nAT+CASSLCFG=0,\"CRINDEX\",0\nAT+CAOPEN=0,0,\"TCP\",\"httpbin.org\",443,0\n\nIf there is an error, check your SIM chip.\n", "@giovanni-campaner was exactly right about the modem clock preventing connection. If you don't care to check the expiration validity of the server cert you can also use\nAT+CSSLCFG=\"ignorertctime\",1,1\n\nThe next issue you'll run into is that some domains are hosted on machines that serve certificates for other domains. In that case you need to use Server Name Indication(SNI) to let the server know which certificate you're looking for.\nAT+CSSLCFG=\"sni\",1,\"mydomain.com\"\n\nSee my Gist for more details\n" ]
[ 1, 1, 0 ]
[]
[]
[ "arduino", "micropython", "ssl" ]
stackoverflow_0064964823_arduino_micropython_ssl.txt
Q: PHP handler type for Wordpress I have a vps server (with Plesk Onyx) in which I have to install Wordpress, and I don't know which php manager is better. The site has a large number of entries, greater than 10,000. So I have to choose between these PHP handlers. Options If the information is useful, these are the statistics of my vps: vCPU: 2 core RAM : 2 GB SSD: 40 GB Multi-Core Geekbench Score: 991 Bandwidth: 2 TB Inode limit: 2 621 440 Dedicated IP Suport IPv4/IPv6 100 Mb/s network Total Access Root Currently the wordpress theme asks for these requirements: Requirement Which PHP handler provides the best performance? I have been using FPM application served by ngine. I understand that the connection that wordpress makes to the database should be a single one and when reviewing phpmyadmin it seems to be like that. But the CPU is permanently at 100% and I can't get it to go down. I removed plugins and placed cache, also cloudflare to handle the dangerous traffic, however with 500 users per hour the site destroys the database. A: Nginx and fpm. Hands down. If you can get the open litespeed server, that'll be even better for WordPress. 2GiB of RAM means you should use MariaDb 6 or better: those versions are smarter about using RAM efficiently, and 2GiB is constrained-RAM provisioning.
PHP handler type for Wordpress
I have a vps server (with Plesk Onyx) in which I have to install Wordpress, and I don't know which php manager is better. The site has a large number of entries, greater than 10,000. So I have to choose between these PHP handlers. Options If the information is useful, these are the statistics of my vps: vCPU: 2 core RAM : 2 GB SSD: 40 GB Multi-Core Geekbench Score: 991 Bandwidth: 2 TB Inode limit: 2 621 440 Dedicated IP Suport IPv4/IPv6 100 Mb/s network Total Access Root Currently the wordpress theme asks for these requirements: Requirement Which PHP handler provides the best performance? I have been using FPM application served by ngine. I understand that the connection that wordpress makes to the database should be a single one and when reviewing phpmyadmin it seems to be like that. But the CPU is permanently at 100% and I can't get it to go down. I removed plugins and placed cache, also cloudflare to handle the dangerous traffic, however with 500 users per hour the site destroys the database.
[ "Nginx and fpm. Hands down. If you can get the open litespeed server, that'll be even better for WordPress.\n2GiB of RAM means you should use MariaDb 6 or better: those versions are smarter about using RAM efficiently, and 2GiB is constrained-RAM provisioning.\n" ]
[ 0 ]
[]
[]
[ "database_performance", "performance", "php", "wordpress" ]
stackoverflow_0074661991_database_performance_performance_php_wordpress.txt