qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,554,142
|
<p>I was given a "simple" assignment and can't seem to get it to work and the docs are not helpful at all.</p>
<p>Assignment:</p>
<ol>
<li>create a POST function that receives a string and then returns the same string</li>
<li>create a static site (just an html form) that allows a user to submit a string which calls the above function.</li>
</ol>
<p>I have a Java function deployed in GCP now that works via Postman, but I get a 403 anytime I try to call it from my local static site.</p>
<p>For postman to work, I used the cloud shell command: <code>gcloud auth print-identity-token</code></p>
<p>I then took that token and put it in the Authorization Bearer Token header.</p>
<p>but, when I do that on the static site, I get the 403:</p>
<pre><code> fetch("https.myGoogleFunctionEndpoint.a.run.app", {
method: "POST",
mode: "no-cors",
headers: {
"Content-Type": "text/plain",
"Authorization": "Bearer [myToken]
},
body: "Working!!!"
})
.then(response => response.body)
.then(data => {
console.log("Success:", data);
})
.catch((error) => {
console.error("Error:", error);
});
</code></pre>
<p><strong>I cannot use --allow-unauthenticated btw. It must stay private.</strong></p>
<p>How do show that I am an authenticated user?</p>
<p>I did create a user in the Identity platform, and can run <a href="https://cloud.google.com/identity-platform/docs/use-rest-api#section-sign-in-email-password" rel="nofollow noreferrer">this command</a> in order to get an ID token... But cant find anywhere that tells me what I am to do with that token... Or if I am even going in the right direction! And this is all just to test it locally, I haven't even uploaded my HTML and JS files to the bucket nor have I set up the api gateway...</p>
<p>Any help would be greatly appreciated!</p>
<p>Here is the Java Fx btw:</p>
<pre><code>package gcfv2;
import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.HttpURLConnection;
public class HttpMethod implements HttpFunction {
@Override
public void service(HttpRequest request, HttpResponse response)
throws IOException {
BufferedWriter writer = response.getWriter();
switch (request.getMethod()) {
case "GET":
response.setStatusCode(HttpURLConnection.HTTP_OK);
writer.write("Hello world!");
break;
case "POST":
response.setStatusCode(HttpURLConnection.HTTP_OK);
response.setContentType("text/plain; charset=utf-8");
writer.write(request.getReader().readLine());
break;
default:
response.setStatusCode(HttpURLConnection.HTTP_BAD_METHOD);
writer.write("Something blew up!");
break;
}
}
}
</code></pre>
|
[
{
"answer_id": 74554399,
"author": "Bill",
"author_id": 4282847,
"author_profile": "https://Stackoverflow.com/users/4282847",
"pm_score": 2,
"selected": false,
"text": "randcomplex() = (c = Complex(rand(2)...); c / abs(c))\n\nrandcomplex(numwanted) = [randcomplex() for _ in 1:numwanted]\n randcomplex(dims...) = (a = zeros(Complex, dims...); for i in eachindex(a) a[i] = randcomplex() end; a)\n"
},
{
"answer_id": 74554548,
"author": "Dan Getz",
"author_id": 3580870,
"author_profile": "https://Stackoverflow.com/users/3580870",
"pm_score": 3,
"selected": true,
"text": "f1(n) = exp.((2*im*π).*rand(n))\n\nf2(n) = map(x->(z = x[1]+im*x[2] ; z ./ abs(z) ),\n eachcol(randn(2,n)))\n\nf3(n) = [im*x[1]+x[2] for x in sincos.(2π*rand(n))]\n\nf4(n) = cispi.(2 .*rand(n))\n julia> using BenchmarkTools\n\njulia> begin\n @btime f1(1_000);\n @btime f2(1_000);\n @btime f3(1_000);\n @btime f4(1_000);\n end;\n 29.390 μs (2 allocations: 23.69 KiB)\n 15.559 μs (2 allocations: 31.50 KiB)\n 25.733 μs (4 allocations: 47.38 KiB)\n 27.662 μs (2 allocations: 23.69 KiB)\n"
},
{
"answer_id": 74558067,
"author": "DNF",
"author_id": 2749865,
"author_profile": "https://Stackoverflow.com/users/2749865",
"pm_score": 2,
"selected": false,
"text": "function f5(n)\n r = rand(2, n)\n for i in 1:n\n a = sqrt(r[1, i]^2 + r[2, i]^2)\n r[1, i] /= a\n r[2, i] /= a\n end\n return reinterpret(reshape, ComplexF64, r)\nend\n\nusing LoopVectorization: @turbo\nfunction f5t(n)\n r = rand(2, n)\n @turbo for i in 1:n\n a = sqrt(r[1, i]^2 + r[2, i]^2)\n r[1, i] /= a\n r[2, i] /= a\n end\n return reinterpret(reshape, ComplexF64, r)\nend\n\njulia> @btime f5(1000);\n 4.186 μs (1 allocation: 15.75 KiB)\n\njulia> @btime f5t(1000);\n 2.900 μs (1 allocation: 15.75 KiB)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74554142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12380096/"
] |
74,554,147
|
<p>Consider the following structure called <code>x</code> whose output is a vector in R:</p>
<pre><code>> x
A
A
A
B
B
C
</code></pre>
<p>I'd like to use <code>split</code> to split <code>x</code> into 3 groups A, B, and C where A has 3 elements, B has 2, and C has 1.</p>
<p>What should the grouping factor argument, <code>f</code>, be in <code>split()</code>?</p>
<p>The above is a trivial example. My structure is much larger.</p>
<p>My real example consists of FASTA headers where multiple DNA sequences correspond to the same species and I need to split according to species. However, the species name occurs in the header like this:</p>
<pre><code>">COLFG678-14|MZ630002|Agabus|adpressus|AEC6988|COI-5P"
</code></pre>
<p>Here the species is <em>Agabus adpressus</em>.</p>
<p>As I am unsure of the most appropriate output at this stage, it could look like</p>
<pre><code>$`Agabus adpressus`
Seq1
Seq2
Seq3
</code></pre>
|
[
{
"answer_id": 74554318,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 2,
"selected": true,
"text": "vals <- c(\">COLFG678-14|MZ630002|Agabus|adpressus|AEC6988|COI-5P\",\n \">CZLFG631-11|MZ730009|Agabus|adpressus|BSF8945|AOL-5N\",\n \">XOLGG558-12|MK630011|Agabus|adpressus|JLD6018|CVI-1P\",\n \">YPLFG578-81|JF830122|Agabus|ajax|XCV0091|CMM-1N\",\n \">CLVFG679-13|KA301202|Agabus|ajax|FFP1111|AND-5Z\")\n\n\nsplit(vals, sub(\"(?:(.*)\\\\|){2}(\\\\w+)\\\\|(\\\\w+)\\\\|.*?$\", \"\\\\1-\\\\2\", vals))\n#> $`Agabus-adpressus`\n#> [1] \">COLFG678-14|MZ630002|Agabus|adpressus|AEC6988|COI-5P\"\n#> [2] \">CZLFG631-11|MZ730009|Agabus|adpressus|BSF8945|AOL-5N\"\n#> [3] \">XOLGG558-12|MK630011|Agabus|adpressus|JLD6018|CVI-1P\"\n#> \n#> $`Agabus-ajax`\n#> [1] \">YPLFG578-81|JF830122|Agabus|ajax|XCV0091|CMM-1N\"\n#> [2] \">CLVFG679-13|KA301202|Agabus|ajax|FFP1111|AND-5Z\"\n"
},
{
"answer_id": 74554685,
"author": "onyambu",
"author_id": 8380272,
"author_profile": "https://Stackoverflow.com/users/8380272",
"pm_score": 2,
"selected": false,
"text": "read.table(text = vals, sep='|')|>\n split(~paste(V3,V4))|>\n map(~invoke(str_c, .x, sep='|'))\n\n$`Agabus adpressus`\n[1] \">COLFG678-14|MZ630002|Agabus|adpressus|AEC6988|COI-5P\"\n[2] \">CZLFG631-11|MZ730009|Agabus|adpressus|BSF8945|AOL-5N\"\n[3] \">XOLGG558-12|MK630011|Agabus|adpressus|JLD6018|CVI-1P\"\n\n$`Agabus ajax`\n[1] \">YPLFG578-81|JF830122|Agabus|ajax|XCV0091|CMM-1N\"\n[2] \">CLVFG679-13|KA301202|Agabus|ajax|FFP1111|AND-5Z\"\n group_by"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74554147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8183972/"
] |
74,554,158
|
<p>We post a message to a slack channel every time a customer does a specific task. We want to change the bot Icon based on what is being posted in the channel.</p>
<p>Is this possible?</p>
<pre><code>public static function send_to_slack($message,$title = null){
$body = array();
$body['text'] = '';
$body['icon_url'] = '';
if(!empty($title)) $body['text'] .= "*$title*\n";
$body['text'] .= $message;
$iconURL = "https://img.icons8.com/emoji/96/000000/penguin--v2.png";
$body['icon_url'] .= $iconURL;
$json = json_encode($body);
//Test Slack Channel
$slack = "SLACKURL"
$response = wp_remote_post( $slack, array(
'method' => 'POST',
'body' => $json,
)
);
if ( is_wp_error( $response ) ) {
return true;
} else {
return true;
}
}
</code></pre>
|
[
{
"answer_id": 74554459,
"author": "user16034511",
"author_id": 16034511,
"author_profile": "https://Stackoverflow.com/users/16034511",
"pm_score": 0,
"selected": false,
"text": " public static function send_to_slack($message,$title = null){\n\n $ch = curl_init(\"https://slack.com/api/chat.postMessage\");\n $data = http_build_query([\n \"token\" => \"BOT-TOKEN\",\n \"channel\" => \"CHANNELID\", //\"#mychannel\",\n \"text\" => $message, //\"Hello, Foo-Bar channel message.\",\n \"username\" => \"MySlackBot\",\n \"icon_url\" => $iconURL\n ]);\n curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');\n curl_setopt($ch, CURLOPT_POSTFIELDS, $data);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\n curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);\n $result = curl_exec($ch);\n curl_close($ch);\n\n return $result;\n\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74554158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16034511/"
] |
74,554,167
|
<p>I have the following object with a set of colors for each shape:</p>
<pre><code>const design = {
designId: 1,
shapes: [
{ shapeId: 'basic-square', color: { r: 255, g: 255, b: 255 }},
{ shapeId: 'basic-circle', color: { r: 255, g: 255, b: 255 }},
{ shapeId: 'basic-diamond', color: { r: 255, g: 0, b: 0 }},
{ shapeId: 'basic-rectangle', color: { r: 0, g: 255, b: 0 }}
]
}
</code></pre>
<p>I want to return the following output which computes the average of each color per design object:</p>
<blockquote>
<p>Design 1: {r: 191.25, g: 191.25, b: 127.5 }</p>
</blockquote>
<p>Keeping in mind Big O, what's the an efficient way to solve this problem?</p>
<p>Here is my attempt, however I was told it was not efficient enough:</p>
<pre><code>const average = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length;
const { shapes } = design;
const reds = shapes.map(shape => shape.color.r)
const greens = shapes.map(shape => shape.color.g)
const blues = shapes.map(shape => shape.color.b)
console.log(`Design ${design.designId}: {r: ${average(reds)}, g: ${average(greens)}, b: ${average(blues)} }`)
</code></pre>
|
[
{
"answer_id": 74554238,
"author": "symlink",
"author_id": 818326,
"author_profile": "https://Stackoverflow.com/users/818326",
"pm_score": 0,
"selected": false,
"text": "Array.map() average() const design = {\n designId: 1,\n shapes: [\n { shapeId: 'basic-square', color: { r: 255, g: 255, b: 255 }},\n { shapeId: 'basic-circle', color: { r: 255, g: 255, b: 255 }},\n { shapeId: 'basic-diamond', color: { r: 255, g: 0, b: 0 }},\n { shapeId: 'basic-rectangle', color: { r: 0, g: 255, b: 0 }}\n ]\n };\n\n//Design 1: {r: 191.25, g: 191.25, b: 127.5 }\n\nfunction average(color) {\n let result = 0;\n for(let i=0; i<design.shapes.length; i++) {\n result += design.shapes[i].color[color]\n }\n return result / design.shapes.length;\n}\n\nconsole.log(`Design ${design.designId}: {r: ${average('r')}, g: ${average('g')}, b: ${average('b')} }`)"
},
{
"answer_id": 74554280,
"author": "pilchard",
"author_id": 13762301,
"author_profile": "https://Stackoverflow.com/users/13762301",
"pm_score": 1,
"selected": false,
"text": "reduce() for const design = {\n designId: 1,\n shapes: [\n { shapeId: 'basic-square', color: { r: 255, g: 255, b: 255 } },\n { shapeId: 'basic-circle', color: { r: 255, g: 255, b: 255 } },\n { shapeId: 'basic-diamond', color: { r: 255, g: 0, b: 0 } },\n { shapeId: 'basic-rectangle', color: { r: 0, g: 255, b: 0 } }\n ]\n}\n\nconst sums = { r: 0, g: 0, b: 0 };\nfor (const { color: { r, g, b } } of design.shapes) {\n sums.r += r\n sums.g += g;\n sums.b += b;\n}\n\nconst len = design.shapes.length;\nconst result = {\n [`Design ${design.designId}`]: {\n r: sums.r / len,\n g: sums.g / len,\n b: sums.b / len\n }\n}\n\nconsole.log(result);"
},
{
"answer_id": 74554310,
"author": "Melchia",
"author_id": 8011544,
"author_profile": "https://Stackoverflow.com/users/8011544",
"pm_score": 3,
"selected": true,
"text": "const design = {\n designId: 1,\n shapes: [\n { shapeId: 'basic-square', color: { r: 255, g: 255, b: 255 }},\n { shapeId: 'basic-circle', color: { r: 255, g: 255, b: 255 }},\n { shapeId: 'basic-diamond', color: { r: 255, g: 0, b: 0 }},\n { shapeId: 'basic-rectangle', color: { r: 0, g: 255, b: 0 }}\n ]\n };\n\nconst { shapes, designId } = design;\n\nconst average = shapes.reduce((acc, curr) => ({\n red: acc.red + curr.color.r / shapes.length,\n green: acc.green + curr.color.g / shapes.length,\n blue: acc.blue + curr.color.b / shapes.length\n }), {\n red: 0, green: 0, blue: 0\n }\n );\n\n\n\nconsole.log(`Design ${designId}: {r: ${average.red}, g: ${average.green}, b: ${average.blue}`)"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74554167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20547034/"
] |
74,554,191
|
<p>I know this sounds a bit stupid but I am extending a text-based game and I'm trying to figure out a way to print out the items that are in the room. I have made an arrayList for the room and added and "Item" into it by using a separate class called Item.</p>
<pre><code>import java.util.ArrayList;
import java.util.List;
public class Item
{
private String itemName;
private Boolean pickUp;
private Integer itemWeight;
/**
* Constructor for objects of class Items
*/
public Item(String itemName, Boolean pickUp, Integer itemWeight)
{
this.itemName = itemName;
this.pickUp = pickUp;
this.itemWeight = itemWeight;
}
/**
* Returns the name of the item
*/
public String getItemName()
{
return itemName;
}
/**
* Returns the pickUp ability of the item
*/
public Boolean getPickUp()
{
return pickUp;
}
/**
* Returns the weight of the item
*/
public Integer getItemWeight()
{
return itemWeight;
}
}
</code></pre>
<p>The part I'm stuck on now is printing those elements out when entering the room. Theres a function in the code that keeps track of the current room and I am trying to use that function to then print out the elements of that corresponding rooms arrayList. Each room in the game is an object from the "Room" class.</p>
<pre><code>public class Room {
private String description;
private String listName;
private HashMap<String, Room> exits; // stores exits of this room.
public Room(String description, String listName)
{
this.description = description;
this.listName = listName;
exits = new HashMap<>();
}
public String getListName()
{
return listName;
}
private void createRooms()
{
Room playground, assemblyHall, groundHallway, lunchHall, ITRoom, groundToilets, headteacherOffice, footballCage, stairs, groundClassroom, firstFloorClassroom, exitGate;
// create the rooms
assemblyHall = new Room("in the assembly hall", "assemblyHallList");
playground = new Room("in the main playground of the school", "playgroundList");
.......
currentRoom = assemblyHall;
ArrayList<Item> assemblyHallList = new ArrayList<Item>();
assemblyHallList.add(new Item("Piece of paper", true, 1));
</code></pre>
<p>These last 2 lines are an example of what I will be doing for every room with more items. I feel like I am going about this the wrong way but this was the only idea I had. The problem I have is printing out the elements when I enter a room as I would need to call on the method to get the name of the arrayList then use that name to then access the list and print out the elements in it but I have no idea how to use the string to accesss the array as I would have to use</p>
<pre><code>currentRoom.getListName()
</code></pre>
<p>to get the name of the list but when I try to print it out it prints the name itself, not the elements. Any help is appreciated and I can send more parts of the class if needed. Didn't include it all as its very big and a lot of it is irrelevant to my problem</p>
|
[
{
"answer_id": 74554324,
"author": "f1sh",
"author_id": 214525,
"author_profile": "https://Stackoverflow.com/users/214525",
"pm_score": 0,
"selected": false,
"text": "ArrayList<Item> assemblyHallList Room assemblyHall = new Room(\"in the assembly hall\", \"assemblyHallList\");\n String listName assemblyHallList createRooms List<Item> assemblyHallList = ...;\nRoom assemblyHall = new Room(\"in the assembly hall\", assemblyHallList);\n listName List<Item>"
},
{
"answer_id": 74554361,
"author": "Metahuman Flash",
"author_id": 14694240,
"author_profile": "https://Stackoverflow.com/users/14694240",
"pm_score": 2,
"selected": true,
"text": "static Hashmap<String, ArrayList<Item>> ArrayList<Item> items = new ArrayList<>();\nitems.add(new Item(\"Piece of paper\", true, 1));\nRoom room = new Room(\"best room\", items);\n public class Room {\n private String description;\n private ArrayList<Item> items;\n private HashMap<String, Room> exits;\n\n public Room(String description, ArrayList<Item> items) \n {\n this.description = description;\n this.items = items;\n exits = new HashMap<>();\n }\n\n // Other members not shown\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74554191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12178509/"
] |
74,554,198
|
<p>I am trying to empty the database of any data, while keeping the relationships and tables as they are</p>
<p>I have no idea if my thinking is right or wrong</p>
|
[
{
"answer_id": 74554324,
"author": "f1sh",
"author_id": 214525,
"author_profile": "https://Stackoverflow.com/users/214525",
"pm_score": 0,
"selected": false,
"text": "ArrayList<Item> assemblyHallList Room assemblyHall = new Room(\"in the assembly hall\", \"assemblyHallList\");\n String listName assemblyHallList createRooms List<Item> assemblyHallList = ...;\nRoom assemblyHall = new Room(\"in the assembly hall\", assemblyHallList);\n listName List<Item>"
},
{
"answer_id": 74554361,
"author": "Metahuman Flash",
"author_id": 14694240,
"author_profile": "https://Stackoverflow.com/users/14694240",
"pm_score": 2,
"selected": true,
"text": "static Hashmap<String, ArrayList<Item>> ArrayList<Item> items = new ArrayList<>();\nitems.add(new Item(\"Piece of paper\", true, 1));\nRoom room = new Room(\"best room\", items);\n public class Room {\n private String description;\n private ArrayList<Item> items;\n private HashMap<String, Room> exits;\n\n public Room(String description, ArrayList<Item> items) \n {\n this.description = description;\n this.items = items;\n exits = new HashMap<>();\n }\n\n // Other members not shown\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74554198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18595527/"
] |
74,554,229
|
<p>I have a large image centered like this:
<a href="https://i.stack.imgur.com/xDX4Y.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xDX4Y.jpg" alt="enter image description here" /></a></p>
<p>I want to image to bleed with a blur on the sides like this:</p>
<p><a href="https://i.stack.imgur.com/sLGPf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sLGPf.png" alt="enter image description here" /></a></p>
<p>Is this possible?
Also, is there a particular term used to describe what I want?</p>
<p>I tried adding a background image and blurring that, but then I realized that just blurs everything. I don't know what else to do.</p>
|
[
{
"answer_id": 74555067,
"author": "Ethan Anderson",
"author_id": 19455904,
"author_profile": "https://Stackoverflow.com/users/19455904",
"pm_score": 2,
"selected": true,
"text": "import './App.css'\n\nexport default function App() {\n return (\n <main>\n <div className='container'>\n {/* ORDERING MATTERS!! */}\n <img className='bleed-blur' src='https://static.vecteezy.com/packs/media/vectors/term-bg-1-666de2d9.jpg' />\n <img className='main-image' src='https://static.vecteezy.com/packs/media/vectors/term-bg-1-666de2d9.jpg' />\n\n\n </div>\n </main>\n )\n}\n .bleed-blur{\n /* required to stack images on top of each other */\n position: absolute;\n\n /* blur effect */\n filter: blur(10px);\n\n /* the size will be relative to the container */\n width: inherit;\n height: inherit;\n}\n\n.container{\n /* will cause other content will not be adjusted to fit into any \n gap left by the element */\n position: relative;\n\n /* you may want to adjust the sizing to your liking*/\n width: 100%;\n height: 50vh; \n\n /* center images within container */\n display: flex;\n justify-content: center;\n align-items: center;\n}\n\n.main-image{\n /* required to stack images on top of each other */\n position: absolute;\n\n /* the size will be relative to the container */\n width: inherit;\n height: inherit;\n\n /* you can change this if you need to, but might cuase issues. \n Although, `scale-down` seems to work well*/\n object-fit: contain;\n}\n .bleed-blur object-fit: contain .bleed-blur{\n /* required to stack images on top of each other */\n position: absolute;\n\n /* blur effect */\n filter: blur(10px);\n\n /* the size will be relative to the container */\n width: inherit;\n height: inherit;\n\n /* you can change this if you need to, but might cuase issues. \n Although, `scale-down` seems to work well*/\n object-fit: cover;\n}\n"
},
{
"answer_id": 74555502,
"author": "Ilham Nopi Hendri",
"author_id": 14158852,
"author_profile": "https://Stackoverflow.com/users/14158852",
"pm_score": 2,
"selected": false,
"text": "*,\n*::before,\n*::after{\n padding:0;\n margin:0;\n box-sizing:border-box;\n}\n.wrapper{\n width:100%;\n height:100vh;\n position:relative;\n background:#000;\n}\n\n.bg{\n position:absolute;\n width:100%;\n height:100%;\n left:0px;\n top:0px;\n right:0px;\n bottom:0px;\n background-image:url(\"https://static.vecteezy.com/packs/media/vectors/term-bg-1-666de2d9.jpg\");\n background-repeat: no-repeat;\n background-size:cover;\n background-position:center;\n display:flex;\n justify-content:center;\n align-item:center;\n overflow:hidden;\n filter: blur(14px);\n overflow:hidden;\n}\nfigure{\n position:absolute;\n top:0;\n bottom:0;\n right:50%;\n transform:translate(50%);\n overflow:hidden;\n width:70%;\n}\nimg{\n width:100%;\n height:100%;\n object-fit:cover;\n object-position: center;\n} <header>\n <div class=\"wrapper\">\n <div class=\"bg\">\n </div> \n <figure>\n <img src=\"https://static.vecteezy.com/packs/media/vectors/term-bg-1-666de2d9.jpg\" />\n </figure>\n </div>\n</header>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19455904/"
] |
74,554,237
|
<p>I'm trying to get the nested values from my locally stored json file with Flutter.</p>
<p>I can get the "outer" values, but I haven't been able to get the "inner" ones. I have googled and searched here, but I still can't make it work, so any help is much appreciated.</p>
<p>I put the code in a sandbox to make it easier to see.
<a href="https://codesandbox.io/s/loving-thunder-meklbc?file=/lib/main.dart" rel="nofollow noreferrer">https://codesandbox.io/s/loving-thunder-meklbc?file=/lib/main.dart</a></p>
<p>If you rather look here this is what some files look like:</p>
<p>json:</p>
<pre><code>[{
"id":184423,
"created":"2022-11-18T09:32:56.000Z",
"raw_data":[
{"measurement_id":18,"index":0,"substance":655,"pressure":20,"temperature":30.03},
{"measurement_id":18,"index":1,"substance":648,"pressure":38,"temperature":30.03},
{"measurement_id":18,"index":2,"substance":636,"pressure":90,"temperature":30.02},
{"measurement_id":18,"index":3,"substance":623,"pressure":130,"temperature":30.05},
{"measurement_id":18,"index":4,"substance":598,"pressure":147,"temperature":29.99}
]
},
{
"id":184423,
"created":"2022-11-19T09:32:56.000Z",
"raw_data":[
{"measurement_id":19,"index":0,"substance":586,"pressure":160,"temperature":30.05},
{"measurement_id":19,"index":1,"substance":564,"pressure":170,"temperature":29.99},
{"measurement_id":19,"index":2,"substance":553,"pressure":173,"temperature":30},
{"measurement_id":19,"index":3,"substance":544,"pressure":162,"temperature":30.02},
{"measurement_id":19,"index":4,"substance":538,"pressure":164,"temperature":30.01}
]
}
]
</code></pre>
<p>handler:</p>
<pre><code>import 'dart:convert';
import 'package:flutter/services.dart' as rootbundle;
import '../model/usermodel.dart';
Future<List<UserModel>> readJsonData() async {
final jsondata = await rootbundle.rootBundle.loadString('/userdata.json');
final list = json.decode(jsondata) as List<dynamic>;
//print(list);
return list.map((e) => UserModel.fromJson(e)).toList();
}
</code></pre>
<p>model:</p>
<pre><code>// ignore_for_file: non_constant_identifier_names
class UserModel {
late int? id, measurementId, index, substance, pressure;
late double? temperature;
UserModel(
this.id,
this.measurementId,
this.index,
this.substance,
this.pressure,
this.temperature,
);
UserModel.fromJson(Map<String, dynamic> json) {
id = json["id"];
measurementId = json['measurement_id'];
index = json['index'];
substance = json['substance'];
pressure = json['pressure'];
temperature = json['temperature'];
}
}
</code></pre>
|
[
{
"answer_id": 74554307,
"author": "Amarghosh",
"author_id": 165297,
"author_profile": "https://Stackoverflow.com/users/165297",
"pm_score": 1,
"selected": false,
"text": "List<UserModel> models = [];\nfor (var item in list) {\n models.addAll(item.map((e) => UserModel.fromJson(e['id'], e['raw_data'])));\n}\nreturn models;\n\nUserModel.fromJson(int id, Map<String, dynamic> json) {\n this.id = id; // parse json (raw_data)\n}\n"
},
{
"answer_id": 74554706,
"author": "Soliev",
"author_id": 19945688,
"author_profile": "https://Stackoverflow.com/users/19945688",
"pm_score": 3,
"selected": true,
"text": "\nclass UserModel {\n UserModel(this.id, this.raw_data);\n\n /// Creates a UserModel from Json map\n factory UserModel.fromJson(Map<String, dynamic> json) => UserModel(\n json['id'] as int?,\n (json['raw_data'] as List<dynamic>?)\n ?.map((e) => Data.fromJson(e as Map<String, dynamic>))\n .toList(),\n );\n\n final int? id;\n final List<Data>? raw_data;\n}\n\n//Data \n\nclass Data {\n Data(\n this.measurement_id,\n this.index,\n this.substance,\n this.pressure,\n this.temperature,\n );\n\n final int? measurement_id;\n final int? index;\n final int? substance;\n final int? pressure;\n final double? temperature;\n\n /// Creates a Data from Json map\n factory Data.fromJson(Map<String, dynamic> json) => Data(\n json['measurement_id'] as int?,\n json['index'] as int?,\n json['substance'] as int?,\n json['pressure'] as int?,\n (json['temperature'] as num?)?.toDouble(),\n );\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13867582/"
] |
74,554,246
|
<p>I'am trying to do a mobile app which is about crypto currencies.</p>
<p>I want to make two <code>TextFields</code> like USDT and BTC, And they are supposed to work like:</p>
<p>Let me say that BTC is equal to 15$,</p>
<p>And USDT is equal to 1$,</p>
<p>Now those text fields should be editable. so if I write 1 on BTC textfield, USDT textfield should me edited as 15.</p>
<p>Also, when I write 30 on USDT textfield, BTC field should become 2. Moreover, while in this position, if I delete 0 from the usdt field, BTC should updated with "0.something" directly.</p>
<p>How can I do that?</p>
<p>Thanks for the replies !</p>
<blockquote>
<p>I managed to do something like USDT is input, and BTC is output. However, I want to make them both input and output. Below are my classes, widgets and codes.</p>
</blockquote>
<pre><code>import 'package:cryptx/Constants/app_colors.dart';
import 'package:cryptx/Providers/basic_providers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class USDTInput extends ConsumerWidget {
const USDTInput({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: TextField(
decoration: InputDecoration(
icon: SizedBox(
height: 30,
child: Image.network(
"https://assets.coingecko.com/coins/images/325/small/Tether.png?1668148663")),
hintText: "USDT",
border: InputBorder.none,
),
onChanged: (value) {
ref
.read(usdProvider.notifier)
.update((state) => value != "" ? num.parse(value) : 0);
},
autocorrect: false,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
),
);
}
}
</code></pre>
<pre><code>import 'package:cryptx/Objects/coin.dart';
import 'package:cryptx/Providers/basic_providers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class CoinOutput extends ConsumerWidget {
const CoinOutput({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
Coin coin = ref.watch(coinDetailProvider) as Coin;
num usd = ref.watch(usdProvider);
num amount = usd != 0 ? usd / coin.current_price : 0;
//return Text(amount.toString());
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: TextField(
decoration: InputDecoration(
icon: SizedBox(height: 30, child: Image.network(coin.image)),
hintText: "Coin",
border: InputBorder.none,
),
controller:
TextEditingController(text: "$amount ${coin.symbol.toUpperCase()}"),
readOnly: true,
autocorrect: false,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
onChanged: (value) {
ref.watch(coin_usdProvider.notifier).update((state) =>
value != "" ? num.parse(value) / coin.current_price : 0);
},
),
);
}
}
</code></pre>
|
[
{
"answer_id": 74554373,
"author": "JerZaw",
"author_id": 15973134,
"author_profile": "https://Stackoverflow.com/users/15973134",
"pm_score": 1,
"selected": false,
"text": "void updateValues(float BTC, var USDT)\n FocusNode TextFields onChanged FocusNode"
},
{
"answer_id": 74554707,
"author": "baek",
"author_id": 1049200,
"author_profile": "https://Stackoverflow.com/users/1049200",
"pm_score": 1,
"selected": true,
"text": "import 'package:flutter/material.dart';\n\nconst Color darkBlue = Color.fromARGB(255, 18, 32, 47);\n\nvoid main() {\n runApp(MyApp());\n}\n\nclass MyApp extends StatefulWidget {\n @override\n State<MyApp> createState() => _MyAppState();\n}\n\nclass _MyAppState extends State<MyApp> {\n final btcTextController = TextEditingController();\n final usdtTextController = TextEditingController();\n final btcFocusNode = FocusNode();\n final usdtFocusNode = FocusNode();\n double btcValue = 15; \n double usdTValue = 1; \n\n String curSelection = \"\";\n\n @override\n void initState() {\n btcTextController.addListener(calcBTC);\n usdtTextController.addListener(calcUSDT);\n super.initState();\n }\n\n void calcBTC() {\n if (btcFocusNode.hasFocus) {\n usdtTextController.clear();\n if (btcTextController.text.isNotEmpty &&\n double.tryParse(btcTextController.text) != null) {\n setState(() {\n usdtTextController.text =\n (double.parse(btcTextController.text) * (btcValue / usdTValue))\n .toString();\n });\n }\n }\n }\n\n void calcUSDT() {\n if (usdtFocusNode.hasFocus) {\n btcTextController.clear();\n if (usdtTextController.text.isNotEmpty &&\n double.tryParse(usdtTextController.text) != null) {\n setState(() {\n btcTextController.text =\n (double.parse(usdtTextController.text) * (usdTValue / btcValue))\n .toString();\n });\n }\n }\n }\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n theme: ThemeData.dark().copyWith(\n scaffoldBackgroundColor: darkBlue,\n ),\n debugShowCheckedModeBanner: false,\n home: Scaffold(\n body: Center(\n child: Card(\n color: Colors.white,\n shape:\n RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),\n elevation: 4,\n child: Container(\n margin: const EdgeInsets.all(10),\n width: 300,\n height: 300,\n child: Column(\n children: [\n Expanded(\n child: TextField(\n style: const TextStyle(color: Colors.black),\n controller: btcTextController,\n focusNode: btcFocusNode,\n decoration: InputDecoration(\n filled: true,\n fillColor: Colors.blue.shade100,\n labelText: 'BTC',\n labelStyle: const TextStyle(color: Colors.pink),\n border: OutlineInputBorder(\n borderRadius: BorderRadius.circular(10),\n borderSide: BorderSide.none,\n )),\n ),\n ),\n Expanded(\n child: TextField(\n style: const TextStyle(color: Colors.black),\n controller: usdtTextController,\n focusNode: usdtFocusNode,\n decoration: InputDecoration(\n \n filled: true,\n fillColor: Colors.blue.shade100,\n labelText: 'USDT',\n labelStyle: const TextStyle(color: Colors.pink),\n border: OutlineInputBorder(\n borderRadius: BorderRadius.circular(10),\n borderSide: BorderSide.none,\n )),\n )),\n ],\n ),\n ),\n ),\n ),\n ),\n );\n }\n}\n\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20277639/"
] |
74,554,248
|
<p>Reading through the URI syntax description (<a href="https://www.rfc-editor.org/rfc/rfc3986" rel="nofollow noreferrer">RFC 3986</a>) and trying to understand what their syntax descriptions mean.</p>
<p>For example, a URI has to have a schema part, which is restricted by the following syntax description:</p>
<pre><code>scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
</code></pre>
<p>But the specification never tells you what * ( and / mean. Anything in quotations seems to mean exactly that character and ALPHA and DIGIT are seemingly the sets of ASCII characters pertaining to the alphanumeric set. I am guessing / is an or, ( may be a group, and * may be 0 or more. But it is not clarified in the specification.</p>
<p>There are other syntax descriptions like:</p>
<pre><code>URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
</code></pre>
<p>I am also guessing the [ means that part is optional.</p>
<p>Does anybody know if my interpretation is correct? And would you be able to point me to the RFC specification of these characters?</p>
|
[
{
"answer_id": 74554274,
"author": "Daniel A. White",
"author_id": 23528,
"author_profile": "https://Stackoverflow.com/users/23528",
"pm_score": 2,
"selected": true,
"text": "/ *"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10821861/"
] |
74,554,255
|
<p>I am trying to use pandas to select some data from an Oracle database. The column in question has the data type <code>TIMESTAMP(6) WITH TIME ZONE</code>. I am in the same time zone as the database, but it contains data that is recorded from a different time zone.</p>
<pre><code>Oracle version: Oracle Database 12c Enterprise Edition Release 12.2.0.1.0 - 64bit Production
Python 3.8.13
SQLAlchemy 1.4.39
cx_Oracle 8.3.0
</code></pre>
<p>In PL/SQL Developer, the query works:</p>
<pre><code>SELECT col
FROM table
</code></pre>
<p>Returns</p>
<pre><code>18-JAN-21 09.54.58.000000000 PM ASIA/BANGKOK
</code></pre>
<p>In Python, I get this error:</p>
<pre><code>import sqlalchemy
import cx_Oracle
server = server
port = port
sid = sid
username = username
password = password
dsn_tns = cx_Oracle.makedsn(server, port, sid)
cnxn = cx_oracle.connect(username, password, dsn_tns)
query = """
SELECT col
FROM table
"""
df = pd.read_sql_query(query, cnxn)
</code></pre>
<p>Output:</p>
<pre><code>DatabaseError: ORA-01805: possible error in date/time operation
</code></pre>
<p>After <a href="https://stackoverflow.com/questions/67090102/oracle-db-query-with-different-time-zones">some SO searching</a>, I tried this:</p>
<pre><code>query = """
SELECT CAST(TO_TIMESTAMP_TZ(
col,
'DD-MMM-YY HH.MI.SS.FF6 TZH TZR')
) AT TIME ZONE 'ASIA/BANGKOK' AS col
FROM table
"""
df = pd.read_sql_query(query, cnxn_tds_dev)
</code></pre>
<p>Which returns a different error message:</p>
<pre><code>ORA-00905: missing keyword
</code></pre>
<p>How can I just select this timestamp column (and several others) using Python/SQLAlchemy/cx_Oracle? Because the query works in PL/SQL Developer, I am assuming it is an issue with cx_Oracle. I will try creating a new Python environment with an older version of cx_Oracle, per <a href="https://stackoverflow.com/questions/7678485/oracle-ora-01805-on-oracle-11g-database/">this post</a>.</p>
|
[
{
"answer_id": 74554727,
"author": "Christopher Jones",
"author_id": 4799035,
"author_profile": "https://Stackoverflow.com/users/4799035",
"pm_score": 1,
"selected": false,
"text": "# create table t (c TIMESTAMP(6) WITH TIME ZONE);\n# insert into t (c) values (systimestamp);\n# commit;\n#\n# Name: pandas\n# Version: 1.5.2\n# Name: SQLAlchemy\n# Version: 1.4.44\n# Name: cx-Oracle\n# Version: 8.3.0\n#\n# Output is like:\n# 0 2022-11-24 11:49:25.505773\n\nimport os\nimport platform\n\nfrom sqlalchemy import create_engine\nimport pandas as pd\n\nimport cx_Oracle\n\nif platform.system() == \"Darwin\":\n cx_Oracle.init_oracle_client(lib_dir=os.environ.get(\"HOME\")+\"/Downloads/instantclient_19_8\")\n\nusername = os.environ.get(\"PYTHON_USERNAME\")\npassword = os.environ.get(\"PYTHON_PASSWORD\")\nconnect_string = os.environ.get(\"PYTHON_CONNECTSTRING\")\nhostname, service_name = connect_string.split(\"/\")\n\nengine = create_engine(f'oracle://{username}:{password}@{hostname}/?service_name={service_name}')\n\nquery = \"\"\"select * from t\"\"\"\ndf = pd.read_sql_query(query, engine)\nprint(df)\n"
},
{
"answer_id": 74562590,
"author": "Evan",
"author_id": 6672746,
"author_profile": "https://Stackoverflow.com/users/6672746",
"pm_score": 0,
"selected": false,
"text": "query = \"SELECT TO_CHAR(col) AS col FROM table\"\ndf = pd.read_sql_query(query, cnxn)\ndf[col] = df[col].apply(pd.to_datetime, format=\"%d-%b-%y %I.%M.%S.%f %p %Z\")\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6672746/"
] |
74,554,287
|
<p>I need help with sorting in Express working with mongooose db.
When i use sort({'price':1}) everythink is good, but when i pass JSON.stringify(sort) which contains and logs out {"price":1} it stops working. Any ideas why?</p>
<pre><code> if(req.query.sortOption){
const str = req.query.sortOption.split(':');
sort[str[0]] = str[1] === 'desc' ? -1:1;
}
console.log(JSON.stringify(sort));
//here logs out {"price":-1} which works when i pass it into sort function as a string
try {
const annoucements = await Annoucement.find(query)
.skip(page * annoucementsPerPage)
.limit(annoucementsPerPage)
.populate('author')
.sort(JSON.stringify(sort))
res.status(200).json({
status: 'Successfully got an annoucement',
results: annoucements.length,
data: {
annoucements,
},
});
} catch (error) {
res.status(500).json({
status: 'Failed to get all annoucements',
message: error,
});
}
};
</code></pre>
|
[
{
"answer_id": 74554727,
"author": "Christopher Jones",
"author_id": 4799035,
"author_profile": "https://Stackoverflow.com/users/4799035",
"pm_score": 1,
"selected": false,
"text": "# create table t (c TIMESTAMP(6) WITH TIME ZONE);\n# insert into t (c) values (systimestamp);\n# commit;\n#\n# Name: pandas\n# Version: 1.5.2\n# Name: SQLAlchemy\n# Version: 1.4.44\n# Name: cx-Oracle\n# Version: 8.3.0\n#\n# Output is like:\n# 0 2022-11-24 11:49:25.505773\n\nimport os\nimport platform\n\nfrom sqlalchemy import create_engine\nimport pandas as pd\n\nimport cx_Oracle\n\nif platform.system() == \"Darwin\":\n cx_Oracle.init_oracle_client(lib_dir=os.environ.get(\"HOME\")+\"/Downloads/instantclient_19_8\")\n\nusername = os.environ.get(\"PYTHON_USERNAME\")\npassword = os.environ.get(\"PYTHON_PASSWORD\")\nconnect_string = os.environ.get(\"PYTHON_CONNECTSTRING\")\nhostname, service_name = connect_string.split(\"/\")\n\nengine = create_engine(f'oracle://{username}:{password}@{hostname}/?service_name={service_name}')\n\nquery = \"\"\"select * from t\"\"\"\ndf = pd.read_sql_query(query, engine)\nprint(df)\n"
},
{
"answer_id": 74562590,
"author": "Evan",
"author_id": 6672746,
"author_profile": "https://Stackoverflow.com/users/6672746",
"pm_score": 0,
"selected": false,
"text": "query = \"SELECT TO_CHAR(col) AS col FROM table\"\ndf = pd.read_sql_query(query, cnxn)\ndf[col] = df[col].apply(pd.to_datetime, format=\"%d-%b-%y %I.%M.%S.%f %p %Z\")\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19294299/"
] |
74,554,295
|
<p>I am trying to find a way to know if an action will trigger an effect at runtime.</p>
<p>I can see the Effects Class at runtime and I can see the created effects in the class members as well but I have no idea how to find out the action that may trigger the effect before the effect is fired.</p>
<p>Any ideas if this is even possible? I ask this because I could use one effect for each action but sometimes actions will fire different effects and many effects can be fired by two different actions, the idea is to know before changing state if an effect may occur or not.</p>
<p>FYI: I am not implementing this anywhere I am just trying to understand the tool better.</p>
|
[
{
"answer_id": 74554727,
"author": "Christopher Jones",
"author_id": 4799035,
"author_profile": "https://Stackoverflow.com/users/4799035",
"pm_score": 1,
"selected": false,
"text": "# create table t (c TIMESTAMP(6) WITH TIME ZONE);\n# insert into t (c) values (systimestamp);\n# commit;\n#\n# Name: pandas\n# Version: 1.5.2\n# Name: SQLAlchemy\n# Version: 1.4.44\n# Name: cx-Oracle\n# Version: 8.3.0\n#\n# Output is like:\n# 0 2022-11-24 11:49:25.505773\n\nimport os\nimport platform\n\nfrom sqlalchemy import create_engine\nimport pandas as pd\n\nimport cx_Oracle\n\nif platform.system() == \"Darwin\":\n cx_Oracle.init_oracle_client(lib_dir=os.environ.get(\"HOME\")+\"/Downloads/instantclient_19_8\")\n\nusername = os.environ.get(\"PYTHON_USERNAME\")\npassword = os.environ.get(\"PYTHON_PASSWORD\")\nconnect_string = os.environ.get(\"PYTHON_CONNECTSTRING\")\nhostname, service_name = connect_string.split(\"/\")\n\nengine = create_engine(f'oracle://{username}:{password}@{hostname}/?service_name={service_name}')\n\nquery = \"\"\"select * from t\"\"\"\ndf = pd.read_sql_query(query, engine)\nprint(df)\n"
},
{
"answer_id": 74562590,
"author": "Evan",
"author_id": 6672746,
"author_profile": "https://Stackoverflow.com/users/6672746",
"pm_score": 0,
"selected": false,
"text": "query = \"SELECT TO_CHAR(col) AS col FROM table\"\ndf = pd.read_sql_query(query, cnxn)\ndf[col] = df[col].apply(pd.to_datetime, format=\"%d-%b-%y %I.%M.%S.%f %p %Z\")\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4475288/"
] |
74,554,329
|
<p>I have found this sql that help avoid high_value long type column.</p>
<pre><code>--VER HIGH VALUE
col partition_name for a30
col high_value for a120
col PARTITION for a20
WITH xml AS
(
SELECT dbms_xmlgen.getxmltype('SELECT table_name,partition_name,partition_position,high_value
FROM dba_tab_partitions
WHERE TABLE_OWNER = UPPER(''MY_SCHEMA'') ----MY SCHEMA HERE') AS x
FROM dual
)
SELECT extractValue(rws.object_value, '/ROW/TABLE_NAME') table_name,
extractValue(rws.object_value, '/ROW/PARTITION_NAME') partition,
extractValue(rws.object_value, '/ROW/HIGH_VALUE') high_value
FROM xml x, table(xmlsequence(extract(x.x, '/ROWSET/ROW'))) rws;
</code></pre>
<p>The sample output:</p>
<pre><code>SAMPLE_TABLE P82 TO_DATE(' 2021-09-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')
SAMPLE_TABLE P83 TO_DATE(' 2021-10-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')
SAMPLE_TABLE P84 TO_DATE(' 2021-11-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')
SAMPLE_TABLE P85 TO_DATE(' 2021-12-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')
SAMPLE_TABLE P86 TO_DATE(' 2022-01-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')
SAMPLE_TABLE P87 TO_DATE(' 2022-02-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')
SAMPLE_TABLE P88 TO_DATE(' 2022-03-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')
SAMPLE_TABLE P89 TO_DATE(' 2022-04-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')
SAMPLE_TABLE P90 TO_DATE(' 2022-05-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')
SAMPLE_TABLE P91 TO_DATE(' 2022-06-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')
SAMPLE_TABLE P92 TO_DATE(' 2022-07-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')
SAMPLE_TABLE P93 TO_DATE(' 2022-08-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')
SAMPLE_TABLE P94 TO_DATE(' 2022-09-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')
SAMPLE_TABLE P95 TO_DATE(' 2022-10-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')
SAMPLE_TABLE P96 TO_DATE(' 2022-11-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')
SAMPLE_TABLE P97 TO_DATE(' 2022-12-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')
SAMPLE_TABLE P98 MAXVALUE
</code></pre>
<p>How can I convert column high_value directly to a date</p>
<p>IE: instead of getting:</p>
<pre><code>`TO_DATE(' 2022-12-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')`
</code></pre>
<p>I'd like to get:</p>
<pre><code>2022-12-01
</code></pre>
<p>Or, if I change the date mask, I got:</p>
<pre><code>alter session set nls_date_format = 'dd/mm/yyyy hh24:mi:ss';
01/12/2022 00:00:00
</code></pre>
|
[
{
"answer_id": 74556806,
"author": "d r",
"author_id": 19023353,
"author_profile": "https://Stackoverflow.com/users/19023353",
"pm_score": 1,
"selected": false,
"text": "Select \n TABLE_NAME, \n PARTITION_NAME, \n PARTITION_POSITION,\n CASE WHEN HIGH_VALUE != 'MAXVALUE' THEN To_Date(SubStr(HIGH_VALUE, 11, 10), 'yyyy-mm-dd') \n ELSE LAST_VALUE(To_Date(SubStr(HIGH_VALUE, 11, 10), 'yyyy-mm-dd')) OVER(ORDER BY PARTITION_NAME ROWS BETWEEN 1 PRECEDING And 1 PRECEDING)\n END \"HIGH_VALUE\"\nFrom \n dba_tab_partitions\nWHERE \n TABLE_OWNER = UPPER(''''MY_SCHEMA'''')'\n/* \n R e s u l t :\nTABLE_NAME PARTITION_NAME PARTITION_POSITION HIGH_VALUE\n------------ -------------- ------------------ ----------\nSAMPLE_TABLE P82 Null 01-SEP-21 \nSAMPLE_TABLE P83 Null 01-OCT-21 \nSAMPLE_TABLE P84 Null 01-NOV-21 \nSAMPLE_TABLE P85 Null 01-DEC-21 \nSAMPLE_TABLE P86 Null 01-JAN-22 \nSAMPLE_TABLE P87 Null 01-FEB-22 \nSAMPLE_TABLE P88 Null 01-MAR-22 \nSAMPLE_TABLE P89 Null 01-APR-22 \nSAMPLE_TABLE P90 Null 01-MAY-22 \nSAMPLE_TABLE P91 Null 01-JUN-22 \nSAMPLE_TABLE P92 Null 01-JUL-22 \nSAMPLE_TABLE P93 Null 01-AUG-22 \nSAMPLE_TABLE P94 Null 01-SEP-22 \nSAMPLE_TABLE P95 Null 01-OCT-22 \nSAMPLE_TABLE P96 Null 01-NOV-22 \nSAMPLE_TABLE P97 Null 01-DEC-22 \nSAMPLE_TABLE P98 Null 01-DEC-22\n*/\n"
},
{
"answer_id": 74557098,
"author": "Barbaros Özhan",
"author_id": 5841306,
"author_profile": "https://Stackoverflow.com/users/5841306",
"pm_score": 0,
"selected": false,
"text": "DECLARE\n v_dt DATE;\n v_chr VARCHAR2(4000);\nBEGIN\n DBMS_OUTPUT.PUT_LINE('table_name partition_name high_value');\n FOR c IN ( \n SELECT table_name,partition_name,partition_position,high_value \n FROM user_tab_partitions \n )\n LOOP \n v_chr := SUBSTR(c.high_value, 1, 4000);\n EXECUTE IMMEDIATE 'SELECT '||v_chr||' FROM dual' INTO v_dt;\n DBMS_OUTPUT.PUT(c.table_name||' ');\n DBMS_OUTPUT.PUT(c.partition_name||' ');\n DBMS_OUTPUT.PUT_LINE(v_dt);\n END LOOP;\nEND;\n/\n user_tab_partitions"
},
{
"answer_id": 74557136,
"author": "astentx",
"author_id": 2778710,
"author_profile": "https://Stackoverflow.com/users/2778710",
"pm_score": 0,
"selected": false,
"text": "HIGH_VALUE create table t (\n id int,\n dt date\n)\npartition by range (dt)\ninterval (interval '3' day) (\n partition pmin values less than(date '2022-01-01')\n)\n insert into t (id, dt)\nselect\n level,\n date '2022-01-01' + dbms_random.value(0,7)*level\nfrom dual\nconnect by level < 10\n with function f_evaluate_date_expr(p_expr varchar2)\n /*Evaluates date expression to avoid any manual parsing*/\n return date\nas\n l_dt date;\nbegin\n if p_expr = 'MAXVALUE' then\n l_dt := timestamp '9999-12-31 23:59:59';\n else\n execute immediate 'select ' || p_expr || ' from dual'\n into l_dt;\n end if;\n\n return l_dt;\nend;\n\nselect\n table_name,\n partition_name,\n f_evaluate_date_expr(high_value) as high_value\nfrom xmltable(\n '/ROWSET/ROW'\n passing dbms_xmlgen.getxmltype('\n select table_name, partition_name, high_value\n from user_tab_partitions\n ')\n columns\n table_name varchar2(30),\n partition_name varchar2(30),\n high_value varchar2(100)\n)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9616557/"
] |
74,554,341
|
<p>I have below <code>array</code> and <code>list</code> in JavaScript.</p>
<pre><code>const headr = [H1, H2 ,H3, H4]
const Year = ['1Y', '2Y' ,'3Y', '4Y']
let arr_ = {
H1 : Array(3)
0 : {Year: '1Y', Type: 'TypeA', Value: -41445643364}
1 : {Year: '2Y', Type: 'TypeA', Value: -11928080380}
2 : {Year: '3Y', Type: 'TypeA', Value: 32370503415}
H4 : Array(4)
0 : {Year: '1Y', Type: 'TypeA', Value: -41445643364}
1 : {Year: '2Y', Type: 'TypeB', Value: -11928080380}
2 : {Year: '3Y', Type: 'TypeA', Value: 32370503415}
3 : {Year: '4Y', Type: 'TypeA', Value: 32370503415}
}
</code></pre>
<p>and, I want to create new <code>array</code> as following format :</p>
<pre><code>H1 : Array(3)
0 : {Year: '1Y', Type: 'TypeA', Value: -41445643364}
1 : {Year: '2Y', Type: 'TypeA', Value: -11928080380}
2 : {Year: '3Y', Type: 'TypeA', Value: 32370503415}
3 : {Year: '4Y', Type: '-', Value: 0}
H2 : Array(4)
0 : {Year: '1Y', Type: '-', Value: 0}
1 : {Year: '2Y', Type: '-', Value: 0}
2 : {Year: '3Y', Type: '-', Value: 0}
3 : {Year: '4Y', Type: '-', Value: 0}
H3 : Array(4)
0 : {Year: '1Y', Type: '-', Value: 0}
1 : {Year: '2Y', Type: '-', Value: 0}
2 : {Year: '3Y', Type: '-', Value: 0}
3 : {Year: '4Y', Type: '-', Value: 0}
H4 : Array(4)
0 : {Year: '1Y', Type: 'TypeA', Value: -41445643364}
1 : {Year: '2Y', Type: 'TypeB', Value: -11928080380}
2 : {Year: '3Y', Type: 'TypeA', Value: 32370503415}
3 : {Year: '4Y', Type: 'TypeA', Value: 32370503415}
}
</code></pre>
<p>How can I achieve the array as the format? I've thinking creating new dictionary or array as below format and using <code>for loop</code> then push value.</p>
<pre><code>let dict_ = {
'H1' : [], 'H2' : [], 'H3' : [], 'H4' : []
}
</code></pre>
|
[
{
"answer_id": 74556806,
"author": "d r",
"author_id": 19023353,
"author_profile": "https://Stackoverflow.com/users/19023353",
"pm_score": 1,
"selected": false,
"text": "Select \n TABLE_NAME, \n PARTITION_NAME, \n PARTITION_POSITION,\n CASE WHEN HIGH_VALUE != 'MAXVALUE' THEN To_Date(SubStr(HIGH_VALUE, 11, 10), 'yyyy-mm-dd') \n ELSE LAST_VALUE(To_Date(SubStr(HIGH_VALUE, 11, 10), 'yyyy-mm-dd')) OVER(ORDER BY PARTITION_NAME ROWS BETWEEN 1 PRECEDING And 1 PRECEDING)\n END \"HIGH_VALUE\"\nFrom \n dba_tab_partitions\nWHERE \n TABLE_OWNER = UPPER(''''MY_SCHEMA'''')'\n/* \n R e s u l t :\nTABLE_NAME PARTITION_NAME PARTITION_POSITION HIGH_VALUE\n------------ -------------- ------------------ ----------\nSAMPLE_TABLE P82 Null 01-SEP-21 \nSAMPLE_TABLE P83 Null 01-OCT-21 \nSAMPLE_TABLE P84 Null 01-NOV-21 \nSAMPLE_TABLE P85 Null 01-DEC-21 \nSAMPLE_TABLE P86 Null 01-JAN-22 \nSAMPLE_TABLE P87 Null 01-FEB-22 \nSAMPLE_TABLE P88 Null 01-MAR-22 \nSAMPLE_TABLE P89 Null 01-APR-22 \nSAMPLE_TABLE P90 Null 01-MAY-22 \nSAMPLE_TABLE P91 Null 01-JUN-22 \nSAMPLE_TABLE P92 Null 01-JUL-22 \nSAMPLE_TABLE P93 Null 01-AUG-22 \nSAMPLE_TABLE P94 Null 01-SEP-22 \nSAMPLE_TABLE P95 Null 01-OCT-22 \nSAMPLE_TABLE P96 Null 01-NOV-22 \nSAMPLE_TABLE P97 Null 01-DEC-22 \nSAMPLE_TABLE P98 Null 01-DEC-22\n*/\n"
},
{
"answer_id": 74557098,
"author": "Barbaros Özhan",
"author_id": 5841306,
"author_profile": "https://Stackoverflow.com/users/5841306",
"pm_score": 0,
"selected": false,
"text": "DECLARE\n v_dt DATE;\n v_chr VARCHAR2(4000);\nBEGIN\n DBMS_OUTPUT.PUT_LINE('table_name partition_name high_value');\n FOR c IN ( \n SELECT table_name,partition_name,partition_position,high_value \n FROM user_tab_partitions \n )\n LOOP \n v_chr := SUBSTR(c.high_value, 1, 4000);\n EXECUTE IMMEDIATE 'SELECT '||v_chr||' FROM dual' INTO v_dt;\n DBMS_OUTPUT.PUT(c.table_name||' ');\n DBMS_OUTPUT.PUT(c.partition_name||' ');\n DBMS_OUTPUT.PUT_LINE(v_dt);\n END LOOP;\nEND;\n/\n user_tab_partitions"
},
{
"answer_id": 74557136,
"author": "astentx",
"author_id": 2778710,
"author_profile": "https://Stackoverflow.com/users/2778710",
"pm_score": 0,
"selected": false,
"text": "HIGH_VALUE create table t (\n id int,\n dt date\n)\npartition by range (dt)\ninterval (interval '3' day) (\n partition pmin values less than(date '2022-01-01')\n)\n insert into t (id, dt)\nselect\n level,\n date '2022-01-01' + dbms_random.value(0,7)*level\nfrom dual\nconnect by level < 10\n with function f_evaluate_date_expr(p_expr varchar2)\n /*Evaluates date expression to avoid any manual parsing*/\n return date\nas\n l_dt date;\nbegin\n if p_expr = 'MAXVALUE' then\n l_dt := timestamp '9999-12-31 23:59:59';\n else\n execute immediate 'select ' || p_expr || ' from dual'\n into l_dt;\n end if;\n\n return l_dt;\nend;\n\nselect\n table_name,\n partition_name,\n f_evaluate_date_expr(high_value) as high_value\nfrom xmltable(\n '/ROWSET/ROW'\n passing dbms_xmlgen.getxmltype('\n select table_name, partition_name, high_value\n from user_tab_partitions\n ')\n columns\n table_name varchar2(30),\n partition_name varchar2(30),\n high_value varchar2(100)\n)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6681701/"
] |
74,554,355
|
<p>I have a nested vector</p>
<pre><code>$a
$a$age
[1] -2702 -2621 -2945
$a$gen
[1] 109 109 105
$b
$b$age
[1] -2702 -2702 -2702
$b$gen
[1] 109 109 109
</code></pre>
<p>I want to divide the elements of $a$age to 25, round them up and the result write in $a$gen, as well as do the same with $b$age and result write in $b$gen</p>
<p>So the output should be</p>
<pre><code>$a
$a$age
[1] -2702 -2621 -2945
$a$gen
[1] 108 104 117
$b
$b$age
[1] -2702 -2702 -2702
$b$gen
[1] 108 108 108
</code></pre>
|
[
{
"answer_id": 74556806,
"author": "d r",
"author_id": 19023353,
"author_profile": "https://Stackoverflow.com/users/19023353",
"pm_score": 1,
"selected": false,
"text": "Select \n TABLE_NAME, \n PARTITION_NAME, \n PARTITION_POSITION,\n CASE WHEN HIGH_VALUE != 'MAXVALUE' THEN To_Date(SubStr(HIGH_VALUE, 11, 10), 'yyyy-mm-dd') \n ELSE LAST_VALUE(To_Date(SubStr(HIGH_VALUE, 11, 10), 'yyyy-mm-dd')) OVER(ORDER BY PARTITION_NAME ROWS BETWEEN 1 PRECEDING And 1 PRECEDING)\n END \"HIGH_VALUE\"\nFrom \n dba_tab_partitions\nWHERE \n TABLE_OWNER = UPPER(''''MY_SCHEMA'''')'\n/* \n R e s u l t :\nTABLE_NAME PARTITION_NAME PARTITION_POSITION HIGH_VALUE\n------------ -------------- ------------------ ----------\nSAMPLE_TABLE P82 Null 01-SEP-21 \nSAMPLE_TABLE P83 Null 01-OCT-21 \nSAMPLE_TABLE P84 Null 01-NOV-21 \nSAMPLE_TABLE P85 Null 01-DEC-21 \nSAMPLE_TABLE P86 Null 01-JAN-22 \nSAMPLE_TABLE P87 Null 01-FEB-22 \nSAMPLE_TABLE P88 Null 01-MAR-22 \nSAMPLE_TABLE P89 Null 01-APR-22 \nSAMPLE_TABLE P90 Null 01-MAY-22 \nSAMPLE_TABLE P91 Null 01-JUN-22 \nSAMPLE_TABLE P92 Null 01-JUL-22 \nSAMPLE_TABLE P93 Null 01-AUG-22 \nSAMPLE_TABLE P94 Null 01-SEP-22 \nSAMPLE_TABLE P95 Null 01-OCT-22 \nSAMPLE_TABLE P96 Null 01-NOV-22 \nSAMPLE_TABLE P97 Null 01-DEC-22 \nSAMPLE_TABLE P98 Null 01-DEC-22\n*/\n"
},
{
"answer_id": 74557098,
"author": "Barbaros Özhan",
"author_id": 5841306,
"author_profile": "https://Stackoverflow.com/users/5841306",
"pm_score": 0,
"selected": false,
"text": "DECLARE\n v_dt DATE;\n v_chr VARCHAR2(4000);\nBEGIN\n DBMS_OUTPUT.PUT_LINE('table_name partition_name high_value');\n FOR c IN ( \n SELECT table_name,partition_name,partition_position,high_value \n FROM user_tab_partitions \n )\n LOOP \n v_chr := SUBSTR(c.high_value, 1, 4000);\n EXECUTE IMMEDIATE 'SELECT '||v_chr||' FROM dual' INTO v_dt;\n DBMS_OUTPUT.PUT(c.table_name||' ');\n DBMS_OUTPUT.PUT(c.partition_name||' ');\n DBMS_OUTPUT.PUT_LINE(v_dt);\n END LOOP;\nEND;\n/\n user_tab_partitions"
},
{
"answer_id": 74557136,
"author": "astentx",
"author_id": 2778710,
"author_profile": "https://Stackoverflow.com/users/2778710",
"pm_score": 0,
"selected": false,
"text": "HIGH_VALUE create table t (\n id int,\n dt date\n)\npartition by range (dt)\ninterval (interval '3' day) (\n partition pmin values less than(date '2022-01-01')\n)\n insert into t (id, dt)\nselect\n level,\n date '2022-01-01' + dbms_random.value(0,7)*level\nfrom dual\nconnect by level < 10\n with function f_evaluate_date_expr(p_expr varchar2)\n /*Evaluates date expression to avoid any manual parsing*/\n return date\nas\n l_dt date;\nbegin\n if p_expr = 'MAXVALUE' then\n l_dt := timestamp '9999-12-31 23:59:59';\n else\n execute immediate 'select ' || p_expr || ' from dual'\n into l_dt;\n end if;\n\n return l_dt;\nend;\n\nselect\n table_name,\n partition_name,\n f_evaluate_date_expr(high_value) as high_value\nfrom xmltable(\n '/ROWSET/ROW'\n passing dbms_xmlgen.getxmltype('\n select table_name, partition_name, high_value\n from user_tab_partitions\n ')\n columns\n table_name varchar2(30),\n partition_name varchar2(30),\n high_value varchar2(100)\n)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16756939/"
] |
74,554,371
|
<p>Basically, I want to know how to replace every A, + and - in a string of A's,+'s and -'s based on rules inputted.
So if I have a chain of the characters mentioned above, and I input that every A will become A+A, every - will become -+-, every + will become A-+. How do I "choose" every single one of the characters in the initial chain, and change them to the replacements so that it outputs the "new" chain?</p>
<p>Being a beginner to Python, I tried basic commands like</p>
<pre><code>input:"Initial chain: "
input:"What does A become? "
input:"What does + become? "
input:"What does - become? "
</code></pre>
<p>but I do not know what to go from there.</p>
|
[
{
"answer_id": 74554425,
"author": "Metahuman Flash",
"author_id": 14694240,
"author_profile": "https://Stackoverflow.com/users/14694240",
"pm_score": 0,
"selected": false,
"text": "chain = input('Initial chain: ')\nr1 = input('What does A become? ')\nr2 = input('What does + become? ')\nr3 = input('What does - become? ')\n\ni = 2 # amount of iterations you would like\nwhile i > 0:\n result = ''\n for c in chain:\n if c == 'A':\n result += r1\n elif c == '+':\n result += r2\n elif c == '-':\n result += r3\n else:\n result += c\n i -= 1\n chain = result\n\nprint(chain)\n"
},
{
"answer_id": 74554467,
"author": "harry",
"author_id": 10727550,
"author_profile": "https://Stackoverflow.com/users/10727550",
"pm_score": -1,
"selected": false,
"text": "original = input(\"Initial Chain: \")\nin1 = input(\"What does A become? \")\nin2 = input(\"What does + become? \")\nin3 = input(\"What does - become? \")\n\nprint(original.replace(\"A\",in1).replace(\"+\",in2).replace(\"-\",in3))\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20586276/"
] |
74,554,376
|
<p>EDIT: I took one observation out from the data frame of the original post and changed some values so writing manually is easier. I am also adding the desired output, so my question is easier to read.</p>
<p>This is a continuation to a question I made in another post:</p>
<p><a href="https://stackoverflow.com/questions/74355233/how-can-i-stack-my-dataset-so-each-observation-relates-to-all-other-observations">How can I stack my dataset so each observation relates to all other observations but itself?</a></p>
<p>In that post, I asked how can I make a row relate to all other observations but itself. I am trying to apply the answers to my dataset, but the issue is that I have a dataset with country-year-party. In my actual dataset, I want an observation to relate to every other observation within country-year.</p>
<p>Say for example I have a data frame with 2 countries (id1) A and B:</p>
<pre><code>df <- data.frame(id1 = c("A","A","A","B","B","B"),
id2 = c("a", "b", "c", "a", "b", "c" ),
x1 = c(1,2,3,1,2,3))
</code></pre>
<p>df</p>
<pre><code> id1 id2 x1
1 A a 1
2 A b 2
3 A c 3
4 B a 1
5 B b 2
6 B c 3
</code></pre>
<p>Each row in column id2 identifies one person a, b and c. I want each person to relate to every other person within country. So person a will be related to person b and c, but it has to be within country. I am trying the following codes:</p>
<pre><code>df <- df %>% group_by(id1) %>% merge( df, by = NULL) %>%
filter(id2.x != id2.y)
</code></pre>
<p>or even:</p>
<pre><code>df <- df %>% group_by(id2) %>%
left_join(df, df, by = character()) %>%
filter(id2.x != id2.y)
</code></pre>
<p>But it leads to the following result:</p>
<pre><code> id1.x id2.x x1.x id1.y id2.y x1.y
1 A b 2 A a 1
2 A c 3 A a 1
3 B b 2 A a 1
4 B c 3 A a 1
5 A a 1 A b 2
6 A c 3 A b 2
7 B a 1 A b 2
8 B c 3 A b 2
9 A a 1 A c 3
10 A b 2 A c 3
11 B a 1 A c 3
12 B b 2 A c 3
13 A b 2 B a 1
14 A c 3 B a 1
15 B b 2 B a 1
16 B c 3 B a 1
17 A a 1 B b 2
18 A c 3 B b 2
19 B a 1 B b 2
20 B c 3 B b 2
21 A a 1 B c 3
22 A b 2 B c 3
23 B a 1 B c 3
24 B b 2 B c 3
</code></pre>
<p>Notice that in observation 3, person b in country B is related to person a in country A. This is what I am trying to avoid. I want person a to relate to b and c, but only within each country. How can i do that?
The desired output would be something like this:</p>
<pre><code> id1.x id2.x x1.x id1.y id2.y x1.y
1 A a 1 A b 2
2 A a 1 A c 3
3 A b 2 A a 1
4 A b 2 A c 3
5 A c 3 A a 1
6 A c 3 A b 2
7 B a 1 B b 2
8 B a 1 B c 3
9 B b 2 B a 1
10 B b 2 B c 3
11 B c 3 B a 1
12 B c 3 B b 2
</code></pre>
<p>So, within each country A and B, each person a,b,c relates to each other but himself. I tried to clarify some questions and simplify my example, let me know if it is clear now and you need more clarification.</p>
|
[
{
"answer_id": 74554593,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 2,
"selected": true,
"text": "df <- data.frame(id1 = c(\"A\",\"A\",\"A\",\"A\",\"B\",\"B\",\"B\",\"B\"),\n id2 = c(\"a\", \"b\", \"c\", \"d\", \"a\", \"b\", \"c\", \"d\"),\n x1 = c(1,2,3,4, 5,6,7,8))\n#base option\nby(df, df$id1, \\(x){\n rws <- t(combn(seq(nrow(x)), 2))\n cbind(x[rws[,1],], x[rws[,2],2:3]) |>\n `colnames<-`(c(\"id1\", \"id2.x\",\"x1.x\", \"id2.y\", \"x2.y\")) \n}) |>\n do.call(what = rbind.data.frame)|>\n `row.names<-`(NULL)\n#> id1 id2.x x1.x id2.y x2.y\n#> 1 A a 1 b 2\n#> 2 A a 1 c 3\n#> 3 A a 1 d 4\n#> 4 A b 2 c 3\n#> 5 A b 2 d 4\n#> 6 A c 3 d 4\n#> 7 B a 5 b 6\n#> 8 B a 5 c 7\n#> 9 B a 5 d 8\n#> 10 B b 6 c 7\n#> 11 B b 6 d 8\n#> 12 B c 7 d 8\n library(tidyverse)\n\nfull_join(df, df, by = \"id1\") |>\n filter(id2.x != id2.y)\n#> id1 id2.x x1.x id2.y x1.y\n#> 1 A a 1 b 2\n#> 2 A a 1 c 3\n#> 3 A a 1 d 4\n#> 4 A b 2 a 1\n#> 5 A b 2 c 3\n#> 6 A b 2 d 4\n#> 7 A c 3 a 1\n#> 8 A c 3 b 2\n#> 9 A c 3 d 4\n#> 10 A d 4 a 1\n#> 11 A d 4 b 2\n#> 12 A d 4 c 3\n#> 13 B a 5 b 6\n#> 14 B a 5 c 7\n#> 15 B a 5 d 8\n#> 16 B b 6 a 5\n#> 17 B b 6 c 7\n#> 18 B b 6 d 8\n#> 19 B c 7 a 5\n#> 20 B c 7 b 6\n#> 21 B c 7 d 8\n#> 22 B d 8 a 5\n#> 23 B d 8 b 6\n#> 24 B d 8 c 7\n"
},
{
"answer_id": 74555169,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 1,
"selected": false,
"text": "expand_grid() group_modify() library(dplyr)\nlibrary(tidyr)\n\ndf %>%\n group_by(id1) %>%\n group_modify(~ expand_grid(.x, .x, .name_repair = make.unique)) %>%\n ungroup() %>%\n filter(id2 != id2.1)\n # A tibble: 12 × 5\n id1 id2 x1 id2.1 x1.1\n <chr> <chr> <dbl> <chr> <dbl>\n 1 A a 1 b 2\n 2 A a 1 c 3\n 3 A b 2 a 1\n 4 A b 2 c 3\n 5 A c 3 a 1\n 6 A c 3 b 2\n 7 B a 1 b 2\n 8 B a 1 c 3\n 9 B b 2 a 1\n10 B b 2 c 3\n11 B c 3 a 1\n12 B c 3 b 2\n"
},
{
"answer_id": 74556113,
"author": "onyambu",
"author_id": 8380272,
"author_profile": "https://Stackoverflow.com/users/8380272",
"pm_score": 2,
"selected": false,
"text": "df %>%\n group_by(id1)%>%\n mutate(vals=map(row_number(), ~cur_data_all()[-.x,]))%>%\n unnest(vals, names_sep = \"_\")\n\n# A tibble: 12 × 6\n# Groups: id1 [2]\n id1 id2 x1 vals_id1 vals_id2 vals_x1\n <chr> <chr> <dbl> <chr> <chr> <dbl>\n 1 A a 1 A b 2\n 2 A a 1 A c 3\n 3 A b 2 A a 1\n 4 A b 2 A c 3\n 5 A c 3 A a 1\n 6 A c 3 A b 2\n 7 B a 1 B b 2\n 8 B a 1 B c 3\n 9 B b 2 B a 1\n10 B b 2 B c 3\n11 B c 3 B a 1\n12 B c 3 B b 2\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19991656/"
] |
74,554,408
|
<p>I'm following the latest <a href="https://getstream.io/tutorials/swiftui-chat/" rel="nofollow noreferrer">tutorial</a> from Stream Chat, which looks great.</p>
<p>Looks like I followed it to the letter except for I replaced the <code>apiKey</code> with one created for me in the dashboard. This was provided when I registered my free trial.</p>
<p>Unfortunately, I'm unable to connect.</p>
<p>Here's my code</p>
<p><strong>SwiftUIChatDemo</strong></p>
<pre><code>import SwiftUI
// 1 Add imports
import StreamChat
import StreamChatSwiftUI
@main
struct SwiftUIChatDemoApp: App {
// 2 Add Adapter
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ChatChannelListView()
}
}
}
</code></pre>
<p><strong>App Delegate</strong></p>
<pre class="lang-swift prettyprint-override"><code>import StreamChat
import StreamChatSwiftUI
import UIKit
import SwiftUI
class AppDelegate: NSObject, UIApplicationDelegate {
// Add context provider
var streamChat: StreamChat?
var chatClient: ChatClient = {
// Low-level client variable with a hard-coded apikey
var config = ChatClientConfig(apiKey: .init("[key I created in dashboard]"))
// Set to use the chat in offline mode
config.isLocalStorageEnabled = true
// Pass the low-level client variable as a parameter of the ChatClient
let client = ChatClient(config: config)
return client
}()
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// Initialize the stream chat client
streamChat = StreamChat(chatClient: chatClient)
connectUser()
return true
}
// The `connectUser` function we need to add.
private func connectUser() {
// This is a hardcoded token valid on Stream's tutorial environment.
let token = try! Token(rawValue: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoibHVrZV9za3l3YWxrZXIifQ.kFSLHRB5X62t0Zlc7nwczWUfsQMwfkpylC6jCUZ6Mc0")
// Call `connectUser` on our SDK to get started.
chatClient.connectUser(
userInfo: .init(id: "luke_skywalker",
name: "Luke Skywalker",
imageURL: URL(string: "https://vignette.wikia.nocookie.net/starwars/images/2/20/LukeTLJ.jpg")!),
token: token
) { error in
if let error = error {
// Some very basic error handling only logging the error.
log.error("connecting the user failed \(error)")
return
}
}
}
}
</code></pre>
<p><strong>SwiftUIChatDemo.app</strong></p>
<pre><code>import SwiftUI
// 1 Add imports
import StreamChat
import StreamChatSwiftUI
@main
struct SwiftUIChatDemoApp: App {
// 2 Add Adapter
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ChatChannelListView()
}
}
}
</code></pre>
|
[
{
"answer_id": 74554523,
"author": "somethingsomethingswift",
"author_id": 19913478,
"author_profile": "https://Stackoverflow.com/users/19913478",
"pm_score": 0,
"selected": false,
"text": "apiKey token"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19913478/"
] |
74,554,431
|
<p>I have an array like this:</p>
<pre><code>[1, 2, 3, 4, 5, nil, 7, 8, 9, nil, nil, 12]
</code></pre>
<p>How can i get an array of the sums of these numbers in groups of 4, so that when a nil is encountered, it's treated as zero?</p>
<p>So that the outcome would be:</p>
<pre><code>[10, 20, 21]
</code></pre>
|
[
{
"answer_id": 74554493,
"author": "markets",
"author_id": 3033649,
"author_profile": "https://Stackoverflow.com/users/3033649",
"pm_score": 4,
"selected": true,
"text": "array = [1, 2, 3, 4, 5, nil, 7, 8, 9, nil, nil, 12]\n\narray.each_slice(4).map { |slice| slice.sum(&:to_i) }\n#=> [10, 20, 21]\n"
},
{
"answer_id": 74554962,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 1,
"selected": false,
"text": "a = [1, 2, 3, 4, 5, nil, 7, 8, 9, nil, nil, 12]\n\n(0...a.size).step(4).map { |i| a[i...i+4].compact.sum }\n# => [10, 20, 21]\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1580201/"
] |
74,554,443
|
<p>I am trying to query an on-premises SQL Server database using a power automate variable.</p>
<p>Is there any suggestions or is this even possible for the time being?</p>
<p>I have attempted the following:</p>
<ol>
<li>Using “Execute a SQL query (V2)” with an on-prem gateway connection. Not supported!</li>
<li>Using “Execute stored procedure (V2)” This won't return a value or allow variables.</li>
<li>Using “Power Query” This has similar issues to 2, that it won't allow power automate variables.</li>
<li>Consider Using Azure Managed Instances and linking the on-premises db to this instance, but can't see a obvious way for Azure to communicate with the on-prem SQL db.</li>
</ol>
<p>Query Example:
SELECT * FROM Customers WHERE Country=<strong>{Power-Automate-Varible}</strong>;</p>
|
[
{
"answer_id": 74573150,
"author": "SwethaKandikonda",
"author_id": 15969981,
"author_profile": "https://Stackoverflow.com/users/15969981",
"pm_score": 1,
"selected": false,
"text": "Execute a SQL query (V2) SELECT * from dbo.ReproTable where Country = '@{outputs('Compose')}'\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20177593/"
] |
74,554,458
|
<p>I have recently shifted to <code>MongoDB</code> and <code>Mongoose</code> with <code>Node.js</code>. And I am wrapping my head around it all coming from <code>SQL</code>.</p>
<p>I have a collection where documents have a similar structure to the following:</p>
<pre><code>{
name: String
rank: Number
}
</code></pre>
<p>Sometimes the <code>name</code> might be the same, but the <code>rank</code> will always be different.</p>
<p>I would like to remove all duplicates of <code>name</code>, but retain the object that has the <strong>LOWEST</strong> <code>rank</code>.</p>
<p>For instance, if my collection looked like this:</p>
<pre><code>{
name: "name1"
rank: 3
},
{
name: "name1"
rank: 4
},
{
name: "name1"
rank: 2
}
</code></pre>
<p>I would like to remove all objects where <code>name</code> is the same except for:</p>
<pre><code>{
name: "name1"
rank: 2
}
</code></pre>
<p>Is this possible to do with mongoose?</p>
|
[
{
"answer_id": 74555216,
"author": "alphadmon",
"author_id": 972399,
"author_profile": "https://Stackoverflow.com/users/972399",
"pm_score": 0,
"selected": false,
"text": "aggregate const duplicates = await collectionName.aggregate([\n {\n $group: {\n _id: \"$name\",\n dups: { $addToSet: \"$_id\" },\n count: { $sum: 1 }\n }\n },\n {\n $match: {\n count: { $gt: 1 }\n }\n }\n]);\n\nduplicates.forEach(async (item) => {\n const duplicate_names = item.dups;\n const duplicate_name = await collectionName.find({ _id: { $in: duplicate_names } }).sort({ rank: 1 });\n\n duplicate_name.shift();\n\n duplicate_name.forEach(async (item) => {\n await collectionName.deleteOne({ _id: item._id });\n });\n});\n"
},
{
"answer_id": 74557190,
"author": "Fabian Strathaus",
"author_id": 17298437,
"author_profile": "https://Stackoverflow.com/users/17298437",
"pm_score": 2,
"selected": true,
"text": "const found = await db.collection.aggregate([\n {\n $group: {\n _id: \"$name\",\n minRank: {\n $min: \"$rank\"\n }\n }\n },\n])\n\n\nawait db.collection.deleteMany({ \n $or: found.map(item => ({\n name: item._id,\n rank: { $ne: item.minRank }\n }))\n})\n name rank name"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/972399/"
] |
74,554,483
|
<p>I want to display data without adding lines, but I don't want print to increment to the right. instead of editing an existing one,
<a href="https://i.stack.imgur.com/4APiP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4APiP.png" alt="enter image description here" /></a>
how to do like docker build result in darts?</p>
|
[
{
"answer_id": 74554510,
"author": "sharon",
"author_id": 19132574,
"author_profile": "https://Stackoverflow.com/users/19132574",
"pm_score": 1,
"selected": false,
"text": "import 'dart:io';\n \nvoid main() {\n var i = 1;\n while (i <= 20) {\n stdout.write(i);\n stdout.write(' ');\n i++;\n }\n}\n"
},
{
"answer_id": 74608899,
"author": "anyusernewbie",
"author_id": 20259643,
"author_profile": "https://Stackoverflow.com/users/20259643",
"pm_score": 1,
"selected": true,
"text": "import 'dart:io';\n\nvoid main() {\n for (var i = 0; i < 1000; i++) {\n stdout.write(\"\\r\");\n stdout.write(\"Load: ${i}\");\n sleep(Duration(milliseconds: 100));\n }\n print(\"\\nFinished\");\n}\n\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20259643/"
] |
74,554,503
|
<p>Goodnight,</p>
<p>I have this code that identifies the ActiveCell and sends the value of that cell to "I6". With the change of the values that appear in "I6", the corresponding photographs of the students will change.</p>
<pre><code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Range("I6").Value = ActiveCell.Value
End Sub
</code></pre>
<p>With this code, I get the value of the cell to appear in "I6" whenever I click on a cell in the table. As long as i click on the "I" column where the student numbers are, everything is fine.</p>
<p>The problem appears when I click on any other table cell ("I14:X43") outside this "I" column.</p>
<p>I needed the code to always identify column "I" (I4:I43) of the active cell row.</p>
<p>Thus, whenever you are entering a record in any cell of the table ("I14:X43"), the code will identify the column "I" of that line and its value (student number). Identifying the value found in column "I" of the active cell row, it will appear in "I6", as it is in this formula and was changing the students' photographs.</p>
<p>At this moment, when I write a value inside the table, it will be this value that will appear in "I6" carrying a photograph that corresponds to the value that was registered/written and not to the number of the student of the line where I am.</p>
<p>However, a friend helped me with this code which works for what I intended but only up to column "Z".</p>
<pre><code>Sub_ Selectionchange
Dim x As String
Dim and As String
x = ActiveCell.Address(0, 0)
y = WorksheetFunction.Replace(x, 1, 1, "=I")
Range("I6").Value = y
End Sub
</code></pre>
<p>Clicking after that "Z" column, the code stops working and 0 appears in the "I6" column.</p>
<p>Can anyone help, please?</p>
<p>Try to getting a vba code to send the column "I" value of the ActiveCell row to cell "I6"</p>
|
[
{
"answer_id": 74554510,
"author": "sharon",
"author_id": 19132574,
"author_profile": "https://Stackoverflow.com/users/19132574",
"pm_score": 1,
"selected": false,
"text": "import 'dart:io';\n \nvoid main() {\n var i = 1;\n while (i <= 20) {\n stdout.write(i);\n stdout.write(' ');\n i++;\n }\n}\n"
},
{
"answer_id": 74608899,
"author": "anyusernewbie",
"author_id": 20259643,
"author_profile": "https://Stackoverflow.com/users/20259643",
"pm_score": 1,
"selected": true,
"text": "import 'dart:io';\n\nvoid main() {\n for (var i = 0; i < 1000; i++) {\n stdout.write(\"\\r\");\n stdout.write(\"Load: ${i}\");\n sleep(Duration(milliseconds: 100));\n }\n print(\"\\nFinished\");\n}\n\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18649290/"
] |
74,554,576
|
<p>I'm trying to hit one api to retrieve a specific string which is then stored in a variable and passed to another http api call but the problem is the api call that needs the argument runs and never sends the correct request. (noobie here btw)</p>
<p>here are the two calls, removed some personal info from it but it still makes sense.</p>
<pre><code>async getMatches() {
return this.http.get('matchesUrl', {
headers: {
'Authorization': 'Bearer **'
}
})
}
async getMatchStats(matchId: string) {
return this.http.get(`specificMatchUrl/${matchId}/`, {
headers: {
'Authorization': 'Bearer **'
}
})
}
</code></pre>
<p>And here is my component:</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import {GetapiService} from '../getapi.service';
@Component({
selector: 'app-gamingpage',
templateUrl: './gamingpage.component.html',
styleUrls: ['./gamingpage.component.scss']
})
export class GamingpageComponent implements OnInit {
title = '';
wins = '';
totalMatches = '';
currentWinStreak = '';
latestMap = '';
matchId = '';
constructor(
private api: GetapiService
) { }
async ngOnInit() {
this.api.getPlayerStats().subscribe((data: any) => {
this.title = data['game_id'];
this.wins = data.lifetime['Wins']
this.totalMatches = data.lifetime['Matches']
this.currentWinStreak = data.lifetime['Current Win Streak']
});
(await this.api.getMatches()).subscribe((data: any) => {
this.matchId = data.items[0].match_id;
});
(await this.api.getMatchStats(this.matchId)).subscribe((data: any) => {
this.latestMap = data.rounds.round_stats['Map']
})
}
}
</code></pre>
<p>I thought that awaiting both calls would fix this because the getMatchStats won't run until getMatches is done and that matchId variable is stored. But when the call is made, the url is incorrect and doesn't contain the matchId. I've verified that console.log is showing it correctly so I must be doing something wrong but can't seem to figure out what. I'm looking at the similar questions but none seem to be doing the same thing as me... or at least what I understand. Thanks in advance.</p>
|
[
{
"answer_id": 74556462,
"author": "Eli Porush",
"author_id": 14598976,
"author_profile": "https://Stackoverflow.com/users/14598976",
"pm_score": -1,
"selected": false,
"text": "this.matchId = (await this.api.getMatches()).items[0].match_id;\n\nthis.latestMap = (await \n this.api.getMatchStats(this.matchId)).rounds.round_stats['Map'];\n"
},
{
"answer_id": 74556773,
"author": "Eliseo",
"author_id": 8558186,
"author_profile": "https://Stackoverflow.com/users/8558186",
"pm_score": 3,
"selected": true,
"text": "this.api.getMatches()).pipe(switchMap((data:any)=>{\n this.matchId =data.items[0].match_id;\n return this.api.getMatchStats(this.matchId)\n})).subscribe((data: any) => {\n this.latestMap = data.rounds.round_stats['Map'];\n});\n"
},
{
"answer_id": 74556850,
"author": "Luis Breuer",
"author_id": 11133426,
"author_profile": "https://Stackoverflow.com/users/11133426",
"pm_score": 0,
"selected": false,
"text": "myObservable.subscribe(\n x => console.log('Observer got a next value: ' + x),\n err => console.error('Observer got an error: ' + err),\n () => console.log('Observer got a complete notification')\n);\n () => {\n (this.api.getMatchStats(this.matchId)).subscribe((data: any) => {\n this.latestMap = data.rounds.round_stats['Map']\n })\n}\n this.api.getMatches().subscribe(\n data => this.matchId = data.items[0].match_id;,\n err => console.error('Observer got an error: ' + err),\n () => {this.api.getMatchStats(this.matchId)).subscribe(\n data => {this.latestMap = data.rounds.round_stats['Map']}\n )}\n);\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14159384/"
] |
74,554,590
|
<pre><code>let ar = ['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩']
let nm = 13
let result = ''
console.log(result)
</code></pre>
<p>how to customize nm variable with index of ar</p>
<p>ex: when nm = 1 so the result is index 1 of ar variable = ١</p>
<p>And nm = 13 , the result is combined index 1 and 3 of ar variable so the result ١٣</p>
|
[
{
"answer_id": 74556462,
"author": "Eli Porush",
"author_id": 14598976,
"author_profile": "https://Stackoverflow.com/users/14598976",
"pm_score": -1,
"selected": false,
"text": "this.matchId = (await this.api.getMatches()).items[0].match_id;\n\nthis.latestMap = (await \n this.api.getMatchStats(this.matchId)).rounds.round_stats['Map'];\n"
},
{
"answer_id": 74556773,
"author": "Eliseo",
"author_id": 8558186,
"author_profile": "https://Stackoverflow.com/users/8558186",
"pm_score": 3,
"selected": true,
"text": "this.api.getMatches()).pipe(switchMap((data:any)=>{\n this.matchId =data.items[0].match_id;\n return this.api.getMatchStats(this.matchId)\n})).subscribe((data: any) => {\n this.latestMap = data.rounds.round_stats['Map'];\n});\n"
},
{
"answer_id": 74556850,
"author": "Luis Breuer",
"author_id": 11133426,
"author_profile": "https://Stackoverflow.com/users/11133426",
"pm_score": 0,
"selected": false,
"text": "myObservable.subscribe(\n x => console.log('Observer got a next value: ' + x),\n err => console.error('Observer got an error: ' + err),\n () => console.log('Observer got a complete notification')\n);\n () => {\n (this.api.getMatchStats(this.matchId)).subscribe((data: any) => {\n this.latestMap = data.rounds.round_stats['Map']\n })\n}\n this.api.getMatches().subscribe(\n data => this.matchId = data.items[0].match_id;,\n err => console.error('Observer got an error: ' + err),\n () => {this.api.getMatchStats(this.matchId)).subscribe(\n data => {this.latestMap = data.rounds.round_stats['Map']}\n )}\n);\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20490929/"
] |
74,554,601
|
<p>There is a web page that I would like to scrape some information from.</p>
<p>I start off with gathering a bunch of HTML Elements.</p>
<pre><code>var theSearch = document.getElementsByClassName('theID');
</code></pre>
<p>I then take that HTML Collection and turn it into an array.</p>
<pre><code>var arr = Array.prototype.slice.call( theSearch );
</code></pre>
<p>Now comes the tricky part.</p>
<p>I'd like to scroll down the page, and grab new items that have appeared on the page.</p>
<pre><code>window.scrollTo(0, document.body.scrollHeight);
</code></pre>
<p>How does one access the newly inserted DOM nodes? Something like ...</p>
<pre><code>var theSearch2 = document.getElementsByClassName('theID');
</code></pre>
<p>... and casting it into a new array ...</p>
<pre><code>var arr2 = Array.prototype.slice.call( theSearch );
</code></pre>
<p>... and pushing the items from <code>arr2</code> to <code>arr</code> like ...</p>
<pre><code>arr.push(...arr2);
</code></pre>
<p>And how would one achieve an ongoing process which keeps scraping until no new items are appended into the page's DOM.</p>
|
[
{
"answer_id": 74556462,
"author": "Eli Porush",
"author_id": 14598976,
"author_profile": "https://Stackoverflow.com/users/14598976",
"pm_score": -1,
"selected": false,
"text": "this.matchId = (await this.api.getMatches()).items[0].match_id;\n\nthis.latestMap = (await \n this.api.getMatchStats(this.matchId)).rounds.round_stats['Map'];\n"
},
{
"answer_id": 74556773,
"author": "Eliseo",
"author_id": 8558186,
"author_profile": "https://Stackoverflow.com/users/8558186",
"pm_score": 3,
"selected": true,
"text": "this.api.getMatches()).pipe(switchMap((data:any)=>{\n this.matchId =data.items[0].match_id;\n return this.api.getMatchStats(this.matchId)\n})).subscribe((data: any) => {\n this.latestMap = data.rounds.round_stats['Map'];\n});\n"
},
{
"answer_id": 74556850,
"author": "Luis Breuer",
"author_id": 11133426,
"author_profile": "https://Stackoverflow.com/users/11133426",
"pm_score": 0,
"selected": false,
"text": "myObservable.subscribe(\n x => console.log('Observer got a next value: ' + x),\n err => console.error('Observer got an error: ' + err),\n () => console.log('Observer got a complete notification')\n);\n () => {\n (this.api.getMatchStats(this.matchId)).subscribe((data: any) => {\n this.latestMap = data.rounds.round_stats['Map']\n })\n}\n this.api.getMatches().subscribe(\n data => this.matchId = data.items[0].match_id;,\n err => console.error('Observer got an error: ' + err),\n () => {this.api.getMatchStats(this.matchId)).subscribe(\n data => {this.latestMap = data.rounds.round_stats['Map']}\n )}\n);\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2359796/"
] |
74,554,605
|
<p>Hey im working on a litle project right now and i need to turn a list of json string into List<TaskStruct.cs>
I have included all the needed code if something is missing let me know!</p>
<p>im getting the json with flurl if that helps</p>
<p>The important bits:</p>
<p>This should get the list from my api:</p>
<pre><code>public async static Task<List<TaskStruct>> GetTasks()
{
return await $"{BASE}tasks/".GetJsonAsync<List<TaskStruct>>();
}
</code></pre>
<p>This is the response from the api:</p>
<pre><code>
[
"{\"id\": \"1\", \"date\": \"25.11.2022\", \"start\": \"10:00\", \"end\": \"13:00\", \"betrag\": \"15\\u20ac\", \"todo\": \"awdawd awd awd awd awd awd aw awa adw\", \"done\": true}",
"{\"id\": \"2\", \"date\": \"26.11.2022\", \"start\": \"10:00\", \"end\": \"13:00\", \"betrag\": \"15\\u20ac\", \"todo\": \"awdawd awd awd awd awd awd aw awa adw\", \"done\": true}",
"{\"id\": \"10362\", \"date\": \"26.11.2022\", \"start\": \"10:00\", \"end\": \"13:00\", \"betrag\": \"15\\u20ac\", \"todo\": \"awdawd awd awd awd awd awd aw awa adw\", \"done\": true}",
"{\"id\": \"23726\", \"date\": \"25.11.2022\", \"start\": \"10:00\", \"end\": \"13:00\", \"betrag\": \"15\\u20ac\", \"todo\": \"awdawd awd awd awd awd awd aw awa adw\", \"done\": true}",
"{\"id\": \"41445\", \"date\": \"26.11.2022\", \"start\": \"10:00\", \"end\": \"13:00\", \"betrag\": \"15\\u20ac\", \"todo\": \"TODO\\r\\n\\r\\n\\r\\nmehr\\r\\n\\r\\n222\\r\\n312\\r\\n312\\r\\n\", \"done\": false}",
"{\"id\": \"49761\", \"date\": \"23.11.2022\", \"start\": \"Start\", \"end\": \"Ende\", \"betrag\": \"Betrag\", \"todo\": \"TODO\", \"done\": false}",
"{\"id\": \"53618\", \"date\": \"23.11.2022\", \"start\": \"Start\", \"end\": \"Ende\", \"betrag\": \"Betrag\", \"todo\": \"TODO\", \"done\": false}",
"{\"id\": \"54019\", \"date\": \"25.11.2022\", \"start\": \"10:00\", \"end\": \"13:00\", \"betrag\": \"15\\u20ac\", \"todo\": \"awdawd awd awd awd awd awd aw awa adw\", \"done\": true}",
"{\"id\": \"87156\", \"date\": \"26.11.2022\", \"start\": \"10:00\", \"end\": \"13:00\", \"betrag\": \"15\\u20ac\", \"todo\": \"awdawd awd awd awd awd awd aw awa adw\", \"done\": true}"
]
</code></pre>
<p>This is the TaskStruct.cs</p>
<pre><code>public struct TaskStruct
{
public string date { get; set; }
public string start { get; set; }
public string end { get; set; }
public string betrag { get; set; }
public string todo { get; set; }
public bool done { get; set; }
public TaskStruct(string date, string start, string end, string betrag, string todo, bool done)
{
this.date = date;
this.start = start;
this.end = end;
this.betrag = betrag;
this.todo = todo;
this.done = done;
}
}
</code></pre>
<p>I then try todo this:</p>
<pre><code>
private async void ShowTasks()
{
foreach (TaskStruct task in await TaskApi.GetTasks())
{
MessageBox.Show(task.todo);
}
}
</code></pre>
<p>But i get a :
System.Reflection.TargetInvocationException: "Exception has been thrown by the target of an invocation."
After a few seconds.</p>
<p>This is the stacktrace:</p>
<pre><code> bei Flurl.Http.FlurlRequest.<HandleExceptionAsync>d__35.MoveNext()
bei Flurl.Http.FlurlResponse.<GetJsonAsync>d__18`1.MoveNext()
bei Flurl.Http.ResponseExtensions.<ReceiveJson>d__0`1.MoveNext()
bei AufgabenNet.TaskApi.<GetTasks>d__2.MoveNext() in C:\Users\justu\source\repos\AufgabenNet\AufgabenNet\TaskApi.cs: Zeile26
bei AufgabenNet.AufgabenNet.<ShowTasks>d__1.MoveNext() in C:\Users\justu\source\repos\AufgabenNet\AufgabenNet\Form1.cs: Zeile13
</code></pre>
<p>This is the inner exception:</p>
<pre><code>InnerException {"Could not cast or convert from System.String to AufgabenNet.TaskStruct."} System.Exception {System.ArgumentException}
</code></pre>
<p>this is the message:</p>
<pre><code>Message "Response could not be deserialized to JSON: GET http://127.0.0.1:5000/tasks/" string
</code></pre>
<p>Which is weird since it looks like valid json</p>
<p>It get the Error on:</p>
<pre><code>return await $"{BASE}tasks/".GetJsonAsync<List<TaskStruct>>();
</code></pre>
|
[
{
"answer_id": 74554726,
"author": "tymtam",
"author_id": 581076,
"author_profile": "https://Stackoverflow.com/users/581076",
"pm_score": 1,
"selected": false,
"text": "foreach(var task in tasks) List<TaskStruct> public async Task<List<TaskStruct>> GetTasks()\n{\n var json = await GetJsonAsync(); // try/catch maybe? \n if(string.IsNullOrEmpty(json) \n {\n ...\n }\n try \n {\n var l = JsonConvert.DeserializeObject<List<TaskStruct>>(json)\n return l; \n }\n catch(...) \n { \n ...\n }\n}\n"
},
{
"answer_id": 74555027,
"author": "Blue Eyed Behemoth",
"author_id": 3577195,
"author_profile": "https://Stackoverflow.com/users/3577195",
"pm_score": 1,
"selected": true,
"text": "[\n \"{\\\"id\\\": \\\"1\\\", \\\"date\\\": \\\"25.11.2022\\\", \\\"start\\\": \\\"10:00\\\", \\\"end\\\": \\\"13:00\\\", \\\"betrag\\\": \\\"15\\\\u20ac\\\", \\\"todo\\\": \\\"awdawd awd awd awd awd awd aw awa adw\\\", \\\"done\\\": true}\",\n \"{\\\"id\\\": \\\"2\\\", \\\"date\\\": \\\"26.11.2022\\\", \\\"start\\\": \\\"10:00\\\", \\\"end\\\": \\\"13:00\\\", \\\"betrag\\\": \\\"15\\\\u20ac\\\", \\\"todo\\\": \\\"awdawd awd awd awd awd awd aw awa adw\\\", \\\"done\\\": true}\",\n \"{\\\"id\\\": \\\"10362\\\", \\\"date\\\": \\\"26.11.2022\\\", \\\"start\\\": \\\"10:00\\\", \\\"end\\\": \\\"13:00\\\", \\\"betrag\\\": \\\"15\\\\u20ac\\\", \\\"todo\\\": \\\"awdawd awd awd awd awd awd aw awa adw\\\", \\\"done\\\": true}\",\n \"{\\\"id\\\": \\\"23726\\\", \\\"date\\\": \\\"25.11.2022\\\", \\\"start\\\": \\\"10:00\\\", \\\"end\\\": \\\"13:00\\\", \\\"betrag\\\": \\\"15\\\\u20ac\\\", \\\"todo\\\": \\\"awdawd awd awd awd awd awd aw awa adw\\\", \\\"done\\\": true}\",\n \"{\\\"id\\\": \\\"41445\\\", \\\"date\\\": \\\"26.11.2022\\\", \\\"start\\\": \\\"10:00\\\", \\\"end\\\": \\\"13:00\\\", \\\"betrag\\\": \\\"15\\\\u20ac\\\", \\\"todo\\\": \\\"TODO\\\\r\\\\n\\\\r\\\\n\\\\r\\\\nmehr\\\\r\\\\n\\\\r\\\\n222\\\\r\\\\n312\\\\r\\\\n312\\\\r\\\\n\\\", \\\"done\\\": false}\",\n \"{\\\"id\\\": \\\"49761\\\", \\\"date\\\": \\\"23.11.2022\\\", \\\"start\\\": \\\"Start\\\", \\\"end\\\": \\\"Ende\\\", \\\"betrag\\\": \\\"Betrag\\\", \\\"todo\\\": \\\"TODO\\\", \\\"done\\\": false}\",\n \"{\\\"id\\\": \\\"53618\\\", \\\"date\\\": \\\"23.11.2022\\\", \\\"start\\\": \\\"Start\\\", \\\"end\\\": \\\"Ende\\\", \\\"betrag\\\": \\\"Betrag\\\", \\\"todo\\\": \\\"TODO\\\", \\\"done\\\": false}\",\n \"{\\\"id\\\": \\\"54019\\\", \\\"date\\\": \\\"25.11.2022\\\", \\\"start\\\": \\\"10:00\\\", \\\"end\\\": \\\"13:00\\\", \\\"betrag\\\": \\\"15\\\\u20ac\\\", \\\"todo\\\": \\\"awdawd awd awd awd awd awd aw awa adw\\\", \\\"done\\\": true}\",\n \"{\\\"id\\\": \\\"87156\\\", \\\"date\\\": \\\"26.11.2022\\\", \\\"start\\\": \\\"10:00\\\", \\\"end\\\": \\\"13:00\\\", \\\"betrag\\\": \\\"15\\\\u20ac\\\", \\\"todo\\\": \\\"awdawd awd awd awd awd awd aw awa adw\\\", \\\"done\\\": true}\"\n]\n var taskStringList = await $\"{BASE}tasks/\".GetJsonAsync<string[]>();\nvar taskList = taskStringList.Select(s => JsonConvert.DeserializeObject<TaskStruct>(s)).ToList();\n [\n {\"id\": \"1\", \"date\": \"25.11.2022\", \"start\": \"10:00\", \"end\": \"13:00\", \"betrag\": \"15\\\\u20ac\", \"todo\": \"awdawd awd awd awd awd awd aw awa adw\", \"done\": true},\n {\"id\": \"2\", \"date\": \"26.11.2022\", \"start\": \"10:00\", \"end\": \"13:00\", \"betrag\": \"15\\\\u20ac\", \"todo\": \"awdawd awd awd awd awd awd aw awa adw\", \"done\": true},\n {\"id\": \"10362\", \"date\": \"26.11.2022\", \"start\": \"10:00\", \"end\": \"13:00\", \"betrag\": \"15\\\\u20ac\", \"todo\": \"awdawd awd awd awd awd awd aw awa adw\", \"done\": true},\n {\"id\": \"23726\", \"date\": \"25.11.2022\", \"start\": \"10:00\", \"end\": \"13:00\", \"betrag\": \"15\\\\u20ac\", \"todo\": \"awdawd awd awd awd awd awd aw awa adw\", \"done\": true},\n {\"id\": \"41445\", \"date\": \"26.11.2022\", \"start\": \"10:00\", \"end\": \"13:00\", \"betrag\": \"15\\\\u20ac\", \"todo\": \"TODO\\\\r\\\\n\\\\r\\\\n\\\\r\\\\nmehr\\\\r\\\\n\\\\r\\\\n222\\\\r\\\\n312\\\\r\\\\n312\\\\r\\\\n\", \"done\": false},\n {\"id\": \"49761\", \"date\": \"23.11.2022\", \"start\": \"Start\", \"end\": \"Ende\", \"betrag\": \"Betrag\", \"todo\": \"TODO\", \"done\": false},\n {\"id\": \"53618\", \"date\": \"23.11.2022\", \"start\": \"Start\", \"end\": \"Ende\", \"betrag\": \"Betrag\", \"todo\": \"TODO\", \"done\": false},\n {\"id\": \"54019\", \"date\": \"25.11.2022\", \"start\": \"10:00\", \"end\": \"13:00\", \"betrag\": \"15\\\\u20ac\", \"todo\": \"awdawd awd awd awd awd awd aw awa adw\", \"done\": true},\n {\"id\": \"87156\", \"date\": \"26.11.2022\", \"start\": \"10:00\", \"end\": \"13:00\", \"betrag\": \"15\\\\u20ac\", \"todo\": \"awdawd awd awd awd awd awd aw awa adw\", \"done\": true}\n]\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9897638/"
] |
74,554,633
|
<p>I am trying to aggregate A into a list of dictionaries. Oracle's <code>LISTAGG()</code> works but does run into the 4k max char limit. I tried with <code>XMLAGG</code> but now I'm getting "and quot;" instead of "". Please suggest the best way of resolving this. <code>XMLCAST</code> ? Will the final outputs of <code>listagg()</code> and the work around be identical ?</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>A</th>
<th>N</th>
</tr>
</thead>
<tbody>
<tr>
<td>{"1":"09","2":"11","3":"2010","4":"XYZ","5":""}</td>
<td>1</td>
</tr>
<tr>
<td>{"1":"09","2":"11","3":"2010","4":"XYZ","6":""}</td>
<td>2</td>
</tr>
<tr>
<td>{"1":"09","2":"11","3":"2010","4":"XYZ","7":""}</td>
<td>3</td>
</tr>
</tbody>
</table>
</div>
<pre><code>select
-- '[' ||
-- LISTAGG(cte.A, ' , ') WITHIN GROUP(
-- ORDER BY
-- cte.N
-- )
-- || ']'
'[' ||
rtrim(xmlagg(xmlelement(e,cte.A,', ').extract('//text()') order by cte.N).getclobval(),', ')
|| ']' aggr_lsts
from cte;
</code></pre>
<p>Bad Output:</p>
<pre><code>[{&quot;1&quot;:&quot;09&quot;,&quot;2&quot;:&quot;11&quot;,&quot;3&quot;:&quot;2010&quot;,&quot;4&quot;:&quot;XYZ&quot;,&quot;5&quot;:&quot;&quot;}, {&quot;1&quot;:&quot;09&quot;,&quot;2&quot;:&quot;11&quot;,&quot;3&quot;:&quot;2010&quot;,&quot;4&quot;:&quot;XYZ&quot;,&quot;6&quot;:&quot;&quot;}, {&quot;1&quot;:&quot;09&quot;,&quot;2&quot;:&quot;11&quot;,&quot;3&quot;:&quot;2010&quot;,&quot;4&quot;:&quot;XYZ&quot;,&quot;7&quot;:&quot;&quot;}]
</code></pre>
<p>Good Output:</p>
<pre><code>[{"1":"09","2":"11","3":"2010","4":"XYZ","5":""} , {"1":"09","2":"11","3":"2010","4":"XYZ","6":""} , {"1":"09","2":"11","3":"2010","4":"XYZ","7":""}]
</code></pre>
<p>Thank you.</p>
|
[
{
"answer_id": 74556098,
"author": "astentx",
"author_id": 2778710,
"author_profile": "https://Stackoverflow.com/users/2778710",
"pm_score": 2,
"selected": false,
"text": "xmlcast XMLQUERY XMLCAST with sample(col, rn) as (\n select column_value, rownum\n from sys.odcivarchar2list(\n '&',\n '>',\n '<',\n '\"',\n 'correctly serializable text'\n )\n)\nselect\n rtrim(xmlcast(xmlquery(\n '//text()'\n passing xmlagg(\n xmlelement(e,col,', ')\n order by rn\n )\n returning content\n ) as clob), ', ') as res\nfrom sample\n JSON_ARRAYAGG with sample(col, rn) as (\n select column_value, rownum\n from sys.odcivarchar2list(\n '{\"a\": 1, \"b\": \"2\"}',\n '{\"a\": 2, \"b\": \"qwe\"}',\n '{\"a\": 3, \"c\": \"test\"}'\n )\n)\nselect\n json_arrayagg(\n col order by rn\n ) as res\nfrom sample\n"
},
{
"answer_id": 74558917,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "JSONAGG SELECT JSON_ARRAYAGG(a FORMAT JSON ORDER BY n RETURNING CLOB) As output\nFROM table_name\n FORMAT JSON RETURNING CLOB VARCHAR2 LISTAGG CREATE TABLE table_name (A, N) AS\nSELECT '{\"1\":\"09\",\"2\":\"11\",\"3\":\"2010\",\"4\":\"XYZ\",\"5\":\"\"}', 1 FROM DUAL UNION ALL\nSELECT '{\"1\":\"09\",\"2\":\"11\",\"3\":\"2010\",\"4\":\"XYZ\",\"6\":\"\"}', 2 FROM DUAL UNION ALL\nSELECT '{\"1\":\"09\",\"2\":\"11\",\"3\":\"2010\",\"4\":\"XYZ\",\"7\":\"\"}', 3 FROM DUAL;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12048975/"
] |
74,554,644
|
<p>I'm trying to add a loginLoading observable where any component can subscribe to it to find weather a user is currently logging in or not.</p>
<p>In my <code>app.component.html</code>:</p>
<pre class="lang-html prettyprint-override"><code><mat-toolbar [ngClass]="{'disable-pointer': loginLoading}">
<a routerLink="login" routerLinkActive="active" id="login"> Login </a>
</mat-toolbar>
</code></pre>
<p>In my <code>app.component.ts</code>:</p>
<pre class="lang-ts prettyprint-override"><code> public loginLoading;
constructor(private authenticationService: AuthenticationService) {}
ngOnInit() {
this.authenticationService.loginLoading.subscribe(loginLoading => {
this.loginLoading = loginLoading;
})
}
</code></pre>
<p>In my <code>login.component.ts</code>:</p>
<pre class="lang-ts prettyprint-override"><code>
constructor(private authenticationService: AuthenticationService){}
ngOnInit(): void {
this.authenticationService.loginLoading.subscribe(loginLoading => this.loginLoading = loginLoading)
this.authenticationService.login().subscribe(
data => {
this.router.navigate([this.state],);
console.log(`after: ${this}`)
},
error => {
this.loginFailed = true
this.error = error.non_field_errors[0]
});
}
</code></pre>
<p>In my <code>AuthenticationService</code>:</p>
<pre class="lang-ts prettyprint-override"><code>private loginLoadingSubject: BehaviorSubject<boolean>;
public loginLoading: Observable<boolean>;
constructor(private http: HttpClient) {
this.loginLoadingSubject = new BehaviorSubject<boolean>(false);
this.loginLoading = this.loginLoadingSubject.asObservable();
}
login() {
this.loginLoadingSubject.next(true)
return this.http.post<any>(`${environment.apiUrl}/login`, {....})
.pipe(map(user => {
.
.
this.loginLoadingSubject.next(false)
.
.
}),
catchError(error => {
this.loginLoadingSubject.next(false)
return throwError(error);
}));
}
</code></pre>
<p>Also here is a very simplified example on <a href="https://stackblitz.com/edit/angular-ivy-tnceho?file=src/app/app.component.html" rel="nofollow noreferrer">stackblitz</a>.</p>
<p>My question is why doesn't angular detect the change in the app's component <code>loginLoading</code> field
in this line <code>this.loginLoading = loginLoading;</code>? Shouldn't this trigger a change detection cycle?</p>
<p>Also if I move the code in the <code>LoginComponent</code>'s <code>ngOnInit()</code> to the <code>LoginComponent</code>'s constructor the error does not appear, does this mean that angular checks for changes after the constructor and befor the <code>ngOnInit()</code>?</p>
<p>I solve this by running change detection manually after this line <code>this.loginLoading = loginLoading;</code> in the <code>AppComponent</code> but i'd prefer if i don't or at least know why should I.</p>
<p>Edit:
I understand that in development mode, angular checks the model didn't change using 1 extra check. What I assumed would happen is since an observable firing a new value would trigger a new change detection cycle the error shouldn't appear.</p>
<p>To my understanding that if an observable fire between the 2 checks (and it's value is bound to the view), angular wouldn't know (and wouldn't trigger change detection again) and therefore the error appears after the second check</p>
|
[
{
"answer_id": 74556098,
"author": "astentx",
"author_id": 2778710,
"author_profile": "https://Stackoverflow.com/users/2778710",
"pm_score": 2,
"selected": false,
"text": "xmlcast XMLQUERY XMLCAST with sample(col, rn) as (\n select column_value, rownum\n from sys.odcivarchar2list(\n '&',\n '>',\n '<',\n '\"',\n 'correctly serializable text'\n )\n)\nselect\n rtrim(xmlcast(xmlquery(\n '//text()'\n passing xmlagg(\n xmlelement(e,col,', ')\n order by rn\n )\n returning content\n ) as clob), ', ') as res\nfrom sample\n JSON_ARRAYAGG with sample(col, rn) as (\n select column_value, rownum\n from sys.odcivarchar2list(\n '{\"a\": 1, \"b\": \"2\"}',\n '{\"a\": 2, \"b\": \"qwe\"}',\n '{\"a\": 3, \"c\": \"test\"}'\n )\n)\nselect\n json_arrayagg(\n col order by rn\n ) as res\nfrom sample\n"
},
{
"answer_id": 74558917,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "JSONAGG SELECT JSON_ARRAYAGG(a FORMAT JSON ORDER BY n RETURNING CLOB) As output\nFROM table_name\n FORMAT JSON RETURNING CLOB VARCHAR2 LISTAGG CREATE TABLE table_name (A, N) AS\nSELECT '{\"1\":\"09\",\"2\":\"11\",\"3\":\"2010\",\"4\":\"XYZ\",\"5\":\"\"}', 1 FROM DUAL UNION ALL\nSELECT '{\"1\":\"09\",\"2\":\"11\",\"3\":\"2010\",\"4\":\"XYZ\",\"6\":\"\"}', 2 FROM DUAL UNION ALL\nSELECT '{\"1\":\"09\",\"2\":\"11\",\"3\":\"2010\",\"4\":\"XYZ\",\"7\":\"\"}', 3 FROM DUAL;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16198850/"
] |
74,554,660
|
<p>Suppose I have a table as follows:</p>
<pre><code>symbol date price volume
GE 2017.01.03 31.82 2,300
GE 2017.01.03 31.69 3,500
GE 2017.01.04 31.92 3,700
GE 2017.01.04 31.8 2,100
GE 2017.01.04 31.75 1,200
GE 2017.01.04 31.76 4,600
MSFT 2017.01.03 63.12 1,800
MSFT 2017.01.03 62.58 3,800
MSFT 2017.01.04 63.12 6,400
MSFT 2017.01.04 62.77 4,200
MSFT 2017.01.04 61.86 2,300
MSFT 2017.01.04 62.3 6,800
F 2017.01.03 12.46 4,200
F 2017.01.03 12.59 5,600
F 2017.01.04 13.24 8,900
F 2017.01.04 13.41 2,300
F 2017.01.04 13.36 6,300
F 2017.01.04 13.17 9,600
</code></pre>
<p>I want to perform some kind of aggregation (say, <code>avg(price)</code> or <code>sum(volume)</code>) by date over all MSFT records. Meanwhile, I want to rename the returned field with the string (like “avgPrice“ or “sumVol“) that is passed in through a variable. Any ideas how I could do this?</p>
<p>Thanks!</p>
<p><em>P.S. The table can be created with the following script:</em></p>
<pre><code>symbol = take(`GE,6) join take(`MSFT,6) join take(`F,6)
date=take(take(2017.01.03,2) join take(2017.01.04,4), 18)
price=31.82 31.69 31.92 31.8 31.75 31.76 63.12 62.58 63.12 62.77 61.86 62.3 12.46 12.59 13.24 13.41 13.36 13.17
volume=2300 3500 3700 2100 1200 4600 1800 3800 6400 4200 2300 6800 4200 5600 8900 2300 6300 9600
t1 = table(symbol, date, price, volume);
t1;
</code></pre>
|
[
{
"answer_id": 74554678,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "SELECT AVG(price) AS avgPrice, SUM(volume) AS sumVol\nFROM yourTable\nWHERE symbol = 'MSFT';\n SELECT symbol, AVG(price) AS avgPrice, SUM(volume) AS sumVol\nFROM yourTable\nGROUP BY symbol;\n"
},
{
"answer_id": 74567621,
"author": "ifyoucouldplz",
"author_id": 20567816,
"author_profile": "https://Stackoverflow.com/users/20567816",
"pm_score": 3,
"selected": true,
"text": "name1 = `avgPrice\nname2 = `sumVol\nwhereConditions = [<symbol=`MSFT>,<volume>x>]\nsql(select=(sqlColAlias(<avg(price)>, name1), sqlColAlias(<sum(volume)>, name2)), from=t1, groupBy=sqlCol(`date)).eval()\n date avgPrice sumVol\n2017.01.03 35.71 21,200\n2017.01.04 35.8717 58,400\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15526999/"
] |
74,554,667
|
<p>What I want to have is nested data grouped by the day number.</p>
<p>This is an example of a array that I want to group. I am using the lodash plugin.</p>
<pre><code>[{
"Pnl": 29.0035635,
"date": "11/14/2022",
"dayNumber": 1,
"translationDayOfWeek": "Monday"
},
{
"Pnl": 50.8878545,
"date": "11/08/2022",
"dayNumber": 2,
"translationDayOfWeek": "Tuesday"
},
{
"Pnl": 73.1014552,
"date": "11/08/2022",
"dayNumber": 2,
"translationDayOfWeek": "Tuesday"
},
{
"Pnl": 32.477,
"date": "11/08/2022",
"dayNumber": 6,
"translationDayOfWeek": "Saturday"
},
{
"Pnl": 25.43999561,
"date": "09/30/2022",
"dayNumber": 5,
"translationDayOfWeek": "Friday"
},
{
"Pnl": 17.6294068,
"date": "09/30/2022",
"dayNumber": 1,
"translationDayOfWeek": "Monday"
}]
</code></pre>
<p>This is want I want for a output:</p>
<pre><code>[
{
"dayNumber": 1,
"orders": [
{
"Pnl": 29.0035635,
"date": "11/14/2022",
"dayNumber": 1,
"translationDayOfWeek": "Monday"
},
{
"Pnl": 17.6294068,
"date": "09/30/2022",
"dayNumber": 1,
"translationDayOfWeek": "Monday"
}
]
},
{
"dayNumber": 2,
"orders": [
{
"Pnl": 50.8878545,
"date": "11/08/2022",
"dayNumber": 2,
"translationDayOfWeek": "Tuesday"
},
{
"Pnl": 73.1014552,
"date": "11/08/2022",
"dayNumber": 2,
"translationDayOfWeek": "Tuesday"
}
]
}
]
</code></pre>
<p>I tried the solutions on <a href="https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value">stackoverflow post</a> but it's not the result I need.</p>
|
[
{
"answer_id": 74554725,
"author": "danh",
"author_id": 294949,
"author_profile": "https://Stackoverflow.com/users/294949",
"pm_score": 0,
"selected": false,
"text": "reduce() let data = [{\n \"Pnl\": 29.0035635,\n \"date\": \"11/14/2022\",\n \"dayNumber\": 1,\n \"translationDayOfWeek\": \"Monday\"\n},\n{\n \"Pnl\": 50.8878545,\n \"date\": \"11/08/2022\",\n \"dayNumber\": 2,\n \"translationDayOfWeek\": \"Tuesday\"\n},\n{\n \"Pnl\": 73.1014552,\n \"date\": \"11/08/2022\",\n \"dayNumber\": 2,\n \"translationDayOfWeek\": \"Tuesday\"\n},\n{\n \"Pnl\": 32.477,\n \"date\": \"11/08/2022\",\n \"dayNumber\": 6,\n \"translationDayOfWeek\": \"Saturday\"\n},\n{\n \"Pnl\": 25.43999561,\n \"date\": \"09/30/2022\",\n \"dayNumber\": 5,\n \"translationDayOfWeek\": \"Friday\"\n},\n{\n \"Pnl\": 17.6294068,\n \"date\": \"09/30/2022\",\n \"dayNumber\": 1,\n \"translationDayOfWeek\": \"Monday\"\n}];\n\nlet grouped = data.reduce((acc, el) => {\n let dayNumber = el.dayNumber;\n acc[dayNumber] ??= { dayNumber, orders: [] };\n acc[dayNumber].orders.push(el);\n return acc;\n}, {});\ngrouped = Object.values(grouped).sort((a,b) => a.dayNumber-b.dayNumber);\n\nconsole.log(grouped) orders grouped.forEach(group => group.orders.sort((a,b) => {\n /* sort based on some prop the OP hasn't defined */\n});\n"
},
{
"answer_id": 74554730,
"author": "Shakya Peiris",
"author_id": 14953535,
"author_profile": "https://Stackoverflow.com/users/14953535",
"pm_score": 0,
"selected": false,
"text": "const arr = [{\n \"Pnl\": 29.0035635,\n \"date\": \"11/14/2022\",\n \"dayNumber\": 1,\n \"translationDayOfWeek\": \"Monday\"\n},\n{\n \"Pnl\": 50.8878545,\n \"date\": \"11/08/2022\",\n \"dayNumber\": 2,\n \"translationDayOfWeek\": \"Tuesday\"\n},\n{\n \"Pnl\": 73.1014552,\n \"date\": \"11/08/2022\",\n \"dayNumber\": 2,\n \"translationDayOfWeek\": \"Tuesday\"\n},\n{\n \"Pnl\": 32.477,\n \"date\": \"11/08/2022\",\n \"dayNumber\": 6,\n \"translationDayOfWeek\": \"Saturday\"\n},\n{\n \"Pnl\": 25.43999561,\n \"date\": \"09/30/2022\",\n \"dayNumber\": 5,\n \"translationDayOfWeek\": \"Friday\"\n},\n{\n \"Pnl\": 17.6294068,\n \"date\": \"09/30/2022\",\n \"dayNumber\": 1,\n \"translationDayOfWeek\": \"Monday\"\n}];\nconst newArr = [];\n\narr.forEach((i) => {\n if (newArr.find(j => j.dayNumber === i.dayNumber)){\n const index = newArr.findIndex(j => j.dayNumber === i.dayNumber)\n newArr[index].orders.push(i);\n }\n else {\n newArr.push({\n dayNumber: i.dayNumber,\n orders: [i]\n })\n }\n})\n\nnewArr.sort((a, b) => parseInt(a.dayNumber) - parseInt(b.dayNumber))\n\nconsole.log(newArr)"
},
{
"answer_id": 74554744,
"author": "subodhkalika",
"author_id": 6682406,
"author_profile": "https://Stackoverflow.com/users/6682406",
"pm_score": 3,
"selected": true,
"text": "const arr = []; //your array\n_.map(\n _.groupBy(arr, function (obj) {return obj.dayNumber}),\n (order,index) => ({dayNumber: index, orders: order})\n)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20374959/"
] |
74,554,671
|
<p>I'm learning and trying to add parameters when calling parameters in functions when getting data from the API, but I'm a bit confused about how I call them in widgets.</p>
<pre><code>static Future<Map<String, DataKuliahModel>> getDataKuliah(String smt) async {
String url = Constant.baseURL;
String token = await UtilSharedPreferences.getToken();
await Future.delayed(const Duration(milliseconds: 1000));
// String responseJson = await rootBundle.loadString('assets/1.json');
Map<String, DataKuliahModel> finalResult = {};
final response = await http.get(
Uri.parse(
'$url/auth/mhs_siakad/perwalian/get_paket',
),
headers: {
'Authorization': 'Bearer $token',
},
);
final result = jsonDecode(response.body)['data'] as Map<String, dynamic>;
result.forEach((key, value) {
DataKuliahModel dataKuliah = DataKuliahModel.fromMap(value);
finalResult.addAll({
key: dataKuliah,
});
});
return finalResult;
}
</code></pre>
<p>and I want to call him here
<a href="https://i.stack.imgur.com/PRbf5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PRbf5.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74554790,
"author": "Soliev",
"author_id": 19945688,
"author_profile": "https://Stackoverflow.com/users/19945688",
"pm_score": 2,
"selected": true,
"text": "import 'package:flutter/material.dart';\n\nclass Services {\n static Future<String> greeting(String name) async {\n /// this function doesn't need to be Future\n /// but when you call API to get some data it should be a Future\n\n return 'Hello $name';\n }\n}\n\nclass MyWidget extends StatelessWidget {\n const MyWidget({super.key});\n\n @override\n Widget build(BuildContext context) {\n return FutureBuilder(\n\n /// pass positional parameter to [greeting] here\n future: Services.greeting('Dash'), \n builder: (context, AsyncSnapshot<String> snapshot) {\n return Center(\n child: Text(snapshot.data ?? 'default'),\n );\n },\n );\n }\n}\n\n smt int String static Future<Map<String, DataKuliahModel>> getDataKuliah(int smt) async {\n String url = Constant.baseURL;\n String token = await UtilSharedPreferences.getToken();\n await Future.delayed(const Duration(milliseconds: 1000));\n // String responseJson = await rootBundle.loadString('assets/1.json');\n\n Map<String, DataKuliahModel> finalResult = {};\n final response = await http.get(\n // Uri.parse(\n // '$url/auth/mhs_siakad/perwalian/get_paket',\n // ),\n Uri.http(url, '/auth/mhs_siakad/perwalian/get_paket', \n {'smt':smt}),\n headers: {\n 'Authorization': 'Bearer $token',\n },\n );\n final result = jsonDecode(response.body)['data'] as Map<String, dynamic>;\n result.forEach((key, value) {\n DataKuliahModel dataKuliah = DataKuliahModel.fromMap(value);\n finalResult.addAll({\n key: dataKuliah,\n });\n });\n return finalResult;\n }\n\n"
},
{
"answer_id": 74555032,
"author": "baek",
"author_id": 1049200,
"author_profile": "https://Stackoverflow.com/users/1049200",
"pm_score": 0,
"selected": false,
"text": "Uri.parse('$url/auth/mhs_siakad/perwalian/get_paket').replace(queryParameters:{ \"smt\":\"$smt\"}); \n // Put this outside your build function\nFuture<Map<String, DataKuliahModel>> DK ; \n\n// Put this in your initState if you want the future to run on page load or use it for events like onTap \nDK = Service.getDataKuliah(<PARAM>); \n\n// This is in your build method\nFutureBuilder(\n\nfuture:DK,\nbuilder: (context, snapshot) {\n// add wigets to display results here\n\n}\n\n)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19132574/"
] |
74,554,704
|
<p>I get these errors when I try to statically link my Go program that uses Gopacket:</p>
<pre><code>/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/libpcap.a(pcap-dbus.o): in function `dbus_write':
(.text+0x103): undefined reference to `dbus_message_demarshal'
/usr/bin/ld: (.text+0x119): undefined reference to `dbus_connection_send'
/usr/bin/ld: (.text+0x122): undefined reference to `dbus_connection_flush'
/usr/bin/ld: (.text+0x12a): undefined reference to `dbus_message_unref'
/usr/bin/ld: (.text+0x178): undefined reference to `dbus_error_free'
/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/libpcap.a(pcap-dbus.o): in function `dbus_read':
(.text+0x1c3): undefined reference to `dbus_connection_pop_message'
/usr/bin/ld: (.text+0x1e1): undefined reference to `dbus_connection_pop_message'
/usr/bin/ld: (.text+0x1f6): undefined reference to `dbus_connection_read_write'
/usr/bin/ld: (.text+0x262): undefined reference to `dbus_message_is_signal'
/usr/bin/ld: (.text+0x27f): undefined reference to `dbus_message_marshal'
/usr/bin/ld: (.text+0x2e3): undefined reference to `dbus_free'
/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/libpcap.a(pcap-dbus.o): in function `dbus_cleanup':
(.text+0x350): undefined reference to `dbus_connection_unref'
/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/libpcap.a(pcap-dbus.o): in function `dbus_activate':
(.text+0x3fa): undefined reference to `dbus_connection_open'
/usr/bin/ld: (.text+0x412): undefined reference to `dbus_bus_register'
...
</code></pre>
<p>Indeed these symbols indeed either do not exist <code>/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/libpcap.a</code> or show up as undefined. For example:</p>
<pre><code>$ readelf -s /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/libpcap.a | grep dbus_message_marshal
42: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND dbus_message_marshal
</code></pre>
<p>None of these functions are called from my program, but are happening because of the dependency to Gopacket.</p>
<p>I have <code>libpcap</code> installed:</p>
<pre><code>$ apt list --installed|grep pcap
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
libpcap-dev/jammy,now 1.10.1-4build1 amd64 [installed]
libpcap0.8-dev/jammy,now 1.10.1-4build1 amd64 [installed]
libpcap0.8/jammy,now 1.10.1-4build1 amd64 [installed,automatic]
</code></pre>
<p>Is there anything else I need? Here's how I compile:</p>
<pre><code>GOOS=linux CGO_ENABLED=1 go build \
-ldflags "-linkmode external -extldflags \"-static\"" \
-o bin/myprog \
-buildvcs=false
</code></pre>
<p>If I do not include <code>-ldflags</code>, the program compiles, but it is not statically linked.</p>
<p>I am using Go 1.18.</p>
|
[
{
"answer_id": 74554790,
"author": "Soliev",
"author_id": 19945688,
"author_profile": "https://Stackoverflow.com/users/19945688",
"pm_score": 2,
"selected": true,
"text": "import 'package:flutter/material.dart';\n\nclass Services {\n static Future<String> greeting(String name) async {\n /// this function doesn't need to be Future\n /// but when you call API to get some data it should be a Future\n\n return 'Hello $name';\n }\n}\n\nclass MyWidget extends StatelessWidget {\n const MyWidget({super.key});\n\n @override\n Widget build(BuildContext context) {\n return FutureBuilder(\n\n /// pass positional parameter to [greeting] here\n future: Services.greeting('Dash'), \n builder: (context, AsyncSnapshot<String> snapshot) {\n return Center(\n child: Text(snapshot.data ?? 'default'),\n );\n },\n );\n }\n}\n\n smt int String static Future<Map<String, DataKuliahModel>> getDataKuliah(int smt) async {\n String url = Constant.baseURL;\n String token = await UtilSharedPreferences.getToken();\n await Future.delayed(const Duration(milliseconds: 1000));\n // String responseJson = await rootBundle.loadString('assets/1.json');\n\n Map<String, DataKuliahModel> finalResult = {};\n final response = await http.get(\n // Uri.parse(\n // '$url/auth/mhs_siakad/perwalian/get_paket',\n // ),\n Uri.http(url, '/auth/mhs_siakad/perwalian/get_paket', \n {'smt':smt}),\n headers: {\n 'Authorization': 'Bearer $token',\n },\n );\n final result = jsonDecode(response.body)['data'] as Map<String, dynamic>;\n result.forEach((key, value) {\n DataKuliahModel dataKuliah = DataKuliahModel.fromMap(value);\n finalResult.addAll({\n key: dataKuliah,\n });\n });\n return finalResult;\n }\n\n"
},
{
"answer_id": 74555032,
"author": "baek",
"author_id": 1049200,
"author_profile": "https://Stackoverflow.com/users/1049200",
"pm_score": 0,
"selected": false,
"text": "Uri.parse('$url/auth/mhs_siakad/perwalian/get_paket').replace(queryParameters:{ \"smt\":\"$smt\"}); \n // Put this outside your build function\nFuture<Map<String, DataKuliahModel>> DK ; \n\n// Put this in your initState if you want the future to run on page load or use it for events like onTap \nDK = Service.getDataKuliah(<PARAM>); \n\n// This is in your build method\nFutureBuilder(\n\nfuture:DK,\nbuilder: (context, snapshot) {\n// add wigets to display results here\n\n}\n\n)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2233706/"
] |
74,554,710
|
<p>Let's say I have two files <code>video.webm</code> and <code>audio.webm</code>. These two files are supposed to be one file combined together, which will become a 'regular' video + audio file. Is this possible using JavaScript?</p>
<p>Example (these are not the actual fetch)</p>
<pre class="lang-js prettyprint-override"><code>const video = await fetch('https://harry-potter.com/video'); // Gets video file of movie Harry Potter.
const videoBlob = await video.blob();
const audio = await fetch('https://harry-potter.com/audio'); // Gets audio file of movie Harry Potter.
const auidoBlob = await audio.blob();
const finalBlob = videoBlob + audioBlob; // I want to combine two blobs.
</code></pre>
|
[
{
"answer_id": 74554790,
"author": "Soliev",
"author_id": 19945688,
"author_profile": "https://Stackoverflow.com/users/19945688",
"pm_score": 2,
"selected": true,
"text": "import 'package:flutter/material.dart';\n\nclass Services {\n static Future<String> greeting(String name) async {\n /// this function doesn't need to be Future\n /// but when you call API to get some data it should be a Future\n\n return 'Hello $name';\n }\n}\n\nclass MyWidget extends StatelessWidget {\n const MyWidget({super.key});\n\n @override\n Widget build(BuildContext context) {\n return FutureBuilder(\n\n /// pass positional parameter to [greeting] here\n future: Services.greeting('Dash'), \n builder: (context, AsyncSnapshot<String> snapshot) {\n return Center(\n child: Text(snapshot.data ?? 'default'),\n );\n },\n );\n }\n}\n\n smt int String static Future<Map<String, DataKuliahModel>> getDataKuliah(int smt) async {\n String url = Constant.baseURL;\n String token = await UtilSharedPreferences.getToken();\n await Future.delayed(const Duration(milliseconds: 1000));\n // String responseJson = await rootBundle.loadString('assets/1.json');\n\n Map<String, DataKuliahModel> finalResult = {};\n final response = await http.get(\n // Uri.parse(\n // '$url/auth/mhs_siakad/perwalian/get_paket',\n // ),\n Uri.http(url, '/auth/mhs_siakad/perwalian/get_paket', \n {'smt':smt}),\n headers: {\n 'Authorization': 'Bearer $token',\n },\n );\n final result = jsonDecode(response.body)['data'] as Map<String, dynamic>;\n result.forEach((key, value) {\n DataKuliahModel dataKuliah = DataKuliahModel.fromMap(value);\n finalResult.addAll({\n key: dataKuliah,\n });\n });\n return finalResult;\n }\n\n"
},
{
"answer_id": 74555032,
"author": "baek",
"author_id": 1049200,
"author_profile": "https://Stackoverflow.com/users/1049200",
"pm_score": 0,
"selected": false,
"text": "Uri.parse('$url/auth/mhs_siakad/perwalian/get_paket').replace(queryParameters:{ \"smt\":\"$smt\"}); \n // Put this outside your build function\nFuture<Map<String, DataKuliahModel>> DK ; \n\n// Put this in your initState if you want the future to run on page load or use it for events like onTap \nDK = Service.getDataKuliah(<PARAM>); \n\n// This is in your build method\nFutureBuilder(\n\nfuture:DK,\nbuilder: (context, snapshot) {\n// add wigets to display results here\n\n}\n\n)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13538357/"
] |
74,554,750
|
<p>So I have 2 different true or false results that tested the same column. So test 1 has the wrong results and test 2 has the correct results. Is there python code that can compare these two results and obtain a confusion matrix result (true positives, false positives, false negatives, and true negatives)?</p>
<p>For example:</p>
<pre><code>Test1
a True
b True
c False
d False
e True
f True
g True
Test2
a True
b True
c True
d True
e True
f True
g False
</code></pre>
|
[
{
"answer_id": 74554790,
"author": "Soliev",
"author_id": 19945688,
"author_profile": "https://Stackoverflow.com/users/19945688",
"pm_score": 2,
"selected": true,
"text": "import 'package:flutter/material.dart';\n\nclass Services {\n static Future<String> greeting(String name) async {\n /// this function doesn't need to be Future\n /// but when you call API to get some data it should be a Future\n\n return 'Hello $name';\n }\n}\n\nclass MyWidget extends StatelessWidget {\n const MyWidget({super.key});\n\n @override\n Widget build(BuildContext context) {\n return FutureBuilder(\n\n /// pass positional parameter to [greeting] here\n future: Services.greeting('Dash'), \n builder: (context, AsyncSnapshot<String> snapshot) {\n return Center(\n child: Text(snapshot.data ?? 'default'),\n );\n },\n );\n }\n}\n\n smt int String static Future<Map<String, DataKuliahModel>> getDataKuliah(int smt) async {\n String url = Constant.baseURL;\n String token = await UtilSharedPreferences.getToken();\n await Future.delayed(const Duration(milliseconds: 1000));\n // String responseJson = await rootBundle.loadString('assets/1.json');\n\n Map<String, DataKuliahModel> finalResult = {};\n final response = await http.get(\n // Uri.parse(\n // '$url/auth/mhs_siakad/perwalian/get_paket',\n // ),\n Uri.http(url, '/auth/mhs_siakad/perwalian/get_paket', \n {'smt':smt}),\n headers: {\n 'Authorization': 'Bearer $token',\n },\n );\n final result = jsonDecode(response.body)['data'] as Map<String, dynamic>;\n result.forEach((key, value) {\n DataKuliahModel dataKuliah = DataKuliahModel.fromMap(value);\n finalResult.addAll({\n key: dataKuliah,\n });\n });\n return finalResult;\n }\n\n"
},
{
"answer_id": 74555032,
"author": "baek",
"author_id": 1049200,
"author_profile": "https://Stackoverflow.com/users/1049200",
"pm_score": 0,
"selected": false,
"text": "Uri.parse('$url/auth/mhs_siakad/perwalian/get_paket').replace(queryParameters:{ \"smt\":\"$smt\"}); \n // Put this outside your build function\nFuture<Map<String, DataKuliahModel>> DK ; \n\n// Put this in your initState if you want the future to run on page load or use it for events like onTap \nDK = Service.getDataKuliah(<PARAM>); \n\n// This is in your build method\nFutureBuilder(\n\nfuture:DK,\nbuilder: (context, snapshot) {\n// add wigets to display results here\n\n}\n\n)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20558532/"
] |
74,554,763
|
<p>It seems that all the examples in the search result are using binding, updating the bound variable oninput. Is this the only approved way other than using external JavaScript? I mean, if I have assigned a <code>@ref</code>, can't I get the current value using the @ref variable, hypothetically like</p>
<pre><code><input type="text" @ref="myinputbox" />
....
string value = myinputbox.Value;
</code></pre>
|
[
{
"answer_id": 74554790,
"author": "Soliev",
"author_id": 19945688,
"author_profile": "https://Stackoverflow.com/users/19945688",
"pm_score": 2,
"selected": true,
"text": "import 'package:flutter/material.dart';\n\nclass Services {\n static Future<String> greeting(String name) async {\n /// this function doesn't need to be Future\n /// but when you call API to get some data it should be a Future\n\n return 'Hello $name';\n }\n}\n\nclass MyWidget extends StatelessWidget {\n const MyWidget({super.key});\n\n @override\n Widget build(BuildContext context) {\n return FutureBuilder(\n\n /// pass positional parameter to [greeting] here\n future: Services.greeting('Dash'), \n builder: (context, AsyncSnapshot<String> snapshot) {\n return Center(\n child: Text(snapshot.data ?? 'default'),\n );\n },\n );\n }\n}\n\n smt int String static Future<Map<String, DataKuliahModel>> getDataKuliah(int smt) async {\n String url = Constant.baseURL;\n String token = await UtilSharedPreferences.getToken();\n await Future.delayed(const Duration(milliseconds: 1000));\n // String responseJson = await rootBundle.loadString('assets/1.json');\n\n Map<String, DataKuliahModel> finalResult = {};\n final response = await http.get(\n // Uri.parse(\n // '$url/auth/mhs_siakad/perwalian/get_paket',\n // ),\n Uri.http(url, '/auth/mhs_siakad/perwalian/get_paket', \n {'smt':smt}),\n headers: {\n 'Authorization': 'Bearer $token',\n },\n );\n final result = jsonDecode(response.body)['data'] as Map<String, dynamic>;\n result.forEach((key, value) {\n DataKuliahModel dataKuliah = DataKuliahModel.fromMap(value);\n finalResult.addAll({\n key: dataKuliah,\n });\n });\n return finalResult;\n }\n\n"
},
{
"answer_id": 74555032,
"author": "baek",
"author_id": 1049200,
"author_profile": "https://Stackoverflow.com/users/1049200",
"pm_score": 0,
"selected": false,
"text": "Uri.parse('$url/auth/mhs_siakad/perwalian/get_paket').replace(queryParameters:{ \"smt\":\"$smt\"}); \n // Put this outside your build function\nFuture<Map<String, DataKuliahModel>> DK ; \n\n// Put this in your initState if you want the future to run on page load or use it for events like onTap \nDK = Service.getDataKuliah(<PARAM>); \n\n// This is in your build method\nFutureBuilder(\n\nfuture:DK,\nbuilder: (context, snapshot) {\n// add wigets to display results here\n\n}\n\n)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/455796/"
] |
74,554,765
|
<p>I have an iterator of characters, and I want to add a newline every N characters:</p>
<pre><code>let iter = "abcdefghijklmnopqrstuvwxyz".chars();
let iter_with_newlines = todo!();
let string: String = iter_with_newlines.collect();
assert_eq("abcdefghij\nklmnopqrst\nuvwxyz", string);
</code></pre>
<p>So basically, I want to intersperse the iterator with a newline every n characters. How can I do this?</p>
<h2>Some Ideas I had</h2>
<p>It would be great if I could do something like this, where <code>chunks</code> would be a method to make <code>Iterator<T></code> into <code>Iterator<Iterator<T></code>: <code>iter.chunks(10).intersperse('\n').flatten()</code></p>
<p>It would also be cool if I could do something like this: <code>iter.chunks.intersperseEvery(10, '\n')</code>, where <code>intersperseEvery</code> is a method that would only intersperse the value every n items.</p>
|
[
{
"answer_id": 74554890,
"author": "Caesar",
"author_id": 401059,
"author_profile": "https://Stackoverflow.com/users/401059",
"pm_score": 1,
"selected": false,
"text": "chunks itertools Vec Vec use itertools::Itertools;\niter\n .chunks(3)\n .into_iter()\n .map(|chunk| chunk.collect::<Vec<_>>())\n .intersperse(vec![','])\n .flat_map(|chunk| chunk.into_iter())\n .collect::<String>();\n"
},
{
"answer_id": 74557357,
"author": "Jmb",
"author_id": 5397009,
"author_profile": "https://Stackoverflow.com/users/5397009",
"pm_score": 2,
"selected": false,
"text": "enumerate flat_map use either::Either;\n\nfn main() {\n let iter = \"abcdefghijklmnopqrstuvwxyz\".chars();\n let iter_with_newlines = iter\n .enumerate()\n .flat_map(|(i, c)| {\n if i % 10 == 0 {\n Either::Left(['\\n', c].into_iter())\n } else {\n Either::Right(std::iter::once(c))\n }\n })\n .skip(1); // The above code add a newline in first position -> skip it\n let string: String = iter_with_newlines.collect();\n assert_eq!(\"abcdefghij\\nklmnopqrst\\nuvwxyz\", string);\n}\n"
},
{
"answer_id": 74587443,
"author": "asdf3.14159",
"author_id": 15478835,
"author_profile": "https://Stackoverflow.com/users/15478835",
"pm_score": 1,
"selected": false,
"text": "// src/intersperse_sparse.rs\n\nuse core::iter::Peekable;\n\n/// An iterator adaptor to insert a particular value\n/// every n elements of the adapted iterator.\n///\n/// Iterator element type is `I::Item`\npub struct IntersperseSparse<I>\nwhere\n I: Iterator,\n I::Item: Clone,\n{\n iter: Peekable<I>,\n step_length: usize,\n index: usize,\n separator: I::Item,\n}\n\nimpl<I> IntersperseSparse<I>\nwhere\n I: Iterator,\n I::Item: Clone,\n{\n #[allow(unused)] // Although this function isn't explicitly exported, it is called in the default implementation of the IntersperseSparseAdapter, which is exported.\n fn new(iter: I, step_length: usize, separator: I::Item) -> Self {\n if step_length == 0 {\n panic!(\"Chunk size cannot be 0!\")\n }\n Self {\n iter: iter.peekable(),\n step_length,\n separator,\n index: 0,\n }\n }\n}\n\nimpl<I> Iterator for IntersperseSparse<I>\nwhere\n I: Iterator,\n I::Item: Clone,\n{\n type Item = I::Item;\n fn next(&mut self) -> Option<Self::Item> {\n if self.index == self.step_length && self.iter.peek().is_some() {\n self.index = 0;\n Some(self.separator.clone())\n } else {\n self.index += 1;\n self.iter.next()\n }\n }\n}\n\n/// An iterator adaptor to insert a particular value created by a function\n/// every n elements of the adapted iterator.\n///\n/// Iterator element type is `I::Item`\npub struct IntersperseSparseWith<I, G>\nwhere\n I: Iterator,\n G: FnMut() -> I::Item,\n{\n iter: Peekable<I>,\n step_length: usize,\n index: usize,\n separator_closure: G,\n}\n\nimpl<I, G> IntersperseSparseWith<I, G>\nwhere\n I: Iterator,\n G: FnMut() -> I::Item,\n{\n #[allow(unused)] // Although this function isn't explicitly exported, it is called in the default implementation of the IntersperseSparseAdapter, which is exported.\n fn new(iter: I, step_length: usize, separator_closure: G) -> Self {\n if step_length == 0 {\n panic!(\"Chunk size cannot be 0!\")\n }\n Self {\n iter: iter.peekable(),\n step_length,\n separator_closure,\n index: 0,\n }\n }\n}\n\nimpl<I, G> Iterator for IntersperseSparseWith<I, G>\nwhere\n I: Iterator,\n G: FnMut() -> I::Item,\n{\n type Item = I::Item;\n fn next(&mut self) -> Option<Self::Item> {\n if self.index == self.step_length && self.iter.peek().is_some() {\n self.index = 0;\n Some((self.separator_closure)())\n } else {\n self.index += 1;\n self.iter.next()\n }\n }\n}\n\n/// Import this trait to use the `iter.intersperse_sparse(n, item)` and `iter.intersperse_sparse(n, ||item)` on all iterators.\npub trait IntersperseSparseAdapter: Iterator {\n fn intersperse_sparse(self, chunk_size: usize, separator: Self::Item) -> IntersperseSparse<Self>\n where\n Self: Sized,\n Self::Item: Clone,\n {\n IntersperseSparse::new(self, chunk_size, separator)\n }\n\n fn intersperse_sparse_with<G>(\n self,\n chunk_size: usize,\n separator_closure: G,\n ) -> IntersperseSparseWith<Self, G>\n where\n Self: Sized,\n G: FnMut() -> Self::Item,\n {\n IntersperseSparseWith::new(self, chunk_size, separator_closure)\n }\n}\n\nimpl<I> IntersperseSparseAdapter for I where I: Iterator {}\n // src/main.rs\n\nmod intersperse_sparse;\nuse intersperse_sparse::IntersperseSparseAdapter;\n\nfn main() {\n let string = \"abcdefg\";\n let new_string: String = string.chars().intersperse_sparse(3, '\\n').collect();\n assert_eq!(new_string, \"abc\\ndef\\ng\");\n}\n"
},
{
"answer_id": 74589384,
"author": "Kaplan",
"author_id": 11199879,
"author_profile": "https://Stackoverflow.com/users/11199879",
"pm_score": 1,
"selected": false,
"text": "Iterator from_fn let mut iter = \"abcdefghijklmnopqrstuvwxyz\".chars().peekable();\nlet mut count = 0;\nlet iter_with_newlines = std::iter::from_fn(move || match iter.peek() {\n Some(_) => {\n if count < 10 {\n count += 1;\n iter.next()\n } else {\n count = 0;\n Some('\\n')\n }\n }\n None => None,\n});\nassert_eq!(\n \"abcdefghij\\nklmnopqrst\\nuvwxyz\",\n iter_with_newlines.collect::<String>()\n);\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15478835/"
] |
74,554,767
|
<p>I am trying to loop a picture/logo which I want to go into each sheet, which contains a rectangle in the top left corner.</p>
<p>Logo successfully fills into the rectangle, however I want to check each sheet if (Rectangle A") is present and then paste the shape which contains the image</p>
<p>I have made an error with the loop where it gets stuck in an infinite loop and pastes it in the same sheet</p>
<p>Can I kindly get some assistance, please</p>
<pre><code> Dim myshape As Shape
Set myshape = ActiveSheet.Shapes("Rectangle A")
myshape.Copy
For Each ws In ActiveWorkbook.Worksheets
If ws.Shapes.Count > 0 Then
ActiveSheet.Shapes("Rectangle A").Select
For Each myshape In ws.Shapes
ActiveSheet.Paste
Next myshape
End If
Next ws
</code></pre>
|
[
{
"answer_id": 74554890,
"author": "Caesar",
"author_id": 401059,
"author_profile": "https://Stackoverflow.com/users/401059",
"pm_score": 1,
"selected": false,
"text": "chunks itertools Vec Vec use itertools::Itertools;\niter\n .chunks(3)\n .into_iter()\n .map(|chunk| chunk.collect::<Vec<_>>())\n .intersperse(vec![','])\n .flat_map(|chunk| chunk.into_iter())\n .collect::<String>();\n"
},
{
"answer_id": 74557357,
"author": "Jmb",
"author_id": 5397009,
"author_profile": "https://Stackoverflow.com/users/5397009",
"pm_score": 2,
"selected": false,
"text": "enumerate flat_map use either::Either;\n\nfn main() {\n let iter = \"abcdefghijklmnopqrstuvwxyz\".chars();\n let iter_with_newlines = iter\n .enumerate()\n .flat_map(|(i, c)| {\n if i % 10 == 0 {\n Either::Left(['\\n', c].into_iter())\n } else {\n Either::Right(std::iter::once(c))\n }\n })\n .skip(1); // The above code add a newline in first position -> skip it\n let string: String = iter_with_newlines.collect();\n assert_eq!(\"abcdefghij\\nklmnopqrst\\nuvwxyz\", string);\n}\n"
},
{
"answer_id": 74587443,
"author": "asdf3.14159",
"author_id": 15478835,
"author_profile": "https://Stackoverflow.com/users/15478835",
"pm_score": 1,
"selected": false,
"text": "// src/intersperse_sparse.rs\n\nuse core::iter::Peekable;\n\n/// An iterator adaptor to insert a particular value\n/// every n elements of the adapted iterator.\n///\n/// Iterator element type is `I::Item`\npub struct IntersperseSparse<I>\nwhere\n I: Iterator,\n I::Item: Clone,\n{\n iter: Peekable<I>,\n step_length: usize,\n index: usize,\n separator: I::Item,\n}\n\nimpl<I> IntersperseSparse<I>\nwhere\n I: Iterator,\n I::Item: Clone,\n{\n #[allow(unused)] // Although this function isn't explicitly exported, it is called in the default implementation of the IntersperseSparseAdapter, which is exported.\n fn new(iter: I, step_length: usize, separator: I::Item) -> Self {\n if step_length == 0 {\n panic!(\"Chunk size cannot be 0!\")\n }\n Self {\n iter: iter.peekable(),\n step_length,\n separator,\n index: 0,\n }\n }\n}\n\nimpl<I> Iterator for IntersperseSparse<I>\nwhere\n I: Iterator,\n I::Item: Clone,\n{\n type Item = I::Item;\n fn next(&mut self) -> Option<Self::Item> {\n if self.index == self.step_length && self.iter.peek().is_some() {\n self.index = 0;\n Some(self.separator.clone())\n } else {\n self.index += 1;\n self.iter.next()\n }\n }\n}\n\n/// An iterator adaptor to insert a particular value created by a function\n/// every n elements of the adapted iterator.\n///\n/// Iterator element type is `I::Item`\npub struct IntersperseSparseWith<I, G>\nwhere\n I: Iterator,\n G: FnMut() -> I::Item,\n{\n iter: Peekable<I>,\n step_length: usize,\n index: usize,\n separator_closure: G,\n}\n\nimpl<I, G> IntersperseSparseWith<I, G>\nwhere\n I: Iterator,\n G: FnMut() -> I::Item,\n{\n #[allow(unused)] // Although this function isn't explicitly exported, it is called in the default implementation of the IntersperseSparseAdapter, which is exported.\n fn new(iter: I, step_length: usize, separator_closure: G) -> Self {\n if step_length == 0 {\n panic!(\"Chunk size cannot be 0!\")\n }\n Self {\n iter: iter.peekable(),\n step_length,\n separator_closure,\n index: 0,\n }\n }\n}\n\nimpl<I, G> Iterator for IntersperseSparseWith<I, G>\nwhere\n I: Iterator,\n G: FnMut() -> I::Item,\n{\n type Item = I::Item;\n fn next(&mut self) -> Option<Self::Item> {\n if self.index == self.step_length && self.iter.peek().is_some() {\n self.index = 0;\n Some((self.separator_closure)())\n } else {\n self.index += 1;\n self.iter.next()\n }\n }\n}\n\n/// Import this trait to use the `iter.intersperse_sparse(n, item)` and `iter.intersperse_sparse(n, ||item)` on all iterators.\npub trait IntersperseSparseAdapter: Iterator {\n fn intersperse_sparse(self, chunk_size: usize, separator: Self::Item) -> IntersperseSparse<Self>\n where\n Self: Sized,\n Self::Item: Clone,\n {\n IntersperseSparse::new(self, chunk_size, separator)\n }\n\n fn intersperse_sparse_with<G>(\n self,\n chunk_size: usize,\n separator_closure: G,\n ) -> IntersperseSparseWith<Self, G>\n where\n Self: Sized,\n G: FnMut() -> Self::Item,\n {\n IntersperseSparseWith::new(self, chunk_size, separator_closure)\n }\n}\n\nimpl<I> IntersperseSparseAdapter for I where I: Iterator {}\n // src/main.rs\n\nmod intersperse_sparse;\nuse intersperse_sparse::IntersperseSparseAdapter;\n\nfn main() {\n let string = \"abcdefg\";\n let new_string: String = string.chars().intersperse_sparse(3, '\\n').collect();\n assert_eq!(new_string, \"abc\\ndef\\ng\");\n}\n"
},
{
"answer_id": 74589384,
"author": "Kaplan",
"author_id": 11199879,
"author_profile": "https://Stackoverflow.com/users/11199879",
"pm_score": 1,
"selected": false,
"text": "Iterator from_fn let mut iter = \"abcdefghijklmnopqrstuvwxyz\".chars().peekable();\nlet mut count = 0;\nlet iter_with_newlines = std::iter::from_fn(move || match iter.peek() {\n Some(_) => {\n if count < 10 {\n count += 1;\n iter.next()\n } else {\n count = 0;\n Some('\\n')\n }\n }\n None => None,\n});\nassert_eq!(\n \"abcdefghij\\nklmnopqrst\\nuvwxyz\",\n iter_with_newlines.collect::<String>()\n);\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16664439/"
] |
74,554,798
|
<p>I have a sheet to apply Query function to get the respective search data row by row. But I need to apply ArrayFormula to automate this search process. I want to know how should I do.</p>
<p><strong>Expected Result</strong></p>
<p>Check phrase Result 1 Result 2 Result 3 Result 4
Apple Apple Ice Apple Custard apple/Sugar apple/Sweetsop Rose apple/Water apple
berry Cape gooseberry/Inca berry/Physalis<br />
man Mango Mangosteen<br />
mom<br />
fruit Dragon fruit Egg fruit Passion fruit Black sapote/Chocolate pudding fruit
j Jackfruit Jujube Jenipapo<br />
nake Snake fruit/Salak<br />
me Horned Melon Honeydew melon Medlar fruit Mouse melon</p>
<p><strong>Currently</strong></p>
<p>Check phrase Result 1 Result 2 Result 3 Result 4
Apple Apple Ice Apple<br />
berry Apple Ice Apple<br />
man Apple Ice Apple<br />
mom Apple Ice Apple<br />
fruit Apple Ice Apple<br />
j Apple Ice Apple<br />
nake Apple Ice Apple<br />
me Apple Ice Apple</p>
<p>What I currently achieve is for single row using this:</p>
<p><code>=IF(LEN(F2:F)=0, IFERROR(1/0), IF(LEN(F2:F)>0, Query(TRANSPOSE(QUERY(Fruits!B:B, "select B where B contains '" & F2:F & "'")),"select * limit 12")))</code></p>
<p>How should I do. Please advise me. I attach my file link here.
[My Google Sheet file]
(<a href="https://docs.google.com/spreadsheets/d/1QDfruKtwJjmRQWqTlO3sBM-e9vp9QKwmla23ss0U1sY/edit#gid=1411907513" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1QDfruKtwJjmRQWqTlO3sBM-e9vp9QKwmla23ss0U1sY/edit#gid=1411907513</a>)</p>
|
[
{
"answer_id": 74554890,
"author": "Caesar",
"author_id": 401059,
"author_profile": "https://Stackoverflow.com/users/401059",
"pm_score": 1,
"selected": false,
"text": "chunks itertools Vec Vec use itertools::Itertools;\niter\n .chunks(3)\n .into_iter()\n .map(|chunk| chunk.collect::<Vec<_>>())\n .intersperse(vec![','])\n .flat_map(|chunk| chunk.into_iter())\n .collect::<String>();\n"
},
{
"answer_id": 74557357,
"author": "Jmb",
"author_id": 5397009,
"author_profile": "https://Stackoverflow.com/users/5397009",
"pm_score": 2,
"selected": false,
"text": "enumerate flat_map use either::Either;\n\nfn main() {\n let iter = \"abcdefghijklmnopqrstuvwxyz\".chars();\n let iter_with_newlines = iter\n .enumerate()\n .flat_map(|(i, c)| {\n if i % 10 == 0 {\n Either::Left(['\\n', c].into_iter())\n } else {\n Either::Right(std::iter::once(c))\n }\n })\n .skip(1); // The above code add a newline in first position -> skip it\n let string: String = iter_with_newlines.collect();\n assert_eq!(\"abcdefghij\\nklmnopqrst\\nuvwxyz\", string);\n}\n"
},
{
"answer_id": 74587443,
"author": "asdf3.14159",
"author_id": 15478835,
"author_profile": "https://Stackoverflow.com/users/15478835",
"pm_score": 1,
"selected": false,
"text": "// src/intersperse_sparse.rs\n\nuse core::iter::Peekable;\n\n/// An iterator adaptor to insert a particular value\n/// every n elements of the adapted iterator.\n///\n/// Iterator element type is `I::Item`\npub struct IntersperseSparse<I>\nwhere\n I: Iterator,\n I::Item: Clone,\n{\n iter: Peekable<I>,\n step_length: usize,\n index: usize,\n separator: I::Item,\n}\n\nimpl<I> IntersperseSparse<I>\nwhere\n I: Iterator,\n I::Item: Clone,\n{\n #[allow(unused)] // Although this function isn't explicitly exported, it is called in the default implementation of the IntersperseSparseAdapter, which is exported.\n fn new(iter: I, step_length: usize, separator: I::Item) -> Self {\n if step_length == 0 {\n panic!(\"Chunk size cannot be 0!\")\n }\n Self {\n iter: iter.peekable(),\n step_length,\n separator,\n index: 0,\n }\n }\n}\n\nimpl<I> Iterator for IntersperseSparse<I>\nwhere\n I: Iterator,\n I::Item: Clone,\n{\n type Item = I::Item;\n fn next(&mut self) -> Option<Self::Item> {\n if self.index == self.step_length && self.iter.peek().is_some() {\n self.index = 0;\n Some(self.separator.clone())\n } else {\n self.index += 1;\n self.iter.next()\n }\n }\n}\n\n/// An iterator adaptor to insert a particular value created by a function\n/// every n elements of the adapted iterator.\n///\n/// Iterator element type is `I::Item`\npub struct IntersperseSparseWith<I, G>\nwhere\n I: Iterator,\n G: FnMut() -> I::Item,\n{\n iter: Peekable<I>,\n step_length: usize,\n index: usize,\n separator_closure: G,\n}\n\nimpl<I, G> IntersperseSparseWith<I, G>\nwhere\n I: Iterator,\n G: FnMut() -> I::Item,\n{\n #[allow(unused)] // Although this function isn't explicitly exported, it is called in the default implementation of the IntersperseSparseAdapter, which is exported.\n fn new(iter: I, step_length: usize, separator_closure: G) -> Self {\n if step_length == 0 {\n panic!(\"Chunk size cannot be 0!\")\n }\n Self {\n iter: iter.peekable(),\n step_length,\n separator_closure,\n index: 0,\n }\n }\n}\n\nimpl<I, G> Iterator for IntersperseSparseWith<I, G>\nwhere\n I: Iterator,\n G: FnMut() -> I::Item,\n{\n type Item = I::Item;\n fn next(&mut self) -> Option<Self::Item> {\n if self.index == self.step_length && self.iter.peek().is_some() {\n self.index = 0;\n Some((self.separator_closure)())\n } else {\n self.index += 1;\n self.iter.next()\n }\n }\n}\n\n/// Import this trait to use the `iter.intersperse_sparse(n, item)` and `iter.intersperse_sparse(n, ||item)` on all iterators.\npub trait IntersperseSparseAdapter: Iterator {\n fn intersperse_sparse(self, chunk_size: usize, separator: Self::Item) -> IntersperseSparse<Self>\n where\n Self: Sized,\n Self::Item: Clone,\n {\n IntersperseSparse::new(self, chunk_size, separator)\n }\n\n fn intersperse_sparse_with<G>(\n self,\n chunk_size: usize,\n separator_closure: G,\n ) -> IntersperseSparseWith<Self, G>\n where\n Self: Sized,\n G: FnMut() -> Self::Item,\n {\n IntersperseSparseWith::new(self, chunk_size, separator_closure)\n }\n}\n\nimpl<I> IntersperseSparseAdapter for I where I: Iterator {}\n // src/main.rs\n\nmod intersperse_sparse;\nuse intersperse_sparse::IntersperseSparseAdapter;\n\nfn main() {\n let string = \"abcdefg\";\n let new_string: String = string.chars().intersperse_sparse(3, '\\n').collect();\n assert_eq!(new_string, \"abc\\ndef\\ng\");\n}\n"
},
{
"answer_id": 74589384,
"author": "Kaplan",
"author_id": 11199879,
"author_profile": "https://Stackoverflow.com/users/11199879",
"pm_score": 1,
"selected": false,
"text": "Iterator from_fn let mut iter = \"abcdefghijklmnopqrstuvwxyz\".chars().peekable();\nlet mut count = 0;\nlet iter_with_newlines = std::iter::from_fn(move || match iter.peek() {\n Some(_) => {\n if count < 10 {\n count += 1;\n iter.next()\n } else {\n count = 0;\n Some('\\n')\n }\n }\n None => None,\n});\nassert_eq!(\n \"abcdefghij\\nklmnopqrst\\nuvwxyz\",\n iter_with_newlines.collect::<String>()\n);\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717079/"
] |
74,554,870
|
<p><strong>I want to close a specified dialog.</strong></p>
<p>My case:</p>
<ul>
<li>Open 2 dialogs (1) and (2), and 2 dialogs are showing at the same time. (2) is overriding (1) and I want to close (1) first.</li>
</ul>
<p>With Android: I can assign each dialog to a variable and use <code>dialog.dismiss()</code>.</p>
<p>I came across this example, it works but it doesn't seem to be the best way.
<a href="https://stackoverflow.com/questions/63262042/how-to-close-a-specific-flutter-alertdialog">How to close a specific Flutter AlertDialog?</a></p>
<p>Thanks for all the answers!</p>
|
[
{
"answer_id": 74555144,
"author": "manhtuan21",
"author_id": 8921450,
"author_profile": "https://Stackoverflow.com/users/8921450",
"pm_score": 1,
"selected": false,
"text": "OverLayEntry class _MyHomePageState extends State<MyHomePage> {\n OverlayEntry? _overlayEntry1;\n OverlayEntry? _overlayEntry2;\n\n @override\n void initState() {\n super.initState();\n\n _overlayEntry1 = OverlayEntry(\n builder: (context) {\n return Material(\n color: Colors.transparent,\n child: Center(\n child: Container(\n height: 300,\n width: 300,\n color: Colors.green,\n ),\n ),\n );\n },\n );\n\n _overlayEntry2 = OverlayEntry(\n builder: (context) {\n return Material(\n color: Colors.transparent,\n child: Center(\n child: InkWell(\n onTap: () {\n _overlayEntry1?.remove();\n },\n child: Container(\n height: 150,\n width: 150,\n color: Colors.red,\n ),\n ),\n ),\n );\n },\n );\n\n }\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n body: Center(\n child: InkWell(\n onTap: () {\n Overlay.of(context)!.insert(_overlayEntry1!);\n Overlay.of(context)!.insert(_overlayEntry2!);\n },\n child: Text('Show overlay'),\n ),\n ),\n );\n }\n}\n"
},
{
"answer_id": 74555915,
"author": "Md. Abu Sufian Sufi",
"author_id": 15366084,
"author_profile": "https://Stackoverflow.com/users/15366084",
"pm_score": 0,
"selected": false,
"text": "Navigator.pop(context) Get.back() .then((e)=> 'previous dialogue open function goes here')"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7592717/"
] |
74,554,876
|
<p>I'm trying to get the image + text in the grid from this picture to be centered, how do i do that?<a href="https://i.stack.imgur.com/qxqcd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qxqcd.png" alt="Gridbox" /></a></p>
|
[
{
"answer_id": 74555144,
"author": "manhtuan21",
"author_id": 8921450,
"author_profile": "https://Stackoverflow.com/users/8921450",
"pm_score": 1,
"selected": false,
"text": "OverLayEntry class _MyHomePageState extends State<MyHomePage> {\n OverlayEntry? _overlayEntry1;\n OverlayEntry? _overlayEntry2;\n\n @override\n void initState() {\n super.initState();\n\n _overlayEntry1 = OverlayEntry(\n builder: (context) {\n return Material(\n color: Colors.transparent,\n child: Center(\n child: Container(\n height: 300,\n width: 300,\n color: Colors.green,\n ),\n ),\n );\n },\n );\n\n _overlayEntry2 = OverlayEntry(\n builder: (context) {\n return Material(\n color: Colors.transparent,\n child: Center(\n child: InkWell(\n onTap: () {\n _overlayEntry1?.remove();\n },\n child: Container(\n height: 150,\n width: 150,\n color: Colors.red,\n ),\n ),\n ),\n );\n },\n );\n\n }\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n body: Center(\n child: InkWell(\n onTap: () {\n Overlay.of(context)!.insert(_overlayEntry1!);\n Overlay.of(context)!.insert(_overlayEntry2!);\n },\n child: Text('Show overlay'),\n ),\n ),\n );\n }\n}\n"
},
{
"answer_id": 74555915,
"author": "Md. Abu Sufian Sufi",
"author_id": 15366084,
"author_profile": "https://Stackoverflow.com/users/15366084",
"pm_score": 0,
"selected": false,
"text": "Navigator.pop(context) Get.back() .then((e)=> 'previous dialogue open function goes here')"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20515851/"
] |
74,554,897
|
<p>I need some help with the query below - I am trying to pull information regarding price and multiply with the quantity & insert the sum into the table. So far I have,</p>
<pre><code>update passenger_baggage
SET passenger_baggage.total_baggage_cost=passenger_baggage.passenger_baggage_quantity*baggage_type.baggage_type_cost
FROM passenger_baggage INNER JOIN baggage_type
ON passenger_baggage.passenger_baggage_id = baggage_type.baggage_type_id
WHERE passenger_id = "3";
</code></pre>
<p>and getting this error</p>
<blockquote>
<p>#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use
near 'FROM passenger_baggage INNER JOIN baggage_type ON
passenger_baggage.passenge...' at line 3</p>
</blockquote>
<p>Expecting the query to multiply the two values & insert the total.</p>
|
[
{
"answer_id": 74554920,
"author": "Paul T.",
"author_id": 7644018,
"author_profile": "https://Stackoverflow.com/users/7644018",
"pm_score": 3,
"selected": true,
"text": "FROM UPDATE update passenger_baggage\nINNER JOIN baggage_type\nON passenger_baggage.passenger_baggage_id = baggage_type.baggage_type_id \nSET passenger_baggage.total_baggage_cost = passenger_baggage.passenger_baggage_quantity * baggage_type.baggage_type_cost\nWHERE passenger_id = \"3\";\n"
},
{
"answer_id": 74554932,
"author": "user17443931",
"author_id": 17443931,
"author_profile": "https://Stackoverflow.com/users/17443931",
"pm_score": 0,
"selected": false,
"text": "UPDATE passenger_baggage, baggage_type \nSET passenger_baggage.total_baggage_cost = passenger_baggage.passenger_baggage_quantity * baggage_type.baggage_type_cost \nWHERE passenger_baggage.passenger_baggage_id = baggage_type.baggage_type_id AND passenger_id = \"3\";\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20586670/"
] |
74,554,906
|
<p>I came across an issue when implementing input type range on my site, i tried to set the background color for the -webkit-slider-thumb to be transparent, but it is not working on the ios device (iphone and ipad) safari, the safari inspector still showing the user agent style instead of the style i already implement in my css and inline html file, here the css style i implement in my css file and inline html:</p>
<p><strong>html file</strong></p>
<pre><code><input class="slider" list="steplist" max="100" name="range" type="range" value ="0" />
</code></pre>
<p><strong>css file</strong></p>
<pre><code>input[type="range"]::-webkit-slider-thumb,
input[type="range"]::-webkit-slider-thumb:active{
background-color: transparent !important;
}
</code></pre>
<p>here is the screencap for the inspector element (i inspected it on ipad os safari):
<a href="https://i.stack.imgur.com/yOcOM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yOcOM.png" alt="enter image description here" /></a></p>
<p>I noticed date the <code>background-color</code> of <code>input[type="range"]::-webkit-slider-thumb</code> value is still white (following user-agent default style) and not following my css file which is transparent</p>
|
[
{
"answer_id": 74607678,
"author": "Wing Chi",
"author_id": 20616686,
"author_profile": "https://Stackoverflow.com/users/20616686",
"pm_score": 2,
"selected": false,
"text": "background: transparent; //Assign input range's id into variable\nconst range = document.querySelector('#r-input'); \n\nfunction rangeOnChange(e) {\n let t = e.target\n \n //Assign range input's properties into variables\n const min = t.min; \n const max = t.max; \n const val = t.value; \n \n /* Adjust range progress as the thumb moves while avoiding overflows */\n t.style.backgroundSize = (val - min) * 89 / (max - min) + '% 100%'; \n}\n\n//Trigger function on thumb move\nrange.addEventListener('input', rangeOnChange);\n\n/* Adjust range progress at start */\nrange.style.backgroundSize = (range.value - range.min) * 89 / (range.max - range.min) + '% 100%'; input[type=\"range\"] {\n \n /* To hide ordinary range input */\n -webkit-appearance: none;\n\n margin-right: 15px;\n height: 7px;\n background: lightgray;\n border-radius: 5px;\n \n /* Range progress background is set */\n background-image: linear-gradient(gray,gray);\n background-size: 70% 100%;\n background-repeat: no-repeat;\n}\n\n/* Thumb styles */\ninput[type=\"range\"]::-webkit-slider-thumb {\n\n /* To hide ordinary thumb */\n -webkit-appearance: none;\n \n height: 15px;\n width: 15px;\n border-radius: 50%;\n \n /* Since range input is created manually, thumb background can be vary in color */\n background: transparent; \n border: 1px solid gray;\n cursor: pointer;\n transition: background .3s ease-in-out;\n} <!-- Since some JS is used, an Id is added here -->\n<input id='r-input' type=\"range\" value=\"70\" min=\"0\" max=\"100\" /><p><small>Try moving transparent thumb to see range progress</small></p>"
},
{
"answer_id": 74673850,
"author": "chardida",
"author_id": 20605402,
"author_profile": "https://Stackoverflow.com/users/20605402",
"pm_score": -1,
"selected": false,
"text": "background-image: url('the url to the image') background-size: contain; background-position: center center; background-repeat: no-repeat;"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11920674/"
] |
74,554,916
|
<p>I am trying to learn c, but everytime i run a code that needs user imput i get segfault error
My os is arch linux
it was compiled with "gcc -o test1 test1.c"
Appearently it happens because the program cannot allocate memory, but none of the tutorials i saw did any extra thing.</p>
<p>here is the code i was trying to run:</p>
<pre><code> #include<stdio.h>
int main(){
int age;
scanf("%d", age);
printf("age = %d", age);
return 0;
}
</code></pre>
<p>and when i run it with ./test1 i get 19315 segmentation fault (core dumped) ./test
I tried looking it up on google and found nothing that solved this</p>
|
[
{
"answer_id": 74555042,
"author": "Nathan Mills",
"author_id": 8890345,
"author_profile": "https://Stackoverflow.com/users/8890345",
"pm_score": 1,
"selected": false,
"text": "scanf() age scanf() scanf(\"%d\", &age);\n age age"
},
{
"answer_id": 74565353,
"author": "Ray",
"author_id": 5196093,
"author_profile": "https://Stackoverflow.com/users/5196093",
"pm_score": 0,
"selected": false,
"text": "scanf(\"%d\", &age) int age; age 42 scanf(\"%d\", age);"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20586637/"
] |
74,554,925
|
<p>so i try to render an array of object into react js component like below:</p>
<pre><code>import React, { useState } from "react";
import { Route, Link } from "react-router-dom";
import {
MdOutlineSpaceDashboard,
MdOutlineStorage,
MdOutlineFactCheck,
MdOutlineCalculate,
MdStickyNote2,
MdAssignmentTurnedIn,
MdOutlineDynamicForm,
MdOutlineArrowDropDown,
} from "react-icons/md";
import { BsChevronDown, BsArrowLeftShort } from "react-icons/bs";
import Logo_Nabati from "../assets/logo-nabati.svg";
const menuItems = [
{ id: 1, label: "Dashboard", icon: MdOutlineSpaceDashboard, link: "/" },
{
id: 2,
label: "Master Data",
icon: MdOutlineStorage,
iconArrow: MdOutlineArrowDropDown,
link: "",
subMenu: true,
subMenuItems: [
{ id: 1, label: "KSBT", link: "/MasterData/list/KSBT" },
{ id: 2, label: "SQ01_RM", link: "/MasterData" },
{ id: 3, label: "SQ01_PM", link: "/MasterData" },
{ id: 4, label: "Depre", link: "/MasterData" },
{ id: 5, label: "OMC", link: "/MasterData" },
{ id: 6, label: "Premix", link: "/MasterData" },
{ id: 7, label: "Routing", link: "/MasterData" },
{ id: 8, label: "MP", link: "/MasterData" },
],
},
{ id: 3, label: "Check COGM", icon: MdOutlineFactCheck, link: "/checkcogm" },
{
id: 4,
label: "Calculation",
icon: MdOutlineCalculate,
link: "/calculation",
},
{
id: 5,
label: "Draft Calculation",
icon: MdStickyNote2,
link: "/draft",
},
{ id: 6, label: "Approved", icon: MdAssignmentTurnedIn, link: "/approval" },
{ id: 7, label: "Task Activity", icon: MdOutlineDynamicForm, link: "/task" },
];
const Sidebar = () => {
const [open, setOpen] = useState(false);
const [submenuOpen, setSubmenuOpen] = useState(false);
return (
<div className="flex">
<div
className={` bg-yellow-400 h-screen p-5 pt-8 ${
open
? "w-50 ease-out delay-150 peer-focus:left-0 duration-200"
: "w-20 ease-out delay-150 peer-focus:left-0 duration-200"
} duration-300 relative`}
>
<BsArrowLeftShort
className={` bg-white text-yellow-300 text-3xl rounded-full absolute -right-3 top-9 border border-yellow-300 cursor-pointer delay-150 duration-200 ${
!open && "rotate-180"
}`}
onClick={() => setOpen(!open)}
/>
<div className={`inline-flex`}>
<img src={Logo_Nabati} width={123} height={75} alt="logo Nabati" />
</div>
<ul className="pt-8">
{menuItems.map(
({ icon: Icon, iconArrow: IconArrow, ...menu }, index) => (
<>
<Link to={menu.link}>
<li
key={index}
className="text-white text-sm text-justify flex items-center gap-x-4 cursor-pointer p-2 hover:bg-red-600 rounded-md mt-2"
>
<Icon className="text-2xl text-white group-hover:text-red-600" />
<span
className={`text-base font-mendium flex-1 duration-200 ${
!open && "hidden"
} `}
>
{menu.label}
</span>
{menu.subMenu && (
<BsChevronDown
className={`text-base font-mendium duration-200 ${
!open && "hidden"
} ${submenuOpen && "rotate-180"}`}
onClick={() => {
setSubmenuOpen(!submenuOpen);
}}
/>
)}
</li>{" "}
</Link>
{menu.subMenu && submenuOpen && open && (
<ul>
{menu.subMenuItems.map((subMenuItem, index) => (
<Link to={subMenuItem.link}>
<li
key={index}
className="text-white text-sm flex items-center gap-x-4 cursor-pointer p-1 px-12 hover:bg-red-500 rounded-md"
>
{subMenuItem.label}
</li>{" "}
</Link>
))}
</ul>
)}
</>
)
)}
</ul>
</div>
</div>
);
};
export default Sidebar;
</code></pre>
<p>even after i put the key={index} on the <li> component i still got warning like this</p>
<pre><code>react-jsx-dev-runtime.development.js:119 Warning: Each child in a list should have a unique "key" prop.
</code></pre>
<p>can someone tell me where di i do wrong here, it supposed to be no problem after i put the key={item} but why i still gettingn error on the console?</p>
|
[
{
"answer_id": 74555042,
"author": "Nathan Mills",
"author_id": 8890345,
"author_profile": "https://Stackoverflow.com/users/8890345",
"pm_score": 1,
"selected": false,
"text": "scanf() age scanf() scanf(\"%d\", &age);\n age age"
},
{
"answer_id": 74565353,
"author": "Ray",
"author_id": 5196093,
"author_profile": "https://Stackoverflow.com/users/5196093",
"pm_score": 0,
"selected": false,
"text": "scanf(\"%d\", &age) int age; age 42 scanf(\"%d\", age);"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16136595/"
] |
74,554,928
|
<p>I am working with a data frame of 100m rows, that I would like to partition into 100 Parquet files of 1m rows each. I do not want to partition on any particular column value: I just want 100 chunks of 1m rows.</p>
<p>I know that this is possible by adding a "dummy" column, and passing that to <code>partition_cols</code>:</p>
<pre class="lang-py prettyprint-override"><code>data_size = len(data)
partition_size = 1_000_000
n_partitions, remainder = divmod(data_size, partition_size)
data["partition_id"] = np.concatenate([
np.repeat(list(range(n_partitions)), partition_size),
np.repeat(n_partitions + 1, remainder),
])
data.to_parquet("out", partition_cols=["partition_id"])
</code></pre>
<p>But it feels wasteful to write an extra 100m 64-bit integers!</p>
<p>Parquet files are also typically <em>compressed</em>, very often using the Snappy algorithm (occasionally GZip or Brotli). And these are long runs of identical integers, so in principle they should compress extremely well.</p>
<p>However, I don't know how the Parquet file format and underlying Arrow array format interact with various compression algorithms. Assuming that I'm using Snappy, will my millions of extra integers be compressed to a handful of bytes? Or will this <code>partition_id</code> column actually inflate the size of my dataset by some appreciable amount?</p>
|
[
{
"answer_id": 74555042,
"author": "Nathan Mills",
"author_id": 8890345,
"author_profile": "https://Stackoverflow.com/users/8890345",
"pm_score": 1,
"selected": false,
"text": "scanf() age scanf() scanf(\"%d\", &age);\n age age"
},
{
"answer_id": 74565353,
"author": "Ray",
"author_id": 5196093,
"author_profile": "https://Stackoverflow.com/users/5196093",
"pm_score": 0,
"selected": false,
"text": "scanf(\"%d\", &age) int age; age 42 scanf(\"%d\", age);"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954547/"
] |
74,554,968
|
<p>I'm a biologist, with no coding knowledge, trying to create a script that reads every *rprt.txt file in a folder.</p>
<p>In line 11 of each file, the fifth word is a number, If that number is 6000<number<14000 then I want to read the fifth word in line 13 and if that number is greater than 600. Copy the file into another folder in that directory.</p>
<p>At this point I've tried a lot of things. I know the next code is exiting the loop but is the best I got.</p>
<pre><code>@echo off
for %%f in (*rprt.txt) do set "name=%%f" &goto first
:first
for /F "skip=10 tokens=5" %%i in (%name%) do set "var1=%%i" &goto nextline
:nextline
for /F "skip=12 tokens=5" %%i in (%name%) do set "var2=%%i" &goto nextline2
:nextline2
if %var1% geq 6000 (if %var2% geq 600 echo.%name% >> valid.txt)
</code></pre>
<p>I've also tried this to test the for loop but I don't understand what's wrong. This prints "echo is off" 3 times</p>
<pre><code>@echo off
for %%f in (*rprt.txt) do (set "name=%%f" & echo %name% >> valid.txt)
</code></pre>
|
[
{
"answer_id": 74555866,
"author": "SomethingDark",
"author_id": 4158862,
"author_profile": "https://Stackoverflow.com/users/4158862",
"pm_score": 1,
"selected": false,
"text": "1 GTR LSS @echo off\nsetlocal enabledelayedexpansion\n\nset \"input_directory=%~dp0\\input\"\nset \"output_directory=%~dp0\\output\"\n\npushd \"%input_directory%\"\nfor %%A in (*_rprt.txt) do (\n for /f \"tokens=5\" %%B in ('findstr /n /r \"^\" \"%%~A\" ^| findstr \"11:\"') do set \"line_11_num=%%B\"\n for /f \"tokens=5\" %%B in ('findstr /n /r \"^\" \"%%~A\" ^| findstr \"13:\"') do set \"line_13_num=%%B\"\n \n call :isNumber !line_11_num! n[11]\n call :isNumber !line_13_num! n[13]\n set /a \"valid_report=!n[11]!+!n[13]!\"\n \n if \"!valid_report!\"==\"0\" (\n if !line_11_num! GTR 6000 if !line_11_num! LSS 14000 (\n if !line_13_num! GTR 600 (\n copy \"%%~A\" \"%output_directory%\"\n )\n )\n )\n)\nexit /b\n\n::------------------------------------------------------------------------------\n:: Determines if a given string is a positive integer\n::\n:: Arguments: %1 - The value to check\n:: %2 - The variable to store the result in\n:: Returns: 0 if the number is a positive integer, 1 otherwise\n::------------------------------------------------------------------------------\n:isNumber\nset \"is_number=0\"\nfor /f \"delims=0123456789\" %%A in (\"%~1\") do set \"is_number=1\"\nset \"%~2=%is_number%\"\nexit /b\n"
},
{
"answer_id": 74555972,
"author": "Magoo",
"author_id": 2128947,
"author_profile": "https://Stackoverflow.com/users/2128947",
"pm_score": 2,
"selected": true,
"text": "@ECHO OFF\nSETLOCAL\nrem The following settings for the directories and filenames are names\nrem that I use for testing and deliberately includes spaces to make sure\nrem that the process works using such names. These will need to be changed to suit your situation.\n\nSET \"sourcedir=u:\\your files\"\nSET \"destdir=u:\\your results\"\n\nFOR %%e IN (\"%sourcedir%\\*rprt.txt\") DO (\n rem %%e has filename\n SET \"line11=\"\n FOR /f \"usebackqskip=10tokens=5\" %%y IN (\"%%e\") DO IF NOT DEFINED line11 (\n SET \"line11=y\"\n SET \"line13=\"\n FOR /f \"usebackqskip=12tokens=5\" %%o IN (\"%%e\") DO IF NOT DEFINED line13 (\n SET \"line13=y\"\n IF %%y gtr 6000 IF %%y lss 14000 IF %%o gtr 600 ECHO COPY \"%%e\" \"%destdir%\"\n )\n )\n)\n\nGOTO :EOF\n usebackq"
},
{
"answer_id": 74557463,
"author": "Aacini",
"author_id": 778560,
"author_profile": "https://Stackoverflow.com/users/778560",
"pm_score": 0,
"selected": false,
"text": "for /F goto for /F findstr findstr for if !delayedExpansion! %standardExpansion% for /F findstr @echo off\nsetlocal EnableDelayedExpansion\n\nrem Read every *rprt.txt file in this folder\nfor %%f in (*rprt.txt) do (\n\n rem Read line 11 and 13 of this file via a redirection\n < \"%%f\" (\n rem Skip first 10 lines\n for /L %%i in (1,1,10) do set /P \"dummy=\"\n rem Read line 11 and line 13\n set /P \"line11=\"\n set /P \"dummy=\"\n set /P \"line13=\"\n )\n\n rem Get the number in line 11 and compare it\n for /F \"tokens=5\" %%i in (\"!line11!\") do set \"num=%%i\"\n if 6000 lss !num! if !num! lss 14000 (\n\n rem Get the number in line 13 and compare it\n for /F \"tokens=5\" %%i in (\"!line13!\") do set \"num=%%i\"\n if !num! gtr 600 copy \"%%f\" anotherFolder\n\n )\n\n)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20586533/"
] |
74,554,989
|
<p>Should I do traditional copy paste the header and footer on every page, or is there any way that I can display it using JavaScript on every page!</p>
<p>Just expecting that if I would save some kilobytes on my .html files by rendering my header and footer on each page via JavaScript?</p>
|
[
{
"answer_id": 74555304,
"author": "DoGzTheFiGhTeR",
"author_id": 17655556,
"author_profile": "https://Stackoverflow.com/users/17655556",
"pm_score": 2,
"selected": true,
"text": "\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n <script type=module src=\"./index.js\"></script>\n </head>\n \n <body>\n <my-header></my-header> \n \n <h1>Home Page</h1>\n \n <my-footer></my-footer>\n </body>\n \n </html>\n\n \n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n <script type=module src=\"./index.js\"></script>\n </head>\n \n <body>\n <my-header></my-header> \n \n <h1>About Page</h1>\n \n <my-footer></my-footer>\n </body>\n \n </html>\n\n \n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n <script type=module src=\"./index.js\"></script>\n </head>\n \n <body>\n <my-header></my-header> \n \n <h1>Contact Page</h1>\n \n <my-footer></my-footer>\n </body>\n \n </html>\n\n \n class MyHeader extends HTMLElement {\n connectedCallback() {\n this.innerHTML = `\n <header>\n <nav>\n <ul>\n <li><a href=index.html>Home</a></li>\n <li><a href=about.html>About</a></li>\n <li><a href=contact.html>Contact</a></li>\n </ul>\n </nav>\n </header>`;\n }\n }\n customElements.define(\"my-header\", MyHeader);\n \n class MyFooter extends HTMLElement {\n connectedCallback() {\n this.innerHTML = `\n <footer>\n © 2022 My Company\n </footer>`;\n }\n }\n customElements.define(\"my-footer\", MyFooter);\n\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74554989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20180952/"
] |
74,555,003
|
<p>I have the following dictionary in python:</p>
<pre><code>dict={('M1 ', 'V1'): 5,
('M1 ', 'V2'): 5,
('M1 ', 'V3'): 5,
('M1 ', 'V4'): 5,
('M2', 'V1'): 5,
('M2', 'V2'): 5,
('M2', 'V3'): 5,
('M2', 'V4'): 5,
('M3', 'V1'): 5,
('M3', 'V2'): 5,
('M3', 'V3'): 5,
('M3', 'V4'): 5}
</code></pre>
<p>For contextualization, "dict" is a matrix distance (('Source', 'Destination'): Value) for an optimization problem, and in conducting a sensitivity analysis, I want to make the distances from M1 so high that the model won't choose it. Therefore, I want to get the python code to change the value of each line where M1 is a source.</p>
|
[
{
"answer_id": 74555046,
"author": "Ahmed Aredah",
"author_id": 5800005,
"author_profile": "https://Stackoverflow.com/users/5800005",
"pm_score": 1,
"selected": false,
"text": "#let's get a list of your keys first\nl = [] #a placeholder for the dict keys that has 'M1' in source\nfor k in dict.keys(): # iterate the keys\n if k[0].strip() == 'M1': # 'M1' in the source node, strip to remove whitespaces if found\n l.append(k) # a list of the keys that has 'M1' as a source\n"
},
{
"answer_id": 74555049,
"author": "Mark",
"author_id": 3874623,
"author_profile": "https://Stackoverflow.com/users/3874623",
"pm_score": 1,
"selected": false,
"text": "M1 d={\n ('M1', 'V1'): 5,\n ('M1', 'V2'): 5,\n ('M1', 'V3'): 5,\n ('M1', 'V4'): 5,\n ('M2', 'V1'): 5,\n ('M2', 'V2'): 5,\n ('M2', 'V3'): 5,\n ('M2', 'V4'): 5,\n ('M3', 'V1'): 5,\n ('M3', 'V2'): 5,\n ('M3', 'V3'): 5,\n ('M3', 'V4'): 5\n}\n\nfor source, dest in d:\n if source == 'M1':\n d[(source, dest)] *= 10000\n \n d {('M1', 'V1'): 50000,\n ('M1', 'V2'): 50000,\n ('M1', 'V3'): 50000,\n ('M1', 'V4'): 50000,\n ('M2', 'V1'): 5,\n ('M2', 'V2'): 5,\n ('M2', 'V3'): 5,\n ('M2', 'V4'): 5,\n ('M3', 'V1'): 5,\n ('M3', 'V2'): 5,\n ('M3', 'V3'): 5,\n ('M3', 'V4'): 5}\n \"M1 \" \"M1\""
},
{
"answer_id": 74555050,
"author": "Dash",
"author_id": 11542834,
"author_profile": "https://Stackoverflow.com/users/11542834",
"pm_score": 1,
"selected": true,
"text": "dict distances = {(...): ...,}\n\nfor source, destination in distances:\n if source == \"M1 \":\n distances[(source, destination)] = 100000 # or something\n\n"
},
{
"answer_id": 74555086,
"author": "Edward Peters",
"author_id": 6016064,
"author_profile": "https://Stackoverflow.com/users/6016064",
"pm_score": 1,
"selected": false,
"text": "\n f = lambda src, dist : (dist * 100) if (src == 'M1 ') else dist\n new_dict = {(src, dst): f(src, v) for (src, dst), v in dict.items()}\n .map()"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10634518/"
] |
74,555,008
|
<p>I'm trying to make the red square on top of the table. I read the articles about Z-index Stacking Context and this stack overflow <a href="https://stackoverflow.com/questions/19850037/override-css-z-index-stacking-context">Override CSS Z-Index Stacking Context</a>.
I guess there's a way to solve it using the transform stuff. But it's not working in my case. It would be helpful if you had some advice. Thanks.</p>
<p><a href="https://i.stack.imgur.com/SJTob.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SJTob.png" alt="enter image description here" /></a></p>
<ul>
<li>html</li>
</ul>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" href="styles.css" />
<script type="module" src="script.js"></script>
</head>
<body>
<div class="top">
<table>
<thead>
<tr>
<th colspan="2">The table header</th>
</tr>
</thead>
<tbody>
<tr>
<td>The table body</td>
<td>with two columns</td>
</tr>
</tbody>
</table>
</div>
<div class="bottom">
<div>
<div><span class="red">Red</span></div>
<div><span class="green">Green</span></div>
<div><span class="blue">Blue</span></div>
</div>
</div>
</body>
</html>
</code></pre>
<ul>
<li>css</li>
</ul>
<pre class="lang-css prettyprint-override"><code>.top {
z-index: 2;
position: relative;
}
.bottom {
z-index: 1;
position: relative;
}
table,
td {
border: 1px solid #333;
z-index: 4;
position: relative;
background-color: #fff;
}
thead,
tfoot {
background-color: #333;
color: #fff;
}
.red,
.green,
.blue {
position: absolute;
width: 100px;
color: white;
line-height: 100px;
text-align: center;
}
.red {
z-index: 111;
top: -40px;
left: 20px;
background: red;
transform: translateZ(1px);
}
.green {
top: -20px;
left: 60px;
background: green;
}
.blue {
top: -10px;
left: 100px;
background: blue;
}
body,
div:first-child {
transform-style: preserve-3d;
}
</code></pre>
<ul>
<li>stackblitz: <a href="https://stackblitz.com/edit/web-platform-8aygtn?file=styles.css" rel="nofollow noreferrer">https://stackblitz.com/edit/web-platform-8aygtn?file=styles.css</a></li>
</ul>
|
[
{
"answer_id": 74555141,
"author": "Aaron Magpantay",
"author_id": 6553004,
"author_profile": "https://Stackoverflow.com/users/6553004",
"pm_score": 0,
"selected": false,
"text": ".top {\n position: relative;\n}\n.bottom {\n position: relative;\n}\ntable,\ntd {\n border: 1px solid #333;\n z-index: 0;\n position: relative;\n background-color: #fff;\n}\nthead,\ntfoot {\n background-color: #333;\n color: #fff;\n}\n.red,\n.green,\n.blue {\n position: absolute;\n width: 100px;\n color: white;\n line-height: 100px;\n text-align: center;\n}\n.red {\n z-index: 1;\n top: -40px;\n left: 20px;\n background: red;\n\n}\n.green {\n top: -20px;\n left: 60px;\n background: green;\n z-index: -3;\n}\n.blue {\n top: -10px;\n left: 100px;\n background: blue;\n z-index: -2;\n} <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <title>Home</title>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width\" />\n <link rel=\"stylesheet\" href=\"styles.css\" />\n <script type=\"module\" src=\"script.js\"></script>\n </head>\n <body>\n <div class=\"top\">\n <table>\n <thead>\n <tr>\n <th colspan=\"2\">The table header</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>The table body</td>\n <td>with two columns</td>\n </tr>\n </tbody>\n </table>\n\n\n </div>\n <div class=\"bottom\">\n <div>\n <div><span class=\"red\">Red</span></div>\n <div><span class=\"green\">Green</span></div>\n <div><span class=\"blue\">Blue</span></div>\n </div>\n </div>\n </body>\n </html> body,\ndiv:first-child {\n transform-style: preserve-3d;\n}\n"
},
{
"answer_id": 74555204,
"author": "jerry",
"author_id": 20493210,
"author_profile": "https://Stackoverflow.com/users/20493210",
"pm_score": 2,
"selected": true,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Home</title>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width\" />\n <link rel=\"stylesheet\" href=\"styles.css\" />\n <script type=\"module\" src=\"script.js\"></script>\n </head>\n <style>\n .top {\n z-index: 2;\n position: relative;\n }\n .bottom {\n z-index: 1;\n position: relative;\n }\n table,\n td {\n border: 1px solid #333;\n z-index: 4;\n position: relative;\n background-color: #fff;\n }\n thead,\n tfoot {\n background-color: #333;\n color: #fff;\n }\n .red,\n .green,\n .blue {\n position: absolute;\n width: 100px;\n color: white;\n line-height: 100px;\n text-align: center;\n }\n .red {\n z-index: 111;\n top: -40px;\n left: 20px;\n background: red;\n transform: translateZ(1px);\n }\n .green {\n top: -20px;\n left: 60px;\n background: green;\n }\n .blue {\n top: -10px;\n left: 100px;\n background: blue;\n }\n body,\n div:first-child {\n z-index: -1;\n transform-style: preserve-3d;\n }\n </style>\n <body>\n <div class=\"top\">\n <table>\n <thead>\n <tr>\n <th colspan=\"2\">The table header</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>The table body</td>\n <td>with two columns</td>\n </tr>\n </tbody>\n </table>\n </div>\n <div class=\"bottom\">\n <div>\n <div><span class=\"red\">Red</span></div>\n <div><span class=\"green\">Green</span></div>\n <div><span class=\"blue\">Blue</span></div>\n </div>\n </div>\n </body>\n</html>"
},
{
"answer_id": 74555206,
"author": "ray",
"author_id": 636077,
"author_profile": "https://Stackoverflow.com/users/636077",
"pm_score": 0,
"selected": false,
"text": "/* .top {\n z-index: 2;\n position: relative;\n} */\n\n.bottom {\n /* z-index: 1; */\n position: relative;\n}\ntable,\ntd {\n border: 1px solid #333;\n z-index: 4;\n position: relative;\n background-color: #fff;\n}\nthead,\ntfoot {\n background-color: #333;\n color: #fff;\n}\n.red,\n.green,\n.blue {\n position: absolute;\n width: 100px;\n color: white;\n line-height: 100px;\n text-align: center;\n}\n.red {\n z-index: 111;\n top: -40px;\n left: 20px;\n background: red;\n /* transform: translateZ(1px); */\n}\n.green {\n top: -20px;\n left: 60px;\n background: green;\n}\n.blue {\n top: -10px;\n left: 100px;\n background: blue;\n}\n/* body,\ndiv:first-child {\n transform-style: preserve-3d;\n} */ <!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Home</title>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width\" />\n <link rel=\"stylesheet\" href=\"styles.css\" />\n <script type=\"module\" src=\"script.js\"></script>\n </head>\n <body>\n <div class=\"top\">\n <table>\n <thead>\n <tr>\n <th colspan=\"2\">The table header</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>The table body</td>\n <td>with two columns</td>\n </tr>\n </tbody>\n </table>\n </div>\n <div class=\"bottom\">\n <div>\n <div><span class=\"red\">Red</span></div>\n <div><span class=\"green\">Green</span></div>\n <div><span class=\"blue\">Blue</span></div>\n </div>\n </div>\n </body>\n</html>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16477447/"
] |
74,555,012
|
<p>I have multiple polygon maps (made up of lines and arcs). I am using turf.lineArc() to calculate points on an arc and to do this the start and end points of the arc need to be <strong>clockwise</strong>, if not they need to be swapped around.
I have the following code to swap the start and end points around (but it is not quite right)</p>
<pre><code>if (endAngle < startAngle) {
endAngle = endAngle + 360;
}
if (startAngle < endAngle) {
var e = endAngle;
endAngle = startAngle;
startAngle = e;
}
while (startAngle - endAngle > 180) {
startAngle = startAngle - 360;
}
var arc = turf.lineArc(center, radius, startAngle, endAngle, options);
</code></pre>
<p>My problem is knowing when to swap the start and end around and when not to. In my attached picture Map1 works correctly without being swapped around but Map2 needs to have the start and end points swapped. (and they both need to use the same code). If map 2 does not have the start and end swapped around turf.lineArc draws a major arc of 353 degrees which is not what I want.
How do I fix my code so I only swap the start and end points when travelling from start to end is in an anti-clockwise direction?</p>
<p>Thank you :)</p>
<p>Edit: Arc can be < 180 or >180 and I know if it is major (>180) or minor (<180)
<a href="https://i.stack.imgur.com/7Wvcd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7Wvcd.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74555141,
"author": "Aaron Magpantay",
"author_id": 6553004,
"author_profile": "https://Stackoverflow.com/users/6553004",
"pm_score": 0,
"selected": false,
"text": ".top {\n position: relative;\n}\n.bottom {\n position: relative;\n}\ntable,\ntd {\n border: 1px solid #333;\n z-index: 0;\n position: relative;\n background-color: #fff;\n}\nthead,\ntfoot {\n background-color: #333;\n color: #fff;\n}\n.red,\n.green,\n.blue {\n position: absolute;\n width: 100px;\n color: white;\n line-height: 100px;\n text-align: center;\n}\n.red {\n z-index: 1;\n top: -40px;\n left: 20px;\n background: red;\n\n}\n.green {\n top: -20px;\n left: 60px;\n background: green;\n z-index: -3;\n}\n.blue {\n top: -10px;\n left: 100px;\n background: blue;\n z-index: -2;\n} <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <title>Home</title>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width\" />\n <link rel=\"stylesheet\" href=\"styles.css\" />\n <script type=\"module\" src=\"script.js\"></script>\n </head>\n <body>\n <div class=\"top\">\n <table>\n <thead>\n <tr>\n <th colspan=\"2\">The table header</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>The table body</td>\n <td>with two columns</td>\n </tr>\n </tbody>\n </table>\n\n\n </div>\n <div class=\"bottom\">\n <div>\n <div><span class=\"red\">Red</span></div>\n <div><span class=\"green\">Green</span></div>\n <div><span class=\"blue\">Blue</span></div>\n </div>\n </div>\n </body>\n </html> body,\ndiv:first-child {\n transform-style: preserve-3d;\n}\n"
},
{
"answer_id": 74555204,
"author": "jerry",
"author_id": 20493210,
"author_profile": "https://Stackoverflow.com/users/20493210",
"pm_score": 2,
"selected": true,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Home</title>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width\" />\n <link rel=\"stylesheet\" href=\"styles.css\" />\n <script type=\"module\" src=\"script.js\"></script>\n </head>\n <style>\n .top {\n z-index: 2;\n position: relative;\n }\n .bottom {\n z-index: 1;\n position: relative;\n }\n table,\n td {\n border: 1px solid #333;\n z-index: 4;\n position: relative;\n background-color: #fff;\n }\n thead,\n tfoot {\n background-color: #333;\n color: #fff;\n }\n .red,\n .green,\n .blue {\n position: absolute;\n width: 100px;\n color: white;\n line-height: 100px;\n text-align: center;\n }\n .red {\n z-index: 111;\n top: -40px;\n left: 20px;\n background: red;\n transform: translateZ(1px);\n }\n .green {\n top: -20px;\n left: 60px;\n background: green;\n }\n .blue {\n top: -10px;\n left: 100px;\n background: blue;\n }\n body,\n div:first-child {\n z-index: -1;\n transform-style: preserve-3d;\n }\n </style>\n <body>\n <div class=\"top\">\n <table>\n <thead>\n <tr>\n <th colspan=\"2\">The table header</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>The table body</td>\n <td>with two columns</td>\n </tr>\n </tbody>\n </table>\n </div>\n <div class=\"bottom\">\n <div>\n <div><span class=\"red\">Red</span></div>\n <div><span class=\"green\">Green</span></div>\n <div><span class=\"blue\">Blue</span></div>\n </div>\n </div>\n </body>\n</html>"
},
{
"answer_id": 74555206,
"author": "ray",
"author_id": 636077,
"author_profile": "https://Stackoverflow.com/users/636077",
"pm_score": 0,
"selected": false,
"text": "/* .top {\n z-index: 2;\n position: relative;\n} */\n\n.bottom {\n /* z-index: 1; */\n position: relative;\n}\ntable,\ntd {\n border: 1px solid #333;\n z-index: 4;\n position: relative;\n background-color: #fff;\n}\nthead,\ntfoot {\n background-color: #333;\n color: #fff;\n}\n.red,\n.green,\n.blue {\n position: absolute;\n width: 100px;\n color: white;\n line-height: 100px;\n text-align: center;\n}\n.red {\n z-index: 111;\n top: -40px;\n left: 20px;\n background: red;\n /* transform: translateZ(1px); */\n}\n.green {\n top: -20px;\n left: 60px;\n background: green;\n}\n.blue {\n top: -10px;\n left: 100px;\n background: blue;\n}\n/* body,\ndiv:first-child {\n transform-style: preserve-3d;\n} */ <!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Home</title>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width\" />\n <link rel=\"stylesheet\" href=\"styles.css\" />\n <script type=\"module\" src=\"script.js\"></script>\n </head>\n <body>\n <div class=\"top\">\n <table>\n <thead>\n <tr>\n <th colspan=\"2\">The table header</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>The table body</td>\n <td>with two columns</td>\n </tr>\n </tbody>\n </table>\n </div>\n <div class=\"bottom\">\n <div>\n <div><span class=\"red\">Red</span></div>\n <div><span class=\"green\">Green</span></div>\n <div><span class=\"blue\">Blue</span></div>\n </div>\n </div>\n </body>\n</html>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15502957/"
] |
74,555,018
|
<p>for example i have <code>excel header</code> list like this</p>
<pre><code>excel_headers = [
'Name',
'Age',
'Sex',
]
</code></pre>
<p>and i have another <code>list</code> to check againt it.</p>
<pre><code>headers = {'Name' : 1, 'Age': 2, 'Sex': 3, 'Whatever': 4}
</code></pre>
<p>i dont care if <code>headers</code> have <em>whatever</em> elements, i care only <em>element in headers</em> has <em>excel_headers</em> element.</p>
<p><code>WHAT I've TRIED</code></p>
<pre><code>lst = all(headers[idx][0] == header for idx,
header in enumerate(excel_headers))
print(lst)
</code></pre>
<p>however it always return <code>False</code>.</p>
<p>any help? pleasse</p>
|
[
{
"answer_id": 74555141,
"author": "Aaron Magpantay",
"author_id": 6553004,
"author_profile": "https://Stackoverflow.com/users/6553004",
"pm_score": 0,
"selected": false,
"text": ".top {\n position: relative;\n}\n.bottom {\n position: relative;\n}\ntable,\ntd {\n border: 1px solid #333;\n z-index: 0;\n position: relative;\n background-color: #fff;\n}\nthead,\ntfoot {\n background-color: #333;\n color: #fff;\n}\n.red,\n.green,\n.blue {\n position: absolute;\n width: 100px;\n color: white;\n line-height: 100px;\n text-align: center;\n}\n.red {\n z-index: 1;\n top: -40px;\n left: 20px;\n background: red;\n\n}\n.green {\n top: -20px;\n left: 60px;\n background: green;\n z-index: -3;\n}\n.blue {\n top: -10px;\n left: 100px;\n background: blue;\n z-index: -2;\n} <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <title>Home</title>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width\" />\n <link rel=\"stylesheet\" href=\"styles.css\" />\n <script type=\"module\" src=\"script.js\"></script>\n </head>\n <body>\n <div class=\"top\">\n <table>\n <thead>\n <tr>\n <th colspan=\"2\">The table header</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>The table body</td>\n <td>with two columns</td>\n </tr>\n </tbody>\n </table>\n\n\n </div>\n <div class=\"bottom\">\n <div>\n <div><span class=\"red\">Red</span></div>\n <div><span class=\"green\">Green</span></div>\n <div><span class=\"blue\">Blue</span></div>\n </div>\n </div>\n </body>\n </html> body,\ndiv:first-child {\n transform-style: preserve-3d;\n}\n"
},
{
"answer_id": 74555204,
"author": "jerry",
"author_id": 20493210,
"author_profile": "https://Stackoverflow.com/users/20493210",
"pm_score": 2,
"selected": true,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Home</title>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width\" />\n <link rel=\"stylesheet\" href=\"styles.css\" />\n <script type=\"module\" src=\"script.js\"></script>\n </head>\n <style>\n .top {\n z-index: 2;\n position: relative;\n }\n .bottom {\n z-index: 1;\n position: relative;\n }\n table,\n td {\n border: 1px solid #333;\n z-index: 4;\n position: relative;\n background-color: #fff;\n }\n thead,\n tfoot {\n background-color: #333;\n color: #fff;\n }\n .red,\n .green,\n .blue {\n position: absolute;\n width: 100px;\n color: white;\n line-height: 100px;\n text-align: center;\n }\n .red {\n z-index: 111;\n top: -40px;\n left: 20px;\n background: red;\n transform: translateZ(1px);\n }\n .green {\n top: -20px;\n left: 60px;\n background: green;\n }\n .blue {\n top: -10px;\n left: 100px;\n background: blue;\n }\n body,\n div:first-child {\n z-index: -1;\n transform-style: preserve-3d;\n }\n </style>\n <body>\n <div class=\"top\">\n <table>\n <thead>\n <tr>\n <th colspan=\"2\">The table header</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>The table body</td>\n <td>with two columns</td>\n </tr>\n </tbody>\n </table>\n </div>\n <div class=\"bottom\">\n <div>\n <div><span class=\"red\">Red</span></div>\n <div><span class=\"green\">Green</span></div>\n <div><span class=\"blue\">Blue</span></div>\n </div>\n </div>\n </body>\n</html>"
},
{
"answer_id": 74555206,
"author": "ray",
"author_id": 636077,
"author_profile": "https://Stackoverflow.com/users/636077",
"pm_score": 0,
"selected": false,
"text": "/* .top {\n z-index: 2;\n position: relative;\n} */\n\n.bottom {\n /* z-index: 1; */\n position: relative;\n}\ntable,\ntd {\n border: 1px solid #333;\n z-index: 4;\n position: relative;\n background-color: #fff;\n}\nthead,\ntfoot {\n background-color: #333;\n color: #fff;\n}\n.red,\n.green,\n.blue {\n position: absolute;\n width: 100px;\n color: white;\n line-height: 100px;\n text-align: center;\n}\n.red {\n z-index: 111;\n top: -40px;\n left: 20px;\n background: red;\n /* transform: translateZ(1px); */\n}\n.green {\n top: -20px;\n left: 60px;\n background: green;\n}\n.blue {\n top: -10px;\n left: 100px;\n background: blue;\n}\n/* body,\ndiv:first-child {\n transform-style: preserve-3d;\n} */ <!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Home</title>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width\" />\n <link rel=\"stylesheet\" href=\"styles.css\" />\n <script type=\"module\" src=\"script.js\"></script>\n </head>\n <body>\n <div class=\"top\">\n <table>\n <thead>\n <tr>\n <th colspan=\"2\">The table header</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>The table body</td>\n <td>with two columns</td>\n </tr>\n </tbody>\n </table>\n </div>\n <div class=\"bottom\">\n <div>\n <div><span class=\"red\">Red</span></div>\n <div><span class=\"green\">Green</span></div>\n <div><span class=\"blue\">Blue</span></div>\n </div>\n </div>\n </body>\n</html>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11823123/"
] |
74,555,028
|
<p>I am getting this error whenrunning on expo. The uid is in firebase.</p>
<p><a href="https://i.stack.imgur.com/tawi7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tawi7.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74555141,
"author": "Aaron Magpantay",
"author_id": 6553004,
"author_profile": "https://Stackoverflow.com/users/6553004",
"pm_score": 0,
"selected": false,
"text": ".top {\n position: relative;\n}\n.bottom {\n position: relative;\n}\ntable,\ntd {\n border: 1px solid #333;\n z-index: 0;\n position: relative;\n background-color: #fff;\n}\nthead,\ntfoot {\n background-color: #333;\n color: #fff;\n}\n.red,\n.green,\n.blue {\n position: absolute;\n width: 100px;\n color: white;\n line-height: 100px;\n text-align: center;\n}\n.red {\n z-index: 1;\n top: -40px;\n left: 20px;\n background: red;\n\n}\n.green {\n top: -20px;\n left: 60px;\n background: green;\n z-index: -3;\n}\n.blue {\n top: -10px;\n left: 100px;\n background: blue;\n z-index: -2;\n} <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <title>Home</title>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width\" />\n <link rel=\"stylesheet\" href=\"styles.css\" />\n <script type=\"module\" src=\"script.js\"></script>\n </head>\n <body>\n <div class=\"top\">\n <table>\n <thead>\n <tr>\n <th colspan=\"2\">The table header</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>The table body</td>\n <td>with two columns</td>\n </tr>\n </tbody>\n </table>\n\n\n </div>\n <div class=\"bottom\">\n <div>\n <div><span class=\"red\">Red</span></div>\n <div><span class=\"green\">Green</span></div>\n <div><span class=\"blue\">Blue</span></div>\n </div>\n </div>\n </body>\n </html> body,\ndiv:first-child {\n transform-style: preserve-3d;\n}\n"
},
{
"answer_id": 74555204,
"author": "jerry",
"author_id": 20493210,
"author_profile": "https://Stackoverflow.com/users/20493210",
"pm_score": 2,
"selected": true,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Home</title>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width\" />\n <link rel=\"stylesheet\" href=\"styles.css\" />\n <script type=\"module\" src=\"script.js\"></script>\n </head>\n <style>\n .top {\n z-index: 2;\n position: relative;\n }\n .bottom {\n z-index: 1;\n position: relative;\n }\n table,\n td {\n border: 1px solid #333;\n z-index: 4;\n position: relative;\n background-color: #fff;\n }\n thead,\n tfoot {\n background-color: #333;\n color: #fff;\n }\n .red,\n .green,\n .blue {\n position: absolute;\n width: 100px;\n color: white;\n line-height: 100px;\n text-align: center;\n }\n .red {\n z-index: 111;\n top: -40px;\n left: 20px;\n background: red;\n transform: translateZ(1px);\n }\n .green {\n top: -20px;\n left: 60px;\n background: green;\n }\n .blue {\n top: -10px;\n left: 100px;\n background: blue;\n }\n body,\n div:first-child {\n z-index: -1;\n transform-style: preserve-3d;\n }\n </style>\n <body>\n <div class=\"top\">\n <table>\n <thead>\n <tr>\n <th colspan=\"2\">The table header</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>The table body</td>\n <td>with two columns</td>\n </tr>\n </tbody>\n </table>\n </div>\n <div class=\"bottom\">\n <div>\n <div><span class=\"red\">Red</span></div>\n <div><span class=\"green\">Green</span></div>\n <div><span class=\"blue\">Blue</span></div>\n </div>\n </div>\n </body>\n</html>"
},
{
"answer_id": 74555206,
"author": "ray",
"author_id": 636077,
"author_profile": "https://Stackoverflow.com/users/636077",
"pm_score": 0,
"selected": false,
"text": "/* .top {\n z-index: 2;\n position: relative;\n} */\n\n.bottom {\n /* z-index: 1; */\n position: relative;\n}\ntable,\ntd {\n border: 1px solid #333;\n z-index: 4;\n position: relative;\n background-color: #fff;\n}\nthead,\ntfoot {\n background-color: #333;\n color: #fff;\n}\n.red,\n.green,\n.blue {\n position: absolute;\n width: 100px;\n color: white;\n line-height: 100px;\n text-align: center;\n}\n.red {\n z-index: 111;\n top: -40px;\n left: 20px;\n background: red;\n /* transform: translateZ(1px); */\n}\n.green {\n top: -20px;\n left: 60px;\n background: green;\n}\n.blue {\n top: -10px;\n left: 100px;\n background: blue;\n}\n/* body,\ndiv:first-child {\n transform-style: preserve-3d;\n} */ <!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Home</title>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width\" />\n <link rel=\"stylesheet\" href=\"styles.css\" />\n <script type=\"module\" src=\"script.js\"></script>\n </head>\n <body>\n <div class=\"top\">\n <table>\n <thead>\n <tr>\n <th colspan=\"2\">The table header</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>The table body</td>\n <td>with two columns</td>\n </tr>\n </tbody>\n </table>\n </div>\n <div class=\"bottom\">\n <div>\n <div><span class=\"red\">Red</span></div>\n <div><span class=\"green\">Green</span></div>\n <div><span class=\"blue\">Blue</span></div>\n </div>\n </div>\n </body>\n</html>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19991906/"
] |
74,555,059
|
<p>How can I tell the compiler that <code>U</code> is equivalent to either <code>std::vector<T></code> or <code>T</code>?</p>
<pre><code>template<typename T, typename U> std::vector<T> foo(T t, U){return std::vector<T>{};}
</code></pre>
|
[
{
"answer_id": 74555193,
"author": "John",
"author_id": 13611002,
"author_profile": "https://Stackoverflow.com/users/13611002",
"pm_score": 0,
"selected": false,
"text": "std::enable_if #include <iostream>\n#include <vector>\n \ntemplate<typename T, typename U, typename = typename std::enable_if< \n std::is_same< T, U >::value || std::is_same<std::vector<T>, U>::value>::type>\nstd::vector<int> foo()\n{\n std::cout << \"on the move!\\n\";\n\n return {};\n}\n\nint main()\n{\n foo<int, int>();\n foo<int, std::vector<int>>();\n //foo<int, float>(); //does not compile, in expectation.\n}\n #include <iostream>\n#include <vector>\n#include <functional>\n \ntemplate<typename T, typename U, typename = typename std::enable_if< \n std::is_same< T, U >::value || std::is_same<std::vector<T>, U>::value>::type>\nvoid foo(std::function<U(void)> func)\n{\n std::cout << \"on the move!\\n\";\n}\n\nint main()\n{\n foo<int>(std::function<int(void)>());\n foo<int>(std::function<std::vector<int>(void)>());\n //foo<int>(std::function<float(void)>()); //does not compile, in expectation.\n}\n"
},
{
"answer_id": 74555362,
"author": "Amro",
"author_id": 15749309,
"author_profile": "https://Stackoverflow.com/users/15749309",
"pm_score": 2,
"selected": false,
"text": "// Generic function\n// UPDATE: you can ignore this function altogether and use the two overloads below\ntemplate<typename T, typename U> std::vector<T> foo(T t, U u) { // Do something}\n\n// First specialization for the case of U == T\n// UPDATE: this is an *overload*, not a specialization\ntemplate<typename T> std::vector<T> foo(T t, T u) { // Do something}\n\n// Second specialization for the case of U == std::vector<T>\n// UPDATE: this is an *overload*, not a specialization\ntemplate<typename T> std::vector<T> foo(T t, std::vector<T> u) { // Do something}\n"
},
{
"answer_id": 74564206,
"author": "Marek R",
"author_id": 1387438,
"author_profile": "https://Stackoverflow.com/users/1387438",
"pm_score": 0,
"selected": false,
"text": "namespace me {\n // c++20 has this, so putting that in own namespace to cover older standards\n template<typename T>\n strut identity {\n using type = T;\n };\n\n template<typename T>\n using identity_t = typename identityT<>::type;\n}\n\n\ntemplate<typename T>\nstd::vector<T> foo(T t, const std::vector<me::indentity_t<T>>& v) {\n auto copy = v;\n copy.push_back(t);\n return copy;\n}\n\ntemplate<typename T>\nstd::vector<T> foo(T t, me::indentity_t<T> v) {\n return { v, t };\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611002/"
] |
74,555,061
|
<p>I have this controller</p>
<pre><code><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Category;
class CategoriesController extends Controller
{
public function index()
{
$categories = Category::all();
return view('home', ['categories'=> $categories]);
}
}
</code></pre>
<p>and my blade is something like this(his call "home.blade.php")</p>
<pre><code> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.3.3/css/swiper.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.3.3/js/swiper.min.js"></script>
<div class="container">
<div class="row text-center mb-3">
<div class="col-md-12">
<h2>Categorias</h2>
<hr>
@foreach($categories as $cat)
<button>{{ $cat->CATEGORIA_NOME }}</button>
@endforeach
</div>
</div>
</code></pre>
<p>the Model:</p>
<pre><code><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
protected $fillable = ['CATEGORIA_NOME', 'CATEGORIA_DESC'];
protected $table = 'CATEGORIA';
protected $primaryKey = 'CATEGORIA_ID';
protected $timestamp = false;
public function categorias()
{
return $this->hasMany(Product::class, 'CATEGORIA_ID');
}
}
</code></pre>
<p>but i still receiving the error:
Undefined variable $categories</p>
<p>I tried to using the</p>
<pre><code> $categories = Category::all();
return view('home', ['categories'=> $categories]);
</code></pre>
<p>or</p>
<p>return view('home')->with('categories', $categories);</p>
<p>but it did not work</p>
|
[
{
"answer_id": 74555193,
"author": "John",
"author_id": 13611002,
"author_profile": "https://Stackoverflow.com/users/13611002",
"pm_score": 0,
"selected": false,
"text": "std::enable_if #include <iostream>\n#include <vector>\n \ntemplate<typename T, typename U, typename = typename std::enable_if< \n std::is_same< T, U >::value || std::is_same<std::vector<T>, U>::value>::type>\nstd::vector<int> foo()\n{\n std::cout << \"on the move!\\n\";\n\n return {};\n}\n\nint main()\n{\n foo<int, int>();\n foo<int, std::vector<int>>();\n //foo<int, float>(); //does not compile, in expectation.\n}\n #include <iostream>\n#include <vector>\n#include <functional>\n \ntemplate<typename T, typename U, typename = typename std::enable_if< \n std::is_same< T, U >::value || std::is_same<std::vector<T>, U>::value>::type>\nvoid foo(std::function<U(void)> func)\n{\n std::cout << \"on the move!\\n\";\n}\n\nint main()\n{\n foo<int>(std::function<int(void)>());\n foo<int>(std::function<std::vector<int>(void)>());\n //foo<int>(std::function<float(void)>()); //does not compile, in expectation.\n}\n"
},
{
"answer_id": 74555362,
"author": "Amro",
"author_id": 15749309,
"author_profile": "https://Stackoverflow.com/users/15749309",
"pm_score": 2,
"selected": false,
"text": "// Generic function\n// UPDATE: you can ignore this function altogether and use the two overloads below\ntemplate<typename T, typename U> std::vector<T> foo(T t, U u) { // Do something}\n\n// First specialization for the case of U == T\n// UPDATE: this is an *overload*, not a specialization\ntemplate<typename T> std::vector<T> foo(T t, T u) { // Do something}\n\n// Second specialization for the case of U == std::vector<T>\n// UPDATE: this is an *overload*, not a specialization\ntemplate<typename T> std::vector<T> foo(T t, std::vector<T> u) { // Do something}\n"
},
{
"answer_id": 74564206,
"author": "Marek R",
"author_id": 1387438,
"author_profile": "https://Stackoverflow.com/users/1387438",
"pm_score": 0,
"selected": false,
"text": "namespace me {\n // c++20 has this, so putting that in own namespace to cover older standards\n template<typename T>\n strut identity {\n using type = T;\n };\n\n template<typename T>\n using identity_t = typename identityT<>::type;\n}\n\n\ntemplate<typename T>\nstd::vector<T> foo(T t, const std::vector<me::indentity_t<T>>& v) {\n auto copy = v;\n copy.push_back(t);\n return copy;\n}\n\ntemplate<typename T>\nstd::vector<T> foo(T t, me::indentity_t<T> v) {\n return { v, t };\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20586781/"
] |
74,555,081
|
<p>I am from Javascript developer and start developing on flutter for company use.
I currently facing an issue about setting profile value to gui.</p>
<pre><code>//profile.dart
import 'package:flutter/material.dart';
import 'package:profile/profile.dart';
import 'package:cs_app/models/user.dart';
import 'package:cs_app/models/cs_data.dart';
import 'package:cs_app/models/profile_data.dart';
import 'package:provider/provider.dart';
class AdminPage extends StatefulWidget {
const AdminPage({Key? key}) : super(key: key);
@override
State<AdminPage> createState() => _AdminPageState();
}
profile_value(key) async {
var value = await profileData.user_profile(key);
print("rtn: " + value);
// rtn: admin, can get the print value
return value;
}
class _AdminPageState extends State<AdminPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Profile(
imageUrl:
"https://images.unsplash.com/photo-1598618356794-eb1720430eb4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80",
name: profile_value("username"), // run func, get rtn value, render
website: profile_value("website"),
designation: profile_value("designation"),
email: "xxx@gmail.com",
phone_number: "12345456",
),
));
}
}
</code></pre>
<pre><code>//profile_data.dart
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:cs_app/views/login.dart';
import 'dart:convert';
import 'package:cs_app/models/sharedPref.dart';
class profileData {
static user_profile(key) async {
var value = await SharedPref().read("user");
var decode_value = json.decode(value);
var key_decode_value = decode_value[key];
print("key: " + key);
print("value: " + key_decode_value);
// key: username
// value: admin
return key_decode_value;
}
}
</code></pre>
<p>In my mindset is when <em>_AdminPageState</em> run, the key will run <em>profile_value(key)</em> to get rtn value.
But it keeps return The argument type 'Future' can't be assigned to the parameter type 'String'.</p>
|
[
{
"answer_id": 74555193,
"author": "John",
"author_id": 13611002,
"author_profile": "https://Stackoverflow.com/users/13611002",
"pm_score": 0,
"selected": false,
"text": "std::enable_if #include <iostream>\n#include <vector>\n \ntemplate<typename T, typename U, typename = typename std::enable_if< \n std::is_same< T, U >::value || std::is_same<std::vector<T>, U>::value>::type>\nstd::vector<int> foo()\n{\n std::cout << \"on the move!\\n\";\n\n return {};\n}\n\nint main()\n{\n foo<int, int>();\n foo<int, std::vector<int>>();\n //foo<int, float>(); //does not compile, in expectation.\n}\n #include <iostream>\n#include <vector>\n#include <functional>\n \ntemplate<typename T, typename U, typename = typename std::enable_if< \n std::is_same< T, U >::value || std::is_same<std::vector<T>, U>::value>::type>\nvoid foo(std::function<U(void)> func)\n{\n std::cout << \"on the move!\\n\";\n}\n\nint main()\n{\n foo<int>(std::function<int(void)>());\n foo<int>(std::function<std::vector<int>(void)>());\n //foo<int>(std::function<float(void)>()); //does not compile, in expectation.\n}\n"
},
{
"answer_id": 74555362,
"author": "Amro",
"author_id": 15749309,
"author_profile": "https://Stackoverflow.com/users/15749309",
"pm_score": 2,
"selected": false,
"text": "// Generic function\n// UPDATE: you can ignore this function altogether and use the two overloads below\ntemplate<typename T, typename U> std::vector<T> foo(T t, U u) { // Do something}\n\n// First specialization for the case of U == T\n// UPDATE: this is an *overload*, not a specialization\ntemplate<typename T> std::vector<T> foo(T t, T u) { // Do something}\n\n// Second specialization for the case of U == std::vector<T>\n// UPDATE: this is an *overload*, not a specialization\ntemplate<typename T> std::vector<T> foo(T t, std::vector<T> u) { // Do something}\n"
},
{
"answer_id": 74564206,
"author": "Marek R",
"author_id": 1387438,
"author_profile": "https://Stackoverflow.com/users/1387438",
"pm_score": 0,
"selected": false,
"text": "namespace me {\n // c++20 has this, so putting that in own namespace to cover older standards\n template<typename T>\n strut identity {\n using type = T;\n };\n\n template<typename T>\n using identity_t = typename identityT<>::type;\n}\n\n\ntemplate<typename T>\nstd::vector<T> foo(T t, const std::vector<me::indentity_t<T>>& v) {\n auto copy = v;\n copy.push_back(t);\n return copy;\n}\n\ntemplate<typename T>\nstd::vector<T> foo(T t, me::indentity_t<T> v) {\n return { v, t };\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13127102/"
] |
74,555,095
|
<p>I am working on a to-do list application for a project. I would like to change the value of a string in an observableCollection. I am able to change the string in the same window but I would like to change the value from a textbox in a secondary window.</p>
<p>So what I tried to do was is change a string in the first window by using a textbox in the second window. By doing the way I have listed below it just blanks out the item I am trying to edit.</p>
<p>I would like to take the test from the textbox in the second window and use it to modify the taskName in the first window. Below I am going to include my code for the two c# files for the windows.</p>
<p>This is the main window but it is called DemoMainWindow:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ToDoList.ViewModels;
using ToDoList.Model;
namespace ToDoList
{
/// <summary>
/// Interaction logic for DemoMainWindow.xaml
/// </summary>
public partial class DemoMainWindow : Window
{
private ViewModel _viewModel;
public string? EditedTaskName { get; set; }
public DemoMainWindow()
{
InitializeComponent();
TxtUCEnteredTask.txtLimitedInput.Text = "Do the dishes";
_viewModel = new ViewModel();
DataContext = _viewModel;
}
private void BtnAddTask_Click(object sender, RoutedEventArgs e)
{
_viewModel.Tasks.Add(new TaskModel() { TaskName = TxtUCEnteredTask.txtLimitedInput.Text });
}
private void BtnDeleteTask_Click(object sender, RoutedEventArgs e)
{
if(LstBoxTasks.SelectedItem != null)
{
#pragma warning disable CS8604 // Possible null reference argument.
_ = _viewModel.Tasks.Remove(item: LstBoxTasks.SelectedItem as TaskModel);
#pragma warning restore CS8604 // Possible null reference argument.
}
}
private void BtnHelp_Click(object sender, RoutedEventArgs e)
{
HelpWindow helpWindow = new HelpWindow();
helpWindow.Show();
}
private string? GetEditedTaskName()
{
return EditedTaskName;
}
private void BtnEditTask_Click(object sender, RoutedEventArgs e)
{
if (LstBoxTasks.SelectedItem != null)
{
EditWindow editWindow = new EditWindow();
editWindow.Show();
//_viewModel.Tasks[LstBoxTasks.SelectedIndex].TaskName = editedTaskName;
}
}
}
}
</code></pre>
<p>This is the code for the C# file of the second window:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace ToDoList
{
/// <summary>
/// Interaction logic for EditWindow.xaml
/// </summary>
public partial class EditWindow : Window
{
public EditWindow()
{
InitializeComponent();
var DemoMainWindow = this.DataContext;
}
private void BtnEdit_Click(object sender, RoutedEventArgs e)
{
((DemoMainWindow)Application.Current.MainWindow).EditedTaskName = EditTextBox.Text;
// _viewModel.Tasks[LstBoxTasks.SelectedIndex].TaskName = TxtUCEnteredTask.txtLimitedInput.Text;
}
}
}
</code></pre>
|
[
{
"answer_id": 74555193,
"author": "John",
"author_id": 13611002,
"author_profile": "https://Stackoverflow.com/users/13611002",
"pm_score": 0,
"selected": false,
"text": "std::enable_if #include <iostream>\n#include <vector>\n \ntemplate<typename T, typename U, typename = typename std::enable_if< \n std::is_same< T, U >::value || std::is_same<std::vector<T>, U>::value>::type>\nstd::vector<int> foo()\n{\n std::cout << \"on the move!\\n\";\n\n return {};\n}\n\nint main()\n{\n foo<int, int>();\n foo<int, std::vector<int>>();\n //foo<int, float>(); //does not compile, in expectation.\n}\n #include <iostream>\n#include <vector>\n#include <functional>\n \ntemplate<typename T, typename U, typename = typename std::enable_if< \n std::is_same< T, U >::value || std::is_same<std::vector<T>, U>::value>::type>\nvoid foo(std::function<U(void)> func)\n{\n std::cout << \"on the move!\\n\";\n}\n\nint main()\n{\n foo<int>(std::function<int(void)>());\n foo<int>(std::function<std::vector<int>(void)>());\n //foo<int>(std::function<float(void)>()); //does not compile, in expectation.\n}\n"
},
{
"answer_id": 74555362,
"author": "Amro",
"author_id": 15749309,
"author_profile": "https://Stackoverflow.com/users/15749309",
"pm_score": 2,
"selected": false,
"text": "// Generic function\n// UPDATE: you can ignore this function altogether and use the two overloads below\ntemplate<typename T, typename U> std::vector<T> foo(T t, U u) { // Do something}\n\n// First specialization for the case of U == T\n// UPDATE: this is an *overload*, not a specialization\ntemplate<typename T> std::vector<T> foo(T t, T u) { // Do something}\n\n// Second specialization for the case of U == std::vector<T>\n// UPDATE: this is an *overload*, not a specialization\ntemplate<typename T> std::vector<T> foo(T t, std::vector<T> u) { // Do something}\n"
},
{
"answer_id": 74564206,
"author": "Marek R",
"author_id": 1387438,
"author_profile": "https://Stackoverflow.com/users/1387438",
"pm_score": 0,
"selected": false,
"text": "namespace me {\n // c++20 has this, so putting that in own namespace to cover older standards\n template<typename T>\n strut identity {\n using type = T;\n };\n\n template<typename T>\n using identity_t = typename identityT<>::type;\n}\n\n\ntemplate<typename T>\nstd::vector<T> foo(T t, const std::vector<me::indentity_t<T>>& v) {\n auto copy = v;\n copy.push_back(t);\n return copy;\n}\n\ntemplate<typename T>\nstd::vector<T> foo(T t, me::indentity_t<T> v) {\n return { v, t };\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18482853/"
] |
74,555,146
|
<p>I have this list:</p>
<pre><code>t=['a','b','c']
</code></pre>
<p>and want to create the output such as:</p>
<pre><code>['a']
['a','b']
['a','b','c']
</code></pre>
<p>I am not sure how to adjust this loop:</p>
<pre><code>for i in t:
print(i)
</code></pre>
<p>I am not sure how to write the loop to create this appending effect from the last iteration and the current iteration. I hope someone can assist.
Thanks.</p>
|
[
{
"answer_id": 74555193,
"author": "John",
"author_id": 13611002,
"author_profile": "https://Stackoverflow.com/users/13611002",
"pm_score": 0,
"selected": false,
"text": "std::enable_if #include <iostream>\n#include <vector>\n \ntemplate<typename T, typename U, typename = typename std::enable_if< \n std::is_same< T, U >::value || std::is_same<std::vector<T>, U>::value>::type>\nstd::vector<int> foo()\n{\n std::cout << \"on the move!\\n\";\n\n return {};\n}\n\nint main()\n{\n foo<int, int>();\n foo<int, std::vector<int>>();\n //foo<int, float>(); //does not compile, in expectation.\n}\n #include <iostream>\n#include <vector>\n#include <functional>\n \ntemplate<typename T, typename U, typename = typename std::enable_if< \n std::is_same< T, U >::value || std::is_same<std::vector<T>, U>::value>::type>\nvoid foo(std::function<U(void)> func)\n{\n std::cout << \"on the move!\\n\";\n}\n\nint main()\n{\n foo<int>(std::function<int(void)>());\n foo<int>(std::function<std::vector<int>(void)>());\n //foo<int>(std::function<float(void)>()); //does not compile, in expectation.\n}\n"
},
{
"answer_id": 74555362,
"author": "Amro",
"author_id": 15749309,
"author_profile": "https://Stackoverflow.com/users/15749309",
"pm_score": 2,
"selected": false,
"text": "// Generic function\n// UPDATE: you can ignore this function altogether and use the two overloads below\ntemplate<typename T, typename U> std::vector<T> foo(T t, U u) { // Do something}\n\n// First specialization for the case of U == T\n// UPDATE: this is an *overload*, not a specialization\ntemplate<typename T> std::vector<T> foo(T t, T u) { // Do something}\n\n// Second specialization for the case of U == std::vector<T>\n// UPDATE: this is an *overload*, not a specialization\ntemplate<typename T> std::vector<T> foo(T t, std::vector<T> u) { // Do something}\n"
},
{
"answer_id": 74564206,
"author": "Marek R",
"author_id": 1387438,
"author_profile": "https://Stackoverflow.com/users/1387438",
"pm_score": 0,
"selected": false,
"text": "namespace me {\n // c++20 has this, so putting that in own namespace to cover older standards\n template<typename T>\n strut identity {\n using type = T;\n };\n\n template<typename T>\n using identity_t = typename identityT<>::type;\n}\n\n\ntemplate<typename T>\nstd::vector<T> foo(T t, const std::vector<me::indentity_t<T>>& v) {\n auto copy = v;\n copy.push_back(t);\n return copy;\n}\n\ntemplate<typename T>\nstd::vector<T> foo(T t, me::indentity_t<T> v) {\n return { v, t };\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19321677/"
] |
74,555,149
|
<p>I have two nested array of objects, how to compare two array of objects by</p>
<p><code>id</code> from arrobj1 and <code>assignId</code> from arrobj2 using javascript</p>
<p>So, I would to know how to compare array of objects by id and assignId and return array of objects using javascript</p>
<pre><code>
Tried
const result = arrobj1.filter(arr1 => {
arrobj2.find(arr2 => arr2.assignId === arr1.id)
});
var arrobj1 =[
{id: 1, name: 'xxx', value:100},
{id: 2, name: 'yyy', value:200},
{id: 3, name: 'zzz', value:400}
]
var arrobj2 =[
{country: 'IN', name: 'lina', assignId:2},
{country: 'MY', name: 'john', assignId:3},
{country: 'SG', name: 'peter', assignId:6}
]
</code></pre>
<pre><code>Expected Code:
[
{id: 2, name: 'yyy', value:200},
{id: 3, name: 'zzz', value:400}
]
</code></pre>
|
[
{
"answer_id": 74555166,
"author": "Zac Anger",
"author_id": 5774952,
"author_profile": "https://Stackoverflow.com/users/5774952",
"pm_score": 1,
"selected": false,
"text": "return const result = arrobj1.filter(arr1 =>\n arrobj2.find(arr2 => arr2.assignId === arr1.id)\n)\n// or\nconst result = arrobj1.filter(arr1 => {\n return arrobj2.find(arr2 => arr2.assignId === arr1.id)\n})\n"
},
{
"answer_id": 74555167,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 0,
"selected": false,
"text": "Array.filter() Array.some() let result = arrobj1.filter(a1 => arrobj2.some(a2 => a2.assignId === a1.id) )\nconsole.log(result)\n return find var arrobj1 =[\n {id: 1, name: 'xxx', value:100},\n {id: 2, name: 'yyy', value:200},\n {id: 3, name: 'zzz', value:400}\n]\n\nvar arrobj2 =[\n {country: 'IN', name: 'lina', assignId:2},\n {country: 'MY', name: 'john', assignId:3},\n {country: 'SG', name: 'peter', assignId:6}\n]\n\nlet result = arrobj1.filter(a1 => arrobj2.some(a2 => a2.assignId === a1.id) )\nconsole.log(result)"
},
{
"answer_id": 74555207,
"author": "Mr.Online",
"author_id": 11383650,
"author_profile": "https://Stackoverflow.com/users/11383650",
"pm_score": 0,
"selected": false,
"text": "filter some some var arrobj1 = [\n { id: 1, name: 'xxx', value: 100 },\n { id: 2, name: 'yyy', value: 200 },\n { id: 3, name: 'zzz', value: 400 },\n]\n\nvar arrobj2 = [\n { country: 'IN', name: 'lina', assignId: 2 },\n { country: 'MY', name: 'john', assignId: 3 },\n { country: 'SG', name: 'peter', assignId: 6 },\n]\n\nvar obj = {}\nfor (const elem of arrobj2) {\n obj[elem.assignId] = true\n}\n\nlet result = arrobj1.filter((a1) => obj[a1.id])\nconsole.log(result)"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18567253/"
] |
74,555,158
|
<p>I'm trying to check if user input is one of the letters in the chosen word by the CPU. Let me know if this is not possible the way I'm trying to do it, thanks.</p>
<pre class="lang-py prettyprint-override"><code>import random
test_list = [ 'yes', 'no']
# guessing list
print("Original list is : " + str(test_list))
cpu_choice =[]
cpu_choice=("Random element is :", random.sample(test_list, 1))
print(cpu_choice)
# i know it gives the answer i'm just using this to test and get the program to work
userinput = input('guess a letter ')
for letter in userinput:
if letter in userinput == letter in cpu_choice:
print('correct')
elif print:
print('wrong')
</code></pre>
|
[
{
"answer_id": 74555224,
"author": "Dash",
"author_id": 11542834,
"author_profile": "https://Stackoverflow.com/users/11542834",
"pm_score": 0,
"selected": false,
"text": "letter in userinput userinput letter if letter in cpu_choice:"
},
{
"answer_id": 74555273,
"author": "Metahuman Flash",
"author_id": 14694240,
"author_profile": "https://Stackoverflow.com/users/14694240",
"pm_score": 2,
"selected": true,
"text": "userinput = input('guess a letter: ')[0]\nmatch = False\nfor letter in cpu_choice[1][0]:\n if letter == userinput:\n match = True\n break\nif match:\n print('correct')\nelse:\n print('wrong')\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20150432/"
] |
74,555,171
|
<p>Suppose I have a class called <code>Circuit</code>, and a dictionary containing data about each circuit component:</p>
<pre class="lang-py prettyprint-override"><code>components = {
'V1': [ ... ],
'L1': [ ... ],
'R1': [ ... ],
'R2': [ ... ],
...
}
</code></pre>
<p>I want to define child objects <code>Circuit.V1</code>, <code>Circuit.L1</code>, and so on.</p>
<p>The crux of the problem is that I have strings ("V1", "L1", ...) that need to be converted into identifiers. The necessary identifiers would be different depending on what data is passed to the constructor of <code>Circuit</code>, so I can't just hard-code them.</p>
<p>Is this possible, and if so, how do I do this?</p>
<p>I haven't been able to find any information on this (searching just brings up basic info on valid identifier names and such). I have found <a href="https://stackoverflow.com/questions/22926385/how-to-convert-a-string-into-an-identifier-in-python">this page</a> but the question was never directly answered.</p>
<p>Right now I can access my circuit component object like <code>Circuit.components['V1']</code>, but that seems a little clunky and I would prefer <code>Circuit.V1</code>.</p>
<p>Edit: The term for the thing I was trying to do is <em>dynamic attribute assignment</em>. Adding this so that others like me who didn't know what keywords to search for can more easily find information.</p>
|
[
{
"answer_id": 74555241,
"author": "ishao",
"author_id": 18925629,
"author_profile": "https://Stackoverflow.com/users/18925629",
"pm_score": 0,
"selected": false,
"text": "class Component:\n V1 = 0\n ... \n\nCircuit = Component() \nCircuit.V1 = 2\n"
},
{
"answer_id": 74555253,
"author": "Juan E.",
"author_id": 11743292,
"author_profile": "https://Stackoverflow.com/users/11743292",
"pm_score": 3,
"selected": true,
"text": "__setattr__ class C:\n ...\n\nc = C()\n\nc.__setattr__(\"V1\", 1)\n\nprint(\"c.V1 = \", c.V1) # c.V1 = 1\n\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14095457/"
] |
74,555,185
|
<p>I have some data that I would like to split into <strong>four groups</strong> based upon particular points in time - the points in time being given by particular dates.</p>
<p>The data I have is this (assume that <code>df</code> has already been created):</p>
<pre><code>df["date"] = pd.to_datetime(df["date"], format = "%Y-%m-%d")
df["year"] = df["date"].dt.year
df["month"] = df["date"].dt.month
df.groupby(by = "year", as_index = False).agg({"month":pd.Series.nunique})
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>year</th>
<th>month</th>
</tr>
</thead>
<tbody>
<tr>
<td>2015</td>
<td>3</td>
</tr>
<tr>
<td>2016</td>
<td>12</td>
</tr>
<tr>
<td>2017</td>
<td>12</td>
</tr>
<tr>
<td>2018</td>
<td>12</td>
</tr>
<tr>
<td>2019</td>
<td>12</td>
</tr>
<tr>
<td>2020</td>
<td>12</td>
</tr>
<tr>
<td>2021</td>
<td>12</td>
</tr>
<tr>
<td>2022</td>
<td>9</td>
</tr>
</tbody>
</table>
</div>
<p>Notice that with this data, 2015 and 2022 are not full years.</p>
<p>My thinking was that because I have 84 months worth of data in total <code>(3 + (6*12) + 9 = 84)</code>, I could split the data into four groups so that each group would have approximately 21 months worth of data in total <code>84 / 4 = 21</code>.</p>
<p>To do this, I would first begin with the earliest date in my data set which is <code>2015-10-02</code>. With this earliest data I would add on 21 months:</p>
<pre><code>from dateutil.relativedelta import relativedelta
min_date = df["date"].min().date()
print([min_date, min_date + relativedelta(months = 21)]
#output
[datetime.date(2015, 10, 2), datetime.date(2017, 7, 2)]
</code></pre>
<p>This date range would constitute the first <em>bin</em> which the first group would fall into</p>
<p>The second group would fall into a date range where the minimum date would be <em>one day more</em> than the maximum date of the previous group's date range:</p>
<pre><code>"2017-07-02" + relativedelta(days = 1) = "2017-07-03"
</code></pre>
<p>This would ensure that the bins of the different groups do not overlap.</p>
<p>The last group would have a bit less data in it as it would include data up till the latest date in the entire dataset which is <code>2022-09-30</code></p>
<p>Overall, the date range bins for the different groups would look something like this</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Group</th>
<th>Date Range</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>"2015-10-02", "2017-07-02"</td>
</tr>
<tr>
<td>B</td>
<td>"2017-07-03", "2019-04-03"</td>
</tr>
<tr>
<td>C</td>
<td>"2019-04-04", "2021-01-04"</td>
</tr>
<tr>
<td>D</td>
<td>"2021-01-05", "2022-9-30"</td>
</tr>
</tbody>
</table>
</div>
<p>I know that I could find these date ranges manually and use them to filter the data set to produce the groups with <code>np.select</code> but this isn't very efficient.</p>
<pre><code>df["Group"] = np.select(
condlist = [
(df["date"] >= "2015-10-02") & (df["date"] <= "2017-07-02"),
(df["date"] >= "2017-07-03") & (df["date"] <= "2019-04-03"),
(df["date"] >= "2019-04-04") & (df["date"] <= "2021-01-04"),
(df["date"] >= "2021-01-05") & (df["date"] <= "2022-09-30")
],
choicelist = ["A", "B", "C", "D"]
)
</code></pre>
<p>Surely there must be a way to find these values (in the way that I want them) without having to find them manually</p>
|
[
{
"answer_id": 74561736,
"author": "Vini",
"author_id": 6927944,
"author_profile": "https://Stackoverflow.com/users/6927944",
"pm_score": 2,
"selected": false,
"text": "pd.cut # toy data\ndf = pd.DataFrame(pd.date_range('2020-01-01', '2022-01-01'), columns = ['date'])\n\n date\n0 2020-01-01\n1 2020-01-02\n2 2020-01-03\n3 2020-01-04\n4 2020-01-05\n.. ...\n from numpy import datetime64\nbin_labels = [1, 2, 3, 4]\ncut_bins = [datetime64('2019-12-31'), datetime64('2020-04-01'), datetime64('2020-12-31'), datetime64('2021-09-01'), datetime64('2022-01-01')]\n df['cut'] = pd.cut(df['date'], bins = cut_bins, labels = bin_labels]\n\n date cut\n0 2020-01-01 1\n1 2020-01-02 1\n2 2020-01-03 1\n3 2020-01-04 1\n4 2020-01-05 1\n.. ... ..\n727 2021-12-28 4\n728 2021-12-29 4\n729 2021-12-30 4\n730 2021-12-31 4\n731 2022-01-01 4\n"
},
{
"answer_id": 74569769,
"author": "JoMcGee",
"author_id": 18937753,
"author_profile": "https://Stackoverflow.com/users/18937753",
"pm_score": 0,
"selected": false,
"text": "from dateutil.relativedelta import relativedelta\nimport numpy as np\n\ndates = []\nstart = df[\"date\"].min().date()\ndates.append(np.datetime64(start))\nwhile start <= df[\"date\"].max().date():\n start = start + relativedetla(months = 21)\n dates.append(np.datetime64(start))\n\ndf[\"Group\"] = pd.cut(\n df[\"date\"], bins = dates,\n labels = [\"A\", \"B\", \"C\", \"D\"],\n right = False #right = False ensures no group overlap in date values\n)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18937753/"
] |
74,555,218
|
<p>This is my code:</p>
<pre><code>render() {
return (
<div className='btndiv'>
<button className='btn'>Hide</button>
</div>
);
}
</code></pre>
<p>When I click the button I want the class of the div to change from .btn.div to .btn divhidden, which basically dissapears it from screen.</p>
<pre><code>.btndivhidden{
display: none
}
</code></pre>
<p>I have watched multiple solutions but many of them are too complicated and put way too much code. How can I achieve this the most efficient and short way?</p>
|
[
{
"answer_id": 74555248,
"author": "rb612",
"author_id": 3813411,
"author_profile": "https://Stackoverflow.com/users/3813411",
"pm_score": 2,
"selected": false,
"text": "export default function App() {\n const [isVisible, setIsVisible] = useState(true);\n\n const handleClick = () => setIsVisible(false);\n\n return (\n <div className={isVisible ? 'btndiv' : 'btndivhidden'}>\n <button className='btn' onClick={handleClick}>\n Hide\n </button>\n </div>\n );\n}\n"
},
{
"answer_id": 74555391,
"author": "Drystan",
"author_id": 20182014,
"author_profile": "https://Stackoverflow.com/users/20182014",
"pm_score": 0,
"selected": false,
"text": "const hideClass = () => {\n const elem = document.querySelector(\".btndiv\");\n elem.classList.replace(\"btndiv\", \"btndivhidden\");\n};\nexport default function App() {\n return (\n <div className=\"App\">\n <div className=\"btndiv\">\n <button className=\"btn\" onClick={() => hideClass()}>\n Hide\n </button>\n </div>\n </div>\n );\n}\n"
},
{
"answer_id": 74555991,
"author": "Thaiyalnayaki",
"author_id": 15431167,
"author_profile": "https://Stackoverflow.com/users/15431167",
"pm_score": 0,
"selected": false,
"text": "import React, { useState } from \"react\";\n\nexport default function App() {\n const [isChange, setIsChange] = useState(true);\n\n const handleChange = () => setIsChange(!isChange);\n\n return (\n <div className={isChange ? \"btndiv\" : \"btndivhidden\"}>\n <button className=\"btn\" onClick={handleChange}>\n Hide\n </button>\n </div>\n );\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19273829/"
] |
74,555,254
|
<p>I currently have a single page in my React app that renders all the components on one page. I would like to have a button open a new component that takes up the whole page, almost like opening a new site.</p>
<p>Is there a way I could do this? Below is my code.</p>
<p><strong>App.js:</strong></p>
<pre><code>import { Route, Routes } from 'react-router-dom';
import './App.css';
import Navbar from './components/Navbar';
import Homepage from './components/Homepage';
import About from './components/About';
import Skills from './components/Skills';
import Projects from './components/Projects';
import ContactMe from './components/ContactMe';
import Contact from './components/Contact';
function App() {
return (
<>
<Navbar />
<div className='homepage-container-web'>
<Homepage />
<About />
<Skills />
<Projects />
<ContactMe />
</div>
<div className='homepage-container-devices'>
<Routes>
<Route path='/' element={<Homepage />} />
<Route path='/about' element={<About />}/>
<Route path='/projects' element={<Projects />}/>
<Route path='/contact' element={<ContactMe />}/>
</Routes>
</div>
</>
);
}
export default App;
</code></pre>
<p><strong>ContactMe.jsx:</strong></p>
<pre><code>import '../App.css';
import { ReactComponent as LinkedInLogo } from '../images/linkedin.svg';
function ContactMe() {
return(
<>
<div className='contact-container' id='contactMe'>
<div className='contact-box'>
<h1>Want to connect?</h1>
<button id='contact-me-btn'>Contact Me </button>
<a>
<LinkedInLogo title='LinkedIn Profile' id='linkedinprofile-svg'/>
</a>
</div>
<div className='contact-container-footer'>
<h7>Designed and built by <a href='https://github.com/BlazingIsFire' target='_blank' title='Github'>Placeholder</a>.</h7>
</div>
</div>
</>
)
}
export default ContactMe;
</code></pre>
<p>I would like the <code><button>Contact me!</button</code> in <strong>ContactMe.jsx</strong> to open a new component / page that's named <code><Contact /></code>. I want the Contact page to take up the entire page.</p>
<p>Any help is appreciated!!</p>
|
[
{
"answer_id": 74555467,
"author": "Ali Nauman",
"author_id": 9917250,
"author_profile": "https://Stackoverflow.com/users/9917250",
"pm_score": 0,
"selected": false,
"text": "Router react-router-dom App function App() {\n\n return (\n // Add an import for this\n <BrowserRouter>\n <Navbar />\n <div className='homepage-container-web'>\n <Routes>\n <Route path='/' element={<Homepage />} />\n <Route path='/about' element={<About />}/>\n <Route path='/projects' element={<Projects />}/>\n <Route path='/contact-me' element={<ContactMe />}/>\n // This was missing\n <Route path='/contact' element={<Contact />}/>\n </Routes>\n </div>\n </BrowserRouter>\n );\n}\n element Route /about About /projects Projects Contact function ContactMe() {\n // Use useNavigate hook\n const navigate = useNavigate();\n\n return (\n <div className=\"contact-container\" id=\"contactMe\">\n <div className=\"contact-box\">\n <h1>Want to connect?</h1>\n // Navigate to /contact-me on click\n <button id=\"contact-me-btn\" onClick={() => navigate(\"/contact-me\")}>\n Contact Me{\" \"}\n </button>\n <a>\n <LinkedInLogo title=\"LinkedIn Profile\" id=\"linkedinprofile-svg\" />\n </a>\n </div>\n <div className=\"contact-container-footer\">\n <h7>\n Designed and built by{\" \"}\n <a\n href=\"https://github.com/BlazingIsFire\"\n target=\"_blank\"\n title=\"Github\"\n >\n Andrew Schweitzer\n </a>\n .\n </h7>\n </div>\n </div>\n );\n}\n\n"
},
{
"answer_id": 74555659,
"author": "DoGzTheFiGhTeR",
"author_id": 17655556,
"author_profile": "https://Stackoverflow.com/users/17655556",
"pm_score": 1,
"selected": false,
"text": "\n import ReactDOM from \"react-dom/client\";\n import { BrowserRouter, Routes, Route } from \"react-router-dom\";\n import Layout from \"./Layout\";\n import Home from \"./Home\";\n import About from \"./About\";\n import Contact from \"./Contact\";\n import Connect from \"./Connect\";\n import Error from \"./Error\";\n \n export default function App() {\n return (\n <BrowserRouter>\n <Routes>\n <Route path=\"/\" element={<Layout />}>\n <Route index element={<Home />} />\n <Route path=\"about\" element={<About />} />\n <Route path=\"contact\" element={<Contact />} />\n </Route>\n <Route path=\"/connect\" element={<Connect />} />\n <Route path=\"*\" element={<Error />} />\n </Routes>\n </BrowserRouter>\n );\n }\n \n const root = ReactDOM.createRoot(document.getElementById(\"root\"));\n root.render(<App />);\n\n \n import { Outlet, Link } from \"react-router-dom\";\n \n const Layout = () => {\n return (\n <>\n <nav>\n <ul>\n <li>\n <Link to=\"/\">Home</Link>\n </li>\n <li>\n <Link to=\"/about\">About</Link>\n </li>\n <li>\n <Link to=\"/contact\">Contact</Link>\n </li>\n </ul>\n </nav>\n <Outlet />\n </>\n );\n };\n \n export default Layout;\n\n \n const Home = () => {\n return <h1>Home</h1>;\n };\n \n export default Home;\n\n \n const About = () => {\n return <h1>About Page</h1>;\n };\n \n export default About;\n\n \n import { Link } from \"react-router-dom\";\n \n const Contact = () => {\n return (\n <div>\n <h1>Contact Me</h1>\n <Link to=\"/connect\">Try & Reach Me!</Link>\n </div>\n );\n };\n \n export default Contact;\n\n \n const Connect = () => {\n return <h1>Connected to me!</h1>;\n };\n \n export default Connect;\n\n \n import { Link } from \"react-router-dom\";\n \n const NoPage = () => {\n return (\n <div>\n <h1>404 No Page Found!</h1>\n <Link to=\"/\">Go Home</Link>\n </div>\n );\n };\n \n export default NoPage;\n\n"
},
{
"answer_id": 74555686,
"author": "Emilian Kasemi",
"author_id": 12637493,
"author_profile": "https://Stackoverflow.com/users/12637493",
"pm_score": 1,
"selected": true,
"text": " function ContactMe({contact}) {\n \n return(\n ................\n \n <a href={`/${contact}`}>\n <button id='contact-me-btn'>\n Click to redirect to {contact === '' ? \"home\" : contact}\n </button>\n </a>\n )\n }\n const navigate = useNavigate();\nnavigate(\"/nameofpage\");\n import { useNavigate } from \"react-router-dom\";\n\nfunction ContactMe({contact}) {\n\nconst navigate = useNavigate();\n \n return(\n ................\n \n \n <button className=\"my-button\" onClick={() => { navigate(`/${contact}`) }}>\n Click to redirect to {contact === '' ? \"home\" : contact}\n </button>\n \n )\n }\n <Link to=\"nameofpage\"> Element </Link>\n import { Link } from \"react-router-dom\";\n\nfunction ContactMe({contact}) {\n \n return(\n ................\n \n <Link to={`/${contact}`}>\n <button id='contact-me-btn'>\n Click to redirect to {contact === '' ? \"home\" : contact}\n </button>\n </Link>\n )\n }\n"
},
{
"answer_id": 74563030,
"author": "Blazing",
"author_id": 20422283,
"author_profile": "https://Stackoverflow.com/users/20422283",
"pm_score": 0,
"selected": false,
"text": "<Homepage /> <Navbar />\n <div className='homepage-container-web'>\n <Routes>\n <Route>\n <Route path='/' element={<Homepage />}/>\n </Route>\n <Route path='/contact' element={<Contact />}/>\n </Routes>\n </div>\n <div className='homepage-container-devices'>\n <Routes>\n <Route path='/' element={<Home />} />\n <Route path='/about' element={<About />}/>\n <Route path='/projects' element={<Projects />}/>\n <Route path='/contact' element={<ContactMe />}/>\n </Routes>\n </div>\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20422283/"
] |
74,555,272
|
<p>I'm creating a flashcard game to ask CompSci questions.</p>
<p>I'm trying to retrieve a random "CardFront" which acts as a varchar stored in an SQLite3 DB table, and output that result to a messagebox to "Prompt" the user with the question.</p>
<p>Only problem I can't seem to figure out is why it is returning with squiggly brackets around the statement?</p>
<pre class="lang-py prettyprint-override"><code>from tkinter import *
import sqlite3
from tkinter import messagebox
def retrieve_random_cardfront():
conn = sqlite3.connect('flashcards.db')
cursor = conn.cursor()
cursor.execute("SELECT CardFront FROM FLASHCARDS ORDER BY RANDOM() LIMIT 1;")
result = cursor.fetchall()
conn.close()
messagebox.showinfo(title='Test', message=result[0])
</code></pre>
<p><a href="https://i.stack.imgur.com/VPYqW.png" rel="nofollow noreferrer">Current Output</a></p>
|
[
{
"answer_id": 74555306,
"author": "Gwendal Delisle Arnold",
"author_id": 6327854,
"author_profile": "https://Stackoverflow.com/users/6327854",
"pm_score": -1,
"selected": true,
"text": "__repr__ from tkinter import *\nimport sqlite3\nfrom tkinter import messagebox\n\ndef retrieve_random_cardfront():\n conn = sqlite3.connect('flashcards.db')\n cursor = conn.cursor()\n cursor.execute(\"SELECT CardFront FROM FLASHCARDS ORDER BY RANDOM() LIMIT 1;\")\n result = cursor.fetchall()\n conn.close()\n messagebox.showinfo(title='Test', message=str(result[0]).strip('{').strip('}'))\n"
},
{
"answer_id": 74555352,
"author": "Dante Zulli",
"author_id": 19446091,
"author_profile": "https://Stackoverflow.com/users/19446091",
"pm_score": 0,
"selected": false,
"text": "data = \"{Data}\"\ndata = data.replace(data[0], \"\")\ndata = data.replace(data[-1], \"\")\nprint(data)\n"
},
{
"answer_id": 74583351,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 0,
"selected": false,
"text": "message = \",\".join(result[0])\nmessagebox.showinfo(title='Test', message=message)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20543836/"
] |
74,555,289
|
<p>This is my Entity Role class</p>
<pre><code>@Entity
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Role implements GrantedAuthority {
@Id
@GeneratedValue
private Integer id;
@Column()
private RoleName roleName;
@Override
public String getAuthority() {
return roleName.name();
}
}
</code></pre>
<p>And this is my RoleName class</p>
<pre><code>
public enum RoleName {
ROLE_USER,
ROLE_ADMIN,
ROLE_DIRECTOR
}
</code></pre>
<p>If I look at the database I see that type of role_name column is integer????
And when I'm writhing a query</p>
<pre><code>insert into role(id, role_name)
values(1, 'ROLE_USER'),
(2, 'ROLE_ADMIN'),
(3, 'ROLE_DIRECTOR');
</code></pre>
<p>it's giving me error message "invalid syntax for type integer: "ROLE_USER"
Can you help me how I can solve this issue and why role_name column is an integer when I give its type enum
This is an error message</p>
<pre><code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file:/C:/Users/dadab/IdeaProjects/app-email-auditing/target/classes/data.sql]: insert into role(id, role_name) values(1, 'ROLE_USER'), (2, 'ROLE_ADMIN'), (3, 'ROLE_DIRECTOR'); nested exception is org.postgresql.util.PSQLException: ОШИБКА: неверный синтаксис для типа integer: "ROLE_USER"
Позиция: 43
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.23.jar:5.3.23]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.23.jar:5.3.23]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.23.jar:5.3.23]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.5.jar:2.7.5]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) ~[spring-boot-2.7.5.jar:2.7.5]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.5.jar:2.7.5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-2.7.5.jar:2.7.5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.5.jar:2.7.5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.5.jar:2.7.5]
at com.example.appemailauditing.AppEmailAuditingApplication.main(AppEmailAuditingApplication.java:10) ~[classes/:na]
Caused by: org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file:/C:/Users/dadab/IdeaProjects/app-email-auditing/target/classes/data.sql]: insert into role(id, role_name) values(1, 'ROLE_USER'), (2, 'ROLE_ADMIN'), (3, 'ROLE_DIRECTOR'); nested exception is org.postgresql.util.PSQLException: ОШИБКА: неверный синтаксис для типа integer: "ROLE_USER"
Позиция: 43
at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:282) ~[spring-jdbc-5.3.23.jar:5.3.23]
at org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.populate(ResourceDatabasePopulator.java:254) ~[spring-jdbc-5.3.23.jar:5.3.23]
at org.springframework.jdbc.datasource.init.DatabasePopulatorUtils.execute(DatabasePopulatorUtils.java:54) ~[spring-jdbc-5.3.23.jar:5.3.23]
at org.springframework.boot.jdbc.init.DataSourceScriptDatabaseInitializer.runScripts(DataSourceScriptDatabaseInitializer.java:90) ~[spring-boot-2.7.5.jar:2.7.5]
at org.springframework.boot.sql.init.AbstractScriptDatabaseInitializer.runScripts(AbstractScriptDatabaseInitializer.java:145) ~[spring-boot-2.7.5.jar:2.7.5]
at org.springframework.boot.sql.init.AbstractScriptDatabaseInitializer.applyScripts(AbstractScriptDatabaseInitializer.java:107) ~[spring-boot-2.7.5.jar:2.7.5]
at org.springframework.boot.sql.init.AbstractScriptDatabaseInitializer.applyDataScripts(AbstractScriptDatabaseInitializer.java:101) ~[spring-boot-2.7.5.jar:2.7.5]
at org.springframework.boot.sql.init.AbstractScriptDatabaseInitializer.initializeDatabase(AbstractScriptDatabaseInitializer.java:76) ~[spring-boot-2.7.5.jar:2.7.5]
at org.springframework.boot.sql.init.AbstractScriptDatabaseInitializer.afterPropertiesSet(AbstractScriptDatabaseInitializer.java:65) ~[spring-boot-2.7.5.jar:2.7.5]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.23.jar:5.3.23]
... 18 common frames omitted
Caused by: org.postgresql.util.PSQLException: ОШИБКА: неверный синтаксис для типа integer: "ROLE_USER"
Позиция: 43
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2675) ~[postgresql-42.3.7.jar:42.3.7]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2365) ~[postgresql-42.3.7.jar:42.3.7]
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:355) ~[postgresql-42.3.7.jar:42.3.7]
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:490) ~[postgresql-42.3.7.jar:42.3.7]
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:408) ~[postgresql-42.3.7.jar:42.3.7]
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:329) ~[postgresql-42.3.7.jar:42.3.7]
at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:315) ~[postgresql-42.3.7.jar:42.3.7]
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:291) ~[postgresql-42.3.7.jar:42.3.7]
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:286) ~[postgresql-42.3.7.jar:42.3.7]
at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:94) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-4.0.3.jar:na]
at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:261) ~[spring-jdbc-5.3.23.jar:5.3.23]
... 28 common frames omitted
</code></pre>
<p>I have tried giving query with double quote</p>
<pre><code>insert into role(id, role_name)
values(1, "ROLE_USER"),
(2, "ROLE_ADMIN"),
(3, "ROLE_DIRECTOR");
</code></pre>
<p>but it gave another error message " column 'ROLE_USER' does not exist "</p>
<p>I'm expectiong a reson why role_name is integer and how to give a column typa an enum</p>
|
[
{
"answer_id": 74555306,
"author": "Gwendal Delisle Arnold",
"author_id": 6327854,
"author_profile": "https://Stackoverflow.com/users/6327854",
"pm_score": -1,
"selected": true,
"text": "__repr__ from tkinter import *\nimport sqlite3\nfrom tkinter import messagebox\n\ndef retrieve_random_cardfront():\n conn = sqlite3.connect('flashcards.db')\n cursor = conn.cursor()\n cursor.execute(\"SELECT CardFront FROM FLASHCARDS ORDER BY RANDOM() LIMIT 1;\")\n result = cursor.fetchall()\n conn.close()\n messagebox.showinfo(title='Test', message=str(result[0]).strip('{').strip('}'))\n"
},
{
"answer_id": 74555352,
"author": "Dante Zulli",
"author_id": 19446091,
"author_profile": "https://Stackoverflow.com/users/19446091",
"pm_score": 0,
"selected": false,
"text": "data = \"{Data}\"\ndata = data.replace(data[0], \"\")\ndata = data.replace(data[-1], \"\")\nprint(data)\n"
},
{
"answer_id": 74583351,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 0,
"selected": false,
"text": "message = \",\".join(result[0])\nmessagebox.showinfo(title='Test', message=message)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18736248/"
] |
74,555,314
|
<p>How can I average a matrix every 24 values? And how can I find the maximum and minimum value for every 24 numbers and compute the maximum minus the minimum?</p>
<pre><code>data <- as.matrix(rnorm(240,8,6))
</code></pre>
|
[
{
"answer_id": 74555436,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 1,
"selected": false,
"text": "set.seed(13)\n\ndata2 <- matrix(data, nrow = 24)\n\ncolMeans(data2)\n# [1] 9.253395 5.994996 8.587498 6.640410 8.450113 7.471933 6.778594 9.770789\n# [9] 7.990745 6.155887\n\napply(data2, MARGIN = 2, \\(x) max(x) - min(x))\n# [1] 22.15314 21.84914 16.47159 22.45381 19.81069 22.68133 31.14436 29.72932\n# [9] 21.05972 20.37183\n"
},
{
"answer_id": 74555444,
"author": "Josh White",
"author_id": 20289207,
"author_profile": "https://Stackoverflow.com/users/20289207",
"pm_score": 0,
"selected": false,
"text": "data <- rnorm(240,8,6), nrow = 24)\ncolMeans(data) # means\n [1] 7.277130 9.168225 9.035287 8.199072 8.586223 6.943131 7.789378 6.325451 8.592744 8.048652\n\n apply(data, 2, function(x) range(x)[2] - range(x)[1]) #range\n [1] 20.05621 22.18245 18.00119 22.14814 23.38163 22.66280 31.46512 20.08090 25.93418 17.03183\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17418925/"
] |
74,555,343
|
<p>I am using Azure Data Factory script to create parameterized SQL query. I understand that the Index specifies the position in which the parameter's value should go in the SQL command. However, I don't know how to handle the situation where pipeline().parameters are used multiple times in the SQL query. In my example below, the RUN_DATE parameter is used twice. When I simply add the same parameters multiple times, it will show "Parameters with duplicate name will be overwritten." Any idea how to solve this?</p>
<p>Here is the query:</p>
<pre><code>@concat('
UPDATE s
SET INSERT_DATE = ''', pipeline().parameters.RUN_DATE,'''',
',UPDATE_DATE = ''', pipeline().parameters.RUN_DATE,'''',
'FROM p
WHERE p.ID = s.ID
AND s.ID = ''', pipeline().parameters.ID,'''',
';')
</code></pre>
<p>See the screenshot:
<a href="https://i.stack.imgur.com/diSSv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/diSSv.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74555436,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 1,
"selected": false,
"text": "set.seed(13)\n\ndata2 <- matrix(data, nrow = 24)\n\ncolMeans(data2)\n# [1] 9.253395 5.994996 8.587498 6.640410 8.450113 7.471933 6.778594 9.770789\n# [9] 7.990745 6.155887\n\napply(data2, MARGIN = 2, \\(x) max(x) - min(x))\n# [1] 22.15314 21.84914 16.47159 22.45381 19.81069 22.68133 31.14436 29.72932\n# [9] 21.05972 20.37183\n"
},
{
"answer_id": 74555444,
"author": "Josh White",
"author_id": 20289207,
"author_profile": "https://Stackoverflow.com/users/20289207",
"pm_score": 0,
"selected": false,
"text": "data <- rnorm(240,8,6), nrow = 24)\ncolMeans(data) # means\n [1] 7.277130 9.168225 9.035287 8.199072 8.586223 6.943131 7.789378 6.325451 8.592744 8.048652\n\n apply(data, 2, function(x) range(x)[2] - range(x)[1]) #range\n [1] 20.05621 22.18245 18.00119 22.14814 23.38163 22.66280 31.46512 20.08090 25.93418 17.03183\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7586562/"
] |
74,555,353
|
<p>Why is the label not showing while using datalist in html if anyone have any idea of why this is not running then please help me..</p>
<p>i tried the same code in another new file then it worked perfectly but when run in this it won't show the label.
p.s. i am using brave browser but it won't show in other browsers too..</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" >
<meta http-equiv="X-UA-Compatible" content="IE=edge" >
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<title>forms</title>
<link rel="stylesheet" href="form.css" >
</head>
<body>
<div id="backgnd">
<div class="image">
<img src="https://images-platform.99static.com//1qWC_KuhJeSkGLZV6M7fC3g5Xb4=/113x113:848x848/fit-in/500x500/99designs-contests-attachments/81/81740/attachment_81740257" alt="burger's logo">
</div>
<form action="/button.html">
<h1>Enter your Credentials</h1>
<p>
A perfect place to order your favoriate burgers..reach us or order online
</p>
<label for="number">number of burgers to be ordered</label>
<br>
<input type="number" name="no_user" id="number" step="1">
<br><br>
<label for="spiciness">
<ins>Level of your Spiciness</ins>
</label>
<br><br>
<span>not spicy</span>
<input type="range" name="spicy" id="spiciness" max="10" min="0" step="0.01">
<span>really spicy</span>
<br><br>
<section class="topping">
<ins>select the topping you would like</ins><br><br>
<input type="checkbox" name="topping" value="lettuce" id="lettuce">
<label for="lettuce">lettuce</label>
<input type="checkbox" name="topping" value="tomato" id="tomato">
<label for="tomato">tomato</label>
<input type="checkbox" name="topping" value="Onion" id="Onion">
<label for="Onion">Onion</label>
</section><br><br>
<section class="Answer">
<strong>what type of burger would you like to have</strong> <br><br>
<input type="radio" name="answer" id="veg">
<label for="veg">Veg</label>
<input type="radio" name="answer" id="Non-veg">
<label for="Non-veg">Non-veg</label>
</section><br><br>
<section class="Burger_type">
<label for="Burger">
<strong>What kind of burger would you like to have?</strong>
</label><br>
<select name="burger" id="Burger">
<option value="veggie-burgers">Veggie Burgers</option>
<option value="beef-burgers">Beef Burgers</option>
<option value="portobello_mushroom-burgers">Portobello Mushroom Burgers</option>
<option value="black_bean-burgers">Black Bean Burgers</option>
</select>
</section><br><br>
<section class="sauce">
<label for="sauce">
<!------------------------ label not showing------------------->
<strong>What type of sauce would you like?</strong>
</label><br>
<input type="text" list="sauces" id="sauce" name="sauce">
<datalist id="sauces">
<option value="ketchup">Ketchup</option>
<option value="mayo">Mayo</option>
<option value="yoghurt">Yoghurt</option>
</datalist>
</section>
</form>
</div>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 74555436,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 1,
"selected": false,
"text": "set.seed(13)\n\ndata2 <- matrix(data, nrow = 24)\n\ncolMeans(data2)\n# [1] 9.253395 5.994996 8.587498 6.640410 8.450113 7.471933 6.778594 9.770789\n# [9] 7.990745 6.155887\n\napply(data2, MARGIN = 2, \\(x) max(x) - min(x))\n# [1] 22.15314 21.84914 16.47159 22.45381 19.81069 22.68133 31.14436 29.72932\n# [9] 21.05972 20.37183\n"
},
{
"answer_id": 74555444,
"author": "Josh White",
"author_id": 20289207,
"author_profile": "https://Stackoverflow.com/users/20289207",
"pm_score": 0,
"selected": false,
"text": "data <- rnorm(240,8,6), nrow = 24)\ncolMeans(data) # means\n [1] 7.277130 9.168225 9.035287 8.199072 8.586223 6.943131 7.789378 6.325451 8.592744 8.048652\n\n apply(data, 2, function(x) range(x)[2] - range(x)[1]) #range\n [1] 20.05621 22.18245 18.00119 22.14814 23.38163 22.66280 31.46512 20.08090 25.93418 17.03183\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20314680/"
] |
74,555,443
|
<p>I have two data frames that I want to merge on a same column name but the values can have different variations of a values.</p>
<p>Examples. Variations of a value :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Variations</th>
</tr>
</thead>
<tbody>
<tr>
<td>USA</td>
</tr>
<tr>
<td>US</td>
</tr>
<tr>
<td>United States</td>
</tr>
<tr>
<td>United States of America</td>
</tr>
<tr>
<td>The United States of America</td>
</tr>
</tbody>
</table>
</div>
<p>And let's suppose the data frames as below:
df1 =</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>country</th>
<th>column B</th>
</tr>
</thead>
<tbody>
<tr>
<td>India</td>
<td>Cell 2</td>
</tr>
<tr>
<td>China</td>
<td>Cell 4</td>
</tr>
<tr>
<td>United States</td>
<td>Cell 2</td>
</tr>
<tr>
<td>UK</td>
<td>Cell 4</td>
</tr>
</tbody>
</table>
</div>
<p>df2 =</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Country</th>
<th>clm</th>
</tr>
</thead>
<tbody>
<tr>
<td>USA</td>
<td>val1</td>
</tr>
<tr>
<td>CH</td>
<td>val2</td>
</tr>
<tr>
<td>IN</td>
<td>val3</td>
</tr>
</tbody>
</table>
</div>
<p>Now how do I merge such that the United States is merged with USA?</p>
<p>I have tried DataFrame merge but it merges only on the matched values of the column name.</p>
<p>Is there a way to match the variations and merge the dataframes?</p>
|
[
{
"answer_id": 74555959,
"author": "PTQuoc",
"author_id": 11850322,
"author_profile": "https://Stackoverflow.com/users/11850322",
"pm_score": 1,
"selected": false,
"text": "reftable df = pd.DataFrame({'name':['USA', 'US', 'United States', 'FR', 'France'],\n 'val':[1,2,3,4,5]})\ndf\n\n name val\n0 USA 1\n1 US 2\n2 United States 3\n3 FR 4\n4 France 5\n reftable = pd.DataFrame({'name':['United States', 'US', 'USA', 'United States of America', 'The United States of America', 'France', 'FR', 'Frank'],\n 'uniqname':['us']*5+['fr']*3})\nreftable\n name uniqname\n0 United States us\n1 US us\n2 USA us\n3 United States of America us\n4 The United States of America us\n5 France fr\n6 FR fr\n7 Frank fr\n new = pd.merge(df, reftable, on='name', how='left')\nnew\n\n name val uniqname\n0 USA 1 us\n1 US 2 us\n2 United States 3 us\n3 FR 4 fr\n4 France 5 fr\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20587008/"
] |
74,555,451
|
<p>I'm looking at the <a href="https://docs.uniswap.org/concepts/protocol/oracle#tick-accumulator" rel="nofollow noreferrer">uniswap docs</a> which states this example:</p>
<blockquote>
<p>An example of finding the price of WETH in a WETH / USDC pool, where
WETH is token0 and USDC is token1:</p>
<p>You have an oracle reading that shows a return of tickCumulative as
[70_000, 1_070_000], with an elapsed time between the observations of
10 seconds.</p>
<p>We can derive the average tick over this interval by taking the
difference in accumulator values (1_070_000 - 70_000 = 1_000_000), and
dividing by the time elapsed (1_000_000 / 10 = 100_000).</p>
<p>With a tick reading of 100_000, we can find the value of token1 (USDC)
in terms of token0 (WETH) by using the current tick as i in the
formula p(i) = 1.0001**i (see 6.1 in the whitepaper).</p>
<p>1.0001**100_000 ≅ 22015.5 USDC / WETH</p>
</blockquote>
<p>The price of WETH is not $22015.50. I though maybe they just use an example with easy numbers. So I decided to try the example from the <a href="https://uniswap.org/whitepaper-v3.pdf" rel="nofollow noreferrer">whitepaper</a> on the <a href="https://polygonscan.com/address/0x45dda9cb7c25131df268515131f647d726f50608#readContract" rel="nofollow noreferrer">USDC/WETH pool</a></p>
<p><a href="https://i.stack.imgur.com/SOHgE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SOHgE.png" alt="enter image description here" /></a></p>
<p>Calling <code>slot0</code> on the contract returns:</p>
<p><a href="https://i.stack.imgur.com/W2Hes.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/W2Hes.png" alt="enter image description here" /></a></p>
<p>Making the price</p>
<blockquote>
<p>1.0001 ** 205930 = 876958666.4726943</p>
</blockquote>
<p>Clearly the price for ETH is not 876958666 USDC. The current tick is 205930, but the price for ETH is just 1200.49 USDC. How do I get the correct USDC price of ETH from the tick?</p>
|
[
{
"answer_id": 74555612,
"author": "Yilmaz",
"author_id": 10262805,
"author_profile": "https://Stackoverflow.com/users/10262805",
"pm_score": 1,
"selected": false,
"text": "TIME WEIGHTED AVERAGE PRICE TWAP consult function consult(address pool, uint32 secondsAgo)\n internal\n view\n returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity){}\n arithmeticMeanTick arithmeticMeanTick getQuoteAtTick function getQuoteAtTick(\n int24 tick,\n uint128 baseAmount,\n address baseToken,\n address quoteToken\n ) internal pure returns (uint256 quoteAmount) {} \n"
},
{
"answer_id": 74579737,
"author": "Ritzy Dev",
"author_id": 19361853,
"author_profile": "https://Stackoverflow.com/users/19361853",
"pm_score": 0,
"selected": false,
"text": "return TickMath.getSqrtRatioAtTick(tick);\n"
},
{
"answer_id": 74619134,
"author": "kfx",
"author_id": 2435820,
"author_profile": "https://Stackoverflow.com/users/2435820",
"pm_score": 2,
"selected": true,
"text": "1.0001 ** 205930 = 876958666.4726943\n 10**6 10**18 10**-12 876958666.4726943 * (10 ** -12) = 0.0008769586664726943\n token1/token0 token0 token1 1 / 0.0008769586664726943 = 1140.3045984164828\n 2**96"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19361853/"
] |
74,555,461
|
<p>I'm trying to use @include. But i got this error : <code>Undefined variable: bookOther (View: /home/infinitr/pinus.infinitree.eco/modules/Tour/Views/frontend/guest_list.blade.php)</code></p>
<p>How can i fix it?</p>
<p>The Controller :</p>
<pre><code>public function guests_list($id){
$booking = Booking::where('id', $id)->first();
$bookOther = BookOther::where('booking_id', '=', $booking->id)->get();
return view('Tour::frontend.guest_list', ['booking'=>$booking, 'bookOther'=>$bookOther, 'layout'=>'guest_list']);
}
</code></pre>
<p>The Route :</p>
<pre><code>Route::get('/guest_list/{id}', '\Modules\Tour\Controllers\TourController@guests_list')->name('guest_list');
</code></pre>
<p>The blade :</p>
<pre><code><div id="booking-customer-{{$booking->id}}" class="tab-pane fade"><br>
@include('Tour::frontend.guest_list')
</div>
</code></pre>
|
[
{
"answer_id": 74555951,
"author": "Muh Raswan Sualdi",
"author_id": 20551663,
"author_profile": "https://Stackoverflow.com/users/20551663",
"pm_score": -1,
"selected": false,
"text": "return view('Tour::frontend.guest_list', ['booking'=>$booking, 'bookOther'=>$bookOther, 'layout'=>'guest_list']); return view('Tour::frontend.guest_list', compact('booking','bookOther', 'layout');"
},
{
"answer_id": 74557824,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 1,
"selected": false,
"text": "@include @include('Tour::frontend.guest_list',[\n 'bookOther' => $bookOther,\n])\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18460864/"
] |
74,555,485
|
<p>I'm writing an android app that is designed for multiple phones to be able to interface with a google sheet at the same time. but I'm getting this error on one of my test phones:</p>
<pre><code>FATAL EXCEPTION: DefaultDispatcher-worker-2
Process: com.example.frcscout22sheets, PID: 9729
java.lang.IllegalArgumentException: the name must not be empty: null
at android.accounts.Account.<init>(Account.java:84)
at android.accounts.Account.<init>(Account.java:69)
at com.google.android.gms.auth.zzl.getToken(com.google.android.gms:play-services-auth-base@@18.0.4:5)
at com.google.android.gms.auth.GoogleAuthUtil.getToken(com.google.android.gms:play-services-auth-base@@18.0.4:3)
at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential.getToken(GoogleAccountCredential.java:267)
at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:292)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:880)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:525)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:466)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:576)
at com.example.frcscout22sheets.Data$onCreateView$2$1.invokeSuspend(Data.kt:55)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:749)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)
Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@afbaf4, Dispatchers.Default]
</code></pre>
<p>this error only occurs on one of my test phones. More specifically, the second one I tested it on. The original one works just fine.</p>
<p>This is the code that throws the error:</p>
<pre><code>package com.example.frcscout22sheets
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import com.google.api.services.sheets.v4.model.ClearValuesRequest
import com.google.api.services.sheets.v4.model.ValueRange
import kotlinx.coroutines.*
class Data : Fragment(R.layout.fragment_data) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
@OptIn(DelicateCoroutinesApi::class)
@RequiresApi(Build.VERSION_CODES.R)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view: View = inflater.inflate(R.layout.fragment_data, container, false)
val matchNumber = view.findViewById<EditText>(R.id.Match_Number)
val teamNumber = view.findViewById<EditText>(R.id.Team_Number)
val autoPoints = view.findViewById<EditText>(R.id.Auto_Points)
val teleopPoints = view.findViewById<EditText>(R.id.Teleop_Points)
val endgamePoints = view.findViewById<EditText>(R.id.Endgame_Points)
val clear = view.findViewById<Button>(R.id.button2)
clear.setOnClickListener(View.OnClickListener {
matchNumber.setText("")
teamNumber.setText("")
autoPoints.setText("")
teleopPoints.setText("")
endgamePoints.setText("")
})
val send = view.findViewById<Button>(R.id.button)
send.setOnClickListener(View.OnClickListener {
GlobalScope.launch {
if (isFull()) {
var row = 0
MainActivity.service.spreadsheets()
while (true) {
row++
println(MainActivity.ID)
if (MainActivity.service.spreadsheets().values().get(MainActivity.ID, "A$row").execute().getValues()[0][0] == "end") {
MainActivity.service.spreadsheets().values().append(MainActivity.ID, "A${row+1}", ValueRange().setValues(listOf(listOf("end")))).setValueInputOption("USER_ENTERED").execute()
MainActivity.service.spreadsheets().values().clear(MainActivity.ID, "A${row}", ClearValuesRequest()).execute()
println(row)
break
}
}
MainActivity.service.spreadsheets().values().append(MainActivity.ID, "A$row", ValueRange().setValues(listOf(listOf(matchNumber.text.toString())))).setValueInputOption("USER_ENTERED").execute()
MainActivity.service.spreadsheets().values().append(MainActivity.ID, "B$row", ValueRange().setValues(listOf(listOf(teamNumber.text.toString())))).setValueInputOption("USER_ENTERED").execute()
MainActivity.service.spreadsheets().values().append(MainActivity.ID, "C$row", ValueRange().setValues(listOf(listOf(autoPoints.text.toString())))).setValueInputOption("USER_ENTERED").execute()
MainActivity.service.spreadsheets().values().append(MainActivity.ID, "D$row", ValueRange().setValues(listOf(listOf(teleopPoints.text.toString())))).setValueInputOption("USER_ENTERED").execute()
MainActivity.service.spreadsheets().values().append(MainActivity.ID, "E$row", ValueRange().setValues(listOf(listOf(endgamePoints.text.toString())))).setValueInputOption("USER_ENTERED").execute()
}
}
})
return view
}
private fun isFull() : Boolean {
if (view?.findViewById<EditText>(R.id.Match_Number)?.text.toString() == "") {
return false
}
if (view?.findViewById<EditText>(R.id.Team_Number)?.text.toString() == "") {
return false
}
if (view?.findViewById<EditText>(R.id.Auto_Points)?.text.toString() == "") {
return false
}
if (view?.findViewById<EditText>(R.id.Teleop_Points)?.text.toString() == "") {
return false
}
if (view?.findViewById<EditText>(R.id.Endgame_Points)?.text.toString() == "") {
return false
}
return true
}
}
</code></pre>
<p>this line specifically:</p>
<pre><code>if (MainActivity.service.spreadsheets().values().get(MainActivity.ID, "A$row").execute().getValues()[0][0] == "end") {
</code></pre>
<p>I login to my google account to get the credentials for the google sheet api inside the mainactivity:</p>
<pre><code>package com.example.frcscout22sheets
import Home
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.example.frcscout22sheets.databinding.ActivityMainBinding
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.Scope
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport
import com.google.api.client.json.gson.GsonFactory
import com.google.api.services.sheets.v4.Sheets
import com.google.api.services.sheets.v4.SheetsScopes
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private var isLoggedIn = false
companion object {
private const val REQUEST_SIGN_IN = 1
lateinit var service : Sheets
lateinit var ID : String
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val dataFragment = Data()
val allianceSelectionFragment = AllianceSelection()
val homeFragment = Home()
setCurrentFragment(homeFragment)
if (!isLoggedIn) {
requestSignIn(baseContext)
}
binding.bottomNavigationView.setOnItemSelectedListener {
when (it.itemId) {
R.id.data -> setCurrentFragment(dataFragment)
R.id.alliance_selection -> setCurrentFragment(allianceSelectionFragment)
R.id.home -> setCurrentFragment(homeFragment)
}
true
}
}
private fun setCurrentFragment(fragment: Fragment) =
supportFragmentManager.beginTransaction().apply {
replace(R.id.flFragment, fragment)
commit()
}
@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_SIGN_IN) {
if (resultCode == RESULT_OK) {
GoogleSignIn.getSignedInAccountFromIntent(data)
.addOnSuccessListener { account ->
val scopes = listOf(SheetsScopes.SPREADSHEETS)
val credential = GoogleAccountCredential.usingOAuth2(baseContext, scopes)
credential.selectedAccount = account.account
val jsonFactory = GsonFactory.getDefaultInstance()
val httpTransport = GoogleNetHttpTransport.newTrustedTransport()
val sheet = Sheets.Builder(httpTransport, jsonFactory, credential)
.setApplicationName(getString(R.string.app_name))
.build()
getSheet(sheet)
}
}
}
}
private fun requestSignIn(context: Context) {
val signInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Scope(SheetsScopes.SPREADSHEETS))
.build()
val client = GoogleSignIn.getClient(context, signInOptions)
startActivityForResult(client.signInIntent, REQUEST_SIGN_IN)
}
private fun getSheet(sheets: Sheets) : Sheets {
service = sheets
println(service)
return sheets
}
}
</code></pre>
<p>I logged in to the account that was working on the original device on the new device and I got the same error.</p>
<p>why might this be happening? What can I do to fix it? Thanks!!</p>
|
[
{
"answer_id": 74555951,
"author": "Muh Raswan Sualdi",
"author_id": 20551663,
"author_profile": "https://Stackoverflow.com/users/20551663",
"pm_score": -1,
"selected": false,
"text": "return view('Tour::frontend.guest_list', ['booking'=>$booking, 'bookOther'=>$bookOther, 'layout'=>'guest_list']); return view('Tour::frontend.guest_list', compact('booking','bookOther', 'layout');"
},
{
"answer_id": 74557824,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 1,
"selected": false,
"text": "@include @include('Tour::frontend.guest_list',[\n 'bookOther' => $bookOther,\n])\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17792511/"
] |
74,555,512
|
<p>We are using drools rule engine 5x
We have a rule configured like</p>
<p>Fact {A,B,C}, Action [X]
Fact {A,B}, Action [Z]</p>
<p>When I pass {A,B,C} I am getting both actions [X],[Z]. Is it expected behaviour from drools engine? Can it be possible to define C as optional fact, in which case, can this be possible?</p>
|
[
{
"answer_id": 74555951,
"author": "Muh Raswan Sualdi",
"author_id": 20551663,
"author_profile": "https://Stackoverflow.com/users/20551663",
"pm_score": -1,
"selected": false,
"text": "return view('Tour::frontend.guest_list', ['booking'=>$booking, 'bookOther'=>$bookOther, 'layout'=>'guest_list']); return view('Tour::frontend.guest_list', compact('booking','bookOther', 'layout');"
},
{
"answer_id": 74557824,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 1,
"selected": false,
"text": "@include @include('Tour::frontend.guest_list',[\n 'bookOther' => $bookOther,\n])\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8451184/"
] |
74,555,529
|
<p>I have a problem,
when I look for the id of an xpath it changes every time I enter the web</p>
<p>how can i use selenium webdriver python
browser.find_element(By.ID,)
if the id changes every time I consult it</p>
<p>first</p>
<pre><code><span data-dojo-attach-point="containerNode,focusNode"
class="tabLabel" role="tab" tabindex="0"
id="icm_widget_SelectorTabContainer_0_tablist_dcf42e75-1d03-4acd-878c-722cbc8e74ec"
name="icm_widget_SelectorTabContainer_0_tablist_dcf42e75-1d03-4acd-878c-722cbc8e74ec"
aria-disabled="false"
title=""
style="user-select: none;"
aria-selected="true">Search</span>
</code></pre>
<p>second</p>
<pre><code><span data-dojo-attach-point="containerNode,focusNode"
class="tabLabel"
role="tab"
tabindex="0"
id="icm_widget_SelectorTabContainer_0_tablist_c9ba5042-90d2-4932-8c2d-762a1dd39982"
name="icm_widget_SelectorTabContainer_0_tablist_c9ba5042-90d2-4932-8c2d-762a1dd39982"
aria-disabled="false"
title=""
style="user-select: none;"
aria-selected="true">Search</span>
</code></pre>
<p>try with</p>
<pre><code>
browser.find_element(By.XPATH
browser.find_element(By.ID
browser.find_element(By.NAME
</code></pre>
<p>same problem, the id changes</p>
|
[
{
"answer_id": 74555951,
"author": "Muh Raswan Sualdi",
"author_id": 20551663,
"author_profile": "https://Stackoverflow.com/users/20551663",
"pm_score": -1,
"selected": false,
"text": "return view('Tour::frontend.guest_list', ['booking'=>$booking, 'bookOther'=>$bookOther, 'layout'=>'guest_list']); return view('Tour::frontend.guest_list', compact('booking','bookOther', 'layout');"
},
{
"answer_id": 74557824,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 1,
"selected": false,
"text": "@include @include('Tour::frontend.guest_list',[\n 'bookOther' => $bookOther,\n])\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8748656/"
] |
74,555,545
|
<p>There is a part of my app where I send an email using a button but for some reason the Intent doesn't work and I don't understand why.</p>
<pre><code>binding.IvMail.setOnClickListener {
val email = Intent(Intent.ACTION_SEND)
.setType("text/plain")
.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.email_subject))
.putExtra(Intent.EXTRA_TEXT, getString(R.string.email_text))
if (activity?.packageManager?.resolveActivity(email, 0) != null) {
startActivity(email)
}
}
</code></pre>
<p>I already searched for other ways to do it but everyone is using Intent.</p>
|
[
{
"answer_id": 74555951,
"author": "Muh Raswan Sualdi",
"author_id": 20551663,
"author_profile": "https://Stackoverflow.com/users/20551663",
"pm_score": -1,
"selected": false,
"text": "return view('Tour::frontend.guest_list', ['booking'=>$booking, 'bookOther'=>$bookOther, 'layout'=>'guest_list']); return view('Tour::frontend.guest_list', compact('booking','bookOther', 'layout');"
},
{
"answer_id": 74557824,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 1,
"selected": false,
"text": "@include @include('Tour::frontend.guest_list',[\n 'bookOther' => $bookOther,\n])\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20587187/"
] |
74,555,575
|
<p>currently i update my node and npm version for stencil bigcommerce when i make bundle for my old project i'm facing this type of problem. can anyone solve my this issue?</p>
<h1>Error: No input specified: provide a file name or a source string to process</h1>
<p>---------WARNING---------
We are currently in the process of deprecating node-sass fork <a href="https://github.com/bigcommerce-labs/node-sass" rel="nofollow noreferrer">https://github.com/bigcommerce-labs/node-sass</a>
Your scss files were compiled using latest node-sass version <a href="https://github.com/sass/node-sass" rel="nofollow noreferrer">https://github.com/sass/node-sass</a>
This error might indicate that your scss file is not compatible with it.
There is still an option to compile scss file old fork by using --use-old-node-sass-fork.
But note, that this will lead to 500 error in production in near future.
---------WARNING---------</p>
|
[
{
"answer_id": 74555951,
"author": "Muh Raswan Sualdi",
"author_id": 20551663,
"author_profile": "https://Stackoverflow.com/users/20551663",
"pm_score": -1,
"selected": false,
"text": "return view('Tour::frontend.guest_list', ['booking'=>$booking, 'bookOther'=>$bookOther, 'layout'=>'guest_list']); return view('Tour::frontend.guest_list', compact('booking','bookOther', 'layout');"
},
{
"answer_id": 74557824,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 1,
"selected": false,
"text": "@include @include('Tour::frontend.guest_list',[\n 'bookOther' => $bookOther,\n])\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20546671/"
] |
74,555,577
|
<p>My JavaScript files don't seem like it is linked to my PHP file.</p>
<p>I am building a WordPress website. I have header.php and calling this header.php file by including</p>
in my main.php file. I added JS path in the head tag in header.php, but it doesn't seem like it's working(the JS files I added are for a carousel, but does not change anything). I just started learning so I can't even guess what I am doing wrong here. What can I do to link my JS files?
<ul>
<li>header.php, main.php, and js folder are in the root folder. Javascript files are in the js folder.</li>
</ul>
<p>-- This is how I linked JS file in header.php. inside of the head tag</p>
<pre><code><head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script type="text/javascript" src="js/Jquery.js"></script>
<script type="text/javascript" src="js/lightslider.js"></script>
<?php wp_head(); ?>
</head>
</code></pre>
|
[
{
"answer_id": 74555951,
"author": "Muh Raswan Sualdi",
"author_id": 20551663,
"author_profile": "https://Stackoverflow.com/users/20551663",
"pm_score": -1,
"selected": false,
"text": "return view('Tour::frontend.guest_list', ['booking'=>$booking, 'bookOther'=>$bookOther, 'layout'=>'guest_list']); return view('Tour::frontend.guest_list', compact('booking','bookOther', 'layout');"
},
{
"answer_id": 74557824,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 1,
"selected": false,
"text": "@include @include('Tour::frontend.guest_list',[\n 'bookOther' => $bookOther,\n])\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20113706/"
] |
74,555,592
|
<p>If I have:</p>
<p>-- public<br />
-- csv<br />
exampleCSV.csv</p>
<p>i.e. /public/csv/exampleCSV.csv</p>
<p>and then:</p>
<pre><code>fetch('csv/exampleCSV.csv')
.then(response => {
console.log(response);
response.blob().then(blob => {
let url = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = url;
a.download = 'exampleCSV.csv';
a.click();
});
});
</code></pre>
<p>Why do I not get the CSV file on click but instead the html page of the react app?</p>
|
[
{
"answer_id": 74555951,
"author": "Muh Raswan Sualdi",
"author_id": 20551663,
"author_profile": "https://Stackoverflow.com/users/20551663",
"pm_score": -1,
"selected": false,
"text": "return view('Tour::frontend.guest_list', ['booking'=>$booking, 'bookOther'=>$bookOther, 'layout'=>'guest_list']); return view('Tour::frontend.guest_list', compact('booking','bookOther', 'layout');"
},
{
"answer_id": 74557824,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 1,
"selected": false,
"text": "@include @include('Tour::frontend.guest_list',[\n 'bookOther' => $bookOther,\n])\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13696540/"
] |
74,555,621
|
<p>I have a string that has characters and numbers
string is like</p>
<pre><code>iPhone8s
</code></pre>
<p>i want the output to be <code>iPhone 8s</code>
I have written this code</p>
<pre><code>s = 'iPhone8s'
re.sub('(\d+(\.\d+)?)', r' \1 ', s).strip()
</code></pre>
<p>but it outputs <code>iPhone 8 s</code> how can i make the output to be <code>iPhone 8s</code></p>
<p>i only want it for string that contains iPhone in it, i dont want to transform <code>random8</code> as <code>random 8</code></p>
|
[
{
"answer_id": 74555677,
"author": "KapBytes Technologies",
"author_id": 20518474,
"author_profile": "https://Stackoverflow.com/users/20518474",
"pm_score": 0,
"selected": false,
"text": "result='iphone8s'.lower().replace('iphone','iPhone ')\n#iPhone 8s\n"
},
{
"answer_id": 74556127,
"author": "uingtea",
"author_id": 4082344,
"author_profile": "https://Stackoverflow.com/users/4082344",
"pm_score": 2,
"selected": false,
"text": "iPhone import re\n\ns = 'iphone8s'\ns = re.sub('iPhone(\\d+)', r'iPhone \\1', s, 0, re.IGNORECASE)\nprint(s) # iPhone 8s\n\ns = 'random8s'\ns = re.sub('iPhone(\\d+)', r'iPhone \\1', s, 0, re.IGNORECASE)\nprint(s) # random8s\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10159065/"
] |
74,555,640
|
<p>I have this button whenever I click this button, I want to append new data to a struct on another viewcontroller and show it on tableview and when I go back to add more data the prev data wont gone. In my case, I can only add 1 data, after I go back and add more data, the previous one is gone.</p>
<p>ViewController segue code and storyboard:</p>
<pre><code>override
</code></pre>
<p><strong>viewcontroller</strong></p>
<p>confirmviewcontroller code and storyboard:</p>
<pre><code>class ConfirmViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
struct menu {
let menuImages : String
let menuPrice : Int
}
@IBOutlet weak var totalLbl: UILabel!
@IBOutlet weak var confirmBtn: UIButton!
@IBOutlet weak var cartTable: UITableView!
var data: [menu] = [
**confirmcontroller storyboard**
</code></pre>
|
[
{
"answer_id": 74555677,
"author": "KapBytes Technologies",
"author_id": 20518474,
"author_profile": "https://Stackoverflow.com/users/20518474",
"pm_score": 0,
"selected": false,
"text": "result='iphone8s'.lower().replace('iphone','iPhone ')\n#iPhone 8s\n"
},
{
"answer_id": 74556127,
"author": "uingtea",
"author_id": 4082344,
"author_profile": "https://Stackoverflow.com/users/4082344",
"pm_score": 2,
"selected": false,
"text": "iPhone import re\n\ns = 'iphone8s'\ns = re.sub('iPhone(\\d+)', r'iPhone \\1', s, 0, re.IGNORECASE)\nprint(s) # iPhone 8s\n\ns = 'random8s'\ns = re.sub('iPhone(\\d+)', r'iPhone \\1', s, 0, re.IGNORECASE)\nprint(s) # random8s\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20587227/"
] |
74,555,652
|
<p>I have a dataframe</p>
<pre><code>city = pd.DataFrame({'id': [1,2,3,4],
'city': ['NRTH CAROLINA','NEW WST AMSTERDAM','EAST TOKYO','LONDON STH']})
</code></pre>
<p>How can I change NRTH to NORTH, WST to WEST, and STH to SOUTH, so the output will be like this</p>
<pre><code>id city
1 NORTH CAROLINA
2 NEW WEST AMSTERDAM
3 EAST TOKYO
4 LONDON STH
</code></pre>
|
[
{
"answer_id": 74555677,
"author": "KapBytes Technologies",
"author_id": 20518474,
"author_profile": "https://Stackoverflow.com/users/20518474",
"pm_score": 0,
"selected": false,
"text": "result='iphone8s'.lower().replace('iphone','iPhone ')\n#iPhone 8s\n"
},
{
"answer_id": 74556127,
"author": "uingtea",
"author_id": 4082344,
"author_profile": "https://Stackoverflow.com/users/4082344",
"pm_score": 2,
"selected": false,
"text": "iPhone import re\n\ns = 'iphone8s'\ns = re.sub('iPhone(\\d+)', r'iPhone \\1', s, 0, re.IGNORECASE)\nprint(s) # iPhone 8s\n\ns = 'random8s'\ns = re.sub('iPhone(\\d+)', r'iPhone \\1', s, 0, re.IGNORECASE)\nprint(s) # random8s\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20341621/"
] |
74,555,691
|
<p>We have variable group in Pipeline and it has below input</p>
<blockquote>
<p>Input: Instance1,Instance2,Inastance3</p>
<p>Expected Output: Instance1 Instance2 Inastance3</p>
</blockquote>
<p>We tried below YAML Code</p>
<pre><code>trigger:
- main
pool:
vmImage: ubuntu-latest
variables:
- group: "DevInstanceList"
- name: InstancesList
value: $[variables.Instances]
steps:
- script: echo $(InstancesList)
- ${{ each env in split(variables.InstancesList, ',')}}:
- script: echo ${{ env }}
</code></pre>
<p>We tried to split using comma seperator and getting below error.</p>
<blockquote>
<p>Error: syntax error: invalid arithmetic operator (error token is
".Instances")</p>
</blockquote>
<p>Instance Defined in Library--> Group variable
<a href="https://i.stack.imgur.com/8JyLy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8JyLy.png" alt="enter image description here" /></a>
Please share your thoughts</p>
|
[
{
"answer_id": 74556339,
"author": "Dilly B",
"author_id": 2670623,
"author_profile": "https://Stackoverflow.com/users/2670623",
"pm_score": 0,
"selected": false,
"text": "- powershell: |\n \n $results = \"$(InstancesList)\".Split(\" \")\n $result[0]\n $result[1]\n $result[2]\n displayName: 'PowerShell Script to split variables'\n trigger: none\n\npool:\n vmimage: ubuntu-latest\n\nvariables:\n - group: TestVariablegroup\n\nsteps:\n- task: PowerShell@2\n inputs:\n targetType: 'inline'\n script: |\n # Write your PowerShell commands here.\n echo $(InstancesName)\n $results = \"$(InstancesName)\".split(\",\")\n foreach ($instance in $results){\n Write-Host \"The selected Instance Name is - $($Instance)\"\n }\n"
},
{
"answer_id": 74557079,
"author": "Ging Yuan-MSFT",
"author_id": 18349408,
"author_profile": "https://Stackoverflow.com/users/18349408",
"pm_score": 3,
"selected": true,
"text": "variables:\n- group: \"DevInstanceList\"\n- name: InstancesList\n value: Instance1,Instance2\n\nsteps:\n- ${{ each env in split(variables.InstancesList, ',')}}:\n - script: echo ${{ env }} \n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10867777/"
] |
74,555,698
|
<p>I'm using this code to get featured image from post. This is my whole code every thing else is working rather than the image i'm trying to display featured image also the posttype i'm using is custom post type.
Can anyone tell what I'm doing wrong?</p>
<pre><code> add_shortcode('get-video-post-type','videos_cpt');
function videos_cpt(){
$args = array(
'post_type' => 'Videos',
'post_status'=>'publish',
);
$result = new WP_Query($args);
if ($result -> have_posts()){
while($result -> have_posts()){
$result -> the_post();
?>
<div id="show-all-post" class="posts-carousel">
<div class="item" id="video-box">
<div class="left-img"><img class="post-image" src="<?php echo get_the_post_thumbnail( get_the_ID() , 'full' ); ?>" alt="image"></div>
<div class="right-content">
<h1 style="color:black;"><?php the_title();?></h1>
<p style="color:black;"><?php echo substr(get_the_excerpt(), 0,50); ?>....</p>
<a href="<?php the_permalink();?>">Read More</a>
</div>
</div>
</div>
<?php
}
}
wp_reset_postdata();
}
</code></pre>
|
[
{
"answer_id": 74556339,
"author": "Dilly B",
"author_id": 2670623,
"author_profile": "https://Stackoverflow.com/users/2670623",
"pm_score": 0,
"selected": false,
"text": "- powershell: |\n \n $results = \"$(InstancesList)\".Split(\" \")\n $result[0]\n $result[1]\n $result[2]\n displayName: 'PowerShell Script to split variables'\n trigger: none\n\npool:\n vmimage: ubuntu-latest\n\nvariables:\n - group: TestVariablegroup\n\nsteps:\n- task: PowerShell@2\n inputs:\n targetType: 'inline'\n script: |\n # Write your PowerShell commands here.\n echo $(InstancesName)\n $results = \"$(InstancesName)\".split(\",\")\n foreach ($instance in $results){\n Write-Host \"The selected Instance Name is - $($Instance)\"\n }\n"
},
{
"answer_id": 74557079,
"author": "Ging Yuan-MSFT",
"author_id": 18349408,
"author_profile": "https://Stackoverflow.com/users/18349408",
"pm_score": 3,
"selected": true,
"text": "variables:\n- group: \"DevInstanceList\"\n- name: InstancesList\n value: Instance1,Instance2\n\nsteps:\n- ${{ each env in split(variables.InstancesList, ',')}}:\n - script: echo ${{ env }} \n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20517109/"
] |
74,555,717
|
<p>How do you pick a word from a string or scanner input, say for instance a search engine search?</p>
<p>I looked up indexOf() for a string but I’m not finding how to make a public void word class from finding a word from a line of text. Hoping every word can be a variable.</p>
|
[
{
"answer_id": 74556339,
"author": "Dilly B",
"author_id": 2670623,
"author_profile": "https://Stackoverflow.com/users/2670623",
"pm_score": 0,
"selected": false,
"text": "- powershell: |\n \n $results = \"$(InstancesList)\".Split(\" \")\n $result[0]\n $result[1]\n $result[2]\n displayName: 'PowerShell Script to split variables'\n trigger: none\n\npool:\n vmimage: ubuntu-latest\n\nvariables:\n - group: TestVariablegroup\n\nsteps:\n- task: PowerShell@2\n inputs:\n targetType: 'inline'\n script: |\n # Write your PowerShell commands here.\n echo $(InstancesName)\n $results = \"$(InstancesName)\".split(\",\")\n foreach ($instance in $results){\n Write-Host \"The selected Instance Name is - $($Instance)\"\n }\n"
},
{
"answer_id": 74557079,
"author": "Ging Yuan-MSFT",
"author_id": 18349408,
"author_profile": "https://Stackoverflow.com/users/18349408",
"pm_score": 3,
"selected": true,
"text": "variables:\n- group: \"DevInstanceList\"\n- name: InstancesList\n value: Instance1,Instance2\n\nsteps:\n- ${{ each env in split(variables.InstancesList, ',')}}:\n - script: echo ${{ env }} \n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20587317/"
] |
74,555,718
|
<p>hey guys I need some help here</p>
<p>the goal:
take input as long is inputs != 999, print greatest sum of 3 consecutive numbers (999 excluded). if less than 3 inputs entered, print all inputs' sum.</p>
<p>can't use arrays</p>
<p>for example</p>
<p><code>7 2 **9 8 7** 6 7 5 9 999 </code></p>
<p>The max sum is 24</p>
<p>because 9+8+7 = 24 (9,8,7 makes the greatest sum of consecutive numbers)</p>
<p>thanks</p>
<pre class="lang-java prettyprint-override"><code>public static void main(String[] args) {
System.out.print("Please enter numbers followed by 999: ");
int num=0, sum=0, maxSum=0;
while (num != 999) {
num = input.nextInt();
}
System.out.println("The max sum is ");
input.close();
}
}
</code></pre>
|
[
{
"answer_id": 74556339,
"author": "Dilly B",
"author_id": 2670623,
"author_profile": "https://Stackoverflow.com/users/2670623",
"pm_score": 0,
"selected": false,
"text": "- powershell: |\n \n $results = \"$(InstancesList)\".Split(\" \")\n $result[0]\n $result[1]\n $result[2]\n displayName: 'PowerShell Script to split variables'\n trigger: none\n\npool:\n vmimage: ubuntu-latest\n\nvariables:\n - group: TestVariablegroup\n\nsteps:\n- task: PowerShell@2\n inputs:\n targetType: 'inline'\n script: |\n # Write your PowerShell commands here.\n echo $(InstancesName)\n $results = \"$(InstancesName)\".split(\",\")\n foreach ($instance in $results){\n Write-Host \"The selected Instance Name is - $($Instance)\"\n }\n"
},
{
"answer_id": 74557079,
"author": "Ging Yuan-MSFT",
"author_id": 18349408,
"author_profile": "https://Stackoverflow.com/users/18349408",
"pm_score": 3,
"selected": true,
"text": "variables:\n- group: \"DevInstanceList\"\n- name: InstancesList\n value: Instance1,Instance2\n\nsteps:\n- ${{ each env in split(variables.InstancesList, ',')}}:\n - script: echo ${{ env }} \n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20587243/"
] |
74,555,728
|
<p>In Java, we can use the <code>instance initialization block</code> to keep track of count of any class objects.</p>
<p>So, in dart how can we do that for a class with <code>const Constructor</code>?</p>
<p>I know that for a non-constant Constructor, we can achieve that by creating a <code>static variable</code> then incrementing its value in Constructor body.</p>
<p>But as we know that, <code>const Constructor</code> can't have a body, then how to keep track of number of instances created for a particular class ?</p>
|
[
{
"answer_id": 74556339,
"author": "Dilly B",
"author_id": 2670623,
"author_profile": "https://Stackoverflow.com/users/2670623",
"pm_score": 0,
"selected": false,
"text": "- powershell: |\n \n $results = \"$(InstancesList)\".Split(\" \")\n $result[0]\n $result[1]\n $result[2]\n displayName: 'PowerShell Script to split variables'\n trigger: none\n\npool:\n vmimage: ubuntu-latest\n\nvariables:\n - group: TestVariablegroup\n\nsteps:\n- task: PowerShell@2\n inputs:\n targetType: 'inline'\n script: |\n # Write your PowerShell commands here.\n echo $(InstancesName)\n $results = \"$(InstancesName)\".split(\",\")\n foreach ($instance in $results){\n Write-Host \"The selected Instance Name is - $($Instance)\"\n }\n"
},
{
"answer_id": 74557079,
"author": "Ging Yuan-MSFT",
"author_id": 18349408,
"author_profile": "https://Stackoverflow.com/users/18349408",
"pm_score": 3,
"selected": true,
"text": "variables:\n- group: \"DevInstanceList\"\n- name: InstancesList\n value: Instance1,Instance2\n\nsteps:\n- ${{ each env in split(variables.InstancesList, ',')}}:\n - script: echo ${{ env }} \n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17031796/"
] |
74,555,777
|
<p>I am a newbie trying to understand list comprehensions in python. My question is different from another posts.</p>
<p>I was asked to write list comprehension code to get the following output:</p>
<p>All odd numbers from 1 to 30 (both inclusive). Those that are multiples of 5 will be marked with an 'x'.</p>
<blockquote>
<p>[1, 3, '5x', 7, 9, 11, 13, '15x', 17, 19, 21, 23, '25x', 27, 29]</p>
</blockquote>
<p>For this, I tried to get it with normal for and if ways. This is my solution and it worked:</p>
<pre><code>odds = []
for i in list(range(1,30+1)):
if i%2 !=0:
odds.append(i)
if i%5 == 0:
odds.append(f'{i}x')
odds.remove(i)
print(odds)
</code></pre>
<p>In the image you can find my failed list comprehension attempt. I need some light to place the rest of the stuff correctly.</p>
<p>Thank you!</p>
<p><img src="https://i.stack.imgur.com/8EM2p.jpg" alt="enter image description here" /></p>
|
[
{
"answer_id": 74555811,
"author": "DYZ",
"author_id": 4492932,
"author_profile": "https://Stackoverflow.com/users/4492932",
"pm_score": 2,
"selected": false,
"text": "[(n if n%5 else f'{n}x') for n in range(1,31) if n%2]\n"
},
{
"answer_id": 74555889,
"author": "Simon",
"author_id": 1960027,
"author_profile": "https://Stackoverflow.com/users/1960027",
"pm_score": 2,
"selected": false,
"text": "[n for n in range(1,31,2) if n%5 != 0] + [f'{n}x' for n in range(1,31,2) if n%5 == 0]\n [[f'{n}x',n][min(n%5,1)] for n in range(1,31,2)]\n min(n%5,1) [f'{n}x',n] n"
},
{
"answer_id": 74556407,
"author": "Arifa Chan",
"author_id": 19574157,
"author_profile": "https://Stackoverflow.com/users/19574157",
"pm_score": 2,
"selected": false,
"text": "numlist = [(i,f'{i}x')[not i%5] for i in range(31) if i%2]\nprint(numlist)\n# [1, 3, '5x', 7, 9, 11, 13, '15x', 17, 19, 21, 23, '25x', 27, 29]\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4728238/"
] |
74,555,787
|
<p>I have a tablix form that has a list of equipment whose names contain a specific prefix.
There are, for example, chlorine filters from 1 to 10 with name like 'Filter #1 cl., Filter #2 cl. and there are cement filters from 1 to 8 with names like 'Filter #1 cmt' etc.</p>
<p>I need the equipment list to be sorted by equipment type from Z to A, like:</p>
<pre><code>Filter #1 cl
Filter #2 cl
Filter #1 cmt
Filter #2 cmt
</code></pre>
<p>I tried to sort by description, but the equipment is displayed randomly like</p>
<pre><code>Filter #1 cmt
Filter #1 cl
Filter #2 cl
Filter #2 cmt
</code></pre>
|
[
{
"answer_id": 74556000,
"author": "Olsgaard",
"author_id": 11148296,
"author_profile": "https://Stackoverflow.com/users/11148296",
"pm_score": 1,
"selected": false,
"text": "SELECT\n RIGHT(filter_column, Charindex(' ', Reverse(filter_column)) - 1) AS filter_name\nFROM filters_table\n"
},
{
"answer_id": 74556054,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 1,
"selected": true,
"text": "SELECT yourcolumn\nFROM yourtable\nORDER BY RIGHT(yourcolumn, (CHARINDEX(' ',REVERSE(yourcolumn),0))),\nSUBSTRING(yourcolumn,0, LEN(yourcolumn) - LEN\n(RIGHT(yourcolumn, Charindex(' ', Reverse(yourcolumn)) - 1)));\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20587361/"
] |
74,555,791
|
<p>According the <a href="https://doc.rust-lang.org/std/vec/struct.Vec.html" rel="nofollow noreferrer">documentation for <code>std::Vec</code></a>, calling <code>shrink_to_fit()</code> will cause the <code>Vec</code>'s capacity to "drop down as close as possible to the length but the allocator may still inform the vector that there is space for a few more elements." <code>Vec::with_capacity()</code> and <code>Vec::reserve_exact()</code> each have a similar note saying that the reserved capacity may still be slightly greater than the length.</p>
<p>Meanwhile, <a href="https://doc.rust-lang.org/std/alloc/trait.GlobalAlloc.html" rel="nofollow noreferrer">the documentation for <code>std::alloc::GlobalAlloc::dealloc()</code></a> states that the layout used to deallocate a block of memory "must be the same layout that was used to allocate that block of memory," which means the layout that is passed to <code>dealloc()</code> needs to have the exact size of the block.</p>
<p>I am working on an FFI function that returns a list and a size. The C code that calls the function will have to call a <code>free_X()</code> function I provide to deallocate the list. To do that, it passes in a pointer to the list and the size of the list. In Rust, I am using a <code>std::Vec</code> for the list and want to shrink it so <code>capacity == length</code> and then <code>std::mem::forget()</code> it and return a pointer to it. The C code will pass in a pointer to a <code>size_t</code> that I will set to the size. Here are examples of what the function signatures will look like in C:</p>
<pre class="lang-c prettyprint-override"><code>List *obtain_list(size_t *size);
void free_list(List *list, size_t *size);
</code></pre>
<p>You can probably see the dilemma. I can shrink the <code>std::Vec</code> with <code>shrink_to_fit()</code>, but <code>my_vec.len()</code> might not equal <code>my_vec.capacity()</code>. Thus, if C passes the <code>size</code> it got from Rust to <code>free_list()</code>, <code>free_list()</code> will create a <code>std::alloc::Layout</code> that doesn't match the allocated block's size (because the block size was <code>my_vec.capacity()</code>, not <code>my_vec.len()</code>). This could result in undefined behavior, per <code>std::alloc::dealloc()</code>'s documentation.</p>
<p>I could return the capacity of the list by changing the function signatures to pass the capacity to C, like so:</p>
<pre><code>List *obtain_list(size_t *size, size_t *capacity);
void free_list(List *list, size_t *size, size_t *capacity);
</code></pre>
<p>I don't like having multiple pointers that are supposed to be initialized by the called function, so I'd probably create a struct instead that holds the list pointer as well as the size and capacity.</p>
<p>That seems hairy to me. I would much rather just return a size. Is there a way to force <code>std::Vec</code> to reallocate its buffer to be exactly the same as the length?</p>
|
[
{
"answer_id": 74556233,
"author": "Kevin Reid",
"author_id": 99692,
"author_profile": "https://Stackoverflow.com/users/99692",
"pm_score": 3,
"selected": true,
"text": "Vec<T> Box<[T]> Vec::into_boxed_slice()"
},
{
"answer_id": 74557112,
"author": "tedtanner",
"author_id": 8297052,
"author_profile": "https://Stackoverflow.com/users/8297052",
"pm_score": 2,
"selected": false,
"text": "Vec::into_boxed_slice() std::alloc::alloc() Vec Vec::into_boxed_slice()"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8297052/"
] |
74,555,803
|
<p>I am trying to add a click event handler to a button that will cause it to change the CSS display property of a sign-in form to 'none'.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// make the form disappear when the user clicks initSignUpBtn
const initSignUpBtn = document.querySelector(".btn signup-btn");
initSignUpBtn.addEventListener("click", () =>{
document.getElementById("signinForm").style.display="none";
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="signin-form" id="signinForm">
<div class="form-group">
<input type="email" class="email-input" id="emailInput" placeholder="Email or username">
</div>
<div class="form-group">
<input type="password" class="pass-input" id="passwordInput" placeholder="Password">
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="checkbox"> Remember me<a class="need-help" href="#">Need Help?</a>
</label>
</div>
<button type="button" class="btn signin-btn" id="signinbtn">Sign in</button>
<button type="button" class="btn signup-btn" id="initSignUpBtn">New? Sign up!</button>
</form></code></pre>
</div>
</div>
</p>
<p>I added an event listener of type 'click' to the button, and wrote an anonymous function that changes the display property of the form to 'none' but this did not work.</p>
|
[
{
"answer_id": 74555837,
"author": "Zac Anger",
"author_id": 5774952,
"author_profile": "https://Stackoverflow.com/users/5774952",
"pm_score": 3,
"selected": true,
"text": "document.getElementById(\"initSignUpBtn\") querySelector document.querySelector(\".btn.signup-btn\") document.querySelector(\".signup-btn\")"
},
{
"answer_id": 74555840,
"author": "jerry",
"author_id": 20493210,
"author_profile": "https://Stackoverflow.com/users/20493210",
"pm_score": 0,
"selected": false,
"text": "<form class=\"signin-form\" id=\"signinForm\">\n <div class=\"form-group\">\n <input type=\"email\" class=\"email-input\" id=\"emailInput\" placeholder=\"Email or username\">\n </div>\n <div class=\"form-group\">\n <input type=\"password\" class=\"pass-input\" id=\"passwordInput\" placeholder=\"Password\">\n </div>\n <div class=\"form-check\">\n <label class=\"form-check-label\">\n <input class=\"form-check-input\" type=\"checkbox\"> Remember me<a class=\"need-help\" href=\"#\">Need Help?</a>\n </label>\n </div>\n <button type=\"button\" class=\"btn signin-btn\" id=\"signinbtn\">Sign in</button>\n <button type=\"button\" class=\"btn signup-btn\" id=\"initSignUpBtn\">New? Sign up!</button>\n\n</form> const initSignUpBtn = document.querySelector(\".btn.signup-btn\");\ninitSignUpBtn.addEventListener(\"click\", () =>{\n document.getElementById(\"signinForm\").style.display=\"none\";\n}); <form class=\"signin-form\" id=\"signinForm\">\n <div class=\"form-group\">\n <input type=\"email\" class=\"email-input\" id=\"emailInput\" placeholder=\"Email or username\">\n </div>\n <div class=\"form-group\">\n <input type=\"password\" class=\"pass-input\" id=\"passwordInput\" placeholder=\"Password\">\n </div>\n <div class=\"form-check\">\n <label class=\"form-check-label\">\n <input class=\"form-check-input\" type=\"checkbox\"> Remember me<a class=\"need-help\" href=\"#\">Need Help?</a>\n </label>\n </div>\n <button type=\"button\" class=\"btn signin-btn\" id=\"signinbtn\">Sign in</button>\n <button type=\"button\" class=\"btn signup-btn\" id=\"initSignUpBtn\">New? Sign up!</button>\n\n</form>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20587367/"
] |
74,555,826
|
<p>Hello i am new to programming and i have a problem on system in which i am trying to make a Booking system.</p>
<p>I want to remove a chunk of objects with same id from an array while clicking a btn.
Here is an array..</p>
<pre><code>array = [
{ id: 1, futsal: "4", time: "06:00 - 09:00", … },
{ id: 1, futsal: "4", time: "06:00 - 09:00", … },
{ id: 1, futsal: "4", time: "06:00 - 09:00", … },
{ id: 2, futsal: "4", time: "07:00 - 08:00", … },
{ id: 2, futsal: "4", time: "07:00 - 07:00", … },
{ id: 3, futsal: "4", time: "08:00 - 09:00", … },
{ id: 3, futsal: "4", time: "08:00 - 09:00", … },
{ id: 3, futsal: "4", time: "08:00 - 09:00", … }]
</code></pre>
<p>I want to remove all the objects with same id at once i.e either all objects with id=1 or 2...</p>
|
[
{
"answer_id": 74555882,
"author": "ray",
"author_id": 636077,
"author_profile": "https://Stackoverflow.com/users/636077",
"pm_score": -1,
"selected": false,
"text": "const array = [\n { id: 1, futsal: \"4\", time: \"06:00 - 09:00\" },\n { id: 1, futsal: \"4\", time: \"06:00 - 09:00\" },\n { id: 1, futsal: \"4\", time: \"06:00 - 09:00\" },\n { id: 2, futsal: \"4\", time: \"07:00 - 08:00\" },\n { id: 2, futsal: \"4\", time: \"07:00 - 07:00\" },\n { id: 3, futsal: \"4\", time: \"08:00 - 09:00\" },\n { id: 3, futsal: \"4\", time: \"08:00 - 09:00\" },\n { id: 3, futsal: \"4\", time: \"08:00 - 09:00\" }\n];\n\n// only items where id is not 2\nconst filtered = array.filter(item => item.id !== 2);\n\nconsole.log(filtered);"
},
{
"answer_id": 74556023,
"author": "Mukesh Soni",
"author_id": 11556649,
"author_profile": "https://Stackoverflow.com/users/11556649",
"pm_score": 0,
"selected": false,
"text": " { id: 1, futsal: \"4\", time: \"06:00 - 09:00\", },\n { id: 1, futsal: \"4\", time: \"06:00 - 09:00\", },\n { id: 1, futsal: \"4\", time: \"06:00 - 09:00\", },\n { id: 2, futsal: \"4\", time: \"07:00 - 08:00\", },\n { id: 2, futsal: \"4\", time: \"07:00 - 07:00\", },\n { id: 3, futsal: \"4\", time: \"08:00 - 09:00\", },\n { id: 3, futsal: \"4\", time: \"08:00 - 09:00\", },\n { id: 3, futsal: \"4\", time: \"08:00 - 09:00\", }\n];\n const itemUIds = items.map(o => o.id)\nconst filteredOption1 = items.filter(({id}, index) => !itemUIds.includes(id, index + 1));\nconsole.log(filteredOption1)\n const filteredOption2 = Object.values(items.reduce((acc,cur)=>Object.assign(acc,{[cur.id]:cur}),{}));\nconsole.log(filteredOption2)\n const uniqueItem:any = {};\nconst filteredOption3 = items.filter(obj => !uniqueItem[obj.id] && (uniqueItem[obj.id] = true));\nconsole.log(filteredOption3);\n"
},
{
"answer_id": 74556068,
"author": "EWW",
"author_id": 20587602,
"author_profile": "https://Stackoverflow.com/users/20587602",
"pm_score": 2,
"selected": false,
"text": "const uniqueIds = [];\n\n const unique = arr.filter(element => {\n const isDuplicate = uniqueIds.includes(element.id);\n\n if (!isDuplicate) {\n uniqueIds.push(element.id);\n\n return true;\n }\n\n return false;\n });\n\n // ️ \n console.log(unique);\n"
},
{
"answer_id": 74556120,
"author": "Suresh Ponnukalai",
"author_id": 3607064,
"author_profile": "https://Stackoverflow.com/users/3607064",
"pm_score": 0,
"selected": false,
"text": "id newArr = [...new Map(array.map(item => [item[\"id\"], item])).values()]// I am passing `id` as key\n array = [\n{ id: 1, futsal: \"4\", time: \"06:00 - 09:00\"},\n{ id: 1, futsal: \"4\", time: \"06:00 - 09:00\"},\n{ id: 1, futsal: \"4\", time: \"06:00 - 09:00\"},\n{ id: 2, futsal: \"4\", time: \"07:00 - 08:00\"},\n{ id: 2, futsal: \"4\", time: \"07:00 - 07:00\"},\n{ id: 3, futsal: \"4\", time: \"08:00 - 09:00\"},\n{ id: 3, futsal: \"4\", time: \"08:00 - 09:00\"},\n{ id: 3, futsal: \"4\", time: \"08:00 - 09:00\"}]\n\nnewArr = [...new Map(array.map(item => [item[\"id\"], item])).values()]\n\nconsole.log(newArr);"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17218747/"
] |
74,555,873
|
<p>I have two collections <strong>Post</strong> (belongs to posts database) and <strong>User</strong> (belongs to account database). My requirements to do join on these two collection. But I am unable to reproduce my requirements.</p>
<p>I am expecting joins on two collections.</p>
|
[
{
"answer_id": 74555882,
"author": "ray",
"author_id": 636077,
"author_profile": "https://Stackoverflow.com/users/636077",
"pm_score": -1,
"selected": false,
"text": "const array = [\n { id: 1, futsal: \"4\", time: \"06:00 - 09:00\" },\n { id: 1, futsal: \"4\", time: \"06:00 - 09:00\" },\n { id: 1, futsal: \"4\", time: \"06:00 - 09:00\" },\n { id: 2, futsal: \"4\", time: \"07:00 - 08:00\" },\n { id: 2, futsal: \"4\", time: \"07:00 - 07:00\" },\n { id: 3, futsal: \"4\", time: \"08:00 - 09:00\" },\n { id: 3, futsal: \"4\", time: \"08:00 - 09:00\" },\n { id: 3, futsal: \"4\", time: \"08:00 - 09:00\" }\n];\n\n// only items where id is not 2\nconst filtered = array.filter(item => item.id !== 2);\n\nconsole.log(filtered);"
},
{
"answer_id": 74556023,
"author": "Mukesh Soni",
"author_id": 11556649,
"author_profile": "https://Stackoverflow.com/users/11556649",
"pm_score": 0,
"selected": false,
"text": " { id: 1, futsal: \"4\", time: \"06:00 - 09:00\", },\n { id: 1, futsal: \"4\", time: \"06:00 - 09:00\", },\n { id: 1, futsal: \"4\", time: \"06:00 - 09:00\", },\n { id: 2, futsal: \"4\", time: \"07:00 - 08:00\", },\n { id: 2, futsal: \"4\", time: \"07:00 - 07:00\", },\n { id: 3, futsal: \"4\", time: \"08:00 - 09:00\", },\n { id: 3, futsal: \"4\", time: \"08:00 - 09:00\", },\n { id: 3, futsal: \"4\", time: \"08:00 - 09:00\", }\n];\n const itemUIds = items.map(o => o.id)\nconst filteredOption1 = items.filter(({id}, index) => !itemUIds.includes(id, index + 1));\nconsole.log(filteredOption1)\n const filteredOption2 = Object.values(items.reduce((acc,cur)=>Object.assign(acc,{[cur.id]:cur}),{}));\nconsole.log(filteredOption2)\n const uniqueItem:any = {};\nconst filteredOption3 = items.filter(obj => !uniqueItem[obj.id] && (uniqueItem[obj.id] = true));\nconsole.log(filteredOption3);\n"
},
{
"answer_id": 74556068,
"author": "EWW",
"author_id": 20587602,
"author_profile": "https://Stackoverflow.com/users/20587602",
"pm_score": 2,
"selected": false,
"text": "const uniqueIds = [];\n\n const unique = arr.filter(element => {\n const isDuplicate = uniqueIds.includes(element.id);\n\n if (!isDuplicate) {\n uniqueIds.push(element.id);\n\n return true;\n }\n\n return false;\n });\n\n // ️ \n console.log(unique);\n"
},
{
"answer_id": 74556120,
"author": "Suresh Ponnukalai",
"author_id": 3607064,
"author_profile": "https://Stackoverflow.com/users/3607064",
"pm_score": 0,
"selected": false,
"text": "id newArr = [...new Map(array.map(item => [item[\"id\"], item])).values()]// I am passing `id` as key\n array = [\n{ id: 1, futsal: \"4\", time: \"06:00 - 09:00\"},\n{ id: 1, futsal: \"4\", time: \"06:00 - 09:00\"},\n{ id: 1, futsal: \"4\", time: \"06:00 - 09:00\"},\n{ id: 2, futsal: \"4\", time: \"07:00 - 08:00\"},\n{ id: 2, futsal: \"4\", time: \"07:00 - 07:00\"},\n{ id: 3, futsal: \"4\", time: \"08:00 - 09:00\"},\n{ id: 3, futsal: \"4\", time: \"08:00 - 09:00\"},\n{ id: 3, futsal: \"4\", time: \"08:00 - 09:00\"}]\n\nnewArr = [...new Map(array.map(item => [item[\"id\"], item])).values()]\n\nconsole.log(newArr);"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20587422/"
] |
74,555,881
|
<p>I added a mesh to a <code>pyvista.Plotter()</code> with</p>
<pre class="lang-py prettyprint-override"><code>p.add_mesh(mesh, show_edges=True, color='linen', pbr=True, metallic=0.8, roughness=0.1, diffuse=1)
</code></pre>
<p>but it displays with a discontinuity (where the mesh started and ended)
<a href="https://i.stack.imgur.com/JSdXi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JSdXi.jpg" alt="enter image description here" /></a></p>
<p>Why is this junction of cells different from similar ones around this toroid?</p>
|
[
{
"answer_id": 74566839,
"author": "Andras Deak -- Слава Україні",
"author_id": 5067311,
"author_profile": "https://Stackoverflow.com/users/5067311",
"pm_score": 1,
"selected": false,
"text": "phi = 0 +x phi = 2*pi +x mesh.extract_feature_edges(boundary_edges=True, non_manifold_edges=True, feature_edges=False, manifold_edges=False).plot() mesh = mesh.clean() tolerance import pyvista as pv\n\n# generate toroid\nsquare = pv.Polygon(n_sides=4).translate((0, -2, 0))\ntoroid = square.extrude_rotate(resolution=8, rotation_axis=(1, 0, 0), capping=False)\n\n# let's see what we've got\nplotter = pv.Plotter()\nplotter.add_mesh(toroid, color='lightblue', smooth_shading=True)\nplotter.view_yz()\nplotter.show()\n print(toroid.n_open_edges)\n# 8\nopen_edges = toroid.extract_feature_edges(\n boundary_edges=True,\n non_manifold_edges=True,\n feature_edges=False,\n manifold_edges=False,\n)\n\nplotter = pv.Plotter()\nplotter.add_mesh(toroid, color='lightblue', smooth_shading=True)\nplotter.add_mesh(open_edges, color='red', line_width=5, render_lines_as_tubes=True)\nplotter.view_yz()\nplotter.show()\n cleaned = toroid.clean(tolerance=1e-12)\nprint(cleaned.n_open_edges)\n# 0\n\nplotter = pv.Plotter()\nplotter.add_mesh(cleaned, color='lightblue', smooth_shading=True)\nplotter.view_yz()\nplotter.show()\n"
},
{
"answer_id": 74567171,
"author": "user258279",
"author_id": 258279,
"author_profile": "https://Stackoverflow.com/users/258279",
"pm_score": 0,
"selected": false,
"text": " [[ 4.8000000e+01 0.0000000e+00 0.0000000e+00]\n [ ... ... ... ]\n [ 4.8000000e+01 -3.9188699e-15 1.1756609e-14]]\n return (x.round(5), y.round(5), z.round(5))\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/258279/"
] |
74,555,886
|
<p>I'm writing something that will create a .csv file in memory and email it as an attachment. The code below successfully emails a .csv file, but it is empty. I'm sure I'm missing something simple...</p>
<pre><code> MemoryStream memoryStream = new MemoryStream();
TextWriter tw = new StreamWriter(memoryStream);
tw.WriteLine("test,hello");
tw.WriteLine("1234,543");
Attachment attachment = new Attachment(memoryStream, new ContentType("text/csv"));
attachment.Name = "test.csv";
var Smtp = new SmtpClient();
Smtp.UseDefaultCredentials = false;
var NetworkCredentials = new NetworkCredential() { UserName = "NOPE@gmail.com", Password = "NO" };
Smtp.Port = 587;
Smtp.EnableSsl = true;
Smtp.Host = "smtp.gmail.com";
Smtp.Credentials = NetworkCredentials;
MailMessage msg = new MailMessage();
msg.From = new MailAddress("NAY@gmail.com");
msg.To.Add("X@gmail.com");
msg.Subject = "subject text";
msg.Body = "Attached is a file.";
msg.Attachments.Add(attachment);
Smtp.Send(msg);
</code></pre>
|
[
{
"answer_id": 74558841,
"author": "Yash Gupta",
"author_id": 5498542,
"author_profile": "https://Stackoverflow.com/users/5498542",
"pm_score": 2,
"selected": false,
"text": " tw.WriteLine(\"test,hello\");\n tw.WriteLine(\"1234,543\");\n MemoryStream tw.Flush();\n MemoryStream MemoryStream MemoryStream Attachment MemoryStream memoryStream.position = 0;\n MemoryStream memoryStream = new MemoryStream();\nTextWriter tw = new StreamWriter(memoryStream);\n\ntw.WriteLine(\"test,hello\");\ntw.WriteLine(\"1234,543\");\n\ntw.Flush();\nmemoryStream.position = 0;\n\n//rest of your code\n"
},
{
"answer_id": 74558939,
"author": "JoeGER94",
"author_id": 8375468,
"author_profile": "https://Stackoverflow.com/users/8375468",
"pm_score": 0,
"selected": false,
"text": "using(var memStream = new MemoryStream(...))\n{\n using(var textWriter = new TextWriter(memStream))\n {\n textWriter.WriteLine(...);\n }\n}\n"
},
{
"answer_id": 74559137,
"author": "kingrazer",
"author_id": 12853476,
"author_profile": "https://Stackoverflow.com/users/12853476",
"pm_score": 0,
"selected": false,
"text": "using(var memStream = new MemoryStream(...))\nusing(var textWriter = new TextWriter(memStream)) \ntextWriter.WriteLine(...);\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3965828/"
] |
74,555,902
|
<p>I have a nested object which can be of any depth</p>
<pre><code>[
{
"id": "3",
"user_id": "1479",
"folder_id": "2",
"is_folder": true,
"folder_name": "folder 3",
"unique_filename": null,
"original_filename": null,
"file_extension": null,
"content_type": null,
"file_size": null,
"description": "People",
"visible": false,
"status": 0,
"deleted_at": null,
"last_access": "2022-11-21T09:34:48.546+02:00",
"created_at": "2022-11-21T09:34:48.546+02:00",
"updated_at": "2022-11-21T09:34:48.546+02:00",
"children": [
{
"id": "36",
"user_id": "1479",
"folder_id": "3",
"is_folder": true,
"folder_name": "folder 4",
"unique_filename": null,
"original_filename": null,
"file_extension": null,
"content_type": null,
"file_size": null,
"description": "People",
"visible": false,
"status": 0,
"deleted_at": null,
"last_access": "2022-11-21T21:33:48.767+02:00",
"created_at": "2022-11-21T21:33:48.767+02:00",
"updated_at": "2022-11-21T21:33:48.767+02:00",
"children": [
{
"id": "37",
"user_id": "1479",
"folder_id": "36",
"is_folder": true,
"folder_name": "folder 37",
"unique_filename": null,
"original_filename": null,
"file_extension": null,
"content_type": null,
"file_size": null,
"description": "People",
"visible": false,
"status": 0,
"deleted_at": null,
"last_access": "2022-11-21T21:38:30.690+02:00",
"created_at": "2022-11-21T21:38:30.690+02:00",
"updated_at": "2022-11-21T21:38:30.690+02:00",
"children": []
}
]
},
{
"id": "42",
"user_id": "1479",
"folder_id": "3",
"is_folder": true,
"folder_name": "folder 41",
"unique_filename": null,
"original_filename": null,
"file_extension": null,
"content_type": null,
"file_size": null,
"description": "People",
"visible": false,
"status": 0,
"deleted_at": null,
"last_access": "2022-11-21T23:38:31.935+02:00",
"created_at": "2022-11-21T23:38:31.935+02:00",
"updated_at": "2022-11-21T23:38:31.935+02:00",
"children": []
}
]
},
{
"id": "5",
"user_id": "1479",
"folder_id": null,
"is_folder": false,
"folder_name": null,
"unique_filename": "drives/users/user_drive_1479/YTHGg4dnzn8O5a4DGHbntsrKhY2n4ycc3hZG5j7YxdIb5yEka9iToJDi9WxQPe4taSjLP53b1s01mctIy69o7m6L92.c",
"original_filename": "sample3.c",
"file_extension": "c",
"content_type": "text/x-c",
"file_size": "126",
"description": null,
"visible": false,
"status": 0,
"deleted_at": null,
"last_access": "2022-11-21T09:37:48.766+02:00",
"created_at": "2022-11-21T09:37:48.767+02:00",
"updated_at": "2022-11-21T09:37:48.767+02:00",
"children": []
},
{
"id": "7",
"user_id": "1479",
"folder_id": null,
"is_folder": false,
"folder_name": null,
"unique_filename": "drives/users/user_drive_1479/FSix4WZx0s9ey89x3foLxmaC1wCHTSw1HQi8fDxQ32bYQyKmyPJBcgeI33KOrdPfAcOChvkBnIBizj5IQbggeprCpz.cpp",
"original_filename": "sample1.cpp",
"file_extension": "cpp",
"content_type": "text/x-c",
"file_size": "94",
"description": null,
"visible": false,
"status": 0,
"deleted_at": null,
"last_access": "2022-11-21T09:37:52.324+02:00",
"created_at": "2022-11-21T09:37:52.324+02:00",
"updated_at": "2022-11-21T09:37:52.324+02:00",
"children": []
},
{
"id": "37",
"user_id": "1479",
"folder_id": "36",
"is_folder": true,
"folder_name": "folder 37",
"unique_filename": null,
"original_filename": null,
"file_extension": null,
"content_type": null,
"file_size": null,
"description": "People",
"visible": false,
"status": 0,
"deleted_at": null,
"last_access": "2022-11-21T21:38:30.690+02:00",
"created_at": "2022-11-21T21:38:30.690+02:00",
"updated_at": "2022-11-21T21:38:30.690+02:00",
"children": []
}
]
</code></pre>
<p>I need to get the value of all the <code>id</code> keys</p>
<p>from the array of objects above the expected outcome would be</p>
<pre><code>[3,36,37,42,5,7,37]
</code></pre>
<p>the code I have tried is shown below</p>
<pre><code> if (data.children) {
console.log(data.id)
data.children.forEach(item => {
this.getObject(item)
})
} else {
console.log(data.id)
}
</code></pre>
<p>the <code>data</code> variable being the array of objects above</p>
<p>I get <code>undefined</code> as a result.</p>
<p>your assistance would be much appreciated</p>
|
[
{
"answer_id": 74558841,
"author": "Yash Gupta",
"author_id": 5498542,
"author_profile": "https://Stackoverflow.com/users/5498542",
"pm_score": 2,
"selected": false,
"text": " tw.WriteLine(\"test,hello\");\n tw.WriteLine(\"1234,543\");\n MemoryStream tw.Flush();\n MemoryStream MemoryStream MemoryStream Attachment MemoryStream memoryStream.position = 0;\n MemoryStream memoryStream = new MemoryStream();\nTextWriter tw = new StreamWriter(memoryStream);\n\ntw.WriteLine(\"test,hello\");\ntw.WriteLine(\"1234,543\");\n\ntw.Flush();\nmemoryStream.position = 0;\n\n//rest of your code\n"
},
{
"answer_id": 74558939,
"author": "JoeGER94",
"author_id": 8375468,
"author_profile": "https://Stackoverflow.com/users/8375468",
"pm_score": 0,
"selected": false,
"text": "using(var memStream = new MemoryStream(...))\n{\n using(var textWriter = new TextWriter(memStream))\n {\n textWriter.WriteLine(...);\n }\n}\n"
},
{
"answer_id": 74559137,
"author": "kingrazer",
"author_id": 12853476,
"author_profile": "https://Stackoverflow.com/users/12853476",
"pm_score": 0,
"selected": false,
"text": "using(var memStream = new MemoryStream(...))\nusing(var textWriter = new TextWriter(memStream)) \ntextWriter.WriteLine(...);\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11998509/"
] |
74,555,904
|
<p>This function is not working properly and is showing this error:</p>
<p><code>Uncaught TypeError: Cannot read properties of undefined (reading 'map')</code></p>
<pre><code>{users.map((users) => {
return (
<div>
<h2>Name : {users.name}</h2>
<p>Age : {users.age}</p>
<button onClick={() => { updateUser(users.id) }}>Ince Age</button>
<button onClick={() => { deleteUser(users.id) }}>delete Age</button>
</div>
)
})}
</code></pre>
|
[
{
"answer_id": 74555934,
"author": "Shilpe Saxena",
"author_id": 13265113,
"author_profile": "https://Stackoverflow.com/users/13265113",
"pm_score": -1,
"selected": false,
"text": "key={users.id}"
},
{
"answer_id": 74555946,
"author": "Jay Vaghasiya",
"author_id": 10562084,
"author_profile": "https://Stackoverflow.com/users/10562084",
"pm_score": 0,
"selected": false,
"text": "{users?.map?.((users) => {\n return (\n <div>\n <h2>Name : {users.name}</h2>\n <p>Age : {users.age}</p>\n <button onClick={() => { updateUser(users.id) }}>Ince Age</button>\n <button onClick={() => { deleteUser(users.id) }}>delete Age</button>\n </div>\n )\n})}\n\n {users && users.length > 0 && users.map((users) => {\n return (\n <div>\n <h2>Name : {users.name}</h2>\n <p>Age : {users.age}</p>\n <button onClick={() => { updateUser(users.id) }}>Ince Age</button>\n <button onClick={() => { deleteUser(users.id) }}>delete Age</button>\n </div>\n )\n})}\n\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15998452/"
] |
74,555,956
|
<p>I'm getting an error for a piece of python code I wrote that shouldn't</p>
<p>This is the function I wrote and the input I gave it.</p>
<pre><code>#turn list of ints into set, remove val from set, and return the length of the set without val.
def foo(nums,val):
sett = set(nums)
sett_without_val = sett.remove(val)
return len(sett_without_val)
print(foo([3,2,2,3],3))
</code></pre>
<p>sett should be {3,2}
sett_without_val should be {2}
and len(sett_without_val) should be 1. I'm not supposed to get this error:</p>
<p>TypeError: object of type 'NoneType' has no len()</p>
<p>I thought it had something to do with the remove method I used, so I used discard instead and still got the exact same error message.</p>
|
[
{
"answer_id": 74555934,
"author": "Shilpe Saxena",
"author_id": 13265113,
"author_profile": "https://Stackoverflow.com/users/13265113",
"pm_score": -1,
"selected": false,
"text": "key={users.id}"
},
{
"answer_id": 74555946,
"author": "Jay Vaghasiya",
"author_id": 10562084,
"author_profile": "https://Stackoverflow.com/users/10562084",
"pm_score": 0,
"selected": false,
"text": "{users?.map?.((users) => {\n return (\n <div>\n <h2>Name : {users.name}</h2>\n <p>Age : {users.age}</p>\n <button onClick={() => { updateUser(users.id) }}>Ince Age</button>\n <button onClick={() => { deleteUser(users.id) }}>delete Age</button>\n </div>\n )\n})}\n\n {users && users.length > 0 && users.map((users) => {\n return (\n <div>\n <h2>Name : {users.name}</h2>\n <p>Age : {users.age}</p>\n <button onClick={() => { updateUser(users.id) }}>Ince Age</button>\n <button onClick={() => { deleteUser(users.id) }}>delete Age</button>\n </div>\n )\n})}\n\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488228/"
] |
74,555,961
|
<p>Hello my currenct code is doing sum on numbers after + including 10 I need it only after, now is doing like 10 + 10 = 20 then 20 +11 = 31 and etc which is wrong, when I change my i with 11 it adds 1 more interaction to the correct and makes the number more than 1000.</p>
<pre><code>
`` `
int i = 10;
int a = 10;
while (a < 1000)
{
a += i++;
}
Console.WriteLine(a);
Console.WriteLine(i);
</code></pre>
<pre><code>
Tried to change the numbers to 11 which is correct but gives me 1 more interaction which I want to remove!
</code></pre>
|
[
{
"answer_id": 74555934,
"author": "Shilpe Saxena",
"author_id": 13265113,
"author_profile": "https://Stackoverflow.com/users/13265113",
"pm_score": -1,
"selected": false,
"text": "key={users.id}"
},
{
"answer_id": 74555946,
"author": "Jay Vaghasiya",
"author_id": 10562084,
"author_profile": "https://Stackoverflow.com/users/10562084",
"pm_score": 0,
"selected": false,
"text": "{users?.map?.((users) => {\n return (\n <div>\n <h2>Name : {users.name}</h2>\n <p>Age : {users.age}</p>\n <button onClick={() => { updateUser(users.id) }}>Ince Age</button>\n <button onClick={() => { deleteUser(users.id) }}>delete Age</button>\n </div>\n )\n})}\n\n {users && users.length > 0 && users.map((users) => {\n return (\n <div>\n <h2>Name : {users.name}</h2>\n <p>Age : {users.age}</p>\n <button onClick={() => { updateUser(users.id) }}>Ince Age</button>\n <button onClick={() => { deleteUser(users.id) }}>delete Age</button>\n </div>\n )\n})}\n\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74555961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20587541/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.